harm-analysis 2.0.0__tar.gz → 2.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/PKG-INFO +47 -5
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/README.md +46 -4
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/pyproject.toml +1 -1
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/_harmonic.py +2 -5
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/_spectral.py +26 -4
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/_spectrum.py +9 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/cli.py +16 -6
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/mcp_server.py +5 -1
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_cli.py +25 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_mcp_server.py +10 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_spectrum_analysis.py +65 -1
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/LICENSE +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/__init__.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/_harm_analysis.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/_plotting.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/_results.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/src/harm_analysis/py.typed +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/__init__.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/conftest.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_docs_cli_examples.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_edge_cases.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_fft_length.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_harm_analysis.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_plotting.py +0 -0
- {harm_analysis-2.0.0 → harm_analysis-2.1.0}/tests/test_validation.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: harm-analysis
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: A Python library to estimate parameters from a signal containing a tone.
|
|
5
5
|
Keywords: DSP,Signal-Processing,THD,SNR
|
|
6
6
|
Author-Email: Eric Macedo <ericsmacedo@gmail.com>
|
|
@@ -43,6 +43,12 @@ Description-Content-Type: text/markdown
|
|
|
43
43
|
* [Sources](https://github.com/ericsmacedo/harm-analysis)
|
|
44
44
|
* [Issues](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
45
45
|
|
|
46
|
+
**THD, SNR, SINAD and THD+N of a signal in one call, from its FFT spectrum.**
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install harm-analysis
|
|
50
|
+
```
|
|
51
|
+
|
|
46
52
|
## Introduction
|
|
47
53
|
|
|
48
54
|
The harmonic analysis package uses FFT to estimate parameters of an input signal.
|
|
@@ -55,13 +61,51 @@ The package provides two main functions:
|
|
|
55
61
|

|
|
56
62
|
<!-- overview-end -->
|
|
57
63
|
|
|
64
|
+
## Why harm-analysis?
|
|
65
|
+
|
|
66
|
+
- **One call, all the metrics**: fundamental, harmonics, DC, noise, THD, SNR, SINAD and THD+N.
|
|
67
|
+
- **Works on real data**: no coherent sampling needed; windowing and spectral leakage are handled for you.
|
|
68
|
+
- **No known tone?** `spec_analysis` finds DC, tones and the noise floor by itself.
|
|
69
|
+
- **Plots included**: pass `plot=True` to draw the annotated spectrum.
|
|
70
|
+
- **Command line too**: `harm-analysis` and `spec-analysis` analyze a text file directly.
|
|
71
|
+
|
|
72
|
+
## Example
|
|
73
|
+
|
|
74
|
+
A 1 kHz tone with a -60 dB second harmonic and some noise:
|
|
75
|
+
|
|
58
76
|
```python
|
|
77
|
+
import numpy as np
|
|
59
78
|
from harm_analysis import harm_analysis
|
|
60
79
|
|
|
61
|
-
|
|
62
|
-
|
|
80
|
+
rng = np.random.default_rng(0)
|
|
81
|
+
fs = 48000
|
|
82
|
+
t = np.arange(4096) / fs
|
|
83
|
+
x = np.sin(2 * np.pi * 1000 * t) + 1e-3 * np.sin(2 * np.pi * 2000 * t) + 1e-4 * rng.standard_normal(t.size)
|
|
84
|
+
|
|
85
|
+
r = harm_analysis(x, fs=fs)
|
|
86
|
+
for name, value in r.to_dict().items():
|
|
87
|
+
print(f"{name:>15}: {np.round(value, 2)}")
|
|
63
88
|
```
|
|
64
89
|
|
|
90
|
+
Output:
|
|
91
|
+
|
|
92
|
+
```text
|
|
93
|
+
fund_db: -3.01
|
|
94
|
+
fund_freq: 1000.0
|
|
95
|
+
harm_freq: [1999.97 3022.05 4023.99 4958.22 5971.06]
|
|
96
|
+
harm_db: [ -63. -107.8 -103.57 -105.74 -103.45]
|
|
97
|
+
dc_db: -109.41
|
|
98
|
+
noise_db: -79.32
|
|
99
|
+
thd_db: -59.99
|
|
100
|
+
snr_db: 76.31
|
|
101
|
+
sinad_db: 59.89
|
|
102
|
+
thdn_db: -59.89
|
|
103
|
+
total_noise_db: -79.32
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Powers are in dB (a unit-amplitude sine is -3 dB); `thd_db`, `snr_db`, `sinad_db`
|
|
107
|
+
and `thdn_db` are relative to the fundamental.
|
|
108
|
+
|
|
65
109
|
See [usage](./docs/usage.md) for examples.
|
|
66
110
|
|
|
67
111
|
AI assistants (Claude, GitHub Copilot, ...) can run the analyses through the included
|
|
@@ -70,8 +114,6 @@ MCP server; see [AI assistants](./docs/ai.md).
|
|
|
70
114
|
|
|
71
115
|
## Installation
|
|
72
116
|
|
|
73
|
-
Installing it is pretty easy:
|
|
74
|
-
|
|
75
117
|
```bash
|
|
76
118
|
pip install harm-analysis
|
|
77
119
|
```
|
|
@@ -17,6 +17,12 @@
|
|
|
17
17
|
* [Sources](https://github.com/ericsmacedo/harm-analysis)
|
|
18
18
|
* [Issues](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
19
19
|
|
|
20
|
+
**THD, SNR, SINAD and THD+N of a signal in one call, from its FFT spectrum.**
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install harm-analysis
|
|
24
|
+
```
|
|
25
|
+
|
|
20
26
|
## Introduction
|
|
21
27
|
|
|
22
28
|
The harmonic analysis package uses FFT to estimate parameters of an input signal.
|
|
@@ -29,13 +35,51 @@ The package provides two main functions:
|
|
|
29
35
|

|
|
30
36
|
<!-- overview-end -->
|
|
31
37
|
|
|
38
|
+
## Why harm-analysis?
|
|
39
|
+
|
|
40
|
+
- **One call, all the metrics**: fundamental, harmonics, DC, noise, THD, SNR, SINAD and THD+N.
|
|
41
|
+
- **Works on real data**: no coherent sampling needed; windowing and spectral leakage are handled for you.
|
|
42
|
+
- **No known tone?** `spec_analysis` finds DC, tones and the noise floor by itself.
|
|
43
|
+
- **Plots included**: pass `plot=True` to draw the annotated spectrum.
|
|
44
|
+
- **Command line too**: `harm-analysis` and `spec-analysis` analyze a text file directly.
|
|
45
|
+
|
|
46
|
+
## Example
|
|
47
|
+
|
|
48
|
+
A 1 kHz tone with a -60 dB second harmonic and some noise:
|
|
49
|
+
|
|
32
50
|
```python
|
|
51
|
+
import numpy as np
|
|
33
52
|
from harm_analysis import harm_analysis
|
|
34
53
|
|
|
35
|
-
|
|
36
|
-
|
|
54
|
+
rng = np.random.default_rng(0)
|
|
55
|
+
fs = 48000
|
|
56
|
+
t = np.arange(4096) / fs
|
|
57
|
+
x = np.sin(2 * np.pi * 1000 * t) + 1e-3 * np.sin(2 * np.pi * 2000 * t) + 1e-4 * rng.standard_normal(t.size)
|
|
58
|
+
|
|
59
|
+
r = harm_analysis(x, fs=fs)
|
|
60
|
+
for name, value in r.to_dict().items():
|
|
61
|
+
print(f"{name:>15}: {np.round(value, 2)}")
|
|
37
62
|
```
|
|
38
63
|
|
|
64
|
+
Output:
|
|
65
|
+
|
|
66
|
+
```text
|
|
67
|
+
fund_db: -3.01
|
|
68
|
+
fund_freq: 1000.0
|
|
69
|
+
harm_freq: [1999.97 3022.05 4023.99 4958.22 5971.06]
|
|
70
|
+
harm_db: [ -63. -107.8 -103.57 -105.74 -103.45]
|
|
71
|
+
dc_db: -109.41
|
|
72
|
+
noise_db: -79.32
|
|
73
|
+
thd_db: -59.99
|
|
74
|
+
snr_db: 76.31
|
|
75
|
+
sinad_db: 59.89
|
|
76
|
+
thdn_db: -59.89
|
|
77
|
+
total_noise_db: -79.32
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Powers are in dB (a unit-amplitude sine is -3 dB); `thd_db`, `snr_db`, `sinad_db`
|
|
81
|
+
and `thdn_db` are relative to the fundamental.
|
|
82
|
+
|
|
39
83
|
See [usage](./docs/usage.md) for examples.
|
|
40
84
|
|
|
41
85
|
AI assistants (Claude, GitHub Copilot, ...) can run the analyses through the included
|
|
@@ -44,8 +88,6 @@ MCP server; see [AI assistants](./docs/ai.md).
|
|
|
44
88
|
|
|
45
89
|
## Installation
|
|
46
90
|
|
|
47
|
-
Installing it is pretty easy:
|
|
48
|
-
|
|
49
91
|
```bash
|
|
50
92
|
pip install harm-analysis
|
|
51
93
|
```
|
|
@@ -29,6 +29,7 @@ from ._plotting import _plot_harm
|
|
|
29
29
|
from ._results import HarmResult
|
|
30
30
|
from ._spectral import _MEDIAN_WINDOW, _detection_threshold_db
|
|
31
31
|
from ._spectrum import (
|
|
32
|
+
_check_bw_above_dc,
|
|
32
33
|
_find_dc_bins,
|
|
33
34
|
_find_freq_bins,
|
|
34
35
|
_int_noise_curve,
|
|
@@ -117,11 +118,7 @@ def _find_bins(x, n_harm, bw_bins, enbw_bins, freq_array, fund_freq=None, fund_b
|
|
|
117
118
|
dc_bins = np.arange(dc_end)
|
|
118
119
|
dc_pow = _power_from_bins(x, dc_bins, enbw_bins=enbw_bins, bw_bins=bw_bins)
|
|
119
120
|
|
|
120
|
-
|
|
121
|
-
raise ValueError(
|
|
122
|
-
f"`bw` is inside the DC component of the spectrum, which extends to {freq_array[dc_end]:.6g} "
|
|
123
|
-
"(in the units of `fs`). Use a larger `bw`."
|
|
124
|
-
)
|
|
121
|
+
_check_bw_above_dc(bw_bins, dc_end, freq_array)
|
|
125
122
|
|
|
126
123
|
if fund_bin is None:
|
|
127
124
|
# the fundamental frequency is found by searching for the bin with the
|
|
@@ -30,6 +30,7 @@ from scipy import signal
|
|
|
30
30
|
from ._plotting import _plot_spec
|
|
31
31
|
from ._results import SpecResult
|
|
32
32
|
from ._spectrum import (
|
|
33
|
+
_check_bw_above_dc,
|
|
33
34
|
_find_dc_bins,
|
|
34
35
|
_find_freq_bins,
|
|
35
36
|
_int_noise_curve,
|
|
@@ -78,11 +79,18 @@ def _detection_threshold_db(n_bins: int, false_alarm_rate: float) -> float:
|
|
|
78
79
|
|
|
79
80
|
|
|
80
81
|
def _find_tones(x, enbw_bins, bw_bins, distance, prominence, height, false_alarm_rate, min_bin=0): # noqa: PLR0913
|
|
82
|
+
"""Find the tones whose peak bin is between `min_bin` and `bw_bins` (inclusive).
|
|
83
|
+
|
|
84
|
+
Peaks are searched in the whole spectrum, so the rolling median and the fs/2 handling
|
|
85
|
+
are the same with or without a `bw`, and then the peaks above `bw_bins` are dropped.
|
|
86
|
+
The detection threshold uses the number of bins in the band (``bw_bins + 1``), so that
|
|
87
|
+
`false_alarm_rate` applies to the analyzed band.
|
|
88
|
+
"""
|
|
81
89
|
x_size = x.size
|
|
82
90
|
x_db = _to_db(x)
|
|
83
91
|
|
|
84
92
|
if height is None:
|
|
85
|
-
height = _rolling_median_bn(x_db, _MEDIAN_WINDOW) + _detection_threshold_db(
|
|
93
|
+
height = _rolling_median_bn(x_db, _MEDIAN_WINDOW) + _detection_threshold_db(bw_bins + 1, false_alarm_rate)
|
|
86
94
|
else:
|
|
87
95
|
height = np.ones(x_size) * height
|
|
88
96
|
|
|
@@ -104,6 +112,9 @@ def _find_tones(x, enbw_bins, bw_bins, distance, prominence, height, false_alarm
|
|
|
104
112
|
elif np.all(np.abs(peaks - fs_2_bin) > distance):
|
|
105
113
|
peaks = np.append(peaks, fs_2_bin)
|
|
106
114
|
|
|
115
|
+
# Tones above the analysis band are not analyzed
|
|
116
|
+
peaks = peaks[peaks <= bw_bins]
|
|
117
|
+
|
|
107
118
|
if peaks.size == 0:
|
|
108
119
|
tones_pow = np.array([])
|
|
109
120
|
tones_loc = np.array([])
|
|
@@ -138,6 +149,7 @@ def spec_analysis( # noqa: PLR0913
|
|
|
138
149
|
prominence: float = 10,
|
|
139
150
|
height: float | None = None,
|
|
140
151
|
false_alarm_rate: float = 1e-3,
|
|
152
|
+
bw: float | None = None,
|
|
141
153
|
) -> SpecResult:
|
|
142
154
|
"""Spectral Analysis.
|
|
143
155
|
|
|
@@ -146,7 +158,7 @@ def spec_analysis( # noqa: PLR0913
|
|
|
146
158
|
|
|
147
159
|
A tone is a peak in the power spectrum (in dB) that meets the `distance`,
|
|
148
160
|
`prominence` and `height` criteria (see :func:`scipy.signal.find_peaks`). All
|
|
149
|
-
bins that are not DC or part of a tone are counted as noise.
|
|
161
|
+
bins up to `bw` that are not DC or part of a tone are counted as noise.
|
|
150
162
|
|
|
151
163
|
By default a peak must stand out from the local noise floor (the median of the
|
|
152
164
|
surrounding bins) by a margin derived from `false_alarm_rate`: noise alone
|
|
@@ -186,6 +198,14 @@ def spec_analysis( # noqa: PLR0913
|
|
|
186
198
|
for the default threshold (ignored if `height` is given). Must be in (0, 1).
|
|
187
199
|
Lower values detect fewer spurious tones but need tones to stand out more from
|
|
188
200
|
the noise. Default is 1e-3.
|
|
201
|
+
bw : float, optional
|
|
202
|
+
Bandwidth of the analysis, in the same units as `fs`. Default is ``fs / 2``.
|
|
203
|
+
Only tones whose peak is at or below `bw` are reported, and `noise_db`
|
|
204
|
+
includes only the bins up to `bw`. Use it when only a band of the
|
|
205
|
+
spectrum matters, e.g. with noise shaped out of the band (sigma-delta) or an
|
|
206
|
+
audio band. A tone that straddles `bw` keeps only its bins up to `bw`, so its
|
|
207
|
+
power is underestimated. The default threshold is computed for the number of
|
|
208
|
+
bins in the band, so `false_alarm_rate` applies to the band.
|
|
189
209
|
|
|
190
210
|
Returns
|
|
191
211
|
-------
|
|
@@ -201,6 +221,7 @@ def spec_analysis( # noqa: PLR0913
|
|
|
201
221
|
ValueError
|
|
202
222
|
If `plot` is True and no `ax` is given, or if an input is invalid: `x` not
|
|
203
223
|
1-D, shorter than 32 samples or containing NaN/inf, `fs` not positive,
|
|
224
|
+
`bw` not in ``(0, fs / 2]`` or inside the DC component of the spectrum,
|
|
204
225
|
`window` not the same length as `x`, or `false_alarm_rate` not in (0, 1).
|
|
205
226
|
|
|
206
227
|
Notes
|
|
@@ -232,15 +253,16 @@ def spec_analysis( # noqa: PLR0913
|
|
|
232
253
|
if plot and ax is None:
|
|
233
254
|
raise ValueError("An `ax` must be provided when `plot` is True.")
|
|
234
255
|
|
|
235
|
-
x = _validate_inputs(x, fs, window=window)
|
|
256
|
+
x = _validate_inputs(x, fs, window=window, bw=bw)
|
|
236
257
|
if not 0 < false_alarm_rate < 1:
|
|
237
258
|
raise ValueError(f"`false_alarm_rate` must be in (0, 1), got {false_alarm_rate}.")
|
|
238
259
|
|
|
239
|
-
x_fft_pow, f_array, enbw_bins, bw_bins = _power_spectrum(x, fs=fs, bw=
|
|
260
|
+
x_fft_pow, f_array, enbw_bins, bw_bins = _power_spectrum(x, fs=fs, bw=bw, window=window)
|
|
240
261
|
sig_len = len(x)
|
|
241
262
|
|
|
242
263
|
dc_end = _find_dc_bins(x_fft_pow)
|
|
243
264
|
dc_bins = np.arange(dc_end)
|
|
265
|
+
_check_bw_above_dc(bw_bins, dc_end, f_array)
|
|
244
266
|
|
|
245
267
|
tones_pow, tones_loc, tones_bins = _find_tones(
|
|
246
268
|
x_fft_pow,
|
|
@@ -329,6 +329,15 @@ def _to_db(power):
|
|
|
329
329
|
return 10 * np.log10(power)
|
|
330
330
|
|
|
331
331
|
|
|
332
|
+
def _check_bw_above_dc(bw_bins, dc_end, freq_array):
|
|
333
|
+
"""Raise a ValueError if the analysis band (`bw_bins`) ends inside the DC bins."""
|
|
334
|
+
if bw_bins <= dc_end:
|
|
335
|
+
raise ValueError(
|
|
336
|
+
f"`bw` is inside the DC component of the spectrum, which extends to {freq_array[dc_end]:.6g} "
|
|
337
|
+
"(in the units of `fs`). Use a larger `bw`."
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
|
|
332
341
|
def _int_noise_curve(x: NDArray[np.float64], noise_bins: NDArray[np.integer]):
|
|
333
342
|
total_noise_array = _mask_array(x, noise_bins)
|
|
334
343
|
total_int_noise = np.cumsum(total_noise_array)
|
|
@@ -100,6 +100,14 @@ opt_fund_freq = click.option(
|
|
|
100
100
|
"spectral component. Use it if the data may contain a stronger tone."
|
|
101
101
|
),
|
|
102
102
|
)
|
|
103
|
+
opt_bw = click.option(
|
|
104
|
+
"--bw",
|
|
105
|
+
type=float,
|
|
106
|
+
default=None,
|
|
107
|
+
help=(
|
|
108
|
+
"Bandwidth of the analysis, in the units of --fs. Default: fs/2. Only the spectrum from DC to --bw is analyzed."
|
|
109
|
+
),
|
|
110
|
+
)
|
|
103
111
|
opt_json = click.option(
|
|
104
112
|
"--json",
|
|
105
113
|
"as_json",
|
|
@@ -179,16 +187,17 @@ def _params_table(params):
|
|
|
179
187
|
@opt_plot
|
|
180
188
|
@opt_sfactor
|
|
181
189
|
@opt_fund_freq
|
|
190
|
+
@opt_bw
|
|
182
191
|
@opt_json
|
|
183
|
-
def harm_analysis_cmd(filename, fs, plot, sep, sfactor, fund_freq, as_json): # noqa: PLR0913
|
|
192
|
+
def harm_analysis_cmd(filename, fs, plot, sep, sfactor, fund_freq, bw, as_json): # noqa: PLR0913
|
|
184
193
|
"""Runs the harm_analysis function for a file containing time domain data."""
|
|
185
194
|
data = _load_data(filename, sep, sfactor)
|
|
186
195
|
|
|
187
196
|
if plot:
|
|
188
197
|
data_ax, spec_ax = _plot_axes()
|
|
189
|
-
results = harm_analysis(data, fs=fs, plot=True, ax=spec_ax, fund_freq=fund_freq)
|
|
198
|
+
results = harm_analysis(data, fs=fs, plot=True, ax=spec_ax, fund_freq=fund_freq, bw=bw)
|
|
190
199
|
else:
|
|
191
|
-
results = harm_analysis(data, fs=fs, fund_freq=fund_freq)
|
|
200
|
+
results = harm_analysis(data, fs=fs, fund_freq=fund_freq, bw=bw)
|
|
192
201
|
|
|
193
202
|
if as_json:
|
|
194
203
|
_print_json(results)
|
|
@@ -206,16 +215,17 @@ def harm_analysis_cmd(filename, fs, plot, sep, sfactor, fund_freq, as_json): #
|
|
|
206
215
|
@opt_plot
|
|
207
216
|
@opt_sep
|
|
208
217
|
@opt_sfactor
|
|
218
|
+
@opt_bw
|
|
209
219
|
@opt_json
|
|
210
|
-
def spec_analysis_cmd(filename, fs, plot, sep, sfactor, as_json): # noqa: PLR0913
|
|
220
|
+
def spec_analysis_cmd(filename, fs, plot, sep, sfactor, bw, as_json): # noqa: PLR0913
|
|
211
221
|
"""Runs the spec_analysis function for a file containing time domain data."""
|
|
212
222
|
data = _load_data(filename, sep, sfactor)
|
|
213
223
|
|
|
214
224
|
if plot:
|
|
215
225
|
data_ax, spec_ax = _plot_axes()
|
|
216
|
-
results = spec_analysis(data, fs=fs, plot=True, ax=spec_ax)
|
|
226
|
+
results = spec_analysis(data, fs=fs, plot=True, ax=spec_ax, bw=bw)
|
|
217
227
|
else:
|
|
218
|
-
results = spec_analysis(data, fs=fs)
|
|
228
|
+
results = spec_analysis(data, fs=fs, bw=bw)
|
|
219
229
|
|
|
220
230
|
if as_json:
|
|
221
231
|
_print_json(results)
|
|
@@ -134,6 +134,7 @@ def run_spec_analysis(
|
|
|
134
134
|
fs: float,
|
|
135
135
|
file_path: str | None = None,
|
|
136
136
|
samples: list[float] | None = None,
|
|
137
|
+
bw: float | None = None,
|
|
137
138
|
delimiter: str | None = None,
|
|
138
139
|
) -> dict[str, Any]:
|
|
139
140
|
"""Detect DC, tones and noise in a signal without a known injected tone.
|
|
@@ -146,11 +147,14 @@ def run_spec_analysis(
|
|
|
146
147
|
fs: Sampling frequency, e.g. 1e6 for 1 MHz.
|
|
147
148
|
file_path: Path to a text file with the time-domain samples.
|
|
148
149
|
samples: The time-domain samples, as an alternative to file_path.
|
|
150
|
+
bw: Bandwidth of the analysis, in the units of fs (default fs / 2). Only tones up to
|
|
151
|
+
bw are reported and noise_db covers only the band up to bw, e.g. the signal band
|
|
152
|
+
of a sigma-delta converter whose noise is shaped above it.
|
|
149
153
|
delimiter: Column delimiter in the file (default: any whitespace).
|
|
150
154
|
"""
|
|
151
155
|
with _input_errors_as_tool_errors():
|
|
152
156
|
x = _load_signal(file_path, samples, delimiter)
|
|
153
|
-
results = spec_analysis(x, fs=fs)
|
|
157
|
+
results = spec_analysis(x, fs=fs, bw=bw)
|
|
154
158
|
return {key: _jsonable(value) for key, value in results.to_dict().items()}
|
|
155
159
|
|
|
156
160
|
|
|
@@ -255,3 +255,28 @@ def test_harm_cli_fund_freq(tmp_path):
|
|
|
255
255
|
assert result.exit_code == 0
|
|
256
256
|
assert np.isclose(default["fund_freq"], 0.1507, atol=1e-4)
|
|
257
257
|
assert np.isclose(json.loads(result.output)["fund_freq"], 0.1003, atol=1e-4)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def test_spec_cli_bw(tmp_path):
|
|
261
|
+
"""--bw is passed to spec_analysis: tones above it are not listed."""
|
|
262
|
+
n = 2**14
|
|
263
|
+
t = np.arange(n) / 1000
|
|
264
|
+
x = np.cos(2 * np.pi * 100.3 * t) + 0.1 * np.cos(2 * np.pi * 300.7 * t)
|
|
265
|
+
path = tmp_path / "data.txt"
|
|
266
|
+
np.savetxt(path, x + np.random.default_rng(1).normal(0, 1e-3, n), delimiter="\n")
|
|
267
|
+
|
|
268
|
+
result = CliRunner().invoke(spec_analysis_cmd, [str(path), "--fs", "1000", "--bw", "200", "--json"])
|
|
269
|
+
|
|
270
|
+
assert result.exit_code == 0
|
|
271
|
+
tones = json.loads(result.output)["tones_freq"]
|
|
272
|
+
assert np.allclose(tones, [100.3], atol=0.01)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def test_harm_cli_bw(tmp_path):
|
|
276
|
+
"""--bw is passed to harm_analysis: harmonics above it are not analyzed."""
|
|
277
|
+
path = _write_tone(tmp_path)
|
|
278
|
+
|
|
279
|
+
result = CliRunner().invoke(harm_analysis_cmd, [path, "--fs", "1", "--bw", "0.15", "--json"])
|
|
280
|
+
|
|
281
|
+
assert result.exit_code == 0
|
|
282
|
+
assert json.loads(result.output)["harm_freq"] == []
|
|
@@ -131,3 +131,13 @@ def test_harm_analysis_fund_freq():
|
|
|
131
131
|
assert not result.is_error
|
|
132
132
|
assert np.isclose(default["fund_freq"], 150.7, atol=0.05)
|
|
133
133
|
assert np.isclose(result.structured_content["fund_freq"], 100.3, atol=0.05)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_spec_analysis_bw():
|
|
137
|
+
"""run_spec_analysis passes bw on: noise_db covers only the band up to bw."""
|
|
138
|
+
result = _call("run_spec_analysis", {"fs": FS, "samples": SIGNAL.tolist(), "bw": 150.0})
|
|
139
|
+
|
|
140
|
+
assert not result.is_error
|
|
141
|
+
expected = spec_analysis(SIGNAL, fs=FS, bw=150.0)
|
|
142
|
+
assert np.isclose(result.structured_content["noise_db"], expected.noise_db)
|
|
143
|
+
assert np.allclose(result.structured_content["tones_freq"], expected.tones_freq)
|
|
@@ -29,7 +29,7 @@ import matplotlib.pyplot as plt
|
|
|
29
29
|
import numpy as np
|
|
30
30
|
from pytest import mark, raises
|
|
31
31
|
|
|
32
|
-
from harm_analysis import SpecResult, spec_analysis
|
|
32
|
+
from harm_analysis import SpecResult, harm_analysis, spec_analysis
|
|
33
33
|
from harm_analysis._spectral import _detection_threshold_db
|
|
34
34
|
from harm_analysis._spectrum import _to_db
|
|
35
35
|
|
|
@@ -213,3 +213,67 @@ def test_spec_analysis_invalid_false_alarm_rate(rate):
|
|
|
213
213
|
"""false_alarm_rate must be in (0, 1)."""
|
|
214
214
|
with raises(ValueError, match="false_alarm_rate"):
|
|
215
215
|
spec_analysis(np.random.default_rng(0).normal(0, 1, 1024), false_alarm_rate=rate)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _shaped_noise_signal():
|
|
219
|
+
"""A 1 kHz tone at -63 dB with first-order shaped noise (sigma-delta style), fs = 10 MHz."""
|
|
220
|
+
fs, n = 10e6, 2**18
|
|
221
|
+
t = np.arange(n) / fs
|
|
222
|
+
noise = np.diff(np.random.default_rng(1).normal(0, 1, n + 1))
|
|
223
|
+
return fs, 0.001 * np.sin(2 * np.pi * 1e3 * t) + noise
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def test_spec_analysis_bw_in_band_noise():
|
|
227
|
+
"""With bw, noise_db is the in-band noise only, the same as harm_analysis with that bw."""
|
|
228
|
+
fs, x = _shaped_noise_signal()
|
|
229
|
+
|
|
230
|
+
full = spec_analysis(x, fs=fs)
|
|
231
|
+
in_band = spec_analysis(x, fs=fs, bw=5e3)
|
|
232
|
+
|
|
233
|
+
assert in_band.noise_db < full.noise_db - 60
|
|
234
|
+
assert np.isclose(in_band.noise_db, harm_analysis(x, fs=fs, n_harm=0, bw=5e3).noise_db)
|
|
235
|
+
assert np.allclose(in_band.tones_freq, [1e3], rtol=1e-3)
|
|
236
|
+
assert np.isclose(in_band.dc_db, full.dc_db)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def test_spec_analysis_bw_drops_tones_above_band():
|
|
240
|
+
"""Tones above bw are not reported; the ones below are unchanged."""
|
|
241
|
+
n, fs = 2**14, 1000
|
|
242
|
+
t = np.arange(n) / fs
|
|
243
|
+
x = np.cos(2 * np.pi * 100.3 * t) + 0.1 * np.cos(2 * np.pi * 300.7 * t)
|
|
244
|
+
x = x + np.random.default_rng(0).normal(0, 1e-4, n)
|
|
245
|
+
|
|
246
|
+
full = spec_analysis(x, fs=fs)
|
|
247
|
+
in_band = spec_analysis(x, fs=fs, bw=200)
|
|
248
|
+
|
|
249
|
+
assert np.allclose(full.tones_freq, [100.3, 300.7], atol=0.01)
|
|
250
|
+
assert np.allclose(in_band.tones_freq, [100.3], atol=0.01)
|
|
251
|
+
assert np.allclose(in_band.tones_db, full.tones_db[:1])
|
|
252
|
+
assert in_band.noise_db < full.noise_db
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def test_spec_analysis_bw_equal_to_nyquist_is_default():
|
|
256
|
+
"""Bw = fs/2 gives the same result as no bw."""
|
|
257
|
+
n, fs = 4096, 1000
|
|
258
|
+
x = np.cos(2 * np.pi * 100.3 * np.arange(n) / fs) + np.random.default_rng(0).normal(0, 1e-3, n)
|
|
259
|
+
|
|
260
|
+
a, b = spec_analysis(x, fs=fs, bw=fs / 2), spec_analysis(x, fs=fs)
|
|
261
|
+
assert a.noise_db == b.noise_db
|
|
262
|
+
assert np.array_equal(a.tones_freq, b.tones_freq)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def test_spec_analysis_bw_plot_marks_band():
|
|
266
|
+
"""With bw, the plot draws the bw marker."""
|
|
267
|
+
fs, x = _shaped_noise_signal()
|
|
268
|
+
fig, ax = plt.subplots()
|
|
269
|
+
spec_analysis(x, fs=fs, bw=5e3, plot=True, ax=ax)
|
|
270
|
+
assert "bw" in [line.get_label() for line in ax.lines]
|
|
271
|
+
plt.close(fig)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@mark.parametrize(("bw", "message"), [(0, "`bw` must be in"), (600, "`bw` must be in"), (0.1, "inside the DC")])
|
|
275
|
+
def test_spec_analysis_invalid_bw(bw, message):
|
|
276
|
+
"""Bw must be in (0, fs/2] and above the DC bins."""
|
|
277
|
+
x = np.random.default_rng(0).normal(0, 1, 1024)
|
|
278
|
+
with raises(ValueError, match=message):
|
|
279
|
+
spec_analysis(x, fs=1000, bw=bw)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|