Open an interactive online version by clicking the badge Binder badge or download the notebook.

Measurement-based equalization filter#

Simon Kersten (1), Marco Berzborn (2)
(1) Institute for Hearing Technology and Acoustics, RWTH Aachen University
(2) Eindhoven University of Technology, Building Acoustics Group

Contact: simon.kersten@akustik.rwth-aachen.de, m.berzborn@tue.nl

In this notebook, you will design a digital equalization filter from measured impulse responses. The aim of creating such filter is to compensate for deviations of a frequency-dependent response from an ideal flat frequency response of devices such as loudspeakers. Ideally, the combined response of the device and the equalization filter matches a desired target response, which is often a flat magnitude spectrum.

The example investigated here is headphone equalization, which is useful when the influence of the headphones on the signal at the ears should be minimized, for example in binaural reproduction. The headphone’s frequency response is denoted as headphone transfer function (HpTF). It can be represented in the time domain by an impulse response, or in the frequency domain by its magnitude and phase spectra. For simplicity, this notebook uses the term HpTF throughout since the design steps focus primarily on the magnitude spectrum, although the time-domain response and phase are also considered.

Duration: 60 Minutes

Requirements: Basic familiarity with digital signals and systems, and frequency responses.

References
Välimäki, V., Reiss, J.D., 2016. All About Audio Equalization: Solutions and Frontiers. Applied Sciences 6, 129. https://doi.org/10.3390/app6050129

Norcross, S.G., Bouchard, M., Soulodre, G.A., 2006. Inverse filtering design using a minimal-phase target function from regularization, in: Audio Engineering Society Convention 121. Audio Engineering Society.

Lindau, A., Brinkmann, F., 2012. Perceptual Evaluation of Headphone Compensation in Binaural Synthesis Based on Non-Individual Recordings. JAES 60, 54–62.

Dependencies
pip install "pyfar>=0.8" pooch nbgrader watermark ipympl
[ ]:
import pyfar as pf
import matplotlib.pyplot as plt
%matplotlib ipympl

Configuration#

Set the global audio settings. Adjust the sampling rate if required for your application.

[ ]:
sampling_rate = 44100

Load headphone impulse responses#

For this tutorial, a set of 12 measured headphone transfer functions (HpTFs) is loaded using the `pyfar.signals.files module <https://pyfar.readthedocs.io/en/stable/modules/pyfar.signals.files.html>`__. The measurements represent 12 repetitions, with the headphones repositioned between measurements. For the purpose of this notebook, only the 12 repetitions for one ear are considered, i.e. channels are sliced to the first channel using [:, 0] below.

Data attribution: The headphone impulse responses were measured with Sennheiser HD-650 headphones and are taken from the FABIAN database by Fabian Brinkmann, Alexander Lindau, Stefan Weinzierl, Gunnar Geissler, Steven van de Par, Markus Müller-Trapet, Rob Opdam, and Michael Vorländer, licensed under CC BY 4.0.

[ ]:
hptf_measured = pf.signals.files.headphone_impulse_responses(sampling_rate=sampling_rate)
hptf_measured = hptf_measured[:, 0]

fig = plt.figure()
ax = pf.plot.time_freq(hptf_measured, unit="ms", lw=0.5)
ax[1].set_ylim(-40, 20)
ax[0].set_title("Measured headphone transfer functions")
plt.show()

Average the measured responses#

To obtain a representative HpTF for the equalization filter design, we calculate the average of the 12 magnitude spectra.

Task: Calculate the average magnitude spectrum using `pyfar.dsp.average <https://pyfar.readthedocs.io/en/stable/modules/pyfar.dsp.html#pyfar.dsp.average>`__ with mode="magnitude_zerophase". This mode discards the phase information; it will be considered after the spectrum inversion. Store the result in the variable hptf_average.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

fig = plt.figure()
ax = pf.plot.freq(hptf_measured, c="gray", lw=0.5, label="Individual measurements")
pf.plot.freq(hptf_average, c="black", label="Average")
ax.set_ylim(-40, 20)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:])
plt.show()

Define the target frequency response#

The first step in designing the equalization filter is to define its target frequency response, which is often a flat magnitude spectrum. In practice however, such equalization is usually restricted to a specific frequency range. In our case, the limited reproduction capabilities of the headphones may require excessive amplification at low frequencies. At high frequencies, the measured response can exhibit pronounced variations sensitive to small changes in headphone positioning, which makes perfect equalization infeasible. Consequently, the target response should be chosen such that it can be achieved reliably without requiring excessive equalization.

Task: Define a Butterworth band-pass filter as the target frequency response using the corresponding pyfar function. Determine and justify meaningful cutoff frequencies and a band-pass filter order by comparing the target response with the measured and averaged HpTFs. Store the filter’s impulse response in the variable target, which will be used for calculating the equalization filter below.

Hint: Consider removing the phase distortion of the target filter by using `pyfar.dsp.zero_phase <https://pyfar.readthedocs.io/en/stable/modules/pyfar.dsp.html#pyfar.dsp.zero_phase>`__ to obtain a zero-phase impulse response. This will ensure that the target response is only defined by its magnitude spectrum.

Note: The `pyfar.Filter classes <https://pyfar.readthedocs.io/en/stable/classes/pyfar.filter.html>`__ provide a method for directly obtaining the impulse response.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

fig = plt.figure()
ax = pf.plot.freq(hptf_measured, c="gray", lw=0.5, label="Individual measurements")
pf.plot.freq(hptf_average, c="black", label="Average")
pf.plot.freq(target, label="Equalization target", c="tab:blue", ls="--")
ax.set_ylim(-40, 20)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-3:], labels[-3:])
plt.show()

Optional: Smooth the magnitude spectrum#

It is often not useful to equalize every detail of a measured magnitude spectrum. Narrow notches and peaks, for example, can be sensitive to small changes in headphone position. Averaging the repeated measurements already reduces some of this variability. A further approach is to smooth the magnitude spectrum before inversion.

Task: Smooth the average HpTF using third-octave smoothing with `pyfar.dsp.smooth_fractional_octave <https://pyfar.readthedocs.io/en/stable/modules/pyfar.dsp.html#pyfar.dsp.smooth_fractional_octave>`__. Store it in the variable hptf_smoothed. In which frequency ranges do the largest differences between the smoothed and unsmoothed spectra occur?

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

fig = plt.figure()
ax = pf.plot.freq(hptf_measured, c="gray", lw=0.5, label="Individual measurements")
pf.plot.freq(hptf_average, c="black", label="Average")
pf.plot.freq(hptf_smoothed, label="Smoothed average", c="tab:red")
pf.plot.freq(target, label="Equalization target", c="tab:blue", ls="--")
ax.set_ylim(-40, 20)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-4:], labels[-4:])
plt.show()

Regularized spectrum inversion#

The equalization filter cannot, in general, be obtained simply by inverting the measured magnitude spectrum. In particular, inverting frequency regions in which the system response rolls off can result in excessive amplification, potentially introducing unwanted audible artifacts such as distortion. Regularization is therefore required to limit the gain of the inverse filter in frequency regions where direct inversion would be unreliable. Regularization can be implemented, for example, by limiting the inversion to a specified frequency range or by defining a frequency-dependent regularization function that controls the inverse filter gain across frequency.

Task: Calculate the regularized inverse of the smoothed magnitude spectrum using the previously defined target response. Use the `pyfar.dsp.RegularizedSpectrumInversion class <https://pyfar.readthedocs.io/en/stable/modules/pyfar.dsp.html#pyfar.dsp.RegularizedSpectrumInversion>`__ to apply regularization outside a defined frequency range. Inspect the resulting filter magnitude response to understand the consequences of your regularization settings.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

fig = plt.figure()
ax = pf.plot.freq(hptf_measured, c="gray", lw=0.5, label="Individual measurements")
pf.plot.freq(hptf_average, c="black", label="Average")
pf.plot.freq(hptf_smoothed, label="Smoothed average", c="tab:red")
pf.plot.freq(target, label="Equalization target", c="tab:blue", ls="--")
pf.plot.freq(hptf_inv, label="Equalization filter", c="tab:orange")
ax.set_ylim(-40, 20)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-5:], labels[-5:])
plt.show()

Phase of the equalization filter#

So far, the design of the equalization filter has primarily focused on achieving a desired magnitude response, ideally matching the target frequency response. However, the phase response is equally important for the practical implementation. While the magnitude response determines the frequency-dependent amplification, the phase response influences the temporal characteristics of the filter, particularly the shape and temporal distribution of its impulse response. The choice of phase is therefore crucial for obtaining a causal and physically realizable filter.

Task: Calculate and compare the zero-phase, linear-phase, and minimum-phase versions from the inverted HpTF magnitude spectrum using the corresponding functions from the pyfar.dsp module. Store them in the variables eq_zero_phase, eq_linear_phase, and eq_minimum_phase. How does the phase response affect the equalization filter? Why is the zero-phase version not suitable for practical use?

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

fig = plt.figure()
ax = pf.plot.time_freq(eq_minimum_phase, dB_time=True, unit="ms", c="black", label="Minimum phase")
pf.plot.time_freq(eq_linear_phase, dB_time=True, unit="ms", c="tab:blue", label="Linear phase")
pf.plot.time_freq(eq_zero_phase, dB_time=True, unit="ms", c="tab:red", label="Zero phase")
ax[1].set_ylim(-40, 20)
ax[0].legend()
plt.show()

Filter length#

The filter length determines the number of coefficients used to represent the impulse response. Limiting the filter length reduces computational requirements and can facilitate real-time implementation. However, truncating the impulse response also affects the resulting frequency response.

Task: Use `pyfar.dsp.time_window <https://pyfar.readthedocs.io/en/stable/modules/pyfar.dsp.html#pyfar.dsp.time_window>`__ to obtain minimum-phase equalization filters with lengths of 128, 256, and 512 samples, and compare them with the non-truncated version (2048 samples). Use eq_minimum_phase_128… as variable names. In which frequency range does the largest effect of the filter length appear? How would the truncation be implemented in the linear-phase version?

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

fig = plt.figure()
ax = pf.plot.time_freq(eq_minimum_phase, dB_time=True, c="black", label=f"Original filter ({eq_minimum_phase.n_samples} samples)")
pf.plot.time_freq(eq_minimum_phase_512, dB_time=True, c="tab:blue", label="512 samples")
pf.plot.time_freq(eq_minimum_phase_256, dB_time=True, c="tab:red", label="256 samples")
pf.plot.time_freq(eq_minimum_phase_128, dB_time=True, c="tab:green", label="128 samples")
ax[0].set_xlim(-1e-3, eq_minimum_phase.signal_length)
ax[0].legend()
plt.show()

Predict the equalization performance#

Finally, we evaluate the designed equalization filter by predicting its effect on the measured HpTFs.

Task: Predict the effect of the equalization filter by convolving each measured HpTF with the minimum-phase equalization filter of the different maximum truncation lengths considered above. Use `pyfar.dsp.convolve <https://pyfar.readthedocs.io/en/stable/modules/pyfar.dsp.html#pyfar.dsp.convolve>`__.

Task: Discuss the results. How consistently does the equalization filter compensate for the measured HpTFs? Identify any remaining deviations and consider possible reasons for them.

[ ]:
# YOUR CODE HERE
raise NotImplementedError()

fig = plt.figure()
ax = pf.plot.freq(eq_prediction_measured, c="gray", lw=0.5, label="Individual predictions")
pf.plot.freq(target, label="Equalization target", c="black", ls="--")
ax.set_ylim(-40, 20)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:])
ax.set_title("Predicted effect of equalization filter")
plt.show()

License notice#

This notebook © 2026 by Simon Kersten and Marco Berzborn is licensed under CC BY 4.0

Watermark#

The following watermark might help others to install specific package versions that might be required to run the notebook. Please give at least the versions of Python, IPython, numpy , and scipy, major third party packagers (e.g., pytorch), and all used pyfar packages.

[ ]:
%load_ext watermark
%watermark -v -m -p numpy,scipy,pyfar,nbgrader,watermark