Ir al contenido

signals.spectra

La referencia de la API se publica en inglés en los dos idiomas: se genera a partir de los docstrings del código, que son su texto original.

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: NDArray[np.float64] | list[float],
y: NDArray[np.float64] | list[float],
fs: float,
*,
window: str = 'hann',
nperseg: int | 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

NameDescription
xInput (reference) signal, 1-D.
yOutput (response) signal, 1-D, same length as x.
fsSample rate, in Hz.
windowSegment taper (default Hann).
npersegWelch segment length; None picks a default.
overlapSegment overlap fraction in [0, 1) (default 0.5).
scaling'density' or 'spectrum'.

Returns: A CoherentOutputSpectrumResult.

Raises

ExceptionWhen
ValueErrorIf the inputs or parameters are invalid.
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,
nperseg: int,
overlap: float,
scaling: str,
)

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

NameDescription
frequenciesOne-sided frequency axis, in Hz.
output_psdMeasured output autospectrum .
coherent_psdCoherent output spectrum .
noise_psdNoise output spectrum .
coherenceOrdinary coherence .
snrSpectral signal-to-noise ratio ( at ).
snr_db of snr, in dB.
random_errorNormalized random error of , (Eq. 9.73), with the measured coherence in place of the true value.
snr_random_errorNormalized random error of the SNR, , first-order propagation of the coherence random error of Eq. 9.82 through .
coherence_biasFirst-order bias of the coherence estimate, (Eq. 9.75).
n_segmentsRaw number of segments averaged.
n_averagesEffective number of independent averages .
resolution_bandwidthEffective noise bandwidth , in Hz.
windowTaper name.
npersegSegment length, in samples.
overlapSegment overlap fraction.
scaling'density' or 'spectrum'.
CoherentOutputSpectrumResult.plot(
ax: Axes | None = None,
*,
language: str = 'en',
**kwargs: Any,
) -> Axes | NDArray[Any]

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

Parameters

NameDescription
languageLabel language, "en" (default) or "es".
cross_spectral_density(
x: NDArray[np.float64] | list[float],
y: NDArray[np.float64] | list[float],
fs: float,
*,
window: str = 'hann',
nperseg: int | 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

NameDescription
xFirst signal, 1-D.
ySecond signal, 1-D, same length as x.
fsSample rate, in Hz.
windowSegment taper (default Hann).
npersegWelch segment length; None picks a default.
overlapSegment overlap fraction in [0, 1) (default 0.5).
scaling'density' or 'spectrum'.

Returns: A CrossSpectralDensityResult.

Raises

ExceptionWhen
ValueErrorIf the inputs or parameters are invalid.
CrossSpectralDensityResult(
frequencies: NDArray[np.float64],
csd: NDArray[np.complex128],
magnitude: NDArray[np.float64],
phase: NDArray[np.float64],
coherence: NDArray[np.float64],
magnitude_random_error: NDArray[np.float64],
phase_std: NDArray[np.float64],
n_segments: int,
n_averages: float,
resolution_bandwidth: float,
window: str,
nperseg: int,
overlap: float,
scaling: str,
)

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

NameDescription
frequenciesOne-sided frequency axis, in Hz.
csdComplex cross-spectral density .
magnitude.
phaseCross-spectrum phase , in radians (unwrapped).
coherenceOrdinary coherence .
magnitude_random_errorNormalized random error of , (Eq. 9.33).
phase_stdStandard deviation of the phase estimate, in radians, (Eq. 9.52).
n_segmentsRaw number of segments averaged.
n_averagesEffective number of independent averages .
resolution_bandwidthEffective noise bandwidth , in Hz.
windowTaper name.
npersegSegment length, in samples.
overlapSegment overlap fraction.
scaling'density' or 'spectrum'.
CrossSpectralDensityResult.plot(
ax: Axes | None = None,
*,
language: str = 'en',
**kwargs: Any,
) -> Axes | NDArray[Any]

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

Parameters

NameDescription
languageLabel language, "en" (default) or "es".
fractional_octave_smoothing(
frequencies: NDArray[np.float64] | list[float],
values: NDArray[np.float64] | list[float],
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

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

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

Raises

ExceptionWhen
ValueErrorIf the inputs or parameters are invalid.
power_spectral_density(
x: NDArray[np.float64] | list[float],
fs: float,
*,
window: str = 'hann',
nperseg: int | 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

NameDescription
xSignal, 1-D.
fsSample rate, in Hz.
windowSegment taper (any scipy window name; default Hann, the B&P Section 11.5.2 recommendation for side-lobe suppression).
npersegWelch 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).
overlapSegment 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).
confidenceConfidence level for the chi-square interval.

Returns: A SpectralDensityResult.

Raises

ExceptionWhen
ValueErrorIf the inputs or parameters are invalid.
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

NameDescription
resolution_bandwidthAnalysis resolution bandwidth , Hz (SpectralDensityResult.resolution_bandwidth).
half_power_bandwidthHalf-power (-3 dB) bandwidth of the spectral peak, in Hz.

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

Raises

ExceptionWhen
ValueErrorIf either bandwidth is not positive.
SpectralDensityResult(
frequencies: NDArray[np.float64],
psd: NDArray[np.float64],
ci_lower: NDArray[np.float64],
ci_upper: NDArray[np.float64],
confidence: float,
random_error: float,
n_segments: int,
n_averages: float,
degrees_of_freedom: float,
resolution_bandwidth: float,
window: str,
nperseg: int,
overlap: float,
scaling: str,
)

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

Attributes

NameDescription
frequenciesOne-sided frequency axis, in Hz.
psdAutospectral density (units²/Hz for 'density' scaling, units² for 'spectrum').
ci_lowerLower 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).
ci_upperUpper chi-square confidence bound on .
confidenceConfidence level of the interval (e.g. 0.95).
random_errorNormalized random error (Eq. 8.158) of the interior bins ( at DC/Nyquist).
n_segmentsRaw number of (possibly overlapped) segments averaged.
n_averagesEffective number of independent averages (equals n_segments without overlap; smaller with overlap).
degrees_of_freedomChi-square degrees of freedom of the interior bins (Eq. 8.162; at DC/Nyquist).
resolution_bandwidthEffective noise bandwidth of the tapered segment, in Hz (drives the bias error of Eq. 8.139).
windowTaper name.
npersegSegment length, in samples.
overlapSegment overlap fraction.
scaling'density' or 'spectrum'.
SpectralDensityResult.plot(
ax: Axes | None = None,
*,
language: str = 'en',
**kwargs: Any,
) -> Axes

Plot the spectral density in dB with its confidence band.

Parameters

NameDescription
languageLabel language, "en" (default) or "es".