end_to_end.py 14 KB

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