Skip to content

Hann

openseize.filtering.fir.Hann

Bases: FIR

A callable type I FIR using a Hann window.

The Hann window has higher side lobe heights than the Hamming window but a faster roll-off. Thus, this filter has higher ripple than the Hamming but it attenuates faster. It is a good general purpose window with strong attenuation and fast roll-off.

Attributes:

Name Type Description

see FIR Base for attributes

Window Characteristics
  • main lobe width (MLW) = 8 pi / len(taps)
  • side lobe height (SLH) = -31.5 dB
  • side lobe roll-off rate (SLRR) = -18 dB/octave
  • approximate peak error (APE) = -44 dB

Examples:

>>> hann = Hann(fpass=300, fstop=350, fs=5000)
>>> hann.btype
'lowpass'
>>> hann = Hann(fpass=600, fstop=400, fs=1800)
>>> hann.btype
'highpass'
>>> hann = Hann(fpass=[400, 1000], fstop=[200, 1200], fs=4000)
>>> hann.btype
'bandpass'
>>> hann = Hann(fpass=[200, 1200], fstop=[400, 1000], fs=5000)
>>> hann.btype
'bandstop'
Source code in openseize/filtering/fir.py
class Hann(FIR):
    """A callable type I FIR using a Hann window.

    The Hann window has higher side lobe heights than the Hamming window but
    a faster roll-off. Thus, this filter has higher ripple than the Hamming
    but it attenuates faster. It is a good general purpose window with
    strong attenuation and fast roll-off.

    Attributes:
        :see FIR Base for attributes

    Window Characteristics:
        - main lobe width (MLW) = 8 pi / len(taps)
        - side lobe height (SLH) = -31.5 dB
        - side lobe roll-off rate (SLRR) = -18 dB/octave
        - approximate peak error (APE) = -44 dB

    Examples:
        >>> hann = Hann(fpass=300, fstop=350, fs=5000)
        >>> hann.btype
        'lowpass'
        >>> hann = Hann(fpass=600, fstop=400, fs=1800)
        >>> hann.btype
        'highpass'
        >>> hann = Hann(fpass=[400, 1000], fstop=[200, 1200], fs=4000)
        >>> hann.btype
        'bandpass'
        >>> hann = Hann(fpass=[200, 1200], fstop=[400, 1000], fs=5000)
        >>> hann.btype
        'bandstop'
    """

    def __init__(self,
                 fpass: Union[float, Tuple[float, float]],
                 fstop: Union[float, Tuple[float, float]],
                 fs: int
    ) -> None:
        """Initialize this Hann windowed FIR.

        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.
        """

        # for plotting, provide a gpass calculated from the peak error
        peak_err = -44
        gpass = -20 * np.log10(1 - 10 ** (peak_err / 20))
        super().__init__(fpass, fstop, gpass=gpass, gstop=peak_err, fs=fs)

    @property
    def numtaps(self):
        """Return the number of taps to meet the transition width."""

        ntaps = int(8 / (self.width / self.nyq))
        # odd tap number to ensure group delay is integer samples
        return ntaps + 1 if ntaps % 2 == 0 else ntaps

__init__(fpass, fstop, fs)

Initialize this Hann windowed FIR.

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
Source code in openseize/filtering/fir.py
def __init__(self,
             fpass: Union[float, Tuple[float, float]],
             fstop: Union[float, Tuple[float, float]],
             fs: int
) -> None:
    """Initialize this Hann windowed FIR.

    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.
    """

    # for plotting, provide a gpass calculated from the peak error
    peak_err = -44
    gpass = -20 * np.log10(1 - 10 ** (peak_err / 20))
    super().__init__(fpass, fstop, gpass=gpass, gstop=peak_err, fs=fs)

numtaps() property

Return the number of taps to meet the transition width.

Source code in openseize/filtering/fir.py
@property
def numtaps(self):
    """Return the number of taps to meet the transition width."""

    ntaps = int(8 / (self.width / self.nyq))
    # odd tap number to ensure group delay is integer samples
    return ntaps + 1 if ntaps % 2 == 0 else ntaps

Bases and Mixins

FIR Base

Bases: abc.ABC, mixins.ViewInstance, FIRViewer

Base class for finite 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.

nyq float

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

width float

The minimum transition width between the pass and stopbands.

coeffs np.ndarray

A 1-D numpy array of filter coeffecients.

Notes

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

btype() property

Returns the string band type of this filter.

ftype() property

Returns the string name of this FIR filter.

pass_attenuation() property

Converts the max passband ripple, gpass, into a pass band attenuation in dB.

cutoff() property

Returns an ndarray of the -6 dB points of each transition band.

__call__(data, chunksize, axis=-1, mode='same', **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
mode str

A numpy convolve mode; one of 'full', 'same', 'valid'.

  • Full: This mode includes all points of the convolution of the filter window and data. This mode does not compensate for the delay introduced by the filter.
  • Same: This mode (Default) returns data of the same size as the input. This mode adjust for the delay introduced by the filter.
  • Valid: This mode returns values only when the filter and data completely overlap. The result using this mode is to shift the data (num_taps - 1) / 2 samples to the left of the input data.
'same'
kwargs

Any valid keyword argument for 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