main.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from sklearn.metrics import accuracy_score
  4. from models import basic
  5. from models.basic import AWGNChannel, BPSKDemod, BPSKMod, BypassChannel, MaryMod, MaryDemod
  6. import misc
  7. def show_constellation(mod, chan, demod, samples=1000):
  8. x = misc.generate_random_bit_array(samples)
  9. x_mod = mod.forward(x)
  10. x_chan = chan.forward(x_mod)
  11. x_demod = demod.forward(x_chan)
  12. x_mod_rect = misc.polar2rect(x_mod)
  13. x_chan_rect = misc.polar2rect(x_chan)
  14. plt.plot(x_chan_rect[:, 0][x], x_chan_rect[:, 1][x], '+')
  15. plt.plot(x_chan_rect[:, 0][~x], x_chan_rect[:, 1][~x], '+')
  16. plt.plot(x_mod_rect[:, 0], x_mod_rect[:, 1], 'ro')
  17. axes = plt.gca()
  18. axes.set_xlim([-2, +2])
  19. axes.set_ylim([-2, +2])
  20. plt.grid()
  21. plt.show()
  22. print('Accuracy : ' + str())
  23. def get_ber(mod, chan, demod, samples=1000):
  24. x = misc.generate_random_bit_array(samples)
  25. x_mod = mod.forward(x)
  26. x_chan = chan.forward(x_mod)
  27. x_demod = demod.forward(x_chan)
  28. return 1 - accuracy_score(x, x_demod)
  29. def get_AWGN_ber(mod, demod, samples=1000, start=-8, stop=5, steps=30):
  30. ber_x = np.linspace(start, stop, steps)
  31. ber_y = []
  32. for noise in ber_x:
  33. ber_y.append(get_ber(mod, AWGNChannel(noise), demod, samples=samples))
  34. return ber_x, ber_y
  35. if __name__ == '__main__':
  36. plt.plot(*get_AWGN_ber(MaryMod(6, 10e6, gray=True), MaryDemod(6, 10e6), samples=12000, start=-15), '-', label='64-QAM')
  37. plt.plot(*get_AWGN_ber(MaryMod(5, 10e6, gray=True), MaryDemod(5, 10e6), samples=12000, start=-15), '-', label='32-QAM')
  38. plt.plot(*get_AWGN_ber(MaryMod(4, 10e6, gray=True), MaryDemod(4, 10e6), samples=12000, start=-15), '-', label='16-QAM')
  39. plt.plot(*get_AWGN_ber(BPSKMod(10e6), BPSKDemod(10e6, 10e3), samples=12000), '-', label='BPSK')
  40. plt.yscale('log')
  41. plt.gca().invert_xaxis()
  42. plt.grid()
  43. plt.xlabel('Noise dB')
  44. plt.ylabel('BER')
  45. plt.legend()
  46. plt.show()
  47. pass