Skip to content

striqt.waveform

Arrays and backends

Array-namespace dispatch between numpy and cupy, axis helpers, and the cupy configuration.

array_namespace

array_namespace(
    a: Array, use_compat: bool = False
) -> ModuleType

return the array API namespace of a.

Parameters:

  • a (Array) –

    a numpy or cupy array

  • use_compat (bool, default: False ) –

    True returns the array_api_compat wrapper of the namespace; False returns the numpy or cupy module itself

Returns:

  • ModuleType –

    the module that implements the array API for a

Raises:

  • TypeError –

    if a is not an array of a supported library

axis_index

axis_index(a, index, axis=-1)

Return a boolean-indexed selection on axis axis' froma'.

a: numpy.ndarray The array to be sliced. mask: boolean index array of size a.shape[axis] axis : int, optional The axis of a to be sliced.

axis_slice

axis_slice(a, start, stop=None, step=None, axis=-1)

Return a slice on the array a on the axis index axis.

a: numpy.ndarray The array to be sliced. start, stop=None, step: The arguments to slice on that axis. axis : int, optional The axis of a to be sliced.

axis_to_blocks

axis_to_blocks(
    y: Array, size: int, truncate=False, axis=0
) -> Array

Returns a view on y reshaped into blocks along axis axis.

Parameters:

  • y (Array) –

    an input array of size (N[0], ... N[K-1])

Raises:

  • TypeError –

    if not isinstance(size, int)

  • IndexError –

    if y.size == 0

  • ValueError –

    if truncate == False and y.shape[axis] % size != 0

Returns:

  • Array –

    view on y with shape (..., N[axis]//size, size, ..., N[K-1]])

binned_mean

binned_mean(
    x: Array,
    count,
    *,
    axis=0,
    truncate=True,
    reject_extrema=False,
    fft=True,
) -> Array

return the mean of x over bins of count samples along axis.

Parameters:

  • x (Array) –

    the array to bin; NaN samples are excluded from each mean

  • count –

    the number of samples per bin

  • axis –

    the axis to bin, shortened by a factor of count in the result

  • truncate –

    True drops the samples at the edges of axis that do not fill a bin; False raises ValueError for a length that is not a multiple of count

  • reject_extrema –

    True excludes the minimum and maximum sample of each bin

  • fft –

    True centers a bin on index x.shape[axis] // 2, the DC bin of an fftfreq axis, and drops edge samples symmetrically; False starts the first bin at index 0; ignored when truncate is False

Returns:

  • Array –

    the binned means, in the array namespace of x

Raises:

  • ValueError –

    if truncate is False and x.shape[axis] is not a multiple of count

configure_cupy cached

configure_cupy() -> None

set the cupy FFT plan cache size to 0 and disable the pinned-memory pool.

Both settings are global to the process: the cuFFT plan cache of the current device holds no plans, and each pinned host allocation is made by the CUDA driver rather than reused from a pool. The settings are applied once per process; later calls, and any call without cupy installed, return with no effect.

histogram_last_axis

histogram_last_axis(
    x: Array, bins: int | Array, range: tuple | None = None
) -> Array

computes a histogram along the last axis of an input array.

For reference see https://stackoverflow.com/questions/44152436/calculate-histograms-along-axis

Parameters:

  • x (Array) –

    input data of shape (M[0], ..., M[K-1], N)

  • bins (int | Array) –

    Number of bins in the histogram, or a vector of bin edges

  • range (tuple | None, default: None ) –

    Bounds on the histogram bins [lower bound, upper bound] inclusive

Returns:

  • Array –

    np.ndarray of shape (M[0], ..., M[K-1], n_bins)

is_cupy_array

is_cupy_array(x: object) -> TypeIsCupy

return whether x is a cupy.ndarray, without importing cupy.

Returns:

  • TypeIsCupy –

    True for a cupy array, and False otherwise, including when cupy is not

  • TypeIsCupy –

    installed; the result narrows the type of x for a type checker

isroundmod

isroundmod(
    value: float | ndarray, div: float, atol: float = 1e-06
) -> bool

return whether value is within atol of a whole multiple of div.

Parameters:

  • value (float | ndarray) –

    the quantity tested, a float or a numpy array of floats

  • div (float) –

    the divisor, in the units of value

  • atol (float, default: 1e-06 ) –

    the largest distance of value / div from the nearest whole number that counts as a multiple

Returns:

  • bool –

    a bool for a scalar value, or a bool array of the shape of value for an

  • bool –

    array; the result is False for a ratio that is not finite

pinned_array_as_cupy

pinned_array_as_cupy(
    x: ndarray,
    stream: Any = None,
    *,
    out: ndarray | None = None,
) -> ndarray

copy the pinned host array x to the device on stream.

The copy is asynchronous, so stream must be synchronized before x is rewritten or out is read. A C-contiguous x with the nbytes of a C-contiguous out is copied in one transfer. Otherwise out must be 2-D with the row count of x, contiguous rows, and a row pitch of at least the row bytes of x. Each row of x is then copied to the head of the matching row of out.

Parameters:

  • x (ndarray) –

    the pinned host array, C-contiguous or 2-D with contiguous rows such as a column slice

  • stream (Any, default: None ) –

    the cupy stream of the copy; None selects the current stream

  • out (ndarray | None, default: None ) –

    the device array to fill; None allocates one shaped like x

Returns:

  • ndarray –

    out, or the allocated device array

Raises:

  • ValueError –

    if x is neither C-contiguous nor 2-D with contiguous rows

  • ValueError –

    if out does not fit the copy of x

Fourier analysis and resampling

FFT and STFT evaluation, window design, overlap-add convolution, and rational resampling.

ResamplerDesign

Bases: TypedDict

the radio and COLA resampler settings that realize a target sample rate.

nfft / nfft_out equals the ratio of the radio rate to the target rate exactly, and both sizes are even multiples of the COLA divisor of window.

fs_sdr instance-attribute

fs_sdr: float

the radio sample rate (in S/s) at the resampler input

lo_offset instance-attribute

lo_offset: float

the offset (in Hz) by which the radio is tuned below the center frequency, a whole number of fs_sdr / nfft bins; 0 without an LO shift

window instance-attribute

window: str | tuple[str, float]

the COLA window of the STFT

nfft instance-attribute

nfft: int

the input block size (in samples)

nfft_out instance-attribute

nfft_out: int

the output block size (in samples)

frequency_shift instance-attribute

frequency_shift: ShiftType

the requested shift direction

passband instance-attribute

passband: tuple[float | None, float | None]

the (low, high) protected band edges (in Hz) relative to the tuned LO; (None, None) for an unbounded bandwidth

fs instance-attribute

fs: float

the radio sample rate (in S/s), equal to fs_sdr

design_cola_resampler

design_cola_resampler(
    fs_base: float,
    fs_target: float,
    bw: float = inf,
    bw_lo: float = 0,
    min_oversampling: float = 1.1,
    min_fft_size=2 * 4096 - 1,
    shift: ShiftType = False,
    window=None,
    fs_sdr: Optional[float] = None,
) -> ResamplerDesign

design the radio sample rate, LO offset, and COLA FFT sizes of a resampler.

nfft / nfft_out equals fs_sdr / fs_target exactly. The sizes are k * p and k * q for the reduced ratio p / q of fs_sdr to fs_target, with k the smallest even multiple of the COLA divisor of window that is 2·3·5·7-smooth and puts nfft_out above min_fft_size. Without fs_sdr, the radio rate is fs_base divided by the largest integer that keeps the rate at or above fs_target + min_oversampling * bw + bw_lo with shift, or at or above fs_target without. With shift, the radio is tuned lo_offset below the center frequency, and the magnitude of lo_offset is bw / 2 + bw_lo / 2 rounded up to a whole number of fs_sdr / nfft bins that is a multiple of the frames per hop of window.

Parameters:

  • fs_base (float) –

    the master clock rate (in S/s) that fs_sdr divides

  • fs_target (float) –

    the sample rate (in S/s) after resampling

  • bw (float, default: inf ) –

    the bandwidth (in Hz) to protect from LO leakage; inf disables the LO shift and leaves the passband unbounded

  • bw_lo (float, default: 0 ) –

    the bandwidth (in Hz) of the LO leakage and phase noise kept out of the protected band

  • min_oversampling (float, default: 1.1 ) –

    the factor applied to bw when sizing fs_sdr for an LO shift

  • min_fft_size –

    the size that nfft_out must exceed

  • shift (ShiftType, default: False ) –

    'left' or 'right' places the protected band below or above the tuned LO; 'none', None, or False leaves the LO at the center frequency

  • window –

    a key of the COLA window divisor table; None selects the divisor 1 for the sizes and the LO offset, and 'hann' in the result

  • fs_sdr (Optional[float], default: None ) –

    the radio sample rate (in S/s) to use instead of selecting one

Returns:

Raises:

  • ValueError –

    if shift is set while bw is infinite, shift is not a recognized direction, window has no COLA divisor, bw exceeds fs_base, the LO shift needs a radio rate above fs_base, no fraction with denominator up to OLA_MAX_FFT_SIZE realizes the rate ratio, or the LO shift does not fit the Nyquist band of the radio at fs_sdr

design_fir_lpf

design_fir_lpf(
    bw: float,
    fs: float,
    *,
    numtaps: int = 4001,
    transition_bw: float = 250000.0,
    dtype: DTypeLike = 'float32',
    xp: XpType = None,
) -> Array

return the taps of a least-squares linear-phase FIR low-pass of width bw.

The gain falls linearly from 1 at bw/2 - transition_bw/2 to 0 at bw/2 + transition_bw/2, so the gain at bw/2 is 1/2. The transition band must lie strictly inside (0, fs/2).

Parameters:

  • bw (float) –

    the passband width (in Hz), centered on 0 Hz

  • fs (float) –

    the sample rate (in S/s)

  • numtaps (int, default: 4001 ) –

    the number of taps, odd for a type I design

  • transition_bw (float, default: 250000.0 ) –

    the width (in Hz) of the transition band

  • dtype (DTypeLike, default: 'float32' ) –

    the dtype of the taps

  • xp (XpType, default: None ) –

    the array namespace of the result; None selects numpy

Returns:

  • Array –

    the numtaps taps as a 1-D array of dtype in xp

Raises:

  • ValueError –

    if the transition band reaches 0 Hz or fs/2

equivalent_noise_bandwidth

equivalent_noise_bandwidth(
    window: WindowSpecType, N, fftbins=True, cached=True
)

return the equivalent noise bandwidth (ENBW) of a window, in bins.

One bin is fs / N wide for a window of N nonzero samples (Harris 1978). The ENBW in Hz is the returned value times fs / N. An FFT of the window zero-padded to N + nzero samples has bins of fs / (N + nzero). The same ENBW spans (N + nzero) / N times as many of those bins.

Parameters:

  • window (WindowSpecType) –

    the window name or (name, parameter) for get_window

  • N –

    the number of nonzero window samples

  • fftbins –

    the get_window periodic-window flag

  • cached –

    True designs the window through the cached get_window; False designs it uncached

Returns:

  • –

    the ENBW as a float: 1.0 for a rectangular window and larger for every other

References

F. J. Harris, "On the use of windows for harmonic analysis with the discrete Fourier transform," Proc. IEEE, vol. 66, no. 1, pp. 51-83, Jan. 1978.

fft

fft(
    x: _AT,
    n: int | None = None,
    axis: int = -1,
    out: _AT | None = None,
    overwrite_x: bool = False,
    plan: Any = None,
    workers: int | None = None,
)

return the discrete Fourier transform of x along axis, on numpy or cupy.

Parameters:

  • x (_AT) –

    the input array, real or complex

  • n (int | None, default: None ) –

    the transform length on numpy, zero-padding or cropping x on axis; None selects x.shape[axis]

  • axis (int, default: -1 ) –

    the axis transformed

  • out (_AT | None, default: None ) –

    on cupy, the buffer written, with the element count of the output and its complex dtype; None allocates the output, and numpy ignores a buffer

  • overwrite_x (bool, default: False ) –

    True allows the transform to use x as scratch space

  • plan (Any, default: None ) –

    on cupy, the cuFFT plan of the transform; numpy accepts and ignores a plan

  • workers (int | None, default: None ) –

    on numpy, the thread count of scipy.fft; None selects half the CPU count, and cupy ignores the count

Returns:

  • –

    the transform, in the complex dtype of the precision of x and the array

  • –

    namespace of x; on cupy with out, a view of out with the shape of x

Raises:

  • NotImplementedError –

    on cupy when n is not None

fftfreq

fftfreq(
    nfft: int,
    fs: float,
    dtype='float64',
    as_index: bool = True,
    xp: ModuleType = np,
) -> Array

return the ascending fftfreq grid (in Hz) of nfft bins at sample rate fs.

The result is cached and must not be modified in place.

Parameters:

  • nfft (int) –

    the number of bins

  • fs (float) –

    the sample rate (in S/s)

  • dtype –

    the floating-point dtype of the result

  • as_index (bool, default: True ) –

    True evaluates each bin in decimal arithmetic, exact to the rounding of dtype; False evaluates in floating point

  • xp (ModuleType, default: np ) –

    the array namespace of the result

Returns:

  • Array –

    a 1-D array of nfft bin center frequencies from -fs/2 toward fs/2

get_max_cupy_fft_chunk

get_max_cupy_fft_chunk() -> int | None

return the sample count per group of a cupy FFT into an out= buffer.

get_window

get_window(
    name_or_tuple: WindowType,
    nwindow: int,
    nzero: int = 0,
    *,
    fftshift: bool = False,
    center_zeros: bool = False,
    fftbins: bool = True,
    norm: bool = True,
    dtype: DTypeLike = 'float32',
    xp: XpType = None,
) -> Array

return a window of nwindow samples for xp, zero-padded to nwindow + nzero.

The design is cached in memory and on disk. A call that misses both runs the scipy window design and writes to the disk cache. Equivalent spellings of the arguments (a dtype given as a string or a numpy.dtype, xp given or omitted, positional or keyword nzero) share one cache entry. A numpy result is the cached array and must not be modified in place.

Parameters:

  • name_or_tuple (WindowType) –

    a window name, (name, parameter) tuple, or Kaiser beta accepted by scipy.signal.get_window, or a name registered by register_extra_windows

  • nwindow (int) –

    the number of nonzero window samples

  • nzero (int, default: 0 ) –

    the number of zero samples appended to the window

  • fftshift (bool, default: False ) –

    True modulates the window by the half-band shift that puts the FFT of a windowed signal in ascending frequency order; the window is then complex when nwindow + nzero is odd

  • center_zeros (bool, default: False ) –

    True splits the nzero zeros before and after the window; False appends all nzero zeros after the window

  • fftbins (bool, default: True ) –

    True for a periodic window (spectral analysis), False for a symmetric one, as in scipy.signal.get_window

  • norm (bool, default: True ) –

    True scales the window to unit time-averaged power

  • dtype (DTypeLike, default: 'float32' ) –

    the floating-point precision of the result (the complex counterpart when fftshift makes the window complex); None keeps scipy's float64

  • xp (XpType, default: None ) –

    the array namespace of the result; None selects numpy

Returns:

  • Array –

    a 1-D array of nwindow + nzero samples in xp

ifft

ifft(
    x: _AT,
    n: int | None = None,
    axis: int = -1,
    out: _AT | None = None,
    overwrite_x: bool = False,
    plan: Any = None,
    workers: int | None = None,
)

return the inverse of fft along axis, on numpy or cupy.

The output is scaled by 1 / n so that ifft inverts fft.

Parameters:

  • x (_AT) –

    the input array, real or complex

  • n (int | None, default: None ) –

    the transform length on numpy, zero-padding or cropping x on axis; None selects x.shape[axis]

  • axis (int, default: -1 ) –

    the axis transformed

  • out (_AT | None, default: None ) –

    on cupy, the buffer written, with the element count of the output and its complex dtype; None allocates the output, and numpy ignores a buffer

  • overwrite_x (bool, default: False ) –

    True allows the transform to use x as scratch space

  • plan (Any, default: None ) –

    on cupy, the cuFFT plan of the transform; numpy accepts and ignores a plan

  • workers (int | None, default: None ) –

    on numpy, the thread count of scipy.fft; None selects half the CPU count, and cupy ignores the count

Returns:

  • –

    the transform, in the complex dtype of the precision of x and the array

  • –

    namespace of x; on cupy with out, a view of out with the shape of x

Raises:

  • NotImplementedError –

    on cupy when n is not None

istft

istft(
    y: Array,
    size=None,
    *,
    nfft: int,
    noverlap: int,
    out=None,
    overwrite_x=False,
    axis=0,
    fftshift: bool = True,
) -> Array

reconstruct the waveform from the STFT y by inverse FFT and overlap-add.

y has windows on axis and nfft frequency bins on axis + 1. The windows are overlap-added at a hop of nfft - noverlap samples.

Parameters:

  • y (Array) –

    the STFT, with at least 2 dimensions

  • size –

    the number of output samples; a longer reconstruction is trimmed about the center, and None keeps every sample

  • nfft (int) –

    the FFT size of the STFT, which is the window length in samples

  • noverlap (int) –

    the overlap (in samples) of consecutive windows in the STFT

  • out –

    a buffer of at least the untrimmed output size in the dtype of y; a non-contiguous buffer is copied, and the result is then not a view of out

  • overwrite_x –

    True overwrites y with the inverse FFT of each window

  • axis –

    the window axis of y

  • fftshift (bool, default: True ) –

    True for bins in the ascending-frequency order returned by stft; False for bins in fftfreq order

Returns:

  • Array –

    the waveform on axis, in the dtype and array namespace of y, of

  • Array –

    y.shape[axis] * (nfft - noverlap) + noverlap samples before trimming to

  • Array –

    size

oaconvolve

oaconvolve(x1, x2, mode='full', axes=-1)

convolve x1 and x2 by overlap-add, as scipy.signal.oaconvolve.

The result is in the array namespace of x1.

oaresample

oaresample(
    x: Array,
    up,
    down,
    fs,
    *,
    window: str | tuple[str, float] = 'hann',
    overwrite_x: bool = False,
    axis: int = 1,
    frequency_shift: float = 0,
    filter_bandwidth: float | None = None,
    transition_bandwidth: float = 250000.0,
    scale: Array | float = 1.0,
    out: Array | None = None,
)

resample x by up / down through STFT overlap-add.

Each STFT block of down samples is cropped or zero-padded to up bins, scaled by the low-pass response and scale, and overlap-added at the output rate. The response has the band edges of design_fir_lpf: the gain is 1/2 at filter_bandwidth / 2 and the transition is centered there.

Parameters:

  • x (Array) –

    the waveform, with time on axis; its length must be a whole number of STFT hops, down + k * (down - noverlap)

  • up –

    the output block size (in samples), an even multiple of the COLA divisor of window

  • down –

    the input block size (in samples), an even multiple of the COLA divisor of window

  • fs –

    the sample rate (in S/s) of x

  • window (str | tuple[str, float], default: 'hann' ) –

    the COLA window of the STFT, a key of the divisor table

  • overwrite_x (bool, default: False ) –

    True permits the STFT to consume the buffer of x; the contents of x are undefined after the call

  • axis (int, default: 1 ) –

    the time axis of x

  • frequency_shift (float, default: 0 ) –

    the frequency (in Hz) moved to the output DC, a multiple of fs / down times the frames per hop of window; 0 keeps the center frequency

  • filter_bandwidth (float | None, default: None ) –

    the passband width (in Hz) of the low-pass; None or inf applies no low-pass

  • transition_bandwidth (float, default: 250000.0 ) –

    the width (in Hz) of the low-pass transition band

  • scale (Array | float, default: 1.0 ) –

    a voltage gain, a scalar or one value per entry of the axis before axis

  • out (Array | None, default: None ) –

    a C-contiguous buffer of at least x.size * up // down elements in the dtype of x that receives the output; x itself is accepted when overwrite_x is True

Returns:

  • –

    the waveform at fs * up / down on axis, of ``x.shape[axis] * up //

  • –

    down` samples, in the dtype and array namespace ofx; a view ofout`

  • –

    when out is given

Raises:

  • ValueError –

    if frequency_shift is nonzero while upsampling, is not a multiple of fs / down times the frames per hop, or moves the output band past an edge of the input band; if up or down is odd or not a multiple of the COLA divisor; if window has no COLA divisor; if filter_bandwidth is finite and at most transition_bandwidth; or if out is not C-contiguous, has another dtype, has fewer than x.size * up // down elements, or shares memory with x without overwrite_x

resample

resample(
    x: _AT,
    num: int,
    axis: int = 0,
    window: None = None,
    domain: Literal['time', 'frequency'] = 'time',
    overwrite_x: bool = False,
    scale: Array | float = 1,
    shift: int = 0,
) -> _AT

resample x to num samples along axis by FFT, as scipy.signal.resample.

Parameters:

  • x (_AT) –

    the waveform, or with domain='frequency' the spectrum of the waveform in ascending frequency order

  • num (int) –

    the number of output samples along axis

  • axis (int, default: 0 ) –

    the axis to resample

  • window (None, default: None ) –

    must be None

  • domain (Literal['time', 'frequency'], default: 'time' ) –

    'time' takes x as a waveform; 'frequency' takes x as a spectrum

  • overwrite_x (bool, default: False ) –

    True evaluates the forward transform in the buffer of x; the contents of x are undefined after the call

  • scale (Array | float, default: 1 ) –

    a gain applied to the output

  • shift (int, default: 0 ) –

    the offset (in input bins) of the kept band above the input center when downsampling, as in resample_edges

Returns:

  • _AT –

    the resampled waveform with num samples on axis, in the dtype and array

  • _AT –

    namespace of x; x itself when x.shape[axis] == num

Raises:

  • ValueError –

    if domain is not 'time' or 'frequency', if window is not None, or if resample_edges rejects shift

set_max_cupy_fft_chunk

set_max_cupy_fft_chunk(count: int | None) -> None

set the sample count per group of a cupy FFT into an out= buffer.

The setting is global to the process.

Parameters:

  • count (int | None) –

    the most samples transformed in one cuFFT call; None selects one group

spectrogram

spectrogram(
    x: _AT,
    *,
    fs: float,
    window: WindowType,
    nperseg: int,
    noverlap: int = 0,
    nzero: int = 0,
    axis: int = 0,
    truncate: bool = True,
    return_axis_arrays: Literal[False],
) -> _AT
spectrogram(
    x: _AT,
    *,
    fs: float,
    window: WindowType,
    nperseg: int,
    noverlap: int = 0,
    nzero: int = 0,
    axis: int = 0,
    truncate: bool = True,
    return_axis_arrays: Literal[True] = True,
) -> tuple[_AT, _AT, _AT]
spectrogram(
    x: _AT,
    *,
    fs: float,
    window: WindowType,
    nperseg: int,
    noverlap: int = 0,
    nzero: int = 0,
    axis: int = 0,
    truncate: bool = True,
    return_axis_arrays: bool,
) -> _AT | tuple[_AT, _AT, _AT]
spectrogram(
    x: _AT,
    *,
    fs: float,
    window: WindowType,
    nperseg: int,
    noverlap: int = 0,
    nzero: int = 0,
    axis: int = 0,
    truncate: bool = True,
    return_axis_arrays: bool = True,
) -> _AT | tuple[_AT, _AT, _AT]

return the power spectrogram of x along axis.

The arguments are those of stft. The noise bandwidth of the output equals the frequency resolution.

Returns:

  • _AT | tuple[_AT, _AT, _AT] –

    (freqs, times, S), with freqs and times the axes of stft and S

  • _AT | tuple[_AT, _AT, _AT] –

    the linear power of each bin in the squared units of x; S alone when

  • _AT | tuple[_AT, _AT, _AT] –

    return_axis_arrays is False

stft

stft(
    x: _AT,
    *,
    fs: float,
    window: Array | str | tuple[str, float],
    nperseg: int = 256,
    noverlap: int = 0,
    nzero: int = 0,
    axis: int = 0,
    truncate: bool = True,
    norm: str | None = None,
    overwrite_x=False,
    return_axis_arrays=True,
    out=None,
) -> tuple[_AT, _AT, _AT]

return the short-time Fourier transform of x along axis.

The transform follows scipy.signal.stft with a reduced parameter set.

Parameters:

  • x (_AT) –

    the waveform, with time on axis

  • fs (float) –

    the sample rate (in S/s) of x, which scales the returned axes

  • window (Array | str | tuple[str, float]) –

    a window array of nperseg - nzero samples, or a name or (name, parameter) pair for get_window; None selects 'rect'

  • nperseg (int, default: 256 ) –

    the segment length and FFT size (in samples)

  • noverlap (int, default: 0 ) –

    the overlap (in samples) of consecutive segments

  • nzero (int, default: 0 ) –

    the number of trailing samples of each segment that are zeroed; the window spans the first nperseg - nzero

  • axis (int, default: 0 ) –

    the time axis of x

  • truncate (bool, default: True ) –

    True drops trailing samples of x that do not fill a segment; False raises ValueError for a partial segment

  • norm (str | None, default: None ) –

    None, or 'power' to scale the window to unit time-averaged power

  • overwrite_x –

    True writes the result into the buffer of x when noverlap is 0, and out is then ignored; ignored when noverlap is nonzero

  • return_axis_arrays –

    True returns the frequency and time axes with the transform; False returns the transform alone

  • out –

    a buffer with the shape and dtype of the transform

Returns:

  • _AT –

    (freqs, times, y): freqs is the ascending bin center frequencies (in

  • _AT –

    Hz), times the segment start times (in s), and y the transform with

  • _AT –

    segments on axis and nperseg bins on axis + 1, in the array

  • tuple[_AT, _AT, _AT] –

    namespace of x; y alone when return_axis_arrays is False

Raises:

  • TypeError –

    if norm is neither None nor 'power'

  • ValueError –

    if truncate is False and x.shape[axis] is not a whole number of segments at nperseg and noverlap

Power

Power detectors, empirical distributions, and conversions between dB, power, and envelope.

dBlinmean

dBlinmean(
    x_dB: _ALD,
    axis: Dims | int | Sequence[int] | None = None,
    overwrite_x: bool = False,
    min_dtype: DTypeLike = 'float32',
) -> _ALD

evaluate the mean in linear power space given power in dB.

This is equivalent to

powtodB(dBtopow(x).mean(axis))

Returns:

  • _ALD –

    array-like object with same shape as x_dB, reduced by the

  • _ALD –

    dimension at the specified axes

dBlinsum

dBlinsum(
    x_dB: _ALD,
    axis: Dims | int | Sequence[int] | None = None,
    overwrite_x: bool = False,
    min_dtype: DTypeLike = 'float32',
) -> _ALD

evaluate the sum in linear power space given power in dB.

This is equivalent to

powtodB(dBtopow(x).sum(axis))

Returns:

  • _ALD –

    array-like object with same shape as x_dB, reduced by the

  • _ALD –

    dimension at the specified axes

dBtopow

dBtopow(
    x: _ALN,
    *,
    overwrite_x: bool = False,
    min_dtype: DTypeLike = 'float32',
) -> _ALN

compute 10**(x/10).

The computation is elementwise in a floating-point dtype no narrower than min_dtype.

Parameters:

  • x (_ALN) –

    values in dB, as a number, array, or pandas/xarray object

  • overwrite_x (bool, default: False ) –

    True to write the result into x when the dtype of x is at least min_dtype

  • min_dtype (DTypeLike, default: 'float32' ) –

    the narrowest floating-point dtype of the computation; a narrower x is widened to min_dtype

Returns:

  • _ALN –

    the values in linear power units, in the container type of x: a Python

  • _ALN –

    number for a number, otherwise the array, pandas, or xarray type of x. An

  • _ALN –

    xarray units attribute is converted from dB to linear power.

Raises:

  • TypeError –

    if min_dtype is None or narrower than float32, or if no array can be associated with the type of x

envtodB

envtodB(
    x: _ALN,
    *,
    abs: bool = True,
    bounded: bool = False,
    overwrite_x: bool = False,
    min_dtype: DTypeLike = 'float32',
) -> _ALN

compute 20*log10(abs(x)), or 20*log10(x) when abs is False.

The computation is elementwise in a floating-point dtype no narrower than min_dtype.

Parameters:

  • x (_ALN) –

    values in linear amplitude (envelope) units, as a number, array, or pandas/xarray object

  • abs (bool, default: True ) –

    True to convert abs(x); a complex x is converted by magnitude in either case

  • bounded (bool, default: False ) –

    True to floor the result at 10*log10(tiny) for the smallest normal value tiny of the computation dtype, the floor of powtodB, so zeros map to the floor instead of -inf

  • overwrite_x (bool, default: False ) –

    True to write the result into x when the dtype of x is at least min_dtype; a complex x is then returned as the real view of the buffer of x

  • min_dtype (DTypeLike, default: 'float32' ) –

    the narrowest floating-point dtype of the computation; a narrower x is widened to min_dtype

Returns:

  • _ALN –

    the dB values, real-valued, in the container type of x: a Python number

  • _ALN –

    for a number, otherwise the array, pandas, or xarray type of x. An xarray

  • _ALN –

    units attribute is converted from amplitude to dB.

Raises:

  • TypeError –

    if min_dtype is None or narrower than float32, or if no array can be associated with the type of x

envtopow

envtopow(
    x: _ALN,
    *,
    overwrite_x: bool = False,
    min_dtype: DTypeLike = 'float32',
) -> _ALN

compute abs(x)**2.

The computation is elementwise in a floating-point dtype no narrower than min_dtype.

Parameters:

  • x (_ALN) –

    values in linear amplitude (envelope) units, real or complex, as a number, array, or pandas/xarray object

  • overwrite_x (bool, default: False ) –

    True to write the result into x when the dtype of x is at least min_dtype; a complex x is then returned as the real view of the buffer of x

  • min_dtype (DTypeLike, default: 'float32' ) –

    the narrowest floating-point dtype of the computation; a narrower x is widened to min_dtype

Returns:

  • _ALN –

    the power values, real-valued, in the container type of x: a Python number

  • _ALN –

    for a number, otherwise the array, pandas, or xarray type of x. An xarray

  • _ALN –

    units attribute is converted from amplitude to linear power.

Raises:

  • TypeError –

    if min_dtype is None or narrower than float32, or if no array can be associated with the type of x

iq_to_bin_power

iq_to_bin_power(
    iq: Array,
    Ts: float,
    Tbin: float,
    randomize: bool = False,
    kind: str = 'mean',
    truncate=False,
    axis=0,
)

return a statistic of the power of iq in bins of Tbin along axis.

On cupy, the statistics 'mean', 'rms', 'max', and 'peak' of contiguous bins are evaluated without a buffer of the size of iq.

Parameters:

  • iq (Array) –

    the waveform, complex or real, with time on axis

  • Ts (float) –

    the sample period (in s) of iq

  • Tbin (float) –

    the bin duration (in s); a whole multiple of Ts unless truncate

  • randomize (bool, default: False ) –

    True draws the bin start samples at random instead of tiling the axis; supported for axis=0 only

  • kind (str, default: 'mean' ) –

    a statistic of the samples in a bin: 'max', 'mean', 'median', 'min', 'peak' (max), 'rms' (mean), a quantile in [0, 1], or a callable with an axis keyword

  • truncate –

    True drops the trailing samples that do not fill a bin and rounds Tbin to whole samples; False raises on either

  • axis –

    the time axis of iq

Returns:

  • –

    the statistic of |iq|**2 per bin, in the real dtype of iq, with the bins

  • –

    on axis in place of the samples

Raises:

  • ValueError –

    if Tbin is not a whole multiple of Ts without truncate, if randomize is set with an axis other than 0, or if kind is not a supported statistic

iq_to_cyclic_power

iq_to_cyclic_power(
    x: Array,
    Ts: float,
    detector_period: float,
    cyclic_period: float,
    truncate=False,
    detectors=('rms', 'peak'),
    cycle_stats=('min', 'mean', 'max'),
    axis=0,
) -> dict[str, dict[str, Array]]

return cyclic statistics of the channel power of x binned along axis.

Each detector in detectors bins the power of x along axis into K samples of detector_period. The detector series is indexed as a matrix of cycles and lags: sample k is in cycle k // L at lag (k % L) * detector_period, where L = cyclic_period / detector_period is the number of detector bins per cycle and M = K / L is the number of cycles. Each cyclic statistic reduces the cycle axis, so the value at lag m summarizes the M samples at the same offset from the start of a cycle. The result spans one cyclic_period at the resolution of detector_period, with L samples per detector and statistic, for any capture length.

With a cyclic_period that is a common multiple of the periods of the expected signals (e.g., 10 ms for TDD cellular frames, 5 ms WiMAX frames, and the 1 ms pulse repetition interval of the SPN-43 radar), the features of those signals fall at the same lags in every cycle. Occupancy with an incommensurate period is spread across all lags. The uplink and downlink levels of a TDD network fall in disjoint lag windows.

With a mismatch dT between cyclic_period and the signal period, such as from a sample clock offset, a feature drifts by M * dT / detector_period lags over the capture and bleeds into neighboring lags. The drift stays within one lag while M * dT is below detector_period, which bounds the usable number of cycles M.

Parameters:

  • x (Array) –

    the IQ waveform, complex or real, with time on axis

  • Ts (float) –

    sample period of the waveform (in s)

  • detector_period (float) –

    duration of each power detector bin (in s), an integer multiple of Ts

  • cyclic_period (float) –

    duration of one cycle (in s), an integer multiple of detector_period

  • truncate –

    True to drop trailing samples that do not complete a detector bin or a cycle, and to round detector_period to the nearest multiple of Ts

  • detectors –

    power detector names accepted by iq_to_bin_power

  • cycle_stats –

    statistics accepted by stat_ufunc_from_shorthand, evaluated across cycles (names such as 'min', 'mean', 'max', or quantiles in (0, 1))

  • axis –

    the time axis of x

Returns:

  • dict[str, dict[str, Array]] –

    dict keyed on detector, of dicts keyed on cyclic statistic, of arrays in the

  • dict[str, dict[str, Array]] –

    namespace of x with the axis dimension replaced by the L cycle lags,

  • dict[str, dict[str, Array]] –

    in linear power units; each statistic is evaluated on the linear power

Raises:

  • ValueError –

    if detectors is None; if cyclic_period is not an integer multiple of detector_period; or, when truncate is False, if detector_period is not an integer multiple of Ts or the capture does not contain a whole number of cycles

References

D.G. Kuester et al., "Cyclic Analysis of Power in Radio Channels".

powtodB

powtodB(
    x: _ALN,
    *,
    abs: bool = True,
    bounded: bool = False,
    overwrite_x: bool = False,
    min_dtype: DTypeLike = 'float32',
) -> _ALN

compute 10*log10(abs(x)), or 10*log10(x) when abs is False.

The computation is elementwise in a floating-point dtype no narrower than min_dtype.

Parameters:

  • x (_ALN) –

    values in linear power units, as a number, array, or pandas/xarray object

  • abs (bool, default: True ) –

    True to convert abs(x); a complex x is converted by magnitude in either case

  • bounded (bool, default: False ) –

    True to floor the result at 10*log10(tiny), where tiny is the smallest normal value of the computation dtype (about -379 dB in float32 and -3077 dB in float64), so zeros map to the floor instead of -inf

  • overwrite_x (bool, default: False ) –

    True to write the result into x when the dtype of x is at least min_dtype; a complex x is then returned as the real view of the buffer of x

  • min_dtype (DTypeLike, default: 'float32' ) –

    the narrowest floating-point dtype of the computation; a narrower x is widened to min_dtype

Returns:

  • _ALN –

    the dB values, real-valued, in the container type of x: a Python number

  • _ALN –

    for a number, otherwise the array, pandas, or xarray type of x. An xarray

  • _ALN –

    units attribute is converted from linear power to dB.

Raises:

  • TypeError –

    if min_dtype is None or narrower than float32, or if no array can be associated with the type of x

sample_ccdf

sample_ccdf(
    a: _AT, edges: _AT, density: bool = True
) -> _AT

return the fraction (or count) of samples in a above each value of edges.

Parameters:

  • a (_AT) –

    the samples, 1-D

  • edges (_AT) –

    the thresholds, 1-D and sorted ascending

  • density (bool, default: True ) –

    True divides each count by a.shape[0]; False returns the counts

Returns:

  • _AT –

    the empirical complementary cumulative distribution at each edge, of shape

  • _AT –

    edges.shape in the array namespace of a: float64 when density,

  • _AT –

    otherwise the integer count dtype of the namespace