Time Series#
Overview#
|
A data array holding some metadata to represent a time-series. |
TimeSeries Class#
- class gwexpy.timeseries.TimeSeries(data: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], unit: UnitLike = None, t0: SupportsToGps | None = None, dt: float | Quantity | None = None, sample_rate: float | Quantity | None = None, times: ArrayLike1D | None = None, channel: Channel | str | None = None, name: str | None = None, *, t0_ns: int | None = None, **kwargs: Any)
ベースクラス:
PlotMixin,TimeSeriesInteropMixin,TimeSeriesAnalysisMixin,TimeSeriesResamplingMixin,TimeSeriesSignalMixin,SignalAnalysisMixin,TimeSeriesSpectralMixin,StatisticsMixin,FittingMixin,PhaseMethodsMixin,TimeSeriesCoreA data array holding some metadata to represent a time-series.
TimeSeries is the primary object used to represent time-domain data in gwexpy. It extends the standard gwpy.timeseries.TimeSeries by incorporating additional mixins for plotting, signal analysis, regularity checks, numerical fitting, statistical methods, and enhanced interoperability.
- パラメータ:
data (array-like) -- Input data array.
unit (~astropy.units.Unit, optional) -- Physical unit of these data.
t0 (~gwpy.time.LIGOTimeGPS, float, str, optional, default: 0) -- GPS epoch associated with these data, any input parsable by ~gwpy.time.to_gps is fine.
t0_ns (int, optional, keyword-only) -- Exact GPS epoch in integer nanoseconds. This is the authoritative epoch representation for
t0_gps_ns; it cannot be combined witht0,epoch,x0,xindex, ortimes.dt (float, ~astropy.units.Quantity, optional, default: 1) -- Time resolution for these data.
sample_rate (float, ~astropy.units.Quantity, optional, default: 1) -- Sample rate for these data.
times (array-like) -- The complete array of times indexing the data. This argument takes precedence over t0 and dt so should be given in place of these if relevant, not alongside.
name (str, optional) -- Descriptive title for this array.
channel (~gwpy.detector.Channel, str, optional) -- Source data stream for these data.
dtype (~numpy.dtype, optional) -- Input data type.
copy (bool, optional, default: False) -- Choose to copy the input data to new memory.
subok (bool, optional, default: True) -- Allow passing of sub-classes by the array generator.
メモ
In addition to the standard GWpy functionality, this class provides advanced features such as time-domain differentiation/integration, rolling statistics, and seamless interoperability with PyTorch, Xarray, and Polars.
Key methods:
plot([method, figsize, xscale])Plot the data for this timeseries.
resample(rate[, window, ftype, n])Resample the TimeSeries.
filter(filt, *[, analog, unit, ...])Filter this TimeSeries with an IIR or FIR filter.
fft([nfft, mode, pad_mode, pad_left, ...])Compute the Discrete Fourier Transform (DFT).
psd(*args, **kwargs)spectrogram(stride[, fftlength, overlap, ...])Compute the average power spectrogram.
サンプル
>>> from gwexpy.timeseries import TimeSeries >>> import numpy as np >>> data = np.array([0.1, -1.2, 0.5]) >>> ts = TimeSeries(data, sample_rate=1000, unit='V') >>> ts <TimeSeries([ 0.1, -1.2, 0.5], unit=Unit("V"), t0=<Quantity 0. s>, dt=<Quantity 0.001 s>, name=None, channel=None)>
Methods
fft([nfft, mode, pad_mode, pad_left, ...])Compute the Discrete Fourier Transform (DFT).
rfft(*args, **kwargs)Real-valued Fast Fourier Transform.
psd(*args, **kwargs)asd(*args, **kwargs)csd(other, *args, **kwargs)spectrogram(stride[, fftlength, overlap, ...])Compute the average power spectrogram.
coherence(*args, **kwargs)filter(filt, *[, analog, unit, ...])Filter this TimeSeries with an IIR or FIR filter.
resample(rate[, window, ftype, n])Resample the TimeSeries.
detrend([detrend])Remove the trend from this TimeSeries.
cepstrum([kind, window, detrend, eps, fft_mode])Compute the cepstrum of the time series.
cwt([wavelet, widths, frequencies, window, ...])Compute the Continuous Wavelet Transform (CWT).
dct([type, norm, window, detrend])Compute the Discrete Cosine Transform (DCT).
emd(*[, method, max_imf, sift_max_iter, ...])Decompose the TimeSeries using Empirical Mode Decomposition (EMD).
hht(*[, emd_method, emd_kwargs, ...])Perform Hilbert-Huang Transform (HHT) on the TimeSeries.
hilbert_analysis(*[, unwrap_phase, ...])Perform Hilbert analysis to extract instantaneous amplitude, phase, and frequency.
- plot(method: str = 'plot', figsize: tuple[int, int] = (12, 4), xscale: str = 'auto-gps', **kwargs) Plot
Plot the data for this timeseries.
- classmethod read(source, *args, parallel=None, nproc=None, **kwargs)
Read a TimeSeries from a supported source.
This override adds explicit CSV and .gwf handling for deterministic behavior when .read() is called through the public API.
GWF accepts the compatible
parallel=andnproc=keywords; see the generated signature and the GWF I/O guide for their constraints.GWexpy GWF parallel reads#
parallel=acceptsNone/False/1for serial reads,Truefor automatic workers, or an integer from 2 through 8.nproc=is the compatibility alias. Supplying both raisesTypeErrorbefore file or backend I/O. Multi-worker reads require a list or tuple of individual local.gwfframe paths (not URIs, caches, queries, globs, or file-like objects), use spawn-safe workers, and propagate worker exceptions, includingImportError, unchanged. Daemon processes cannot start these workers and are rejected during preflight.
- write(target, *args, **kwargs)
Write a TimeSeries through the registered I/O handlers.
- property t0_gps_ns: int
GPS epoch as exact integer nanoseconds.
Objects constructed with
t0_ns=return the original integer authority without a float conversion. Legacy objects constructed with GWpy's float-compatible epoch inputs retain their historical behaviour and are normalised throughLIGOTimeGPSon demand.
- property t0: Any
GWpy-compatible epoch view, synchronized with exact metadata.
- property x0: Any
GWpy-compatible axis-origin alias, synchronized with
t0_ns.
- property dt: Any
GWpy-compatible cadence view synchronized with exact metadata.
- property dx: Any
GWpy-compatible cadence alias synchronized with exact metadata.
- copy(order: Literal['C', 'F', 'A', 'K'] = 'C') TimeSeries
Copy this series without reconstructing its exact epoch from
t0.
- to_simpeg(location: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, rx_type: str = 'PointElectricField', orientation: str = 'x', **kwargs: Any) Any
Convert to SimPEG Data object.
- パラメータ:
location (array_like, optional) -- Rx location (x, y, z). Default is [0, 0, 0].
rx_type (str, optional) -- Receiver class name. Default "PointElectricField".
orientation (str, optional) -- Receiver orientation ('x', 'y', 'z'). Default 'x'.
**kwargs (Any) -- Additional arguments passed to SimPEG converter.
- 戻り値の型:
simpeg.data.Data
- classmethod from_simpeg(data_obj: Any, **kwargs: Any) TimeSeries
Create TimeSeries from SimPEG Data object.
- パラメータ:
data_obj (simpeg.data.Data) -- Input SimPEG Data.
**kwargs (Any) -- Additional arguments passed to constructor.
- 戻り値の型:
- classmethod from_control(response: Any, **kwargs: Any) TimeSeries | TimeSeriesDict
Create TimeSeries from python-control TimeResponseData.
- パラメータ:
response (control.TimeResponseData) -- The simulation result from python-control.
**kwargs (dict) -- Additional arguments passed to the constructor.
- 戻り値:
The converted time-domain data.
- 戻り値の型:
TimeSeries or TimeSeriesDict
- arima(order: tuple[int, int, int] = (1, 0, 0), *, seasonal_order: tuple[int, int, int, int] | None = None, auto: bool = False, **kwargs: Any) Any
Fit an ARIMA or SARIMAX model to this TimeSeries.
This method wraps statsmodels.tsa.arima.model.ARIMA (or SARIMAX). If auto=True, it uses pmdarima to automatically find the best parameters.
- パラメータ:
- 戻り値:
Object containing the fitted model, with methods .predict(), .forecast(), .plot().
- 戻り値の型:
ArimaResult
- ar(p: int = 1, **kwargs: Any) Any
Fit an AutoRegressive AR(p) model.
Shortcut for .arima(order=(p, 0, 0)).
- DictClass
TimeSeriesDictの別名です。
- T
View of the transposed array.
Same as
self.transpose().サンプル
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.T array([[1, 3], [2, 4]])
>>> a = np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> a.T array([1, 2, 3, 4])
参考
transpose
- abs(**kwargs) Self | Quantity
Return the absolute value of the data in this Array.
参考
numpy.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: TimeSeries | BaseTimeSeries | ArrayLike, *, inplace: bool = True, gap: Any = None, pad: Any = None, resize: bool = True) TimeSeriesCore
Append another TimeSeries, returning a GWexpy TimeSeries.
- argmax(axis=None, out=None, *, keepdims=False)
- argmin(axis=None, out=None, *, keepdims=False)
- argpartition(kth, axis=-1, kind='introselect', order=None)
Returns the indices that would partition this array.
Refer to numpy.argpartition for full documentation.
参考
numpy.argpartitionequivalent function
- argsort(axis=-1, kind=None, order=None, *, stable=None)
- asd(*args: Any, **kwargs: Any) FrequencySeries
- asfreq(rule: str | int | float | number | Quantity, method: str | None = None, fill_value: Any = nan, *, origin: str | int | float | number | Quantity = 't0', offset: int | float | number | Quantity | None = None, align: Literal['ceil', 'floor'] = 'ceil', tolerance: float | Quantity | None = None, max_gap: float | Quantity | None = None, copy: bool = True) TimeSeriesResamplingMixin
Reindex the TimeSeries to a new fixed-interval grid associated with the given rule.
- パラメータ:
rule (str, float, or Quantity) -- Target time interval (e.g., '1s', 0.1, 0.5*u.s).
method (str or None) -- Fill method: None (exact), 'ffill', 'bfill', 'nearest'.
fill_value (scalar) -- Value for missing data points.
origin (str) -- Reference point for grid alignment: 't0' or 'gps0'.
offset (Quantity) -- Time offset from origin.
align (str) -- Grid alignment: 'ceil' or 'floor'.
tolerance (float) -- Tolerance for matching times.
max_gap (float) -- Maximum gap for interpolation.
copy (bool) -- Whether to copy data.
- 戻り値:
Reindexed series.
- 戻り値の型:
- astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
Copy of the array, cast to a specified type.
- パラメータ:
dtype (str or dtype) -- Typecode or data-type to which the array is cast.
order ({'C', 'F', 'A', 'K'}, optional) -- Controls the memory layout order of the result. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. Default is 'K'.
casting ({'no', 'equiv', 'safe', 'same_kind', 'same_value', 'unsafe'}, optional) --
Controls what kind of data casting may occur. Defaults to 'unsafe' for backwards compatibility.
'no' means the data types should not be cast at all.
'equiv' means only byte-order changes are allowed.
'safe' means only casts which can preserve values are allowed.
'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed.
'unsafe' means any data conversions may be done.
'same_value' means any data conversions may be done, but the values must not change, including rounding of floats or overflow of ints
Added in version 2.4: Support for
'same_value'was added.subok (bool, optional) -- If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
copy (bool, optional) -- By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
- 戻り値:
arr_t -- Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
- 戻り値の型:
ndarray
- 例外:
ComplexWarning -- When casting from complex to float or int. To avoid this, one should use
a.real.astype(t).ValueError -- When casting using
'same_value'and the values change or would overflow
サンプル
>>> import numpy as np >>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5])
>>> x.astype(int) array([1, 2, 2])
>>> x.astype(int, casting="same_value") Traceback (most recent call last): ... ValueError: could not cast 'same_value' double to long
>>> x[:2].astype(int, casting="same_value") array([1, 2])
- auto_coherence(dt: float, fftlength: float | None = None, overlap: float | None = None, window: WindowLike = 'hann', **kwargs) FrequencySeries
Calculate the coherence between this series and a shifted copy of itself.
The standard
TimeSeries.coherence()is calculated between the input TimeSeries and acroppedcopy of itself. Since the cropped version will be shorter, the input series will be shortened to match.- パラメータ:
dt (float) -- Duration (in seconds) of time-shift.
fftlength (float, optional) -- Number of seconds in single FFT, defaults to a single FFT covering the full duration.
overlap (float, optional) -- Number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0.
window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.kwargs -- Any other keyword arguments accepted by
matplotlib.mlab.cohere()exceptNFFT,window, andnoverlapwhich are superceded by the above keyword arguments.
- 戻り値:
coherence -- The coherence FrequencySeries of this TimeSeries with the other.
- 戻り値の型:
~gwpy.frequencyseries.FrequencySeries
メモ
The
TimeSeries.auto_coherence()will perform best whendtis approximatelyfftlength / 2.参考
matplotlib.mlab.cohereFor details of the coherence calculator.
- average_fft(fftlength: float | Quantity | None = None, overlap: float | Quantity = 0, window: WindowLike | None = None) FrequencySeries
Compute the averaged one-dimensional DFT of this TimeSeries.
This method computes a number of FFTs of duration
fftlengthandoverlap(both given in seconds), and returns the mean average. This method is analogous to the Welch average method for power spectra.- パラメータ:
fftlength (float) -- Number of seconds in single FFT; by default uses whole TimeSeries.
overlap (float, optional) -- Number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0.
window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.
- 戻り値:
out -- The transformed output, with populated frequencies array metadata.
- 戻り値の型:
complex-valued ~gwpy.frequencyseries.FrequencySeries
参考
TimeSeries.fftThe FFT method used.
- bandpass(flow: float, fhigh: float, gpass: float = 2, gstop: float = 30, fstop: tuple[float, float] | None = None, type: Literal['fir', 'iir'] = 'iir', *, filtfilt: bool = True, **kwargs) TimeSeries
Filter this TimeSeries with a band-pass filter.
- パラメータ:
flow (float) -- Lower corner frequency of pass band.
fhigh (float) -- Upper corner frequency of pass band.
gpass (float) -- The maximum loss in the passband (dB).
gstop (float) -- The minimum attenuation in the stopband (dB).
fstop (tuple of float, optional) --
(low, high)edge-frequencies of stop band.type (str) -- The filter type, either
'iir'or'fir'.filtfilt (bool, optional) -- If True, apply the filter using a forward-backward filter design, otherwise apply the filter in a single pass. Defaults to True.
kwargs -- Other keyword arguments are passed to
gwpy.signal.filter_design.bandpass()
- 戻り値:
bpseries -- A band-passed version of the input TimeSeries.
- 戻り値の型:
TimeSeries
参考
gwpy.signal.filter_design.bandpassFor details on the filter design.
TimeSeries.filterFor details on how the filter is applied.
- base
Base object if memory is from some other object.
サンプル
The base of an array that owns its memory is None:
>>> import numpy as np >>> x = np.array([1,2,3,4]) >>> x.base is None True
Slicing creates a view, whose memory is shared with x:
>>> y = x[2:] >>> y.base is x True
- baseband(*, phase: Sequence[int | float | number] | ndarray[tuple[Any, ...], dtype[floating]] | ndarray[tuple[Any, ...], dtype[complex128]] | None = None, f0: int | float | number | Quantity | None = None, fdot: int | float | number | Quantity = 0.0, fddot: int | float | number | Quantity = 0.0, phase_epoch: int | float | number | None = None, phase0: float = 0.0, lowpass: float | Quantity | None = None, lowpass_kwargs: dict[str, Any] | None = None, output_rate: int | float | number | Quantity | None = None, resample_kwargs: dict[str, Any] | None = None, singlesided: bool = False) TimeSeriesSignalMixin
Demodulate the TimeSeries to baseband with optional lowpass and resampling.
This method performs frequency mixing (heterodyning) to shift a carrier frequency to baseband (DC), optionally followed by lowpass filtering and/or resampling. The processing chain is:
mix_down(f0) → [lowpass(cutoff)] → [resample(output_rate)]
Two primary modes are supported:
- Mode A (Analysis bandwidth explicit):
baseband(f0=fc, lowpass=cutoff, output_rate=None|...)- Applies lowpass filter after mixing to define analysis bandwidth - Optionally resamples to reduce data rate- Mode B (Downsample priority):
baseband(f0=fc, lowpass=None, output_rate=rate)- Skips explicit lowpass; relies on resample's anti-aliasing - Useful when avoiding double-filtering
- パラメータ:
phase (array_like or None, optional) -- Explicit phase array (radians) for mixing. Mutually exclusive with f0/fdot/fddot.
f0 (float or Quantity, optional) -- Center frequency (Hz) for mixing. The signal at f0 is shifted to DC. Must satisfy 0 < f0 < Nyquist for regular series.
fdot (float or Quantity, default=0.0) -- Frequency derivative (Hz/s) for chirp signals.
fddot (float or Quantity, default=0.0) -- Second frequency derivative (Hz/s²) for accelerating chirps.
phase_epoch (float or None, optional) -- Reference epoch for phase model.
phase0 (float, default=0.0) -- Initial phase offset (radians).
lowpass (float or Quantity or None, optional) -- Lowpass filter corner frequency (Hz). Defines the analysis bandwidth (half-bandwidth) around baseband. Must satisfy 0 < lowpass < Nyquist. If both lowpass and output_rate are specified, lowpass must be less than output_rate/2 (the new Nyquist).
lowpass_kwargs (dict or None, optional) -- Additional arguments passed to
lowpass(). GWpy-compatible options includetype,gpass,gstop,fstop,filtfilt.output_rate (float or Quantity or None, optional) -- Output sample rate (Hz). If specified, resamples the output. Must be > 0. Uses GWpy's
resample()internally.resample_kwargs (dict or None, optional) -- Additional arguments passed to
resample(). GWpy-compatible options includewindow,ftype,n.singlesided (bool, default=False) -- If True, double the amplitude (for real input signals).
- 戻り値:
Complex baseband signal.
- 戻り値の型:
- 例外:
ValueError -- If f0 <= 0.
ValueError -- If f0 >= Nyquist (for regular series).
ValueError -- If lowpass <= 0 or lowpass >= Nyquist.
ValueError -- If output_rate <= 0.
ValueError -- If both lowpass and output_rate are None.
ValueError -- If lowpass >= output_rate/2 (exceeds new Nyquist).
メモ
Preprocessing: No automatic preprocessing is applied. Users should apply demean, detrend, or filtering as needed before calling. DC offset and low-frequency trends can affect the baseband result.
Lowpass vs f0: It is generally recommended to set lowpass < f0 to capture only the modulation around the carrier. However, this is not enforced to allow flexibility in edge cases.
GWpy alignment: The lowpass and resample operations delegate to GWpy's methods with their default parameters. Customization is available via lowpass_kwargs and resample_kwargs.
サンプル
Mode A (with lowpass):
>>> ts = TimeSeries(np.cos(2 * np.pi * 100 * t), dt=0.001, unit='V') >>> z = ts.baseband(f0=100, lowpass=10) # 10 Hz analysis bandwidth
Mode B (resample only):
>>> z = ts.baseband(f0=100, lowpass=None, output_rate=50)
With both:
>>> z = ts.baseband(f0=100, lowpass=10, output_rate=50)
- byteswap(inplace=False)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.
- パラメータ:
inplace (bool, optional) -- If
True, swap bytes in-place, default isFalse.- 戻り値:
out -- The byteswapped array. If inplace is
True, this is a view to self.- 戻り値の型:
ndarray
サンプル
>>> import numpy as np >>> A = np.array([1, 256, 8755], dtype=np.int16) >>> list(map(hex, A)) ['0x1', '0x100', '0x2233'] >>> A.byteswap(inplace=True) array([ 256, 1, 13090], dtype=int16) >>> list(map(hex, A)) ['0x100', '0x1', '0x3322']
Arrays of byte-strings are not swapped
>>> A = np.array([b'ceg', b'fac']) >>> A.byteswap() array([b'ceg', b'fac'], dtype='|S3')
A.view(A.dtype.newbyteorder()).byteswap()produces an array with the same values but different representation in memory>>> A = np.array([1, 2, 3],dtype=np.int64) >>> A.view(np.uint8) array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0], dtype=uint8) >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True) array([1, 2, 3], dtype='>i8') >>> A.view(np.uint8) array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3], dtype=uint8)
- cepstrum(kind: Literal['real', 'complex', 'power'] = 'real', *, window: WindowLike | None = None, detrend: bool = False, eps: float | None = None, fft_mode: str = 'gwpy') FrequencySeries
Compute the cepstrum of the time series.
The cepstrum is the inverse Fourier transform of the log spectrum. It is useful for detecting periodicity in the spectrum, such as for pitch detection, echo analysis, and deconvolution.
- パラメータ:
kind ({'real', 'complex', 'power'}, optional) -- Type of cepstrum to compute: - 'real': IFFT of log magnitude spectrum (default) - 'complex': IFFT of log complex spectrum - 'power': IFFT of log power spectrum
window (str, tuple, or array-like, optional) -- Window function to apply before the transform.
detrend (bool, optional) -- If True, remove linear trend before the transform.
eps (float, optional) -- Small value to add to spectrum to avoid log(0).
fft_mode (str, optional) -- FFT mode (reserved for future use).
- 戻り値:
The cepstrum with quefrency axis (in seconds).
- 戻り値の型:
メモ
The x-axis of the output is in "quefrency" (time units), which represents periodicity in the spectrum. Peaks in the cepstrum indicate harmonic spacing or echo delays.
サンプル
>>> ts = TimeSeries(data, sample_rate=1024) >>> ceps = ts.cepstrum(kind='real') >>> # Find fundamental period from peak in cepstrum
- 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.- パラメータ:
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.
- 例外:
ValueError -- If any metadata elements aren't compatible.
TypeError -- If the dtype can't be safely cast between the arrays.
- choose(choices, out=None, mode='raise')
- clip(min=<no value>, max=<no value>, out=None, **kwargs)
Return an array whose values are limited to
[min, max]. One of max or min must be given.Refer to numpy.clip for full documentation.
参考
numpy.clipequivalent function
- coherence(*args: Any, **kwargs: Any) FrequencySeries
- coherence_spectrogram(other: TimeSeries, stride: float, fftlength: float | None = None, overlap: float | None = None, window: WindowLike = 'hann', nproc: int = 1) Spectrogram
Calculate the coherence spectrogram between this TimeSeries and other.
- パラメータ:
other (TimeSeries) -- The second TimeSeries in this CSD calculation.
stride (float) -- Number of seconds in single PSD (column of spectrogram).
fftlength (float) -- Number of seconds in single FFT.
overlap (float, optional) -- Number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0.
window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.nproc (int) -- Number of parallel processes to use when calculating individual coherence spectra.
- 戻り値:
spectrogram -- Time-frequency coherence spectrogram as generated from the input time-series.
- 戻り値の型:
~gwpy.spectrogram.Spectrogram
- compress(condition, axis=None, out=None)
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
参考
numpy.compressequivalent function
- conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
参考
numpy.conjugateequivalent function
- conjugate()
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
参考
numpy.conjugateequivalent function
- convolve(fir: numpy.ndarray, window: WindowLike = 'hann') Self
Convolve this TimeSeries with an FIR filter using the overlap-save method.
- パラメータ:
fir (numpy.ndarray) -- The time domain filter to convolve with.
window (str, optional) -- Window function to apply to boundaries, default:
'hann'seescipy.signal.get_window()for details on acceptable formats.
- 戻り値:
out -- The result of the convolution.
- 戻り値の型:
TimeSeries
参考
scipy.signal.fftconvolveFor details on the convolution scheme used here.
TimeSeries.filterFor an alternative method designed for short filters.
メモ
The output TimeSeries is the same length and has the same timestamps as the input.
Due to filter settle-in, a segment half the length of fir will be corrupted at the left and right boundaries. To prevent spectral leakage these segments will be windowed before convolving.
- correlate(mfilter: TimeSeries, window: WindowLike = 'hann', detrend: Literal['linear', 'constant'] = 'linear', *, whiten: bool = False, wduration: float = 2, highpass: float | None = None, **asd_kw) TimeSeries
Cross-correlate this TimeSeries with another signal.
- パラメータ:
mfilter (TimeSeries) -- the time domain signal to correlate with
window (str, optional) -- window function to apply to timeseries prior to FFT, default:
'hann'seescipy.signal.get_window()for details on acceptable formatsdetrend (str, optional) -- type of detrending to do before FFT (see ~TimeSeries.detrend for more details), default:
'linear'whiten (bool, optional) -- boolean switch to enable (True) or disable (False) data whitening, default: False
wduration (float, optional) -- duration (in seconds) of the time-domain FIR whitening filter, only used if whiten=True, defaults to 2 seconds
highpass (float, optional) -- highpass corner frequency (in Hz) of the FIR whitening filter, only used if whiten=True, default: None
**asd_kw -- keyword arguments to pass to TimeSeries.asd to generate an ASD, only used if whiten=True
- 戻り値:
snr -- the correlated signal-to-noise ratio (SNR) timeseries
- 戻り値の型:
TimeSeries
参考
TimeSeries.asdfor details on the ASD calculation
TimeSeries.convolvefor details on convolution with the overlap-save method
メモ
The window argument is used in ASD estimation, whitening, and preventing spectral leakage in the output. It is not used to condition the matched-filter, which should be windowed before passing to this method.
Due to filter settle-in, a segment half the length of mfilter will be corrupted at the beginning and end of the output. See ~TimeSeries.convolve for more details.
The input and matched-filter will be detrended, and the output will be normalised so that the SNR measures number of standard deviations from the expected mean.
- correlation(other, method='pearson', **kwargs)
Calculate correlation coefficient with another TimeSeries.
- パラメータ:
other (TimeSeries) -- The series to compare with.
method (str) -- 'pearson', 'kendall', 'mic', or 'distance'.
**kwargs -- Additional arguments passed to the underlying function.
- 戻り値:
The correlation coefficient.
- 戻り値の型:
- crop(start: Any | None = None, end: Any | None = None, *, copy: bool = False) TimeSeriesCore
Crop this series to the given GPS start and end times.
Accepts any time format supported by gwexpy.time.to_gps (str, datetime, pandas, obspy, etc).
- csd(other: Any, *args: Any, **kwargs: Any) FrequencySeries
- csd_spectrogram(other: TimeSeries, stride: float, fftlength: float | None = None, overlap: float = 0, window: WindowLike = 'hann', nproc: int = 1, **kwargs) Spectrogram
Calculate the cross spectral density spectrogram with
other.- パラメータ:
other (~gwpy.timeseries.TimeSeries) -- Second time-series for cross spectral density calculation.
stride (float) -- Number of seconds in single PSD (column of spectrogram).
fftlength (float) -- Number of seconds in single FFT.
overlap (float, optional) -- Number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0.
window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.nproc (int) -- Maximum number of independent frame reading processes, default is set to single-process file reading.
kwargs -- Other keyword arguments are passed to the underlying CSD-generation method.
- 戻り値:
spectrogram -- Time-frequency cross spectrogram as generated from the two input time-series.
- 戻り値の型:
~gwpy.spectrogram.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.
- パラメータ:
None
- 戻り値:
c -- Possessing attributes data, shape, strides, etc.
- 戻り値の型:
Python object
メモ
Below are the public attributes of this object which were documented in "Guide to NumPy" (we have omitted undocumented public attributes, as well as documented private attributes):
- _ctypes.data
A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as:
self._array_interface_['data'][0].Note that unlike
data_as, a reference won't be kept to the array: code 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.サンプル
>>> import numpy as np >>> import ctypes >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32) >>> x array([[0, 1], [2, 3]], dtype=int32) >>> x.ctypes.data 31962608 # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)) <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents c_uint(0) >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents c_ulong(4294967296) >>> x.ctypes.shape <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary >>> x.ctypes.strides <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
- cumprod(axis=None, dtype=None, out=None)
Return the cumulative product of the elements along the given axis.
Refer to numpy.cumprod for full documentation.
参考
numpy.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.
参考
numpy.cumsumequivalent function
- cwt(wavelet: str = 'cmor1.5-1.0', widths: Any = None, frequencies: Any = None, *, window: Any = None, detrend: bool = False, output: str = 'spectrogram', chunk_size: int | None = None, **kwargs: Any) Any
Compute the Continuous Wavelet Transform (CWT).
The CWT provides a time-frequency representation of the signal using a wavelet basis. Unlike STFT, CWT uses wavelets of varying width to achieve better time resolution at high frequencies and better frequency resolution at low frequencies.
- パラメータ:
wavelet (str, optional) -- Wavelet to use. Default is 'cmor1.5-1.0' (Complex Morlet). See pywt.wavelist() for available wavelets.
widths (array-like, optional) -- Wavelet scales to use. Mutually exclusive with frequencies.
frequencies (array-like or Quantity, optional) -- Target frequencies in Hz. Scales are computed from these. Mutually exclusive with widths.
window (str, tuple, or array-like, optional) -- Window function to apply before the transform.
detrend (bool, optional) -- If True, remove linear trend before the transform.
output ({'spectrogram', 'ndarray'}, optional) -- Output format. 'spectrogram' returns a gwpy Spectrogram. 'ndarray' returns (coefficients, frequencies) tuple.
chunk_size (int, optional) -- Number of scales to process at once for memory efficiency.
**kwargs -- Additional arguments passed to pywt.cwt().
- 戻り値:
If output='spectrogram': a Spectrogram object. If output='ndarray': (coefficients, frequencies) tuple.
- 戻り値の型:
Spectrogram or tuple
メモ
Requires the pywt (PyWavelets) package.
Complex Coefficients
For complex wavelets (e.g., 'cmor', 'morl'), the CWT coefficients are complex-valued, containing both magnitude and phase information:
np.abs(coefs): Envelope/magnitude (instantaneous amplitude)np.angle(coefs): Instantaneous phase (radians)np.real(coefs): Real part (in-phase component)np.imag(coefs): Imaginary part (quadrature component)
For time-frequency power analysis, use
np.abs(coefs)**2.The returned Spectrogram object preserves complex dtype. To visualize, apply
np.abs()before plotting.サンプル
>>> ts = TimeSeries(data, sample_rate=1024) >>> spec = ts.cwt(frequencies=np.logspace(0, 2, 50)) >>> power = np.abs(spec.value)**2 # Time-frequency power
- data
Python buffer object pointing to the start of the array's data.
- dct(type: int = 2, norm: str = 'ortho', *, window: WindowLike | None = None, detrend: bool = False) FrequencySeries
Compute the Discrete Cosine Transform (DCT).
The DCT expresses the signal as a sum of cosine functions at different frequencies. It is widely used in signal compression and spectral analysis due to its energy compaction properties.
- パラメータ:
type (int, optional) -- DCT type (1, 2, 3, or 4). Default is 2 (most common).
norm (str, optional) -- Normalization mode: 'ortho' for orthonormal, None for standard. Default is 'ortho'.
window (str, tuple, or array-like, optional) -- Window function to apply before the transform.
detrend (bool, optional) -- If True, remove linear trend before the transform.
- 戻り値:
The DCT coefficients as a FrequencySeries. The frequencies represent DCT bin indices (k / 2*N*dt).
- 戻り値の型:
メモ
The DCT is useful for analyzing signals where edge effects are a concern, as it implicitly assumes even symmetry at boundaries.
サンプル
>>> ts = TimeSeries(data, sample_rate=1024) >>> dct_coeffs = ts.dct()
- decompose(bases: Collection[UnitBase] = ()) Self
Generates a new Quantity with the units decomposed. Decomposed units have only irreducible units in them (see astropy.units.UnitBase.decompose).
- パラメータ:
bases (sequence of ~astropy.units.UnitBase, optional) -- The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a ~astropy.units.UnitsError if it's not possible to do so.
- 戻り値:
newq -- A new object equal to this quantity with units decomposed.
- 戻り値の型:
~astropy.units.Quantity
- degree(unwrap: bool = False) TimeSeriesSignalMixin
Calculate the phase angle of the TimeSeries in degrees.
Computes np.angle(self.value) directly. Works for both real and complex time series. For real signals, this will return 0 or 180 depending on sign.
For instantaneous phase of a real signal via Hilbert transform, use
instantaneous_phase()instead.- パラメータ:
unwrap (bool, optional) -- If True, unwrap the phase. Default is False.
- 戻り値:
Phase angle in degrees.
- 戻り値の型:
- demodulate(f: float, stride: float = 1, *, exp: bool = False, deg: bool = True) tuple[TimeSeries, TimeSeries] | TimeSeries
Compute the average magnitude and phase of the TimeSeries at a.
given frequency (GWpy-compatible).
This method replicates the GWpy
TimeSeries.demodulate()algorithm. It heterodynes the signal at a fixed frequency, averages over strides, and returns either the complex demodulated signal or (magnitude, phase) trends.- パラメータ:
f (float or Quantity) -- Frequency (Hz) at which to demodulate.
stride (float or Quantity, default: 1.0) -- Time step for averaging in seconds.
exp (bool, default: False) -- If True, return a single complex TimeSeries ($mag cdot e^{iphi}$). If False (default), return a tuple of (magnitude, phase) TimeSeries.
deg (bool, default: True) -- If True, return phase in degrees; else radians.
- 戻り値:
out -- Demodulated result. If
exp=True, a complex TimeSeries. Ifexp=False, a tuple of (magnitude, phase) TimeSeries.- 戻り値の型:
TimeSeries or tuple
メモ
Phase Convention (GWpy-identical) The phase model is built as $phi(t) = 2pi f t$. The mixing operation is $x(t) cdot e^{-iphi(t)}$. The result is always multiplied by 2 (
singlesided=True) to recover the full amplitude of real signals, matching GWpy.参考
TimeSeries.heterodynefor the underlying heterodyne method with arbitrary phase.
TimeSeries.lock_infor a more flexible lock-in amplifier interface.
- detrend(detrend: Literal['constant', 'linear'] = 'constant') Self
Remove the trend from this TimeSeries.
This method just wraps
scipy.signal.detrend()to return an object of the same type as the input.- パラメータ:
detrend (str, optional) -- the type of detrending.
- 戻り値:
detrended -- the detrended input series
- 戻り値の型:
TimeSeries
参考
scipy.signal.detrendfor details on the options for the detrend argument, and how the operation is done
- device
- diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.
Refer to
numpy.diagonal()for full documentation.参考
numpy.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.- パラメータ:
- 戻り値:
diff -- The n order differences. The shape of the output is the same as the input, except along axis where the dimension is smaller by n.
- 戻り値の型:
Series
参考
numpy.diffFor documentation on the underlying method.
- distance_correlation(other)
Calculate Distance Correlation (dCor).
Distance correlation is a measure of dependence between two random vectors that is 0 if and only if the random vectors are independent. It can detect non-linear relationships.
- パラメータ:
other (TimeSeries) -- The series to compare with.
- 戻り値:
The distance correlation (0 to 1).
- 戻り値の型:
- dot(b, out=None)
- dtype: np.dtype[Any]
Data-type of the array's elements.
警告
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).- パラメータ:
None
- 戻り値:
d
- 戻り値の型:
numpy dtype object
参考
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.
サンプル
>>> 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 duration: Quantity
Duration of this series in seconds.
- Type:
~astropy.units.Quantity scalar
- ediff1d(to_end=None, to_begin=None)
- emd(*, method: str = 'eemd', max_imf: int | None = None, sift_max_iter: int = 1000, stopping_criterion: Any = 'default', eemd_noise_std: float = 0.2, eemd_trials: int = 100, random_state: int | None = None, return_residual: bool = True, eemd_parallel: bool | None = None, eemd_processes: int | None = None, eemd_noise_kind: str | None = None) Any
Decompose the TimeSeries using Empirical Mode Decomposition (EMD).
This method applies EMD or Ensemble EMD (EEMD) to decompose the signal into Intrinsic Mode Functions (IMFs) and a residual.
- パラメータ:
method (str, default='eemd') -- Decomposition method. Either 'emd' or 'eemd'.
max_imf (int or None, default=None) -- Maximum number of IMFs to extract. If None, extracts all.
sift_max_iter (int, default=1000) -- Maximum iterations per sifting process.
stopping_criterion (Any, default='default') -- If
'default'orNone, keep PyEMD defaults. If a numeric value, it is passed to PyEMD'sstd_thrstopping criterion. Other types are not supported.eemd_noise_std (float, default=0.2) -- Standard deviation of added noise for EEMD (ratio of signal std).
eemd_trials (int, default=100) -- Number of ensemble trials for EEMD.
random_state (int or None, default=None) -- Random seed for reproducibility. If provided and the decomposer supports
noise_seed(), it will be used. Otherwise, NumPy's random state is temporarily set and restored.return_residual (bool, default=True) -- If True, include the residual in the output.
eemd_parallel (bool or None, default=None) -- Enable parallel processing for EEMD. If None, uses PyEMD default.
eemd_processes (int or None, default=None) -- Number of processes for parallel EEMD. If None, uses PyEMD default.
eemd_noise_kind (str or None, default=None) -- Type of noise for EEMD ('normal', 'uniform'). If None, uses default.
- 戻り値:
Dictionary containing IMFs (keys: 'IMF1', 'IMF2', ...) and optionally 'residual'.
- 戻り値の型:
TimeSeriesDict
- 例外:
ImportError -- If PyEMD is not installed.
ValueError -- If an unknown method is specified or no IMFs are extracted.
メモ
Optional Dependency: Requires the
PyEMDpackage.EEMD Stochasticity: EEMD adds noise to the signal and performs multiple decompositions. Results may vary between runs unless
random_stateis specified.Endpoint Artifacts: EMD envelope extrapolation can cause artifacts at signal boundaries. Consider padding or cropping edges in downstream analysis.
Residual Handling: The residual is extracted using PyEMD's
get_imfs_and_residue()method if available, otherwise via theresidueattribute. This ensures correct IMF count.サンプル
>>> ts = TimeSeries(data, dt=0.01, unit='V') >>> imfs = ts.emd(method='eemd', eemd_trials=50, random_state=42) >>> for key, imf in imfs.items(): ... print(f"{key}: {imf.shape}")
- envelope(*args: Any, **kwargs: Any) TimeSeriesSignalMixin
Compute the envelope (amplitude) of the TimeSeries via Hilbert transform.
- property epoch: Time | None
GPS epoch for these data.
This attribute is stored internally by the t0 attribute.
- property equivalencies
A list of equivalencies that will be applied by default during unit conversions.
- fastmi(other, **kwargs)
Estimate mutual information using a fast copula/probit + FFT-based estimator.
- classmethod fetch(channel: str | Channel, start: SupportsToGps, end: SupportsToGps, *, host: str | None = None, port: int | None = None, verbose: bool | str = False, connection: nds2.connection | None = None, verify: bool = False, pad: float | None = None, allow_tape: bool | None = None, scaled: bool | None = None, type: int | str | None = None, dtype: int | str | None = None) Self
Fetch data from NDS.
- パラメータ:
channel (str, ~gwpy.detector.Channel) -- The name (or representation) of the data channel to fetch.
start (~gwpy.time.LIGOTimeGPS, float, str) -- GPS start time of required data, any input parseable by ~gwpy.time.to_gps is fine
end (~gwpy.time.LIGOTimeGPS, float, str, optional) -- GPS end time of required data, defaults to end of data found; any input parseable by ~gwpy.time.to_gps is fine
host (str, optional) --
URL of NDS server to use, if blank will try any server (in a relatively sensible order) to get the data
One of
connectionorhostmust be given.port (int, optional) -- Port number for NDS server query, must be given with host.
verify (bool, optional) -- Check channels exist in database before asking for data. Default is True.
verbose (bool, optional) -- This argument is deprecated and will be removed in a future release. Use DEBUG-level logging instead, see Logging with GWpy.
connection (nds2.connection, optional) --
Open NDS connection to use. Default is to open a new connection using
hostandportarguments.One of
connectionorhostmust be given.pad (float, optional) -- Float value to insert between gaps. Default behaviour is to raise an exception when any gaps are found.
scaled (bool, optional) -- Apply slope and bias calibration to ADC data, for non-ADC data this option has no effect.
allow_tape (bool, optional) -- Allow data access from slow tapes. If
hostorconnectionis given, the default is to do whatever the server default is, otherwise servers will be searched withallow_tape=Falsefirst, thenallow_tape=Trueif that fails.type (int, str, optional) -- NDS2 channel type integer or string name to match. Default is to search for any channel type.
dtype (numpy.dtype, str, type, or dict, optional) -- NDS2 data type to match. Default is to search for any data type.
- classmethod fetch_open_data(ifo: str, start: SupportsToGps, end: SupportsToGps, sample_rate: float = 4096, version: int | None = None, format: Literal['gwf', 'hdf5'] = 'hdf5', host: str = 'https://gwosc.org', *, verbose: bool | None = None, cache: bool | None = None, **kwargs) Self
Fetch open-access data from GWOSC.
This is just a shim around
TimeSeries.get(..., source='gwosc').- パラメータ:
ifo (str) -- The two-character prefix of the IFO in which you are interested, e.g. 'L1'.
start (~gwpy.time.LIGOTimeGPS, float, str, optional) -- GPS start time of required data, defaults to start of data found; any input parseable by ~gwpy.time.to_gps is fine.
end (~gwpy.time.LIGOTimeGPS, float, str, optional) -- GPS end time of required data, defaults to end of data found; any input parseable by ~gwpy.time.to_gps is fine.
sample_rate (float, optional,) -- The sample rate of desired data; most data are stored by GWOSC at 4096 Hz, however there may be event-related data releases with a 16384 Hz rate, default: 4096.
version (int, optional) -- Version of files to download, defaults to highest discovered version.
format (str, optional) --
The data format to download and parse, default:
'h5py''hdf5''gwf'- requires LALFrame
host (str, optional) -- HTTP host name of GWOSC server to access.
verbose (bool, optional) -- This argument is deprecated and will be removed in a future release. Use DEBUG-level logging instead, see Logging with GWpy.
cache (bool, optional) -- Save/read a local copy of the remote URL, default: False; useful if the same remote data are to be accessed multiple times. Set
GWPY_CACHE=1in the environment to auto-cache.timeout (float, optional) -- The time to wait for a response from the GWOSC server.
kwargs -- Any other keyword arguments are passed to the TimeSeries.read method that parses the file that was downloaded.
サンプル
>>> from gwpy.timeseries import (TimeSeries, StateVector) >>> print(TimeSeries.fetch_open_data('H1', 1126259446, 1126259478)) TimeSeries([ 2.17704028e-19, 2.08763900e-19, 2.39681183e-19, ..., 3.55365541e-20, 6.33533516e-20, 7.58121195e-20] unit: Unit(dimensionless), t0: 1126259446.0 s, dt: 0.000244140625 s, name: Strain, channel: None) >>> print(StateVector.fetch_open_data('H1', 1126259446, 1126259478)) StateVector([127,127,127,127,127,127,127,127,127,127,127,127, 127,127,127,127,127,127,127,127,127,127,127,127, 127,127,127,127,127,127,127,127] unit: Unit(dimensionless), t0: 1126259446.0 s, dt: 1.0 s, name: quality/simple, channel: None, bits: Bits(0: data present 1: passes cbc CAT1 test 2: passes cbc CAT2 test 3: passes cbc CAT3 test 4: passes burst CAT1 test 5: passes burst CAT2 test 6: passes burst CAT3 test, channel=None, epoch=1126259446.0))
For the StateVector, the naming of the bits will be
format-dependent, because they are recorded differently by GWOSC in different formats.メモ
StateVector data are not available in
txt.gzformat.
- fft(nfft: NumberLike | None = None, *, mode: Literal['gwpy', 'transient'] = 'gwpy', pad_mode: Literal['zero', 'reflect'] = 'zero', pad_left: NumberLike = 0, pad_right: NumberLike = 0, nfft_mode: str | None = None, other_length: NumberLike | None = None, **kwargs: Any) FrequencySeries
Compute the Discrete Fourier Transform (DFT).
- パラメータ:
nfft (int, optional) -- Length of the FFT.
mode (str, optional) -- "gwpy": standard GWpy FFT (normalized). "transient": transient-restoration mode for round-trip IFFT.
pad_mode (str, optional) -- Padding mode ("zero", "reflect"). Only for "transient" mode.
pad_left (int, optional) -- Padding length (samples or seconds).
pad_right (int, optional) -- Padding length (samples or seconds).
nfft_mode (str, optional) -- "next_fast_len" for optimal performance.
other_length (int, optional) -- For convolution-like transforms.
**kwargs -- Additional keyword arguments forwarded to the output constructor.
- 戻り値の型:
FrequencySeries
- fftgram(fftlength: float, overlap: float | None = None, window: WindowLike = 'hann', **kwargs) Spectrogram
Calculate the Fourier-gram of this TimeSeries.
At every
stride, a single, complex FFT is calculated.- パラメータ:
fftlength (float) -- Number of seconds in single FFT.
overlap (float, optional) -- Number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0.
window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.kwargs -- Other keyword arguments are passed to the
scipy.signal.spectrogram()method.
- 戻り値:
spectrogram -- A Spectrogram containing the complex-valued output of 1D FFTs at every
stridein the input TimeSeries, with each column corresponding to a single FFT.- 戻り値の型:
~gwpy.spectrogram.Spectrogram
- fill(value)
- filter(filt: FilterCompatible, *, analog: bool = False, unit: str = 'rad/s', normalize_gain: bool = False, filtfilt: bool = True, **kwargs) Self
Filter this TimeSeries with an IIR or FIR filter.
- パラメータ:
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.
filtfilt (bool, optional) -- Filter forward and backwards to preserve phase, default: False.
analog (bool, optional) -- If True, filter coefficients will be converted from Hz to Z-domain digital representation, default: False.
inplace (bool, optional) -- If True, this array will be overwritten with the filtered version, default: False.
- unitstr, optional
For analogue ZPK filters, the units in which the zeros and poles are specified. Either
'Hz'or'rad/s'(default).- normalize_gainbool, 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").- kwargs
Other keyword arguments are passed to the filter method.
- 戻り値:
result -- The filtered version of the input TimeSeries.
- 戻り値の型:
TimeSeries
メモ
IIR filters are converted into digital cascading second-order sections before being applied to the data.
FIR filters are passed directly to
scipy.signal.lfilter()orscipy.signal.filtfilt()without any conversions.参考
scipy.signal.sosfiltFor details on filtering with second-order sections.
scipy.signal.sosfiltfiltFor details on forward-backward filtering with second-order sections
scipy.signal.lfilterFor details on filtering (without SOS).
scipy.signal.filtfiltFor details on forward-backward filtering (without SOS).
- 例外:
ValueError -- If
filtarguments cannot be interpreted properly.
サンプル
We can design an arbitrarily complicated filter using
gwpy.signal.filter_design>>> from gwpy.signal import filter_design >>> bp = filter_design.bandpass(50, 250, 4096.) >>> notches = [filter_design.notch(f, 4096.) for f in (60, 120, 180)] >>> zpk = filter_design.concatenate_zpks(bp, *notches)
And then can download some data from GWOSC to apply it using TimeSeries.filter:
>>> from gwpy.timeseries import TimeSeries >>> data = TimeSeries.fetch_open_data('H1', 1126259446, 1126259478) >>> filtered = data.filter(zpk, filtfilt=True)
We can plot the original signal, and the filtered version, cutting off either end of the filtered data to remove filter-edge artefacts
>>> from gwpy.plot import Plot >>> plot = Plot(data, filtered[128:-128], separate=True) >>> plot.show()
- classmethod find(channel: str | Channel, start: SupportsToGps, end: SupportsToGps, *, observatory: str | None = None, frametype: str | None = None, frametype_match: str | re.Pattern | None = None, host: str | None = None, urltype: str | None = 'file', ext: str = 'gwf', pad: float | None = None, scaled: bool | None = None, allow_tape: bool | None = None, parallel: int = 1, verbose: bool | str = False, **readargs) Self
Find and return data for multiple channels using GWDataFind.
This method uses
gwdatafindto discover the URLs that provide the requested data, then reads those files usingTimeSeriesDict.read().This is just a shim around
TimeSeries.get(..., source='gwdatafind').- パラメータ:
channel (str) -- Name of data channel to find.
start (~gwpy.time.LIGOTimeGPS, float, str) -- GPS start time of required data, any input parseable by ~gwpy.time.to_gps is fine.
end (~gwpy.time.LIGOTimeGPS, float, str) -- GPS end time of required data, defaults to end of data found; any input parseable by ~gwpy.time.to_gps is fine.
observatory (str, optional) -- The observatory to use when searching for data. Default is to use the observatory from the channel name prefix, but this should be specified when searching for data in a multi-observatory dataset (e.g. observatory='HLV').
frametype (str, optional) -- Name of frametype (dataset) in which this channel is stored. Default is to search all available datasets for a match, which can be very slow.
frametype_match (str, optional) -- Regular expression to use for frametype matching.
host (str, optional) -- Name of the GWDataFind server to use. Default is set by gwdatafind.utils.get_default_host.
urltype (str, optional) -- The URL type to use. Default is "file" to use paths available on the file system.
ext (str, optional) -- The file extension for which to search. "gwf" is the only file extension supported, but this may be extended in the future.
pad (float, optional) -- Value with which to fill gaps in the source data, by default gaps will result in a ValueError.
scaled (bool, optional) -- Apply slope and bias calibration to ADC data, for non-ADC data this option has no effect.
parallel (int, optional) -- Number of parallel processes to use.
allow_tape (bool, optional) -- Allow reading from frame files on (slow) magnetic tape.
verbose (bool, optional) -- This argument is deprecated and will be removed in a future release. Use DEBUG-level logging instead, see Logging with GWpy.
readargs -- Any other keyword arguments to be passed to .read().
- find_gates(tzero: float = 1.0, *, whiten: bool = True, threshold: float = 50.0, cluster_window: float = 0.5, **whiten_kwargs) SegmentList
Identify points that should be gates using a provided threshold.
This method identifies points in the TimeSeries that exceed a provided threshold, and returns a list of segments that should be gated. The gating points are clustered within a provided time window.
This method is useful for identifying high amplitude peaks in the data that should be removed or masked out.
- パラメータ:
tzero (int, optional) -- Half-width time duration (seconds) in which the timeseries is set to zero.
whiten (bool, optional) -- If True, data will be whitened before gating points are discovered, use of this option is highly recommended.
threshold (float, optional) -- Amplitude threshold, if the data exceeds this value a gating window will be placed.
cluster_window (float, optional) -- Time duration (seconds) over which gating points will be clustered.
whiten_kwargs -- Other keyword arguments will be passed to the TimeSeries.whiten method if it is being used when discovering gating points.
- 戻り値:
out -- A list of segments that should be gated based on the provided parameters.
- 戻り値の型:
~gwpy.segments.SegmentList
参考
TimeSeries.gateFor a method that applies the identified gates.
- find_peaks(height: Any | None = None, threshold: Any | None = None, distance: Any | None = None, prominence: Any | None = None, width: Any | None = None, method: str = 'amplitude', **kwargs: Any) Any
Find peaks in the series.
Wraps scipy.signal.find_peaks with support for unit quantities.
- fit(model: Any, x_range: tuple[float, float] | None = None, sigma: Any | None = None, p0: dict[str, float] | None = None, limits: dict[str, tuple[float, float]] | None = None, fixed: Iterable[str] | None = None, **kwargs: Any) Any
Fit the data to a model using iminuit.
- パラメータ:
model (callable or str) -- The model function to fit. Can be a callable with signature
f(x, p1, p2, ...)or a string name of a pre-defined model.x_range (tuple of float, optional) -- The (min, max) range of the x-axis to include in the fit.
sigma (array-like or scalar, optional) -- The errors or weights for the data points.
p0 (dict, optional) -- Initial guesses for the parameter values.
limits (dict, optional) -- Lower and upper bounds for parameters.
fixed (iterable of str, optional) -- Names of parameters to keep fixed during the fit.
**kwargs -- Additional arguments passed to the fitting engine.
- 戻り値:
An object containing the fit results, including best-fit parameters, errors, and plotting methods.
- 戻り値の型:
- fit_arima(order: tuple = (1, 0, 0), **kwargs: Any) Any
Fit ARIMA model to the series.
- パラメータ:
order (tuple) -- (p, d, q) order of the ARIMA model.
**kwargs -- Additional arguments passed to the ARIMA fitting function.
- 戻り値:
Fitted model result.
- 戻り値の型:
ARIMAResult
参考
gwexpy.timeseries.arima.fit_arima
- flags
Information about the memory layout of the array.
- 変数:
(C) (C_CONTIGUOUS) -- The data is in a single, C-style contiguous segment.
(F) (F_CONTIGUOUS) -- The data is in a single, Fortran-style contiguous segment.
(O) (OWNDATA) -- The array owns the memory it uses or borrows it from another object.
(W) (WRITEABLE) -- The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.
(A) (ALIGNED) -- The data and all elements are aligned appropriately for the hardware.
(X) (WRITEBACKIFCOPY) -- This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.
FNC -- F_CONTIGUOUS and not C_CONTIGUOUS.
FORC -- F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
(B) (BEHAVED) -- ALIGNED and WRITEABLE.
(CA) (CARRAY) -- BEHAVED and C_CONTIGUOUS.
(FA) (FARRAY) -- BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
メモ
The flags object can be accessed dictionary-like (as in
a.flags['WRITEABLE']), or by using lowercased attribute names (as 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.
- パラメータ:
order ({'C', 'F', 'A', 'K'}) -- 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran- style) order. 'A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. 'K' means to flatten a in the order the elements occur in memory. The default is 'C'.
- 戻り値:
y -- A copy of the input array, flattened to one dimension.
- 戻り値の型:
~astropy.units.Quantity
参考
ravelReturn a flattened array.
flatA 1-D flat iterator over the array.
サンプル
>>> a = Array([[1,2], [3,4]], unit='m', name='Test') >>> a.flatten() <Quantity [1., 2., 3., 4.] m>
- classmethod from_arrakis(series: arrakis.block.Series, *, copy: bool = True, **metadata) Self
Construct a new series from an arrakis.Series object.
- パラメータ:
series (arrakis.Series) -- The input Arrakis data series to read.
copy (bool, optional) -- If True, copy the contained data array to new to a new array.
metadata -- Any other metadata keyword arguments to pass to the TimeSeries constructor.
- 戻り値:
timeseries -- A new TimeSeries containing the data from the arrakis.Series and the appropriate metadata.
- 戻り値の型:
TimeSeries
- classmethod from_astropy_timeseries(ap_ts: Any, column: str = 'value', unit: Any | None = None) Any
Create from astropy.timeseries.TimeSeries.
- パラメータ:
ap_ts (astropy.timeseries.TimeSeries) -- Input TimeSeries.
column (str) -- Column name containing data.
unit (Unit, optional) -- Physical unit.
- 戻り値の型:
- classmethod from_cupy(array: Any, *, t0: Any = None, dt: Any = None, unit: Any | None = None) Any
Create from cupy array.
- パラメータ:
array (cupy.ndarray) -- Input array.
t0 (required) -- Time parameters.
dt (required) -- Time parameters.
unit (Unit, optional) -- Physical unit.
- 戻り値の型:
- classmethod from_dask(array: Any, *, t0: Any = None, dt: Any = None, unit: Any | None = None, compute: bool = True) Any
Create from dask.array.
- パラメータ:
array (dask.array.Array) -- Input array.
t0 (required) -- Time parameters.
dt (required) -- Time parameters.
unit (Unit, optional) -- Physical unit.
compute (bool) -- Whether to compute immediately.
- 戻り値の型:
- classmethod from_dict(data_dict: dict, *, unit: Any | None = None, channel: Any | None = None, name: Any | None = None, t0: Any | None = None, dt: Any | None = None) Any
Create TimeSeries from a dictionary.
- パラメータ:
data_dict (dict) -- Dictionary representation.
unit (optional) -- Metadata to assign when absent from the dictionary; an explicit value takes priority over a value stored in
data_dict.channel (optional) -- Metadata to assign when absent from the dictionary; an explicit value takes priority over a value stored in
data_dict.name (optional) -- Metadata to assign when absent from the dictionary; an explicit value takes priority over a value stored in
data_dict.t0 (optional) -- Metadata to assign when absent from the dictionary; an explicit value takes priority over a value stored in
data_dict.dt (optional) -- Metadata to assign when absent from the dictionary; an explicit value takes priority over a value stored in
data_dict.
- 戻り値の型:
- classmethod from_hdf5_dataset(group: Any, path: str, *, unit: Any | None = None, channel: Any | None = None, name: Any | None = None, t0: Any | None = None, dt: Any | None = None) Any
Read from HDF5 group/dataset.
- パラメータ:
group (h5py.Group or h5py.File) -- Source group.
path (str) -- Dataset path.
unit (optional) -- Metadata to assign when absent from the dataset attributes; an explicit value takes priority over a stored attribute.
channel (optional) -- Metadata to assign when absent from the dataset attributes; an explicit value takes priority over a stored attribute.
name (optional) -- Metadata to assign when absent from the dataset attributes; an explicit value takes priority over a stored attribute.
t0 (optional) -- Metadata to assign when absent from the dataset attributes; an explicit value takes priority over a stored attribute.
dt (optional) -- Metadata to assign when absent from the dataset attributes; an explicit value takes priority over a stored attribute.
- 戻り値の型:
- classmethod from_jax(array: Any, *, t0: Any = None, dt: Any = None, unit: Any | None = None) Any
Create from jax array.
- パラメータ:
array (jax.numpy.ndarray) -- Input array.
t0 (required) -- Time parameters.
dt (required) -- Time parameters.
unit (Unit, optional) -- Physical unit.
- 戻り値の型:
- classmethod from_json(json_str: str, *, unit: Any | None = None, channel: Any | None = None, name: Any | None = None, t0: Any | None = None, dt: Any | None = None) Any
Create TimeSeries from a JSON string.
- パラメータ:
json_str (str) -- JSON representation.
unit (optional) -- Metadata to assign when absent from the payload; an explicit value takes priority over a value stored in the JSON.
channel (optional) -- Metadata to assign when absent from the payload; an explicit value takes priority over a value stored in the JSON.
name (optional) -- Metadata to assign when absent from the payload; an explicit value takes priority over a value stored in the JSON.
t0 (optional) -- Metadata to assign when absent from the payload; an explicit value takes priority over a value stored in the JSON.
dt (optional) -- Metadata to assign when absent from the payload; an explicit value takes priority over a value stored in the JSON.
- 戻り値の型:
- classmethod from_lal(lalts: LALTimeSeriesType, *, copy: bool = True) Self
Generate a new TimeSeries from a LAL TimeSeries of any type.
- classmethod from_mne(raw: Any, channel: str, *, unit: Any | None = None) Any
Create TimeSeries from mne.io.Raw.
- パラメータ:
raw (mne.io.Raw) -- Input MNE data.
channel (str) -- Channel name to extract. REQUIRED.
unit (Unit, optional) -- Physical unit.
- 戻り値の型:
- classmethod from_nds2_buffer(buffer: nds2.buffer, *, scaled: bool | None = None, copy: bool = True, **metadata) Self
Construct a new series from an nds2.buffer object.
Requires: NDS2
- パラメータ:
buffer (nds2.buffer) -- The input NDS2-client buffer to read.
scaled (bool, optional) -- Apply slope and bias calibration to ADC data, for non-ADC data this option has no effect.
copy (bool, optional) -- Tf True, copy the contained data array to new to a new array.
metadata -- Any other metadata keyword arguments to pass to the TimeSeries constructor.
- 戻り値:
timeseries -- A new TimeSeries containing the data from the nds2.buffer, and the appropriate metadata.
- 戻り値の型:
TimeSeries
- classmethod from_netcdf4(ds: Any, var_name: str, *, unit: Any | None = None, channel: Any | None = None, name: Any | None = None, t0: Any | None = None, dt: Any | None = None) Any
Read from a live netCDF4 Dataset object.
- パラメータ:
ds (netCDF4.Dataset) -- Source dataset.
var_name (str) -- Variable name.
unit (optional) -- Metadata to assign when absent from the variable attributes; an explicit value takes priority over a stored attribute.
channel (optional) -- Metadata to assign when absent from the variable attributes; an explicit value takes priority over a stored attribute.
name (optional) -- Metadata to assign when absent from the variable attributes; an explicit value takes priority over a stored attribute.
t0 (optional) -- Metadata to assign when absent from the variable attributes; an explicit value takes priority over a stored attribute.
dt (optional) -- Metadata to assign when absent from the variable attributes; an explicit value takes priority over a stored attribute.
- 戻り値の型:
- classmethod from_obspy(tr: Any, *, unit: Any | None = None, name_policy: str = 'id') Any
Create TimeSeries from obspy.Trace.
Accepts a single-trace
obspy.Streamas well. A multi-traceStreamraises aTypeErrordirecting toTimeSeriesDict.from_obspy.- パラメータ:
tr (obspy.Trace or obspy.Stream) -- Input trace (or a Stream containing exactly one trace).
unit (Unit, optional) -- Physical unit.
name_policy (str) -- How to derive name: 'id', 'station', etc.
- 戻り値の型:
- classmethod from_obspy_trace(tr: Any, *, unit: Any | None = None, name_policy: str = 'id') Any
Alias for from_obspy().
- classmethod from_pandas(series: Any, *, unit: Any | None = None, t0: Any = None, dt: Any = None, channel: Any | None = None, name: Any | None = None) Any
Create TimeSeries from pandas.Series.
- パラメータ:
series (pandas.Series) -- Input series.
unit (Unit, optional) -- Physical unit of the data.
t0 (Quantity or float, optional) -- Start time.
dt (Quantity or float, optional) -- Sample interval.
channel (str or Channel, optional) -- Channel to assign (a plain Series cannot carry one).
name (str, optional) -- Name to assign (overrides
series.name).
- 戻り値の型:
- classmethod from_polars(data: Any, times: str | None = 'time', unit: Any | None = None, *, channel: Any | None = None, name: Any | None = None, t0: Any | None = None, dt: Any | None = None) Any
Create TimeSeries from polars.DataFrame or polars.Series.
- パラメータ:
data (polars.DataFrame or polars.Series) -- Input data.
times (str, optional) -- If data is a DataFrame, name of the column to use as time.
unit (Unit, optional) -- Physical unit.
channel (optional) -- Metadata to assign (a polars object cannot carry channel/name).
name (optional) -- Metadata to assign (a polars object cannot carry channel/name).
t0 (optional) -- Timing to assign for a plain Series; ignored for a DataFrame, where they are inferred from the time column.
dt (optional) -- Timing to assign for a plain Series; ignored for a DataFrame, where they are inferred from the time column.
- 戻り値の型:
- classmethod from_pycbc(pycbcseries: pycbc.types.TimeSeries, *, copy: bool = True) Self
Convert a pycbc.types.timeseries.TimeSeries into a TimeSeries.
- パラメータ:
pycbcseries (pycbc.types.timeseries.TimeSeries) -- The input PyCBC ~pycbc.types.timeseries.TimeSeries array.
copy (bool, optional) -- If True, copy these data to a new array.
- 戻り値:
timeseries -- A GWpy version of the input timeseries.
- 戻り値の型:
TimeSeries
- classmethod from_pydub(seg: Any, *, unit: Any | None = None) Any
Create from pydub.AudioSegment.
- パラメータ:
seg (pydub.AudioSegment) -- Input audio segment.
unit (Unit, optional) -- Physical unit.
- 戻り値の型:
- classmethod from_pyroomacoustics_mic_signals(room: Any, *, mic: int | None = None, unit: Any | None = None) Any
Create from pyroomacoustics simulated microphone signals.
- パラメータ:
room (pyroomacoustics.Room) -- Room object after
simulate()has been called.mic (int, optional) -- Microphone index. If None, all microphones are returned as a
TimeSeriesDict.unit (str or astropy.units.Unit, optional) -- Unit to assign to the result.
- 戻り値の型:
TimeSeries or TimeSeriesDict
- classmethod from_pyroomacoustics_rir(room: Any, *, source: int | None = None, mic: int | None = None, unit: Any | None = None) Any
Create from pyroomacoustics room impulse responses.
- パラメータ:
room (pyroomacoustics.Room) -- Room object after
compute_rir()orsimulate()has been called.source (int, optional) -- Source index. If None and mic is also None, all pairs are returned as a
TimeSeriesDict.mic (int, optional) -- Microphone index.
unit (str or astropy.units.Unit, optional) -- Unit to assign to the result.
- 戻り値の型:
TimeSeries or TimeSeriesDict
- classmethod from_pyroomacoustics_source(room: Any, *, source: int = 0, unit: Any | None = None) Any
Create from a pyroomacoustics sound source signal.
- パラメータ:
room (pyroomacoustics.Room) -- Room object with at least one source added.
source (int, default 0) -- Source index.
unit (str or astropy.units.Unit, optional) -- Unit to assign to the result.
- 戻り値の型:
- classmethod from_pyspice_transient(analysis: Any, *, node: str | None = None, branch: str | None = None, unit: Any | None = None) Any
Create from a PySpice TransientAnalysis.
- パラメータ:
analysis (PySpice.Spice.Simulation.TransientAnalysis) -- The transient analysis result from a PySpice simulation.
node (str, optional) -- Node name to extract. If None and branch is also None, all nodes and branches are returned as a
TimeSeriesDict.branch (str, optional) -- Branch name to extract (e.g. the name of a voltage source for current measurement). Cannot be combined with node.
unit (str or astropy.units.Unit, optional) -- Unit to assign to the result.
- 戻り値の型:
TimeSeries or TimeSeriesDict
- classmethod from_root(obj: Any, return_error: bool = False) Any
Create TimeSeries from ROOT TGraph or TH1.
- パラメータ:
obj (ROOT.TGraph or ROOT.TH1) -- Input ROOT object.
return_error (bool, default False) -- If True, return (series, error_series).
- 戻り値の型:
TimeSeries or tuple of TimeSeries
- classmethod from_skrf_impulse_response(ntwk: Any, *, port_pair: tuple[int, int] | None = None, n: int | None = None, pad: int = 0, unit: Any | None = None) Any
Create from a scikit-rf Network impulse response.
- パラメータ:
ntwk (skrf.Network) -- The scikit-rf Network object.
port_pair (tuple[int, int], optional) -- Zero-based
(row, col)port indices to compute the impulse response for. If None, all port pairs are computed and aTimeSeriesDictis returned for multi-port networks.n (int, optional) -- Number of IFFT points. See
Network.impulse_response.pad (int, default 0) -- Number of zero-padding points.
unit (str or astropy.units.Unit, optional) -- Unit to assign to the result.
- 戻り値の型:
TimeSeries or TimeSeriesDict
- classmethod from_skrf_step_response(ntwk: Any, *, port_pair: tuple[int, int] | None = None, n: int | None = None, pad: int = 0, unit: Any | None = None) Any
Create from a scikit-rf Network step response.
- パラメータ:
ntwk (skrf.Network) -- The scikit-rf Network object.
port_pair (tuple[int, int], optional) -- Zero-based
(row, col)port indices to compute the step response for. If None, all port pairs are computed and aTimeSeriesDictis returned for multi-port networks.n (int, optional) -- Number of IFFT points. See
Network.step_response.pad (int, default 0) -- Number of zero-padding points.
unit (str or astropy.units.Unit, optional) -- Unit to assign to the result.
- 戻り値の型:
TimeSeries or TimeSeriesDict
- classmethod from_sqlite(conn: Any, series_id: Any) Any
Load from sqlite3 database.
- パラメータ:
conn (sqlite3.Connection) -- Database connection.
series_id (str) -- Identifier for the series.
- 戻り値の型:
- classmethod from_tensorflow(tensor: Any, *, t0: Any = None, dt: Any = None, unit: Any | None = None) Any
Create from tensorflow.Tensor.
- パラメータ:
tensor (tensorflow.Tensor) -- Input tensor.
t0 (required) -- Time parameters.
dt (required) -- Time parameters.
unit (Unit, optional) -- Physical unit.
- 戻り値の型:
- classmethod from_torch(tensor: Any, *, t0: Any = None, dt: Any = None, unit: Any | None = None) Any
Create from torch.Tensor.
- パラメータ:
- 戻り値の型:
- classmethod from_xarray(da: Any, *, unit: Any | None = None, channel: Any | None = None, name: Any | None = None) Any
Create TimeSeries from xarray.DataArray.
- パラメータ:
- 戻り値の型:
- gate(tzero: float = 1.0, tpad: float = 0.5, *, whiten: bool = True, threshold: float = 50.0, cluster_window: float = 0.5, **whiten_kwargs) Self
Remove high amplitude peaks from data using inverse Tukey window.
Points will be discovered automatically using a provided threshold and clustered within a provided time window.
- パラメータ:
tzero (int, optional) -- Half-width time duration (seconds) in which the timeseries is set to zero.
tpad (int, optional) -- Half-width time duration (seconds) in which the Tukey window is tapered.
whiten (bool, optional) -- If True, data will be whitened before gating points are discovered, use of this option is highly recommended.
threshold (float, optional) -- Amplitude threshold, if the data exceeds this value a gating window will be placed.
cluster_window (float, optional) -- Time duration (seconds) over which gating points will be clustered.
whiten_kwargs -- Other keyword arguments will be passed to the TimeSeries.whiten method if it is being used when discovering gating points.
- 戻り値:
out -- A copy of the original TimeSeries that has had gating windows applied.
- 戻り値の型:
~gwpy.timeseries.TimeSeries
サンプル
Read data into a TimeSeries
>>> from gwpy.timeseries import TimeSeries >>> data = TimeSeries.fetch_open_data('H1', 1135148571, 1135148771)
Apply gating using custom arguments
>>> gated = data.gate( ... tzero=1.0, ... tpad=1.0, ... threshold=10.0, ... fftlength=4, ... overlap=2, ... method='median', ... )
Plot the original data and the gated data, whiten both for visualization purposes
>>> overlay = data.whiten(4,2,method="median").plot( ... dpi=150, ... label="Ungated", ... color="dodgerblue", ... zorder=2, ... ) >>> ax = overlay.gca() >>> ax.plot( ... gated.whiten(4, 2, method="median"), ... label="Gated", ... color="orange", ... zorder=3, ... ) >>> ax.set_xlim(1135148661, 1135148681) >>> ax.legend() >>> overlay.show()
参考
TimeSeries.maskFor the method that masks out unwanted data.
TimeSeries.find_gatesFor the method that identifies gating points.
TimeSeries.whitenFor the whitening filter used to identify gating points.
- gauch(fftlength, window=40, stride=None, overlap=None, **kwargs)
Compute GauCh (Modified KS test) for non-Gaussianity detection.
Accepts rng= / seed= (forwarded to gwexpy.statistics.gauch.compute_gauch) for a reproducible Monte Carlo null distribution.
- 戻り値の型:
GauChResult
- get = <gwpy.timeseries.connect.TimeSeriesGet object>
- 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.
- パラメータ:
サンプル
>>> 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.]])
- granger_causality(other, maxlag=10, test='ssr_ftest', verbose=False)
Check if 'other' Granger-causes 'self'.
Null Hypothesis: The past values of 'other' do NOT help in predicting 'self'.
- パラメータ:
other (TimeSeries) -- The potential cause series.
maxlag (int) -- Maximum lag to check.
test (str) -- Statistical test to use ('ssr_ftest', 'ssr_chi2test', etc.).
verbose (bool) -- Whether to print verbose output.
- 戻り値:
- The minimum p-value across all lags up to maxlag.
A small p-value (e.g., < 0.05) indicates Granger causality.
- 戻り値の型:
- heterodyne(phase: ArrayLike, stride: float = 1, *, singlesided: bool = False) TimeSeries
Compute the average magnitude and phase of the TimeSeries after.
heterodyning with a given phase series.
This method replicates the GWpy
TimeSeries.heterodyne()algorithm exactly. The input TimeSeries is heterodyned against a phase series and averaged over fixed strides.- パラメータ:
phase (array_like or TimeSeries) -- Phase to mix with (radians). Must have
len(phase) == len(self).stride (float or Quantity, default: 1.0) -- Time step for averaging in seconds. Strides are rounded to the nearest number of samples (
int(stride * sample_rate)). Trailing samples that do not form a full stride are discarded.singlesided (bool, default: False) -- If True, double the amplitude of the output (conventional for real signals). Default is False, aligning with GWpy.
- 戻り値:
Complex demodulated signal with
dt = stride. The output value representsmag * exp(1j * phase_out)where mag/phase are the average magnitude and phase over each stride.- 戻り値の型:
- 例外:
TypeError -- If
phaseis not array_like (i.e.len(phase)fails).ValueError -- If
len(phase) != len(self).
メモ
Algorithm (GWpy-identical)
stridesamp = int(stride * self.sample_rate.value)(floor truncation)nsteps = int(self.size // stridesamp)(trailing samples discarded)For each step
stepinrange(nsteps):istart = stridesamp * stepiend = istart + stridesamp(exclusive end)mixed = exp(-1j * phase[istart:iend]) * self.value[istart:iend]out[step] = 2 * mixed.mean() if singlesided else mixed.mean()
Output
sample_rate = 1 / stride
参考
TimeSeries.demodulatefor heterodyning at a fixed frequency (GWpy)
TimeSeries.lock_infor a higher-level lock-in amplifier interface
- hht(*, emd_method: str = 'eemd', emd_kwargs: dict[str, Any] | None = None, hilbert_kwargs: dict[str, Any] | None = None, output: str = 'dict', n_bins: int = 100, freq_bins: Any = None, fmin: float | Quantity | None = None, fmax: float | Quantity | None = None, weight: str = 'ia2', if_policy: str = 'drop', finite_only: bool = True) Any
Perform Hilbert-Huang Transform (HHT) on the TimeSeries.
HHT combines Empirical Mode Decomposition (EMD) with Hilbert Spectral Analysis to create a time-frequency representation of non-stationary signals.
- パラメータ:
emd_method (str, default='eemd') -- EMD method to use ('emd' or 'eemd').
emd_kwargs (dict or None, default=None) -- Additional keyword arguments for
emd().hilbert_kwargs (dict or None, default=None) -- Additional keyword arguments for
hilbert_analysis(). Common options includepad,if_smooth.output (str, default='dict') -- Output format: 'dict' or 'spectrogram'.
output='spectrogram') (Spectrogram Options (only used when)
-------------------------------------------------------------
n_bins (int, default=100) -- Number of frequency bins (used if
freq_binsis None).freq_bins (array-like or Quantity, optional) -- Custom frequency bin edges. If provided, overrides
n_binsandfmin/fmax.fmin (float or Quantity, optional) -- Minimum frequency for binning (default: 0).
fmax (float or Quantity, optional) -- Maximum frequency for binning (default: Nyquist frequency).
weight ({'ia2', 'ia'}, default='ia2') -- Weighting for the spectrogram: - 'ia2': Squared instantaneous amplitude (power-like) - 'ia': Instantaneous amplitude (magnitude)
if_policy ({'drop', 'clip'}, default='drop') -- Policy for IF values outside frequency bins: - 'drop': Ignore out-of-range values - 'clip': Clip to nearest bin edge
finite_only (bool, default=True) -- If True, exclude NaN/Inf values in IF/IA during spectrogram binning. Note: This does not allow NaN in the original signal passed to EMD; it only affects Hilbert analysis output.
- 戻り値:
- If
output='dict': Dictionary with keys 'imfs', 'ia', 'if', 'residual'.
- If
output='spectrogram': GWpy Spectrogram representing the Hilbert spectrum.
- If
- 戻り値の型:
dict or Spectrogram
- 例外:
ImportError -- If PyEMD is not installed.
ValueError -- If EMD returns no IMFs or unknown output format specified.
メモ
Optional Dependency: Requires PyEMD for EMD decomposition.
What is HHT?: Unlike STFT or wavelet transforms, HHT provides instantaneous frequency estimates that can capture rapid frequency variations. The Hilbert spectrum (spectrogram output) is a binned representation of these IF curves, not a power spectral density.
Default Weighting: The default
weight='ia2'produces a power-like representation where energy is proportional to amplitude squared. Useweight='ia'for magnitude representation.Edge Artifacts: Both EMD envelope extrapolation and Hilbert transform can produce artifacts at boundaries. Consider: 1. Pre-padding the signal 2. Using
hilbert_kwargs={'pad': N}3. Cropping edges from the resultサンプル
>>> ts = TimeSeries(data, dt=0.01, unit='V') >>> # Dictionary output >>> result = ts.hht(emd_method='eemd', output='dict') >>> imfs = result['imfs'] >>> inst_freq = result['if']
>>> # Spectrogram output with custom settings >>> spec = ts.hht( ... output='spectrogram', ... n_bins=200, ... fmin=10, ... fmax=100, ... weight='ia', ... hilbert_kwargs={'pad': 100, 'if_smooth': 10} ... )
- highpass(frequency: float, gpass: float = 2, gstop: float = 30, fstop: float | None = None, type: Literal['fir', 'iir'] = 'iir', *, filtfilt: bool = True, **kwargs) TimeSeries
Filter this TimeSeries with a high-pass filter.
- パラメータ:
frequency (float) -- High-pass corner frequency.
gpass (float) -- The maximum loss in the passband (dB).
gstop (float) -- The minimum attenuation in the stopband (dB).
fstop (float) -- Stop-band edge frequency, defaults to
frequency * 1.5.type (str) -- The filter type, either
'iir'or'fir'.filtfilt (bool, optional) -- If True, apply the filter using a forward-backward filter design, otherwise apply the filter in a single pass. Defaults to True.
kwargs -- Other keyword arguments are passed to
gwpy.signal.filter_design.highpass().
- 戻り値:
hpseries -- A high-passed version of the input TimeSeries.
- 戻り値の型:
TimeSeries
参考
gwpy.signal.filter_design.highpassFor details on the filter design.
TimeSeries.filterFor details on how the filter is applied.
- hilbert(pad: int | float | number | Quantity = 0, pad_mode: str = 'reflect', pad_value: float = 0.0, nan_policy: Literal['raise', 'propagate'] = 'raise', copy: bool = True) TimeSeriesSignalMixin
Compute the analytic signal via Hilbert transform.
For a real input x(t), returns the complex analytic signal:
z(t) = x(t) + i * H[x(t)]
where H[x] is the Hilbert transform of x, computed via SciPy.
If input is already complex, returns a copy.
- パラメータ:
pad (int or Quantity, default=0) -- Number of samples (or time duration) to pad on each side before applying the Hilbert transform. Padding can help reduce endpoint artifacts. Default is 0 (no padding).
pad_mode (str, default='reflect') -- Padding mode ('reflect', 'constant', 'edge', etc.).
pad_value (float, default=0.0) -- Value for 'constant' padding mode.
nan_policy ({'raise', 'propagate'}, default='raise') -- How to handle NaNs/Infs: 'raise' raises ValueError (default), 'propagate' allows NaNs to propagate through.
copy (bool, default=True) -- If input is complex, whether to return a copy.
- 戻り値:
Complex analytic signal with the same length as input.
- 戻り値の型:
- 例外:
ValueError -- If input contains NaN or infinite values and nan_policy='raise'.
ValueError -- If the TimeSeries has irregular sampling.
メモ
Preprocessing: This method does NOT apply any automatic preprocessing. Users should apply demean, detrend, filtering, or windowing as needed before calling this method.
Endpoint artifacts: The Hilbert transform can exhibit artifacts at the edges due to spectral leakage. Use padding or window the data appropriately if edge effects are a concern.
Mathematical definition: The Hilbert transform H[x] is defined as the convolution of x(t) with 1/(πt). The analytic signal z(t) has the property that its Fourier transform is zero for negative frequencies.
サンプル
>>> ts = TimeSeries(np.sin(2 * np.pi * 10 * np.linspace(0, 1, 1000)), ... dt=0.001, unit='V') >>> analytic = ts.hilbert() >>> envelope = np.abs(analytic.value)
- hilbert_analysis(*, unwrap_phase: bool = True, frequency_unit: str = 'Hz', if_smooth: int | Quantity | None = None, **hilbert_kwargs: Any) dict[str, Any]
Perform Hilbert analysis to extract instantaneous amplitude, phase, and frequency.
This method computes the analytic signal via Hilbert transform and extracts the instantaneous amplitude (IA), phase, and frequency (IF).
- パラメータ:
unwrap_phase (bool, default=True) -- If True, unwrap the phase to remove discontinuities.
frequency_unit (str, default='Hz') -- Unit for the instantaneous frequency output.
if_smooth (int, Quantity, or None, default=None) -- Optional smoothing window for instantaneous frequency. If int, number of samples. If Quantity, time duration. Applies a simple moving average filter. Odd window lengths are recommended; even values are automatically incremented.
**hilbert_kwargs -- Additional keyword arguments passed to
hilbert(). Common options include: -pad: Samples or duration to pad (reduces edge effects) -pad_mode: Padding mode ('reflect', 'constant', etc.) -nan_policy: How to handle NaN values
- 戻り値:
Dictionary containing: - 'analytic': Complex analytic signal - 'amplitude': Instantaneous amplitude (envelope) - 'phase': Instantaneous phase (radians, optionally unwrapped) - 'frequency': Instantaneous frequency
- 戻り値の型:
- 例外:
ValueError -- If dt is not defined.
メモ
Edge Effects: Both the Hilbert transform and numerical differentiation introduce artifacts at signal boundaries. Use the
padparameter to mitigate, or crop the output edges in downstream analysis.IF Calculation: Instantaneous frequency is computed as:
IF = (1 / 2π) * d(phase) / dt
This can be noisy for complex signals. Use
if_smoothto apply post-hoc smoothing.Padding: To reduce edge effects, pass
pad=Nwhere N is the number of samples (or a duration Quantity) to pad on each side before the Hilbert transform.サンプル
>>> ts = TimeSeries(np.sin(2 * np.pi * 10 * t), dt=0.001, unit='V') >>> result = ts.hilbert_analysis(pad=100, if_smooth=10) >>> amplitude = result['amplitude'] >>> frequency = result['frequency']
- histogram(bins=None, range=None, weights=None, density=False, **kwargs)
Compute a histogram of the values in this TimeSeries.
- パラメータ:
bins (int or sequence or str, optional) -- Binning specification (passed to np.histogram).
range ((float, float), optional) -- The lower and upper range of the bins.
weights (array_like, optional) -- Weights for each sample.
density (bool, optional) -- If True, return a probability density histogram.
**kwargs -- Additional arguments passed to np.histogram.
- 戻り値:
A gwexpy.histogram.Histogram object.
- 戻り値の型:
- hurst(**kwargs: Any) Any
Compute Hurst exponent.
The Hurst exponent is a measure of long-term memory of a time series. H < 0.5: anti-persistent (mean-reverting) H = 0.5: random walk H > 0.5: persistent (trending)
- 戻り値:
Hurst exponent.
- 戻り値の型:
参考
gwexpy.timeseries.hurst.hurst
- imag
The imaginary part of the array.
サンプル
>>> import numpy as np >>> x = np.sqrt([1+0j, 0+1j]) >>> x.imag array([ 0. , 0.70710678]) >>> x.imag.dtype dtype('float64')
- impute(*, method: str = 'linear', limit: int | None = None, axis: int | str = 'time', max_gap: float | u.Quantity | None = None, **kwargs: Any) TimeSeries
Impute missing values.
- パラメータ:
method (str) -- Interpolation method: 'linear', 'nearest', 'ffill', 'bfill', etc.
limit (int, optional) -- Maximum number of consecutive NaNs to fill.
axis (str) -- Axis along which to interpolate.
max_gap (float, optional) -- Maximum gap (in time units) to interpolate across.
**kwargs -- Additional arguments passed to the imputation function.
- 戻り値:
Imputed series.
- 戻り値の型:
参考
gwexpy.timeseries.preprocess.impute_timeseries
- info: QuantityInfoBase
Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information.
- inject(other: Series, *, inplace: bool = False) Self
Add two compatible Series along their shared x-axis values.
- パラメータ:
other (Series) -- A Series whose xindex intersects with self.xindex.
inplace (bool, optional) -- If True (default) perform the operation in-place, modifying the current series. If False copy the data to new memory before modifying.
- 戻り値:
out -- The sum of self and other along their shared x-axis values.
- 戻り値の型:
Series
- 例外:
ValueError -- If self and other have incompatible units or xindex intervals.
メモ
The offset between
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.
- パラメータ:
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.
- 戻り値:
out -- A copy of quantity with
valuesinserted. Note that the insertion does not occur in-place: a new quantity array is returned.- 戻り値の型:
~astropy.units.Quantity
サンプル
>>> import astropy.units as u >>> q = [1, 2] * u.m >>> q.insert(0, 50 * u.cm) <Quantity [ 0.5, 1., 2.] m>
>>> q = [[1, 2], [3, 4]] * u.m >>> q.insert(1, [10, 20] * u.m, axis=0) <Quantity [[ 1., 2.], [ 10., 20.], [ 3., 4.]] m>
>>> q.insert(1, 10 * u.m, axis=1) <Quantity [[ 1., 10., 2.], [ 3., 10., 4.]] m>
- instantaneous_frequency(unwrap: bool = True, smooth: int | float | number | Quantity | None = None, **kwargs: Any) TimeSeriesSignalMixin
Compute the instantaneous frequency of the TimeSeries.
The instantaneous frequency is derived from the time derivative of the unwrapped instantaneous phase obtained via Hilbert transform.
- パラメータ:
unwrap (bool, default=True) -- If True, unwrap the phase before differentiation (recommended). Setting to False may cause issues at phase wrap points.
smooth (int, Quantity, or None, default=None) -- Optional smoothing window. If int, number of samples. If Quantity, time duration. Default is None (no smoothing).
**kwargs -- Passed to
hilbert()viainstantaneous_phase(). Common options include pad for reducing endpoint artifacts.
- 戻り値:
Instantaneous frequency with unit 'Hz'. The output has the same length as the input (endpoints are not trimmed).
- 戻り値の型:
- 例外:
ValueError -- If the TimeSeries has no defined dt (sample rate).
メモ
Definition: The instantaneous frequency is computed as:
phase = instantaneous_phase(unwrap=True, deg=False) # radians dphi_dt = np.gradient(phase, dt) # time derivative f_inst = dphi_dt / (2 * π) # convert to Hz
Preprocessing: No automatic preprocessing is applied. Users should apply demean, detrend, filtering, or windowing as needed before calling.
Endpoint artifacts: The underlying Hilbert transform may exhibit artifacts at the edges. The endpoints of the instantaneous frequency may also be less accurate due to numerical differentiation. When evaluating accuracy, consider using only the central portion of the output.
Smoothing: The smooth parameter provides optional post-hoc smoothing via moving average. By default, no smoothing is applied.
サンプル
>>> t = np.linspace(0, 1, 1000) >>> ts = TimeSeries(np.cos(2 * np.pi * 50 * t), dt=0.001, unit='V') >>> f_inst = ts.instantaneous_frequency() >>> # Central region should be close to 50 Hz >>> np.median(f_inst.value[100:-100]) 50.0
- instantaneous_phase(deg: bool = False, unwrap: bool = False, **kwargs: Any) TimeSeriesSignalMixin
Compute the instantaneous phase of the TimeSeries via Hilbert transform.
This method first computes the analytic signal using Hilbert transform, then extracts the phase using np.angle(). Use this for real-valued signals when you need the instantaneous phase.
For complex-valued signals, consider using
radian()ordegree()which directly compute np.angle() without Hilbert transform.- パラメータ:
deg (bool, default=False) -- If True, return phase in degrees. Default is False (radians).
unwrap (bool, default=False) -- If True, unwrap the phase to remove discontinuities. Uses period=2π for radians, period=360 for degrees.
**kwargs -- Passed to
hilbert(). Common options include pad for reducing endpoint artifacts.
- 戻り値:
Instantaneous phase with unit 'rad' or 'deg'. The output has the same length as the input (endpoints are not trimmed).
- 戻り値の型:
メモ
Definition: The instantaneous phase is computed as:
analytic = hilbert(x) phase = np.angle(analytic) # in radians if unwrap: phase = np.unwrap(phase, period=2*np.pi) # or 360 for degrees
Preprocessing: No automatic preprocessing is applied. Users should apply demean, detrend, filtering, or windowing as needed before calling.
Endpoint artifacts: The underlying Hilbert transform may exhibit artifacts at the edges. Consider padding or windowing if edge effects are a concern.
サンプル
>>> ts = TimeSeries(np.sin(2 * np.pi * 10 * np.linspace(0, 1, 1000)), ... dt=0.001, unit='V') >>> phase = ts.instantaneous_phase(unwrap=True) # rad, unwrapped >>> phase_deg = ts.instantaneous_phase(deg=True, unwrap=True) # degrees
- is_compatible(other: list | ndarray) bool
Check whether this series and other have compatible metadata.
This method tests that the sample size <Series.dx>, and the ~Series.unit match.
- is_contiguous(other: Series | ndarray | list, tol: float = 3.814697265625e-06) int
Check whether other is contiguous with self.
- パラメータ:
other (Series, numpy.ndarray) -- Another series of the same type to test for contiguity.
tol (float, optional) -- The numerical tolerance of the test.
- 戻り値:
1 -- If
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.
メモ
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 is_regular: bool
Return True if this series has a regular grid (constant spacing).
- property isscalar
True if the value of this quantity is a scalar, or False if it is an array-like object.
注釈
This is subtly different from numpy.isscalar in that numpy.isscalar returns False for a zero-dimensional array (e.g.
np.array(1)), while this is True for quantities, since quantities cannot represent true numpy scalars.
- item(*args)
Copy an element of an array to a scalar Quantity and return it.
Like
item()except that it always returns a Quantity, not a Python scalar.
- itemsize
Length of one array element in bytes.
サンプル
>>> import numpy as np >>> x = np.array([1,2,3], dtype=np.float64) >>> x.itemsize 8 >>> x = np.array([1,2,3], dtype=np.complex128) >>> x.itemsize 16
- ktau(other)
Calculate Kendall's rank correlation coefficient.
- kurtosis(axis=None, fisher=True, nan_policy='propagate')
Compute the kurtosis (Fisher or Pearson) of the data.
Kurtosis is a measure of the "tailedness" of the probability distribution.
- パラメータ:
axis (int or None, optional) -- Axis along which to compute kurtosis. If None, compute over the flattened array.
fisher (bool, optional) -- If True, Fisher's definition is used (normal ==> 0.0). If False, Pearson's definition is used (normal ==> 3.0).
nan_policy (str, optional) -- How to handle NaNs: 'propagate', 'raise', or 'omit'.
- 戻り値:
The kurtosis value(s).
- 戻り値の型:
float or ndarray
- laplace(*, sigma: float | Quantity = 0.0, frequencies: ndarray | Quantity | None = None, t_start: float | Quantity | None = None, t_stop: float | Quantity | None = None, window: str | tuple | ndarray | None = None, detrend: bool = False, normalize: str = 'integral', dtype: dtype | None = None, chunk_size: int | None = None, **kwargs: Any) Any
Compute the Laplace Transform.
- パラメータ:
sigma (float or Quantity, optional) -- The real part of the complex frequency s = sigma + j*omega.
frequencies (array_like or Quantity, optional) -- The frequencies (omega / 2pi) at which to evaluate.
t_start (float or Quantity, optional) -- Time range for the transform.
t_stop (float or Quantity, optional) -- Time range for the transform.
window (str, tuple, or array_like, optional) -- Window function to apply.
detrend (bool, optional) -- If True, detrend the data before transforming.
normalize ({"integral", "mean"}, optional) -- Normalization mode.
dtype (dtype, optional) -- Output data type.
chunk_size (int, optional) -- Number of frequencies to process at once for memory efficiency.
**kwargs -- Additional keyword arguments forwarded to the output constructor.
- 戻り値の型:
FrequencySeries
- local_hurst(window: Any, **kwargs: Any) TimeSeries
Compute local Hurst exponent over a sliding window.
- パラメータ:
- 戻り値:
Local Hurst exponent series.
- 戻り値の型:
参考
gwexpy.timeseries.hurst.local_hurst
- lock_in(f0: int | float | number | Quantity | None = None, *, phase: Sequence[int | float | number] | ndarray[tuple[Any, ...], dtype[floating]] | ndarray[tuple[Any, ...], dtype[complex128]] | None = None, fdot: int | float | number | Quantity = 0.0, fddot: int | float | number | Quantity = 0.0, phase_epoch: int | float | number | None = None, phase0: float = 0.0, stride: int | float | number | Quantity | None = None, bandwidth: int | float | number | Quantity | None = None, singlesided: bool = True, output: Literal['complex', 'amp_phase', 'iq'] = 'amp_phase', deg: bool = True, **kwargs: Any) Any
Perform lock-in amplification (demodulation + filtering/averaging).
This method extracts the complex amplitude (or magnitude and phase) of a specific frequency component from the TimeSeries. It supports two independent operational modes based on how the post-mixing signal is smoothed:
- Mode 1: Stride-Average (bandwidth is None)
The signal is mixed with the reference and averaged over non-overlapping contiguous time intervals of length
stride. The output sample rate becomes1/stride. This mode is numerically identical to GWpy'sdemodulate(withexp=True).- Mode 2: LPF-Filtering (bandwidth is not None)
The signal is mixed with the reference and passed through a low-pass filter with a cutoff frequency of
bandwidth. By default, a zero-phase IIR filter is used (viafiltfilt). The output sample rate remains the same as the input unlessoutput_rateis specified in**kwargs.
- パラメータ:
f0 (float or Quantity, optional) -- Center frequency (Hz) for the reference phase model. Mutually exclusive with
phase.phase (array_like, optional) -- Explicit reference phase array in radians. Must have the same length as the input TimeSeries. If provided, f0-based parameters must NOT be specified.
fdot (float or Quantity, default: 0.0) -- First derivative of frequency (Hz/s) for chirped signals.
fddot (float or Quantity, default: 0.0) -- Second derivative of frequency (Hz/s²) for accelerating signals.
phase_epoch (float or Quantity, optional) -- Reference time (GPS) for the phase model. If None (default), use the start time of the TimeSeries.
phase0 (float, default: 0.0) -- Initial phase offset in radians at
phase_epoch.stride (float or Quantity, optional) -- Averaging time step in seconds. Required for Stride-Average mode. Must NOT be specified if
bandwidthis provided.bandwidth (float or Quantity, optional) -- Low-pass filter cutoff frequency in Hz. Required for LPF mode. Defines the analysis bandwidth (half-bandwidth) around DC.
singlesided (bool, default: True) -- If True (default), multiply the output by 2. This is the convention for recovering the full amplitude of a real-valued input signal $A \cos(\omega t + \phi)$.
output ({'amp_phase', 'complex', 'iq'}, default: 'amp_phase') -- Formatting of the returned data: -
'amp_phase': Returns a tuple of (amplitude, phase). -'complex': Returns a complex TimeSeries ($mag \cdot e^{i\phi}$). -'iq': Returns a tuple of (In-phase, Quadrature) TimeSeries.deg (bool, default: True) -- If True and
output='amp_phase', the phase is returned in degrees. Otherwise, radians.**kwargs (Any) -- Additional keyword arguments passed to
baseband()in LPF mode. Common options:type(filter type),filtfilt(bool).
- 戻り値:
out -- The demodulated signal in the requested format. Returns a tuple for
'amp_phase'and'iq', and a single TimeSeries for'complex'. Metadata liket0,name, andchannelare preserved. Theunitof the amplitude/complex/IQ result is the same as the input signal.- 戻り値の型:
TimeSeries or tuple
メモ
Phase Convention
The mixing uses the negative exponential convention:
\[Z(t) = 2 \cdot \text{LPF}\{ x(t) \cdot e^{-i\phi(t)} \} \quad (\text{if singlesided=True})\]For a real input \(x(t) = A \cos(\omega t + \phi_0)\), this operation correctly recovers the complex amplitude \(A e^{i\phi_0}\).
Edge Handling
Stride mode: Discards any remainder samples at the end that do not form a full stride. The result is anchored at the start of each stride.
LPF mode: Filter transients occur at the boundaries. Using
filtfilt=True(default) minimizes phase distortion but transients still exist. Padding the input is recommended for short series.
Numerical Precision The phase is calculated relative to
phase_epochto maintain precision for high frequencies or long durations.サンプル
Recover amplitude and phase of a 100 Hz signal:
>>> import numpy as np >>> t = np.linspace(0, 10, 163840) >>> data = np.cos(2 * np.pi * 100 * t + np.pi/4) >>> ts = TimeSeries(data, sample_rate=16384, t0=0) >>> amp, phase = ts.lock_in(f0=100, stride=1.0) >>> print(f"Amp: {amp.value.mean():.2f}, Phase: {phase.value.mean():.2f}") Amp: 1.00, Phase: 45.00
Using LPF mode for higher time resolution:
>>> complex_ts = ts.lock_in(f0=100, bandwidth=5.0, output='complex')
- lowpass(frequency: float, gpass: float = 2, gstop: float = 30, fstop: float | None = None, type: Literal['fir', 'iir'] = 'iir', *, filtfilt: bool = True, **kwargs) TimeSeries
Filter this TimeSeries with a Butterworth low-pass filter.
- パラメータ:
frequency (float) -- Low-pass corner frequency.
gpass (float) -- The maximum loss in the passband (dB).
gstop (float) -- The minimum attenuation in the stopband (dB).
fstop (float) -- Stop-band edge frequency, defaults to frequency * 1.5.
type (str) -- The filter type, either
'iir'or'fir'.filtfilt (bool, optional) -- If True, apply the filter using a forward-backward filter design, otherwise apply the filter in a single pass. Defaults to True.
kwargs -- Other keyword arguments are passed to
gwpy.signal.filter_design.lowpass().
- 戻り値:
lpseries -- A low-passed version of the input TimeSeries.
- 戻り値の型:
TimeSeries
参考
gwpy.signal.filter_design.lowpassFor details on the filter design.
TimeSeries.filterFor details on how the filter is applied.
- mT
View of the matrix transposed array.
The matrix transpose is the transpose of the last two dimensions, even if the array is of higher dimension.
Added in version 2.0.
- 例外:
ValueError -- If the array is of dimension less than 2.
サンプル
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.mT array([[1, 3], [2, 4]])
>>> a = np.arange(8).reshape((2, 2, 2)) >>> a array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> a.mT array([[[0, 2], [1, 3]], [[4, 6], [5, 7]]])
- ma(q: int = 1, **kwargs: Any) Any
Fit a Moving Average MA(q) model.
Shortcut for .arima(order=(0, 0, q)).
- mask(deadtime: SegmentList | None = None, flag: str | None = None, *, query_open_data: bool = False, const: float = nan, tpad: float = 0.5, inplace: bool = False, **kwargs) Self
Mask portions of this TimeSeries that fall within a given list of segments.
- パラメータ:
deadtime (SegmentList, optional) -- A list of time segments defining the deadtime (i.e., masked portions) of the output, will supersede flag if given.
flag (str, optional) -- The name of a data-quality flag for which to query, required if deadtime is not given.
query_open_data (bool, optional) -- If True, will query for publicly released data-quality segments through the Gravitational-wave Open Science Center (GWOSC).
const (float, optional) -- Constant value with which to mask deadtime data.
tpad (float, optional) -- Length of time (in seconds) over which to taper off data at mask segment boundaries.
inplace (bool, optional) -- If True, this array will be overwritten with the masked version, otherwise (False, default) a modified copy will be returned.
kwargs (dict, optional) -- Additional keyword arguments to ~gwpy.segments.DataQualityFlag.query or ~gwpy.segments.DataQualityFlag.fetch_open_data, see "Notes" below.
- 戻り値:
out -- The masked version of this TimeSeries.
- 戻り値の型:
TimeSeries
メモ
If tpad is nonzero, the Tukey (tapered cosine) window is used to smoothly ramp data down to zero over a timescale tpad approaching every segment boundary in deadtime. However, this does not apply to the left or right bounds of the original TimeSeries.
The deadtime segment list will always be coalesced and restricted to the limits of self.span. In particular, when querying a data-quality flag, this means the start and end arguments to ~gwpy.segments.DataQualityFlag.query will effectively be reset and therefore need not be given.
If flag is interpreted positively, i.e. if flag being active corresponds to a "good" state, then its complement in self.span will be used to define the deadtime for masking.
参考
gwpy.segments.DataQualityFlag.queryFor the method to query segments of a given data-quality flag.
gwpy.segments.DataQualityFlag.fetch_open_dataFor the method to query data-quality flags from the GWOSC database.
scipy.signal.windows.tukeyFor the Tukey (tapered cosine) window used for tapering.
- max(axis=None, out=None, keepdims=False, initial=<no value>, where=<no value>, *, ignore_nan=False)
- mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True, ignore_nan=False)
- median(axis=None, **kwargs)
Compute the median.
- パラメータ:
axis (int or None, optional) -- Axis along which to compute the median. If None, compute over the flattened array.
ignore_nan (bool, optional) -- If True, use
numpy.nanmedianand ignore NaNs. The default is False, matching GWpy and NumPy NaN propagation.**kwargs -- Passed to the GWpy implementation, or to
numpy.nanmedianwhenignore_nan=True.
- 戻り値:
The median value(s). If the object carries a unit, the result is returned with the same unit where applicable.
- 戻り値の型:
Any
- mic(other, alpha=0.6, c=15, est='mic_approx')
Calculate Maximal Information Coefficient (MIC) using minepy.
Note: On Python 3.11+, minepy must be built from source. Use python scripts/install_minepy.py provided in the gwexpy repository.
- min(axis=None, out=None, keepdims=False, initial=<no value>, where=<no value>, *, ignore_nan=False)
- mix_down(*, phase: Sequence[int | float | number] | ndarray[tuple[Any, ...], dtype[floating]] | ndarray[tuple[Any, ...], dtype[complex128]] | None = None, f0: int | float | number | Quantity | None = None, fdot: int | float | number | Quantity = 0.0, fddot: int | float | number | Quantity = 0.0, phase_epoch: int | float | number | None = None, phase0: float = 0.0, singlesided: bool = False, copy: bool = True) TimeSeriesSignalMixin
Mix the TimeSeries with a complex oscillator.
- nbytes
Total bytes consumed by the elements of the array.
メモ
Does not include memory consumed by non-element attributes of the array object.
参考
sys.getsizeofMemory consumed by the object itself without parents in case view. This does include memory consumed by non-element attributes.
サンプル
>>> import numpy as np >>> x = np.zeros((3,5,2), dtype=np.complex128) >>> x.nbytes 480 >>> np.prod(x.shape) * x.itemsize 480
- ndim: int
Number of array dimensions.
サンプル
>>> import numpy as np >>> x = np.array([1, 2, 3]) >>> x.ndim 1 >>> y = np.zeros((2, 3, 4)) >>> y.ndim 3
- nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
参考
numpy.nonzeroequivalent function
- notch(frequency: QuantityLike, type: Literal['iir'] = 'iir', *, filtfilt: bool = True, **kwargs) Self
Notch out a frequency in this TimeSeries.
- パラメータ:
frequency (float, ~astropy.units.Quantity) -- Frequency (default in Hertz) at which to apply the notch.
type (str, optional) -- Type of filter to apply, currently only 'iir' is supported.
filtfilt (bool, optional) -- Whether to apply zero-phase filtering (default is True).
kwargs -- Other keyword arguments to pass to gwpy.signal.filter_design.notch.
- 戻り値:
notched -- A notch-filtered copy of the input TimeSeries.
- 戻り値の型:
TimeSeries
参考
TimeSeries.filterFor details on the filtering method.
gwpy.signal.filter_design.notchFor details on the IIR filter design method.
- override_unit(unit: UnitLike, parse_strict: Literal['raise', 'warn', 'silent'] = 'raise') None
Reset the unit of these data.
Use of this method is discouraged in favour of to(), which performs accurate conversions from one unit to another. The method should really only be used when the original unit of the array is plain wrong.
- パラメータ:
unit (~astropy.units.Unit, str) -- the unit to force onto this array
parse_strict (str) -- how to handle errors in the unit parsing, default is to raise the underlying exception from astropy.units
参考
gwpy.detector.units.parse_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.
- パラメータ:
pad_width (int, tuple[int, int]) -- Number of samples by which to pad each end of the array; given a single int to pad both ends by the same amount, or a
(before, after)tuple for assymetric padding.kwargs -- Other keyword arguments are passed to numpy.pad.
- 戻り値:
series -- The padded version of the input.
- 戻り値の型:
Series
参考
numpy.padFor details on the pad function and valid keyword arguments.
- partial_correlation(other, *, controls=None, method: str = 'residual', **kwargs)
Calculate partial correlation between self and other, controlling for controls.
- パラメータ:
other (TimeSeries) -- The series to compare with.
controls (TimeSeries or list[TimeSeries], optional) -- Control variables to regress out. If None, falls back to Pearson correlation.
method ({"residual", "precision"}) --
"residual": regress out controls and correlate residuals.
"precision": compute partial correlation via precision matrix.
**kwargs -- Extra arguments for the underlying solver (e.g., rcond for pinv).
- partition(kth, axis=-1, kind='introselect', order=None)
Partially sorts the elements in the array in such a way that the value of the element in k-th position is in the position it would be in a sorted array. In the output array, all elements smaller than the k-th element are located to the left of this element and all equal or greater are located to its right. The ordering of the elements in the two partitions on the either side of the k-th element in the output array is undefined.
- パラメータ:
kth (int or sequence of ints) --
Element index to partition by. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once.
バージョン 1.22.0 で非推奨: Passing booleans as index is deprecated.
axis (int, optional) -- Axis along which to sort. Default is -1, which means sort along the last axis.
kind ({'introselect'}, optional) -- Selection algorithm. Default is 'introselect'.
order (str or list of str, optional) -- When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need to be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
参考
numpy.partitionReturn a partitioned copy of an array.
argpartitionIndirect partition.
sortFull sort.
メモ
See
np.partitionfor notes on the different algorithms.サンプル
>>> import numpy as np >>> a = np.array([3, 4, 2, 1]) >>> a.partition(3) >>> a array([2, 1, 3, 4]) # may vary
>>> a.partition((1, 3)) >>> a array([1, 2, 3, 4])
- pcc(other)
Calculate the Pearson correlation coefficient.
- phase(unwrap: bool = False, deg: bool = False, **kwargs: Any) Any
Calculate the phase of the data.
- パラメータ:
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.
- 戻り値:
The phase of the data.
- 戻り値の型:
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.
- パラメータ:
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.
警告
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.
- 戻り値:
series -- The modified series.
- 戻り値の型:
Series
- prod(axis=None, dtype=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the product of the array elements over the given axis
Refer to numpy.prod for full documentation.
参考
numpy.prodequivalent function
- psd(*args: Any, **kwargs: Any) FrequencySeries
- put(indices, values, mode='raise')
- q_gram(qrange: tuple[float, float] = (4, 64), frange: tuple[float, float] = (0, inf), mismatch: float = 0.2, snrthresh: float = 5.5, **kwargs) EventTable
Scan a TimeSeries using the multi-Q transform.
- パラメータ:
qrange (tuple of float, optional) --
(low, high)range of Qs to scan.frange (tuple of float, optional) --
(low, high)range of frequencies to scan.mismatch (float, optional) -- Maximum allowed fractional mismatch between neighbouring tiles.
snrthresh (float, optional) -- Lower inclusive threshold on individual tile SNR to keep in the table.
kwargs -- Other keyword arguments to be passed to
QTiling.transform(), including'epoch'and'search'.
- 戻り値:
qgram -- A table of time-frequency tiles on the most significant QPlane.
- 戻り値の型:
EventTable
参考
TimeSeries.q_transformFor a method to interpolate the raw Q-transform over a regularly gridded spectrogram.
gwpy.signal.qtransformFor code and documentation on how the Q-transform is implemented.
gwpy.table.EventTable.tileTo render this EventTable as a collection of polygons.
メモ
Only tiles with signal energy greater than or equal to snrthresh ** 2 / 2 will be stored in the output EventTable. The table columns are
'time','duration','frequency','bandwidth', and'energy'.
- q_transform(qrange: tuple[float, float] = (4, 64), frange: tuple[float, float] = (0, inf), gps: float | None = None, search: float = 0.5, tres: str | float = '<default>', fres: str | float = '<default>', *, logf: bool = False, norm: str = 'median', mismatch: float = 0.2, outseg: Segment | None = None, whiten: bool | FrequencySeries = True, fduration: float = 2, highpass: float | None = None, **asd_kw) Spectrogram
Compute the multi-Q transform and return an interpolated spectrogram.
By default, this method returns a high-resolution spectrogram in both time and frequency, which can result in a large memory footprint. If you know that you only need a subset of the output for, say, a figure, consider using
outsegand the other keyword arguments to restrict the size of the returned data.- パラメータ:
qrange (tuple of float, optional) --
(low, high)range of Qs to scan.frange (tuple of float, optional) --
(log, high)range of frequencies to scan.gps (float, optional) -- Central time of interest for determine loudest Q-plane.
search (float, optional) -- Window around gps in which to find peak energies, only used if gps is given.
tres (float, optional) -- Desired time resolution (seconds) of output Spectrogram, default is
abs(outseg) / 1000.fres (float, int, None, optional) -- Desired frequency resolution (Hertz) of output Spectrogram, or, if
logf=True, the number of frequency samples; give None to skip this step and return the original resolution, default is 0.5 Hz or 500 frequency samples.logf (bool, optional) -- If True, use logarithmically sampled frequencies in the output (using
fresas the number of frequency samples), otherwise use linearly sampled frequencies of the specified resolution.norm (bool, str, optional) -- If True normalise the returned Q-transform output by the median; if False do not normalize; if a string, specify how to normalize the output, e.g.
'mean'or'median'.mismatch (float) -- Maximum allowed fractional mismatch between neighbouring tiles.
outseg (~gwpy.segments.Segment, optional) -- GPS [start, stop) segment for output Spectrogram, default is the full duration of the input.
whiten (bool, ~gwpy.frequencyseries.FrequencySeries, optional) -- If True, whiten the data before computing the Q-transform; if False, do not whiten the data; if a FrequencySeries, use that as the amplitude spectral density (ASD) to whiten the data.
fduration (float, optional) -- Duration (in seconds) of the time-domain FIR whitening filter, only used if whiten is not False, defaults to 2 seconds.
highpass (float, optional) -- Highpass corner frequency (in Hz) of the FIR whitening filter, used only if whiten is not False, default: None.
asd_kw -- Keyword arguments to pass to TimeSeries.asd to generate an ASD to use when whitening the data.
- 戻り値:
out -- Output Spectrogram of normalised Q energy.
- 戻り値の型:
~gwpy.spectrogram.Spectrogram
参考
TimeSeries.asdFor documentation on acceptable
**asd_kw.TimeSeries.whitenFor documentation on how the whitening is done.
gwpy.signal.qtransformFor code and documentation on how the Q-transform is implemented.
メモ
This method will return a Spectrogram of dtype
float32ifnormis given, andfloat64otherwise.To optimize plot rendering with ~matplotlib.axes.Axes.pcolormesh, the output ~gwpy.spectrogram.Spectrogram can be given a log-sampled frequency axis by passing logf=True at runtime. The fres argument is then the number of points on the frequency axis. Note, this is incompatible with ~matplotlib.axes.Axes.imshow.
It is also highly recommended to use the outseg keyword argument when only a small window around a given GPS time is of interest. This will speed up this method a little, but can greatly speed up rendering the resulting Spectrogram using pcolormesh.
If you aren't going to use pcolormesh in the end, don't worry.
サンプル
>>> from numpy.random import normal >>> from scipy.signal import gausspulse >>> from gwpy.timeseries import TimeSeries
Generate a TimeSeries containing Gaussian noise sampled at 4096 Hz, centred on GPS time 0, with a sine-Gaussian pulse ('glitch') at 500 Hz:
>>> noise = TimeSeries( ... normal(loc=1, size=4096*4), ... sample_rate=4096, ... epoch=-2, ... ) >>> glitch = TimeSeries( ... gausspulse(noise.times.value, fc=500) * 4, ... sample_rate=4096, ... ) >>> data = noise + glitch
Compute and plot the Q-transform of these data:
>>> q = data.q_transform() >>> plot = q.plot() >>> ax = plot.gca() >>> ax.set_xlim(-.2, .2) >>> ax.set_epoch(0) >>> plot.show()
- radian(unwrap: bool = False) TimeSeriesSignalMixin
Calculate the phase angle of the TimeSeries in radians.
Computes np.angle(self.value) directly. Works for both real and complex time series. For real signals, this will return 0 or π depending on sign.
For instantaneous phase of a real signal via Hilbert transform, use
instantaneous_phase()instead.- パラメータ:
unwrap (bool, optional) -- If True, unwrap the phase. Default is False.
- 戻り値:
Phase angle in radians.
- 戻り値の型:
- ravel(order='C')
Return a flattened array.
Refer to numpy.ravel for full documentation.
参考
numpy.ravelequivalent function
ndarray.flata flat iterator on the array.
- rayleigh_spectrogram(stride: float, fftlength: float | None = None, overlap: float | None = 0, window: WindowLike = 'hann', nproc: int = 1, **kwargs: Any) Spectrogram
Compute the Rayleigh statistic spectrogram.
This method overrides the base gwpy implementation to return gwexpy.spectrogram.Spectrogram instead of gwpy.spectrogram.Spectrogram.
- 戻り値:
gwexpy.spectrogram.Spectrogram instance
- 戻り値の型:
メモ
The default path preserves GWpy's segment selection and numerical result. GWexpy's corrected hop-count implementation remains private and is used only by the GWexpy-specific TimeSeries.rayleigh_test().
- rayleigh_spectrum(fftlength: float | None = None, overlap: float = 0, window: WindowLike = 'hann') FrequencySeries
Calculate the Rayleigh FrequencySeries for this TimeSeries.
The Rayleigh statistic is calculated as the ratio of the standard deviation and the mean of a number of periodograms.
- パラメータ:
fftlength (float) -- Number of seconds in single FFT, defaults to a single FFT covering the full duration.
overlap (float, optional) -- Number of seconds of overlap between FFTs, passing None will choose based on the window method, default:
0.window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.
- 戻り値:
psd -- A data series containing the PSD.
- 戻り値の型:
~gwpy.frequencyseries.FrequencySeries
- rayleigh_test(fftlength, stride, n_samples=None, **kwargs)
Compute Rayleigh statistic p-value spectrogram.
Accepts rng= / seed= (forwarded to gwexpy.statistics.rayleigh_test.rayleigh_pvalue) for a reproducible Monte Carlo null distribution.
- パラメータ:
fftlength (float) -- FFT length in seconds.
stride (float) -- Stride in seconds. Each output column aggregates the periodogram segments falling in one stride.
n_samples (int, optional) -- Number of periodogram segments per column. Derived from fftlength, stride and overlap when omitted, which is almost always what you want; an explicit value that disagrees with the derived one emits a UserWarning. Before v0.1.12 this defaulted to the constant
39, unrelated to the data (#506).overlap (float, optional) -- Segment overlap in seconds. Must resolve to either
0or GWpy's recommended overlap for the window (50% for the default hann); see Raises.**kwargs -- Forwarded to rayleigh_pvalue (n_monte_carlo, rng, seed).
- 戻り値:
The DC bin and, for an even FFT length in samples, the Nyquist bin are NaN -- their power is not exponentially distributed. See rayleigh_pvalue.
- 戻り値の型:
- 例外:
ValueError -- If overlap resolves to anything other than
0or the recommended overlap. At other fractions the per-segment powers stop being even approximately i.i.d. exponential, so the null distribution no longer describes the statistic; GWpy also either raises (25%) or silently uses a fraction of the data (75%).
- real
The real part of the array.
サンプル
>>> import numpy as np >>> x = np.sqrt([1+0j, 0+1j]) >>> x.real array([ 1. , 0.70710678]) >>> x.real.dtype dtype('float64')
参考
numpy.realequivalent function
- repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
参考
numpy.repeatequivalent function
- resample(rate: float, window: WindowLike = 'hamming', ftype: Literal['fir', 'iir'] = 'fir', n: int | None = None, **kwargs: Any) TimeSeries
Resample the TimeSeries.
If
rateis a time-string (e.g."1s") or time Quantity, perform time-bin aggregation. Its keyword arguments areclosed("left"or"right"),label("left","right", or"center"),origin("t0"or"gps0"),align("floor"or"ceil"), andnan_policy("omit"or"propagate"). Withclosed="right", the first bin includes both of its edges and later bins are right-closed.Time-bin widths must be real, finite, positive scalars. Invalid time-bin enum values or widths raise
ValueError.offsetmust be a real, finite scalar with either a time-compatible or dimensionless unit. Other rates use signal-processing resampling (GWpy standard).
- reshape(shape, /, *, order='C', copy=None)
- reshape(*shape, order='C', copy=None) None
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
参考
numpy.reshapeequivalent function
メモ
Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example,
a.reshape(4, 2)is equivalent toa.reshape((4, 2)).
- resize(new_shape, /, *, refcheck=True)
- resize(*new_shape, refcheck=True) None
Change shape and size of array in-place.
- パラメータ:
new_shape (tuple of ints, or n ints) -- Shape of resized array.
refcheck (bool, optional) -- If False, reference count will not be checked. Default is True. See Notes below for more explanation.
- 戻り値の型:
None
- 例外:
ValueError -- If a does not own its own data or references or views to may exist.
参考
resizeReturn a new array with the specified shape.
メモ
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
Reallocating arrays in-place can often lead to memory fragmentation and should be avoided. If the goal is to reclaim over-allocated memory, alternatives are to create a view or a copy of just the desired data, or using two passes to build the array: one to cheaply determine the shape and another to allocate and fill. Benchmark your use case to determine what is optimum. You may be surprised to find
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.
参照
サンプル
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]])
- rfft(*args: Any, **kwargs: Any) FrequencySeries
Real-valued Fast Fourier Transform.
Compute the one-dimensional discrete Fourier Transform for real input. This method delegates to GWpy's TimeSeries.rfft() and returns a FrequencySeries with Hermitian symmetry.
- パラメータ:
- 戻り値:
The FFT of the input, with Hermitian symmetry (only positive frequencies). The output length is
len(self) // 2 + 1.- 戻り値の型:
- 例外:
ValueError -- If the TimeSeries is not regularly sampled.
参考
numpy.fft.rfftNumPy's real FFT function
TimeSeries.fftStandard FFT with complex output (both pos/neg freqs)
FrequencySeries.ifftInverse FFT
gwpy.timeseries.TimeSeries.rfftGWpy's rfft implementation
メモ
For real-valued input, the FFT is Hermitian-symmetric, so only the positive frequencies are stored to save memory. The output has length
n//2 + 1for input lengthn.サンプル
>>> from gwexpy.timeseries import TimeSeries >>> ts = TimeSeries([1.0, 2.0, 3.0, 4.0], sample_rate=1.0) >>> fft = ts.rfft() >>> print(fft.size) 3
- rms(stride: float = 1, *, ignore_nan: bool | None = None) TimeSeries
Calculate the root-mean-square value once per
strideseconds.gwpy-compatible: returns a new TimeSeries holding one RMS value per
stride-second window (dt = stride), mirroring gwpy.timeseries.TimeSeries.rms. This overrides the generic numpy-stylermsfromStatisticalMethodsMixin(which reduces alongaxis) so that existing gwpy code such asdata.rms(10)keeps working.- パラメータ:
stride (float, optional) -- Stride in seconds between RMS calculations. Quantity-like values are intentionally rejected to keep the public API narrow.
ignore_nan (bool, optional) -- Explicit GWexpy extension. If true, calculate each window from finite samples. If omitted or false, use the GWpy default route.
- 戻り値:
rms -- A new TimeSeries of RMS values with
dt = stride. Any trailing partial window is dropped, matching gwpy.- 戻り値の型:
TimeSeries
- 例外:
ValueError -- If the series is not regularly sampled, or
strideis shorter than one sample period.
メモ
The result is dimensionless, matching GWpy. For complex data the GWpy convention
sqrt(mean(|x|**2))is used.
- rolling_max(window: Any, *, center: bool = False, min_count: int = 1, nan_policy: str = 'omit', backend: str = 'auto', ignore_nan: bool | None = None) TimeSeries
Compute the rolling maximum over time.
- パラメータ:
- 戻り値:
Rolling maximum.
- 戻り値の型:
- rolling_mean(window: Any, *, center: bool = False, min_count: int = 1, nan_policy: str = 'omit', backend: str = 'auto', ignore_nan: bool | None = None) TimeSeries
Compute the rolling mean over time.
- パラメータ:
- 戻り値:
Rolling mean.
- 戻り値の型:
- rolling_median(window: Any, *, center: bool = False, min_count: int = 1, nan_policy: str = 'omit', backend: str = 'auto', ignore_nan: bool | None = None) TimeSeries
Compute the rolling median over time.
- パラメータ:
- 戻り値:
Rolling median.
- 戻り値の型:
- rolling_min(window: Any, *, center: bool = False, min_count: int = 1, nan_policy: str = 'omit', backend: str = 'auto', ignore_nan: bool | None = None) TimeSeries
Compute the rolling minimum over time.
- パラメータ:
- 戻り値:
Rolling minimum.
- 戻り値の型:
- rolling_std(window: Any, *, center: bool = False, min_count: int = 1, nan_policy: str = 'omit', backend: str = 'auto', ddof: int = 0, ignore_nan: bool | None = None) TimeSeries
Compute the rolling standard deviation over time.
- パラメータ:
center (bool) -- If True, center the window on each point.
min_count (int) -- Minimum number of observations required.
nan_policy (str) -- How to handle NaN values.
backend (str) -- Computation backend.
ddof (int) -- Delta degrees of freedom.
ignore_nan (bool, optional) -- If True, ignore NaNs (overrides nan_policy).
- 戻り値:
Rolling standard deviation.
- 戻り値の型:
- round(decimals=0, out=None)
- property sample_rate: Quantity
Data rate for this TimeSeries in samples per second (Hertz).
This attribute is stored internally by the dx attribute
- 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.
- パラメータ:
- 戻り値の型:
None
参考
getfieldサンプル
>>> import numpy as np >>> x = np.eye(3) >>> x.getfield(np.float64) array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) >>> x.setfield(3, np.int32) >>> x.getfield(np.int32) array([[3, 3, 3], [3, 3, 3], [3, 3, 3]], dtype=int32) >>> x array([[1.0e+000, 1.5e-323, 1.5e-323], [1.5e-323, 1.0e+000, 1.5e-323], [1.5e-323, 1.5e-323, 1.0e+000]]) >>> x.setfield(np.eye(3), np.int32) >>> x array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
- setflags(write=None, align=None, uic=None)
Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.
These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY flag can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)
- パラメータ:
メモ
Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only three of which can be changed by the user: WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);
WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array.
All flags can be accessed using the single (upper case) letter as well as the full name.
サンプル
>>> import numpy as np >>> y = np.array([[3, 1, 7], ... [2, 0, 0], ... [8, 5, 9]]) >>> y array([[3, 1, 7], [2, 0, 0], [8, 5, 9]]) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False >>> y.setflags(write=0, align=0) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False WRITEBACKIFCOPY : False >>> y.setflags(uic=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot set WRITEBACKIFCOPY flag to True
- shape: tuple[int, ...]
Tuple of array dimensions.
The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.
警告
Setting
arr.shapeis discouraged and may be deprecated in the future. Using ndarray.reshape is the preferred approach.サンプル
>>> import numpy as np >>> x = np.array([1, 2, 3, 4]) >>> x.shape (4,) >>> y = np.zeros((2, 3, 4)) >>> y.shape (2, 3, 4) >>> y.shape = (3, 8) >>> y array([[ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.]]) >>> y.shape = (3, 6) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot reshape array of size 24 into shape (3,6) >>> np.zeros((4,2))[::2].shape = (-1,) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Incompatible shape for in-place modification. Use `.reshape()` to make a copy with the desired shape.
参考
numpy.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.
- パラメータ:
delta (float, ~astropy.units.Quantity, str) -- The amount by which to shift (in x-axis units if float), give a negative value to shift backwards in time
サンプル
>>> from gwpy.types import Series >>> a = Series([1, 2, 3, 4, 5], x0=0, dx=1, xunit='m') >>> print(a.x0) 0.0 m >>> a.shift(5) >>> print(a.x0) 5.0 m >>> a.shift('-1 km') -995.0 m
- property si
Returns a copy of the current Quantity instance with SI units. The value of the resulting object will be scaled.
- size: int
Number of elements in the array.
Equal to
np.prod(a.shape), i.e., the product of the array's dimensions.メモ
a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested
np.prod(a.shape), which returns an instance ofnp.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.サンプル
>>> import numpy as np >>> x = np.zeros((3, 5, 2), dtype=np.complex128) >>> x.size 30 >>> np.prod(x.shape) 30
- skewness(axis=None, nan_policy='propagate')
Compute the skewness of the data.
Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean.
- smooth(width: Any, method: str = 'amplitude', ignore_nan: bool = True) Any
Smooth the series.
- パラメータ:
width (int) -- Number of samples for the smoothing winow.
method (str, optional) -- Smoothing target: 'amplitude', 'power', 'complex', 'db'.
ignore_nan (bool, optional) -- If True, ignore NaNs.
- 戻り値:
Smoothed series.
- 戻り値の型:
Series
- sort(axis=-1, kind=None, order=None, *, stable=None)
Sort an array in-place. Refer to numpy.sort for full documentation.
- パラメータ:
axis (int, optional) -- Axis along which to sort. Default is -1, which means sort along the last axis.
kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}, optional) -- Sorting algorithm. The default is 'quicksort'. Note that both 'stable' and 'mergesort' use timsort under the covers and, in general, the actual implementation will vary with datatype. The 'mergesort' option is retained for backwards compatibility.
order (str or list of str, optional) -- When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
stable (bool, optional) --
Sort stability. If
True, the returned array will maintain the relative order ofavalues which compare as equal. IfFalseorNone, this is not guaranteed. Internally, this option selectskind='stable'. Default:None.Added in version 2.0.0.
参考
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.
メモ
See numpy.sort for notes on the different sorting algorithms.
サンプル
>>> import numpy as np >>> a = np.array([[1,4], [3,1]]) >>> a.sort(axis=1) >>> a array([[1, 4], [1, 3]]) >>> a.sort(axis=0) >>> a array([[1, 3], [1, 4]])
Use the order keyword to specify a field to use when sorting a structured array:
>>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) >>> a.sort(order='y') >>> a array([(b'c', 1), (b'a', 2)], dtype=[('x', 'S1'), ('y', '<i8')])
- property span: Segment
Time (seconds) spanned by this series.
- spectral_variance(stride: float, fftlength: float | None = None, overlap: float | None = None, method: str = 'median', window: WindowLike = 'hann', *, nproc: int = 1, filter_: FilterCompatible | None = None, bins: ArrayLike | 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 TimeSeries.
- パラメータ:
stride (float) -- Number of seconds in single PSD (column of spectrogram).
fftlength (float) -- Number of seconds in single FFT.
method (str, optional) -- FFT-averaging method (default:
'median'), see Notes for more details.overlap (float, optional) -- Number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0.
window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.nproc (int) -- Maximum number of independent frame reading processes, default is set to single-process file reading.
filter (FilterCompatible, optional) -- Filter to apply to each time-bin of the spectrogram prior to variance calculation.
bins (numpy.ndarray, optional, default None) -- Array of histogram bin edges, including the rightmost edge.
low (float, optional) -- Left edge of lowest amplitude bin, only read if
binsis not given.high (float, optional) -- Right edge of highest amplitude bin, only read if
binsis not given.nbins (int, optional) -- Number of bins to generate, only read if
binsis not given.log (bool, optional) -- Calculate amplitude bins over a logarithmic scale, only read if
binsis not given.norm (bool, optional) -- Normalise bin counts to a unit sum.
density (bool, optional) -- Normalise bin counts to a unit integral.
- 戻り値:
specvar -- 2D-array of spectral frequency-amplitude counts.
- 戻り値の型:
SpectralVariance
参考
numpy.histogramFor details on specifying bins and weights.
メモ
The accepted
methodarguments are:'bartlett': a mean average of non-overlapping periodograms'median': a median average of overlapping periodograms'welch': a mean average of overlapping periodograms
- spectrogram(stride: float, fftlength: float | None = None, overlap: float | None = None, window: WindowLike = 'hann', method: str = 'median', nproc: int = 1, **kwargs: Any) Spectrogram
Compute the average power spectrogram.
This method overrides the base gwpy implementation to return gwexpy.spectrogram.Spectrogram instead of gwpy.spectrogram.Spectrogram.
- 戻り値:
gwexpy.spectrogram.Spectrogram instance
- 戻り値の型:
- spectrogram2(fftlength: float, overlap: float | None = None, window: WindowLike = 'hann', **kwargs: Any) Spectrogram
Compute an alternative spectrogram (spectrogram2).
Returns Spectrogram.
- squeeze(axis=None)
Remove axes of length one from a.
Refer to numpy.squeeze for full documentation.
参考
numpy.squeezeequivalent function
- standardize(*, method: str = 'zscore', ddof: int = 0, robust: bool = False) TimeSeries
Standardize the series.
- パラメータ:
- 戻り値:
Standardized series.
- 戻り値の型:
参考
gwexpy.timeseries.preprocess.standardize_timeseries
- std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True, ignore_nan=False)
- step(**kwargs) Plot
Create a step plot of this series.
- kwargs
All keyword arguments are passed to the
plot()method. of this series.
参考
plotFor details of the plotting.
- stlt(stride: Any = None, window: Any = None, fftlength: Any = None, overlap: Any = None, *, sigmas: Any = 0.0, frequencies: Any = None, scaling: str = 'dt', time_ref: str = 'start', onesided: bool | None = None, legacy: bool = False, **kwargs: Any) Any
Compute Short-Time Laplace Transform (STLT).
Chunk the time series, apply window w[n] * exp(-sigma * t_rel[n]), and compute FFT.
- パラメータ:
stride (Quantity or str, optional) -- Step size in seconds between chunks.
window (Quantity, str, or array-like, optional) -- If Quantity/str with units: window duration (legacy style or alias for fftlength). If str (no units) or array: window function (passed to scipy.signal.get_window). Default 'hann'.
fftlength (Quantity or str, optional) -- Window duration. Preferred over 'window' for specifying duration.
overlap (Quantity or str, optional) -- Overlap duration.
sigmas (float or array-like or Quantity, optional) -- Real part of Laplace frequency s = sigma + j*omega. Default 0.
frequencies (array-like, optional) -- Output frequencies in Hz. If provided, STLT is evaluated at these frequencies (arbitrary points are supported). If None, uses the FFT frequency grid. For performance, the implementation may choose an optimized evaluation strategy (FFT + bin selection, zoom FFT for large uniform grids, or direct DFT for arbitrary frequency lists).
scaling (str, optional) -- 'dt' (multiply by dt, discrete integral), 'none' (raw FFT). Default 'dt'.
time_ref (str, optional) -- Time reference for the exponential term within each window. 'start': t_rel in [0, T_win]. 'center': t_rel in [-T_win/2, T_win/2]. Recommended for large sigmas to avoid overflow. Default 'start'.
onesided (bool, optional) -- If True, return one-sided FFT (real input only). If False, return two-sided FFT. If None, defaults to True for real data, False for complex data.
legacy (bool, optional) -- If True, use the old magnitude-outer-product implementation (deprecated).
**kwargs -- Additional keyword arguments forwarded to legacy or output helpers.
- 戻り値:
3D transform result with shape (time, sigma, frequency).
- 戻り値の型:
LaplaceGram
メモ
This method uses a fully vectorized implementation for performance, broadcasting over sigmas and time chunks.
- strides
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element
(i[0], i[1], ..., i[n])in an array a is:offset = sum(np.array(i) * a.strides)
A more detailed explanation of strides can be found in The N-dimensional array (ndarray).
警告
Setting
arr.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.メモ
Imagine an array of 32-bit integers (each 4 bytes):
x = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=np.int32)
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be
(20, 4).サンプル
>>> import numpy as np >>> y = np.reshape(np.arange(2 * 3 * 4, dtype=np.int32), (2, 3, 4)) >>> y array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]], dtype=np.int32) >>> y.strides (48, 16, 4) >>> y[1, 1, 1] np.int32(17) >>> offset = sum(y.strides * np.array((1, 1, 1))) >>> offset // y.itemsize np.int64(17)
>>> x = np.reshape(np.arange(5*6*7*8, dtype=np.int32), (5, 6, 7, 8)) >>> x = x.transpose(2, 3, 1, 0) >>> x.strides (32, 4, 224, 1344) >>> i = np.array([3, 5, 2, 2], dtype=np.int32) >>> offset = sum(i * x.strides) >>> x[3, 5, 2, 2] np.int32(813) >>> offset // x.itemsize np.int64(813)
- student_t_spectrogram(fftlength, stride=None, window=40, overlap=None, frange=None)
Compute Student-t degree of freedom (nu) spectrogram.
See gwexpy.statistics.student_t_indicator.compute_student_t_nu for the input validation contract and the resulting GPS (not relative-to-start) time axis.
- 戻り値の型:
- sum(axis=None, dtype=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the sum of the array elements over the given axis.
Refer to numpy.sum for full documentation.
参考
numpy.sumequivalent function
- swapaxes(axis1, axis2, /)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
参考
numpy.swapaxesequivalent function
- take(indices, axis=None, out=None, mode='raise')
- taper(side: Literal['left', 'right', 'leftright'] = 'leftright', duration: float | None = None, nsamples: int | None = None) Self
Taper the ends of this TimeSeries smoothly to zero.
- パラメータ:
side (str, optional) -- The side of the TimeSeries to taper, must be one of 'left', 'right', or 'leftright'.
duration (float, optional) -- The duration of time to taper, will override nsamples if both are provided as arguments.
nsamples (int, optional) -- The number of samples to taper, will be overridden by duration if both are provided as arguments.
- 戻り値:
out -- A copy of self tapered at one or both ends.
- 戻り値の型:
TimeSeries
- 例外:
ValueError -- If side is not one of
('left', 'right', 'leftright').
サンプル
To see the effect of the Tukey (tapered cosine) window, we can taper a sinusoidal TimeSeries at both ends:
>>> import numpy >>> from gwpy.timeseries import TimeSeries >>> t = numpy.linspace(0, 1, 2048) >>> series = TimeSeries(numpy.cos(10.5*numpy.pi*t), times=t) >>> tapered = series.taper()
We can plot it to see how the ends now vary smoothly from 0 to 1:
>>> from gwpy.plot import Plot >>> plot = Plot(series, tapered, separate=True, sharex=True) >>> plot.show()
メモ
The
TimeSeries.taper()automatically tapers from the second stationary point (local maximum or minimum) on the specified side of the input. However, the method will never taper more than half the full width of the TimeSeries, and will fail if there are no stationary points.See
scipy.signal.windows.tukey()for the Tukey (tapered cosine) window used for tapering, and seescipy.signal.get_window()for other common window formats.
- property times: Index
Array of GPS times for each sample.
- to(unit, equivalencies=[], copy=True)
Return a new ~astropy.units.Quantity object with the specified unit.
- パラメータ:
unit (unit-like) -- An object that represents the unit to convert to. Must be an ~astropy.units.UnitBase object or a string parseable by the ~astropy.units package.
equivalencies (list of tuple) -- A list of equivalence pairs to try if the units are not directly convertible. See Equivalencies. If not provided or
[], class default equivalencies will be used (none for ~astropy.units.Quantity, but may be set for subclasses) If None, no equivalencies will be applied at all, not even any set globally or within a context.copy (bool, optional) -- If True (default), then the value is copied. Otherwise, a copy will only be made if necessary.
参考
to_valueget the numerical value in a given unit.
- to_astropy_timeseries(column: str = 'value', time_format: str = 'gps') Any
Convert to astropy.timeseries.TimeSeries.
- パラメータ:
- 戻り値の型:
- 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.
- パラメータ:
device ("cpu") -- Must be
"cpu".stream (None, optional) -- Currently unsupported.
- 戻り値:
out -- Returns the same array.
- 戻り値の型:
Self
- to_hdf5_dataset(group: Any, path: str, *, overwrite: bool = False, compression: str | None = None, compression_opts: Any = None) None
Write to HDF5 group/dataset.
- to_jax() Any
Convert to JAX Array.
- to_lal() LALTimeSeriesType
Convert this TimeSeries into a LAL TimeSeries.
注釈
This operation always copies data to new memory.
- to_librosa(y_dtype: ~typing.Any = <class 'numpy.float32'>) Any
Export to librosa-compatible numpy array.
- パラメータ:
y_dtype (dtype) -- Output dtype (librosa expects float32).
- 戻り値:
(y, sr) where y is the audio signal and sr is sample rate.
- 戻り値の型:
- to_mne(info: Any = None) Any
Convert to
mne.io.RawArray(single-channel).- パラメータ:
info (mne.Info, optional) -- Channel information. Created if not provided.
- 戻り値の型:
mne.io.RawArray
- to_neo(units: Any | None = None) Any
Convert to neo.AnalogSignal.
- パラメータ:
units (str or Unit, optional) -- Units for the signal.
- 戻り値の型:
neo.core.AnalogSignal
- to_netcdf4(ds: Any, var_name: str, **kwargs: Any) None
Write to a live netCDF4 Dataset object.
- パラメータ:
ds (netCDF4.Dataset) -- Target dataset.
var_name (str) -- Variable name.
**kwargs -- Additional arguments for createVariable.
- to_obspy(*, stats_extra: dict[str, Any] | None = None, dtype: Any = None) Any
Convert to obspy.Trace.
- パラメータ:
stats_extra (dict, optional) -- Extra stats to add to the Trace.
dtype (dtype, optional) -- Output data type.
- 戻り値の型:
obspy.Trace
- to_obspy_trace(*, stats_extra: dict[str, Any] | None = None, dtype: Any = None) Any
Alias for to_obspy().
- to_pandas(index: Literal['datetime', 'seconds', 'gps'] = 'datetime', *, name: str | None = None, copy: bool = False) Any
Convert TimeSeries to pandas.Series.
- to_polars(name: str | None = None, as_dataframe: bool = True, times: str = 'time', time_unit: str = 'datetime') Any
Convert TimeSeries to polars object.
- パラメータ:
name (str, optional) -- Name for the polars Series/Column.
as_dataframe (bool, default True) -- If True, returns a DataFrame with a time column. If False, returns a raw Series of values.
times (str, default "time") -- Name of the time column (only if as_dataframe=True).
time_unit (str, default "datetime") -- Format of the time column: "datetime", "gps", or "unix".
- 戻り値の型:
polars.DataFrame or polars.Series
- to_pycbc(*, copy: bool = True) pycbc.types.TimeSeries
Convert this TimeSeries into a PyCBC ~pycbc.types.timeseries.TimeSeries.
- パラメータ:
copy (bool, optional, default: True) -- If True, copy these data to a new array.
- 戻り値:
timeseries -- A PyCBC representation of this TimeSeries.
- 戻り値の型:
~pycbc.types.timeseries.TimeSeries
- to_pyroomacoustics_source() tuple[ndarray, int]
Export as a signal and sample rate tuple for pyroomacoustics.
- 戻り値:
signal (numpy.ndarray) -- 1D float64 array of the signal samples.
fs (int) -- Sample rate in Hz.
- to_sqlite(conn: Any, series_id: str | None = None, *, overwrite: bool = False) Any
Save to sqlite3 database.
- パラメータ:
conn (sqlite3.Connection) -- Database connection.
series_id (str, optional) -- Identifier for the series.
overwrite (bool) -- Whether to overwrite existing.
- 戻り値:
The series_id used.
- 戻り値の型:
- 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.- パラメータ:
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.
- 戻り値:
A string with the contents of this Quantity
- 戻り値の型:
- to_tgraph(error: Any | None = None) Any
Convert to ROOT TGraph or TGraphErrors.
- パラメータ:
error (Series, Quantity, or array-like, optional) -- Error bars for the y-axis.
- 戻り値の型:
ROOT.TGraph or ROOT.TGraphErrors
- to_th1d(error: Any | None = None) Any
Convert to ROOT TH1D.
- パラメータ:
error (Series, Quantity, or array-like, optional) -- Bin errors.
- 戻り値の型:
ROOT.TH1D
- 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.
- パラメータ:
unit (unit-like, optional) -- The unit in which the value should be given. If not given or None, use the current unit.
equivalencies (list of tuple, optional) -- A list of equivalence pairs to try if the units are not directly convertible (see Equivalencies). If not provided or
[], class default equivalencies will be used (none for ~astropy.units.Quantity, but may be set for subclasses). If None, no equivalencies will be applied at all, not even any set globally or within a context.
- 戻り値:
value -- The value in the units specified. For arrays, this will be a view of the data if no unit conversion was necessary.
- 戻り値の型:
ndarray or scalar
参考
toGet a new instance in a different unit.
- to_xarray(time_coord: Literal['datetime', 'seconds', 'gps'] = 'datetime') Any
Convert to xarray.DataArray.
- パラメータ:
time_coord (str) -- Name of the time coordinate.
- 戻り値の型:
xarray.DataArray
- 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)
- transfer_function(other: TimeSeries, fftlength: NumberLike | None = None, overlap: NumberLike | None = None, window: str | ArrayLike | None = 'hann', average: str = 'mean', *, mode: Literal['steady', 'transient'] = 'steady', method: Literal['gwpy', 'csd_psd', 'fft', 'auto'] | None = None, fft_kwargs: dict[str, Any] | None = None, downsample: NumberLike | None = None, align: Literal['intersection', 'none'] = 'intersection', epsilon: float | None = None, **kwargs: Any) Any
Compute the transfer function between this TimeSeries and another.
This TimeSeries (self) is the 'A-channel' (reference, denominator), while other is the 'B-channel' (test, numerator).
- パラメータ:
other (TimeSeries) -- The test TimeSeries (numerator).
fftlength (float, optional) -- Length of the FFT, in seconds. Only used for mode="steady".
overlap (float, optional) -- Overlap between segments, in seconds. Only used for mode="steady".
window (str, numpy.ndarray, optional) -- Window function to apply (mode="steady" only).
average (str, optional) -- Method to average segments (mode="steady" only).
mode (str, optional) --
- "steady" (default): GWpy-compatible averaged estimator using
H(f) = CSD_{A,B}(f) / PSD_A(f) Use for steady-state system identification with noise averaging.
- "transient": Instantaneous FFT ratio
H(f) = FFT_B(f) / FFT_A(f) Use for single-shot transient response analysis.
method (str, optional) -- Deprecated: use mode instead. For backward compatibility: "gwpy"/"csd_psd" -> mode="steady", "fft" -> mode="transient", "auto" -> auto-select.
fft_kwargs (dict, optional) -- Additional keyword arguments for FFT (mode="transient" only).
downsample (float, optional) -- Whether to downsample if sample rates differ (mode="transient" only).
align (str, optional) -- Alignment method: "intersection" or "none" (mode="transient" only).
epsilon (float, optional) -- L2 regularization parameter to prevent division by zero or numerical instability. If provided, the division is performed as: - steady mode: \(H(f) = \text{CSD}(f) / (\text{PSD}(f) + \epsilon)\) - transient mode: \(H(f) = (FFT_B \cdot FFT_A^*) / (|FFT_A|^2 + \epsilon)\)
**kwargs -- Additional keyword arguments forwarded to the steady-state spectral estimators.
- 戻り値:
out -- Transfer function.
- 戻り値の型:
FrequencySeries
メモ
- steady mode (GWpy-compatible):
Uses cross-spectral density and power spectral density:
\[\begin{split}H(f) = \\frac{\\mathrm{CSD}_{A,B}(f)}{\\mathrm{PSD}_A(f)}\end{split}\]This is the standard estimator for steady-state system identification, providing noise averaging through overlapped segmented FFTs. Results are numerically identical to GWpy's transfer_function.
- transient mode (gwexpy extension):
Uses direct FFT ratio without averaging:
\[\begin{split}H_{\\mathrm{transient}}(f) = \\frac{\\mathrm{FFT}_B(f)}{\\mathrm{FFT}_A(f)}\end{split}\]Use this for single-shot transient response analysis where averaging would obscure the instantaneous transfer characteristics. Employs the corrected transient FFT with proper DC/Nyquist handling.
- division semantics (steady/transient):
den == 0, num == 0 -> NaN (real: np.nan, complex: np.nan + 1j*np.nan)
den == 0, num > 0 -> +inf (complex dtype: np.inf + 0j)
den == 0, num < 0 -> -inf (complex dtype: -np.inf + 0j)
den == 0, complex num (imag != 0) -> inf * exp(1j * angle(num))
サンプル
Steady-state transfer function (GWpy-compatible):
>>> tf = reference.transfer_function(test, mode="steady", fftlength=1.0)
Transient transfer function:
>>> tf = input_signal.transfer_function(output_signal, mode="transient")
- transpose(*axes)
Returns a view of the array with axes transposed.
Refer to numpy.transpose for full documentation.
- パラメータ:
axes (None, tuple of ints, or n ints) --
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means that the array's i-th axis becomes the transposed array's j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a "convenience" alternative to the tuple form).
- 戻り値:
p -- View of the array with its axes suitably permuted.
- 戻り値の型:
ndarray
参考
transposeEquivalent function.
ndarray.TArray property returning the array transposed.
ndarray.reshapeGive a new shape to an array without changing its data.
サンプル
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.transpose() array([[1, 3], [2, 4]]) >>> a.transpose((1, 0)) array([[1, 3], [2, 4]]) >>> a.transpose(1, 0) array([[1, 3], [2, 4]])
>>> a = np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> a.transpose() array([1, 2, 3, 4])
- property unit: UnitBase | None
The physical unit of these data.
- unwrap_phase(deg: bool = False, **kwargs: Any) TimeSeriesSignalMixin
Alias for instantaneous_phase(unwrap=True).
- update(other: QuantityLike, *, inplace: bool = True, gap: Literal['raise', 'ignore', 'pad'] | None = None, pad: float | None = None) Self
Update this series by appending new data like a buffer.
Old data (at the start) are dropped to maintain a fixed size.
This is a convenience method that just calls ~Series.append with
resize=False.- パラメータ:
other (Series, numpy.ndarray) -- The data to add to the end of this Series.
inplace (bool) -- If True (default) modify the data in place. If False copy the data to new memory.
gap (str, optional) --
Action to perform if there's a gap between the other series and this one. One of
'raise'- raise a ValueError'ignore'- remove gap and join data'pad'- pad gap with zeros
If
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.
- 戻り値:
series -- Either the same series (if
inplace=True) or a new series (ifinplace=False) withotherdata added to the end of this 'buffer'.- 戻り値の型:
Series
参考
appendFor details of the data manipulation.
- property value
The numerical value of this instance.
参考
to_valueGet the numerical value in a given unit.
- value_at(x: QuantityLike) Quantity
Return the value of this Series at the given xindex value.
- パラメータ:
x (float, ~astropy.units.Quantity) -- The xindex value at which to search.
- 戻り値:
y -- The value of this Series at the given xindex value.
- 戻り値の型:
~astropy.units.Quantity
- 例外:
IndexError -- If
xdoesn't match an X-index value.
- var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True, ignore_nan=False)
- view([dtype][, type])
New view of array with the same data.
注釈
Passing None for
dtypeis different from omitting the parameter, since the former invokesdtype(None)which is an alias fordtype('float64').- パラメータ:
dtype (data-type or ndarray sub-class, optional) -- Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the
typeparameter).type (Python type, optional) -- Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.
メモ
a.view()is used two different ways:a.view(some_dtype)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.バージョン 1.23.0 で変更: Only the last axis needs to be contiguous. Previously, the entire array had to be C-contiguous.
サンプル
>>> import numpy as np >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
Viewing array data using a different type and dtype:
>>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)]) >>> y = x.view(dtype=nonneg, type=np.recarray) >>> x["a"] array([-1], dtype=int8) >>> y.a array([255], dtype=uint8)
Creating a view on a structured array so it can be used in calculations
>>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([2., 3.])
Making changes to the view changes the underlying array
>>> xv[0,1] = 20 >>> x array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
Using a view to convert an array to a recarray:
>>> z = x.view(np.recarray) >>> z.a array([1, 3], dtype=int8)
Views share data:
>>> x[0] = (9, 10) >>> z[0] np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
>>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16) >>> y = x[:, ::2] >>> y array([[1, 3], [4, 6]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): ... ValueError: To change to a dtype of a different size, the last axis must be contiguous >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 3)], [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
However, views that change dtype are totally fine for arrays with a contiguous last axis, even if the rest of the axes are not C-contiguous:
>>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4) >>> x.transpose(1, 0, 2).view(np.int16) array([[[ 256, 770], [3340, 3854]], [[1284, 1798], [4368, 4882]], [[2312, 2826], [5396, 5910]]], dtype=int16)
- whiten(fftlength: float | None = None, overlap: float = 0, method: str = 'median', window: WindowLike = 'hann', detrend: Literal['linear', 'constant'] = 'constant', asd: FrequencySeries | None = None, fduration: float = 2, highpass: float | None = None, **kwargs) Self
Whiten this TimeSeries using inverse spectrum truncation.
- パラメータ:
fftlength (float, optional) -- FFT integration length (in seconds) for ASD estimation.
overlap (float, optional) -- Number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0.
method (str, optional) -- FFT-averaging method (default:
'median').window (str, numpy.ndarray, optional) -- Window function to apply to timeseries prior to FFT, see
scipy.signal.get_window()for details on acceptable formats.detrend (str, optional) -- Type of detrending to do before FFT (see ~TimeSeries.detrend for more details).
asd (~gwpy.frequencyseries.FrequencySeries, optional) -- The amplitude spectral density using which to whiten the data, overrides other ASD arguments, default: None.
fduration (float, optional) -- Duration (in seconds) of the time-domain FIR whitening filter, must be no longer than fftlength, default: 2 seconds.
highpass (float, optional) -- Highpass corner frequency (in Hz) of the FIR whitening filter.
kwargs -- Other keyword arguments are passed to the TimeSeries.asd method to estimate the amplitude spectral density FrequencySeries of this TimeSeries.
- 戻り値:
out -- A whitened version of the input data with zero mean and unit variance.
- 戻り値の型:
TimeSeries
参考
TimeSeries.asdFor details on the ASD calculation.
TimeSeries.convolveFor details on convolution with the overlap-save method.
gwpy.signal.filter_design.fir_from_transferFor FIR filter design through spectrum truncation.
メモ
The accepted
methodarguments are:'bartlett': a mean average of non-overlapping periodograms'median': a median average of overlapping periodograms'welch': a mean average of overlapping periodograms
The
windowargument is used in ASD estimation, FIR filter design, and in preventing spectral leakage in the output.Due to filter settle-in, a segment of length
0.5*fdurationwill be corrupted at the beginning and end of the output. See ~TimeSeries.convolve for more details.The input is detrended and the output normalised such that, if the input is stationary and Gaussian, then the output will have zero mean and unit variance.
For more on inverse spectrum truncation, see arXiv:gr-qc/0509116.
- xcorr(other: Any, *, maxlag: float | None = None, normalize: str | None = None, mode: str = 'full', demean: bool = True) TimeSeriesSignalMixin
Compute the time-domain cross-correlation between two TimeSeries.
- property xindex: Index
Positions of the data on the x-axis.
- property xspan: Segment
X-axis [low, high) segment encompassed by these data.
- property xunit: UnitBase
Unit of x-axis index.
- zip() ndarray
Zip the xindex and value arrays of this Series.
- 戻り値:
stacked -- The array formed by stacking the the xindex and value of this series
- 戻り値の型:
2-d numpy.ndarray
サンプル
>>> a = Series([0, 2, 4, 6, 8], xindex=[-5, -4, -3, -2, -1]) >>> a.zip() array([[-5., 0.], [-4., 2.], [-3., 4.], [-2., 6.], [-1., 8.]])
- zpk(zeros: ArrayLike1D, poles: ArrayLike1D, gain: float, *, analog: bool = False, unit: str = 'rad/s', normalize_gain: bool = False, filtfilt: bool = True, **kwargs) TimeSeries
Filter this TimeSeries by applying a digital zero-pole-gain filter.
- パラメータ:
zeros (array-like) -- Zeros of the transfer function.
poles (array-like) -- Poles of the transfer function.
gain (float) -- System gain.
analog (bool, optional) -- Type of filter being applied. If
analog=Truethe zeros/poles/gain will be transformed from analogue (s-plane) to digital (z-plane) representation using the bilinear transform.unit (str) -- 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").filtfilt (bool, optional) -- If True (default), apply the filter using a forward-backward filter design, otherwise apply the filter in a single pass.
kwargs -- Other keyword arguments are passed to the filter method.
- 戻り値:
timeseries -- The filtered version of the input data.
- 戻り値の型:
TimeSeries
参考
TimeSeries.filterFor details on how a digital ZPK-format filter is applied.
gwpy.signal.filter_design.prepare_digital_filterFor details on preparing the digital ZPK filter for application.
サンプル
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)
- df: Any
- channel_names: Any
Module Contents#
gwexpy.timeseries - Time series data containers and operations.
- class gwexpy.timeseries.TimeSeriesDict
ベースクラス:
PlotMixin,DictMapMixin,PhaseMethodsMixin,TimeSeriesDictA dictionary of TimeSeries, indexed by name.
TimeSeriesDict is a specialized dictionary designed to hold and manipulate multiple TimeSeries objects simultaneously. It provides batch processing methods (e.g., resample, filter, fft) that operate on all entries at once, and supports advanced I/O for multi-channel data (HDF5, Zarr, CSV).
- パラメータ:
*args -- A mapping or iterable of (key, TimeSeries) pairs.
**kwargs -- Additional keyword arguments for the dictionary.
メモ
This class is highly interoperable, supporting conversions to and from Pandas DataFrames, Polars DataFrames, and MNE Raw objects. It also supports matrix conversion via to_matrix().
Key methods:
read(source, *args[, parallel, nproc])Read a TimeSeriesDict from a supported source.
write(target, *args, **kwargs)Write the collection to a supported target.
plot([label, method, figsize, xscale])Plot the data for this TimeSeriesDict.
resample(rate, **kwargs)Resample items in the TimeSeriesDict.
fft(*args, **kwargs)Apply FFT to each TimeSeries.
psd(*args, **kwargs)Compute PSD for each TimeSeries.
サンプル
>>> from gwexpy.timeseries import TimeSeries, TimeSeriesDict >>> tsd = TimeSeriesDict() >>> tsd['H1'] = TimeSeries([1, 2], sample_rate=1) >>> tsd {'H1': <TimeSeries([1, 2], unit=Unit(dimensionless), t0=<Quantity 0. s>, dt=<Quantity 1. s>, name=None, channel=None)>}
- append(other, *, copy=True, **kwargs) TimeSeriesDict
Append another mapping of TimeSeries or a single TimeSeries to each item.
- asd(*args, **kwargs)
Compute ASD for each TimeSeries. Returns a FrequencySeriesDict.
- asfreq(*args, **kwargs)
Apply asfreq to each TimeSeries in the dict.
- average_fft(*args, **kwargs)
Apply average_fft to each TimeSeries. Returns a FrequencySeriesDict.
- baseband(*args, **kwargs)
Apply baseband to each item.
- coherence(other=None, *args, fftlength=None, overlap=None, window='hann', symmetric=True, include_diagonal=True, diagonal_value=1.0, **kwargs)
Compute coherence for each element or as a matrix depending on other.
- coherence_matrix(other=None, *args, fftlength=None, overlap=None, window='hann', symmetric=True, include_diagonal=True, diagonal_value=1.0, **kwargs)
Compute coherence matrix for all pairs.
- パラメータ:
other (TimeSeriesDict or TimeSeriesList, optional) -- Another collection for cross-coherence.
*args -- Positional arguments forwarded to TimeSeries.coherence.
fftlength (float, optional) -- FFT length in seconds.
overlap (float, optional) -- Overlap between segments in seconds.
window (str, optional) -- Window function name (default 'hann').
symmetric (bool, optional) -- If True, exploit symmetry (default True).
include_diagonal (bool, optional) -- Whether to include diagonal elements (default True).
diagonal_value (float, optional) -- Value for diagonal elements (default 1.0).
**kwargs -- Additional keyword arguments forwarded to TimeSeries.coherence.
- 戻り値:
The coherence matrix.
- 戻り値の型:
メモ
If include_diagonal is True and diagonal_value is not None, the diagonal is filled with that value without computation. If diagonal_value is None, the diagonal coherence is computed. Uncomputed elements are represented as NaN. The frequency axis is taken from the first computed element without alignment/truncation; dt and fftlength consistency is enforced before computation.
- correlation(other=None, **kwargs)
Compute correlation. Vectorized via TimeSeriesMatrix.
- crop(start=None, end=None, *, copy=False) TimeSeriesDict
Crop each TimeSeries in place and return
self.Accepts any time format supported by gwexpy.time.to_gps (str, datetime, pandas, obspy, etc).
- csd(other=None, *args, fftlength=None, overlap=None, window='hann', hermitian=True, include_diagonal=True, **kwargs)
Compute CSD for each element or as a matrix depending on other.
- csd_matrix(other=None, *args, fftlength=None, overlap=None, window='hann', hermitian=True, include_diagonal=True, **kwargs)
Compute Cross-Spectral Density matrix for all pairs.
- パラメータ:
other (TimeSeriesDict or TimeSeriesList, optional) -- Another collection for cross-CSD. If None, compute self-CSD matrix.
*args -- Positional arguments forwarded to TimeSeries.csd.
fftlength (float, optional) -- FFT length in seconds.
overlap (float, optional) -- Overlap between segments in seconds.
window (str, optional) -- Window function name (default 'hann').
hermitian (bool, optional) -- If True, exploit Hermitian symmetry (default True).
include_diagonal (bool, optional) -- Must be True for CSD matrices; False raises ValueError because the diagonal is always the PSD.
**kwargs -- Additional keyword arguments forwarded to TimeSeries.csd.
- 戻り値:
The CSD matrix.
- 戻り値の型:
メモ
The diagonal of a self-CSD matrix is always computed as the PSD. Any uncomputed elements are represented as complex NaN. The frequency axis is taken from the first computed element without alignment/truncation; dt and fftlength consistency is enforced before computation.
- decimate(*args, **kwargs)
Decimate each TimeSeries in the dict.
- degree(*args, **kwargs)
Compute instantaneous phase (in degrees) of each item.
- detrend(*args, **kwargs)
Detrend each TimeSeries in the dict.
- distance_correlation(other, **kwargs)
Compute distance correlation. Vectorized via TimeSeriesMatrix.
- envelope(*args, **kwargs)
Apply envelope to each item.
- fft(*args, **kwargs)
Apply FFT to each TimeSeries. Returns a FrequencySeriesDict.
- filter(*args, **kwargs)
Filter each TimeSeries in the dict.
- classmethod from_control(response: Any, **kwargs) TimeSeriesDict
Create TimeSeriesDict from python-control TimeResponseData.
- パラメータ:
response (control.TimeResponseData) -- The simulation result from python-control.
**kwargs (dict) -- Additional arguments passed to the TimeSeries constructor.
- 戻り値:
The converted time-domain data.
- 戻り値の型:
TimeSeriesDict
- classmethod from_mne(raw, *, unit_map=None)
Create from mne.io.Raw.
- classmethod from_obspy(stream, *, unit=None, name_policy='id')
Create a TimeSeriesDict from an obspy.Stream (or Trace).
Each Trace in the Stream becomes a TimeSeries, keyed by its name (per
name_policy).
- classmethod from_pandas(df, *, unit_map=None, t0=None, dt=None)
Create TimeSeriesDict from pandas.DataFrame.
- classmethod from_polars(df, *, time_column='time', unit_map=None)
Create TimeSeriesDict from polars.DataFrame.
- gate(*args, **kwargs)
Gate each TimeSeries in the dict.
- heterodyne(*args, **kwargs)
Apply heterodyne to each item.
- hilbert(*args, **kwargs)
Apply Hilbert transform to each item.
- histogram(*args, **kwargs)
Compute Histogram for each TimeSeries. Returns a HistogramDict.
- ica(*args, **kwargs)
Perform ICA decomposition across channels.
- impute(*args, **kwargs)
Apply impute to each item.
- instantaneous_frequency(*args, **kwargs)
Apply instantaneous_frequency to each item.
- instantaneous_phase(*args, **kwargs)
Apply instantaneous_phase to each item.
- is_contiguous(*args, **kwargs)
Check contiguity with another object for each TimeSeries.
- ktau(other, **kwargs)
Compute Kendall's tau. Vectorized via TimeSeriesMatrix.
- kurtosis(**kwargs)
Compute kurtosis. Vectorized via TimeSeriesMatrix.
- lock_in(*args, **kwargs)
Apply lock_in to each item.
Returns TimeSeriesDict (if output='complex') or tuple of TimeSeriesDicts.
- mask(*args, **kwargs)
Mask each TimeSeries in the dict.
- max(**kwargs)
Compute maximum. Vectorized via TimeSeriesMatrix.
- mean(**kwargs)
Compute mean. Vectorized via TimeSeriesMatrix.
- mic(other, **kwargs)
Compute MIC. Vectorized via TimeSeriesMatrix.
- min(**kwargs)
Compute minimum. Vectorized via TimeSeriesMatrix.
- mix_down(*args, **kwargs)
Apply mix_down to each item.
- notch(*args, **kwargs)
Notch filter each TimeSeries in the dict.
- pca(*args, **kwargs)
Perform PCA decomposition across channels.
- pcc(other, **kwargs)
Compute Pearson correlation. Vectorized via TimeSeriesMatrix.
- plot(label: str = 'key', method: str = 'plot', figsize: tuple[float, float] = (12, 4), xscale: str = 'auto-gps', **kwargs) Plot
Plot the data for this TimeSeriesDict.
- prepend(other, **kwargs) TimeSeriesDict
Prepend
otherto this mapping key by key.Returns self.
- psd(*args, **kwargs)
Compute PSD for each TimeSeries. Returns a FrequencySeriesDict.
- q_transform(*args, **kwargs)
Compute Q-transform for each TimeSeries. Returns a SpectrogramDict.
- radian(*args, **kwargs)
Compute instantaneous phase (in radians) of each item.
- classmethod read(source, *args: Any, parallel=None, nproc=None, **kwargs: Any)
Read a TimeSeriesDict from a supported source.
GWexpy GWF parallel reads#
parallel=acceptsNone/False/1for serial reads,Truefor automatic workers, or an integer from 2 through 8.nproc=is the compatibility alias. Supplying both raisesTypeErrorbefore file or backend I/O. Multi-worker reads require a list or tuple of individual local.gwfframe paths (not URIs, caches, queries, globs, or file-like objects), use spawn-safe workers, and propagate worker exceptions, includingImportError, unchanged. Daemon processes cannot start these workers and are rejected during preflight.
- resample(rate, **kwargs)
Resample items in the TimeSeriesDict.
In-place operation (updates the dict contents).
If rate is time-like, performs time-bin resampling. Otherwise performs signal processing resampling (gwpy's native behavior).
- rms(**kwargs)
Compute root-mean-square. Vectorized via TimeSeriesMatrix.
- rolling_max(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling max to each item.
- rolling_mean(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling mean to each item.
- rolling_median(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling median to each item.
- rolling_min(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling min to each item.
- rolling_std(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ddof=0, ignore_nan=None)
Apply rolling std to each item.
- shift(*args, **kwargs)
Shift each TimeSeries in the dict.
- skewness(**kwargs)
Compute skewness. Vectorized via TimeSeriesMatrix.
- spectrogram(*args, **kwargs)
Compute spectrogram for each TimeSeries. Returns a SpectrogramDict.
- spectrogram2(*args, **kwargs)
Compute spectrogram2 for each TimeSeries. Returns a SpectrogramDict.
- state_segments(*args, **kwargs)
Run state_segments on each item (returns Series of SegmentLists).
- std(**kwargs)
Compute standard deviation. Vectorized via TimeSeriesMatrix.
- taper(*args, **kwargs)
Taper each TimeSeries in the dict.
- to_matrix(*, align='intersection', **kwargs)
Convert the dictionary to a TimeSeriesMatrix with alignment.
- to_mne(info=None, picks=None)
Convert to mne.io.RawArray.
- to_obspy(*, stats_extra=None, dtype=None)
Convert to an obspy.Stream (one Trace per TimeSeries).
- to_pandas(index='datetime', *, copy=False)
Convert to pandas.DataFrame.
- to_polars(time_column='time', time_unit='datetime')
Convert to polars.DataFrame.
- unwrap_phase(*args, **kwargs)
Apply unwrap_phase to each item.
- value_at(*args, **kwargs)
Get value at a specific time for each TimeSeries.
- whiten(*args, **kwargs)
Whiten each TimeSeries in the dict.
- zpk(*args, **kwargs)
Apply ZPK filter to each TimeSeries in the dict.
- class gwexpy.timeseries.TimeSeriesList(*items: _T)
ベースクラス:
PlotMixin,ListMapMixin,PhaseMethodsMixin,TimeSeriesListA list of TimeSeries objects.
TimeSeriesList is a specialized list designed to hold and manipulate multiple TimeSeries objects. It provides batch processing methods that operate on all entries at once.
- パラメータ:
*args -- An iterable of TimeSeries objects.
メモ
Key methods:
plot(**kwargs)Plot this object using
gwexpy.plot.Plot.append(item)Append object to the end of the list.
extend(item)Extend list by appending elements from the iterable.
csd_matrix([other, fftlength, overlap, ...])Compute Cross Spectral Density Matrix.
coherence_matrix([other, fftlength, ...])Compute Coherence Matrix.
サンプル
>>> from gwexpy.timeseries import TimeSeries, TimeSeriesList >>> tsl = TimeSeriesList([TimeSeries([1, 2], sample_rate=1)]) >>> tsl [<TimeSeries([1, 2], unit=Unit(dimensionless), t0=<Quantity 0. s>, dt=<Quantity 1. s>, name=None, channel=None)>]
- asd(*args, **kwargs)
Compute ASD for each TimeSeries. Returns a FrequencySeriesList.
- average_fft(*args, **kwargs)
Apply average_fft to each TimeSeries. Returns a FrequencySeriesList.
- baseband(*args, **kwargs)
Apply baseband to each item.
- coherence(other=None, *args, fftlength=None, overlap=None, window='hann', symmetric=True, include_diagonal=True, diagonal_value=1.0, **kwargs)
Compute coherence for each element or as a matrix depending on other.
- coherence_matrix(other=None, *args, fftlength=None, overlap=None, window='hann', symmetric=True, include_diagonal=True, diagonal_value=1.0, **kwargs)
Compute Coherence Matrix.
- パラメータ:
other (TimeSeriesDict or TimeSeriesList, optional) -- Other collection.
*args -- Positional arguments forwarded to TimeSeries.coherence.
fftlength -- See TimeSeries.coherence().
overlap -- See TimeSeries.coherence().
window -- See TimeSeries.coherence().
symmetric (bool, default=True) -- If True and other is None, compute only upper triangle and copy to lower.
include_diagonal (bool, default=True) -- Include diagonal.
diagonal_value (float or None, default=1.0) -- Value to fill diagonal if include_diagonal is True. If None, compute diagonal coherence.
**kwargs -- Additional keyword arguments forwarded to TimeSeries.coherence.
- 戻り値の型:
メモ
If include_diagonal is True and diagonal_value is not None, the diagonal is filled with that value without computation. If diagonal_value is None, the diagonal coherence is computed. Uncomputed elements are represented as NaN. The frequency axis is taken from the first computed element without alignment/truncation; dt and fftlength consistency is enforced before computation.
- correlation(other=None, **kwargs)
Compute correlation. Vectorized via TimeSeriesMatrix.
- crop(start=None, end=None, copy=False) TimeSeriesList
Crop each
TimeSeriesin the list.Accepts any time format supported by gwexpy.time.to_gps (str, datetime, pandas, obspy, etc). Returns a new TimeSeriesList.
- csd(other=None, *args, fftlength=None, overlap=None, window='hann', hermitian=True, include_diagonal=True, **kwargs)
Compute CSD for each element or as a matrix depending on other.
- csd_matrix(other=None, *args, fftlength=None, overlap=None, window='hann', hermitian=True, include_diagonal=True, **kwargs)
Compute Cross Spectral Density Matrix.
- パラメータ:
other (TimeSeriesDict or TimeSeriesList, optional) -- Other collection for cross-CSD.
*args -- Positional arguments forwarded to TimeSeries.csd.
fftlength -- See TimeSeries.csd() arguments.
overlap -- See TimeSeries.csd() arguments.
window -- See TimeSeries.csd() arguments.
hermitian (bool, default=True) -- If True and other is None, compute only upper triangle and conjugate fill lower.
include_diagonal (bool, default=True) -- Must be True for CSD matrices; False raises ValueError because the diagonal is always the PSD.
**kwargs -- Additional keyword arguments forwarded to TimeSeries.csd.
- 戻り値の型:
メモ
The diagonal of a self-CSD matrix is always computed as the PSD. Any uncomputed elements are represented as complex NaN. The frequency axis is taken from the first computed element without alignment/truncation; dt and fftlength consistency is enforced before computation.
- decimate(*args, **kwargs)
Decimate each TimeSeries in the list.
- degree(*args, **kwargs)
Compute instantaneous phase (in degrees) of each item.
- detrend(*args, **kwargs)
Detrend each TimeSeries in the list.
- envelope(*args, **kwargs)
Apply envelope to each item.
- fft(*args, **kwargs)
Apply FFT to each TimeSeries. Returns a FrequencySeriesList.
- filter(*args, **kwargs)
Filter each TimeSeries in the list.
- gate(*args, **kwargs)
Gate each TimeSeries in the list.
- heterodyne(*args, **kwargs)
Apply heterodyne to each item.
- hilbert(*args, **kwargs)
Apply Hilbert transform to each item.
- histogram(*args, **kwargs)
Compute Histogram for each TimeSeries. Returns a HistogramList.
- ica(*args, **kwargs)
Perform ICA decomposition across channels.
- impute(*, method='interpolate', limit=None, axis='time', max_gap=None, **kwargs)
Impute missing data (NaNs) in each TimeSeries.
- パラメータ:
method (str, optional) -- Imputation method ('interpolate', 'fill', etc.).
limit (int, optional) -- Maximum number of consecutive NaNs to fill.
axis (str, optional) -- Axis to impute along.
max_gap (float, optional) -- Maximum gap size to fill (in seconds).
**kwargs -- Passed to TimeSeries.impute().
- 戻り値の型:
TimeSeriesList
- instantaneous_frequency(*args, **kwargs)
Apply instantaneous_frequency to each item.
- instantaneous_phase(*args, **kwargs)
Apply instantaneous_phase to each item.
- is_contiguous(*args, **kwargs)
Check contiguity with another object for each TimeSeries.
- kurtosis(**kwargs)
Compute kurtosis. Vectorized via TimeSeriesMatrix.
- lock_in(*args, **kwargs)
Apply lock_in to each item.
- mask(*args, **kwargs)
Mask each TimeSeries in the list.
- max(**kwargs)
Compute maximum. Vectorized via TimeSeriesMatrix.
- mean(**kwargs)
Compute mean. Vectorized via TimeSeriesMatrix.
- mic(other, **kwargs)
Compute MIC. Vectorized via TimeSeriesMatrix.
- min(**kwargs)
Compute minimum. Vectorized via TimeSeriesMatrix.
- mix_down(*args, **kwargs)
Apply mix_down to each item.
- notch(*args, **kwargs)
Notch filter each TimeSeries in the list.
- pca(*args, **kwargs)
Perform PCA decomposition across channels.
- psd(*args, **kwargs)
Compute PSD for each TimeSeries. Returns a FrequencySeriesList.
- q_transform(*args, **kwargs)
Compute Q-transform for each TimeSeries. Returns a SpectrogramList.
- radian(*args, **kwargs)
Compute instantaneous phase (in radians) of each item.
- resample(*args, **kwargs)
Resample each TimeSeries in the list.
- rms(**kwargs)
Compute root-mean-square. Vectorized via TimeSeriesMatrix.
- rolling_max(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling max to each element.
- rolling_mean(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling mean to each element.
- rolling_median(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling median to each element.
- rolling_min(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ignore_nan=None)
Apply rolling min to each element.
- rolling_std(window, *, center=False, min_count=1, nan_policy='omit', backend='auto', ddof=0, ignore_nan=None)
Apply rolling std to each element.
- shift(*args, **kwargs)
Shift each TimeSeries in the list.
- skewness(**kwargs)
Compute skewness. Vectorized via TimeSeriesMatrix.
- spectrogram(*args, **kwargs)
Compute spectrogram for each TimeSeries. Returns a SpectrogramList.
- spectrogram2(*args, **kwargs)
Compute spectrogram2 for each TimeSeries. Returns a SpectrogramList.
- std(**kwargs)
Compute standard deviation. Vectorized via TimeSeriesMatrix.
- taper(*args, **kwargs)
Taper each TimeSeries in the list.
- to_matrix(*, align='intersection', **kwargs)
Convert list to TimeSeriesMatrix with alignment.
- パラメータ:
align (str, optional) -- Alignment strategy ('intersection', 'union', etc.). Default 'intersection'.
**kwargs -- Additional arguments passed to alignment function.
- 戻り値:
Matrix with all series aligned to common time axis.
- 戻り値の型:
- to_pandas(**kwargs)
Convert a
TimeSeriesListto a pandasDataFrame.Each element becomes a column. ASSUMES common time axis.
- unwrap_phase(*args, **kwargs)
Apply unwrap_phase to each item.
- value_at(*args, **kwargs)
Get value at a specific time for each TimeSeries.
- whiten(*args, **kwargs)
Whiten each TimeSeries in the list.
- zpk(*args, **kwargs)
ZPK filter each TimeSeries in the list.
- class gwexpy.timeseries.TimeSeriesMatrix(data: ndarray | list | tuple | _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | TimeSeries | TimeSeriesMatrix | None = None, times: XIndex | Quantity | ndarray | None = None, dt: float | Quantity | None = None, t0: float | Quantity | None = None, sample_rate: float | Quantity | None = None, epoch: float | Quantity | None = None, **kwargs: Any)
ベースクラス:
PhaseMethodsMixin,TimeSeriesMatrixCoreMixin,TimeSeriesMatrixAnalysisMixin,TimeSeriesMatrixSpectralMixin,TimeSeriesMatrixInteropMixin,SeriesMatrixA 2D matrix of TimeSeries objects sharing a common time axis.
TimeSeriesMatrix represents a 2-dimensional array (rows x columns) where each element is a TimeSeries. All elements in the matrix must share the same time synchronization (same t0, dt, and number of samples).
This class is ideal for representing multi-channel data from a detector sub-system or a set of sensors where the spatial or logical relationship is best represented as a grid.
- パラメータ:
data (array-like) -- The data values for the matrix. Should be of shape (rows, columns, samples).
times (array-like, optional) -- The time values corresponding to each sample. If provided, dt and t0 are ignored.
dt (float, ~astropy.units.Quantity, optional) -- The time step between samples.
t0 (float, ~astropy.units.Quantity, optional) -- The start time of the data.
sample_rate (float, ~astropy.units.Quantity, optional) -- The sample rate of the data (1/dt).
epoch (float, ~astropy.units.Quantity, optional) -- The epoch of the data.
**kwargs -- Additional keyword arguments: - channel_names: list of strings for channel labels. - unit: physical unit of the data. - name: descriptive title for the matrix.
メモ
TimeSeriesMatrix supports element-wise signal processing (e.g., detrend, filter, resample) and bivariate spectral methods (e.g., csd, coherence) between matrices.
Key methods:
plot(**kwargs)Plot this object using
gwexpy.plot.Plot.fft(**kwargs)Compute the FFT of each element.
psd(**kwargs)Compute the PSD of each element.
csd(other, *args, **kwargs)Apply TimeSeries.csd element-wise with another TimeSeries object.
coherence(other, *args, **kwargs)Apply TimeSeries.coherence element-wise with another TimeSeries object.
to_dict()Convert matrix to an appropriate collection dict (e.g. TimeSeriesDict).
サンプル
>>> from gwexpy.timeseries import TimeSeriesMatrix >>> import numpy as np >>> data = np.ones((2, 2, 3)) >>> tsm = TimeSeriesMatrix(data, sample_rate=1, unit='m') >>> tsm <SeriesMatrix shape=(2, 2, 3) rows=('row0', 'row1') cols=('col0', 'col1')>
- auto_coherence(*args, **kwargs)
Apply univariate spectral method TimeSeries.auto_coherence element-wise.
Computes the auto_coherence for each entry in the matrix, returning a FrequencySeriesMatrix containing the results.
- bandpass(*args, **kwargs)
Apply TimeSeries.bandpass element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- coherence(other, *args, **kwargs)
Apply TimeSeries.coherence element-wise with another TimeSeries object.
This method delegates the bivariate call to each TimeSeries in the matrix, using the provided other object as the second operand.
- csd(other, *args, **kwargs)
Apply TimeSeries.csd element-wise with another TimeSeries object.
This method delegates the bivariate call to each TimeSeries in the matrix, using the provided other object as the second operand.
- default_xunit = 's'
- detrend(*args, **kwargs)
Apply TimeSeries.detrend element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- dict_class
TimeSeriesDictの別名です。
- filter(*args, **kwargs)
Apply TimeSeries.filter element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- highpass(*args, **kwargs)
Apply TimeSeries.highpass element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- list_class
TimeSeriesListの別名です。
- lowpass(*args, **kwargs)
Apply TimeSeries.lowpass element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- notch(*args, **kwargs)
Apply TimeSeries.notch element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- classmethod read(source, *args: Any, **kwargs: Any)
Read a TimeSeriesMatrix from a supported source.
- resample(*args, **kwargs)
Apply TimeSeries.resample element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- series_class
TimeSeriesの別名です。
- series_type = 'time'
- taper(*args, **kwargs)
Apply TimeSeries.taper element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- transfer_function(other, *args, **kwargs)
Apply TimeSeries.transfer_function element-wise with another TimeSeries object.
This method delegates the bivariate call to each TimeSeries in the matrix, using the provided other object as the second operand.
- whiten(*args, **kwargs)
Apply TimeSeries.whiten element-wise to all entries in the matrix.
This method delegates the call to the underlying TimeSeries objects, preserving the matrix structure and per-element metadata while updating the data values and time axis according to the operation.
- meta: MetaDataMatrix
- rows: MetaDataDict
- cols: MetaDataDict
- unit: u.Unit | None
- class gwexpy.timeseries.Transform
ベースクラス:
objectBase interface for reusable preprocessing transforms.
Subclasses implement
transform()and optionallyfit()andinverse_transform(). The interface accepts individual TimeSeries objects as well as GWexpy collections such as TimeSeriesMatrix, TimeSeriesDict, and TimeSeriesList.サンプル
>>> transform = ImputeTransform(method="interpolate") >>> filled = transform.fit_transform(ts) >>> filled.shape == ts.shape True
- fit(x)
Fit the transform to the input data and return self.
- fit_transform(x)
Fit the transform and immediately apply it to x.
- inverse_transform(y)
Reverse the transform when supported by the subclass.
- supports_inverse = False
- transform(x)
Apply the transform to input data.
Subclasses must override this method.
- class gwexpy.timeseries.Pipeline(steps: Sequence[tuple[str, Transform]])
ベースクラス:
objectCompose multiple transforms into a deterministic preprocessing chain.
The pipeline applies each step in order during
fit()andtransform(), mirroring common ML preprocessing workflows while preserving GWexpy metadata and collection types.- パラメータ:
steps (sequence of (str, Transform)) -- Ordered (name, transform) pairs to execute.
サンプル
>>> pipeline = Pipeline( ... [ ... ("impute", ImputeTransform(method="interpolate")), ... ("standardize", StandardizeTransform()), ... ] ... ) >>> standardized = pipeline.fit_transform(ts_matrix) >>> standardized.shape == ts_matrix.shape True
- fit(x)
Fit each step in order using the output of the previous step.
- fit_transform(x)
Fit the pipeline and return the transformed output.
- inverse_transform(y, *, strict: bool = True)
Apply supported inverse transforms in reverse order.
- パラメータ:
y (data) -- Transformed data.
strict (bool, optional) -- If True, raise error if any step doesn't support inverse.
- transform(x)
Apply every fitted transform in sequence.
- class gwexpy.timeseries.ImputeTransform(method: str = 'interpolate', **kwargs)
ベースクラス:
TransformImpute missing values using existing lower-level helpers.
- transform(x)
Apply imputation to TimeSeries, Matrix, or Collections.
- class gwexpy.timeseries.StandardizeTransform(method: str = 'zscore', ddof: int = 0, robust: bool = False, axis: str = 'time', *, multivariate: bool = False, align: str = 'intersection')
ベースクラス:
TransformStandardize TimeSeries or matrix objects with optional robust scaling.
- fit(x)
Fit standardization parameters (center, scale) for the input data.
- inverse_transform(y)
Reverse standardization transformation.
- supports_inverse = True
- transform(x)
Apply standardization using fitted parameters.
- class gwexpy.timeseries.WhitenTransform(method: Literal['pca', 'zca'] = 'pca', eps: float | Literal['auto'] | None = 'auto', n_components: int | None = None, *, multivariate: bool = True, align: str = 'intersection')
ベースクラス:
TransformWhiten TimeSeriesMatrix-like data with PCA or ZCA.
- fit(x)
Fit whitening parameters for the input data.
- inverse_transform(y)
Reverse whitening transformation.
- supports_inverse = True
- transform(x)
Apply whitening transform.
- class gwexpy.timeseries.PCATransform(n_components: int | None = None, *, multivariate: bool = True, align: str = 'intersection', **kwargs)
ベースクラス:
TransformWrap PCA using existing decomposition helpers.
- fit(x)
Fit PCA model for the input data.
- inverse_transform(y)
Reverse PCA transformation (reconstruct from scores).
- supports_inverse = True
- transform(x)
Apply PCA transformation (project to scores).
- class gwexpy.timeseries.ICATransform(n_components: int | None = None, *, multivariate: bool = True, align: str = 'intersection', **kwargs)
ベースクラス:
TransformWrap ICA using existing decomposition helpers.
- fit(x)
Fit ICA model for the input data.
- inverse_transform(y)
Reverse ICA transformation (reconstruct from sources).
- supports_inverse = True
- transform(x)
Apply ICA transformation (project to sources).