Helpers

Fast and flexible implementation of partitioned convolution.

This module is part of the libdamp package.

class libdamp.helpers.convolution.Convolution(B, N, L=None, K=None, C=1)[source]

Bases: Module

Fast and Flexible FIR Filter implementation

An implementation of the Generalized Uniformly Partitioned Overlap Save (GUPOLS) algorithm as described in [1]. It allows for a time-varying filter. Upon filter exchange, the next input signal frame is processed both with the new and the previous filter, and a time-domain cross-fade between the two filter output signals is performed to avoid discontinuities.

Note that variable names follow the algorithmic description in [1].

set_filter(h)[source]

Set the (possibly time-varying) filter

Parameters:

h (torch.Tensor) – Time-domain filter impulse response(s) with shape (1, N) (mono or multi-channel input mode), shape (F, N) (multi-channel filter mode), or shape (C, N) (batch mode). See __init__() documentation for more info about modes.

forward(x)[source]

Implements forward pass of torch.nn.Module

process(x)[source]

Process a frame of input signal samples

Parameters:

x (torch.Tensor) – time-domain input signal with shape (1, B) (mono or multi-channel filter mode) or shape (C, B) (multi-channel input or batch mode). See __init__() documentation for more info about modes.

Collection of helper functions and classes related to FIR filters.

This module is part of the libdamp package.

libdamp.helpers.filters.freqz(b: Tensor, a: Tensor, N: int = 1024, dtype: dtype = torch.complex64) Tensor[source]

Sample frequency response of a digital filter.

Computes the frequency response H(z) of an IIR filter given numerator (b) and denominator (a) coefficients. The frequency response is computed by evaluating the transfer function on the unit circle in the z-plane.

Parameters:
  • b (torch.Tensor) – Numerator coefficients of shape (batch, order) or (order,).

  • a (torch.Tensor) – Denominator coefficients of shape (batch, order) or (order,). First coefficient must be 1.0.

  • N (int) – Determines frequency resolution: the frequency response is evaluated at (N+1)//2 + 1 uniformly spaced frequency points from 0 to Nyquist frequency (default: 1024)

  • dtype (torch.dtype) – Compute frequency response in this dtype - complex64 for 32-bit or complex128 for 64-bit precision

Returns:

Complex-valued frequency response of shape (batch, (N+1)//2 + 1) or ((N+1)//2 + 1,) containing only the positive frequency half.

Return type:

torch.Tensor

libdamp.helpers.filters.combined_freqz(b: Tensor, a: Tensor, N: int = 1024, parallel: bool = False) Tensor[source]

Sample frequency response of a series of digital filters.

Computes the combined frequency response of multiple filters arranged either in series (cascaded) or parallel configuration.

Parameters:
  • b (torch.Tensor) – Numerator coefficients of shape (…, num_filters, order).

  • a (torch.Tensor) – Denominator coefficients of shape (…, num_filters, order).

  • N (int) – Determines frequency resolution: the frequency response is evaluated at (N+1)//2 + 1 uniformly spaced frequency points

  • parallel (bool) – If True, computes parallel configuration (sum of responses). If False, computes series configuration (product of responses) (default: False)

Returns:

Combined complex-valued frequency response of shape (…, (N+1)//2 + 1) containing only the positive frequency half.

Return type:

torch.Tensor

libdamp.helpers.filters.design_resonant_filter(f: Tensor, r: Tensor, fs: float) tuple[Tensor, Tensor][source]

Design second-order IIR resonance (peak) filters.

Creates filter coefficients for resonant (peaking) filters that amplify energy around specific frequencies.

Parameters:
  • f (torch.Tensor) – Center frequency or frequencies in Hz, shape (batch,) or scalar.

  • r (torch.Tensor) – Notch radius between 0 and 1 controlling filter sharpness. Values closer to 1 produce sharper, narrower resonances. Values closer to 0 produce wider resonances. Shape must match f or be broadcastable to f.

  • fs (float) – Sampling rate in Hz.

Returns:

  • b (torch.Tensor) – Numerator coefficients of shape (batch, 3) or (3,).

  • a (torch.Tensor) – Denominator coefficients of shape (batch, 3) or (3,).

libdamp.helpers.filters.design_butter_bandpass(fc: Tensor, bw: Tensor, fs: float, order: int = 2, dtype: dtype = torch.float32) tuple[Tensor, Tensor][source]

Design digital Butterworth bandpass filter coefficients.

Creates an IIR bandpass filter using the bilinear transform method with an analog lowpass-to-bandpass prototype transformation. The resulting filter has order 2*order (each lowpass pole maps to two bandpass poles).

The design follows the standard procedure: 1. Design an analog Butterworth lowpass prototype with unit cutoff frequency 2. Warp center frequency and bandwidth for digital filter design 3. Apply LP to BP frequency transformation in the s-plane 4. Transform from s-plane to z-plane using Tustin’s bilinear method

Parameters:
  • fc (torch.Tensor) – Center frequency in Hz, shape (batch,) or scalar.

  • bw (torch.Tensor) – Bandwidth in Hz (distance between -3 dB points), shape (batch,) or scalar.

  • fs (float) – Sampling rate in Hz.

  • order (int) – Prototype lowpass filter order. The resulting bandpass filter has order 2*order.

  • dtype (torch.dtype) – Computation dtype. Use float64 for higher filter orders to avoid numerical issues.

Returns:

  • b (torch.Tensor) – Numerator (feedforward) coefficients, shape (batch, 2*order+1) or (2*order+1,).

  • a (torch.Tensor) – Denominator (feedback) coefficients, shape (batch, 2*order+1) or (2*order+1,).

libdamp.helpers.filters.design_butter_filter(fc: Tensor, fs: float, order: int = 2, dtype: dtype = torch.float32) tuple[Tensor, Tensor][source]

Design digital Butterworth lowpass filter coefficients.

Creates an IIR lowpass filter with maximally flat magnitude response in the passband using the bilinear transform method. Butterworth filters have the property that they have zero ripple in both the passband and stopband.

The design method follows scipy.signal.iirfilter: 1. Design an analog Butterworth prototype with unit cutoff frequency 2. Warp frequencies for digital filter design 3. Transform from s-plane to z-plane using Tustin’s bilinear method

Parameters:
  • fc (torch.Tensor) – Cutoff frequency in Hz, shape (batch,) or scalar.

  • fs (float) – Sampling rate in Hz.

  • order (int) – Filter order. Higher orders produce steeper rolloff.

  • dtype (torch.dtype) – Computation dtype. Use float64 for higher filter orders to avoid numerical issues.

Returns:

  • b (torch.Tensor) – Numerator (feedforward) coefficients of shape (batch, order+1) or (order+1,).

  • a (torch.Tensor) – Denominator (feedback) coefficients of shape (batch, order+1) or (order+1,).

libdamp.helpers.filters.design_fir_filter(f: Tensor, m: Tensor, fs: float, N: int, phase: Literal['linear', 'minimum'] = 'linear', return_fd: bool = False, min_mag: float = 1e-10) Tensor[source]

Design an FIR filter based on desired magnitude response.

Creates a finite impulse response (FIR) filter with prescribed magnitude response at specified frequencies using frequency sampling with optional window smoothing. Supports both linear-phase and minimum-phase designs.

Parameters:
  • f (torch.Tensor) – Frequencies at which desired magnitudes are specified, shape (M,) or (batch, M) in Hz.

  • m (torch.Tensor) – Desired magnitudes at those frequencies, shape (M,) or (batch, M).

  • fs (float) – Sampling rate in Hz.

  • N (int) – Resulting filter length in samples. Shorter filters may not accurately represent low-frequency characteristics due to frequency resolution limitations.

  • phase (Literal["linear", "minimum"]) – How the phase response of the filter should be calculated (default: “linear”) Options: - “linear”: return a linear-phase filter with a symmetric impulse response - “minimum”: return a minimum-phase filter, see also [1]

  • return_fd (bool) – If True, returns the filter in the frequency domain. If False, returns it in the time domain (default: False).

  • min_mag (float) – Minimum magnitude floor to avoid log(0) issues with minimum-phase design (default: 1e-10).

Returns:

res – Filter coefficients either in time domain (shape (N,)) or frequency domain (shape ((N+1)//2+1,)), depending on return_fd.

Return type:

torch.Tensor

References

[1]: A. V. Oppenheim and R. W. Schafer, ‘Discrete-time signal processing’, pp. 781-787

libdamp.helpers.filters.iir_freq_sampling(b: Tensor, a: Tensor, x: Tensor, N: int = 1024) Tensor[source]

Apply IIR filter using frequency sampling method with frame-based processing.

This method transforms signal and filter to frequency domain in frames, multiplies them and transforms back.

Parameters:
  • b (torch.Tensor) – Numerator (feedforward) coefficients of shape (batch, order) or (batch, frames, order).

  • a (torch.Tensor) – Denominator (feedback) coefficients of shape (batch, order) or (batch, frames, order). The first coefficient must be 1.0.

  • x (torch.Tensor) – Input signal of shape (batch, length).

  • N (int) – Length of the sampled impulse response in time domain (sampling (N+1)//2+1 points in frequency domain).

Returns:

y – Filtered signal of same shape as input x.

Return type:

torch.Tensor

Collection of helper functions for calculating spectral representations.

This module is part of the libdamp package.

libdamp.helpers.freq.hz2midi(f: Tensor | float, a4_ref: float = 440.0, zero_val: int | float = -1) Tensor[source]

Convert frequency to MIDI pitch with respect to a reference.

Frequency 0 Hz is handled separately and mapped to the given value zero_val.

Parameters:
  • f (torch.Tensor | float) – Frequency in Hz.

  • a4_ref (float) – Reference frequency for MIDI pitch 69 (A4) in Hz (default: 440).

  • zero_val (int or float) – Special value to assign to 0 Hz input (default: -1).

Returns:

MIDI pitch with the same shape as input f.

Return type:

torch.Tensor

libdamp.helpers.freq.midi2hz(p: Tensor | float, a4_ref: float = 440.0, zero_val: int | float = -1) Tensor[source]

Convert MIDI pitch to frequency.

Frequency 0 Hz is handled separately based on the given value zero_val.

Parameters:
  • p (torch.Tensor | float) – MIDI pitch.

  • a4_ref (float) – Reference frequency for MIDI pitch 69 (A4) in Hz (default: 440).

  • zero_val (int or float) – Special value that indicates 0 Hz output (default: -1).

Returns:

Frequency in Hz with the same shape as input p.

Return type:

torch.Tensor

libdamp.helpers.freq.timbre2harmonics(timbre: Literal['square', 'triangle', 'sawtooth', 'flat', 'clarinet-like', 'random_harmonic', 'random_inharmonic', 'random_inharmonic_sawtooth'], H: int, harmonic_sigma: float = 0.02, amplitude_sigma: float = 0.5) Tensor[source]

Generate an overtone distribution from a timbre descriptor.

Parameters:
  • timbre (str) –

    Name of the desired timbre.

    • ”square”: odd harmonics with amplitudes ~ 1/n (even harmonics are zero).

    • ”triangle”: alternating-sign series with amplitudes ~ 1/n^2.

    • ”sawtooth”: alternating-sign series with amplitudes ~ 1/n. Fundamental has amplitude 1.

    • ”flat”: all harmonics with unit amplitude.

    • ”clarinet-like”: odd harmonics only, amplitudes ~ 1/n.

    • ”random_harmonic”: harmonic factors 1..H, amplitudes ~ N(1, amplitude_sigma), clipped at 0.

    • ”random_inharmonic”: harmonic factors for n>=2 are jittered by N(n, harmonic_sigma), and amplitudes ~ N(1, amplitude_sigma), clipped at 0. The first harmonic factor remains 1.

    • ”random_inharmonic_sawtooth”: harmonic factors for n>=2 are jittered by N(n, harmonic_sigma), and amplitudes follow the sawtooth series (no amplitude randomness). The first harmonic amplitude (of fundamental) remains 1.

  • H (int) – number of harmonics to return

  • harmonic_sigma (float) – Standard deviation of the harmonic randomness (used only for “random_inharmonic” and “random_inharmonic_sawtooth”).

  • amplitude_sigma (float) – Standard deviation of the amplitude randomness (used only for “random_harmonic” and “random_inharmonic”).

Returns:

A – (H, 2) tensor, where the first column contains the harmonic frequency factors (including fundamental) and the second column contains the harmonic amplitudes.

Return type:

torch.Tensor

Helper function to calculate an incremental modulo

This can be a huge bottleneck if calculated over a long sequence, so that we leverage Triton to accelerate it on CUDA devices.

Disclaimer: The Triton-accelerated version of incremental_mod was generated with Claude Sonnet 4.5

libdamp.helpers.incremental_mod.incremental_mod(mod: Tensor, increment: Tensor | None = None) Tensor[source]

Compute an “incremental modulo” along the last dimension.

Unlike a standard elementwise modulo, this operation maintains a running counter that is updated step by step. At each position k, the counter is incremented, compared against mod[…, k], and wrapped if needed. This makes the result stateful, in contrast to torch.cumsum(increment) % mod.

Example

>>> mod = torch.Tensor([5, 3, 6])
>>> inc = torch.Tensor([2, 2, 2])
>>> incremental_mod(mod, inc)
Tensor([0., 2., 1.])
Parameters:
  • mod (torch.Tensor) – Shape (…, N) Tensor of positive moduli

  • increment (torch.Tensor, optional) – Increments of the same shape as mod. Defaults to ones.

Returns:

Tensor of the same shape as mod containing the incremental modulo

Return type:

torch.Tensor

libdamp.helpers.incremental_mod.incremental_mod_triton(mod, increment=None)[source]

Triton GPU implementation (at least 100x faster than incremental_mod_python)

libdamp.helpers.incremental_mod.incremental_mod_python(mod: Tensor, increment: Tensor | None) Tensor[source]

Direct implementation (very slow)

Collection of torch helper modules.

This module is part of the libdamp package.

class libdamp.helpers.modules.SelectItem(item_index: int)[source]

Bases: Module

Select an output in a torch.nn.Sequential pipeline.

forward(inputs)[source]

Return only the selected item from a tuple/list of inputs.

Parameters:

inputs (tuple or list) – A sequence of items from which the indexed item will be selected.

Returns:

The item at index specified during initialization.

Return type:

object

class libdamp.helpers.modules.ConvStack(N_inp: int, N_out: int)[source]

Bases: Module

Stack of convolutional layers. (adapted from https://github.com/jongwook/onsets-and-frames/blob/master/onsets_and_frames/transcriber.py)

forward(mel)[source]

Implementation of forward step.

Parameters:

mel (torch.Tensor) – Mel spectrogram input with shape (B, 1, F, N_inp).

class libdamp.helpers.modules.FreqToBins(num_bins: int = 360, f_min: float = 32.7, f_max: float = 1975.5, target_smoothing: float = 20.0, out_of_bounds: Literal['snap', 'smooth'] = 'snap')[source]

Bases: Module

Convert frequencies to a binned distribution.

forward(f)[source]

Forward pass to convert single frequencies to binned distributions.

Parameters:

f (torch.Tensor) – Frequency values in Hz, shape (B, …, K).

Returns:

Normalized probability distribution over bins, shape (B, …, K, num_bins).

Return type:

torch.Tensor

class libdamp.helpers.modules.LogitsToFreq(bins_per_freq: int = 360, f_min: float = 32.7, f_max: float = 1975.5)[source]

Bases: Module

Convert bin-frequency network outputs to frequencies.

forward(x)[source]

Forward pass to convert binned frequency outputs to frequencies using weighted average.

Parameters:

x (torch.Tensor) – Logits tensor whose last dimension is a multiple of bins_per_freq.

Returns:

Estimated frequencies in Hz with shape x.shape[:-1] + (x.shape[-1] // bins_per_freq,).

Return type:

torch.Tensor

Collection of scaling functions to keep values in a prescribed range.

This module is part of the libdamp package.

libdamp.helpers.scaling.exp_sigmoid(x, x_max: float = 2.0, x_min: float = 1e-08, exp: float = 1.0) Tensor[source]

Scale values between a minimum and maximum value with an exponentiated sigmoid

Parameters:
  • x (torch.Tensor or array-like) – Input values to scale

  • x_max (float) – Maximum output value (default: 2.0)

  • x_min (float) – Minimum output value (default: 1e-8)

  • exp (float) – Exponent for the sigmoid (default: 1.0)

Returns:

Scaled values in range (x_min, x_min + x_max).

Return type:

torch.Tensor

Collection of helper functions that operate on tensors.

This module is part of the libdamp package.

libdamp.helpers.tensors.tensor_linspace(start: Tensor, end: Tensor, steps: int = 10) Tensor[source]

Vectorized version of torch.linspace.

Parameters:
  • start (torch.Tensor) – Starting values of any shape.

  • end (torch.Tensor) – Ending values of the same shape as start.

  • steps (int) – Number of steps to interpolate between start and end.

Returns:

Interpolated values of shape start.size() + (steps,), where the first element equals start, the last equals end, and intermediate elements linearly interpolate.

Return type:

torch.Tensor

Notes

From https://github.com/zhaobozb/layout2im/blob/master/models/bilinear.py#L246

libdamp.helpers.tensors.apply_along_dim(x: Tensor, func, dim: int = 0) Tensor[source]

Apply a function along a specified dimension.

Parameters:
  • x (torch.Tensor) – Input data tensor.

  • func (callable) – Function to be applied on each subtensor.

  • dim (int) – Dimension along which to apply the function (default: 0).

Returns:

Result tensor with func applied along the specified dimension.

Return type:

torch.Tensor

Notes

Use with caution as this is typically slow compared to vectorized operations.

libdamp.helpers.tensors.ensure_tensor(x, dtype: dtype | None = None, min_dims: int | None = None, throw_smaller: bool = False, throw_larger: bool = False) Tensor[source]

Converts lists or numpy arrays into a torch.Tensor if required

Parameters:
  • x (Any) – Data that will be converted to a torch.Tensor if it not already is one.

  • dtype (torch.dtype or None) – Optional target dtype for the tensor. If None is given, the type is inferred from x (default: None).

  • min_dims (int or None) – Optional target number of dimensions for the tensor. If None is given, the tensor is not expanded. The behavior if x has too few or too many dimensions depends on throw_smaller and throw_larger (see below).

  • throw_smaller (bool) – If False, new dimensions are added to the beginning of the tensor if it has too few dimensions. Otherwise an error is thrown if the number of dimensions is too small (default: False).

  • throw_larger (bool) – If False, nothing happens if the number of dimensions of x is larger than min_dims. Otherwise an error is thrown if the number of dimensions is too large (default: False).

Returns:

The input converted to a tensor with the specified properties.

Return type:

torch.Tensor

libdamp.helpers.tensors.interpolate_samples(x: Tensor, N: int, mode: Literal['const', 'center_linear', 'end_linear', 'half_linear', 'const_smooth'] = 'const', prev_val: Tensor | None = None)[source]

Interpolation of the last axis of a tensor x.

This function provides several ways to expand a frame-wise representation of some parameters to a sample-wise one.

Parameters:
  • x (torch.Tensor) – input tensor with shape (batch, channels, num_frames), where the last axis gives one value per frame.

  • N (int) – Target number of samples per frame.

  • mode (Literal["const", "center_linear", "end_linear", "half_linear", "const_smooth"]) –

    interpolation mode (default: “const”)

    Available options:

    • ”const”: the parameter value stays constant for each whole frame

    • ”center_linear”: linear interpolation over the full length-N frame, where the given value in x is reached in the middle of the frame. Note that this mode may behave similar to other DDSP libraries, but is not compatible with consecutive frame-wise processing, since the values in the second half of the last current frame depend on the target value for the following frame.

    • ”end_linear”: linear interpolation over the full length-N frame, where the given value in x is reached at the end of the frame. This mode is compatible with consecutive frame-wise processing if a prev_val is provided.

    • ”half_linear”: linear interpolation over the first half of a length-N frame, where the given value in x is reached in the middle of the frame and stays constant until the end. This mode is compatible with consecutive frame-wise processing if a prev_val is provided.

    • ”const_smooth”: like “const”, but the resulting tensor is smoothed by convolving with a Hann window of size N // 4. This mode is not compatible with consecutive frame-wise processing, since the values in the second half of the last current frame depend on the target value for the following frame.

  • prev_val (torch.Tensor) – optional starting value for the interpolation method (see above, default: None)

Returns:

  • y (torch.Tensor) – output tensor with shape (batch, channels, N*num_frames), where the last axis contains interpolated values.

  • See also (https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html)

libdamp.helpers.tensors.smooth(x: Tensor, win_length: int = 3, win_type: str = 'rectangular', pad_mode: str = 'replicate') Tensor[source]

Smooth a tensor along its last axis using windowed convolution.

Parameters:
  • x (torch.Tensor) – Input tensor to smooth along the last axis.

  • win_length (int) – Window length for the smoothing (default: 3).

  • win_type (str) – Window type for the smoothing. See libdamp.helpers.transforms.get_window for valid options (default: “rectangular”).

  • pad_mode (str) – Padding mode for convolution borders (default: “replicate”).

Returns:

Smoothed tensor with the same shape as input.

Return type:

torch.Tensor

libdamp.helpers.tensors.cubic_hermite_splines(x: Tensor) Tensor[source]

Evaluate the first four cubic Hermite splines at the given points x

Parameters:

x (torch.Tensor) – Points at which the splines should be evaluated along the last axis, shape: (…, N).

Returns:

y – Evaluated values for the first four cubic Hermite splines, shape: (…, 4, N).

Return type:

torch.Tensor

libdamp.helpers.tensors.interpolate_pchip(x: Tensor, y: Tensor, xs: Tensor, extrapolate: Literal['const', 'linear'] = 'const') Tensor[source]

Interpolation with a Piecewise Cubic Hermite Interpolating Polynomial

This function interpolates points based on a Piecewise Cubic Hermite Interpolating Polynomial (PCHIP). It ensures a smooth function by making sure that the slope (i.e., first derivative) at each support point is continuous. For efficiency, the inputs x and xs are expected to be sorted.

Parameters:
  • x (torch.Tensor) – x values of the support points, shape: (…, N) – it is possible to give a 1D x and a 2D y, e.g., if the x values are constant across batches.

  • y (torch.Tensor) – y values of the support points, shape same as x, or with an extra batch dimension.

  • xs (torch.Tensor) – x values at which the PCHIP shall be evaluated, shape: (…, M) – a single xs can be given, e.g., if the interpolation points are constant across batches.

  • extrapolate (Literal["const", "linear"]) –

    method used for values in xs that are outside of the support points

    Options:

    • ”const”: use the y value for the first and last support point for all xs outside of the support point range. The slope at the edge points is set to 0 to ensure a smooth transition.

    • ”linear”: use the slope of the edge points to calculate a linearly interpolated y value for all xs outside of the support point range.

Returns:

ys – Interpolated values at xs, shape: (…, M).

Return type:

torch.Tensor

See also

This

https

//stackoverflow.com/questions/61616810/how-to-do-cubic-spline-interpolation-and-integration-in-pytorch

libdamp.helpers.tensors.interpolate_linear(x: Tensor, y: Tensor, xs: Tensor, extrapolate: Literal['const', 'linear'] = 'const') Tensor[source]

Linear interpolation with arbitrary support and sampling points.

For efficiency, the inputs x and xs are expected to be sorted.

Parameters:
  • x (torch.Tensor) – x values of the support points, shape: (…, N) – it is possible to give a 1D x and a 2D y, e.g., if the x values are constant across batches.

  • y (torch.Tensor) – y values of the support points, shape same as x, or with an extra batch dimension.

  • xs (torch.Tensor) – x values at which the linear interpolation shall be evaluated, shape: (…, M) – a single xs can be given, e.g., if the interpolation points are constant across batches.

  • extrapolate (Literal["const", "linear"]) –

    method used for values in xs that are outside of the support points

    Options:

    • ”const”: use the y value for the first and last support point for all xs outside of the support point range. The slope at the edge points is set to 0 to ensure a smooth transition.

    • ”linear”: use the slope of the edge points to calculate a linearly interpolated y value for all xs outside of the support point range.

Returns:

ys – Interpolated values at xs, shape: (…, M).

Return type:

torch.Tensor

libdamp.helpers.tensors.poly(roots)[source]

Equivalent of numpy.poly in PyTorch

Parameters:

roots (torch.Tensor) – roots along the last dimension

Collection of helper functions and classes related to signal transforms.

This module is part of the libdamp package.

libdamp.helpers.transforms.get_window(win_type: str, win_length: int) Tensor[source]

Return a window function.

Parameters:
  • win_type (str) – window type, can either be a function name of a torch window function [1] or a window name recognized by scipy.signal.windows.get_window() [2].

  • win_length (int) – window length in samples

Returns:

win – a 1D tensor containing the sampled window function

Return type:

torch.Tensor

References

[1]: https://pytorch.org/docs/stable/torch.html#spectral-ops [2]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.get_window.html

libdamp.helpers.transforms.stft(x: Tensor, N: int, H: int, win_type: str = 'hann', with_phase: bool = True, center: bool = True) tuple[Tensor, Tensor] | Tensor[source]

Calculate the short-time Fourier transform (STFT) of a signal.

Parameters:
  • x (torch.Tensor) – Input audio signal(s) where the STFT is calculated along the last axis.

  • N (int) – Window and transform size in samples.

  • H (int) – Hop size in samples.

  • win_type (str) – Window function to use for the STFT. See get_window() for options (default: “hann”).

  • with_phase (bool) – Whether to return magnitude and phase separately (True) or magnitude only (False) (default: True).

  • center (bool) – Whether to center-pad the signal before STFT (default: True).

Returns:

If with_phase=True: (magnitude, phase) tuple, each shape (…, freq_bins, time_frames). If with_phase=False: magnitude-only tensor of shape (…, freq_bins, time_frames).

Return type:

tuple[torch.Tensor, torch.Tensor] or torch.Tensor

libdamp.helpers.transforms.istft(X: Tensor, N: int, H: int, win_type: str = 'hann') Tensor[source]

Calculate the inverse STFT of a signal.

Parameters:
  • X (torch.Tensor) – complex input STFT(s), where the inverse transform is calculated on the last two axes

  • N (int) – window and transform size in samples

  • H (int) – hop size in samples

  • win_type (str) – window function to be used for the STFT (see get_window() for options, default: “hann”)

Returns:

x – time-domain signal reconstructed from the input STFT

Return type:

torch.Tensor

libdamp.helpers.transforms.hilbert(x: Tensor) Tensor[source]

Hilbert transform along the last dimension of input signal x.

Parameters:

x (torch.Tensor) – Input signal of shape (…, num_samples).

Returns:

Complex-valued analytic signal with the same shape as input.

Return type:

torch.Tensor, shape (…, num_samples)