pyfar.dsp.filter#

The following documents the pyfar filters. Visit filter types for an introduction of the different filters and filter classes for more information on pyfar filter objects.

Classes:

GammatoneBands(freq_range[, resolution, ...])

Generate reconstructing auditory filter bank.

Functions:

bell(signal, center_frequency, gain, quality)

Create and apply second order bell (parametric equalizer) filter.

bessel(signal, N, frequency[, btype, norm, ...])

Create and apply digital Bessel/Thomson IIR filter.

butterworth(signal, N, frequency[, btype, ...])

Create and apply a digital Butterworth IIR filter.

chebyshev1(signal, N, ripple, frequency[, ...])

Create and apply digital Chebyshev Type I IIR filter.

chebyshev2(signal, N, attenuation, frequency)

Create and apply digital Chebyshev Type II IIR filter.

crossover(signal, N, frequency[, sampling_rate])

Create and apply Linkwitz-Riley crossover network.

elliptic(signal, N, ripple, attenuation, ...)

Create and apply digital Elliptic (Cauer) IIR filter.

erb_frequencies(freq_range[, resolution, ...])

Get frequencies that are linearly spaced on the ERB frequency scale.

fractional_octave_bands(signal, num_fractions)

Create and/or apply an energy preserving fractional octave filter bank.

fractional_octave_frequencies([...])

Return the octave center frequencies according to the IEC 61260:1:2014 standard.

high_shelve(signal, frequency, gain, order)

Create and/or apply first or second order high shelve filter.

high_shelve_cascade(signal, frequency[, ...])

Create and apply constant slope filter from cascaded 2nd order high shelves.

low_shelve(signal, frequency, gain, order[, ...])

Create and apply first or second order low shelve filter.

low_shelve_cascade(signal, frequency[, ...])

Create and apply constant slope filter from cascaded 2nd order low shelves.

notch(signal, center_frequency, quality[, ...])

Create and apply or return a second order IIR notch filter.

reconstructing_fractional_octave_bands(signal)

Create and/or apply an amplitude preserving fractional octave filter bank.

class pyfar.dsp.filter.GammatoneBands(freq_range, resolution=1, reference_frequency=1000, delay=0.004, sampling_rate=44100)[source]#

Bases: object

Generate reconstructing auditory filter bank.

Generate a forth order reconstructing Gammatone auditory filter bank according to [1]. The center frequencies of the Gammatone filters are calculated using the ERB scale (see erb_frequencies).

This is a Python port of the hohmann2002 filter bank contained in the Auditory Modeling Toolbox [2]. The filter bank can handle single and multi channel input and allows for an almost perfect reconstruction of the input signal (see examples below).

Calling GFB = GammatoneBands() constructs the filter bank. Afterwards the class methods GFB.process() and GFB.reconstruct can be used to filter and reconstruct signals. All relevant data such as the filter coefficients can be obtained for example through GFB.coefficients. See below for more documentation.

Parameters:
  • freq_range (array like) – 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.

  • resolution (number) – 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. A value of 0.5 would result in two filter bands per ERB.

  • reference_frequency (number) – The frequency relative to which the filter bands are distributed. The default is 1000 Hz.

  • delay (number) – The delay in seconds that the filter bank will have, i.e., the delay that is added to the input signal after being filtered and summed again. The default is 0.004 seconds.

  • sampling_rate (number) – The sampling rate of the filter bank in Hz. The default is 44100 Hz.

Examples

>>> import pyfar as pf
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> # generate the filter bank object
>>> GFB = pf.dsp.filter.GammatoneBands([0, 22050])
>>>
>>> # apply the filter bank to an impulse
>>> x = pf.signals.impulse(2**13)
>>> real, imag = GFB.process(x)
>>> env = pf.Signal(np.abs(real.time + 1j * imag.time), 44100)
>>>
>>> # use pyfar plot style
>>> pf.plot.use()
>>>
>>> # the output is complex:
>>> # Real part gives band-limited Gammatone output
>>> # Imaginary part gives the Hilbert Transform thereof
>>> # Absolute value gives the Envelope
>>> plt.figure()
>>> ax = pf.plot.time(real[2], label='real part', unit='ms')
>>> pf.plot.time(imag[2], label='imaginary part', unit='ms')
>>> pf.plot.time(env[2], label='envelope', unit='ms')
>>> plt.legend()
>>>
>>> # show the magnitude response of the filter bank
>>> plt.figure()
>>> ax = pf.plot.freq(real)
>>> ax.set_ylim(-40, 5)
>>>
>>> # reconstruct the filtered impulse
>>> # the reconstruction error can be decreased
>>> # using the filter bank parameter 'resolution'
>>> y = GFB.reconstruct(real, imag)
>>> plt.figure()
>>> ax = pf.plot.time_freq(y, label="reconstructed impulse", unit='ms')
>>> ax[0].set_xlim(0, 20)
>>> ax[1].set_ylim(-40, 5)
>>> ax[0].legend()
>>>
>>> # manipulate filter output before the reconstruction
>>> # (manipulations must be applied to the real and imaginary output)
>>> real.time[20:25] *= .5
>>> imag.time[20:25] *= .5
>>>
>>> y = GFB.reconstruct(real, imag)
>>> plt.figure()
>>> ax = pf.plot.time_freq(
...     y, unit='ms',
...     label="manipulated and reconstructed and impulse")
>>> ax[0].set_xlim(0, 20)
>>> ax[1].set_ylim(-40, 5)
>>> ax[0].legend()

(Source code)

../_images/pyfar-dsp-filter-1_00.png

(png, hires.png, pdf)#

../_images/pyfar-dsp-filter-1_01.png

(png, hires.png, pdf)#

../_images/pyfar-dsp-filter-1_02.png

(png, hires.png, pdf)#

../_images/pyfar-dsp-filter-1_03.png

(png, hires.png, pdf)#

References

Attributes:

coefficients

Get the filter coefficients a as in Eq.

delay

Get the desired delay of the filter bank in seconds

delays

Get the delays required for summing the filter bands.

freq_range

Get the frequency range of the filter bank in Hz

frequencies

Get the center frequencies of the Gammatone filters in Hz

gains

Get the gains required for summing the filter bands.

n_bands

Get the number of bands in the filter bank

normalizations

Get the normalization per band described below Eq.

phase_factors

Get the phase factors required for summing the filter bands.

reference_frequency

Get the reference frequency of the filter bank in Hz

resolution

Get the resolution of the filter bank in ERB units

sampling_rate

Get the sampling rate of the filter bank in Hz

Methods:

copy()

Return a copy of the audio object.

process(signal[, reset])

Filter an input signal.

reconstruct(real, imag)

Reconstruct filter bands.

property coefficients#

Get the filter coefficients a as in Eq. (7) in Hohmann 2002 per band.

copy()[source]#

Return a copy of the audio object.

property delay#

Get the desired delay of the filter bank in seconds

property delays#

Get the delays required for summing the filter bands.

Section 4 in Hohmann 2002 describes, how the delays are calculated.

property freq_range#

Get the frequency range of the filter bank in Hz

property frequencies#

Get the center frequencies of the Gammatone filters in Hz

property gains#

Get the gains required for summing the filter bands.

Section 4 in Hohmann 2002 describes, how the gains are calculated.

property n_bands#

Get the number of bands in the filter bank

property normalizations#

Get the normalization per band described below Eq. (9) in Hohmann 2002.

property phase_factors#

Get the phase factors required for summing the filter bands.

Section 4 in Hohmann 2002 describes, how the factors are calculated.

process(signal, reset=True)[source]#

Filter an input signal.

The filter output is a complex valued time signal, whose real and imaginary part are returned separately.

  • If the filter bank is used for analysis purposes only, the imaginary part is not required for further processing.

  • If the filter bank is used for analysis and re-synthesis, any further processing must be applied to the real and imaginary part. Any complex-valued operations must be applied to the complex valued output as a whole.

Parameters:
  • signal (Signal) – The data to be filtered

  • reset (bool, optional) – If true the internal state of the filter bank is reset before the filters are applied. Not resetting the state can be useful for blockwise processing. The default is True.

Returns:

  • real (Signal) – The real part of the complex output signal. This represents the band-limited Gammatone filter output.

  • imag (Signal) – The imaginary part of the complex output signal. This approximates the Hilbert transform of the band-limited Gammatone filter output.

Notes

  • sqrt(real.time**2 + imag.time**2) gives the envelope of the Gammatone filter output.

  • If the cshape of the output signals real.cshape and imag.cshape generally is (self.n_bands, ) + signal.cshape.

  • An exception to this occurs if signal.cshape is (1, ), i.e., signal is a single channel signal. In this case the cshape of the output signals is (self.n_bands) and not (self.n_bands, 1).

reconstruct(real, imag)[source]#

Reconstruct filter bands.

The summation process is described in Section 4 of Hohmann 2002 and uses the pre-calculated delays, phase factors and gains.

Parameters:
  • real (Signal) – The real part of the filtered input signal as returned by filter.

  • imag (Signal) – The imaginary part of the filtered input signal as returned by filter.

Returns:

reconstructed – The summed input. summed.cshape matches the cshape or the original signal before it was filtered.

Return type:

Signal

property reference_frequency#

Get the reference frequency of the filter bank in Hz

property resolution#

Get the resolution of the filter bank in ERB units

property sampling_rate#

Get the sampling rate of the filter bank in Hz

pyfar.dsp.filter.bell(signal, center_frequency, gain, quality, bell_type='II', quality_warp='cos', sampling_rate=None)[source]#

Create and apply second order bell (parametric equalizer) filter.

Uses the implementation of [3].

Parameters:
  • signal (Signal, None) – The signal to be filtered. Pass None to create the filter without applying it.

  • center_frequency (number) – Center frequency of the parametric equalizer in Hz

  • gain (number) – Gain of the parametric equalizer in dB

  • quality (number) – Quality of the parametric equalizer, i.e., the inverse of the bandwidth

  • bell_type (str) –

    Defines the bandwidth/quality. The default is 'II'.

    'I'

    not recommended. Also known as ‘constant Q’.

    'II'

    defines the bandwidth by the points 3 dB below the maximum if the gain is positive and 3 dB above the minimum if the gain is negative. Also known as ‘symmetric’.

    'III'

    defines the bandwidth by the points at gain/2. Also known as ‘half pad loss’.

  • quality_warp (str) – Sets the pre-warping for the quality ('cos', 'sin', or 'tan'). The default is 'cos'.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterIIR) – Filter object. Only returned if signal = None.

References

pyfar.dsp.filter.bessel(signal, N, frequency, btype='lowpass', norm='phase', sampling_rate=None)[source]#

Create and apply digital Bessel/Thomson IIR filter.

This is a wrapper for scipy.signal.bessel. Which creates digital Bessel filter coefficients in second-order sections (SOS).

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • N (int) – The order of the Bessel/Thomson filter.

  • frequency (number, array like) – The cut off-frequency in Hz if btype is 'lowpass' or 'highpass'. An array like containing the lower and upper cut-off frequencies in Hz if btype is bandpass or bandstop.

  • btype (str) – One of the following 'lowpass', 'highpass', 'bandpass', 'bandstop'. The default is 'lowpass'.

  • norm (str) –

    Critical frequency normalization:

    'phase'

    The filter is normalized such that the phase response reaches its midpoint at angular (e.g. rad/s) frequency Wn. This happens for both low-pass and high-pass filters, so this is the “phase-matched” case. The magnitude response asymptotes are the same as a Butterworth filter of the same order with a cutoff of Wn. This is the default, and matches MATLAB’s implementation.

    'delay'

    The filter is normalized such that the group delay in the passband is 1/Wn (e.g., seconds). This is the “natural” type obtained by solving Bessel polynomials.

    'mag'

    The filter is normalized such that the gain magnitude is -3 dB at the angular frequency Wn.

    The default is ‘phase’.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterSOS) – SOS Filter object. Only returned if signal = None.

pyfar.dsp.filter.butterworth(signal, N, frequency, btype='lowpass', sampling_rate=None)[source]#

Create and apply a digital Butterworth IIR filter.

This is a wrapper for scipy.signal.butter. Which creates digital Butterworth filter coefficients in second-order sections (SOS).

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • N (int) – The order of the Butterworth filter

  • frequency (number, array like) – The cut off-frequency in Hz if btype is lowpass or highpass. An array like containing the lower and upper cut-off frequencies in Hz if btype is bandpass or bandstop.

  • btype (str) – One of the following 'lowpass', 'highpass', 'bandpass', 'bandstop'. The default is 'lowpass'.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterSOS) – SOS Filter object. Only returned if signal = None.

pyfar.dsp.filter.chebyshev1(signal, N, ripple, frequency, btype='lowpass', sampling_rate=None)[source]#

Create and apply digital Chebyshev Type I IIR filter.

This is a wrapper for scipy.signal.cheby1. Which creates digital Chebyshev Type I filter coefficients in second-order sections (SOS).

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • N (int) – The order of the Chebychev filter.

  • ripple (number) – The passband ripple in dB.

  • frequency (number, array like) – The cut off-frequency in Hz if btype is 'lowpass' or 'highpass'. An array like containing the lower and upper cut-off frequencies in Hz if btype is 'bandpass' or 'bandstop'.

  • btype (str) – One of the following 'lowpass', 'highpass', 'bandpass', 'bandstop'. The default is 'lowpass'.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterSOS) – SOS Filter object. Only returned if signal = None.

pyfar.dsp.filter.chebyshev2(signal, N, attenuation, frequency, btype='lowpass', sampling_rate=None)[source]#

Create and apply digital Chebyshev Type II IIR filter.

This is a wrapper for scipy.signal.cheby2. Which creates digital Chebyshev Type II filter coefficients in second-order sections (SOS).

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • N (int) – The order of the Chebychev filter.

  • attenuation (number) – The minimum stop band attenuation in dB.

  • frequency (number, array like) – The frequency in Hz where the attenuatoin is first reached if btype is 'lowpass' or 'highpass'. An array like containing the lower and upper frequencies in Hz if btype is 'bandpass' or 'bandstop'.

  • btype (str) – One of the following 'lowpass', 'highpass', 'bandpass', 'bandstop'. The default is 'lowpass'.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterSOS) – SOS Filter object. Only returned if signal = None.

pyfar.dsp.filter.crossover(signal, N, frequency, sampling_rate=None)[source]#

Create and apply Linkwitz-Riley crossover network.

Linkwitz-Riley crossover filters ([4], [5]) are designed by cascading Butterworth filters of order N/2. where N must be even.

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • N (int) – The order of the Linkwitz-Riley crossover network, must be even.

  • frequency (number, array-like) – Characteristic frequencies of the crossover network. If a single number is passed, the network consists of a single lowpass and highpass. If M frequencies are passed, the network consists of 1 lowpass, M-1 bandpasses, and 1 highpass.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterSOS) – Filter object. Only returned if signal = None.

References

pyfar.dsp.filter.elliptic(signal, N, ripple, attenuation, frequency, btype='lowpass', sampling_rate=None)[source]#

Create and apply digital Elliptic (Cauer) IIR filter.

This is a wrapper for scipy.signal.ellip. Which creates digital Elliptic (Cauer) filter coefficients in second-order sections (SOS).

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • N (int) – The order of the Elliptic filter.

  • ripple (number) – The passband ripple in dB.

  • attenuation (number) – The minimum stop band attenuation in dB.

  • frequency (number, array like) – The cut off-frequency in Hz if btype is 'lowpass' or 'highpass'. An array like containing the lower and upper cut-off frequencies in Hz if btype is 'bandpass' or 'bandstop'.

  • btype (str) – One of the following 'lowpass', 'highpass', 'bandpass', 'bandstop'. The default is 'lowpass'.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterSOS) – SOS Filter object. Only returned if signal = None.

pyfar.dsp.filter.erb_frequencies(freq_range, resolution=1, reference_frequency=1000)[source]#

Get frequencies that are linearly spaced on the ERB frequency scale.

The human auditory system analyzes sound in auditory filters, whose band- width is often given as a equivalent rectangular bandwidth (ERB). The ERB denotes the bandwidth of a perfect rectangular band-pass that has the same energy as the auditory filter. The ERB frequency scale is directly constructed from this concept: One ERB unit is defined as the frequency dependent ERB of the auditory filter at a given center frequency (cf. [6], Section 3B).

The implementation follows Eq. (16) and (17) in [7] and was ported from the auditory modeling toolbox [8].

Parameters:
  • freq_range (array like) – The upper and lower frequency limits in Hz between which the frequency vector is computed.

  • resolution (number, optional) – The frequency resolution in ERB units. The default of 1 returns frequencies that are spaced by 1 ERB unit, a value of 0.5 would return frequencies that are spaced by 0.5 ERB units.

  • reference_frequency (number, optional) – The reference frequency in Hz relative to which the frequency vector is constructed. The default is 1000.

Returns:

frequencies – The frequencies in Hz that are linearly distributed on the ERB scale with a spacing given by resolution ERB units.

Return type:

numpy array

References

pyfar.dsp.filter.fractional_octave_bands(signal, num_fractions, sampling_rate=None, freq_range=(20.0, 20000.0), order=14)[source]#

Create and/or apply an energy preserving fractional octave filter bank.

The filters are designed using second order sections of Butterworth band-pass filters. Note that if the upper cut-off frequency of a band lies above the Nyquist frequency, a high-pass filter is applied instead. Due to differences in the design of band-pass and high-pass filters, their slopes differ, potentially introducing an error in the summed energy in the stop- band region of the respective filters.

Note

This filter bank has -3 dB cut-off frequencies. For sufficiently large values of 'order', the summed energy of the filter bank equals the energy of input signal, i.e., the filter bank is energy preserving (reconstructing). This is useful for analysis energetic properties of the input signal such as the room acoustic property reverberation time. For an amplitude preserving filter bank with -6 dB cut-off frequencies see reconstructing_fractional_octave_bands.

Parameters:
  • signal (Signal, None) – The signal to be filtered. Pass None to create the filter without applying it.

  • num_fractions (int, optional) – The number of bands an octave is divided into. Eg., 1 refers to octave bands and 3 to third octave bands. The default is 1.

  • sampling_rate (None, int) – The sampling rate in Hz. Only required if signal is None. The default is None.

  • freq_range (array, tuple, optional) – The lower and upper frequency limits. The default is frequency_range=(20, 20e3).

  • order (int, optional) – Order of the Butterworth filter. The default is 14.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterSOS) – Filter object. Only returned if signal = None.

Examples

Filter an impulse into octave bands. The summed energy of all bands equals the energy of the input signal.

>>> import pyfar as pf
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> # generate the data
>>> x = pf.signals.impulse(2**17)
>>> y = pf.dsp.filter.fractional_octave_bands(
...     x, 1, freq_range=(20, 8e3))
>>> # frequency domain plot
>>> y_sum = pf.FrequencyData(
...     np.sum(np.abs(y.freq)**2, 0), y.frequencies)
>>> pf.plot.freq(y)
>>> ax = pf.plot.freq(y_sum, color='k', log_prefix=10, linestyle='--')
>>> ax.set_title(
...     "Filter bands and the sum of their squared magnitudes")

(Source code, png, hires.png, pdf)

../_images/pyfar-dsp-filter-2.png
pyfar.dsp.filter.fractional_octave_frequencies(num_fractions=1, frequency_range=(20, 20000.0), return_cutoff=False)[source]#

Return the octave center frequencies according to the IEC 61260:1:2014 standard.

For numbers of fractions other than 1 and 3, only the exact center frequencies are returned, since nominal frequencies are not specified by corresponding standards.

Parameters:
  • num_fractions (int, optional) – The number of bands an octave is divided into. Eg., 1 refers to octave bands and 3 to third octave bands. The default is 1.

  • frequency_range (array, tuple) – The lower and upper frequency limits, the default is frequency_range=(20, 20e3).

Returns:

  • nominal (array, float) – The nominal center frequencies in Hz specified in the standard. Nominal frequencies are only returned for octave bands and third octave bands.

  • exact (array, float) – The exact center frequencies in Hz, resulting in a uniform distribution of frequency bands over the frequency range.

  • cutoff_freq (tuple, array, float) – The lower and upper critical frequencies in Hz of the bandpass filters for each band as a tuple corresponding to (f_lower, f_upper).

pyfar.dsp.filter.high_shelve(signal, frequency, gain, order, shelve_type='I', sampling_rate=None)[source]#

Create and/or apply first or second order high shelve filter.

Uses the implementation of [9].

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • frequency (number) – Characteristic frequency of the shelve in Hz.

  • gain (number) – Gain of the shelve in dB.

  • order (number) – The shelve order. Must be 1 or 2.

  • shelve_type (str) –

    Defines the characteristic frequency. The default is 'I'.

    'I'

    Defines the characteristic frequency 3 dB below the gain value if the gain is positive and 3 dB above the gain value if the gain is negative.

    'II'

    Defines the characteristic frequency at 3 dB if the gain is positive and at -3 dB if the gain is negative.

    'III'

    Defines the characteristic frequency at gain/2 dB.

    For types I and II the absolute value of the gain must be sufficiently large (> 9 dB) to set the characteristic frequency according to the above rules with an error below 0.5 dB. For smaller absolute gain values the gain at the characteristic frequency becomes less accurate. For type III the characteristic frequency is always set correctly.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterIIR) – Filter object. Only returned if signal = None.

References

pyfar.dsp.filter.high_shelve_cascade(signal, frequency, frequency_type='lower', gain=None, slope=None, bandwidth=None, N=None, sampling_rate=None)[source]#

Create and apply constant slope filter from cascaded 2nd order high shelves.

The filters - also known as High-Schultz filters (cf. [10]) - are defined by their characteristic frequency, gain, slope, and bandwidth. Two out of the three parameter gain, slope, and bandwidth must be specified, while the third parameter is calculated as

gain = bandwidth * slope

bandwidth = abs(gain/slope)

slope = gain/bandwidth

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • frequency (number) – Characteristic frequency in Hz (see frequency_type)

  • frequency_type (string) –

    Defines how frequency is used

    'upper'

    frequency gives the upper characteristic frequency. In this case the lower characteristic frequency is given by 2**bandwidth / frequency

    'lower'

    frequency gives the lower characteristic frequency. In this case the upper characteristic frequency is given by 2**bandwidth * frequency

  • gain (number) – The filter gain in dB. The default is None, which calculates the gain from the slope and bandwidth (must be given if gain is None).

  • slope (number) – Filter slope in dB per octave, with positive values denoting a rising filter slope and negative values denoting a falling filter slope. The default is None, which calculates the slope from the gain and bandwidth (must be given if slope is None).

  • bandwidth (number) – The bandwidth of the filter in octaves. The default is None, which calculates the bandwidth from gain and slope (must be given if bandwidth is None).

  • N (int) – Number of shelve filters that are cascaded. The default is None, which calculated the minimum N that is required to satisfy Eq. (11) in Schultz et al. 2020, i.e., the minimum N that is required for a good approximation of the ideal filter response.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal, FilterSOS) – The filtered signal (returned if sampling_rate = None) or the Filter object (returned if signal = None).

  • N (int) – The number of shelve filters that were cascaded

  • ideal (FrequencyData) – The ideal, piece-wise magnitude response of the filter

References

Examples

Generate a filter with a bandwith of 4 octaves and a gain of -60 dB and compare it to the piece-wise constant idealized magnitude response.

>>> import pyfar as pf
>>> import matplotlib.pyplot as plt
>>>
>>> impulse = pf.signals.impulse(40e3, sampling_rate=40000)
>>> impulse, N, ideal = pf.dsp.filter.high_shelve_cascade(
>>>     impulse, 250, "lower", -60, None, 4)
>>>
>>> pf.plot.freq(ideal, c='k', ls='--', label="ideal")
>>> pf.plot.freq(impulse, label="actual")
>>> plt.legend()

(Source code, png, hires.png, pdf)

../_images/pyfar-dsp-filter-3.png
pyfar.dsp.filter.low_shelve(signal, frequency, gain, order, shelve_type='I', sampling_rate=None)[source]#

Create and apply first or second order low shelve filter.

Uses the implementation of [11].

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • frequency (number) – Characteristic frequency of the shelve in Hz.

  • gain (number) – Gain of the shelve in dB.

  • order (number) – The shelve order. Must be 1 or 2.

  • shelve_type (str) –

    Defines the characteristic frequency. The default is 'I'.

    'I'

    Defines the characteristic frequency 3 dB below the gain value if the gain is positive and 3 dB above the gain value if the gain is negative.

    'II'

    Defines the characteristic frequency at 3 dB if the gain is positive and at -3 dB if the gain is negative.

    'III'

    Defines the characteristic frequency at gain/2 dB.

    For types I and II the absolute value of the gain must be sufficiently large (> 9 dB) to set the characteristic frequency according to the above rules with an error below 0.5 dB. For smaller absolute gain values the gain at the characteristic frequency becomes less accurate. For type III the characteristic frequency is always set correctly.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterIIR) – Filter object. Only returned if signal = None.

References

pyfar.dsp.filter.low_shelve_cascade(signal, frequency, frequency_type='upper', gain=None, slope=None, bandwidth=None, N=None, sampling_rate=None)[source]#

Create and apply constant slope filter from cascaded 2nd order low shelves.

The filters - also known as Low-Schultz filters (cf. [12]) - are defined by their characteristic frequency, gain, slope, and bandwidth. Two out of the three parameter gain, slope, and bandwidth must be specified, while the third parameter is calculated as

gain = -bandwidth * slope

bandwidth = abs(gain/slope)

slope = -gain/bandwidth

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • frequency (number) – Characteristic frequency in Hz (see frequency_type)

  • frequency_type (string) –

    Defines how frequency is used

    'upper'

    frequency gives the upper characteristic frequency. In this case the lower characteristic frequency is given by 2**bandwidth / frequency

    'lower'

    frequency gives the lower characteristic frequency. In this case the upper characteristic frequency is given by 2**bandwidth * frequency

  • gain (number) – The filter gain in dB. The default is None, which calculates the gain from the slope and bandwidth (must be given if gain is None).

  • slope (number) – Filter slope in dB per octave, with positive values denoting a rising filter slope and negative values denoting a falling filter slope. The default is None, which calculates the slope from the gain and bandwidth (must be given if slope is None).

  • bandwidth (number) – The bandwidth of the filter in octaves. The default is None, which calculates the bandwidth from gain and slope (must be given if bandwidth is None).

  • N (int) – Number of shelve filters that are cascaded. The default is None, which calculated the minimum N that is required to satisfy Eq. (11) in Schultz et al. 2020, i.e., the minimum N that is required for a good approximation of the ideal filter response.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

  • signal (Signal, FilterSOS) – The filtered signal (returned if sampling_rate = None) or the Filter object (returned if signal = None).

  • N (int) – The number of shelve filters that were cascaded

  • ideal (FrequencyData) – The ideal, piece-wise magnitude response of the filter

References

Examples

Generate a filter with a bandwith of 4 octaves and a gain of -60 dB and compare it to the piece-wise constant idealized magnitude response.

>>> import pyfar as pf
>>> import matplotlib.pyplot as plt
>>>
>>> impulse = pf.signals.impulse(40e3, sampling_rate=40000)
>>> impulse, N, ideal = pf.dsp.filter.low_shelve_cascade(
>>>     impulse, 4000, "upper", -60, None, 4)
>>>
>>> pf.plot.freq(ideal, c='k', ls='--', label="ideal")
>>> pf.plot.freq(impulse, label="actual")
>>> plt.legend()

(Source code, png, hires.png, pdf)

../_images/pyfar-dsp-filter-4.png
pyfar.dsp.filter.notch(signal, center_frequency, quality, sampling_rate=None)[source]#

Create and apply or return a second order IIR notch filter.

A notch filter is a band-stop filter with a narrow bandwidth (high quality factor). It rejects a narrow frequency band around the center frequency with a gain of 0 (\(-\infty\) dB) at the center frequency and leaves the rest of the spectrum little changed with gains close to 1 (0 dB). Wrapper for scipy.signal.iirnotch.

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • center_frequency (number) – Frequency in Hz at which the magnitude response will be 0 (\(-\infty\) dB).

  • quality (number) – The quality characterizes notch filter -3 dB bandwidth relative to its center frequency (both in Hz), i.e, quality = center_frequency/bandwidth.

  • sampling_rate (None, number) – The sampling rate in Hz. Only required if signal is None. The default is None.

Returns:

output – The function returns a filtered version of the input signal if sampling_rate = None or the filter itself if signal = None.

Return type:

Signal, FilterIIR

References

pyfar.dsp.filter.reconstructing_fractional_octave_bands(signal, num_fractions=1, frequency_range=(63, 16000), overlap=1, slope=0, n_samples=4096, sampling_rate=None)[source]#

Create and/or apply an amplitude preserving fractional octave filter bank.

Note

This filter bank has -6 dB cut-off frequencies. For sufficient lengths of 'n_samples', the summed output of the filter bank equals the input signal, i.e., the filter bank is amplitude preserving (reconstructing). This is useful for analysis and synthesis applications such as room acoustical simulations. For an energy preserving filter bank with -3 dB cut-off frequencies see fractional_octave_bands.

The filters have a linear phase with a delay of n_samples/2 and are windowed with a Hanning window to suppress side lobes of the finite filters. The magnitude response of the filters is designed similar to [13] with two exceptions:

  1. The magnitude response is designed using squared sine/cosine ramps to obtain -6 dB at the cut-off frequencies.

  2. The overlap between the filters is calculated between the center and upper cut-off frequencies and not between the center and lower cut-off frequencies. This enables smaller pass-bands with unity gain, which might be advantageous for applications that apply analysis and resynthesis.

Parameters:
  • signal (Signal, None) – The Signal to be filtered. Pass None to create the filter without applying it.

  • num_fractions (int, optional) – Octave fraction, e.g., 3 for third-octave bands. The default is 1.

  • frequency_range (tuple, optional) – Frequency range for fractional octave in Hz. The default is (63, 16000)

  • overlap (float) – Band overlap of the filter slopes between 0 and 1. Smaller values yield wider pass-bands and steeper filter slopes. The default is 1.

  • slope (int, optional) – Number > 0 that defines the width and steepness of the filter slopes. Larger values yield wider pass-bands and steeper filter slopes. The default is 0.

  • n_samples (int, optional) – Length of the filter in samples. Longer filters yield more exact filters. The default is 2**12.

  • sampling_rate (int) – Sampling frequency in Hz. The default is None. Only required if signal=None.

Returns:

  • signal (Signal) – The filtered signal. Only returned if sampling_rate = None.

  • filter (FilterFIR) – FIR Filter object. Only returned if signal = None.

  • frequencies (np.ndarray) – Center frequencies of the filters.

References

Examples

Filter and re-synthesize an impulse signal.

>>> import pyfar as pf
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> # generate data
>>> x = pf.signals.impulse(2**12)
>>> y, f = pf.dsp.filter.reconstructing_fractional_octave_bands(x)
>>> y_sum = pf.Signal(np.sum(y.time, 0), y.sampling_rate)
>>> # time domain plot
>>> ax = pf.plot.time_freq(y_sum, color='k', unit='ms')
>>> pf.plot.time(x, ax=ax[0], unit='ms')
>>> ax[0].set_xlim(-20, 250)
>>> ax[0].set_title("Original (blue) and reconstructed pulse (black)")
>>> # frequency domain plot
>>> pf.plot.freq(y_sum, color='k', ax=ax[1])
>>> pf.plot.freq(y, ax=ax[1])
>>> ax[1].set_title(
...     "Reconstructed (black) and filtered impulse (colored)")

(Source code, png, hires.png, pdf)

../_images/pyfar-dsp-filter-5.png