Surface NMR processing and inversion GUI
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

harmonic.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import numpy as np
  2. from scipy.optimize import least_squares
  3. def harmonic ( sN, f0, fs, nK, t ):
  4. """
  5. Performs inverse calculation of harmonics contaminating a signal.
  6. Args:
  7. sN = signal containing noise
  8. f0 = base frequency of the sinusoidal noise
  9. fs = sampling frequency
  10. nK = number of harmonics to calculate
  11. t = time samples
  12. """
  13. print("building matrix ")
  14. A = np.zeros( (len(t), 2*nK) )
  15. for irow, tt in enumerate(t):
  16. A[irow, 0::2] = np.cos( np.arange(nK)*2*np.pi*(f0/fs)*irow )
  17. A[irow, 1::2] = np.sin( np.arange(nK)*2*np.pi*(f0/fs)*irow )
  18. # brutal
  19. #for k, ik in enumerate( np.arange(0, 2*nK, 2) ):
  20. # A[irow, ik ] = np.cos( k*2*np.pi*(f0/fs)*irow )
  21. # A[irow, ik+1] = np.sin( k*2*np.pi*(f0/fs)*irow )
  22. v = np.linalg.lstsq(A, sN, rcond=None) #, rcond=1e-8)
  23. alpha = v[0][0::2]
  24. beta = v[0][1::2]
  25. amp = np.sqrt( alpha**2 + beta**2 )
  26. phase = np.arctan(- beta/alpha)
  27. h = np.zeros(len(t))
  28. for ik in range(nK):
  29. h += np.sqrt(alpha[ik]**2 + beta[ik]**2) * np.cos( 2.*np.pi*ik * (f0/fs) * np.arange(0, len(t), 1 ) + phase[ik] )
  30. #plt.matshow(A, aspect='auto')
  31. #plt.colorbar()
  32. #plt.figure()
  33. #plt.plot(alpha)
  34. #plt.plot(beta)
  35. #plt.plot(amp)
  36. #plt.figure()
  37. #plt.plot(h)
  38. #plt.title("modelled noise")
  39. return h
  40. if __name__ == "__main__":
  41. import matplotlib.pyplot as plt
  42. f0 = 60 # Hz
  43. delta = np.random.rand()
  44. fs = 50000 #1e4
  45. t = np.arange(0, 1, 1/fs)
  46. phi = .234
  47. A = 1.0
  48. nK = 20
  49. sN = A * np.sin( (delta+f0)*2*np.pi*t + phi ) + np.random.normal(0,.1,len(t))
  50. sNc = A * np.sin( (delta+f0)*2*np.pi*t + phi )
  51. h = harmonic(sN, f0, fs, nK, t)
  52. plt.figure()
  53. plt.plot(t, sN, label="sN")
  54. plt.plot(t, sN-h, label="sN-h")
  55. plt.plot(t, h, label='h')
  56. plt.title("true noise")
  57. plt.legend()
  58. plt.figure()
  59. plt.plot(t, sN-sNc, label='true noise')
  60. plt.plot(t, sN-h, label='harmonic removal')
  61. plt.legend()
  62. plt.title("true noise")
  63. plt.show()
  64. print("hello")