Skip to content

Instantly share code, notes, and snippets.

@wiccy46
Created July 25, 2019 21:01
Show Gist options
  • Select an option

  • Save wiccy46/dc242c151858c48afe65cfa3bf935d20 to your computer and use it in GitHub Desktop.

Select an option

Save wiccy46/dc242c151858c48afe65cfa3bf935d20 to your computer and use it in GitHub Desktop.
[dbfft] Power Spectrum in dB #python #dsp
def dbfft(x, fs, win=None, ref=32768):
"""
Calculate spectrum in dB scale
Args:
x: input signal
fs: sampling frequency
win: vector containing window samples (same length as x).
If not provided, then rectangular window is used by default.
ref: reference value used for dBFS scale. 32768 for int16 and 1 for float
Returns:
freq: frequency vector
s_db: spectrum in dB scale
"""
N = len(x) # Length of input sequence
if win is None:
win = np.ones(1, N)
if len(x) != len(win):
raise ValueError('Signal and window must be of the same length')
x = x * win
# Calculate real FFT and frequency vector
sp = np.fft.rfft(x)
freq = np.arange((N / 2) + 1) / (float(N) / fs)
# Scale the magnitude of FFT by window and factor of 2,
# because we are using half of FFT spectrum.
s_mag = np.abs(sp) * 2 / np.sum(win)
# Convert to dBFS
s_dbfs = 20 * np.log10(s_mag/ref)
if len(freq) > len(s_dbfs):
freq = freq[:len(s_dbfs)]
if len(s_dbfs) > len(freq):
s_dbfs = s_dbfs[:len(freq)]
return freq, s_dbfs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment