Filterbanks (dsptoolbox.filterbanks)

Filter Banks

This is a collection of useful filters and filter banks.

Perfect magnitude reconstruction:

  • linkwitz_riley_crossovers()

Perfect reconstruction:

  • reconstructing_fractional_octave_bands()

Psychoacoustics:

  • auditory_filters_gammatone()

Other:

  • qmf_crossover(): Quadrature mirror filters crossover.

  • fractional_octave_bands(): Butterworth bandpass filter bank with signal energy conservation.

  • weightning_filter(): A- or C-Weightning filter.

  • complementary_fir_filter(): Create a complementary FIR filter from a linear-phase FIR prototype.

  • LatticeLadderFilter(): Filter with lattice-ladder topology.

  • PhaseLinearizer(): Design an FIR filter that linearizes a phase spectrum.

  • GroupDelayDesigner(): Design an FIR filter that matches a target group delay.

  • StateVariableFilter(): SV-Filter discretized with a topology-preserving transform.

  • IIRFilter(): General IIR filter implemented as transposed direct-form 2.

  • FIRFilter(): FIR filter implemented in the time domain.

  • FIRFilterOverlapSave(): FIR filter implemented for real-time processing using RFFT and overlap-save.

  • FIRUniformPartitioned(): FIR filter implemented for real-time processing using RFFT and overlap-save and a partitioned filter.

  • FIRUniformPartitioned(): FIR filter implemented for real-time processing using RFFT and overlap-save and a partitioned filter. Capable of vectorized multichannel processing.

  • WarpedFIR(): FIR filter implemented in the time domain with efficient warping.

  • WarpedIIR(): IIR filter implemented in the time domain with warping.

  • ParallelFilter(): Find the (least-squares) optimal linear combination of parallel SOS to approximate an IR.

  • KautzFilter(): Kautz filters with an orthonormal pole basis.

  • ExponentialAverageFilter().

  • StateSpaceFilter(): Filter with state space representation.

  • FilterChain(): Filter structure for applying all other filters sequentially.

  • pinking_filter(): Get a -3 dB/octave filter.

  • matched_biquad(): Analog-matched biquad filters.

  • gaussian_kernel(): IIR first-order approximation of a gaussian window.

  • fractional_delay(): IIR filter with tunable, fractional delay.

  • arma(): IIR filter approximation of an impulse response.

class dsptoolbox.filterbanks.ArmaMethod(*values)

Bases: Enum

Method to use for computing estimating the ARMA parameters.

YuleWalker and Burg (see [1]) deliver AR parameters, while the MA parameters are subsequently fitted using a least-squares approximation.

SteiglitzMcBride [3] and Prony [4] deliver directly both AR and MA parameters. SteiglitzMcBride utilizes YuleWalker as initial estimate for the AR parameters.

References

  • [1]: Larry Marple. A New Autoregressive Spectrum Analysis Algorithm. IEEE Transactions on Acoustics, Speech, and Signal Processing vol 28, no. 4, 1980.

  • [2]: McFee, Brian, Colin Raffel, Dawen Liang, Daniel PW Ellis, Matt McVicar, Eric Battenberg, and Oriol Nieto. “librosa: Audio and music signal analysis in python.” In Proceedings of the 14th python in science conference, pp. 18-25. 2015.

  • [3]: K. Steiglitz and L. McBride, “A technique for the identification of linear systems,” in IEEE Transactions on Automatic Control, vol. 10, no. 4, pp. 461-464, October 1965, doi: 10.1109/TAC.1965.1098181.

  • [4]: S. Hu, S.M. Wu, Prony estimation of AR parameters of an ARMA time series, Mechanical Systems and Signal Processing, Volume 3, Issue 2, 1989, Pages 207-211, ISSN 0888-3270, https://doi.org/10.1016/0888-3270(89)90017-4.

Burg = 2
Prony = 3
SteiglitzMcBride = 4
YuleWalker = 1
class dsptoolbox.filterbanks.ExponentialAverageFilter(increase_time_s: float, decrease_time_s: float, sampling_rate_hz: int, accuracy_step_response: float = 0.95)

Bases: RealtimeFilter

Methods

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

process_sample(x: float, channel: int)

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.FIRFilter(b: ndarray[tuple[Any, ...], dtype[float64]])

Bases: RealtimeFilter

FIR filter implemented in the time domain. This class is written for experimentation purposes and realtime applications, but using scipy.signal.lfilter or some convolution function should be preferred for usual offline filtering tasks.

Methods

from_filter(fir)

Instantiate FIR filter.

process_sample(x, channel)

Process a sample.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

static from_filter(fir: Filter)

Instantiate FIR filter.

Parameters:
firFilter

FIR filter.

Returns:
FIRFilter
process_sample(x: float, channel: int)

Process a sample.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.FIRFilterOverlapSave(b: ndarray[tuple[Any, ...], dtype[float64]])

Bases: RealtimeFilter

Execute a convolution of an FIR filter with the overlap-save scheme. This can be used in realtime with block-processing.

Methods

from_filter(fir)

Instantiate FIR filter.

prepare(blocksize_samples, n_channels)

Prepare the filter for block processing.

process_block(block, channel)

Apply FIR filter to a block.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

static from_filter(fir: Filter)

Instantiate FIR filter.

Parameters:
firFilter

FIR filter.

prepare(blocksize_samples: int, n_channels: int)

Prepare the filter for block processing.

Parameters:
blocksize_samplesint

Size of blocks in samples.

n_channelsint

Number of channels to prepare the buffers.

process_block(block: ndarray[tuple[Any, ...], dtype[float64]], channel: int) ndarray[tuple[Any, ...], dtype[float64]]

Apply FIR filter to a block. It is expected to have a single dimension.

Parameters:
blockNDArray[np.float64]

Block of new samples. It is expected that it only has a single dimension corresponding to the defined block size.

channelint

Channel to which the passed block corresponds. It is not checked for performance.

process_sample(x: float, channel: int)

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.FIRUniformPartitioned(fir: ndarray[tuple[Any, ...], dtype[float64]])

Bases: FIRFilterOverlapSave

FIR filter implemented with overlap-save scheme and uniform filter partitions. This type of filter can be used when the FIR filter is considerably long.

Methods

from_filter(fir)

Instantiate FIR filter.

prepare(blocksize_samples, n_channels)

Prepare the filter for block processing.

process_block(block, channel)

Apply FIR filter to a block.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

static from_filter(fir: Filter)

Instantiate FIR filter.

Parameters:
firFilter

FIR filter.

prepare(blocksize_samples: int, n_channels: int)

Prepare the filter for block processing.

Parameters:
blocksize_samplesint

Size of blocks in samples.

n_channelsint

Number of channels to prepare the buffers.

process_block(block: ndarray[tuple[Any, ...], dtype[float64]], channel: int)

Apply FIR filter to a block. It is expected to have a single dimension.

Parameters:
blockNDArray[np.float64]

Block of new samples. It is expected that it only has a single dimension corresponding to the defined block size.

channelint

Channel to which the passed block corresponds. It is not checked for performance.

reset_state()

Reset all filter states to 0.

class dsptoolbox.filterbanks.FIRUniformPartitionedMultichannel(fir: ndarray[tuple[Any, ...], dtype[float64]])

Bases: FIRUniformPartitioned

FIR filter implemented with overlap-save scheme and uniform filter partitions. This type of filter can be used when the FIR filter is considerably long. This version always processes multiple channels at once with different inputs and different outputs. This might be more efficient that doing each channel individually due to vectorization.

Methods

from_filter(fir)

Instantiate FIR filter.

prepare(blocksize_samples)

Prepares the processing.

process_block(block)

Process an input block.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

prepare(blocksize_samples: int)

Prepares the processing.

Parameters:
blocksize_samplesint

Block size to use

process_block(block: ndarray[tuple[Any, ...], dtype[float64]])

Process an input block.

Parameters:
blockNDArray[np.float64]

Block with input data. It is expected to have shape (time samples, channels) and always contain all channels to process.

Returns:
NDArray[np.float64]

Output of convolution with shape (time samples, channels)

class dsptoolbox.filterbanks.FilterChain(filters: list[RealtimeFilter])

Bases: RealtimeFilter

This is a utility class for applying a series of real-time filters sequentially.

Attributes:
n_filters

Methods

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

property n_filters
process_sample(x: float, channel: int)

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.FirDesigner(target_magnitude_response: ndarray[tuple[Any, ...], dtype[float64]], target_group_delay_s: ndarray[tuple[Any, ...], dtype[float64]], time_data_length_samples: int, sampling_rate_hz: int)

Bases: object

This class designs an FIR filter with a desired magnitude and group delay response.

Methods

get_filter()

Get FIR filter.

get_filter_as_ir()

Get the phase filter as an ImpulseResponse.

set_parameters([delay_increase_ms, ...])

Set parameters for the FIR filter.

get_filter() Filter

Get FIR filter.

get_filter_as_ir() ImpulseResponse

Get the phase filter as an ImpulseResponse.

set_parameters(delay_increase_ms: float = 0.0, additional_length_samples: int | None = 0, trapezoidal_integration: bool = True, ensure_integer_delay: bool = False)

Set parameters for the FIR filter.

Parameters:
delay_increase_msfloat, optional

This is an overall increase in delay to the current group delay (in milliseconds). Increasing this improves the quality of the designed filter but also makes it longer. Default: 0.

additional_length_samplesint, optional

When obtaining the group delay, some energy might leak into the latest samples. Through this parameter, the last samples can be retained at the expense of a longer filter. Pass 0 to retain only the theoretical minimum. Pass None to return the whole computed IR. Default: 0.

trapezoidal_integrationbool, optional

In order to obtain a phase response, the desired group delay must be integrated using a numerical integration method. Trapezoidal or Simpson integration can be used. The former tends to be more stable but delivers less smooth responses. It will be activated when True, otherwise, pass False to use Simpson. Default: True.

ensure_integer_delaybool, optional

When True, integer delay for the phase response is ensured by forcing nyquist frequency to be exclusively real. Default: False.

class dsptoolbox.filterbanks.GroupDelayDesigner(target_group_delay_s: ndarray[tuple[Any, ...], dtype[float64]], time_data_length_samples: int, sampling_rate_hz: int)

Bases: FirDesigner

This class designs an FIR filter with a desired group delay response.

Methods

get_filter()

Get FIR filter.

get_filter_as_ir()

Get the phase filter as an ImpulseResponse.

set_parameters([delay_increase_ms, ...])

Set parameters for the FIR filter.

class dsptoolbox.filterbanks.IIRFilter(b: ndarray[tuple[Any, ...], dtype[float64]], a: ndarray[tuple[Any, ...], dtype[float64]])

Bases: RealtimeFilter

IIR filter implemented as a transposed direct form 2. This class is written for experimentation purposes and realtime applications, but using scipy.signal.lfilter should be preferred for common offline filtering tasks.

Methods

from_filter(iir)

Instantiate IIR filter.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

static from_filter(iir: Filter)

Instantiate IIR filter.

Parameters:
iirFilter

IIR filter.

Returns:
IIRFilter
process_sample(x: float, channel: int)

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.KautzFilter(poles: ndarray[tuple[Any, ...], dtype[complex128]], sampling_rate_hz: int)

Bases: RealtimeFilter

Class for a Kautz filter that can process real-valued signals. See references for details on Kautz Filters and their uses.

Methods

filter_signal(signal)

Filter a whole signal with the Kautz filter.

fit_coefficients_to_ir(ir)

Fit Kautz filter coefficients to an impulse response.

fit_poles_and_coefficients_to_ir(ir, order, ...)

Find optimal poles for fitting an IR using the algorithm of [1] and based on [2].

from_ir(ir, order, iterations)

Approximate the IR with an optimal pole basis and coefficients.

get_ir(length_samples)

Return an impulse response from the Kautz filter.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_filter_coefficients(c_real, c_complex)

Set the filter coefficients for each section of the Kautz filter.

set_n_channels(n_channels)

Set the number of channels to be filtered.

References

filter_signal(signal: Signal) Signal

Filter a whole signal with the Kautz filter.

fit_coefficients_to_ir(ir: ImpulseResponse)

Fit Kautz filter coefficients to an impulse response. See references for the details on how this is accomplished.

Parameters:
irImpulseResponse

Single-channel impulse response to which to fit the filter coefficients. This works best for minimum-phase IRs and IRs without initial delay.

References

fit_poles_and_coefficients_to_ir(ir: ImpulseResponse, order: int, iterations: int)

Find optimal poles for fitting an IR using the algorithm of [1] and based on [2].

References

  • [1]: This function is a port from the matlab toolbox: http://legacy.spa.aalto.fi/software/kautz/kautz.htm

  • [2]: H.Brandenstein and R. Unbehauen, “Least-Square Approximation of FIR by IIR Filters”, IEEE Transactions on Signal Processing, vol. 46, no. 1, pp. 21 - 30, 1998.

static from_ir(ir: ImpulseResponse, order: int, iterations: int)

Approximate the IR with an optimal pole basis and coefficients. The algorithm is a port from [1] and based on [2].

Parameters:
irImpulseResponse

IR to approximate

orderint

Order of the Kautz filter.

iterationsint

Number of iterations for finding optimal poles.

Returns:
KautzFilter

References

  • [1]: This function is a port from the matlab toolbox: http://legacy.spa.aalto.fi/software/kautz/kautz.htm

  • [2]: H.Brandenstein and R. Unbehauen, “Least-Square Approximation of FIR by IIR Filters”, IEEE Transactions on Signal Processing, vol. 46, no. 1, pp. 21 - 30, 1998.

get_ir(length_samples: int) ImpulseResponse

Return an impulse response from the Kautz filter.

process_sample(x: float, channel: int)

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_filter_coefficients(c_real: ndarray[tuple[Any, ...], dtype[float64]], c_complex: ndarray[tuple[Any, ...], dtype[float64]])

Set the filter coefficients for each section of the Kautz filter. Optimal filter coefficients (in a least-squares sense) can be found by analyzing an IR with the desired magnitude and phase response in fit_coefficients_to_ir().

Parameters:
c_realNDArray[np.float64]

Coefficients corresponding to the real poles.

c_complexNDArray[np.float64]

Coefficients for the complex poles. The coefficients will be used with adjacent complex-conjugated pairs, i.e., pole a+1j*b and then pole a-1j*b.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.LatticeLadderFilter(k_coefficients: ndarray[tuple[Any, ...], dtype[float64]], c_coefficients: ndarray[tuple[Any, ...], dtype[float64]] | None = None, sampling_rate_hz: int | None = None)

Bases: RealtimeFilter

This is a class that handles a Lattice/Ladder filter representation. Depending on the k (reflection) or c (feedforward) coefficients, it might be a lattice or lattice/ladder filter structure.

The filtering is done on a pure-python implementation and is considerably slower than scipy.signal.lfilter.

Methods

filter_signal(signal)

Filtering using a lattice ladder structure (general IIR filter).

from_filter(filt)

Convert an IIR or FIR filter into its lattice-ladder filter representation.

process_sample(x, channel)

Filtering using a lattice ladder structure (general IIR filter).

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

References

  • Oppenheim, A. V., Schafer, R. W.,, Buck, J. R. (1999). Discrete-Time Signal Processing. Prentice-hall Englewood Cliffs.

filter_signal(signal: Signal) Signal

Filtering using a lattice ladder structure (general IIR filter). The implementation follows [1].

Parameters:
signalSignal

Signal to filter.

Returns:
Signal

Filtered signal.

References

  • [1]: Oppenheim, A. V., Schafer, R. W.,, Buck, J. R. (1999). Discrete-Time Signal Processing. Prentice-hall Englewood Cliffs.

static from_filter(filt: Filter) LatticeLadderFilter

Convert an IIR or FIR filter into its lattice-ladder filter representation. Filtering is then done using the lattice coefficients. If the filter uses second-order sections, the lattice-ladder coefficients are also computed and used in second-order sections.

Parameters:
filt: `Filter`

Filter to convert into its lattice filter representation.

Returns:
new_filtLatticeLadderFilter

New filter representation.

Notes

  • Linear phase FIR filters produce unstable reflection coefficients and can therefore not be converted into lattice filters. When trying to do this, an assertion error is raised.

process_sample(x: float, channel: int)

Filtering using a lattice ladder structure (general IIR filter). The implementation follows [1].

Parameters:
xfloat

Input sample

channelint

Channel to use (filter state)

Returns:
float

Filtered sample

References

  • [1]: Oppenheim, A. V., Schafer, R. W.,, Buck, J. R. (1999). Discrete-Time Signal Processing. Prentice-hall Englewood Cliffs.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.ParallelFilter(poles: ndarray[tuple[Any, ...], dtype[complex128]], n_fir: int, sampling_rate_hz: int)

Bases: RealtimeFilter

Filter bank that processes filtering using SOS in parallel and an FIR part. See [1] for details.

Methods

filter_signal(signal)

Filter a signal using the parallel filter bank.

fit_to_ir(ir)

Fit the filter coefficients of this filter bank to an IR using the frequency-domain least-squares approximation as outlined in [1].

get_ir(length_samples)

Get an impulse response from the filter bank.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_coefficients(iir_coefficients[, fir])

Set the parallel filter coefficients.

set_n_channels(n_channels)

Set the number of channels to be filtered.

set_parameters([delay_iir_samples, ...])

Parameters for the parallel filter bank.

References

  • [1]: Bank, B. (2022). Warped, Kautz, and Fixed-Pole Parallel Filters: A

Review. Journal of the Audio Engineering Society.

filter_signal(signal: Signal) Signal

Filter a signal using the parallel filter bank.

Parameters:
signalSignal

Signal to be filtered.

Returns:
Signal

Filtered signal. It has the same length as the input.

fit_to_ir(ir: ImpulseResponse)

Fit the filter coefficients of this filter bank to an IR using the frequency-domain least-squares approximation as outlined in [1].

Parameters:
irImpulseResponse

IR to approximate. The IR should contain a single channel. For the approximation to deliver satisfactory results, it is recommended that the IR be minimum phase.

References

  • [1]: Bank, B. (2022). Warped, Kautz, and Fixed-Pole Parallel Filters:

A Review. Journal of the Audio Engineering Society.

get_ir(length_samples: int)

Get an impulse response from the filter bank.

process_sample(x: float, channel: int)

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_coefficients(iir_coefficients: ndarray[tuple[Any, ...], dtype[float64]], fir: ndarray[tuple[Any, ...], dtype[float64]] | None = None)

Set the parallel filter coefficients.

Parameters:
iir_coefficientsNDArray[np.float64]

Coefficients for each SOS. It must have shape (n_sos, 2).

firNDArray[np.float64]

FIR coefficients.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

set_parameters(delay_iir_samples: int = 0, fir_offset_ms: float = 0.0)

Parameters for the parallel filter bank.

Parameters:
delay_iir_samplesint, optional

This delay is applied to the IIR part of the filter bank. It can be used in order to separate the influence of the zeros from the poles in the transfer function when setting delay_iir_samples = n_fir. Default: 0.

fir_offset_msfloat, optional

A delay between the FIR coefficients can be added with this offset. Set to 0 if all FIR coefficients should be contiguous. Default: 0.

class dsptoolbox.filterbanks.PhaseLinearizer(phase_response: ndarray[tuple[Any, ...], dtype[float64]], time_data_length_samples: int, sampling_rate_hz: int)

Bases: GroupDelayDesigner

This class designs an FIR filter that linearizes a known phase response.

Methods

get_filter()

Get FIR filter.

get_filter_as_ir()

Get the phase filter as an ImpulseResponse.

set_parameters([delay_increase_percent, ...])

Set parameters for the FIR filter.

set_parameters(delay_increase_percent: float = 100.0, additional_length_samples: int | None = 0, trapezoidal_integration: bool = True, ensure_integer_delay: bool = False)

Set parameters for the FIR filter.

Parameters:
delay_increase_percentfloat, optional

This is the increase (in percentage) in delay to the current maximum group delay. Increasing this improves the quality of the designed filter but also makes it longer. Passing a value of 100 means that the total group delay will be 2 times larger than the longest group delay. Default: 100.

additional_length_samplesint, optional

When obtaining the group delay, some energy might leak into the latest samples. Through this parameter, the last samples can be retained at the expense of a longer filter. Pass 0 to retain only the theoretical minimum or None for the whole computed IR. Default: 0.

trapezoidal_integrationbool, optional

In order to obtain a phase response, the desired group delay must be integrated using a numerical integration method. Trapezoidal or Simpson can be used. The former tends to be more stable but delivers less smooth responses. It will be activated when True, otherwise, pass False to use Simpson. Default: True.

ensure_integer_delaybool, optional

When True, integer delay for the phase response is ensured by forcing nyquist frequency to be exclusively real. Default: False.

class dsptoolbox.filterbanks.StateSpaceFilter(A: ndarray[tuple[Any, ...], dtype[float64]], B: ndarray[tuple[Any, ...], dtype[float64]], C: ndarray[tuple[Any, ...], dtype[float64]], D: ndarray[tuple[Any, ...], dtype[float64]])

Bases: RealtimeFilter

Methods

from_filter(filt)

Get a state-space filter from a common IIR representation.

from_filter_as_sos_list(filt)

Get a state-space filter from a common IIR representation.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

static from_filter(filt: Filter)

Get a state-space filter from a common IIR representation. This function converts always to b and a coefficients before going into A, B, C, D matrices. For better numerical stability in high order filters, refer to from_filter_as_sos_list.

Parameters:
filtFilter
Returns:
StateSpaceFilter
static from_filter_as_sos_list(filt: Filter)

Get a state-space filter from a common IIR representation. This function converts each SOS of the original filter into A, B, C, D matrices and returns a list of second-order StateSpaceFilter.

Parameters:
filtFilter
Returns:
list[StateSpaceFilter]
process_sample(x: float, channel: int)

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.StateVariableFilter(frequency_hz: float, resonance: float, sampling_rate_hz: int)

Bases: RealtimeFilter

This is a state variable filter discretized using the topology-preserving transform (trapezoidal integrator).

Methods

filter_signal(signal)

Filter a signal.

get_ir(length_samples)

Get an IR from the VS-Filter.

plot_group_delay(length_samples[, range_hz])

Plot the group delay of each band output of the filter.

plot_magnitude(length_samples[, range_hz, ...])

Plot the magnitude response of each band output of the filter.

plot_phase(length_samples[, range_hz, unwrap])

Plot the phase of each band output of the filter.

process_sample(sample[, channel])

Process a single sample using a specific channel.

reset_state()

Reset filter states.

set_n_channels(n_channels)

Set the number of channels to be filtered.

set_parameters(frequency_hz, resonance, ...)

Set filter parameters.

filter_signal(signal: Signal) MultiBandSignal

Filter a signal.

Parameters:
signalSignal

Input signal to be filtered.

Returns:
MultiBandSignal

Multiband signal containing the four outputs of the filter: lowpass, highpass, bandpass and allpass (saved in this order in the multiband signal).

Notes

  • Current filter states are used and they are NOT set to zero afterwards.

get_ir(length_samples: int) MultiBandSignal

Get an IR from the VS-Filter.

Parameters:
length_samplesint

Length of the IR in samples.

Returns:
MultiBandSignal

Impulse responses of the filter in following order: lowpass, highpass, bandpass and allpass.

plot_group_delay(length_samples: int, range_hz: list[float] | None = [20.0, 20000.0]) tuple[Figure, Axes]

Plot the group delay of each band output of the filter.

Parameters:
length_samplesint

Length of the IR.

range_hzlist, None, optional

Range of Hz to plot. Default: [20, 20e3].

Returns:
Figure, Axes

Matplotlib’s figure and axes.

plot_magnitude(length_samples: int, range_hz: list | None = [20, 20000.0], range_db: list | None = None) tuple[Figure, Axes]

Plot the magnitude response of each band output of the filter.

Parameters:
length_samplesint

Length of the IR.

range_hzlist, None, optional

Range of Hz to plot. Default: [20, 20e3].

range_dblist, None, optional

Range of dB to plot. Pass None to plot automatically. Default: None.

Returns:
Figure, Axes

Matplotlib’s figure and axes.

plot_phase(length_samples: int, range_hz: list | None = [20, 20000.0], unwrap: bool = False) tuple[Figure, Axes]

Plot the phase of each band output of the filter.

Parameters:
length_samplesint

Length of the IR.

range_hzlist, None, optional

Range of Hz to plot. Default: [20, 20e3].

unwrapbool, optional

When True, the phase response is unwrapped. Default: False.

Returns:
Figure, Axes

Matplotlib’s figure and axes.

process_sample(sample: float, channel: int = 0) tuple[float, float, float, float]

Process a single sample using a specific channel. Outputs are lowpass, highpass, bandpass, allpass.

reset_state()

Reset filter states.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

set_parameters(frequency_hz: float, resonance: float, n_channels: int)

Set filter parameters.

Parameters:
frequency_hzfloat

Cutoff frequency.

resonancefloat

Resonance parameter.

n_channelsint

Number of channels to be filtered (Necessary for the filter’s states).

class dsptoolbox.filterbanks.WarpedFIR(b: ndarray[tuple[Any, ...], dtype[float64]], warping_factor: float, sampling_rate_hz: int)

Bases: RealtimeFilter

The Warped FIR filter has a structure like a common FIR filter but with allpasses instead of unit delays between each coefficient. This warps the input during the filtering stage.

This implementation is done efficiently according to [1].

Methods

filter_signal(signal)

Filter a whole signal with the warped FIR filter.

from_filter(filt, warping_factor)

Instantiate with the coefficients of a filter.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

References

  • [1]: Karjalainen, M. & Härmä, Aki & Laine, Unto & Huopaniemi, J.. (1997). Warped filters and their audio applications. 4 pp.. 10.1109/ASPAA.1997.625615.

filter_signal(signal: Signal) Signal

Filter a whole signal with the warped FIR filter. The existing buffers are left unmodified in this operation.

Parameters:
signalSignal

Signal to be filtered.

static from_filter(filt: Filter, warping_factor: float)

Instantiate with the coefficients of a filter. It must be FIR

Parameters:
filtFilter

Filter with coefficients.

warping_factorfloat

Factor to use for warping.

Returns:
WarpedFIR
process_sample(x: float, channel: int) float

Process a sample with the filter for a given channel. Channel index is not checked for speed.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels: int)

Set the number of channels to be filtered.

class dsptoolbox.filterbanks.WarpedIIR(b: ndarray[tuple[Any, ...], dtype[float64]], a: ndarray[tuple[Any, ...], dtype[float64]], warping_factor: float, sampling_rate_hz: int)

Bases: WarpedFIR

The Warped IIR filter has a structure which warps the input during the filtering stage. This implementation is done according to [1].

Methods

filter_signal(signal)

Filter a whole signal with the warped FIR filter.

from_filter(filt, warping_factor)

Instantiate with the coefficients of a filter.

process_sample(x, channel)

Process a sample with the filter for a given channel.

reset_state()

Reset all filter states to 0.

set_n_channels(n_channels)

Set the number of channels to be filtered.

References

  • [1]: Karjalainen, M. & Härmä, Aki & Laine, Unto & Huopaniemi, J.. (1997). Warped filters and their audio applications. 4 pp.. 10.1109/ASPAA.1997.625615.

static from_filter(filt: Filter, warping_factor: float)

Instantiate with the coefficients of a filter. It must be IIR

Parameters:
filtFilter

Filter with coefficients.

warping_factorfloat

Factor to use for warping.

Returns:
WarpedFIR
process_sample(x: float, channel: int) float

Process a sample with the filter for a given channel. Channel index is not checked for speed.

dsptoolbox.filterbanks.arma(ir: ImpulseResponse, order_a: int, order_b: int = 0, method: ArmaMethod = ArmaMethod.YuleWalker, n_iterations_steiglitz_mcbride: int = 5) Filter

Create an IIR filter approximation to an impulse response with an autoregressive (AR), moving-average (MA) process model estimation. Not all methods deliver stable filters consistently. See notes for details.

Parameters:
irImpulseResponse

Impulse response to be approximated. This should be done for a single-channel IR.

order_aint

Order of the denominator coefficients of the IIR filter. These are the reflection or autoregressive coefficients.

order_bint, optional

Order of the numerator coefficients. These are the moving-average coefficients. Pass 0 to obtain a pure AR estimation.

methodArmaMethod, optional

Method to use for obtaining the AR or ARMA parameters. Burg’s method is explained in [1] and the implementation was taken from [2]. See [3] and [4] for for Steiglitz-McBride and Prony methods respectively. Default: YuleWalker.

n_iterations_steiglitz_mcbrideint, optional

Define the number of iterations to compute when using the SteiglitzMcBride method. If another method is selected, this parameter is ignored. Default: 5.

Returns:
Filter

IIR filter with the provided orders for the numerator and denominator coefficients.

Notes

  • For YuleWalker and Burg: This function finds the autoregressive (AR) parameters first by solving the Yule-Walker equations through the Levinson-Durbin recursion or using Burg’s method. Afterwards, the moving-average (MA) parameters are obtained through a least-squares approximation.

  • Prony and SteiglitzMcBride approximate both AR and MA parameters directly, whereas the initial estimate used by SteiglitzMcBride for the AR parameters is the output of YuleWalker.

  • YuleWalker and Burg are ensured to deliver stable filters. Prony and SteiglitzMcBride could potentially give unstable filters in some cases. This should always be assessed.

  • A number of iterations must be passed for SteiglitzMcBride.

  • Due to the AR(MA) parameter estimation in the time domain, the phase response is also approximated.

  • Minimum-phase impulse responses deliver the best approximations.

  • AR or MA orders above 120 are not recommended for warping due to greater effects of numerical errors.

References

  • [1]: Larry Marple. A New Autoregressive Spectrum Analysis Algorithm. IEEE Transactions on Acoustics, Speech, and Signal Processing vol 28, no. 4, 1980.

  • [2]: McFee, Brian, Colin Raffel, Dawen Liang, Daniel PW Ellis, Matt McVicar, Eric Battenberg, and Oriol Nieto. “librosa: Audio and music signal analysis in python.” In Proceedings of the 14th python in science conference, pp. 18-25. 2015.

  • [3]: K. Steiglitz and L. McBride, “A technique for the identification of linear systems,” in IEEE Transactions on Automatic Control, vol. 10, no. 4, pp. 461-464, October 1965, doi: 10.1109/TAC.1965.1098181.

  • [4]: S. Hu, S.M. Wu, Prony estimation of AR parameters of an ARMA time series, Mechanical Systems and Signal Processing, Volume 3, Issue 2, 1989, Pages 207-211, ISSN 0888-3270, https://doi.org/10.1016/0888-3270(89)90017-4.

dsptoolbox.filterbanks.auditory_filters_gammatone(frequency_range_hz=[20, 20000], resolution: float = 1, sampling_rate_hz: int | None = None) GammaToneFilterBank

Generate an auditory filter bank for analysis purposes. This code was taken and adapted from the pyfar package. In this implementation, the reference frequency is fixed to 1000 Hz and delay to 4 ms.

For a more general implementation of this filter bank please refer to the pyfar package or the octave/matlab auditory modelling toolbox. See references.

Parameters:
frequency_range_hzarray-like, optional

The upper and lower frequency in Hz between which the filter bank is constructed. Values must be larger than 0 and not exceed half the sampling rate. Default: [20, 20e3].

resolutionnumber, optional

The frequency resolution of the filter bands in equivalent rectangular bandwidth (ERB) units. The bands of the filter bank are distributed linearly on the ERB scale. The default value of 1 results in one filter band per ERB. Default: 1.

sampling_rate_hzint

The sampling rate of the filter bank in Hz. Default: None.

Methods

Apart from all the methods of the `FilterBank` class, there is also the

`reconstruct()` method, which takes a `MultiBandSignal` and recreates

the original `Signal` from it.

Returns:
gammatone_fbGammaToneFilterBank

Auditory filters, gamma tone filter bank.

References

dsptoolbox.filterbanks.complementary_fir_filter(fir: Filter) Filter

Returns a complementary filter for an FIR filter with linear phase. It returns for instance a lowpass from a highpass prototype. Combined, they deliver perfect magnitude reconstruction (with some quantization error) and a constant group delay. This method might only return meaningful results if the filter prototype has linear phase. It is the most precise for odd lengths, but it can be used for even lengths as well.

Parameters:
firFilter

Filter prototype with linear phase.

Returns:
fir_complementaryFilter

Complementary filter.

Notes

  • For even length FIR filters, a windowed sinc function has to be computed. It uses by default the length of the filter together with a kaiser window with side lobe suppression of 60 dB. Depending on the filter length, this might give a small error for in the summed magnitude response of both filters.

dsptoolbox.filterbanks.fractional_delay(fractional_delay_samples: float, order: int, sampling_rate_hz: int) Filter

Returns a Thiran allpass filter that has an almost constant group delay. The coefficients are computed according to the closed-form formula presented in [1]. The total delay of the filter in samples is always order + fractional_delay_samples.

Parameters:
fractional_delay_samplesfloat

Non-integer delay of the filter. The value must be in range ]0, 1[.

orderint

Order of the IIR filter.

sampling_rate_hzint

Sampling rate of the filter.

Returns:
Filter

References

  • [1]: T. I. Laakso, V. Valimaki, M. Karjalainen and U. K. Laine, “Splitting the unit delay [FIR/all pass filters design],” in IEEE Signal Processing Magazine, vol. 13, no. 1, pp. 30-60, Jan. 1996, doi: 10.1109/79.482137.

dsptoolbox.filterbanks.fractional_octave_bands(frequency_range_hz=[31.5, 16000.0], octave_fraction: int = 1, filter_order: int = 6, sampling_rate_hz: int | None = None) tuple[FilterBank, ndarray[tuple[Any, ...], dtype[float64]], tuple[ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]]]]

Create and return a filter bank containing a set of of fractional octave filters that are compliant with the specifications presented in [1]. These are butterworth filters with at least order 3. For offline applications where phase or time information is also needed, filtering with zero_phase=True is recommended (the filter order will be doubled).

For even filter orders, this filter bank is energy preserving.

Parameters:
frequency_range_hzarray-like, optional

Frequency range in Hz for which to compute the filter bank. Default: [31.5, 16000].

octave_fractionint, optional

Octave fraction to use. Default: 1.

filter_orderint, optional

Filter order to be used. Less than 4 is not recommended. Default: 4.

sampling_rate_hzint

Sampling rate in Hz.

Returns:
octave_filter_bankFilterBank

Filter bank containing fractional octave band filters.

center_freqs_hzNDArray[np.float64]

Center frequencies of each band in Hz.

(lower_hz, upper_hz)tuple[NDArray[np.float64], NDArray[np.float64]]

Lower and upper bounds of each band in Hz.

References

  • [1]: ANSI S1.11:2004.

dsptoolbox.filterbanks.gaussian_kernel(kernel_length_seconds: float, kernel_boundary_value: float = 0.01, approximation_order: int = 12, sampling_rate_hz: int | None = None)

Approximate a gaussian FIR window with a first-order IIR approximation kernel according to [1]. The resulting filter must be applied using zero-phase filtering.

Parameters:
kernel_length_secondsfloat

Kernel length in seconds used to define the width of the gaussian bell in relation to time. It corresponds to the time between t=0 and t=t0 where y(t0)=kernel_boundary_value.

kernel_boundary_valuefloat, optional

Value that the gaussian window should reach after kernel_length_seconds. Default: 1e-2.

approximation_orderint, optional

Order of the approximation. This corresponds to the number of times that the filter will be applied (when using zero-phase filtering). The higher this number, the better the approximation. This should be an even number. Values around 10 will be sufficient in most cases. Default: 12.

sampling_rate_hzint

Sampling rate in Hz for the filter.

Returns:
Filter

IIR filter with the approximation kernel. It should always be applied using zero-phase filtering!

References

  • [1]: Alvarez, Mazorra, “Signal and Image Restoration using Shock Filters and Anisotropic Diffusion,” SIAM J. on Numerical Analysis, vol. 31, no. 2, pp. 590-605, 1994. http://www.jstor.org/stable/2158018

dsptoolbox.filterbanks.linkwitz_riley_crossovers(crossover_frequencies_hz, order, sampling_rate_hz: int) LRFilterBank

Returns a linkwitz-riley crossovers filter bank.

Parameters:
crossover_frequencies_hzarray-like

Frequencies at which to set the crossovers.

orderarray-like

Order of the crossovers. The higher, the steeper. See notes for more details.

sampling_rate_hzint

Sampling rate for the filterbank.

Returns:
LRFilterBank

Filter bank in form of LRFilterBank class which contains the same methods as the FilterBank class but is generated with different internal implementations.

Notes

  • Only even orders correspond to Linkwitz-Riley crossovers, but odd orders are still supported, since they deliver perfect magnitude reconstruction as well. Odd orders have band crossing at -3 dB, even orders at -6 dB.

  • All crossovers are butterworth filters except for 2nd order which are based on sallen-key filters (Q=0.5) with phase-inverted high band.

  • Slopes:
    • Order -> -x dB / Octave

    • 1 -> -6 dB / Octave

    • 2 -> -12 dB / Octave

    • 3 -> -18 dB / Octave

    • 4 -> -24 dB / Octave

    • 5 -> -30 dB / Octave

    • 7 -> -42 dB / Octave

    • 8 -> -48 dB / Octave

    • etc…

dsptoolbox.filterbanks.matched_biquad(eq_type: BiquadEqType, freq_hz: float, gain_db: float, q: float, sampling_rate_hz: int, q_factor: float | None = None) Filter

This returns a biquad digital filter (EQ) that is matched to better fit an analog prototype than the standard biquad implementation as defined in [1]. This is due to the frequency warping that occurs when the frequency approaches nyquist. See notes for details.

Parameters:
eq_typeBiquadEqType

Type of biquad filter to create. Choose from “peaking”, “lowpass”, “highpass”, “bandpass”, “lowshelf”, “highshelf”.

freq_hzfloat

Characteristic frequency in Hz.

gain_dbfloat

Characteristic gain in dB.

qfloat

Quality factor. The frequency response differs in its bandwidth from the standard biquad implementation due to frequency warping. This is specially clear for normalized frequencies higher than 0.2. Beware that the implemented shelving filters do not support setting a quality factor. Analyzing the resulting magnitude response carefully is advised.

sampling_rate_hzint

Sampling rate for the digital filter.

q_factorfloat, None, optional

Factor by which to scale q for peaking filters. This is useful for attempting to obtain similar bandwidths as the standard biquad implementation in [1]. If None, an approximation formula is used, which works well in the gain range [-20, 20] dB and normalized frequency [0, 0.2]. With increasing frequency, the warping of the standard implementation produces larger errors, so approximating the bandwidth there would defeat the purpose of the matching biquad. It always should be greater than 0. Default: None.

Returns:
Filter

Matched biquad filter.

Notes

Frequency warping generates significant deformations of the frequency response of a digital filter near nyquist when compared to the analog prototype. These filters alleviate for this at the expense of a more involved computation. Using matched biquads is only useful when designing filters or filter banks that have normalized frequencies above 0.15 or 0.2, e.g., above 7.2 kHz for 48 kHz sampling rate.

The approach used here comes from [2], though there are others. See references.

For shelving filters, [5] is implemented. This implementation does not support selecting a quality factor, i.e., q is fixed to sqrt(2)/2.

References

  • [1]: R. Bristow-Johnson, Cookbook formulae for audio EQ biquad filter coefficients.

  • [2]: M. Vicanek. Matched Second Order Digital Filters. 2016.

  • [3]: S. J. Orfanidis, Digital Parametric Equalizer Design With Prescribed Nyquist-Frequency Gain. 1997.

  • [4]: M. Massberg, Digital Low-Pass Filter Design with Analog-Matched Magnitude Response. 2011.

  • [5]: M. Vicanek. Matched Two-Pole Digital Shelving Filters. 2024.

dsptoolbox.filterbanks.pinking_filter(frequency_0_db: float, sampling_rate_hz: int) Filter

Return a filter with approximately -3 dB/octave roll-off. Usually used to turn white noise into pink noise. This is designed as an IIR filter with 4 zeros and 5 poles and implemented with second-order sections. See notes for details.

Parameters:
frequency_0_dbfloat

Frequency [Hz] that should have 0 dB amplification by the filter.

sampling_rate_hzint

Sampling rate in Hz.

Returns:
Filter

IIR filter.

Notes

  • In order to make white noise pink without changing its overall RMS value, the frequency_0_db parameter can be set to around 2.7 kHz for a sampling rate of 48 kHz. This corresponds to approximately 0.1125 normalized frequency.

  • This filter approximates a -3 dB/octave roll-off, though its frequency response might be slightly distorted for very low or high frequencies.

  • The zeros and poles were taken from

https://dsp.stackexchange.com/questions/27520/filter-to-add-3db-per-octave

dsptoolbox.filterbanks.qmf_crossover(lowpass: Filter) QMFCrossover

This creates quadrature mirror filters that work as a two band, maximally decimated filter bank. For a 1st order FIR filter, this filter bank is ensured to have perfect reconstruction capabilities.

Parameters:
lowpassFilter

Lowpass filter prototype with which to create the other filters.

Returns:
fbQMFCrossover

Quadrature mirror filters crossover.

Notes

  • The best results for avoiding imperfections in the reconstructed magnitude when using FIR filters are obtained by using a lowpass whose corresponding highpass’s power sums to be approximately 1, i.e., 1 = |H0(z)| ** 2 + |H1(z)| ** 2, where H0 is the lowpass and H1 is the highpass response.

References

dsptoolbox.filterbanks.reconstructing_fractional_octave_bands(frequency_range_hz=[63, 16000], octave_fraction: int = 1, overlap: float = 1, slope: int = 0, n_samples: int = 2048, sampling_rate_hz: int | None = None) FilterBank

Create a perfect reconstruction filter bank with linear-phase characteristics. According to (Antoni J., 2010). This implementation is taken from the pyfar package. See references for more information about it.

Parameters:
frequency_range_hztuple, optional

Frequency range in Hz. Default:[ 63, 16e3].

octave_fractionint, optional

Octave fraction used to define bandwidth. Default: 1.

overlapfloat, optional

Band overlap of the filter slopes between 0 and 1. Smaller values yield wider pass-bands and steeper filter slopes. Default: 1.

slopeint, optional

Number > 0 that defines the width and steepness of the filter slopes. Larger values yield wider pass-bands and steeper filter slopes. Default: 0.

n_samplesint, optional

Length of the filter in samples. Longer filters are more precise. Default: 2**11 = 2048.

sampling_rateint

Sampling frequency in Hz. Default: None.

Returns:
filt_bankFilterBank

Filter Bank object with FIR filters.

References

dsptoolbox.filterbanks.weighting_filter(a_weighting: bool = True, sampling_rate_hz: int | None = None)

Returns a digital IIR weighting filter according to [1]. The approximation is based on the coefficients given in [2].

Parameters:
a_weightingbool, optional

When True, an A-Weighting filter is returned, otherwise it is C-Weighting. Default: True.

sampling_rate_hzint

Sampling rate for the digital filter.

Returns:
weighting_filterFilter

Weighting filter.

References