API reference¶
At a glance¶
from harm_analysis import harm_analysis, spec_analysis, HarmResult, SpecResult
Name |
What it does |
|---|---|
Analyze a signal with an injected tone: fundamental, harmonics, DC, noise, THD, SNR, SINAD and THD+N. Returns a |
|
Detect DC, tones and noise in a signal without a known tone. Returns a |
|
Results of |
|
Results of |
Conventions shared by both functions:
Input: a 1-D, real, finite array of at least 32 samples, and the sampling frequency
fs. Frequencies in the results are in the units offs.Output: powers in dB relative to the signal’s units squared (a sine of amplitude 1 is −3.01 dB). A power of zero is
-infdB. Arrays (harmonics, tones) are NumPy arrays, empty when there is nothing.Plotting: pass
plot=Trueand a Matplotlibax; the spectrum is drawn on thatax, which you can keep customizing.Errors: invalid input raises
ValueErrororTypeErrorwith a message that names the parameter (see Invalid input).
How each metric is computed is explained in How it works.
Functions¶
- harm_analysis.harm_analysis(x, fs=1, bw=None, n_harm=5, window=None, plot=False, ax=None, fund_freq=None)[source]¶
Harmonic Analysis.
Calculates the fundamental, harmonics, DC and noise power of the input signal x, and from them the THD, SNR, SINAD and THD+N.
Intended for signals with an injected tone (e.g. simulations or measurements of a circuit driven by a sine wave). The THD is computed from the fundamental and the first n_harm harmonics, using a power spectrum of the same length as the input signal. A Hann window is applied to the signal before the power spectrum is obtained, unless another window is given.
- Parameters:
x (array_like) – Input signal, containing a tone.
fs (float, optional) – Sampling frequency. Frequencies in the results are in the same units. Default is 1.
bw (float, optional) – Bandwidth to use for the calculation of the metrics, in the same units as fs. Default is
fs / 2. Also useful to exclude another tone (or noise) with amplitude greater than the fundamental and located above a certain frequency (see the shaped noise example).n_harm (int, optional) – Number of harmonics used in the THD calculation. Default is 5. Harmonics above bw are ignored.
window (array_like, optional) – Window that will be multiplied with the signal, with the same length as x. Default is a Hann window.
plot (bool, optional) – If True, the power spectrum is plotted on ax. The caller keeps the reference to ax and can keep customizing it after the call (title, scale, limits, etc.).
ax (matplotlib.axes.Axes or None, optional) – Axes to plot on. Required if plot is True.
fund_freq (float, optional) – Expected frequency of the fundamental, in the same units as fs. The fundamental is the spectral peak nearest to it (within 3 bins), which must stand out from the local noise floor. Use it when the signal may contain a component stronger than the injected tone. Default is None: the highest spectral component between DC and bw.
- Returns:
The analysis results (fundamental, harmonics, DC, noise, THD, SNR, SINAD and THD+N). See
HarmResultfor the fields. UseHarmResult.to_dict()to get them as a dictionary.Powers of zero are reported as
-infdB (no warning is raised).- Return type:
- Raises:
TypeError – If x or window is complex or not numeric.
ValueError – If the input signal is constant (all zeros or DC only), as there is no tone to analyze; if bw is so low that it falls inside the DC component of the spectrum; if fund_freq is outside the band, inside the DC component or has no tone near it (a peak that does not stand out from the noise floor); if plot is True and no ax is given; or if an input is invalid: x not 1-D, shorter than 32 samples or containing NaN/inf, fs not positive, window not the same length as x, bw not in
(0, fs / 2], or n_harm negative.
Notes
Without fund_freq, the fundamental is taken to be the highest spectral component between DC and bw. If the signal contains a stronger tone, that tone is reported as the fundamental. Pass fund_freq (or use bw to exclude a stronger tone above the fundamental) to analyze the intended tone; any other tone in the band is then counted as noise and lowers the SNR.
Ensure that the frequency components are far enough apart to accommodate for the sidelobe width of the Hann window. If this is not feasible, you can use a different window by using the “window” input.
A component exactly at fs/2 (e.g. the 2nd harmonic of a fundamental at fs/4) is sampled as
A * cos(phase) * (-1)**n, so its measured power isA**2 * cos(phase)**2and depends on its phase. Components within about one bin of fs/2 (or of DC) overlap their mirror image and are also phase dependent.References
- [1] Harris, Fredric J. “On the use of windows for harmonic analysis
with the discrete Fourier transform.” Proceedings of the IEEE 66.1 (1978): 51-83.
- [2] Cerna, Michael, and Audrey F. Harvey. The fundamentals of
FFT-based signal analysis and measurement. Application Note 041, National Instruments, 2000.
Examples
A 100.3 Hz tone with a 2nd harmonic 40 dB below it, sampled at 1 kHz:
>>> import numpy as np >>> from harm_analysis import harm_analysis >>> fs = 1000 >>> t = np.arange(4096) / fs >>> rng = np.random.default_rng(0) >>> x = np.cos(2 * np.pi * 100.3 * t) + 0.01 * np.cos(2 * np.pi * 200.6 * t) >>> x = x + rng.normal(0, 1e-4, t.size) >>> results = harm_analysis(x, fs=fs) >>> round(results.fund_freq, 1) 100.3 >>> round(results.fund_db, 2) -3.01 >>> round(results.thd_db, 1) -40.0 >>> round(float(results.harm_freq[0]), 1) 200.6
All metrics as a dictionary:
>>> list(results.to_dict())[:4] ['fund_db', 'fund_freq', 'harm_freq', 'harm_db']
Plot the spectrum on your own axes, then keep customizing them:
>>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> results = harm_analysis(x, fs=fs, plot=True, ax=ax) >>> ax.set_xscale("log") >>> plt.close(fig)
- harm_analysis.spec_analysis(x, fs=1, window=None, plot=False, ax=None, distance=6, prominence=10, height=None, false_alarm_rate=0.001, bw=None)[source]¶
Spectral Analysis.
Auto-detects DC, tones, and noise from the spectrum. Intended for signals without a known injected tone.
A tone is a peak in the power spectrum (in dB) that meets the distance, prominence and height criteria (see
scipy.signal.find_peaks()). All bins up to bw that are not DC or part of a tone are counted as noise.By default a peak must stand out from the local noise floor (the median of the surrounding bins) by a margin derived from false_alarm_rate: noise alone produces a false tone in at most about false_alarm_rate of the analyzed spectra (white Gaussian noise; measured between 0.4x and 1.5x of the rate). The margin grows slowly with the signal length (about 13.5 dB for 1024 samples and 15 dB for 262144 samples with the default rate), since a longer spectrum has more noise bins that could exceed it.
- Parameters:
x (array_like) – Input signal.
fs (float, optional) – Sampling frequency. Frequencies in the results are in the same units. Default is 1.
window (array_like, optional) – Window that will be multiplied with the signal, with the same length as x. Default is a Hann window.
plot (bool, optional) – If True, the power spectrum is plotted on ax. The caller keeps the reference to ax and can keep customizing it after the call (title, scale, limits, etc.).
ax (matplotlib.axes.Axes or None, optional) – Axes to plot on. Required if plot is True.
distance (int, optional) – Required minimal distance (>= 1), in frequency bins, between neighbouring peaks. Smaller peaks are removed first until the condition is fulfilled for all remaining peaks. Default is 6.
prominence (float, optional) – Required prominence of peaks, in dB. Default is 10.
height (float, optional) – Required height of peaks, in dB (absolute). Default is None, which uses a threshold above the local noise floor set by false_alarm_rate.
false_alarm_rate (float, optional) – Target probability that noise alone produces a false tone in a spectrum, used for the default threshold (ignored if height is given). Must be in (0, 1). Lower values detect fewer spurious tones but need tones to stand out more from the noise. Default is 1e-3.
bw (float, optional) – Bandwidth of the analysis, in the same units as fs. Default is
fs / 2. Only tones whose peak is at or below bw are reported, and noise_db includes only the bins up to bw. Use it when only a band of the spectrum matters, e.g. with noise shaped out of the band (sigma-delta) or an audio band. A tone that straddles bw keeps only its bins up to bw, so its power is underestimated. The default threshold is computed for the number of bins in the band, so false_alarm_rate applies to the band.
- Returns:
The analysis results (DC, noise and the detected tones). See
SpecResultfor the fields. UseSpecResult.to_dict()to get them as a dictionary.- Return type:
- Raises:
TypeError – If x or window is complex or not numeric.
ValueError – If plot is True and no ax is given, or if an input is invalid: x not 1-D, shorter than 32 samples or containing NaN/inf, fs not positive, bw not in
(0, fs / 2]or inside the DC component of the spectrum, window not the same length as x, or false_alarm_rate not in (0, 1).
Notes
A component exactly at fs/2 (e.g. the 2nd harmonic of a fundamental at fs/4) is sampled as
A * cos(phase) * (-1)**n, so its measured power isA**2 * cos(phase)**2and depends on its phase. Components within about one bin of fs/2 (or of DC) overlap their mirror image and are also phase dependent.Examples
A signal with a DC offset of 0.5 and two tones, sampled at 1 kHz:
>>> import numpy as np >>> from harm_analysis import spec_analysis >>> fs = 1000 >>> t = np.arange(4096) / fs >>> rng = np.random.default_rng(0) >>> x = 0.5 + np.cos(2 * np.pi * 100.3 * t) + 0.1 * np.cos(2 * np.pi * 250.7 * t) >>> x = x + rng.normal(0, 1e-4, t.size) >>> results = spec_analysis(x, fs=fs) >>> round(results.dc, 3) 0.5 >>> results.tones_freq.round(1).tolist() [100.3, 250.7] >>> results.tones_db.round(1).tolist() [-3.0, -23.0]
Results¶
Both functions return a result object with one attribute per metric. Use
to_dict() to get the values as a dictionary, for example to print or serialize
them.
- class harm_analysis.HarmResult(fund_db, fund_freq, harm_freq, harm_db, dc_db, noise_db, thd_db, snr_db, sinad_db, thdn_db, total_noise_db)[source]¶
Results of
harm_analysis().All powers are in dB relative to the input signal’s units squared, and all frequencies are in the same units as
fs. A power of zero is reported as-infdB.- harm_freq¶
Frequency of each harmonic. Empty if no harmonics were analyzed.
- Type:
- harm_db¶
Power of each harmonic in decibels. Empty if no harmonics were analyzed.
- Type:
- thd_db¶
Total harmonic distortion in decibels.
numpy.nanifn_harmis 0 or if all harmonics are outside the bandwidth.- Type:
- total_noise_db¶
Noise power in decibels integrated over the whole spectrum, from DC to fs/2, also beyond bw (DC, the fundamental and the analyzed harmonics excluded; harmonics above bw are not analyzed, so they count as noise here). Equal to noise_db when bw is not given.
- Type:
- class harm_analysis.SpecResult(dc, dc_db, noise_db, tones_db, tones_freq)[source]¶
Results of
spec_analysis().All powers are in dB relative to the input signal’s units squared, and all frequencies are in the same units as
fs. A power of zero is reported as-infdB.- tones_db¶
Power of each detected tone in decibels. Empty if no tones were detected.
- Type:
- tones_freq¶
Frequency of each detected tone. Empty if no tones were detected.
- Type: