Pārlūkot izejas kodu

harmonic removal

tags/1.6.1
Trevor Irons 5 gadus atpakaļ
vecāks
revīzija
ee706a6d4c
1 mainītis faili ar 79 papildinājumiem un 0 dzēšanām
  1. 79
    0
      akvo/tressel/harmonic.py

+ 79
- 0
akvo/tressel/harmonic.py Parādīt failu

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

Notiek ielāde…
Atcelt
Saglabāt