sparrowpy.dsp#

Module for filter generation and signal processing in sparrowpy.

This module provides functions to synthesize a room impulse response (IR) from an energy time curve (ETC), e.g. obtained from a sparrowpy radiosity simulation. This method follows [1].

Examples

Synthesize an impulse response from an ETC for the 500Hz, 1kHz and 2kHz octave bands.

>>> import numpy as np
>>> import pyfar as pf
>>> import sparrowpy as sp

Room and simulation parameters.

>>> room_volume = 150  # m^3
>>> speed_of_sound = 343.2  # m/s
>>> sampling_rate = 44100  # Hz
>>> etc_duration = 1  # s
>>> etc_time_resolution = 1 / 1000  # s

Build an example ETC for three frequency bands.

>>> etc_times = np.arange(0, etc_duration, etc_time_resolution)[None]
>>> decays = np.array([-5, -10, -15])[:, None]
>>> etc_data = np.exp(decays * etc_times)
>>> etc = pf.TimeData(etc_data, etc_times)[None]
>>> center_frequencies = np.array([500, 1e3, 2e3])

Generate a dirac sequence based on the room’s reflection density.

>>> n_samples = int(sampling_rate * etc_duration)
>>> reflection_density, t_start = sp.dsp.reflection_density_room(
...     room_volume=room_volume,
...     n_samples=n_samples,
...     speed_of_sound=speed_of_sound,
...     max_reflection_density=int(sampling_rate / 4),
...     sampling_rate=sampling_rate)
>>> dirac_seq = sp.dsp.dirac_sequence(
...     reflection_density, n_samples, t_start,
...     sampling_rate=sampling_rate, seed=0)

Apply bandpass filtering using butterworth filtering.

>>> filtered_dirac_seq, bandwidth = sp.dsp.band_filter_signal(
...     dirac_seq, center_frequencies, 1,
... )

Weight the filtered dirac sequence by the ETC to synthesize the IR.

>>> impulse_response = sp.dsp.weight_signal_by_etc(
...     energy_time_curve=etc,
...     signal=filtered_dirac_seq,
...     bandwidth=bandwidth,
... )

Sum all frequency bands and plot the result.

>>> impulse_response.time = np.sum(impulse_response.time, axis=1)
>>> ax = pf.plot.time_freq(impulse_response, dB_time=True)

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

../_images/sparrowpy-dsp-1.png

References

Functions:

band_filter_signal(signal, frequencies, ...)

Fractional octave band filter input signal and return the respective frequency bandwidths.

dirac_sequence(reflection_density, n_samples)

Dirac sequence based on the reflection density over time.

energy_time_curve_from_impulse_response(signal)

Calculate the energy time curve from impulse responses.

reflection_density_room(room_volume, n_samples)

Calculates the reflection density and starting time in a diffuse room.

weight_signal_by_etc(energy_time_curve, signal)

Weight a signal with a given energy time curve.

sparrowpy.dsp.band_filter_signal(signal: Signal, frequencies: ndarray, num_fractions: int, order=4)[source]#

Fractional octave band filter input signal and return the respective frequency bandwidths.

This method filters an input signal into fractional octave bands with Butterworth filtering.

Note

This function uses the pyfar method pyfar.dsp.filter.butterworth.

Parameters:
  • signal (pyfar.Signal) – Input broad-spectrum signal.

  • frequencies (np.ndarray) – Frequencies in which to filter the signal of shape (n_frequencies) in Hz. The user may input an arbitrary array of frequencies in which to filter the signal. The closest fractional octave bands to the input frequencies will be returned in the same order.

  • num_fractions (int) – The number of bands an octave is divided into. E.g., 1 refers to octave bands and 3 to third octave bands. All positive integers are allowed.

  • order (int, optional) – Butterworth filter order for the signal filtering. By default 4.

Returns:

  • band_filtered_signal (pyfar.Signal) – Band-filtered signal of cshape (signal.cshape + (len(freqs))

  • bandwidth (np.ndarray) – Array of bandwidth values in Hz of the fractional octave bands corresponding to the input frequencies of shape (n_frequencies).

sparrowpy.dsp.dirac_sequence(reflection_density, n_samples, t_start=0, sampling_rate=44100, seed=None)[source]#

Dirac sequence based on the reflection density over time.

The Dirac sequence is generated based on the chapter 5.3.4 of [2].

The time difference between each dirac in the sequence is Poisson distributed and can be calculated based on:

\[\Delta t_a = \frac{1}{\mu} \cdot \ln{\frac{1}{z}}\]

with z being a random number in the range of \(z \in (0, 1]\) and \(\mu\) being the reflection_density over time. Each dirac has an amplitude of 1 or -1, which is chosen randomly with equal probability. The dirac sequence generation starts after \(t_\text{start}\).

Parameters:
  • reflection_density (pyfar.TimeData) – reflection density \(\mu\) in \(1/s^2\) over time. An error is raised if the reflection sensitivity is greater than sampling_rate/2. Schröder suggested a maximum reflection density of sampling_rate/4 \(1/s^2\).

  • n_samples (int) – The length of the dirac sequence in samples.

  • t_start (float) – The dirac sequence generation starts after \(t_\text{start}\) in seconds. The default is 0.

  • sampling_rate (int, optional) – The sampling rate of the dirac sequence in Hz. The default is 44100 Hz.

  • seed (int, None, optional) – The seed for the random generator. Pass a seed to obtain identical results for multiple calls. The default is None, which will yield different results with every call. See numpy.random.default_rng for more information.

Returns:

dirac_sequence – Signal of the generated dirac impulse sequence.

Return type:

pyfar.Signal

References

Examples

Generate a Dirac sequence based on the reflection density of a room with a volume of 5000 m³.

>>> import pyfar as pf
>>> import sparrowpy as sp
>>> n_samples = 22050
>>> reflection_density, t_0 = sp.dsp.reflection_density_room(
...     5000, n_samples, max_reflection_density=5e3)
>>> dirac_sequence = sp.dsp.dirac_sequence(
...     reflection_density, n_samples, t_start=t_0, seed=0)
>>> ax = pf.plot.time(dirac_sequence, linewidth=.5)
>>> ax.set_title("Dirac sequence")

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

../_images/sparrowpy-dsp-2.png

Generate a Dirac sequence based on a constant reflection density.

>>> import pyfar as pf
>>> import numpy as np
>>> import sparrowpy as sp
>>> n_samples = 22050
>>> reflection_density = pf.TimeData(
...     np.ones(n_samples)*100, np.arange(n_samples)/44100)
>>> dirac_sequence = sp.dsp.dirac_sequence(
...     reflection_density, n_samples, t_start=0, seed=0)
>>> ax = pf.plot.time(dirac_sequence, linewidth=.5)
>>> ax.set_title("Dirac sequence")

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

../_images/sparrowpy-dsp-3.png
sparrowpy.dsp.energy_time_curve_from_impulse_response(signal, delta_time=0.01, bandwidth=None)[source]#

Calculate the energy time curve from impulse responses.

\[E_n = \sum_{g(k)}^{g(k+1)} h(i)^2 \cdot \frac{f_s/2}{BW}\]

where \(g(k)=floor(k \cdot f_s \cdot \Delta t)\) representing the range of each energy window with length \(\Delta t\) and \(h(i)\) is the impulse response signal. \(BW\) is the bandwidth of the energy time curve, which is set to half the sampling rate by default.

Parameters:
  • signal (pyfar.Signal) – The impulse responses from which the energy time curve is calculated. The cshape should be (..., n_bands).

  • delta_time (float, optional) – The time resolution of the energy time curve, by default 0.01 seconds.

  • bandwidth (float, array_like, optional) – Bandwidth for each signal channel, by default None, which means its assumed for the full bandwidth \(BW = f_s/2\). The shape should be (n_bands,).

Returns:

etc – The energy time curve of the impulse responses.

Return type:

pyfar.TimeData

Examples

Generate the energy time curve from an impulse for full bandwidth.

>>> import pyfar as pf
>>> import sparrowpy as sp
>>> n_samples = 44100
>>> impulse_response = pf.signals.impulse(n_samples)
>>> etc = sp.dsp.energy_time_curve_from_impulse_response(
...     impulse_response, delta_time=0.01)
>>> ax = pf.plot.time(impulse_response, dB=True)
>>> ax = pf.plot.time(etc, ax=ax, dB=True, log_prefix=10)
>>> ax.set_title("Energy time curve from impulse response")

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

../_images/sparrowpy-dsp-4.png

Generate the energy time curve from octave band filtered white noise.

>>> import pyfar as pf
>>> import sparrowpy as sp
>>> n_samples = 44100
>>> white_noise = pf.signals.noise(n_samples, 'white')
>>> cutoff_freq = pf.dsp.filter.fractional_octave_frequencies(
...     1, (1e3, 20e3), return_cutoff=True)[2]
>>> bw = cutoff_freq[1] - cutoff_freq[0]
>>> filtered_white_noise = pf.dsp.filter.fractional_octave_bands(
...     white_noise, 1, frequency_range=(1e3, 20e3),)
>>> filtered_white_noise.time = np.rollaxis(filtered_white_noise.time,
...     0,-1)
>>> etc = sp.dsp.energy_time_curve_from_impulse_response(
...     filtered_white_noise, 0.01, bw)
>>> ax = pf.plot.time(etc, dB=True, log_prefix=10)
>>> ax.set_title("ETC from octave band filtered white noise")

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

../_images/sparrowpy-dsp-5.png
sparrowpy.dsp.reflection_density_room(room_volume, n_samples, speed_of_sound=None, max_reflection_density=None, sampling_rate=44100)[source]#

Calculates the reflection density and starting time in a diffuse room.

The reflection density and starting time based on the chapter 5.3.4 of [3]. The starting time \(t_\text{start}\) can be calculated based on:

\[t_\text{start} = \left(\frac{2 V \cdot \ln(2)}{4 \pi c^3}\right)^{1/3}\]

where \(V\) is the room volume in \(m^3\) and \(c\) is the speed of sound in the room. The reflection density \(\mu\) is calculated based on the following equation:

\[\mu = \min{\left(\frac{4 \pi c^3 \cdot t^2}{V}, \mu_{max}\right)}\]

with \(t\) being the time vector in seconds based on sampling_rate and n_samples and \(\mu_{max}\) being the maximum reflection density.

Note

This function can be used to generate the Dirac sequence for the room impulse response synthesis using sparrowpy.dsp.dirac_sequence.

Parameters:
  • room_volume (float) – Volume of the room \(V\) in \(m^3\).

  • n_samples (int) – The length of the signal in samples.

  • speed_of_sound (float, None, optional) – Speed of sound in the room. By default, 343.2 m/s is used.

  • max_reflection_density (int, optional) – The maximum reflection density. The default is None, which means that the reflection density is not limited.

  • sampling_rate (int, optional) – The sampling rate in Hz. The default is 44100.

Returns:

  • reflection_density (pyfar.TimeData) – reflection density \(\mu\) in \(1/s^2\) over time.

  • t_start (float) – The dirac sequence generation starts after \(t_\text{start}\).

References

Examples

Generate the reflection densities for a room with a different volumes.

>>> import sparrowpy as sp
>>> import pyfar as pf
>>> n_samples = 8800
>>> sampling_rate = 44100
>>> for v in [100, 500, 1000, 5000]:
>>>     reflection_density, t_0 = sp.dsp.reflection_density_room(
...         v, n_samples, sampling_rate)
>>>     ax = pf.plot.time(
...         reflection_density,
...         label=f"V={v} m$^3$ -> $t_0={t_0*1e3:.1f}$ ms")
>>> ax.legend()
>>> ax.set_title("Reflection density")

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

../_images/sparrowpy-dsp-6.png
sparrowpy.dsp.weight_signal_by_etc(energy_time_curve: TimeData, signal: Signal, bandwidth=None) → Signal[source]#

Weight a signal with a given energy time curve.

The signals are weighed by the respective energy time curve over time after Chapter 5.3.4 of [4]:

\[h_i = \nu_i \cdot \sqrt{\frac{E_n(k)}{\sum^{g(k)}_{g(k-1)+1} \nu_i^2}} \cdot \sqrt{\frac{BW}{f_s/2}}\]

where \(h_i\) and \(\nu_i\) represent respectively the weighted output signal and the input signal at a given time sample \(i\). \(g(k)=\lfloor k \cdot f_s \cdot \Delta t \rfloor\) represents the range of each energy window with given length \(\Delta t\) of the ETC entry \(E(k)\) with index \(k\). \(BW\) is the bandwidth of the energy time curve.

Parameters:
  • energy_time_curve (pyfar.TimeData) – Energy time curve of a sound propagation simulation of cshape (..., n_freq_bands) and broadcastable to signal. The ETC entries must be equally spaced in time.

  • signal (pyfar.Signal) – signal to be weighted by the etc of cshape (..., n_freq_bands) and broadcastable to energy_time_curve.

  • bandwidth (np.ndarray) – Bandwidth for the frequency band in Hz of shape (n_freq_bands). By default, signal will be processed as full spectrum sampling_rate/2.

Returns:

weighted_signal – signal weighted by the energy_time_curve. The cshape matches the cshape of the etc.

Return type:

pyfar.Signal

References

Examples

Weight white noise by a single broadband exponential decay etc.

>>> import pyfar as pf
>>> import sparrowpy as sp
>>> import numpy as np
>>> n_samples = 44100
>>> white_noise = pf.dsp.normalize(pf.signals.noise(n_samples,rms=1))
>>> delta_t = 1/1000
>>> times = np.arange(0,white_noise.times[-1],delta_t)
>>> decay = np.exp(-4*times)
>>> etc = pf.TimeData(data=decay,times=times)
>>> weighted_noise = sp.dsp.weight_signal_by_etc(energy_time_curve=etc,
...                                               signal=white_noise)
>>> ax=pf.plot.time(white_noise,label="input signal",dB=True)
>>> ax=pf.plot.time(weighted_noise,label="weighted signal",
...                 ax=ax,dB=True)
>>> ax.set_title("Signal weighting by exponential decaying ETC")
>>> ax.legend()

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

../_images/sparrowpy-dsp-7.png

Weight white noise channels with varying bandwidths by a constant ETC.

>>> import pyfar as pf
>>> import sparrowpy as sp
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> n_samples = 44100
>>> bandwidth = np.array([2000,1000,500])
>>> white_noise = pf.dsp.normalize(pf.signals.noise(n_samples,rms=1))
>>> white_noise.time = np.repeat(white_noise.time,bandwidth.shape[0],
...                              axis=0)
>>> delta_t = 1/1000
>>> times = np.arange(0,white_noise.times[-1],delta_t)
>>> etc =pf.TimeData(data=np.ones((bandwidth.shape[0],times.shape[0])),
...                  times=times)
>>> weighted_noise_bandwise = sp.dsp.weight_signal_by_etc(
...     energy_time_curve=etc,
...     signal=white_noise,
...     bandwidth=bandwidth,
... )
>>> ax=pf.plot.time(weighted_noise_bandwise,
...              label=[f"{bandwidth[i]}Hz bandwidth" \
...                             for i in range(bandwidth.shape[0])],
...              dB=True)
>>> ax.legend()
>>> ax.set_title("Bandwidth-scaled white noise")

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

../_images/sparrowpy-dsp-8.png

Weight white noise of equal bandwidth by varied exponential decay ETCs.

>>> import pyfar as pf
>>> import sparrowpy as sp
>>> import numpy as np
>>> n_samples = 44100
>>> n_channels = 5
>>> white_noise = pf.signals.noise(
...                     n_samples,
...                     rms=np.ones((n_channels,)),
...                     )
>>> delta_t = 1/1000
>>> times = np.arange(0,white_noise.times[-1],delta_t)
>>> decay = np.empty((n_channels,times.shape[0]))
>>> for i in range(n_channels):
...     decay[i,:] = np.exp(-3*i*times)
>>> etc = pf.TimeData(data=decay,times=times)
>>> weighted_noise_bandwise = sp.dsp.weight_signal_by_etc(
...     energy_time_curve=etc,
...     signal=white_noise,
...     bandwidth=200*np.ones((n_channels,)),
... )
>>> ax=pf.plot.time(
...     weighted_noise_bandwise,
...     label=[f"exp(-{i*3}t) decay" for i in range(n_channels)],
...     )
>>> ax.legend()
>>> ax.set_title(
...     "Multiple white noise channels weighted by independent ETCs"
...     )

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

../_images/sparrowpy-dsp-9.png