スペクトログラム (Spectrogram)

Note

ページ種別: 二次 API カテゴリ

安定性: 安定

概要

Note

学習ステップ: 入門チュートリアルの後や、時間周波数ワークフローから正確な API 詳細に戻りたい場合にこのページを使ってください。

See also

チュートリアル(機能別)

機能別に学び始めるためのチュートリアル一覧。

Spectrogram: 基本

API を引く前に確認したい Spectrogram の基本例。

FFT の仕様と規約 (FFT_Conventions)

GWexpy が採用するフーリエ正規化と軸の規約。

信号抽出: 色付き雑音からの微弱信号回収

Spectrogram 系 API に戻れる時間周波数事例。

数値的安定性と精度

FFT ベースの時間周波数解析で確認すべき安定化ノート。

トピック別参照 (Topics)

規約や高度・理論解説を概念別にたどる入口。

Spectrogram(data[, unit, t0, dt, f0, df, ...])

A 2D time-frequency 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

A 2D time-frequency spectrogram.

Spectrogram represents a 2-dimensional array of spectral data, where the first dimension corresponds to time and the second dimension corresponds to frequency. It extends the core GWpy ~gwpy.spectrogram.Spectrogram with additional signal processing (e.g., bootstrap ASD estimation, cleaning) and interoperability methods.

Parameters:
  • data (array-like) – 2D array of spectral data.

  • times (array-like, optional) – Time values corresponding to each row. If provided, dt and t0 are ignored.

  • dt (float, ~astropy.units.Quantity, optional) – Time step between rows.

  • t0 (float, ~astropy.units.Quantity, optional) – Start time of the data.

  • frequencies (array-like, optional) – Frequency values corresponding to each column. If provided, df and f0 are ignored.

  • df (float, ~astropy.units.Quantity, optional) – Frequency step between columns.

  • f0 (float, ~astropy.units.Quantity, optional) – Start frequency of the data.

  • **kwargs – Additional keyword arguments passed to the ~gwpy.spectrogram.Spectrogram constructor.

Notes

Key methods:

plot(**kwargs)

Plot this object using gwexpy.plot.Plot.

imshow(**kwargs)

Plot using Matplotlib imshow (GWpy-compatible).

pcolormesh(**kwargs)

Plot using Matplotlib pcolormesh (GWpy-compatible).

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

Estimate robust ASD from this spectrogram using bootstrap resampling.

normalize([method, reference, percentile])

Normalize the spectrogram along the time axis.

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

Clean the spectrogram by removing artifacts.

rebin([dt, df])

Rebin the spectrogram in time and/or frequency.

Examples

>>> from gwexpy.spectrogram import Spectrogram
>>> import numpy as np
>>> data = np.ones((2, 2))
>>> spec = Spectrogram(data, dt=1, f0=0, df=1)
>>> spec
<Spectrogram([[1., 1.],
              [1., 1.]],
             unit=Unit(dimensionless),
             name=None,
             epoch=<Time object: scale='utc' format='gps' value=0.0>,
             channel=None,
             x0=<Quantity 0. s>,
             dx=<Quantity 1. s>,
             xindex=<Index [0., 1.] s>,
             y0=<Quantity 0. Hz>,
             dy=<Quantity 1. Hz>,
             yindex=<Index [0., 1.] Hz>)>

メソッド

plot(**kwargs)

Plot this object using gwexpy.plot.Plot.

crop([start, end, copy])

Crop this series to the given x-axis extent.

percentile(percentile)

Calculate a given spectral percentile for this Spectrogram.

ratio(operand)

Calculate the ratio of this Spectrogram against a reference.

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

Apply the given filter to this Spectrogram.

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:
  • n_boot (int, optional) – Number of bootstrap resamples to draw.

  • method (str, optional) – Bootstrap estimator to use.

  • average (str, optional) – Deprecated alias for method.

  • ci (float, optional) – Central confidence interval width.

  • window (str, optional) – Window function used for overlap-correction defaults.

  • 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.

  • return_map (bool, optional) – If True, return the full bootstrap map in addition to the summary.

  • ignore_nan (bool, optional) – If True, ignore NaN values during resampling.

  • **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]

Estimate bootstrap ASD with the convenience wrapper.

Parameters:
  • n_boot (int, optional) – Number of bootstrap resamples to draw.

  • average (str, optional) – Averaging method passed through to bootstrap.

  • ci (float, optional) – Central confidence interval width.

  • window (str, optional) – Window function used for overlap-correction defaults.

  • 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.

  • return_map (bool, optional) – If True, return the full bootstrap map in addition to the summary.

  • ignore_nan (bool, optional) – If True, ignore NaN values during resampling.

  • **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 for Elephant or Neo compatibility.

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 a 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) Self[source]

Rebin the spectrogram in time and/or frequency.

Rebinning averages only complete bins. If the time or frequency axis length is not divisible by the requested bin size, trailing samples that do not form a complete bin are discarded.

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:

Self

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) Self[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:

Self

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) Self | tuple[Self, 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:

  • Self – 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

>>> import numpy as np
>>> data = np.ones((10, 5))
>>> 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.0 Hz'
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

>>> import numpy as np
>>> data = np.ones((10, 5))
>>> 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.0 s'

モジュール内容

gwexpy.spectrogram - Spectrogram data containers and operations.

class gwexpy.spectrogram.SpectrogramList(initlist=None)[source]

Bases: PhaseMethodsMixin, UserList

A list of Spectrogram objects.

SpectrogramList is a specialized list designed to hold and manipulate multiple Spectrogram objects. It provides batch processing methods (e.g., crop, rebin, bootstrap) that operate on all entries at once.

Parameters:

initlist (iterable, optional) – An initial list of Spectrogram objects.

Notes

Spectrogram objects can be very large in memory. For large datasets, consider using SpectrogramMatrix for more efficient 3D/4D operations, or use the inplace=True option in methods like rebin when available.

Key methods:

plot(**kwargs)

Plot all spectrograms stacked vertically.

to_matrix()

Convert to SpectrogramMatrix (N, Time, Freq).

bootstrap(*args, **kwargs)

Estimate robust ASD from each spectrogram in the list (returns FrequencySeriesList).

rebin(dt, df[, inplace])

Rebin each spectrogram.

crop(*args, **kwargs)

Crop each spectrogram in time.

Examples

>>> from gwexpy.spectrogram import Spectrogram, SpectrogramList
>>> import numpy as np
>>> spec = Spectrogram(np.ones((2, 2)), dt=1, f0=0, df=1)
>>> sl = SpectrogramList([spec])
>>> sl
[<Spectrogram([[1., 1.],
              [1., 1.]],
             unit=Unit(dimensionless),
             name=None,
             epoch=<Time object: scale='utc' format='gps' value=0.0>,
             channel=None,
             x0=<Quantity 0. s>,
             dx=<Quantity 1. s>,
             xindex=<Index [0., 1.] s>,
             y0=<Quantity 0. Hz>,
             dy=<Quantity 1. Hz>,
             yindex=<Index [0., 1.] Hz>)>]
append(item)[source]

Append a spectrogram, coercing compatible base objects when needed.

extend(other)[source]

Extend the list with validated spectrogram objects.

read(source, *args, **kwargs)[source]

Read spectrograms into the list from HDF5.

write(target, *args, **kwargs)[source]

Write list to file.

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/inplace and positional inplace are accepted for backwards compatibility but will be removed in a future release.

  • **kwargs – Deprecated: t0/t1/inplace and positional inplace are accepted for backwards compatibility but will be removed in a future release.

crop_frequencies(f0, f1, inplace=False)[source]

Crop frequencies.

rebin(dt, df, inplace=False)[source]

Rebin each spectrogram.

interpolate(dt, df, inplace=False)[source]

Interpolate each spectrogram.

plot(**kwargs)[source]

Plot all spectrograms stacked vertically.

plot_summary(**kwargs)[source]

Plot the list as spectrograms with percentile summaries.

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_torch(*args, **kwargs) list[source]

Convert each item to torch.Tensor. Returns a list.

to_tensorflow(*args, **kwargs) list[source]

Convert each item to tensorflow.Tensor. Returns a list.

to_jax(*args, **kwargs) list[source]

Convert each item to jax.Array. Returns a list.

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.

bootstrap(*args, **kwargs)[source]

Estimate robust ASD from each spectrogram in the list (returns FrequencySeriesList).

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

Compute phase (in radians) of each spectrogram.

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

Compute phase (in degrees) of each spectrogram.

class gwexpy.spectrogram.SpectrogramDict(dict=None, **kwargs)[source]

Bases: PlotMixin, PhaseMethodsMixin, UserDict

A dictionary of Spectrogram objects, indexed by name.

SpectrogramDict is a specialized dictionary designed to hold and manipulate multiple Spectrogram objects simultaneously. It supports batch I/O (HDF5), normalization, and conversion to multivariate SpectrogramMatrix.

Parameters:
  • dict (mapping, optional) – A mapping or iterable of (key, Spectrogram) pairs.

  • **kwargs – Additional keyword arguments for the dictionary.

Notes

Spectrogram objects can be very large in memory. For large datasets, prefer SpectrogramMatrix or HDF5-backed storage.

Key methods:

read(source, *args, **kwargs)

Read dictionary from HDF5 file keys -> dict keys.

write(target, *args, **kwargs)

Write dictionary to file.

plot(**kwargs)

Plot this object using gwexpy.plot.Plot.

to_matrix()

Convert to SpectrogramMatrix.

rebin(dt, df[, inplace])

Rebin each spectrogram to new time/frequency resolution.

Examples

>>> from gwexpy.spectrogram import Spectrogram, SpectrogramDict
>>> import numpy as np
>>> sd = SpectrogramDict()
>>> sd['H1'] = Spectrogram(np.ones((2, 2)), dt=1, f0=0, df=1)
>>> sd
{'H1': <Spectrogram([[1., 1.],
              [1., 1.]],
             unit=Unit(dimensionless),
             name=None,
             epoch=<Time object: scale='utc' format='gps' value=0.0>,
             channel=None,
             x0=<Quantity 0. s>,
             dx=<Quantity 1. s>,
             xindex=<Index [0., 1.] s>,
             y0=<Quantity 0. Hz>,
             dy=<Quantity 1. Hz>,
             yindex=<Index [0., 1.] Hz>)>}
update(other=None, **kwargs)[source]

Update the dictionary with validated spectrogram objects.

read(source, *args, **kwargs)[source]

Read dictionary from HDF5 file keys -> dict keys.

write(target, *args, **kwargs)[source]

Write dictionary to file.

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/inplace and positional inplace are accepted for backwards compatibility but will be removed in a future release.

  • **kwargs – Deprecated: t0/t1/inplace and positional inplace are 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

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

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 the dictionary as spectrograms with percentile summaries.

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_torch(*args, **kwargs) dict[source]

Convert each item to torch.Tensor. Returns a dict.

to_tensorflow(*args, **kwargs) dict[source]

Convert each item to tensorflow.Tensor. Returns a dict.

to_jax(*args, **kwargs) dict[source]

Convert each item to jax.Array. Returns a dict.

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.

bootstrap(*args, **kwargs)[source]

Estimate robust ASD from each spectrogram in the dict (returns FrequencySeriesDict).

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

Compute phase (in radians) of each spectrogram.

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

Compute phase (in degrees) of each spectrogram.

class gwexpy.spectrogram.SpectrogramMatrix(data: ArrayLike | SpectrogramMatrix, times: IndexLike | None = None, frequencies: IndexLike | None = None, unit: UnitLike = None, name: str | None = None, rows: MetaDataCollectionType = None, cols: MetaDataCollectionType = None, meta: Any = None, **kwargs: Any)[source]

Bases: PhaseMethodsMixin, SpectrogramMatrixCoreMixin, SpectrogramMatrixAnalysisMixin, SeriesMatrix

Evaluation Matrix for Spectrograms (Time-Frequency maps).

SpectrogramMatrix represents a collection of Spectrograms, structured as a multivariate matrix with dimensions either:

  • 3D: (Batch, Time, Frequency)

  • 4D: (Row, Col, Time, Frequency)

It extends the core ~gwexpy.types.seriesmatrix.SeriesMatrix with spectrogram-specific axes (times and frequencies) and analysis methods.

Parameters:
  • data (array-like) – The data values for the matrix. Should be 3D or 4D.

  • times (array-like, optional) – The time values corresponding to each row.

  • frequencies (array-like, optional) – The frequency values corresponding to each column.

  • unit (str, ~astropy.units.Unit, optional) – Physical unit of the data.

  • **kwargs – Additional keyword arguments passed to the ~gwexpy.types.seriesmatrix.SeriesMatrix constructor.

Notes

Serialization is supported via HDF5 and Pickle. Metadata is preserved per-element in the meta attribute.

Key methods:

plot_summary(**kwargs)

Plot the matrix as side-by-side spectrograms and percentile summaries.

to_dict()

Convert to SpectrogramDict.

to_list()

Convert to SpectrogramList.

radian([unwrap])

Calculate the phase of the matrix in radians.

Examples

>>> from gwexpy.spectrogram import SpectrogramMatrix
>>> import numpy as np
>>> data = np.ones((1, 2, 2))
>>> sm = SpectrogramMatrix(data, times=[0, 1], frequencies=[10, 20])
>>> sm
<SeriesMatrix shape=(1, 2, 2) rows=('batch0',) cols=('col0',)>
series_class

alias of Spectrogram

dict_class

alias of SpectrogramDict

list_class

alias of SpectrogramList

row_keys()[source]

Return the row metadata keys.

col_keys()[source]

Return the column metadata keys.

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).

row_index(key)[source]

Return the integer index for a row key.

col_index(key)[source]

Return the integer index for a column key.

to_series_2Dlist()[source]

Convert matrix to a 2D nested list of Spectrogram objects.

to_series_1Dlist()[source]

Convert matrix to a flat 1D list of Spectrogram objects.

to_list()[source]

Convert to SpectrogramList.

to_dict()[source]

Convert to SpectrogramDict.

property shape3D

Return the display-oriented 3D shape view.

plot_summary(**kwargs)[source]

Plot the matrix as side-by-side spectrograms and percentile summaries.