harm-analysis 1.2.1__tar.gz → 1.3.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.2.1 → harm_analysis-1.3.0}/PKG-INFO +28 -1
- {harm_analysis-1.2.1 → harm_analysis-1.3.0}/README.md +26 -0
- {harm_analysis-1.2.1 → harm_analysis-1.3.0}/pyproject.toml +5 -2
- {harm_analysis-1.2.1 → harm_analysis-1.3.0}/src/harm_analysis/__init__.py +2 -2
- harm_analysis-1.2.1/src/harm_analysis/harm_analysis.py → harm_analysis-1.3.0/src/harm_analysis/_harm_analysis.py +269 -141
- harm_analysis-1.3.0/src/harm_analysis/cli.py +139 -0
- harm_analysis-1.3.0/tests/conftest.py +31 -0
- {harm_analysis-1.2.1 → harm_analysis-1.3.0}/tests/test_cli.py +17 -6
- {harm_analysis-1.2.1 → harm_analysis-1.3.0}/tests/test_harm_analysis.py +33 -18
- harm_analysis-1.3.0/tests/test_spectrum_analysis.py +71 -0
- harm_analysis-1.2.1/src/harm_analysis/cli.py +0 -75
- harm_analysis-1.2.1/tests/test_harm_analysis_cli.py +0 -91
- {harm_analysis-1.2.1 → harm_analysis-1.3.0}/LICENSE +0 -0
- {harm_analysis-1.2.1 → harm_analysis-1.3.0}/tests/__init__.py +0 -0
- {harm_analysis-1.2.1 → harm_analysis-1.3.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.3.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>
|
|
@@ -17,6 +17,7 @@ Requires-Python: <4.0,>=3.10.0
|
|
|
17
17
|
Requires-Dist: click>=8.2.1
|
|
18
18
|
Requires-Dist: matplotlib>=3.10.3
|
|
19
19
|
Requires-Dist: numpy>=2.2.6
|
|
20
|
+
Requires-Dist: rich>=14.1.0
|
|
20
21
|
Requires-Dist: scipy>=1.15.3
|
|
21
22
|
Description-Content-Type: text/markdown
|
|
22
23
|
|
|
@@ -34,3 +35,29 @@ Description-Content-Type: text/markdown
|
|
|
34
35
|
[](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
35
36
|
[](https://github.com/ericsmacedo/harm-analysis/pulls)
|
|
36
37
|
[](https://github.com/ericsmacedo/harm-analysis/pulls?q=is%3Apr+is%3Aclosed)
|
|
38
|
+
|
|
39
|
+
# Harmonic Analysis package
|
|
40
|
+
|
|
41
|
+
* [Documentation](https://harm-analysis.readthedocs.io/en/stable/)
|
|
42
|
+
* [PyPI](https://pypi.org/project/harm-analysis/)
|
|
43
|
+
* [Sources](https://github.com/ericsmacedo/harm-analysis)
|
|
44
|
+
* [Issues](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
45
|
+
|
|
46
|
+
## Introduction
|
|
47
|
+
|
|
48
|
+
The harmonic analysis package uses FFT to estimate parameters of an input signal.
|
|
49
|
+
The package provides two main functions:
|
|
50
|
+
|
|
51
|
+
- `harm_analysis`: for simulations with an injected tone, returning SNR, THDN, Noise, etc.
|
|
52
|
+
- `spec_analysis`: for cases without an injected tone, that auto-detects DC, tones, and noise from the spectrum.
|
|
53
|
+
|
|
54
|
+
See [usage](./docs/usage.md) for examples.
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
Installing it is pretty easy:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
pip install harm-analysis
|
|
63
|
+
```
|
|
@@ -12,3 +12,29 @@
|
|
|
12
12
|
[](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
13
13
|
[](https://github.com/ericsmacedo/harm-analysis/pulls)
|
|
14
14
|
[](https://github.com/ericsmacedo/harm-analysis/pulls?q=is%3Apr+is%3Aclosed)
|
|
15
|
+
|
|
16
|
+
# Harmonic Analysis package
|
|
17
|
+
|
|
18
|
+
* [Documentation](https://harm-analysis.readthedocs.io/en/stable/)
|
|
19
|
+
* [PyPI](https://pypi.org/project/harm-analysis/)
|
|
20
|
+
* [Sources](https://github.com/ericsmacedo/harm-analysis)
|
|
21
|
+
* [Issues](https://github.com/ericsmacedo/harm-analysis/issues)
|
|
22
|
+
|
|
23
|
+
## Introduction
|
|
24
|
+
|
|
25
|
+
The harmonic analysis package uses FFT to estimate parameters of an input signal.
|
|
26
|
+
The package provides two main functions:
|
|
27
|
+
|
|
28
|
+
- `harm_analysis`: for simulations with an injected tone, returning SNR, THDN, Noise, etc.
|
|
29
|
+
- `spec_analysis`: for cases without an injected tone, that auto-detects DC, tones, and noise from the spectrum.
|
|
30
|
+
|
|
31
|
+
See [usage](./docs/usage.md) for examples.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## Installation
|
|
35
|
+
|
|
36
|
+
Installing it is pretty easy:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install harm-analysis
|
|
40
|
+
```
|
|
@@ -19,6 +19,7 @@ dependencies = [
|
|
|
19
19
|
"click>=8.2.1",
|
|
20
20
|
"matplotlib>=3.10.3",
|
|
21
21
|
"numpy>=2.2.6",
|
|
22
|
+
"rich>=14.1.0",
|
|
22
23
|
"scipy>=1.15.3",
|
|
23
24
|
]
|
|
24
25
|
keywords = [
|
|
@@ -27,7 +28,7 @@ keywords = [
|
|
|
27
28
|
"THD",
|
|
28
29
|
"SNR",
|
|
29
30
|
]
|
|
30
|
-
version = "1.
|
|
31
|
+
version = "1.3.0"
|
|
31
32
|
|
|
32
33
|
[project.urls]
|
|
33
34
|
Homepage = "https://github.com/ericsmacedo/harm-analysis"
|
|
@@ -35,12 +36,14 @@ Documentation = "https://harm-analysis.readthedocs.io/en/stable/"
|
|
|
35
36
|
"Bug Tracker" = "https://github.com/ericsmacedo/harm-analysis/issues"
|
|
36
37
|
|
|
37
38
|
[project.scripts]
|
|
38
|
-
harm-analysis = "harm_analysis.cli:
|
|
39
|
+
harm-analysis = "harm_analysis.cli:harm_analysis_cmd"
|
|
40
|
+
spec-analysis = "harm_analysis.cli:spec_analysis_cmd"
|
|
39
41
|
|
|
40
42
|
[dependency-groups]
|
|
41
43
|
dev = [
|
|
42
44
|
"contextlib-chdir>=1.0.2",
|
|
43
45
|
"coveralls>=3.3.1",
|
|
46
|
+
"invoke>=2.2.0",
|
|
44
47
|
"mkdocs-click>=0.8.1",
|
|
45
48
|
"mkdocs-include-markdown-plugin>=6.0.5",
|
|
46
49
|
"mkdocs-literate-nav>=0.6.1",
|
|
@@ -25,10 +25,44 @@ import sys
|
|
|
25
25
|
|
|
26
26
|
import numpy as np
|
|
27
27
|
from matplotlib.axes import Axes
|
|
28
|
+
from numpy.lib.stride_tricks import as_strided
|
|
28
29
|
from numpy.typing import NDArray
|
|
29
30
|
from scipy import signal
|
|
30
31
|
|
|
31
32
|
|
|
33
|
+
def _rolling_median_vec(x, window_size):
|
|
34
|
+
"""Compute rolling median of a 1D array using vectorized striding.
|
|
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
|
+
|
|
53
|
+
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
|
+
|
|
57
|
+
# Build a sliding window view
|
|
58
|
+
shape = (len(x), window_size)
|
|
59
|
+
strides = (x_pad.strides[0], x_pad.strides[0])
|
|
60
|
+
windows = as_strided(x_pad, shape=shape, strides=strides)
|
|
61
|
+
|
|
62
|
+
# Median along the window dimension
|
|
63
|
+
return np.median(windows, axis=1)
|
|
64
|
+
|
|
65
|
+
|
|
32
66
|
def _arg_x_as_expected(value):
|
|
33
67
|
"""Ensure argument `x` is a 1-D C-contiguous array of dtype('float64').
|
|
34
68
|
|
|
@@ -251,10 +285,13 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
251
285
|
|
|
252
286
|
# the fundamental frequency is found by searching for the bin with the
|
|
253
287
|
# maximum value, excluding DC
|
|
254
|
-
|
|
288
|
+
max_loc = np.argmax(x[dc_end:bw_bins]) + dc_end
|
|
255
289
|
|
|
256
290
|
# list containing bins of fundamental
|
|
257
|
-
fund_bins = _find_freq_bins(x,
|
|
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])
|
|
258
295
|
|
|
259
296
|
# THD+N bins (all bins excluding DC and the fundamental)
|
|
260
297
|
thdn_bins = np.setdiff1d(np.arange(len(x)), np.concatenate((fund_bins, dc_bins)))
|
|
@@ -267,7 +304,7 @@ def _find_bins(x, n_harm, bw_bins):
|
|
|
267
304
|
else:
|
|
268
305
|
noise_bins = np.setdiff1d(thdn_bins, harm_bins)
|
|
269
306
|
|
|
270
|
-
return fund_bins, harm_loc, harm_bins, dc_bins, noise_bins, thdn_bins
|
|
307
|
+
return fund_loc, fund_bins, harm_loc, harm_bins, dc_bins, noise_bins, thdn_bins
|
|
271
308
|
|
|
272
309
|
|
|
273
310
|
def _find_harm(x, fund_loc, n_harm, bw_bins):
|
|
@@ -281,7 +318,7 @@ def _find_harm(x, fund_loc, n_harm, bw_bins):
|
|
|
281
318
|
harm_loc = harm_loc[harm_loc <= bw_bins]
|
|
282
319
|
|
|
283
320
|
if harm_loc.size != 0:
|
|
284
|
-
harm_bins = np.concatenate([_find_freq_bins(x, loc) for loc in harm_loc])
|
|
321
|
+
harm_bins = np.concatenate([_find_freq_bins(x, int(loc)) for loc in harm_loc])
|
|
285
322
|
else:
|
|
286
323
|
harm_bins = None
|
|
287
324
|
harm_loc = None
|
|
@@ -366,17 +403,111 @@ def _int_noise_curve(x: NDArray[np.float64], noise_bins: NDArray[np.float64]):
|
|
|
366
403
|
return 10 * np.log10(total_int_noise)
|
|
367
404
|
|
|
368
405
|
|
|
369
|
-
def
|
|
406
|
+
def _find_tones(x, enbw_bins, bw_bins):
|
|
407
|
+
x_db = 10 * np.log10(x)
|
|
408
|
+
|
|
409
|
+
# TODO: decide which number is appropriate for the median window
|
|
410
|
+
rol_median = _rolling_median_vec(x_db, 101) + 16
|
|
411
|
+
|
|
412
|
+
peaks, _ = signal.find_peaks(
|
|
413
|
+
x_db,
|
|
414
|
+
distance=6,
|
|
415
|
+
height=rol_median,
|
|
416
|
+
prominence=10,
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if len(peaks) > 0:
|
|
420
|
+
tones_bins = np.concatenate([_find_freq_bins(x_db, int(loc)) for loc in peaks])
|
|
421
|
+
|
|
422
|
+
breaks = np.where(np.diff(tones_bins) > 1)[0] + 1
|
|
423
|
+
bin_groups = np.split(tones_bins, breaks)
|
|
424
|
+
|
|
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
|
+
else:
|
|
431
|
+
tones_bins = None
|
|
432
|
+
tones_loc = None
|
|
433
|
+
tones_amp = None
|
|
434
|
+
|
|
435
|
+
return tones_loc, tones_amp, tones_bins
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _annotate(ax, x, y, text):
|
|
439
|
+
ax.annotate(
|
|
440
|
+
str(text),
|
|
441
|
+
xy=(x, y),
|
|
442
|
+
xytext=(0, 15),
|
|
443
|
+
textcoords="offset points",
|
|
444
|
+
ha="center",
|
|
445
|
+
va="bottom",
|
|
446
|
+
fontsize=10,
|
|
447
|
+
fontweight="bold",
|
|
448
|
+
bbox={"boxstyle": "round,pad=0.3", "edgecolor": "brown", "facecolor": "white"},
|
|
449
|
+
arrowprops={"arrowstyle": "-", "color": "brown"},
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _plot_spec( # noqa: PLR0913
|
|
454
|
+
x: NDArray[np.float64],
|
|
455
|
+
freq_array: NDArray[np.float64],
|
|
456
|
+
dc_bins: NDArray[np.float64],
|
|
457
|
+
noise_bins: NDArray[np.float64],
|
|
458
|
+
int_noise: NDArray[np.float64],
|
|
459
|
+
enbw_bins: float,
|
|
460
|
+
bw_bins: int,
|
|
461
|
+
ax,
|
|
462
|
+
tones_freq: None | NDArray[np.float64] = None,
|
|
463
|
+
tones_bins: None | NDArray[np.float64] = None,
|
|
464
|
+
):
|
|
465
|
+
x_db = 10 * np.log10(x)
|
|
466
|
+
|
|
467
|
+
dc_noise_array = _mask_array(x_db, np.concatenate((dc_bins, noise_bins)))
|
|
468
|
+
|
|
469
|
+
if tones_bins is not None:
|
|
470
|
+
tones_array = _mask_array(x_db, tones_bins)
|
|
471
|
+
ax.plot(freq_array, tones_array, label="Tones")
|
|
472
|
+
|
|
473
|
+
if tones_freq is not None:
|
|
474
|
+
breaks = np.where(np.diff(tones_bins) > 1)[0] + 1
|
|
475
|
+
bin_groups = np.split(tones_bins, breaks)
|
|
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}")
|
|
481
|
+
|
|
482
|
+
ax.plot(freq_array, dc_noise_array, label="DC and Noise", color="black")
|
|
483
|
+
ax.plot(freq_array, int_noise, label="Integrated noise", color="green")
|
|
484
|
+
|
|
485
|
+
if bw_bins != len(freq_array) - 1:
|
|
486
|
+
ax.axvline(freq_array[bw_bins], color="black", alpha=0.3, label="bw", linestyle="--")
|
|
487
|
+
|
|
488
|
+
ax.legend()
|
|
489
|
+
ax.grid()
|
|
490
|
+
|
|
491
|
+
ax.set_ylabel("[dB]")
|
|
492
|
+
ax.set_xlabel("[Hz]")
|
|
493
|
+
|
|
494
|
+
return ax
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _plot_harm( # noqa: PLR0913
|
|
370
498
|
x: NDArray[np.float64],
|
|
371
499
|
freq_array: NDArray[np.float64],
|
|
372
500
|
dc_bins: NDArray[np.float64],
|
|
373
|
-
fund_bins: None | NDArray[np.float64],
|
|
374
|
-
harm_bins: None | NDArray[np.float64],
|
|
375
501
|
noise_bins: NDArray[np.float64],
|
|
376
502
|
int_noise: NDArray[np.float64],
|
|
503
|
+
int_noise_p_harm: NDArray[np.float64],
|
|
377
504
|
enbw_bins: float,
|
|
378
505
|
bw_bins: int,
|
|
379
506
|
ax,
|
|
507
|
+
fund_freq: None | float = None,
|
|
508
|
+
harm_freq: None | NDArray[np.float64] = None,
|
|
509
|
+
fund_bins: None | NDArray[np.float64] = None,
|
|
510
|
+
harm_bins: None | NDArray[np.float64] = None,
|
|
380
511
|
):
|
|
381
512
|
x_db = 10 * np.log10(x)
|
|
382
513
|
|
|
@@ -386,18 +517,27 @@ def _plot( # noqa: PLR0913
|
|
|
386
517
|
if fund_bins is not None:
|
|
387
518
|
ax.plot(freq_array, fund_array, label="Fundamental")
|
|
388
519
|
|
|
520
|
+
if fund_freq is not None:
|
|
521
|
+
x_marker = fund_freq
|
|
522
|
+
y_marker = 10 * np.log10(np.sum(x[fund_bins] / enbw_bins))
|
|
523
|
+
_annotate(ax, x_marker, y_marker, "F")
|
|
524
|
+
|
|
389
525
|
if harm_bins is not None:
|
|
390
526
|
harm_array = _mask_array(x_db, harm_bins)
|
|
391
527
|
ax.plot(freq_array, harm_array, label="Harmonics")
|
|
392
528
|
|
|
393
|
-
|
|
394
|
-
|
|
529
|
+
if harm_freq is not None:
|
|
530
|
+
breaks = np.where(np.diff(harm_bins) > 1)[0] + 1
|
|
531
|
+
bin_groups = np.split(harm_bins, breaks)
|
|
395
532
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
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}")
|
|
537
|
+
|
|
538
|
+
ax.plot(freq_array, dc_noise_array, label="DC and Noise", color="black")
|
|
539
|
+
ax.plot(freq_array, int_noise_p_harm, label="Integrated noise (inc. harmonics)", color="green")
|
|
540
|
+
ax.plot(freq_array, int_noise, label="Integrated noise", color="purple")
|
|
401
541
|
|
|
402
542
|
if bw_bins != len(freq_array) - 1:
|
|
403
543
|
ax.axvline(freq_array[bw_bins], color="black", alpha=0.3, label="bw", linestyle="--")
|
|
@@ -411,6 +551,35 @@ def _plot( # noqa: PLR0913
|
|
|
411
551
|
return ax
|
|
412
552
|
|
|
413
553
|
|
|
554
|
+
def _harm_analysis(
|
|
555
|
+
x: NDArray[np.float64],
|
|
556
|
+
fs: float = 1,
|
|
557
|
+
bw: float | None = None,
|
|
558
|
+
window=None,
|
|
559
|
+
):
|
|
560
|
+
sig_len = len(x)
|
|
561
|
+
# length of the array returned by the np.fft.rfft function
|
|
562
|
+
rfft_len = _rfft_length(sig_len)
|
|
563
|
+
|
|
564
|
+
if window is None:
|
|
565
|
+
window = signal.windows.hann(sig_len, sym=False)
|
|
566
|
+
|
|
567
|
+
# window metrics
|
|
568
|
+
coherent_gain, enbw = _win_metrics(window)
|
|
569
|
+
enbw_bins = enbw * sig_len
|
|
570
|
+
|
|
571
|
+
# Obtain the single-sided power spectrum
|
|
572
|
+
x_fft_pow, f_array = _fft_pow(x=x, win=window, n_fft=sig_len, fs=fs, coherent_gain=coherent_gain)
|
|
573
|
+
|
|
574
|
+
# Convert bw to number of bins
|
|
575
|
+
if bw is None:
|
|
576
|
+
bw_bins = rfft_len - 1
|
|
577
|
+
else:
|
|
578
|
+
bw_bins = np.argmin(np.abs(f_array - bw))
|
|
579
|
+
|
|
580
|
+
return x_fft_pow, f_array, enbw_bins, bw_bins
|
|
581
|
+
|
|
582
|
+
|
|
414
583
|
def harm_analysis( # noqa: PLR0913
|
|
415
584
|
x: NDArray[np.float64],
|
|
416
585
|
fs: float = 1,
|
|
@@ -420,52 +589,58 @@ def harm_analysis( # noqa: PLR0913
|
|
|
420
589
|
plot=False,
|
|
421
590
|
ax=None,
|
|
422
591
|
):
|
|
423
|
-
"""
|
|
592
|
+
"""Harmonic Analysis.
|
|
593
|
+
|
|
594
|
+
Calculates SNR, THD, Fundamental power, and Noise power of the input signal x.
|
|
424
595
|
|
|
425
596
|
The total harmonic distortion is determined from the fundamental frequency and the
|
|
426
597
|
first five harmonics using a power spectrum of the same length as the input signal.
|
|
427
598
|
A hann window is applied to the signal, before the power spectrum is obtained.
|
|
428
599
|
|
|
600
|
+
For simulations with an injected tone.
|
|
601
|
+
|
|
602
|
+
|
|
429
603
|
Parameters
|
|
430
604
|
----------
|
|
431
605
|
x : array_like
|
|
432
606
|
Input signal, containing a tone.
|
|
433
607
|
fs : float, optional
|
|
434
|
-
|
|
608
|
+
Sampling frequency.
|
|
435
609
|
n_harm : int, optional
|
|
436
|
-
|
|
610
|
+
Number of harmonics used in the THD calculation.
|
|
437
611
|
window : array_like, optional
|
|
438
|
-
|
|
439
|
-
Hann window.
|
|
612
|
+
Window that will be multiplied with the signal. Default is Hann window.
|
|
440
613
|
bw : float, optional
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
614
|
+
Bandwidth to use for the calculation of the metrics, in same units as fs.
|
|
615
|
+
Also useful to filter another tone (or noise) with amplitude greater than the
|
|
616
|
+
fundamental and located above a certain frequency (see shaped noise example).
|
|
444
617
|
plot : bool or None, optional
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
618
|
+
If True, the power spectrum result is plotted. If specified,
|
|
619
|
+
an `ax` must be provided, and the function returns a dictionary
|
|
620
|
+
with the results and the specified axes (`ax`). If plot is not set,
|
|
621
|
+
only the results are returned.
|
|
449
622
|
ax : plt.Axes or None, optional
|
|
450
|
-
|
|
623
|
+
Axes to be used for plotting. Required if plot is set to True.
|
|
451
624
|
|
|
452
|
-
Returns:
|
|
453
|
-
-------
|
|
454
|
-
dict
|
|
455
|
-
A dictionary containing the analysis results:
|
|
456
|
-
|
|
457
|
-
* "fund_db": Fundamental power in decibels (sig_pow_db),
|
|
458
|
-
* "fund_freq": Frequency of the fundamental tone (sig_freq),
|
|
459
|
-
* "dc_db": DC power in decibels (dc_db),
|
|
460
|
-
* "noise_db": Noise power in decibels (noise_pow_db),
|
|
461
|
-
* "thd_db": Total harmonic distortion in decibels (thd_db). Returns a np.nan if
|
|
462
|
-
n_harms is set to 0, or if all the harmonics are outside the bandwidth.
|
|
463
|
-
* "snr_db": Signal-to-noise ratio in decibels (snr_db),
|
|
464
|
-
* "sinad_db": Signal to noise and distortion ratio in decibels.
|
|
465
|
-
* "thdn_db": Total harmonic distortion plus noise in decibels (thdn_db).
|
|
466
|
-
* "total_noise_and_dist": Total noise and distortion in decibels.
|
|
467
625
|
|
|
468
|
-
|
|
626
|
+
Returns
|
|
627
|
+
-------
|
|
628
|
+
properties: dict
|
|
629
|
+
|
|
630
|
+
Dictionary containing the analysis results
|
|
631
|
+
|
|
632
|
+
- `fund_db`: Fundamental power in decibels.
|
|
633
|
+
- `fund_freq` Frequency of the fundamental tone.
|
|
634
|
+
- `dc_db`: DC power in decibels.
|
|
635
|
+
- `noise_db`: Noise power in decibels.
|
|
636
|
+
- `thd_db`: Total harmonic distortion in decibels. Returns `numpy.nan` if
|
|
637
|
+
`n_harm` is 0 or if all harmonics are outside the bandwidth.
|
|
638
|
+
- `snr_db`: Signal-to-noise ratio in decibels.
|
|
639
|
+
- `sinad_db`: Signal-to-noise-and-distortion ratio in decibels.
|
|
640
|
+
- `thdn_db`: Total harmonic distortion plus noise in decibels.
|
|
641
|
+
- `total_noise_and_dist`: Total noise and distortion in decibels.
|
|
642
|
+
|
|
643
|
+
ax : matplotlib axes
|
|
469
644
|
If plot is set to True, the Axes used for plotting is returned.
|
|
470
645
|
|
|
471
646
|
Notes:
|
|
@@ -477,64 +652,20 @@ def harm_analysis( # noqa: PLR0913
|
|
|
477
652
|
sidelobe width of the Hann window. If this is not feasible, you can use a different
|
|
478
653
|
window by using the "window" input.
|
|
479
654
|
|
|
480
|
-
Examples:
|
|
481
|
-
--------
|
|
482
|
-
|
|
483
|
-
.. plot:: tutorial/examples/run_harm_analysis.py
|
|
484
|
-
:include-source:
|
|
485
|
-
|
|
486
|
-
The code above also outputs:
|
|
487
|
-
|
|
488
|
-
.. code-block::
|
|
489
|
-
|
|
490
|
-
Function results:
|
|
491
|
-
fund_db [dB]: 3.0103153618915335
|
|
492
|
-
fund_freq [dB]: 100.1300002671261
|
|
493
|
-
dc_db [dB]: -18.174340815733466
|
|
494
|
-
noise_db [dB]: -69.86388900477726
|
|
495
|
-
thd_db [dB]: -45.0412474024929
|
|
496
|
-
snr_db [dB]: 72.87420436666879
|
|
497
|
-
sinad_db [dB]: 45.034100280257974
|
|
498
|
-
thdn_db [dB]: -45.034100280257974
|
|
499
|
-
total_noise_and_dist [dB]: -42.023784918366445
|
|
500
|
-
|
|
501
|
-
The example below shows how to use the bw for cases where the fundamental is not
|
|
502
|
-
the highest spectral component in the signal. For the example, we set bw to
|
|
503
|
-
5 kHz. The metrics will only be calculated up to the bw frequency.
|
|
504
|
-
|
|
505
|
-
.. plot:: tutorial/examples/run_shaped_noise_example.py
|
|
506
|
-
:include-source:
|
|
507
|
-
|
|
508
655
|
References:
|
|
509
656
|
----------
|
|
510
|
-
|
|
657
|
+
- [1] Harris, Fredric J. "On the use of windows for harmonic analysis
|
|
511
658
|
with the discrete Fourier transform." Proceedings of the
|
|
512
659
|
IEEE 66.1 (1978): 51-83.
|
|
513
|
-
|
|
660
|
+
- [2] Cerna, Michael, and Audrey F. Harvey. The fundamentals of
|
|
514
661
|
FFT-based signal analysis and measurement. Application Note
|
|
515
662
|
041, National Instruments, 2000.
|
|
516
|
-
"""
|
|
517
|
-
|
|
518
|
-
# length of the array returned by the np.fft.rfft function
|
|
519
|
-
rfft_len = _rfft_length(sig_len)
|
|
520
|
-
|
|
521
|
-
if window is None:
|
|
522
|
-
window = signal.windows.hann(sig_len, sym=False)
|
|
523
|
-
|
|
524
|
-
# window metrics
|
|
525
|
-
coherent_gain, enbw = _win_metrics(window)
|
|
526
|
-
enbw_bins = enbw * sig_len
|
|
527
|
-
|
|
528
|
-
# Obtain the single-sided power spectrum
|
|
529
|
-
x_fft_pow, f_array = _fft_pow(x=x, win=window, n_fft=sig_len, fs=fs, coherent_gain=coherent_gain)
|
|
663
|
+
""" # noqa: D416
|
|
664
|
+
x_fft_pow, f_array, enbw_bins, bw_bins = _harm_analysis(x, fs=fs, bw=bw, window=window)
|
|
530
665
|
|
|
531
|
-
|
|
532
|
-
if bw is None:
|
|
533
|
-
bw_bins = rfft_len - 1
|
|
534
|
-
else:
|
|
535
|
-
bw_bins = np.argmin(np.abs(f_array - bw))
|
|
666
|
+
sig_len = len(x)
|
|
536
667
|
|
|
537
|
-
fund_bins, harm_loc, harm_bins, dc_bins, noise_bins, thdn_bins = _find_bins(
|
|
668
|
+
fund_loc, fund_bins, harm_loc, harm_bins, dc_bins, noise_bins, thdn_bins = _find_bins(
|
|
538
669
|
x=x_fft_pow, n_harm=n_harm, bw_bins=bw_bins
|
|
539
670
|
)
|
|
540
671
|
|
|
@@ -547,13 +678,12 @@ def harm_analysis( # noqa: PLR0913
|
|
|
547
678
|
# THD+N is recriprocal to SINAD (SINAD_dB = -THD+N_dB)
|
|
548
679
|
thdn_power = _power_from_bins(x_fft_pow, thdn_bins, enbw_bins, bw_bins) / fund_power
|
|
549
680
|
|
|
550
|
-
# Estimate frequency using a weighted average
|
|
551
|
-
sig_freq = np.average(fund_bins, weights=x_fft_pow[fund_bins]) * fs / sig_len
|
|
552
|
-
|
|
553
681
|
# total integrated noise curve
|
|
554
|
-
int_noise = _int_noise_curve(x=x_fft_pow / enbw_bins, noise_bins=
|
|
682
|
+
int_noise = _int_noise_curve(x=x_fft_pow / enbw_bins, noise_bins=noise_bins)
|
|
683
|
+
int_noise_p_harm = _int_noise_curve(x=x_fft_pow / enbw_bins, noise_bins=thdn_bins)
|
|
555
684
|
|
|
556
685
|
# Calculate THD, Signal Power and N metrics in dB
|
|
686
|
+
sig_freq = fund_loc * fs / sig_len
|
|
557
687
|
dc_db = 10 * np.log10(dc_power)
|
|
558
688
|
sig_pow_db = 10 * np.log10(fund_power)
|
|
559
689
|
noise_pow_db = 10 * np.log10(noise_power)
|
|
@@ -564,9 +694,11 @@ def harm_analysis( # noqa: PLR0913
|
|
|
564
694
|
if harm_bins is not None:
|
|
565
695
|
harm_power = _power_from_bins(x_fft_pow, harm_bins, enbw_bins, bw_bins)
|
|
566
696
|
thd_db = 10 * np.log10(harm_power / fund_power)
|
|
697
|
+
harm_freq = harm_loc * fs / sig_len
|
|
567
698
|
else:
|
|
568
699
|
harm_power = np.nan
|
|
569
700
|
thd_db = np.nan
|
|
701
|
+
harm_freq = None
|
|
570
702
|
|
|
571
703
|
results = {
|
|
572
704
|
"fund_db": sig_pow_db,
|
|
@@ -582,8 +714,10 @@ def harm_analysis( # noqa: PLR0913
|
|
|
582
714
|
|
|
583
715
|
if plot is False:
|
|
584
716
|
return results
|
|
585
|
-
ax =
|
|
717
|
+
ax = _plot_harm(
|
|
586
718
|
x=x_fft_pow,
|
|
719
|
+
fund_freq=sig_freq,
|
|
720
|
+
harm_freq=harm_freq,
|
|
587
721
|
freq_array=f_array,
|
|
588
722
|
dc_bins=dc_bins,
|
|
589
723
|
fund_bins=fund_bins,
|
|
@@ -591,6 +725,7 @@ def harm_analysis( # noqa: PLR0913
|
|
|
591
725
|
noise_bins=noise_bins,
|
|
592
726
|
ax=ax,
|
|
593
727
|
int_noise=int_noise,
|
|
728
|
+
int_noise_p_harm=int_noise_p_harm,
|
|
594
729
|
enbw_bins=enbw_bins,
|
|
595
730
|
bw_bins=bw_bins,
|
|
596
731
|
)
|
|
@@ -598,7 +733,7 @@ def harm_analysis( # noqa: PLR0913
|
|
|
598
733
|
return results, ax
|
|
599
734
|
|
|
600
735
|
|
|
601
|
-
def
|
|
736
|
+
def spec_analysis( # noqa: PLR0913
|
|
602
737
|
x: NDArray[np.float64],
|
|
603
738
|
fs: float = 1,
|
|
604
739
|
bw: float | None = None,
|
|
@@ -606,70 +741,61 @@ def dc_measurement( # noqa: PLR0913
|
|
|
606
741
|
plot=False,
|
|
607
742
|
ax: None | Axes = None,
|
|
608
743
|
):
|
|
609
|
-
"""
|
|
744
|
+
"""Spectral Analysis.
|
|
610
745
|
|
|
611
|
-
|
|
612
|
-
first five harmonics using a power spectrum of the same length as the input signal.
|
|
613
|
-
A hann window is applied to the signal, before the power spectrum is obtained.
|
|
746
|
+
Auto-detects DC, tones, and noise from the spectrum.
|
|
614
747
|
|
|
615
748
|
Parameters
|
|
616
749
|
----------
|
|
617
750
|
x : array_like
|
|
618
751
|
Input signal, containing a tone.
|
|
619
752
|
fs : float, optional
|
|
620
|
-
|
|
753
|
+
Sampling frequency.
|
|
621
754
|
window : array_like, optional
|
|
622
|
-
|
|
623
|
-
|
|
755
|
+
Window that will be multiplied with the signal. Default is
|
|
756
|
+
Hann window.
|
|
624
757
|
bw : float, optional
|
|
625
|
-
|
|
626
|
-
Also useful to filter another tone (or noise) with amplitude greater than the
|
|
627
|
-
fundamental and located above a certain frequency (see shaped noise example).
|
|
758
|
+
Bandwidth to use for the calculation of the metrics, in same units as fs.
|
|
628
759
|
plot : bool or None, optional
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
760
|
+
If True, the power spectrum result is plotted. If specified,
|
|
761
|
+
an `ax` must be provided, and the function returns a dictionary
|
|
762
|
+
with the results and the specified axes (`ax`). If plot is not set,
|
|
763
|
+
only the results are returned.
|
|
633
764
|
ax : plt.Axes or None, optional
|
|
634
|
-
|
|
765
|
+
Axes to be used for plotting. Required if plot is set to True.
|
|
635
766
|
|
|
636
|
-
Returns
|
|
767
|
+
Returns
|
|
637
768
|
-------
|
|
638
|
-
dict
|
|
639
|
-
A dictionary containing the analysis results
|
|
769
|
+
properties : dict
|
|
770
|
+
A dictionary containing the analysis results
|
|
640
771
|
|
|
641
|
-
|
|
642
|
-
|
|
772
|
+
- `dc_db`: DC power in decibels (dc_db),
|
|
773
|
+
- `noise_db`: Noise power in decibels (noise_pow_db),
|
|
643
774
|
|
|
644
775
|
plt.axes
|
|
645
776
|
If plot is set to True, the Axes used for plotting is returned.
|
|
646
777
|
|
|
647
|
-
"""
|
|
778
|
+
""" # noqa: D416
|
|
779
|
+
x_fft_pow, f_array, enbw_bins, bw_bins = _harm_analysis(x, fs=fs, bw=bw, window=window)
|
|
648
780
|
sig_len = len(x)
|
|
649
|
-
# length of the array returned by the np.fft.rfft function
|
|
650
|
-
rfft_len = _rfft_length(sig_len)
|
|
651
781
|
|
|
652
|
-
|
|
653
|
-
|
|
782
|
+
dc_end = _find_dc_bins(x_fft_pow)
|
|
783
|
+
dc_bins = np.arange(dc_end)
|
|
654
784
|
|
|
655
|
-
|
|
656
|
-
coherent_gain, enbw = _win_metrics(window)
|
|
657
|
-
enbw_bins = enbw * sig_len
|
|
785
|
+
tones_loc, tones_amp, tones_bins = _find_tones(x_fft_pow, enbw_bins=enbw_bins, bw_bins=bw_bins)
|
|
658
786
|
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
# Convert bw to number of bins
|
|
663
|
-
if bw is None:
|
|
664
|
-
bw_bins = rfft_len - 1
|
|
787
|
+
if tones_loc is not None:
|
|
788
|
+
tones_freq = tones_loc * fs / sig_len
|
|
789
|
+
tones_amp_db = 10 * np.log10(tones_amp)
|
|
665
790
|
else:
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
dc_end = _find_dc_bins(x_fft_pow)
|
|
669
|
-
dc_bins = np.arange(dc_end)
|
|
791
|
+
tones_freq = None
|
|
792
|
+
tones_amp_db = None
|
|
670
793
|
|
|
671
794
|
# Obtain noise bins, by removing the DC bins from the bin list
|
|
672
|
-
|
|
795
|
+
if tones_bins is not None:
|
|
796
|
+
noise_bins = np.setdiff1d(np.arange(len(x_fft_pow)), np.concatenate((dc_bins, tones_bins)))
|
|
797
|
+
else:
|
|
798
|
+
noise_bins = np.setdiff1d(np.arange(len(x_fft_pow)), dc_bins)
|
|
673
799
|
|
|
674
800
|
dc_power = _power_from_bins(x_fft_pow, dc_bins, enbw_bins, bw_bins)
|
|
675
801
|
noise_power = _power_from_bins(x_fft_pow, noise_bins, enbw_bins, bw_bins)
|
|
@@ -686,21 +812,23 @@ def dc_measurement( # noqa: PLR0913
|
|
|
686
812
|
"dc": dc,
|
|
687
813
|
"dc_db": dc_db,
|
|
688
814
|
"noise_db": noise_pow_db,
|
|
815
|
+
"tones_amp_db": tones_amp_db,
|
|
816
|
+
"tones_freq": tones_freq,
|
|
689
817
|
}
|
|
690
818
|
|
|
691
819
|
if plot is False:
|
|
692
820
|
return results
|
|
693
|
-
ax =
|
|
821
|
+
ax = _plot_spec(
|
|
694
822
|
x=x_fft_pow,
|
|
695
823
|
freq_array=f_array,
|
|
696
824
|
dc_bins=dc_bins,
|
|
697
|
-
fund_bins=None,
|
|
698
|
-
harm_bins=None,
|
|
699
825
|
noise_bins=noise_bins,
|
|
700
826
|
ax=ax,
|
|
701
827
|
int_noise=int_noise,
|
|
702
828
|
enbw_bins=enbw_bins,
|
|
703
829
|
bw_bins=bw_bins,
|
|
830
|
+
tones_freq=tones_freq,
|
|
831
|
+
tones_bins=tones_bins,
|
|
704
832
|
)
|
|
705
833
|
|
|
706
834
|
return results, ax
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) 2025 ericsmacedo
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
"""CLI for harm_analysis."""
|
|
23
|
+
|
|
24
|
+
import click
|
|
25
|
+
import matplotlib.pyplot as plt
|
|
26
|
+
import numpy as np
|
|
27
|
+
from matplotlib.ticker import EngFormatter
|
|
28
|
+
from rich.console import Console
|
|
29
|
+
from rich.table import Table, box
|
|
30
|
+
|
|
31
|
+
from ._harm_analysis import harm_analysis, spec_analysis
|
|
32
|
+
|
|
33
|
+
console = Console()
|
|
34
|
+
|
|
35
|
+
arg_filepath = click.argument("filename", type=click.Path(exists=True, readable=True))
|
|
36
|
+
opt_fs = click.option("--fs", default=1.0, help="Sampling frequency.")
|
|
37
|
+
opt_sep = click.option("--sep", default=" ", help="Separator between items.")
|
|
38
|
+
opt_plot = click.option("--plot", is_flag=True, help="Plot the power spectrum of the data")
|
|
39
|
+
opt_sfactor = click.option(
|
|
40
|
+
"--sfactor",
|
|
41
|
+
default="1",
|
|
42
|
+
help="Scaling factor to apply to the data. Examples: 1/8, 5, etc",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@click.command(name="harm-analysis")
|
|
47
|
+
@arg_filepath
|
|
48
|
+
@opt_fs
|
|
49
|
+
@opt_sep
|
|
50
|
+
@opt_plot
|
|
51
|
+
@opt_sfactor
|
|
52
|
+
def harm_analysis_cmd(filename, fs, plot, sep, sfactor):
|
|
53
|
+
"""Runs the harm_analysis function for a file containing time domain data."""
|
|
54
|
+
# scaling factor
|
|
55
|
+
file_data = np.fromfile(filename, sep=sep) * eval(sfactor)
|
|
56
|
+
|
|
57
|
+
if plot is True:
|
|
58
|
+
fig, ax = plt.subplots(1, 2, figsize=(15, 5))
|
|
59
|
+
results, ax[1] = harm_analysis(file_data, fs=fs, plot=True, ax=ax[1])
|
|
60
|
+
else:
|
|
61
|
+
results = harm_analysis(file_data, fs=fs, plot=False)
|
|
62
|
+
|
|
63
|
+
print("Function results:")
|
|
64
|
+
table = Table(box=box.MARKDOWN, title="Parameters")
|
|
65
|
+
table.add_column("Parameter", justify="right")
|
|
66
|
+
table.add_column("value", style="magenta")
|
|
67
|
+
for key, value in results.items():
|
|
68
|
+
table.add_row(key, str(value))
|
|
69
|
+
|
|
70
|
+
console.print(table)
|
|
71
|
+
|
|
72
|
+
if plot is True:
|
|
73
|
+
ax[1].grid(True, which="both")
|
|
74
|
+
ax[1].set_title("Power spectrum")
|
|
75
|
+
ax[1].set_xscale("log")
|
|
76
|
+
ax[1].xaxis.set_major_formatter(EngFormatter(unit="Hz"))
|
|
77
|
+
|
|
78
|
+
ax[0].set_title("Data")
|
|
79
|
+
ax[0].plot(file_data)
|
|
80
|
+
ax[0].grid(True, which="both", linestyle="-")
|
|
81
|
+
ax[0].set_xlabel("[n]")
|
|
82
|
+
|
|
83
|
+
plt.tight_layout()
|
|
84
|
+
plt.show()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@click.command(name="spec-analysis")
|
|
88
|
+
@arg_filepath
|
|
89
|
+
@opt_fs
|
|
90
|
+
@opt_plot
|
|
91
|
+
@opt_sep
|
|
92
|
+
@opt_sfactor
|
|
93
|
+
def spec_analysis_cmd(filename, fs, plot, sep, sfactor):
|
|
94
|
+
"""Runs the harm_analysis function for a file containing time domain data."""
|
|
95
|
+
# scaling factor
|
|
96
|
+
file_data = np.fromfile(filename, sep=sep) * eval(sfactor)
|
|
97
|
+
|
|
98
|
+
if plot is True:
|
|
99
|
+
fig, ax = plt.subplots(1, 2, figsize=(15, 5))
|
|
100
|
+
results, ax[1] = spec_analysis(file_data, fs=fs, plot=True, ax=ax[1])
|
|
101
|
+
else:
|
|
102
|
+
results = spec_analysis(file_data, fs=fs)
|
|
103
|
+
|
|
104
|
+
tones_amp_db = results["tones_amp_db"]
|
|
105
|
+
tones_freq = results["tones_freq"]
|
|
106
|
+
|
|
107
|
+
table = Table(box=box.MARKDOWN, title="Parameters")
|
|
108
|
+
table.add_column("Parameter", justify="right")
|
|
109
|
+
table.add_column("value", style="magenta")
|
|
110
|
+
|
|
111
|
+
for key, value in results.items():
|
|
112
|
+
if key in {"tones_amp_db", "tones_freq"}:
|
|
113
|
+
continue
|
|
114
|
+
table.add_row(key, str(value))
|
|
115
|
+
|
|
116
|
+
tones_table = Table(box=box.MARKDOWN, title="Tones")
|
|
117
|
+
tones_table.add_column("Tone")
|
|
118
|
+
tones_table.add_column("Amplitude [dB]")
|
|
119
|
+
tones_table.add_column("Frequency [Hz]")
|
|
120
|
+
|
|
121
|
+
for i, amp in enumerate(tones_amp_db):
|
|
122
|
+
tones_table.add_row(f"T{i}", str(amp), str(tones_freq[i]))
|
|
123
|
+
|
|
124
|
+
console.print(table)
|
|
125
|
+
console.print(tones_table)
|
|
126
|
+
|
|
127
|
+
if plot is True:
|
|
128
|
+
ax[1].grid(True, which="both")
|
|
129
|
+
ax[1].set_title("Power spectrum")
|
|
130
|
+
ax[1].set_xscale("log")
|
|
131
|
+
ax[1].xaxis.set_major_formatter(EngFormatter(unit="Hz"))
|
|
132
|
+
|
|
133
|
+
ax[0].set_title("Data")
|
|
134
|
+
ax[0].plot(file_data)
|
|
135
|
+
ax[0].grid(True, which="both", linestyle="-")
|
|
136
|
+
ax[0].set_xlabel("[n]")
|
|
137
|
+
|
|
138
|
+
plt.tight_layout()
|
|
139
|
+
plt.show()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Config file for tests."""
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2025 ericsmacedo
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
|
|
24
|
+
# tests/conftest.py
|
|
25
|
+
import os
|
|
26
|
+
|
|
27
|
+
os.environ.setdefault("MPLBACKEND", "Agg")
|
|
28
|
+
|
|
29
|
+
import matplotlib
|
|
30
|
+
|
|
31
|
+
matplotlib.use("Agg", force=True)
|
|
@@ -22,13 +22,16 @@
|
|
|
22
22
|
|
|
23
23
|
"""Tests the CLI for the harmonic analysis function."""
|
|
24
24
|
|
|
25
|
+
import matplotlib.pyplot as plt
|
|
25
26
|
import numpy as np
|
|
26
27
|
from click.testing import CliRunner
|
|
28
|
+
from pytest import mark
|
|
27
29
|
|
|
28
|
-
from harm_analysis.cli import
|
|
30
|
+
from harm_analysis.cli import harm_analysis_cmd, spec_analysis_cmd
|
|
29
31
|
|
|
30
32
|
|
|
31
|
-
|
|
33
|
+
@mark.parametrize("cli_name", ["harm", "spec"])
|
|
34
|
+
def test_cli(monkeypatch, cli_name):
|
|
32
35
|
"""Test for harm_analysis function.
|
|
33
36
|
|
|
34
37
|
Checks if the function can obtain results with less than 0.1 dB of error.
|
|
@@ -60,10 +63,18 @@ def test_harm_analysis_cli():
|
|
|
60
63
|
|
|
61
64
|
runner = CliRunner()
|
|
62
65
|
|
|
63
|
-
|
|
66
|
+
called = {}
|
|
64
67
|
|
|
65
|
-
|
|
68
|
+
def fake_show():
|
|
69
|
+
called["was_called"] = True
|
|
70
|
+
|
|
71
|
+
monkeypatch.setattr(plt, "show", fake_show)
|
|
66
72
|
|
|
73
|
+
if cli_name == "harm":
|
|
74
|
+
result = runner.invoke(harm_analysis_cmd, ["test_data_cli.txt", "--fs", fs, "--plot"])
|
|
75
|
+
elif cli_name == "spec":
|
|
76
|
+
result = runner.invoke(spec_analysis_cmd, ["test_data_cli.txt", "--fs", fs, "--plot"])
|
|
67
77
|
|
|
68
|
-
|
|
69
|
-
|
|
78
|
+
assert "was_called" in called
|
|
79
|
+
|
|
80
|
+
assert result.exit_code == 0
|
|
@@ -24,14 +24,17 @@
|
|
|
24
24
|
|
|
25
25
|
import logging
|
|
26
26
|
|
|
27
|
+
import matplotlib.pyplot as plt
|
|
27
28
|
import numpy as np
|
|
29
|
+
from pytest import mark
|
|
28
30
|
|
|
29
|
-
from harm_analysis import
|
|
31
|
+
from harm_analysis import harm_analysis, spec_analysis
|
|
30
32
|
|
|
31
33
|
rng = np.random.default_rng()
|
|
32
34
|
|
|
33
35
|
|
|
34
|
-
|
|
36
|
+
@mark.parametrize("plot_en", [True, False])
|
|
37
|
+
def test_harm_analysis(plot_en):
|
|
35
38
|
"""Test for harm_analysis function.
|
|
36
39
|
|
|
37
40
|
Checks if the function can obtain results with less than 0.1 dB of error.
|
|
@@ -63,7 +66,11 @@ def test_harm_analysis():
|
|
|
63
66
|
snr_db = fund_pow_db - noise_pow_db
|
|
64
67
|
thdn_db = 10 * np.log10(10 ** (noise_pow_db / 10) + 10 ** (thd_db / 10))
|
|
65
68
|
|
|
66
|
-
|
|
69
|
+
if plot_en:
|
|
70
|
+
fig, ax = plt.subplots()
|
|
71
|
+
results, ax = harm_analysis(x, fs=fs, plot=True, ax=ax)
|
|
72
|
+
else:
|
|
73
|
+
results = harm_analysis(x, fs=fs)
|
|
67
74
|
|
|
68
75
|
print("Function results:")
|
|
69
76
|
for key, value in results.items():
|
|
@@ -92,7 +99,8 @@ def test_harm_analysis():
|
|
|
92
99
|
assert np.isclose(results["thdn_db"], thdn_db, rtol=tolerance)
|
|
93
100
|
|
|
94
101
|
|
|
95
|
-
|
|
102
|
+
@mark.parametrize("plot_en", [True, False])
|
|
103
|
+
def test_harm_analysis_dc(plot_en):
|
|
96
104
|
"""Test for harm_analysis function.
|
|
97
105
|
|
|
98
106
|
Checks if the function can operate when DC frequency component is highest than the
|
|
@@ -125,7 +133,11 @@ def test_harm_analysis_dc():
|
|
|
125
133
|
snr_db = fund_pow_db - noise_pow_db
|
|
126
134
|
thdn_db = 10 * np.log10(10 ** (noise_pow_db / 10) + 10 ** (thd_db / 10))
|
|
127
135
|
|
|
128
|
-
|
|
136
|
+
if plot_en:
|
|
137
|
+
fig, ax = plt.subplots()
|
|
138
|
+
results, ax = harm_analysis(x, fs=fs, plot=True, ax=ax)
|
|
139
|
+
else:
|
|
140
|
+
results = harm_analysis(x, fs=fs)
|
|
129
141
|
|
|
130
142
|
print("Function results:")
|
|
131
143
|
for key, value in results.items():
|
|
@@ -274,13 +286,12 @@ def test_harm_analysis_harm_zero():
|
|
|
274
286
|
assert np.isclose(results["thdn_db"], thdn_db, rtol=tolerance)
|
|
275
287
|
|
|
276
288
|
|
|
277
|
-
def
|
|
289
|
+
def test_spec_analysis():
|
|
278
290
|
"""Test for harm_analysis function."""
|
|
279
291
|
# test signal
|
|
280
292
|
n = 2**18
|
|
281
293
|
fs = 1000
|
|
282
294
|
t = np.arange(0, n / fs, 1 / fs)
|
|
283
|
-
bw = 250
|
|
284
295
|
|
|
285
296
|
noise_pow_db = -70
|
|
286
297
|
harm_pow = 0.01**2 / 2
|
|
@@ -295,9 +306,15 @@ def test_dc_measurement():
|
|
|
295
306
|
|
|
296
307
|
f1 = 100.13
|
|
297
308
|
|
|
298
|
-
x =
|
|
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
|
+
)
|
|
299
316
|
|
|
300
|
-
results =
|
|
317
|
+
results = spec_analysis(x, fs=fs)
|
|
301
318
|
|
|
302
319
|
print("Function results:")
|
|
303
320
|
for key, value in results.items():
|
|
@@ -313,14 +330,12 @@ def test_dc_measurement():
|
|
|
313
330
|
|
|
314
331
|
tolerance = 0.3
|
|
315
332
|
|
|
316
|
-
|
|
317
|
-
assert np.isclose(results["dc_db"], dc_power_db, rtol=tolerance)
|
|
318
|
-
assert np.isclose(results["noise_db"], thdn_db - 3, rtol=tolerance)
|
|
333
|
+
amp_arr = np.asarray([2, 0.01, 3])
|
|
319
334
|
|
|
335
|
+
amp_arr_db = 10 * np.log10((amp_arr**2) / 2)
|
|
320
336
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
test_dc_measurement()
|
|
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)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Tests spectrum analysis function."""
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2025 ericsmacedo
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
|
|
24
|
+
import matplotlib.pyplot as plt
|
|
25
|
+
import numpy as np
|
|
26
|
+
from pytest import mark
|
|
27
|
+
|
|
28
|
+
from harm_analysis import spec_analysis
|
|
29
|
+
|
|
30
|
+
rng = np.random.default_rng()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@mark.parametrize("plot_en", [True, False])
|
|
34
|
+
def test_harm_analysis(plot_en):
|
|
35
|
+
"""Test for harm_analysis function.
|
|
36
|
+
|
|
37
|
+
Checks if the function can obtain results with less than 0.1 dB of error.
|
|
38
|
+
"""
|
|
39
|
+
# test signal
|
|
40
|
+
n = 4096
|
|
41
|
+
fs = 1000
|
|
42
|
+
t = np.arange(0, n / fs, 1 / fs)
|
|
43
|
+
f1 = 100.13
|
|
44
|
+
|
|
45
|
+
noise = rng.normal(loc=0, scale=10 ** (-70 / 20), size=len(t))
|
|
46
|
+
|
|
47
|
+
# Test signal
|
|
48
|
+
# Tone with harmonics, DC and white gaussian noise
|
|
49
|
+
x = (
|
|
50
|
+
noise
|
|
51
|
+
+ 0.1234
|
|
52
|
+
+ 2 * np.cos(2 * np.pi * f1 * t)
|
|
53
|
+
+ 0.01 * np.cos(2 * np.pi * f1 * 2 * t)
|
|
54
|
+
+ 0.005 * np.cos(2 * np.pi * f1 * 3 * t)
|
|
55
|
+
+ 0.01 * np.cos(2 * np.pi * f1 * 0.43 * t)
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# Use the harm_analysis function
|
|
59
|
+
if plot_en:
|
|
60
|
+
fig, ax = plt.subplots()
|
|
61
|
+
spec_analysis(x, fs=fs, plot=True, ax=ax)
|
|
62
|
+
else:
|
|
63
|
+
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)
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
# MIT License
|
|
2
|
-
#
|
|
3
|
-
# Copyright (c) 2025 ericsmacedo
|
|
4
|
-
#
|
|
5
|
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
# in the Software without restriction, including without limitation the rights
|
|
8
|
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
# furnished to do so, subject to the following conditions:
|
|
11
|
-
#
|
|
12
|
-
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
# copies or substantial portions of the Software.
|
|
14
|
-
#
|
|
15
|
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
# SOFTWARE.
|
|
22
|
-
"""CLI for harm_analysis."""
|
|
23
|
-
|
|
24
|
-
import click
|
|
25
|
-
import matplotlib.pyplot as plt
|
|
26
|
-
import numpy as np
|
|
27
|
-
from matplotlib.ticker import EngFormatter
|
|
28
|
-
|
|
29
|
-
from .harm_analysis import dc_measurement, harm_analysis
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
@click.command()
|
|
33
|
-
@click.argument("filename", type=click.Path(exists=True, readable=True))
|
|
34
|
-
@click.option("--fs", default=1.0, help="Sampling frequency.")
|
|
35
|
-
@click.option("--plot", is_flag=True, help="Plot the power spectrum of the data")
|
|
36
|
-
@click.option("--dc", is_flag=True, help="Run only DC measurement")
|
|
37
|
-
@click.option("--sep", default=" ", help="Separator between items.")
|
|
38
|
-
@click.option(
|
|
39
|
-
"--sfactor",
|
|
40
|
-
default="1",
|
|
41
|
-
help="Scaling factor to apply to the data. Examples: 1/8, 5, etc",
|
|
42
|
-
)
|
|
43
|
-
def cli(filename, fs, plot, sep, sfactor, dc): # noqa: PLR0913
|
|
44
|
-
"""Runs the harm_analysis function for a file containing time domain data."""
|
|
45
|
-
# scaling factor
|
|
46
|
-
file_data = np.fromfile(filename, sep=sep) * eval(sfactor)
|
|
47
|
-
|
|
48
|
-
if plot is True:
|
|
49
|
-
fig, ax = plt.subplots(1, 2, figsize=(15, 5))
|
|
50
|
-
if dc:
|
|
51
|
-
results, ax[1] = dc_measurement(file_data, fs=fs, plot=True, ax=ax[1])
|
|
52
|
-
else:
|
|
53
|
-
results, ax[1] = harm_analysis(file_data, fs=fs, plot=True, ax=ax[1])
|
|
54
|
-
elif dc:
|
|
55
|
-
results = dc_measurement(file_data, fs=fs)
|
|
56
|
-
else:
|
|
57
|
-
results = harm_analysis(file_data, fs=fs, plot=False)
|
|
58
|
-
|
|
59
|
-
print("Function results:")
|
|
60
|
-
for key, value in results.items():
|
|
61
|
-
click.echo(f"{key.ljust(10)}: {value}")
|
|
62
|
-
|
|
63
|
-
if plot is True:
|
|
64
|
-
ax[1].grid(True, which="both")
|
|
65
|
-
ax[1].set_title("Power spectrum")
|
|
66
|
-
ax[1].set_xscale("log")
|
|
67
|
-
ax[1].xaxis.set_major_formatter(EngFormatter(unit="Hz"))
|
|
68
|
-
|
|
69
|
-
ax[0].set_title("Data")
|
|
70
|
-
ax[0].plot(file_data)
|
|
71
|
-
ax[0].grid(True, which="both", linestyle="-")
|
|
72
|
-
ax[0].set_xlabel("[n]")
|
|
73
|
-
|
|
74
|
-
plt.tight_layout()
|
|
75
|
-
plt.show()
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
# MIT License
|
|
2
|
-
#
|
|
3
|
-
# Copyright (c) 2025 ericsmacedo
|
|
4
|
-
#
|
|
5
|
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
# in the Software without restriction, including without limitation the rights
|
|
8
|
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
# furnished to do so, subject to the following conditions:
|
|
11
|
-
#
|
|
12
|
-
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
# copies or substantial portions of the Software.
|
|
14
|
-
#
|
|
15
|
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
# SOFTWARE.
|
|
22
|
-
|
|
23
|
-
# MIT License
|
|
24
|
-
#
|
|
25
|
-
# Copyright (c) 2025 ericsmacedo
|
|
26
|
-
#
|
|
27
|
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
28
|
-
# of this software and associated documentation files (the "Software"), to deal
|
|
29
|
-
# in the Software without restriction, including without limitation the rights
|
|
30
|
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
31
|
-
# copies of the Software, and to permit persons to whom the Software is
|
|
32
|
-
# furnished to do so, subject to the following conditions:
|
|
33
|
-
#
|
|
34
|
-
# The above copyright notice and this permission notice shall be included in all
|
|
35
|
-
# copies or substantial portions of the Software.
|
|
36
|
-
#
|
|
37
|
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRAnTY OF ANY KIND, EXPRESS OR
|
|
38
|
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
39
|
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
40
|
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
41
|
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
42
|
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
43
|
-
# SOFTWARE.
|
|
44
|
-
|
|
45
|
-
"""Tests the CLI for the harmonic analysis function."""
|
|
46
|
-
|
|
47
|
-
import numpy as np
|
|
48
|
-
from click.testing import CliRunner
|
|
49
|
-
|
|
50
|
-
from harm_analysis.cli import cli
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
def test_harm_analysis_cli():
|
|
54
|
-
"""Test for harm_analysis function.
|
|
55
|
-
|
|
56
|
-
Checks if the function can obtain results with less than 0.1 dB of error.
|
|
57
|
-
"""
|
|
58
|
-
# test signal
|
|
59
|
-
n = 2048
|
|
60
|
-
fs = 1000
|
|
61
|
-
t = np.arange(0, n / fs, 1 / fs)
|
|
62
|
-
|
|
63
|
-
noise_pow_db = -70
|
|
64
|
-
noise_std = 10 ** (noise_pow_db / 20)
|
|
65
|
-
dc_level = 0.123456789
|
|
66
|
-
|
|
67
|
-
random_state = np.random.RandomState(1234567890)
|
|
68
|
-
noise = random_state.normal(loc=0, scale=noise_std, size=len(t))
|
|
69
|
-
|
|
70
|
-
f1 = 100.13
|
|
71
|
-
|
|
72
|
-
x = (
|
|
73
|
-
dc_level
|
|
74
|
-
+ 2 * np.cos(2 * np.pi * f1 * t)
|
|
75
|
-
+ 0.01 * np.cos(2 * np.pi * f1 * 2 * t)
|
|
76
|
-
+ 0.005 * np.cos(2 * np.pi * f1 * 3 * t)
|
|
77
|
-
+ noise
|
|
78
|
-
)
|
|
79
|
-
|
|
80
|
-
# Save data to TXT file
|
|
81
|
-
np.savetxt("test_data_cli.txt", x, delimiter="\n")
|
|
82
|
-
|
|
83
|
-
runner = CliRunner()
|
|
84
|
-
|
|
85
|
-
result = runner.invoke(cli, ["test_data_cli.txt", "--fs", fs])
|
|
86
|
-
|
|
87
|
-
assert result.exit_code == 0
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
if __name__ == "__main__":
|
|
91
|
-
test_harm_analysis_cli()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|