Frequency Series

Note

Page role: Secondary API category

Stability: Stable

Overview

Note

Learning path: Use this page after the basic FrequencySeries tutorial or when a fitting/spectral workflow sends you back to the exact API surface.

See also

Tutorials (Feature-Oriented Learning)

Tutorial hub for feature-first learning paths.

FrequencySeries: Basics

Basic FrequencySeries walkthrough before API lookup.

Physics Models and Analysis Theory

Background on frequency-domain modeling and spectral interpretation.

FFT Specifications and Conventions

Fourier normalization and axis conventions used by GWexpy.

Spectral Estimation

PSD / ASD estimation helpers that commonly produce or consume FrequencySeries objects.

Case Study: Bootstrap PSD and GLS Fitting

Frequency-domain fitting workflow that maps back to this API.

Reference Topics

Theory/concept landing for validation assumptions and convention-heavy questions.

FrequencySeries(data[, unit, f0, df, ...])

A data array holding some metadata to represent a frequency series.

FrequencySeries Class

class gwexpy.frequencyseries.FrequencySeries(data: ArrayLike1D, unit: UnitLike = None, f0: u.Quantity | float | None = None, df: u.Quantity | float | None = None, frequencies: ArrayLike1D | None = None, name: str | None = None, epoch: SupportsToGps | None = None, channel: Channel | str | None = None, **kwargs: Any)[source]

Bases: PlotMixin, SignalAnalysisMixin, RegularityMixin, FittingMixin, StatisticalMethodsMixin, FrequencySeries

A data array holding some metadata to represent a frequency series.

FrequencySeries is the primary object used to represent frequency-domain data in gwexpy. It extends the standard gwpy.frequencyseries.FrequencySeries by incorporating additional mixins for plotting, signal analysis, regularity checks, numerical fitting, and statistical methods.

Parameters:
  • data (array-like) – Input data array.

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

  • f0 (float, ~astropy.units.Quantity, optional, default: 0) – Starting frequency for these data.

  • df (float, ~astropy.units.Quantity, optional, default: 1) – Frequency resolution for these data.

  • frequencies (array-like) – The complete array of frequencies indexing the data. This argument takes precedence over f0 and df so should be given in place of these if relevant, not alongside.

  • epoch (~gwpy.time.LIGOTimeGPS, float, str, optional) – GPS epoch associated with these data, any input parsable by ~gwpy.time.to_gps is fine.

  • name (str, optional) – Descriptive title for this array.

  • channel (~gwpy.detector.Channel, str, optional) – Source data stream for these data.

  • dtype (~numpy.dtype, optional) – Input data type.

  • copy (bool, optional, default: False) – Choose to copy the input data to new memory.

  • subok (bool, optional, default: True) – Allow passing of sub-classes by the array generator.

Notes

In addition to the standard GWpy functionality, this class provides advanced features such as frequency-domain differentiation/integration, histogramming, and seamless interoperability with Polars, Pandas, and ROOT (TGraph/TH1).

Key methods:

plot(**kwargs)

Plot this object using gwexpy.plot.Plot.

ifft(*[, mode, trim, original_n, pad_left, ...])

Inverse FFT returning a gwexpy TimeSeries, supporting transient round-trip.

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

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

differentiate([order])

Differentiate the FrequencySeries in the frequency domain.

integrate([order])

Integrate the FrequencySeries in the frequency domain.

to_db([ref, amplitude])

Convert this series to decibels.

Examples

>>> from gwexpy.frequencyseries import FrequencySeries
>>> import numpy as np
>>> data = np.ones(10)
>>> fs = FrequencySeries(data, df=1.0, f0=0.0, unit='V/Hz')
>>> fs
<FrequencySeries([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
                 unit=Unit("V / Hz"),
                 f0=<Quantity 0. Hz>,
                 df=<Quantity 1. Hz>,
                 epoch=None,
                 name=None,
                 channel=None)>

Methods

ifft(*[, mode, trim, original_n, pad_left, ...])

Inverse FFT returning a gwexpy TimeSeries, supporting transient round-trip.

idct([type, norm, n])

Compute the Inverse Discrete Cosine Transform (IDCT).

rms([axis, keepdims, ignore_nan])

Compute the Root Mean Square (RMS) value.

abs(**kwargs)

Return the absolute value of the data in this Array.

angle([unwrap])

Calculate the phase angle of this FrequencySeries.

phase([unwrap])

Calculate the phase of this FrequencySeries.

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

Apply a filter to this FrequencySeries.

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

Read data into a FrequencySeries.

Arguments and keywords depend on the output format, see the online documentation for full details for each format, the parameters below are common to most formats.

Parameters:
  • source (str, os.PathLike, file, or list of these) –

    Source of data, any of the following:

    • Path of a single data file

    • List of data file paths

    • Path of LAL-format cache file

  • args – Other arguments are (in general) specific to the given format.

  • format (str, optional) – Source format identifier. If not given, the format will be detected if possible. See below for list of acceptable formats.

  • kwargs – Other keywords are (in general) specific to the given format.

Raises:

IndexError – If source is an empty list.

Notes

The available built-in formats are:

Format

Read

Write

Auto-identify

li

Yes

No

No

lsf

Yes

No

No

mem

Yes

No

No

orf

Yes

No

No

sdb

Yes

No

No

taffmat

Yes

No

No

wdf

Yes

No

No

win

Yes

No

No

win32

Yes

No

No

wvf

Yes

No

No

phase(unwrap: bool = False) FrequencySeries[source]

Calculate the phase of this FrequencySeries.

Parameters:

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

Returns:

The phase of the series, in radians.

Return type:

FrequencySeries

angle(unwrap: bool = False) FrequencySeries[source]

Calculate the phase angle of this FrequencySeries.

Alias for phase(unwrap=unwrap).

Parameters:

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

Returns:

The phase of the series, in radians.

Return type:

FrequencySeries

histogram(bins=None, range=None, weights=None, density=False, **kwargs)[source]

Compute a histogram of the values in this FrequencySeries.

Useful for analyzing the distribution of spectral density levels.

Parameters:
  • bins (int or sequence or str, optional) – Binning specification (passed to np.histogram).

  • range ((float, float), optional) – The lower and upper range of the bins.

  • weights (array_like, optional) – Weights for each sample.

  • density (bool, optional) – If True, return a probability density histogram.

  • **kwargs – Additional arguments passed to np.histogram.

Returns:

A gwexpy.histogram.Histogram object.

Return type:

Histogram

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

Calculate the phase of this FrequencySeries in degrees.

Parameters:

unwrap (bool, optional) – If True, unwrap the phase before converting to degrees.

Returns:

The phase of the series, in degrees.

Return type:

FrequencySeries

differentiate(order: int = 1) FrequencySeries[source]

Differentiate the FrequencySeries in the frequency domain.

Multiplies by (i * 2 * pi * f)^order.

Parameters:

order (int, optional) – Order of differentiation. Default is 1.

Returns:

The differentiated series.

Return type:

FrequencySeries

integrate(order: int = 1) FrequencySeries[source]

Integrate the FrequencySeries in the frequency domain.

Divides by (i * 2 * pi * f)^order.

Parameters:

order (int, optional) – Order of integration. Default is 1.

Returns:

The integrated series.

Return type:

FrequencySeries

to_db(ref: Any = 1.0, amplitude: bool = True) FrequencySeries[source]

Convert this series to decibels.

Parameters:
  • ref (float or Quantity, optional) – Reference value for 0 dB. Default is 1.0.

  • amplitude (bool, optional) – If True (default), treat data as amplitude (20 * log10). If False, treat data as power (10 * log10).

Returns:

The series in dB.

Return type:

FrequencySeries

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

Apply a [b, a] filter to this FrequencySeries.

Inherited from gwpy.

to_pandas(index: Literal['frequency'] = 'frequency', *, name: str | None = None, copy: bool = False) Any[source]

Convert to pandas.Series.

classmethod from_pandas(series: Any, **kwargs: Any) Any[source]

Create FrequencySeries from pandas.Series.

to_polars(name: str | None = None, as_dataframe: bool = True, frequencies: str = 'frequency') Any[source]

Convert this series to a polars.DataFrame or polars.Series.

Parameters:
  • name (str, optional) – Name for the polars Series/Column.

  • as_dataframe (bool, default True) – If True, returns a DataFrame with a ‘frequency’ column. If False, returns a raw Series of values.

  • frequencies (str, default "frequency") – Name of the frequency column (only if as_dataframe=True).

Return type:

polars.DataFrame or polars.Series

classmethod from_polars(data: Any, frequencies: str | None = 'frequency', **kwargs: Any) Any[source]

Create a FrequencySeries from a polars.DataFrame or polars.Series.

Parameters:
  • data (polars.DataFrame or polars.Series) – Input data.

  • frequencies (str, optional) – If data is a DataFrame, name of the column to use as frequency.

  • **kwargs – Additional arguments passed to frequency series constructor.

Return type:

FrequencySeries

to_tgraph(error: Any | None = None) Any[source]

Convert to ROOT TGraph or TGraphErrors.

to_th1d(error: Any | None = None) Any[source]

Convert to ROOT TH1D.

classmethod from_root(obj: Any, return_error: bool = False, **kwargs: Any) Any[source]

Create FrequencySeries from ROOT TGraph or TH1.

to_xarray(freq_coord: Literal['Hz'] = 'Hz') Any[source]

Convert to xarray.DataArray.

classmethod from_xarray(da: Any, **kwargs: Any) Any[source]

Create FrequencySeries from xarray.DataArray.

to_hdf5_dataset(group: Any, path: str, *, overwrite: bool = False, compression: str | None = None, compression_opts: Any = None) Any[source]

Write to HDF5 dataset within a group.

classmethod from_hdf5_dataset(group: Any, path: str) Any[source]

Read FrequencySeries from HDF5 dataset.

ifft(*, mode: str = 'auto', trim: bool = True, original_n: int | None = None, pad_left: int | None = None, pad_right: int | None = None, **kwargs: Any) Any[source]

Inverse FFT returning a gwexpy TimeSeries, supporting transient round-trip.

Parameters:
  • mode ({"auto", "gwpy", "transient"}) – auto: use transient restoration if _gwex_fft_mode==”transient” is detected, otherwise GWpy compatible.

  • trim (bool) – Whether to remove padding and trim to original length during transient mode.

  • original_n (int, optional) – Explicitly specify the length after restoration (takes priority).

  • pad_right (int, optional) – Specify padding lengths for transient mode to override defaults.

  • pad_left (int, optional) – Specify padding lengths for transient mode to override defaults.

  • **kwargs (Any) – Additional arguments passed to parent ifft.

idct(type: int = 2, norm: str = 'ortho', *, n: int | None = None) Any[source]

Compute the Inverse Discrete Cosine Transform (IDCT).

Reconstructs a time-domain signal from DCT coefficients.

Parameters:
  • type (int, optional) – DCT type (1, 2, 3, or 4). Should match the type used for the forward DCT. Default is 2.

  • norm (str, optional) – Normalization mode: ‘ortho’ for orthonormal, None for standard. Default is ‘ortho’.

  • n (int, optional) – Length of the output time series. If None, uses the stored original_n attribute if available.

Returns:

The reconstructed time series.

Return type:

TimeSeries

Notes

For a proper roundtrip, use the same type and norm as the forward DCT transform.

Examples

>>> from gwexpy.frequencyseries import FrequencySeries
>>> import numpy as np
>>> fs = FrequencySeries(np.ones(10), df=1.0)
>>> ts = fs.idct(n=10)
differentiate_time() Any[source]

Apply time differentiation in frequency domain.

Multiplies by (2 * pi * i * f). Converting Displacement -> Velocity -> Acceleration.

Return type:

FrequencySeries

integrate_time() Any[source]

Apply time integration in frequency domain.

Divides by (2 * pi * i * f). Converting Acceleration -> Velocity -> Displacement.

Return type:

FrequencySeries

quadrature_sum(other: Any) Any[source]

Compute sqrt(self^2 + other^2) assuming checking independence.

Operates on magnitude. Phase information is lost (returns real).

Parameters:

other (FrequencySeries) – The other series to add.

Returns:

Magnitude combined series.

Return type:

FrequencySeries

group_delay() Any[source]

Calculate the group delay of the series.

Group delay is defined as -d(phase)/d(omega), where omega = 2 * pi * f. It represents the time delay of the envelope of a signal at a given frequency.

Returns:

A new FrequencySeries representing the group delay in seconds.

Return type:

FrequencySeries

rebin(width: float | Quantity) FrequencySeries[source]

Rebin the FrequencySeries to a new resolution.

Parameters:

width (float or Quantity) – New bin width in Hz.

Returns:

The rebinned series.

Return type:

FrequencySeries

to_control_frd(frequency_unit: Literal['rad/s', 'Hz'] = 'Hz') Any[source]

Convert to control.FRD.

classmethod from_control_frd(frd: Any, *, frequency_unit: Literal['Hz', 'rad/s'] = 'Hz') Any[source]

Create from control.FRD.

classmethod from_finesse_frequency_response(sol: Any, *, output: Any | None = None, input_dof: Any | None = None, unit: Any | None = None) Any[source]

Create from finesse FrequencyResponseSolution.

Parameters:
  • sol (finesse.analysis.actions.lti.FrequencyResponseSolution) – The frequency response solution from a Finesse 3 simulation.

  • output (str or object, optional) – Output DOF name. Combined with input_dof to select one transfer function.

  • input_dof (str or object, optional) – Input DOF name.

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

Return type:

FrequencySeries or FrequencySeriesMatrix

classmethod from_finesse_noise(sol: Any, *, output: Any | None = None, noise: str | None = None, unit: Any | None = None) Any[source]

Create from finesse NoiseProjectionSolution.

Parameters:
  • sol (finesse.analysis.actions.noise.NoiseProjectionSolution) – The noise projection solution from a Finesse 3 simulation.

  • output (str or object, optional) – Output node name.

  • noise (str, optional) – Specific noise source name.

  • unit (str or astropy.units.Unit, optional) – Unit to assign to the data (e.g., "m/sqrt(Hz)").

Return type:

FrequencySeries or FrequencySeriesDict

classmethod from_pyspice_ac(analysis: Any, *, node: str | None = None, branch: str | None = None, unit: Any | None = None) Any[source]

Create from a PySpice AcAnalysis.

Parameters:
  • analysis (PySpice.Spice.Simulation.AcAnalysis) – The AC analysis result from a PySpice simulation.

  • node (str, optional) – Node name to extract. If None and branch is also None, all signals are returned as a FrequencySeriesDict.

  • branch (str, optional) – Branch name to extract.

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

Return type:

FrequencySeries or FrequencySeriesDict

classmethod from_pyspice_noise(analysis: Any, *, node: str | None = None, unit: Any | None = None) Any[source]

Create from a PySpice NoiseAnalysis.

Parameters:
  • analysis (PySpice.Spice.Simulation.NoiseAnalysis) – The noise analysis result from a PySpice simulation.

  • node (str, optional) – Node name to extract (e.g. "onoise"). If None, all signals are returned as a FrequencySeriesDict.

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

Return type:

FrequencySeries or FrequencySeriesDict

classmethod from_pyspice_distortion(analysis: Any, *, node: str | None = None, unit: Any | None = None) Any[source]

Create from a PySpice DistortionAnalysis.

Parameters:
  • analysis (PySpice.Spice.Simulation.DistortionAnalysis) – The distortion analysis result from a PySpice simulation.

  • node (str, optional) – Node name to extract. If None, all signals are returned as a FrequencySeriesDict.

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

Return type:

FrequencySeries or FrequencySeriesDict

classmethod from_skrf_network(ntwk: Any, *, parameter: str = 's', port_pair: tuple[int, int] | None = None, unit: Any | None = None) Any[source]

Create from a scikit-rf Network.

Parameters:
  • ntwk (skrf.Network) – The scikit-rf Network object.

  • parameter (str, default "s") – Which network parameter to extract ("s", "z", "y", "a", "t", or "h").

  • port_pair (tuple[int, int], optional) – Zero-based (row, col) port indices. If None, 1-port networks return a FrequencySeries and multi-port networks return a FrequencySeriesMatrix.

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

Return type:

FrequencySeries or FrequencySeriesMatrix

to_skrf_network(*, parameter: str = 's', z0: float = 50.0, port_names: list[str] | None = None, name: str | None = None) Any[source]

Convert to a scikit-rf Network.

Parameters:
  • parameter (str, default "s") – Network parameter the data represents.

  • z0 (float, default 50.0) – Reference impedance in Ohms.

  • port_names (list[str], optional) – Names for each port.

  • name (str, optional) – Name for the resulting Network.

Return type:

skrf.Network

to_torch(device: str | None = None, dtype: Any = None, requires_grad: bool = False, copy: bool = False) Any[source]

Convert to torch.Tensor.

Parameters:
  • device (str or torch.device, optional) – Target device (e.g. ‘cpu’, ‘cuda’).

  • dtype (torch.dtype, optional) – Target data type. Defaults to preserving complex64/128 or float32/64.

  • requires_grad (bool, optional) – If True, enable gradient tracking.

  • copy (bool, optional) – If True, force a copy of the data.

Return type:

torch.Tensor

classmethod from_torch(tensor: Any, frequencies: Any, unit: Any | None = None) Any[source]

Create FrequencySeries from torch.Tensor.

Parameters:
  • tensor (torch.Tensor) – Input tensor.

  • frequencies (Array or Quantity) – Frequency array matching the tensor size.

  • unit (Unit or str, optional) – Data unit.

Return type:

FrequencySeries

to_tensorflow(dtype: Any = None) Any[source]

Convert to tensorflow.Tensor.

Return type:

tensorflow.Tensor

classmethod from_tensorflow(tensor: Any, frequencies: Any, unit: Any | None = None) Any[source]

Create FrequencySeries from tensorflow.Tensor.

to_jax(dtype: Any = None) Any[source]

Convert to JAX array.

Return type:

jax.Array

classmethod from_jax(array: Any, frequencies: Any, unit: Any | None = None) Any[source]

Create FrequencySeries from JAX array.

to_cupy(dtype: Any = None) Any[source]

Convert to CuPy array.

Return type:

cupy.ndarray

classmethod from_cupy(array: Any, frequencies: Any, unit: Any | None = None) Any[source]

Create FrequencySeries from CuPy array.

to_quantities(units: str | None = None) Any[source]

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

Parameters:

units (str or quantities.UnitQuantity, optional) – Target units.

Return type:

quantities.Quantity

classmethod from_quantities(q: Any, frequencies: Any) Any[source]

Create FrequencySeries from quantities.Quantity.

Parameters:
  • q (quantities.Quantity) – Input data.

  • frequencies (array-like) – Frequencies corresponding to the data.

Return type:

FrequencySeries

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

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

Create FrequencySeries from MNE-Python Spectrum object.

Parameters:
  • spectrum (mne.time_frequency.Spectrum) – Input spectrum data.

  • **kwargs – Additional arguments passed to constructor.

Return type:

FrequencySeries or FrequencySeriesDict

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

Convert to Obspy Trace.

Parameters:

**kwargs (Any) – Additional arguments passed to ObsPy Trace constructor.

Return type:

obspy.Trace

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

Create FrequencySeries from Obspy Trace.

Parameters:
  • trace (obspy.Trace) – Input trace.

  • **kwargs – Additional arguments.

Return type:

FrequencySeries

to_simpeg(location=None, rx_type='PointElectricField', orientation='x', **kwargs) Any[source]

Convert to SimPEG Data object.

Parameters:
  • location (array_like, optional) – Rx location (x, y, z). Default is [0, 0, 0].

  • rx_type (str, optional) – Receiver class name. Default “PointElectricField”.

  • orientation (str, optional) – Receiver orientation (‘x’, ‘y’, ‘z’). Default ‘x’.

  • **kwargs (Any) – Additional arguments passed to SimPEG Data constructor.

Return type:

simpeg.data.Data

classmethod from_simpeg(data_obj: Any, **kwargs: Any) Any[source]

Create FrequencySeries from SimPEG Data object.

Parameters:
  • data_obj (simpeg.data.Data) – Input SimPEG Data.

  • **kwargs (Any) – Additional arguments passed to SimPEG converter.

Return type:

FrequencySeries

to_specutils(**kwargs)[source]

Convert to specutils.Spectrum1D.

Parameters:

**kwargs (Any) – Arguments passed to Spectrum1D constructor.

Return type:

specutils.Spectrum1D

classmethod from_specutils(spectrum, **kwargs)[source]

Create FrequencySeries from specutils.Spectrum1D.

Parameters:
  • spectrum (specutils.Spectrum1D) – Input spectrum.

  • **kwargs (Any) – Additional arguments passed to constructor.

Return type:

FrequencySeries

to_pyspeckit(**kwargs)[source]

Convert to pyspeckit.Spectrum.

Parameters:

**kwargs (Any) – Arguments passed to pyspeckit.Spectrum constructor.

Return type:

pyspeckit.Spectrum

classmethod from_pyspeckit(spectrum, **kwargs)[source]

Create FrequencySeries from pyspeckit.Spectrum.

Parameters:
  • spectrum (pyspeckit.Spectrum) – Input spectrum.

  • **kwargs (Any) – Additional arguments passed to constructor.

Return type:

FrequencySeries

DictClass

alias of FrequencySeriesDict

Module Contents

class gwexpy.frequencyseries.BifrequencyMap(data: QuantityLike, unit: UnitBase | str | None = None, x0: QuantityLike | None = None, dx: QuantityLike | None = None, xindex: QuantityLike | None = None, xunit: UnitBase | str | None = None, y0: QuantityLike | None = None, dy: QuantityLike | None = None, yindex: QuantityLike | None = None, yunit: UnitBase | str | None = None, **kwargs)[source]

Bases: Array2D

A map class with two distinct frequency axes.

BifrequencyMap represents a 2-dimensional frequency-frequency mapping, typically used for response functions, correlation matrices, or coupling kernels between different frequency bins.

Data is stored with mapping: (rows, columns) = (frequency2, frequency1).

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

  • xindex (array-like, optional) – Frequency axis 2 (rows).

  • yindex (array-like, optional) – Frequency axis 1 (columns).

  • **kwargs – Additional keyword arguments passed to the ~gwpy.types.Array2D constructor.

Notes

The propagate method allows applying this map to an input FrequencySeries to calculate the resulting output FrequencySeries via matrix-vector multiplication.

Examples

>>> from gwexpy.frequencyseries import BifrequencyMap
>>> import numpy as np
>>> data = np.eye(3)
>>> f = [10, 20, 30]
>>> bfm = BifrequencyMap.from_points(data, f, f)
>>> bfm
<BifrequencyMap([[1., 0., 0.],
                 [0., 1., 0.],
                 [0., 0., 1.]],
                unit=Unit(dimensionless),
                name=None,
                frequency2=[10.0 Hz, ..., 30.0 Hz],
                frequency1=[10.0 Hz, ..., 30.0 Hz])>
property frequency1

Frequency axis 1 (X-axis/Columns).

property frequency2

Frequency axis 2 (Y-axis/Rows).

classmethod from_points(data, f2, f1, **kwargs)[source]

Create an instance from data and two frequency axes.

Parameters:
  • data (array-like) – 2D array with shape (len(f2), len(f1)).

  • f2 (array-like) – Frequency axis 2 (Y-axis/Rows).

  • f1 (array-like) – Frequency axis 1 (X-axis/Columns).

  • **kwargs – Additional keyword arguments passed to the constructor.

propagate(input_spectrum, interpolate=True, fill_value=0)[source]

Apply the response function to an input spectrum and calculate the output spectrum.

If the frequency axis of the input spectrum differs from axis 1 (xindex) of this map, linear interpolation can be applied automatically.

Parameters:
  • input_spectrum (FrequencySeries) – The input noise spectrum.

  • interpolate (bool, optional) – If True, interpolates the input spectrum to match axis 1 of the map. If False, raises an error if the sizes do not match. Default is True.

  • fill_value (float, optional) – Value used for points outside the interpolation range. Default is 0.

Returns:

The resulting spectrum with axis 2 (frequency2).

Return type:

FrequencySeries

inverse(rcond=None) BifrequencyMap[source]

Calculate the (pseudo-)inverse of the BifrequencyMap.

Parameters:

rcond (float or None) – Cutoff for small singular values. Same as np.linalg.pinv.

Returns:

inv_map – New BifrequencyMap instance representing the inverse matrix.

Return type:

BifrequencyMap

crop(low=None, high=None, low2=None, high2=None) BifrequencyMap[source]

Crop this BifrequencyMap to a specific frequency range.

Parameters:
  • low (float, u.Quantity, optional) – Lower bound for frequency1 (X/cols).

  • high (float, u.Quantity, optional) – Upper bound for frequency1 (X/cols).

  • low2 (float, u.Quantity, optional) – Lower bound for frequency2 (Y/rows). If None, uses low.

  • high2 (float, u.Quantity, optional) – Upper bound for frequency2 (Y/rows). If None, uses high.

Returns:

cropped – The cropped map.

Return type:

BifrequencyMap

plot(method='imshow', **kwargs)[source]

Plot the data.

Parameters:
  • method (str, optional) – ‘imshow’ or ‘pcolormesh’. Default is ‘imshow’.

  • **kwargs – Keywork arguments passed to the plotting method or Plot constructor.

get_slice(at, axis='f1')[source]

Extract a 1D slice (FrequencySeries) at a specific frequency on one axis.

Parameters:
  • at (float or Quantity) – The frequency value to slice at.

  • axis (str, optional) – The axis to slice along (‘f1’ or ‘f2’). ‘f1’: Fix f1=at, return spectrum along f2. ‘f2’: Fix f2=at, return spectrum along f1. Default is ‘f1’.

Returns:

The extracted 1D spectrum.

Return type:

FrequencySeries

diagonal(method='mean', bins=None, absolute=False, **kwargs)[source]

Calculate statistics along the diagonal axis (f2 - f1).

Parameters:
  • method (str, optional) – Statistical method to use. Supported: ‘mean’, ‘median’, ‘max’, ‘min’, ‘std’, ‘rms’, ‘percentile’. Default is ‘mean’. All methods ignore NaNs in the data by default.

  • bins (int or array-like, optional) – Number of bins or bin edges for the diagonal axis. If None (default), it is automatically determined based on the resolution of frequency axes (max(df1, df2)).

  • absolute (bool, optional) – If True, calculates statistics along the absolute difference abs(f2 - f1). Default is False.

  • **kwargs – Additional arguments passed to the statistical function. For ‘percentile’, use percentile=….

Returns:

The result of the diagonal projection.

Return type:

FrequencySeries

convolute(input_spectrum, interpolate=True, fill_value=0)[source]

Convolutes the map with an input spectrum (integration along f1).

Calculates:

S_out(f2) = integral( M(f2, f1) * S_in(f1) * df1 )

This is similar to propagate, but multiplies by the frequency bin width (df) to perform an integration rather than a simple sum.

Parameters:
  • input_spectrum (FrequencySeries) – Input spectrum S_in(f1).

  • interpolate (bool, optional) – If True, interpolates input spectrum to match map’s f1 axis. Default is True.

  • fill_value (float, optional) – Fill value for interpolation. Default is 0.

Returns:

Output spectrum S_out(f2).

Return type:

FrequencySeries

plot_lines(xaxis='f1', color='f2', num_lines=None, ax=None, cmap=None, **kwargs)[source]

Plot the map as a set of lines (1D spectra).

Parameters:
  • xaxis (str, optional) – The x-axis definition for each line. - ‘f1’: Frequency 1. - ‘f2’: Frequency 2. - ‘diff’, ‘f2-f1’: Frequency 2 - Frequency 1. - ‘diff_inv’, ‘f1-f2’: Frequency 1 - Frequency 2. - ‘abs_diff’, '|f2-f1|': absolute value of (Frequency 2 - Frequency 1). Default is ‘f1’.

  • color (str, optional) – The parameter to use for coloring the lines (and defining the slices). - ‘f2’ (default): Iterate over Frequency 2 (rows). Each line is a row at fixed f2. Color is f2. - ‘f1’: Iterate over Frequency 1 (columns). Each line is a column at fixed f1. Color is f1. - ‘diff’, ‘f2-f1’: (Not fully implemented for slicing) Ideally iterate over diagonals.

  • num_lines (int, optional) – Maximum number of lines to plot. If None, plot all. Lines are subsampled uniformly if count exceeds num_lines.

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure is created.

  • cmap (str or Colormap, optional) – Colormap to use.

  • **kwargs – Additional arguments passed to LineCollection.

Returns:

The figure or axes where the plot was drawn.

Return type:

matplotlib.figure.Figure or matplotlib.axes.Axes

class gwexpy.frequencyseries.SeriesType(value)[source]

Bases: Enum

Enumeration of series types.

TIME = 'time'
FREQ = 'freq'
class gwexpy.frequencyseries.FrequencySeriesMatrix(data: ndarray | list | tuple | _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | FrequencySeriesMatrix | None = None, frequencies: XIndex | Quantity | ndarray | None = None, df: float | Quantity | None = None, f0: float | Quantity | None = None, **kwargs: Any)[source]

Bases: FrequencySeriesMatrixCoreMixin, FrequencySeriesMatrixAnalysisMixin, SeriesMatrix

A 2D matrix of FrequencySeries objects sharing a common frequency axis.

FrequencySeriesMatrix represents a 2-dimensional array (rows x columns) where each element is a FrequencySeries. All elements in the matrix must share the same frequency synchronization (same f0, df, and number of frequency bins).

This class is typically used to represent multi-channel spectral data, such as Cross-Spectral Density (CSD) matrices, coherence matrices, or multi-channel Power Spectral Densities (PSDs).

Parameters:
  • data (array-like, optional) – The data values for the matrix. Should be of shape (rows, columns, frequencies).

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

  • df (float, ~astropy.units.Quantity, optional) – The frequency resolution.

  • f0 (float, ~astropy.units.Quantity, optional) – The start frequency.

  • **kwargs – Additional keyword arguments: - channel_names: list of strings for channel labels. - unit: physical unit of the data. - name: descriptive title for the matrix.

Notes

FrequencySeriesMatrix supports element-wise spectral operations (e.g., zpk, filter, smooth) and statistical aggregations.

Key methods:

plot(**kwargs)

Plot this object using gwexpy.plot.Plot.

smooth(width[, method, ignore_nan])

Smooth the frequency series matrix along the frequency axis.

to_dict()

Convert matrix to an appropriate collection dict (e.g. TimeSeriesDict).

Examples

>>> from gwexpy.frequencyseries import FrequencySeriesMatrix
>>> import numpy as np
>>> data = np.ones((2, 2, 100))
>>> fsm = FrequencySeriesMatrix(data, df=1, unit='V/Hz')
>>> fsm
<SeriesMatrix shape=(2, 2, 100) rows=('row0', 'row1') cols=('col0', 'col1')>
series_class

alias of FrequencySeries

dict_class

alias of FrequencySeriesDict

list_class

alias of FrequencySeriesList

series_type = 'freq'
default_xunit = 'Hz'
default_yunit = None
class gwexpy.frequencyseries.FrequencySeriesBaseDict(*args: Any, **kwargs: Any)[source]

Bases: OrderedDict[str, _FS]

Ordered mapping container for FrequencySeries objects.

This is a lightweight GWpy-inspired container: - enforces EntryClass on insertion/update - provides map-style helpers (copy, crop, plot) - default values for setdefault() must be FrequencySeries (None not allowed)

Non-trivial operations (I/O, fetching, axis coercion, joins) are intentionally out-of-scope for this MVP.

EntryClass

alias of FrequencySeries

property span

Frequency extent across all elements (based on xspan).

setdefault(key: str, default: _FS | None = None) _FS[source]

Set a default entry after validating its type.

copy() FrequencySeriesBaseDict[_FS][source]

Return a deep copy of the mapping values.

crop(start: Any = None, end: Any = None, copy: bool = False) FrequencySeriesBaseDict[_FS][source]

Crop each contained series in place and return self.

plot(label: str = 'key', method: str = 'plot', figsize: Any | None = None, **kwargs: Any)[source]

Plot data.

Parameters:
  • label (str, optional) –

    labelling method, one of

    • 'key': use dictionary key (default)

    • 'name': use name attribute of each item

  • method (str, optional) – method of Plot to call, default: 'plot'

  • figsize (tuple, optional) – (width, height) tuple in inches

  • **kwargs – other keyword arguments passed to the plot method

plot_all(*args: Any, **kwargs: Any)[source]

Alias for plot(). Plots all series in the dict.

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

Read data into a FrequencySeriesDict.

Parameters:
  • source (str, file-like) – Source of data, either a file path or a file-like object.

  • *args – Arguments passed to the underlying reader.

  • **kwargs – Keyword arguments passed to the underlying reader.

Returns:

A new dict containing the data read from the source.

Return type:

FrequencySeriesDict

The available built-in formats are:

Format

Read

Write

Auto-identify

li

Yes

No

No

lsf

Yes

No

No

mem

Yes

No

No

orf

Yes

No

No

sdb

Yes

No

No

taffmat

Yes

No

No

wdf

Yes

No

No

win

Yes

No

No

win32

Yes

No

No

wvf

Yes

No

No

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

Write the mapping through the Astropy I/O registry.

class gwexpy.frequencyseries.FrequencySeriesDict(*args: Any, **kwargs: Any)[source]

Bases: DictMapMixin, FrequencySeriesBaseDict[FrequencySeries]

A dictionary of FrequencySeries, indexed by name.

FrequencySeriesDict is a specialized dictionary designed to hold and manipulate multiple FrequencySeries objects simultaneously. It provides batch processing methods (e.g., zpk, filter, smooth) that operate on all entries at once, and supports advanced I/O for multi-channel data (HDF5, Zarr, CSV).

Parameters:
  • *args – A mapping or iterable of (key, FrequencySeries) pairs.

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

Notes

This class is highly interoperable, supporting conversions to and from Pandas DataFrames and Xarray Datasets. It also supports matrix conversion via to_matrix().

Key methods:

read(source, *args, **kwargs)

Read data into a FrequencySeriesDict.

write(target, *args, **kwargs)

Write dict to file (HDF5, ROOT, etc.).

plot([label, method, figsize])

Plot data.

zpk(*args, **kwargs)

Apply ZPK filter to each FrequencySeries.

smooth(*args, **kwargs)

Smooth each FrequencySeries.

to_pandas(**kwargs)

Convert the dict to a pandas.DataFrame.

Examples

>>> from gwexpy.frequencyseries import FrequencySeries, FrequencySeriesDict
>>> fsd = FrequencySeriesDict()
>>> fsd['H1'] = FrequencySeries([1, 2], df=1)
>>> fsd
FrequencySeriesDict([('H1', <FrequencySeries([1, 2],
                 unit=Unit(dimensionless),
                 f0=<Quantity 0. Hz>,
                 df=<Quantity 1. Hz>,
                 epoch=None,
                 name=None,
                 channel=None)>)])
EntryClass

alias of FrequencySeries

crop(*args, **kwargs) FrequencySeriesDict[source]

Crop each FrequencySeries in the dict.

This is an in-place, GWpy-compatible operation that returns self.

pad(*args, **kwargs)

Pad each FrequencySeries in the dict.

interpolate(*args, **kwargs)

Interpolate each FrequencySeries in the dict.

append(*args, **kwargs) FrequencySeriesDict[source]

Append to each FrequencySeries in the dict in place.

Return self.

prepend(*args, **kwargs) FrequencySeriesDict[source]

Prepend to each FrequencySeries in the dict in place.

Return self.

zpk(*args, **kwargs)

Apply ZPK filter to each FrequencySeries.

filter(*args, **kwargs)

Apply filter to each FrequencySeries.

apply_response(*args, **kwargs)

Apply response to each FrequencySeries.

phase(*args, **kwargs)

Compute phase of each FrequencySeries.

angle(*args, **kwargs) FrequencySeriesDict[source]

Alias for phase(). Returns a new FrequencySeriesDict.

degree(*args, **kwargs)

Compute phase (in degrees) of each FrequencySeries.

to_db(*args, **kwargs)

Convert each FrequencySeries to dB.

differentiate_time(*args, **kwargs)

Apply time differentiation to each item.

integrate_time(*args, **kwargs)

Apply time integration to each item.

group_delay(*args, **kwargs)

Compute group delay of each item.

smooth(*args, **kwargs)

Smooth each FrequencySeries.

rebin(*args, **kwargs)

Rebin each FrequencySeries in the dict.

histogram(*args, **kwargs)

Compute Histogram for each FrequencySeries. Returns a HistogramDict.

ifft(*args, **kwargs)

Compute IFFT of each FrequencySeries. Returns a TimeSeriesDict.

to_control_frd(*args, **kwargs)

Convert each item to control.FRD. Returns a dict.

to_torch(*args, **kwargs)

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

to_tensorflow(*args, **kwargs)

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

to_jax(*args, **kwargs)

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

to_cupy(*args, **kwargs)

Convert each item to cupy.ndarray. Returns a dict.

to_pandas(**kwargs)[source]

Convert the dict to a pandas.DataFrame.

Keys become columns.

to_xarray()[source]

Convert the dict to an xarray.Dataset.

Keys become data variables.

to_matrix()[source]

Convert this FrequencySeriesDict to a FrequencySeriesMatrix (Nx1).

to_tmultigraph(name: str | None = None) Any[source]

Convert to ROOT TMultiGraph.

classmethod from_finesse_frequency_response(sol: Any, *, unit: Any | None = None) FrequencySeriesDict[source]

Create from finesse FrequencyResponseSolution.

Returns a dict keyed by "output -> input" for all DOF pairs.

Parameters:
  • sol (finesse.analysis.actions.lti.FrequencyResponseSolution) – The frequency response solution from a Finesse 3 simulation.

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

classmethod from_finesse_noise(sol: Any, *, output: Any | None = None, unit: Any | None = None) FrequencySeriesDict[source]

Create from finesse NoiseProjectionSolution.

Returns a dict keyed by "output: noise_source" strings.

Parameters:
  • sol (finesse.analysis.actions.noise.NoiseProjectionSolution) – The noise projection solution from a Finesse 3 simulation.

  • output (str or object, optional) – Output node name. If None, all outputs are included.

  • unit (str or astropy.units.Unit, optional) – Unit to assign to the data (e.g., "m/sqrt(Hz)").

classmethod from_pyspice_ac(analysis: Any, *, unit: Any | None = None) FrequencySeriesDict[source]

Create from a PySpice AcAnalysis.

Returns a dict keyed by signal name for all nodes and branches.

Parameters:
  • analysis (PySpice.Spice.Simulation.AcAnalysis) – The AC analysis result from a PySpice simulation.

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

classmethod from_pyspice_noise(analysis: Any, *, unit: Any | None = None) FrequencySeriesDict[source]

Create from a PySpice NoiseAnalysis.

Returns a dict keyed by signal name for all noise nodes.

Parameters:
  • analysis (PySpice.Spice.Simulation.NoiseAnalysis) – The noise analysis result from a PySpice simulation.

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

classmethod from_skrf_network(ntwk: Any, *, parameter: str = 's', unit: Any | None = None) FrequencySeriesDict[source]

Create from a scikit-rf Network.

Returns a dict keyed by port-pair labels (e.g. "S11", "S21").

Parameters:
  • ntwk (skrf.Network) – The scikit-rf Network object.

  • parameter (str, default "s") – Which network parameter to extract ("s", "z", "y", "a", "t", or "h").

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

write(target: str, *args: Any, **kwargs: Any) Any[source]

Write dict to file (HDF5, ROOT, etc.).

class gwexpy.frequencyseries.FrequencySeriesBaseList(*items: _FS | Iterable[_FS])[source]

Bases: PlotMixin, list[_FS]

List container for FrequencySeries objects with type enforcement.

EntryClass

alias of FrequencySeries

property segments

Frequency spans of each element (xspan).

append(item: _FS)[source]

Append one validated item and return self.

extend(items: Iterable[_FS]) None[source]

Extend the list with validated items.

insert(index: int, item: _FS) None[source]

Insert one validated item at the requested position.

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

Plot this collection using gwexpy Plot.

copy() FrequencySeriesBaseList[_FS][source]

Return a deep copy of the list values.

plot_all(*args: Any, **kwargs: Any)[source]

Alias for plot(). Plots all series.

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

Read data into a FrequencySeriesList.

Parameters:
  • source (str, file-like) – Source of data, either a file path or a file-like object.

  • *args – Arguments passed to the underlying reader.

  • **kwargs – Keyword arguments passed to the underlying reader.

Returns:

A new list containing the data read from the source.

Return type:

FrequencySeriesList

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

Write the list through the Astropy I/O registry.

class gwexpy.frequencyseries.FrequencySeriesList(*items: _FS | Iterable[_FS])[source]

Bases: ListMapMixin, FrequencySeriesBaseList[FrequencySeries]

A list of FrequencySeries objects.

FrequencySeriesList is a specialized list designed to hold and manipulate multiple FrequencySeries objects. It provides batch processing methods that operate on all entries at once.

Parameters:

*args – An iterable of FrequencySeries objects.

Notes

Key methods:

plot(**kwargs)

Plot this collection using gwexpy Plot.

append(item)

Append one validated item and return self.

extend(items)

Extend the list with validated items.

zpk(*args, **kwargs)

Apply ZPK filter to each FrequencySeries in the list.

smooth(*args, **kwargs)

Smooth each FrequencySeries.

Examples

>>> from gwexpy.frequencyseries import FrequencySeries, FrequencySeriesList
>>> fsl = FrequencySeriesList([FrequencySeries([1, 2], df=1)])
>>> fsl
[<FrequencySeries([1, 2],
                 unit=Unit(dimensionless),
                 f0=<Quantity 0. Hz>,
                 df=<Quantity 1. Hz>,
                 epoch=None,
                 name=None,
                 channel=None)>]
EntryClass

alias of FrequencySeries

crop(*args, **kwargs)

Crop each FrequencySeries in the list.

pad(*args, **kwargs)

Pad each FrequencySeries in the list.

interpolate(*args, **kwargs)

Interpolate each FrequencySeries in the list.

zpk(*args, **kwargs)

Apply ZPK filter to each FrequencySeries in the list.

filter(*args, **kwargs)

Apply filter to each FrequencySeries in the list.

apply_response(*args, **kwargs)

Apply response to each FrequencySeries in the list.

phase(*args, **kwargs)

Compute phase of each FrequencySeries.

angle(*args, **kwargs) FrequencySeriesList[source]

Alias for phase(). Returns a new FrequencySeriesList.

degree(*args, **kwargs)

Compute phase (in degrees) of each FrequencySeries.

to_db(*args, **kwargs)

Convert each FrequencySeries to dB.

differentiate_time(*args, **kwargs)

Apply time differentiation to each item.

integrate_time(*args, **kwargs)

Apply time integration to each item.

group_delay(*args, **kwargs)

Compute group delay of each item.

smooth(*args, **kwargs)

Smooth each FrequencySeries.

rebin(*args, **kwargs)

Rebin each FrequencySeries in the list.

histogram(*args, **kwargs)

Compute Histogram for each FrequencySeries. Returns a HistogramList.

ifft(*args, **kwargs)

Compute IFFT of each FrequencySeries. Returns a TimeSeriesList.

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

Convert each item to control.FRD.

Return a list of FRD objects.

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

Convert each item to torch.Tensor.

Return a list of tensors.

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

Convert each item to tensorflow.Tensor.

Return a list of tensors.

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

Convert each item to jax.Array.

Return a list of arrays.

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

Convert each item to cupy.ndarray.

Return a list of arrays.

to_pandas(**kwargs)[source]

Convert the list to a pandas.DataFrame.

Columns are named by channel name or index.

to_xarray()[source]

Convert the list to an xarray.DataArray.

Concatenate items along a new channel dimension.

to_tmultigraph(name: str | None = None) Any[source]

Convert to ROOT TMultiGraph.

write(target: str, *args: Any, **kwargs: Any) Any[source]

Write list to file (HDF5, ROOT, etc.).