-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathamp_spec.py
95 lines (77 loc) · 2.26 KB
/
amp_spec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def amp_spec(data,dt):
"""
Compute the power spectrum of a given signal
Uses numpy
Assumes data is a numpy array, column vector
"""
import scipy.signal as sci
import numpy as np
ndim = data.ndim
if ndim==1 :
x = data
x = x[:,np.newaxis]
# Detrend signal
x = sci.detrend(x,axis=0)
npts = x.shape[0]
nfft = npts
if np.all(np.isreal(data)):
if (npts%2 == 0):
nf = round(nfft/2.) + 1
fvec_p = np.arange(0,nfft/2+1)/(nfft*dt)
fvec_n = np.arange(-(nfft/2),0)/(nfft*dt)
else:
nf = round((nfft+1)/2)
fvec_p = np.arange(0,(nfft-1)/2+1)/(nfft*dt)
fvec_n = np.arange(-(nfft-1)/2,0)/(nfft*dt)
# Create vector as in FFT sampling
# except with nyquist in positive freq
# (matlab and Python numpy.fft)
fvec = np.concatenate((fvec_p,fvec_n))
freq = np.zeros((nf,1))
spec = np.zeros((nf,1))
fdata = np.fft.fft(x,nfft,0)
spec = abs(fdata[0:nf])
freq = fvec[0:nf]
#print(npts, nfft, nf)
#print('freq ', freq)
return freq,spec
def amp_spec_taper(data,dt):
"""
Compute the power spectrum of a given signal
Uses numpy
Assumes data is a numpy array, column vector
Applies a hanning taper before FFT
"""
import scipy.signal as sci
import numpy as np
ndim = data.ndim
if ndim==1 :
x = data
x = x[:,np.newaxis]
# Detrend signal
x = sci.detrend(x,axis=0)
npts = x.shape[0]
hwin = np.hanning(npts)
hwin = hwin[:,np.newaxis]
nfft = npts
# Apply taper
x = x*hwin
if np.all(np.isreal(data)):
if (npts%2 == 0):
nf = round(nfft/2.) + 1
fvec_p = np.arange(0,nfft/2+1)/(nfft*dt)
fvec_n = np.arange(-(nfft/2),0)/(nfft*dt)
else:
nf = round((nfft+1)/2)
fvec_p = np.arange(0,(nfft-1)/2+1)/(nfft*dt)
fvec_n = np.arange(-(nfft-1)/2,0)/(nfft*dt)
# Create vector as in FFT sampling
# except with nyquist in positive freq
# (matlab and Python numpy.fft)
fvec = np.concatenate((fvec_p,fvec_n))
freq = np.zeros((nf,1))
spec = np.zeros((nf,1))
fdata = np.fft.fft(x,nfft,0)
spec = abs(fdata[0:nf])
freq = fvec[0:nf]
return freq,spec