gwexpy.spectrogram.Spectrogram

class gwexpy.spectrogram.Spectrogram(data: ArrayLike, unit: UnitLike = None, t0: SupportsToGps | None = None, dt: Quantity | float | None = None, f0: Quantity | float | None = None, df: Quantity | float | None = None, times: ArrayLike1D | None = None, frequencies: ArrayLike1D | None = None, name: str | None = None, channel: Channel | str | None = None, **kwargs)[source]

Bases: PlotMixin, PhaseMethodsMixin, InteropMixin, Spectrogram

Extends gwpy.spectrogram.Spectrogram with additional interop methods.

__init__()

Methods

__init__()

abs(**kwargs)

Return the absolute value of the data in this Array.

all([axis, out])

angle([unwrap, deg])

Alias for phase(unwrap=unwrap, deg=deg).

any([axis, out])

append(other, *[, inplace, gap, pad, resize])

Connect another series onto this one.

argmax([axis, out, keepdims])

argmin([axis, out, keepdims])

argpartition(kth[, axis, kind, order])

Returns the indices that would partition this array.

argsort([axis, kind, order])

astype(dtype[, order, casting, subok, copy])

Copy of the array, cast to a specified type.

bootstrap([n_boot, method, average, ci, ...])

Estimate robust ASD from this spectrogram using bootstrap resampling.

bootstrap_asd([n_boot, average, ci, window, ...])

Convenience wrapper for bootstrap ASD estimation.

byteswap([inplace])

Swap the bytes of the array elements

check_compatible(other[, casting, ...])

Check whether this Series and other are compatible.

choose(choices[, out, mode])

clean([method, threshold, window_size, ...])

Clean the spectrogram by removing artifacts.

clip([min, max, out])

Return an array whose values are limited to [min, max].

compress(condition[, axis, out])

Return selected slices of this array along given axis.

conj()

Complex-conjugate all elements.

conjugate()

Return the complex conjugate, element-wise.

copy([order])

Return a copy of the array.

crop([start, end, copy])

Crop this series to the given x-axis extent.

crop_frequencies([low, high, copy])

Crop this Spectrogram to the specified frequencies.

cumprod([axis, dtype, out])

Return the cumulative product of the elements along the given axis.

cumsum([axis, dtype, out])

Return the cumulative sum of the elements along the given axis.

decompose([bases])

Generates a new Quantity with the units decomposed.

degree([unwrap])

Calculate the phase of this Spectrogram in degrees.

diagonal([offset, axis1, axis2])

Return specified diagonals.

diff([n, axis])

Calculate the n-th order discrete difference along given axis.

dot(b[, out])

dump(file)

Not implemented, use .value.dump() instead.

dumps()

Not implemented, use .value.dumps() instead.

ediff1d([to_end, to_begin])

fill(value)

filter(filt, *[, analog, sample_rate, unit, ...])

Apply the given filter to this Spectrogram.

flatten([order])

Return a copy of the array collapsed into one dimension.

from_mne(tfr, **kwargs)

Create Spectrogram from MNE-Python TFR object.

from_obspy(stream, **kwargs)

Create Spectrogram from Obspy Stream.

from_pyroomacoustics_stft(stft_obj, *[, ...])

Create from a pyroomacoustics STFT object.

from_quantities(q, times, frequencies)

Create Spectrogram from quantities.Quantity.

from_root(obj[, return_error])

Create Spectrogram from ROOT TH2D.

from_spectra(*spectra, **kwargs)

Build a new Spectrogram from a list of spectra.

getfield(dtype[, offset])

Returns a field of the given array as a certain type.

imshow(**kwargs)

Plot using Matplotlib imshow (GWpy-compatible).

inject(other, *[, inplace])

Add two compatible Series along their shared x-axis values.

insert(obj, values[, axis])

Insert values along the given axis before the given indices and return a new ~astropy.units.Quantity object.

is_compatible(other)

Check whether this series and other have compatible metadata.

is_contiguous(other[, tol])

Check whether other is contiguous with self.

item(*args)

Copy an element of an array to a scalar Quantity and return it.

itemset(*args)

max([axis, out, keepdims, initial, where])

Return the maximum along a given axis.

mean([axis, dtype, out, keepdims, where])

median([axis])

Return the median of the data in this Array.

min([axis, out, keepdims, initial, where])

Return the minimum along a given axis.

newbyteorder([new_order])

Return the array with the same data viewed with a different byte order.

nonzero()

Return the indices of the elements that are non-zero.

normalize([method, reference, percentile])

Normalize the spectrogram along the time axis.

override_unit(unit[, parse_strict])

Reset the unit of these data.

pad(pad_width, **kwargs)

Pad this series to a new size.

partition(kth[, axis, kind, order])

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

pcolormesh(**kwargs)

Plot using Matplotlib pcolormesh (GWpy-compatible).

percentile(percentile)

Calculate a given spectral percentile for this Spectrogram.

phase([unwrap, deg])

Calculate the phase of the data.

plot(**kwargs)

Plot this object using gwexpy.plot.Plot.

prepend(other, *[, inplace, gap, pad, resize])

Connect another series onto the start of the current one.

prod([axis, dtype, out, keepdims, initial, ...])

Return the product of the array elements over the given axis

ptp([axis, out, keepdims])

Peak to peak (maximum - minimum) value along a given axis.

put(indices, values[, mode])

radian([unwrap])

Calculate the phase of this Spectrogram in radians.

ratio(operand)

Calculate the ratio of this Spectrogram against a reference.

ravel([order])

Return a flattened array.

rebin([dt, df])

Rebin the spectrogram in time and/or frequency.

repeat(repeats[, axis])

Repeat elements of an array.

reshape(shape[, order])

Returns an array containing the same data with a new shape.

resize(new_shape[, refcheck])

Change shape and size of array in-place.

round([decimals, out])

searchsorted(v, *args, **kwargs)

setfield(val, dtype[, offset])

Put a value into a specified place in a field defined by a data-type.

setflags([write, align, uic])

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

shift(delta)

Shift this Series forward on the X-axis by delta.

sort([axis, kind, order])

Sort an array in-place.

squeeze([axis])

Remove axes of length one from a.

std([axis, dtype, out, ddof, keepdims, where])

step(**kwargs)

Create a step plot of this series.

sum([axis, dtype, out, keepdims, initial, where])

Return the sum of the array elements over the given axis.

swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged.

take(indices[, axis, out, mode])

to(unit[, equivalencies, copy])

Return a new ~astropy.units.Quantity object with the specified unit.

to_cupy([dtype])

Convert to CuPy Array.

to_dask([chunks])

Convert to Dask Array.

to_frequencyseries_list()

Convert this Spectrogram to a list of FrequencySeries, one per time bin.

to_jax()

Convert to JAX Array.

to_mne([info])

Convert to MNE-Python object.

to_obspy(**kwargs)

Convert to Obspy Stream.

to_pyroomacoustics_stft(*[, hop, ...])

Export as a pyroomacoustics STFT object.

to_quantities([units])

Convert to quantities.Quantity (Elephant/Neo compatible).

to_string([unit, precision, format, subfmt, ...])

Generate a string representation of the quantity and its unit.

to_tensorflow([dtype])

Convert to tensorflow.Tensor.

to_th2d([error])

Convert to ROOT TH2D.

to_timeseries_list()

Convert this Spectrogram to a list of TimeSeries, one per frequency bin.

to_torch([device, dtype, requires_grad, copy])

Convert to torch.Tensor.

to_value([unit, equivalencies])

The numerical value, possibly in a different unit.

to_zarr(store[, path])

Save to Zarr storage.

tobytes([order])

Not implemented, use .value.tobytes() instead.

tofile(fid[, sep, format])

Not implemented, use .value.tofile() instead.

tolist()

tostring([order])

Not implemented, use .value.tostring() instead.

trace([offset, axis1, axis2, dtype, out])

transpose(*axes)

Returns a view of the array with axes transposed.

update(other, *[, inplace, gap, pad])

Update this series by appending new data like a buffer.

value_at(x, y)

Return the value of this Series at the given (x, y) coordinates.

var([axis, dtype, out, ddof, keepdims, where])

variance([bins, low, high, nbins, log, ...])

Calculate the SpectralVariance of this Spectrogram.

view([dtype][, type])

New view of array with the same data.

zip()

Zip the xindex and value arrays of this Series.

zpk(zeros, poles, gain, *[, analog, ...])

Filter this Spectrogram by applying a zero-pole-gain filter.

Attributes

T

Return the transpose of this Array2D.

band

Frequency band described by these data.

base

Base object if memory is from some other object.

cgs

Returns a copy of the current Quantity instance with CGS units.

channel

Instrumental channel associated with these data.

ctypes

An object to simplify the interaction of the array with the ctypes module.

data

Python buffer object pointing to the start of the array's data.

df

Frequency spacing for these data.

dt

Time (seconds) between successive bins.

dtype

Data-type of the array's elements.

dx

X-axis sample separation.

dy

Y-axis sample separation.

epoch

GPS epoch for these data.

equivalencies

A list of equivalencies that will be applied by default during unit conversions.

f0

Starting frequency for these data.

flags

Information about the memory layout of the array.

flat

A 1-D iterator over the Quantity array.

frequencies

Series of frequencies for these data.

imag

The imaginary part of the array.

info

Container for meta information like name, description, format.

isscalar

True if the value of this quantity is a scalar, or False if it is an array-like object.

itemsize

Length of one array element in bytes.

name

Name for this data set.

nbytes

Total bytes consumed by the elements of the array.

ndim

Number of array dimensions.

read

real

The real part of the array.

shape

Tuple of array dimensions.

si

Returns a copy of the current Quantity instance with SI units.

size

Number of elements in the array.

span

GPS [start, stop) span for these data.

strides

Tuple of bytes to step in each dimension when traversing an array.

t0

GPS time of first time bin.

times

Series of GPS times for each sample

unit

The physical unit of these data.

value

The numerical value of this instance.

write

x0

X-axis coordinate of the first data point.

xindex

Positions of the data on the x-axis.

xspan

X-axis [low, high) segment encompassed by these data.

xunit

Unit of x-axis index.

y0

Y-axis coordinate of the first data point.

yindex

Positions of the data on the y-axis.

yspan

Y-axis [low, high) segment encompassed by these data.

yunit

Unit of Y-axis index.

bootstrap(n_boot=1000, method='median', average=None, ci=0.68, window='hann', fftlength=None, overlap=None, nfft=None, noverlap=None, block_size=None, rebin_width=None, return_map=False, ignore_nan=True, **kwargs)[source]

Estimate robust ASD from this spectrogram using bootstrap resampling.

This is a convenience wrapper around gwexpy.spectral.bootstrap_spectrogram.

Parameters:
  • fftlength (float or Quantity, optional) – FFT segment length in seconds (e.g. 1.0 or 1.0 * u.s). Used for VIF overlap-correlation correction. If None, the correction is estimated from spectrogram metadata. Cannot be used with nfft.

  • overlap (float or Quantity, optional) – Overlap between FFT segments in seconds. If None, defaults to the recommended overlap for window (50 % for Hann). Cannot be used with noverlap.

  • nfft (int, optional) – FFT segment length in samples. Alternative to fftlength. Cannot be used with fftlength.

  • noverlap (int, optional) – Overlap length in samples. Must be used with nfft. Cannot be used with overlap.

  • block_size (float, Quantity, or 'auto', optional) – Duration of blocks for block bootstrap in seconds. Can be specified as float (seconds), Quantity with time units, or ‘auto’. If ‘auto’, estimates size based on overlap ratio. If None, perform standard bootstrap with analytical VIF correction.

  • rebin_width (float, optional) – Frequency rebinning width in Hz before bootstrapping.

  • **kwargs – Additional keyword arguments. Passing the removed nperseg or noverlap parameters will raise TypeError.

Examples

>>> from gwexpy.spectrogram import Spectrogram
>>> import numpy as np
>>> from astropy import units as u
>>>
>>> # Create synthetic spectrogram
>>> np.random.seed(42)
>>> spec_data = np.random.random((100, 50))
>>> spec = Spectrogram(spec_data, dt=1.0*u.s, f0=10*u.Hz, df=1*u.Hz)
>>>
>>> # Bootstrap estimation with time-based parameters
>>> result = spec.bootstrap(
...     n_boot=100,
...     fftlength=4.0,    # 4 seconds
...     overlap=2.0,      # 2 seconds
...     block_size=2.0,   # 2 seconds block
...     window='hann',
...     method='median'
... )
>>> print(result.value.shape)
(50,)
bootstrap_asd(n_boot=1000, average='median', ci=0.68, window='hann', fftlength=None, overlap=None, nfft=None, noverlap=None, block_size=None, rebin_width=None, return_map=False, ignore_nan=True, **kwargs)[source]

Convenience wrapper for bootstrap ASD estimation.

Parameters:
  • fftlength (float or Quantity, optional) – FFT segment length in seconds (e.g. 1.0 or 1.0 * u.s). Used for VIF overlap-correlation correction. Cannot be used with nfft.

  • overlap (float or Quantity, optional) – Overlap between FFT segments in seconds. Cannot be used with noverlap.

  • nfft (int, optional) – FFT segment length in samples. Alternative to fftlength.

  • noverlap (int, optional) – Overlap length in samples. Must be used with nfft.

  • block_size (float, Quantity, or 'auto', optional) – Duration of blocks for block bootstrap in seconds. Can be specified as float (seconds), Quantity with time units, or ‘auto’.

  • rebin_width (float, optional) – Frequency rebinning width in Hz before bootstrapping.

  • **kwargs – Additional keyword arguments. Passing the removed nperseg or noverlap parameters will raise TypeError.

Examples

>>> from gwexpy.spectrogram import Spectrogram
>>> import numpy as np
>>> from astropy import units as u
>>>
>>> # Create synthetic spectrogram
>>> np.random.seed(42)
>>> spec_data = np.random.random((100, 50))
>>> spec = Spectrogram(spec_data, dt=1.0*u.s, f0=10*u.Hz, df=1*u.Hz)
>>>
>>> # Bootstrap ASD estimation
>>> result = spec.bootstrap_asd(
...     n_boot=100,
...     fftlength=4.0,    # 4 seconds
...     overlap=2.0,      # 2 seconds
...     block_size=2.0,   # 2 seconds block
...     window='hann',
...     average='median'
... )
>>> print(result.value.shape)
(50,)
to_th2d(error=None)[source]

Convert to ROOT TH2D.

to_quantities(units=None)[source]

Convert to quantities.Quantity (Elephant/Neo compatible).

classmethod from_quantities(q, times, frequencies)[source]

Create Spectrogram from quantities.Quantity.

Parameters:
  • q (quantities.Quantity) – Input data (Time x Frequency matrix).

  • times (array-like) – Time axis.

  • frequencies (array-like) – Frequency axis.

classmethod from_root(obj, return_error=False)[source]

Create Spectrogram from ROOT TH2D.

to_mne(info: Any | None = None) Any[source]

Convert to MNE-Python object.

Parameters:

info (mne.Info, optional) – MNE Info object.

Return type:

mne.time_frequency.EpochsTFRArray

classmethod from_mne(tfr: Any, **kwargs: Any) Any[source]

Create Spectrogram from MNE-Python TFR object.

Parameters:
  • tfr (mne.time_frequency.EpochsTFR or AverageTFR) – Input TFR data.

  • **kwargs – Additional arguments passed to constructor.

Return type:

Spectrogram or SpectrogramDict

to_obspy(**kwargs: Any) Any[source]

Convert to Obspy Stream.

Return type:

obspy.Stream

classmethod from_obspy(stream: Any, **kwargs: Any) Any[source]

Create Spectrogram from Obspy Stream.

Parameters:
  • stream (obspy.Stream) – Input stream.

  • **kwargs – Additional arguments.

Return type:

Spectrogram

classmethod from_pyroomacoustics_stft(stft_obj: Any, *, channel: int | None = None, fs: float | None = None, unit: Any | None = None) Any[source]

Create from a pyroomacoustics STFT object.

Parameters:
  • stft_obj (pyroomacoustics.stft.STFT) – STFT object with .X, .hop, and .N attributes.

  • channel (int, optional) – Channel index. If None, all channels are returned as a SpectrogramDict for multi-channel data.

  • fs (float, optional) – Sample rate in Hz. Required if stft_obj has no fs attribute.

  • unit (str or astropy.units.Unit, optional) – Unit to assign to the result.

Return type:

Spectrogram or SpectrogramDict

to_pyroomacoustics_stft(*, hop: int | None = None, analysis_window: Any | None = None) Any[source]

Export as a pyroomacoustics STFT object.

Parameters:
  • hop (int, optional) – Hop size in samples. If None, estimated from the spectrogram metadata.

  • analysis_window (numpy.ndarray, optional) – Analysis window for the STFT object.

Return type:

pyroomacoustics.stft.STFT

rebin(dt: float | Quantity | None = None, df: float | Quantity | None = None) Spectrogram[source]

Rebin the spectrogram in time and/or frequency.

Parameters:
  • dt (float or Quantity, optional) – New time bin width in seconds.

  • df (float or Quantity, optional) – New frequency bin width in Hz.

Returns:

The rebinned spectrogram.

Return type:

Spectrogram

imshow(**kwargs)[source]

Plot using Matplotlib imshow (GWpy-compatible).

This method is provided for convenience and forwards arguments to gwpy.spectrogram.Spectrogram.imshow().

Common keyword arguments include ax, cmap, norm (or log=True in GWpy), and color scaling controls like vmin/vmax. For the full set of supported keywords, see the GWpy documentation.

pcolormesh(**kwargs)[source]

Plot using Matplotlib pcolormesh (GWpy-compatible).

This method is provided for convenience and forwards arguments to gwpy.spectrogram.Spectrogram.pcolormesh().

Common keyword arguments include ax, cmap, norm and vmin/vmax. For the full set of supported keywords, see the GWpy documentation.

radian(unwrap: bool = False) Spectrogram[source]

Calculate the phase of this Spectrogram in radians.

Parameters:

unwrap (bool, optional) – If True, unwrap the phase to remove discontinuities along the time axis. Default is False.

Returns:

A new Spectrogram containing the phase in radians. All other metadata (times, frequencies, channel, epoch, etc.) are preserved.

Return type:

Spectrogram

degree(unwrap: bool = False) Spectrogram[source]

Calculate the phase of this Spectrogram in degrees.

Parameters:

unwrap (bool, optional) – If True, unwrap the phase to remove discontinuities along the time axis. Default is False.

Returns:

A new Spectrogram containing the phase in degrees. All other metadata (times, frequencies, channel, epoch, etc.) are preserved.

Return type:

Spectrogram

normalize(method: str = 'snr', reference: Any | None = None, *, percentile: float = 50.0) Spectrogram[source]

Normalize the spectrogram along the time axis.

Parameters:
  • method ({'snr', 'median', 'mean', 'percentile', 'reference'}) –

    Normalization method.

    • 'snr': Divide each time slice by the median PSD along the time axis (equivalent to 'median'). If reference is given, use it as the denominator instead.

    • 'median': Divide by the median along the time axis per frequency bin.

    • 'mean': Divide by the mean along the time axis.

    • 'percentile': Divide by the given percentile along the time axis.

    • 'reference': Divide by a user-provided reference spectrum. reference must be given.

  • reference (FrequencySeries or array-like, optional) – Reference spectrum used as the denominator for 'snr' (if provided) or 'reference' mode.

  • percentile (float, optional) – Percentile value for 'percentile' mode. Default is 50.0 (equivalent to median).

Returns:

Normalized spectrogram. Unit is set to dimensionless for ratio methods.

Return type:

Spectrogram

clean(method: str = 'threshold', *, threshold: float = 5.0, window_size: int | None = None, fill: str = 'median', persistence_threshold: float = 0.8, amplitude_threshold: float = 3.0, return_mask: bool = False) Spectrogram | tuple[Spectrogram, ndarray][source]

Clean the spectrogram by removing artifacts.

Parameters:
  • method ({'threshold', 'rolling_median', 'line_removal', 'combined'}) –

    Cleaning method.

    • 'threshold': Remove outlier pixels using MAD-based detection.

    • 'rolling_median': Normalize slow trends with a rolling median filter along the time axis.

    • 'line_removal': Remove persistent narrowband lines.

    • 'combined': Apply threshold, then rolling_median, then line_removal sequentially.

  • threshold (float, optional) – MAD sigma threshold for outlier detection. Default 5.0.

  • window_size (int, optional) – Rolling window size in time bins for 'rolling_median' and 'combined' modes. If None, defaults to shape[0] // 4 (clamped to at least 3).

  • fill ({'median', 'nan', 'zero', 'interpolate'}) – How to fill masked/outlier values (for threshold method).

  • persistence_threshold (float, optional) – Fraction threshold for line detection (0.0-1.0). Default 0.8.

  • amplitude_threshold (float, optional) – Factor above global median for line detection. Default 3.0.

  • return_mask (bool, optional) – If True, also return a boolean mask of cleaned pixels.

Returns:

  • Spectrogram – Cleaned spectrogram.

  • mask (ndarray, optional) – Boolean mask where True = pixel was cleaned. Only returned when return_mask is True.

to_timeseries_list() tuple[TimeSeriesList, Quantity][source]

Convert this Spectrogram to a list of TimeSeries, one per frequency bin.

For a Spectrogram with shape (ntimes, nfreqs), this extracts each column (frequency bin) as a TimeSeries with the same time axis.

Returns:

  • ts_list (TimeSeriesList) – A list of TimeSeries, one for each frequency bin. Each TimeSeries has length ntimes.

  • frequencies (Quantity) – The frequency axis of this Spectrogram (length nfreqs).

Notes

  • Each TimeSeries inherits unit, epoch, channel from this Spectrogram.

  • name is set to "{original_name}_f{freq}" or "f{freq}" if the Spectrogram has no name, where freq is the frequency value.

Examples

>>> spec = Spectrogram(data, t0=0, dt=0.1, f0=10, df=5, name="test")
>>> ts_list, freqs = spec.to_timeseries_list()
>>> len(ts_list)  # equals nfreqs
5
>>> ts_list[0].name
'test_f10.0Hz'
to_frequencyseries_list() tuple[FrequencySeriesList, Quantity][source]

Convert this Spectrogram to a list of FrequencySeries, one per time bin.

For a Spectrogram with shape (ntimes, nfreqs), this extracts each row (time bin) as a FrequencySeries with the same frequency axis.

Returns:

  • fs_list (FrequencySeriesList) – A list of FrequencySeries, one for each time bin. Each FrequencySeries has length nfreqs.

  • times (Quantity) – The time axis of this Spectrogram (length ntimes).

Notes

  • Each FrequencySeries inherits unit, epoch, channel from this Spectrogram.

  • name is set to "{original_name}_t{time}" or "t{time}" if the Spectrogram has no name, where time is the time value.

Examples

>>> spec = Spectrogram(data, t0=0, dt=0.1, f0=10, df=5, name="test")
>>> fs_list, times = spec.to_frequencyseries_list()
>>> len(fs_list)  # equals ntimes
10
>>> fs_list[0].name
'test_t0.0s'