-
Notifications
You must be signed in to change notification settings - Fork 0
/
ai_ber.py
287 lines (249 loc) · 9.65 KB
/
ai_ber.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
"""
AI based RX models BER plots
Model ID format:
YYYYMMDDvHHmm # Format Codes '%y%m%dv%H%M'
e.g. '20240426v1241'
Model file path format:
'models/{modulation}/{model_fid}/model.keras'.format(modulation=IQ, model_fid=model_fid)
e.g. ./models/bpsk/gru_temel/240514v1217/model.keras
BER running identification format:
run_id
monDDHHmm # Format datetime.now().strftime("%b%d%H%M")
e.g. may131105
status : not-working
v0.1.1 >
last update : (16 May 2024, 21:32)
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import datetime
from constants import FS, G_DELAY, snr_to_nos, dict_h, BERtau1, gbKSE, BCJR, TRBER, SSSgbKSE
from rx_config import init_gpu
from rx_utils import prep_ts_data
from ber_util import gen_data, add_awgn, bit_checker
from keras.api.saving import load_model
from utils import TicTocGenerator, tic, toc, check_path_base
# initialize GPU, to avoid to waste gpu memory
init_gpu()
# Modulation Type
IQ = 'bpsk' # bpsk qpsk # noqa
# Select the model to run
# model_fid = 'gru_temel/240514v1217'
name_and_model_fid = 'gru_temel/240514v1217' # model full id # TODO or? add 'best', 'latest' options as suffix
# do not edit
try:
model_name, model_fid = name_and_model_fid.split('/')
except ValueError:
assert 0, 'invalid name_and_model_fid variable, e.g. model_name/model_id'
BASELINE = False # baseline via hard decision on rx data (rx > 0) ? 1 : 0;
NO_TAU = False # "False": Use TAU parameter, "True": disable TAU effect (have to be the same as TAU = 1)
# TAU Value
TAU = [0.6, 0.7, 0.8] # [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
# SNR Level
SNR = [i for i in range(14 + 1)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 'NoNoise']
# Length of Neighborhood (LoN)
# number of consecutive sample considered during calculation, min 2
LoN = 4 # e.g. LoN=3; [. . . S . . .], total 7 sample
# TODO remove before run
snr_to_nos = {k: int(v/1000) for k, v in snr_to_nos.items()} # DEV ONLY
path = 'models/{modulation}/{name_and_model_fid}/model.keras'.format(
modulation=IQ,
name_and_model_fid=name_and_model_fid)
model_conf =
check_path_base(path)
model = load_model(filepath=path,
custom_objects=None, compile=True, safe_mode=True)
# model specific configurations
pre_process = True # 'None' TODO update automatically based on model parameters, read from the model config file
# run id
run_id = datetime.now().strftime("%b%d%H%M")
rid = '{model}_{id}_run{run}'.format(model=model.name, id=model_fid, run=run_id)
batch_size = 256
# flow configurations
initial_seed = 2346
noise_seed = 54764 # constant for all cases
init_nos = int(1e+2) # number of symbol to generate, send, and decode at each turn
#
# one time process, and constants (to optimize the process, get these out of the for loop)
#
# generate the filter
# sPSF = get_h(fs=FS, g_delay=G_DELAY) # TODO implement dynamic h composition
# TODO support for variable sampling frequency, FS
assert FS == 10, "Only FS=10 supported, current implementation does not support 'FS: {fs}'".format(fs=FS)
# G_DELAY FS based h generation
hPSF = np.array(dict_h[G_DELAY]).astype(np.float16)
assert np.array_equal(hPSF, hPSF[::-1]), 'symmetry mismatch!'
tt1 = TicTocGenerator() # create an instance of the TicTocGen generator
for tau in TAU:
# t, elapsed = time.time() - t
# t = time.time() # tic
tic(tt1)
step = int(tau * FS)
print("New turn for TAU:{tau:.2f}".format(tau=tau))
result = dict({'SNR': [], 'NoE': [], 'NoB': [], 'BER': []})
#
# LOOP to BER
#
for _i_, snr in enumerate(SNR):
nos = snr_to_nos.get(snr, 4000000)
# set seed value for random data
turn_seed = initial_seed + _i_
#
# [SOURCE] Data Generation, Message
#
data, bits = gen_data(n=nos, mod=IQ, seed=43523) # IQ options: ('bpsk', 'qpsk')
#
# TX side
#
if NO_TAU: # disable TAU effect
tx_data = data
else:
#
# [TX] up-sample
# extend the data by up sampling (in order to be able to apply FTN)
s_up_sampled = np.zeros(step * len(data), dtype=np.float16)
s_up_sampled[::step] = data
#
# [TX] apply FTN (tau)
# apply the filter
tx_data = np.convolve(hPSF, s_up_sampled)
#
# [CHANNEL] add AWGN noise (snr)
# Channel Modelling, add noise
rch = add_awgn(inputs=tx_data, snr=snr, seed=1234)
#
# RX side
#
if NO_TAU:
rx_data = rch
else:
#
# [RX] apply matched filter
mf = np.convolve(hPSF, rch)
#
# [RX] down-sample (subsample)
# p_loc = 2 * G_DELAY * FS # 81 for g_delay=4 and FS = 10,
# 4*10=40 from first conv@TX, and +40 from last conv@RX
# remove additional prefix and suffix symbols due to CONV
rx_data = mf[2 * G_DELAY * FS:-(2 * G_DELAY * FS):step]
# [DEBUG]
# plt.plot(np.real(mf[:250]))
# plt.plot(np.imag(mf[:250]))
# plt.plot(np.real(rx_data[:250]))
# single to time series data
if pre_process:
if 'lstm' in model.name or 'gru' in model.name:
X = prep_ts_data(rx_data, lon=LoN)
else:
raise NotImplementedError
else:
X = rx_data
# X, y = get_song_data_ber(X_i, y_i, L=L, m=m)
# [DEBUG] data check point
#
# import pandas as pd
# cpn = 100
# df = pd.DataFrame()
# df['bits'] = bits[:cpn] # message bits
# df['tx'] = tx_data[G_DELAY*FS:(G_DELAY*FS+cpn*step):step] # TX output to channel
# df['rCH'] = rch[G_DELAY*FS:(G_DELAY*FS+cpn*step):step] # channel effect (AWGN) added
# df['mf'] = mf[p_loc:(p_loc+cpn*step):step] # match filter applied to RAW RX data
# df['rx_data'] = pd.DataFrame(rx_data[:cpn]) # down sampled RX after match filer
#
# df.plot()
if BASELINE:
y_hat = (X > 0) * 1
y_hat = np.reshape(y_hat, -1)
else:
y_pred = model.predict(X, batch_size=batch_size) # noqa
# y_pred = model.predict_on_batch(X) # noqa
if IQ == 'bpsk':
# hard desicion on the predictions
y_pred_bit = (y_pred > 0.5) * 1
else:
y_pred_bit = "" # TODO missing implementation
y_hat = np.reshape(y_pred_bit, -1)
# debug
# plt.figure()
# plt.plot(bits[:40])
# plt.plot(y_hat[:40])
# plt.legend(['bits', 'predictions'])
# plt.show()
noe, nob = bit_checker(bits, y_hat)
tBER = noe / nob
# save data into the result dictionary
result['SNR'].append(snr)
result['NoE'].append(noe)
result['NoB'].append(nob)
result['BER'].append(tBER)
# print("BER for given turn:\t{bit} bits\t{err} error\tBER: {ber}".format(bit=nob, err=noe, ber=tBER))
print("{snr} dB SNR,\t{bit} bits\t{err} error\tBER: {ber}".format(snr=snr, bit=nob, err=noe, ber=tBER))
if noe == 0:
break
td = toc(tt1)
print("time elapsed\t{td:.3f} seconds".format(td=td))
# DEBUG
# SNR : 100 dB, TAU = 1
# BER for given turn: 1000000 bits 136276 error BER: 0.136276
# SNR : 10 dB, TAU = 1
# BER for given turn: 1000000 bits 143702 error BER: 0.143702
# SNR : 10 dB, TAU = 0.8
# BER for given turn: 1000000 bits 144115 error BER: 0.144115
df = pd.DataFrame.from_dict(result)
# set save path for current run
ber_result_path = 'ber/{modulation}/{model}/{model_id}/'.format(
modulation=IQ,
model=model.name,
model_id=model_fid)
# TODO add model id (train info)
check_path_base(ber_result_path)
df.to_csv(ber_result_path + 'ber_results.csv', index=False)
print(df['BER'].values)
# pd.read_csv('ref_ber/no_ftn.csv')
drf0 = pd.DataFrame.from_dict(TRBER)
# drf1 = pd.DataFrame.from_dict(ref_ber_bpsk)
drf1 = pd.DataFrame.from_dict(SSSgbKSE)
drf2 = pd.DataFrame.from_dict(BCJR)
drf3 = pd.DataFrame.from_dict(gbKSE)
drf4 = pd.DataFrame.from_dict(BERtau1)
# combine the results
# df_comp = df[['SNR', 'BER']]
# df_comp = df_comp.rename(columns={'BER': 'DUT_tau_{tau:.2f}'.format(tau=TAU)})
# df_comp = df_comp.merge(drf0, on='SNR', how='outer')
# df_comp = drf0
# df_comp = df_comp.merge(drf1, on='SNR', how='outer')
# df_comp = df_comp.merge(drf2, on='SNR', how='outer')
# df_comp = df_comp.merge(drf3, on='SNR', how='outer')
# df_comp = df_comp.merge(drf4, on='SNR', how='outer')
# sort by SNR
# df_comp = df_comp.sort_values(by='SNR')
fig, ax = plt.subplots()
# df_comp.plot(ax=ax, x="SNR", logy=True, marker='d')
drf0.plot(ax=ax, x="SNR", logy=True, marker='v')
drf1.plot(ax=ax, x="SNR", logy=True, marker='o', linestyle='dashdot')
drf2.plot(ax=ax, x="SNR", logy=True, marker='X', linestyle='dotted')
drf3.plot(ax=ax, x="SNR", logy=True, marker='d', linestyle='dashed')
# drf4.plot(ax=ax, x="SNR", logy=True, marker='*', linestyle='dashdot')
plt.title('GRU based FTN Detector')
plt.xlabel('Eb/No[dB], SNR')
plt.ylabel('BER')
plt.xlim([0, 11])
plt.grid(visible=True, which='both')
plt.show()
# references and resources and more
#
# up sampling, https://stackoverflow.com/a/25858023
# TODO add organize debug tools and prepare reference data for BER plots
# import pandas as pd
#
# df_ref = pd.DataFrame(columns=['SNR', 'BER'])
# ref_snr = []
# ref_ber = []
# for snr, ber in ref_ber_bpsk.items():
# ref_snr.append(snr)
# ref_ber.append(ber)
# df_ref['SNR'] = pd.DataFrame(ref_snr)
# df_ref['BER'] = pd.DataFrame(ref_ber)
#
# df_ref.plot(ax=ax, x="SNR", y="BER", logy=True, marker='d')