harm-analysis 1.3.0__tar.gz → 1.4.1__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-1.3.0 → harm_analysis-1.4.1}/PKG-INFO +4 -6
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/README.md +2 -5
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/pyproject.toml +3 -1
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/src/harm_analysis/_harm_analysis.py +223 -223
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/src/harm_analysis/cli.py +13 -10
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/tests/test_cli.py +37 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/tests/test_harm_analysis.py +2 -57
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/tests/test_spectrum_analysis.py +64 -10
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/LICENSE +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/src/harm_analysis/__init__.py +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/tests/__init__.py +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/tests/conftest.py +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.1}/tests/test_data_cli.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: harm-analysis
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.1
|
|
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>
|
|
@@ -14,6 +14,7 @@ Project-URL: Homepage, https://github.com/ericsmacedo/harm-analysis
|
|
|
14
14
|
Project-URL: Documentation, https://harm-analysis.readthedocs.io/en/stable/
|
|
15
15
|
Project-URL: Bug Tracker, https://github.com/ericsmacedo/harm-analysis/issues
|
|
16
16
|
Requires-Python: <4.0,>=3.10.0
|
|
17
|
+
Requires-Dist: bottleneck>=1.6.0
|
|
17
18
|
Requires-Dist: click>=8.2.1
|
|
18
19
|
Requires-Dist: matplotlib>=3.10.3
|
|
19
20
|
Requires-Dist: numpy>=2.2.6
|
|
@@ -24,21 +25,18 @@ Description-Content-Type: text/markdown
|
|
|
24
25
|
|
|
25
26
|
[](https://badge.fury.io/py/harm-analysis)
|
|
26
27
|
[](https://github.com/ericsmacedo/harm-analysis/actions/workflows/main.yml)
|
|
27
|
-
[](https://harm-analysis.readthedocs.io/en/latest/)
|
|
28
29
|
[](https://coveralls.io/github/ericsmacedo/harm-analysis?branch=main)
|
|
29
30
|
[](https://pypi.python.org/pypi/harm-analysis)
|
|
30
31
|
[](https://semver.org/)
|
|
31
32
|
|
|
32
33
|
[](https://pypi.python.org/pypi/harm-analysis)
|
|
33
|
-
[](https://github.com/ericsmacedo/harm-analysis/graphs/contributors/)
|
|
34
34
|
[](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request)
|
|
35
35
|
[](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
36
|
-
[](https://github.com/ericsmacedo/harm-analysis/pulls)
|
|
37
|
-
[](https://github.com/ericsmacedo/harm-analysis/pulls?q=is%3Apr+is%3Aclosed)
|
|
38
36
|
|
|
39
37
|
# Harmonic Analysis package
|
|
40
38
|
|
|
41
|
-
* [Documentation](https://harm-analysis.readthedocs.io/en/
|
|
39
|
+
* [Documentation](https://harm-analysis.readthedocs.io/en/latest/)
|
|
42
40
|
* [PyPI](https://pypi.org/project/harm-analysis/)
|
|
43
41
|
* [Sources](https://github.com/ericsmacedo/harm-analysis)
|
|
44
42
|
* [Issues](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
@@ -1,21 +1,18 @@
|
|
|
1
1
|
|
|
2
2
|
[](https://badge.fury.io/py/harm-analysis)
|
|
3
3
|
[](https://github.com/ericsmacedo/harm-analysis/actions/workflows/main.yml)
|
|
4
|
-
[](https://harm-analysis.readthedocs.io/en/latest/)
|
|
5
5
|
[](https://coveralls.io/github/ericsmacedo/harm-analysis?branch=main)
|
|
6
6
|
[](https://pypi.python.org/pypi/harm-analysis)
|
|
7
7
|
[](https://semver.org/)
|
|
8
8
|
|
|
9
9
|
[](https://pypi.python.org/pypi/harm-analysis)
|
|
10
|
-
[](https://github.com/ericsmacedo/harm-analysis/graphs/contributors/)
|
|
11
10
|
[](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request)
|
|
12
11
|
[](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
13
|
-
[](https://github.com/ericsmacedo/harm-analysis/pulls)
|
|
14
|
-
[](https://github.com/ericsmacedo/harm-analysis/pulls?q=is%3Apr+is%3Aclosed)
|
|
15
12
|
|
|
16
13
|
# Harmonic Analysis package
|
|
17
14
|
|
|
18
|
-
* [Documentation](https://harm-analysis.readthedocs.io/en/
|
|
15
|
+
* [Documentation](https://harm-analysis.readthedocs.io/en/latest/)
|
|
19
16
|
* [PyPI](https://pypi.org/project/harm-analysis/)
|
|
20
17
|
* [Sources](https://github.com/ericsmacedo/harm-analysis)
|
|
21
18
|
* [Issues](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
@@ -16,6 +16,7 @@ classifiers = [
|
|
|
16
16
|
]
|
|
17
17
|
requires-python = ">=3.10.0,<4.0"
|
|
18
18
|
dependencies = [
|
|
19
|
+
"bottleneck>=1.6.0",
|
|
19
20
|
"click>=8.2.1",
|
|
20
21
|
"matplotlib>=3.10.3",
|
|
21
22
|
"numpy>=2.2.6",
|
|
@@ -28,7 +29,7 @@ keywords = [
|
|
|
28
29
|
"THD",
|
|
29
30
|
"SNR",
|
|
30
31
|
]
|
|
31
|
-
version = "1.
|
|
32
|
+
version = "1.4.1"
|
|
32
33
|
|
|
33
34
|
[project.urls]
|
|
34
35
|
Homepage = "https://github.com/ericsmacedo/harm-analysis"
|
|
@@ -54,6 +55,7 @@ dev = [
|
|
|
54
55
|
"pytest-cov>=5.0.0",
|
|
55
56
|
"ruff>=0.11.2",
|
|
56
57
|
"test2ref>=0.4.2",
|
|
58
|
+
"truststore>=0.10.4",
|
|
57
59
|
]
|
|
58
60
|
|
|
59
61
|
[build-system]
|
|
@@ -23,44 +23,25 @@
|
|
|
23
23
|
|
|
24
24
|
import sys
|
|
25
25
|
|
|
26
|
+
import bottleneck as bn
|
|
26
27
|
import numpy as np
|
|
27
28
|
from matplotlib.axes import Axes
|
|
28
|
-
from numpy.lib.stride_tricks import as_strided
|
|
29
29
|
from numpy.typing import NDArray
|
|
30
30
|
from scipy import signal
|
|
31
31
|
|
|
32
32
|
|
|
33
|
-
def
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
Parameters
|
|
37
|
-
----------
|
|
38
|
-
x : ndarray
|
|
39
|
-
Input 1D array.
|
|
40
|
-
window_size : int
|
|
41
|
-
Size of the sliding window (must be odd).
|
|
42
|
-
|
|
43
|
-
Returns:
|
|
44
|
-
-------
|
|
45
|
-
medians : ndarray
|
|
46
|
-
Array of the same length as x with rolling medians.
|
|
47
|
-
"""
|
|
48
|
-
if window_size % 2 == 0:
|
|
49
|
-
raise ValueError("window_size must be odd")
|
|
50
|
-
if window_size < 1:
|
|
51
|
-
raise ValueError("window_size must be >= 1")
|
|
52
|
-
|
|
33
|
+
def _rolling_median_bn(x, window_size):
|
|
34
|
+
if window_size % 2 == 0 or window_size < 1:
|
|
35
|
+
window_size += 1
|
|
53
36
|
k = window_size // 2
|
|
54
|
-
# Reflect padding at both ends
|
|
55
|
-
x_pad = np.r_[x[k:0:-1], x, x[-2 : -k - 2 : -1]]
|
|
56
37
|
|
|
57
|
-
#
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
38
|
+
# reflect padding (bn.move_median doesn't center by itself)
|
|
39
|
+
x_pad = np.pad(x, k, mode="reflect")
|
|
40
|
+
|
|
41
|
+
# bn.move_median uses a centered window when you pad manually
|
|
42
|
+
out = bn.move_median(x_pad, window=window_size, min_count=window_size)
|
|
61
43
|
|
|
62
|
-
|
|
63
|
-
return np.median(windows, axis=1)
|
|
44
|
+
return out[window_size - 1 :]
|
|
64
45
|
|
|
65
46
|
|
|
66
47
|
def _arg_x_as_expected(value):
|
|
@@ -80,38 +61,6 @@ def _arg_x_as_expected(value):
|
|
|
80
61
|
return value
|
|
81
62
|
|
|
82
63
|
|
|
83
|
-
def _rfft_length(n):
|
|
84
|
-
"""Compute the length of the real FFT (Fast Fourier Transform) result for a given
|
|
85
|
-
signal length.
|
|
86
|
-
|
|
87
|
-
Parameters
|
|
88
|
-
----------
|
|
89
|
-
n : int
|
|
90
|
-
The length of the input signal.
|
|
91
|
-
|
|
92
|
-
Returns:
|
|
93
|
-
-------
|
|
94
|
-
int
|
|
95
|
-
The length of the real FFT result for the input signal.
|
|
96
|
-
|
|
97
|
-
Notes:
|
|
98
|
-
-----
|
|
99
|
-
The length of the real FFT result is determined based on the input signal length:
|
|
100
|
-
- If `n` is even, the length is calculated as (n/2) + 1.
|
|
101
|
-
- If `n` is odd, the length is calculated as (n+1)/2.
|
|
102
|
-
|
|
103
|
-
Examples:
|
|
104
|
-
--------
|
|
105
|
-
>>> signal_length = 7
|
|
106
|
-
>>> result_length = rfft_length(signal_length)
|
|
107
|
-
>>> print(f"The length of np.fft.rfft(x) for a signal of length {signal_length} is: {result_length}")
|
|
108
|
-
The length of np.fft.rfft(x) for a signal of length 7 is: 4.
|
|
109
|
-
""" # noqa: D205
|
|
110
|
-
if n % 2 == 0:
|
|
111
|
-
return (n // 2) + 1
|
|
112
|
-
return (n + 1) // 2
|
|
113
|
-
|
|
114
|
-
|
|
115
64
|
def _win_metrics(x):
|
|
116
65
|
"""Compute the coherent gain and the equivalent noise bandwidth of a window.
|
|
117
66
|
|
|
@@ -174,7 +123,7 @@ def _fft_pow(x: NDArray[np.float64], win: NDArray[np.float64], n_fft: int, fs: f
|
|
|
174
123
|
return x_fft_pow, f_array
|
|
175
124
|
|
|
176
125
|
|
|
177
|
-
def _find_freq_bins(
|
|
126
|
+
def _find_freq_bins(x: NDArray[np.float64], idx: int, bw_bins: int, enbw_bins: float):
|
|
178
127
|
"""Find frequency Bins of fundamental and harmonics.
|
|
179
128
|
|
|
180
129
|
Finds the frequency bins of frequencies. The end/start of a frequency
|
|
@@ -184,44 +133,68 @@ def _find_freq_bins(x_fft: NDArray[np.float64], freq: NDArray[np.float64]) -> ND
|
|
|
184
133
|
|
|
185
134
|
Arguments:
|
|
186
135
|
---------
|
|
187
|
-
|
|
188
|
-
|
|
136
|
+
x: NDArray
|
|
137
|
+
Input signal
|
|
138
|
+
|
|
139
|
+
idx: int
|
|
140
|
+
index indicating where to look for local maxima
|
|
189
141
|
|
|
190
|
-
|
|
191
|
-
|
|
142
|
+
bw_bins: int
|
|
143
|
+
Bandwidth to consider when calculating parameters
|
|
192
144
|
|
|
193
|
-
|
|
194
|
-
|
|
145
|
+
enbw_bins: float
|
|
146
|
+
Equivalent noise bandwidth of the window used, in bins.
|
|
195
147
|
|
|
196
148
|
Returns:
|
|
197
|
-
|
|
149
|
+
bins: NDArray
|
|
150
|
+
list of bins of peak
|
|
151
|
+
|
|
152
|
+
peak_loc: float
|
|
153
|
+
Location of the bin. Calculated using a weighted average of the peak bins
|
|
154
|
+
|
|
155
|
+
peak_val: float
|
|
156
|
+
power of the peak.
|
|
157
|
+
|
|
198
158
|
"""
|
|
199
|
-
|
|
159
|
+
x_size = x.size
|
|
160
|
+
|
|
161
|
+
# find local max near bin
|
|
162
|
+
width = 3
|
|
163
|
+
search_start = max(0, idx - width)
|
|
164
|
+
search_end = min(x_size, idx + width + 1)
|
|
165
|
+
local_max_idx = int(np.argmax(x[search_start:search_end]) + search_start)
|
|
166
|
+
|
|
167
|
+
# Search for start/end of the peak
|
|
168
|
+
start_idx = max(0, local_max_idx - 100)
|
|
169
|
+
end_idx = min(x_size, local_max_idx + 100)
|
|
200
170
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
171
|
+
if local_max_idx == 0:
|
|
172
|
+
peak_start = 0
|
|
173
|
+
else:
|
|
174
|
+
d_start = np.diff(x[start_idx:local_max_idx])
|
|
175
|
+
starts = np.where(d_start < 0)[0]
|
|
176
|
+
if starts.size == 0:
|
|
177
|
+
peak_start = start_idx
|
|
178
|
+
else:
|
|
179
|
+
peak_start = starts[-1] + start_idx + 1
|
|
205
180
|
|
|
206
|
-
|
|
207
|
-
|
|
181
|
+
if local_max_idx == x_size - 1:
|
|
182
|
+
peak_end = x_size
|
|
183
|
+
else:
|
|
184
|
+
d_end = np.diff(x[local_max_idx:end_idx])
|
|
185
|
+
ends = np.where(d_end > 0)[0]
|
|
186
|
+
if ends.size == 0:
|
|
187
|
+
peak_end = end_idx
|
|
188
|
+
else:
|
|
189
|
+
peak_end = ends[0] + local_max_idx + 1
|
|
208
190
|
|
|
209
|
-
|
|
210
|
-
end = freq
|
|
211
|
-
max_n_smp = 30
|
|
212
|
-
# find end of peak (right side)
|
|
213
|
-
for i in range(fft_length - freq - 1):
|
|
214
|
-
if x_fft[freq + i] - x_fft[freq + i + 1] <= 0 or (i > max_n_smp):
|
|
215
|
-
end = freq + i + 1
|
|
216
|
-
break
|
|
191
|
+
bins = np.arange(peak_start, peak_end)
|
|
217
192
|
|
|
218
|
-
#
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
start = freq - i
|
|
222
|
-
break
|
|
193
|
+
# Estimate precise location using a weighted average
|
|
194
|
+
peak_loc = np.average(bins, weights=x[bins])
|
|
195
|
+
peak_val = _power_from_bins(x, bins, enbw_bins=enbw_bins, bw_bins=bw_bins)
|
|
223
196
|
|
|
224
|
-
return
|
|
197
|
+
return peak_val, peak_loc, bins
|
|
225
198
|
|
|
226
199
|
|
|
227
200
|
def _find_dc_bins(x_fft: NDArray[np.float64]) -> int | np.signedinteger:
|
|
@@ -244,7 +217,7 @@ def _find_dc_bins(x_fft: NDArray[np.float64]) -> int | np.signedinteger:
|
|
|
244
217
|
return np.argmax(np.diff(x_fft[:50]) > 0) + 1
|
|
245
218
|
|
|
246
219
|
|
|
247
|
-
def _find_bins(x, n_harm, bw_bins):
|
|
220
|
+
def _find_bins(x, n_harm, bw_bins, enbw_bins):
|
|
248
221
|
"""Find all bins that belong to the fundamental, harmonics, DC, and noise.
|
|
249
222
|
|
|
250
223
|
Parameters
|
|
@@ -258,19 +231,6 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
258
231
|
n_harm : int
|
|
259
232
|
Number of harmonics to find
|
|
260
233
|
|
|
261
|
-
Returns:
|
|
262
|
-
-------
|
|
263
|
-
fund_bins : ndarray
|
|
264
|
-
Bins of fundamental frequency
|
|
265
|
-
harm_loc : ndarray
|
|
266
|
-
Locations of harmonics
|
|
267
|
-
harm_bins : ndarray
|
|
268
|
-
Bins of harmonics
|
|
269
|
-
dc_bins : ndarray
|
|
270
|
-
Bins of DC component
|
|
271
|
-
noise_bins : ndarray
|
|
272
|
-
Bins of noise
|
|
273
|
-
|
|
274
234
|
Notes:
|
|
275
235
|
-----
|
|
276
236
|
This function only works for the right-sided power spectrum (positive frequencies
|
|
@@ -279,6 +239,7 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
279
239
|
# Index of last dc bin
|
|
280
240
|
dc_end = _find_dc_bins(x)
|
|
281
241
|
dc_bins = np.arange(dc_end)
|
|
242
|
+
dc_pow = np.sum(x[dc_bins])
|
|
282
243
|
|
|
283
244
|
if bw_bins <= dc_end:
|
|
284
245
|
sys.exit("Error: max bandwidth is too low and is inside the detected dc bins.")
|
|
@@ -288,42 +249,61 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
288
249
|
max_loc = np.argmax(x[dc_end:bw_bins]) + dc_end
|
|
289
250
|
|
|
290
251
|
# list containing bins of fundamental
|
|
291
|
-
fund_bins = _find_freq_bins(x, max_loc)
|
|
292
|
-
|
|
293
|
-
# Estimate precise location using a weighted average
|
|
294
|
-
fund_loc = np.average(fund_bins, weights=x[fund_bins])
|
|
252
|
+
fund_pow, fund_loc, fund_bins = _find_freq_bins(x, max_loc, bw_bins=bw_bins, enbw_bins=enbw_bins)
|
|
295
253
|
|
|
296
254
|
# THD+N bins (all bins excluding DC and the fundamental)
|
|
297
255
|
thdn_bins = np.setdiff1d(np.arange(len(x)), np.concatenate((fund_bins, dc_bins)))
|
|
298
256
|
|
|
299
|
-
harm_loc, harm_bins = _find_harm(x, fund_loc, n_harm, bw_bins)
|
|
257
|
+
harm_pow, harm_loc, harm_bins = _find_harm(x, fund_loc, n_harm, bw_bins, enbw_bins=enbw_bins)
|
|
300
258
|
|
|
301
259
|
# Remaining bins are considered noise.
|
|
302
|
-
if harm_bins
|
|
303
|
-
noise_bins = thdn_bins
|
|
304
|
-
else:
|
|
260
|
+
if harm_bins.size > 0:
|
|
305
261
|
noise_bins = np.setdiff1d(thdn_bins, harm_bins)
|
|
262
|
+
else:
|
|
263
|
+
noise_bins = thdn_bins
|
|
264
|
+
|
|
265
|
+
noise_pow = _power_from_bins(x, noise_bins, enbw_bins=enbw_bins, bw_bins=bw_bins)
|
|
306
266
|
|
|
307
|
-
|
|
267
|
+
# According to wikipedia, THD+N in dB is equal to
|
|
268
|
+
# 10*log10(sum(harmonics power + Noise power)/fundamental power).
|
|
269
|
+
# THD+N is recriprocal to SINAD (SINAD_dB = -THD+N_dB)
|
|
270
|
+
thdn_pow = _power_from_bins(x, thdn_bins, enbw_bins=enbw_bins, bw_bins=bw_bins) / fund_pow
|
|
271
|
+
|
|
272
|
+
return (
|
|
273
|
+
(fund_pow, fund_loc, fund_bins),
|
|
274
|
+
(harm_pow, harm_loc, harm_bins),
|
|
275
|
+
(dc_pow, dc_bins),
|
|
276
|
+
(noise_pow, noise_bins),
|
|
277
|
+
(thdn_pow, thdn_bins),
|
|
278
|
+
)
|
|
308
279
|
|
|
309
280
|
|
|
310
|
-
def _find_harm(x, fund_loc, n_harm, bw_bins):
|
|
281
|
+
def _find_harm(x, fund_loc, n_harm, bw_bins, enbw_bins):
|
|
311
282
|
if n_harm <= 0:
|
|
312
|
-
|
|
313
|
-
|
|
283
|
+
harm_loc = np.array([])
|
|
284
|
+
harm_pow = np.array([])
|
|
285
|
+
harm_bins = np.array([])
|
|
314
286
|
else:
|
|
315
287
|
# calculate the frequency of the harmonics.
|
|
316
288
|
# frequencies > fs/2 are ignored
|
|
317
289
|
harm_loc = fund_loc * np.arange(2, n_harm + 2)
|
|
318
290
|
harm_loc = harm_loc[harm_loc <= bw_bins]
|
|
319
291
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
292
|
+
harm_loc_list = []
|
|
293
|
+
harm_pow_list = []
|
|
294
|
+
harm_bins_list = []
|
|
295
|
+
if harm_loc.size > 0:
|
|
296
|
+
for loc in harm_loc:
|
|
297
|
+
harm_pow, harm_loc, harm_bins = _find_freq_bins(x, int(loc), bw_bins=bw_bins, enbw_bins=enbw_bins)
|
|
298
|
+
harm_loc_list.append(harm_loc)
|
|
299
|
+
harm_pow_list.append(harm_pow)
|
|
300
|
+
harm_bins_list.append(harm_bins)
|
|
325
301
|
|
|
326
|
-
|
|
302
|
+
harm_loc = np.asarray(harm_loc_list)
|
|
303
|
+
harm_pow = np.asarray(harm_pow_list)
|
|
304
|
+
harm_bins = np.hstack(harm_bins_list)
|
|
305
|
+
|
|
306
|
+
return harm_pow, harm_loc, harm_bins
|
|
327
307
|
|
|
328
308
|
|
|
329
309
|
def _power_from_bins(x_fft_pow, bins, enbw_bins, bw_bins):
|
|
@@ -403,36 +383,50 @@ def _int_noise_curve(x: NDArray[np.float64], noise_bins: NDArray[np.float64]):
|
|
|
403
383
|
return 10 * np.log10(total_int_noise)
|
|
404
384
|
|
|
405
385
|
|
|
406
|
-
def _find_tones(x, enbw_bins, bw_bins):
|
|
386
|
+
def _find_tones(x, enbw_bins, bw_bins, distance, prominence, height): # noqa: PLR0913
|
|
387
|
+
x_size = x.size
|
|
407
388
|
x_db = 10 * np.log10(x)
|
|
408
389
|
|
|
409
|
-
|
|
410
|
-
|
|
390
|
+
if height is None:
|
|
391
|
+
height = _rolling_median_bn(x_db, 51) + 16
|
|
392
|
+
else:
|
|
393
|
+
height = np.ones(x_size) * height
|
|
411
394
|
|
|
412
395
|
peaks, _ = signal.find_peaks(
|
|
413
396
|
x_db,
|
|
414
|
-
distance=
|
|
415
|
-
height=
|
|
416
|
-
prominence=
|
|
397
|
+
distance=distance,
|
|
398
|
+
height=height,
|
|
399
|
+
prominence=prominence,
|
|
417
400
|
)
|
|
418
401
|
|
|
419
|
-
|
|
420
|
-
|
|
402
|
+
fs_2_bin = x_size - 1
|
|
403
|
+
|
|
404
|
+
if x_db[-1] > height[-1]:
|
|
405
|
+
if peaks.size == 0:
|
|
406
|
+
peaks = np.array([fs_2_bin])
|
|
407
|
+
elif np.all(np.abs(peaks - fs_2_bin) > distance):
|
|
408
|
+
peaks = np.append(peaks, fs_2_bin)
|
|
421
409
|
|
|
422
|
-
|
|
423
|
-
|
|
410
|
+
if peaks.size == 0:
|
|
411
|
+
tones_pow = np.array([])
|
|
412
|
+
tones_loc = np.array([])
|
|
413
|
+
tones_bins = np.array([])
|
|
424
414
|
|
|
425
|
-
tones_loc = np.empty(len(peaks))
|
|
426
|
-
tones_amp = np.empty(len(peaks))
|
|
427
|
-
for i, bins in enumerate(bin_groups):
|
|
428
|
-
tones_loc[i] = np.average(bins, weights=x_db[bins])
|
|
429
|
-
tones_amp[i] = _power_from_bins(x, bins, enbw_bins, bw_bins)
|
|
430
415
|
else:
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
416
|
+
tones_pow_list = []
|
|
417
|
+
tones_loc_list = []
|
|
418
|
+
tones_bins_list = []
|
|
419
|
+
for loc in peaks:
|
|
420
|
+
tone_pow, tone_loc, tone_bins = _find_freq_bins(x, int(loc), bw_bins=bw_bins, enbw_bins=enbw_bins)
|
|
421
|
+
tones_pow_list.append(tone_pow)
|
|
422
|
+
tones_loc_list.append(tone_loc)
|
|
423
|
+
tones_bins_list.append(tone_bins)
|
|
434
424
|
|
|
435
|
-
|
|
425
|
+
tones_pow = np.asarray(tones_pow_list)
|
|
426
|
+
tones_loc = np.asarray(tones_loc_list)
|
|
427
|
+
tones_bins = np.hstack(tones_bins_list)
|
|
428
|
+
|
|
429
|
+
return tones_pow, tones_loc, tones_bins
|
|
436
430
|
|
|
437
431
|
|
|
438
432
|
def _annotate(ax, x, y, text):
|
|
@@ -456,28 +450,24 @@ def _plot_spec( # noqa: PLR0913
|
|
|
456
450
|
dc_bins: NDArray[np.float64],
|
|
457
451
|
noise_bins: NDArray[np.float64],
|
|
458
452
|
int_noise: NDArray[np.float64],
|
|
459
|
-
enbw_bins: float,
|
|
460
453
|
bw_bins: int,
|
|
461
454
|
ax,
|
|
462
|
-
tones_freq:
|
|
463
|
-
tones_bins:
|
|
455
|
+
tones_freq: NDArray[np.float64],
|
|
456
|
+
tones_bins: NDArray[np.float64],
|
|
457
|
+
tones_db: NDArray[np.float64],
|
|
464
458
|
):
|
|
465
459
|
x_db = 10 * np.log10(x)
|
|
466
460
|
|
|
467
461
|
dc_noise_array = _mask_array(x_db, np.concatenate((dc_bins, noise_bins)))
|
|
468
462
|
|
|
469
|
-
if tones_bins
|
|
463
|
+
if tones_bins.size > 0:
|
|
470
464
|
tones_array = _mask_array(x_db, tones_bins)
|
|
471
465
|
ax.plot(freq_array, tones_array, label="Tones")
|
|
472
466
|
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
for i, bins in enumerate(bin_groups):
|
|
478
|
-
x_marker = tones_freq[i]
|
|
479
|
-
y_marker = 10 * np.log10(np.sum(x[bins] / enbw_bins))
|
|
480
|
-
_annotate(ax, x_marker, y_marker, f"T{i}")
|
|
467
|
+
for i in range(tones_db.size):
|
|
468
|
+
x_marker = tones_freq[i]
|
|
469
|
+
y_marker = tones_db[i]
|
|
470
|
+
_annotate(ax, x_marker, y_marker, f"T{i}")
|
|
481
471
|
|
|
482
472
|
ax.plot(freq_array, dc_noise_array, label="DC and Noise", color="black")
|
|
483
473
|
ax.plot(freq_array, int_noise, label="Integrated noise", color="green")
|
|
@@ -501,39 +491,35 @@ def _plot_harm( # noqa: PLR0913
|
|
|
501
491
|
noise_bins: NDArray[np.float64],
|
|
502
492
|
int_noise: NDArray[np.float64],
|
|
503
493
|
int_noise_p_harm: NDArray[np.float64],
|
|
504
|
-
enbw_bins: float,
|
|
505
494
|
bw_bins: int,
|
|
506
495
|
ax,
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
fund_bins:
|
|
510
|
-
harm_bins:
|
|
496
|
+
fund_pow_db: float,
|
|
497
|
+
fund_freq: float,
|
|
498
|
+
fund_bins: NDArray[np.float64],
|
|
499
|
+
harm_bins: NDArray[np.float64],
|
|
500
|
+
harm_freq: NDArray[np.float64],
|
|
501
|
+
harm_pow_db: NDArray[np.float64],
|
|
511
502
|
):
|
|
512
503
|
x_db = 10 * np.log10(x)
|
|
513
504
|
|
|
514
505
|
fund_array = _mask_array(x_db, fund_bins)
|
|
515
506
|
dc_noise_array = _mask_array(x_db, np.concatenate((dc_bins, noise_bins)))
|
|
516
507
|
|
|
517
|
-
if fund_bins
|
|
508
|
+
if fund_bins.size > 0:
|
|
518
509
|
ax.plot(freq_array, fund_array, label="Fundamental")
|
|
519
510
|
|
|
520
|
-
if fund_freq is not None:
|
|
521
511
|
x_marker = fund_freq
|
|
522
|
-
y_marker =
|
|
512
|
+
y_marker = fund_pow_db
|
|
523
513
|
_annotate(ax, x_marker, y_marker, "F")
|
|
524
514
|
|
|
525
|
-
if harm_bins
|
|
515
|
+
if harm_bins.size > 0:
|
|
526
516
|
harm_array = _mask_array(x_db, harm_bins)
|
|
527
517
|
ax.plot(freq_array, harm_array, label="Harmonics")
|
|
528
518
|
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
for i, bins in enumerate(bin_groups):
|
|
534
|
-
x_marker = harm_freq[i]
|
|
535
|
-
y_marker = 10 * np.log10(np.sum(x[bins] / enbw_bins))
|
|
536
|
-
_annotate(ax, x_marker, y_marker, f"{i + 1}")
|
|
519
|
+
for i in range(harm_pow_db.size):
|
|
520
|
+
x_marker = harm_freq[i]
|
|
521
|
+
y_marker = harm_pow_db[i]
|
|
522
|
+
_annotate(ax, x_marker, y_marker, f"H{i + 1}")
|
|
537
523
|
|
|
538
524
|
ax.plot(freq_array, dc_noise_array, label="DC and Noise", color="black")
|
|
539
525
|
ax.plot(freq_array, int_noise_p_harm, label="Integrated noise (inc. harmonics)", color="green")
|
|
@@ -551,15 +537,13 @@ def _plot_harm( # noqa: PLR0913
|
|
|
551
537
|
return ax
|
|
552
538
|
|
|
553
539
|
|
|
554
|
-
def
|
|
540
|
+
def _power_spectrum(
|
|
555
541
|
x: NDArray[np.float64],
|
|
556
542
|
fs: float = 1,
|
|
557
543
|
bw: float | None = None,
|
|
558
|
-
window=None,
|
|
544
|
+
window: None | NDArray[np.float64] = None,
|
|
559
545
|
):
|
|
560
546
|
sig_len = len(x)
|
|
561
|
-
# length of the array returned by the np.fft.rfft function
|
|
562
|
-
rfft_len = _rfft_length(sig_len)
|
|
563
547
|
|
|
564
548
|
if window is None:
|
|
565
549
|
window = signal.windows.hann(sig_len, sym=False)
|
|
@@ -573,7 +557,7 @@ def _harm_analysis(
|
|
|
573
557
|
|
|
574
558
|
# Convert bw to number of bins
|
|
575
559
|
if bw is None:
|
|
576
|
-
bw_bins =
|
|
560
|
+
bw_bins = x_fft_pow.size - 1
|
|
577
561
|
else:
|
|
578
562
|
bw_bins = np.argmin(np.abs(f_array - bw))
|
|
579
563
|
|
|
@@ -585,9 +569,9 @@ def harm_analysis( # noqa: PLR0913
|
|
|
585
569
|
fs: float = 1,
|
|
586
570
|
bw: float | None = None,
|
|
587
571
|
n_harm: int = 5,
|
|
588
|
-
window=None,
|
|
589
|
-
plot=False,
|
|
590
|
-
ax=None,
|
|
572
|
+
window: None | NDArray[np.float64] = None,
|
|
573
|
+
plot: bool = False,
|
|
574
|
+
ax: None | Axes = None,
|
|
591
575
|
):
|
|
592
576
|
"""Harmonic Analysis.
|
|
593
577
|
|
|
@@ -633,12 +617,14 @@ def harm_analysis( # noqa: PLR0913
|
|
|
633
617
|
- `fund_freq` Frequency of the fundamental tone.
|
|
634
618
|
- `dc_db`: DC power in decibels.
|
|
635
619
|
- `noise_db`: Noise power in decibels.
|
|
620
|
+
- `harm_db`: Harmonics power in decibels.
|
|
621
|
+
- `harm_freq`: Harmonics frequency in Hz.
|
|
636
622
|
- `thd_db`: Total harmonic distortion in decibels. Returns `numpy.nan` if
|
|
637
623
|
`n_harm` is 0 or if all harmonics are outside the bandwidth.
|
|
638
624
|
- `snr_db`: Signal-to-noise ratio in decibels.
|
|
639
625
|
- `sinad_db`: Signal-to-noise-and-distortion ratio in decibels.
|
|
640
626
|
- `thdn_db`: Total harmonic distortion plus noise in decibels.
|
|
641
|
-
- `
|
|
627
|
+
- `total_noise_and_dist_db`: Total noise and distortion in decibels.
|
|
642
628
|
|
|
643
629
|
ax : matplotlib axes
|
|
644
630
|
If plot is set to True, the Axes used for plotting is returned.
|
|
@@ -661,22 +647,19 @@ def harm_analysis( # noqa: PLR0913
|
|
|
661
647
|
FFT-based signal analysis and measurement. Application Note
|
|
662
648
|
041, National Instruments, 2000.
|
|
663
649
|
""" # noqa: D416
|
|
664
|
-
x_fft_pow, f_array, enbw_bins, bw_bins =
|
|
650
|
+
x_fft_pow, f_array, enbw_bins, bw_bins = _power_spectrum(x, fs=fs, bw=bw, window=window)
|
|
665
651
|
|
|
666
652
|
sig_len = len(x)
|
|
667
653
|
|
|
668
|
-
|
|
669
|
-
x=x_fft_pow, n_harm=n_harm, bw_bins=bw_bins
|
|
654
|
+
fund_info, harm_info, dc_info, noise_info, thdn_info = _find_bins(
|
|
655
|
+
x=x_fft_pow, n_harm=n_harm, bw_bins=bw_bins, enbw_bins=enbw_bins
|
|
670
656
|
)
|
|
671
657
|
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
# 10*log10(sum(harmonics power + Noise power)/fundamental power).
|
|
678
|
-
# THD+N is recriprocal to SINAD (SINAD_dB = -THD+N_dB)
|
|
679
|
-
thdn_power = _power_from_bins(x_fft_pow, thdn_bins, enbw_bins, bw_bins) / fund_power
|
|
658
|
+
fund_pow, fund_loc, fund_bins = fund_info
|
|
659
|
+
harm_pow, harm_loc, harm_bins = harm_info
|
|
660
|
+
dc_pow, dc_bins = dc_info
|
|
661
|
+
noise_pow, noise_bins = noise_info
|
|
662
|
+
thdn_pow, thdn_bins = thdn_info
|
|
680
663
|
|
|
681
664
|
# total integrated noise curve
|
|
682
665
|
int_noise = _int_noise_curve(x=x_fft_pow / enbw_bins, noise_bins=noise_bins)
|
|
@@ -684,32 +667,34 @@ def harm_analysis( # noqa: PLR0913
|
|
|
684
667
|
|
|
685
668
|
# Calculate THD, Signal Power and N metrics in dB
|
|
686
669
|
sig_freq = fund_loc * fs / sig_len
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
670
|
+
harm_freq = harm_loc * fs / sig_len
|
|
671
|
+
dc_db = 10 * np.log10(dc_pow)
|
|
672
|
+
sig_db = 10 * np.log10(fund_pow)
|
|
673
|
+
noise_db = 10 * np.log10(noise_pow)
|
|
674
|
+
harm_db = 10 * np.log10(harm_pow)
|
|
675
|
+
thdn_db = 10 * np.log10(thdn_pow)
|
|
676
|
+
snr_db = sig_db - noise_db
|
|
692
677
|
|
|
693
678
|
# THD in dB is equal to 10*log10(sum(harmonics power)/fundamental power)
|
|
694
|
-
if harm_bins
|
|
695
|
-
|
|
696
|
-
thd_db = 10 * np.log10(harm_power / fund_power)
|
|
679
|
+
if harm_bins.size > 0:
|
|
680
|
+
thd_db = 10 * np.log10(np.sum(harm_pow) / fund_pow)
|
|
697
681
|
harm_freq = harm_loc * fs / sig_len
|
|
698
682
|
else:
|
|
699
|
-
harm_power = np.nan
|
|
700
683
|
thd_db = np.nan
|
|
701
684
|
harm_freq = None
|
|
702
685
|
|
|
703
686
|
results = {
|
|
704
|
-
"fund_db":
|
|
687
|
+
"fund_db": sig_db,
|
|
705
688
|
"fund_freq": sig_freq,
|
|
689
|
+
"harm_freq": harm_freq,
|
|
690
|
+
"harm_db": harm_db,
|
|
706
691
|
"dc_db": dc_db,
|
|
707
|
-
"noise_db":
|
|
692
|
+
"noise_db": noise_db,
|
|
708
693
|
"thd_db": thd_db,
|
|
709
694
|
"snr_db": snr_db,
|
|
710
695
|
"sinad_db": -thdn_db,
|
|
711
696
|
"thdn_db": thdn_db,
|
|
712
|
-
"
|
|
697
|
+
"total_noise_and_dist_db": int_noise[-1],
|
|
713
698
|
}
|
|
714
699
|
|
|
715
700
|
if plot is False:
|
|
@@ -717,16 +702,17 @@ def harm_analysis( # noqa: PLR0913
|
|
|
717
702
|
ax = _plot_harm(
|
|
718
703
|
x=x_fft_pow,
|
|
719
704
|
fund_freq=sig_freq,
|
|
720
|
-
harm_freq=harm_freq,
|
|
721
705
|
freq_array=f_array,
|
|
722
706
|
dc_bins=dc_bins,
|
|
723
707
|
fund_bins=fund_bins,
|
|
708
|
+
fund_pow_db=sig_db,
|
|
724
709
|
harm_bins=harm_bins,
|
|
710
|
+
harm_freq=harm_freq,
|
|
711
|
+
harm_pow_db=harm_db,
|
|
725
712
|
noise_bins=noise_bins,
|
|
726
713
|
ax=ax,
|
|
727
714
|
int_noise=int_noise,
|
|
728
715
|
int_noise_p_harm=int_noise_p_harm,
|
|
729
|
-
enbw_bins=enbw_bins,
|
|
730
716
|
bw_bins=bw_bins,
|
|
731
717
|
)
|
|
732
718
|
|
|
@@ -736,10 +722,12 @@ def harm_analysis( # noqa: PLR0913
|
|
|
736
722
|
def spec_analysis( # noqa: PLR0913
|
|
737
723
|
x: NDArray[np.float64],
|
|
738
724
|
fs: float = 1,
|
|
739
|
-
bw: float | None = None,
|
|
740
725
|
window: None | NDArray[np.float64] = None,
|
|
741
|
-
plot=False,
|
|
726
|
+
plot: bool = False,
|
|
742
727
|
ax: None | Axes = None,
|
|
728
|
+
distance: int = 6,
|
|
729
|
+
prominence: int = 10,
|
|
730
|
+
height: int | None = None,
|
|
743
731
|
):
|
|
744
732
|
"""Spectral Analysis.
|
|
745
733
|
|
|
@@ -754,13 +742,18 @@ def spec_analysis( # noqa: PLR0913
|
|
|
754
742
|
window : array_like, optional
|
|
755
743
|
Window that will be multiplied with the signal. Default is
|
|
756
744
|
Hann window.
|
|
757
|
-
bw : float, optional
|
|
758
|
-
Bandwidth to use for the calculation of the metrics, in same units as fs.
|
|
759
745
|
plot : bool or None, optional
|
|
760
746
|
If True, the power spectrum result is plotted. If specified,
|
|
761
747
|
an `ax` must be provided, and the function returns a dictionary
|
|
762
748
|
with the results and the specified axes (`ax`). If plot is not set,
|
|
763
749
|
only the results are returned.
|
|
750
|
+
distance: number, optional
|
|
751
|
+
Required minimal horizontal distance (>= 1) in samples between neighbouring peaks.
|
|
752
|
+
Smaller peaks are removed first until the condition is fulfilled for all remaining peaks.
|
|
753
|
+
prominence: number or ndarray, optional
|
|
754
|
+
Required prominence of peaks in dB. Either a number, None, or an array matching x
|
|
755
|
+
height: number or ndarray or sequence, optional
|
|
756
|
+
Required height of peaks in dB. Either a number, None, an array matching x.
|
|
764
757
|
ax : plt.Axes or None, optional
|
|
765
758
|
Axes to be used for plotting. Required if plot is set to True.
|
|
766
759
|
|
|
@@ -769,30 +762,37 @@ def spec_analysis( # noqa: PLR0913
|
|
|
769
762
|
properties : dict
|
|
770
763
|
A dictionary containing the analysis results
|
|
771
764
|
|
|
772
|
-
- `
|
|
773
|
-
- `
|
|
765
|
+
- `dc`: DC level in the same units as the input signal x.
|
|
766
|
+
- `dc_db`: DC power in decibels.
|
|
767
|
+
- `noise_db`: Noise power in decibels.
|
|
768
|
+
- `tones_db`: Array with the amplitude of the detected tones in dB.
|
|
769
|
+
- `tones_freq`: Array with the frequencies of the detected tones in Hz.
|
|
770
|
+
|
|
774
771
|
|
|
775
772
|
plt.axes
|
|
776
773
|
If plot is set to True, the Axes used for plotting is returned.
|
|
777
774
|
|
|
778
775
|
""" # noqa: D416
|
|
779
|
-
x_fft_pow, f_array, enbw_bins, bw_bins =
|
|
776
|
+
x_fft_pow, f_array, enbw_bins, bw_bins = _power_spectrum(x, fs=fs, bw=None, window=window)
|
|
780
777
|
sig_len = len(x)
|
|
781
778
|
|
|
782
779
|
dc_end = _find_dc_bins(x_fft_pow)
|
|
783
780
|
dc_bins = np.arange(dc_end)
|
|
784
781
|
|
|
785
|
-
|
|
782
|
+
tones_pow, tones_loc, tones_bins = _find_tones(
|
|
783
|
+
x_fft_pow,
|
|
784
|
+
enbw_bins=enbw_bins,
|
|
785
|
+
bw_bins=bw_bins,
|
|
786
|
+
distance=distance,
|
|
787
|
+
prominence=prominence,
|
|
788
|
+
height=height,
|
|
789
|
+
)
|
|
786
790
|
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
tones_amp_db = 10 * np.log10(tones_amp)
|
|
790
|
-
else:
|
|
791
|
-
tones_freq = None
|
|
792
|
-
tones_amp_db = None
|
|
791
|
+
tones_freq = tones_loc * fs / sig_len
|
|
792
|
+
tones_db = 10 * np.log10(tones_pow)
|
|
793
793
|
|
|
794
794
|
# Obtain noise bins, by removing the DC bins from the bin list
|
|
795
|
-
if tones_bins
|
|
795
|
+
if tones_bins.size > 0:
|
|
796
796
|
noise_bins = np.setdiff1d(np.arange(len(x_fft_pow)), np.concatenate((dc_bins, tones_bins)))
|
|
797
797
|
else:
|
|
798
798
|
noise_bins = np.setdiff1d(np.arange(len(x_fft_pow)), dc_bins)
|
|
@@ -806,13 +806,13 @@ def spec_analysis( # noqa: PLR0913
|
|
|
806
806
|
# Calculate THD, Signal Power and N metrics in dB
|
|
807
807
|
dc_db = 10 * np.log10(dc_power)
|
|
808
808
|
dc = 10 ** (dc_db / 20)
|
|
809
|
-
|
|
809
|
+
noise_db = 10 * np.log10(noise_power)
|
|
810
810
|
|
|
811
811
|
results = {
|
|
812
812
|
"dc": dc,
|
|
813
813
|
"dc_db": dc_db,
|
|
814
|
-
"noise_db":
|
|
815
|
-
"
|
|
814
|
+
"noise_db": noise_db,
|
|
815
|
+
"tones_db": tones_db,
|
|
816
816
|
"tones_freq": tones_freq,
|
|
817
817
|
}
|
|
818
818
|
|
|
@@ -825,10 +825,10 @@ def spec_analysis( # noqa: PLR0913
|
|
|
825
825
|
noise_bins=noise_bins,
|
|
826
826
|
ax=ax,
|
|
827
827
|
int_noise=int_noise,
|
|
828
|
-
enbw_bins=enbw_bins,
|
|
829
828
|
bw_bins=bw_bins,
|
|
830
829
|
tones_freq=tones_freq,
|
|
831
830
|
tones_bins=tones_bins,
|
|
831
|
+
tones_db=tones_db,
|
|
832
832
|
)
|
|
833
833
|
|
|
834
834
|
return results, ax
|
|
@@ -91,7 +91,7 @@ def harm_analysis_cmd(filename, fs, plot, sep, sfactor):
|
|
|
91
91
|
@opt_sep
|
|
92
92
|
@opt_sfactor
|
|
93
93
|
def spec_analysis_cmd(filename, fs, plot, sep, sfactor):
|
|
94
|
-
"""Runs the
|
|
94
|
+
"""Runs the spec_analysis function for a file containing time domain data."""
|
|
95
95
|
# scaling factor
|
|
96
96
|
file_data = np.fromfile(filename, sep=sep) * eval(sfactor)
|
|
97
97
|
|
|
@@ -101,7 +101,7 @@ def spec_analysis_cmd(filename, fs, plot, sep, sfactor):
|
|
|
101
101
|
else:
|
|
102
102
|
results = spec_analysis(file_data, fs=fs)
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
tones_db = results["tones_db"]
|
|
105
105
|
tones_freq = results["tones_freq"]
|
|
106
106
|
|
|
107
107
|
table = Table(box=box.MARKDOWN, title="Parameters")
|
|
@@ -113,16 +113,19 @@ def spec_analysis_cmd(filename, fs, plot, sep, sfactor):
|
|
|
113
113
|
continue
|
|
114
114
|
table.add_row(key, str(value))
|
|
115
115
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
116
|
+
if tones_db.size == 0:
|
|
117
|
+
print("No tones detected")
|
|
118
|
+
else:
|
|
119
|
+
tones_table = Table(box=box.MARKDOWN, title="Tones")
|
|
120
|
+
tones_table.add_column("Tone")
|
|
121
|
+
tones_table.add_column("Amplitude [dB]")
|
|
122
|
+
tones_table.add_column("Frequency [Hz]")
|
|
120
123
|
|
|
121
|
-
|
|
122
|
-
|
|
124
|
+
for i, amp in enumerate(tones_db):
|
|
125
|
+
tones_table.add_row(f"T{i}", str(amp), str(tones_freq[i]))
|
|
123
126
|
|
|
124
|
-
|
|
125
|
-
|
|
127
|
+
console.print(table)
|
|
128
|
+
console.print(tones_table)
|
|
126
129
|
|
|
127
130
|
if plot is True:
|
|
128
131
|
ax[1].grid(True, which="both")
|
|
@@ -78,3 +78,40 @@ def test_cli(monkeypatch, cli_name):
|
|
|
78
78
|
assert "was_called" in called
|
|
79
79
|
|
|
80
80
|
assert result.exit_code == 0
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_cli_no_tones(monkeypatch):
|
|
84
|
+
"""Test for harm_analysis function.
|
|
85
|
+
|
|
86
|
+
Checks if the function can obtain results with less than 0.1 dB of error.
|
|
87
|
+
"""
|
|
88
|
+
# test signal
|
|
89
|
+
n = 2048
|
|
90
|
+
fs = 1000
|
|
91
|
+
t = np.arange(0, n / fs, 1 / fs)
|
|
92
|
+
|
|
93
|
+
noise_pow_db = -70
|
|
94
|
+
noise_std = 10 ** (noise_pow_db / 20)
|
|
95
|
+
dc_level = 0.123456789
|
|
96
|
+
|
|
97
|
+
random_state = np.random.RandomState(1234567890)
|
|
98
|
+
noise = random_state.normal(loc=0, scale=noise_std, size=len(t))
|
|
99
|
+
|
|
100
|
+
x = dc_level + noise
|
|
101
|
+
|
|
102
|
+
# Save data to TXT file
|
|
103
|
+
np.savetxt("test_data_cli.txt", x, delimiter="\n")
|
|
104
|
+
|
|
105
|
+
runner = CliRunner()
|
|
106
|
+
|
|
107
|
+
called = {}
|
|
108
|
+
|
|
109
|
+
def fake_show():
|
|
110
|
+
called["was_called"] = True
|
|
111
|
+
|
|
112
|
+
monkeypatch.setattr(plt, "show", fake_show)
|
|
113
|
+
|
|
114
|
+
result = runner.invoke(spec_analysis_cmd, ["test_data_cli.txt", "--fs", fs, "--plot"])
|
|
115
|
+
|
|
116
|
+
assert result.exit_code == 0
|
|
117
|
+
assert "was_called" in called
|
|
@@ -28,7 +28,7 @@ import matplotlib.pyplot as plt
|
|
|
28
28
|
import numpy as np
|
|
29
29
|
from pytest import mark
|
|
30
30
|
|
|
31
|
-
from harm_analysis import harm_analysis
|
|
31
|
+
from harm_analysis import harm_analysis
|
|
32
32
|
|
|
33
33
|
rng = np.random.default_rng()
|
|
34
34
|
|
|
@@ -282,60 +282,5 @@ def test_harm_analysis_harm_zero():
|
|
|
282
282
|
assert np.isclose(results["fund_freq"], f1, rtol=tolerance)
|
|
283
283
|
assert np.isclose(results["dc_db"], dc_power_db, rtol=tolerance)
|
|
284
284
|
assert np.isclose(results["noise_db"], noise_pow_db - 3, rtol=tolerance)
|
|
285
|
-
assert results["thd_db"]
|
|
285
|
+
assert np.isnan(results["thd_db"])
|
|
286
286
|
assert np.isclose(results["thdn_db"], thdn_db, rtol=tolerance)
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
def test_spec_analysis():
|
|
290
|
-
"""Test for harm_analysis function."""
|
|
291
|
-
# test signal
|
|
292
|
-
n = 2**18
|
|
293
|
-
fs = 1000
|
|
294
|
-
t = np.arange(0, n / fs, 1 / fs)
|
|
295
|
-
|
|
296
|
-
noise_pow_db = -70
|
|
297
|
-
harm_pow = 0.01**2 / 2
|
|
298
|
-
thdn = 10 ** (noise_pow_db / 10) + harm_pow
|
|
299
|
-
thdn_db = 10 * np.log10(thdn)
|
|
300
|
-
|
|
301
|
-
noise_std = 10 ** (noise_pow_db / 20)
|
|
302
|
-
|
|
303
|
-
dc_level = 0.123456789
|
|
304
|
-
dc_power_db = 20 * np.log10(dc_level)
|
|
305
|
-
noise = rng.normal(loc=0, scale=noise_std, size=len(t))
|
|
306
|
-
|
|
307
|
-
f1 = 100.13
|
|
308
|
-
|
|
309
|
-
x = (
|
|
310
|
-
dc_level
|
|
311
|
-
+ 2 * np.cos(2 * np.pi * f1 * t)
|
|
312
|
-
+ 0.01 * np.cos(2 * np.pi * f1 * 2 * t)
|
|
313
|
-
+ 3 * np.cos(2 * np.pi * f1 * 3 * t)
|
|
314
|
-
+ noise
|
|
315
|
-
)
|
|
316
|
-
|
|
317
|
-
results = spec_analysis(x, fs=fs)
|
|
318
|
-
|
|
319
|
-
print("Function results:")
|
|
320
|
-
for key, value in results.items():
|
|
321
|
-
print(f"{key.ljust(10)} [dB]: {value}")
|
|
322
|
-
|
|
323
|
-
logging.info(
|
|
324
|
-
"\n"
|
|
325
|
-
"Expected values\n"
|
|
326
|
-
f" Total noise (dB): {thdn_db}\n"
|
|
327
|
-
f" DC power [dB]: {dc_power_db}\n"
|
|
328
|
-
f" DC level: {dc_level}\n"
|
|
329
|
-
)
|
|
330
|
-
|
|
331
|
-
tolerance = 0.3
|
|
332
|
-
|
|
333
|
-
amp_arr = np.asarray([2, 0.01, 3])
|
|
334
|
-
|
|
335
|
-
amp_arr_db = 10 * np.log10((amp_arr**2) / 2)
|
|
336
|
-
|
|
337
|
-
assert np.isclose(results["dc"], dc_level, rtol=tolerance)
|
|
338
|
-
assert np.isclose(results["dc_db"], dc_power_db, rtol=tolerance)
|
|
339
|
-
assert np.isclose(results["noise_db"], noise_pow_db, rtol=tolerance)
|
|
340
|
-
assert np.allclose(results["tones_freq"], np.asarray([f1, 2 * f1, 3 * f1]), rtol=tolerance)
|
|
341
|
-
assert np.allclose(results["tones_amp_db"], amp_arr_db, rtol=tolerance)
|
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
22
|
# SOFTWARE.
|
|
23
23
|
|
|
24
|
+
import logging
|
|
25
|
+
|
|
24
26
|
import matplotlib.pyplot as plt
|
|
25
27
|
import numpy as np
|
|
26
28
|
from pytest import mark
|
|
@@ -30,9 +32,69 @@ from harm_analysis import spec_analysis
|
|
|
30
32
|
rng = np.random.default_rng()
|
|
31
33
|
|
|
32
34
|
|
|
35
|
+
def test_spec_analysis():
|
|
36
|
+
"""Test for spec_analysis function."""
|
|
37
|
+
# test signal
|
|
38
|
+
n = 2**18
|
|
39
|
+
fs = 1000
|
|
40
|
+
t = np.arange(0, n / fs, 1 / fs)
|
|
41
|
+
|
|
42
|
+
noise_pow_db = -70
|
|
43
|
+
harm_pow = 0.01**2 / 2
|
|
44
|
+
thdn = 10 ** (noise_pow_db / 10) + harm_pow
|
|
45
|
+
thdn_db = 10 * np.log10(thdn)
|
|
46
|
+
|
|
47
|
+
noise_std = 10 ** (noise_pow_db / 20)
|
|
48
|
+
|
|
49
|
+
dc_level = 0.123456789
|
|
50
|
+
dc_power_db = 20 * np.log10(dc_level)
|
|
51
|
+
noise = rng.normal(loc=0, scale=noise_std, size=len(t))
|
|
52
|
+
|
|
53
|
+
f1 = 100.13
|
|
54
|
+
|
|
55
|
+
x = (
|
|
56
|
+
dc_level
|
|
57
|
+
+ 2 * np.cos(2 * np.pi * f1 * t)
|
|
58
|
+
+ 0.01 * np.cos(2 * np.pi * f1 * 2 * t)
|
|
59
|
+
+ 3 * np.cos(2 * np.pi * f1 * 3 * t)
|
|
60
|
+
+ 3 * np.cos(2 * np.pi * fs / 2 * t)
|
|
61
|
+
+ noise
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
results = spec_analysis(x, fs=fs)
|
|
65
|
+
|
|
66
|
+
print("Function results:")
|
|
67
|
+
for key, value in results.items():
|
|
68
|
+
print(f"{key.ljust(10)} [dB]: {value}")
|
|
69
|
+
|
|
70
|
+
logging.info(
|
|
71
|
+
"\n"
|
|
72
|
+
"Expected values\n"
|
|
73
|
+
f" Total noise (dB): {thdn_db}\n"
|
|
74
|
+
f" DC power [dB]: {dc_power_db}\n"
|
|
75
|
+
f" DC level: {dc_level}\n"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
tolerance = 0.3
|
|
79
|
+
|
|
80
|
+
amp_arr = np.asarray([2, 0.01, 3])
|
|
81
|
+
|
|
82
|
+
amp_arr_db = 10 * np.log10((amp_arr**2) / 2)
|
|
83
|
+
|
|
84
|
+
sig_fs2 = 3 * np.cos(2 * np.pi * fs / 2 * t)
|
|
85
|
+
pow_fs2 = np.mean(sig_fs2**2)
|
|
86
|
+
amp_arr_db = np.append(amp_arr_db, 10 * np.log10(pow_fs2))
|
|
87
|
+
|
|
88
|
+
assert np.isclose(results["dc"], dc_level, rtol=tolerance)
|
|
89
|
+
assert np.isclose(results["dc_db"], dc_power_db, rtol=tolerance)
|
|
90
|
+
assert np.isclose(results["noise_db"], noise_pow_db, rtol=tolerance)
|
|
91
|
+
assert np.allclose(results["tones_freq"], np.asarray([f1, 2 * f1, 3 * f1, fs / 2]), rtol=tolerance)
|
|
92
|
+
assert np.allclose(results["tones_db"], amp_arr_db, rtol=tolerance)
|
|
93
|
+
|
|
94
|
+
|
|
33
95
|
@mark.parametrize("plot_en", [True, False])
|
|
34
|
-
def
|
|
35
|
-
"""Test for
|
|
96
|
+
def test_spec_analysis_plot(plot_en):
|
|
97
|
+
"""Test for spec_analysis function.
|
|
36
98
|
|
|
37
99
|
Checks if the function can obtain results with less than 0.1 dB of error.
|
|
38
100
|
"""
|
|
@@ -61,11 +123,3 @@ def test_harm_analysis(plot_en):
|
|
|
61
123
|
spec_analysis(x, fs=fs, plot=True, ax=ax)
|
|
62
124
|
else:
|
|
63
125
|
spec_analysis(x, fs=fs)
|
|
64
|
-
|
|
65
|
-
# TODO: add assertions
|
|
66
|
-
# assert np.isclose(results["fund_db"], fund_pow_db, rtol=tolerance)
|
|
67
|
-
# assert np.isclose(results["fund_freq"], f1, rtol=tolerance)
|
|
68
|
-
# assert np.isclose(results["dc_db"], dc_power_db, rtol=tolerance)
|
|
69
|
-
# assert np.isclose(results["noise_db"], noise_pow_db, rtol=tolerance)
|
|
70
|
-
# assert np.isclose(results["thd_db"], thd_db, rtol=tolerance)
|
|
71
|
-
# assert np.isclose(results["thdn_db"], thdn_db, rtol=tolerance)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|