Skip to content

Signal Class

Bases: ndarray

A signal consisting of samples (array) and a sample frequency (float).

ATTRIBUTE DESCRIPTION
fs

Sample frequency.

samples

Amount of samples in signal.

channels

Amount of channels in signal.

duration

Duration of signal in seconds.

TYPE: float

values

Values of signal as instance of np.ndarray.

TYPE: ndarray

Attributes

samples property

samples

Amount of samples in signal.

channels property

channels

Amount of channels.

duration property

duration: float

Duration of signal in seconds.

values property

values: ndarray

Return the values of this signal as an instance of np.ndarray.

Functions

__new__

__new__(data, fs)

Create a new signal.

PARAMETER DESCRIPTION
data

Signal values.

fs

Sample frequency.

Source code in acoustic_toolbox/_signal.py
def __new__(cls, data, fs):
    """Create a new signal.

    Args:
        data: Signal values.
        fs: Sample frequency.
    """
    obj = np.asarray(data).view(cls)
    obj.fs = fs
    return obj

calibrate_to

calibrate_to(decibel, inplace: bool = False) -> Signal

Calibrate signal to value decibel.

Tip

Values of decibel are broadcasted. To set a value per channel, use decibel[...,None].

PARAMETER DESCRIPTION
decibel

Value to calibrate to.

inplace

Whether to perform inplace or not.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

Calibrated signal.

Source code in acoustic_toolbox/_signal.py
def calibrate_to(self, decibel, inplace: bool = False) -> Signal:
    """Calibrate signal to value `decibel`.

    Tip:
        Values of `decibel` are broadcasted. To set a value per channel, use `decibel[...,None]`.

    Args:
        decibel: Value to calibrate to.
        inplace: Whether to perform inplace or not.

    Returns:
        Calibrated signal.
    """
    decibel = decibel * np.ones(self.shape)
    gain = decibel - self.leq()[..., None]
    return self.gain(gain, inplace=inplace)

calibrate_with

calibrate_with(
    other: Signal, decibel, inplace: bool = False
) -> Signal

Calibrate signal with other signal.

PARAMETER DESCRIPTION
other

Other signal/array.

TYPE: Signal

decibel

Signal level of other.

inplace

Whether to perform inplace or not.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

Calibrated signal.

Source code in acoustic_toolbox/_signal.py
def calibrate_with(self, other: Signal, decibel, inplace: bool = False) -> Signal:
    """Calibrate signal with other signal.

    Args:
      other: Other signal/array.
      decibel: Signal level of `other`.
      inplace: Whether to perform inplace or not.

    Returns:
      Calibrated signal.
    """
    if not isinstance(other, Signal):
        other = Signal(other, self.fs)
    gain = decibel - other.leq()
    return self.gain(gain, inplace=inplace)

decimate

decimate(
    factor, zero_phase=False, ftype="iir", order=None
) -> Signal

Decimate signal by integer factor. Before downsampling a low-pass filter is applied.

PARAMETER DESCRIPTION
factor

Downsampling factor.

zero_phase

Prevent phase shift by filtering with filtfilt instead of lfilter.

DEFAULT: False

ftype

Filter type.

DEFAULT: 'iir'

order

Filter order.

DEFAULT: None

RETURNS DESCRIPTION
Signal

Decimated signal.

.. seealso:: :func:scipy.signal.decimate .. seealso:: :meth:resample: Decimated signal.

Source code in acoustic_toolbox/_signal.py
def decimate(self, factor, zero_phase=False, ftype="iir", order=None) -> Signal:
    """Decimate signal by integer `factor`. Before downsampling a low-pass filter is applied.

    Args:
        factor: Downsampling factor.
        zero_phase: Prevent phase shift by filtering with ``filtfilt`` instead of ``lfilter``.
        ftype: Filter type.
        order: Filter order.

    Returns:
        Decimated signal.

    .. seealso:: :func:`scipy.signal.decimate`
    .. seealso:: :meth:`resample`: Decimated signal.

    """
    return Signal(
        signal.decimate(
            x=self, q=factor, n=order, ftype=ftype, zero_phase=zero_phase
        ),
        self.fs / factor,
    )

resample

resample(
    nsamples, times=None, axis=-1, window=None
) -> Signal

Resample signal.

Tip

You might want to low-pass filter this signal before resampling.

PARAMETER DESCRIPTION
samples

New amount of samples.

times

Times corresponding to samples.

DEFAULT: None

axis

Axis.

DEFAULT: -1

window

Window.

DEFAULT: None

RETURNS DESCRIPTION
Signal

Resampled signal.

See Also: - scipy.signal.resample - decimate

Source code in acoustic_toolbox/_signal.py
def resample(self, nsamples, times=None, axis=-1, window=None) -> Signal:
    """Resample signal.

    Tip:
        You might want to low-pass filter this signal before resampling.

    Args:
      samples: New amount of samples.
      times: Times corresponding to samples.
      axis: Axis.
      window: Window.

    Returns:
        Resampled signal.
    See Also:
        - [`scipy.signal.resample`][scipy.signal.resample]
        - [`decimate`][acoustic_toolbox._signal.Signal.decimate]

    """
    return Signal(
        resample(self, nsamples, times, axis, window),
        nsamples / self.samples * self.fs,
    )

upsample

upsample(factor: int, axis: int = -1) -> Signal

Upsample signal with integer factor.

PARAMETER DESCRIPTION
factor

Upsample factor.

TYPE: int

axis

Axis.

TYPE: int DEFAULT: -1

See Also
Source code in acoustic_toolbox/_signal.py
def upsample(self, factor: int, axis: int = -1) -> Signal:
    """Upsample signal with integer factor.

    Args:
      factor: Upsample factor.
      axis: Axis.

    See Also:
        - [`resample`][acoustic_toolbox._signal.Signal.resample]
    """
    return self.resample(int(self.samples * factor), axis=axis)

gain

gain(decibel, inplace: bool = False) -> Signal

Apply gain of decibel decibels.

PARAMETER DESCRIPTION
decibel

Decibels

inplace

In place

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

Amplified signal.

Source code in acoustic_toolbox/_signal.py
def gain(self, decibel, inplace: bool = False) -> Signal:
    """Apply gain of `decibel` decibels.

    Args:
      decibel: Decibels
      inplace: In place

    Returns:
      Amplified signal.

    """
    factor = 10.0 ** (decibel / 20.0)
    if inplace:
        self *= factor
        return self
    else:
        return self * factor

pick

pick(
    start: float = 0.0, stop: float | None = None
) -> Signal

Get signal from start time to stop time.

PARAMETER DESCRIPTION
start

Start time.

TYPE: float DEFAULT: 0.0

stop

End time.

TYPE: float | None DEFAULT: None

RETURNS DESCRIPTION
Signal

Selected part of the signal.

Source code in acoustic_toolbox/_signal.py
def pick(self, start: float = 0.0, stop: float | None = None) -> Signal:
    """Get signal from start time to stop time.

    Args:
      start: Start time.
      stop: End time.

    Returns:
      Selected part of the signal.

    """
    if start is not None:
        start = int(np.floor(start * self.fs))
    if stop is not None:
        stop = int(np.floor(stop * self.fs))
    return self[..., start:stop]

times

times() -> ndarray

Time vector.

RETURNS DESCRIPTION
ndarray

A vector with a timestamp for each sample.

Source code in acoustic_toolbox/_signal.py
def times(self) -> np.ndarray:
    """Time vector.

    Returns:
      A vector with a timestamp for each sample.

    """
    return np.arange(0, self.samples) / self.fs

energy

energy() -> ndarray

Signal energy.

RETURNS DESCRIPTION
ndarray

Total energy per channel.

ndarray

$$

ndarray

E = \sum_{n=0}^{N-1} |x_n|^2

ndarray

$$

Source code in acoustic_toolbox/_signal.py
def energy(self) -> np.ndarray:
    r"""Signal energy.

    Returns:
        Total energy per channel.

        $$
        E = \sum_{n=0}^{N-1} |x_n|^2
        $$

    """
    return float((self * self).sum())

power

power()

Signal power.

\[ P = \frac{1}{N} \sum_{n=0}^{N-1} |x_n|^2 \]
Source code in acoustic_toolbox/_signal.py
def power(self):
    r"""Signal power.

    $$
    P = \frac{1}{N} \sum_{n=0}^{N-1} |x_n|^2
    $$
    """
    return self.energy() / len(self)

ms

ms()

Mean value squared of signal.

See Also

acoustic_toolbox.signal.ms

Source code in acoustic_toolbox/_signal.py
def ms(self):
    """Mean value squared of signal.

    See Also:
        [`acoustic_toolbox.signal.ms`][acoustic_toolbox._signal.Signal.ms]
    """
    return signal.ms(self)

rms

rms()

Root mean squared of signal.

See Also

acoustic_toolbox.signal.rms

Source code in acoustic_toolbox/_signal.py
def rms(self):
    """Root mean squared of signal.

    See Also:
        [`acoustic_toolbox.signal.rms`][acoustic_toolbox._signal.Signal.rms]
    """
    return signal.rms(self)

weigh

weigh(
    weighting: str = "A", zero_phase: bool = False
) -> Signal

Apply frequency-weighting. By default 'A'-weighting is applied.

Note

By default the weighting filter is applied in the time domain using scipy.signal.sosfilt causing a frequency-dependent delay.

In case a delay is undesired, the filter can be applied in the frequency domain using [scipy.signal.fft][] by setting zero_phase=True.

PARAMETER DESCRIPTION
weighting

Frequency-weighting filter to apply. Valid options are 'A', 'C' and 'Z'. Default weighting is 'A'.

TYPE: str DEFAULT: 'A'

zero_phase

Prevent phase shift by filtering with fft instead of sosfilt.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

Weighted signal.

Source code in acoustic_toolbox/_signal.py
def weigh(self, weighting: str = "A", zero_phase: bool = False) -> Signal:
    """Apply frequency-weighting. By default 'A'-weighting is applied.

    Note:
        By default the weighting filter is applied in the time domain using
        [`scipy.signal.sosfilt`][scipy.signal.sosfilt] causing a frequency-dependent delay.

        In case a delay is undesired, the filter can be applied in the frequency domain using
        [`scipy.signal.fft`][scipy.signal.fft] by setting `zero_phase=True`.

    Args:
        weighting: Frequency-weighting filter to apply.
                   Valid options are 'A', 'C' and 'Z'. Default weighting is 'A'.
        zero_phase: Prevent phase shift by filtering with ``fft`` instead of ``sosfilt``.

    Returns:
        Weighted signal.
    """
    return self._construct(
        frequency_weighting(
            self, self.fs, weighting=weighting, zero_phase=zero_phase
        )
    )

correlate

correlate(other: Signal | None = None, mode: str = 'full')

Correlate signal with other signal. In case other==None this method returns the autocorrelation.

PARAMETER DESCRIPTION
other

Other signal.

TYPE: Signal | None DEFAULT: None

mode

Mode.

TYPE: str DEFAULT: 'full'

RAISES DESCRIPTION
ValueError

If sample frequencies are not the same.

ValueError

If not supported for multichannel signals.

See Also
Source code in acoustic_toolbox/_signal.py
def correlate(self, other: Signal | None = None, mode: str = "full"):
    """Correlate signal with `other` signal. In case `other==None` this
    method returns the autocorrelation.

    Args:
      other: Other signal.
      mode: Mode.

    Raises:
        ValueError: If sample frequencies are not the same.
        ValueError: If not supported for multichannel signals.

    See Also:
        - [`np.correlate`][numpy.correlate]
        - [`scipy.signal.fftconvolve`][scipy.signal.fftconvolve]
    """
    if other is None:
        other = self
    if self.fs != other.fs:
        raise ValueError("Cannot correlate. Sample frequencies are not the same.")
    if self.channels > 1 or other.channels > 1:
        raise ValueError(
            "Cannot correlate. Not supported for multichannel signals."
        )
    return self._construct(fftconvolve(self, other[::-1], mode=mode))

amplitude_envelope

amplitude_envelope() -> Signal

Amplitude envelope.

RETURNS DESCRIPTION
Signal

Amplitude envelope.

See Also
Source code in acoustic_toolbox/_signal.py
def amplitude_envelope(self) -> Signal:
    """Amplitude envelope.

    Returns:
        Amplitude envelope.

    See Also:
        - [`acoustic_toolbox.signal.amplitude_envelope`][acoustic_toolbox._signal.Signal.amplitude_envelope]

    """
    return self._construct(signal.amplitude_envelope(self, self.fs))

instantaneous_frequency

instantaneous_frequency() -> Signal

Instantaneous frequency.

RETURNS DESCRIPTION
Signal

Instantaneous frequency of signal

See Also
Source code in acoustic_toolbox/_signal.py
def instantaneous_frequency(self) -> Signal:
    """Instantaneous frequency.

    Returns:
        Instantaneous frequency of signal

    See Also:
        - [`acoustic_toolbox.signal.instantaneous_frequency`][acoustic_toolbox._signal.Signal.instantaneous_frequency]


    """
    return self._construct(signal.instantaneous_frequency(self, self.fs))

instantaneous_phase

instantaneous_phase() -> Signal

Instantaneous phase.

RETURNS DESCRIPTION
Signal

Instantaneous phase of signal

See Also
Source code in acoustic_toolbox/_signal.py
def instantaneous_phase(self) -> Signal:
    """Instantaneous phase.

    Returns:
        Instantaneous phase of signal

    See Also:
        - [`acoustic_toolbox.signal.instantaneous_phase`][acoustic_toolbox._signal.Signal.instantaneous_phase]
    """
    return self._construct(signal.instantaneous_phase(self, self.fs))

detrend

detrend(**kwargs) -> Signal

Detrend signal.

PARAMETER DESCRIPTION
**kwargs

DEFAULT: {}

RETURNS DESCRIPTION
Signal

Detrended signal.

See Also
Source code in acoustic_toolbox/_signal.py
def detrend(self, **kwargs) -> Signal:
    """Detrend signal.

    Args:
        **kwargs:

    Returns:
        Detrended signal.

    See Also:
        - [`scipy.signal.detrend`][scipy.signal.detrend]

    """
    return self._construct(detrend(self, **kwargs))

unwrap

unwrap() -> Signal

Unwrap signal in case the signal represents wrapped phase.

RETURNS DESCRIPTION
Signal

Unwrapped signal.

See Also
Source code in acoustic_toolbox/_signal.py
def unwrap(self) -> Signal:
    """Unwrap signal in case the signal represents wrapped phase.

    Returns:
        Unwrapped signal.

    See Also:
        - [`np.unwrap`][numpy.unwrap]
    """
    return self._construct(np.unwrap(self))

complex_cepstrum

complex_cepstrum(
    N: int | None = None,
) -> tuple[ndarray, ndarray, int]

Complex cepstrum.

PARAMETER DESCRIPTION
N

Amount of bins.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
ndarray

Quefrency

ndarray

Complex cepstrum

int

Delay in amount of samples.

See Also
Source code in acoustic_toolbox/_signal.py
def complex_cepstrum(
    self, N: int | None = None
) -> tuple[np.ndarray, np.ndarray, int]:
    """Complex cepstrum.

    Args:
        N: Amount of bins.

    Returns:
        Quefrency
        Complex cepstrum
        Delay in amount of samples.

    See Also:
        - [`acoustic_toolbox.cepstrum.complex_cepstrum`][acoustic_toolbox._signal.Signal.complex_cepstrum]

    """
    if N is not None:
        times = np.linspace(0.0, self.duration, N, endpoint=False)
    else:
        times = self.times()
    cepstrum, ndelay = complex_cepstrum(self, n=N)
    return times, cepstrum, ndelay

real_cepstrum

real_cepstrum(N=None)

Real cepstrum.

PARAMETER DESCRIPTION
N

Amount of bins.

DEFAULT: None

RETURNS DESCRIPTION

Quefrency

Real cepstrum.

See Also
Source code in acoustic_toolbox/_signal.py
def real_cepstrum(self, N=None):
    """Real cepstrum.

    Args:
      N: Amount of bins.

    Returns:
      Quefrency
      Real cepstrum.

    See Also:
        - [`acoustic_toolbox.cepstrum.real_cepstrum`][acoustic_toolbox._signal.Signal.real_cepstrum]

    """
    if N is not None:
        times = np.linspace(0.0, self.duration, N, endpoint=False)
    else:
        times = self.times()
    return times, real_cepstrum(self, n=N)

power_spectrum

power_spectrum(N: int | None = None)

Power spectrum.

PARAMETER DESCRIPTION
N

Amount of bins.

TYPE: int | None DEFAULT: None

See Also
Source code in acoustic_toolbox/_signal.py
def power_spectrum(self, N: int | None = None):
    """Power spectrum.

    Args:
        N: Amount of bins.

    See Also:
        - [`acoustic_toolbox.signal.power_spectrum`][acoustic_toolbox._signal.Signal.power_spectrum]
    """
    return signal.power_spectrum(self, self.fs, N=N)

angle_spectrum

angle_spectrum(N: int | None = None)

Phase angle spectrum. Wrapped.

PARAMETER DESCRIPTION
N

amount of bins.

TYPE: int | None DEFAULT: None

See Also
Source code in acoustic_toolbox/_signal.py
def angle_spectrum(self, N: int | None = None):
    """Phase angle spectrum. Wrapped.

    Args:
      N: amount of bins.

    See Also:
        - [`acoustic_toolbox.signal.angle_spectrum`][acoustic_toolbox._signal.Signal.angle_spectrum]
        - [`acoustic_toolbox.signal.phase_spectrum`][acoustic_toolbox._signal.Signal.phase_spectrum]
        - [`phase_spectrum`][acoustic_toolbox._signal.Signal.phase_spectrum]
    """
    return signal.angle_spectrum(self, self.fs, N=N)

phase_spectrum

phase_spectrum(N=None)

Phase spectrum. Unwrapped.

PARAMETER DESCRIPTION
N

Amount of bins.

DEFAULT: None

See Also
Source code in acoustic_toolbox/_signal.py
def phase_spectrum(self, N=None):
    """Phase spectrum. Unwrapped.

    Args:
      N: Amount of bins.

    See Also:
        - [`acoustic_toolbox.signal.phase_spectrum`][acoustic_toolbox._signal.Signal.phase_spectrum]
        - [`acoustic_toolbox.signal.angle_spectrum`][acoustic_toolbox._signal.Signal.angle_spectrum]
        - [`angle_spectrum`][acoustic_toolbox._signal.Signal.angle_spectrum]
    """
    return signal.phase_spectrum(self, self.fs, N=N)

peak

peak(axis=-1)

Peak sound pressure.

PARAMETER DESCRIPTION
axis

Axis.

DEFAULT: -1

See Also
Source code in acoustic_toolbox/_signal.py
def peak(self, axis=-1):
    """Peak sound pressure.

    Args:
      axis: Axis.

    See Also:
        - [`acoustic_toolbox.standards.iso_tr_25417_2007.peak_sound_pressure`][acoustic_toolbox.standards.iso_tr_25417_2007.peak_sound_pressure]
    """
    return standards.iso_tr_25417_2007.peak_sound_pressure(self, axis=axis)

peak_level

peak_level(axis=-1)

Peak sound pressure level.

PARAMETER DESCRIPTION
axis

Axis.

DEFAULT: -1

See Also
Source code in acoustic_toolbox/_signal.py
def peak_level(self, axis=-1):
    """Peak sound pressure level.

    Args:
      axis: Axis.

    See Also:
        - [`acoustic_toolbox.standards.iso_tr_25417_2007.peak_sound_pressure_level`][acoustic_toolbox.standards.iso_tr_25417_2007.peak_sound_pressure_level]
    """
    return standards.iso_tr_25417_2007.peak_sound_pressure_level(self, axis=axis)

min

min(axis=-1)

Return the minimum along a given axis.

PARAMETER DESCRIPTION
axis

Axis.

DEFAULT: -1

See Also
  • Refer to np.amin for full documentation.
Source code in acoustic_toolbox/_signal.py
def min(self, axis=-1):
    """Return the minimum along a given axis.

    Args:
      axis: Axis.

    See Also:
        - Refer to [`np.amin`][numpy.amin] for full documentation.
    """
    return np.ndarray.min(self, axis=axis)

max

max(axis=-1)

Return the maximum along a given axis.

PARAMETER DESCRIPTION
axis

Axis.

DEFAULT: -1

See Also
  • Refer to np.amax for full documentation.
Source code in acoustic_toolbox/_signal.py
def max(self, axis=-1):
    """Return the maximum along a given axis.

    Args:
      axis: Axis.

    See Also:
        - Refer to [`np.amax`][numpy.amax] for full documentation.
    """
    return np.ndarray.max(self, axis=axis)

max_level

max_level(axis=-1)

Maximum sound pressure level.

PARAMETER DESCRIPTION
axis

Axis.

DEFAULT: -1

See Also
Source code in acoustic_toolbox/_signal.py
def max_level(self, axis=-1):
    """Maximum sound pressure level.

    Args:
      axis: Axis.

    See Also:
        - [`acoustic_toolbox.standards.iso_tr_25417_2007.max_sound_pressure_level`][acoustic_toolbox.standards.iso_tr_25417_2007.max_sound_pressure_level]
    """
    return standards.iso_tr_25417_2007.max_sound_pressure_level(self, axis=axis)

sound_exposure

sound_exposure(axis=-1)

Sound exposure.

PARAMETER DESCRIPTION
axis

Axis.

DEFAULT: -1

See Also
Source code in acoustic_toolbox/_signal.py
def sound_exposure(self, axis=-1):
    """Sound exposure.

    Args:
      axis: Axis.

    See Also:
        - [`acoustic_toolbox.standards.iso_tr_25417_2007.sound_exposure`][acoustic_toolbox.standards.iso_tr_25417_2007.sound_exposure]
    """
    return standards.iso_tr_25417_2007.sound_exposure(self, self.fs, axis=axis)

sound_exposure_level

sound_exposure_level(axis=-1)

Sound exposure level.

PARAMETER DESCRIPTION
axis

Axis.

DEFAULT: -1

See Also
Source code in acoustic_toolbox/_signal.py
def sound_exposure_level(self, axis=-1):
    """Sound exposure level.

    Args:
      axis: Axis.

    See Also:
        - [`acoustic_toolbox.standards.iso_tr_25417_2007.sound_exposure_level`][acoustic_toolbox.standards.iso_tr_25417_2007.sound_exposure_level]
    """
    return standards.iso_tr_25417_2007.sound_exposure_level(
        self, self.fs, axis=axis
    )

plot_complex_cepstrum

plot_complex_cepstrum(N: int | None = None, **kwargs)

Plot complex cepstrum of signal.

PARAMETER DESCRIPTION
N

Amount of bins.

TYPE: int | None DEFAULT: None

**kwargs

DEFAULT: {}

Valid kwargs:

PARAMETER DESCRIPTION
xscale

X-axis scale.

yscale

Y-axis scale.

xlim

X-axis limits.

ylim

Y-axis limits.

frequency

Boolean indicating whether the x-axis should show time in seconds or quefrency

TYPE: bool

xlabel_frequency

Label in case frequency is shown.

Source code in acoustic_toolbox/_signal.py
def plot_complex_cepstrum(self, N: int | None = None, **kwargs):
    """Plot complex cepstrum of signal.

    Args:
      N: Amount of bins.
      **kwargs:

    **Valid kwargs:**

    Other Args:
        xscale: X-axis scale.
        yscale: Y-axis scale.
        xlim: X-axis limits.
        ylim: Y-axis limits.
        frequency (bool): Boolean indicating whether the x-axis should show time in seconds or quefrency
        xlabel_frequency: Label in case frequency is shown.
    """
    params = {
        "xscale": "linear",
        "yscale": "linear",
        "xlabel": "$t$ in s",
        "ylabel": "$C$",
        "title": "Complex cepstrum",
        "frequency": False,
        "xlabel_frequency": "$f$ in Hz",
    }
    params.update(kwargs)

    t, ceps, _ = self.complex_cepstrum(N=N)
    if params["frequency"]:
        t = 1.0 / t
        params["xlabel"] = params["xlabel_frequency"]
        t = t[::-1]
        ceps = ceps[::-1]
    return _base_plot(t, ceps, params)

plot_real_cepstrum

plot_real_cepstrum(N: int | None = None, **kwargs)

Plot real cepstrum of signal.

PARAMETER DESCRIPTION
N

Amount of bins.

TYPE: int | None DEFAULT: None

**kwargs

DEFAULT: {}

Valid kwargs:

PARAMETER DESCRIPTION
xscale

X-axis scale.

yscale

Y-axis scale.

xlim

X-axis limits.

ylim

Y-axis limits.

frequency

Boolean indicating whether the x-axis should show time in seconds or quefrency

TYPE: bool

xlabel_frequency

Label in case frequency is shown.

Source code in acoustic_toolbox/_signal.py
def plot_real_cepstrum(self, N: int | None = None, **kwargs):
    """Plot real cepstrum of signal.

    Args:
      N: Amount of bins.
      **kwargs:

    **Valid kwargs:**

    Other Args:
        xscale: X-axis scale.
        yscale: Y-axis scale.
        xlim: X-axis limits.
        ylim: Y-axis limits.
        frequency (bool): Boolean indicating whether the x-axis should show time in seconds or quefrency
        xlabel_frequency: Label in case frequency is shown.
    """
    params = {
        "xscale": "linear",
        "yscale": "linear",
        "xlabel": "$t$ in s",
        "ylabel": "$C$",
        "title": "Real cepstrum",
        "frequency": False,
        "xlabel_frequency": "$f$ in Hz",
    }
    params.update(kwargs)

    t, ceps = self.real_cepstrum(N=N)
    if params["frequency"]:
        t = 1.0 / t
        params["xlabel"] = params["xlabel_frequency"]
        t = t[::-1]
        ceps = ceps[::-1]
    return _base_plot(t, ceps, params)

plot_power_spectrum

plot_power_spectrum(N=None, **kwargs)

Plot spectrum of signal.

PARAMETER DESCRIPTION
N

Amount of bins.

DEFAULT: None

**kwargs

DEFAULT: {}

Valid kwargs:

PARAMETER DESCRIPTION
xscale

X-axis scale.

yscale

Y-axis scale.

xlim

X-axis limits.

ylim

Y-axis limits.

reference

Reference power

See Also
Source code in acoustic_toolbox/_signal.py
def plot_power_spectrum(self, N=None, **kwargs):  # filename=None, scale='log'):
    """Plot spectrum of signal.

    Args:
      N: Amount of bins.
      **kwargs:

    **Valid kwargs:**

    Other Args:
        xscale: X-axis scale.
        yscale: Y-axis scale.
        xlim: X-axis limits.
        ylim: Y-axis limits.
        reference: Reference power

    See Also:
        - [`acoustic_toolbox.signal.power_spectrum`][acoustic_toolbox._signal.Signal.power_spectrum]
    """
    params = {
        "xscale": "log",
        "yscale": "linear",
        "xlabel": "$f$ in Hz",
        "ylabel": "$L_{p}$ in dB",
        "title": "SPL",
        "reference": REFERENCE_PRESSURE**2.0,
    }
    params.update(kwargs)

    f, o = self.power_spectrum(N=N)
    return _base_plot(f, 10.0 * np.log10(o / params["reference"]), params)

plot_angle_spectrum

plot_angle_spectrum(N: int | None = None, **kwargs)

Plot phase angle spectrum of signal. Wrapped.

PARAMETER DESCRIPTION
N

Amount of bins.

TYPE: int | None DEFAULT: None

**kwargs

DEFAULT: {}

Valid kwargs:

PARAMETER DESCRIPTION
xscale

X-axis scale.

yscale

Y-axis scale.

xlim

X-axis limits.

ylim

Y-axis limits.

reference

Reference power

Source code in acoustic_toolbox/_signal.py
def plot_angle_spectrum(self, N: int | None = None, **kwargs):
    """Plot phase angle spectrum of signal. Wrapped.

    Args:
      N: Amount of bins.
      **kwargs:

    **Valid kwargs:**

    Other Args:
        xscale: X-axis scale.
        yscale: Y-axis scale.
        xlim: X-axis limits.
        ylim: Y-axis limits.
        reference: Reference power
    """
    params = {
        "xscale": "linear",
        "yscale": "linear",
        "xlabel": "$f$ in Hz",
        "ylabel": r"$\angle \phi$",
        "title": "Phase response (wrapped)",
    }
    params.update(kwargs)
    f, o = self.angle_spectrum(N=N)
    return _base_plot(f, o, params)

plot_phase_spectrum

plot_phase_spectrum(N: int | None = None, **kwargs)

Plot phase spectrum of signal. Unwrapped.

PARAMETER DESCRIPTION
N

Amount of bins.

TYPE: int | None DEFAULT: None

**kwargs

DEFAULT: {}

Valid kwargs:

PARAMETER DESCRIPTION
xscale

X-axis scale.

yscale

Y-axis scale.

xlim

X-axis limits.

ylim

Y-axis limits.

reference

Reference power

Source code in acoustic_toolbox/_signal.py
def plot_phase_spectrum(self, N: int | None = None, **kwargs):
    """Plot phase spectrum of signal. Unwrapped.

    Args:
      N: Amount of bins.
      **kwargs:

    **Valid kwargs:**

    Other Args:
        xscale: X-axis scale.
        yscale: Y-axis scale.
        xlim: X-axis limits.
        ylim: Y-axis limits.
        reference: Reference power
    """
    params = {
        "xscale": "linear",
        "yscale": "linear",
        "xlabel": "$f$ in Hz",
        "ylabel": r"$\angle \phi$",
        "title": "Phase response (unwrapped)",
    }
    params.update(kwargs)
    f, o = self.phase_spectrum(N=N)
    return _base_plot(f, o, params)

spectrogram

spectrogram(**kwargs)

Spectrogram of signal.

RETURNS DESCRIPTION

Time

Frequency

Power

See Also

See scipy.signal.spectrogram. Some of the default values have been changed. The generated spectrogram consists by default of complex values.

Source code in acoustic_toolbox/_signal.py
def spectrogram(self, **kwargs):
    """Spectrogram of signal.

    Returns:
      Time
      Frequency
      Power

    See Also:
        See [`scipy.signal.spectrogram`][scipy.signal.spectrogram]. Some of the default values have been changed.
        The generated spectrogram consists by default of complex values.

    """
    params = {
        "nfft": 4096,
        "noverlap": 128,
        "mode": "complex",
    }
    params.update(kwargs)

    t, s, P = spectrogram(self, fs=self.fs, **params)

    return t, s, P

plot_spectrogram

plot_spectrogram(**kwargs)

Plot spectrogram of the signal.

Note

This method only works for a single channel.

Valid kwargs:

PARAMETER DESCRIPTION
xlim

X-axis limits.

ylim

Y-axis limits.

clim

Color limits.

NFFT

Amount of FFT bins.

noverlap

Amount of overlap between FFT bins.

title

Title.

xlabel

X-axis label.

ylabel

Y-axis label.

clabel

Color label.

colorbar

Whether to show the colorbar.

Source code in acoustic_toolbox/_signal.py
def plot_spectrogram(self, **kwargs):
    """Plot spectrogram of the signal.

    Note:
        This method only works for a single channel.

    **Valid kwargs:**

    Other Args:
        xlim: X-axis limits.
        ylim: Y-axis limits.
        clim: Color limits.
        NFFT: Amount of FFT bins.
        noverlap: Amount of overlap between FFT bins.
        title: Title.
        xlabel: X-axis label.
        ylabel: Y-axis label.
        clabel: Color label.
        colorbar: Whether to show the colorbar.
    """
    # TODO: use `spectrogram`.
    params = {
        "xlim": None,
        "ylim": None,
        "clim": None,
        "NFFT": 4096,
        "noverlap": 128,
        "title": "Spectrogram",
        "xlabel": "$t$ in s",
        "ylabel": "$f$ in Hz",
        "clabel": "SPL in dB",
        "colorbar": True,
    }
    params.update(kwargs)

    if self.channels > 1:
        raise ValueError(
            "Cannot plot spectrogram of multichannel signal. Please select a single channel."
        )

    # Check if an axes object is passed in. Otherwise, create one.
    ax0 = params.get("ax", plt.figure().add_subplot(111))
    ax0.set_title(params["title"])

    data = np.squeeze(self)
    try:
        _, _, _, im = ax0.specgram(
            data,
            Fs=self.fs,
            noverlap=params["noverlap"],
            NFFT=params["NFFT"],
            mode="magnitude",
            scale_by_freq=False,
        )
    except AttributeError:
        raise NotImplementedError(
            "Your version of matplotlib is incompatible due to lack of support of the mode keyword argument to matplotlib.mlab.specgram."
        )

    if params["colorbar"]:
        cb = ax0.get_figure().colorbar(mappable=im)
        cb.set_label(params["clabel"])

    ax0.set_xlim(params["xlim"])
    ax0.set_ylim(params["ylim"])
    im.set_clim(params["clim"])

    ax0.set_xlabel(params["xlabel"])
    ax0.set_ylabel(params["ylabel"])

    return ax0

fast_levels

fast_levels(integration_time: float = 0.125)

Calculate the FAST time weighted level as every integration_time seconds.

PARAMETER DESCRIPTION
integration_time

timestep for the output. Default value is 0.125 second (FAST) but can set to other values if desired.

TYPE: float DEFAULT: 0.125

RETURNS DESCRIPTION

sound pressure level as function of time.

See Also
  • [acoustic_toolbox.standards.iec_61672_1_2013.time_averaged_sound_level][]
  • [acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_sound_level][]
Source code in acoustic_toolbox/_signal.py
def fast_levels(self, integration_time: float = 0.125):
    """Calculate the FAST time weighted level as every `integration_time` seconds.

    Args:
        integration_time: timestep for the output. Default value is 0.125 second (FAST) but can set to other values if desired.

    Returns:
        sound pressure level as function of time.

    See Also:
        - [`acoustic_toolbox.standards.iec_61672_1_2013.time_averaged_sound_level`][acoustic_toolbox.standards.iec_61672_1_2013.time_averaged_sound_level]
        - [`acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_sound_level`][acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_sound_level]

    """
    return standards.iec_61672_1_2013.time_weighted_level(
        self.values, self.fs, time_mode="fast", integration_time=integration_time
    )

slow_levels

slow_levels(integration_time: float = 1.0)

Calculate the SLOW time weighted level as every integration_time seconds.

PARAMETER DESCRIPTION
integration_time

Averaging time constant. Default value is 1.0 second.

TYPE: float DEFAULT: 1.0

Returns: sound pressure level as function of time.

See Also
Source code in acoustic_toolbox/_signal.py
def slow_levels(self, integration_time: float = 1.0):
    """Calculate the SLOW time weighted level as every `integration_time` seconds.

    Args:
        integration_time: Averaging time constant. Default value is 1.0 second.
    Returns:
        sound pressure level as function of time.

    See Also:
        - [`acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_level`][acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_level]

    """
    return standards.iec_61672_1_2013.time_weighted_level(
        self.values, self.fs, time_mode="slow", integration_time=integration_time
    )

leq_levels

leq_levels(integration_time: float = 1.0)

Calculate the equivalent level (leq) as every integration_time seconds.

PARAMETER DESCRIPTION
integration_time

timestep for the output. Default value is 1.0 second but can set to other values if desired.

TYPE: float DEFAULT: 1.0

RETURNS DESCRIPTION

sound pressure level as function of time.

See Also
Source code in acoustic_toolbox/_signal.py
def leq_levels(self, integration_time: float = 1.0):
    """Calculate the equivalent level (leq) as every `integration_time` seconds.

    Args:
        integration_time: timestep for the output. Default value is 1.0 second but can set to other values if desired.

    Returns:
        sound pressure level as function of time.

    See Also:
        - [`acoustic_toolbox.standards.iec_61672_1_2013.time_averaged_level`][acoustic_toolbox.standards.iec_61672_1_2013.time_averaged_level]

    """
    return standards.iec_61672_1_2013.time_averaged_level(
        self.values, self.fs, integration_time=integration_time
    )

levels

levels(time: float = 0.125, method: str = 'average')

Calculate sound pressure level as function of time.

PARAMETER DESCRIPTION
time

Averaging time or integration time constant. Default value is 0.125 corresponding to FAST.

TYPE: float DEFAULT: 0.125

method

Use time average or time weighting.

TYPE: str DEFAULT: 'average'

RETURNS DESCRIPTION

sound pressure level as function of time.

See Also
Source code in acoustic_toolbox/_signal.py
def levels(self, time: float = 0.125, method: str = "average"):
    """Calculate sound pressure level as function of time.

    Args:
        time: Averaging time or integration time constant. Default value is 0.125 corresponding to FAST.
        method: Use time `average` or time `weighting`.

    Returns:
        sound pressure level as function of time.

    See Also:
        - [`acoustic_toolbox.standards.iec_61672_1_2013.time_averaged_level`][acoustic_toolbox.standards.iec_61672_1_2013.time_averaged_level]
        - [`acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_level`][acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_level]

    """
    warnings.warn(
        'Signal.levels is deprecated. Use Signal.fast_levels, Signal.slow_levels (for "weighting") or Signal.leq_levels (for "average") instead.',
        DeprecationWarning,
        stacklevel=2,
    )
    if method == "average":
        return time_averaged_level(self.values, self.fs, time)
    elif method == "weighting":
        if time == 0.125:
            time_mode = "fast"
        elif time == 1.0:
            time_mode = "slow"
        else:
            raise ValueError(
                "Invalid time for weighting. Use 0.125 (FAST) or 1.0 (SLOW)."
            )
        return time_weighted_level(
            self.values, self.fs, time_mode=time_mode, integration_time=time
        )
    else:
        raise ValueError("Invalid method")

leq

leq()

Equivalent level. Single-value number.

See Also
Source code in acoustic_toolbox/_signal.py
def leq(self):
    """Equivalent level. Single-value number.

    See Also:
        - [`acoustic_toolbox.standards.iso_tr_25417_2007.equivalent_sound_pressure_level`][acoustic_toolbox.standards.iso_tr_25417_2007.equivalent_sound_pressure_level]
    """
    return standards.iso_tr_25417_2007.equivalent_sound_pressure_level(self.values)

plot_levels

plot_levels(**kwargs)

Plot sound pressure level as function of time.

See Also
Source code in acoustic_toolbox/_signal.py
def plot_levels(self, **kwargs):
    """Plot sound pressure level as function of time.

    See Also:
        - [`levels`][acoustic_toolbox._signal.Signal.levels]
    """
    params = {
        "xscale": "linear",
        "yscale": "linear",
        "xlabel": "$t$ in s",
        "ylabel": "$L_{p,F}$ in dB",
        "title": "SPL",
        "time": 0.125,
        "method": "average",
        "labels": None,
    }
    params.update(kwargs)
    t, L = self.levels(params["time"], params["method"])
    L_masked = np.ma.masked_where(np.isinf(L), L)
    return _base_plot(t, L_masked, params)

bandpass

bandpass(
    lowcut, highcut, order=8, zero_phase=False
) -> Signal

Filter signal with band-pass filter.

PARAMETER DESCRIPTION
lowcut

Lower cornerfrequency.

highcut

Upper cornerfrequency.

order

Filter order. (Default value = 8)

DEFAULT: 8

zero_phase

Prevent phase error by filtering in both directions (filtfilt). (Default value = False)

DEFAULT: False

RETURNS DESCRIPTION
class

Signal.

TYPE: Signal

See Also
Source code in acoustic_toolbox/_signal.py
def bandpass(self, lowcut, highcut, order=8, zero_phase=False) -> Signal:
    """Filter signal with band-pass filter.

    Args:
        lowcut: Lower cornerfrequency.
        highcut: Upper cornerfrequency.
        order: Filter order. (Default value = 8)
        zero_phase: Prevent phase error by filtering in both directions (filtfilt). (Default value = False)

    Returns:
        class:`Signal`.

    See Also:
        - [`acoustic_toolbox.signal.bandpass`][acoustic_toolbox.signal.bandpass]

    """
    return type(self)(
        signal.bandpass(
            self, lowcut, highcut, self.fs, order=order, zero_phase=zero_phase
        ),
        self.fs,
    )

bandstop

bandstop(
    lowcut,
    highcut,
    order: int = 8,
    zero_phase: bool = False,
) -> Signal

Filter signal with band-stop filter.

PARAMETER DESCRIPTION
lowcut

Lower cornerfrequency.

highcut

Upper cornerfrequency.

order

Filter order.

TYPE: int DEFAULT: 8

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

Band-pass filtered signal

See Also
Source code in acoustic_toolbox/_signal.py
def bandstop(
    self, lowcut, highcut, order: int = 8, zero_phase: bool = False
) -> Signal:
    """Filter signal with band-stop filter.

    Args:
        lowcut: Lower cornerfrequency.
        highcut: Upper cornerfrequency.
        order: Filter order.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
        Band-pass filtered signal

    See Also:
        - [`acoustic_toolbox.signal.bandstop`][acoustic_toolbox.signal.bandstop]

    """
    return type(self)(
        signal.bandstop(
            self, lowcut, highcut, self.fs, order=order, zero_phase=zero_phase
        ),
        self.fs,
    )

highpass

highpass(
    cutoff, order: int = 4, zero_phase: bool = False
) -> Signal

Filter signal with high-pass filter.

PARAMETER DESCRIPTION
cutoff

Cornerfrequency.

order

Filter order.

TYPE: int DEFAULT: 4

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

High-pass filtered signal

See Also
Source code in acoustic_toolbox/_signal.py
def highpass(self, cutoff, order: int = 4, zero_phase: bool = False) -> Signal:
    """Filter signal with high-pass filter.

    Args:
        cutoff: Cornerfrequency.
        order: Filter order.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
        High-pass filtered signal

    See Also:
        - [`acoustic_toolbox.signal.highpass`][acoustic_toolbox.signal.highpass]

    """
    return type(self)(
        signal.highpass(self, cutoff, self.fs, order=order, zero_phase=zero_phase),
        self.fs,
    )

lowpass

lowpass(
    cutoff, order: int = 4, zero_phase: bool = False
) -> Signal

Filter signal with low-pass filter.

PARAMETER DESCRIPTION
cutoff

Cornerfrequency.

order

Filter order.

TYPE: int DEFAULT: 4

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

Low-pass filtered signal

See Also
Source code in acoustic_toolbox/_signal.py
def lowpass(self, cutoff, order: int = 4, zero_phase: bool = False) -> Signal:
    """Filter signal with low-pass filter.

    Args:
        cutoff: Cornerfrequency.
        order: Filter order.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
        Low-pass filtered signal

    See Also:
        - [`acoustic_toolbox.signal.lowpass`][acoustic_toolbox.signal.lowpass]

    """
    return type(self)(
        signal.lowpass(self, cutoff, self.fs, order=order, zero_phase=zero_phase),
        self.fs,
    )

octavepass

octavepass(
    center,
    fraction,
    order: int = 8,
    zero_phase: bool = False,
) -> Signal

Filter signal with fractional-octave band-pass filter.

PARAMETER DESCRIPTION
center

Center frequency. Any value in the band will suffice.

fraction

Band designator.

order

Filter order.

TYPE: int DEFAULT: 8

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Signal

Band-pass filtered signal

See Also
Source code in acoustic_toolbox/_signal.py
def octavepass(
    self, center, fraction, order: int = 8, zero_phase: bool = False
) -> Signal:
    """Filter signal with fractional-octave band-pass filter.

    Args:
        center: Center frequency. Any value in the band will suffice.
        fraction: Band designator.
        order: Filter order.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
        Band-pass filtered signal

    See Also:
        - [`acoustic_toolbox.signal.octavepass`][acoustic_toolbox.signal.octavepass]

    """
    return type(self)(
        signal.octavepass(
            self,
            center,
            self.fs,
            fraction=fraction,
            order=order,
            zero_phase=zero_phase,
        ),
        self.fs,
    )

bandpass_frequencies

bandpass_frequencies(
    frequencies: "Frequencies",
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
) -> tuple["Frequencies", Signal]

Apply bandpass filters for frequencies.

PARAMETER DESCRIPTION
frequencies

Instance of :class:acoustic_toolbox.signal.Frequencies

TYPE: 'Frequencies'

order

Filter order.

TYPE: int DEFAULT: 8

purge

Discard bands of which the upper corner frequency is above the Nyquist frequency.

TYPE: bool DEFAULT: True

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
'Frequencies'

Frequencies

Signal

Band-pass filtered signal.

See Also
Source code in acoustic_toolbox/_signal.py
def bandpass_frequencies(
    self,
    frequencies: "Frequencies",
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
) -> tuple["Frequencies", Signal]:
    """Apply bandpass filters for frequencies.

    Args:
        frequencies: Instance of :class:`acoustic_toolbox.signal.Frequencies`
        order: Filter order.
        purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
        Frequencies
        Band-pass filtered signal.

    See Also:
        - [`acoustic_toolbox.signal.bandpass_frequencies`][acoustic_toolbox.signal.bandpass_frequencies]

    """
    frequencies, filtered = signal.bandpass_frequencies(
        self, self.fs, frequencies, order, purge, zero_phase=zero_phase
    )
    return frequencies, type(self)(filtered, self.fs)

octaves

octaves(
    frequencies: "Frequencies"
    | ndarray = NOMINAL_OCTAVE_CENTER_FREQUENCIES,
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
)

Apply 1/1-octaves bandpass filters.

PARAMETER DESCRIPTION
frequencies

Band-pass filter frequencies.

TYPE: 'Frequencies' | ndarray DEFAULT: NOMINAL_OCTAVE_CENTER_FREQUENCIES

order

Filter order.

TYPE: int DEFAULT: 8

purge

Discard bands of which the upper corner frequency is above the Nyquist frequency.

TYPE: bool DEFAULT: True

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

Frequencies

Band-pass filtered signal.

See Also
Source code in acoustic_toolbox/_signal.py
def octaves(
    self,
    frequencies: "Frequencies" | np.ndarray = NOMINAL_OCTAVE_CENTER_FREQUENCIES,
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
):
    """Apply 1/1-octaves bandpass filters.

    Args:
        frequencies: Band-pass filter frequencies.
        order: Filter order.
        purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
        Frequencies
        Band-pass filtered signal.

    See Also:
        - [`acoustic_toolbox.signal.bandpass_octaves`][acoustic_toolbox.signal.bandpass_octaves]
    """
    frequencies, octaves = signal.bandpass_octaves(
        self, self.fs, frequencies, order, purge, zero_phase=zero_phase
    )
    return frequencies, type(self)(octaves, self.fs)

third_octaves

third_octaves(
    frequencies: "Frequencies" = NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES,
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
)

Apply ⅓-octaves bandpass filters.

PARAMETER DESCRIPTION
frequencies

Band-pass filter frequencies.

TYPE: 'Frequencies' DEFAULT: NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES

order

Filter order.

TYPE: int DEFAULT: 8

purge

Discard bands of which the upper corner frequency is above the Nyquist frequency.

TYPE: bool DEFAULT: True

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

Frequencies and band-pass filtered signal.

See Also
Source code in acoustic_toolbox/_signal.py
def third_octaves(
    self,
    frequencies: "Frequencies" = NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES,
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
):
    """Apply 1/3-octaves bandpass filters.

    Args:
        frequencies: Band-pass filter frequencies.
        order: Filter order.
        purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
      Frequencies and band-pass filtered signal.

    See Also:
        - [`acoustic_toolbox.signal.bandpass_third_octaves`][acoustic_toolbox.signal.bandpass_third_octaves]

    """
    frequencies, octaves = signal.bandpass_third_octaves(
        self, self.fs, frequencies, order, purge, zero_phase=zero_phase
    )
    return frequencies, type(self)(octaves, self.fs)

fractional_octaves

fractional_octaves(
    frequencies: "Frequencies" | None = None,
    fraction: int = 1,
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
)

Apply 1/N-octaves bandpass filters.

PARAMETER DESCRIPTION
frequencies

Band-pass filter frequencies.

TYPE: 'Frequencies' | None DEFAULT: None

fraction

Default band-designator of fractional-octaves.

TYPE: int DEFAULT: 1

order

Filter order.

TYPE: int DEFAULT: 8

purge

Discard bands of which the upper corner frequency is above the Nyquist frequency.

TYPE: bool DEFAULT: True

zero_phase

Prevent phase error by filtering in both directions (filtfilt).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

Frequencies and band-pass filtered signal.

See Also
Source code in acoustic_toolbox/_signal.py
def fractional_octaves(
    self,
    frequencies: "Frequencies" | None = None,
    fraction: int = 1,
    order: int = 8,
    purge: bool = True,
    zero_phase: bool = False,
):
    """Apply 1/N-octaves bandpass filters.

    Args:
        frequencies: Band-pass filter frequencies.
        fraction: Default band-designator of fractional-octaves.
        order: Filter order.
        purge: Discard bands of which the upper corner frequency is above the Nyquist frequency.
        zero_phase: Prevent phase error by filtering in both directions (filtfilt).

    Returns:
      Frequencies and band-pass filtered signal.

    See Also:
        - [`acoustic_toolbox.signal.bandpass_fractional_octaves`][acoustic_toolbox.signal.bandpass_fractional_octaves]

    """
    if frequencies is None:
        frequencies = signal.OctaveBand(
            fstart=NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES[0],
            fstop=self.fs / 2.0,
            fraction=fraction,
        )
    frequencies, octaves = signal.bandpass_fractional_octaves(
        self, self.fs, frequencies, fraction, order, purge, zero_phase=zero_phase
    )
    return frequencies, type(self)(octaves, self.fs)

plot_octaves

plot_octaves(**kwargs)

Plot octaves.

See Also
Source code in acoustic_toolbox/_signal.py
def plot_octaves(self, **kwargs):
    """Plot octaves.

    See Also:
        - [`octaves`][acoustic_toolbox._signal.Signal.octaves]
    """
    params = {
        "xscale": "log",
        "yscale": "linear",
        "xlabel": "$f$ in Hz",
        "ylabel": "$L_{p}$ in dB",
        "title": "1/1-Octaves SPL",
    }
    params.update(kwargs)
    f, o = self.octaves()
    print(len(f.center), len(o.leq()))
    return _base_plot(f.center, o.leq().T, params)

plot_third_octaves

plot_third_octaves(**kwargs)

Plot ⅓-octaves.

See Also
Source code in acoustic_toolbox/_signal.py
def plot_third_octaves(self, **kwargs):
    """Plot 1/3-octaves.

    See Also:
        - [`third_octaves`][acoustic_toolbox._signal.Signal.third_octaves]
    """
    params = {
        "xscale": "log",
        "yscale": "linear",
        "xlabel": "$f$ in Hz",
        "ylabel": "$L_{p}$ in dB",
        "title": "1/3-Octaves SPL",
    }
    params.update(kwargs)
    f, o = self.third_octaves()
    return _base_plot(f.center, o.leq().T, params)

plot_fractional_octaves

plot_fractional_octaves(
    frequencies=None,
    fraction=1,
    order=8,
    purge=True,
    zero_phase=False,
    **kwargs,
)

Plot fractional octaves.

Source code in acoustic_toolbox/_signal.py
def plot_fractional_octaves(
    self,
    frequencies=None,
    fraction=1,
    order=8,
    purge=True,
    zero_phase=False,
    **kwargs,
):
    """Plot fractional octaves."""
    title = "1/{}-Octaves SPL".format(fraction)

    params = {
        "xscale": "log",
        "yscale": "linear",
        "xlabel": "$f$ in Hz",
        "ylabel": "$L_p$ in dB",
        "title": title,
    }
    params.update(kwargs)
    f, o = self.fractional_octaves(
        frequencies=frequencies,
        fraction=fraction,
        order=order,
        purge=purge,
        zero_phase=zero_phase,
    )
    return _base_plot(f.center, o.leq().T, params)

plot

plot(**kwargs)

Plot signal as function of time. By default the entire signal is plotted.

Valid kwargs:

PARAMETER DESCRIPTION
filename

Name of file.

start

First sample index.

stop

Last sample index.

Source code in acoustic_toolbox/_signal.py
def plot(self, **kwargs):
    """Plot signal as function of time. By default the entire signal is plotted.

    **Valid kwargs:**

    Other Args:
        filename: Name of file.
        start: First sample index.
        stop: Last sample index.
    """
    params = {
        "xscale": "linear",
        "yscale": "linear",
        "xlabel": "$t$ in s",
        "ylabel": "$x$ in -",
        "title": "Signal",
    }
    params.update(kwargs)
    return _base_plot(self.times(), self, params)

normalize

normalize(gap=6.0, inplace=False)

Normalize signal.

The parameter gap can be understood as using gap decibels fewer for the dynamic range.

By default a 6 decibel gap is used.

PARAMETER DESCRIPTION
gap

Gap between maximum value and ceiling in decibel.

DEFAULT: 6.0

inplace

Normalize signal in place.

DEFAULT: False

Source code in acoustic_toolbox/_signal.py
def normalize(self, gap=6.0, inplace=False):
    """Normalize signal.

    The parameter `gap` can be understood as using `gap` decibels fewer for the dynamic range.

    By default a 6 decibel gap is used.

    Args:
      gap: Gap between maximum value and ceiling in decibel.
      inplace: Normalize signal in place.
    """
    factor = np.abs(self).max() * 10.0 ** (gap / 20.0)
    if inplace:
        self /= factor[..., None]
        return self
    else:
        return self / factor[..., None]

to_wav

to_wav(filename, depth=16)

Save signal as WAV file.

By default, this function saves a normalized 16-bit version of the signal with at least 6 dB range till clipping occurs.

PARAMETER DESCRIPTION
filename

Name of file to save to.

depth

If given, convert to integer with specified depth. Else, try to store using the original data type.

DEFAULT: 16

Source code in acoustic_toolbox/_signal.py
def to_wav(self, filename, depth=16):
    """Save signal as WAV file.

    By default, this function saves a normalized 16-bit version of the signal with at least 6 dB range till clipping occurs.

    Args:
        filename: Name of file to save to.
        depth: If given, convert to integer with specified depth. Else, try to store using the original data type.

    """
    data = self
    dtype = data.dtype if not depth else "int" + str(depth)
    if depth:
        data = (data * 2 ** (depth - 1) - 1).astype(dtype)
    wavfile.write(filename, int(self.fs), data.T)

from_wav classmethod

from_wav(filename, normalize=True) -> Signal

Create an instance of Signal from a WAV file.

PARAMETER DESCRIPTION
filename

Filename of WAV file.

normalize

Whether to normalize the signal.

DEFAULT: True

RETURNS DESCRIPTION
Signal

Signal

Source code in acoustic_toolbox/_signal.py
@classmethod
def from_wav(cls, filename, normalize=True) -> Signal:
    """Create an instance of `Signal` from a WAV file.

    Args:
        filename: Filename of WAV file.
        normalize: Whether to normalize the signal.

    Returns:
        Signal
    """
    fs, data = wavfile.read(filename)
    data = data.astype(np.float32, copy=False).T
    if normalize:
        data /= np.max(np.abs(data))
    return cls(data, fs=fs)

:::