misc.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import numpy as np
  2. import math
  3. import matplotlib.pyplot as plt
  4. def display_alphabet(alphabet, values=None, a_vals=False, title="Alphabet constellation diagram"):
  5. rect = polar2rect(alphabet)
  6. if values is not None:
  7. rect2 = polar2rect(values)
  8. plt.plot(rect2[:, 0], rect2[:, 1], 'r.')
  9. plt.plot(rect[:, 0], rect[:, 1], 'b.', markersize=12)
  10. plt.title(title)
  11. N = math.ceil(math.log2(len(alphabet)))
  12. if a_vals:
  13. for i, value in enumerate(rect):
  14. plt.annotate(xy=value+[0.01, 0.01], s=format(i, f'0{N}b'))
  15. plt.xlabel('Real')
  16. plt.ylabel('Imaginary')
  17. plt.grid()
  18. plt.show()
  19. def bit_matrix2one_hot(matrix: np.ndarray) -> np.ndarray:
  20. """
  21. Returns a copy of bit encoded matrix to one hot matrix. A row examples:
  22. [1010] (decimal 10) => [0000 0100 0000 0000]
  23. [0011] (decimal 3) => [0000 0000 0000 1000]
  24. each number represents true/false value in column
  25. """
  26. N = matrix.shape[1]
  27. encoder = 2**np.arange(N)
  28. values = np.dot(matrix, encoder)
  29. result = np.zeros((matrix.shape[0], 2**N), dtype=bool)
  30. result[np.arange(matrix.shape[0]), values] = True
  31. return result
  32. def one_hot2bit_matrix(matrix: np.ndarray) -> np.ndarray:
  33. """
  34. Returns a copy of one hot matrix to bit encoded matrix. A row examples:
  35. [0000 0100 0000 0000] => [1010] (decimal 10)
  36. [0000 0000 0000 1000] => [0011] (decimal 3)
  37. each number represents true/false value in column
  38. """
  39. N = math.ceil(math.log2(matrix.shape[1]))
  40. values = np.dot(matrix, np.arange(2**N))
  41. return int2bit_array(values, N)
  42. def int2bit_array(int_arr: np.ndarray, N: int) -> np.ndarray:
  43. x0 = np.array([int_arr], dtype=np.uint8)
  44. x1 = np.unpackbits(x0.T, bitorder='little', axis=1)
  45. result = x1[:, :N].astype(bool) # , indices
  46. return result
  47. def polar2rect(array, amp_column=0, phase_column=1) -> np.ndarray:
  48. """
  49. Return copy of array with amp_column and phase_column as polar coordinates replaced by rectangular coordinates
  50. """
  51. if len(array) == 2 or len(array.shape) == 1:
  52. array = np.array([array])
  53. if array.shape[1] < 2:
  54. raise ValueError('Matrix has less than two columns')
  55. result = array.copy()
  56. result[:, amp_column] = np.cos(array[:, phase_column]) * array[:, amp_column]
  57. result[:, phase_column] = np.sin(array[:, phase_column]) * array[:, amp_column]
  58. return result
  59. def rect2polar(array, x_column=0, y_column=1) -> np.ndarray:
  60. """
  61. Return copy of array with x_column and y_column as rectangular coordinates replaced by polar coordinates
  62. """
  63. if len(array) == 2 or len(array.shape) == 1:
  64. array = np.array([array])
  65. if array.shape[1] < 2:
  66. raise ValueError('Matrix has less than two columns')
  67. x_arr = array[:, x_column]
  68. y_arr = array[:, y_column]
  69. result = array.copy()
  70. result[:, x_column] = np.sqrt(x_arr**2 + y_arr**2)
  71. result[x_arr != 0, y_column] = np.arctan(y_arr[x_arr != 0, ] / x_arr[x_arr != 0, ])
  72. result[np.bitwise_and(x_arr == 0, y_arr < 0), y_column] = -np.pi / 2
  73. result[np.bitwise_and(x_arr == 0, y_arr == 0), y_column] = 0
  74. result[np.bitwise_and(x_arr == 0, y_arr > 0), y_column] = np.pi / 2
  75. result[np.bitwise_and(x_arr < 0, y_arr < 0), y_column] -= np.pi
  76. result[np.bitwise_and(x_arr < 0, y_arr >= 0), y_column] += np.pi
  77. return result
  78. def generate_random_bit_array(size):
  79. z, o = np.zeros(int(size // 2), dtype=bool), np.ones(int(size // 2), dtype=bool)
  80. if size % 2 == 1:
  81. p = (z, o, [np.random.choice([True, False])])
  82. else:
  83. p = (z, o)
  84. arr = np.concatenate(p)
  85. np.random.shuffle(arr)
  86. return arr