信号処理 (Signal Processing)

安定性: 安定

フィルタリング、窓関数、Q変換、およびスペクトル推定に関するユーティリティ。

class gwexpy.signal.WhiteningModel(mean, W)[source]

Bases: object

Model resulting from whitening transformation.

Parameters:
  • mean (ndarray) – Mean of the original data.

  • W (ndarray) – Whitening matrix.

inverse_transform(X_w)[source]

Project whitened data back to original space.

Parameters:

X_w (ndarray or array-like) – Whitened data with shape (n_samples, n_components).

Returns:

X_rec – Reconstructed data.

Return type:

ndarray

gwexpy.signal.whiten(X, *, method='pca', eps=None, n_components=None, return_model=True)[source]

Whiten an array using PCA or ZCA whitening.

Parameters:
  • X (ndarray) – Input data with shape (n_samples, n_features).

  • method (str, optional) –

    Whitening method: ‘pca’ or ‘zca’. Default is ‘pca’.

    • 'pca': Principal Component Analysis whitening. Projects data onto principal components and scales to unit variance. The output may have a different orientation relative to the original feature space.

    • 'zca': Zero-phase Component Analysis whitening (also known as Mahalanobis whitening). The whitened data maintains maximum correlation with the original data while achieving decorrelation. This preserves the original axes alignment better than PCA.

  • eps (float or str or None, optional) – Small constant added to eigenvalues to avoid division by zero. If None or ‘auto’ (default), the value is determined from data variance.

  • n_components (int, optional) – Number of components to keep. If None, keep all components. For PCA, reduces dimensionality. For ZCA, reduces dimensionality but loses the channel-preserving property, and a warning is issued.

  • return_model (bool, optional) – If True, return (X_whitened, model). If False, return only X_whitened.

Returns:

  • X_whitened (ndarray) – Whitened data with shape (n_samples, n_components) or (n_samples, n_features) if n_components is None.

  • model (WhiteningModel, optional) – Model for inverse transformation (if return_model=True).

Notes

Both PCA and ZCA whitening produce data with approximately identity covariance matrix (assuming sufficient samples). The difference is in the rotation:

  • PCA: W = S^(-1/2) @ U^T where U and S are from SVD of covariance matrix.

  • ZCA: W = U @ S^(-1/2) @ U^T, which applies the inverse rotation.

The inverse_transform method uses the pseudo-inverse of the whitening matrix to project back to the original space.

class gwexpy.signal.StandardizationModel(mean, scale, axis)[source]

Bases: object

Model resulting from standardization transformation.

Parameters:
  • mean (ndarray) – Mean of the original data.

  • scale (ndarray) – Scale (std or MAD) of the original data.

  • axis (int or str) – Axis along which standardization was performed.

inverse_transform(X_std)[source]

Undo standardization: X = X_std * scale + mean.

Parameters:

X_std (ndarray or array-like) – Standardized data.

Returns:

X – Original-scale data.

Return type:

ndarray

gwexpy.signal.standardize(X, *, method='zscore', ddof=0, axis=-1, return_model=True)[source]

Standardize an array using z-score or robust standardization.

Parameters:
  • X (ndarray) – Input data.

  • method (str, optional) –

    Standardization method: ‘zscore’ or ‘robust’ (alias: ‘mad’). Default is ‘zscore’.

    • 'zscore': Uses mean and standard deviation: (X - mean) / std.

    • 'robust' or 'mad': Uses median and MAD (median absolute deviation): (X - median) / (1.4826 * MAD). The constant 1.4826 is the reciprocal of the MAD of a standard normal distribution, which ensures that the resulting scale is equivalent to the standard deviation for Gaussian data.

  • ddof (int, optional) – Delta degrees of freedom for std calculation. Default is 0.

  • axis (int, optional) – Axis along which to standardize. Default is -1.

  • return_model (bool, optional) – If True, return (X_standardized, model). If False, return only X_standardized.

Returns:

  • X_standardized (ndarray) – Standardized data.

  • model (StandardizationModel, optional) – Model for inverse transformation (if return_model=True).

Notes

NaN values are handled using nanmean/nanstd for zscore and nanmedian for robust methods, so NaN values in the input are ignored during computation but preserved in the output.

If the scale (std or MAD) is zero, a value of 1.0 is used to avoid division by zero.

gwexpy.signal.impute(values, *, method='interpolate', limit=None, times=None, max_gap=None, fill_value=nan)[source]

Impute missing values in an array.

Parameters:
  • values (ndarray) – 1D array with potential NaN values.

  • method (str, optional) – Imputation method: ‘interpolate’, ‘ffill’, ‘bfill’, ‘mean’, ‘median’. Default is ‘interpolate’.

  • limit (int, optional) – Maximum number of consecutive NaNs to fill. For ‘ffill’ and ‘bfill’, limits the forward/backward propagation. For ‘interpolate’, limits the number of consecutive NaNs that will be filled; any excess NaNs are restored to NaN after interpolation.

  • times (ndarray, optional) – Time array corresponding to values. Used for time-based interpolation and max_gap calculation. Must be 1D and strictly increasing.

  • max_gap (float, optional) – Maximum gap duration (in units of times) to fill. After interpolation, any NaN that was within a gap larger than this threshold is restored to NaN. This post-processing ensures that large temporal gaps are not bridged by interpolation.

  • fill_value (float, optional) – Value to use for edge NaNs that cannot be interpolated or propagated. Only applies when there are no valid values to propagate from.

Returns:

imputed – Array with imputed values.

Return type:

ndarray

Notes

The max_gap parameter works as follows:

  1. First, standard interpolation is performed.

  2. Then, gaps in the original times array are identified.

  3. Any interpolated values within gaps exceeding max_gap are reverted to NaN.

This “fill then restore” approach ensures that the interpolation algorithm can be applied uniformly while still respecting gap constraints.

Similarly, limit for ‘interpolate’ method:

  1. Interpolation fills all internal NaNs.

  2. Consecutive NaN runs longer than limit have their excess positions restored to NaN (forward direction).

フィルタ設計

gwexpy.signal.filter_design.bandpass(flow: QuantityLike, fhigh: QuantityLike, sample_rate: QuantityLike, fstop: tuple[QuantityLike, QuantityLike] | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['zpk'] = 'zpk', **kwargs) ZpkType[source]
gwexpy.signal.filter_design.bandpass(flow: QuantityLike, fhigh: QuantityLike, sample_rate: QuantityLike, fstop: tuple[QuantityLike, QuantityLike] | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['ba'] = 'ba', **kwargs) BAType
gwexpy.signal.filter_design.bandpass(flow: QuantityLike, fhigh: QuantityLike, sample_rate: QuantityLike, fstop: tuple[QuantityLike, QuantityLike] | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['sos'] = 'sos', **kwargs) SosType
gwexpy.signal.filter_design.bandpass(flow: QuantityLike, fhigh: QuantityLike, sample_rate: QuantityLike, fstop: tuple[QuantityLike, QuantityLike] | None = None, gpass: float = 2, gstop: float = 30, type: Literal['fir'] = 'fir', **kwargs) TapsType

Design a band-pass filter for the given cutoff frequencies.

Parameters:
  • flow (float, ~astropy.units.Quantity) – Lower corner frequency of pass band.

  • fhigh (float, ~astropy.units.Quantity) – Upper corner frequency of pass band.

  • sample_rate (float, ~astropy.units.Quantity) – Sampling rate of target data.

  • fstop (tuple of float) – (low, high) edge-frequencies of stop band.

  • gpass (float) – The maximum loss in the passband (dB).

  • gstop (float) – The minimum attenuation in the stopband (dB).

  • type (str) – The filter type, either 'iir' or 'fir'.

  • output (str, optional, default: 'zpk') – The output format for an IIR filter, either 'zpk', 'ba', or 'sos'.

  • kwargs – Other keyword arguments are passed directly to iirdesign() or firwin().

Returns:

The formatted filter. The output format for an IIR filter depends on the input arguments, default is a tuple of (zeros, poles, gain).

Return type:

filter

Notes

By default a digital filter is returned, meaning the zeros and poles are given in the Z-domain in units of radians/sample.

Examples

To create a band-pass filter for 100-1000 Hz for 4096 Hz-sampled data:

>>> from gwpy.signal.filter_design import bandpass
>>> bp = bandpass(100, 1000, 4096)

To view the filter, you can use the ~gwpy.plot.BodePlot:

>>> from gwpy.plot import BodePlot
>>> plot = BodePlot(bp, sample_rate=4096)
>>> plot.show()
gwexpy.signal.filter_design.concatenate_zpks(*zpks: ZpkCompatible) ZpkType[source]

Concatenate a list of zero-pole-gain (ZPK) filters.

Parameters:

*zpks – One or more zero-pole-gain format, each one should be a 3-tuple containing an array of zeros, an array of poles, and a gain float.

Returns:

  • zeros (numpy.ndarray) – The concatenated array of zeros.

  • poles (numpy.ndarray) – The concatenated array of poles.

  • gain (float) – The overall gain.

Examples

Create a lowpass and a highpass filter, and combine them:

>>> from gwpy.signal.filter_design import (
...     highpass, lowpass, concatenate_zpks)
>>> hp = highpass(100, 4096)
>>> lp = lowpass(1000, 4096)
>>> zpk = concatenate_zpks(hp, lp)

Plot the filter:

>>> from gwpy.plot import BodePlot
>>> plot = BodePlot(zpk, sample_rate=4096)
>>> plot.show()
gwexpy.signal.filter_design.fir_from_transfer(transfer: Array1D, ntaps: int, window: WindowLike = 'hann', ncorner: int | None = None) NDArray[source]

Design a Type II FIR filter given an arbitrary transfer function.

Parameters:
  • transfer (numpy.ndarray) – Transfer function to start from, must have at least ten samples.

  • ntaps (int) – Number of taps in the final filter, must be an even number.

  • window (str, numpy.ndarray, optional) – Window function to truncate with, see scipy.signal.get_window for details on acceptable formats.

  • ncorner (int, optional) – Number of extra samples to zero off at low frequency.

Returns:

out – A time domain FIR filter of length ntaps.

Return type:

numpy.ndarray

Notes

The final FIR filter will use ~numpy.fft.rfft FFT normalisation.

If ncorner is not None, then ncorner extra samples will be zeroed on the left as a hard highpass filter.

See also

scipy.signal.remez

An alternative FIR filter design using the Remez exchange algorithm.

gwexpy.signal.filter_design.frequency_response(filt: FilterCompatible, frequencies: NDArray | int | None, *, analog: bool = False, sample_rate: QuantityLike = 1.0, unit: str | UnitBase = 'rad/s', normalize_gain: bool = False) tuple[numpy.ndarray[tuple[int]], numpy.ndarray[tuple[int]]][source]

Compute the frequency response of a filter at given frequencies.

Parameters:
  • filt (FilterCompatible) – Filter definition in one of the supported formats.

  • frequencies (numpy.ndarray) – Frequencies (in Hz) at which to compute the response.

  • analog (bool, optional) – Whether the filter is analogue (True) or digital (False).

  • sample_rate (astropy.units.Quantity-like, optional) – Sample rate of the digital data (only used if analog is False).

  • unit (str, optional) – For analogue ZPK filters, the units in which the zeros and poles are specified. Either 'Hz' or 'rad/s' (default).

  • normalize_gain (bool, optional) –

    Whether to normalize the gain when converting from Hz to rad/s.

    • False (default): Multiply zeros/poles by -2π but leave gain unchanged. This matches the LIGO GDS ‘f’ plane convention (plane='f' in s2z()).

    • True: Normalize gain to preserve frequency response magnitude. Gain is scaled by \(|∏p_i/∏z_i| · (2π)^{(n_p - n_z)}\). Use this when your filter was designed with the transfer function \(H(f) = k·∏(f-z_i)/∏(f-p_i)\) in Hz. This matches the LIGO GDS ‘n’ plane convention (plane='n' in s2z()).

    Only used for analogue filters in Hz (analog=True, unit="Hz").

Returns:

  • frequencies (numpy.ndarray) – Frequencies at which the response was computed. If analog=True, unit='rad/s', these are in rad/s, otherwise they are in Hz.

  • response (numpy.ndarray) – Frequency response of the filter at the given frequencies.

gwexpy.signal.filter_design.highpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: float | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['zpk'] = 'zpk', **kwargs) ZpkType[source]
gwexpy.signal.filter_design.highpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: float | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['ba'] = 'ba', **kwargs) BAType
gwexpy.signal.filter_design.highpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: float | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['sos'] = 'sos', **kwargs) SosType
gwexpy.signal.filter_design.highpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: float | None = None, gpass: float = 2, gstop: float = 30, type: Literal['fir'] = 'fir', **kwargs) TapsType

Design a high-pass filter for the given cutoff frequency.

Parameters:
  • frequency (float, ~astropy.units.Quantity) – Corner frequency of high-pass filter.

  • sample_rate (float, ~astropy.units.Quantity) – Sampling rate of target data.

  • fstop (float) – Edge-frequency of stop-band.

  • gpass (float) – The maximum loss in the passband (dB)

  • gstop (float) – The minimum attenuation in the stopband (dB).

  • type (str) – The filter type, either 'iir' or 'fir'.

  • output (str, optional, default: 'zpk') – The output format for an IIR filter, either 'zpk', 'ba', or 'sos'.

  • kwargs – Other keyword arguments are passed directly to iirdesign() or firwin().

Returns:

The formatted filter. The output format for an IIR filter depends on the input arguments, default is a tuple of (zeros, poles, gain).

Return type:

filter

Notes

By default a digital filter is returned, meaning the zeros and poles are given in the Z-domain in units of radians/sample.

Examples

To create a high-pass filter at 100 Hz for 4096 Hz-sampled data:

>>> from gwpy.signal.filter_design import highpass
>>> hp = highpass(100, 4096)

To view the filter, you can use the ~gwpy.plot.BodePlot:

>>> from gwpy.plot import BodePlot
>>> plot = BodePlot(hp, sample_rate=4096)
>>> plot.show()
gwexpy.signal.filter_design.is_sos(sos: object) bool[source]

Return True if sos looks like a SOS-format filter definition.

Returns:

issosTrue if input argument looks like a 2D-array giving second-order sections.

Return type:

bool

gwexpy.signal.filter_design.is_zpk(zpktup: object) bool[source]

Return True if zpktup looks like a ZPK-format filter definition.

Returns:

iszpkTrue if input argument looks like a 3-tuple giving arrays of zeros and poles, and a gain (float).

Return type:

bool

gwexpy.signal.filter_design.lowpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: QuantityLike | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['zpk'] = 'zpk', **kwargs) ZpkType[source]
gwexpy.signal.filter_design.lowpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: QuantityLike | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['ba'] = 'ba', **kwargs) BAType
gwexpy.signal.filter_design.lowpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: QuantityLike | None = None, gpass: float = 2, gstop: float = 30, type: Literal['iir'] = 'iir', output: Literal['sos'] = 'sos', **kwargs) SosType
gwexpy.signal.filter_design.lowpass(frequency: QuantityLike, sample_rate: QuantityLike, fstop: QuantityLike | None = None, gpass: float = 2, gstop: float = 30, type: Literal['fir'] = 'fir', **kwargs) TapsType

Design a low-pass filter for the given cutoff frequency.

Parameters:
  • frequency (float) – Corner frequency of low-pass filter (Hertz).

  • sample_rate (float) – Sampling rate of target data (Hertz).

  • fstop (float, optional) – Edge-frequency of stop-band (Hertz).

  • gpass (float, optional, default: 2) – The maximum loss in the passband (dB).

  • gstop (float, optional, default: 30) – The minimum attenuation in the stopband (dB).

  • type (str, optional, default: 'iir') – The filter type, either 'iir' or 'fir'.

  • output (str, optional, default: 'zpk') – The output format for an IIR filter, either 'zpk', 'ba', or 'sos'.

  • kwargs – Other keyword arguments are passed directly to iirdesign() or firwin().

Returns:

The formatted filter. The output format for an IIR filter depends on the input arguments, default is a tuple of (zeros, poles, gain).

Return type:

filter

Notes

By default a digital filter is returned, meaning the zeros and poles are given in the Z-domain in units of radians/sample.

Examples

To create a low-pass filter at 1000 Hz for 4096 Hz-sampled data:

>>> from gwpy.signal.filter_design import lowpass
>>> lp = lowpass(1000, 4096)

To view the filter, you can use the ~gwpy.plot.BodePlot:

>>> from gwpy.plot import BodePlot
>>> plot = BodePlot(lp, sample_rate=4096)
>>> plot.show()
gwexpy.signal.filter_design.notch(frequency: QuantityLike, sample_rate: QuantityLike, type: Literal['iir'] = 'iir', output: Literal['zpk'] = 'zpk', **kwargs) ZpkType[source]
gwexpy.signal.filter_design.notch(frequency: QuantityLike, sample_rate: QuantityLike, type: Literal['iir'] = 'iir', output: Literal['ba'] = 'ba', **kwargs) BAType
gwexpy.signal.filter_design.notch(frequency: QuantityLike, sample_rate: QuantityLike, type: Literal['iir'] = 'iir', output: Literal['sos'] = 'sos', **kwargs) SosType

Design a ZPK notch filter for the given frequency and sampling rate.

Parameters:
  • frequency (float, ~astropy.units.Quantity) – Frequency (default in Hertz) at which to apply the notch.

  • sample_rate (float, ~astropy.units.Quantity) – Number of samples per second for TimeSeries to which this notch filter will be applied.

  • type (str, optional, default: ‘iir’) – Type of filter to apply, currently only ‘iir’ is supported.

  • output (str, optional, default: ‘zpk’) – Output format for notch.

  • kwargs – Other keyword arguments to pass to scipy.signal.iirdesign.

Returns:

The formatted filter. The output format for an IIR filter depends on the input arguments, default is a tuple of (zeros, poles, gain).

Return type:

filter

See also

scipy.signal.iirdesign

For details on the IIR filter design method and the output formats.

Notes

By default a digital filter is returned, meaning the zeros and poles are given in the Z-domain in units of radians/sample.

Examples

To create a low-pass filter at 1000 Hz for 4096 Hz-sampled data:

>>> from gwpy.signal.filter_design import notch
>>> n = notch(100, 4096)

To view the filter, you can use the ~gwpy.plot.BodePlot:

>>> from gwpy.plot import BodePlot
>>> plot = BodePlot(n, sample_rate=4096)
>>> plot.show()
gwexpy.signal.filter_design.parse_filter(filt: TapsType | BAType | signal.TransferFunction) tuple[Literal['ba'], BAType][source]
gwexpy.signal.filter_design.parse_filter(filt: SosType) tuple[Literal['sos'], SosType]
gwexpy.signal.filter_design.parse_filter(filt: ZpkCompatible | LinearTimeInvariant) tuple[Literal['zpk'], ZpkType]

Parse arbitrary input args into a TF, ZPK, or SOS filter definition.

No transformations are applied to the filter, it is simply unpacked into a standard form.

Parameters:

filt (numpy.ndarray or tuple) –

Filter definition. Any of the following formats are supported:

  • FIR taps as a 1D numpy.ndarray

  • IIR transfer function as a 2-tuple of 1D numpy.ndarray

  • IIR zero-pole-gain as a 3-tuple of 1D numpy.ndarray and a float

  • IIR second-order-sections as a 2D numpy.ndarray

  • scipy.signal.lti or scipy.signal.dlti object

Returns:

  • ftype (str) – Either 'ba' 'zpk' or 'sos'.

  • filt (numpy.ndarray or tuple) – The filter components for the returned ftype. If 'ba', a 2-tuple of numerator and denominator arrays. If 'zpk', a 3-tuple of zeros, poles, and gain. If 'sos', a 2D array of second-order sections.

gwexpy.signal.filter_design.prepare_analog_filter(filt: FilterCompatible, *, unit: str | UnitBase = 'Hz', normalize_gain: bool = False) tuple[Literal['ba', 'zpk', 'sos'], BAType | ZpkType | SosType][source]

Prepare an analog filter by parsing and converting units.

This handles:

  1. Parsing filter specification

  2. Converting Hz → rad/s for ZPK filters (if unit=’Hz’)

  3. Applying gain normalization (if requested)

Does NOT:

  • Convert to digital

  • Extract gain for SOS

  • Apply prewarping

Parameters:
  • filt (filter specification) – Filter as (b, a), (z, p, k), sos array, or ~scipy.signal.lti object.

  • unit (str, optional) – For analogue ZPK filters, the units in which the zeros and poles are specified. Either 'Hz' or 'rad/s' (default).

  • normalize_gain (bool, optional) –

    Whether to normalize the gain when converting from Hz to rad/s.

    • False (default): Multiply zeros/poles by -2π but leave gain unchanged. This matches the LIGO GDS ‘f’ plane convention (plane='f' in s2z()).

    • True: Normalize gain to preserve frequency response magnitude. Gain is scaled by \(|∏p_i/∏z_i| · (2π)^{(n_p - n_z)}\). Use this when your filter was designed with the transfer function \(H(f) = k·∏(f-z_i)/∏(f-p_i)\) in Hz. This matches the LIGO GDS ‘n’ plane convention (plane='n' in s2z()).

    Ignored when unit=’rad/s’.

Returns:

  • form (str) – Filter form: 'ba', 'zpk', or 'sos'.

  • filt (tuple or numpy.ndarray) – Filter coefficients in the identified form.

See also

prepare_digital_filter

Prepare filter for digital filtering with prewarping and gain extraction.

parse_filter

Parse filter specification without unit conversion.

gwexpy.signal.filter_design.prepare_digital_filter(filt: FilterCompatible, *, analog: bool = False, sample_rate: QuantityLike = 1.0, unit: str | UnitBase = 'Hz', normalize_gain: bool = False, output: Literal['ba'] = 'zpk') BAType[source]
gwexpy.signal.filter_design.prepare_digital_filter(filt: FilterCompatible, *, analog: bool = False, sample_rate: QuantityLike = 1.0, unit: str | UnitBase = 'Hz', normalize_gain: bool = False, output: Literal['zpk'] = 'zpk') ZpkType
gwexpy.signal.filter_design.prepare_digital_filter(filt: FilterCompatible, *, analog: bool = False, sample_rate: QuantityLike = 1.0, unit: str | UnitBase = 'Hz', normalize_gain: bool = False, output: Literal['sos'] = 'zpk') SosType

Prepare a filter for digital filtering.

This function parses the input filter specification, optionally converts an analog filter to digital using prewarping + bilinear transform, and returns the filter in the requested format.

For incoming digital filters, this function basically does nothing.

Parameters:
  • filt (filter specification) –

    Filter as (b, a), (z, p, k), sos array, or ~scipy.signal.lti object.

    For digital filters (analog=False), the input filter coefficients are assumed to already be in digital form (z-domain).

    For analog filters (analog=True), the input filter coefficients should be in the units specified by unit (default: Hz).

  • analog (bool, optional) – When True, the input filter is analog and will be converted to digital using prewarping + bilinear transform (GDS method). When False (default), the input filter is already digital.

  • sample_rate (float, ~astropy.units.Quantity, optional) – Sampling frequency (Hz) of the digital system. Required when analog=True.

  • unit (str, optional) – For analogue ZPK filters, the units in which the zeros and poles are specified. Either 'Hz' or 'rad/s' (default).

  • normalize_gain (bool, optional) –

    Whether to normalize the gain when converting from Hz to rad/s.

    • False (default): Multiply zeros/poles by -2π but leave gain unchanged. This matches the LIGO GDS ‘f’ plane convention (plane='f' in s2z()).

    • True: Normalize gain to preserve frequency response magnitude. Gain is scaled by \(|∏p_i/∏z_i| · (2π)^{(n_p - n_z)}\). Use this when your filter was designed with the transfer function \(H(f) = k·∏(f-z_i)/∏(f-p_i)\) in Hz. This matches the LIGO GDS ‘n’ plane convention (plane='n' in s2z()).

    Only used for analogue filters in Hz (analog=True, unit="Hz").

  • prewarp (bool, optional) – If True, apply prewarping before bilinear transform (default). If False, skip prewarping (not recommended). Ignored when analog=False.

  • output (str, optional) –

    Desired output filter form:

    • 'zpk': zero-pole-gain tuple (default)

    • 'ba': numerator-denominator tuple

    • 'sos': second-order sections array with separated gain

Returns:

filt_out – Filter coefficients in the requested form:

  • output='ba': 2-tuple of (b, a) arrays

  • output='zpk': 3-tuple of (zeros, poles, gain)

  • output='sos': 2-tuple of (sos_array, gain)

For output='sos', the returned SOS array has unit gain in all sections, and the overall gain is returned separately. This must be applied to the filter output: filtered_data * gain.

Return type:

tuple

Raises:

ValueError – If analog=True but sample_rate is not provided.

See also

prepare_analog_filter

Prepare analog filter without digital conversion.

scipy.signal.sosfilt

Apply SOS filter to data.

Notes

Prewarping

Unlike scipy.signal.bilinear and scipy.signal.bilinear_zpk which do NOT perform prewarping, this function applies prewarping by default. Prewarping ensures the digital filter’s frequency response matches the analogue design at the pole/zero frequencies.

Examples

Prepare a digital filter from analog specification:

>>> from gwpy.signal.filter_design import prepare_digital_filter
>>> zpk = ([100], [10], 1.0)  # 100 Hz zero, 10 Hz pole, gain 1.0
>>> sos = prepare_digital_filter(
...     zpk,
...     analog=True,
...     sample_rate=4096,
...     unit='Hz',
...     output='sos',
... )

Apply to data:

>>> from scipy import signal
>>> filtered = signal.sosfilt(sos, data)

Q変換

class gwexpy.signal.qtransform.QGram(plane: QPlane, energies: list[TimeSeries], search: tuple[float, float] | None)[source]

Bases: object

Store tile energies over an irregularly gridded plane.

Parameters:
  • plane (QPlane) – The time-frequency plane over which to populate.

  • energies (list of TimeSeries) – A list of signal energies for each row of tiles.

  • search (~gwpy.segments.Segment) – Search window of interest to determine the loudest tile.

interpolate(tres: float | None | str = '<default>', fres: float | None | str = '<default>', *, logf: bool = False, outseg: Segment | None = None) Spectrogram[source]

Interpolate this QGram over a regularly-gridded spectrogram.

Parameters:
  • tres (float) – Desired time resolution (seconds) of output Spectrogram, default is abs(outseg) / 1000.

  • fres (float, int, None) – Desired frequency resolution (Hertz) of output Spectrogram, or, if logf=True, the number of frequency samples; give None to skip this step and return the original resolution, default is 0.5 Hz or 500 frequency samples.

  • logf (bool) – Boolean switch to enable (True) or disable (False) use of log-sampled frequencies in the output Spectrogram.

  • outseg (~gwpy.segments.Segment) – GPS [start, stop) segment for output Spectrogram, default is the full duration of the input.

Returns:

out – Output Spectrogram of normalised Q energy.

Return type:

~gwpy.spectrogram.Spectrogram

See also

scipy.interpolate

This method uses ~scipy.interpolate.InterpolatedUnivariateSpline to cast all frequency rows to a common time-axis, and then ~scipy.interpolate.interp2d to apply the desired frequency resolution across the band.

Notes

This method will return a Spectrogram of dtype float32 if norm is given, and float64 otherwise.

To optimize plot rendering with ~matplotlib.axes.Axes.pcolormesh, the output ~gwpy.spectrogram.Spectrogram can be given a log-sampled frequency axis by passing logf=True at runtime. The fres argument is then the number of points on the frequency axis. Note, this is incompatible with ~matplotlib.axes.Axes.imshow.

It is also highly recommended to use the outseg keyword argument when only a small window around a given GPS time is of interest.

table(snrthresh: float = 5.5) EventTable[source]

Represent this QPlane as an EventTable.

Parameters:

snrthresh (float) – Lower inclusive threshold on individual tile SNR to keep in the table, default: 5.5.

Returns:

out – A table of time-frequency tiles on this QPlane.

Return type:

~gwpy.table.EventTable

Notes

Only tiles with signal energy greater than or equal to snrthresh ** 2 / 2 will be stored in the output EventTable.

class gwexpy.signal.qtransform.QPlane(q: float, frange: tuple[float, float], duration: float, sampling: float, mismatch: float = 0.2)[source]

Bases: QBase

Iterable representation of a Q-transform plane.

For a given Q, an array of frequencies can be iterated over, yielding a QTile each time.

Parameters:
  • q (float) – The Q-value for this plane.

  • frange (tuple of float) – (low, high) range of frequencies for this plane.

  • duration (float) – The duration of the data to be Q-transformed.

  • sampling (float) – Sampling rate (in Hertz) of data to be Q-transformed.

  • mismatch (float) – Maximum fractional mismatch between neighbouring tiles.

property frequencies: NDArray[numpy.float64]

Array of central frequencies for this QPlane.

property farray: NDArray[numpy.float64]

Array of frequencies for the lower-edge of each frequency bin.

property whitening_duration: float

The recommended data duration required for whitening.

transform(fseries: FrequencySeries, *, norm: bool | str = True, epoch: float | LIGOTimeGPS | None = None, search: Segment | None = None) QGram[source]

Calculate the energy QGram for the given fseries.

Parameters:
  • fseries (~gwpy.frequencyseries.FrequencySeries) – The complex FFT of a time-series data set.

  • norm (bool, str) – Normalize the energy of the output by the median (if True or 'median') or the 'mean', if False the output is the complex ~numpy.fft.ifft output of the Q-tranform.

  • epoch (~gwpy.time.LIGOTimeGPS, float) – The epoch of these data, only used for metadata in the output TimeSeries, and not requires if the input fseries has the epoch populated.

  • search (~gwpy.segments.Segment) – Search window of interest to determine the loudest Q-plane.

Returns:

results – The complex energies of the Q-transform of the input fseries at each frequency.

Return type:

QGram

See also

QTile.transform

For details on the transform over a row of (Q, frequency) tiles.

QGram

An object with energies populated over time-frequency tiles.

class gwexpy.signal.qtransform.QTile(q: float, frequency: float, duration: float, sampling: float, mismatch: float = 0.2)[source]

Bases: QBase

Representation of a tile with fixed Q and frequency.

property bandwidth: float

The bandwidth for tiles in this row.

property ntiles: int

The number of tiles in this row.

property windowsize: int

The size of the frequency-domain window for this row.

get_window() NDArray[numpy.float64][source]

Generate the bi-square window for this row.

Returns:

window

Return type:

numpy.ndarray

get_data_indices() ndarray[tuple[int], dtype[int64]][source]

Return the index array of interesting frequencies for this row.

property padding: tuple[int, int]

The (left, right) padding required for the IFFT.

transform(fseries: FrequencySeries, *, norm: bool | str = True, epoch: float | LIGOTimeGPS | None = None) TimeSeries[source]

Calculate the energy TimeSeries for the given fseries.

Parameters:
  • fseries (~gwpy.frequencyseries.FrequencySeries) – The complex FFT of a time-series data set.

  • norm (bool, str) – Normalize the energy of the output by the median (if True or 'median') or the 'mean', if False the output is the energy (power) of the Q-tranform.

  • epoch (~gwpy.time.LIGOTimeGPS, float) – The epoch of these data, only used for metadata in the output TimeSeries, and not requires if the input fseries has the epoch populated.

Returns:

energy – A TimeSeries of the energy from the Q-transform of this tile against the data.

Return type:

~gwpy.timeseries.TimeSeries

class gwexpy.signal.qtransform.QTiling(duration: float, sampling: float, qrange: tuple[float, float] = (4, 64), frange: tuple[float, float] = (0, inf), mismatch: float = 0.2)[source]

Bases: QObject

Iterable constructor of QPlane objects.

For a given Q-range, each of the resulting QPlane objects can be iterated over.

Parameters:
  • duration (float) – The duration of the data to be Q-transformed.

  • qrange (tuple of float) – (low, high) pair of Q extrema.

  • frange (tuple of float) – (low, high) pair of frequency extrema.

  • sampling (float) – Sampling rate (in Hertz) of data to be Q-transformed.

  • mismatch (float) – Maximum fractional mismatch between neighbouring tiles.

property qs: ndarray

Array of Q values for this QTiling.

property whitening_duration: float

The recommended data duration required for whitening.

transform(fseries: FrequencySeries, **kwargs) tuple[QGram, float][source]

Compute the time-frequency plane at fixed Q with the most significant tile.

Parameters:
  • fseries (~gwpy.timeseries.FrequencySeries) – The complex FFT of a time-series data set.

  • kwargs – Other keyword arguments to pass to QPlane.transform.

Returns:

  • out (QGram) – Signal energies over the time-frequency plane containing the most significant tile.

  • far (float) – Crudely estimated false alarm rate (FAR) for the detected signal.

See also

QPlane.transform

Compute the Q-transform over a single time-frequency plane.

gwexpy.signal.qtransform.q_scan(data: TimeSeries, mismatch: float = 0.2, qrange: tuple[float, float] = (4, 64), frange: tuple[float, float] = (0, inf), duration: float | None = None, sampling: float | None = None, **kwargs) tuple[QGram, float][source]

Transform data by scanning over a QTiling.

This utility is provided mainly to allow direct manipulation of the QTiling.transform output. Most users probably just want to use q_transform(), which wraps around this.

Parameters:
  • data (~gwpy.timeseries.TimeSeries or ndarray) – The time- or frequency-domain input data.

  • mismatch (float) – Maximum allowed fractional mismatch between neighbouring tiles.

  • qrange (tuple of float) – (low, high) range of Qs to scan.

  • frange (tuple of float) – (low, high) range of frequencies to scan.

  • duration (float) – Duration (seconds) of input, required if data is not a TimeSeries.

  • sampling (float) – Sample rate (Hertz) of input, required if data is not a TimeSeries.

  • kwargs – Other keyword arguments to be passed to QTiling.transform(), including 'epoch' and 'search'

Returns:

  • qgram (QGram) – The raw output of QTiling.transform().

  • far (float) – Expected false alarm rate (Hertz) of white Gaussian noise with the same peak energy and total duration as qgram.

窓関数

gwexpy.signal.window.canonical_name(name: str) str[source]

Find the canonical name for the given window in scipy.signal.

Parameters:

name (str) – The name of the window you want.

Returns:

realname – The name of the window as implemented in scipy.signal.window.

Return type:

str

Raises:

ValueError – If name cannot be resolved to a window function in scipy.signal.

Examples

>>> from gwpy.signal.window import canonical_name
>>> canonical_name("hann")
'hann'
>>> canonical_name("ksr")
'kaiser'
gwexpy.signal.window.get_window(window: WindowLike, Nx: int, *args, **kwargs) NDArray[source]

Return a window of a given length and type.

This is a thin wrapper around scipy.signal.get_window that handles pre-computed window arrays.

Parameters:
  • window (str, float, tuple, numpy.ndarray) – The specification for the window. Anything accepted by scipy.signal.get_window or an array-like object that is already a window (for convenience).

  • Nx (int) – The size of the window. If window is an array, this size will be checked against the size of the array.

  • args – All other arguments are passed to scipy.signal.get_window.

  • kwargs – All other arguments are passed to scipy.signal.get_window.

Returns:

window – A 1-d window array with size Nx.

Return type:

numpy.ndarray

Raises:

ValueError – If an window is given an array that doesn’t have shape matching (Nx,).

See also

scipy.signal.get_window

For details of available window types and valid arguments.

gwexpy.signal.window.planck(size: int, nleft: int = 0, nright: int = 0) NDArray[source]

Return a Planck taper window.

Deprecated since version 4.0.0: This function is deprecated and will be removed in a future release. Use a different window function (e.g. ~scipy.signal.windows.tukey) or implement your own version of the Planck window if needed.

Parameters:
  • size (int) – Number of samples in the output window.

  • nleft (int) – Number of samples to taper on the left, should be less than size/2.

  • nright (int) – Number of samples to taper on the right, should be less than size/2.

Returns:

w – The window, with the maximum value normalized to 1 and at least one end tapered smoothly to 0.

Return type:

ndarray

Examples

To taper 0.1 seconds on both ends of one second of data sampled at 2048 Hz:

>>> from gwpy.signal.window import planck
>>> w = planck(2048, nleft=205, nright=205)

References

gwexpy.signal.window.recommended_overlap(name: str, nfft: int | None = None) float | int[source]

Return the recommended fractional overlap for the given window.

If nfft is given, the return is in samples.

Parameters:
  • name (str) – The name of the window you are using.

  • nfft (int) – The length of the window.

Returns:

rov – The recommended overlap (ROV) for the given window, in samples if nfft is given (int), otherwise fractional (float).

Return type:

float, int

Examples

>>> from gwpy.signal.window import recommended_overlap
>>> recommended_overlap("hann")
0.5
>>> recommended_overlap("blackmanharris", nfft=128)
85