Spectrogram#
Overview#
Note
Learning path: Use this page after the introductory spectrogram tutorial or when a time-frequency workflow needs exact API details.
|
A 2D time-frequency spectrogram. |
Spectrogram Class#
- class gwexpy.spectrogram.Spectrogram(data: ArrayLike, unit: UnitLike = None, t0: SupportsToGps | None = None, dt: Quantity | float | None = None, f0: Quantity | float | None = None, df: Quantity | float | None = None, times: ArrayLike1D | None = None, frequencies: ArrayLike1D | None = None, name: str | None = None, channel: Channel | str | None = None, **kwargs)
Bases:
PlotMixin,PhaseMethodsMixin,InteropMixin,SpectrogramA 2D time-frequency spectrogram.
Spectrogram represents a 2-dimensional array of spectral data, where the first dimension corresponds to time and the second dimension corresponds to frequency. It extends the core GWpy ~gwpy.spectrogram.Spectrogram with additional signal processing (e.g., bootstrap ASD estimation, cleaning) and interoperability methods.
Results may carry
provenanceas a detached JSON-safe mapping withschema="gwexpy.spectrogram.provenance"andschema_version=1. The mapping is propagated through derived Spectrogram operations and the supported pickle and HDF5 round-trips.- Parameters:
data (array-like) – 2D array of spectral data.
times (array-like, optional) – Time values corresponding to each row. If provided, dt and t0 are ignored.
dt (float, ~astropy.units.Quantity, optional) – Time step between rows.
t0 (float, ~astropy.units.Quantity, optional) – Start time of the data.
frequencies (array-like, optional) – Frequency values corresponding to each column. If provided, df and f0 are ignored.
df (float, ~astropy.units.Quantity, optional) – Frequency step between columns.
f0 (float, ~astropy.units.Quantity, optional) – Start frequency of the data.
**kwargs – Additional keyword arguments passed to the ~gwpy.spectrogram.Spectrogram constructor.
Notes
Key methods:
plot([method, figsize, xscale])Plot the data for this Spectrogram.
imshow(**kwargs)Plot using Matplotlib
imshow(GWpy-compatible).pcolormesh(**kwargs)Plot using Matplotlib
pcolormesh(GWpy-compatible).bootstrap([n_boot, method, average, ci, ...])Estimate robust ASD from this spectrogram using bootstrap resampling.
normalize([method, reference, percentile])Normalize the spectrogram along the time axis.
clean([method, threshold, window_size, ...])Clean the spectrogram by removing artifacts.
rebin([dt, df])Rebin the spectrogram in time and/or frequency.
Examples
>>> from gwexpy.spectrogram import Spectrogram >>> import numpy as np >>> data = np.ones((2, 2)) >>> spec = Spectrogram(data, dt=1, f0=0, df=1) >>> spec <Spectrogram([[1., 1.], [1., 1.]], unit=Unit(dimensionless), name=None, epoch=<Time object: scale='utc' format='gps' value=0.0>, channel=None, x0=<Quantity 0. s>, dx=<Quantity 1. s>, xindex=<Index [0., 1.] s>, y0=<Quantity 0. Hz>, dy=<Quantity 1. Hz>, yindex=<Index [0., 1.] Hz>)>
Methods
plot([method, figsize, xscale])Plot the data for this Spectrogram.
crop([start, end, copy])Crop this series to the given x-axis extent.
percentile(percentile)Calculate a given spectral percentile for this Spectrogram.
ratio(operand)Calculate the ratio of this Spectrogram against a reference.
filter(filt, *[, analog, sample_rate, unit, ...])Apply the given filter to this Spectrogram.
- plot(method: str = 'pcolormesh', figsize: tuple[float, float] = (12, 6), xscale: str = 'auto-gps', **kwargs) Plot
Plot the data for this Spectrogram.
- property provenance: dict[str, Any] | None
A detached, versioned JSON-safe record of this result’s analysis.
- bootstrap(n_boot=1000, method='median', average=None, ci=0.68, window='hann', fftlength=None, overlap=None, nfft=None, noverlap=None, block_size=None, rebin_width=None, return_map=False, ignore_nan=True, **kwargs)
Estimate robust ASD from this spectrogram using bootstrap resampling.
This is a convenience wrapper around gwexpy.spectral.bootstrap_spectrogram.
- Parameters:
n_boot (int, optional) – Number of bootstrap resamples to draw.
method (str, optional) – Bootstrap estimator to use.
average (str, optional) – Deprecated alias for method.
ci (float, optional) – Central confidence interval width.
window (str, optional) – Window function used for overlap-correction defaults.
fftlength (float or Quantity, optional) – FFT segment length in seconds (e.g.
1.0or1.0 * u.s). Used for VIF overlap-correlation correction. If None, the correction is estimated from spectrogram metadata. Cannot be used with nfft.overlap (float or Quantity, optional) – Overlap between FFT segments in seconds. If None, defaults to the recommended overlap for window (50 % for Hann). Cannot be used with noverlap.
nfft (int, optional) – FFT segment length in samples. Alternative to fftlength. Cannot be used with fftlength.
noverlap (int, optional) – Overlap length in samples. Must be used with nfft. Cannot be used with overlap.
block_size (float, Quantity, or 'auto', optional) – Duration of blocks for block bootstrap in seconds. Can be specified as float (seconds), Quantity with time units, or ‘auto’. If ‘auto’, estimates size based on overlap ratio. If None, perform standard bootstrap with analytical VIF correction.
rebin_width (float, optional) – Frequency rebinning width in Hz before bootstrapping.
return_map (bool, optional) – If True, return the full bootstrap map in addition to the summary.
ignore_nan (bool, optional) – If True, ignore NaN values during resampling.
**kwargs – Additional keyword arguments. Passing the removed
npersegornoverlapparameters will raiseTypeError.
Examples
>>> from gwexpy.spectrogram import Spectrogram >>> import numpy as np >>> from astropy import units as u >>> >>> # Create synthetic spectrogram >>> np.random.seed(42) >>> spec_data = np.random.random((100, 50)) >>> spec = Spectrogram(spec_data, dt=1.0*u.s, f0=10*u.Hz, df=1*u.Hz) >>> >>> # Bootstrap estimation with time-based parameters >>> result = spec.bootstrap( ... n_boot=100, ... fftlength=4.0, # 4 seconds ... overlap=2.0, # 2 seconds ... block_size=2.0, # 2 seconds block ... window='hann', ... method='median' ... ) >>> print(result.value.shape) (50,)
- bootstrap_asd(n_boot=1000, average='median', ci=0.68, window='hann', fftlength=None, overlap=None, nfft=None, noverlap=None, block_size=None, rebin_width=None, return_map=False, ignore_nan=True, **kwargs)
Estimate bootstrap ASD with the convenience wrapper.
- Parameters:
n_boot (int, optional) – Number of bootstrap resamples to draw.
average (str, optional) – Averaging method passed through to bootstrap.
ci (float, optional) – Central confidence interval width.
window (str, optional) – Window function used for overlap-correction defaults.
fftlength (float or Quantity, optional) – FFT segment length in seconds (e.g.
1.0or1.0 * u.s). Used for VIF overlap-correlation correction. Cannot be used with nfft.overlap (float or Quantity, optional) – Overlap between FFT segments in seconds. Cannot be used with noverlap.
nfft (int, optional) – FFT segment length in samples. Alternative to fftlength.
noverlap (int, optional) – Overlap length in samples. Must be used with nfft.
block_size (float, Quantity, or 'auto', optional) – Duration of blocks for block bootstrap in seconds. Can be specified as float (seconds), Quantity with time units, or ‘auto’.
rebin_width (float, optional) – Frequency rebinning width in Hz before bootstrapping.
return_map (bool, optional) – If True, return the full bootstrap map in addition to the summary.
ignore_nan (bool, optional) – If True, ignore NaN values during resampling.
**kwargs – Additional keyword arguments. Passing the removed
npersegornoverlapparameters will raiseTypeError.
Examples
>>> from gwexpy.spectrogram import Spectrogram >>> import numpy as np >>> from astropy import units as u >>> >>> # Create synthetic spectrogram >>> np.random.seed(42) >>> spec_data = np.random.random((100, 50)) >>> spec = Spectrogram(spec_data, dt=1.0*u.s, f0=10*u.Hz, df=1*u.Hz) >>> >>> # Bootstrap ASD estimation >>> result = spec.bootstrap_asd( ... n_boot=100, ... fftlength=4.0, # 4 seconds ... overlap=2.0, # 2 seconds ... block_size=2.0, # 2 seconds block ... window='hann', ... average='median' ... ) >>> print(result.value.shape) (50,)
- to_th2d(error=None)
Convert to ROOT TH2D.
- to_quantities(units=None)
Convert to quantities.Quantity for Elephant or Neo compatibility.
- classmethod from_quantities(q, times, frequencies)
Create Spectrogram from quantities.Quantity.
- Parameters:
q (quantities.Quantity) – Input data (Time x Frequency matrix).
times (array-like) – Time axis.
frequencies (array-like) – Frequency axis.
- classmethod from_root(obj, return_error=False)
Create a Spectrogram from ROOT TH2D.
- to_mne(info: Any | None = None) Any
Convert to MNE-Python object.
- Parameters:
info (mne.Info, optional) – MNE Info object.
- Return type:
mne.time_frequency.EpochsTFRArray
- classmethod from_mne(tfr: Any, **kwargs: Any) Any
Create Spectrogram from MNE-Python TFR object.
- Parameters:
tfr (mne.time_frequency.EpochsTFR or AverageTFR) – Input TFR data.
**kwargs – Additional arguments passed to constructor.
- Return type:
Spectrogram or SpectrogramDict
- classmethod from_obspy(stream: Any, **kwargs: Any) Any
Create Spectrogram from Obspy Stream.
- Parameters:
stream (obspy.Stream) – Input stream.
**kwargs – Additional arguments.
- Return type:
- classmethod from_pyroomacoustics_stft(stft_obj: Any, *, channel: int | None = None, fs: float | None = None, unit: Any | None = None) Any
Create from a pyroomacoustics STFT object.
- Parameters:
stft_obj (pyroomacoustics.stft.STFT) – STFT object with
.X,.hop, and.Nattributes.channel (int, optional) – Channel index. If None, all channels are returned as a
SpectrogramDictfor multi-channel data.fs (float, optional) – Sample rate in Hz. Required if
stft_objhas nofsattribute.unit (str or astropy.units.Unit, optional) – Unit to assign to the result.
- Return type:
Spectrogram or SpectrogramDict
- to_pyroomacoustics_stft(*, hop: int | None = None, analysis_window: Any | None = None) Any
Export as a pyroomacoustics STFT object.
- Parameters:
hop (int, optional) – Hop size in samples. If None, estimated from the spectrogram metadata.
analysis_window (numpy.ndarray, optional) – Analysis window for the STFT object.
- Return type:
pyroomacoustics.stft.STFT
- rebin(dt: float | Quantity | None = None, df: float | Quantity | None = None) Self
Rebin the spectrogram in time and/or frequency.
Rebinning averages only complete bins. If the time or frequency axis length is not divisible by the requested bin size, trailing samples that do not form a complete bin are discarded.
- imshow(**kwargs)
Plot using Matplotlib
imshow(GWpy-compatible).This method is provided for convenience and forwards arguments to
gwpy.spectrogram.Spectrogram.imshow().Common keyword arguments include
ax,cmap,norm(orlog=Truein GWpy), and color scaling controls likevmin/vmax. For the full set of supported keywords, see the GWpy documentation.
- pcolormesh(**kwargs)
Plot using Matplotlib
pcolormesh(GWpy-compatible).This method is provided for convenience and forwards arguments to
gwpy.spectrogram.Spectrogram.pcolormesh().Common keyword arguments include
ax,cmap,normandvmin/vmax. For the full set of supported keywords, see the GWpy documentation.
- radian(unwrap: bool = False) Spectrogram
Calculate the phase of this Spectrogram in radians.
- Parameters:
unwrap (bool, optional) – If True, unwrap the phase to remove discontinuities along the time axis. Default is False.
- Returns:
A new Spectrogram containing the phase in radians. All other metadata (times, frequencies, channel, epoch, etc.) are preserved.
- Return type:
- degree(unwrap: bool = False) Spectrogram
Calculate the phase of this Spectrogram in degrees.
- Parameters:
unwrap (bool, optional) – If True, unwrap the phase to remove discontinuities along the time axis. Default is False.
- Returns:
A new Spectrogram containing the phase in degrees. All other metadata (times, frequencies, channel, epoch, etc.) are preserved.
- Return type:
- normalize(method: str = 'snr', reference: Any | None = None, *, percentile: float = 50.0) Self
Normalize the spectrogram along the time axis.
- Parameters:
method ({'snr', 'median', 'mean', 'percentile', 'reference'}) –
Normalization method.
'snr': Divide each time slice by the median PSD along the time axis (equivalent to'median'). If reference is given, use it as the denominator instead.'median': Divide by the median along the time axis per frequency bin.'mean': Divide by the mean along the time axis.'percentile': Divide by the given percentile along the time axis.'reference': Divide by a user-provided reference spectrum. reference must be given.
reference (FrequencySeries or array-like, optional) – Reference spectrum used as the denominator for
'snr'(if provided) or'reference'mode.percentile (float, optional) – Percentile value for
'percentile'mode. Default is 50.0 (equivalent to median).
- Returns:
Normalized spectrogram. Unit is set to dimensionless for ratio methods.
- Return type:
Self
- clean(method: str = 'threshold', *, threshold: float = 5.0, window_size: int | None = None, fill: str = 'median', persistence_threshold: float = 0.8, amplitude_threshold: float = 3.0, return_mask: bool = False) Self | tuple[Self, ndarray]
Clean the spectrogram by removing artifacts.
- Parameters:
method ({'threshold', 'rolling_median', 'line_removal', 'combined'}) –
Cleaning method.
'threshold': Remove outlier pixels using MAD-based detection.'rolling_median': Normalize slow trends with a rolling median filter along the time axis.'line_removal': Remove persistent narrowband lines.'combined': Apply threshold, then rolling_median, then line_removal sequentially.
threshold (float, optional) – MAD sigma threshold for outlier detection. Default 5.0.
window_size (int, optional) – Rolling window size in time bins for
'rolling_median'and'combined'modes. If None, defaults toshape[0] // 4(clamped to at least 3).fill ({'median', 'nan', 'zero', 'interpolate'}) – How to fill masked/outlier values (for threshold method).
persistence_threshold (float, optional) – Fraction threshold for line detection (0.0-1.0). Default 0.8.
amplitude_threshold (float, optional) – Factor above global median for line detection. Default 3.0.
return_mask (bool, optional) – If True, also return a boolean mask of cleaned pixels.
- Returns:
Self – Cleaned spectrogram.
mask (ndarray, optional) – Boolean mask where True = pixel was cleaned. Only returned when return_mask is True.
- to_timeseries_list() tuple[TimeSeriesList, Quantity]
Convert this Spectrogram to a list of TimeSeries, one per frequency bin.
For a Spectrogram with shape
(ntimes, nfreqs), this extracts each column (frequency bin) as a TimeSeries with the same time axis.- Returns:
ts_list (TimeSeriesList) – A list of TimeSeries, one for each frequency bin. Each TimeSeries has length
ntimes.frequencies (Quantity) – The frequency axis of this Spectrogram (length
nfreqs).
Notes
Each TimeSeries inherits
unit,epoch,channelfrom this Spectrogram.nameis set to"{original_name}_f{freq}"or"f{freq}"if the Spectrogram has no name, wherefreqis the frequency value.
Examples
>>> import numpy as np >>> data = np.ones((10, 5)) >>> spec = Spectrogram(data, t0=0, dt=0.1, f0=10, df=5, name="test") >>> ts_list, freqs = spec.to_timeseries_list() >>> len(ts_list) # equals nfreqs 5 >>> ts_list[0].name 'test_f10.0 Hz'
- to_frequencyseries_list() tuple[FrequencySeriesList, Quantity]
Convert this Spectrogram to a list of FrequencySeries, one per time bin.
For a Spectrogram with shape
(ntimes, nfreqs), this extracts each row (time bin) as a FrequencySeries with the same frequency axis.- Returns:
fs_list (FrequencySeriesList) – A list of FrequencySeries, one for each time bin. Each FrequencySeries has length
nfreqs.times (Quantity) – The time axis of this Spectrogram (length
ntimes).
Notes
Each FrequencySeries inherits
unit,epoch,channelfrom this Spectrogram.nameis set to"{original_name}_t{time}"or"t{time}"if the Spectrogram has no name, wheretimeis the time value.
Examples
>>> import numpy as np >>> data = np.ones((10, 5)) >>> spec = Spectrogram(data, t0=0, dt=0.1, f0=10, df=5, name="test") >>> fs_list, times = spec.to_frequencyseries_list() >>> len(fs_list) # equals ntimes 10 >>> fs_list[0].name 'test_t0.0 s'
- property T: Self
Return the transpose of this Array2D.
- abs(**kwargs) Self | Quantity
Return the absolute value of the data in this Array.
See also
numpy.absoluteFor details of all available positional and keyword arguments, and for details of the return value.
- all(axis=None, out=None)
- angle(unwrap: bool = False, deg: bool = False, **kwargs: Any) Any
Alias for phase(unwrap=unwrap, deg=deg).
- 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.
- Parameters:
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.
Warning
inplaceappend 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
padis given and is not None, the default isgap='pad', otherwisegap='raise'.If
gap='pad'is given, the default forpadis0.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.
- Returns:
series – A new series containing joined data sets.
- Return type:
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.
See also
numpy.argpartitionequivalent 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.
- Parameters:
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.
- Returns:
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.
- Return type:
ndarray
- Raises:
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
Examples
>>> 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])
- property band: Segment
Frequency band described by these data.
- base
Base object if memory is from some other object.
Examples
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.
- Parameters:
inplace (bool, optional) – If
True, swap bytes in-place, default isFalse.- Returns:
out – The byteswapped array. If inplace is
True, this is a view to self.- Return type:
ndarray
Examples
>>> 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.
- 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
otherare compatible.- Parameters:
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=Falseand either (or both) of the series are irregular, this method just returns without doing anything.
- Raises:
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.
See also
numpy.clipequivalent function
- compress(condition, axis=None, out=None)
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
See also
numpy.compressequivalent function
- conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See also
numpy.conjugateequivalent function
- conjugate()
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See also
numpy.conjugateequivalent function
- copy(order='C')
Return a copy of the array.
- Parameters:
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.)
Notes
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.Examples
>>> 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
objectarray 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.
- Parameters:
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).
- Returns:
series – A new series with a sub-set of the input data.
- Return type:
Series
Notes
If either
startorendare outside of the original Series span, warnings will be printed and the limits will be restricted to thexspan.
- crop_frequencies(low: float | Quantity | None = None, high: float | Quantity | None = None, *, copy: bool = False) Spectrogram
Crop this Spectrogram to the specified frequencies.
- Parameters:
low (float, optional) – Lower frequency bound for cropped Spectrogram.
high (float, optional) – Upper frequency bound for cropped Spectrogram.
copy (bool, optional) – If False return a view of the original data, otherwise create a fresh memory copy.
- Returns:
spec – A new Spectrogram with a subset of data from the frequency axis
- Return type:
Spectrogram
- 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.
- Parameters:
None
- Returns:
c – Possessing attributes data, shape, strides, etc.
- Return type:
Python object
See also
Notes
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 likectypes.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 toself.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_parameterattribute which will return an integer equal to the data attribute.Examples
>>> 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.
See also
numpy.cumprodequivalent 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.
See also
numpy.cumsumequivalent 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).
- Parameters:
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.
- Returns:
newq – A new object equal to this quantity with units decomposed.
- Return type:
~astropy.units.Quantity
- device
- property df: Quantity
Frequency spacing for these data.
- 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.See also
numpy.diagonalequivalent 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.- Parameters:
- Returns:
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.
- Return type:
Series
See also
numpy.diffFor documentation on the underlying method.
- dot(b, out=None)
- property dt: Quantity
Time (seconds) between successive bins.
- dtype
Data-type of the array’s elements.
Warning
Setting
arr.dtypeis discouraged and may be deprecated in the future. Setting will replace thedtypewithout modifying the memory (see also ndarray.view and ndarray.astype).- Parameters:
None
- Returns:
d
- Return type:
numpy dtype object
See also
ndarray.astypeCast the values contained in the array to a new data-type.
ndarray.viewCreate a view of the same data but a different data-type.
Examples
>>> 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.
- property dy: Quantity
Y-axis sample separation.
- ediff1d(to_end=None, to_begin=None)
- property equivalencies
A list of equivalencies that will be applied by default during unit conversions.
- property f0: Quantity
Starting frequency for these data.
- fill(value)
- filter(filt: FilterCompatible, *, analog: bool = False, sample_rate: QuantityLike | None = None, unit: str = 'rad/s', normalize_gain: bool = False, inplace: bool = False, **kwargs) Self
Apply the given filter to this Spectrogram.
- Parameters:
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) – If True, filter definition will be converted from Hertz to Z-domain digital representation, default: False.
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 Spectrogram (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'ins2z()).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'ins2z()).
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, default: False.
kwargs – Additional keyword arguments passed to the filter function.
- Returns:
result – The filtered version of the input Spectrogram, if
inplace=Truewas given, this is just a reference to the modified input array.- Return type:
Spectrogram
- Raises:
ValueError – If
filtarguments cannot be interpreted properly.
- flags
Information about the memory layout of the array.
- Variables:
(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.
Notes
The flags object can be accessed dictionary-like (as in
a.flags['WRITEABLE']), or by using lowercased attribute names (as ina.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
Trueif the data is truly aligned.WRITEABLE can only be set
Trueif 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 ifarr.shape[dim] == 1or the array has no elements. It does not generally hold thatself.strides[-1] == self.itemsizefor C-style contiguous arrays orself.strides[0] == self.itemsizefor Fortran-style contiguous arrays is true.
- property flat
A 1-D iterator over the Quantity array.
This returns a
QuantityIteratorinstance, 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.
- Parameters:
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’.
- Returns:
y – A copy of the input array, flattened to one dimension.
- Return type:
~astropy.units.Quantity
See also
ravelReturn a flattened array.
flatA 1-D flat iterator over the array.
Examples
>>> 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 these data.
- classmethod from_spectra(*spectra: FrequencySeries, **kwargs) Spectrogram
Build a new Spectrogram from a list of spectra.
- Parameters:
*spectra (~gwpy.frequencyseries.FrequencySeries) – One or more frequency series to stack.
dt (float, ~astropy.units.Quantity, optional) – Stride between given spectra.
kwargs – Other keyword arguments to pass to the constructor.
- Returns:
A new Spectrogram from a vertical stacking of the spectra The new object takes the metadata from the first given ~gwpy.frequencyseries.FrequencySeries if not given explicitly.
- Return type:
Notes
Each ~gwpy.frequencyseries.FrequencySeries passed to this constructor must be the same length.
- 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.
- Parameters:
Examples
>>> 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.
Examples
>>> 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.
- Parameters:
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.
- Returns:
out – The sum of self and other along their shared x-axis values.
- Return type:
Series
- Raises:
ValueError – If self and other have incompatible units or xindex intervals.
Notes
The offset between
selfandotherwill 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()andplanck()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.
- Parameters:
obj (int, slice or sequence of int) – Object that defines the index or indices before which
valuesis inserted.values (array-like) – Values to insert. If the type of
valuesis different from that of quantity,valuesis converted to the matching type.valuesshould be shaped so that it can be broadcast appropriately The unit ofvaluesmust be consistent with this quantity.axis (int, optional) – Axis along which to insert
values. Ifaxisis None then the quantity array is flattened before insertion.
- Returns:
out – A copy of quantity with
valuesinserted. Note that the insertion does not occur in-place: a new quantity array is returned.- Return type:
~astropy.units.Quantity
Examples
>>> 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>
- 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.
- Parameters:
other (Series, numpy.ndarray) – Another series of the same type to test for contiguity.
tol (float, optional) – The numerical tolerance of the test.
- Returns:
1 – If
otheris contiguous with this series, i.e. would attach seamlessly onto the end.-1 – If
otheris anti-contiguous with this seires, i.e. would attach seamlessly onto the start.0 – If
otheris completely dis-contiguous with this series.
Notes
If
otheris an array that doesn’t have index information (e.g. a numpy.ndarray), this method always returns1.If
self*or*other`have an irregular Index array (e.g. aren’t linearly sampled), this method will always return1ifotherstarts afterselffinishes, or-1`if the inverse. If the two arrays overlap, that is bad and will raise an error.
- property isscalar
True if the value of this quantity is a scalar, or False if it is an array-like object.
Note
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.
Examples
>>> 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
- 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.
- Raises:
ValueError – If the array is of dimension less than 2.
Examples
>>> 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=<no value>, initial=<no value>, where=<no value>)
Return the maximum along a given axis.
Refer to numpy.amax for full documentation.
See also
numpy.amaxequivalent function
- mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
- median(axis: int | Iterable[int] | None = None, **kwargs) Self | Quantity
Return the median of the data in this Array.
See also
numpy.medianFor details of all available positional and keyword arguments, and for details of the return value.
- min(axis=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See also
numpy.aminequivalent function
- nbytes
Total bytes consumed by the elements of the array.
Notes
Does not include memory consumed by non-element attributes of the array object.
See also
sys.getsizeofMemory consumed by the object itself without parents in case view. This does include memory consumed by non-element attributes.
Examples
>>> 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.
Examples
>>> 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.
See also
numpy.nonzeroequivalent 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.
- Parameters:
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
See also
gwpy.detector.units.parse_unitFor 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.
- Parameters:
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.
- Returns:
series – The padded version of the input.
- Return type:
Series
See also
numpy.padFor 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.
- Parameters:
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.
Deprecated since version 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.
See also
numpy.partitionReturn a partitioned copy of an array.
argpartitionIndirect partition.
sortFull sort.
Notes
See
np.partitionfor notes on the different algorithms.Examples
>>> 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])
- percentile(percentile: float) FrequencySeries
Calculate a given spectral percentile for this Spectrogram.
- Parameters:
percentile (float) – percentile (0 - 100) of the bins to compute
- Returns:
spectrum – the given percentile FrequencySeries calculated from this SpectralVaraicence
- Return type:
~gwpy.frequencyseries.FrequencySeries
- phase(unwrap: bool = False, deg: bool = False, **kwargs: Any) Any
Calculate the phase of the data.
- Parameters:
unwrap (bool, optional) – If True, unwrap the phase to remove discontinuities. Default is False.
deg (bool, optional) – If True, return the phase in degrees. Default is False (radians).
**kwargs – Additional arguments passed to the underlying calculation.
- Returns:
The phase of the data.
- Return type:
Series or Matrix or Collection
- 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.
- Parameters:
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.
Warning
inplaceappend 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
padis given and is not None, the default isgap='pad', otherwisegap='raise'.If
gap='pad'is given, the default forpadis0.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.
- Returns:
series – The modified series.
- Return type:
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.
See also
numpy.prodequivalent function
- put(indices, values, mode='raise')
- ratio(operand: FrequencySeries | Quantity | Literal['mean', 'median']) Spectrogram
Calculate the ratio of this Spectrogram against a reference.
- Parameters:
operand (str, FrequencySeries, Quantity) –
A ~gwpy.frequencyseries.FrequencySeries or ~astropy.units.Quantity to weight against, or one of
'mean'Weight against the mean of each spectrum in this Spectrogram.
'median'Weight against the median of each spectrum in this Spectrogram.
- Returns:
spectrogram – A new Spectrogram.
- Return type:
Spectrogram
- Raises:
ValueError – If
operandis given as a str that isn’t supported.
- ravel(order='C')
Return a flattened array.
Refer to numpy.ravel for full documentation.
See also
numpy.ravelequivalent function
ndarray.flata flat iterator on the array.
- read = <gwpy.spectrogram.connect.SpectrogramRead object>
- real
The real part of the array.
Examples
>>> import numpy as np >>> x = np.sqrt([1+0j, 0+1j]) >>> x.real array([ 1. , 0.70710678]) >>> x.real.dtype dtype('float64')
See also
numpy.realequivalent function
- repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See also
numpy.repeatequivalent 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.
See also
numpy.reshapeequivalent function
Notes
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 toa.reshape((4, 2)).
- resize(new_shape, /, *, refcheck=True)
- resize(*new_shape, refcheck=True) None
Change shape and size of array in-place.
- Parameters:
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.
- Return type:
None
- Raises:
ValueError – If a does not own its own data or references or views to may exist.
See also
resizeReturn a new array with the specified shape.
Notes
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
resizeactually 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.
References
Examples
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]])
- 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.
- Parameters:
- Return type:
None
See also
getfieldExamples
>>> 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.)
- Parameters:
Notes
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.
Examples
>>> 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.
Warning
Setting
arr.shapeis discouraged and may be deprecated in the future. Using ndarray.reshape is the preferred approach.Examples
>>> 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.
See also
numpy.shapeEquivalent getter function.
numpy.reshapeFunction similar to setting
shape.ndarray.reshapeMethod similar to setting
shape.
- shift(delta: QuantityLike) None
Shift this Series forward on the X-axis by
delta.This modifies the series in-place.
- Parameters:
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
Examples
>>> 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.Notes
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 ofnp.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.Examples
>>> import numpy as np >>> x = np.zeros((3, 5, 2), dtype=np.complex128) >>> x.size 30 >>> np.prod(x.shape) 30
- sort(axis=-1, kind=None, order=None, *, stable=None)
Sort an array in-place. Refer to numpy.sort for full documentation.
- Parameters:
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 ofavalues which compare as equal. IfFalseorNone, this is not guaranteed. Internally, this option selectskind='stable'. Default:None.Added in version 2.0.0.
See also
numpy.sortReturn a sorted copy of an array.
numpy.argsortIndirect sort.
numpy.lexsortIndirect stable sort on multiple keys.
numpy.searchsortedFind elements in sorted array.
numpy.partitionPartial sort.
Notes
See numpy.sort for notes on the different sorting algorithms.
Examples
>>> 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')])
- property span: Segment
GPS [start, stop) span for these data.
- squeeze(axis=None)
Remove axes of length one from a.
Refer to numpy.squeeze for full documentation.
See also
numpy.squeezeequivalent function
- std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
- step(**kwargs) Plot
Create a step plot of this series.
- kwargs
All keyword arguments are passed to the
plot()method. of this series.
See also
plotFor 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).
Warning
Setting
arr.stridesis 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.Notes
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).See also
Examples
>>> 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.
See also
numpy.sumequivalent function
- swapaxes(axis1, axis2, /)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See also
numpy.swapaxesequivalent function
- property t0: Quantity
GPS time of first time bin.
- take(indices, axis=None, out=None, mode='raise')
- property times: Index
Series of GPS times for each sample
- to(unit, equivalencies=[], copy=True)
Return a new ~astropy.units.Quantity object with the specified unit.
- Parameters:
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.
See also
to_valueget the numerical value in a given unit.
- to_cupy(dtype=None) Any
Convert to CuPy Array.
- to_dask(chunks='auto') Any
Convert to Dask Array.
- 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.
- Parameters:
device ("cpu") – Must be
"cpu".stream (None, optional) – Currently unsupported.
- Returns:
out – Returns the same array.
- Return type:
Self
- to_jax() Any
Convert to JAX Array.
- 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
thresholdkeyword, which is controlled via the[units.quantity]configuration itemlatex_array_threshold. This is treated separately because the numpy default of 1000 is too big for most browsers to handle.- Parameters:
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'andformat='latex_inline'. Supported values are:’inline’: Use
$ ... $as delimiters.’display’: Use
$\displaystyle ... $as delimiters.
- Returns:
A string with the contents of this Quantity
- Return type:
- to_torch(device: str | None = None, dtype: Any = None, requires_grad: bool = False, copy: bool = False) Any
Convert to torch.Tensor.
- to_value(unit=None, equivalencies=[])
The numerical value, possibly in a different unit.
- Parameters:
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.
- Returns:
value – The value in the units specified. For arrays, this will be a view of the data if no unit conversion was necessary.
- Return type:
ndarray or scalar
See also
toGet a new instance in a different unit.
- to_zarr(store, path=None, **kwargs) Any
Save to Zarr storage.
- 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.
- Parameters:
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).
- Returns:
p – View of the array with its axes suitably permuted.
- Return type:
ndarray
See also
transposeEquivalent function.
ndarray.TArray property returning the array transposed.
ndarray.reshapeGive a new shape to an array without changing its data.
Examples
>>> 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.- Parameters:
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
padis given and is not None, the default isgap='pad', otherwisegap='raise'.If
gap='pad'is given, the default forpadis0.pad (float, optional) – Value with which to pad discontiguous series, by default gaps will result in a ValueError.
- Returns:
series – Either the same series (if
inplace=True) or a new series (ifinplace=False) withotherdata added to the end of this ‘buffer’.- Return type:
Series
See also
appendFor details of the data manipulation.
- property value
The numerical value of this instance.
See also
to_valueGet the numerical value in a given unit.
- value_at(x: QuantityLike, y: QuantityLike) Quantity
Return the value of this Series at the given (x, y) coordinates.
- Parameters:
x (float, ~astropy.units.Quantity) – The xindex value at which to search.
y (float, ~astropy.units.Quantity) – The yindex value at which to search.
- Returns:
z – The value of this Series at the given coordinates.
- Return type:
~astropy.units.Quantity
- Raises:
IndexError – If
xor y` don’t match a value on their respective index.
- var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
- variance(bins: ArrayLike1D | None = None, low: float | None = None, high: float | None = None, nbins: int = 500, *, log: bool = False, norm: bool = False, density: bool = False) SpectralVariance
Calculate the SpectralVariance of this Spectrogram.
- Parameters:
bins (~numpy.ndarray, optional, default None) – array of histogram bin edges, including the rightmost edge
low (float, optional, default: None) – left edge of lowest amplitude bin, only read if
binsis not givenhigh (float, optional, default: None) – right edge of highest amplitude bin, only read if
binsis not givennbins (int, optional, default: 500) – number of bins to generate, only read if
binsis not givenlog (bool, optional, default: False) – calculate amplitude bins over a logarithmic scale, only read if
binsis not givennorm (bool, optional, default: False) – normalise bin counts to a unit sum
density (bool, optional, default: False) – normalise bin counts to a unit integral
- Returns:
specvar – 2D-array of spectral frequency-amplitude counts
- Return type:
SpectralVariance
See also
numpy.histogramfor details on specifying bins and weights
- view([dtype][, type])
New view of array with the same data.
Note
Passing None for
dtypeis different from omitting the parameter, since the former invokesdtype(None)which is an alias fordtype('float64').- Parameters:
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
typeparameter).type (Python type, optional) – Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.
Notes
a.view()is used two different ways:a.view(some_dtype)ora.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)ora.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), ifsome_dtypehas 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 ofamust be contiguous. This axis will be resized in the result.Changed in version 1.23.0: Only the last axis needs to be contiguous. Previously, the entire array had to be C-contiguous.
Examples
>>> 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)
- write = <gwpy.spectrogram.connect.SpectrogramWrite object>
- 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.
- property y0: Quantity
Y-axis coordinate of the first data point.
- property yindex: Index
Positions of the data on the y-axis.
- property yspan: Segment
Y-axis [low, high) segment encompassed by these data.
- Type:
~gwpy.segments.Segment
- property yunit: UnitBase
Unit of Y-axis index.
- zip() ndarray
Zip the xindex and value arrays of this Series.
- Returns:
stacked – The array formed by stacking the the xindex and value of this series
- Return type:
2-d numpy.ndarray
Examples
>>> 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 = False, sample_rate: QuantityLike | None = None, unit: str = 'rad/s', normalize_gain: bool = False) Self
Filter this Spectrogram by applying a zero-pole-gain filter.
- Parameters:
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.
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 Spectrogram (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'ins2z()).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'ins2z()).
Only used for analogue filters in Hz (
analog=True, unit="Hz").
- Returns:
specgram – The frequency-domain filtered version of the input data.
- Return type:
Spectrogram
See also
Spectrogram.filterFor details on how a digital ZPK-format filter is applied.
Examples
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)
Module Contents#
gwexpy.spectrogram - Spectrogram data containers and operations.
- class gwexpy.spectrogram.SpectrogramList(initlist=None)
Bases:
PhaseMethodsMixin,UserListA list of Spectrogram objects.
SpectrogramList is a specialized list designed to hold and manipulate multiple Spectrogram objects. It provides batch processing methods (e.g., crop, rebin, bootstrap) that operate on all entries at once.
- Parameters:
initlist (iterable, optional) – An initial list of Spectrogram objects.
Notes
Spectrogram objects can be very large in memory. For large datasets, consider using SpectrogramMatrix for more efficient 3D/4D operations, or use the inplace=True option in methods like rebin when available.
Key methods:
plot(**kwargs)Plot all spectrograms stacked vertically.
to_matrix()Convert to SpectrogramMatrix (N, Time, Freq).
bootstrap(*args, **kwargs)Estimate robust ASD from each spectrogram in the list (returns FrequencySeriesList).
rebin(dt, df[, inplace])Rebin each spectrogram.
crop(*args, **kwargs)Crop each spectrogram in time.
Examples
>>> from gwexpy.spectrogram import Spectrogram, SpectrogramList >>> import numpy as np >>> spec = Spectrogram(np.ones((2, 2)), dt=1, f0=0, df=1) >>> sl = SpectrogramList([spec]) >>> sl [<Spectrogram([[1., 1.], [1., 1.]], unit=Unit(dimensionless), name=None, epoch=<Time object: scale='utc' format='gps' value=0.0>, channel=None, x0=<Quantity 0. s>, dx=<Quantity 1. s>, xindex=<Index [0., 1.] s>, y0=<Quantity 0. Hz>, dy=<Quantity 1. Hz>, yindex=<Index [0., 1.] Hz>)>]
- append(item)
Append a spectrogram, coercing compatible base objects when needed.
- bootstrap(*args, **kwargs)
Estimate robust ASD from each spectrogram in the list (returns FrequencySeriesList).
- crop(*args, **kwargs)
Crop each spectrogram in time.
- Parameters:
start (float, optional) – Start time.
end (float, optional) – End time.
copy (bool, optional) – If True (default), return a new list. If False, modify in place.
*args – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.**kwargs – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.
- crop_frequencies(f0, f1, inplace=False)
Crop frequencies.
- degree(unwrap: bool = False) SpectrogramList
Compute phase (in degrees) of each spectrogram.
- extend(other)
Extend the list with validated spectrogram objects.
- interpolate(dt, df, inplace=False)
Interpolate each spectrogram.
- plot(**kwargs)
Plot all spectrograms stacked vertically.
- plot_summary(**kwargs)
Plot the list as spectrograms with percentile summaries.
- radian(unwrap: bool = False) SpectrogramList
Compute phase (in radians) of each spectrogram.
- read(source, *args, **kwargs)
Read spectrograms into the list from HDF5.
- rebin(dt, df, inplace=False)
Rebin each spectrogram.
- to_cupy(*args, **kwargs) list
Convert each item to cupy.ndarray. Returns a list.
- to_dask(*args, **kwargs) list
Convert each item to dask.array. Returns a list.
- to_jax(*args, **kwargs) list
Convert each item to jax.Array. Returns a list.
- to_matrix()
Convert to SpectrogramMatrix (N, Time, Freq).
Validation follows SeriesMatrix base rules:
Shape must be identical across elements.
Times/frequencies are compared by converting to reference (first element) unit using .to_value(), then requiring np.array_equal (no tolerance). (Reuses gwexpy.types.seriesmatrix_validation logic).
Units, names, and channels may differ and are preserved per-element in the matrix’s MetaDataMatrix.
- Returns:
3D array of (N, Time, Freq) with per-element metadata.
- Return type:
- Raises:
ValueError – If shape or axes differ after unit conversion.
- to_tensorflow(*args, **kwargs) list
Convert each item to tensorflow.Tensor. Returns a list.
- to_torch(*args, **kwargs) list
Convert each item to torch.Tensor. Returns a list.
- write(target, *args, **kwargs)
Write list to file.
- class gwexpy.spectrogram.SpectrogramDict(dict=None, **kwargs)
Bases:
PlotMixin,PhaseMethodsMixin,UserDictA dictionary of Spectrogram objects, indexed by name.
SpectrogramDict is a specialized dictionary designed to hold and manipulate multiple Spectrogram objects simultaneously. It supports batch I/O (HDF5), normalization, and conversion to multivariate SpectrogramMatrix.
- Parameters:
dict (mapping, optional) – A mapping or iterable of (key, Spectrogram) pairs.
**kwargs – Additional keyword arguments for the dictionary.
Notes
Spectrogram objects can be very large in memory. For large datasets, prefer SpectrogramMatrix or HDF5-backed storage.
Key methods:
read(source, *args, **kwargs)Read dictionary from HDF5 file keys -> dict keys.
write(target, *args, **kwargs)Write dictionary to file.
plot(**kwargs)Plot this object using
gwexpy.plot.Plot.to_matrix()Convert to SpectrogramMatrix.
rebin(dt, df[, inplace])Rebin each spectrogram to new time/frequency resolution.
Examples
>>> from gwexpy.spectrogram import Spectrogram, SpectrogramDict >>> import numpy as np >>> sd = SpectrogramDict() >>> sd['H1'] = Spectrogram(np.ones((2, 2)), dt=1, f0=0, df=1) >>> sd {'H1': <Spectrogram([[1., 1.], [1., 1.]], unit=Unit(dimensionless), name=None, epoch=<Time object: scale='utc' format='gps' value=0.0>, channel=None, x0=<Quantity 0. s>, dx=<Quantity 1. s>, xindex=<Index [0., 1.] s>, y0=<Quantity 0. Hz>, dy=<Quantity 1. Hz>, yindex=<Index [0., 1.] Hz>)>}
- bootstrap(*args, **kwargs)
Estimate robust ASD from each spectrogram in the dict (returns FrequencySeriesDict).
- crop(*args, **kwargs)
Crop each spectrogram in time.
- Parameters:
start (float, optional) – Start time.
end (float, optional) – End time.
copy (bool, optional) – If True (default), return a new dict. If False, modify in place.
*args – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.**kwargs – Deprecated:
t0/t1/inplaceand positionalinplaceare accepted for backwards compatibility but will be removed in a future release.
- Return type:
SpectrogramDict
- crop_frequencies(f0, f1, inplace=False)
Crop each spectrogram in frequency.
- degree(unwrap: bool = False) SpectrogramDict
Compute phase (in degrees) of each spectrogram.
- interpolate(dt, df, inplace=False)
Interpolate each spectrogram to new resolution.
- plot_summary(**kwargs)
Plot the dictionary as spectrograms with percentile summaries.
- radian(unwrap: bool = False) SpectrogramDict
Compute phase (in radians) of each spectrogram.
- read(source, *args, **kwargs)
Read dictionary from HDF5 file keys -> dict keys.
- rebin(dt, df, inplace=False)
Rebin each spectrogram to new time/frequency resolution.
- to_cupy(*args, **kwargs) dict
Convert each item to cupy.ndarray. Returns a dict.
- to_dask(*args, **kwargs) dict
Convert each item to dask.array. Returns a dict.
- to_jax(*args, **kwargs) dict
Convert each item to jax.Array. Returns a dict.
- to_matrix()
Convert to SpectrogramMatrix.
Validation follows SeriesMatrix base rules:
Shape must be identical across elements.
Times/frequencies are compared by converting to reference (first element) unit using .to_value(), then requiring np.array_equal (no tolerance). (Reuses gwexpy.types.seriesmatrix_validation logic).
Units, names, and channels may differ and are preserved per-element in the matrix’s MetaDataMatrix.
- Returns:
3D array of (N, Time, Freq) with per-element metadata.
- Return type:
- Raises:
ValueError – If shape or axes differ after unit conversion.
- to_tensorflow(*args, **kwargs) dict
Convert each item to tensorflow.Tensor. Returns a dict.
- to_torch(*args, **kwargs) dict
Convert each item to torch.Tensor. Returns a dict.
- update(other=None, **kwargs)
Update the dictionary with validated spectrogram objects.
- write(target, *args, **kwargs)
Write dictionary to file.
- class gwexpy.spectrogram.SpectrogramMatrix(data: ndarray | list | tuple | _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | SpectrogramMatrix, times: XIndex | Quantity | ndarray | None = None, frequencies: XIndex | Quantity | ndarray | None = None, unit: UnitBase | str | None = None, name: str | None = None, rows: MetaDataDictLike | dict[str, MetaData | MetaDataLike | dict[str, Any]] | list[MetaData | MetaDataLike | dict[str, Any]] | None = None, cols: MetaDataDictLike | dict[str, MetaData | MetaDataLike | dict[str, Any]] | list[MetaData | MetaDataLike | dict[str, Any]] | None = None, meta: Any = None, **kwargs: Any)
Bases:
PhaseMethodsMixin,SpectrogramMatrixCoreMixin,SpectrogramMatrixAnalysisMixin,SeriesMatrixEvaluation Matrix for Spectrograms (Time-Frequency maps).
SpectrogramMatrix represents a collection of Spectrograms, structured as a multivariate matrix with dimensions either:
3D:
(Batch, Time, Frequency)4D:
(Row, Col, Time, Frequency)
It extends the core ~gwexpy.types.seriesmatrix.SeriesMatrix with spectrogram-specific axes (times and frequencies) and analysis methods.
- Parameters:
data (array-like) – The data values for the matrix. Should be 3D or 4D.
times (array-like, optional) – The time values corresponding to each row.
frequencies (array-like, optional) – The frequency values corresponding to each column.
unit (str, ~astropy.units.Unit, optional) – Physical unit of the data.
**kwargs – Additional keyword arguments passed to the ~gwexpy.types.seriesmatrix.SeriesMatrix constructor.
Notes
Serialization is supported via HDF5 and Pickle. Metadata is preserved per-element in the meta attribute.
Key methods:
plot_summary(**kwargs)Plot the matrix as side-by-side spectrograms and percentile summaries.
to_dict()Convert to SpectrogramDict.
to_list()Convert to SpectrogramList.
radian([unwrap])Calculate the phase of the matrix in radians.
Examples
>>> from gwexpy.spectrogram import SpectrogramMatrix >>> import numpy as np >>> data = np.ones((1, 2, 2)) >>> sm = SpectrogramMatrix(data, times=[0, 1], frequencies=[10, 20]) >>> sm <SeriesMatrix shape=(1, 2, 2) rows=('batch0',) cols=('col0',)>
- astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
Cast matrix data to dtype, including the frequency axis.
_rebuild_with_values (used by clip/round) falls back to astype instead of copy whenever the operation changes dtype – e.g. clipping an integer-valued matrix against float or Quantity bounds. The inherited ~gwexpy.types.series_matrix_structure.SeriesMatrixStructureMixin.astype does not resupply frequencies either, so that path silently dropped it the same way the un-overridden copy used to.
- col_index(key)
Return the integer index for a column key.
- col_keys()
Return the column metadata keys.
- conj() SpectrogramMatrix
Return a conjugate with axes and public metadata independent.
- copy(order='C')
Create a deep copy of this matrix, including the frequency axis.
The inherited ~gwexpy.types.series_matrix_structure.SeriesMatrixStructureMixin.copy only knows about the row/col/xindex metadata shared by every ~gwexpy.types.seriesmatrix.SeriesMatrix; it does not resupply frequencies – a SpectrogramMatrix-specific axis – so a bare call silently dropped frequencies/f0/df (and anything derived from them, such as clip/round, which rebuild via copy).
- dict_class
alias of
SpectrogramDict
- property imag: SpectrogramMatrix
Return a fully independent imaginary component with both axes intact.
- is_compatible(other: Any) bool
Check compatibility with another SpectrogramMatrix/object.
Overrides SeriesMatrix.is_compatible to avoid loop range issues due to mismatch between data shape (Time axis) and metadata shape (Batch/Col).
- list_class
alias of
SpectrogramList
- plot_summary(**kwargs)
Plot the matrix as side-by-side spectrograms and percentile summaries.
- property real: SpectrogramMatrix
Return a fully independent real component with both axes intact.
- row_index(key)
Return the integer index for a row key.
- row_keys()
Return the row metadata keys.
- series_class
alias of
Spectrogram
- property shape3D
Return the display-oriented 3D shape view.
- to_dict()
Convert to SpectrogramDict.
- to_list()
Convert to SpectrogramList.
- to_series_1Dlist()
Convert matrix to a flat 1D list of Spectrogram objects.
- to_series_2Dlist()
Convert matrix to a 2D nested list of Spectrogram objects.
- meta: MetaDataMatrix
- rows: MetaDataDict
- cols: MetaDataDict