sample.utils.dsp module

DSP utilities

sample.utils.dsp.a2db(a: ndarray, floor: Optional[ndarray] = None, floor_db: bool = False, out: Optional[ndarray] = None)

Convert linear amplitude values to decibel

Parameters:
  • a (array) – Amplitude values

  • floor (array) – Floor value(s). If specified, the amplitude values will be clipped to this value. Use this to avoid computing the logarithm of zero

  • floor_db (bool) – Set this to True if floor is specified in decibel

  • out (array) – Optional. Array to use for storing results

Returns:

Decibel values

Return type:

array

sample.utils.dsp.bin2f(b: ndarray, nfft: int, fs: float = 1, out: Optional[ndarray] = None) ndarray

Convert FFT bin indices to frequency values

Parameters:
  • b (array) – Bin indices

  • nfft (int) – FFT size

  • fs (float) – Sample frequency

  • out (array) – Optional. Array to use for storing results

Returns:

Frequency values in Hz

Return type:

array

sample.utils.dsp.complex2db(c, out: Optional[ndarray] = None, **kwargs)

Convert linear complex values to decibel

Parameters:
  • c (array) – Amplitude values

  • out (array) – Optional. Array to use for storing results

  • **kwargs – Keyword arguments for a2db()

Returns:

Decibel values

Return type:

array

sample.utils.dsp.db2a(d: float, out: Optional[ndarray] = None) float

Convert decibels to linear amplitude values

Parameters:
  • d (array) – Decibel values

  • out (array) – Optional. Array to use for storing results

Returns:

Amplitude values

Return type:

array

sample.utils.dsp.detrend(y: ndarray, x: Optional[ndarray] = None, model: Optional[BaseEstimator] = None) ndarray

Remove trends from a signal

Parameters:
  • y (array) – Array of signal samples. Must be monodimensional

  • x (array) – Optional. Time-steps for the signal. If unspecified y is assumed to be uniformly sampled

  • model (Estimator) – Sklearn-like estimator to estimate signal trend. If None, then construct a new instance of sklearn.linear_model.LinearRegression

Returns:

The model prediction residuals

Return type:

array

sample.utils.dsp.dychotomic_zero_crossing(func: Callable[[float], float], lo: float, hi: float, steps: int = 16)

Dichotomicly search for a zero crossing

Parameters:
  • func (callable) – Function to evaluate

  • lo (float) – Lower boundary for dichotomic search

  • hi (float) – Higher boundary for dichotomic search

  • steps (int) – Number of steps for the search

Returns:

Argument for which the function is close to zero

Return type:

float

sample.utils.dsp.expi(x: ndarray, out: Optional[ndarray] = None) ndarray

Exponential of imaginary input

Parameters:
  • x (array) – Input array, to be multiplied by \(i\)

  • out (array) – Optional. Array to use for storing results

Returns:

\(e^{ix}\)

Return type:

array

sample.utils.dsp.f2bin(f: ndarray, nfft: int, fs: float = 1) ndarray

Convert frequency values to FFT bin indices

Parameters:
  • f (array) – Frequency values in Hz

  • nfft (int) – FFT size

  • fs (float) – Sample frequency

Returns:

Bin indices

Return type:

array

sample.utils.dsp.fft2autocorrelogram(a: ndarray, real: bool = True, n: Optional[int] = None, nfft: Optional[int] = None, power: bool = False) ndarray

Compute the autocorrelogram from the FFT of a signal

Parameters:
  • a (array) – FFT

  • real (bool) – Wheter the FFT is one-sided (sufficient for real signals, default) or two-sided (output will be complex)

  • n (int) – Signal length in samples. Default is the size of a for a two-sided FFT (real=False) or twice as much for a one-sided FFT (real=True)

  • nfft (int) – FFT size. Default is n

  • power (bool) – If True, the input a is interpreted as the power spectrum, instead of the FFT or the magnitude

Returns:

The autocorrelogram of the signal

Return type:

array

sample.utils.dsp.local_maxima(x: ndarray, w: int = 1, key: Optional[ndarray] = None, logical_and: bool = False, out: Optional[ndarray] = None) ndarray

Find local maxima in a function

Parameters:
  • x (array) – Function

  • w (int) – Window radius for maxima detection

  • key (array) – Function to look over to evaluate local optimality. If unspecified, x itself will be used

  • out (array) – Array of bool to overwrite with output

  • logical_and (bool) – If True, then write in out the logical conjunction of this function output and the data already in out

Returns:

Array of boolean values (True for maxima)

Return type:

array

sample.utils.dsp.lombscargle_as_fft(t: ndarray, x: ndarray, nfft: int, fs: float = 1, hpf: Optional[float] = None, lpf: Optional[float] = None, **kwargs)

Compute a Lomb-Scargle periodogram for the same frequencies as a FFT

Parameters:
  • t (array) – Sample times

  • x (array) – Signal

  • nfft (int) – FFT size

  • fs (float) – Sample frequency for the analogous uniformly-sampled signal

  • hpf (float) – If specified, cut off frequencies below this value (in Hz)

  • lpf (float) – If specified, cut off frequencies abow this value (in Hz)

  • **kwargs – Keyword arguments for scipy.signal.lombscargle()

Returns:

The Lomb-Scargle periodogram and the frequencies at which it is evaluated

Return type:

array, array

sample.utils.dsp.lombscargle_autocorrelogram(t: ndarray, x: ndarray, n: Optional[int] = None, nfft: Optional[int] = None, fs: float = 1, **kwargs) ndarray

Compute the autocorrelogram of an unevenly sampled signal using the Lomb-Scargle periodogram

Parameters:
  • t (array) – Sample times

  • x (array) – Signal

  • n (int) – Autocorrelogram size

  • nfft (int) – FFT size

  • fs (float) – Sample frequency for the analogous uniformly-sampled signal

  • **kwargs – Keyword arguments for lombscargle_as_fft()

Returns:

Autocorrelogram

Return type:

array

sample.utils.dsp.n_windows(input_size: int, wsize: int, hop: Optional[int] = None) int

Number of windows for overlapping windows operations

Parameters:
  • input_size (int) – Size of input array

  • wsize (int) – Size of the windows

  • hop (int) – Distance in samples between consecutive windows

Returns:

Number of windows

Return type:

int

sample.utils.dsp.normalize(x: ndarray, out: Optional[ndarray] = None, *, mode: str = 'peak') ndarray

Normalize the array to have absolute peak at one

Parameters:
  • x (array) – Array to normalize

  • mode (str) – Type of normalization (peak, rms, range)

  • out (array) – Optional. Array to use for storing results

Returns:

Normalized array

Return type:

array

sample.utils.dsp.onset_detection(x, detection_fn: ~typing.Callable[[~numpy.ndarray], ~numpy.ndarray] = <function spectral_flux>, w: int = 3, m: int = 3, alpha: float = 0.75, delta: float = 1.5, **kwargs)

Detect onsets in signal, as defined in [1]

Parameters:
  • x (array) – Signal

  • detection_fn (callable) – Detection function to use. Default is spectral_flux()

  • w (int) – Window radius for maxima detection

  • m (int) – Window radius multiplier for offsetting the average window to the left (before the onset)

  • alpha (float) – Feedback coefficient for non-linear filter (higher values result in slower envelopes)

  • delta (float) – Threshold for onset detection relative to local average

  • kwargs – Keyword arguments for detection_fn

Returns:

Array of boolean values (True for onsets)

Return type:

array

References

sample.utils.dsp.onset_selection(x, w: int = 3, m: int = 3, alpha: float = 0.75, delta: float = 1.5)

Select onsets from a detection signal, e.g. spectral_flux(), as defined in [1]

Parameters:
  • x (array) – Function

  • w (int) – Window radius for maxima detection

  • m (int) – Window radius multiplier for offsetting the average window to the left (before the onset)

  • alpha (float) – Feedback coefficient for non-linear filter (higher values result in slower envelopes)

  • delta (float) – Threshold for onset detection relative to local average

Returns:

Array of boolean values (True for onsets)

Return type:

array

References

sample.utils.dsp.overlapping_windows(a: ndarray, wsize: int, hop: Optional[int] = None, writeable: bool = False)

Return a view on the array as a matrix of overlapping windows. Please note that this function does not alter in any way the input array. If some preprocessing is needed, e.g. zero-padding, it should be done before invoking this function

Parameters:
  • a (ndarray) – The array. If it is not 1d already, it is linearized

  • wsize (int) – Size of the windows

  • hop (int) – Distance in samples between consecutive windows. It should be at least 1, it often is at most wsize. If None, then use wsize (non-overlapping windows)

  • writeable (bool) – If False (default) the output view is read-only

Returns:

Overlapping windows. Shape is (n_windows, wsize)

Return type:

ndarray

Example

>>> from sample.utils.dsp import overlapping_windows
>>> import numpy as np
>>> a = np.arange(64)
>>> b = overlapping_windows(a, wsize=16)
>>> # Check array shape
>>> b.shape
(4, 16)
>>> from sample.utils import numpy_id
>>> # Test that the new array still refers to the same memory
>>> numpy_id(a) == numpy_id(b)
True
>>> # Use view to perform mean filtering
>>> np.mean(b, axis=-1)
array([ 7.5, 23.5, 39.5, 55.5])
sample.utils.dsp.spectral_flux(x: ~numpy.ndarray, tf_fn: ~typing.Callable[[~numpy.ndarray], ~typing.Tuple[~numpy.ndarray, ...]] = <function stft>, **kwargs) Tuple[ndarray, ndarray]

Compute spectral flux from a signal, as defined in [1]

Parameters:
  • x (array) – Signal

  • tf_fn (callable) – Function to transform x to a time-frequency domain. It should output a tuple of outputs, where the last output is the time-frequency matrix (frequency x time). By default:func:scipy.signal.stft is used

  • kwargs – Keyword arguments for tf_fn

Returns:

Spectral flux feature

Return type:

array

References

sample.utils.dsp.spectral_flux_from_tf(x: ndarray) ndarray

Compute spectral flux from a time-frequency matrix, as defined in [1]

Parameters:

x (array) – Time-frequency matrix (frequency x time)

Returns:

Spectral flux feature

Return type:

array

References

sample.utils.dsp.strided_convolution(x: ndarray, kernel: ndarray, stride: int = 1, out: Optional[ndarray] = None)

Compute a strided convolution as a matrix multiplication between overlapping_windows() of the signal and the flipped kernel.

Parameters:
  • x (array) – The input array

  • kernel (array) – Convolution kernel

  • stride (int) – Output sample period (in number of input samples). Note that for the default stride=1, the output is the (non-strided) convolution. In this case, consider using other convolution functions, which will be more efficient

  • out (array) – Optional. Array to use for storing results

Returns:

Strided convolution

Return type:

array

sample.utils.dsp.strided_convolution_complex_kernel(x: ndarray, kernel: ndarray, stride: int = 1, out: Optional[ndarray] = None, dtype: Optional[type] = None)

Compute a strided convolution as a matrix multiplication between overlapping_windows() of the signal and the flipped kernel. Call this function when kernel is complex

Parameters:
  • x (array) – The input array

  • kernel (array) – Convolution kernel

  • stride (int) – Output sample period (in number of input samples). Note that for the default stride=1, the output is the (non-strided) convolution. In this case, consider using other convolution functions, which will be more efficient

  • out (array) – Optional. Array to use for storing results

  • dtype (type) – Explicit dtype for output when out is unspecified

Returns:

Strided convolution

Return type:

array