Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. from bokeh.plotting import figure, output_file, vplot, show
  2. import numpy as np
  3. import random
  4.  
  5. n = 1024
  6. a = 1.0
  7. sample_period = 0.001
  8. t = np.linspace(0, n * sample_period, n)
  9. dt = t[1] - t[0]
  10. data = np.abs(np.sin(t * 2 * np.pi) * a)
  11.  
  12. def fft(data, sample_period, power=False, use_db=True):
  13. dt = sample_period
  14. sp = np.fft.rfft(data)
  15.  
  16. if power:
  17. spectrum = (np.abs(sp) * 2 * dt) ** 2
  18. else:
  19. spectrum = np.abs(sp) * 2 * dt
  20.  
  21. if use_db:
  22. max_input = np.max(data)
  23. if power:
  24. spectrum = 20 * np.log10(spectrum / max_input)
  25. else:
  26. spectrum = 10 * np.log10(spectrum / max_input)
  27. n = len(data)
  28. freqs = np.fft.fftfreq(n, sample_period)
  29.  
  30. # Ignore the negative part of frequency. It's because of symmetry of FFT.
  31. idx = np.argsort(freqs)
  32. idx = filter(lambda i: freqs[i] > 0, idx)
  33.  
  34. return freqs[idx], spectrum[idx].real
  35.  
  36. freqs, spectrum = fft(data, dt, use_db=False)
  37. freqs_db, spectrum_db = fft(data, dt, use_db=True)
  38. output_file("lines.html")
  39.  
  40. p1 = figure(width=800, height=300, title="data")
  41. p1.line(t, data, legend="data", line_width=1, color="red")
  42.  
  43. p2 = figure(width=800, height=300, title="FFT", x_axis_label="Frequency(Hz)", y_axis_label="Amplitude")
  44. p2.line(freqs, spectrum, legend="data", line_width=2, color="blue")
  45.  
  46. p3 = figure(width=800, height=300, title="FFT(dB)", x_axis_label="Frequency(Hz)", y_axis_label="Amplitude(dB)")
  47. p3.line(freqs_db, spectrum_db, legend="data", line_width=2, color="blue")
  48.  
  49. p = vplot(p1, p2, p3)
  50.  
  51. # Show the results.
  52. show(p)
  53. print(spectrum.real[10])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement