Classes (dsptoolbox.classes)¶
The main classes are listed here. For some filterbanks, special classes are used but the api works almost equally as for the main FilterBank class.
Signal¶
Signal class
- class dsptoolbox.classes.signal.Signal(path: str | None = None, time_data=None, sampling_rate_hz: int | None = None, constrain_amplitude: bool = False, activate_cache: bool = False)¶
Bases:
MultichannelDataClass for general signals (time series). Most of the methods and supported computations are focused on audio signals, but some features might be generalizable to all kinds of time series. It is assumed that audio is always represented in floating point type.
- Attributes:
amplitude_scale_factorThis is the scaling factor (multiplied) when the amplitude is automatically constrained to the range [-1., 1.].
calibrated_signalWhen True, this signal has been (amplitude) calibrated, so that it represents sound pressure in Pa.
constrain_amplitudeWhen True, the amplitude of the signal is always constrained to the [-1., 1.] range.
is_complex_signalWhen True, this signal contains an imaginary part.
length_samplesGet the number of samples in the signal.
length_secondsGet the duration of the signal in seconds.
metadataReturn dictionary with metadata about the signal.
metadata_strGenerate string with metadata about the signal.
- number_of_channels
sampling_rate_hzGet the sampling rate in Hz.
spectrum_methodGet the spectrum computation method.
spectrum_scalingGet the spectrum scaling method.
spectrum_smoothingGet the spectrum smoothing parameter in fraction of octaves.
time_dataGet the time domain signal data.
time_data_imaginaryImaginary part of the time data saved as np.float64.
time_vector_sCorresponding time vector for the signal.
Methods
add_channel([path, new_time_data, ...])Adds new channels to this signal object.
Deletes the time window of the signal in case there is any.
copy()Returns a copy of the object.
copy_with_new_time_data(new_time_data)Copy all attributes of the signal but with new time data.
from_file(path)Create a signal from a path to a wav or flac audio file.
from_time_data(time_data, sampling_rate_hz)Create a signal from an array of PCM samples.
get_channels(channels)Returns a signal object with the selected channels.
get_csm([force_computation])Get Cross spectral matrix for all channels with the shape (frequencies, channels, channels).
get_spectrogram([force_computation])Returns a matrix containing the STFT of a specific channel.
get_spectrum([force_computation])Returns spectrum according to the stored parameters.
plot_csm([range_hz, with_phase])Plots the cross spectral matrix of the multichannel signal.
plot_group_delay([range_hz, smoothing, ...])Plots group delay of each channel.
plot_magnitude([range_hz, normalize, ...])Plots magnitude spectrum.
plot_phase([range_hz, unwrap, smoothing, ...])Plots phase of the frequency response, only available if the method for the spectrum is FFT.
plot_spectrogram([channel_number, ...])Plots STFT matrix of the given channel.
plot_spl([normalize_at_peak, ...])Plots the momentary sound pressure level (dB or dBFS) of each channel.
Plots time signals.
remove_channel([channel_number])Removes a channel.
save_signal(path[, mode, bit_depth])Saves the Signal object as wav, flac or pickle.
set_spectrogram_parameters([...])Sets all necessary parameters for the computation of the spectrogram.
set_spectrum_parameters([method, smoothing, ...])Sets all necessary parameters for the computation of the spectrum.
Prints all the signal information to the console.
sum_channels()Return a copy of the signal where all channels are summed into one.
swap_channels(new_order)Rearranges the channels (inplace) in the new given order.
- __init__(path: str | None = None, time_data=None, sampling_rate_hz: int | None = None, constrain_amplitude: bool = False, activate_cache: bool = False)¶
Signal class that saves time data, channel and sampling rate information as well as spectrum, cross-spectral matrix and more.
- Parameters:
- pathstr, optional
A path to audio files. Reading is done with the soundfile library. Wave and Flac audio files are accepted. Default: None.
- time_dataarray-like, NDArray[np.float64], optional
Time data of the signal. It is saved as a matrix with the form (time samples, channel number). Default: None.
- sampling_rate_hzint, optional
Sampling rate of the signal in Hz. Default: None.
- constrain_amplitudebool, optional
When True, audio is normalized to 0 dBFS peak level in case that there are amplitude values greater than 1. Otherwise, there is no normalization and the audio data is not constrained to [-1, 1]. A warning is always shown when audio gets normalized and the used normalization factor is saved as amplitude_scale_factor. Default: False.
- activate_cachebool, optional
When True, spectra, CSM and STFT will be cached. They will not be computed again if no parameters have changed. Set to False to avoid caching altogether. Default: False.
- add_channel(path: str | None = None, new_time_data: ndarray[tuple[Any, ...], dtype[float64]] | None = None, sampling_rate_hz: int | None = None, allow_padding_trimming: bool = True) Self¶
Adds new channels to this signal object.
- Parameters:
- pathstr, optional
Path to the file containing new channel information.
- new_time_dataNDArray[np.float64], optional
np.array with new channel data.
- sampling_rate_hzint, optional
Sampling rate for the new data
- allow_padding_trimmingbool, optional
Activates padding or trimming at the end of signal in case the new data does not match previous data. Default: True.
- Returns:
- self
- property amplitude_scale_factor: float¶
This is the scaling factor (multiplied) when the amplitude is automatically constrained to the range [-1., 1.].
This factor is computed by checking peak amplitude of the real and imaginary parts of the time signal independently. The largest peak value is then used as the normalization factor for both.
- property calibrated_signal: bool¶
When True, this signal has been (amplitude) calibrated, so that it represents sound pressure in Pa.
- property constrain_amplitude: bool¶
When True, the amplitude of the signal is always constrained to the [-1., 1.] range. It will be automatically scaled if it surpasses these values so that peak values are either -1. or 1. Use False to avoid any amplitude scaling.
If this is triggered, the scaling factor is also saved in the signal.
- copy_with_new_time_data(new_time_data: ArrayLike) Signal¶
Copy all attributes of the signal but with new time data.
- Parameters:
- new_time_dataArrayLike
New valid time data.
- Returns:
- Signal
Signal with new time data
Notes
This signal object will own the time data alone, so when passing an array, it is checked whether its memory belongs to another array or not. If so, a copy is made.
- static from_file(path: str)¶
Create a signal from a path to a wav or flac audio file.
- Parameters:
- pathstr
Path to file.
- Returns:
- Signal
- static from_time_data(time_data: ndarray[tuple[Any, ...], dtype[float64]], sampling_rate_hz: int, constrain_amplitude: bool = True)¶
Create a signal from an array of PCM samples.
- Parameters:
- time_dataarray-like, NDArray[np.float64]
Time data of the signal. It is saved as a matrix with the form (time samples, channel number).
- sampling_rate_hzint
Sampling rate of the signal in Hz.
- constrain_amplitudebool, optional
When True, audio is normalized to 0 dBFS peak level in case that there are amplitude values greater than 1. Otherwise, there is no normalization and the audio data is not constrained to [-1, 1]. A warning is always shown when audio gets normalized and the used normalization factor is saved as amplitude_scale_factor. Default: True.
- Returns:
- Signal
- get_csm(force_computation=False) tuple[ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]]]¶
Get Cross spectral matrix for all channels with the shape (frequencies, channels, channels). It uses the parameters stored in set_spectrum_parameters.
- Parameters:
- force_computationbool, optional
When True, computation is forced even if there is cached data. Default: False.
- Returns:
- f_csmNDArray[np.float64]
Frequency vector.
- csmNDArray[np.float64]
Cross spectral matrix with shape (frequency, channels, channels).
- get_spectrogram(force_computation: bool = False) tuple[ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[complex128]]]¶
Returns a matrix containing the STFT of a specific channel.
- Parameters:
- force_computationbool, optional
Forces new computation of the STFT. Default: False.
- Returns:
- t_sNDArray[np.float64]
Time vector.
- f_hzNDArray[np.float64]
Frequency vector.
- spectrogramNDArray[np.complex128]
Complex spectrogram with shape (frequency, time, channel).
- get_spectrum(force_computation=False) tuple[ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[complex128 | float64]]]¶
Returns spectrum according to the stored parameters.
- Parameters:
- force_computationbool, optional
Forces spectrum computation.
- Returns:
- spectrum_freqsNDArray[np.float64]
Frequency vector.
- spectrumNDArray[np.complex128 | np.float64]
Spectrum matrix for each channel.
- property length_samples: int¶
Get the number of samples in the signal.
- Returns:
- int
Number of time samples.
- property length_seconds: float¶
Get the duration of the signal in seconds.
- Returns:
- float
Signal duration in seconds.
- plot_csm(range_hz=[20, 20000.0], with_phase: bool = True) tuple[Figure, Axes]¶
Plots the cross spectral matrix of the multichannel signal.
- Parameters:
- range_hzarray-like with length 2, optional
Range of Hz to be showed. Default: [20, 20e3].
- with_phasebool, optional
When True, the unwrapped phase is also plotted. Default: True.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_group_delay(range_hz: list[float] | None = [20.0, 20000.0], smoothing: int = 0, remove_ir_latency: str | ArrayLike | None = None) tuple[Figure, Axes]¶
Plots group delay of each channel.
- Parameters:
- range_hzarray-like with length 2, None, optional
Range of frequencies for which to show group delay. Pass None to avoid any specific range. Default: [20, 20e3].
- smoothingint, optional
When different than 0, smoothing is applied to the group delay along the (1/smoothing) octave band. This only affects the values in the plot. Default: 0.
- remove_ir_latencystr {“peak”, “min_phase”}, ArrayLike, None, optional
If the signal is an impulse response, the delay of the impulse can be removed. IR delay removal options are:
str {“peak” or “min_phase”}: By regarding its delay in relation to the minimum-phase equivalent or its peak in the time signal.
ArrayLike: Delay in samples to remove from each channel.
None: no latency removal.
Default: None.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_magnitude(range_hz: list[float] | None = [20.0, 20000.0], normalize: MagnitudeNormalization = MagnitudeNormalization.NoNormalization, range_db=None, smoothing: int = 0, show_info_box: bool = False) tuple[Figure, Axes]¶
Plots magnitude spectrum. Change parameters of spectrum with set_spectrum_parameters.
- Parameters:
- range_hzarray-like with length 2, None, optional
Range for which to plot the magnitude response. Use None to avoid setting any specific range. Default: [20, 20000].
- normalizeMagnitudeNormalization, optional
Mode for normalization. Default: NoNormalization.
- range_dbarray-like with length 2, optional
Range in dB for which to plot the magnitude response. Default: None.
- smoothingint, optional
Smoothing across the (1/smoothing) octave band. It only applies to the plot data and not to get_spectrum(). Default: 0 (no smoothing).
- show_info_boxbool, optional
Plots a info box regarding spectrum parameters and plot parameters. If it is str, it overwrites the standard message. Default: False.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
Notes
Smoothing is only applied on the plot data.
In case the signal has been calibrated and the time data is given in Pascal, the plotted values in dB will be scaled by p0=(20e-6 Pa)**2 when no normalization is active.
- plot_phase(range_hz: list[float] | None = [20.0, 20000.0], unwrap: bool = False, smoothing: int = 0, remove_ir_latency: str | None | ArrayLike = None) tuple[Figure, Axes]¶
Plots phase of the frequency response, only available if the method for the spectrum is FFT.
- Parameters:
- range_hzarray-like with length 2, None, optional
Range of frequencies for which to show group delay. Default: [20, 20e3].
- unwrapbool, optional
When True, the unwrapped phase is plotted. Default: False.
- smoothingint, optional
When different than 0, the phase response is smoothed across the 1/smoothing-octave band. This only applies smoothing to the plot data. Default: 0.
- remove_ir_latencystr {“peak”, “min_phase”}, ArrayLike, None, optional
If the signal is an impulse response, the delay of the impulse can be removed. IR delay removal options are:
str {“peak” or “min_phase”}: By regarding its delay in relation to the minimum-phase equivalent or its peak in the time signal.
ArrayLike: Delay in samples to remove from each channel.
None: no latency removal.
Default: None.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_spectrogram(channel_number: int = 0, log_freqs: bool = True, dynamic_range_db: float = 50) tuple[Figure, Axes]¶
Plots STFT matrix of the given channel.
- Parameters:
- channel_numberint, optional
Selected channel to plot spectrogram. Default: 0 (first).
- logfreqsbool, optional
When True, frequency axis is plotted logarithmically. Default: True.
- dynamic_range_dbfloat, optional
This sets the dynamic range to show for the spectrogram. The plotted colormap goes from the maximum down to maximum minus dynamic range. For example, dynamic_range_db=50 plots for a peak value of 30 dB the colormap of the spectrogram between [30, -20] dB. Default: 50.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_spl(normalize_at_peak: bool = False, dynamic_range_db: float | None = 100.0, window_length_s: float = 0.0) tuple[Figure, list[Axes]]¶
Plots the momentary sound pressure level (dB or dBFS) of each channel. If the signal is calibrated and not normalized at peak, the values correspond to dB, otherwise they are dBFS.
- Parameters:
- normalize_at_peakbool, optional
When True, each channel gets normalize by its peak value. Default: False.
- dynamic_range_dbfloat, optional
This is the range in dB used for plotting. Each plot will be in the range [peak + 1 - dynamic_range_db, peak + 1]. Pass None to avoid setting any range. Default: 100.
- window_length_sfloat, optional
When different than 0, a moving average along the time axis is done with the given length. Default: 0.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axlist of matplotlib.axes.Axes
Axes.
Notes
All values are clipped to be at least -800 dBFS.
If it is an analytic signal and normalization is applied, the peak value of the real part is used as the normalization factor.
If the time window is not 0, effects at the edges of the signal might be present due to zero-padding.
- plot_time() tuple[Figure, list[Axes]]¶
Plots time signals.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axlist of matplotlib.axes.Axes
Axes.
- save_signal(path: str, mode: str = 'wav', bit_depth: int = 32)¶
Saves the Signal object as wav, flac or pickle.
- Parameters:
- pathstr
Path for the signal to be saved.
- modestr, optional
Mode of saving. Available modes are ‘wav’, ‘flac’, ‘pkl’. Default: ‘wav’.
- bit_depthint, optional
Bit depth when saving a signal in ‘wav’ or ‘flac’ format. Only 16, 24, 32 and 64 are valid. 32 and 64 are only valid for ‘wav’. Default: 32.
- set_spectrogram_parameters(window_length_samples: int = 1024, window_type: Window = Window.Hann, overlap_percent: float = 50.0, fft_length_samples: int | None = None, detrend: bool = False, padding: bool = True, scaling: SpectrumScaling = SpectrumScaling.FFTBackward) Self¶
Sets all necessary parameters for the computation of the spectrogram.
- Parameters:
- window_length_samplesint, optional
Window size. Default: 1024.
- window_typeWindow, optional
Type of window to use. Default: Hann.
- overlap_percentfloat, optional
Overlap in percent. Default: 50.
- fft_length_samplesint, optional
Length of the FFT window for each time window. This affects the frequency resolution and can also crop the time window. Pass None to use the window length. Default: None.
- detrendbool, optional
Detrending (subtracting mean) for each time frame. Default: False.
- paddingbool, optional
Padding signal in the beginning and end to center it in order to avoid losing energy because of windowing. Default: True.
- scalingSpectrumScaling, optional
Scaling of spectrum. Default: FFTBackwards.
- Returns:
- self
References
Heinzel, G., Rüdiger, A., & Schilling, R. (2002). Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new at-top windows.
- set_spectrum_parameters(method: SpectrumMethod = SpectrumMethod.WelchPeriodogram, smoothing: int = 0, pad_to_fast_length: bool = True, window_length_samples: int = 1024, window_type: Window = Window.Hann, overlap_percent: float = 50, detrend: bool = True, average: str = 'mean', scaling: SpectrumScaling = SpectrumScaling.FFTBackward) Self¶
Sets all necessary parameters for the computation of the spectrum.
- Parameters:
- methodSpectrumMethod, optional
Method to use in order to acquire the spectrum. See notes for details. Default: WelchPeriodogram.
- smoothingint, optional
Smoothing across (1/smoothing) octave bands. It will only be applied on the spectrum. Smoothes magnitude AND phase. For accesing the smoothing algorithm, refer to dsptoolbox.tools.fractional_octave_smoothing(). If smoothing is applied here, Signal.get_spectrum() returns the smoothed spectrum, but plotting ignores this parameter. Default: 0 (no smoothing).
- pad_to_fast_lengthbool, optional
When True and method=FFT, the spectrum will be zero-padded to have a length that is fast for computing the FFT. Default: True.
- window_length_samplesint, optional
Window size. Default: 1024.
- window_typeWindow, optional
Choose type of window. Default: Hann.
- overlap_percentfloat, optional
Overlap in percent. Default: 50.
- detrendbool, optional
Detrending (subtracting mean). Default: True.
- averagestr, optional
Averaging method. Choose from ‘mean’ or ‘median’. Default: ‘mean’.
- scalingSpectrumScaling, optional
Scaling of spectrum. See references for details about scaling. Default: FFTBackward.
- Returns:
- self
Notes
- On the SpectrumComputation:
FFT should be done for deterministic signals and impulse responses.
WelchPeriodogram can be applied to stochastic signals and as an averaged spectrum for non-stationary signals.
References
Heinzel, G., Rüdiger, A., & Schilling, R. (2002). Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new at-top windows.
- show_info()¶
Prints all the signal information to the console.
- property spectrum_method: SpectrumMethod¶
Get the spectrum computation method.
- Returns:
- SpectrumMethod
The method used for spectrum computation (e.g., FFT, WelchPeriodogram).
- property spectrum_scaling: SpectrumScaling¶
Get the spectrum scaling method.
- Returns:
- SpectrumScaling
The scaling method used for spectrum computation.
- property spectrum_smoothing: float¶
Get the spectrum smoothing parameter in fraction of octaves.
- Returns:
- float
Smoothing parameter. 0 means no smoothing. Positive values indicate smoothing in fractions of octaves.
- property time_data: ndarray[tuple[Any, ...], dtype[float64]]¶
Get the time domain signal data.
- Returns:
- NDArray[np.float64]
Time data as a 2D array with shape (time_samples, number_of_channels). Real part of the signal. Use time_data_imaginary for the imaginary part if it exists.
ImpulseResponse¶
- class dsptoolbox.classes.impulse_response.ImpulseResponse(path: str | None = None, time_data: ndarray[tuple[Any, ...], dtype[float64]] | None = None, sampling_rate_hz: int | None = None, constrain_amplitude: bool = True, activate_cache: bool = False)¶
Bases:
Signal- Attributes:
amplitude_scale_factorThis is the scaling factor (multiplied) when the amplitude is automatically constrained to the range [-1., 1.].
calibrated_signalWhen True, this signal has been (amplitude) calibrated, so that it represents sound pressure in Pa.
constrain_amplitudeWhen True, the amplitude of the signal is always constrained to the [-1., 1.] range.
is_complex_signalWhen True, this signal contains an imaginary part.
length_samplesGet the number of samples in the signal.
length_secondsGet the duration of the signal in seconds.
metadataReturn dictionary with metadata about the signal.
metadata_strGenerate string with metadata about the signal.
- number_of_channels
sampling_rate_hzGet the sampling rate in Hz.
spectrum_methodGet the spectrum computation method.
spectrum_scalingGet the spectrum scaling method.
spectrum_smoothingGet the spectrum smoothing parameter in fraction of octaves.
time_dataGet the time domain signal data.
time_data_imaginaryImaginary part of the time data saved as np.float64.
time_vector_sCorresponding time vector for the signal.
Methods
add_channel([path, new_time_data, ...])Adds new channels to this signal object.
clear_time_window()Deletes the time window of the signal in case there is any.
copy()Returns a copy of the object.
copy_with_new_time_data(new_time_data)Copy all attributes of the signal but with new time data.
from_file(path)Create an impulse response from a path to a wav or flac audio file.
from_signal(signal)Create an impulse response from a signal.
from_time_data(time_data, sampling_rate_hz)Create an impulse response from an array of PCM samples.
get_channels(channels)Returns a signal object with the selected channels.
get_csm([force_computation])Get Cross spectral matrix for all channels with the shape (frequencies, channels, channels).
get_spectrogram([force_computation])Returns a matrix containing the STFT of a specific channel.
get_spectrum([force_computation])Returns spectrum according to the stored parameters.
plot_bode([range_hz, normalize, range_db, ...])Create a bode plot where magnitude and phase response are plotted together.
plot_csm([range_hz, with_phase])Plots the cross spectral matrix of the multichannel signal.
plot_group_delay([range_hz, smoothing, ...])Plots group delay of each channel.
plot_magnitude([range_hz, normalize, ...])Plots magnitude spectrum.
plot_phase([range_hz, unwrap, smoothing, ...])Plots phase of the frequency response, only available if the method for the spectrum is FFT.
plot_spectrogram([channel_number, ...])Plots STFT matrix of the given channel.
plot_spl([normalize_at_peak, ...])Plots the momentary sound pressure level (dB or dBFS) of each channel.
Plots time signals.
remove_channel([channel_number])Removes a channel.
save_signal(path[, mode, bit_depth])Saves the Signal object as wav, flac or pickle.
set_spectrogram_parameters([...])Sets all necessary parameters for the computation of the spectrogram.
set_spectrum_parameters([method, smoothing, ...])Sets all necessary parameters for the computation of the spectrum.
set_window(window)Sets the window used for the IR.
show_info()Prints all the signal information to the console.
sum_channels()Return a copy of the signal where all channels are summed into one.
swap_channels(new_order)Rearranges the channels (inplace) in the new given order.
- __init__(path: str | None = None, time_data: ndarray[tuple[Any, ...], dtype[float64]] | None = None, sampling_rate_hz: int | None = None, constrain_amplitude: bool = True, activate_cache: bool = False)¶
Instantiate impulse response.
- Parameters:
- pathstr, optional
A path to audio files. Reading is done with the soundfile library. Wave and Flac audio files are accepted. Default: None.
- time_dataarray-like, NDArray[np.float64], optional
Time data of the signal. It is saved as a matrix with the form (time samples, channel number). Default: None.
- sampling_rate_hzint, optional
Sampling rate of the signal in Hz. Default: None.
- constrain_amplitudebool, optional
When True, audio is normalized to 0 dBFS peak level in case that there are amplitude values greater than 1. Otherwise, there is no normalization and the audio data is not constrained to [-1, 1]. A warning is always shown when audio gets normalized and the used normalization factor is saved as amplitude_scale_factor. Default: True.
- activate_cachebool, optional
When True, spectra, CSM and STFT will be cached. They will not be computed again if no parameters have changed. Set to False to avoid caching altogether. Default: False.
- Returns:
- ImpulseResponse
- copy_with_new_time_data(new_time_data: ArrayLike) ImpulseResponse¶
Copy all attributes of the signal but with new time data.
- Parameters:
- new_time_dataArrayLike
New valid time data.
- Returns:
- Signal
Signal with new time data
Notes
This signal object will own the time data alone, so when passing an array, it is checked whether its memory belongs to another array or not. If so, a copy is made.
- static from_file(path: str)¶
Create an impulse response from a path to a wav or flac audio file.
- Parameters:
- pathstr
Path to file.
- Returns:
- ImpulseResponse
- static from_signal(signal: Signal)¶
Create an impulse response from a signal.
- Parameters:
- signalSignal
- Returns:
- ImpulseResponse
- static from_time_data(time_data: ndarray[tuple[Any, ...], dtype[float64]], sampling_rate_hz: int, constrain_amplitude: bool = True)¶
Create an impulse response from an array of PCM samples.
- Parameters:
- time_dataarray-like, NDArray[np.float64], optional
Time data of the signal. It is saved as a matrix with the form (time samples, channel number). Default: None.
- sampling_rate_hzint, optional
Sampling rate of the signal in Hz. Default: None.
- constrain_amplitudebool, optional
When True, audio is normalized to 0 dBFS peak level in case that there are amplitude values greater than 1. Otherwise, there is no normalization and the audio data is not constrained to [-1, 1]. A warning is always shown when audio gets normalized and the used normalization factor is saved as amplitude_scale_factor. Default: True.
- Returns:
- ImpulseResponse
- plot_bode(range_hz=[20, 20000.0], normalize: MagnitudeNormalization = MagnitudeNormalization.NoNormalization, range_db=None, show_group_delay: bool = False, range_rad_s=None, smoothing: int = 0, remove_ir_latency: str | None | ArrayLike = None) tuple[Figure, list[Axes]]¶
Create a bode plot where magnitude and phase response are plotted together.
- Parameters:
- range_hzarray-like with length 2, optional
Range for which to plot the magnitude response. Default: [20, 20000].
- normalizeMagnitudeNormalization, optional
Mode for normalization. Default: NoNormalization.
- range_dbarray-like with length 2, optional
Range in dB for which to plot the magnitude response. Default: None.
- show_group_delaybool, optional
When True, the group delay is shown instead of the phase response. It is computed with the numerical derivative of the phase response. Default: False.
- range_sarray-like with length 2, optional
Range for plotting the group delay or phase response. Default: None.
- smoothingint, optional
Smoothing across the (1/smoothing) octave band. It only applies to the plot data and not to get_spectrum(). It is applied to both magnitude and phase/group delay response. Default: 0 (no smoothing).
- remove_ir_latencystr {“peak”, “min_phase”}, ArrayLike, None, optional
If the signal is an impulse response, the delay of the impulse can be removed. IR delay removal options are:
str {“peak” or “min_phase”}: By regarding its delay in relation to the minimum-phase equivalent or its peak in the time signal.
ArrayLike: Delay in samples to remove from each channel.
None: no latency removal.
Default: None.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axlist of matplotlib.axes.Axes
List containing the two axes of the plot.
- plot_spl(normalize_at_peak: bool = False, dynamic_range_db: float | None = 100.0, window_length_s: float = 0.0) tuple[Figure, list[Axes]]¶
Plots the momentary sound pressure level (dB or dBFS) of each channel. If the signal is calibrated and not normalized at peak, the values correspond to dB, otherwise they are dBFS.
- Parameters:
- normalize_at_peakbool, optional
When True, each channel gets normalize by its peak value. Default: False.
- dynamic_range_dbfloat, optional
This is the range in dB used for plotting. Each plot will be in the range [peak + 1 - dynamic_range_db, peak + 1]. Pass None to avoid setting any range. Default: 100.
- window_length_sfloat, optional
When different than 0, a moving average along the time axis is done with the given length. Default: 0.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axlist of matplotlib.axes.Axes
Axes.
Notes
All values are clipped to be at least -800 dBFS.
If it is an analytic signal and normalization is applied, the peak value of the real part is used as the normalization factor.
If the time window is not 0, effects at the edges of the signal might be present due to zero-padding.
MultiBandSignal¶
- class dsptoolbox.classes.multibandsignal.MultiBandSignal(bands: list | None = None, same_sampling_rate: bool = True, info: dict | None = None)¶
Bases:
objectThe MultiBandSignal class contains multiple Signal objects which are to be interpreted as frequency bands of the same signal. Since every signal has also multiple channels, the object resembles somewhat a 3D-Matrix representation of a signal.
The MultiBandSignal can be multirate system if the attribute same_sampling_rate is set to False. A dictionary called info can also carry all kinds of metadata that might characterize the signals.
- Attributes:
bandsGet the list of signal bands.
is_complex_signalCheck if the signal has complex (imaginary) time data.
length_samplesGet the number of samples in each band.
length_secondsGet the duration of the signal in seconds.
metadataGet a dictionary with metadata about the multibandsignal.
metadata_strGet a formatted string representation of the metadata.
number_of_bandsGet the number of bands in the MultiBandSignal.
number_of_channelsGet the number of channels in each band.
same_sampling_rateGet whether all bands share the same sampling rate.
sampling_rate_hzGet the sampling rate(s) in Hz.
Methods
add_band(sig[, index])Adds a new band to the MultiBandSignal.
collapse()Collapses MultiBandSignal by summing all of its bands and returning one Signal (possibly multichannel).
copy()Returns a copy of the object.
get_all_bands([channel])Broadcasts and returns the MultiBandSignal as a Signal object with all bands as channels in the output.
Get all time data saved in the MultiBandSignal.
remove_band([index, return_band])Removes a band from the MultiBandSignal.
save_signal(path)Saves the MultiBandSignal object as a pickle.
Show information about the MultiBandSignal.
swap_bands(new_order)Rearranges the bands in the new given order.
- __init__(bands: list | None = None, same_sampling_rate: bool = True, info: dict | None = None)¶
MultiBandSignal contains a composite band list where each index is a Signal object with the same number of channels. For multirate systems, the parameter same_sampling_rate has to be set to False.
- Parameters:
- bandslist, optional
List or tuple containing different Signal objects. All of them should be associated to the same Signal. This means that the channel numbers have to match. Set to None for initializing the object. Default: None.
- same_sampling_ratebool, optional
When True, every Signal should have the same sampling rate. Set to False for a multirate system. Default: True.
- infodict, optional
A dictionary with generic information about the MultiBandSignal can be passed. Default: None.
- add_band(sig: Signal, index: int = -1)¶
Adds a new band to the MultiBandSignal.
- Parameters:
- sigSignal
Signal to be added.
- indexint, optional
Index at which to insert the new Signal. Default: -1.
- property bands: list[Signal]¶
Get the list of signal bands.
- Returns:
- list[Signal]
List of Signal objects representing the bands.
- collapse() Signal¶
Collapses MultiBandSignal by summing all of its bands and returning one Signal (possibly multichannel).
- Returns:
- new_sigSignal
Collapsed Signal.
- copy() MultiBandSignal¶
Returns a copy of the object.
- Returns:
- new_sigMultiBandSignal
Copy of Signal.
- get_all_bands(channel: int = 0) Signal | tuple[list[ndarray[tuple[Any, ...], dtype[float64]]], list[ndarray[tuple[Any, ...], dtype[float64]]]]¶
Broadcasts and returns the MultiBandSignal as a Signal object with all bands as channels in the output. This is done only for a single channel of the original signal.
- Parameters:
- channelint, optional
Channel to choose from the band signals.
- Returns:
- sigSignal or list of NDArray[np.float64] and list of int
Multichannel signal with all the bands. If the MultiBandSignal does not have the same sampling rate for all signals, a list with the time data vectors and a list containing their sampling rates are returned.
- get_all_time_data() tuple[ndarray[tuple[Any, ...], dtype[float64]], int] | list[tuple[ndarray[tuple[Any, ...], dtype[float64]], int]]¶
Get all time data saved in the MultiBandSignal. If it has consistent sampling rate, a single array with shape (time samples, band, channel) is returned, otherwise a list of bands with arrays with shape (time samples, channel) is returned.
- Returns:
- if self.same_sampling_rate=True
- time_dataNDArray[np.float64]
Time samples.
- int
Sampling rate in Hz
- else
- list[tuple[NDArray[np.float64], int]]
List with each band where time samples and sampling rate are contained.
- property is_complex_signal: bool¶
Check if the signal has complex (imaginary) time data.
- Returns:
- bool
True if the bands contain complex time data, False otherwise. Returns False if there are no bands.
- property length_samples: list[int] | int¶
Get the number of samples in each band.
- Returns:
- int | list[int]
If same_sampling_rate is True, returns a single integer representing the number of samples in each band. If False, returns a list of integers with the number of samples for each band respectively. Returns 0 if there are no bands.
- property length_seconds: float¶
Get the duration of the signal in seconds.
- Returns:
- float
Duration in seconds. Returns 0.0 if there are no bands. Only valid when same_sampling_rate is True.
- property metadata_str: str¶
Get a formatted string representation of the metadata.
- Returns:
- str
Formatted metadata string containing information about the MultiBandSignal and all its bands.
- property number_of_bands: int¶
Get the number of bands in the MultiBandSignal.
- Returns:
- int
Number of Signal objects (bands) contained.
- property number_of_channels: int¶
Get the number of channels in each band.
- Returns:
- int
Number of channels. All bands must have the same number of channels.
- remove_band(index: int = -1, return_band: bool = False)¶
Removes a band from the MultiBandSignal.
- Parameters:
- indexint, optional
This is the index from the bands list at which the band will be erased. When -1, last band is erased. Default: -1.
- return_bandbool, optional
When True, the erased band is returned. Otherwise, the multibandsignal is returned. Default: False.
- property same_sampling_rate: bool¶
Get whether all bands share the same sampling rate.
- Returns:
- bool
True if all bands have the same sampling rate, False otherwise (multirate system).
- property sampling_rate_hz: int¶
Get the sampling rate(s) in Hz.
- Returns:
- int | list[int]
Sampling rate(s) in Hz. Returns a single integer if same_sampling_rate is True, otherwise a list of integers.
- save_signal(path: str)¶
Saves the MultiBandSignal object as a pickle.
- Parameters:
- pathstr
Path for the multiband signal to be saved with format .pkl.
- show_info()¶
Show information about the MultiBandSignal.
- swap_bands(new_order)¶
Rearranges the bands in the new given order.
- Parameters:
- new_orderarray-like
New rearrangement of bands.
Filter¶
Contains Filter class
- class dsptoolbox.classes.filter.Filter(filter_coefficients: dict, sampling_rate_hz: int)¶
Bases:
objectClass for creating and storing linear digital filters with all their metadata.
- Attributes:
baGet the filter coefficients in ba (b, a) form.
has_sosCheck if the filter has second-order sections (SOS) representation.
has_zpkCheck if the filter has zero-pole-gain (zpk) representation.
is_firCheck if the filter is a finite impulse response (FIR) filter.
is_iirCheck if the filter is an infinite impulse response (IIR) filter.
metadataGet a dictionary with metadata about the filter properties.
metadata_strGet a string with metadata about the filter properties.
orderGet the order of the filter.
sampling_rate_hzGet the sampling rate in Hz.
sosGet the filter coefficients in second-order sections (SOS) form.
warning_if_complexGet the warning flag for complex-valued filters.
zpkGet the filter coefficients in zero-pole-gain (zpk) form.
Methods
biquad(eq_type, frequency_hz, gain_db, q, ...)Return a biquad filter according to [1].
copy()Returns a copy of the object.
filter_and_resample_signal(signal, ...)Filters and resamples signal.
filter_signal(signal[, channels, ...])Takes in a Signal object and filters selected channels.
fir_filter(order, frequency_hz, ...[, window])Design an FIR filter using scipy.signal.firwin.
fir_from_file(path[, channel])Read an FIR filter from an audio file.
from_ba(b, a, sampling_rate_hz)Create a filter from some b (numerator) and a (denominator) coefficients.
from_sos(sos, sampling_rate_hz)Create a filter from second-order sections.
from_zpk(z, p, k, sampling_rate_hz)Create a filter from zero-pole representation.
get_coefficients(coefficients_mode)Return a copy of the filter coefficients.
get_group_delay(frequency_vector_hz[, ...])Obtain the group delay of the filter using scipy.signal.group_delay.
get_ir(length_samples[, zero_phase])Gets an impulse response of the filter with given length.
get_transfer_function(frequency_vector_hz)Obtain the complex transfer function of the filter analytically evaluated for a given frequency vector.
iir_filter(order, frequency_hz, ...[, ...])Return an IIR filter using scipy.signal.iirfilter.
initialize_zi([number_of_channels])Initializes zi for steady-state filtering.
plot_group_delay(length_samples[, range_hz, ...])Plots group delay of the filter.
plot_magnitude(length_samples[, range_hz, ...])Plots magnitude spectrum.
plot_phase(length_samples[, range_hz, ...])Plots phase spectrum.
plot_taps([show_info_box, in_db])Plots filter taps for an FIR filter.
plot_zp([show_info_box])Plots zeros and poles with the unit circle.
save_filter(path)Saves the Filter object as a pickle.
Prints all the filter parameters to the console.
- __init__(filter_coefficients: dict, sampling_rate_hz: int)¶
The Filter class contains all parameters and metadata needed for using a digital filter.
- Parameters:
- filter_coefficientsdict
Dictionary containing configuration for the filter. The dictionary must exclusively contain one of the following keys: - FilterCoefficientsType.Zpk - FilterCoefficientsType.Sos - FilterCoefficientsType.Ba
- sampling_rate_hzint
Sampling rate in Hz for the digital filter.
- property ba: list[ndarray[tuple[Any, ...], dtype[float64 | complex128]]]¶
Get the filter coefficients in ba (b, a) form.
- Returns:
- list[NDArray]
List containing [b, a] where b are numerator coefficients and a are denominator coefficients.
- static biquad(eq_type: BiquadEqType, frequency_hz: float, gain_db: float, q: float, sampling_rate_hz: int) Filter¶
Return a biquad filter according to [1].
- Parameters:
- eq_typeBiquadEqType
EQ type.
- frequency_hzfloat
Frequency of the biquad in Hz.
- gain_dbfloat
Gain of biquad in dB.
- qfloat
Quality factor.
- sampling_rate_hzint
Sampling rate in Hz.
- Returns:
- Filter
- filter_and_resample_signal(signal: Signal, new_sampling_rate_hz: int) Signal¶
Filters and resamples signal. This is only available for all channels and sampling rates that are achievable by (only) down- or upsampling. This method is for allowing specific filters to be decimators/interpolators. If you just want to resample a signal, use the function in the standard module.
If this filter is iir, standard resampling is applied. If it is fir, an efficient polyphase representation will be used.
NOTE: Beware that no additional lowpass filter is used in the resampling step which can lead to aliases or other effects if this Filter is not adequate!
- Parameters:
- signalSignal
Signal to be filtered and resampled.
- new_sampling_rate_hzint
New sampling rate to resample to.
- Returns:
- new_sigSignal
New down- or upsampled signal.
- filter_signal(signal: Signal, channels=None, activate_zi: bool = False, zero_phase: bool = False) Signal¶
Takes in a Signal object and filters selected channels. Exports a new Signal object.
- Parameters:
- signalSignal
Signal to be filtered.
- channelsint or array-like, optional
Channel or array of channels to be filtered. When None, all channels are filtered. If only some channels are selected, these will be filtered and the others will be bypassed (and returned). Default: None.
- activate_ziint, optional
Gives the zi to update the filter values. Default: False.
- zero_phasebool, optional
Uses zero-phase filtering on signal. Be aware that the filter is applied twice in this case. Default: False.
- Returns:
- new_signalSignal
New Signal object.
- static fir_filter(order: int, frequency_hz: float | ArrayLike, type_of_pass: FilterPassType, sampling_rate_hz: int, window: Window = Window.Hamming) Filter¶
Design an FIR filter using scipy.signal.firwin.
- Parameters:
- orderint
Filter order. It corresponds to the number of taps - 1.
- frequency_hzfloat | ArrayLike
Frequency or frequencies of the filter in Hz.
- type_of_passFilterPassType
Type of filter pass.
- sampling_rate_hzint
Sampling rate in Hz.
- windowWindow, optional
Window to apply to the FIR filter. Default: Hamming.
- Returns:
- Filter
- static fir_from_file(path: str, channel: int = 0) Filter¶
Read an FIR filter from an audio file.
- Parameters:
- pathstr
Path to audio file. It will be read using Signal.from_file().
- channelint, optional
Channel to take from the audio file for the FIR filter. Default: 0.
- Returns:
- Filter
FIR filter.
- static from_ba(b: ArrayLike, a: ArrayLike, sampling_rate_hz: int) Filter¶
Create a filter from some b (numerator) and a (denominator) coefficients.
- Parameters:
- bArrayLike
Numerator coefficients.
- aArrayLike
Denominator coefficients.
- sampling_rate_hzint
Sampling rate in Hz.
- Returns:
- Filter
- static from_sos(sos: ndarray[tuple[Any, ...], dtype[float64]], sampling_rate_hz: int) Filter¶
Create a filter from second-order sections.
- Parameters:
- sosNDArray[np.float64]
Second-order sections.
- sampling_rate_hzint
Sampling rate in Hz.
- Returns:
- Filter
- static from_zpk(z: ndarray[tuple[Any, ...], dtype[float64]], p: ndarray[tuple[Any, ...], dtype[float64]], k: float, sampling_rate_hz: int) Filter¶
Create a filter from zero-pole representation.
- Parameters:
- zNDArray[np.float64]
Zeros
- pNDArray[np.float64]
Poles
- kfloat
Gain
- sampling_rate_hzint
Sampling rate in Hz.
- Returns:
- Filter
- get_coefficients(coefficients_mode: FilterCoefficientsType)¶
Return a copy of the filter coefficients.
- Parameters:
- coefficients_modeFilterCoefficients
Type of filter coefficients to be returned.
- Returns:
- coefficientsarray-like
Array with filter coefficients with shape depending on mode: - ba: list(b, a) with b and a of type NDArray[np.float64]. - sos: NDArray[np.float64] with shape (n_sections, 6). - zpk: tuple(z, p, k) with z, p, k of type
NDArray[np.complex128] and float
- get_group_delay(frequency_vector_hz: ndarray[tuple[Any, ...], dtype[float64]], in_seconds: bool = True) ndarray[tuple[Any, ...], dtype[float64]]¶
Obtain the group delay of the filter using scipy.signal.group_delay. To this end, filter coefficients in ba-form are always used. This could lead to numerical imprecisions in case the filter has a large order.
- Parameters:
- frequency_vector_hzNDArray[np.float64]
Frequency vector for which to compute the group delay.
- in_secondsbool, optional
When True, the output is given in seconds. Otherwise it is in samples. Default: True.
- Returns:
- group_delayNDArray[np.float64]
Group delay with shape (frequency).
- get_ir(length_samples: int, zero_phase: bool = False) ImpulseResponse¶
Gets an impulse response of the filter with given length.
- Parameters:
- length_samplesint
Length for the impulse response in samples.
- zero_phasebool, optional
When True, zero-phase filtering is applied to the IR. Default: False.
- Returns:
- ir_filtImpulseResponse
Impulse response of the filter.
- get_transfer_function(frequency_vector_hz: ndarray[tuple[Any, ...], dtype[float64]]) ndarray[tuple[Any, ...], dtype[complex128]]¶
Obtain the complex transfer function of the filter analytically evaluated for a given frequency vector.
- Parameters:
- frequency_vector_hzNDArray[np.float64]
Frequency vector for which to compute the transfer function
- Returns:
- NDArray[np.complex128]
Complex transfer function
Notes
This method uses scipy’s freqz to compute the transfer function. In the case of FIR filters, it might be significantly faster and more precise to use a direct FFT approach.
- property has_sos: bool¶
Check if the filter has second-order sections (SOS) representation.
- Returns:
- bool
True if SOS representation is available, False otherwise.
- property has_zpk: bool¶
Check if the filter has zero-pole-gain (zpk) representation.
- Returns:
- bool
True if ZPK representation is available, False otherwise.
- static iir_filter(order: int, frequency_hz: float | ArrayLike, type_of_pass: FilterPassType, sampling_rate_hz: int, filter_design_method: IirDesignMethod = IirDesignMethod.Butterworth, passband_ripple_db: float | None = None, stopband_attenuation_db: float | None = None) Filter¶
Return an IIR filter using scipy.signal.iirfilter. IIR filters are always implemented as SOS by default.
- Parameters:
- orderint
Filter order.
- frequency_hzfloat | ArrayLike
Frequency or frequencies of the filter in Hz.
- type_of_passFilterPassType
Type of pass.
- sampling_rate_hzint
Sampling rate in Hz.
- filter_design_methodIirDesignMethod, optional
Design method for the IIR filter. Default: Butterworth.
- passband_ripple_dbfloat, None, optional
Passband ripple in dB for Chebyshev1 and Elliptic. Default: None.
- stopband_attenuation_dbfloat, None, optional
Minimum stopband attenutation in dB for Chebyshev2 and Elliptic. Default: None.
- Returns:
- Filter
- initialize_zi(number_of_channels: int = 1)¶
Initializes zi for steady-state filtering. The number of parallel zi’s can be defined externally.
- Parameters:
- number_of_channelsint, optional
Number of channels is needed for the number of filter’s zi’s. Default: 1.
- property is_fir: bool¶
Check if the filter is a finite impulse response (FIR) filter.
- Returns:
- bool
True if this is an FIR filter, False if it is IIR.
- property is_iir: bool¶
Check if the filter is an infinite impulse response (IIR) filter.
- Returns:
- bool
True if this is an IIR filter, False if it is FIR.
- property order¶
Get the order of the filter.
- Returns:
- int
Filter order (highest power of the transfer function).
- plot_group_delay(length_samples: int, range_hz: list[float] | None = [20.0, 20000.0], show_info_box: bool = False) tuple[Figure, Axes]¶
Plots group delay of the filter. Different methods are used for FIR or IIR filters.
- Parameters:
- length_samplesint
Length of ir for magnitude plot.
- range_hzarray-like with length 2, None, optional
Range for which to plot the magnitude response. Pass None to avoid setting any range. Default: [20, 20000].
- show_info_boxbool, optional
Shows an information box on the plot. Default: False.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_magnitude(length_samples: int, range_hz: list[float] | None = [20.0, 20000.0], normalize: MagnitudeNormalization = MagnitudeNormalization.NoNormalization, zero_phase: bool = False, show_info_box: bool = True) tuple[Figure, Axes]¶
Plots magnitude spectrum. Change parameters of spectrum with set_spectrum_parameters.
- Parameters:
- length_samplesint
Length of IR for magnitude plot. See notes for details.
- range_hzarray-like with length 2, None, optional
Range for which to plot the magnitude response. Use None to avoid setting any specific range. Default: [20, 20000].
- normalizeMagnitudeNormalization, optional
Mode for normalization. Default: NoNormalization.
- zero_phasebool, optional
Plots magnitude for zero phase filtering. Default: False.
- show_info_boxbool, optional
Shows an information box on the plot. Default: True.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
Notes
An IR of the filter is obtained by filtering a dirac impulse in the case of IIR filters. For FIR filters, the taps are used and, if necessary, zero-padded. The IR length determines the frequency resolution.
- plot_phase(length_samples: int, range_hz: list[float] | None = [20.0, 20000.0], unwrap: bool = False, show_info_box: bool = False) tuple[Figure, Axes]¶
Plots phase spectrum.
- Parameters:
- length_samplesint, optional
Length of IR for phase plot. See notes for details.
- range_hzarray-like with length 2, None, optional
Range for which to plot the magnitude response. Default: [20, 20000].
- unwrapbool, optional
Unwraps the phase to show. Default: False.
- show_info_boxbool, optional
Shows an information box on the plot. Default: False.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
Notes
An IR of the filter is obtained by filtering a dirac impulse in the case of IIR filters. For FIR filters, the taps are used and, if necessary, zero-padded. The IR length determines the frequency resolution.
- plot_taps(show_info_box: bool = False, in_db: bool = False) tuple[Figure, Axes]¶
Plots filter taps for an FIR filter. IIR filters will raise an assertion error.
- Parameters:
- show_info_boxbool, optional
Shows an information box on the plot. Default: False.
- in_dbbool, optional
When True, the FIR coefficients are shown in dB. Default: False.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_zp(show_info_box: bool = False) tuple[Figure, Axes]¶
Plots zeros and poles with the unit circle. This returns None and produces no plot if user decides that conversion ba->sos is too costly.
- Parameters:
- show_info_boxbool, optional
Shows an information box on the plot. Default: False.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- property sampling_rate_hz¶
Get the sampling rate in Hz.
- Returns:
- int
Sampling rate in Hz.
- save_filter(path: str)¶
Saves the Filter object as a pickle.
- Parameters:
- pathstr
Path for the filter to be saved with format .pkl.
- show_info()¶
Prints all the filter parameters to the console.
- property sos: ndarray[tuple[Any, ...], dtype[float64 | complex128]]¶
Get the filter coefficients in second-order sections (SOS) form.
- Returns:
- NDArray[np.float64 | np.complex128]
Second-order sections array with shape (n_sections, 6). Each row contains [b0, b1, b2, a0, a1, a2] for one section.
- property warning_if_complex¶
Get the warning flag for complex-valued filters.
- Returns:
- bool
When True, a warning is issued if a complex-valued filter is used.
FilterBank¶
- class dsptoolbox.classes.filterbank.FilterBank(filters: list | None = None, same_sampling_rate: bool = True, info: dict | None = None)¶
Bases:
objectStandard template for filter banks containing filters, filters’ initial values, metadata and some useful plotting methods.
- Attributes:
filtersGet the list of filters in the FilterBank.
metadataGet a dictionary with metadata about the filter bank properties.
metadata_strGet a string with metadata about the filter bank properties.
number_of_filtersGet the number of filters in the FilterBank.
same_sampling_rateGet whether all filters share the same sampling rate.
sampling_rate_hzGet the sampling rate(s) in Hz.
Methods
add_filter(filt[, index])Adds a new filter at the end of the filters dictionary.
copy()Returns a copy of the object.
filter_multiband_signal(mbsignal[, ...])Applies the filter bank to a MultiBandSignal and returns the output as a MultiBandSignal as well.
filter_signal(...)Applies the filter bank to a signal and returns a multiband signal or a Signal object.
firs_from_file(path)Read an audio file and return each channel as an FIR filter in a FilterBank.
get_ir(...)Returns impulse response from the filter bank.
get_transfer_function(frequency_vector_hz, mode)Compute the complex transfer function of the filter bank for specified frequencies.
initialize_zi([number_of_channels])Initiates the zi of the filters for the given number of channels.
plot_group_delay(length_samples, mode[, ...])Plots the phase response of each filter.
plot_magnitude(length_samples, mode[, ...])Plots the magnitude response of each filter.
plot_phase(length_samples, mode[, range_hz, ...])Plots the phase response of each filter.
remove_filter([index, return_filter])Removes a filter from the filter bank.
save_filterbank(path)Saves the FilterBank object as a pickle.
Show information about the filter bank.
swap_filters(new_order)Rearranges the filters in the new given order.
- __init__(filters: list | None = None, same_sampling_rate: bool = True, info: dict | None = None)¶
FilterBank object saves multiple filters and some metadata. It also allows for easy filtering with multiple filters. Since the digital filters that are supported are linear systems, the order in which they are saved and applied to a signal is not relevant.
- Parameters:
- filterslist, optional
List containing filters.
- same_sampling_ratebool, optional
When True, every Filter should have the same sampling rate. Set to False for a multirate system. Default: True.
- infodict, optional
Dictionary containing general information about the filter bank. Some parameters of the filter bank are automatically read from the filters dictionary.
Methods
General
add_filter, remove_filter, swap_filters, copy, save_filterbank.
Prints and plots
plot_magnitude, plot_phase, plot_group_delay, show_info.
- add_filter(filt: Filter, index: int = -1) Self¶
Adds a new filter at the end of the filters dictionary.
- Parameters:
- filtFilter
Filter to be added to the FilterBank.
- indexint, optional
Index at which to insert the new Filter. Default: -1.
- Returns:
- self
- copy() FilterBank¶
Returns a copy of the object.
- Returns:
- new_sigFilterBank
Copy of filter bank.
- filter_multiband_signal(mbsignal: MultiBandSignal, activate_zi: bool = False, zero_phase: bool = False) MultiBandSignal¶
Applies the filter bank to a MultiBandSignal and returns the output as a MultiBandSignal as well. Only ‘parallel’ mode is supported.
NOTE: all channels contained in the MultiBandSignal are filtered.
- Parameters:
- signalSignal
Signal to be filtered.
- activate_zibool, optional
Takes in the filter initial values and updates them for streaming purposes. Default: False.
- zero_phasebool, optional
Activates zero_phase filtering for the filter bank. It cannot be used at the same time with zi=True. Default: False.
- Returns:
- new_sigMultiBandSignal.
New signal after filtering.
- filter_signal(signal: Signal, mode: Literal[FilterBankMode.Sequential, FilterBankMode.Summed], activate_zi: bool = False, zero_phase: bool = False) Signal¶
- filter_signal(signal: Signal, mode: Literal[FilterBankMode.Parallel], activate_zi: bool = False, zero_phase: bool = False) MultiBandSignal
Applies the filter bank to a signal and returns a multiband signal or a Signal object.
- Parameters:
- signalSignal
Signal to be filtered.
- modeFilterBankMode
Way to apply filter bank to the signal.
- activate_zibool, optional
Takes in the filter initial values and updates them for streaming purposes. Default: False.
- zero_phasebool, optional
Activates zero_phase filtering for the filter bank. It cannot be used at the same time with zi=True. Default: False.
- Returns:
- new_sig‘sequential’ or ‘summed’ -> Signal.
‘parallel’ -> MultiBandSignal.
New signal after filtering.
- property filters: list[Filter]¶
Get the list of filters in the FilterBank.
- Returns:
- list[Filter]
List of Filter objects contained in this FilterBank.
- static firs_from_file(path: str)¶
Read an audio file and return each channel as an FIR filter in a FilterBank.
- Parameters:
- pathstr
Path to audio file.
- get_ir(length_samples: int, mode: Literal[FilterBankMode.Parallel], zero_phase: bool = False) MultiBandSignal¶
- get_ir(length_samples: int, mode: Literal[FilterBankMode.Sequential, FilterBankMode.Summed], zero_phase: bool = False) Signal
Returns impulse response from the filter bank.
- Parameters:
- length_samplesint
Length of the impulse response to be generated. If some filter is longer than the given length, then the length is adapted.
- modeFilterBankMode
Filtering mode.
- zero_phasebool, optional
When True, zero phase filtering is activated. Default: False.
- Returns:
- irMultiBandSignal or Signal
Impulse response of the filter bank.
- get_transfer_function(frequency_vector_hz: ndarray[tuple[Any, ...], dtype[float64]], mode: FilterBankMode) ndarray[tuple[Any, ...], dtype[complex128]]¶
Compute the complex transfer function of the filter bank for specified frequencies. The output is based on the filter bank filtering mode.
- Parameters:
- frequency_vector_hzNDArray[np.float64]
Frequency vector to evaluate frequencies at.
- modeFilterBankMode
Way of applying the filter bank. If “parallel”, the resulting transfer function will have shape (frequency, filter). In the cases of “sequential” and “summed”, it will have shape (frequency).
- Returns:
- NDArray[np.complex128]
Complex transfer function of the filter bank.
- initialize_zi(number_of_channels: int = 1)¶
Initiates the zi of the filters for the given number of channels.
- Parameters:
- number_of_channelsint, optional
Number of channels is needed for the number of filters’ zi’s. Default: 1.
- property number_of_filters: int¶
Get the number of filters in the FilterBank.
- Returns:
- int
Number of Filter objects contained.
- plot_group_delay(length_samples: int, mode: FilterBankMode, range_hz: list[float] | None = [20.0, 20000.0]) tuple[Figure, Axes] | None¶
Plots the phase response of each filter.
- Parameters:
- length_samplesint
Length (in samples) of the IR to be generated for the plot.
- modeFilterBankMode
Type of plot. ‘parallel’ plots every filter’s frequency response, ‘sequential’ plots the frequency response after having filtered one impulse with every filter in the FilterBank. ‘summed’ sums up every filter output.
- range_hzarray-like, optional
Range of Hz to plot. Default: [20, 20e3].
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_magnitude(length_samples: int, mode: FilterBankMode, range_hz: list[float] | None = [20.0, 20000.0], zero_phase: bool = False) tuple[Figure, Axes] | None¶
Plots the magnitude response of each filter.
- Parameters:
- length_samplesint
Length (in samples) of the IR to be generated for the plot.
- modeFilterBankMode
Type of plot. ‘parallel’ plots every filter’s frequency response, ‘sequential’ plots the frequency response after having filtered one impulse with every filter in the FilterBank. ‘summed’ sums up every frequency response.
- range_hzarray-like, None, optional
Range of Hz to plot. Use None to avoid any specific range. Default: [20., 20e3].
- zero_phasebool, optional
When True, zero-phase filtering is used. Default: False.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- plot_phase(length_samples: int, mode: FilterBankMode, range_hz=[20, 20000.0], unwrap: bool = False) tuple[Figure, Axes] | None¶
Plots the phase response of each filter.
- Parameters:
- length_samplesint
Length (in samples) of the IR to be generated for the plot.
- modeFilterBankMode
Type of plot. ‘parallel’ plots every filter’s frequency response, ‘sequential’ plots the frequency response after having filtered one impulse with every filter in the FilterBank. ‘summed’ sums up every filter output.
- range_hzarray-like, optional
Range of Hz to plot. Default: [20, 20e3].
- unwrapbool, optional
When True, unwrapped phase is plotted. Default: False.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axmatplotlib.axes.Axes
Axes.
- remove_filter(index: int = -1, return_filter: bool = False) Filter | Self¶
Removes a filter from the filter bank.
- Parameters:
- indexint, optional
This is the index from the filters list at which the filter will be erased. When -1, last filter is erased. Default: -1.
- return_filterbool, optional
When True, the erased filter is returned. Otherwise, the filterbank instance is returned. Default: False.
- Returns:
- Filter | self
- property same_sampling_rate: bool¶
Get whether all filters share the same sampling rate.
- Returns:
- bool
True if all filters have the same sampling rate, False otherwise (multirate system).
- property sampling_rate_hz: int | list[int]¶
Get the sampling rate(s) in Hz.
- Returns:
- int | list[int]
Sampling rate in Hz. Returns a single integer if same_sampling_rate is True, otherwise a list of integers.
- save_filterbank(path: str)¶
Saves the FilterBank object as a pickle.
- Parameters:
- pathstr
Path for the filter bank to be saved with format .pkl.
- show_info()¶
Show information about the filter bank.
Spectrum¶
- class dsptoolbox.classes.spectrum.Spectrum(frequency_vector_hz: ndarray[tuple[Any, ...], dtype[float64]], spectral_data: ArrayLike)¶
Bases:
MultichannelData- Attributes:
frequency_vector_hzGet the frequency vector in Hz.
frequency_vector_typeGet the type of frequency spacing in the frequency vector.
has_coherenceCheck if coherence data has been set for this spectrum.
is_complexWhen True, the spectral data is complex.
is_magnitudeCheck if the spectral data is in magnitude form.
length_frequency_binsGet the number of frequency bins in the spectrum.
number_frequency_binsGet the number of frequency bins in the spectrum.
- number_of_channels
spectral_dataGet the spectral data.
spectrum_typeGet the spectrum type (Magnitude or Complex).
Methods
apply_gain(gain_db)Add gain to spectrum.
apply_octave_smoothing(octave_fraction[, ...])Apply octave smoothing (inplace) on the spectral data.
copy()Copy the spectral data.
from_filter(frequency_vector_hz, filt[, complex])Obtain spectrum from computing the filter transfer function.
from_filterbank(frequency_vector_hz, ...[, ...])Obtain spectrum from computing the transfer function of a filter bank.
from_signal(sig[, complex])Instantiate from the spectrum of a signal.
get_channels(channels)Returns a signal object with the selected channels.
get_energy([f_lower_hz, f_upper_hz])Integrate the spectrum in order to obtain the total energy in a frequency region.
Obtain an interpolated spectrum.
normalize(reference_frequency_hz[, ...])Normalize spectrum to be 0 dB at the specified frequency.
Plots coherence.
plot_magnitude([in_db, normalization, ...])Plot the magnitude spectrum.
remove_channel([channel_number])Removes a channel.
resample(new_freqs_hz)Resample current spectrum (inplace) to new frequency vector.
save_spectrum(path)Saves the Spectrum object as a pickle.
set_coherence(coherence)Sets the coherence matrix from the transfer function computation.
set_interpolator_parameters([domain, ...])Set the parameters of the interpolator.
sum_channels([power_sum])Sum all channels of the spectrum and return new spectrum with single channel.
swap_channels(new_order)Rearranges the channels (inplace) in the new given order.
to_signal(sampling_rate_hz[, length_seconds])Convert the current spectrum to a time signal using an inverse rFFT.
trim(f_lower_hz, f_upper_hz[, inclusive])Trim the spectrum (inplace) to the new boundaries.
warp(warping_factor, sampling_rate_hz)Transform (inplace) the spectrum by warping it through interpolation with the stored interpolation parameters.
- __init__(frequency_vector_hz: ndarray[tuple[Any, ...], dtype[float64]], spectral_data: ArrayLike)¶
Spectrum class. If the data is complex, it is regarded as the complex spectrum. Otherwise, it is assumed to be the magnitude (linear) spectrum. No rescaling is applied.
- Parameters:
- frequency_vector_hzNDArray[np.float64]
Frequency vector for the spectral data.
- spectral_dataArrayLike
Spectral data. It should be broadcastable to a 2D-Array. If its data is not complex, it is assumed to be the magnitude spectrum (no negative values are supported).
- apply_gain(gain_db: float | ndarray[tuple[Any, ...], dtype[float64]])¶
Add gain to spectrum.
- Parameters:
- gain_dbfloat, NDArray[np.float64]
Gain to apply. It should be either a single value for all channels or a vector with a gain for each channel.
- Returns:
- self
- apply_octave_smoothing(octave_fraction: float, window_type: Window = Window.Hann)¶
Apply octave smoothing (inplace) on the spectral data. When complex, the smoothing happens on the magnitude and phase representation. Otherwise, the smoothing happens on the magnitude spectrum.
- Parameters:
- octave_fractionfloat
Octave fraction across which to apply smoothing.
- window_typeWindow, optional
Type of window to use. Default: Hann.
- Returns:
- self
Notes
If the frequency vector was other than logarithmic or linear, the resulting data will have a linear frequency vector with around 1 Hz resolution. Interpolation using the saved interpolator parameters will be used.
- property frequency_vector_hz¶
Get the frequency vector in Hz.
- Returns:
- NDArray[np.float64]
Frequency vector in Hz. Must be 1D, non-negative, and strictly ascending.
- property frequency_vector_type: FrequencySpacing¶
Get the type of frequency spacing in the frequency vector.
- Returns:
- FrequencySpacing
Frequency spacing type (Linear, Logarithmic, or Other).
- static from_filter(frequency_vector_hz: ndarray[tuple[Any, ...], dtype[float64]], filt: Filter, complex: bool = False) Spectrum¶
Obtain spectrum from computing the filter transfer function.
- Parameters:
- frequency_vector_hzNDArray[np.float64]
Frequency vector to compute.
- filtFilter
Filter to obtain the spectrum from.
- complexbool, optional
When True, the complex spectrum is saved. Otherwise, it is the magnitude spectrum. Default: False.
- static from_filterbank(frequency_vector_hz: ndarray[tuple[Any, ...], dtype[float64]], filter_bank: FilterBank, mode: FilterBankMode, complex: bool = False) Spectrum¶
Obtain spectrum from computing the transfer function of a filter bank.
- Parameters:
- frequency_vector_hzNDArray[np.float64]
Frequency vector to compute.
- filter_bankFilterBank
FilterBank to obtain the spectrum from.
- modeFilterBankMode
Mode for the filter bank.
- complexbool, optional
When True, the complex spectrum is saved. Otherwise, it is the magnitude spectrum. Default: False.
- static from_signal(sig: Signal, complex: bool = False) Spectrum¶
Instantiate from the spectrum of a signal. It can be complex or not. The spectrum is always generated with the Signal.get_spectrum() method without changing its parameters.
- Parameters:
- sigSignal
Input signal.
- complexbool, optional
When True, the spectral data will be complex. To this end, the spectrum of the signal must be complex. An assertion will be raised if this is not the case. Default: False.
- get_energy(f_lower_hz: float | None = None, f_upper_hz: float | None = None) ndarray[tuple[Any, ...], dtype[float64]]¶
Integrate the spectrum in order to obtain the total energy in a frequency region. Depending on the original scaling, this can represent the RMS value of the underlying signal exactly.
This is computed by using trapezoidal integration across the frequency axis. The passed frequency limits are always included in the computation.
- Parameters:
- f_lower_hzfloat, None, optional
Lower frequency bound. Pass None to integrate until the last available frequency bin. Default: None.
- f_upper_hzfloat, None, optional
Upper frequency bound. Pass None to integrate until the last available frequency bin. Default: None.
- Returns:
- NDArray[np.float64]
- get_interpolated_spectrum(requested_frequency: ndarray[tuple[Any, ...], dtype[float64]], output_type: SpectrumType) ndarray[tuple[Any, ...], dtype[_ScalarT]]¶
Obtain an interpolated spectrum. Refer to set_interpolator_parameters() to modify the interpolation.
- Parameters:
- requested_frequencyNDArray[np.float64], None
Frequencies to which to interpolate.
- output_typeSpectrumType
Output for the data.
- Returns:
- NDArray
- property has_coherence: bool¶
Check if coherence data has been set for this spectrum.
- Returns:
- bool
True if coherence attribute exists, False otherwise.
- property is_complex: bool¶
When True, the spectral data is complex. Counterpart to is_magnitude for consistency with Signal class which has is_complex_signal.
- property is_magnitude: bool¶
Check if the spectral data is in magnitude form.
- Returns:
- bool
True if the spectral data contains only real (magnitude) values, False if it contains complex values.
- property length_frequency_bins: int¶
Get the number of frequency bins in the spectrum.
- Returns:
- int
Alias for number_frequency_bins. Number of frequency bins (length of the frequency vector).
- normalize(reference_frequency_hz: float, reference_channel: int | None = None)¶
Normalize spectrum to be 0 dB at the specified frequency.
- Parameters:
- reference_frequency_hzfloat
Frequency at which to normalize.
- reference_channelint, None, optional
Reference channel to normalize to. If None, each channel is normalized by itself at the reference frequency. Default: None.
- Returns:
- self
- property number_frequency_bins: int¶
Get the number of frequency bins in the spectrum.
- Returns:
- int
Number of frequency bins (length of the frequency vector).
- plot_coherence() tuple[Figure, list[Axes]]¶
Plots coherence. If not available, an attribute error will be triggered.
- Returns:
- figmatplotlib.figure.Figure
Figure.
- axlist of matplotlib.axes.Axes
Axes.
- plot_magnitude(in_db: bool = True, normalization: MagnitudeNormalization = MagnitudeNormalization.NoNormalization, dynamic_range_db: float | None = None)¶
Plot the magnitude spectrum.
- Parameters:
- in_dbbool, True
When True, the data is converted to dB.
- normalizationMagnitudeNormalization, optional
Type of normalization (per-channel) to apply. Default: NoNormalization.
- dynamic_range_dbfloat, None, optional
Pass a dynamic range in order to constrain the plot. Use None to avoid it. Default: None.
- resample(new_freqs_hz: ndarray[tuple[Any, ...], dtype[float64]])¶
Resample current spectrum (inplace) to new frequency vector. The stored interpolation parameters will be used.
- Parameters:
- new_freqs_hzNDArray[np.float64]
New frequency vector.
- Returns:
- self
- save_spectrum(path: str)¶
Saves the Spectrum object as a pickle.
- Parameters:
- pathstr
Path for the filter to be saved. Use only folder1/folder2/name (it can be passed with .pkl at the end or without it).
- set_coherence(coherence: ndarray[tuple[Any, ...], dtype[float64]])¶
Sets the coherence matrix from the transfer function computation.
- Parameters:
- coherenceNDArray[np.float64]
Coherence matrix. It must match the shape of the saved spectral data.
- set_interpolator_parameters(domain: InterpolationDomain = InterpolationDomain.Power, scheme: InterpolationScheme = InterpolationScheme.Linear, edges_handling: InterpolationEdgeHandling = InterpolationEdgeHandling.ZeroPad)¶
Set the parameters of the interpolator.
- Parameters:
- domainInterpolationDomain, optional
Domain to use during the interpolation. Default: Power.
- interpolation_schemeInterpolationScheme, optional
Type of interpolation to realize. See notes for details. Default: Linear.
- edges_handlingInterpolationEdgeHandling, optional
Type of handling for interpolating outside the saved range. See notes for details. Default: ZeroPad.
Notes
The domain for spectrum interpolation defaults to power. This renders the most accurate results, though spectrum interpolation always has some error if done directly on the frequency data. Zero-padding the time series or computing DFT directly is the correct way of obtaining the values of different frequency bins.
- property spectral_data: ndarray[tuple[Any, ...], dtype[float64 | complex128]]¶
Get the spectral data.
- Returns:
- NDArray[np.float64 | np.complex128]
Spectral data as a 2D array with shape (number_of_frequency_bins, number_of_channels). Real values represent magnitude spectrum, complex values represent complex spectrum.
- property spectrum_type: SpectrumType¶
Get the spectrum type (Magnitude or Complex).
- Returns:
- SpectrumType
Spectrum type indicating whether the data is magnitude or complex.
- sum_channels(power_sum: bool = True) Spectrum¶
Sum all channels of the spectrum and return new spectrum with single channel.
- Parameters:
- power_sumbool, optional
When True, all channels are summed in their power representation. Otherwise, they are summed in either magnitude or complex representation, depending on the type of spectral data. Default: True.
- Returns:
- self
- to_signal(sampling_rate_hz: int, length_seconds: float | None = None) Signal¶
Convert the current spectrum to a time signal using an inverse rFFT. Its data must be complex.
- Parameters:
- sampling_rate_hzint
Requested sampling rate of the time signal.
- length_secondsfloat, None, optional
Length of time signal in seconds. For linearly-spaced data and None, it will be inferred from the frequency resolution. For other frequency spacings, it is required. Default: None.
- Returns:
- Signal
Notes
For linearly-spaced frequency data, it will be checked if an interpolation is necessary considering the current frequency vector. If a length in seconds is requested, the time signal is first computed and then zero-padded or trimmed accordingly in case no interpolation was needed.
Non-linear frequency data will always trigger an interpolation in the magnitude and phase domains with zero-padding outside the known frequency domain.
- trim(f_lower_hz: float | None, f_upper_hz: float | None, inclusive: bool = True)¶
Trim the spectrum (inplace) to the new boundaries.
- Parameters:
- f_lower_hzfloat, None
Lowest frequency point in Hz.
- f_upper_hzfloat, None
Highest frequency point in Hz.
- inclusivebool, optional
When True, the given frequencies are included in the result vector. Default: True.
- Returns:
- self
- warp(warping_factor: float, sampling_rate_hz: int)¶
Transform (inplace) the spectrum by warping it through interpolation with the stored interpolation parameters. This is done according to the formula shown in [1].
- Parameters:
- warping_factorfloat
Warping factor between ]-1;1[.
- sampling_rate_hzint
Assumed sampling rate while warping. It must be valid for the current frequency vector, i.e., no aliasing is to be expected.
- Returns:
- self
Notes
The formula presented in [1] has been modified with a negative sign for lambda in order to match the warping formulation used in this python package.
Negative lambda values increase the resolution for lower frequencies, while positive values expand higher frequencies.
References
[1]: Germán Ramos, José J. López, Basilio Pueo. Cascaded warped-FIR and FIR filter structure for loudspeaker equalization with low computational cost requirements. Digital Signal Processing, Volume 19, Issue 3, 2009, Pages 393-409, ISSN 1051-2004, https://doi.org/10.1016/j.dsp.2008.01.003.