Esempio n. 1
0
 def testDistanceC(self):
     ntest = 1000
     lats1, lons1, lats2, lons2 = self.get_critical_random_locations(ntest)
     for i in range(ntest):
         orthodrome.distance_accurate50m(
             lats1[i], lons1[i], lats2[i], lons2[i],
             implementation='c')
 def testDistanceC(self):
     ntest = 1000
     lats1, lons1, lats2, lons2 = self.get_critical_random_locations(ntest)
     for i in range(ntest):
         orthodrome.distance_accurate50m(
             lats1[i], lons1[i], lats2[i], lons2[i],
             implementation='c')
Esempio n. 3
0
def process(args, scenario_folder, n_tests=1, show=True):
    nstart = 8
    array_centers = []
    from .guesstimate_depth_v02 import PlotSettings, plot

    events = []
    stations = []
    mod = insheim_layered_model()

    for i in range(nstart, nstart+1):
        i = 8
        scenario_folder = "scenarios/"
        print("%s/scenario_%s/event.txt" % (scenario_folder, i))

        events.append(model.load_events("%s/scenario_%s/event.txt" % (scenario_folder, i))[0])
        stations.append(model.load_stations("%s/scenario_%s/stations.pf" % (scenario_folder, i)))
        traces = io.load(pjoin("%sscenario_%s/" % (scenario_folder, i), 'traces.mseed'))

        event = events[0]
        stations = stations[0]
        min_dist = min(
            [ortho.distance_accurate50m(s, event) for s in stations])
        max_dist = max(
            [ortho.distance_accurate50m(s, event) for s in stations])
        tmin = CakeTiming(phase_selection='first(p|P|PP)-10', fallback_time=0.001)
        tmax = CakeTiming(phase_selection='first(p|P|PP)+52', fallback_time=1000.)
        timing=(tmin, tmax)

        fns = ['.']


        array_id = "INS"


        settings_fn = pjoin("%sscenario_%s/" % (scenario_folder, i), 'plot_settings.yaml')
        settings = PlotSettings.from_argument_parser(args)

        if not settings.trace_filename:
            settings.trace_filename = pjoin("%sscenario_%s/" % (scenario_folder, i), 'beam.mseed')
        if not settings.station_filename:
            fn_array_center = pjoin("%sscenario_%s/" % (scenario_folder, i), 'array_center.pf')
            settings.station_filename = fn_array_center
            station = model.load_stations(fn_array_center)

            settings.store_id = 'landau_100hz'


        settings.event_filename = pjoin("%sscenario_%s/" % (scenario_folder, i), "event.txt")
        settings.save_as = pjoin("%sscenario_%s/" % (scenario_folder, i), "depth_%(array-id)s.png")
        plot(settings)
        if args.overwrite_settings:
            settings.dump(filename=settings_fn)
        if show is True:
            plt.show()
Esempio n. 4
0
 def testDistancePython(self):
     ntest = 1000
     lats1, lons1, lats2, lons2 = self.get_critical_random_locations(ntest)
     loc1 = orthodrome.Loc(0., 0.)
     loc2 = orthodrome.Loc(0., 0.)
     for i in range(ntest):
         loc1.lat, loc1.lon = lats1[i], lons1[i]
         loc2.lat, loc2.lon = lats2[i], lons2[i]
         orthodrome.distance_accurate50m(loc1,
                                         loc2,
                                         implementation='python')
 def testDistancePython(self):
     ntest = 1000
     lats1, lons1, lats2, lons2 = self.get_critical_random_locations(ntest)
     loc1 = orthodrome.Loc(0., 0.)
     loc2 = orthodrome.Loc(0., 0.)
     for i in range(ntest):
         loc1.lat, loc1.lon = lats1[i], lons1[i]
         loc2.lat, loc2.lon = lats2[i], lons2[i]
         orthodrome.distance_accurate50m(
             loc1, loc2,
             implementation='python')
 def testDistancePythonC(self):
     ntest = 100
     lats1, lons1, lats2, lons2 = self.get_critical_random_locations(ntest)
     for i in range(ntest):
         dist_py = orthodrome.distance_accurate50m(
             lats1[i], lons1[i], lats2[i], lons2[i],
             implementation='python')
         dist_c = orthodrome.distance_accurate50m(
             lats1[i], lons1[i], lats2[i], lons2[i],
             implementation='c')
         num.testing.assert_almost_equal(dist_py, dist_c)
Esempio n. 7
0
 def testDistancePythonC(self):
     ntest = 100
     lats1, lons1, lats2, lons2 = self.get_critical_random_locations(ntest)
     for i in range(ntest):
         dist_py = orthodrome.distance_accurate50m(
             lats1[i], lons1[i], lats2[i], lons2[i],
             implementation='python')
         dist_c = orthodrome.distance_accurate50m(
             lats1[i], lons1[i], lats2[i], lons2[i],
             implementation='c')
         num.testing.assert_almost_equal(dist_py, dist_c)
Esempio n. 8
0
def weed_stations(stations, event, distances=(30., 90.)):
    """
    Weed stations, that are not within the given distance range(min, max) to
    a reference event.

    Parameters
    ----------
    stations : list
        of :class:`pyrocko.model.Station`
    event
        :class:`pyrocko.model.Event`
    distances : tuple
        of minimum and maximum distance [deg] for station-event pairs

    Returns
    -------
    weeded_stations : list
        of :class:`pyrocko.model.Station`
    """

    weeded_stations = []
    for station in stations:
        distance = orthodrome.distance_accurate50m(event, station) * m2d

        if distance >= distances[0] and distance <= distances[1]:
            weeded_stations.append(station)

    return weeded_stations
    def do_run(source, return_dict=None):
        if return_dict is None:
            return_dict = defaultdict()

        for target in targets:
            dist = orthodrome.distance_accurate50m(source, target)
            args = (source.depth, dist)

            tmin = store.t('first(%s)' % phase_ids_start, args)
            if tmin is None and p_fallback:
                print 'Using p_fallback'
                tmin = store.t(p_fallback, args)
            tmin += source.time

            tmax = store.t('first(%s)' % phase_ids_end, args)
            if tmax is None:
                if s_fallback is not None:
                    tmax = store.t(s_fallback, args)
                else:
                    raise Exception("cannot interpolate tmax. Target: \n%s."%target+\
                                        '\n Source: %s'%source)

            tmax += source.time

            m = PhaseMarker(nslc_ids=target.codes,
                            tmin=tmin,
                            tmax=tmax,
                            kind=1,
                            event=source,
                            phasename='p-s')

            return_dict[target] = m
        return return_dict
Esempio n. 10
0
def get_bins_pairs(p, staTarget1, staTarget2, comp1, comp2):
    "This function is just to get the proper imputs. take 0.17 sec to compute"
    for ia, asta in enumerate(p['sources']):
        if asta.station == staTarget1:
            break
    for ib, bsta in enumerate(p['receivers']):  #[ia+1:]):
        if bsta.station == staTarget2:
            break
    A = asta.station
    B = bsta.station
    namepairA_B = A + '.' + B
    # get dist between pair
    distpairA_B = orthodrome.distance_accurate50m(asta, bsta) / 1000.
    print '>> Dist = %s km' % distpairA_B, 'for pair %s' % namepairA_B
    # get respective binfile
    bin1 = glob.glob('%s/*.%s.%s.*' % (p['bindirA'], A, comp1))
    bin2 = glob.glob('%s/*.%s.%s.*' % (p['bindirB'], B, comp2))
    # if both files exists open
    if bin1 != [] and bin2 != []:
        bin1 = raw_open(bin1[0], dt=1. / p['df'])  #, shape=shape,)
        bin2 = raw_open(bin2[0], dt=1. / p['df'])  #, shape=shape,)
    else:
        print '>> No files in common...'
        print '>> Exit!'
        sys.exit()

    return bin1, bin2, namepairA_B, asta, bsta, distpairA_B
Esempio n. 11
0
def weed_stations(stations, event, distances=(30., 90.)):
    """
    Weed stations, that are not within the given distance range(min, max) to
    a reference event.

    Parameters
    ----------
    stations : list
        of :class:`pyrocko.model.Station`
    event
        :class:`pyrocko.model.Event`
    distances : tuple
        of minimum and maximum distance [deg] for station-event pairs

    Returns
    -------
    weeded_stations : list
        of :class:`pyrocko.model.Station`
    """

    weeded_stations = []
    logger.debug('Valid distance range: [%f, %f]!' %
                 (distances[0], distances[1]))
    for station in stations:
        distance = orthodrome.distance_accurate50m(event, station) * m2d
        logger.debug('Distance of station %s: %f [deg]' %
                     (station.station, distance))
        if distance >= distances[0] and distance <= distances[1]:
            logger.debug('Inside defined distance range!')
            weeded_stations.append(station)
        else:
            logger.debug('Outside defined distance range!')

    return weeded_stations
Esempio n. 12
0
def setup_distances_crusts(stations, events, do_round=True):
    ''' Propose a fomosto store configuration for P-pP Array beam forming.
    :param event: Event instance
    :param station: Station instance.'''
    distances = {}
    models = {}
    for s in stations:
        for e in events:
            event_profile = crust2x2.get_profile(e.lat, e.lon)
            station_profile = crust2x2.get_profile(s.lat, s.lon)
            k1 = station_profile._ident
            k2 = event_profile._ident
            models[k1] = station_profile
            models[k2] = event_profile
            key = (s.station, k1, k2)
            distance = ortho.distance_accurate50m(e, s)
            if not key in distances:
                if do_round:
                    distances[key] = (math.floor(distance - 1),
                                      math.ceil(distance + 1))
                else:
                    distances[key] = (distance - 1, distance + 1)
            else:
                d1, d2 = distances[key]
                if do_round:
                    distances[key] = (min(d1, math.floor(distance - 1)),
                                      max(d2, math.ceil(distance + 1)))
                else:
                    distances[key] = (min(d1,
                                          distance - 1), max(d2, distance + 1))

    return distances, models
Esempio n. 13
0
    def do_run(source, return_dict=None):
        if return_dict is None:
            return_dict = defaultdict()

        for target in targets:
            dist = orthodrome.distance_accurate50m(source, target)
            args = (source.depth, dist)

            tmin = store.t('first(%s)'%phase_ids_start, args)
            if tmin is None and p_fallback:
                print 'Using p_fallback'
                tmin = store.t(p_fallback, args)
            tmin += source.time

            tmax = store.t('first(%s)'%phase_ids_end, args)
            if tmax is None:
                if s_fallback is not None:
                    tmax = store.t(s_fallback, args)
                else:
                    raise Exception("cannot interpolate tmax. Target: \n%s."%target+\
                                        '\n Source: %s'%source) 

            tmax += source.time

            m = PhaseMarker(nslc_ids=target.codes,
                            tmin=tmin,
                            tmax=tmax,
                            kind=1,
                            event=source,
                            phasename='p-s')

            return_dict[target] = m
        return return_dict 
def setup_distances_crusts(stations, events, do_round=True):
    ''' Propose a fomosto store configuration for P-pP Array beam forming.
    :param event: Event instance
    :param station: Station instance.'''
    distances = {}
    models = {}
    for s in stations:
        for e in events:
            event_profile = crust2x2.get_profile(e.lat, e.lon)
            station_profile = crust2x2.get_profile(s.lat, s.lon)
            k1 = station_profile._ident
            k2 = event_profile._ident
            models[k1] = station_profile
            models[k2] = event_profile
            key = (s.station, k1, k2)
            distance = ortho.distance_accurate50m(e, s)
            if not key in distances:
                if do_round:
                    distances[key] = (math.floor(distance-1),
                                      math.ceil(distance+1))
                else:
                    distances[key] = (distance-1, distance+1)
            else:
                d1, d2 = distances[key]
                if do_round:
                    distances[key] = (min(d1, math.floor(distance-1)),
                                      max(d2, math.ceil(distance+1)))
                else:
                    distances[key] = (min(d1, distance-1), max(d2, distance+1))

    return distances, models
    def run_n_write(self, fn):
        picks = []
        datastr = ''
        progbar = progressbar.ProgressBar(maxval=len(self.events)).start()
        for i, event in enumerate(self.events):
            datastr += '#######\n'
            datastr += str(event.name)+'\n'
            for station in self.stations:
                distance = orthodrome.distance_accurate50m(station, event)*cake.m2d
                for phasename, phase in self.wanted_phases.items():
                    phases = [cake.PhaseDef(k) for k in phase]
                    arrivals = self.model.arrivals(distances=[distance],
                                                   phases=phases,
                                                   zstart=event.depth)
                    nsl = station.nsl()
                    if len(arrivals)==0:
                        print 'PHASE NOT FOUND for event %s, phase %s, station %s' % (event.name, phase.given_name(), '.'.join(nsl))
                        continue

                    t = min(arrivals, key=lambda x: x.t).t
                    #t = self.reduce_stf(event, t)
                    datastr += '%s %s \n'%('.'.join(nsl) , t)
                    m = gui_util.PhaseMarker(tmin=t+event.time,
                                             tmax=t+event.time,
                                             nslc_ids=(nsl+tuple(('*')), ),
                                             phasename=phasename, 
                                             event=event)
                    picks.append(m)
            progbar.update(i)

        progbar.finish()
        with open(fn, 'w') as f:
            f.write(datastr)

        gui_util.save_markers(picks, 'picks.pf')
Esempio n. 16
0
    def set_event_relative_data(self, event, distance_3d=False):
        surface_dist = orthodrome.distance_accurate50m(event, self)
        if distance_3d:
            dd = event.depth - self.depth
            self.dist_m = math.sqrt(dd**2 + surface_dist**2)
        else:
            self.dist_m = surface_dist

        self.dist_deg = surface_dist / orthodrome.earthradius_equator * orthodrome.r2d
        self.azimuth = orthodrome.azimuth(event, self)
        self.backazimuth = orthodrome.azimuth(self, event)
Esempio n. 17
0
    def set_event_relative_data(self, event, distance_3d=False):
        surface_dist = orthodrome.distance_accurate50m(event, self)
        if distance_3d:
            dd = event.depth - self.depth
            self.dist_m = math.sqrt(dd**2 + surface_dist**2)
        else:
            self.dist_m = surface_dist

        self.dist_deg = surface_dist / orthodrome.earthradius_equator * \
            orthodrome.r2d
        self.azimuth = orthodrome.azimuth(event, self)
        self.backazimuth = orthodrome.azimuth(self, event)
Esempio n. 18
0
    def testLocationObjects(self):
        class Dummy(object):
            def __init__(self, lat, lon, depth):
                self.lat = lat
                self.lon = lon
                self.depth = depth

        a0 = Location(lat=10., lon=12., depth=1100.)
        a1 = guts.clone(a0)
        a1.set_origin(lat=9., lon=11)

        b0 = Location(lat=11., lon=13., depth=2100.)
        b1 = guts.clone(b0)
        b1.set_origin(lat=9., lon=11)
        b2 = Dummy(b0.lat, b0.lon, b0.depth)

        dist_ab = orthodrome.distance_accurate50m(a0.lat, a0.lon, b0.lat,
                                                  b0.lon)

        azi_ab, bazi_ab = orthodrome.azibazi(a0.lat, a0.lon, b0.lat, b0.lon)

        def g_to_e(*args):
            return num.array(orthodrome.geodetic_to_ecef(*args))

        a_vec = g_to_e(a0.lat, a0.lon, -a0.depth)
        b_vec = g_to_e(b0.lat, b0.lon, -b0.depth)

        dist_3d_compare = math.sqrt(num.sum((a_vec - b_vec)**2))

        north_shift_compare, east_shift_compare = orthodrome.latlon_to_ne(
            a0.lat, a0.lon, b0.lat, b0.lon)

        for a in [a0, a1]:
            for b in [b0, b1, b2]:
                dist = a.distance_to(b)
                assert_allclose(dist, dist_ab)

                dist_3d = a.distance_3d_to(b)
                assert_allclose(dist_3d, dist_3d_compare, rtol=0.001)

                azi, bazi = a.azibazi_to(b)
                assert_allclose(azi % 360., azi_ab % 360., rtol=1e-2)
                assert_allclose(bazi % 360., bazi_ab % 360., rtol=1e-2)

                north_shift, east_shift = a.offset_to(b)
                assert_allclose((north_shift, east_shift),
                                (north_shift_compare, east_shift_compare),
                                rtol=5e-3)

        for x, y in [(a0, a1), (b0, b1), (b0, b2), (b1, b2)]:
            dist = x.distance_to(y)
            assert_allclose(dist, 0.0)
 def estimate(self, phase, station):
     event = phase.get_event()
     distance = orthodrome.distance_accurate50m(station, event)*cake.m2d
     phasenames = self.map_phasenames(phase.get_phasename())
     phases = [cake.PhaseDef(pn) for pn in phasenames]
     arrivals = self.model.arrivals(distances=[distance],
                                    phases=phases,
                                    zstart=event.depth)
     if len(arrivals)==0:
         logging.warning('no arrivals: %s'%self)
     
     t = min(arrivals, key=lambda x:x.t).t
     return self.return_residual(phase, t)
Esempio n. 20
0
def process_loaded_waveforms(traces_unsorted, stations, event, gf_freq, mod,
                             pre, post):
    traces_processed = []

    traces_unsorted.sort(key=lambda a: a.full_id)
    traces = trace.degapper(traces_unsorted,
                            maxgap=300000000,
                            fillmethod='zeros',
                            deoverlap='use_second',
                            maxlap=None)
    for st in stations:
        for tr in traces:
            nsamples = len(tr.ydata)
            if st.station == tr.station:
                dists = (orthodrome.distance_accurate50m(
                    event.lat, event.lon, st.lat, st.lon) +
                         st.elevation) * cake.m2d
                processed = False
                for i, arrival in enumerate(
                        mod.arrivals([dists],
                                     phases=["p", "P", "S"],
                                     zstart=event.depth)):
                    if processed is False:
                        try:
                            tr.chop(event.time + arrival.t - pre,
                                    event.time + arrival.t + post,
                                    want_incomplete=True)
                            if 1. / gf_freq != tr.deltat:
                                tr.resample(1. / gf_freq)
                            traces_processed.append(tr)
                            processed = True
                        except:
                            data_zeros = np.zeros(int(500 * (1 / tr.deltat)))
                            t1 = trace.Trace(station=st.station,
                                             channel=tr.channel,
                                             deltat=tr.deltat,
                                             tmin=event.time + arrival.t -
                                             pre - 5,
                                             ydata=data_zeros)
                            if np.isnan(np.max(tr.ydata)) is False:
                                t1.add(tr)
                                t1.chop(event.time + arrival.t - pre,
                                        event.time + arrival.t + post,
                                        want_incomplete=True)
                                tr = t1
                                if 1. / gf_freq != tr.deltat:
                                    tr.resample(1. / gf_freq)
                                traces_processed.append(tr)
                                processed = True

    return traces_processed, nsamples
Esempio n. 21
0
def beam(scenario_folder, n_tests=1, show=False):
    nstart = 8
    array_centers = []

    events = []
    stations = []
    mod = insheim_layered_model()

    for i in range(nstart, n_tests):
        print("%s/scenario_%s/event.txt" % (scenario_folder, i))

        events.append(model.load_events("%s/scenario_%s/event.txt" % (scenario_folder, i))[0])
        stations.append(model.load_stations("%s/scenario_%s/stations.pf" % (scenario_folder, i)))
        traces = io.load(pjoin("%sscenario_%s/" % (scenario_folder, i), 'traces.mseed'))

        event = events[0]
        stations = stations[0]
        min_dist = min(
            [ortho.distance_accurate50m(s, event) for s in stations])
        max_dist = max(
            [ortho.distance_accurate50m(s, event) for s in stations])
        tmin = CakeTiming(phase_selection='first(p|P|PP)-10', fallback_time=0.001)
        tmax = CakeTiming(phase_selection='first(p|P|PP)+52', fallback_time=1000.)
        timing=(tmin, tmax)
        tstart = timing[0].t(mod, (event.depth, min_dist))
        tend = timing[1].t(mod, (event.depth, max_dist))

        normalize = True
        bf = BeamForming(stations, traces, normalize=normalize)
        bf.process(event=event,
                   timing=tmin,
                   fn_dump_center=pjoin("%sscenario_%s/" % (scenario_folder, i), 'array_center.pf'),
                   fn_beam=pjoin("%sscenario_%s/" % (scenario_folder, i), 'beam.mseed'),
                   station="INS")
        if show is True:
            bf.plot(fn=pjoin("%sscenario_%s/" % (scenario_folder, i), 'beam_shifts.png'))

        array_centers.append(bf.station_c)
Esempio n. 22
0
    def call(self, plot_rays=False):

        self.cleanup()
        wanted = self.wanted_phases()

        if not wanted:
            return

        viewer = self.get_viewer()
        pile = self.get_pile()

        event, stations = self.get_active_event_and_stations()
        
        if not stations:
            self.fail('No station information available.')

        self.update_model()
        model = self._model[1]

        depth = event.depth
        if depth is None:
            depth = 0.0

        allrays = []
        alldists = []
        for station in stations:
            dist = orthodrome.distance_accurate50m(event, station)
            alldists.append(dist)

            rays = model.arrivals(phases=wanted, distances=[dist*cake.m2d], zstart=depth)

            for ray in rays:
                time = ray.t
                name = ray.given_phase().name
                incidence_angle = ray.incidence_angle()
                takeoff_angle = ray.takeoff_angle()

                time += event.time + self.tshift
                m = PhaseMarker([ (station.network, station.station, '*', '*') ], time, time, 2, phasename=name, event=event, incidence_angle=incidence_angle, takeoff_angle=takeoff_angle)
                self.add_marker(m)

            allrays.extend(rays)

        if plot_rays:
            fig = self.figure(name='Ray Paths')
            from pyrocko import cake_plot
            cake_plot.my_rays_plot(model, None, allrays, depth, 0.0, 
                    num.array(alldists)*cake.m2d, axes=fig.gca())
            
            fig.canvas.draw()
Esempio n. 23
0
def get_bounds(stations,
               events=None,
               usestations=False,
               printall=False,
               show_fig=False,
               km=False):
    scale = 1.0 / 1000.0 if km else 1
    if printall:
        print("using stations: ")
        for s in stations:
            print(s)
            print(".......................................\n\n\n")
    maxdistances = []
    mindistances = []
    alldists = {}
    for e in events:
        dists = [
            orthodrome.distance_accurate50m(e, s) * scale for s in stations
        ]
        alldists[e] = dists
        maxdistances.append(max(dists))
        mindistances.append(min(dists))

    depths = [e.depth for e in events]
    if printall:
        for e, dists in alldists.items():
            i = 0
            for s in stations:
                print("%s \n %s DISTANCE: %s \n\n" % (e, s, dists[i]))
                print("=" * 20)
                i += 1
        if len(maxdistances) == 1:
            print("maximum distances: ", maxdistances[0])
            print("minimum distances: ", mindistances[0])

    if show_fig:
        f, axs = plt.subplots(2)

        axs[0].hist(maxdistances, bins=20, color="r")
        axs[0].hist(mindistances, bins=20, color="g")
        axs[0].set_title("Minimum (green) and maximum (red) distances [km]")
        axs[1].hist(depths, bins=20)
        axs[1].set_title("Depths [km]")
        axs[0].get_xaxis().get_major_formatter().set_useOffset(False)
        axs[1].get_xaxis().get_major_formatter().set_useOffset(False)
        plt.show()

    else:
        return mindistances, maxdistances, depths
Esempio n. 24
0
def assoicate_single(ev, data_dir, store_id, store,
                     stations=None, pre=0.5,
                     post=3, reference_event=None, min_len=420,
                     pick_sigma=0.02):
    events = []
    waveforms = []
    labels = []
    gf_freq = store.config.sample_rate
    mod = store.config.earthmodel_1d
    found = False
    pathlist = Path(data_dir).glob('ev_*/')
    for path in sorted(pathlist):
        targets = []
        path = str(path)+"/"
        try:
            event = model.load_events(path+"event.txt")[0]
            if ev.time-10 < event.time and ev.time+10 > event.time:
                traces_loaded = io.load(path+"/waveforms/rest/traces.mseed")
                stations_unsorted = model.load_stations(data_dir+"stations.pf")
                for st in stations_unsorted:
                    st.dist = orthodrome.distance_accurate50m(st.lat, st.lon,
                                                              event.lat,
                                                              event.lon)
                    st.azi = orthodrome.azimuth(st.lat, st.lon, event.lat,
                                                event.lon)
                stations = sorted(stations_unsorted, key=lambda x: x.dist,
                                  reverse=True)

                traces_processed = []
                traces = wp.check_traces(traces_loaded, stations, min_len=min_len)

                traces_processed, nsamples = wp.process_loaded_waveforms(traces,
                                                                         stations,
                                                                         ev,
                                                                         gf_freq,
                                                                         mod,
                                                                         pre,
                                                                         post)
                if found is False:
                    events.append(event)
                    waveforms.append(traces_processed)
                    found = True
        except:
            pass
    data_events, nsamples = wp.prepare_waveforms(waveforms)
    return data_events, nsamples, event
Esempio n. 25
0
def weed_stations(stations,
                  event,
                  distances=(30., 90.),
                  remove_duplicate=False):
    """
    Weed stations, that are not within the given distance range(min, max) to
    a reference event.

    Parameters
    ----------
    stations : list
        of :class:`pyrocko.model.Station`
    event
        :class:`pyrocko.model.Event`
    distances : tuple
        of minimum and maximum distance [deg] for station-event pairs

    Returns
    -------
    weeded_stations : list
        of :class:`pyrocko.model.Station`
    """

    weeded_stations = []
    logger.debug('Valid distance range: [%f, %f]!' %
                 (distances[0], distances[1]))
    check_duplicate = []
    for station in stations:
        distance = orthodrome.distance_accurate50m(event, station) * m2d
        logger.debug('Distance of station %s: %f [deg]' %
                     (station.station, distance))
        if distance >= distances[0] and distance <= distances[1]:
            logger.debug('Inside defined distance range!')
            ns_str = '{}.{}'.format(station.network, station.station)
            if ns_str in check_duplicate and remove_duplicate:
                logger.warning('Station %s already in wavemap! Multiple '
                               'locations not supported yet! '
                               'Discarding duplicate ...' % ns_str)
            else:
                weeded_stations.append(station)
                check_duplicate.append(ns_str)
        else:
            logger.debug('Outside defined distance range!')

    return weeded_stations
Esempio n. 26
0
def prep_data_batch(data_dir, store_id, stations=None, pre=0.5,
                    post=3, reference_event=None, min_len=420,
                    pick_sigma=0.02):
    engine = LocalEngine(store_superdirs=['/home/asteinbe/gf_stores'])
    store = engine.get_store(store_id)
    mod = store.config.earthmodel_1d
    gf_freq = store.config.sample_rate
    cake_phase = cake.PhaseDef("P")
    phase_list = [cake_phase]
    events = []
    waveforms = []
    waveforms_shifted = []
    events = scedc_util.scedc_fm_to_pyrocko(file)
    labels = labels_from_events(events)
    pathlist = Path(data_dir).glob('ev_0/')
    for path in sorted(pathlist):
        try:
            targets = []
            path = str(path)+"/"
            event = model.load_events(path+"event.txt")[0]
            traces_loaded = io.load(path+"traces.mseed")
            stations_unsorted = model.load_stations(data_dir+"stations.pf")
            for st in stations_unsorted:
                st.dist = orthodrome.distance_accurate50m(st.lat, st.lon,
                                                          event.lat,
                                                          event.lon)
                st.azi = orthodrome.azimuth(st.lat, st.lon, event.lat,
                                            event.lon)
            stations = sorted(stations_unsorted, key=lambda x: x.dist,
                              reverse=True)

            traces_processed = []
            traces = check_traces(traces_loaded, stations, min_len=min_len)
            traces_processed, nsamples = wp.process_loaded_waveforms(traces,
                                                                  stations,
                                                                  event,
                                                                  gf_freq,
                                                                  mod,
                                                                  pre, post)
            events.append(event)
            waveforms.append(traces_processed)
        except:
            pass
    return waveforms, nsamples, events, waveforms_shifted
Esempio n. 27
0
def calcuate_msd(events, start=0, end=None, distance_3d=True):
    base_event = events[start]
    distances = []
    time_rel = []
    if end is None:
        end = len(events)
    for i in range(0, end):
        if i == start:
            pass
        else:
            surface_dist = orthodrome.distance_accurate50m(
                base_event, events[i])
            if distance_3d:
                dd = base_event.depth - events[i].depth
                dist_m = math.sqrt(dd**2 + surface_dist**2)
                distances.append(dist_m)
        time_rel.append(base_event.time - events[i].time)
    msd = (1. / (end - start)) * (num.sum(distances))
    return distances, time_rel, msd
    def get_traces(self, event, stations, trace_selector, tpad):
        p = self.get_pile()
        trace_selector_viewer = self.get_viewer_trace_selector('visible')
        if self.time_window == 'distance dependant':
            for station in stations:
                distance = orthodrome.distance_accurate50m(event, station)
                tmin = distance / self.vmax
                tmax = (distance + event.depth) / self.vmin

                for trs in p.chopper(
                        tmin=event.time + tmin,
                        tmax=event.time + tmax,
                        tpad=tpad,
                        trace_selector=lambda tr:
                    (trace_selector(tr) and trace_selector_viewer(tr) and tr.
                     nslc_id[:3] == station.nsl())):

                    for tr in trs:
                        yield tr

        elif self.time_window == 'fixed':
            tmin = 0.
            tmax = self.duration_fixed
            for trs in p.chopper(
                    tmin=event.time + tmin,
                    tmax=event.time + tmax,
                    tpad=tpad,
                    trace_selector=lambda tr:
                (trace_selector(tr) and trace_selector_viewer(tr))):

                for tr in trs:
                    yield tr

        else:
            for trs in self.chopper_selected_traces(
                    fallback=True,
                    tpad=tpad,
                    trace_selector=trace_selector,
                    mode='inview'):

                for tr in trs:
                    yield tr
def get_bounds(stations, events=None, usestations=False, printall=False, show_fig=False, km=False):
    scale = 1./1000. if km else 1
    if printall:
        print 'using stations: '
        for s in stations:
            print s
            print '.......................................\n\n\n'
    maxdistances = []
    mindistances = []
    alldists = {}
    for e in events:
        dists = [orthodrome.distance_accurate50m(e, s)*scale for s in stations]
        alldists[e] = dists
        maxdistances.append(max(dists))
        mindistances.append(min(dists))

    depths = [e.depth for e in events]
    if printall:
        for e, dists in alldists.items():
            i = 0
            for s in stations:
                print '%s \n %s DISTANCE: %s \n\n' % (e, s, dists[i])
                print '='*20
                i += 1
        if len(maxdistances)==1:
            print 'maximum distances: ', maxdistances[0]
            print 'minimum distances: ', mindistances[0]

    if show_fig:
        f, axs = plt.subplots(2)

        axs[0].hist(maxdistances, bins=20, color='r')
        axs[0].hist(mindistances, bins=20, color='g')
        axs[0].set_title('Minimum (green) and maximum (red) distances [km]')
        axs[1].hist(depths, bins=20)
        axs[1].set_title('Depths [km]')
        axs[0].get_xaxis().get_major_formatter().set_useOffset(False)
        axs[1].get_xaxis().get_major_formatter().set_useOffset(False)
        plt.show()

    else:
        return mindistances, maxdistances, depths
Esempio n. 30
0
def find_closest_grid_point(lat_ev, lon_ev, depth_ev, path_models=None,
                            gf_store_id=None, min_dist=7000.,
                            min_dist_depth=10000.):
    pathlist = Path(path_models).glob('model_%s_*' % gf_store_id)
    k = 0
    for path in sorted(pathlist):
        path = str(path)
        model_coordinates = path.split("_")
        lat = float(model_coordinates[3])
        lon = float(model_coordinates[4])
        depth = float(model_coordinates[5])
        dist = orthodrome.distance_accurate50m(lat_ev, lon_ev, lat, lon)
        if dist < min_dist:
            min_dist = dist
            dist_depth = abs(depth-depth_ev)
            if dist_depth < min_dist_depth:
                min_dist_depth = dist_depth
                best_model = path
        k = k+1
    return best_model
Esempio n. 31
0
    def process(self, fband, taper):
        for event in self.candidates:
            section = Section(event, self.stations)
            skipped = 0
            unskipped = 0
            for i_s, s in enumerate(self.stations):
                dist = distance_accurate50m(event, s)
                arrival = self.phaser.t(self.phase_selection, (event.depth, dist))
                if arrival==None:
                    skipped +=1
                    logger.debug('skipping event %s at stations %s. Reason no phase arrival'
                                % (event, s))
                    continue
                else:
                    unskipped +=1
                selector = lambda tr: util.match_nslc('%s.*%s'%(s.nsl_string(),
                                                                self.component),
                                                      tr.nslc_id)
                window_min, window_max = self.window.t()
                tr = self.data_pile.chopper(tmin=event.time+arrival - window_min,
                                            tmax=event.time+arrival + window_max,
                                            trace_selector=selector)
                _tr = tr.next()
                try:
                    assert len(_tr) in (0, 1)
                    self.all_nslc_ids.add(_tr[0].nslc_id)
                    section.extend(_tr)
                except IndexError:
                    continue
                try:
                    tr.next()
                    raise Exception('More than one trace returned')
                except StopIteration:
                    continue

            logger.debug('skipped %s/%s'%(skipped, unskipped))

            section.finish(self.reference_nsl, fband, taper)
            self.sections.append(section)
Esempio n. 32
0
def make_reference_markers_cake(source, targets, model):

    assert len(source) == 1

    ref_marker = defaultdict(dict)
    phases_start = ['p', 'P']
    phases_start = [cake.PhaseDef(ph) for ph in phases_start]

    phases_end = ['s', 'S']
    phases_end = [cake.PhaseDef(ph) for ph in phases_end]

    for s in source:
        for target in targets:
            dist = orthodrome.distance_accurate50m(s, target) * cake.m2d
            tmin = min(model.arrivals([dist],
                                      phases_start,
                                      zstart=s.depth,
                                      zstop=s.depth),
                       key=lambda x: x.t).t

            tmax = min(model.arrivals([dist],
                                      phases_end,
                                      zstart=s.depth,
                                      zstop=s.depth),
                       key=lambda x: x.t).t

            tmin += s.time
            tmax += s.time
            assert tmin != tmax
            m = gui_util.PhaseMarker(nslc_ids=target.codes,
                                     tmin=tmin,
                                     tmax=tmax,
                                     kind=1,
                                     event=source,
                                     phasename='range')

            ref_marker[s][target] = m
    return ref_marker
    def call(self):
       
        viewer = self.get_viewer()
        tmin, tmax = viewer.get_time_range()
        
        cat = self.catalogs[self.catalog]
        event_names = cat.get_event_names(
            time_range=(tmin,tmax), 
            magmin=self.magmin)

        if self.ref_station is not 'None':
            ref_station = self.get_viewer().get_station(tuple(self.ref_station.split('.')))

        for event_name in event_names:
            event = cat.get_event(event_name)
            if self.ref_station is not 'None':
                dist = orthodrome.distance_accurate50m(event, ref_station)
                if self.distmin and dist<self.distmin:
                    break
                if self.distmax and dist>self.distmax:
                    break
            marker = EventMarker(event)
            self.add_markers([marker])
Esempio n. 34
0
def get_traces(p,
               event,
               stations,
               trace_selector,
               tpad,
               time_window="distance_dependant",
               vmin=1500,
               vmax=6000,
               duration_fixed=200):

    # trace_selector_viewer = self.get_viewer_trace_selector('visible')
    if time_window == 'distance_dependant':
        for station in stations:
            distance = orthodrome.distance_accurate50m(event, station)
            tmin = distance / vmax
            tmax = (distance + event.depth) / vmin

            for trs in p.chopper(
                    tmin=event.time + tmin,
                    tmax=event.time + tmax,
                    tpad=tpad,
                    trace_selector=lambda tr:
                (trace_selector(tr) and tr.nslc_id[:3] == station.nsl())):

                for tr in trs:
                    yield tr

    elif time_window == 'fixed':  # put here chopper
        tmin = 0.
        tmax = duration_fixed
        for trs in p.chopper(tmin=event.time + tmin,
                             tmax=event.time + tmax,
                             tpad=tpad,
                             trace_selector=lambda tr: (trace_selector(tr))):

            for tr in trs:
                yield tr
Esempio n. 35
0
    def process(self, fband, taper):
        for event in self.candidates:
            section = Section(event, self.stations)
            skipped = 0
            unskipped = 0
            for i_s, s in enumerate(self.stations):
                dist = distance_accurate50m(event, s)
                arrival = self.phaser.t(self.phase_selection,
                                        (event.depth, dist))
                if arrival is None:
                    skipped += 1
                    logger.debug('skipping event %s at stations %s. ' +
                                 'Reason no phase arrival' % (event, s))
                    continue
                else:
                    unskipped += 1
                selector = lambda tr: util.match_nslc(
                    '%s.*%s' % (s.nsl_string(), self.component), tr.nslc_id)
                window_min, window_max = self.window.t()
                tr = self.data_pile.chopper(
                    tmin=event.time + arrival - window_min,
                    tmax=event.time + arrival + window_max,
                    trace_selector=selector)
                _tr = next(tr, False)  # does not work without try and except?!
                if not _tr or len(_tr) != 1:
                    continue
                if not _tr[0].ydata.size:
                    continue
                self.all_nslc_ids.add(_tr[0].nslc_id)

                section.extend(_tr)

            logger.debug('skipped %s/%s' % (skipped, unskipped))

            section.finish(self.reference_nsl, fband, taper)
            self.sections.append(section)
def interrelation(picks, interest="depth", stations=None):
    """:param interests: list of things you are interested in (depth|distance)"""
    if stations:
        station = dict(zip([s.nsl() for s in stations], stations))
    
    results = {}
    for p in picks:
        one_id = p.one_nslc()[:3]
        phasename = p.get_phasename()
        if stations is not None and one_id not in stations_ids:
            continue
        else:
            subresults = results.get(one_id, {})
            residuals = subresults.get(phasename, [])
            if interest=="depth":
                data_want = p.get_event().depth
            elif interest=="distance":
                data_want = orthodrome.distance_accurate50m(p.get_event(),
                                                            stations[one_id])
            residuals.append((data_want, p.residual))
            subresults[phasename] = residuals
            results[one_id] = subresults

    return results
Esempio n. 37
0
def make_reference_markers_cake(source, targets, model):
    
    assert len(source) == 1
    
    ref_marker = defaultdict(dict)
    phases_start = ['p','P']
    phases_start = [cake.PhaseDef(ph) for ph in phases_start]

    phases_end = ['s', 'S']
    phases_end = [cake.PhaseDef(ph) for ph in phases_end]
    
    for s in source:
        for target in targets:
            dist = orthodrome.distance_accurate50m(s, target)*cake.m2d
            tmin = min(model.arrivals([dist], 
                                    phases_start,
                                    zstart=s.depth,
                                    zstop=s.depth), key=lambda x: x.t).t

            tmax = min(model.arrivals([dist], 
                                    phases_end, 
                                    zstart=s.depth,
                                    zstop=s.depth), key=lambda x: x.t).t

            tmin += s.time
            tmax += s.time
            assert tmin!=tmax
            m = gui_util.PhaseMarker(nslc_ids=target.codes, 
                                    tmin=tmin,
                                    tmax=tmax,
                                    kind=1,
                                    event=source,
                                    phasename='range')

            ref_marker[s][target] = m
    return ref_marker
    def invert(self, args):
        align_phase = 'P'
        ampl_scaler = '4*standard deviation'

        for array_id in self.provider.use:
            try:
                if args.array_id and array_id != args.array_id:
                    continue
            except AttributeError:
                pass
            subdir = pjoin('array_data', array_id)
            settings_fn = pjoin(subdir, 'plot_settings.yaml')
            if os.path.isfile(settings_fn):
                settings = PlotSettings.load(filename=pjoin(settings_fn))
                settings.update_from_args(self.args)
            else:
                logger.warn('no settings found: %s' % array_id)
                continue
            if settings.store_superdirs:
                engine = LocalEngine(store_superdirs=settings.store_superdirs)
            else:
                engine = LocalEngine(use_config=True)
            try:
                store = engine.get_store(settings.store_id)
            except seismosizer.NoSuchStore as e:
                logger.info('%s ... skipping.' % e)
                return
            try:
                store = engine.get_store(settings.store_id)
            except seismosizer.NoSuchStore as e:
                logger.info('%s ... skipping.' % e)
                return

            if not settings.trace_filename:
                settings.trace_filename = pjoin(subdir, 'beam.mseed')
            if not settings.station_filename:
                settings.station_filename = pjoin(subdir, 'array_center.pf')
            zoom_window = settings.zoom
            mod = store.config.earthmodel_1d

            zstart, zstop, inkr = settings.depths.split(':')
            test_depths = num.arange(float(zstart)*km, float(zstop)*km, float(inkr)*km)
            traces = io.load(settings.trace_filename)
            event = model.load_events(settings.event_filename)
            assert len(event)==1
            event = event[0]
            event.depth = float(settings.depth) * 1000.
            base_source = MTSource.from_pyrocko_event(event)

            test_sources = []
            for d in test_depths:
                s = base_source.clone()
                s.depth = float(d)
                test_sources.append(s)

            stations = model.load_stations(settings.station_filename)
            station = filter(lambda s: match_nslc('%s.%s.%s.*' % s.nsl(), traces[0].nslc_id), stations)
            if len(station) != 1:
                logger.error('no matching stations found. %s %s' % []) 
            else:
                station = station[0]
            targets = [station_to_target(station, quantity=settings.quantity, store_id=settings.store_id)]
            try:
                request = engine.process(targets=targets, sources=test_sources)
            except seismosizer.NoSuchStore as e:
                logger.info('%s ... skipping.' % e)
                return
            except meta.OutOfBounds as error:
                if settings.force_nearest_neighbor:
                    logger.warning('%s  Using nearest neighbor instead.' % error)
                    mod_targets = []
                    for t in targets:
                        closest_source = min(test_sources, key=lambda s: s.distance_to(t))
                        farthest_source = max(test_sources, key=lambda s: s.distance_to(t))
                        min_dist_delta = store.config.distance_min - closest_source.distance_to(t)
                        max_dist_delta = store.config.distance_max - farthest_source.distance_to(t)
                        if min_dist_delta < 0:
                            azi, bazi = closest_source.azibazi_to(t)
                            newlat, newlon = ortho.azidist_to_latlon(t.lat, t.lon, azi, min_dist_delta*cake.m2d)
                        elif max_dist_delta < 0:
                            azi, bazi = farthest_source.azibazi_to(t)
                            newlat, newlon = ortho.azidist_to_latlon(t.lat, t.lon, azi, max_dist_delta*cake.m2d)
                        t.lat, t.lon = newlat, newlon
                        mod_targets.append(t)
                    request = engine.process(targets=mod_targets, sources=test_sources)
                else:
                    raise error

            candidates = []
            for s, t, tr in request.iter_results():
                tr.deltat = regularize_float(tr.deltat)
                if True:
                    tr = integrate_differentiate(tr, 'differentiate')
                tr = settings.do_filter(tr)
                candidates.append((s, tr))
            assert len(traces)==1
            ref = traces[0]
            ref = settings.do_filter(ref)
            dist = ortho.distance_accurate50m(event, station)
            tstart = self.provider.timings[array_id].timings[0].t(mod, (event.depth, dist)) + event.time
            tend = self.provider.timings[array_id].timings[1].t(mod, (event.depth, dist)) + event.time
            ref = ref.chop(tstart, tend)
            misfits = []

            center_freqs = num.arange(1., 9., 4.)
            num_f_widths = len(center_freqs)

            mesh_fc = num.zeros(len(center_freqs)*num_f_widths*len(candidates))
            mesh_fwidth = num.zeros(len(center_freqs)*num_f_widths*len(candidates))
            misfits_array = num.zeros((len(center_freqs), num_f_widths, len(candidates)))
            depths_array = num.zeros((len(center_freqs), num_f_widths, len(candidates)))
            debug = False
            pb = ProgressBar(maxval=max(center_freqs)).start()
            i = 0
            for i_fc, fc in enumerate(center_freqs):
                if debug:
                    fig = plt.figure()

                fl_min = fc-fc*2./5.
                fr_max = fc+fc*2./5.
                widths = num.linspace(fl_min, fr_max, num_f_widths)

                for i_width, width in enumerate(widths):
                    i_candidate = 0
                    mesh_fc[i] = fc
                    mesh_fwidth[i] = width
                    i += 1
                    for source, candidate in candidates:
                        candidate = candidate.copy()
                        tstart = self.provider.timings[array_id].timings[0].t(mod, (source.depth, dist)) + event.time
                        tend = self.provider.timings[array_id].timings[1].t(mod, (source.depth, dist)) + event.time
                        filters = [
                            ButterworthResponse(corner=float(fc+width*0.5), order=4, type='low'),
                            ButterworthResponse(corner=float(fc-width*0.5), order=4, type='high')]
                        settings.filters = filters
                        candidate = settings.do_filter(candidate)
                        candidate.chop(tmin=tstart, tmax=tend)
                        candidate.shift(float(settings.correction))
                        m, n, aproc, bproc = ref.misfit(candidate=candidate, setup=settings.misfit_setup, debug=True)
                        aproc.set_codes(station='aproc')
                        bproc.set_codes(station='bproc')
                        if debug:
                            ax = fig.add_subplot(len(test_depths)+1, 1, i+1)
                            ax.plot(aproc.get_xdata(), aproc.get_ydata())
                            ax.plot(bproc.get_xdata(), bproc.get_ydata())
                        mf = m/n
                        #misfits.append((source.depth, mf))
                        misfits_array[i_fc][i_width][i_candidate] = mf
                        i_candidate += 1
                pb.update(fc)

            pb.finish()
            fig = plt.figure()
            ax = fig.add_subplot(111)
            i_best_fits = num.argmin(misfits_array, 2)
            print 'best fits: \n', i_best_fits
            best_fits = num.min(misfits_array, 2)
            #cmap = matplotlib.cm.get_cmap()
            xmesh, ymesh = num.meshgrid(mesh_fc, mesh_fwidth)
            #c = (best_fits-num.min(best_fits))/(num.max(best_fits)-num.min(best_fits))
            ax.scatter(xmesh, ymesh, best_fits*100)
            #ax.scatter(mesh_fc, mesh_fwidth, c)
            #ax.scatter(mesh_fc, mesh_fwidth, s=best_fits)
            ax.set_xlabel('fc')
            ax.set_ylabel('f_width')
        plt.legend()
        plt.show()
Esempio n. 39
0
    def call(self, plot_rays=False):

        self.cleanup()
        wanted = self.wanted_phases()

        if not wanted:
            return

        event, stations = self.get_active_event_and_stations()

        if not stations:
            self.fail('No station information available.')

        self.update_model()
        model = self._model[1]

        depth = event.depth
        if depth is None:
            depth = 0.0

        allrays = []
        alldists = []
        for station in stations:
            dist = orthodrome.distance_accurate50m(event, station)
            alldists.append(dist)

            if self.use_station_depth:
                rdepth = station.depth
            else:
                rdepth = 0.0

            multi_dists = []
            nmax = 1
            for i in range(0, nmax):
                multi_dists.append(dist * cake.m2d + 360. * i)
                multi_dists.append((i + 1) * 360. - dist * cake.m2d)

            rays = model.arrivals(phases=wanted,
                                  distances=multi_dists,
                                  zstart=depth,
                                  zstop=rdepth)

            for ray in rays:
                time = ray.t
                name = ray.given_phase().name
                incidence_angle = ray.incidence_angle()
                takeoff_angle = ray.takeoff_angle()

                time += event.time + self.tshift
                m = PhaseMarker([(station.network, station.station, '*', '*')],
                                time,
                                time,
                                2,
                                phasename=name,
                                event=event,
                                incidence_angle=incidence_angle,
                                takeoff_angle=takeoff_angle)
                self.add_marker(m)

            allrays.extend(rays)

        if plot_rays:
            fig = self.figure(name='Ray Paths')
            from pyrocko import cake_plot
            cake_plot.my_rays_plot(model,
                                   None,
                                   allrays,
                                   depth,
                                   0.0,
                                   num.array(alldists) * cake.m2d,
                                   axes=fig.gca())

            fig.canvas.draw()
Esempio n. 40
0
from pyrocko import model, orthodrome as ortho
stations = model.load_stations('GERES/array_center.pf')
events = model.load_events('castor_event_IGN.dat')
for s in stations:
    print(s)
    print('distance in deg ',
          ortho.distance_accurate50m(s, events[0]) / 110.54 / 1000.)
Esempio n. 41
0
 def set_event_relative_data( self, event ):
     self.dist_m = orthodrome.distance_accurate50m( event, self )
     self.dist_deg = self.dist_m / orthodrome.earthradius_equator *orthodrome.r2d
     self.azimuth = orthodrome.azimuth(event, self)
     self.backazimuth = orthodrome.azimuth(self, event)
SkS_Phase = cake.PhaseDef('p')

nslc = []; statLat = []; statLon = []
distances = []
stationList = []
azi = 45

arrivals_dict={}
distanc=range(40*km,180*km,15*km)
print range(10,180,15)
for dist in distanc:
    print dist
    
    statLat , statLon = lat_lon_from_dist_azi(olon, olat, dist, azi)
    stat = model.Station(network=nslc, lat=statLat, lon=statLon)
    distances.append(orthodrome.distance_accurate50m(source_loc,stat)*cake.m2d)

    for n,arrival in enumerate(cake.mod.arrivals(distances, phases=SkS_Phase, zstart=source_depth)):

        if not str(arrival.path) in arrivals_dict.keys():
            arrivals_dict[str(arrival.path)]=[[arrival.x, arrival.efficiency()*100]]
        else:
            arrivals_dict[str(arrival.path)].append([arrival.x, arrival.efficiency()*100])

leg=[]
import matplotlib.pyplot as plt
for k in arrivals_dict.keys():
    x=[]; eff=[] 
    #ofile.write(")

    for line in arrivals_dict[k]:
Esempio n. 43
0
 def get_radius(self):
     coords = self.coordinates
     return od.distance_accurate50m(coords[:, 0].min(), coords[:, 1].min(),
                                    coords[:, 0].max(),
                                    coords[:, 1].max()) / 2.
Esempio n. 44
0
 def get_radius(self):
     coords = self.coordinates
     return od.distance_accurate50m(
         coords[:, 0].min(), coords[:, 1].min(),
         coords[:, 0].max(), coords[:, 1].max()) / 2.
    def process(self, event, timing, bazi=None, slow=None,  restitute=False, *args, **kwargs):
        '''
        :param timing: CakeTiming. Uses the definition without the offset.
        :param fn_dump_center: filename to where center stations shall be dumped
        :param fn_beam: filename of beam trace
        :param model: earthmodel to use (optional)
        :param earthmodel to use (optional)
        :param network: network code (optional)
        :param station: station code (optional)
        '''
        logger.debug('start beam forming')
        stations = self.stations
        network_code = kwargs.get('responses', None)
        network_code = kwargs.get('network', '')
        station_code = kwargs.get('station', 'STK')
        c_station_id = (network_code, station_code)

        lat_c, lon_c, z_c = self.c_lat_lon_z

        self.station_c = Station(lat=float(lat_c),
                                 lon=float(lon_c),
                                 elevation=float(z_c),
                                 depth=0.,
                                 name='Array Center',
                                 network=c_station_id[0],
                                 station=c_station_id[1][:5])
        fn_dump_center = kwargs.get('fn_dump_center', 'array_center.pf')
        fn_beam = kwargs.get('fn_beam', 'beam.mseed')
        if event:
            mod = cake.load_model(crust2_profile=(event.lat, event.lon))
            dist = ortho.distance_accurate50m(event, self.station_c)
            ray = timing.t(mod, (event.depth, dist), get_ray=True)
            if ray is None:
                logger.error('None of defined phases available at beam station:\n %s' % self.station_c)
                return
            else:
                b = ortho.azimuth(self.station_c, event)
                if b>=0.:
                    self.bazi = b
                elif b<0.:
                    self.bazi = 360.+b
                self.slow = ray.p/(cake.r2d*cake.d2m)
        else:
            self.bazi = bazi
            self.slow = slow

        logger.info('stacking %s with slowness %1.4f s/km at back azimut %1.1f '
                    'degrees' %('.'.join(c_station_id), self.slow*cake.km, self.bazi))

        lat0 = num.array([lat_c]*len(stations))
        lon0 = num.array([lon_c]*len(stations))
        lats = num.array([s.lat for s in stations])
        lons = num.array([s.lon for s in stations])
        ns, es = ortho.latlon_to_ne_numpy(lat0, lon0, lats, lons)
        theta = num.float(self.bazi*num.pi/180.)
        R = num.array([[num.cos(theta), -num.sin(theta)],
                        [num.sin(theta), num.cos(theta)]])
        distances = R.dot(num.vstack((es, ns)))[1]
        channels = set()
        self.stacked = {}
        num_stacked = {}
        self.t_shifts = {}
        self.shifted_traces = []
        taperer = trace.CosFader(xfrac=0.05)
        if self.diff_dt_treat=='downsample':
            self.traces.sort(key=lambda x: x.deltat)
        elif self.diff_dt_treat=='oversample':
            dts = [t.deltat for t in self.traces]
            for tr in self.traces:
                tr.resample(min(dts))

        for tr in self.traces:
            if tr.nslc_id[:2] == c_station_id:
                continue
            tr = tr.copy(data=True)
            tr.ydata = tr.ydata.astype(num.float64) - tr.ydata.mean(dtype=num.float64)
            tr.taper(taperer)
            try:
                stack_trace = self.stacked[tr.channel]
                num_stacked[tr.channel] += 1
            except KeyError:
                stack_trace = tr.copy(data=True)
                stack_trace.set_ydata(num.zeros(
                    len(stack_trace.get_ydata())))

                stack_trace.set_codes(network=c_station_id[0],
                                      station=c_station_id[1],
                                      location='',
                                      channel=tr.channel)

                self.stacked[tr.channel] = stack_trace
                channels.add(tr.channel)
                num_stacked[tr.channel] = 1

            nslc_id = tr.nslc_id

            try:
                stats = filter(lambda x: util.match_nslc(
                    '%s.%s.%s.*' % x.nsl(), nslc_id), stations)

                stat = stats[0]
            except IndexError:
                break

            i = stations.index(stat)
            d = distances[i]
            t_shift = d*self.slow
            tr.shift(t_shift)
            #stat = viewer.get_station(tr.nslc_id[:2])
            self.t_shifts[tr.nslc_id[:2]] = t_shift
            if self.normalize_std:
                tr.ydata = tr.ydata/tr.ydata.std()

            if num.abs(tr.deltat-stack_trace.deltat)>0.000001:
                if self.diff_dt_treat=='downsample':
                    stack_trace.downsample_to(tr.deltat)
                elif self.diff_dt_treat=='upsample':
                    raise Exception('something went wrong with the upsampling, previously')
            stack_trace.add(tr)

            tr.set_station('%s_s' % tr.station)
            self.shifted_traces.append(tr)

        if self.post_normalize:
            for ch, tr in self.stacked.items():
                tr.set_ydata(tr.get_ydata()/num_stacked[ch])
        #for ch, tr in self.stacked.items():
        #    if num_stacked[ch]>1:
        #        self.add_trace(tr)
        self.save_station(fn_dump_center)
        self.checked_nslc([stack_trace])
        self.save(stack_trace, fn_beam)
 def estimate(self, phase, station):
     distance = orthodrome.distance_accurate50m(station, phase.get_event())*cake.m2d
     phasenames = self.map_phasenames(phase.get_phasename())
     phase_str = "first(%s)"%("|".join(phasenames))
     t = self.store.t(phase_str, (phase.get_event().depth, distance))
     return self.return_residual(phase, t)
Esempio n. 47
0
def gdist(a, b):
    return int(orthodrome.distance_accurate50m(a, b) / 1000.)
Esempio n. 48
0
def max_dist(event, stations):
    dists = [distance_accurate50m(event, s) for s in stations]
    return max(dists)
Esempio n. 49
0
from pyrocko import orthodrome, model

e = model.Event(lat=37.58, lon=57.11)
s = model.Event(lat=34.884, lon=57.159)
dist = orthodrome.distance_accurate50m(e, s)
print(dist/1000)

# Azimuth and Back Azimuth
az = orthodrome.azibazi(e, s)
print (az)
Esempio n. 50
0
    def call(self):
        self.cleanup()

        viewer = self.get_viewer()

        master = viewer.get_active_event()

        if master is None:
            self.fail('no master event selected')

        stations = list(viewer.stations.values())
        stations.sort(key=lambda s: (s.network,s.station))

        if not stations:
            self.fail('no station information available')

        # gather events to be processed

        events = []
        for m in viewer.markers:
            if isinstance(m, EventMarker):
                if m.kind == 0:
                    events.append( m.get_event() )

        events.sort(key=lambda ev: ev.time)

        event_to_number = {}
        for iev, ev in enumerate(events):
            event_to_number[ev] = iev

        if self.model_select.startswith('Global'):
            model_key = 'global'
        else:
            model_key = master.lat, master.lon

        if model_key != self.model_key:
            if self.model_select.startswith('Global'):
                self.model = cake.load_model()
            else:
                latlon = master.lat, master.lon
                profile = crust2x2.get_profile(*latlon)
                profile.set_layer_thickness(crust2x2.LWATER, 0.0)
                self.model = cake.LayeredModel.from_scanlines(
                        cake.from_crust2x2_profile(profile))

            self.model_key = model_key

        phases = { 
                'P': ([ cake.PhaseDef(x) for x in 'P p'.split() ], 'Z'),
                'S': ([ cake.PhaseDef(x) for x in 'S s'.split() ], 'NE'),
            }

        phasenames = phases.keys()
        phasenames.sort()

        # synthetic arrivals and ray geometry for master event
        master_depth = master.depth
        if self.master_depth_km is not None:
            master_depth = self.master_depth_km * km

        tt = {}
        g = {}
        for iphase, phasename in enumerate(phasenames):
            for istation, station in enumerate(stations):
                dist = orthodrome.distance_accurate50m(master, station)
                azi = orthodrome.azimuth(master, station)

                arrivals = self.model.arrivals(
                        phases=phases[phasename][0], 
                        distances=[ dist*cake.m2d ],
                        zstart = master_depth,
                        zstop = 0.0)

                if arrivals:
                    first = arrivals[0]
                    tt[station.network, station.station, phasename] = first.t

                    takeoff = first.takeoff_angle()
                    u = first.path.first_straight().u_in(first.endgaps)

                    g[iphase, istation] = num.array([
                            math.cos(azi*d2r) * math.sin(takeoff*d2r) * u,
                            math.sin(azi*d2r) * math.sin(takeoff*d2r) * u,
                            math.cos(takeoff*d2r) * u ])
        
        # gather picks for each event

        for ev in events:
            picks = {}
            for m2 in viewer.markers:
                if isinstance(m2, PhaseMarker) and m2.kind == 0:
                    if m2.get_event() == ev:
                        net, sta, _, _ = m2.one_nslc()
                        picks[net,sta,m2.get_phasename()] = (m2.tmax + m2.tmin) / 2.0

            ev.picks = picks

        # time corrections for extraction windows

        dataobs = []
        datasyn = []
        for phasename in phasenames:
            for station in stations:
                nsp = station.network, station.station, phasename
                datasyn.append(tt.get(nsp,None))
                for ev in events:
                    if nsp in ev.picks: 
                        ttobs = ev.picks[nsp] - ev.time
                    else:
                        ttobs = None

                    dataobs.append(ttobs)

        ttsyn = num.array(datasyn, dtype=num.float).reshape((
            len(phasenames),
            len(stations)))

        ttobs = num.array(dataobs, dtype=num.float).reshape((
            len(phasenames),
            len(stations),
            len(events)))

        ttres = ttobs - ttsyn[:,:,num.newaxis]
        tt_corr_event = num.nansum( ttres, axis=1) /  \
                num.nansum( num.isfinite(ttres), axis=1 )

        tt_corr_event = num.where(num.isfinite(tt_corr_event), tt_corr_event, 0.)

        ttres -= tt_corr_event[:,num.newaxis,:]
        tt_corr_station = num.nansum( ttres, axis=2) /  \
                num.nansum( num.isfinite(ttres), axis=2 )

        tt_corr_station = num.where(num.isfinite(tt_corr_station), tt_corr_station, 0.)

        ttres -= tt_corr_station[:,:, num.newaxis]

        tevents_raw = num.array( [ ev.time for ev in events ] )

        tevents_corr = tevents_raw + num.mean(tt_corr_event, axis=0)

        # print timing information

        print 'timing stats'

        for iphasename, phasename in enumerate(phasenames):
            data = []
            for ev in events:
                iev = event_to_number[ev]
                for istation, station in enumerate(stations):
                    nsp = station.network, station.station, phasename
                    if nsp in tt and nsp in ev.picks: 
                        tarr = ev.time + tt[nsp]
                        tarr_ec = tarr + tt_corr_event[iphasename, iev]
                        tarr_ec_sc = tarr_ec + tt_corr_station[iphasename, istation]
                        tobs = ev.picks[nsp]

                        data.append((tobs-tarr, tobs-tarr_ec, tobs-tarr_ec_sc))

            if data:

                data = num.array(data, dtype=num.float).T

                print 'event %10s %3s %3i %15.2g %15.2g %15.2g' % (
                        (ev.name, phasename, data.shape[1]) + 
                            tuple( num.mean(num.abs(x)) for x in data ))
            else:
                print 'event %10s %3s no picks' % (ev.name, phasename)

        # extract and preprocess waveforms

        tpad = 0.0
        for f in self.corner_highpass, self.corner_lowpass:
            if f is not None:
                tpad = max(tpad, 1.0/f)


        pile = self.get_pile()
        waveforms = {}
        for ev in events:
            iev = event_to_number[ev]
            markers = []
            for iphasename, phasename in enumerate(phasenames):
                for istation, station in enumerate(stations):
                    nsp = station.network, station.station, phasename
                    if nsp in tt:
                        tarr = ev.time + tt[nsp]
                        nslcs = [ ( station.network, station.station, '*', '*' ) ]
                        marker = PhaseMarker( nslcs, tarr, tarr, 1, event=ev,
                                phasename=phasename)
                        markers.append(marker)

                        tarr2 = tarr + tt_corr_station[iphasename, istation] + \
                                tt_corr_event[iphasename, iev]

                        marker = PhaseMarker( nslcs, tarr2, tarr2, 2, event=ev,
                                phasename=phasename)

                        markers.append(marker)

                        tmin = tarr2+self.tstart
                        tmax = tarr2+self.tend

                        marker = PhaseMarker( nslcs, 
                                tmin, tmax, 3, event=ev,
                                phasename=phasename)

                        markers.append(marker)

                        trs = pile.all(tmin, tmax, tpad=tpad, trace_selector=
                                lambda tr: tr.nslc_id[:2] == nsp[:2], 
                                want_incomplete=False)

                        trok = []
                        for tr in trs:
                            if num.all(tr.ydata[0] == tr.ydata):
                                continue

                            if self.corner_highpass:
                                tr.highpass(4, self.corner_highpass)
                            if self.corner_lowpass:
                                tr.lowpass(4, self.corner_lowpass)



                            tr.chop(tmin, tmax)
                            tr.set_location(ev.name)
                            #tr.shift( - (tmin - master.time) )
                            
                            if num.all(num.isfinite(tr.ydata)):
                                trok.append(tr)

                        waveforms[nsp+(iev,)] = trok

            self.add_markers(markers)

        def get_channel(trs, cha):
            for tr in trs:
                if tr.channel == cha:
                    return tr
            return None

        nevents = len(events)
        nstations = len(stations)
        nphases = len(phasenames)

        # correlate waveforms

        coefs = num.zeros((nphases, nstations, nevents, nevents))
        coefs.fill(num.nan)
        tshifts = coefs.copy()
        tshifts_picked = coefs.copy()
        for iphase, phasename in enumerate(phasenames):
            for istation, station in enumerate(stations):
                nsp = station.network, station.station, phasename

                for a in events:
                    ia = event_to_number[a]
                    for b in events:
                        ib = event_to_number[b]

                        if ia == ib:
                            continue

                        if nsp in a.picks and nsp in b.picks:
                            tshifts_picked[iphase,istation,ia,ib] = \
                                    b.picks[nsp] - a.picks[nsp]
                     
                        wa = waveforms[nsp+(ia,)]
                        wb = waveforms[nsp+(ib,)]

                        channels = list(set([ tr.channel for tr in wa + wb ]))
                        channels.sort()

                        tccs = []
                        for cha in channels:
                            if cha[-1] not in phases[phasename][1]:
                                continue

                            ta = get_channel(wa, cha)
                            tb = get_channel(wb, cha)
                            if ta is None or tb is None:
                                continue

                            tcc = trace.correlate(ta,tb, mode='full', normalization='normal',
                                    use_fft=True)
                            
                            tccs.append(tcc)
                        
                        if not tccs:
                            continue

                        tc = None
                        for tcc in tccs:
                            if tc is None:
                                tc = tcc
                            else:
                                tc.add(tcc)

                        tc.ydata *= 1./len(tccs)

                        tmid = tc.tmin*0.5 + tc.tmax*0.5
                        tlen = (tc.tmax - tc.tmin)*0.5
                        tc_cut = tc.chop(tmid-tlen*0.5, tmid+tlen*0.5, inplace=False)

                        tshift, coef = tc_cut.max()

                        if (tshift < tc.tmin + 0.5*tc.deltat or
                                tc.tmax - 0.5*tc.deltat < tshift):
                            continue

                        coefs[iphase,istation,ia,ib] = coef
                        tshifts[iphase,istation,ia,ib] = tshift

                        if self.show_correlation_traces:
                            tc.shift(master.time - (tc.tmax + tc.tmin)/2.)
                            self.add_trace(tc)


        #tshifts = tshifts_picked

        coefssum_sta = num.nansum(coefs, axis=2) / num.sum(num.isfinite(coefs), axis=2)
        csum_sta = num.nansum(coefssum_sta, axis=2) / num.sum(num.isfinite(coefssum_sta), axis=2)

        for iphase, phasename in enumerate(phasenames):
            for istation, station in enumerate(stations):
                print 'station %-5s %s %15.2g' % (station.station, phasename, csum_sta[iphase,istation])

        coefssum = num.nansum(coefs, axis=1) / num.sum(num.isfinite(coefs), axis=1)
        csumevent = num.nansum(coefssum, axis=2) / num.sum(num.isfinite(coefssum), axis=2)
        above = num.where(num.isfinite(coefs), coefs >= self.min_corr, 0)

        csumabove = num.sum(num.sum(above, axis=1), axis=2)

        coefssum = num.ma.masked_invalid(coefssum)

        print 'correlation stats'

        for iphase, phasename in enumerate(phasenames):
            for ievent, event in enumerate(events):
                print 'event %10s %3s %8i %15.2g' % (
                        event.name, phasename, 
                        csumabove[iphase,ievent], csumevent[iphase,ievent])

        # plot event correlation matrix

        fframe = self.figure_frame()
        fig = fframe.gcf()

        for iphase, phasename in enumerate(phasenames):

            p = fig.add_subplot(1,nphases,iphase+1)
            p.set_xlabel('Event number')
            p.set_ylabel('Event number')
            mesh = p.pcolormesh(coefssum[iphase])
            cb = fig.colorbar(mesh, ax=p)
            cb.set_label('Max correlation coefficient')

        if self.save:
            fig.savefig(self.output_filename(dir='correlation.pdf'))

        fig.canvas.draw()


        # setup and solve linear system

        data = []
        rows = []
        weights = []
        for iphase in xrange(nphases):
            for istation in xrange(nstations):
                for ia in xrange(nevents):
                    for ib in xrange(ia+1,nevents):
                        k = iphase, istation, ia, ib
                        w = coefs[k]
                        if not num.isfinite(tshifts[k]) \
                                or not num.isfinite(w) or w < self.min_corr:
                            continue

                        row = num.zeros(nevents*4)
                        row[ia*4:ia*4+3] = g[iphase,istation]
                        row[ia*4+3] = -1.0
                        row[ib*4:ib*4+3] = -g[iphase,istation]
                        row[ib*4+3] = 1.0
                        
                        weights.append(w)

                        rows.append(row)
                        data.append(tshifts[iphase,istation,ia,ib])

        nsamp = len(data)

        for i in range(4):
            row = num.zeros(nevents*4)
            row[i::4] = 1.
            rows.append(row)
            data.append(0.0)

        if self.fix_depth:
            for ievent in range(nevents):
                row = num.zeros(nevents*4)
                row[ievent*4+2] = 1.0 
                rows.append(row)
                data.append(0.0)

        a = num.array(rows, dtype=num.float)
        d = num.array(data, dtype=num.float)
        w = num.array(weights, dtype=num.float)

        if self.weighting == 'equal':
            w[:nsamp] = 1.0
        elif self.weighting == 'linear':
            pass
        elif self.weighting == 'quadratic':
            w[:nsamp] = w[:nsamp]**2

        a[:nsamp,:] *= w[:,num.newaxis]
        d[:nsamp] *= w[:nsamp]

        x, residuals, rank, singular = num.linalg.lstsq(a,d)

        x0 = num.zeros(nevents*4)
        x0[3::4] = tevents_corr
        mean_abs_residual0 = num.mean( 
                num.abs((num.dot(a[:nsamp], x0) - d[:nsamp])/w[:nsamp]))
        
        mean_abs_residual = num.mean( 
                num.abs((num.dot(a[:nsamp],x) - d[:nsamp])/w[:nsamp]))

        print mean_abs_residual0, mean_abs_residual

        # distorted solutions

        npermutations = 100
        noiseamount = mean_abs_residual
        xdistorteds = []
        for i in range(npermutations):
            dnoisy = d.copy()
            dnoisy[:nsamp] += num.random.normal(size=nsamp)*noiseamount*w[:nsamp]
            xdistorted, residuals, rank, singular = num.linalg.lstsq(a,dnoisy)
            xdistorteds.append(xdistorted)

            mean_abs_residual = num.mean(num.abs(num.dot(a,xdistorted)[:nsamp] - dnoisy[:nsamp]))

        tmean = num.mean([ e.time for e in events ])

        north = x[0::4]
        east = x[1::4]
        down = x[2::4] 
        etime = x[3::4] + tmean

        def plot_range(x):
            mi, ma = num.percentile(x, [10., 90.])
            ext = (ma-mi)/5.
            mi -= ext
            ma += ext
            return mi, ma

        lat, lon = orthodrome.ne_to_latlon(master.lat, master.lon, north, east)

        events_out = []
        for ievent, event in enumerate(events):
            event_out = model.Event(time=etime[ievent],
                    lat=lat[ievent],
                    lon=lon[ievent],
                    depth=down[ievent] + master_depth,
                    name = event.name)

            mark = EventMarker(event_out, kind=4)
            self.add_marker(mark)
            events_out.append(event_out)

        model.Event.dump_catalog(events_out, 'events.relocated.txt')

        # plot results

        ned_orig = []
        for event in events:
            n, e = orthodrome.latlon_to_ne(master, event)
            d = event.depth

            ned_orig.append((n,e,d))

        ned_orig = num.array(ned_orig)

        ned_orig[:,0] -= num.mean(ned_orig[:,0])
        ned_orig[:,1] -= num.mean(ned_orig[:,1])
        ned_orig[:,2] -= num.mean(ned_orig[:,2])

        north0, east0, down0 = ned_orig.T

        north2, east2, down2, time2 = num.hstack(xdistorteds).reshape((-1,4)).T

        fframe = self.figure_frame()
        fig = fframe.gcf()

        color_sym = (0.1,0.1,0.0)
        color_scat = (0.3,0.5,1.0,0.2)

        d = u'\u0394 '

        if not self.fix_depth:
            p = fig.add_subplot(2,2,1, aspect=1.0)
        else:
            p = fig.add_subplot(1,1,1, aspect=1.0)

        mi_north, ma_north = plot_range(north)
        mi_east, ma_east = plot_range(east)
        mi_down, ma_down = plot_range(down)

        p.set_xlabel(d+'East [km]')
        p.set_ylabel(d+'North [km]')
        p.plot(east2/km, north2/km, '.', color=color_scat, markersize=2)
        p.plot(east/km, north/km, '+', color=color_sym)
        p.plot(east0/km, north0/km, 'x', color=color_sym)
        p0 = p

        for i,ev in enumerate(events):
            p.text(east[i]/km, north[i]/km, ev.name, clip_on=True)

        if not self.fix_depth:


            p = fig.add_subplot(2,2,2, sharey=p0, aspect=1.0)
            p.set_xlabel(d+'Depth [km]')
            p.set_ylabel(d+'North [km]')
            p.plot(down2/km, north2/km, '.', color=color_scat, markersize=2)
            p.plot(down/km, north/km, '+', color=color_sym)
            for i,ev in enumerate(events):
                p.text(down[i]/km, north[i]/km, ev.name, clip_on=True)


            p1 = p

            p = fig.add_subplot(2,2,3, sharex=p0, aspect=1.0)
            p.set_xlabel(d+'East [km]')
            p.set_ylabel(d+'Depth [km]')
            p.plot(east2/km, down2/km, '.', color=color_scat, markersize=2)
            p.plot(east/km, down/km, '+', color=color_sym)
            for i,ev in enumerate(events):
                p.text(east[i]/km, down[i]/km, ev.name, clip_on=True)


            p.invert_yaxis()
            p2 = p

        p0.set_xlim(mi_east/km, ma_east/km)
        p0.set_ylim(mi_north/km, ma_north/km)

        if not self.fix_depth:
            p1.set_xlim(mi_down/km, ma_down/km)
            p2.set_ylim(mi_down/km, ma_down/km)
            
        if self.save:
            fig.savefig(self.output_filename(dir='locations.pdf'))

        fig.canvas.draw()
Esempio n. 51
0
    def call(self):

        self.cleanup()
        viewer = self.get_viewer()

        vtmin, vtmax = viewer.get_time_range()
        pile = self.get_pile()
        traces = list(
            pile.chopper(tmin=vtmin,
                         tmax=vtmax,
                         trace_selector=viewer.trace_selector))
        event, _ = self.get_active_event_and_stations()
        traces = [tr for trs in traces for tr in trs]
        stations = []
        for tr in traces:
            if tr.nslc_id[:2] in viewer.stations.keys():
                stations.append(viewer.get_station(viewer.station_key(tr)))
        distances = [ortho.distance_accurate50m(event, s) for s in stations]
        distances = [d / 1000. for d in distances]
        maxd = max(distances)
        mind = min(distances)
        distances = dict(zip([s.nsl() for s in stations], distances))
        matching_traces = [
            x for x in traces
            if util.match_nslc(self.get_station_patterns(stations), x.nslc_id)
        ]
        if self.add_markers:
            markers = self.get_markers()
            markers = [
                m for m in markers
                if m.tmax <= vtmax and m.tmin >= vtmin and m.selected
            ]
            markers = dict(zip([tuple(m.nslc_ids) for m in markers], markers))

        if self.fig is None or self.fframe.closed is True or not self._live_update:
            self.fframe = self.pylab(get='figure_frame')
            self.fig = self.fframe.gcf()

        if self._live_update:
            self.fig.clf()

        ymin = mind - 0.06 * (maxd - mind)
        ymax = maxd + 0.06 * (maxd - mind)
        ax = self.fig.add_subplot(111)
        xmin = 9E9
        xmax = -xmin
        texts = []
        manual_scale = 0.1 * (maxd - mind) * self.yscale

        if self.ampl_scaler == 'total min/max':
            max_trace = max(matching_traces,
                            key=lambda x: max(abs(x.get_ydata())))
            tr_maxy = max(abs(max_trace.get_ydata()))
            ampl_scale = float(tr_maxy)

        for tr in matching_traces:
            if viewer.highpass:
                tr.highpass(4, viewer.highpass)
            if viewer.lowpass:
                tr.lowpass(4, viewer.lowpass)
            if tr.nslc_id[:3] not in distances.keys():
                continue

            if self.t_red:
                red = distances[tr.nslc_id[:3]] / self.t_red
            else:
                red = 0.
            y_pos = distances[tr.nslc_id[:3]]
            xdata = tr.get_xdata() - red - event.time
            xmin = min(xmin, min(xdata))
            xmax = max(xmax, max(xdata))
            tr_ydata = tr.get_ydata()
            if self.ampl_scaler == 'trace min/max':
                ampl_scale = float(max(abs(tr_ydata)))
            elif self.ampl_scaler == 'standard deviation':
                ampl_scale = float(num.std(tr_ydata))
            ydata = (tr_ydata / ampl_scale * manual_scale) + y_pos
            ax.plot(xdata, ydata, c='black', linewidth=0.2)
            if self.fill_between:
                ax.fill_between(xdata,
                                y_pos,
                                ydata,
                                where=ydata > y_pos,
                                color='black',
                                alpha=0.5)
            texts.append(
                ax.text(xmax,
                        y_pos,
                        '%s.%s.%s.%s' % tr.nslc_id,
                        horizontalalignment='right',
                        fontsize=6.))
            if self.add_markers:
                for ids, m in markers.items():
                    if m.match_nslc(tr.nslc_id) or ids == ():
                        c = m.select_color(m.color_b)
                        c = [ci / 255. for ci in c]
                        t = m.tmin
                        x = [t - red - event.time, t - red - event.time]
                        y = [
                            y_pos - (maxd - mind) * 0.025,
                            y_pos + (maxd - mind) * 0.025
                        ]
                        ax.plot(x, y, linewidth=1, color=c)
                        label = m.get_label()
                        if not label:
                            label = ''

                        ax.text(x[1] - x[1] * 0.005,
                                y[1],
                                label,
                                color=c,
                                fontsize=6,
                                verticalalignment='top',
                                horizontalalignment='right')
        for txt in texts:
            txt.set_x(xmax)
        vred_str = '= '+str(round(self.t_red, 2)) + 'km/s' if self.t_red \
                else 'off'
        ax.text(0.5,
                0.01,
                'time window: %s - %s  |   Reduction velocity %s' %
                (util.tts(vtmin), util.tts(vtmax), vred_str),
                verticalalignment='bottom',
                horizontalalignment='center',
                transform=self.fig.transFigure)

        ax.set_ylim([ymin, ymax])
        ax.set_xlim([xmin, xmax])
        ax.set_ylabel('Distance [km]')
        ax.set_xlabel('(red.) Time [s]')
        self.fig.canvas.draw()
    def download(self, event, directory='array_data', timing=None, length=None,
                 want='all', force=False, prefix=False, dump_config=False,
                 get_responses=False):
        """:param want: either 'all' or ID as string or list of IDs as strings
        """
        use = []
        #ts = {}
        unit = 'M'
        if all([timing, length]) is None:
            raise Exception('Define one of "timing" and "length"')
        prefix = prefix or ''
        directory = pjoin(prefix, directory)
        if not os.path.isdir(directory):
            os.mkdir(directory)
        pzresponses = {}
        logger.info('download data: %s at %sN %sE' % (
            event.name, event.lat, event.lon))
        for site, array_data_provder in self.providers.items():
            logger.info('requesting data from site %s' % site)
            for array_id, codes in array_data_provder.items():
                if array_id not in want and want != ['all']:
                    continue
                sub_directory = pjoin(directory, array_id)
                logger.info("%s" % array_id)
                codes = array_data_provder[array_id]
                if not isinstance(codes, list):
                    codes = [codes]
                selection = [
                    c + tuple((event.time, event.time+1000.)) for c in codes]
                logger.debug('selection: %s' % selection)
                try:
                #    if site=='bgr':
                #        st = ws.station(url='http://eida.bgr.de/', selection=selection)
                #    else:
                #        st = ws.station(site=site, selection=selection)
                    st = ws.station(site=site, selection=selection)
                except ws.EmptyResult as e:
                    logging.error('No results: %s %s. skip' % (e, array_id))
                    continue
                except ValueError as e:
                    logger.error(e)
                    logger.error('...skipping...')
                    continue

                stations = st.get_pyrocko_stations()
                min_dist = min(
                    [ortho.distance_accurate50m(s, event) for s in stations])
                max_dist = max(
                    [ortho.distance_accurate50m(s, event) for s in stations])

                mod = cake.load_model(crust2_profile=(event.lat, event.lon))
                if length:
                    tstart = 0.
                    tend = length
                elif timing:
                    tstart = timing[0].t(mod, (event.depth, min_dist))
                    tend = timing[1].t(mod, (event.depth, max_dist))
                selection = [
                    c + tuple((event.time + tstart, event.time + tend)
                              ) for c in codes]
                try:
                    d = ws.dataselect(site=site, selection=selection)
                    store.remake_dir(sub_directory, force)
                    store.remake_dir(pjoin(sub_directory, 'responses'), force)
                    fn = pjoin(sub_directory, 'traces.mseed')
                    with open(fn, 'w') as f:
                        f.write(d.read())
                        f.close()
                    if get_responses:
                        trs = io.load(fn, getdata=False)
                        logger.info('Request responses from %s' % site)
                        if progressbar:
                            pb = progressbar.ProgressBar(maxval=len(trs)).start()
                        for i_tr, tr in enumerate(trs):
                            try:
                                st = ws.station(
                                    site=site, selection=selection, level='response')
                                pzresponse = st.get_pyrocko_response(
                                    nslc=tr.nslc_id,
                                    timespan=(tr.tmin, tr.tmax),
                                    fake_input_units=unit)
                                pzresponse.regularize()
                            except fdsnstation.NoResponseInformation as e:
                                logger.warn("no response information: %s" % e)
                                pzresponse = None
                                pass
                            except fdsnstation.MultipleResponseInformation as e:
                                logger.warn("MultipleResponseInformation: %s" % e)
                                pzresponse = None
                                pass
                            pzresponses[tr.nslc_id] = pzresponse
                            pzresponses[tr.nslc_id].dump(filename=pjoin(
                                sub_directory,
                                'responses',
                                'resp_%s.yaml' % '.'.join(tr.nslc_id)))
                            if progressbar:
                                pb.update(i_tr)
                        if progressbar:
                            pb.finish()
                    model.dump_stations(
                        stations, pjoin(sub_directory, 'stations.pf'))

                    if timing:
                        t = Timings(list(timing))
                        self.timings[array_id] = t
                    if array_id not in use and array_id not in self.use:
                        use.append(array_id)
                except ws.EmptyResult as e:
                    logging.error('%s on %s' % (e, array_id))

        self.use.extend(use)
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.))
Esempio n. 54
0
    def call(self):

        self.cleanup()
        viewer = self.get_viewer()

        vtmin, vtmax = viewer.get_time_range()
        pile = self.get_pile()
        traces = [
            tr for tr in pile.chopper(
                tmin=vtmin, tmax=vtmax, trace_selector=viewer.trace_selector)]

        event, stations = self.get_active_event_and_stations()
        traces = [tr for trs in traces for tr in trs]

        stations_by_nsl = {s.nsl(): s for s in self.get_stations()}
        stations = [
            stations_by_nsl.get(station_key(tr), None) for tr in traces]

        distances = [
            ortho.distance_accurate50m(event, s) for s in stations if
            s is not None]

        distances = [d/1000. for d in distances]
        maxd = max(distances)
        mind = min(distances)
        distances = dict(zip([s.nsl() for s in stations], distances))
        matching_traces = [x for x in traces if util.match_nslc(
                            self.get_station_patterns(stations), x.nslc_id)]
        if self.add_markers:
            markers = self.get_markers()
            markers = [
                m for m in markers if m.tmax <= vtmax and
                m.tmin >= vtmin and m.selected]

            markers = dict(zip([tuple(m.nslc_ids) for m in markers], markers))

        if self.fig is None or self.fframe.closed or not self._live_update:
            self.fframe = self.pylab(get='figure_frame')
            self.fig = self.fframe.gcf()

        if self._live_update:
            self.fig.clf()

        ymin = mind-0.06*(maxd-mind)
        ymax = maxd+0.06*(maxd-mind)
        ax = self.fig.add_subplot(111)
        xmin = 9E9
        xmax = -xmin
        texts = []
        manual_scale = 0.1 * (maxd-mind)*self.yscale

        if self.ampl_scaler == 'total min/max':
            max_trace = max(
                matching_traces, key=lambda x: max(abs(x.get_ydata())))

            tr_maxy = max(abs(max_trace.get_ydata()))
            ampl_scale = float(tr_maxy)

        for tr in matching_traces:
            if viewer.highpass:
                tr.highpass(4, viewer.highpass)
            if viewer.lowpass:
                tr.lowpass(4, viewer.lowpass)
            if tr.nslc_id[:3] not in distances.keys():
                continue

            if self.t_red:
                red = distances[tr.nslc_id[:3]]/self.t_red
            else:
                red = 0.
            y_pos = distances[tr.nslc_id[:3]]
            xdata = tr.get_xdata()-red-event.time
            xmin = min(xmin, min(xdata))
            xmax = max(xmax, max(xdata))
            tr_ydata = tr.get_ydata()
            if self.ampl_scaler == 'trace min/max':
                ampl_scale = float(max(abs(tr_ydata)))
            elif self.ampl_scaler == 'standard deviation':
                ampl_scale = float(num.std(tr_ydata))
            ydata = (tr_ydata/ampl_scale * manual_scale) + y_pos
            ax.plot(xdata, ydata, c='black', linewidth=0.2)

            if self.fill_between:
                ax.fill_between(
                    xdata, y_pos, ydata, where=ydata > y_pos, color='black',
                    alpha=0.5)

            texts.append(
                ax.text(
                    xmax, y_pos, '%s.%s.%s.%s' % tr.nslc_id,
                    horizontalalignment='right', fontsize=6.))

            if self.add_markers:
                for ids, m in markers.items():
                    if m.match_nslc(tr.nslc_id) or ids == ():
                        c = m.select_color(m.color_b)
                        c = [ci/255. for ci in c]
                        t = m.tmin
                        x = [t-red-event.time, t-red-event.time]
                        y = [y_pos-(maxd-mind)*0.025, y_pos+(maxd-mind)*0.025]
                        ax.plot(x, y, linewidth=1, color=c)
                        label = m.get_label()
                        if not label:
                            label = ''

                        ax.text(x[1]-x[1]*0.005, y[1], label, color=c,
                                fontsize=6,
                                verticalalignment='top',
                                horizontalalignment='right')

        for txt in texts:
            txt.set_x(xmax)

        vred_str = '= '+str(round(self.t_red, 2)) + 'km/s' if self.t_red \
            else 'off'

        ax.text(0.5, 0.01, 'time window: %s - %s  |   Reduction velocity %s' %
                (util.tts(vtmin), util.tts(vtmax), vred_str),
                verticalalignment='bottom', horizontalalignment='center',
                transform=self.fig.transFigure)

        ax.set_ylim([ymin, ymax])
        ax.set_xlim([xmin, xmax])
        ax.set_ylabel('Distance [km]')
        ax.set_xlabel('(red.) Time [s]')
        self.fig.canvas.draw()
Esempio n. 55
0
def from_palantiri():
    km = 1000.
    try:
        path = sys.argv[3]
        evpath = path
    except:
        path = None
        evpath = 'events/' + str(sys.argv[1])

    C = config.Config(evpath)
    Origin = C.parseConfig('origin')
    Config = C.parseConfig('config')
    cfg = ConfigObj(dict=Config)
    step = cfg.UInt('step')
    step2 = cfg.UInt('step_f2')
    duration = cfg.UInt('duration')
    forerun = cfg.UInt('forerun')
    deltat = step
    deltat2 = step2
    rel = 'events/' + str(sys.argv[1]) + '/work/semblance/'

    dimx = int(Config['dimx'])
    dimy = int(Config['dimy'])

    origin = OriginCfg(Origin)
    depth = origin.depth() * 1000.
    ev = event.Event(lat=origin.lat(),
                     lon=origin.lon(),
                     depth=depth,
                     time=util.str_to_time(origin.time()))
    data, data_int, data_boot, data_int_boot, path_in_str, maxs, datamax, n_files = load(
        0, path=path)
    values_orig = data[:, 2]
    values_orig = num.append(values_orig, num.array([0., 0.]))

    lat_orig = data[:, 1]
    lon_orig = data[:, 0]

    ncorners = 4
    lon_grid_orig = num.linspace(num.min(lat_orig), num.max(lat_orig), (dimy))
    lat_grid_orig = num.linspace(num.min(lon_orig), num.max(lon_orig), dimx)

    if path is None:
        ntimes = int((forerun + duration) / step)
    else:
        ntimes = n_files

    verts = []
    lon_diff = ((lon_orig)[dimy + 1] - (lon_orig)[0]) / 4.
    lat_diff = ((lat_orig)[1] - (lat_orig)[0]) / 4.

    dist = orthodrome.distance_accurate50m(lat_grid_orig[1], lon_grid_orig[1],
                                           lat_grid_orig[0], lon_grid_orig[0])

    for x, y in zip(lon_orig, lat_orig):

        xyz = ([dist / 2., dist / 2.,
                depth], [-dist / 2., dist / 2.,
                         depth], [-dist / 2., -dist / 2.,
                                  depth], [dist / 2., -dist / 2., depth])
        latlon = ([x, y], [x, y], [x, y], [x, y])
        patchverts = num.hstack((latlon, xyz))
        verts.append(patchverts)

    vertices = num.vstack(verts)

    npatches = int(len(vertices))  #*2?
    faces1 = num.arange(ncorners * npatches,
                        dtype='int64').reshape(npatches, ncorners)
    faces2 = num.fliplr(faces1)
    faces = num.vstack((faces2, faces1))
    srf_semblance_list = []
    for i in range(0, ntimes):
        if len(sys.argv) < 4:
            print("missing input arrayname")
        else:
            data, data_int, data_boot, data_int_boot, path_in_str, maxsb, datamaxb, n_files = load(
                0, step=i, path=path)
            srf_semblance = data[:, 2]
            srf_semblance = num.append(srf_semblance, num.array([0., 0.]))
            srf_semblance = duplicate_property(srf_semblance)
            srf_semblance_list.append(srf_semblance)

    srf_semblance = num.asarray(srf_semblance_list).T
    srf_times = num.linspace(0, forerun + duration, ntimes)
    geom = Geometry(times=srf_times, event=ev)
    geom.setup(vertices, faces)
    sub_headers = tuple([str(i) for i in srf_times])
    geom.add_property((('semblance', 'float64', sub_headers)), srf_semblance)
    dump(geom, filename='geom.yaml')
axes.set_axis_off()
axes.set_xlim(-1.1, 1.1)
axes.set_ylim(-1.1, 1.1)

projection = 'lambert'

beachball.plot_beachball_mpl(
    mt, axes,
    position=(0., 0.),
    size=2.0,
    color_t=(0.7, 0.4, 0.4),
    projection=projection,
    size_units='data')

for rlat, rlon in rlatlons:
    distance = orthodrome.distance_accurate50m(slat, slon, rlat, rlon)
    rays = mod.arrivals(
        phases=cake.PhaseDef('P'),
        zstart=sdepth, zstop=rdepth, distances=[distance*cake.m2d])

    if not rays:
        continue

    takeoff = rays[0].takeoff_angle()
    azi = orthodrome.azimuth(slat, slon, rlat, rlon)

    # to spherical coordinates, r, theta, phi in radians
    rtp = num.array([[1., num.deg2rad(takeoff), num.deg2rad(90.-azi)]])

    # to 3D coordinates (x, y, z)
    points = beachball.numpy_rtp2xyz(rtp)