開発版ドキュメント · 0.2.3 30c2f8ba · 入門例の検証対象 0.2.3 · 版情報 · 既知の制限

Frequency Series#

Overview#

注釈

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

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)

ベースクラス: 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.

パラメータ:
  • 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.

メモ

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([method, xscale])

Plot the data for this FrequencySeries.

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.

サンプル

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

plot(method: str = 'plot', xscale: str = 'log', **kwargs) Plot

Plot the data for this FrequencySeries.

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

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.

パラメータ:
  • 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.

例外:

IndexError -- If source is an empty list.

メモ

The available built-in formats are:

Format

Read

Write

Auto-identify

csv

Yes

Yes

Yes

hdf5

Yes

Yes

Yes

ligolw

Yes

No

No

txt

Yes

Yes

Yes

write(target, *args, **kwargs)

Write a FrequencySeries through the registered I/O handlers.

Registry-generated format documentation follows.

phase(unwrap: bool = False) FrequencySeries

Calculate the phase of this FrequencySeries.

パラメータ:

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

戻り値:

The phase of the series, in radians.

戻り値の型:

FrequencySeries

angle(unwrap: bool = False) FrequencySeries

Calculate the phase angle of this FrequencySeries.

Alias for phase(unwrap=unwrap).

パラメータ:

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

戻り値:

The phase of the series, in radians.

戻り値の型:

FrequencySeries

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

Compute a histogram of the values in this FrequencySeries.

Useful for analyzing the distribution of spectral density levels.

パラメータ:
  • 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.

戻り値:

A gwexpy.histogram.Histogram object.

戻り値の型:

Histogram

degree(unwrap: bool = False) FrequencySeries

Calculate the phase of this FrequencySeries in degrees.

パラメータ:

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

戻り値:

The phase of the series, in degrees.

戻り値の型:

FrequencySeries

differentiate(order: int = 1) FrequencySeries

Differentiate the FrequencySeries in the frequency domain.

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

パラメータ:

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

戻り値:

The differentiated series.

戻り値の型:

FrequencySeries

integrate(order: int = 1) FrequencySeries

Integrate the FrequencySeries in the frequency domain.

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

パラメータ:

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

戻り値:

The integrated series.

戻り値の型:

FrequencySeries

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

Convert this series to decibels.

パラメータ:
  • 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).

戻り値:

The series in dB.

戻り値の型:

FrequencySeries

filterba(*args, **kwargs)

Apply a legacy filter definition to this FrequencySeries.

This preserves the call shape from GWpy 3.0.14; GWpy 4 no longer provides filterba.

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

Convert to pandas.Series.

classmethod from_pandas(series: Any, **kwargs: Any) Any

Create FrequencySeries from pandas.Series.

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

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

パラメータ:
  • 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).

戻り値の型:

polars.DataFrame or polars.Series

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

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

パラメータ:
  • 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.

戻り値の型:

FrequencySeries

to_tgraph(error: Any | None = None) Any

Convert to ROOT TGraph or TGraphErrors.

to_th1d(error: Any | None = None) Any

Convert to ROOT TH1D.

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

Create FrequencySeries from ROOT TGraph or TH1.

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

Convert to xarray.DataArray.

classmethod from_xarray(da: Any, **kwargs: Any) Any

Create FrequencySeries from xarray.DataArray.

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

Write to HDF5 dataset within a group.

classmethod from_hdf5_dataset(group: Any, path: str) Any

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

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

パラメータ:
  • 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

Compute the Inverse Discrete Cosine Transform (IDCT).

Reconstructs a time-domain signal from DCT coefficients.

パラメータ:
  • 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.

戻り値:

The reconstructed time series.

戻り値の型:

TimeSeries

メモ

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

サンプル

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

Apply time differentiation in frequency domain.

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

戻り値の型:

FrequencySeries

integrate_time() Any

Apply time integration in frequency domain.

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

戻り値の型:

FrequencySeries

quadrature_sum(other: Any) Any

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

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

パラメータ:

other (FrequencySeries) -- The other series to add.

戻り値:

Magnitude combined series.

戻り値の型:

FrequencySeries

group_delay() Any

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.

戻り値:

A new FrequencySeries representing the group delay in seconds.

戻り値の型:

FrequencySeries

rebin(width: float | Quantity) FrequencySeries

Rebin the FrequencySeries to a new resolution.

パラメータ:

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

戻り値:

The rebinned series.

戻り値の型:

FrequencySeries

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

Convert to control.FRD.

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

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

Create from finesse FrequencyResponseSolution.

パラメータ:
  • 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.

戻り値の型:

FrequencySeries or FrequencySeriesMatrix

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

Create from finesse NoiseProjectionSolution.

パラメータ:
  • 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)").

戻り値の型:

FrequencySeries or FrequencySeriesDict

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

Create from a PySpice AcAnalysis.

パラメータ:
  • 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.

戻り値の型:

FrequencySeries or FrequencySeriesDict

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

Create from a PySpice NoiseAnalysis.

パラメータ:
  • 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.

戻り値の型:

FrequencySeries or FrequencySeriesDict

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

Create from a PySpice DistortionAnalysis.

パラメータ:
  • 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.

戻り値の型:

FrequencySeries or FrequencySeriesDict

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

Create from a scikit-rf Network.

パラメータ:
  • 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.

戻り値の型:

FrequencySeries or FrequencySeriesMatrix

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

Convert to a scikit-rf Network.

パラメータ:
  • 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.

戻り値の型:

skrf.Network

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

Convert to torch.Tensor.

パラメータ:
  • 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.

戻り値の型:

torch.Tensor

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

Create FrequencySeries from torch.Tensor.

パラメータ:
  • tensor (torch.Tensor) -- Input tensor.

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

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

戻り値の型:

FrequencySeries

to_tensorflow(dtype: Any = None) Any

Convert to tensorflow.Tensor.

戻り値の型:

tensorflow.Tensor

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

Create FrequencySeries from tensorflow.Tensor.

to_jax(dtype: Any = None) Any

Convert to JAX array.

戻り値の型:

jax.Array

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

Create FrequencySeries from JAX array.

to_cupy(dtype: Any = None) Any

Convert to CuPy array.

戻り値の型:

cupy.ndarray

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

Create FrequencySeries from CuPy array.

to_quantities(units: str | None = None) Any

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

パラメータ:

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

戻り値の型:

quantities.Quantity

classmethod from_quantities(q: Any, frequencies: Any) Any

Create FrequencySeries from quantities.Quantity.

パラメータ:
  • q (quantities.Quantity) -- Input data.

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

戻り値の型:

FrequencySeries

to_mne(info: Any | None = None) Any

Convert to MNE-Python object.

パラメータ:

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

戻り値の型:

mne.time_frequency.SpectrumArray

classmethod from_mne(spectrum: Any, **kwargs: Any) Any

Create FrequencySeries from MNE-Python Spectrum object.

パラメータ:
  • spectrum (mne.time_frequency.Spectrum) -- Input spectrum data.

  • **kwargs -- Additional arguments passed to constructor.

戻り値の型:

FrequencySeries or FrequencySeriesDict

to_obspy(**kwargs: Any) Any

Convert to Obspy Trace.

パラメータ:

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

戻り値の型:

obspy.Trace

classmethod from_obspy(trace: Any, **kwargs: Any) Any

Create FrequencySeries from Obspy Trace.

パラメータ:
  • trace (obspy.Trace) -- Input trace.

  • **kwargs -- Additional arguments.

戻り値の型:

FrequencySeries

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

Convert to SimPEG Data object.

パラメータ:
  • 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.

戻り値の型:

simpeg.data.Data

classmethod from_simpeg(data_obj: Any, **kwargs: Any) Any

Create FrequencySeries from SimPEG Data object.

パラメータ:
  • data_obj (simpeg.data.Data) -- Input SimPEG Data.

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

戻り値の型:

FrequencySeries

to_specutils(**kwargs)

Convert to specutils.Spectrum1D.

パラメータ:

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

戻り値の型:

specutils.Spectrum1D

classmethod from_specutils(spectrum, **kwargs)

Create FrequencySeries from specutils.Spectrum1D.

パラメータ:
  • spectrum (specutils.Spectrum1D) -- Input spectrum.

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

戻り値の型:

FrequencySeries

to_pyspeckit(**kwargs)

Convert to pyspeckit.Spectrum.

パラメータ:

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

戻り値の型:

pyspeckit.Spectrum

classmethod from_pyspeckit(spectrum, **kwargs)

Create FrequencySeries from pyspeckit.Spectrum.

パラメータ:
  • spectrum (pyspeckit.Spectrum) -- Input spectrum.

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

戻り値の型:

FrequencySeries

DictClass

FrequencySeriesDictの別名です。

T

View of the transposed array.

Same as self.transpose().

サンプル

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.T
array([[1, 3],
       [2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.T
array([1, 2, 3, 4])

参考

transpose

abs(**kwargs) Self | Quantity

Return the absolute value of the data in this Array.

参考

numpy.absolute

For details of all available positional and keyword arguments, and for details of the return value.

all(axis=None, out=None)
any(axis=None, out=None)
append(other: numpy.ndarray | Series, *, inplace: bool = True, gap: Literal['raise', 'ignore', 'pad'] | None = None, pad: float | None = None, resize: bool = True) Self

Connect another series onto this one.

パラメータ:
  • other (numpy.ndarray, Series) -- Another Series, or a simple data array to connect to this one.

  • inplace (bool, optional) --

    If True (default) perform the operation in-place, modifying current series. If False copy the data to new memory before modifying.

    警告

    inplace append bypasses the reference check in numpy.ndarray.resize, so be carefully to only use this for arrays that haven't been sharing their memory!

  • gap (str, optional) --

    Action to perform if there's a gap between the other series and this one. One of

    • 'raise' - raise a ValueError

    • 'ignore' - remove gap and join data

    • 'pad' - pad gap with zeros

    If pad is given and is not None, the default is gap='pad', otherwise gap='raise'.

    If gap='pad' is given, the default for pad is 0.

  • pad (float, optional) -- Value with which to pad discontiguous series, by default gaps will result in a ValueError.

  • resize (bool, optional) -- If True (default) resize this array to accommodate new data. If False roll the current data like a buffer to the left and insert new data at the other end.

戻り値:

series -- A new series containing joined data sets.

戻り値の型:

Series

argmax(axis=None, out=None, *, keepdims=False)
argmin(axis=None, out=None, *, keepdims=False)
argpartition(kth, axis=-1, kind='introselect', order=None)

Returns the indices that would partition this array.

Refer to numpy.argpartition for full documentation.

参考

numpy.argpartition

equivalent function

argsort(axis=-1, kind=None, order=None, *, stable=None)
astype(dtype, order='K', casting='unsafe', subok=True, copy=True)

Copy of the array, cast to a specified type.

パラメータ:
  • dtype (str or dtype) -- Typecode or data-type to which the array is cast.

  • order ({'C', 'F', 'A', 'K'}, optional) -- Controls the memory layout order of the result. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. Default is 'K'.

  • casting ({'no', 'equiv', 'safe', 'same_kind', 'same_value', 'unsafe'}, optional) --

    Controls what kind of data casting may occur. Defaults to 'unsafe' for backwards compatibility.

    • 'no' means the data types should not be cast at all.

    • 'equiv' means only byte-order changes are allowed.

    • 'safe' means only casts which can preserve values are allowed.

    • 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed.

    • 'unsafe' means any data conversions may be done.

    • 'same_value' means any data conversions may be done, but the values must not change, including rounding of floats or overflow of ints

    Added in version 2.4: Support for 'same_value' was added.

  • subok (bool, optional) -- If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.

  • copy (bool, optional) -- By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.

戻り値:

arr_t -- Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.

戻り値の型:

ndarray

例外:
  • ComplexWarning -- When casting from complex to float or int. To avoid this, one should use a.real.astype(t).

  • ValueError -- When casting using 'same_value' and the values change or would overflow

サンプル

>>> import numpy as np
>>> x = np.array([1, 2, 2.5])
>>> x
array([1. ,  2. ,  2.5])
>>> x.astype(int)
array([1, 2, 2])
>>> x.astype(int, casting="same_value")
Traceback (most recent call last):
...
ValueError: could not cast 'same_value' double to long
>>> x[:2].astype(int, casting="same_value")
array([1, 2])
base

Base object if memory is from some other object.

サンプル

The base of an array that owns its memory is None:

>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> x.base is None
True

Slicing creates a view, whose memory is shared with x:

>>> y = x[2:]
>>> y.base is x
True
byteswap(inplace=False)

Swap the bytes of the array elements

Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.

パラメータ:

inplace (bool, optional) -- If True, swap bytes in-place, default is False.

戻り値:

out -- The byteswapped array. If inplace is True, this is a view to self.

戻り値の型:

ndarray

サンプル

>>> import numpy as np
>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> list(map(hex, A))
['0x1', '0x100', '0x2233']
>>> A.byteswap(inplace=True)
array([  256,     1, 13090], dtype=int16)
>>> list(map(hex, A))
['0x100', '0x1', '0x3322']

Arrays of byte-strings are not swapped

>>> A = np.array([b'ceg', b'fac'])
>>> A.byteswap()
array([b'ceg', b'fac'], dtype='|S3')

A.view(A.dtype.newbyteorder()).byteswap() produces an array with the same values but different representation in memory

>>> A = np.array([1, 2, 3],dtype=np.int64)
>>> A.view(np.uint8)
array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
       0, 0], dtype=uint8)
>>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
array([1, 2, 3], dtype='>i8')
>>> A.view(np.uint8)
array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
       0, 3], dtype=uint8)
property cgs

Returns a copy of the current Quantity instance with CGS units. The value of the resulting object will be scaled.

property channel: Channel | None

Instrumental channel associated with these data.

check_compatible(other: list | numpy.ndarray, casting: Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe'] | None = 'safe', *, irregular_equal: bool = True) None

Check whether this Series and other are compatible.

パラメータ:
  • other (numpy.ndarray, Series) -- The array to compare to.

  • casting (str, optional) -- The type of casting to support when comparing dtypes.

  • irregular_equal (bool, optional) -- Require irregular indices to be equal (default). If irregular_equal=False and either (or both) of the series are irregular, this method just returns without doing anything.

例外:
  • ValueError -- If any metadata elements aren't compatible.

  • TypeError -- If the dtype can't be safely cast between the arrays.

choose(choices, out=None, mode='raise')
clip(min=<no value>, max=<no value>, out=None, **kwargs)

Return an array whose values are limited to [min, max]. One of max or min must be given.

Refer to numpy.clip for full documentation.

参考

numpy.clip

equivalent function

compress(condition, axis=None, out=None)

Return selected slices of this array along given axis.

Refer to numpy.compress for full documentation.

参考

numpy.compress

equivalent function

conj()

Complex-conjugate all elements.

Refer to numpy.conjugate for full documentation.

参考

numpy.conjugate

equivalent function

conjugate()

Return the complex conjugate, element-wise.

Refer to numpy.conjugate for full documentation.

参考

numpy.conjugate

equivalent function

copy(order='C')

Return a copy of the array.

パラメータ:

order ({'C', 'F', 'A', 'K'}, optional) -- Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if a is Fortran contiguous, 'C' otherwise. 'K' means match the layout of a as closely as possible. (Note that this function and numpy.copy() are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)

参考

numpy.copy

Similar function with different default behavior

numpy.copyto

メモ

This function is the preferred method for creating an array copy. The function numpy.copy() is similar, but it defaults to using order 'K', and will not pass sub-classes through by default.

サンプル

>>> import numpy as np
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
       [0, 0, 0]])
>>> y
array([[1, 2, 3],
       [4, 5, 6]])
>>> y.flags['C_CONTIGUOUS']
True

For arrays containing Python objects (e.g. dtype=object), the copy is a shallow one. The new array will contain the same object which may lead to surprises if that object can be modified (is mutable):

>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = a.copy()
>>> b[2][0] = 10
>>> a
array([1, 'm', list([10, 3, 4])], dtype=object)

To ensure all elements within an object array are copied, use copy.deepcopy:

>>> import copy
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> c = copy.deepcopy(a)
>>> c[2][0] = 10
>>> c
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)
crop(start: Quantity | float | None = None, end: Quantity | float | None = None, *, copy: bool = False) Self

Crop this series to the given x-axis extent.

パラメータ:
  • start (float, optional) -- Lower limit of x-axis to crop to, defaults to x0.

  • end (float, optional) -- Upper limit of x-axis to crop to, defaults to series end.

  • copy (bool, optional) -- Copy the input data to fresh memory, otherwise return a view (default).

戻り値:

series -- A new series with a sub-set of the input data.

戻り値の型:

Series

メモ

If either start or end are outside of the original Series span, warnings will be printed and the limits will be restricted to the xspan.

ctypes

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

This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.

パラメータ:

None

戻り値:

c -- Possessing attributes data, shape, strides, etc.

戻り値の型:

Python object

メモ

Below are the public attributes of this object which were documented in "Guide to NumPy" (we have omitted undocumented public attributes, as well as documented private attributes):

_ctypes.data

A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as: self._array_interface_['data'][0].

Note that unlike data_as, a reference won't be kept to the array: code like ctypes.c_void_p((a + b).ctypes.data) will result in a pointer to a deallocated array, and should be spelt (a + b).ctypes.data_as(ctypes.c_void_p)

_ctypes.shape

A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform (see ~numpy.ctypeslib.c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.

Type:

(c_intp*self.ndim)

_ctypes.strides

A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.

Type:

(c_intp*self.ndim)

_ctypes.data_as(obj)

Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).

The returned pointer will keep a reference to the array.

_ctypes.shape_as(obj)

Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short).

_ctypes.strides_as(obj)

Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong).

If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as_parameter attribute which will return an integer equal to the data attribute.

サンプル

>>> import numpy as np
>>> import ctypes
>>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
>>> x
array([[0, 1],
       [2, 3]], dtype=int32)
>>> x.ctypes.data
31962608 # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
<__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
c_uint(0)
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
c_ulong(4294967296)
>>> x.ctypes.shape
<numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
>>> x.ctypes.strides
<numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
cumprod(axis=None, dtype=None, out=None)

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

Refer to numpy.cumprod for full documentation.

参考

numpy.cumprod

equivalent function

cumsum(axis=None, dtype=None, out=None)

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

Refer to numpy.cumsum for full documentation.

参考

numpy.cumsum

equivalent function

data

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

decompose(bases: Collection[UnitBase] = ()) Self

Generates a new Quantity with the units decomposed. Decomposed units have only irreducible units in them (see astropy.units.UnitBase.decompose).

パラメータ:

bases (sequence of ~astropy.units.UnitBase, optional) -- The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a ~astropy.units.UnitsError if it's not possible to do so.

戻り値:

newq -- A new object equal to this quantity with units decomposed.

戻り値の型:

~astropy.units.Quantity

device
property df: Quantity

Frequency spacing of this FrequencySeries

diagonal(offset=0, axis1=0, axis2=1)

Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.

Refer to numpy.diagonal() for full documentation.

参考

numpy.diagonal

equivalent function

diff(n: int = 1, axis: int = -1) Self

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

The first order difference is given by out[n] = a[n+1] - a[n] along the given axis, higher order differences are calculated by using diff recursively.

パラメータ:
  • n (int, optional) -- The number of times values are differenced.

  • axis (int, optional) -- The axis along which the difference is taken, default is the last axis.

戻り値:

diff -- The n order differences. The shape of the output is the same as the input, except along axis where the dimension is smaller by n.

戻り値の型:

Series

参考

numpy.diff

For documentation on the underlying method.

dot(b, out=None)
dtype

Data-type of the array's elements.

警告

Setting arr.dtype is discouraged and may be deprecated in the future. Setting will replace the dtype without modifying the memory (see also ndarray.view and ndarray.astype).

パラメータ:

None

戻り値:

d

戻り値の型:

numpy dtype object

参考

ndarray.astype

Cast the values contained in the array to a new data-type.

ndarray.view

Create a view of the same data but a different data-type.

numpy.dtype

サンプル

>>> import numpy as np
>>> x = np.arange(4).reshape((2, 2))
>>> x
array([[0, 1],
       [2, 3]])
>>> x.dtype
dtype('int64')   # may vary (OS, bitness)
>>> isinstance(x.dtype, np.dtype)
True
dump(file)

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

dumps()

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

property dx: Quantity

X-axis sample separation.

ediff1d(to_end=None, to_begin=None)
property epoch: Time | None

GPS epoch associated with these data.

property equivalencies

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

property f0: Quantity

Starting frequency for this FrequencySeries

fill(value)
filter(filt: FilterCompatible, *, analog: bool = False, sample_rate: QuantityLike | None = None, unit: str = 'rad/s', normalize_gain: bool = False, inplace: bool = False) Self

Apply a filter to this FrequencySeries.

The input filter argument is designed to accept any filter created by the scipy.signal filter design functions, and operates on the conventions of that module.

パラメータ:
  • filt (numpy.ndarray or tuple) --

    The filter to be applied. This can be specified in any of the following forms, with the appropriate number of elements in the tuple:

    • numpy.ndarray - 1D array of FIR filter coefficients.

    • tuple[numpy.ndarray, numpy.ndarray] - numerator/demoinator polynomials of the transfer function.

    • numpy.ndarray - 2D array of SOS coefficients.

    • tuple[numpy.ndarray, numpy.ndarray, float] - zero-pole-gain representation.

  • analog (bool, optional) -- Type of ZPK being applied, if analog=True all parameters will be converted in the Z-domain for digital filtering via the bilinear transform.

  • sample_rate (float, ~astropy.units.Quantity, optional) -- Sample rate of data (in Hertz), used to apply a digital filter. Defaults to the last frequency value of this FrequencySeries (i.e. the Nyquist frequency).

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

  • inplace (bool, optional) -- If True, this array will be overwritten with the filtered version.

戻り値:

result -- The filtered version of the input FrequencySeries, if inplace=True was given, this is just a reference to the modified input array.

戻り値の型:

FrequencySeries

例外:

ValueError -- If filt arguments cannot be interpreted properly.

参考

FrequencySeries.zpk

For applying a zero-pole-gain filter, including in other units (e.g. poles and zeros specified in Hertz).

find_peaks(height: Any | None = None, threshold: Any | None = None, distance: Any | None = None, prominence: Any | None = None, width: Any | None = None, method: str = 'amplitude', **kwargs: Any) Any

Find peaks in the series.

Wraps scipy.signal.find_peaks with support for unit quantities.

fit(model: Any, x_range: tuple[float, float] | None = None, sigma: Any | None = None, p0: dict[str, float] | None = None, limits: dict[str, tuple[float, float]] | None = None, fixed: Iterable[str] | None = None, **kwargs: Any) Any

Fit the data to a model using iminuit.

パラメータ:
  • model (callable or str) -- The model function to fit. Can be a callable with signature f(x, p1, p2, ...) or a string name of a pre-defined model.

  • x_range (tuple of float, optional) -- The (min, max) range of the x-axis to include in the fit.

  • sigma (array-like or scalar, optional) -- The errors or weights for the data points.

  • p0 (dict, optional) -- Initial guesses for the parameter values.

  • limits (dict, optional) -- Lower and upper bounds for parameters.

  • fixed (iterable of str, optional) -- Names of parameters to keep fixed during the fit.

  • **kwargs -- Additional arguments passed to the fitting engine.

戻り値:

An object containing the fit results, including best-fit parameters, errors, and plotting methods.

戻り値の型:

FitResult

flags

Information about the memory layout of the array.

変数:
  • (C) (C_CONTIGUOUS) -- The data is in a single, C-style contiguous segment.

  • (F) (F_CONTIGUOUS) -- The data is in a single, Fortran-style contiguous segment.

  • (O) (OWNDATA) -- The array owns the memory it uses or borrows it from another object.

  • (W) (WRITEABLE) -- The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.

  • (A) (ALIGNED) -- The data and all elements are aligned appropriately for the hardware.

  • (X) (WRITEBACKIFCOPY) -- This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.

  • FNC -- F_CONTIGUOUS and not C_CONTIGUOUS.

  • FORC -- F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).

  • (B) (BEHAVED) -- ALIGNED and WRITEABLE.

  • (CA) (CARRAY) -- BEHAVED and C_CONTIGUOUS.

  • (FA) (FARRAY) -- BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.

メモ

The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using lowercased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access.

Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags.

The array flags cannot be set arbitrarily:

  • WRITEBACKIFCOPY can only be set False.

  • ALIGNED can only be set True if the data is truly aligned.

  • WRITEABLE can only be set True if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface or is a string.

Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays.

Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true.

property flat

A 1-D iterator over the Quantity array.

This returns a QuantityIterator instance, which behaves the same as the ~numpy.flatiter instance returned by ~numpy.ndarray.flat, and is similar to, but not a subclass of, Python's built-in iterator object.

flatten(order: str = 'C') Quantity

Return a copy of the array collapsed into one dimension.

Any index information is removed as part of the flattening, and the result is returned as a ~astropy.units.Quantity array.

パラメータ:

order ({'C', 'F', 'A', 'K'}) -- 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran- style) order. 'A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. 'K' means to flatten a in the order the elements occur in memory. The default is 'C'.

戻り値:

y -- A copy of the input array, flattened to one dimension.

戻り値の型:

~astropy.units.Quantity

参考

ravel

Return a flattened array.

flat

A 1-D flat iterator over the array.

サンプル

>>> a = Array([[1,2], [3,4]], unit='m', name='Test')
>>> a.flatten()
<Quantity [1., 2., 3., 4.] m>
property frequencies: Index

Series of frequencies for each sample

classmethod from_lal(lalfs: LALFrequencySeriesType, *, copy: bool = True) Self

Generate a new FrequencySeries from a LAL FrequencySeries.

Any type of LAL FrequencySeries is supported.

classmethod from_pycbc(fs: pycbc.types.TimeSeries, *, copy: bool = True) Self

Convert a pycbc.types.frequencyseries.FrequencySeries.

パラメータ:
  • fs (pycbc.types.frequencyseries.FrequencySeries) -- The input PyCBC ~pycbc.types.frequencyseries.FrequencySeries array.

  • copy (bool, optional) -- If True, copy these data to a new array.

戻り値:

spectrum -- A GWpy version of the input frequency series.

戻り値の型:

FrequencySeries

getfield(dtype, offset=0)

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

A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.

パラメータ:
  • dtype (str or dtype) -- The data type of the view. The dtype size of the view can not be larger than that of the array itself.

  • offset (int) -- Number of bytes to skip before beginning the element view.

サンプル

>>> import numpy as np
>>> x = np.diag([1.+1.j]*2)
>>> x[1, 1] = 2 + 4.j
>>> x
array([[1.+1.j,  0.+0.j],
       [0.+0.j,  2.+4.j]])
>>> x.getfield(np.float64)
array([[1.,  0.],
       [0.,  2.]])

By choosing an offset of 8 bytes we can select the complex part of the array for our view:

>>> x.getfield(np.float64, offset=8)
array([[1.,  0.],
       [0.,  4.]])
imag

The imaginary part of the array.

サンプル

>>> import numpy as np
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.imag
array([ 0.        ,  0.70710678])
>>> x.imag.dtype
dtype('float64')
info: QuantityInfoBase

Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information.

inject(other: Series, *, inplace: bool = False) Self

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

パラメータ:
  • other (Series) -- A Series whose xindex intersects with self.xindex.

  • inplace (bool, optional) -- If True (default) perform the operation in-place, modifying the current series. If False copy the data to new memory before modifying.

戻り値:

out -- The sum of self and other along their shared x-axis values.

戻り値の型:

Series

例外:

ValueError -- If self and other have incompatible units or xindex intervals.

メモ

The offset between self and other will be rounded to the nearest sample if they are not exactly aligned.

If self.xindex is an array of timestamps, and if other.xspan is not a subset of self.xspan, then other will be cropped before being adding to self.

Users may wish to taper or window their Series before passing it to this method. See TimeSeries.taper() and planck() for more information.

insert(obj, values, axis=None)

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

This is a thin wrapper around the numpy.insert function.

パラメータ:
  • obj (int, slice or sequence of int) -- Object that defines the index or indices before which values is inserted.

  • values (array-like) -- Values to insert. If the type of values is different from that of quantity, values is converted to the matching type. values should be shaped so that it can be broadcast appropriately The unit of values must be consistent with this quantity.

  • axis (int, optional) -- Axis along which to insert values. If axis is None then the quantity array is flattened before insertion.

戻り値:

out -- A copy of quantity with values inserted. Note that the insertion does not occur in-place: a new quantity array is returned.

戻り値の型:

~astropy.units.Quantity

サンプル

>>> import astropy.units as u
>>> q = [1, 2] * u.m
>>> q.insert(0, 50 * u.cm)
<Quantity [ 0.5,  1.,  2.] m>
>>> q = [[1, 2], [3, 4]] * u.m
>>> q.insert(1, [10, 20] * u.m, axis=0)
<Quantity [[  1.,  2.],
           [ 10., 20.],
           [  3.,  4.]] m>
>>> q.insert(1, 10 * u.m, axis=1)
<Quantity [[  1., 10.,  2.],
           [  3., 10.,  4.]] m>
interpolate(df: float) Self

Interpolate this FrequencySeries to a new resolution.

パラメータ:

df (float) -- Desired frequency resolution of the interpolated FrequencySeries, in Hz.

戻り値:

out -- The interpolated version of the input FrequencySeries.

戻り値の型:

FrequencySeries

参考

numpy.interp

For the underlying 1-D linear interpolation scheme.

is_compatible(other: list | ndarray) bool

Check whether this series and other have compatible metadata.

This method tests that the sample size <Series.dx>, and the ~Series.unit match.

is_contiguous(other: Series | ndarray | list, tol: float = 3.814697265625e-06) int

Check whether other is contiguous with self.

パラメータ:
  • other (Series, numpy.ndarray) -- Another series of the same type to test for contiguity.

  • tol (float, optional) -- The numerical tolerance of the test.

戻り値:

  • 1 -- If other is contiguous with this series, i.e. would attach seamlessly onto the end.

  • -1 -- If other is anti-contiguous with this seires, i.e. would attach seamlessly onto the start.

  • 0 -- If other is completely dis-contiguous with this series.

メモ

If other is an array that doesn't have index information (e.g. a numpy.ndarray), this method always returns 1.

If self *or* other` have an irregular Index array (e.g. aren't linearly sampled), this method will always return 1 if other starts after self finishes, or -1` if the inverse. If the two arrays overlap, that is bad and will raise an error.

property is_regular: bool

Return True if this series has a regular grid (constant spacing).

property isscalar

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

注釈

This is subtly different from numpy.isscalar in that numpy.isscalar returns False for a zero-dimensional array (e.g. np.array(1)), while this is True for quantities, since quantities cannot represent true numpy scalars.

item(*args)

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

Like item() except that it always returns a Quantity, not a Python scalar.

itemsize

Length of one array element in bytes.

サンプル

>>> import numpy as np
>>> x = np.array([1,2,3], dtype=np.float64)
>>> x.itemsize
8
>>> x = np.array([1,2,3], dtype=np.complex128)
>>> x.itemsize
16
kurtosis(axis=None, fisher=True, nan_policy='propagate')

Compute the kurtosis (Fisher or Pearson) of the data.

Kurtosis is a measure of the "tailedness" of the probability distribution.

パラメータ:
  • axis (int or None, optional) -- Axis along which to compute kurtosis. If None, compute over the flattened array.

  • fisher (bool, optional) -- If True, Fisher's definition is used (normal ==> 0.0). If False, Pearson's definition is used (normal ==> 3.0).

  • nan_policy (str, optional) -- How to handle NaNs: 'propagate', 'raise', or 'omit'.

戻り値:

The kurtosis value(s).

戻り値の型:

float or ndarray

mT

View of the matrix transposed array.

The matrix transpose is the transpose of the last two dimensions, even if the array is of higher dimension.

Added in version 2.0.

例外:

ValueError -- If the array is of dimension less than 2.

サンプル

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.mT
array([[1, 3],
       [2, 4]])
>>> a = np.arange(8).reshape((2, 2, 2))
>>> a
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])
>>> a.mT
array([[[0, 2],
        [1, 3]],

       [[4, 6],
        [5, 7]]])
max(axis=None, out=None, keepdims=False, initial=<no value>, where=<no value>, *, ignore_nan=False)
mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True, ignore_nan=False)
median(axis=None, **kwargs)

Compute the median.

パラメータ:
  • axis (int or None, optional) -- Axis along which to compute the median. If None, compute over the flattened array.

  • ignore_nan (bool, optional) -- If True, use numpy.nanmedian and ignore NaNs. The default is False, matching GWpy and NumPy NaN propagation.

  • **kwargs -- Passed to the GWpy implementation, or to numpy.nanmedian when ignore_nan=True.

戻り値:

The median value(s). If the object carries a unit, the result is returned with the same unit where applicable.

戻り値の型:

Any

min(axis=None, out=None, keepdims=False, initial=<no value>, where=<no value>, *, ignore_nan=False)
property name: str | None

Name for this data set.

nbytes

Total bytes consumed by the elements of the array.

メモ

Does not include memory consumed by non-element attributes of the array object.

参考

sys.getsizeof

Memory consumed by the object itself without parents in case view. This does include memory consumed by non-element attributes.

サンプル

>>> import numpy as np
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
>>> np.prod(x.shape) * x.itemsize
480
ndim

Number of array dimensions.

サンプル

>>> import numpy as np
>>> x = np.array([1, 2, 3])
>>> x.ndim
1
>>> y = np.zeros((2, 3, 4))
>>> y.ndim
3
nonzero()

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

Refer to numpy.nonzero for full documentation.

参考

numpy.nonzero

equivalent function

override_unit(unit: UnitLike, parse_strict: Literal['raise', 'warn', 'silent'] = 'raise') None

Reset the unit of these data.

Use of this method is discouraged in favour of to(), which performs accurate conversions from one unit to another. The method should really only be used when the original unit of the array is plain wrong.

パラメータ:
  • unit (~astropy.units.Unit, str) -- the unit to force onto this array

  • parse_strict (str) -- how to handle errors in the unit parsing, default is to raise the underlying exception from astropy.units

参考

gwpy.detector.units.parse_unit

For details of unit string parsing.

pad(pad_width: int | tuple[int, int], **kwargs) Self

Pad this series to a new size.

This just wraps numpy.pad and handles shifting the Index to accommodate padding on the left.

パラメータ:
  • pad_width (int, tuple[int, int]) -- Number of samples by which to pad each end of the array; given a single int to pad both ends by the same amount, or a (before, after) tuple for assymetric padding.

  • kwargs -- Other keyword arguments are passed to numpy.pad.

戻り値:

series -- The padded version of the input.

戻り値の型:

Series

参考

numpy.pad

For details on the pad function and valid keyword arguments.

partition(kth, axis=-1, kind='introselect', order=None)

Partially sorts the elements in the array in such a way that the value of the element in k-th position is in the position it would be in a sorted array. In the output array, all elements smaller than the k-th element are located to the left of this element and all equal or greater are located to its right. The ordering of the elements in the two partitions on the either side of the k-th element in the output array is undefined.

パラメータ:
  • kth (int or sequence of ints) --

    Element index to partition by. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once.

    バージョン 1.22.0 で非推奨: Passing booleans as index is deprecated.

  • axis (int, optional) -- Axis along which to sort. Default is -1, which means sort along the last axis.

  • kind ({'introselect'}, optional) -- Selection algorithm. Default is 'introselect'.

  • order (str or list of str, optional) -- When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need to be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

参考

numpy.partition

Return a partitioned copy of an array.

argpartition

Indirect partition.

sort

Full sort.

メモ

See np.partition for notes on the different algorithms.

サンプル

>>> import numpy as np
>>> a = np.array([3, 4, 2, 1])
>>> a.partition(3)
>>> a
array([2, 1, 3, 4]) # may vary
>>> a.partition((1, 3))
>>> a
array([1, 2, 3, 4])
prepend(other: QuantityLike, *, inplace: bool = True, gap: Literal['raise', 'ignore', 'pad'] | None = None, pad: float | None = None, resize: bool = True) Series

Connect another series onto the start of the current one.

パラメータ:
  • other (numpy.ndarray, Series) -- The data to prepend to this series.

  • inplace (bool, optional) --

    If True (default) perform the operation in-place, modifying current series. If False copy the data to new memory before modifying.

    警告

    inplace append bypasses the reference check in numpy.ndarray.resize, so be carefully to only use this for arrays that haven't been sharing their memory!

  • gap (str, optional) --

    Action to perform if there's a gap between the other series and this one. One of

    • 'raise' - raise a ValueError

    • 'ignore' - remove gap and join data

    • 'pad' - pad gap with zeros

    If pad is given and is not None, the default is gap='pad', otherwise gap='raise'.

    If gap='pad' is given, the default for pad is 0.

  • pad (float, optional) -- Value with which to pad discontiguous series, by default gaps will result in a ValueError.

  • resize (bool, optional) -- If True (default) resize this array to accommodate new data. If False roll the current data like a buffer to the left or right (depending on prepend) and insert new data at the other end.

戻り値:

series -- The modified series.

戻り値の型:

Series

prod(axis=None, dtype=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>)

Return the product of the array elements over the given axis

Refer to numpy.prod for full documentation.

参考

numpy.prod

equivalent function

put(indices, values, mode='raise')
ravel(order='C')

Return a flattened array.

Refer to numpy.ravel for full documentation.

参考

numpy.ravel

equivalent function

ndarray.flat

a flat iterator on the array.

real

The real part of the array.

サンプル

>>> import numpy as np
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.real
array([ 1.        ,  0.70710678])
>>> x.real.dtype
dtype('float64')

参考

numpy.real

equivalent function

repeat(repeats, axis=None)

Repeat elements of an array.

Refer to numpy.repeat for full documentation.

参考

numpy.repeat

equivalent function

reshape(shape, /, *, order='C', copy=None)
reshape(*shape, order='C', copy=None) None

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

Refer to numpy.reshape for full documentation.

参考

numpy.reshape

equivalent function

メモ

Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(4, 2) is equivalent to a.reshape((4, 2)).

resize(new_shape, /, *, refcheck=True)
resize(*new_shape, refcheck=True) None

Change shape and size of array in-place.

パラメータ:
  • new_shape (tuple of ints, or n ints) -- Shape of resized array.

  • refcheck (bool, optional) -- If False, reference count will not be checked. Default is True. See Notes below for more explanation.

戻り値の型:

None

例外:

ValueError -- If a does not own its own data or references or views to may exist.

参考

resize

Return a new array with the specified shape.

メモ

This reallocates space for the data area if necessary.

Only contiguous arrays (data elements consecutive in memory) can be resized.

Reallocating arrays in-place can often lead to memory fragmentation and should be avoided. If the goal is to reclaim over-allocated memory, alternatives are to create a view or a copy of just the desired data, or using two passes to build the array: one to cheaply determine the shape and another to allocate and fill. Benchmark your use case to determine what is optimum. You may be surprised to find resize actually slows down or bloats your application.

The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory.

On Python 3.13 and older, the check allows objects with exactly one reference to be reallocated in-place. On Python 3.14 and newer, the array must be uniquely referenced. See [1] for more details.

If you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.

参照

サンプル

Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:

>>> import numpy as np
>>> a = np.array([[0, 1], [2, 3]], order='C')
>>> a.resize((2, 1))
>>> a
array([[0],
       [1]])
>>> a = np.array([[0, 1], [2, 3]], order='F')
>>> a.resize((2, 1))
>>> a
array([[0],
       [2]])

Enlarging an array: as above, but missing entries are filled with zeros:

>>> b = np.array([[0, 1], [2, 3]])
>>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
>>> b
array([[0, 1, 2],
       [3, 0, 0]])

Referencing an array prevents resizing...

>>> c = a
>>> a.resize((1, 1))
Traceback (most recent call last):
...
ValueError: cannot resize an array that references or is referenced ...

Unless refcheck is False:

>>> a.resize((1, 1), refcheck=False)
>>> a
array([[0]])
>>> c
array([[0]])
rms(axis=None, keepdims=False, ignore_nan=True)

Compute the Root Mean Square (RMS) value.

パラメータ:
  • axis (int or None, optional) -- Axis along which to compute RMS. If None, compute over the flattened array.

  • keepdims (bool, optional) -- If True, the reduced axes are left in the result as dimensions with size one.

  • ignore_nan (bool, optional) -- If True (default), NaNs are ignored during computation.

戻り値:

The RMS value(s). Returns ~astropy.units.Quantity if the object has a unit.

戻り値の型:

Quantity or float

round(decimals=0, out=None)
searchsorted(v, *args, **kwargs)
setfield(val, dtype, offset=0)

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

Place val into a's field defined by dtype and beginning offset bytes into the field.

パラメータ:
  • val (object) -- Value to be placed in field.

  • dtype (dtype object) -- Data-type of the field in which to place val.

  • offset (int, optional) -- The number of bytes into the field at which to place val.

戻り値の型:

None

参考

getfield

サンプル

>>> import numpy as np
>>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[1.,  0.,  0.],
       [0.,  1.,  0.],
       [0.,  0.,  1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
       [3, 3, 3],
       [3, 3, 3]], dtype=int32)
>>> x
array([[1.0e+000, 1.5e-323, 1.5e-323],
       [1.5e-323, 1.0e+000, 1.5e-323],
       [1.5e-323, 1.5e-323, 1.0e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[1.,  0.,  0.],
       [0.,  1.,  0.],
       [0.,  0.,  1.]])
setflags(write=None, align=None, uic=None)

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY flag can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)

パラメータ:
  • write (bool, optional) -- Describes whether or not a can be written to.

  • align (bool, optional) -- Describes whether or not a is aligned properly for its type.

  • uic (bool, optional) -- Describes whether or not a is a copy of another "base" array.

メモ

Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only three of which can be changed by the user: WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.

WRITEABLE (W) the data area can be written to;

ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);

WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array.

All flags can be accessed using the single (upper case) letter as well as the full name.

サンプル

>>> import numpy as np
>>> y = np.array([[3, 1, 7],
...               [2, 0, 0],
...               [8, 5, 9]])
>>> y
array([[3, 1, 7],
       [2, 0, 0],
       [8, 5, 9]])
>>> y.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : False
  ALIGNED : False
  WRITEBACKIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot set WRITEBACKIFCOPY flag to True
shape

Tuple of array dimensions.

The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.

警告

Setting arr.shape is discouraged and may be deprecated in the future. Using ndarray.reshape is the preferred approach.

サンプル

>>> import numpy as np
>>> x = np.array([1, 2, 3, 4])
>>> x.shape
(4,)
>>> y = np.zeros((2, 3, 4))
>>> y.shape
(2, 3, 4)
>>> y.shape = (3, 8)
>>> y
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
>>> y.shape = (3, 6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot reshape array of size 24 into shape (3,6)
>>> np.zeros((4,2))[::2].shape = (-1,)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Incompatible shape for in-place modification. Use
`.reshape()` to make a copy with the desired shape.

参考

numpy.shape

Equivalent getter function.

numpy.reshape

Function similar to setting shape.

ndarray.reshape

Method similar to setting shape.

shift(delta: QuantityLike) None

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

This modifies the series in-place.

パラメータ:

delta (float, ~astropy.units.Quantity, str) -- The amount by which to shift (in x-axis units if float), give a negative value to shift backwards in time

サンプル

>>> from gwpy.types import Series
>>> a = Series([1, 2, 3, 4, 5], x0=0, dx=1, xunit='m')
>>> print(a.x0)
0.0 m
>>> a.shift(5)
>>> print(a.x0)
5.0 m
>>> a.shift('-1 km')
-995.0 m
property si

Returns a copy of the current Quantity instance with SI units. The value of the resulting object will be scaled.

size

Number of elements in the array.

Equal to np.prod(a.shape), i.e., the product of the array's dimensions.

メモ

a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.

サンプル

>>> import numpy as np
>>> x = np.zeros((3, 5, 2), dtype=np.complex128)
>>> x.size
30
>>> np.prod(x.shape)
30
skewness(axis=None, nan_policy='propagate')

Compute the skewness of the data.

Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean.

パラメータ:
  • axis (int or None, optional) -- Axis along which to compute skewness. If None, compute over the flattened array.

  • nan_policy (str, optional) -- How to handle NaNs: 'propagate', 'raise', or 'omit'.

戻り値:

The skewness value(s).

戻り値の型:

float or ndarray

smooth(width: Any, method: str = 'amplitude', ignore_nan: bool = True) Any

Smooth the series.

パラメータ:
  • width (int) -- Number of samples for the smoothing winow.

  • method (str, optional) -- Smoothing target: 'amplitude', 'power', 'complex', 'db'.

  • ignore_nan (bool, optional) -- If True, ignore NaNs.

戻り値:

Smoothed series.

戻り値の型:

Series

sort(axis=-1, kind=None, order=None, *, stable=None)

Sort an array in-place. Refer to numpy.sort for full documentation.

パラメータ:
  • axis (int, optional) -- Axis along which to sort. Default is -1, which means sort along the last axis.

  • kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}, optional) -- Sorting algorithm. The default is 'quicksort'. Note that both 'stable' and 'mergesort' use timsort under the covers and, in general, the actual implementation will vary with datatype. The 'mergesort' option is retained for backwards compatibility.

  • order (str or list of str, optional) -- When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

  • stable (bool, optional) --

    Sort stability. If True, the returned array will maintain the relative order of a values which compare as equal. If False or None, this is not guaranteed. Internally, this option selects kind='stable'. Default: None.

    Added in version 2.0.0.

参考

numpy.sort

Return a sorted copy of an array.

numpy.argsort

Indirect sort.

numpy.lexsort

Indirect stable sort on multiple keys.

numpy.searchsorted

Find elements in sorted array.

numpy.partition

Partial sort.

メモ

See numpy.sort for notes on the different sorting algorithms.

サンプル

>>> import numpy as np
>>> a = np.array([[1,4], [3,1]])
>>> a.sort(axis=1)
>>> a
array([[1, 4],
       [1, 3]])
>>> a.sort(axis=0)
>>> a
array([[1, 3],
       [1, 4]])

Use the order keyword to specify a field to use when sorting a structured array:

>>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
>>> a.sort(order='y')
>>> a
array([(b'c', 1), (b'a', 2)],
      dtype=[('x', 'S1'), ('y', '<i8')])
squeeze(axis=None)

Remove axes of length one from a.

Refer to numpy.squeeze for full documentation.

参考

numpy.squeeze

equivalent function

std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True, ignore_nan=False)
step(**kwargs) Plot

Create a step plot of this series.

kwargs

All keyword arguments are passed to the plot() method. of this series.

参考

plot

For details of the plotting.

strides

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

The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:

offset = sum(np.array(i) * a.strides)

A more detailed explanation of strides can be found in The N-dimensional array (ndarray).

警告

Setting arr.strides is discouraged and may be deprecated in the future. numpy.lib.stride_tricks.as_strided should be preferred to create a new view of the same data in a safer way.

メモ

Imagine an array of 32-bit integers (each 4 bytes):

x = np.array([[0, 1, 2, 3, 4],
              [5, 6, 7, 8, 9]], dtype=np.int32)

This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be (20, 4).

サンプル

>>> import numpy as np
>>> y = np.reshape(np.arange(2 * 3 * 4, dtype=np.int32), (2, 3, 4))
>>> y
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]], dtype=np.int32)
>>> y.strides
(48, 16, 4)
>>> y[1, 1, 1]
np.int32(17)
>>> offset = sum(y.strides * np.array((1, 1, 1)))
>>> offset // y.itemsize
np.int64(17)
>>> x = np.reshape(np.arange(5*6*7*8, dtype=np.int32), (5, 6, 7, 8))
>>> x = x.transpose(2, 3, 1, 0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3, 5, 2, 2], dtype=np.int32)
>>> offset = sum(i * x.strides)
>>> x[3, 5, 2, 2]
np.int32(813)
>>> offset // x.itemsize
np.int64(813)
sum(axis=None, dtype=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>)

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

Refer to numpy.sum for full documentation.

参考

numpy.sum

equivalent function

swapaxes(axis1, axis2, /)

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

Refer to numpy.swapaxes for full documentation.

参考

numpy.swapaxes

equivalent function

take(indices, axis=None, out=None, mode='raise')
to(unit, equivalencies=[], copy=True)

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

パラメータ:
  • unit (unit-like) -- An object that represents the unit to convert to. Must be an ~astropy.units.UnitBase object or a string parseable by the ~astropy.units package.

  • equivalencies (list of tuple) -- A list of equivalence pairs to try if the units are not directly convertible. See Equivalencies. If not provided or [], class default equivalencies will be used (none for ~astropy.units.Quantity, but may be set for subclasses) If None, no equivalencies will be applied at all, not even any set globally or within a context.

  • copy (bool, optional) -- If True (default), then the value is copied. Otherwise, a copy will only be made if necessary.

参考

to_value

get the numerical value in a given unit.

to_device(device, /, *, stream=None)

For Array API compatibility. Since NumPy only supports CPU arrays, this method is a no-op that returns the same array.

パラメータ:
  • device ("cpu") -- Must be "cpu".

  • stream (None, optional) -- Currently unsupported.

戻り値:

out -- Returns the same array.

戻り値の型:

Self

to_lal() LALFrequencySeriesType

Convert this FrequencySeries into a LAL FrequencySeries.

戻り値:

lalspec -- An XLAL-format FrequencySeries of a given type, e.g. REAL8FrequencySeries.

戻り値の型:

FrequencySeries

to_pycbc(*, copy: bool = True) pycbc.types.FrequencySeries

Convert this FrequencySeries into a PyCBC FrequencySeries.

パラメータ:

copy (bool, optional) -- If True, copy these data to a new array.

戻り値:

frequencyseries -- A PyCBC representation of this FrequencySeries.

戻り値の型:

pycbc.types.frequencyseries.FrequencySeries

to_string(unit=None, precision=None, format=None, subfmt=None, *, formatter=None)

Generate a string representation of the quantity and its unit.

The behavior of this function can be altered via the numpy.set_printoptions function and its various keywords. The exception to this is the threshold keyword, which is controlled via the [units.quantity] configuration item latex_array_threshold. This is treated separately because the numpy default of 1000 is too big for most browsers to handle.

パラメータ:
  • unit (unit-like, optional) -- Specifies the unit. If not provided, the unit used to initialize the quantity will be used.

  • precision (number, optional) -- The level of decimal precision. If None, or not provided, it will be determined from NumPy print options.

  • format (str, optional) --

    The format of the result. If not provided, an unadorned string is returned. Supported values are:

    • 'latex': Return a LaTeX-formatted string

    • 'latex_inline': Return a LaTeX-formatted string that uses negative exponents instead of fractions

  • formatter (str, callable, dict, optional) -- The formatter to use for the value. If a string, it should be a valid format specifier using Python's mini-language. If a callable, it will be treated as the default formatter for all values and will overwrite default Latex formatting for exponential notation and complex numbers. If a dict, it should map a specific type to a callable to be directly passed into numpy.array2string. If not provided, the default formatter will be used.

  • subfmt (str, optional) --

    Subformat of the result. For the moment, only used for format='latex' and format='latex_inline'. Supported values are:

    • 'inline': Use $ ... $ as delimiters.

    • 'display': Use $\displaystyle ... $ as delimiters.

戻り値:

A string with the contents of this Quantity

戻り値の型:

str

to_value(unit=None, equivalencies=[])

The numerical value, possibly in a different unit.

パラメータ:
  • unit (unit-like, optional) -- The unit in which the value should be given. If not given or None, use the current unit.

  • equivalencies (list of tuple, optional) -- A list of equivalence pairs to try if the units are not directly convertible (see Equivalencies). If not provided or [], class default equivalencies will be used (none for ~astropy.units.Quantity, but may be set for subclasses). If None, no equivalencies will be applied at all, not even any set globally or within a context.

戻り値:

value -- The value in the units specified. For arrays, this will be a view of the data if no unit conversion was necessary.

戻り値の型:

ndarray or scalar

参考

to

Get a new instance in a different unit.

tobytes(order='C')

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

tofile(fid, sep='', format='%s')

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

tolist()
tostring(order='C')

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

trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
transpose(*axes)

Returns a view of the array with axes transposed.

Refer to numpy.transpose for full documentation.

パラメータ:

axes (None, tuple of ints, or n ints) --

  • None or no argument: reverses the order of the axes.

  • tuple of ints: i in the j-th place in the tuple means that the array's i-th axis becomes the transposed array's j-th axis.

  • n ints: same as an n-tuple of the same ints (this form is intended simply as a "convenience" alternative to the tuple form).

戻り値:

p -- View of the array with its axes suitably permuted.

戻り値の型:

ndarray

参考

transpose

Equivalent function.

ndarray.T

Array property returning the array transposed.

ndarray.reshape

Give a new shape to an array without changing its data.

サンプル

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.transpose()
array([[1, 3],
       [2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
       [2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
       [2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.transpose()
array([1, 2, 3, 4])
property unit: UnitBase | None

The physical unit of these data.

update(other: QuantityLike, *, inplace: bool = True, gap: Literal['raise', 'ignore', 'pad'] | None = None, pad: float | None = None) Self

Update this series by appending new data like a buffer.

Old data (at the start) are dropped to maintain a fixed size.

This is a convenience method that just calls ~Series.append with resize=False.

パラメータ:
  • other (Series, numpy.ndarray) -- The data to add to the end of this Series.

  • inplace (bool) -- If True (default) modify the data in place. If False copy the data to new memory.

  • gap (str, optional) --

    Action to perform if there's a gap between the other series and this one. One of

    • 'raise' - raise a ValueError

    • 'ignore' - remove gap and join data

    • 'pad' - pad gap with zeros

    If pad is given and is not None, the default is gap='pad', otherwise gap='raise'.

    If gap='pad' is given, the default for pad is 0.

  • pad (float, optional) -- Value with which to pad discontiguous series, by default gaps will result in a ValueError.

戻り値:

series -- Either the same series (if inplace=True) or a new series (if inplace=False) with other data added to the end of this 'buffer'.

戻り値の型:

Series

参考

append

For details of the data manipulation.

property value

The numerical value of this instance.

参考

to_value

Get the numerical value in a given unit.

value_at(x: QuantityLike) Quantity

Return the value of this Series at the given xindex value.

パラメータ:

x (float, ~astropy.units.Quantity) -- The xindex value at which to search.

戻り値:

y -- The value of this Series at the given xindex value.

戻り値の型:

~astropy.units.Quantity

例外:

IndexError -- If x doesn't match an X-index value.

var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True, ignore_nan=False)
view([dtype][, type])

New view of array with the same data.

注釈

Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float64').

パラメータ:
  • dtype (data-type or ndarray sub-class, optional) -- Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter).

  • type (Python type, optional) -- Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.

メモ

a.view() is used two different ways:

a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory.

a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory.

For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the last axis of a must be contiguous. This axis will be resized in the result.

バージョン 1.23.0 で変更: Only the last axis needs to be contiguous. Previously, the entire array had to be C-contiguous.

サンプル

>>> import numpy as np
>>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])

Viewing array data using a different type and dtype:

>>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
>>> y = x.view(dtype=nonneg, type=np.recarray)
>>> x["a"]
array([-1], dtype=int8)
>>> y.a
array([255], dtype=uint8)

Creating a view on a structured array so it can be used in calculations

>>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
>>> xv = x.view(dtype=np.int8).reshape(-1,2)
>>> xv
array([[1, 2],
       [3, 4]], dtype=int8)
>>> xv.mean(0)
array([2.,  3.])

Making changes to the view changes the underlying array

>>> xv[0,1] = 20
>>> x
array([(1, 20), (3,  4)], dtype=[('a', 'i1'), ('b', 'i1')])

Using a view to convert an array to a recarray:

>>> z = x.view(np.recarray)
>>> z.a
array([1, 3], dtype=int8)

Views share data:

>>> x[0] = (9, 10)
>>> z[0]
np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])

Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.:

>>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
>>> y = x[:, ::2]
>>> y
array([[1, 3],
       [4, 6]], dtype=int16)
>>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
Traceback (most recent call last):
    ...
ValueError: To change to a dtype of a different size, the last axis must be contiguous
>>> z = y.copy()
>>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
array([[(1, 3)],
       [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])

However, views that change dtype are totally fine for arrays with a contiguous last axis, even if the rest of the axes are not C-contiguous:

>>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
>>> x.transpose(1, 0, 2).view(np.int16)
array([[[ 256,  770],
        [3340, 3854]],

       [[1284, 1798],
        [4368, 4882]],

       [[2312, 2826],
        [5396, 5910]]], dtype=int16)
property x0: Quantity

X-axis coordinate of the first data point.

property xindex: Index

Positions of the data on the x-axis.

property xspan: Segment

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

property xunit: UnitBase

Unit of x-axis index.

zip() ndarray

Zip the xindex and value arrays of this Series.

戻り値:

stacked -- The array formed by stacking the the xindex and value of this series

戻り値の型:

2-d numpy.ndarray

サンプル

>>> a = Series([0, 2, 4, 6, 8], xindex=[-5, -4, -3, -2, -1])
>>> a.zip()
array([[-5.,  0.],
       [-4.,  2.],
       [-3.,  4.],
       [-2.,  6.],
       [-1.,  8.]])
zpk(zeros: ArrayLike1D, poles: ArrayLike1D, gain: float, *, analog: bool = True, sample_rate: QuantityLike | None = None, unit: str = 'rad/s', normalize_gain: bool = False) Self

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

パラメータ:
  • zeros (array-like) -- List of zero frequencies (in Hertz).

  • poles (array-like) -- List of pole frequencies (in Hertz).

  • gain (float) -- DC gain of filter.

  • analog (bool, optional) -- Type of ZPK being applied, if analog=True all parameters will be converted in the Z-domain for digital filtering via the bilinear transform.

  • sample_rate (float, ~astropy.units.Quantity, optional) -- Sample rate of data (in Hertz), used to apply a digital filter. Defaults to the last frequency value of this FrequencySeries (i.e. the Nyquist frequency).

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

戻り値:

spectrum -- The frequency-domain filtered version of the input data.

戻り値の型:

FrequencySeries

参考

FrequencySeries.filter

For details on how a digital ZPK-format filter is applied.

サンプル

To apply a zpk filter with file poles at 100 Hz, and five zeros at 1 Hz (giving an overall DC gain of 1e-10):

>>> data2 = data.zpk([100]*5, [1]*5, 1e-10)
dt: Any

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)

ベースクラス: 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).

パラメータ:
  • 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.

メモ

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

サンプル

>>> 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])>
convolute(input_spectrum, interpolate=True, fill_value=0)

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.

パラメータ:
  • 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.

戻り値:

Output spectrum S_out(f2).

戻り値の型:

FrequencySeries

crop(start=None, end=None, *legacy_axes, copy=False, low=<object object>, high=<object object>, low2=<object object>, high2=<object object>) BifrequencyMap

Crop this map using the GWpy first-axis contract by default.

パラメータ:
  • start (float, ~astropy.units.Quantity, optional) -- Bounds on the GWpy xindex (frequency2) axis.

  • end (float, ~astropy.units.Quantity, optional) -- Bounds on the GWpy xindex (frequency2) axis.

  • *legacy_axes -- Optional low2, high2 positional bounds for the explicit legacy two-axis route.

  • copy (bool, optional) -- Copy the selected data instead of returning a view.

  • low (float, ~astropy.units.Quantity, optional) -- Backwards-compatible aliases for start and end.

  • high (float, ~astropy.units.Quantity, optional) -- Backwards-compatible aliases for start and end.

  • low2 (float, u.Quantity, optional) -- Explicitly select the legacy two-axis crop and set the lower bound for frequency2 (rows).

  • high2 (float, u.Quantity, optional) -- Explicitly select the legacy two-axis crop and set the upper bound for frequency2 (rows).

戻り値:

cropped -- The cropped map.

戻り値の型:

BifrequencyMap

diagonal(offset=0, axis1=0, axis2=1, *, method=<object object>, bins=<object object>, absolute=<object object>, **kwargs)

Return a GWpy diagonal or an explicit binned projection.

パラメータ:
  • offset (int, optional) -- Standard NumPy/GWpy diagonal selection parameters.

  • axis1 (int, optional) -- Standard NumPy/GWpy diagonal selection parameters.

  • axis2 (int, optional) -- Standard NumPy/GWpy diagonal selection parameters.

  • method (str, keyword-only, optional) -- Statistical method to use. Supported: 'mean', 'median', 'max', 'min', 'std', 'rms', 'percentile'. All methods ignore NaNs in the data by default.

  • bins (int or array-like, keyword-only, 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, keyword-only, optional) -- If True, calculates statistics along the absolute difference abs(f2 - f1).

  • **kwargs -- Additional arguments passed to the statistical function. For 'percentile', use percentile=....

戻り値:

The ordinary diagonal view, or an explicitly requested binned projection.

戻り値の型:

BifrequencyMap or FrequencySeries

property frequency1

Frequency axis 1 (X-axis/Columns).

property frequency2

Frequency axis 2 (Y-axis/Rows).

classmethod from_points(data, f2, f1, **kwargs)

Create an instance from data and two frequency axes.

パラメータ:
  • 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.

get_slice(at, axis='f1')

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

パラメータ:
  • 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'.

戻り値:

The extracted 1D spectrum.

戻り値の型:

FrequencySeries

inverse(rcond=None) BifrequencyMap

Calculate the (pseudo-)inverse of the BifrequencyMap.

パラメータ:

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

戻り値:

inv_map -- New BifrequencyMap instance representing the inverse matrix.

戻り値の型:

BifrequencyMap

plot(method='imshow', **kwargs)

Plot the data.

パラメータ:
  • method (str, optional) -- 'imshow' or 'pcolormesh'. Default is 'imshow'.

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

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

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

パラメータ:
  • 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.

戻り値:

The figure or axes where the plot was drawn.

戻り値の型:

matplotlib.figure.Figure or matplotlib.axes.Axes

propagate(input_spectrum, interpolate=True, fill_value=0)

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.

パラメータ:
  • 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.

戻り値:

The resulting spectrum with axis 2 (frequency2).

戻り値の型:

FrequencySeries

class gwexpy.frequencyseries.SeriesType(value)

ベースクラス: 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)

ベースクラス: 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).

パラメータ:
  • 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.

メモ

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

サンプル

>>> 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')>
default_xunit = 'Hz'
default_yunit = None
dict_class

FrequencySeriesDictの別名です。

list_class

FrequencySeriesListの別名です。

series_class

FrequencySeriesの別名です。

series_type = 'freq'
class gwexpy.frequencyseries.FrequencySeriesBaseDict(*args: Any, **kwargs: Any)

ベースクラス: 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

FrequencySeriesの別名です。

copy() FrequencySeriesBaseDict[_FS]

Return a deep copy of the mapping values.

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

Crop each contained series in place and return self.

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

Plot data.

パラメータ:
  • 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)

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

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

Read data into a FrequencySeriesDict.

パラメータ:
  • 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.

戻り値:

A new dict containing the data read from the source.

戻り値の型:

FrequencySeriesDict

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

Set a default entry after validating its type.

property span

Frequency extent across all elements (based on xspan).

write(target, *args, **kwargs)

Write the mapping through the Astropy I/O registry.

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

ベースクラス: 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).

パラメータ:
  • *args -- A mapping or iterable of (key, FrequencySeries) pairs.

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

メモ

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.

サンプル

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

FrequencySeriesの別名です。

angle(*args, **kwargs) FrequencySeriesDict

Alias for phase(). Returns a new FrequencySeriesDict.

append(*args, **kwargs) FrequencySeriesDict

Append to each FrequencySeries in the dict in place.

Return self.

apply_response(*args, **kwargs)

Apply response to each FrequencySeries.

crop(*args, **kwargs) FrequencySeriesDict

Crop each FrequencySeries in the dict.

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

degree(*args, **kwargs)

Compute phase (in degrees) of each FrequencySeries.

differentiate_time(*args, **kwargs)

Apply time differentiation to each item.

filter(*args, **kwargs)

Apply filter to each FrequencySeries.

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

Create from finesse FrequencyResponseSolution.

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

パラメータ:
  • 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

Create from finesse NoiseProjectionSolution.

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

パラメータ:
  • 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

Create from a PySpice AcAnalysis.

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

パラメータ:
  • 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

Create from a PySpice NoiseAnalysis.

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

パラメータ:
  • 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

Create from a scikit-rf Network.

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

パラメータ:
  • 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.

group_delay(*args, **kwargs)

Compute group delay of each item.

histogram(*args, **kwargs)

Compute Histogram for each FrequencySeries. Returns a HistogramDict.

ifft(*args, **kwargs)

Compute IFFT of each FrequencySeries. Returns a TimeSeriesDict.

integrate_time(*args, **kwargs)

Apply time integration to each item.

interpolate(*args, **kwargs)

Interpolate each FrequencySeries in the dict.

pad(*args, **kwargs)

Pad each FrequencySeries in the dict.

phase(*args, **kwargs)

Compute phase of each FrequencySeries.

prepend(*args, **kwargs) FrequencySeriesDict

Prepend to each FrequencySeries in the dict in place.

Return self.

rebin(*args, **kwargs)

Rebin each FrequencySeries in the dict.

smooth(*args, **kwargs)

Smooth each FrequencySeries.

to_control_frd(*args, **kwargs)

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

to_cupy(*args, **kwargs)

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

to_db(*args, **kwargs)

Convert each FrequencySeries to dB.

to_jax(*args, **kwargs)

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

to_matrix()

Convert this FrequencySeriesDict to a FrequencySeriesMatrix (Nx1).

to_pandas(**kwargs)

Convert the dict to a pandas.DataFrame.

Keys become columns.

to_tensorflow(*args, **kwargs)

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

to_tmultigraph(name: str | None = None) Any

Convert to ROOT TMultiGraph.

to_torch(*args, **kwargs)

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

to_xarray()

Convert the dict to an xarray.Dataset.

Keys become data variables.

write(target: str, *args: Any, **kwargs: Any) Any

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

zpk(*args, **kwargs)

Apply ZPK filter to each FrequencySeries.

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

ベースクラス: PlotMixin, list[_FS]

List container for FrequencySeries objects with type enforcement.

EntryClass

FrequencySeriesの別名です。

append(item: _FS)

Append one validated item and return self.

copy() FrequencySeriesBaseList[_FS]

Return a deep copy of the list values.

extend(items: Iterable[_FS]) None

Extend the list with validated items.

insert(index: int, item: _FS) None

Insert one validated item at the requested position.

plot(**kwargs: Any) Any

Plot this collection using gwexpy Plot.

plot_all(*args: Any, **kwargs: Any)

Alias for plot(). Plots all series.

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

Read data into a FrequencySeriesList.

パラメータ:
  • 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.

戻り値:

A new list containing the data read from the source.

戻り値の型:

FrequencySeriesList

property segments

Frequency spans of each element (xspan).

write(target, *args, **kwargs)

Write the list through the Astropy I/O registry.

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

ベースクラス: 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.

パラメータ:

*args -- An iterable of FrequencySeries objects.

メモ

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.

サンプル

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

FrequencySeriesの別名です。

angle(*args, **kwargs) FrequencySeriesList

Alias for phase(). Returns a new FrequencySeriesList.

apply_response(*args, **kwargs)

Apply response to each FrequencySeries in the list.

crop(*args, **kwargs)

Crop each FrequencySeries in the list.

degree(*args, **kwargs)

Compute phase (in degrees) of each FrequencySeries.

differentiate_time(*args, **kwargs)

Apply time differentiation to each item.

filter(*args, **kwargs)

Apply filter to each FrequencySeries in the list.

group_delay(*args, **kwargs)

Compute group delay of each item.

histogram(*args, **kwargs)

Compute Histogram for each FrequencySeries. Returns a HistogramList.

ifft(*args, **kwargs)

Compute IFFT of each FrequencySeries. Returns a TimeSeriesList.

integrate_time(*args, **kwargs)

Apply time integration to each item.

interpolate(*args, **kwargs)

Interpolate each FrequencySeries in the list.

pad(*args, **kwargs)

Pad each FrequencySeries in the list.

phase(*args, **kwargs)

Compute phase of each FrequencySeries.

rebin(*args, **kwargs)

Rebin each FrequencySeries in the list.

smooth(*args, **kwargs)

Smooth each FrequencySeries.

to_control_frd(*args, **kwargs) list

Convert each item to control.FRD.

Return a list of FRD objects.

to_cupy(*args, **kwargs) list

Convert each item to cupy.ndarray.

Return a list of arrays.

to_db(*args, **kwargs)

Convert each FrequencySeries to dB.

to_jax(*args, **kwargs) list

Convert each item to jax.Array.

Return a list of arrays.

to_pandas(**kwargs)

Convert the list to a pandas.DataFrame.

Columns are named by channel name or index.

to_tensorflow(*args, **kwargs) list

Convert each item to tensorflow.Tensor.

Return a list of tensors.

to_tmultigraph(name: str | None = None) Any

Convert to ROOT TMultiGraph.

to_torch(*args, **kwargs) list

Convert each item to torch.Tensor.

Return a list of tensors.

to_xarray()

Convert the list to an xarray.DataArray.

Concatenate items along a new channel dimension.

write(target: str, *args: Any, **kwargs: Any) Any

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

zpk(*args, **kwargs)

Apply ZPK filter to each FrequencySeries in the list.