end_to_end.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import math
  2. import tensorflow as tf
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from sklearn.metrics import accuracy_score
  6. from sklearn.preprocessing import OneHotEncoder
  7. from tensorflow.keras import layers, losses
  8. from models.custom_layers import ExtractCentralMessage, OpticalChannel, DigitizationLayer, BitsToSymbols, SymbolsToBits
  9. class EndToEndAutoencoder(tf.keras.Model):
  10. def __init__(self,
  11. cardinality,
  12. samples_per_symbol,
  13. messages_per_block,
  14. channel,
  15. custom_loss_fn=False):
  16. """
  17. The autoencoder that aims to find a encoding of the input messages. It should be noted that a "block" consists
  18. of multiple "messages" to introduce memory into the simulation as this is essential for modelling inter-symbol
  19. interference. The autoencoder architecture was heavily influenced by IEEE 8433895.
  20. :param cardinality: Number of different messages. Chosen such that each message encodes log_2(cardinality) bits
  21. :param samples_per_symbol: Number of samples per transmitted symbol
  22. :param messages_per_block: Total number of messages in transmission block
  23. :param channel: Channel Layer object. Must be a subclass of keras.layers.Layer with an implemented forward pass
  24. """
  25. super(EndToEndAutoencoder, self).__init__()
  26. # Labelled M in paper
  27. self.cardinality = cardinality
  28. self.bits_per_symbol = int(math.log(self.cardinality, 2))
  29. # Labelled n in paper
  30. self.samples_per_symbol = samples_per_symbol
  31. # Labelled N in paper - conditional +=1 to ensure odd value
  32. if messages_per_block % 2 == 0:
  33. messages_per_block += 1
  34. self.messages_per_block = messages_per_block
  35. # Channel Model Layer
  36. if isinstance(channel, layers.Layer):
  37. self.channel = tf.keras.Sequential([
  38. layers.Flatten(),
  39. channel,
  40. ExtractCentralMessage(self.messages_per_block, self.samples_per_symbol)
  41. ], name="channel_model")
  42. else:
  43. raise TypeError("Channel must be a subclass of \"tensorflow.keras.layers.layer\"!")
  44. # Boolean identifying if bit mapping is to be learnt
  45. self.custom_loss_fn = custom_loss_fn
  46. # other parameters/metrics
  47. self.symbol_error_rate = None
  48. self.bit_error_rate = None
  49. self.snr = 20 * math.log(0.5 / channel.rx_stddev, 10)
  50. # Model Hyper-parameters
  51. leaky_relu_alpha = 0
  52. relu_clip_val = 1.0
  53. # layer configuration
  54. encoding_layers = [
  55. layers.Input(shape=(self.messages_per_block, self.cardinality)),
  56. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  57. layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  58. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  59. layers.TimeDistributed(layers.LeakyReLU(alpha=leaky_relu_alpha)),
  60. layers.TimeDistributed(layers.Dense(self.samples_per_symbol, activation='sigmoid')),
  61. # layers.TimeDistributed(layers.Dense(self.samples_per_symbol)),
  62. # layers.TimeDistributed(layers.ReLU(max_value=relu_clip_val))
  63. ]
  64. decoding_layers = [
  65. layers.Dense(2 * self.cardinality),
  66. layers.LeakyReLU(alpha=leaky_relu_alpha),
  67. layers.Dense(2 * self.cardinality),
  68. layers.LeakyReLU(alpha=leaky_relu_alpha),
  69. layers.Dense(self.cardinality, activation='softmax')
  70. ]
  71. # Encoding Neural Network
  72. self.encoder = tf.keras.Sequential([
  73. *encoding_layers
  74. ], name="encoding_model")
  75. # Decoding Neural Network
  76. self.decoder = tf.keras.Sequential([
  77. *decoding_layers
  78. ], name="decoding_model")
  79. def cost(self, y_true, y_pred):
  80. symbol_cost = losses.CategoricalCrossentropy()(y_true, y_pred)
  81. y_bits_true = SymbolsToBits(self.cardinality)(y_true)
  82. y_bits_pred = SymbolsToBits(self.cardinality)(y_pred)
  83. bit_cost = losses.BinaryCrossentropy()(y_bits_true, y_bits_pred)
  84. a = 1
  85. return symbol_cost + a * bit_cost
  86. def generate_random_inputs(self, num_of_blocks, return_vals=False):
  87. """
  88. A method that generates a list of one-hot encoded messages. This is utilized for generating the test/train data.
  89. :param num_of_blocks: Number of blocks to generate. A block contains multiple messages to be transmitted in
  90. consecutively to model ISI. The central message in a block is returned as the label for training.
  91. :param return_vals: If true, the raw decimal values of the input sequence will be returned
  92. """
  93. cat = [np.arange(self.cardinality)]
  94. enc = OneHotEncoder(handle_unknown='ignore', sparse=False, categories=cat)
  95. mid_idx = int((self.messages_per_block - 1) / 2)
  96. rand_int = np.random.randint(self.cardinality, size=(num_of_blocks * self.messages_per_block, 1))
  97. out = enc.fit_transform(rand_int)
  98. out_arr = np.reshape(out, (num_of_blocks, self.messages_per_block, self.cardinality))
  99. if return_vals:
  100. out_val = np.reshape(rand_int, (num_of_blocks, self.messages_per_block, 1))
  101. return out_val, out_arr, out_arr[:, mid_idx, :]
  102. return out_arr, out_arr[:, mid_idx, :]
  103. def train(self, num_of_blocks=1e6, epochs=1, batch_size=None, train_size=0.8, lr=1e-3):
  104. """
  105. Method to train the autoencoder. Further configuration to the loss function, optimizer etc. can be made in here.
  106. :param num_of_blocks: Number of blocks to generate for training. Analogous to the dataset size.
  107. :param batch_size: Number of samples to consider on each update iteration of the optimization algorithm
  108. :param train_size: Float less than 1 representing the proportion of the dataset to use for training
  109. :param lr: The learning rate of the optimizer. Defines how quickly the algorithm converges
  110. """
  111. X_train, y_train = self.generate_random_inputs(int(num_of_blocks * train_size))
  112. X_test, y_test = self.generate_random_inputs(int(num_of_blocks * (1 - train_size)))
  113. opt = tf.keras.optimizers.Adam(learning_rate=lr)
  114. if self.custom_loss_fn:
  115. loss_fn = self.cost
  116. else:
  117. loss_fn = losses.CategoricalCrossentropy()
  118. self.compile(optimizer=opt,
  119. loss=loss_fn,
  120. metrics=['accuracy'],
  121. loss_weights=None,
  122. weighted_metrics=None,
  123. run_eagerly=False
  124. )
  125. self.fit(x=X_train,
  126. y=y_train,
  127. batch_size=batch_size,
  128. epochs=epochs,
  129. shuffle=True,
  130. validation_data=(X_test, y_test)
  131. )
  132. def test(self, num_of_blocks=1e4, length_plot=False, plt_show=True):
  133. X_test, y_test = self.generate_random_inputs(int(num_of_blocks))
  134. y_out = self.call(X_test)
  135. y_pred = tf.argmax(y_out, axis=1)
  136. y_true = tf.argmax(y_test, axis=1)
  137. self.symbol_error_rate = 1 - accuracy_score(y_true, y_pred)
  138. bits_pred = SymbolsToBits(self.cardinality)(tf.one_hot(y_pred, self.cardinality)).numpy().flatten()
  139. bits_true = SymbolsToBits(self.cardinality)(y_test).numpy().flatten()
  140. self.bit_error_rate = 1 - accuracy_score(bits_true, bits_pred)
  141. if (length_plot):
  142. lengths = np.linspace(0, 70, 50)
  143. ber_l = []
  144. for l in lengths:
  145. tx_channel = OpticalChannel(fs=self.channel.layers[1].fs,
  146. num_of_samples=self.channel.layers[1].num_of_samples,
  147. dispersion_factor=self.channel.layers[1].dispersion_factor,
  148. fiber_length=l,
  149. lpf_cutoff=self.channel.layers[1].lpf_cutoff,
  150. rx_stddev=self.channel.layers[1].rx_stddev,
  151. sig_avg=self.channel.layers[1].sig_avg,
  152. enob=self.channel.layers[1].enob)
  153. test_channel = tf.keras.Sequential([
  154. layers.Flatten(),
  155. tx_channel,
  156. ExtractCentralMessage(self.messages_per_block, self.samples_per_symbol)
  157. ], name="test channel (variable length)")
  158. X_test_l, y_test_l = self.generate_random_inputs(int(num_of_blocks))
  159. y_out_l = self.decoder(test_channel(self.encoder(X_test_l)))
  160. y_pred_l = tf.argmax(y_out_l, axis=1)
  161. # y_true_l = tf.argmax(y_test_l, axis=1)
  162. bits_pred_l = SymbolsToBits(self.cardinality)(tf.one_hot(y_pred_l, self.cardinality)).numpy().flatten()
  163. bits_true_l = SymbolsToBits(self.cardinality)(y_test_l).numpy().flatten()
  164. bit_error_rate_l = 1 - accuracy_score(bits_true_l, bits_pred_l)
  165. ber_l.append(bit_error_rate_l)
  166. plt.plot(lengths, ber_l)
  167. plt.yscale('log')
  168. if plt_show:
  169. plt.show()
  170. print("SYMBOL ERROR RATE: {}".format(self.symbol_error_rate))
  171. print("BIT ERROR RATE: {}".format(self.bit_error_rate))
  172. pass
  173. def view_encoder(self):
  174. '''
  175. A method that views the learnt encoder for each distint message. This is displayed as a plot with a subplot for
  176. each message/symbol.
  177. '''
  178. mid_idx = int((self.messages_per_block - 1) / 2)
  179. # Generate inputs for encoder
  180. messages = np.zeros((self.cardinality, self.messages_per_block, self.cardinality))
  181. idx = 0
  182. for msg in messages:
  183. msg[mid_idx, idx] = 1
  184. idx += 1
  185. # Pass input through encoder and select middle messages
  186. encoded = self.encoder(messages)
  187. enc_messages = encoded[:, mid_idx, :]
  188. # Compute subplot grid layout
  189. i = 0
  190. while 2 ** i < self.cardinality ** 0.5:
  191. i += 1
  192. num_x = int(2 ** i)
  193. num_y = int(self.cardinality / num_x)
  194. # Plot all symbols
  195. fig, axs = plt.subplots(num_y, num_x, figsize=(2.5 * num_x, 2 * num_y))
  196. t = np.arange(self.samples_per_symbol)
  197. if isinstance(self.channel.layers[1], OpticalChannel):
  198. t = t / self.channel.layers[1].fs
  199. sym_idx = 0
  200. for y in range(num_y):
  201. for x in range(num_x):
  202. axs[y, x].plot(t, enc_messages[sym_idx].numpy().flatten(), 'x')
  203. axs[y, x].set_title('Symbol {}'.format(str(sym_idx)))
  204. sym_idx += 1
  205. for ax in axs.flat:
  206. ax.set(xlabel='Time', ylabel='Amplitude', ylim=(0, 1))
  207. for ax in axs.flat:
  208. ax.label_outer()
  209. plt.show()
  210. pass
  211. def view_sample_block(self):
  212. '''
  213. Generates a random string of input message and encodes them. In addition to this, the output is passed through
  214. digitization layer without any quantization noise for the low pass filtering.
  215. '''
  216. # Generate a random block of messages
  217. val, inp, _ = self.generate_random_inputs(num_of_blocks=1, return_vals=True)
  218. # Encode and flatten the messages
  219. enc = self.encoder(inp)
  220. flat_enc = layers.Flatten()(enc)
  221. chan_out = self.channel.layers[1](flat_enc)
  222. # Instantiate LPF layer
  223. lpf = DigitizationLayer(fs=self.channel.layers[1].fs,
  224. num_of_samples=self.messages_per_block * self.samples_per_symbol,
  225. sig_avg=0)
  226. # Apply LPF
  227. lpf_out = lpf(flat_enc)
  228. # Time axis
  229. t = np.arange(self.messages_per_block * self.samples_per_symbol)
  230. if isinstance(self.channel.layers[1], OpticalChannel):
  231. t = t / self.channel.layers[1].fs
  232. # Plot the concatenated symbols before and after LPF
  233. plt.figure(figsize=(2 * self.messages_per_block, 6))
  234. for i in range(1, self.messages_per_block):
  235. plt.axvline(x=t[i * self.samples_per_symbol], color='black')
  236. plt.plot(t, flat_enc.numpy().T, 'x')
  237. plt.plot(t, lpf_out.numpy().T)
  238. plt.plot(t, chan_out.numpy().flatten())
  239. plt.ylim((0, 1))
  240. plt.xlim((t.min(), t.max()))
  241. plt.title(str(val[0, :, 0]))
  242. plt.show()
  243. pass
  244. def call(self, inputs, training=None, mask=None):
  245. tx = self.encoder(inputs)
  246. rx = self.channel(tx)
  247. outputs = self.decoder(rx)
  248. return outputs
  249. SAMPLING_FREQUENCY = 336e9
  250. CARDINALITY = 32
  251. SAMPLES_PER_SYMBOL = 32
  252. MESSAGES_PER_BLOCK = 9
  253. DISPERSION_FACTOR = -21.7 * 1e-24
  254. FIBER_LENGTH = 50
  255. FIBER_LENGTH_STDDEV = 5
  256. if __name__ == '__main__':
  257. stddevs = [0, 1, 5, 10]
  258. legend = []
  259. for s in stddevs:
  260. optical_channel = OpticalChannel(fs=SAMPLING_FREQUENCY,
  261. num_of_samples=MESSAGES_PER_BLOCK * SAMPLES_PER_SYMBOL,
  262. dispersion_factor=DISPERSION_FACTOR,
  263. fiber_length=FIBER_LENGTH,
  264. fiber_length_stddev=s,
  265. lpf_cutoff=32e9,
  266. rx_stddev=0.01,
  267. sig_avg=0.5,
  268. enob=10)
  269. ae_model = EndToEndAutoencoder(cardinality=CARDINALITY,
  270. samples_per_symbol=SAMPLES_PER_SYMBOL,
  271. messages_per_block=MESSAGES_PER_BLOCK,
  272. channel=optical_channel,
  273. custom_loss_fn=True)
  274. print(ae_model.snr)
  275. ae_model.train(num_of_blocks=3e5, epochs=5)
  276. ae_model.test(length_plot=True, plt_show=False)
  277. # plt.legend(['{} +/- {}'.format(FIBER_LENGTH, s)])
  278. legend.append('{} +/- {}'.format(FIBER_LENGTH, s))
  279. plt.legend(legend)
  280. plt.show()
  281. plt.savefig('ber_vs_length.eps', format='eps')
  282. # ae_model.view_encoder()
  283. # ae_model.view_sample_block()
  284. # # ae_model.summary()
  285. # ae_model.encoder.summary()
  286. # ae_model.channel.summary()
  287. # ae_model.decoder.summary()
  288. pass