Skip to content

signals.spectra

Calibrated spectral-density estimation with statistical error analysis.

Welch-averaged auto- and cross-spectral density estimators that report, alongside the spectrum itself, the statistical quality of the estimate, following Bendat & Piersol, Random Data: Analysis and Measurement Procedures (4th ed., 2010):

  • the number of averages: the raw segment count and the effective number of independent averages once the correlation between overlapped, tapered segments is accounted for (Section 11.5.2.2 and its Ref. 11, Welch 1967);
  • the normalized random error of the autospectrum estimate, (Eq. 8.158), and of the cross-spectrum magnitude and phase, (Eq. 9.33) and (Eq. 9.52);
  • chi-square confidence intervals for the autospectrum: the sampling distribution is with degrees of freedom (Eq. 8.162), giving the interval (Eq. 8.163);
  • the first-order resolution-bias error: (Eq. 8.139), which for a resonance peak of half-power bandwidth becomes (Eq. 8.141), exposed here as resolution_bias_error;
  • the coherent output spectrum and the noise output spectrum of the single-input/single-output model (Eqs. 9.55-9.56), with the spectral signal-to-noise ratio and the random error (Eq. 9.73).

The same Welch core (Hann taper and 50% overlap by default, detrend off so absolute calibration is preserved) also backs the H1/H2 frequency response and coherence estimators of phonometry.electroacoustics.frequency_response and the p-p intensity probe of phonometry.emission.intensity.

A fractional-octave smoothing utility completes the module: a constant-power rectangular kernel of 1/n-octave width in log-frequency (the constant-percentage resolution bandwidth that Bendat & Piersol, Section 8.5.3, recommend for resonant-response spectra), applicable to power spectra, magnitude responses and dB curves. A flat spectrum is left exactly unchanged.

The taper the window parameter selects is characterized, with the figures of merit of Harris (1978), by phonometry.signals.windows.window_metrics; the whole-record alternative to Welch segment averaging, Thomson’s multitaper estimator, is phonometry.signals.multitaper.multitaper_psd.

Auto-generated from the source docstrings by scripts/generate_api_docs.py (make api-docs). Do not edit by hand.

coherent_output_spectrum(
x: Signal | NumericArrayLike,
y: Signal | NumericArrayLike,
fs: float | None = None,
*,
window: str | tuple[str | NumericArrayLike, ...] = 'hann',
nperseg: int | np.integer[Any] | None = None,
overlap: float = 0.5,
scaling: Literal['density', 'spectrum'] = 'density',
) -> CoherentOutputSpectrumResult

Coherent output spectrum and spectral SNR (Bendat & Piersol 9.2.2).

Splits the measured output autospectrum into the coherent part linearly explained by the input x and the noise remainder , and reports the spectral signal-to-noise ratio together with the Bendat & Piersol random errors (Eqs. 9.73 and 9.82). For additive uncorrelated output noise of known level the coherence satisfies , which is the closed-form oracle used to verify the implementation.

Parameters

Name Description
x Input (reference) signal, 1-D. Accepts a phonometry.io.Signal, whose calibration is applied to the samples, so all three densities come out in Pa²/Hz, or Pa² for scaling='spectrum'. The coherence and the signal-to-noise ratio are ratios and do not move.
y Output (response) signal, 1-D, same length as x. Accepts a phonometry.io.Signal, whose calibration is applied to the samples, so all three densities come out in Pa²/Hz, or Pa² for scaling='spectrum'. The coherence and the signal-to-noise ratio are ratios and do not move.
fs Sample rate, in Hz. Required when both records are bare arrays; either may be a Signal and supply it, and two Signals recorded at different rates are refused rather than arbitrated.
window Segment taper, a scipy window name or a tuple of a name and its parameters, such as ("kaiser", 8.6) (default Hann).
nperseg Welch segment length; None picks a default.
overlap Segment overlap fraction in [0, 1) (default 0.5).
scaling 'density' or 'spectrum'.

Returns: A CoherentOutputSpectrumResult.

Raises

Exception When
ValueError If the inputs or parameters are invalid.
TypeError if overlap is not a single number, or nperseg is a flag, a text or an array where a count goes, or scaling is not a text, or x or y holds a text or a value that is not a real number.
CoherentOutputSpectrumResult(
frequencies: NDArray[np.float64],
output_psd: NDArray[np.float64],
coherent_psd: NDArray[np.float64],
noise_psd: NDArray[np.float64],
coherence: NDArray[np.float64],
snr: NDArray[np.float64],
snr_db: NDArray[np.float64],
random_error: NDArray[np.float64],
snr_random_error: NDArray[np.float64],
coherence_bias: NDArray[np.float64],
n_segments: int,
n_averages: float,
resolution_bandwidth: float,
window: str | tuple[str | NumericArrayLike, ...],
nperseg: int,
overlap: float,
scaling: Literal['density', 'spectrum'],
)

Coherent output spectrum of a single-input/single-output model.

The measured output autospectrum splits into the part linearly explained by the input, (Eq. 9.55), and the uncorrelated noise remainder (Eq. 9.56), with (Eq. 9.57). Their ratio is the spectral signal-to-noise ratio.

Attributes

Name Description
frequencies One-sided frequency axis, in Hz.
output_psd Measured output autospectrum .
coherent_psd Coherent output spectrum .
noise_psd Noise output spectrum .
coherence Ordinary coherence .
snr Spectral signal-to-noise ratio ( at ).
snr_db of snr, in dB.
random_error Normalized random error of , (Eq. 9.73), with the measured coherence in place of the true value.
snr_random_error Normalized random error of the SNR, , first-order propagation of the coherence random error of Eq. 9.82 through .
coherence_bias First-order bias of the coherence estimate, (Eq. 9.75).
n_segments Raw number of segments averaged.
n_averages Effective number of independent averages .
resolution_bandwidth Effective noise bandwidth , in Hz.
window The taper, a window name or a tuple of a name and its parameters, as given (a list parameter as a tuple).
nperseg Segment length, in samples.
overlap Segment overlap fraction.
scaling 'density' or 'spectrum'.
CoherentOutputSpectrumResult.plot(
ax: None = None,
*,
language: Literal['en', 'es'] = 'en',
**kwargs: Any,
) -> tuple[Axes, Axes]
CoherentOutputSpectrumResult.plot(
ax: Axes,
*,
language: Literal['en', 'es'] = 'en',
**kwargs: Any,
) -> Axes

Plot the output/coherent/noise spectra and the spectral SNR.

Parameters

Name Description
language Label language, "en" (default) or "es".
cross_spectral_density(
x: Signal | NumericArrayLike,
y: Signal | NumericArrayLike,
fs: float | None = None,
*,
window: str | tuple[str | NumericArrayLike, ...] = 'hann',
nperseg: int | np.integer[Any] | None = None,
overlap: float = 0.5,
scaling: Literal['density', 'spectrum'] = 'density',
) -> CrossSpectralDensityResult

Calibrated cross-spectral density with statistical error analysis.

Welch’s method on both channels; alongside the result reports the ordinary coherence and the Bendat & Piersol random errors: (Eq. 9.33) for the magnitude and (Eq. 9.52) for the phase, with the measured coherence in place of the unknown true value.

Parameters

Name Description
x First signal, 1-D. Accepts a phonometry.io.Signal, whose calibration is applied to the samples, so the cross-spectrum and its magnitude come out in Pa²/Hz, or Pa² for scaling='spectrum'. The coherence and the phase are ratios and do not move.
y Second signal, 1-D, same length as x. Accepts a phonometry.io.Signal, whose calibration is applied to the samples, so the cross-spectrum and its magnitude come out in Pa²/Hz, or Pa² for scaling='spectrum'. The coherence and the phase are ratios and do not move.
fs Sample rate, in Hz. Required when both records are bare arrays; either may be a Signal and supply it, and two Signals recorded at different rates are refused rather than arbitrated.
window Segment taper, a scipy window name or a tuple of a name and its parameters, such as ("kaiser", 8.6) (default Hann).
nperseg Welch segment length; None picks a default.
overlap Segment overlap fraction in [0, 1) (default 0.5).
scaling 'density' or 'spectrum'.

Returns: A CrossSpectralDensityResult.

Raises

Exception When
ValueError If the inputs or parameters are invalid.
TypeError if overlap is not a single number, or nperseg is a flag, a text or an array where a count goes, or scaling is not a text, or x or y holds a text or a value that is not a real number.
CrossSpectralDensityResult(
frequencies: NDArray[np.float64],
csd: NDArray[np.complex128],
magnitude: NDArray[np.float64],
phase_rad: NDArray[np.float64],
coherence: NDArray[np.float64],
magnitude_random_error: NDArray[np.float64],
phase_standard_deviation_rad: NDArray[np.float64],
n_segments: int,
n_averages: float,
resolution_bandwidth: float,
window: str | tuple[str | NumericArrayLike, ...],
nperseg: int,
overlap: float,
scaling: Literal['density', 'spectrum'],
)

Welch cross-spectral density with its statistical error (B&P Ch. 9).

The error formulas replace the unknown true coherence with the computed estimate, as Bendat & Piersol recommend for measured data (Section 9.2).

Attributes

Name Description
frequencies One-sided frequency axis, in Hz.
csd Complex cross-spectral density .
magnitude .
phase_rad Cross-spectrum phase , in radians (unwrapped).
coherence Ordinary coherence .
magnitude_random_error Normalized random error of , (Eq. 9.33).
phase_standard_deviation_rad Standard deviation of the phase estimate, in radians, (Eq. 9.52).
n_segments Raw number of segments averaged.
n_averages Effective number of independent averages .
resolution_bandwidth Effective noise bandwidth , in Hz.
window The taper, a window name or a tuple of a name and its parameters, as given (a list parameter as a tuple).
nperseg Segment length, in samples.
overlap Segment overlap fraction.
scaling 'density' or 'spectrum'.
CrossSpectralDensityResult.plot(
ax: None = None,
*,
language: Literal['en', 'es'] = 'en',
**kwargs: Any,
) -> tuple[Axes, Axes, Axes]
CrossSpectralDensityResult.plot(
ax: Axes,
*,
language: Literal['en', 'es'] = 'en',
**kwargs: Any,
) -> Axes

Plot the magnitude, phase (with ±σ band) and coherence.

Parameters

Name Description
language Label language, "en" (default) or "es".
fractional_octave_smoothing(
values: NumericArrayLike,
*,
frequencies: NumericArrayLike,
fraction: float = 3.0,
domain: Literal['power', 'amplitude', 'db'] = 'power',
) -> NDArray[np.float64]

Smooth a spectrum with a constant-power 1/n-octave kernel.

Each output point is the power average of the input over a rectangular window of 1/fraction octave centred (geometrically) on its frequency: . This is the constant-percentage resolution bandwidth that Bendat & Piersol (Section 8.5.3) recommend for spectra of resonant systems, and the de facto standard presentation of loudspeaker and room responses. The average is computed on power regardless of domain (amplitudes are squared first, dB levels converted), so smoothing conserves band power rather than amplitude; a flat spectrum is left exactly unchanged.

The window is clipped at the ends of the frequency axis, and points at non-positive frequencies (where a log-frequency window is undefined) are copied unchanged.

Parameters

Name Description
frequencies Frequency axis, 1-D, strictly increasing.
values Spectrum sampled on frequencies: power-like values ('power'), magnitudes ('amplitude') or levels in dB ('db').
fraction The n of the 1/n-octave width (default 3, one-third octave).
domain How values map to power (see above). The output is returned in the same domain.

Returns: Smoothed spectrum, same shape and domain as values.

Raises

Exception When
ValueError If the inputs or parameters are invalid.
TypeError if fraction is not a single number, or domain is not a text, or frequencies or values holds a text or a value that is not a real number.
power_spectral_density(
x: Signal | NumericArrayLike,
fs: float | None = None,
*,
window: str | tuple[str | NumericArrayLike, ...] = 'hann',
nperseg: int | np.integer[Any] | None = None,
overlap: float = 0.5,
scaling: Literal['density', 'spectrum'] = 'density',
confidence: float = 0.95,
) -> SpectralDensityResult

Calibrated autospectral density with chi-square confidence interval.

Welch’s method (Bendat & Piersol Section 11.5.2: tapered, overlapped segment averaging, no detrending so absolute calibration is preserved). Alongside the result reports the effective number of independent averages , the normalized random error (Eq. 8.158) and the chi-square confidence interval with degrees of freedom (Eq. 8.163). For the first-order resolution-bias error at a resonance peak see resolution_bias_error.

Parameters

Name Description
x Signal, 1-D. Accepts a phonometry.io.Signal, whose calibration is applied to the samples, so the density and its confidence interval come out in Pa²/Hz, or Pa² for scaling='spectrum'.
fs Sample rate, in Hz. Required for a bare array; a Signal brings its own, and an explicit value that disagrees with it raises instead of silently winning.
window Segment taper, a scipy window name or a tuple of a name and its parameters, such as ("kaiser", 8.6) (default Hann, the B&P Section 11.5.2 recommendation for side-lobe suppression).
nperseg Welch segment length; None picks a length giving a bin spacing of at most 4 Hz (the resolution bandwidth further depends on the taper; see SpectralDensityResult.resolution_bandwidth).
overlap Segment overlap fraction in [0, 1) (default 0.5, which with a Hann taper retrieves most of the stability lost to tapering, B&P Section 11.5.2.2).
scaling 'density' (units²/Hz) or 'spectrum' (units² per segment bandwidth).
confidence Confidence level for the chi-square interval.

Returns: A SpectralDensityResult.

Raises

Exception When
ValueError If the inputs or parameters are invalid.
TypeError if confidence or overlap is not a single number, or nperseg is a flag, a text or an array where a count goes, or scaling is not a text, or x holds a text or a value that is not a real number.
resolution_bias_error(
resolution_bandwidth: float,
half_power_bandwidth: float,
) -> float

First-order resolution-bias error at a resonance peak (Eq. 8.141).

for a resonance of half-power bandwidth analysed with resolution bandwidth : peaks are underestimated (and valleys overestimated) by frequency smoothing, in the direction of reduced dynamic range (B&P Section 8.5.1). The approximation assumes .

Parameters

Name Description
resolution_bandwidth Analysis resolution bandwidth , Hz (SpectralDensityResult.resolution_bandwidth).
half_power_bandwidth Half-power (-3 dB) bandwidth of the spectral peak, in Hz.

Returns: Normalized bias error (dimensionless, negative at a peak).

Raises

Exception When
ValueError If either bandwidth is not positive.
TypeError if half_power_bandwidth or resolution_bandwidth is not a single number.
SpectralDensityResult(
frequencies: NDArray[np.float64],
psd: NDArray[np.float64],
confidence_lower: NDArray[np.float64],
confidence_upper: NDArray[np.float64],
confidence: float,
random_error: float,
n_segments: int,
n_averages: float,
degrees_of_freedom: float,
resolution_bandwidth: float,
window: str | tuple[str | NumericArrayLike, ...],
nperseg: int,
overlap: float,
scaling: Literal['density', 'spectrum'],
)

Welch autospectral density with its statistical error (B&P Ch. 8).

Attributes

Name Description
frequencies One-sided frequency axis, in Hz.
psd Autospectral density (units²/Hz for 'density' scaling, units² for 'spectrum').
confidence_lower Lower chi-square confidence bound on (Eq. 8.163; the DC bin, and the Nyquist bin for an even segment length, use degrees of freedom, a wider interval, because those bins carry a single real Fourier component).
confidence_upper Upper chi-square confidence bound on .
confidence Confidence level of the interval (e.g. 0.95).
random_error Normalized random error (Eq. 8.158) of the interior bins ( at DC/Nyquist).
n_segments Raw number of (possibly overlapped) segments averaged.
n_averages Effective number of independent averages (equals n_segments without overlap; smaller with overlap).
degrees_of_freedom Chi-square degrees of freedom of the interior bins (Eq. 8.162; at DC/Nyquist).
resolution_bandwidth Effective noise bandwidth of the tapered segment, in Hz (drives the bias error of Eq. 8.139).
window The taper, a window name or a tuple of a name and its parameters, as given (a list parameter as a tuple).
nperseg Segment length, in samples.
overlap Segment overlap fraction.
scaling 'density' or 'spectrum'.
SpectralDensityResult.plot(
ax: Axes | None = None,
*,
language: Literal['en', 'es'] = 'en',
**kwargs: Any,
) -> Axes

Plot the spectral density in dB with its confidence band.

Parameters

Name Description
language Label language, "en" (default) or "es".