harm-analysis 1.4.1__tar.gz → 2.0.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.
Files changed (30) hide show
  1. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/PKG-INFO +17 -1
  2. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/README.md +14 -0
  3. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/pyproject.toml +16 -14
  4. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/src/harm_analysis/__init__.py +6 -2
  5. harm_analysis-2.0.0/src/harm_analysis/_harm_analysis.py +27 -0
  6. harm_analysis-2.0.0/src/harm_analysis/_harmonic.py +423 -0
  7. harm_analysis-2.0.0/src/harm_analysis/_plotting.py +218 -0
  8. harm_analysis-2.0.0/src/harm_analysis/_results.py +116 -0
  9. harm_analysis-2.0.0/src/harm_analysis/_spectral.py +300 -0
  10. harm_analysis-2.0.0/src/harm_analysis/_spectrum.py +363 -0
  11. harm_analysis-2.0.0/src/harm_analysis/cli.py +244 -0
  12. harm_analysis-2.0.0/src/harm_analysis/mcp_server.py +163 -0
  13. harm_analysis-2.0.0/src/harm_analysis/py.typed +0 -0
  14. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/tests/__init__.py +1 -1
  15. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/tests/conftest.py +1 -1
  16. harm_analysis-2.0.0/tests/test_cli.py +257 -0
  17. harm_analysis-2.0.0/tests/test_docs_cli_examples.py +74 -0
  18. harm_analysis-2.0.0/tests/test_edge_cases.py +286 -0
  19. harm_analysis-2.0.0/tests/test_fft_length.py +130 -0
  20. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/tests/test_harm_analysis.py +100 -34
  21. harm_analysis-2.0.0/tests/test_mcp_server.py +133 -0
  22. harm_analysis-2.0.0/tests/test_plotting.py +133 -0
  23. harm_analysis-2.0.0/tests/test_spectrum_analysis.py +215 -0
  24. harm_analysis-2.0.0/tests/test_validation.py +103 -0
  25. harm_analysis-1.4.1/src/harm_analysis/_harm_analysis.py +0 -834
  26. harm_analysis-1.4.1/src/harm_analysis/cli.py +0 -142
  27. harm_analysis-1.4.1/tests/test_cli.py +0 -117
  28. harm_analysis-1.4.1/tests/test_data_cli.txt +0 -2048
  29. harm_analysis-1.4.1/tests/test_spectrum_analysis.py +0 -125
  30. {harm_analysis-1.4.1 → harm_analysis-2.0.0}/LICENSE +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: harm-analysis
3
- Version: 1.4.1
3
+ Version: 2.0.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>
@@ -20,6 +20,8 @@ Requires-Dist: matplotlib>=3.10.3
20
20
  Requires-Dist: numpy>=2.2.6
21
21
  Requires-Dist: rich>=14.1.0
22
22
  Requires-Dist: scipy>=1.15.3
23
+ Provides-Extra: mcp
24
+ Requires-Dist: mcp>=2; extra == "mcp"
23
25
  Description-Content-Type: text/markdown
24
26
 
25
27
 
@@ -49,8 +51,22 @@ The package provides two main functions:
49
51
  - `harm_analysis`: for simulations with an injected tone, returning SNR, THDN, Noise, etc.
50
52
  - `spec_analysis`: for cases without an injected tone, that auto-detects DC, tones, and noise from the spectrum.
51
53
 
54
+ <!-- overview-start -->
55
+ ![harm_analysis measures SNR, THD and SINAD of a test tone; spec_analysis finds DC, tones and noise in any signal](https://raw.githubusercontent.com/ericsmacedo/harm-analysis/main/docs/images/overview.png)
56
+ <!-- overview-end -->
57
+
58
+ ```python
59
+ from harm_analysis import harm_analysis
60
+
61
+ r = harm_analysis(x, fs=48000)
62
+ print(r.snr_db, r.thd_db, r.sinad_db)
63
+ ```
64
+
52
65
  See [usage](./docs/usage.md) for examples.
53
66
 
67
+ AI assistants (Claude, GitHub Copilot, ...) can run the analyses through the included
68
+ MCP server; see [AI assistants](./docs/ai.md).
69
+
54
70
 
55
71
  ## Installation
56
72
 
@@ -25,8 +25,22 @@ The package provides two main functions:
25
25
  - `harm_analysis`: for simulations with an injected tone, returning SNR, THDN, Noise, etc.
26
26
  - `spec_analysis`: for cases without an injected tone, that auto-detects DC, tones, and noise from the spectrum.
27
27
 
28
+ <!-- overview-start -->
29
+ ![harm_analysis measures SNR, THD and SINAD of a test tone; spec_analysis finds DC, tones and noise in any signal](https://raw.githubusercontent.com/ericsmacedo/harm-analysis/main/docs/images/overview.png)
30
+ <!-- overview-end -->
31
+
32
+ ```python
33
+ from harm_analysis import harm_analysis
34
+
35
+ r = harm_analysis(x, fs=48000)
36
+ print(r.snr_db, r.thd_db, r.sinad_db)
37
+ ```
38
+
28
39
  See [usage](./docs/usage.md) for examples.
29
40
 
41
+ AI assistants (Claude, GitHub Copilot, ...) can run the analyses through the included
42
+ MCP server; see [AI assistants](./docs/ai.md).
43
+
30
44
 
31
45
  ## Installation
32
46
 
@@ -29,7 +29,7 @@ keywords = [
29
29
  "THD",
30
30
  "SNR",
31
31
  ]
32
- version = "1.4.1"
32
+ version = "2.0.0"
33
33
 
34
34
  [project.urls]
35
35
  Homepage = "https://github.com/ericsmacedo/harm-analysis"
@@ -39,23 +39,31 @@ Documentation = "https://harm-analysis.readthedocs.io/en/stable/"
39
39
  [project.scripts]
40
40
  harm-analysis = "harm_analysis.cli:harm_analysis_cmd"
41
41
  spec-analysis = "harm_analysis.cli:spec_analysis_cmd"
42
+ harm-analysis-mcp = "harm_analysis.mcp_server:main"
43
+
44
+ [project.optional-dependencies]
45
+ mcp = [
46
+ "mcp>=2",
47
+ ]
42
48
 
43
49
  [dependency-groups]
44
50
  dev = [
51
+ "colorama>=0.4.6",
45
52
  "contextlib-chdir>=1.0.2",
46
53
  "coveralls>=3.3.1",
47
54
  "invoke>=2.2.0",
48
- "mkdocs-click>=0.8.1",
49
- "mkdocs-include-markdown-plugin>=6.0.5",
50
- "mkdocs-literate-nav>=0.6.1",
51
- "mkdocs-material>=9.5.18",
52
- "mkdocstrings-python>=1.9.2",
53
- "mypy>=1.9.0",
54
55
  "pre-commit>=4.1.0",
55
56
  "pytest-cov>=5.0.0",
56
57
  "ruff>=0.11.2",
58
+ "furo>=2024.8.6",
59
+ "myst-parser>=4.0.0",
60
+ "sphinx>=8.1.3",
61
+ "sphinx-click>=6.0.0",
62
+ "sphinx-copybutton>=0.5.2",
57
63
  "test2ref>=0.4.2",
58
64
  "truststore>=0.10.4",
65
+ "ty>=0.0.99",
66
+ "mcp>=2",
59
67
  ]
60
68
 
61
69
  [build-system]
@@ -137,6 +145,7 @@ filterwarnings = [
137
145
  ]
138
146
  testpaths = [
139
147
  "tests",
148
+ "src",
140
149
  ]
141
150
 
142
151
  [tool.coverage.run]
@@ -149,10 +158,3 @@ exclude_lines = [
149
158
  "pragma: no cover",
150
159
  "assert False",
151
160
  ]
152
-
153
- [tool.mypy]
154
- disable_error_code = "misc"
155
- ignore_missing_imports = true
156
- overrides = [
157
- { module = "tests.*", allow_untyped_defs = true },
158
- ]
@@ -1,6 +1,6 @@
1
1
  # MIT License
2
2
  #
3
- # Copyright (c) 2025 ericsmacedo
3
+ # Copyright (c) 2025-2026 ericsmacedo
4
4
  #
5
5
  # Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  # of this software and associated documentation files (the "Software"), to deal
@@ -21,9 +21,13 @@
21
21
  # SOFTWARE.
22
22
  """Harmonic Analysis."""
23
23
 
24
- from ._harm_analysis import harm_analysis, spec_analysis
24
+ from ._harmonic import harm_analysis
25
+ from ._results import HarmResult, SpecResult
26
+ from ._spectral import spec_analysis
25
27
 
26
28
  __all__ = [
29
+ "HarmResult",
30
+ "SpecResult",
27
31
  "harm_analysis",
28
32
  "spec_analysis",
29
33
  ]
@@ -0,0 +1,27 @@
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2025-2026 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
+ """Harm Analysis core functions."""
23
+
24
+ from ._harmonic import harm_analysis
25
+ from ._spectral import spec_analysis
26
+
27
+ __all__ = ["harm_analysis", "spec_analysis"]
@@ -0,0 +1,423 @@
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2025-2026 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
+ """Harm Analysis core functions."""
23
+
24
+ import numpy as np
25
+ from matplotlib.axes import Axes
26
+ from numpy.typing import NDArray
27
+
28
+ from ._plotting import _plot_harm
29
+ from ._results import HarmResult
30
+ from ._spectral import _MEDIAN_WINDOW, _detection_threshold_db
31
+ from ._spectrum import (
32
+ _find_dc_bins,
33
+ _find_freq_bins,
34
+ _int_noise_curve,
35
+ _power_from_bins,
36
+ _power_spectrum,
37
+ _to_db,
38
+ _validate_inputs,
39
+ )
40
+
41
+ # Half-width, in bins, of the search for the fundamental around `fund_freq`
42
+ _FUND_SEARCH_BINS = 3
43
+ # Probability that noise alone passes as the fundamental at `fund_freq`
44
+ _FUND_FALSE_ALARM_RATE = 1e-3
45
+
46
+
47
+ def _peak_near(x, fund_freq, fund_bin, dc_end, bw_bins, freq_array): # noqa: PLR0913
48
+ """Return the bin of the tone within ``_FUND_SEARCH_BINS`` of `fund_bin`.
49
+
50
+ Raises a ValueError if `fund_bin` is inside the DC bins, if the spectrum keeps rising
51
+ past the search range, or if the peak does not stand out from the local noise floor
52
+ (so noise is never analyzed as the fundamental).
53
+ """
54
+ if fund_bin < dc_end:
55
+ raise ValueError(
56
+ f"`fund_freq` ({fund_freq:.6g}) is inside the DC component of the spectrum, which extends to "
57
+ f"{freq_array[dc_end]:.6g} (in the units of `fs`)."
58
+ )
59
+ lo = max(dc_end, fund_bin - _FUND_SEARCH_BINS)
60
+ hi = min(bw_bins, fund_bin + _FUND_SEARCH_BINS)
61
+ peak = lo + int(np.argmax(x[lo : hi + 1]))
62
+ rising_below = peak == lo and peak > dc_end and x[peak - 1] > x[peak]
63
+ rising_above = peak == hi and peak + 1 < x.size and x[peak + 1] > x[peak]
64
+ if rising_below or rising_above:
65
+ raise ValueError(
66
+ f"No spectral peak found within {_FUND_SEARCH_BINS} bins of `fund_freq` ({fund_freq:.6g}); "
67
+ "check `fund_freq` and `fs`."
68
+ )
69
+
70
+ # The peak must be a tone, not noise: compare it with the local noise floor using the
71
+ # tone-detection threshold of spec_analysis for a single, known location.
72
+ half = _MEDIAN_WINDOW // 2
73
+ floor_db = np.median(_to_db(x[max(0, peak - half) : peak + half + 1]))
74
+ excess_db = _to_db(x[peak]) - floor_db
75
+ if excess_db < _detection_threshold_db(1, _FUND_FALSE_ALARM_RATE):
76
+ raise ValueError(
77
+ f"No tone found near `fund_freq` ({fund_freq:.6g}): the largest peak within {_FUND_SEARCH_BINS} "
78
+ f"bins is only {excess_db:.1f} dB above the local noise floor; check `fund_freq` and `fs`."
79
+ )
80
+ return peak
81
+
82
+
83
+ def _find_bins(x, n_harm, bw_bins, enbw_bins, freq_array, fund_freq=None, fund_bin=None): # noqa: PLR0913
84
+ """Find all bins that belong to the fundamental, harmonics, DC, and noise.
85
+
86
+ Parameters
87
+ ----------
88
+ x : ndarray
89
+ Input signal. The input should be the absolute value of the right-sided power
90
+ spectrum.
91
+ bw_bins : int
92
+ Max bin to look for the fundamental tone. The function will only try to find
93
+ the fundamental up to this point.
94
+ n_harm : int
95
+ Number of harmonics to find
96
+ freq_array : ndarray
97
+ Frequency of each bin of `x`, used in error messages.
98
+ fund_freq : float or None
99
+ Expected frequency of the fundamental (for error messages).
100
+ fund_bin : int or None
101
+ Expected bin of the fundamental. If None, the highest bin between DC and
102
+ `bw_bins` is used; otherwise the peak within ``_FUND_SEARCH_BINS`` of it.
103
+
104
+ Raises:
105
+ ------
106
+ ValueError
107
+ If the analysis band (`bw_bins`) ends inside the DC bins, or if `fund_bin` is
108
+ inside the DC bins or has no tone near it.
109
+
110
+ Notes:
111
+ -----
112
+ This function only works for the right-sided power spectrum (positive frequencies
113
+ only).
114
+ """
115
+ # Index of last dc bin
116
+ dc_end = int(_find_dc_bins(x))
117
+ dc_bins = np.arange(dc_end)
118
+ dc_pow = _power_from_bins(x, dc_bins, enbw_bins=enbw_bins, bw_bins=bw_bins)
119
+
120
+ if bw_bins <= dc_end:
121
+ raise ValueError(
122
+ f"`bw` is inside the DC component of the spectrum, which extends to {freq_array[dc_end]:.6g} "
123
+ "(in the units of `fs`). Use a larger `bw`."
124
+ )
125
+
126
+ if fund_bin is None:
127
+ # the fundamental frequency is found by searching for the bin with the
128
+ # maximum value, excluding DC
129
+ max_loc = int(np.argmax(x[dc_end:bw_bins])) + dc_end
130
+ else:
131
+ max_loc = _peak_near(x, fund_freq, fund_bin, dc_end, bw_bins, freq_array)
132
+
133
+ # list containing bins of fundamental
134
+ fund_pow, fund_loc, fund_bins = _find_freq_bins(x, max_loc, bw_bins=bw_bins, enbw_bins=enbw_bins, min_bin=dc_end)
135
+
136
+ # THD+N bins (all bins excluding DC and the fundamental)
137
+ thdn_bins = np.setdiff1d(np.arange(len(x)), np.concatenate((fund_bins, dc_bins)))
138
+
139
+ harm_pow, harm_loc, harm_bins = _find_harm(
140
+ x, fund_loc, n_harm, bw_bins, enbw_bins=enbw_bins, min_bin=dc_end, fund_bins=fund_bins
141
+ )
142
+
143
+ # Remaining bins are considered noise.
144
+ if harm_bins.size > 0:
145
+ noise_bins = np.setdiff1d(thdn_bins, harm_bins)
146
+ else:
147
+ noise_bins = thdn_bins
148
+
149
+ noise_pow = _power_from_bins(x, noise_bins, enbw_bins=enbw_bins, bw_bins=bw_bins)
150
+
151
+ # According to wikipedia, THD+N in dB is equal to
152
+ # 10*log10(sum(harmonics power + Noise power)/fundamental power).
153
+ # THD+N is recriprocal to SINAD (SINAD_dB = -THD+N_dB)
154
+ thdn_pow = _power_from_bins(x, thdn_bins, enbw_bins=enbw_bins, bw_bins=bw_bins) / fund_pow
155
+
156
+ return (
157
+ (fund_pow, fund_loc, fund_bins),
158
+ (harm_pow, harm_loc, harm_bins),
159
+ (dc_pow, dc_bins),
160
+ (noise_pow, noise_bins),
161
+ (thdn_pow, thdn_bins),
162
+ )
163
+
164
+
165
+ def _find_harm(x, fund_loc, n_harm, bw_bins, enbw_bins, min_bin=0, fund_bins=None): # noqa: PLR0913
166
+ """Find the power, location and bins of the harmonics inside the analysis band.
167
+
168
+ Returns empty arrays if `n_harm` is 0 or if all harmonics are above `bw_bins`
169
+ (the `bw` limit or fs/2).
170
+
171
+ Bins that belong to the fundamental (`fund_bins`) are never counted as harmonic: without
172
+ a noise floor, the fundamental's leakage can reach the harmonic frequencies, and that
173
+ power must not be counted twice. A harmonic left with no bins has zero power.
174
+ """
175
+ # Expected bin of each harmonic; harmonics above the band are ignored
176
+ harm_locs = fund_loc * np.arange(2, n_harm + 2)
177
+ harm_locs = harm_locs[harm_locs <= bw_bins]
178
+
179
+ if harm_locs.size == 0: # n_harm == 0, or all harmonics outside the band
180
+ return np.array([]), np.array([]), np.array([], dtype=int)
181
+
182
+ exclude = np.array([], dtype=int) if fund_bins is None else fund_bins
183
+ harm_pow, harm_loc, harm_bins = [], [], []
184
+ for expected in harm_locs:
185
+ _, loc, bins = _find_freq_bins(x, int(expected), bw_bins=bw_bins, enbw_bins=enbw_bins, min_bin=min_bin)
186
+ bins = np.setdiff1d(bins, exclude)
187
+ harm_pow.append(_power_from_bins(x, bins, enbw_bins=enbw_bins, bw_bins=bw_bins))
188
+ harm_loc.append(loc if bins.size else expected)
189
+ harm_bins.append(bins)
190
+
191
+ return np.array(harm_pow), np.array(harm_loc), np.concatenate(harm_bins).astype(int)
192
+
193
+
194
+ def _last_value(curve) -> float:
195
+ """Return the last unmasked value of an integrated (masked) curve, or -inf if all are masked.
196
+
197
+ The integrated noise curve is masked at bins that are not noise, so its last element is
198
+ masked whenever the last bin (fs/2) belongs to a tone or harmonic.
199
+ """
200
+ values = np.ma.compressed(curve)
201
+ return float(values[-1]) if values.size else -np.inf
202
+
203
+
204
+ def harm_analysis( # noqa: PLR0913
205
+ x: NDArray[np.float64],
206
+ fs: float = 1,
207
+ bw: float | None = None,
208
+ n_harm: int = 5,
209
+ window: None | NDArray[np.float64] = None,
210
+ plot: bool = False,
211
+ ax: None | Axes = None,
212
+ fund_freq: float | None = None,
213
+ ) -> HarmResult:
214
+ """Harmonic Analysis.
215
+
216
+ Calculates the fundamental, harmonics, DC and noise power of the input signal x,
217
+ and from them the THD, SNR, SINAD and THD+N.
218
+
219
+ Intended for signals with an injected tone (e.g. simulations or measurements of
220
+ a circuit driven by a sine wave). The THD is computed from the fundamental and
221
+ the first `n_harm` harmonics, using a power spectrum of the same length as the
222
+ input signal. A Hann window is applied to the signal before the power spectrum
223
+ is obtained, unless another `window` is given.
224
+
225
+ Parameters
226
+ ----------
227
+ x : array_like
228
+ Input signal, containing a tone.
229
+ fs : float, optional
230
+ Sampling frequency. Frequencies in the results are in the same units.
231
+ Default is 1.
232
+ bw : float, optional
233
+ Bandwidth to use for the calculation of the metrics, in the same units as
234
+ `fs`. Default is ``fs / 2``. Also useful to exclude another tone (or noise)
235
+ with amplitude greater than the fundamental and located above a certain
236
+ frequency (see the shaped noise example).
237
+ n_harm : int, optional
238
+ Number of harmonics used in the THD calculation. Default is 5. Harmonics
239
+ above `bw` are ignored.
240
+ window : array_like, optional
241
+ Window that will be multiplied with the signal, with the same length as `x`.
242
+ Default is a Hann window.
243
+ plot : bool, optional
244
+ If True, the power spectrum is plotted on `ax`. The caller keeps the
245
+ reference to `ax` and can keep customizing it after the call (title,
246
+ scale, limits, etc.).
247
+ ax : matplotlib.axes.Axes or None, optional
248
+ Axes to plot on. Required if `plot` is True.
249
+ fund_freq : float, optional
250
+ Expected frequency of the fundamental, in the same units as `fs`. The
251
+ fundamental is the spectral peak nearest to it (within 3 bins), which must
252
+ stand out from the local noise floor. Use it when
253
+ the signal may contain a component stronger than the injected tone. Default
254
+ is None: the highest spectral component between DC and `bw`.
255
+
256
+ Returns
257
+ -------
258
+ HarmResult
259
+ The analysis results (fundamental, harmonics, DC, noise, THD, SNR, SINAD and
260
+ THD+N). See :class:`HarmResult` for the fields. Use
261
+ :meth:`HarmResult.to_dict` to get them as a dictionary.
262
+
263
+ Powers of zero are reported as ``-inf`` dB (no warning is raised).
264
+
265
+ Raises
266
+ ------
267
+ TypeError
268
+ If `x` or `window` is complex or not numeric.
269
+ ValueError
270
+ If the input signal is constant (all zeros or DC only), as there is no tone to
271
+ analyze; if `bw` is so low that it falls inside the DC component of the
272
+ spectrum; if `fund_freq` is outside the band, inside the DC component or has
273
+ no tone near it (a peak that does not stand out from the noise floor); if
274
+ `plot` is True and no `ax` is given; or if an input is invalid:
275
+ `x` not 1-D, shorter than 32 samples or containing NaN/inf, `fs` not positive,
276
+ `window` not the same length as `x`, `bw` not in ``(0, fs / 2]``, or `n_harm`
277
+ negative.
278
+
279
+ Notes
280
+ -----
281
+ Without `fund_freq`, the fundamental is taken to be the highest spectral
282
+ component between DC and `bw`. If the signal contains a stronger tone, that tone
283
+ is reported as the fundamental. Pass `fund_freq` (or use `bw` to exclude a
284
+ stronger tone above the fundamental) to analyze the intended tone; any other tone
285
+ in the band is then counted as noise and lowers the SNR.
286
+
287
+ Ensure that the frequency components are far enough apart to accommodate for the
288
+ sidelobe width of the Hann window. If this is not feasible, you can use a different
289
+ window by using the "window" input.
290
+
291
+ A component exactly at fs/2 (e.g. the 2nd harmonic of a fundamental at fs/4) is
292
+ sampled as ``A * cos(phase) * (-1)**n``, so its measured power is
293
+ ``A**2 * cos(phase)**2`` and depends on its phase. Components within about one
294
+ bin of fs/2 (or of DC) overlap their mirror image and are also phase dependent.
295
+
296
+ References
297
+ ----------
298
+ - [1] Harris, Fredric J. "On the use of windows for harmonic analysis
299
+ with the discrete Fourier transform." Proceedings of the
300
+ IEEE 66.1 (1978): 51-83.
301
+ - [2] Cerna, Michael, and Audrey F. Harvey. The fundamentals of
302
+ FFT-based signal analysis and measurement. Application Note
303
+ 041, National Instruments, 2000.
304
+
305
+ Examples
306
+ --------
307
+ A 100.3 Hz tone with a 2nd harmonic 40 dB below it, sampled at 1 kHz:
308
+
309
+ >>> import numpy as np
310
+ >>> from harm_analysis import harm_analysis
311
+ >>> fs = 1000
312
+ >>> t = np.arange(4096) / fs
313
+ >>> rng = np.random.default_rng(0)
314
+ >>> x = np.cos(2 * np.pi * 100.3 * t) + 0.01 * np.cos(2 * np.pi * 200.6 * t)
315
+ >>> x = x + rng.normal(0, 1e-4, t.size)
316
+ >>> results = harm_analysis(x, fs=fs)
317
+ >>> round(results.fund_freq, 1)
318
+ 100.3
319
+ >>> round(results.fund_db, 2)
320
+ -3.01
321
+ >>> round(results.thd_db, 1)
322
+ -40.0
323
+ >>> round(float(results.harm_freq[0]), 1)
324
+ 200.6
325
+
326
+ All metrics as a dictionary:
327
+
328
+ >>> list(results.to_dict())[:4]
329
+ ['fund_db', 'fund_freq', 'harm_freq', 'harm_db']
330
+
331
+ Plot the spectrum on your own axes, then keep customizing them:
332
+
333
+ >>> import matplotlib.pyplot as plt
334
+ >>> fig, ax = plt.subplots()
335
+ >>> results = harm_analysis(x, fs=fs, plot=True, ax=ax)
336
+ >>> ax.set_xscale("log")
337
+ >>> plt.close(fig)
338
+ """ # noqa: D416
339
+ if plot and ax is None:
340
+ raise ValueError("An `ax` must be provided when `plot` is True.")
341
+
342
+ x = _validate_inputs(x, fs, window=window, bw=bw, n_harm=n_harm)
343
+ band = fs / 2 if bw is None else bw
344
+ if fund_freq is not None and not (np.isfinite(fund_freq) and 0 < fund_freq <= band):
345
+ raise ValueError(
346
+ f"`fund_freq` must be in (0, {'fs / 2' if bw is None else 'bw'}] = (0, {band}], got {fund_freq}."
347
+ )
348
+
349
+ if np.ptp(x) == 0:
350
+ raise ValueError("No fundamental tone found: the input signal is constant (all zeros or DC only).")
351
+
352
+ x_fft_pow, f_array, enbw_bins, bw_bins = _power_spectrum(x, fs=fs, bw=bw, window=window)
353
+
354
+ sig_len = len(x)
355
+
356
+ fund_info, harm_info, dc_info, noise_info, thdn_info = _find_bins(
357
+ x=x_fft_pow,
358
+ n_harm=n_harm,
359
+ bw_bins=bw_bins,
360
+ enbw_bins=enbw_bins,
361
+ freq_array=f_array,
362
+ fund_freq=fund_freq,
363
+ fund_bin=None if fund_freq is None else round(fund_freq * sig_len / fs),
364
+ )
365
+
366
+ fund_pow, fund_loc, fund_bins = fund_info
367
+ harm_pow, harm_loc, harm_bins = harm_info
368
+ dc_pow, dc_bins = dc_info
369
+ noise_pow, noise_bins = noise_info
370
+ thdn_pow, thdn_bins = thdn_info
371
+
372
+ # total integrated noise curve
373
+ int_noise = _int_noise_curve(x=x_fft_pow / enbw_bins, noise_bins=noise_bins)
374
+ int_noise_p_harm = _int_noise_curve(x=x_fft_pow / enbw_bins, noise_bins=thdn_bins)
375
+
376
+ # Calculate THD, Signal Power and N metrics in dB
377
+ sig_freq = fund_loc * fs / sig_len
378
+ dc_db = _to_db(dc_pow)
379
+ sig_db = _to_db(fund_pow)
380
+ noise_db = _to_db(noise_pow)
381
+ harm_db = _to_db(harm_pow)
382
+ thdn_db = _to_db(thdn_pow)
383
+ snr_db = sig_db - noise_db
384
+
385
+ # THD in dB is equal to 10*log10(sum(harmonics power)/fundamental power)
386
+ harm_freq = np.asarray(harm_loc, dtype=np.float64) * fs / sig_len
387
+ thd_db = _to_db(np.sum(harm_pow) / fund_pow) if harm_pow.size > 0 else np.nan
388
+
389
+ results = HarmResult(
390
+ fund_db=float(sig_db),
391
+ fund_freq=float(sig_freq),
392
+ harm_db=np.asarray(harm_db, dtype=np.float64),
393
+ harm_freq=harm_freq,
394
+ dc_db=float(dc_db),
395
+ noise_db=float(noise_db),
396
+ thd_db=float(thd_db),
397
+ snr_db=float(snr_db),
398
+ sinad_db=float(-thdn_db),
399
+ thdn_db=float(thdn_db),
400
+ total_noise_db=_last_value(int_noise),
401
+ )
402
+
403
+ if not plot:
404
+ return results
405
+
406
+ _plot_harm(
407
+ x=x_fft_pow,
408
+ fund_freq=sig_freq,
409
+ freq_array=f_array,
410
+ dc_bins=dc_bins,
411
+ fund_bins=fund_bins,
412
+ fund_pow_db=sig_db,
413
+ harm_bins=harm_bins,
414
+ harm_freq=harm_freq,
415
+ harm_pow_db=harm_db,
416
+ noise_bins=noise_bins,
417
+ ax=ax,
418
+ int_noise=int_noise,
419
+ int_noise_p_harm=int_noise_p_harm,
420
+ bw_bins=bw_bins,
421
+ )
422
+
423
+ return results