tiskitpy.SpectralDensity

class tiskitpy.SpectralDensity(freqs, seed_ids, chan_units, n_windows, window_type, window_s, chan_clean_sequences=None, ts_starttime=None, ts_endtime=None, starttimes=None, data=None, instrument_responses=None)

Bases: object

Class for spectral density functions.

Warning

The standard constructor is rarely used, generate objects using SpectralDensity.from_stream()

No public attributes, access data through provided methods

autospect(channel)

Get auto-spectral_density function for the channel

Parameters:

channel (str) – channel id

Returns:

auto-spectral density function

Return type:

(numpy.ndarray)

property avoided_spans

time spans unused during processing

Return type:

(tiskitpy.TimeSpans)

channel_id(test_id, ch_identifier='id')

Return channel id, verifying that it exists and is unique

Can expand wildcards, if they match only one channel

Parameters:
  • test_id (str) – channel id to search for

  • ch_identifier (str) – description of the kind of channel (input, output…), useful for error messages

channel_instrument_response(channel)

Get channel’s instrument response

Parameters:

channel (str) – channel name

Return type:

(numpy.ndarray)

channel_units(channel)

Get channel’s input (physical) units

Parameters:

channel (str) – the channel name

Returns:

Channel’s input units

Return type:

(str)

clean_sequence(channel)

Clean sequence applied to this channel

Parameters:

channel (str) – a channel name

Returns:

List of cleaners applied, in order

Return type:

(list)

property clean_sequences

Returns: (list of list):

coh_signif(prob=0.95)

Get the coherence significance level

Parameters:

prob (float) – probability of an incoherent frequency passing this value (between 0 and 1)

Return type:

(float)

coherence(in_chan, out_chan)

Get coherence between the channels

Parameters:
  • in_chan (str) – input channel. Must match one of the coordinates in _ds

  • out_chan (str) – output channel. Must match one of the coordinates in _ds

Returns:

Coherence absolute value

Return type:

(numpy.ndarray)

Coherence is a real-valued quantity, for the cross-spectral phase, use the cross-spectral density function. From Bendat & Piersol (1986), Appendix B, gamma_xy^2 (f)

static compare_tapers(N)

Plot a comparison of all window types

Parameters:

N (int) – window length

crossspect(in_id, out_id)

Get cross-spectral density function for the channels

Parameters:
  • in_id (str) – input channel id

  • out_id (str) – output channel id

Returns:

cross-spectral density function

Return type:

(numpy.ndarray)

property freqs

Frequencies of the spectral density functions

Return type:

(numpy.ndarray)

classmethod from_stream(stream, window_s=1000, windowtype='prol4pi', inv=None, data_cleaner=None, starttimes=None, time_spans=None, avoid_spans=None, remove_eqs=False, z_threshold=3, quiet=False, ignore_gaps=False)

Calculate spectral density functions from the provided stream

Should add a window selection algorithm, for now just steps by the window length

Parameters:
  • stream (obspy.core.stream.Stream) – data

  • window_s (float) – desired window length in seconds

  • windowtype (str) – window taper type. Must be in WINDOW_TAPERS

  • inv (obspy.core.inventory.Inventory) – inventory containing instrument responses. If none is found for the given channel, will look in the channel’s stats.response object

  • data_cleaner (DataCleaner) – Data cleaner to apply to channels as ffts are calculated

  • starttimes (list of obspy.UTCDateTime) – Use provided start window times (ignores z_threshold). Incompatible with time_spans

  • time_spans (TimeSpans) – only use windows in the provided time spans. Incompatible with starttimes

  • avoid_spans (TimeSpans) – Do NOT use data from the provided time spans. Incompatible with starttimes and “time_spans”

  • subtract_rf_suffix (str) – suffix to add to channel names if rf is subtracted

  • remove_eqs (bool, str) –

    Avoid time spans associated with earthquakes, using default parameters of TimeSpans.from_eqs()

    • If str: filename of QuakeML file containing earthquakes.

    • If True, download earthquakes from USGS website or appropriately-named local file.

    • If False, do not remove earthquakes.

  • z_threshold (float or None) – reject windows with z-score greater than this value. None: no rejection

  • quiet (bool) – only output errors and beyond to console

  • ignore_gaps (bool) – Ignore gaps in the data (otherwise, integrates them into the time_spans attribute)

property ids

seed_ids + any cleaning information ** Previously called _channel_names **

Type:

List of Channel ids

property n_windows

The number of data windows used to calculate spectra

Return type:

(int)

plot(**kwargs)

Shortcut for plot_autospectra()

plot_autospectra(x=None, overlay=False, plot_peterson=True, show=True, outfile=None, title=None, ylim=None, grid=False, **fig_kw)

Plot autospectra

Parameters:
  • x (list of str) – limit to the listed channels

  • overlay (bool) – put all spect on one axis

  • plot_peterson (bool) – plot Peterson Noise model if any channel has units of \((m/s^2)^2/Hz\)

  • show (bool) – show on desktop

  • outfile (str) – save figure to this filename

  • title (str) – custom plot title

  • ylim (tuple, None) – (min, max) dBs to plot on each y axis

  • grid (bool or str) – False, True, ‘major’, ‘minor’, or ‘both’

  • fig_kw (dict) – all additional keyword arguments (such as figsize and dpi) are passed to the pyplot.figure call

Returns:

array of axis pairs

[row, column][0=amplitude, 1=phase]

Return type:

numpy.ndarray

plot_coherences(x=None, y=None, display='sparse', show=True, outfile=None, label_by='full', sort_by='full', overlay=False, title=None, **fig_kw)

Plot coherences

Parameters:
  • x (list of str or None) – limit to the listed input channels

  • y (list of str or None) – limit to the listed output channels

  • display (str) – How to arrange plots: “full”: a row for every channel, a column for every channel, every cell filled; “sparse”: Only plot the upper diagonal; “minimal”: Plot upper diagonal elements in the least number of cells possible “overlay”: One plot with all upper diagonal elemetns overlain

  • overlay (bool) – [GRANDFATHERED]: same as display=”overlay”

  • show (bool) – show on desktop

  • title (str) – Customize overall figure title

  • outfile (str) – save to the named file

  • label_by (str) – labels to put on x and y axes (‘full’, ‘chan’ or ‘loc-chan’)

  • sort_by (str) – how to sort x and y axes (‘full’, ‘chan’ or ‘loc-chan’)

  • fig_kw (dict) – all additional keyword arguments (such as figsize and dpi) are passed to the pyplot.figure call

Returns:

array of axis pairs

[row, column][0=amplitude, 1=phase]

Return type:

numpy.ndarray

plot_cross_spectra(x=None, show=True, show_coherence=False, outfile=None, plot_peterson=False, **fig_kw)

Plot cross (and auto) spectra

Parameters:
  • x (list of str) – limit to the listed channels

  • show (bool) – show on desktop

  • plot_peterson (bool) – plot Peterson Noise model if any channel has units of \((m/s^2)^2/Hz\)

  • show_coherence (bool) – show coherence as well

  • fig_kw (dict) – all additional keyword arguments (such as figsize and dpi) are passed to the pyplot.figure call

Returns:

array of axis pairs

[row, column][0=amplitude, 1=phase]

Return type:

numpy.ndarray

plot_one_autospectra(key, **kwargs)

Plot one autospectral density

Arguments are the same as for plot_one_spectra(), except there is no subkey argument and show_phase is ignored

Returns:

amplitude plot axis

Return type:

ax_a (matplotlib.axes.axis)

plot_one_coherence(in_chan, out_chan, fig=None, fig_grid=(1, 1), plot_spot=(0, 0), show_xlabel=True, show_ylabel=True, ax_a=None, ax_p=None, ylabel=None, label=None, title=None, show_phase=True, plot_legend=True, outfile=None, show=False, **kwargs)

Plot one coherence

Parameters:
  • in_chan (str) – input (driving) channel

  • out_chan (str) – output (response) channel

  • fig (matplotlib.figure.Figure) – figure to plot on, if None this method will plot on the current figure or create a new figure.

  • fig_grid (tuple) – this plot sits in a grid of this many (rows, columns)

  • plot_spot (tuple) – put this plot at this (row,column) of the figure grid

  • show_xlabel (bool) – put an xlabel on this subplot

  • show_ylabel (bool) – put a ylabel on this subplot

  • ylabel (str) – label to put on y axis (if show_ylabel). If not speficied, will use ‘Coherence’

  • label (str) – text to put in legend

  • ax_a (Axis) – use an existing axis for the amplitude plot

  • ax_p (Axis) – use this existing axis for the phase plot

  • title (str) – title to put on this subplot

  • show_phase (bool) – show phase as well as amplitude

  • outfile (str) – plot to the named file

  • show (bool) – show on the screen (False by default: parent function shows)

  • kwargs (dict) – values to pass on to plotting routines

Returns:

tuple containing:
  • (matplotlib.axes.axis): amplitude plot axis

  • (matplotlib.axes.axis): phase plot axis

Return type:

(tuple)

plot_one_spectra(key, subkey, fig=None, fig_grid=(1, 1), plot_spot=(0, 0), show_xlabel=True, show_ylabel=None, ax_a=None, ax_p=None, ylabel=None, label=None, title=None, show_coherence=False, show_phase=True, plot_peterson=True, outfile=None, annotate=True, ylim=None, **plot_kws)

Plot one spectral density

Parameters:
  • key (str) – input (driving) channel

  • subkey (str) – output (response) channel

  • fig (matplotlib.figure.Figure) – figure to plot on, if None this method will plot on the current figure or create a new figure.

  • fig_grid (tuple) – this plot sits in a grid of this many (rows, columns)

  • subplot_spot (tuple) – put this plot at this (row, column) of the figure grid

  • show_xlabel (bool) – put an xlabel on this subplot

  • show_ylabel (bool) – put a ylabel on this subplot

  • ylabel (str) – label to put on y axis (if show_label). If not speficied, will use ‘dB ref UNITS/Hz’

  • label (str) – ‘units’: print units without channel name in legend

  • ax_a (Axis) – use an existing axis for the amplitude plot

  • ax_p (Axis) – use this existing axis for the phase plot

  • title (str) – title to put on this subplot

  • show_coherence (bool) – draw coherence on the same plot

  • show_phase (bool) – show phase as well as amplitude

  • plot_peterson (bool) – plot Peterson Noise model if channel has units of \((m/s^2)^2/Hz\)

  • outfile (str) – save figure to this filename

  • ylim (tuple, None) – (min, max) dBs to plot on each y axis

  • **plot_kws (dict) – keywords to pass on to plot command

Returns:

tuple containing

ax_a (matplotlib.axes.axis): amplitude plot axis ax_p (matplotlib.axes.axis): phase plot axis

Return type:

(tuple)

static plots(sds, labels=None, channel=None, x=None, overlay=True, plot_peterson=True, show=True, outfile=None, title=None, line_kws=None, **fig_kw)

Plot overlaid autospectra of multiple SpectralDensity objects

Parameters:
  • sds (list) – SpectralDensity objects to plot

  • labels (list of dict) – labels for each SpectralDensity object

  • channel (str) – Limit to the given channel code

  • x – see plot()

  • overlay – see plot()

  • plot_peterson – see plot()

  • show – see plot()

  • outfile – see plot()

  • title – see plot()

  • line_kws (list of dict) – matplotlib.lines.Line2D keywords for each SpectralDensity function

  • **kwargs – any arguments used in plot_autospectra, except overlay (always true)

Returns:

fig axa (): amplitude axis

Return type:

figinfo (list)

static plots_coherences(sds, labels=None, channel_pair=None, x=None, y=None, display='sparse', show=True, outfile=None, label_by='chan', sort_by='chan', title=None, line_kws=None, **fig_kw)

Plot overlaid coherences of multiple SpectralDensity objects

Parameters:
  • sds (list) – SpectralDensity objects to plot. Each must have the same seed_ids

  • labels (list of str) – labels for each sds object

  • channel_pair (None or 2-tuple) – if a 2-tuple, plot only a single channel_pair, specified as (in_chan, out_chan)

  • x (None or list)

  • y (None or list) – y-axis channel names

  • display (str) – UNUSED

  • show (bool) – plot to the scrren

  • outfile (None or str) – save plot to the given filename

  • label_by= (None or str) – organize labels by ‘full’, ‘chan’, or ‘loc-chan’

  • sort_by= (None or str) – sort labels by ‘full’, ‘chan’, or ‘loc-chan’

  • title (str) – Title for figure

  • line_kws (list of dict) – matplotlib.lines.Line2D keywords for each SpectralDensity object

  • **fig_kws – any arguments for the figure)

Returns:

fig axa (): amplitude axis

Return type:

figinfo (list)

put_autospect(channel, auto_spect)

Equivalent to put_cross_spect(channel, channel, auto_spect)

Parameters:
  • channel (str) – auto-spectra channel id

  • auto_spect (numpy.ndarray) – the auto-spectral density

put_channel_instrument_response(channel, instrument_response)

Put a channel’s instrument response into the object

Verifies that the instrument_response has the same shape as the object’s frequency property and that it is of type=`complex`

Parameters:
  • channel (str) – the channel name

  • instrument_response (numpy.ndarray) – the instrument response

put_clean_sequence(channel, clean_sequence)

Put a channel’s clean_sequence into the object

Parameters:
  • channel (str) – the channel name

  • clean_sequence (list of str) – clean channels/methods, in order

put_crossspect(in_id, out_id, cross_spect)

Put data into one of the cross-spectra. Also puts the complex conjugate in the symmetric index

Parameters:
  • in_id (str) – cross-spectra input channel

  • out_id (str) – cross-spectra output channel

  • cross_spect (numpy.ndarray) – a cross-spectral density

replace_channel_id(channel, replacement)
Parameters:
  • channel (str) – original channel id

  • replacement (str) – replacement channel id

seed_id(id)
property seed_ids

list of seed_ids

property starttimes

Start times for each data window used to calculate spectra

Return type:

(list of obspy.UTCDateTimes)

units(in_id, out_id)

The units of the given cross- or auto-spectra

Parameters:
  • in_id (str) – input channel

  • out_id (str) – output channel

Returns:

the units

Return type:

(str)

property used_spans

time spans used during processing

Return type:

(tiskitpy.TimeSpans)

property used_times

GRANDFATHERED. Use .used_spans

property window_seconds

length of each window, in seconds

Return type:

(float)

property window_type

The type of window used to calculate the spectral densities

Return type:

(str)