aweber commited on
Commit
72d88b2
·
verified ·
1 Parent(s): 124a5e5

Update tasks/utils/fourier.py

Browse files
Files changed (1) hide show
  1. tasks/utils/fourier.py +92 -170
tasks/utils/fourier.py CHANGED
@@ -1,170 +1,92 @@
1
- import numpy as np
2
- import plotly.express as px
3
- import scipy
4
- from sklearn.base import BaseEstimator
5
-
6
- ###################################
7
- ####### Signal Processing #########
8
- ###################################
9
-
10
- # Building a class Fourier for better use of Fourier Analysis.
11
-
12
-
13
- class Fourier:
14
- """
15
- Apply the Discrete Fourier Transform (DFT) on the signal using the Fast Fourier
16
- Transform (FFT) from the scipy package.
17
-
18
- Example:
19
- fourier = Fourier(signal, sampling_rate=2000.0)
20
- """
21
-
22
- def __init__(self, signal, sampling_rate):
23
- """
24
- Initialize the Fourier class.
25
-
26
- Args:
27
- signal (np.ndarray): The samples of the signal
28
- sampling_rate (float): The sampling per second of the signal
29
-
30
- Additional parameters,which are required to generate Fourier calculations, are
31
- calculated and defined to be initialized here too:
32
- time_step (float): 1.0/sampling_rate
33
- time_axis (np.ndarray): Generate the time axis from the duration and
34
- the time_step of the signal. The time axis is
35
- for better representation of the signal.
36
- duration (float): The duration of the signal in seconds.
37
- frequencies (numpy.ndarray): The frequency axis to generate the spectrum.
38
- fourier (numpy.ndarray): The DFT using rfft from the scipy package.
39
- """
40
- self.signal = signal
41
- self.sampling_rate = sampling_rate
42
- self.time_step = 1.0 / self.sampling_rate
43
- self.duration = len(self.signal) / self.sampling_rate
44
- self.time_axis = np.arange(0, self.duration, self.time_step)
45
- self.frequencies = scipy.fft.rfftfreq(len(self.signal), d=self.time_step)
46
- self.fourier = scipy.fft.rfft(self.signal)
47
-
48
- # Generate the actual amplitudes of the spectrum
49
- def amplitude(self):
50
- """
51
- Method of Fourier
52
-
53
- Returns:
54
- numpy.ndarray of the actual amplitudes of the sinusoids.
55
- """
56
- return 2 * np.abs(self.fourier) / len(self.signal)
57
-
58
- # Generate the phase information from the output of rfft
59
- def phase(self, degree=False):
60
- """
61
- Method of Fourier
62
-
63
- Args:
64
- degree: To choose the type of phase representation (Radian, Degree).
65
- By default, it's in radian.
66
-
67
- Returns:
68
- numpy.ndarray of the phase information of the Fourier output.
69
- """
70
- return np.angle(self.fourier, deg=degree)
71
-
72
- # Plot the Signal and the Spectrum interactively
73
- def plot_time(self, ylabel="Amplitude", title="Time Domain", line_color="#00FF00"):
74
- """
75
- Plot the Signal in Time Domain using plotly.
76
-
77
- Args:
78
- ylabel (String): Label of the y-axis in Time-Domain
79
- title (String): Title of the Time-Domain plot
80
- line_color (String): The color of the line chart (HTML Code)
81
-
82
- Returns:
83
- One figure: the time-domain.
84
- """
85
- # Time Domain
86
- self.fig = px.line(x=self.time_axis, y=self.signal)
87
- self.fig.update_layout(
88
- {
89
- "title": {
90
- "text": title,
91
- "font": {"size": 30, "family": "Times New Roman, bold"},
92
- "x": 0.5,
93
- "xanchor": "center",
94
- "yanchor": "top",
95
- },
96
- "xaxis": {"title": "Time [sec]"},
97
- "yaxis": {"title": ylabel},
98
- "hovermode": "x unified",
99
- }
100
- )
101
- self.fig.update_traces(
102
- line_color=line_color,
103
- line_width=1,
104
- hovertemplate="Time= %{x}<br>Amplitude= %{y}",
105
- )
106
- return self.fig
107
-
108
- def plot_frequency(
109
- self, ylabel="Amplitude", title="Frequency Domain", line_color="#FF0000"
110
- ):
111
- """
112
- Plot the Signal in Frequency Domain using plotly.
113
-
114
- Args:
115
- ylabel (String): Label of the y-axis in Frequency-Domain
116
- title (String): Title of the frequency-Domain plot
117
- line_color (String): The color of the line chart (HTML Code)
118
-
119
- Returns:
120
- One figure: the frequency-domain.
121
- """
122
- # Frequency Domain
123
- self.fig = px.line(x=self.frequencies, y=self.amplitude())
124
- self.fig.update_layout(
125
- {
126
- "title": {
127
- "text": title,
128
- "font": {"size": 30, "family": "Times New Roman, bold"},
129
- "x": 0.5,
130
- "xanchor": "center",
131
- "yanchor": "top",
132
- },
133
- "xaxis": {"title": "Frequency [Hz]"},
134
- "yaxis": {"title": ylabel},
135
- "hovermode": "x unified",
136
- }
137
- )
138
- self.fig.update_traces(
139
- line_color=line_color,
140
- line_width=1,
141
- hovertemplate="Time= %{x}<br>Amplitude= %{y}",
142
- )
143
- return self.fig
144
-
145
-
146
- # define the transformer
147
- class FourierPreprocessor(BaseEstimator):
148
- def __init__(self, sampling_rate=12000, len_sig=36000):
149
- print("Initialising transformer...")
150
- self.sampling_rate = sampling_rate
151
- self.len_sig = len_sig
152
-
153
- def fit(self, X, y=None):
154
- return self
155
-
156
- def transform(self, X):
157
- transformed_X = []
158
- for sig in X:
159
- try:
160
- if len(sig) != self.len_sig:
161
- sig = scipy.signal.resample(sig, self.len_sig)
162
- # Convert signal to frequency domain
163
- fourier = np.array(
164
- Fourier(signal=sig, sampling_rate=self.sampling_rate).amplitude()
165
- )
166
- except Exception as e:
167
- print(e)
168
- fourier = np.zeros(shape=(18001,))
169
- transformed_X.append(fourier)
170
- return np.array(transformed_X)
 
1
+ import numpy as np
2
+ import scipy
3
+ from sklearn.base import BaseEstimator
4
+
5
+ # Building a class Fourier for better use of Fourier Analysis.
6
+
7
+ class Fourier:
8
+ """
9
+ Apply the Discrete Fourier Transform (DFT) on the signal using the Fast Fourier
10
+ Transform (FFT) from the scipy package.
11
+
12
+ Example:
13
+ fourier = Fourier(signal, sampling_rate=2000.0)
14
+ """
15
+
16
+ def __init__(self, signal, sampling_rate):
17
+ """
18
+ Initialize the Fourier class.
19
+
20
+ Args:
21
+ signal (np.ndarray): The samples of the signal
22
+ sampling_rate (float): The sampling per second of the signal
23
+
24
+ Additional parameters,which are required to generate Fourier calculations, are
25
+ calculated and defined to be initialized here too:
26
+ time_step (float): 1.0/sampling_rate
27
+ time_axis (np.ndarray): Generate the time axis from the duration and
28
+ the time_step of the signal. The time axis is
29
+ for better representation of the signal.
30
+ duration (float): The duration of the signal in seconds.
31
+ frequencies (numpy.ndarray): The frequency axis to generate the spectrum.
32
+ fourier (numpy.ndarray): The DFT using rfft from the scipy package.
33
+ """
34
+ self.signal = signal
35
+ self.sampling_rate = sampling_rate
36
+ self.time_step = 1.0 / self.sampling_rate
37
+ self.duration = len(self.signal) / self.sampling_rate
38
+ self.time_axis = np.arange(0, self.duration, self.time_step)
39
+ self.frequencies = scipy.fft.rfftfreq(len(self.signal), d=self.time_step)
40
+ self.fourier = scipy.fft.rfft(self.signal)
41
+
42
+ # Generate the actual amplitudes of the spectrum
43
+ def amplitude(self):
44
+ """
45
+ Method of Fourier
46
+
47
+ Returns:
48
+ numpy.ndarray of the actual amplitudes of the sinusoids.
49
+ """
50
+ return 2 * np.abs(self.fourier) / len(self.signal)
51
+
52
+ # Generate the phase information from the output of rfft
53
+ def phase(self, degree=False):
54
+ """
55
+ Method of Fourier
56
+
57
+ Args:
58
+ degree: To choose the type of phase representation (Radian, Degree).
59
+ By default, it's in radian.
60
+
61
+ Returns:
62
+ numpy.ndarray of the phase information of the Fourier output.
63
+ """
64
+ return np.angle(self.fourier, deg=degree)
65
+
66
+
67
+
68
+ # define the transformer
69
+ class FourierPreprocessor(BaseEstimator):
70
+ def __init__(self, sampling_rate=12000, len_sig=36000):
71
+ print("Initialising transformer...")
72
+ self.sampling_rate = sampling_rate
73
+ self.len_sig = len_sig
74
+
75
+ def fit(self, X, y=None):
76
+ return self
77
+
78
+ def transform(self, X):
79
+ transformed_X = []
80
+ for sig in X:
81
+ try:
82
+ if len(sig) != self.len_sig:
83
+ sig = scipy.signal.resample(sig, self.len_sig)
84
+ # Convert signal to frequency domain
85
+ fourier = np.array(
86
+ Fourier(signal=sig, sampling_rate=self.sampling_rate).amplitude()
87
+ )
88
+ except Exception as e:
89
+ print(e)
90
+ fourier = np.zeros(shape=(18001,))
91
+ transformed_X.append(fourier)
92
+ return np.array(transformed_X)