Skip to content

Commit 190ceea

Browse files
committed
Fixed issue with leaky indices
1 parent d637c9d commit 190ceea

File tree

2 files changed

+41
-8
lines changed

2 files changed

+41
-8
lines changed

adc_eval/spectrum.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -90,18 +90,25 @@ def find_harmonics(spectrum, freq, nfft, bin_sig, psig, harms=5, leak=20):
9090
bin_harm = int(harm - (zone - 1) * nfft / 2)
9191

9292
# Make sure we pick the max bin where power is maximized; due to spectral leakage
93-
bin_harm_max = bin_harm
93+
# if bin_harm == nfft/2, set to bin of 0
94+
if bin_harm == nfft/2:
95+
bin_harm = 0
96+
pwr_max = spectrum[bin_harm]
9497
for i in range(bin_harm - leak, bin_harm + leak + 1):
95-
if spectrum[i] > spectrum[bin_harm_max]:
96-
bin_harm_max = i
97-
98-
bin_harm = bin_harm_max
98+
try:
99+
pwr = spectrum[i]
100+
if pwr > pwr_max:
101+
bin_harm_max = i
102+
pwr_max = pwr
103+
except IndexError:
104+
# bin + leakage out of bounds, so stop looking
105+
break
99106

100107
harm_stats["harm"][harm_index]["bin"] = bin_harm
101-
harm_stats["harm"][harm_index]["power"] = spectrum[bin_harm]
108+
harm_stats["harm"][harm_index]["power"] = pwr
102109
harm_stats["harm"][harm_index]["freq"] = round(freq[bin_harm] / 1e6, 1)
103-
harm_stats["harm"][harm_index]["dBc"] = dBW(spectrum[bin_harm] / psig)
104-
harm_stats["harm"][harm_index]["dB"] = dBW(spectrum[bin_harm])
110+
harm_stats["harm"][harm_index]["dBc"] = dBW(pwr / psig)
111+
harm_stats["harm"][harm_index]["dB"] = dBW(pwr)
105112

106113
harm_index = harm_index + 1
107114

tests/test_spectrum_plotting.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,32 @@ def test_find_harmonics_with_leakage(self):
7070
msg=msg_txt,
7171
)
7272

73+
def test_find_harmonics_with_leakage_outside_bounds(self):
74+
"""Test find harmonics with leakage bins exceeding array bounds."""
75+
self.bin = self.nfft / 4 - 0.5
76+
(freq, pwr) = self.gen_spectrum(5)
77+
leakage_bins = 10
78+
stats = spectrum.find_harmonics(
79+
pwr, freq, self.nfft, self.bin, self.arms, harms=2, leak=leakage_bins
80+
81+
)
82+
self.assertEqual(stats["harm"][2]["bin"], self.nfft/2 - 1)
83+
84+
def test_find_harmonics_on_fft_bound(self):
85+
"""Test find harmonics with harmonics landing at nfft/2."""
86+
self.nfft = 2**12
87+
self.bin = self.nfft / 8
88+
(freq, pwr) = self.gen_spectrum(10)
89+
leakage_bins = 10
90+
stats = spectrum.find_harmonics(
91+
pwr, freq, self.nfft, self.bin, self.arms, harms=5, leak=leakage_bins
92+
93+
)
94+
self.assertEqual(stats["harm"][2]["bin"], 2 * self.bin)
95+
self.assertEqual(stats["harm"][3]["bin"], 3 * self.bin)
96+
self.assertEqual(stats["harm"][4]["bin"], 0)
97+
self.assertEqual(stats["harm"][5]["bin"], self.nfft - 5*self.bin)
98+
7399
def test_plot_string(self):
74100
"""Test proper return of plotting string."""
75101
self.bin = 13

0 commit comments

Comments
 (0)