end_to_end.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import math
  2. import tensorflow as tf
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from sklearn.preprocessing import OneHotEncoder
  6. from tensorflow.keras import layers, losses
  7. from tensorflow.keras import backend as K
  8. from models.custom_layers import ExtractCentralMessage, OpticalChannel, DigitizationLayer, BitsToSymbols
  9. import itertools
  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. # Layer configuration for the case when bit mapping is to be learnt
  48. if self.bit_mapping:
  49. encoding_layers = [
  50. layers.Input(shape=(self.messages_per_block, self.bits_per_symbol)),
  51. BitsToSymbols(self.cardinality),
  52. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  53. layers.TimeDistributed(layers.LeakyReLU(alpha=0.01)),
  54. # layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  55. # layers.TimeDistributed(layers.LeakyReLU(alpha=0.01)),
  56. # layers.TimeDistributed(layers.Dense(self.samples_per_symbol, activation='sigmoid')),
  57. layers.TimeDistributed(layers.Dense(self.samples_per_symbol)),
  58. layers.TimeDistributed(layers.ReLU(max_value=1.0))
  59. ]
  60. decoding_layers = [
  61. layers.Dense(2 * self.cardinality),
  62. layers.LeakyReLU(alpha=0.01),
  63. # layers.Dense(2 * self.cardinality),
  64. # layers.LeakyReLU(alpha=0.01),
  65. layers.Dense(self.cardinality),
  66. layers.LeakyReLU(alpha=0.01),
  67. layers.Dense(self.bits_per_symbol, activation='sigmoid'),
  68. ]
  69. # layer configuration for the case when only symbol mapping is to be learnt
  70. else:
  71. encoding_layers = [
  72. layers.Input(shape=(self.messages_per_block, self.cardinality)),
  73. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  74. layers.TimeDistributed(layers.LeakyReLU(alpha=0.01)),
  75. layers.TimeDistributed(layers.Dense(2 * self.cardinality)),
  76. layers.TimeDistributed(layers.LeakyReLU(alpha=0.01)),
  77. # layers.TimeDistributed(layers.Dense(self.samples_per_symbol, activation='sigmoid')),
  78. layers.TimeDistributed(layers.Dense(self.samples_per_symbol)),
  79. layers.TimeDistributed(layers.ReLU(max_value=1.0))
  80. ]
  81. decoding_layers = [
  82. layers.Dense(2 * self.cardinality),
  83. layers.LeakyReLU(alpha=0.01),
  84. layers.Dense(2 * self.cardinality),
  85. layers.LeakyReLU(alpha=0.01),
  86. layers.Dense(self.cardinality),
  87. layers.LeakyReLU(alpha=0.01),
  88. layers.Dense(self.bits_per_symbol, activation='sigmoid'),
  89. ]
  90. # Encoding Neural Network
  91. self.encoder = tf.keras.Sequential([
  92. *encoding_layers
  93. ], name="encoding_model")
  94. # Decoding Neural Network
  95. self.decoder = tf.keras.Sequential([
  96. *decoding_layers
  97. ], name="decoding_model")
  98. def generate_random_inputs(self, num_of_blocks, return_vals=False):
  99. """
  100. A method that generates a list of one-hot encoded messages. This is utilized for generating the test/train data.
  101. :param num_of_blocks: Number of blocks to generate. A block contains multiple messages to be transmitted in
  102. consecutively to model ISI. The central message in a block is returned as the label for training.
  103. :param return_vals: If true, the raw decimal values of the input sequence will be returned
  104. """
  105. cat = [np.arange(self.cardinality)]
  106. enc = OneHotEncoder(handle_unknown='ignore', sparse=False, categories=cat)
  107. mid_idx = int((self.messages_per_block - 1) / 2)
  108. if self.bit_mapping:
  109. rand_int = np.random.randint(2, size=(num_of_blocks * self.messages_per_block * self.bits_per_symbol, 1))
  110. out = rand_int
  111. out_arr = np.reshape(out, (num_of_blocks, self.messages_per_block, self.bits_per_symbol))
  112. if return_vals:
  113. #TODO
  114. else:
  115. rand_int = np.random.randint(self.cardinality, size=(num_of_blocks * self.messages_per_block, 1))
  116. out = enc.fit_transform(rand_int)
  117. out_arr = np.reshape(out, (num_of_blocks, self.messages_per_block, self.cardinality))
  118. if return_vals:
  119. out_val = np.reshape(rand_int, (num_of_blocks, self.messages_per_block, 1))
  120. return out_val, out_arr, out_arr[:, mid_idx, :]
  121. return out_arr, out_arr[:, mid_idx, :]
  122. def train(self, num_of_blocks=1e6, batch_size=None, train_size=0.8, lr=1e-2):
  123. """
  124. Method to train the autoencoder. Further configuration to the loss function, optimizer etc. can be made in here.
  125. :param num_of_blocks: Number of blocks to generate for training. Analogous to the dataset size.
  126. :param batch_size: Number of samples to consider on each update iteration of the optimization algorithm
  127. :param train_size: Float less than 1 representing the proportion of the dataset to use for training
  128. :param lr: The learning rate of the optimizer. Defines how quickly the algorithm converges
  129. """
  130. X_train, y_train = self.generate_random_inputs(int(num_of_blocks * train_size))
  131. X_test, y_test = self.generate_random_inputs(int(num_of_blocks * (1 - train_size)))
  132. opt = tf.keras.optimizers.Adam(learning_rate=lr)
  133. self.compile(optimizer=opt,
  134. loss=losses.BinaryCrossentropy(),
  135. metrics=['accuracy'],
  136. loss_weights=None,
  137. weighted_metrics=None,
  138. run_eagerly=False
  139. )
  140. history = self.fit(x=X_train,
  141. y=y_train,
  142. batch_size=batch_size,
  143. epochs=1,
  144. shuffle=True,
  145. validation_data=(X_test, y_test)
  146. )
  147. plt.plot(history.history['accuracy'])
  148. plt.plot(history.history['val_accuracy'])
  149. plt.show()
  150. def view_encoder(self):
  151. '''
  152. A method that views the learnt encoder for each distint message. This is displayed as a plot with a subplot for
  153. each message/symbol.
  154. '''
  155. # Generate inputs for encoder
  156. messages = np.zeros((self.cardinality, self.messages_per_block, self.cardinality))
  157. mid_idx = int((self.messages_per_block - 1) / 2)
  158. idx = 0
  159. for msg in messages:
  160. msg[mid_idx, idx] = 1
  161. idx += 1
  162. # Pass input through encoder and select middle messages
  163. encoded = self.encoder(messages)
  164. enc_messages = encoded[:, mid_idx, :]
  165. # Compute subplot grid layout
  166. i = 0
  167. while 2 ** i < self.cardinality ** 0.5:
  168. i += 1
  169. num_x = int(2 ** i)
  170. num_y = int(self.cardinality / num_x)
  171. # Plot all symbols
  172. fig, axs = plt.subplots(num_y, num_x, figsize=(2.5 * num_x, 2 * num_y))
  173. t = np.arange(self.samples_per_symbol)
  174. if isinstance(self.channel.layers[1], OpticalChannel):
  175. t = t / self.channel.layers[1].fs
  176. sym_idx = 0
  177. for y in range(num_y):
  178. for x in range(num_x):
  179. axs[y, x].plot(t, enc_messages[sym_idx], 'x')
  180. axs[y, x].set_title('Symbol {}'.format(str(sym_idx)))
  181. sym_idx += 1
  182. for ax in axs.flat:
  183. ax.set(xlabel='Time', ylabel='Amplitude', ylim=(0, 1))
  184. for ax in axs.flat:
  185. ax.label_outer()
  186. plt.show()
  187. pass
  188. def view_sample_block(self):
  189. '''
  190. Generates a random string of input message and encodes them. In addition to this, the output is passed through
  191. digitization layer without any quantization noise for the low pass filtering.
  192. '''
  193. # Generate a random block of messages
  194. val, inp, _ = self.generate_random_inputs(num_of_blocks=1, return_vals=True)
  195. # Encode and flatten the messages
  196. enc = self.encoder(inp)
  197. flat_enc = layers.Flatten()(enc)
  198. # Instantiate LPF layer
  199. lpf = DigitizationLayer(fs=self.channel.layers[1].fs,
  200. num_of_samples=self.messages_per_block * self.samples_per_symbol,
  201. q_stddev=0)
  202. # Apply LPF
  203. lpf_out = lpf(flat_enc)
  204. # Time axis
  205. t = np.arange(self.messages_per_block * self.samples_per_symbol)
  206. if isinstance(self.channel.layers[1], OpticalChannel):
  207. t = t / self.channel.layers[1].fs
  208. # Plot the concatenated symbols before and after LPF
  209. plt.figure(figsize=(2 * self.messages_per_block, 6))
  210. for i in range(1, self.messages_per_block):
  211. plt.axvline(x=t[i * self.samples_per_symbol], color='black')
  212. plt.plot(t, flat_enc.numpy().T, 'x')
  213. plt.plot(t, lpf_out.numpy().T)
  214. plt.ylim((0, 1))
  215. plt.xlim((t.min(), t.max()))
  216. plt.title(str(val[0, :, 0]))
  217. plt.show()
  218. pass
  219. def call(self, inputs, training=None, mask=None):
  220. tx = self.encoder(inputs)
  221. rx = self.channel(tx)
  222. outputs = self.decoder(rx)
  223. return outputs
  224. SAMPLING_FREQUENCY = 336e9
  225. CARDINALITY = 32
  226. SAMPLES_PER_SYMBOL = 24
  227. MESSAGES_PER_BLOCK = 9
  228. DISPERSION_FACTOR = -21.7 * 1e-24
  229. FIBER_LENGTH = 50
  230. if __name__ == '__main__':
  231. optical_channel = OpticalChannel(fs=SAMPLING_FREQUENCY,
  232. num_of_samples=MESSAGES_PER_BLOCK * SAMPLES_PER_SYMBOL,
  233. dispersion_factor=DISPERSION_FACTOR,
  234. fiber_length=FIBER_LENGTH)
  235. ae_model = EndToEndAutoencoder(cardinality=CARDINALITY,
  236. samples_per_symbol=SAMPLES_PER_SYMBOL,
  237. messages_per_block=MESSAGES_PER_BLOCK,
  238. channel=optical_channel,
  239. bit_mapping=True)
  240. ae_model.train(num_of_blocks=1e6)
  241. # ae_model.view_encoder()
  242. # ae_model.view_sample_block()
  243. # ae_model.summary()
  244. ae_model.encoder.summary()
  245. ae_model.channel.summary()
  246. ae_model.decoder.summary()
  247. pass