Пример #1
0
def window_on_trace(obs_tr, syn_tr, config, station=None,
                    event=None, user_module=None, _verbose=False,
                    figure_mode=False, figure_dir=None,
                    figure_format="pdf"):
    """
    Window selection on a trace(obspy.Trace)

    :param observed: observed trace
    :type observed: obspy.Trace
    :param synthetic: synthetic trace
    :type synthetic: obspy.Trace
    :param config: window selection config
    :type config_dict: pyflex.Config
    :param station: station information which provids station location to
        calculate the epicenter distance
    :type station: obspy.Inventory or pyflex.Station
    :param event: event information, providing the event information
    :type event: pyflex.Event, obspy.Catalog or obspy.Event
    :param user_module: user module as a string
    :type user_module: str
    :param figure_mode: output figure flag
    :type figure_mode: bool
    :param figure_dir: output figure directory
    :type figure_dir: str
    :param _verbose: verbose flag
    :type _verbose: bool
    :return:
    """

    if not isinstance(obs_tr, obspy.Trace):
        raise ValueError("Input obs_tr should be obspy.Trace")
    if not isinstance(syn_tr, obspy.Trace):
        raise ValueError("Input syn_tr should be obspy.Trace")
    if not isinstance(config, pyflex.Config):
        raise ValueError("Input config should be pyflex.Config")

    # Ridvan Orsvuran, 2016
    # If user gives a user_module, use it to update acceptance levels
    # as arrays.
    if user_module is not None and user_module != "None":
        config = update_user_levels(user_module, config, station,
                                    event, obs_tr, syn_tr)

    ws = pyflex.WindowSelector(obs_tr, syn_tr, config,
                               event=event, station=station)
    try:
        windows = ws.select_windows()
    except Exception as err:
        print("Error(%s): %s" % (obs_tr.id, err))
        windows = []

    if figure_mode:
        plot_window_figure(figure_dir, obs_tr.id, ws, _verbose,
                           figure_format=figure_format)

    if _verbose:
        print("Station %s picked %i windows" % (obs_tr.id, len(windows)))

    return windows
Пример #2
0
    def select_windows_plus(self):
        """
        Mid-level custom window selection function that calls Pyflex select 
        windows, but includes additional window suppression functionality.
        Includes custom Pyflex addition of outputting rejected windows, which
        will be used internally for plotting.

        .. note::
            Pyflex will throw a ValueError if the arrival of the P-wave
            is too close to the initial portion of the waveform, considered the
            'noise' section. This happens for short source-receiver distances
            (< 100km).

            This error becomes a PyflexError if no event/station attributes
            are provided to the WindowSelector

            We could potentially deal with this by zero-padding the
            waveforms, and running select_windows() again, but for now we just
            raise a ManagerError and allow processing to continue
        """
        logger.info(f"running Pyflex w/ map: {self.config.pyflex_preset}")

        nwin, window_dict, reject_dict = 0, {}, {}
        for comp in self.config.component_list:
            try:
                obs = self.st_obs.select(component=comp)[0]
                syn = self.st_syn.select(component=comp)[0]
            # IndexError thrown when trying to access an empty Stream
            except IndexError:
                continue

            # Pyflex throws a TauP warning from ObsPy #2280, ignore that
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", UserWarning)
                ws = pyflex.WindowSelector(observed=obs,
                                           synthetic=syn,
                                           config=self.config.pyflex_config,
                                           event=self.event,
                                           station=self.inv)
                try:
                    windows = ws.select_windows()
                except (IndexError, pyflex.PyflexError):
                    # see docstring note for why this error is to be addressed
                    raise ManagerError("Cannot window, most likely because "
                                       "the source-receiver distance is too "
                                       "small w.r.t the minimum period")

            # Suppress windows that contain low-amplitude signals
            if self.config.win_amp_ratio > 0:
                windows, ws.rejects["amplitude"] = \
                       reject_on_global_amplitude_ratio(
                                            data=obs.data, windows=windows,
                                            ratio=self.config.win_amp_ratio
                                            )
            # ==================================================================
            # NOTE: Additional windowing criteria may be added here if necessary
            # ==================================================================
            if windows:
                window_dict[comp] = windows
            if ws.rejects:
                reject_dict[comp] = ws.rejects

            # Count windows and tell User
            logger.info(f"{len(windows)} window(s) selected for comp {comp}")
            nwin += len(windows)

        self.windows = window_dict
        self.rejwins = reject_dict
        self.stats.nwin = nwin
Пример #3
0
def window_on_trace(obs_tr, syn_tr, config, station=None,
                    event=None, user_module=None,
                    figure_mode=False, figure_dir=None,
                    figure_format="pdf"):
    """
    Window selection on a trace(obspy.Trace)

    :param observed: observed trace
    :type observed: obspy.Trace
    :param synthetic: synthetic trace
    :type synthetic: obspy.Trace
    :param config: window selection config
    :type config_dict: pyflex.Config
    :param station: station information which provids station location to
        calculate the epicenter distance
    :type station: obspy.Inventory or pyflex.Station
    :param event: event information, providing the event information
    :type event: pyflex.Event, obspy.Catalog or obspy.Event
    :param user_module: user module as a string
    :type user_module: str
    :param figure_mode: output figure flag
    :type figure_mode: bool
    :param figure_dir: output figure directory
    :type figure_dir: str
    :return:
    """

    if not isinstance(obs_tr, obspy.Trace):
        raise ValueError("Input obs_tr should be obspy.Trace")
    if not isinstance(syn_tr, obspy.Trace):
        raise ValueError("Input syn_tr should be obspy.Trace")
    if not isinstance(config, pyflex.Config):
        raise ValueError("Input config should be pyflex.Config")

    # Ridvan Orsvuran, 2016
    # If user gives a user_module, use it to update acceptance levels
    # as arrays.
    if user_module is not None and user_module != "None":
        config = update_user_levels(user_module, config, station,
                                    event, obs_tr, syn_tr)

    config = set_config_for_selection_mode(config, station, event, obs_tr)
    logger.debug("unique values in config.tshift_acceptance_level: "
                 "{}".format(np.unique(config.tshift_acceptance_level)))
    logger.debug("unique values in config.dlna_acceptance_level: "
                 "{}".format(np.unique(config.dlna_acceptance_level)))
    logger.debug("unique values in config.cc_acceptance_level: "
                 "{}".format(np.unique(config.cc_acceptance_level)))
    logger.debug("unique values in config.s2n_limit: "
                 "{}".format(np.unique(config.s2n_limit)))

    # set the signal_end_index to trace npts
    config.signal_end_index = obs_tr.stats.npts

    ws = pyflex.WindowSelector(obs_tr, syn_tr, config,
                               event=event, station=station)
    try:
        windows = ws.select_windows()
    except Exception as err:
        logger.warning("Error(%s): %s" % (obs_tr.id, err))
        windows = []

    if figure_mode:
        plot_window_figure(figure_dir, obs_tr.id, ws,
                           figure_format=figure_format)

    logger.info("Station %s picked %i windows" % (obs_tr.id, len(windows)))

    return windows
Пример #4
0
def test_reading_and_writing_windows(tmpdir):
    """
    Tests reading and writing of window sets.
    """
    config = pyflex.Config(min_period=50.0,
                           max_period=150.0,
                           stalta_waterlevel=0.08,
                           tshift_acceptance_level=15.0,
                           dlna_acceptance_level=1.0,
                           cc_acceptance_level=0.80,
                           c_0=0.7,
                           c_1=4.0,
                           c_2=0.0,
                           c_3a=1.0,
                           c_3b=2.0,
                           c_4a=3.0,
                           c_4b=10.0)

    ws = pyflex.WindowSelector(observed=OBS_DATA,
                               synthetic=SYNTH_DATA,
                               config=config)
    windows = ws.select_windows()
    assert len(windows) > 0

    # Write/read to/from file.
    filename = os.path.join(str(tmpdir), "window.json")
    ws.write(filename)

    ws2 = pyflex.WindowSelector(observed=OBS_DATA,
                                synthetic=SYNTH_DATA,
                                config=config)
    ws2.load(filename)
    assert ws.windows == ws2.windows
    os.remove(filename)

    # Write/read to/from open file.
    with open(filename, "w") as fh:
        ws.write(fh)

        ws2 = pyflex.WindowSelector(observed=OBS_DATA,
                                    synthetic=SYNTH_DATA,
                                    config=config)
        fh.seek(0, 0)
        ws2.load(filename)
    assert ws.windows == ws2.windows

    # Write/read to/from StringIO.
    with io.StringIO() as fh:
        ws.write(fh)

        ws2 = pyflex.WindowSelector(observed=OBS_DATA,
                                    synthetic=SYNTH_DATA,
                                    config=config)
        fh.seek(0, 0)
        ws2.load(filename)
    assert ws.windows == ws2.windows

    # Write/read to/from BytesIO.
    with io.BytesIO() as fh:
        ws.write(fh)

        ws2 = pyflex.WindowSelector(observed=OBS_DATA,
                                    synthetic=SYNTH_DATA,
                                    config=config)
        fh.seek(0, 0)
        ws2.load(filename)
    assert ws.windows == ws2.windows
Пример #5
0
#for datafile in glob.glob(datadir + "/HDC.G.*.sac"):
for datafile in glob.glob(datadir + "/*.sac"):
    #copy config
    config = copy.copy(config_base)
    # print datafile
    print "===================\nObsd file:", datafile
    data = read(datafile)
    sta = data[0].stats.station
    nw = data[0].stats.network
    comp = data[0].stats.channel
    loc = data[0].stats.location
    syntfile = sta+"."+nw+".MX"+comp[-1:]+".sac"
    syntfile = os.path.join(syntdir, syntfile)
    if os.path.exists(syntfile):
        print "Synt file:", syntfile
        synt = read(syntfile)
        ws = pyflex.WindowSelector(data, synt, config)
        windows = ws.select_windows()
        # output fig
        outfn = sta + "." + nw + "." + loc + ".MX" + comp[-1:] + ".pdf"
        figfn = os.path.join(figdir, outfn)
        print "Output fig:", figfn
        ws.plot(figfn)
        # output win
        outfn = sta + "." + nw+ "." + loc + ".MX" + comp[-1:] + ".win"
        winfn = os.path.join(outputdir, outfn)
        print "Output win:", winfn
        ws.write_text(winfn)
    else:
        print "Synt file not exists..."
Пример #6
0
def window_on_trace(obs_tr,
                    syn_tr,
                    config,
                    station=None,
                    event=None,
                    _verbose=False,
                    figure_mode=False,
                    figure_dir=None,
                    figure_format="pdf"):
    """
    Window selection on a trace(obspy.Trace)

    :param observed: observed trace
    :type observed: obspy.Trace
    :param synthetic: synthetic trace
    :type synthetic: obspy.Trace
    :param config: window selection config
    :type config_dict: pyflex.Config
    :param station: station information which provids station location to
        calculate the epicenter distance
    :type station: obspy.Inventory or pyflex.Station
    :param event: event information, providing the event information
    :type event: pyflex.Event, obspy.Catalog or obspy.Event
    :param figure_mode: output figure flag
    :type figure_mode: bool
    :param figure_dir: output figure directory
    :type figure_dir: str
    :param _verbose: verbose flag
    :type _verbose: bool
    :return:
    """

    if not isinstance(obs_tr, obspy.Trace):
        raise ValueError("Input obs_tr should be obspy.Trace")
    if not isinstance(syn_tr, obspy.Trace):
        raise ValueError("Input syn_tr should be obspy.Trace")
    if not isinstance(config, pyflex.Config):
        raise ValueError("Input config should be pyflex.Config")

    ws = pyflex.WindowSelector(obs_tr,
                               syn_tr,
                               config,
                               event=event,
                               station=station)
    try:
        windows = ws.select_windows()
    except:
        print("Error on %s" % obs_tr.id)
        windows = []

    if figure_mode:
        plot_window_figure(figure_dir,
                           obs_tr.id,
                           ws,
                           _verbose,
                           figure_format=figure_format)

    if _verbose:
        print("Station %s picked %i windows" % (obs_tr.id, len(windows)))

    return windows