Beispiel #1
0
    def profile(self, *args, **kwargs):
        """
        Return profile of receiver functions in the stream.

        See `.profile.profile()` for help on arguments.
        """
        from rf.profile import profile
        return profile(self, *args, **kwargs)
Beispiel #2
0
    def profile(self, *args, **kwargs):
        """
        Return profile of receiver functions in the stream.

        See `.profile.profile()` for help on arguments.
        """
        from rf.profile import profile
        return profile(self, *args, **kwargs)
Beispiel #3
0
def run_commands(command,
                 commands=(),
                 events=None,
                 inventory=None,
                 objects=None,
                 get_waveforms=None,
                 data=None,
                 plugin=None,
                 phase=None,
                 moveout_phase=None,
                 path_in=None,
                 path_out=None,
                 format='Q',
                 newformat=None,
                 **kw):
    """Load files, apply commands and write result files."""
    for opt in kw:
        if opt not in DICT_OPTIONS:
            raise ParseError('Unknown config option: %s' % opt)
    for opt in DICT_OPTIONS:
        default = None if opt == 'boxbins' else {}
        d = kw.setdefault(opt, default)
        if isinstance(d, basestring):
            kw[opt] = json.loads(d)
    if phase is not None:
        kw['options']['phase'] = phase
    if moveout_phase is not None:
        kw['moveout']['phase'] = moveout_phase
    if kw['boxbins'] is not None:
        kw['boxes']['bins'] = np.linspace(*kw['boxbins'])

    try:
        if command == 'calc':
            assert len(commands) < 3
            if len(commands) == 2:
                assert commands[0] != commands[1]
        elif command == 'calc':
            assert len(commands) < 2
    except:
        raise ParseError('calc or moveout command given more than once')

    # Read events and inventory
    try:
        if command in ('stack', 'plot'):
            events = None
        elif command != 'print' or objects[0] == 'events':
            if (not isinstance(events, obspy.Catalog)
                    or not isinstance(events, list) or
                (len(events) == 2 and isinstance(events[0], basestring))):
                if isinstance(events, basestring):
                    format_ = None
                else:
                    events, format_ = events
                events = obspy.read_events(events, format_)
        if command != 'print' or objects[0] == 'stations':
            if not isinstance(inventory, obspy.Inventory):
                if isinstance(inventory, basestring):
                    format_ = None
                else:
                    inventory, format_ = inventory
                inventory = obspy.read_inventory(inventory, format_)
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        print('cannot read events or stations')
        return
    # Initialize get_waveforms
    if command == 'data':
        try:
            # Initialize get_waveforms
            if get_waveforms is None:
                get_waveforms = init_data(data,
                                          client_options=kw['client_options'],
                                          plugin=plugin)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            print('cannot initalize data')
            return
    # Print command
    if command == 'print':
        if objects[0] == 'events':
            print(events.__str__(True))
        elif objects[0] == 'stations':
            print(inventory)
        else:
            from rf.rfstream import RFStream
            stream = sum((read_rf(fname) for fname in objects), RFStream())
            print(stream.__str__(True))
        return
    # Select appropriate iterator
    if command == 'data':
        iter_ = iter_event_data(events,
                                inventory,
                                get_waveforms,
                                pbar=tqdm(),
                                **kw['options'])
    elif command == 'plot-profile':
        iter_ = _iter_profile(path_in, format)
    else:
        yt = command == 'profile'
        iter_ = iter_event_processed_data(events,
                                          inventory,
                                          path_in,
                                          format,
                                          pbar=tqdm(),
                                          yield_traces=yt)
    # Run all commands
    if command == 'convert':
        for stream in iter_:
            write(stream, path_out, newformat)
    elif command == 'plot':
        for stream in iter_:
            channels = set(tr.stats.channel for tr in stream)
            for ch in channels:
                st2 = stream.select(channel=ch)
                fname = PLOT_FNAMES.format(root=path_out, **st2[0].stats)
                _create_dir(fname)
                st2.sort(['back_azimuth'])
                st2.plot_rf(fname, **kw['plot'])
    elif command == 'plot-profile':
        for stream in iter_:
            channels = set(tr.stats.channel for tr in stream)
            for ch in channels:
                st2 = stream.select(channel=ch)
                fname = PLOT_PROFILE_FNAMES.format(root=path_out,
                                                   **st2[0].stats)
                _create_dir(fname)
                st2.plot_profile(fname, **kw['plot_profile'])
    elif command == 'stack':
        for stream in iter_:
            stack = stream.stack()
            write(stack, path_out, format, type='stack')
    elif command == 'profile':
        from rf.profile import get_profile_boxes, profile
        boxx = get_profile_boxes(**kw['boxes'])
        prof = profile(iter_, boxx, **kw['profile'])
        write(prof, path_out, format, type='profile')
    else:
        commands = [command] + list(commands)
        for stream in iter_:
            for command in commands:
                if command == 'data':
                    pass
                elif command == 'calc':
                    stream.rf(**kw['rf'])
                elif command == 'moveout':
                    stream.moveout(**kw['moveout'])
                else:
                    raise NotImplementedError
            write(stream, path_out, format)
        'fillcolors': ('black', 'gray'),
        'trace_height': 0.1
    }
    stream.select(component='L',
                  station='PB01').sort(['back_azimuth']).plot_rf(**kw)
    plt.savefig('PB01' + '_L_RF.png')
    for sta in ('PB01', 'PB04'):
        stream.select(component='Q',
                      station=sta).sort(['back_azimuth']).plot_rf(**kw)
        plt.savefig(sta + '_Q_RF.png')

if not os.path.exists(profilefile):
    stream = read_rf(rffile, 'H5')
    ppoints = stream.ppoints(70)
    boxes = get_profile_boxes((-21.3, -70.7),
                              90,
                              np.linspace(0, 180, 73),
                              width=530)
    plt.figure(figsize=(10, 10))
    plot_profile_map(boxes, inventory=inventory, ppoints=ppoints)
    pstream = profile(tqdm(stream), boxes)
    pstream.write(profilefile, 'H5')
    plt.savefig('profilefile.png')

if not os.path.exists('profile_plot.png'):
    pstream = read_rf(profilefile)
    pstream.trim2(-5, 20, 'onset')
    pstream.select(channel='??Q').normalize().plot_profile(scale=1.5,
                                                           top='hist')
    plt.gcf().set_size_inches(15, 10)
    plt.savefig('profile_plot.png')
Beispiel #5
0
from rf import get_profile_boxes, iter_event_data, IterMultipleComponents
from rf.imaging import plot_profile_map
from rf.profile import profile
from tqdm import tqdm

data = read_rf('data/7X-rf_profile_data-15deg.h5', 'H5')
data_cleaned = read_rf('data/7X-rf_profile_data-15deg-out.h5', 'H5')
inc_set = list(set([tr.stats.inclination for tr in data_cleaned]))
data_filtered = RFStream([
    tr for tr in data if tr.stats.inclination in inc_set
    and tr.stats.station not in ['MIJ2', 'MIL2']
])
stream = RFStream()
for stream3c in tqdm(IterMultipleComponents(data_filtered, 'onset', 3)):
    stream3c.filter('bandpass', freqmin=0.1, freqmax=1)
    stream3c.trim2(-25, 75, 'onset')
    if len(stream3c) != 3:
        continue
    stream3c.rf()
    stream3c.moveout()
    stream.extend(stream3c)
stream.write('data/7X-rf_profile_rfs_0.1Hz_1Hz', 'H5')
ppoints = stream.ppoints(70)
boxes = get_profile_boxes((-18.4, 139.1),
                          135,
                          np.linspace(0, 440, 80),
                          width=500)
pstream = profile(stream, boxes)
pstream.write('data/7X-rf_profile_profile-15deg_0.1Hz_1Hz_70km_ppoints.h5',
              'H5')
Beispiel #6
0
def run_commands(command, commands=(), events=None, inventory=None,
                 objects=None, get_waveforms=None, data=None, plugin=None,
                 phase=None, moveout_phase=None,
                 path_in=None, path_out=None, format='Q',
                 newformat=None, **kw):
    """Load files, apply commands and write result files."""
    for opt in kw:
        if opt not in DICT_OPTIONS:
            raise ParseError('Unknown config option: %s' % opt)
    for opt in DICT_OPTIONS:
        default = None if opt == 'boxbins' else {}
        d = kw.setdefault(opt, default)
        if isinstance(d, basestring):
            kw[opt] = json.loads(d)
    if phase is not None:
        kw['options']['phase'] = phase
    if moveout_phase is not None:
        kw['moveout']['phase'] = moveout_phase
    if kw['boxbins'] is not None:
        kw['boxes']['bins'] = np.linspace(*kw['boxbins'])

    try:
        if command == 'calc':
            assert len(commands) < 3
            if len(commands) == 2:
                assert commands[0] != commands[1]
        elif command == 'calc':
            assert len(commands) < 2
    except Exception:
        raise ParseError('calc or moveout command given more than once')

    # Read events and inventory
    try:
        if command in ('stack', 'plot'):
            events = None
        elif command != 'print' or objects[0] == 'events':
            if (not isinstance(events, obspy.Catalog) or
                    not isinstance(events, list) or
                    (len(events) == 2 and isinstance(events[0], basestring))):
                if isinstance(events, basestring):
                    format_ = None
                else:
                    events, format_ = events
                events = obspy.read_events(events, format_)
        if command != 'print' or objects[0] == 'stations':
            if not isinstance(inventory, obspy.Inventory):
                if isinstance(inventory, basestring):
                    format_ = None
                else:
                    inventory, format_ = inventory
                inventory = obspy.read_inventory(inventory, format_)
    except Exception:
        print('cannot read events or stations')
        return
    # Initialize get_waveforms
    if command == 'data':
        try:
            # Initialize get_waveforms
            if get_waveforms is None:
                get_waveforms = init_data(
                    data, client_options=kw['client_options'], plugin=plugin)
        except Exception:
            print('cannot initalize data')
            return
    # Print command
    if command == 'print':
        if objects[0] == 'events':
            print(events.__str__(True))
        elif objects[0] == 'stations':
            print(inventory)
        else:
            from rf.rfstream import RFStream
            stream = sum((read_rf(fname) for fname in objects), RFStream())
            print(stream.__str__(True))
        return
    # Select appropriate iterator
    if command == 'data':
        iter_ = iter_event_data(events, inventory, get_waveforms, pbar=tqdm(),
                                **kw['options'])
    elif command == 'plot-profile':
        iter_ = _iter_profile(path_in, format)
    else:
        yt = command == 'profile'
        iter_ = iter_event_processed_data(
            events, inventory, path_in, format, pbar=tqdm(), yield_traces=yt)
    # Run all commands
    if command == 'convert':
        for stream in iter_:
            write(stream, path_out, newformat)
    elif command == 'plot':
        for stream in iter_:
            channels = set(tr.stats.channel for tr in stream)
            for ch in channels:
                st2 = stream.select(channel=ch)
                fname = PLOT_FNAMES.format(root=path_out, **st2[0].stats)
                _create_dir(fname)
                st2.sort(['back_azimuth'])
                st2.plot_rf(fname, **kw['plot'])
    elif command == 'plot-profile':
        for stream in iter_:
            channels = set(tr.stats.channel for tr in stream)
            for ch in channels:
                st2 = stream.select(channel=ch)
                fname = PLOT_PROFILE_FNAMES.format(root=path_out,
                                                   **st2[0].stats)
                _create_dir(fname)
                st2.plot_profile(fname, **kw['plot_profile'])
    elif command == 'stack':
        for stream in iter_:
            stack = stream.stack()
            write(stack, path_out, format, type='stack')
    elif command == 'profile':
        from rf.profile import get_profile_boxes, profile
        boxx = get_profile_boxes(**kw['boxes'])
        prof = profile(iter_, boxx, **kw['profile'])
        write(prof, path_out, format, type='profile')
    else:
        commands = [command] + list(commands)
        for stream in iter_:
            for command in commands:
                if command == 'data':
                    pass
                elif command == 'calc':
                    stream.rf(**kw['rf'])
                elif command == 'moveout':
                    stream.moveout(**kw['moveout'])
                else:
                    raise NotImplementedError
            write(stream, path_out, format)