-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_chirps.py
376 lines (304 loc) · 12.7 KB
/
make_chirps.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import numpy as np
import matplotlib.pyplot as plt
from utilities import *
from scipy.signal import stft, chirp, spectrogram
import itertools
from RANSAC import RANSAC_fit
from sklearn import linear_model
import json
from matplotlib import cm
def make_2slope_chirp(amp=1, mu=0, sigmas=[0]):
# Define parameters
T = 1e-4
fs = int(4800e6)
t_half = np.linspace(0, T/2, int((T/2)*fs))
t_full = np.linspace(0, T, int(T*fs))
# chirp
signal1 = amp * chirp(t_half, f0=1300e6, f1=1500e6, t1=(T / 2), method='linear')
signal2 = amp * chirp(t_half, f0=1500e6, f1=2300e6, t1=(T / 2), method='linear')
unified_signal = np.zeros(signal1.size + signal2.size)
unified_signal[:signal1.size] = signal1[:]
unified_signal[signal1.size:] = signal2[:]
# Initiate chirps dict
chirps = {'fs': [],
'T': [],
'linear': [],
'signal': [],
'snr': [],
'sigma': [],
'spec': []
}
for sigma in sigmas:
linear = [[[0, 1300e6], [T/2, 1500e6]], [[T/2, 1500e6], [T, 2300e6]]]
# Add noise
noise = np.random.normal(mu, sigma, unified_signal.shape)
noisy_signal = unified_signal + noise
# Calculate SNR
snr = np.around(calcSNR(unified_signal, noise), 2)
# Get stft
_, _, Zxx = stft(noisy_signal, fs=fs, nperseg=2048, noverlap=64)
# Append to dict
chirps['fs'].append(fs)
chirps['T'].append(T)
chirps['linear'].append(linear)
chirps['signal'].append(noisy_signal.tolist())
chirps['snr'].append(snr.tolist())
chirps['sigma'].append(sigma)
chirps['spec'].append(np.abs(Zxx).tolist())
return chirps
def make_chirps(amp=1, mu=0, sigmas=[0], second_chirp=False):
# Define parameters
T = [1e-4]
freqs = list(itertools.combinations([1300e6, 2300e6], 2))
combs = list(itertools.product(T, freqs))
# Initiate chirps dict
chirps = {'fs': [],
'T': [],
'linear': [],
'signal': [],
'snr': [],
'sigma': [],
'spec': []
}
for i, sigma in enumerate(sigmas):
for ((T), (f0, f1)) in combs:
# Define signal
fs = int(4800e6)
t = np.linspace(0, T, int(T*fs))
# Chirp
signal = amp*chirp(t, f0=f0, f1=f1, t1=T, method='linear')
# Linear Signal
linear = [[0, f0], [T, f1]]
# add another, fixed chirp to test hough
if second_chirp:
scnd_chirp = amp*chirp(t, f0=2000e6, f1=1500e6, t1=T, method='linear')
signal = signal + scnd_chirp
linear = [linear, [[0, 2000e6], [T, 1500e6]]]
# Add noise
noise = np.random.normal(mu, sigma, signal.shape)
noisy_signal = signal + noise
# Calculate SNR
snr = np.around(calcSNR(signal, noise), 2)
# Get stft
# _, _, Zxx = stft(noisy_signal, fs=fs, nperseg=2048, noverlap=64)
_, _, Zxx = stft(noisy_signal, fs=fs, nperseg=2048, noverlap=2048-64)
# Append to dict
chirps['fs'].append(fs)
chirps['T'].append(T)
chirps['linear'].append(linear)
chirps['signal'].append(noisy_signal.tolist())
chirps['snr'].append(snr.tolist())
chirps['sigma'].append(sigma)
chirps['spec'].append(np.abs(Zxx).tolist())
if (i+1) % 50 == 0:
print(f'Finished {i+1} samples...')
return chirps
def test_chirps(data, graph=False, plot_time_freq_curve=False, plot_only_predictions=False, plot_article_figures=False, plot_stft=False):
sample = np.random.randint(len(data['sigma']))
fs = data['fs'][sample]
T = data['T'][sample]
S = np.array(data['spec'][sample])
snr = np.array(data['snr'][sample])
linear = np.array(data['linear'][sample])
f_step, t_step = S.shape
# Build axes
t = np.linspace(0, T, t_step)
f = np.linspace(0, fs/2, f_step)
# Extract time frequency curve
X, y_no_med = extractTimeFrequencyCurve(S, fs, T)
y = medianFilter(y_no_med.copy(), N_med=99)
if plot_time_freq_curve:
plt.title("Time / Frequency curve, SNR: %1.2f [dB]" % snr)
plt.plot(X * 1e6, y_no_med * 1e-6, color='red', label='Peak frequency before Median filter')
plt.plot(X*1e6, y * 1e-6, color='blue', label='Peak frequency after Median filter')
plt.xlabel(r'$Time [\mu s]$')
plt.ylabel('Frequency [MHz]')
plt.legend()
plt.show()
# Our RANSAC - with median
line_X = np.linspace(X.min(), X.max(), num=200)[:, np.newaxis]
a, b = RANSAC_fit(X, y, n_iterations=5000, threshold=0.4e-4)
our_prediction = a*line_X + b
# Our RANSAC - without median
a_no_med, b_no_med = RANSAC_fit(X, y_no_med, n_iterations=5000, threshold=0.4e-4)
our_prediction_no_med = a_no_med*line_X + b_no_med
# Sklearn RANSAC
ransac = linear_model.RANSACRegressor()
ransac.fit(X, y)
inlier_mask = ransac.inlier_mask_
outlier_mask = np.logical_not(inlier_mask)
line_y_ransac = ransac.predict(line_X)
a_ransac = ransac.estimator_.coef_
b_ransac = ransac.estimator_.intercept_
# Sklearn Linear Regressor
lr = linear_model.LinearRegression()
reg = lr.fit(X, y)
line_y_lin_regres = lr.predict(line_X)
if graph:
# Plots
fig, axs = plt.subplots(2)
# Plot STFT
axs[0].set_title('STFT of noisy chirp')
axs[0].pcolormesh(t*1e6, f*1e-6, S, shading='gouraud')
axs[0].set(xlabel=r'$Time [\mu s]$', ylabel='Frequency [MHz]')
# Inlires & Outlires
axs[1].set_title('Linear models')
axs[1].scatter(X[inlier_mask]*1e6, y[inlier_mask]*1e-6,
color='yellowgreen', marker='.', label='Inliers')
axs[1].scatter(X[outlier_mask]*1e6, y[outlier_mask]
* 1e-6, color='gold', marker='.', label='Outliers')
# Our RANSAC - with median
axs[1].plot(line_X*1e6, our_prediction*1e-6,
color='green', linewidth=1, label='RANSAC')
# Our RANSAC - without median
axs[1].plot(line_X*1e6, our_prediction_no_med*1e-6,
color='blue', linewidth=1, label='RANSAC NO MEDIAN')
# # Sklearn RANSAC
# axs[1].plot(line_X*1e6, line_y_ransac*1e-6,
# color='cornflowerblue', linewidth=2, label='sklearn RANSAC')
# Sklearn Linear Regressor
axs[1].plot(line_X*1e6, line_y_lin_regres*1e-6, color='red',
linewidth=2, label='LSM')
# Real Linear Chirp
axs[1].plot(linear[:, 0]*1e6, linear[:, 1]*1e-6,
linewidth=1, label='Real Linear Chirp')
axs[1].set(xlabel=r'$Time [\mu s]$', ylabel='Frequency [MHz]')
axs[1].legend()
plt.tight_layout()
plt.show()
if plot_stft:
# Plot STFT
plt.title('STFT of noisy chirp')
plt.pcolormesh(t*1e6, f*1e-6, S, shading='gouraud')
plt.xlabel(r'$Time [\mu s]$')
plt.ylabel('Frequency [MHz]')
plt.savefig(f'{sample}.png')
if plot_article_figures:
fig = plt.figure()
# plot 3d STFT
ax = fig.add_subplot(111, projection='3d')
X_mesh, Z_mesh = np.meshgrid(t * 1e6, f * 1e-6)
ax.plot_surface(X_mesh, Z_mesh, S, cmap=cm.coolwarm)
ax.set(xlabel=r'$Time [\mu s]$', ylabel='Frequency [MHz]')
plt.tight_layout()
plt.show()
# plot STFT flat
fig = plt.figure()
ax = fig.add_subplot(111)
ax.pcolormesh(t * 1e6, f * 1e-6, S, shading='gouraud')
ax.set(xlabel=r'$Time [\mu s]$', ylabel='Frequency [MHz]')
plt.tight_layout()
plt.show()
# plot time frequency curve
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(X * 1e6, y_no_med * 1e-6, color='red', label='Peak frequency before Median filter')
ax.set(xlabel=r'$Time [\mu s]$', ylabel='Frequency [MHz]')
plt.ylim(0, 2500)
plt.xlim(0, 100)
plt.autoscale(False)
plt.tight_layout()
plt.show()
if plot_only_predictions:
# Inlires & Outlires
# plt.set_title('Linear models')
plt.scatter(X[inlier_mask]*1e6, y[inlier_mask]*1e-6,
color='yellowgreen', marker='.', label='Inliers')
plt.scatter(X[outlier_mask]*1e6, y[outlier_mask]*1e-6,
color='gold', marker='.', label='Outliers')
# Our RANSAC - with median
plt.plot(line_X*1e6, our_prediction*1e-6,
color='green', linewidth=1, label='RANSAC')
# Our RANSAC - without median
plt.plot(line_X*1e6, our_prediction_no_med*1e-6,
color='blue', linewidth=1, label='RANSAC NO MEDIAN')
# Sklearn Linear Regressor
plt.plot(line_X*1e6, line_y_lin_regres*1e-6, color='red',
linewidth=2, label='LSM')
# Real Linear Chirp
plt.plot(linear[:, 0]*1e6, linear[:, 1]*1e-6,
linewidth=1, label='Real Linear Chirp')
plt.xlabel(r'$Time [\mu s]$')
plt.ylabel('Frequency [MHz]')
plt.legend()
plt.tight_layout()
plt.show()
def chirp_cre_test():
n_sigmas = 15
cre_0_mean = np.zeros(n_sigmas)
cre_1_mean = np.zeros(n_sigmas)
cre_2_mean = np.zeros(n_sigmas)
for test in range(100):
sigmas = np.linspace(1, 20, n_sigmas)
data = make_chirps(sigmas=sigmas)
cres = {'lsm': [],
'ransac': [],
'ransac_no_median': []}
snrs = []
for sample in range(len(data['signal'])):
fs = data['fs'][sample]
T = [1e-4]
S = np.array(data['spec'][sample])
snr = np.array(data['snr'][sample])
linear = np.array(data['linear'][sample])
f_step, t_step = S.shape
# Build axes
t = np.linspace(0, T, t_step)
f = np.linspace(0, fs/2, f_step)
# Extract time frequency curve
X, y_no_med = extractTimeFrequencyCurve(S, fs, T)
y = medianFilter(y_no_med.copy(), N_med=99)
# Our RANSAC - with median
line_X = np.linspace(X.min(), X.max(), num=200)[:, np.newaxis]
a, b = RANSAC_fit(X, y, n_iterations=5000, threshold=0.4e-4)
our_prediction = a*line_X + b
# Our RANSAC - without median
a_no_med, b_no_med = RANSAC_fit(
X, y_no_med, n_iterations=5000, threshold=0.4e-4)
our_prediction_no_med = a_no_med*line_X + b_no_med
# Sklearn RANSAC
ransac = linear_model.RANSACRegressor()
ransac.fit(X, y)
inlier_mask = ransac.inlier_mask_
outlier_mask = np.logical_not(inlier_mask)
line_y_ransac = ransac.predict(line_X)
a_ransac = ransac.estimator_.coef_
b_ransac = ransac.estimator_.intercept_
# Sklearn Linear Regressor
lr = linear_model.LinearRegression()
reg = lr.fit(X, y)
line_y_lin_regres = lr.predict(line_X)
# calculate errors
chirpSlope, chirpIntercept = getSlopeAndInterceptFromPoints(
linear[0, 0], linear[0, 1], linear[1, 0], linear[1, 1])
cre_ransac = calcCRE(chirpSlope, chirpIntercept, a, b, 0, T)
cres['ransac'].append(cre_ransac)
cre_ransac_no_med = calcCRE(
chirpSlope, chirpIntercept, a_no_med, b_no_med, 0, T)
cres['ransac_no_median'].append(cre_ransac_no_med)
cre_lsm = calcCRE(chirpSlope, chirpIntercept,
reg.coef_, reg.intercept_, 0, T)
cres['lsm'].append(cre_lsm)
snrs.append(snr)
# print(
# f'SNR = {snr} [db] | CRE RANSAC = {cre_ransac} [%] | CRE RANSAC WITHOUT MEDIAN = {cre_ransac_no_med} [%] | CRE LSM = {cre_lsm} [%]')
if (test + 1) % 10 == 0:
print(f'Finished {test+1} tests...')
# Add cres
cre_0_mean += np.array(cres['ransac'])
cre_1_mean += np.array(cres['ransac_no_median'])
cre_2_mean += np.array(cres['lsm'])
cre_0_mean = cre_0_mean / (test+1)
cre_1_mean = cre_1_mean / (test+1)
cre_2_mean = cre_2_mean / (test+1)
plt.plot(snrs, cre_0_mean, 'g.', label='RANSAC')
plt.plot(snrs, cre_0_mean, 'g--')
plt.plot(snrs, cre_1_mean,
'b.', label='RANSAC NO MEDIAN')
plt.plot(snrs, cre_1_mean, 'b--')
plt.plot(snrs, cre_2_mean, 'r.', label='LSM')
plt.plot(snrs, cre_2_mean, 'r--')
plt.xlabel('SNR [db]')
plt.ylabel('CRE [%]')
plt.legend()
plt.show()