Skip to content

Butterworth

openseize.filtering.iir.Butter

Bases: IIR

A callable digital Butterworth IIR filter.

This IIR filter meets both the pass and stop band attenuation criteria and is maximally flat in the pass band (no ripple). This lack of pass band ripple comes at the cost of slower roll-off compared with Chebyshev and Elliptical filters meaning a higher order will be required to meet a particular stop band specification.

Attributes:

Name Type Description

see IIR Base for attributes

Examples:

>>> # design a low pass filter with a max ripple of 1 dB and minimum
... # attenuation of 40 dB
>>> butter = Butter(fpass=300, fstop=350, fs=5000, gpass=1,
...                 gstop=40)
>>> butter.btype
'lowpass'
>>> butter = Butter(fpass=600, fstop=400, fs=1800, gpass=0.5,
...                 gstop=40)
>>> butter.btype
'highpass'
>>> butter = Butter(fpass=[400, 1000], fstop=[200, 1200], fs=4000)
>>> butter.btype
'bandpass'
>>> butter = Butter(fpass=[200, 1200], fstop=[400, 1000], fs=5000)
>>> butter.btype
'bandstop'
Source code in openseize/filtering/iir.py
class Butter(IIR):
    """A callable digital Butterworth IIR filter.

    This IIR filter meets both the pass and stop band attenuation criteria
    and is maximally flat in the pass band (no ripple). This lack of pass
    band ripple comes at the cost of slower roll-off compared with Chebyshev
    and Elliptical filters meaning a higher order will be required to meet
    a particular stop band specification.

    Attributes:
        : see IIR Base for attributes

    Examples:
        >>> # design a low pass filter with a max ripple of 1 dB and minimum
        ... # attenuation of 40 dB
        >>> butter = Butter(fpass=300, fstop=350, fs=5000, gpass=1,
        ...                 gstop=40)
        >>> butter.btype
        'lowpass'
        >>> butter = Butter(fpass=600, fstop=400, fs=1800, gpass=0.5,
        ...                 gstop=40)
        >>> butter.btype
        'highpass'
        >>> butter = Butter(fpass=[400, 1000], fstop=[200, 1200], fs=4000)
        >>> butter.btype
        'bandpass'
        >>> butter = Butter(fpass=[200, 1200], fstop=[400, 1000], fs=5000)
        >>> butter.btype
        'bandstop'
    """

    def __init__(self,
                 fpass: Union[float, Tuple[float, float]],
                 fstop: Union[float, Tuple[float, float]],
                 fs: int,
                 gpass: float = 1.0,
                 gstop: float = 40.0,
                 fmt: str = 'sos'
    ) -> None:
        """Initialize this Butterworth IIR filter.

        Args:
            fpass:
                The pass band edge frequency in the same units as fs OR
                a 2-el sequence of edge frequencies that are monotonically
                increasing and in [0, fs/2].
            fstop:
                The stop band edge frequency in the same units as fs OR
                a 2-el sequence of edge frequencies that are monotonically
                increasing and in [0, fs/2].
            fs:
                The sampling rate of the digital system.
            gpass:
                The maximum allowable ripple in the pass band in dB.
                Default of 1.0 dB is ~ 11% amplitude ripple.
            gstop:
                The minimum attenuation required in the stop band in dB.
                Default of 40 dB is a 99% amplitude attenuation.
            fmt:
                A scipy filter format specification. Must be one of:

                - 'sos': The second-order section cascade format. This
                  format is recommended as it is more stable than 'ba'.
                - 'ba': Transfer function format. This format is less stable
                  but requires fewer computations compared with 'sos'.
                - 'zpk': This format is not used and will be converted to
                  'sos'.
        """

        super().__init__(fpass, fstop, gpass, gstop, fs, fmt)

    @property
    def order(self):
        """Returns the minimum order and 3 dB point of this filter."""

        return sps.buttord(self.fpass, self.fstop, self.gpass, self.gstop,
                             fs=self.fs)

__init__(fpass, fstop, fs, gpass=1.0, gstop=40.0, fmt='sos')

Initialize this Butterworth IIR filter.

Parameters:

Name Type Description Default
fpass Union[float, Tuple[float, float]]

The pass band edge frequency in the same units as fs OR a 2-el sequence of edge frequencies that are monotonically increasing and in [0, fs/2].

required
fstop Union[float, Tuple[float, float]]

The stop band edge frequency in the same units as fs OR a 2-el sequence of edge frequencies that are monotonically increasing and in [0, fs/2].

required
fs int

The sampling rate of the digital system.

required
gpass float

The maximum allowable ripple in the pass band in dB. Default of 1.0 dB is ~ 11% amplitude ripple.

1.0
gstop float

The minimum attenuation required in the stop band in dB. Default of 40 dB is a 99% amplitude attenuation.

40.0
fmt str

A scipy filter format specification. Must be one of:

  • 'sos': The second-order section cascade format. This format is recommended as it is more stable than 'ba'.
  • 'ba': Transfer function format. This format is less stable but requires fewer computations compared with 'sos'.
  • 'zpk': This format is not used and will be converted to 'sos'.
'sos'
Source code in openseize/filtering/iir.py
def __init__(self,
             fpass: Union[float, Tuple[float, float]],
             fstop: Union[float, Tuple[float, float]],
             fs: int,
             gpass: float = 1.0,
             gstop: float = 40.0,
             fmt: str = 'sos'
) -> None:
    """Initialize this Butterworth IIR filter.

    Args:
        fpass:
            The pass band edge frequency in the same units as fs OR
            a 2-el sequence of edge frequencies that are monotonically
            increasing and in [0, fs/2].
        fstop:
            The stop band edge frequency in the same units as fs OR
            a 2-el sequence of edge frequencies that are monotonically
            increasing and in [0, fs/2].
        fs:
            The sampling rate of the digital system.
        gpass:
            The maximum allowable ripple in the pass band in dB.
            Default of 1.0 dB is ~ 11% amplitude ripple.
        gstop:
            The minimum attenuation required in the stop band in dB.
            Default of 40 dB is a 99% amplitude attenuation.
        fmt:
            A scipy filter format specification. Must be one of:

            - 'sos': The second-order section cascade format. This
              format is recommended as it is more stable than 'ba'.
            - 'ba': Transfer function format. This format is less stable
              but requires fewer computations compared with 'sos'.
            - 'zpk': This format is not used and will be converted to
              'sos'.
    """

    super().__init__(fpass, fstop, gpass, gstop, fs, fmt)

order() property

Returns the minimum order and 3 dB point of this filter.

Source code in openseize/filtering/iir.py
@property
def order(self):
    """Returns the minimum order and 3 dB point of this filter."""

    return sps.buttord(self.fpass, self.fstop, self.gpass, self.gstop,
                         fs=self.fs)

Bases and Mixins

IIR Base

Bases: abc.ABC, IIRViewer, mixins.ViewInstance

Base class for infinite impulse response filters.

Attributes:

Name Type Description
fpass np.ndarray

1-D numpy array of start and stop edge frequencies of this filter's passband(s).

fstop np.ndarray

1-D numpy array of start and stop edge frequencies of this filter's stopband(s).

gpass float

Maximum ripple in the passband(s) in dB.

gstop float

Minimum attenuation in the stopbands in dB.

fs int

The sampling rate of the digital system.

fmt

A scipy filter coeffecient format specification. Must be one of:

  • 'sos': The second-order section cascade format. This format is recommended as it is more stable than 'ba'.
  • 'ba': Transfer function format. This format is less stable but requires fewer computations compared with 'sos'.
  • 'zpk': This format is not used and will be converted to 'sos'.
nyq float

The nyquist rate of the digital system, fs/2.

coeffs np.ndarray

A numpy array of filter coeffecients.

Notes

This IIR ABC defines the common and expected methods of all concrete IIR filters in the openseize.filtering.iir module. Inheritors must override abstract methods and properties of this base to be instantiable.

btype() property

Returns the string band type of this IIR filter.

ftype() property

Returns the string name of this IIR filter.

__call__(data, chunksize, axis=-1, dephase=True, zi=None, **kwargs)

Apply this filter to an ndarray or producer of ndarrays.

Parameters:

Name Type Description Default
data Union[Producer, np.ndarray]

The data to be filtered.

required
chunksize int

The number of samples to hold in memory during filtering.

required
axis int

The axis of data along which to apply the filter. If data is multidimensional, the filter will be independently applied along all slices of axis.

-1
dephase bool

Removes the delay introduced by this filter by running the filter in the forward and reverse directions of data's samples.

True
zi Optional[np.ndarray]

Initial conditions for this filter. The shape depends on the fmt attribute. For 'sos' format, zi has shape nsections x (...,2,...) where (...,2,...) has the same shape as data but with 2 along axis. For more information see lfilter_zi and sosfilt_zi in scipy's signal module. This argument is ignored if dephase is True.

None
kwargs

Keyword arguments are passed to the producer constructor.

{}

Returns:

Type Description
Union[Producer, np.ndarray]

Filtered result with type matching input 'data' parameter.

Viewer Mixin

A collection of common plotting methods for both IIR, FIR and Parks-McClellan filters.

All filters in openseize have the ability to plot their impulse response and frequency response to a matplotlib figure called the Viewer. This mixin is inherited by specific IIR, FIR and ParksMcClellan Viewers in this file. Each of these specific viewers is inherited by the corresponding filter type (i.e. IIR, FIR, ParksMcClellan) in the openseize filtering module.

plot(size=(8, 6), gridalpha=0.3, worN=2048, rope=-100, axarr=None, show=True)

Plots the impulse and frequency response of this filter.

Parameters:

Name Type Description Default
size Tuple[int, int]

tuple The figure size to display for the plots. Default is 8 x 6.

(8, 6)
gridalpha float

float in [0, 1] The alpha transparency of each subplots grid. Default is 0.3

0.3
worN int

int The number of frequencies to compute the gain and phase responses over. Default is 2048 frequencies.

2048
rope float

float For plotting, all values below this region of practical equivalence will be set to this value. Default is -100 dB. Any filter response smaller than this will be set to -100 for plotting.

-100
axarr Optional[Sequence[plt.Axes]]

A Matplotlib axis array. An optional axis array to plot the impulse and frequency responses to. Default None means a new axis is created.

None