スペクトログラム (Spectrogram)
gwexpy.spectrogram - Spectrogram data containers and operations.
- 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,SpectrogramExtends gwpy.spectrogram.Spectrogram with additional interop methods.
- 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.0or1.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
npersegornoverlapparameters will raiseTypeError.
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.0or1.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
npersegornoverlapparameters will raiseTypeError.
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,)
- 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 toshape[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.
- 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
- 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
- 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.Nattributes.channel (int, optional) – Channel index. If None, all channels are returned as a
SpectrogramDictfor multi-channel data.fs (float, optional) – Sample rate in Hz. Required if
stft_objhas nofsattribute.unit (str or astropy.units.Unit, optional) – Unit to assign to the result.
- Return type:
Spectrogram or SpectrogramDict
- 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.
- 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(orlog=Truein GWpy), and color scaling controls likevmin/vmax. For the full set of supported keywords, see the GWpy documentation.
- 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
- 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,normandvmin/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
- 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
- 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,channelfrom this Spectrogram.nameis set to"{original_name}_t{time}"or"t{time}"if the Spectrogram has no name, wheretimeis 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'
- 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
- to_obspy(**kwargs: Any) Any[source]
Convert to Obspy Stream.
- Return type:
obspy.Stream
- 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
- to_quantities(units=None)[source]
Convert to quantities.Quantity (Elephant/Neo compatible).
- to_th2d(error=None)[source]
Convert to ROOT TH2D.
- 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,channelfrom this Spectrogram.nameis set to"{original_name}_f{freq}"or"f{freq}"if the Spectrogram has no name, wherefreqis 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'
- class gwexpy.spectrogram.SpectrogramList(initlist=None)[source]
Bases:
PhaseMethodsMixin,UserListList of Spectrogram objects. Reference: similar to TimeSeriesList but for 2D Spectrograms.
Note
Spectrogram objects can be very large in memory. Use inplace=True where possible to avoid deep copies.
- append(item)[source]
- bootstrap(*args, **kwargs)[source]
Estimate robust ASD from each spectrogram in the list (returns FrequencySeriesList).
- crop(*args, **kwargs)[source]
Crop each spectrogram in time.
- Parameters:
start (float, optional) – Start time.
end (float, optional) – End time.
copy (bool, optional) – If True (default), return a new list. If False, modify in place.
*args – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.**kwargs – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.
- crop_frequencies(f0, f1, inplace=False)[source]
Crop frequencies.
- degree(unwrap: bool = False) SpectrogramList[source]
Compute phase (in degrees) of each spectrogram.
- extend(other)[source]
- interpolate(dt, df, inplace=False)[source]
Interpolate each spectrogram.
- plot(**kwargs)[source]
Plot all spectrograms stacked vertically.
- plot_summary(**kwargs)[source]
Plot List as side-by-side Spectrograms and percentile summaries.
- radian(unwrap: bool = False) SpectrogramList[source]
Compute phase (in radians) of each spectrogram.
- read(source, *args, **kwargs)[source]
Read spectrograms into the list from HDF5.
- rebin(dt, df, inplace=False)[source]
Rebin each spectrogram.
- to_cupy(*args, **kwargs) list[source]
Convert each item to cupy.ndarray. Returns a list.
- to_dask(*args, **kwargs) list[source]
Convert each item to dask.array. Returns a list.
- to_jax(*args, **kwargs) list[source]
Convert each item to jax.Array. Returns a list.
- to_matrix()[source]
Convert to SpectrogramMatrix (N, Time, Freq).
Validation follows SeriesMatrix base rules:
Shape must be identical across elements.
Times/frequencies are compared by converting to reference (first element) unit using .to_value(), then requiring np.array_equal (no tolerance). (Reuses gwexpy.types.seriesmatrix_validation logic).
Units, names, and channels may differ and are preserved per-element in the matrix’s MetaDataMatrix.
- Returns:
3D array of (N, Time, Freq) with per-element metadata.
- Return type:
SpectrogramMatrix
- Raises:
ValueError – If shape or axes differ after unit conversion.
- to_tensorflow(*args, **kwargs) list[source]
Convert each item to tensorflow.Tensor. Returns a list.
- to_torch(*args, **kwargs) list[source]
Convert each item to torch.Tensor. Returns a list.
- write(target, *args, **kwargs)[source]
Write list to file.
- class gwexpy.spectrogram.SpectrogramDict(dict=None, **kwargs)[source]
Bases:
PlotMixin,PhaseMethodsMixin,UserDictDictionary of Spectrogram objects.
Note
Spectrogram objects can be very large in memory. Use inplace=True where possible to update container in-place.
- bootstrap(*args, **kwargs)[source]
Estimate robust ASD from each spectrogram in the dict (returns FrequencySeriesDict).
- crop(*args, **kwargs)[source]
Crop each spectrogram in time.
- Parameters:
start (float, optional) – Start time.
end (float, optional) – End time.
copy (bool, optional) – If True (default), return a new dict. If False, modify in place.
*args – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.**kwargs – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.
- Return type:
SpectrogramDict
- crop_frequencies(f0, f1, inplace=False)[source]
Crop each spectrogram in frequency.
- Parameters:
f0 (float or Quantity) – Start and end frequencies.
f1 (float or Quantity) – Start and end frequencies.
inplace (bool, optional) – If True, modify in place.
- Return type:
SpectrogramDict
- degree(unwrap: bool = False) SpectrogramDict[source]
Compute phase (in degrees) of each spectrogram.
- interpolate(dt, df, inplace=False)[source]
Interpolate each spectrogram to new resolution.
- Parameters:
dt (float) – New time resolution.
df (float) – New frequency resolution.
inplace (bool, optional) – If True, modify in place.
- Return type:
SpectrogramDict
- plot_summary(**kwargs)[source]
Plot Dictionary as side-by-side Spectrograms and percentile summaries.
- radian(unwrap: bool = False) SpectrogramDict[source]
Compute phase (in radians) of each spectrogram.
- read(source, *args, **kwargs)[source]
Read dictionary from HDF5 file keys -> dict keys.
- rebin(dt, df, inplace=False)[source]
Rebin each spectrogram to new time/frequency resolution.
- Parameters:
dt (float) – New time bin size.
df (float) – New frequency bin size.
inplace (bool, optional) – If True, modify in place.
- Return type:
SpectrogramDict
- to_cupy(*args, **kwargs) dict[source]
Convert each item to cupy.ndarray. Returns a dict.
- to_dask(*args, **kwargs) dict[source]
Convert each item to dask.array. Returns a dict.
- to_jax(*args, **kwargs) dict[source]
Convert each item to jax.Array. Returns a dict.
- to_matrix()[source]
Convert to SpectrogramMatrix.
Validation follows SeriesMatrix base rules:
Shape must be identical across elements.
Times/frequencies are compared by converting to reference (first element) unit using .to_value(), then requiring np.array_equal (no tolerance). (Reuses gwexpy.types.seriesmatrix_validation logic).
Units, names, and channels may differ and are preserved per-element in the matrix’s MetaDataMatrix.
- Returns:
3D array of (N, Time, Freq) with per-element metadata.
- Return type:
SpectrogramMatrix
- Raises:
ValueError – If shape or axes differ after unit conversion.
- to_tensorflow(*args, **kwargs) dict[source]
Convert each item to tensorflow.Tensor. Returns a dict.
- to_torch(*args, **kwargs) dict[source]
Convert each item to torch.Tensor. Returns a dict.
- update(other=None, **kwargs)[source]
- write(target, *args, **kwargs)[source]
Write dictionary to file.
- class gwexpy.spectrogram.SpectrogramMatrix(data, times=None, frequencies=None, unit=None, name=None, rows=None, cols=None, meta=None, **kwargs)[source]
Bases:
PhaseMethodsMixin,SpectrogramMatrixCoreMixin,SpectrogramMatrixAnalysisMixin,SeriesMatrixEvaluation Matrix for Spectrograms (Time-Frequency maps).
This class represents a collection of Spectrograms, structured as either:
3D: (Batch, Time, Frequency)
4D: (Row, Col, Time, Frequency)
It inherits from SeriesMatrix, providing powerful indexing, metadata management, and analysis capabilities (slicing, interpolation, statistics).
Serialization
Pickle round-trips are supported via a custom
__reduce__/__setstate__that appends__dict__to the ndarray state. This preserves axis metadata such astimes/frequencies,rows/cols, andmetaas long as they live in__dict__. Attributes stored elsewhere or pointing to external resources still require higher-level I/O (e.g., HDF5) for full fidelity.- col_index(key)[source]
- col_keys()[source]
- dict_class
alias of
SpectrogramDict
- is_compatible(other: Any) bool[source]
Check compatibility with another SpectrogramMatrix/object. Overrides SeriesMatrix.is_compatible to avoid loop range issues due to mismatch between data shape (Time axis) and metadata shape (Batch/Col).
- list_class
alias of
SpectrogramList
- plot_summary(**kwargs)[source]
Plot Matrix as side-by-side Spectrograms and percentile summaries.
- row_index(key)[source]
- row_keys()[source]
- series_class
alias of
Spectrogram
- property shape3D
- to_dict()[source]
Convert to SpectrogramDict.
- to_list()[source]
Convert to SpectrogramList.
- to_series_1Dlist()[source]
Convert matrix to a flat 1D list of Spectrogram objects.
- to_series_2Dlist()[source]
Convert matrix to a 2D nested list of Spectrogram objects.