pdh_demo2.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python3
  2. import matplotlib
  3. import matplotlib.pyplot as plt
  4. from matplotlib import animation
  5. import numpy as np
  6. from numpy import cos, pi
  7. matplotlib.rcParams.update({'font.size': 15})
  8. c = 3E8 # m/s
  9. L = 1.0 # m
  10. FSR = 2*pi*c/(2*L) # Hz
  11. A0 = 1.0
  12. w0 = 1E9*FSR
  13. f0 = w0 / 2 / pi
  14. a_mod = 200
  15. w_mod = 0.0002 * w0
  16. f_mod = w_mod / 2 / pi
  17. def R_e(w):
  18. T = 0.05
  19. R = 1-T
  20. return 1 - T**2 / (1 + R**2 - 2*R*cos(w*2*L/c))
  21. def get_ref_power(freqs, powers):
  22. return sum(power*R_e(freq) for freq, power in zip(freqs, powers))
  23. def main():
  24. sample_n = 2000000
  25. ts = np.linspace(0, 10000*(1/f0), sample_n)
  26. dt = ts[1]-ts[0]
  27. mod = a_mod*np.sin(w_mod*ts)
  28. Es = A0*np.cos(w0*ts + mod)
  29. print("FSR", FSR)
  30. print(1/f0, dt)
  31. n_groups = 100
  32. win_size = int((1/f_mod) / dt / 12)
  33. win_spacing = (sample_n - win_size) // (n_groups+2)
  34. fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, ncols=1)
  35. def do_plot(i):
  36. print(i)
  37. # ax0.clear()
  38. ax1.clear()
  39. n = ts.size // n_groups
  40. win_start = (win_size//2) + i*win_spacing
  41. win_end = win_start + win_size
  42. print(f"{win_start},{win_end}")
  43. # sec_ts = ts[win_start:win_end]
  44. sec = Es[win_start:win_end]
  45. # mod_sec = mod[win_start:win_end]
  46. sec_ft = np.fft.rfftn(sec)
  47. freq = np.fft.fftfreq(sec.size, d=dt)[:n//2]
  48. power = (sec_ft[:n//2].real**2 + sec_ft[:n//2].imag**2) / win_size
  49. # ax0.plot(sec_ts, mod_sec)
  50. ax0.plot(ts[(win_start+win_end) // 2], mod[(win_start+win_end) // 2], 'k.')
  51. ax0.set_ylim(-1.1*a_mod, 1.1*a_mod)
  52. ax0.set_xlim(0, ts[-1])
  53. ax1.plot(2*pi*freq/w0, power)
  54. ax1.set_xlim(0.80, 1.20)
  55. ref_power = get_ref_power(freq, power)
  56. ax2.plot(ts[(win_start+win_end) // 2], ref_power, 'r.')
  57. ax2.set_xlim(0, ts[-1])
  58. plt.tight_layout()
  59. anim = animation.FuncAnimation(fig, do_plot, n_groups)
  60. anim.save("output.mp4")
  61. if __name__ == '__main__':
  62. main()