harm-analysis 1.3.0__tar.gz → 1.4.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-1.3.0 → harm_analysis-1.4.0}/PKG-INFO +4 -6
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/README.md +2 -5
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/pyproject.toml +2 -1
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/src/harm_analysis/_harm_analysis.py +206 -223
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/src/harm_analysis/cli.py +13 -10
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/tests/test_cli.py +37 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/tests/test_harm_analysis.py +2 -57
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/tests/test_spectrum_analysis.py +64 -10
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/LICENSE +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/src/harm_analysis/__init__.py +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/tests/__init__.py +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/tests/conftest.py +0 -0
- {harm_analysis-1.3.0 → harm_analysis-1.4.0}/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.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>
|
|
@@ -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.0"
|
|
32
33
|
|
|
33
34
|
[project.urls]
|
|
34
35
|
Homepage = "https://github.com/ericsmacedo/harm-analysis"
|
|
@@ -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,58 @@ 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
|
|
200
160
|
|
|
201
|
-
# find local
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
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)
|
|
205
166
|
|
|
206
|
-
|
|
207
|
-
|
|
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)
|
|
208
170
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
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
|
|
171
|
+
if local_max_idx == 0:
|
|
172
|
+
peak_start = 0
|
|
173
|
+
else:
|
|
174
|
+
peak_start = np.where(np.diff(x[start_idx:local_max_idx]) < 0)[0][-1] + start_idx + 1
|
|
217
175
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
break
|
|
176
|
+
if local_max_idx == x_size - 1:
|
|
177
|
+
peak_end = x_size
|
|
178
|
+
else:
|
|
179
|
+
peak_end = np.where(np.diff(x[local_max_idx:end_idx]) > 0)[0][0] + local_max_idx + 1
|
|
223
180
|
|
|
224
|
-
|
|
181
|
+
bins = np.arange(peak_start, peak_end)
|
|
182
|
+
|
|
183
|
+
# Estimate precise location using a weighted average
|
|
184
|
+
peak_loc = np.average(bins, weights=x[bins])
|
|
185
|
+
peak_val = _power_from_bins(x, bins, enbw_bins=enbw_bins, bw_bins=bw_bins)
|
|
186
|
+
|
|
187
|
+
return peak_val, peak_loc, bins
|
|
225
188
|
|
|
226
189
|
|
|
227
190
|
def _find_dc_bins(x_fft: NDArray[np.float64]) -> int | np.signedinteger:
|
|
@@ -244,7 +207,7 @@ def _find_dc_bins(x_fft: NDArray[np.float64]) -> int | np.signedinteger:
|
|
|
244
207
|
return np.argmax(np.diff(x_fft[:50]) > 0) + 1
|
|
245
208
|
|
|
246
209
|
|
|
247
|
-
def _find_bins(x, n_harm, bw_bins):
|
|
210
|
+
def _find_bins(x, n_harm, bw_bins, enbw_bins):
|
|
248
211
|
"""Find all bins that belong to the fundamental, harmonics, DC, and noise.
|
|
249
212
|
|
|
250
213
|
Parameters
|
|
@@ -258,19 +221,6 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
258
221
|
n_harm : int
|
|
259
222
|
Number of harmonics to find
|
|
260
223
|
|
|
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
224
|
Notes:
|
|
275
225
|
-----
|
|
276
226
|
This function only works for the right-sided power spectrum (positive frequencies
|
|
@@ -279,6 +229,7 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
279
229
|
# Index of last dc bin
|
|
280
230
|
dc_end = _find_dc_bins(x)
|
|
281
231
|
dc_bins = np.arange(dc_end)
|
|
232
|
+
dc_pow = np.sum(x[dc_bins])
|
|
282
233
|
|
|
283
234
|
if bw_bins <= dc_end:
|
|
284
235
|
sys.exit("Error: max bandwidth is too low and is inside the detected dc bins.")
|
|
@@ -288,42 +239,61 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
288
239
|
max_loc = np.argmax(x[dc_end:bw_bins]) + dc_end
|
|
289
240
|
|
|
290
241
|
# 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])
|
|
242
|
+
fund_pow, fund_loc, fund_bins = _find_freq_bins(x, max_loc, bw_bins=bw_bins, enbw_bins=enbw_bins)
|
|
295
243
|
|
|
296
244
|
# THD+N bins (all bins excluding DC and the fundamental)
|
|
297
245
|
thdn_bins = np.setdiff1d(np.arange(len(x)), np.concatenate((fund_bins, dc_bins)))
|
|
298
246
|
|
|
299
|
-
harm_loc, harm_bins = _find_harm(x, fund_loc, n_harm, bw_bins)
|
|
247
|
+
harm_pow, harm_loc, harm_bins = _find_harm(x, fund_loc, n_harm, bw_bins, enbw_bins=enbw_bins)
|
|
300
248
|
|
|
301
249
|
# Remaining bins are considered noise.
|
|
302
|
-
if harm_bins
|
|
303
|
-
noise_bins = thdn_bins
|
|
304
|
-
else:
|
|
250
|
+
if harm_bins.size > 0:
|
|
305
251
|
noise_bins = np.setdiff1d(thdn_bins, harm_bins)
|
|
252
|
+
else:
|
|
253
|
+
noise_bins = thdn_bins
|
|
306
254
|
|
|
307
|
-
|
|
255
|
+
noise_pow = _power_from_bins(x, noise_bins, enbw_bins=enbw_bins, bw_bins=bw_bins)
|
|
256
|
+
|
|
257
|
+
# According to wikipedia, THD+N in dB is equal to
|
|
258
|
+
# 10*log10(sum(harmonics power + Noise power)/fundamental power).
|
|
259
|
+
# THD+N is recriprocal to SINAD (SINAD_dB = -THD+N_dB)
|
|
260
|
+
thdn_pow = _power_from_bins(x, thdn_bins, enbw_bins=enbw_bins, bw_bins=bw_bins) / fund_pow
|
|
261
|
+
|
|
262
|
+
return (
|
|
263
|
+
(fund_pow, fund_loc, fund_bins),
|
|
264
|
+
(harm_pow, harm_loc, harm_bins),
|
|
265
|
+
(dc_pow, dc_bins),
|
|
266
|
+
(noise_pow, noise_bins),
|
|
267
|
+
(thdn_pow, thdn_bins),
|
|
268
|
+
)
|
|
308
269
|
|
|
309
270
|
|
|
310
|
-
def _find_harm(x, fund_loc, n_harm, bw_bins):
|
|
271
|
+
def _find_harm(x, fund_loc, n_harm, bw_bins, enbw_bins):
|
|
311
272
|
if n_harm <= 0:
|
|
312
|
-
|
|
313
|
-
|
|
273
|
+
harm_loc = np.array([])
|
|
274
|
+
harm_pow = np.array([])
|
|
275
|
+
harm_bins = np.array([])
|
|
314
276
|
else:
|
|
315
277
|
# calculate the frequency of the harmonics.
|
|
316
278
|
# frequencies > fs/2 are ignored
|
|
317
279
|
harm_loc = fund_loc * np.arange(2, n_harm + 2)
|
|
318
280
|
harm_loc = harm_loc[harm_loc <= bw_bins]
|
|
319
281
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
282
|
+
harm_loc_list = []
|
|
283
|
+
harm_pow_list = []
|
|
284
|
+
harm_bins_list = []
|
|
285
|
+
if harm_loc.size > 0:
|
|
286
|
+
for loc in harm_loc:
|
|
287
|
+
harm_pow, harm_loc, harm_bins = _find_freq_bins(x, int(loc), bw_bins=bw_bins, enbw_bins=enbw_bins)
|
|
288
|
+
harm_loc_list.append(harm_loc)
|
|
289
|
+
harm_pow_list.append(harm_pow)
|
|
290
|
+
harm_bins_list.append(harm_bins)
|
|
325
291
|
|
|
326
|
-
|
|
292
|
+
harm_loc = np.asarray(harm_loc_list)
|
|
293
|
+
harm_pow = np.asarray(harm_pow_list)
|
|
294
|
+
harm_bins = np.hstack(harm_bins_list)
|
|
295
|
+
|
|
296
|
+
return harm_pow, harm_loc, harm_bins
|
|
327
297
|
|
|
328
298
|
|
|
329
299
|
def _power_from_bins(x_fft_pow, bins, enbw_bins, bw_bins):
|
|
@@ -403,36 +373,50 @@ def _int_noise_curve(x: NDArray[np.float64], noise_bins: NDArray[np.float64]):
|
|
|
403
373
|
return 10 * np.log10(total_int_noise)
|
|
404
374
|
|
|
405
375
|
|
|
406
|
-
def _find_tones(x, enbw_bins, bw_bins):
|
|
376
|
+
def _find_tones(x, enbw_bins, bw_bins, distance, prominence, height): # noqa: PLR0913
|
|
377
|
+
x_size = x.size
|
|
407
378
|
x_db = 10 * np.log10(x)
|
|
408
379
|
|
|
409
|
-
|
|
410
|
-
|
|
380
|
+
if height is None:
|
|
381
|
+
height = _rolling_median_bn(x_db, 51) + 16
|
|
382
|
+
else:
|
|
383
|
+
height = np.ones(x_size) * height
|
|
411
384
|
|
|
412
385
|
peaks, _ = signal.find_peaks(
|
|
413
386
|
x_db,
|
|
414
|
-
distance=
|
|
415
|
-
height=
|
|
416
|
-
prominence=
|
|
387
|
+
distance=distance,
|
|
388
|
+
height=height,
|
|
389
|
+
prominence=prominence,
|
|
417
390
|
)
|
|
418
391
|
|
|
419
|
-
|
|
420
|
-
tones_bins = np.concatenate([_find_freq_bins(x_db, int(loc)) for loc in peaks])
|
|
392
|
+
fs_2_bin = x_size - 1
|
|
421
393
|
|
|
422
|
-
|
|
423
|
-
|
|
394
|
+
if x_db[-1] > height[-1]:
|
|
395
|
+
if peaks.size == 0:
|
|
396
|
+
peaks = np.array([fs_2_bin])
|
|
397
|
+
elif np.all(np.abs(peaks - fs_2_bin) > distance):
|
|
398
|
+
peaks = np.append(peaks, fs_2_bin)
|
|
399
|
+
|
|
400
|
+
if peaks.size == 0:
|
|
401
|
+
tones_pow = np.array([])
|
|
402
|
+
tones_loc = np.array([])
|
|
403
|
+
tones_bins = np.array([])
|
|
424
404
|
|
|
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
405
|
else:
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
406
|
+
tones_pow_list = []
|
|
407
|
+
tones_loc_list = []
|
|
408
|
+
tones_bins_list = []
|
|
409
|
+
for loc in peaks:
|
|
410
|
+
tone_pow, tone_loc, tone_bins = _find_freq_bins(x, int(loc), bw_bins=bw_bins, enbw_bins=enbw_bins)
|
|
411
|
+
tones_pow_list.append(tone_pow)
|
|
412
|
+
tones_loc_list.append(tone_loc)
|
|
413
|
+
tones_bins_list.append(tone_bins)
|
|
414
|
+
|
|
415
|
+
tones_pow = np.asarray(tones_pow_list)
|
|
416
|
+
tones_loc = np.asarray(tones_loc_list)
|
|
417
|
+
tones_bins = np.hstack(tones_bins_list)
|
|
434
418
|
|
|
435
|
-
return
|
|
419
|
+
return tones_pow, tones_loc, tones_bins
|
|
436
420
|
|
|
437
421
|
|
|
438
422
|
def _annotate(ax, x, y, text):
|
|
@@ -456,28 +440,24 @@ def _plot_spec( # noqa: PLR0913
|
|
|
456
440
|
dc_bins: NDArray[np.float64],
|
|
457
441
|
noise_bins: NDArray[np.float64],
|
|
458
442
|
int_noise: NDArray[np.float64],
|
|
459
|
-
enbw_bins: float,
|
|
460
443
|
bw_bins: int,
|
|
461
444
|
ax,
|
|
462
|
-
tones_freq:
|
|
463
|
-
tones_bins:
|
|
445
|
+
tones_freq: NDArray[np.float64],
|
|
446
|
+
tones_bins: NDArray[np.float64],
|
|
447
|
+
tones_db: NDArray[np.float64],
|
|
464
448
|
):
|
|
465
449
|
x_db = 10 * np.log10(x)
|
|
466
450
|
|
|
467
451
|
dc_noise_array = _mask_array(x_db, np.concatenate((dc_bins, noise_bins)))
|
|
468
452
|
|
|
469
|
-
if tones_bins
|
|
453
|
+
if tones_bins.size > 0:
|
|
470
454
|
tones_array = _mask_array(x_db, tones_bins)
|
|
471
455
|
ax.plot(freq_array, tones_array, label="Tones")
|
|
472
456
|
|
|
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}")
|
|
457
|
+
for i in range(tones_db.size):
|
|
458
|
+
x_marker = tones_freq[i]
|
|
459
|
+
y_marker = tones_db[i]
|
|
460
|
+
_annotate(ax, x_marker, y_marker, f"T{i}")
|
|
481
461
|
|
|
482
462
|
ax.plot(freq_array, dc_noise_array, label="DC and Noise", color="black")
|
|
483
463
|
ax.plot(freq_array, int_noise, label="Integrated noise", color="green")
|
|
@@ -501,39 +481,35 @@ def _plot_harm( # noqa: PLR0913
|
|
|
501
481
|
noise_bins: NDArray[np.float64],
|
|
502
482
|
int_noise: NDArray[np.float64],
|
|
503
483
|
int_noise_p_harm: NDArray[np.float64],
|
|
504
|
-
enbw_bins: float,
|
|
505
484
|
bw_bins: int,
|
|
506
485
|
ax,
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
fund_bins:
|
|
510
|
-
harm_bins:
|
|
486
|
+
fund_pow_db: float,
|
|
487
|
+
fund_freq: float,
|
|
488
|
+
fund_bins: NDArray[np.float64],
|
|
489
|
+
harm_bins: NDArray[np.float64],
|
|
490
|
+
harm_freq: NDArray[np.float64],
|
|
491
|
+
harm_pow_db: NDArray[np.float64],
|
|
511
492
|
):
|
|
512
493
|
x_db = 10 * np.log10(x)
|
|
513
494
|
|
|
514
495
|
fund_array = _mask_array(x_db, fund_bins)
|
|
515
496
|
dc_noise_array = _mask_array(x_db, np.concatenate((dc_bins, noise_bins)))
|
|
516
497
|
|
|
517
|
-
if fund_bins
|
|
498
|
+
if fund_bins.size > 0:
|
|
518
499
|
ax.plot(freq_array, fund_array, label="Fundamental")
|
|
519
500
|
|
|
520
|
-
if fund_freq is not None:
|
|
521
501
|
x_marker = fund_freq
|
|
522
|
-
y_marker =
|
|
502
|
+
y_marker = fund_pow_db
|
|
523
503
|
_annotate(ax, x_marker, y_marker, "F")
|
|
524
504
|
|
|
525
|
-
if harm_bins
|
|
505
|
+
if harm_bins.size > 0:
|
|
526
506
|
harm_array = _mask_array(x_db, harm_bins)
|
|
527
507
|
ax.plot(freq_array, harm_array, label="Harmonics")
|
|
528
508
|
|
|
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}")
|
|
509
|
+
for i in range(harm_pow_db.size):
|
|
510
|
+
x_marker = harm_freq[i]
|
|
511
|
+
y_marker = harm_pow_db[i]
|
|
512
|
+
_annotate(ax, x_marker, y_marker, f"H{i + 1}")
|
|
537
513
|
|
|
538
514
|
ax.plot(freq_array, dc_noise_array, label="DC and Noise", color="black")
|
|
539
515
|
ax.plot(freq_array, int_noise_p_harm, label="Integrated noise (inc. harmonics)", color="green")
|
|
@@ -551,15 +527,13 @@ def _plot_harm( # noqa: PLR0913
|
|
|
551
527
|
return ax
|
|
552
528
|
|
|
553
529
|
|
|
554
|
-
def
|
|
530
|
+
def _power_spectrum(
|
|
555
531
|
x: NDArray[np.float64],
|
|
556
532
|
fs: float = 1,
|
|
557
533
|
bw: float | None = None,
|
|
558
|
-
window=None,
|
|
534
|
+
window: None | NDArray[np.float64] = None,
|
|
559
535
|
):
|
|
560
536
|
sig_len = len(x)
|
|
561
|
-
# length of the array returned by the np.fft.rfft function
|
|
562
|
-
rfft_len = _rfft_length(sig_len)
|
|
563
537
|
|
|
564
538
|
if window is None:
|
|
565
539
|
window = signal.windows.hann(sig_len, sym=False)
|
|
@@ -573,7 +547,7 @@ def _harm_analysis(
|
|
|
573
547
|
|
|
574
548
|
# Convert bw to number of bins
|
|
575
549
|
if bw is None:
|
|
576
|
-
bw_bins =
|
|
550
|
+
bw_bins = x_fft_pow.size - 1
|
|
577
551
|
else:
|
|
578
552
|
bw_bins = np.argmin(np.abs(f_array - bw))
|
|
579
553
|
|
|
@@ -585,9 +559,9 @@ def harm_analysis( # noqa: PLR0913
|
|
|
585
559
|
fs: float = 1,
|
|
586
560
|
bw: float | None = None,
|
|
587
561
|
n_harm: int = 5,
|
|
588
|
-
window=None,
|
|
589
|
-
plot=False,
|
|
590
|
-
ax=None,
|
|
562
|
+
window: None | NDArray[np.float64] = None,
|
|
563
|
+
plot: bool = False,
|
|
564
|
+
ax: None | Axes = None,
|
|
591
565
|
):
|
|
592
566
|
"""Harmonic Analysis.
|
|
593
567
|
|
|
@@ -633,12 +607,14 @@ def harm_analysis( # noqa: PLR0913
|
|
|
633
607
|
- `fund_freq` Frequency of the fundamental tone.
|
|
634
608
|
- `dc_db`: DC power in decibels.
|
|
635
609
|
- `noise_db`: Noise power in decibels.
|
|
610
|
+
- `harm_db`: Harmonics power in decibels.
|
|
611
|
+
- `harm_freq`: Harmonics frequency in Hz.
|
|
636
612
|
- `thd_db`: Total harmonic distortion in decibels. Returns `numpy.nan` if
|
|
637
613
|
`n_harm` is 0 or if all harmonics are outside the bandwidth.
|
|
638
614
|
- `snr_db`: Signal-to-noise ratio in decibels.
|
|
639
615
|
- `sinad_db`: Signal-to-noise-and-distortion ratio in decibels.
|
|
640
616
|
- `thdn_db`: Total harmonic distortion plus noise in decibels.
|
|
641
|
-
- `
|
|
617
|
+
- `total_noise_and_dist_db`: Total noise and distortion in decibels.
|
|
642
618
|
|
|
643
619
|
ax : matplotlib axes
|
|
644
620
|
If plot is set to True, the Axes used for plotting is returned.
|
|
@@ -661,22 +637,19 @@ def harm_analysis( # noqa: PLR0913
|
|
|
661
637
|
FFT-based signal analysis and measurement. Application Note
|
|
662
638
|
041, National Instruments, 2000.
|
|
663
639
|
""" # noqa: D416
|
|
664
|
-
x_fft_pow, f_array, enbw_bins, bw_bins =
|
|
640
|
+
x_fft_pow, f_array, enbw_bins, bw_bins = _power_spectrum(x, fs=fs, bw=bw, window=window)
|
|
665
641
|
|
|
666
642
|
sig_len = len(x)
|
|
667
643
|
|
|
668
|
-
|
|
669
|
-
x=x_fft_pow, n_harm=n_harm, bw_bins=bw_bins
|
|
644
|
+
fund_info, harm_info, dc_info, noise_info, thdn_info = _find_bins(
|
|
645
|
+
x=x_fft_pow, n_harm=n_harm, bw_bins=bw_bins, enbw_bins=enbw_bins
|
|
670
646
|
)
|
|
671
647
|
|
|
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
|
|
648
|
+
fund_pow, fund_loc, fund_bins = fund_info
|
|
649
|
+
harm_pow, harm_loc, harm_bins = harm_info
|
|
650
|
+
dc_pow, dc_bins = dc_info
|
|
651
|
+
noise_pow, noise_bins = noise_info
|
|
652
|
+
thdn_pow, thdn_bins = thdn_info
|
|
680
653
|
|
|
681
654
|
# total integrated noise curve
|
|
682
655
|
int_noise = _int_noise_curve(x=x_fft_pow / enbw_bins, noise_bins=noise_bins)
|
|
@@ -684,32 +657,34 @@ def harm_analysis( # noqa: PLR0913
|
|
|
684
657
|
|
|
685
658
|
# Calculate THD, Signal Power and N metrics in dB
|
|
686
659
|
sig_freq = fund_loc * fs / sig_len
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
660
|
+
harm_freq = harm_loc * fs / sig_len
|
|
661
|
+
dc_db = 10 * np.log10(dc_pow)
|
|
662
|
+
sig_db = 10 * np.log10(fund_pow)
|
|
663
|
+
noise_db = 10 * np.log10(noise_pow)
|
|
664
|
+
harm_db = 10 * np.log10(harm_pow)
|
|
665
|
+
thdn_db = 10 * np.log10(thdn_pow)
|
|
666
|
+
snr_db = sig_db - noise_db
|
|
692
667
|
|
|
693
668
|
# 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)
|
|
669
|
+
if harm_bins.size > 0:
|
|
670
|
+
thd_db = 10 * np.log10(np.sum(harm_pow) / fund_pow)
|
|
697
671
|
harm_freq = harm_loc * fs / sig_len
|
|
698
672
|
else:
|
|
699
|
-
harm_power = np.nan
|
|
700
673
|
thd_db = np.nan
|
|
701
674
|
harm_freq = None
|
|
702
675
|
|
|
703
676
|
results = {
|
|
704
|
-
"fund_db":
|
|
677
|
+
"fund_db": sig_db,
|
|
705
678
|
"fund_freq": sig_freq,
|
|
679
|
+
"harm_freq": harm_freq,
|
|
680
|
+
"harm_db": harm_db,
|
|
706
681
|
"dc_db": dc_db,
|
|
707
|
-
"noise_db":
|
|
682
|
+
"noise_db": noise_db,
|
|
708
683
|
"thd_db": thd_db,
|
|
709
684
|
"snr_db": snr_db,
|
|
710
685
|
"sinad_db": -thdn_db,
|
|
711
686
|
"thdn_db": thdn_db,
|
|
712
|
-
"
|
|
687
|
+
"total_noise_and_dist_db": int_noise[-1],
|
|
713
688
|
}
|
|
714
689
|
|
|
715
690
|
if plot is False:
|
|
@@ -717,16 +692,17 @@ def harm_analysis( # noqa: PLR0913
|
|
|
717
692
|
ax = _plot_harm(
|
|
718
693
|
x=x_fft_pow,
|
|
719
694
|
fund_freq=sig_freq,
|
|
720
|
-
harm_freq=harm_freq,
|
|
721
695
|
freq_array=f_array,
|
|
722
696
|
dc_bins=dc_bins,
|
|
723
697
|
fund_bins=fund_bins,
|
|
698
|
+
fund_pow_db=sig_db,
|
|
724
699
|
harm_bins=harm_bins,
|
|
700
|
+
harm_freq=harm_freq,
|
|
701
|
+
harm_pow_db=harm_db,
|
|
725
702
|
noise_bins=noise_bins,
|
|
726
703
|
ax=ax,
|
|
727
704
|
int_noise=int_noise,
|
|
728
705
|
int_noise_p_harm=int_noise_p_harm,
|
|
729
|
-
enbw_bins=enbw_bins,
|
|
730
706
|
bw_bins=bw_bins,
|
|
731
707
|
)
|
|
732
708
|
|
|
@@ -736,10 +712,12 @@ def harm_analysis( # noqa: PLR0913
|
|
|
736
712
|
def spec_analysis( # noqa: PLR0913
|
|
737
713
|
x: NDArray[np.float64],
|
|
738
714
|
fs: float = 1,
|
|
739
|
-
bw: float | None = None,
|
|
740
715
|
window: None | NDArray[np.float64] = None,
|
|
741
|
-
plot=False,
|
|
716
|
+
plot: bool = False,
|
|
742
717
|
ax: None | Axes = None,
|
|
718
|
+
distance: int = 6,
|
|
719
|
+
prominence: int = 10,
|
|
720
|
+
height: int | None = None,
|
|
743
721
|
):
|
|
744
722
|
"""Spectral Analysis.
|
|
745
723
|
|
|
@@ -754,8 +732,6 @@ def spec_analysis( # noqa: PLR0913
|
|
|
754
732
|
window : array_like, optional
|
|
755
733
|
Window that will be multiplied with the signal. Default is
|
|
756
734
|
Hann window.
|
|
757
|
-
bw : float, optional
|
|
758
|
-
Bandwidth to use for the calculation of the metrics, in same units as fs.
|
|
759
735
|
plot : bool or None, optional
|
|
760
736
|
If True, the power spectrum result is plotted. If specified,
|
|
761
737
|
an `ax` must be provided, and the function returns a dictionary
|
|
@@ -769,30 +745,37 @@ def spec_analysis( # noqa: PLR0913
|
|
|
769
745
|
properties : dict
|
|
770
746
|
A dictionary containing the analysis results
|
|
771
747
|
|
|
772
|
-
- `
|
|
773
|
-
- `
|
|
748
|
+
- `dc`: DC level in the same units as the input signal x.
|
|
749
|
+
- `dc_db`: DC power in decibels.
|
|
750
|
+
- `noise_db`: Noise power in decibels.
|
|
751
|
+
- `tones_db`: Array with the amplitude of the detected tones in dB.
|
|
752
|
+
- `tones_freq`: Array with the frequencies of the detected tones in Hz.
|
|
753
|
+
|
|
774
754
|
|
|
775
755
|
plt.axes
|
|
776
756
|
If plot is set to True, the Axes used for plotting is returned.
|
|
777
757
|
|
|
778
758
|
""" # noqa: D416
|
|
779
|
-
x_fft_pow, f_array, enbw_bins, bw_bins =
|
|
759
|
+
x_fft_pow, f_array, enbw_bins, bw_bins = _power_spectrum(x, fs=fs, bw=None, window=window)
|
|
780
760
|
sig_len = len(x)
|
|
781
761
|
|
|
782
762
|
dc_end = _find_dc_bins(x_fft_pow)
|
|
783
763
|
dc_bins = np.arange(dc_end)
|
|
784
764
|
|
|
785
|
-
|
|
765
|
+
tones_pow, tones_loc, tones_bins = _find_tones(
|
|
766
|
+
x_fft_pow,
|
|
767
|
+
enbw_bins=enbw_bins,
|
|
768
|
+
bw_bins=bw_bins,
|
|
769
|
+
distance=distance,
|
|
770
|
+
prominence=prominence,
|
|
771
|
+
height=height,
|
|
772
|
+
)
|
|
786
773
|
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
tones_amp_db = 10 * np.log10(tones_amp)
|
|
790
|
-
else:
|
|
791
|
-
tones_freq = None
|
|
792
|
-
tones_amp_db = None
|
|
774
|
+
tones_freq = tones_loc * fs / sig_len
|
|
775
|
+
tones_db = 10 * np.log10(tones_pow)
|
|
793
776
|
|
|
794
777
|
# Obtain noise bins, by removing the DC bins from the bin list
|
|
795
|
-
if tones_bins
|
|
778
|
+
if tones_bins.size > 0:
|
|
796
779
|
noise_bins = np.setdiff1d(np.arange(len(x_fft_pow)), np.concatenate((dc_bins, tones_bins)))
|
|
797
780
|
else:
|
|
798
781
|
noise_bins = np.setdiff1d(np.arange(len(x_fft_pow)), dc_bins)
|
|
@@ -806,13 +789,13 @@ def spec_analysis( # noqa: PLR0913
|
|
|
806
789
|
# Calculate THD, Signal Power and N metrics in dB
|
|
807
790
|
dc_db = 10 * np.log10(dc_power)
|
|
808
791
|
dc = 10 ** (dc_db / 20)
|
|
809
|
-
|
|
792
|
+
noise_db = 10 * np.log10(noise_power)
|
|
810
793
|
|
|
811
794
|
results = {
|
|
812
795
|
"dc": dc,
|
|
813
796
|
"dc_db": dc_db,
|
|
814
|
-
"noise_db":
|
|
815
|
-
"
|
|
797
|
+
"noise_db": noise_db,
|
|
798
|
+
"tones_db": tones_db,
|
|
816
799
|
"tones_freq": tones_freq,
|
|
817
800
|
}
|
|
818
801
|
|
|
@@ -825,10 +808,10 @@ def spec_analysis( # noqa: PLR0913
|
|
|
825
808
|
noise_bins=noise_bins,
|
|
826
809
|
ax=ax,
|
|
827
810
|
int_noise=int_noise,
|
|
828
|
-
enbw_bins=enbw_bins,
|
|
829
811
|
bw_bins=bw_bins,
|
|
830
812
|
tones_freq=tones_freq,
|
|
831
813
|
tones_bins=tones_bins,
|
|
814
|
+
tones_db=tones_db,
|
|
832
815
|
)
|
|
833
816
|
|
|
834
817
|
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
|