77def db_to_pow (value , places = 3 ):
88 """Convert dBW to W."""
99 if isinstance (value , np .ndarray ):
10- return 10 * np . log10 ( value )
10+ return 10 ** ( 0.1 * value )
1111 return round (10 ** (0.1 * value ), places )
1212
1313
@@ -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 = 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
@@ -118,7 +125,9 @@ def calc_psd(data, fs, nfft=2**12, single_sided=False):
118125 psd = np .mean (XF , axis = 1 ) / (fs / nfft ) # average the ffts and divide by bin width
119126 freq = fs * np .linspace (0 , 1 , nfft )
120127 if single_sided :
128+ # First we double all the bins, then we halve the DC bin
121129 psd = 2 * psd [0 : int (nfft / 2 )]
130+ psd [0 ] /= 2
122131 freq = freq [0 : int (nfft / 2 )]
123132 return (freq , psd )
124133
0 commit comments