pysep.pplot

PrettyPlot (pplot): pretty plotting of ObsPy Streams with options for spectrograms, TauP arrivals, plotting other time-series data, record sections, grid plotting, instrument response removal and processing.

Run from the command line with pplot -h, or from Python with from pysep.pplot import PrettyPlot.

Attributes

Classes

PrettyPlot

Command line and scriptable waveform and spectrogram plotter. Every

Functions

parse_args()

All modifications are accomplished with command line arguments

_float_or_none(value)

Argparse type that accepts a float or the string 'none'

find_nearest(array, value)

Find the nearest index in a consecutive (time) array given a chosen value

_nearest_pow_2(x)

Find power of two nearest to x

spectrogram(ax, xvals, data, samp_rate[, xrange, ...])

Computes and plots the spectrogram of a time series on a shared time axis.

fast_remove_response(tr, inventory[, output, ...])

Remove the instrument response of a Trace in place, like ObsPy's

merge_stream(st[, fill])

Merge traces with the same ID into one continuous trace each, e.g., the

convert_timezone(code, st)

When plotting in absolute time (args.time == "a*"), we allow time

set_plot_aesthetic(ax[, xtick_labels, ytick_labels, ...])

Set a uniform look for figures. Adapted from

_set_xaxis_obspy_dates(ax[, ticklabels_small, ...])

Set Formatter/Locator of x-Axis to use ObsPyAutoDateFormatter and do some

cmaphex(nvals[, cmap])

Return a list of hex codes for nvals of a cmap which can be used to

main()

Command line entry point for pplot: parse arguments, convert the

Module Contents

pysep.pplot.SECONDS_PER_DAY = 86400.0[source]
pysep.pplot.FONTSIZES[source]
pysep.pplot.parse_args()[source]

All modifications are accomplished with command line arguments

pysep.pplot._float_or_none(value)[source]

Argparse type that accepts a float or the string ‘none’

Parameters:

value (str) – command line value

Return type:

float or None

Returns:

the value as a float, or None if ‘none’ was given

pysep.pplot.find_nearest(array, value)[source]

Find the nearest index in a consecutive (time) array given a chosen value

pysep.pplot._nearest_pow_2(x)[source]

Find power of two nearest to x

>>> _nearest_pow_2(3)
2.0
>>> _nearest_pow_2(15)
16.0
Parameters:

x (float) – Number

Return type:

int

Returns:

Nearest power of 2 to x

pysep.pplot.spectrogram(ax, xvals, data, samp_rate, xrange=None, per_lap=0.9, wlen=None, log=False, dbscale=False, mult=8.0, cmap=None, ncolors=256, zorder=None, clip=[0.0, 1.0], vmax=None, max_cols=2000, max_rows=1024)[source]

Computes and plots the spectrogram of a time series on a shared time axis.

Note

Modified from ObsPy’s spectrogram function https://docs.obspy.org/_modules/obspy/imaging/spectrogram.html #spectrogram

Only the displayed time range is computed, and the number of columns and rows is capped so that hours of data stay fast to compute and draw. A linear frequency axis is drawn with imshow; a log frequency axis uses pcolormesh on log-spaced rows.

Parameters:
  • ax (matplotlib.axes.Axes) – axis to plot into, sharing its x-axis with the waveform

  • xvals (np.ndarray) – x-axis value of every sample in data (seconds, minutes, hours or Matplotlib date numbers)

  • data (np.ndarray) – time series

  • samp_rate (float) – sampling rate of data in Hz

  • xrange (tuple of float or None) – (xmin, xmax) in xvals units to compute the spectrogram over, e.g. the plot’s x-limits. None uses all of data

  • per_lap (float) – fraction of overlap of the sliding window, 0 to 1

  • wlen (float or None) – window length in seconds. If None, the shortest power-of-two window of at least 128 samples is used that gives no more than max_cols columns, so long time ranges get longer windows (and finer frequency resolution) instead of millions of columns

  • log (bool) – logarithmic frequency axis if True, linear otherwise

  • dbscale (bool) – if True 10 * log10 of the power is plotted, if False the square root

  • mult (float) – zero-pad each window to mult times its length for a smoother look, limited so there are at most max_rows frequencies

  • cmap (str or None) – colormap name, defaults to ObsPy’s sequential colormap

  • ncolors (int) – number of discrete colors in the colormap

  • zorder (float) – zorder of the image

  • clip ([float, float]) – clip the color range at these fractions of the amplitude range (linear or dB depending on dbscale)

  • vmax (float or None) – absolute upper color limit, overrides the upper clip

  • max_cols (int) – maximum number of time columns

  • max_rows (int) – maximum number of frequency rows

Return type:

matplotlib.cm.ScalarMappable

Returns:

the plotted image, for a colorbar

pysep.pplot.fast_remove_response(tr, inventory, output='VEL', water_level=60.0, pre_filt=None, zero_mean=True, taper=True, taper_fraction=0.05, n_eval=2**15)[source]

Remove the instrument response of a Trace in place, like ObsPy’s Trace.remove_response(), but much faster for long traces.

ObsPy evaluates the full response with evalresp at every FFT frequency (about one million points for an hour of 100 Hz data), which dominates the run time. The response is smooth, so here it is evaluated at about n_eval frequencies (evenly spaced, plus log-spaced points at low frequency) and interpolated (real and imaginary parts) onto the FFT grid. Every other step (demean, taper, pre-filter, water level, inverse FFT) follows ObsPy 1.5 exactly. Traces short enough to need fewer than n_eval frequencies, and polynomial responses, are passed straight to ObsPy.

Parameters:
  • tr (obspy.core.trace.Trace) – trace to correct, modified in place

  • inventory (obspy.core.inventory.Inventory) – inventory containing the trace’s response

  • output (str) – ‘DISP’, ‘VEL’, ‘ACC’ or ‘DEF’

  • water_level (float or None) – water level in dB, None to turn it off

  • pre_filt (list of float or None) – four corner frequencies of the frequency-domain taper

  • zero_mean (bool) – demean the data before deconvolution

  • taper (bool) – apply a cosine taper before deconvolution

  • taper_fraction (float) – fraction of the trace tapered at each end

  • n_eval (int) – number of frequencies at which the response is evaluated

Return type:

obspy.core.trace.Trace

Returns:

the corrected trace

pysep.pplot.merge_stream(st, fill='interpolate')[source]

Merge traces with the same ID into one continuous trace each, e.g., the segments of a gappy file, or consecutive day files of one channel. Traces keep the order in which their IDs first appear in st.

Parameters:
  • st (obspy.core.stream.Stream) – stream to merge

  • fill (str or float) – how to fill gaps: ‘interpolate’ (linear between the samples on either side), ‘latest’ (repeat the last sample before the gap), or a number to fill with

Return type:

obspy.core.stream.Stream

Returns:

merged stream

pysep.pplot.convert_timezone(code, st)[source]

When plotting in absolute time (args.time == “a*”), we allow time shifting by time zone to get to the correct time local time. Returns streams with converted time

Note

Confusingly, trying to input time zones in UTCDateTime like UTCDateTime(“YYYY-MM-DDTHH:MM:SS-09) assumes that the given date is in local time, and that the modifier -09 is the conversion to UTC. But since seismic data is IN UTC, we cannot use this because it shifts us in the wrong way.

Parameters:

code (str) – e.g., +08 to shift forward by 8 hours

pysep.pplot.set_plot_aesthetic(ax, xtick_labels=True, ytick_labels=True, ytick_fontsize=FONTSIZES['ytick_label'], xtick_fontsize=FONTSIZES['xtick_label'], tick_linewidth=1.5, tick_length=5.0, tick_direction='in', ytick_format='sci', xlabel_fontsize=FONTSIZES['axis_label'], ylabel_fontsize=FONTSIZES['axis_label'], axis_linewidth=1.5, spine_zorder=500, title_fontsize=FONTSIZES['title'], spine_top=True, spine_bot=True, spine_left=True, spine_right=True, xtick_minor=None, xtick_major=None, ytick_minor=None, ytick_major=None, xgrid_major=True, xgrid_minor=True, ygrid_major=True, ygrid_minor=True, **kwargs)[source]

Set a uniform look for figures. Adapted from pysep.utils.plot.set_plot_aesthetic() but with PrettyPlot’s own defaults (see FONTSIZES), so the two are kept separate.

pysep.pplot._set_xaxis_obspy_dates(ax, ticklabels_small=True, minticks=3, maxticks=6)[source]

Set Formatter/Locator of x-Axis to use ObsPyAutoDateFormatter and do some other tweaking.

In contrast to normal matplotlib AutoDateFormatter e.g. shows full timestamp on first tick when zoomed in so far that matplotlib would only show hours or minutes on all ticks (making it impossible to tell the date from the axis labels) and also shows full timestamp in matplotlib figures info line (mouse-over info of current cursor position).

Return type:

None

pysep.pplot.cmaphex(nvals, cmap='seismic')[source]

Return a list of hex codes for nvals of a cmap which can be used to provide a sequential colormap made up of discrete color values

class pysep.pplot.PrettyPlot(fids, idx=0, taper=0, fmin=None, fmax=None, zerophase=False, corners=4, resample=False, t0=0, tstart=0, detrend=False, integrate=0, merge=False, merge_fill='interpolate', differentiate=0, trim_pct=1.0, inv=None, rr_output='VEL', rr_water_level=60.0, rr_pre_filt=None, rr_zero_mean=True, rr_taper=True, rr_taper_fraction=0.05, rr_exact=False, wf_abs=False, wf_type='default', wf_norm=False, wf_scale=1, wf_recsec_spacing=1, wf_spacing_exact=False, wf_order=None, wf_grid=None, nrows=None, ncols=None, colors='k', alphas=None, labels=None, linewidth=0.5, ylabel='Amplitude', ylim=None, ylim_grid=None, xlim=None, time='s', minticks=3, maxticks=6, tmarks=None, tmarks_c='k', group_vels=None, tp_phases=None, tp_model='iasp91', tp_dist_km=None, tp_dist_deg=None, tp_depth=None, tp_start=None, tp_cmap='rainbow_r', tp_plot_rays=False, spectrogram=False, sp_cmap='viridis', sp_numcol=256, sp_dbscale=True, sp_logscale=False, sp_clip=None, sp_vmax=None, sp_idx=0, sp_wlen=None, sp_overlap=0.9, add_trace=None, tr_time='a', tr_label='', tr_ylabel='', tr_color='C0', fig_size=None, dpi=100, fig_len=8, fig_asp=None, legend=True, ncol_legend=1, title=None, title_append='', title_prepend='', subplot_label=None, save=None, output=None, show=True, frameoff=False, transparent=False, **kwargs)[source]

Command line and scriptable waveform and spectrogram plotter. Every command line option of pplot is a keyword argument; call PrettyPlot.run() to make the figure.

Input parameters, see argparser for descriptions

fids[source]
idx = 0[source]
merge = False[source]
merge_fill = 'interpolate'[source]
taper = 0[source]
fmin = None[source]
fmax = None[source]
zerophase = False[source]
corners = 4[source]
resample = False[source]
t0 = 0[source]
tstart = 0[source]
detrend = False[source]
integrate = 0[source]
differentiate = 0[source]
trim_pct = 1.0[source]
inv = None[source]
rr_output = 'VEL'[source]
rr_water_level = 60.0[source]
rr_pre_filt = None[source]
rr_zero_mean = True[source]
rr_taper = True[source]
rr_taper_fraction = 0.05[source]
rr_exact = False[source]
wf_abs = False[source]
wf_type = 'default'[source]
wf_norm = False[source]
wf_scale = 1[source]
wf_recsec_spacing = 1[source]
wf_spacing_exact = False[source]
wf_order = None[source]
nrows = None[source]
ncols = None[source]
colors = 'k'[source]
alphas = None[source]
labels = None[source]
linewidth = 0.5[source]
ylim = None[source]
ylim_grid = None[source]
ylabel = 'Amplitude'[source]
time = 's'[source]
maxticks = 6[source]
minticks = 3[source]
xlim = None[source]
tmarks = None[source]
tmarks_c = 'k'[source]
group_vels = None[source]
tp_phases = None[source]
tp_model = 'iasp91'[source]
tp_dist_km = None[source]
tp_dist_deg = None[source]
tp_depth = None[source]
tp_start = None[source]
tp_cmap = 'rainbow_r'[source]
tp_plot_rays = False[source]
spectrogram = False[source]
sp_cmap = 'viridis'[source]
sp_numcol = 256[source]
sp_dbscale = True[source]
sp_logscale = False[source]
sp_clip = [0.0, 1.0][source]
sp_vmax = None[source]
sp_idx = 0[source]
sp_wlen = None[source]
sp_overlap = 0.9[source]
add_trace = None[source]
tr_time = 'a'[source]
tr_label = ''[source]
tr_ylabel = ''[source]
tr_color = 'C0'[source]
fig_size = None[source]
dpi = 100[source]
fig_len = 8[source]
fig_asp = None[source]
legend = True[source]
ncol_legend = 1[source]
title = None[source]
title_append = ''[source]
title_prepend = ''[source]
subplot_label = None[source]
save = None[source]
output = None[source]
show = True[source]
frameoff = False[source]
transparent = False[source]
_xvals = None[source]
_data = None[source]
_labels = None[source]
_colors = None[source]
_alphas = None[source]
_ylims = None[source]
_ref_time = None[source]
_tz_shift = 0.0[source]
st[source]
setup_plot()[source]

Set up the plot based on input parameters, choose how the figure and axes visually appears

trim_waveform()[source]

Trim the waveform data so we don’t plot the whole thing. Has some functionality to add buffer to the trimmed tail ends of the data for FFT style processing which requires stable ends.

_seconds_per_unit()[source]

Return the number of seconds in one unit of a relative time axis

Return type:

float

Returns:

1 for ‘s’, 60 for ‘m’, 3600 for ‘h’

_rel_to_seconds(x)[source]

Convert a value on the relative time axis to seconds after the reference time (first sample of the first trace as read)

Parameters:

x (float) – time in the units of time, including t0/tstart offsets

Return type:

float

Returns:

seconds after _ref_time

_default_origin()[source]

Origin time used for TauP arrivals and group velocities when tp_start is not given: the start of xlim if set, otherwise the first plotted sample. Matches the units of the time axis.

Return type:

UTCDateTime or float

Returns:

UTCDateTime if time is absolute, else relative time

remove_response()[source]

Remove the instrument response with ObsPy’s Stream.remove_response() using the StationXML given by inv. Runs after trimming, so only the (buffered) plot window is deconvolved, and before all other processing. If no ylabel was set, it is updated to match the output units.

process_waveforms()[source]

Process the waveforms based on input parameters with options for filtering, detrending, tapering etc.

get_plot_parameters()[source]

Establish what will be plotted and the styles for each of them. The data itself will control things like stacking or record sections. The final internal attributes created are: xvals, data, labels, colors, alphas

plot_waveforms()[source]

Plot the waveforms based on plot parameters defined before

plot_additional_traces()[source]

Plot additional time series with a common X axis but with a different Y axis. This can be used to plot other geophysical or physical data. Required parameters would be add_trace which should be in an ObsPy readable format. Spectrogram of this other data can be plotted, too.

Does not work with wf_type='grid' option

plot_spectrogram()[source]

Plot spectrogram on a separate axis above the main waveform plot. Plots the spectrogram for the sp_idx index of the Stream. Cannot be used in conjunction with wf_type='grid' option

plot_taup_arrivals()[source]

Get and plot TauP arrivals based on theoretical model, event distance and depth. Phases can be input. Relevant parameters are:

Parameters:
  • str) (- tp_phases (list of)

  • (str) (- tp_model)

  • (float) (- tp_start) – Choose one of tp_dist_km or tp_dist_deg

  • (float)

  • (float)

  • (float) – to match the data. TauP arrivals are given in relative timing

plot_tmarks()[source]

Plot time marks if requested

plot_group_vels(c='r', alpha=1, ls='-', lw=2.0, fontsize=FONTSIZES['group_velocity_label'], zorder=100)[source]

Create time mark lines for a given set of group velocities group_vel given in units of km/s Requires values from TauP arrivals, namely: tp_dist and tp_start to get the correct arrival time Annotates the value of the group velocity at the max amplitude of the waveform.

set_ylim()[source]

Establish ylims either by user set or from the natural plot lims

set_pplot_aesthetics()[source]

Set plot aesthetics to give a standard look to all the waveform figures

annotate_subplot_label()[source]

Annotate subplot label. Only works in a select amount of cases

finalize()[source]

Final plot adjustments

run()[source]

Main plotting function

pysep.pplot.main()[source]

Command line entry point for pplot: parse arguments, convert the negative (*_off, no*) flags to keyword arguments and run PrettyPlot