logreg_10-20.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import itertools as itt
  2. import sys
  3. import time
  4. import datetime
  5. import serial
  6. import win32event
  7. import win32file
  8. import win32api
  9. import pywintypes
  10. import subprocess
  11. import matplotlib
  12. import numpy as np
  13. from sklearn.linear_model import LinearRegression
  14. from scipy.signal import butter, filtfilt
  15. freq = 3000000
  16. sample_rate = 2000000
  17. amp = 1
  18. xgain = 35
  19. rf_filename = "test_linreg.bin"
  20. port = 11
  21. adc_filename = "pico_params.xml"
  22. below_trigger = False
  23. sync_filename = "Sync_param.xml"
  24. pico_rate = 80e6
  25. # sample rate - 1st element
  26. # period - 2nd element
  27. # inverse duty cycle - 3rd element
  28. # number - 4th element
  29. def load_csv(file_path):
  30. try:
  31. with open(file_path, 'r', encoding='utf-8') as f:
  32. cleaned_lines = []
  33. for line in f:
  34. line = line.strip()
  35. if line.endswith(','):
  36. line = line[:-1]
  37. cleaned_lines.append(line)
  38. f.close()
  39. loaded_array = np.loadtxt(cleaned_lines, delimiter=',')
  40. if loaded_array.ndim == 1:
  41. loaded_array = loaded_array.reshape(-1, 1)
  42. return loaded_array
  43. except Exception as e:
  44. print(f"Could not load file:\n{e}")
  45. return -1
  46. ls_tup = [
  47. list(item)
  48. for item in itt.product(
  49. range(1, 3),
  50. range(1, 11),
  51. range(1, 6),
  52. range(1, 6)
  53. )
  54. ]
  55. ls_ls = []
  56. for tup in ls_tup:
  57. ls_ls.append(list(tup))
  58. for x in ls_ls:
  59. if x[0] == 1: # sr in MHz
  60. x[0] = 10
  61. elif x[0] == 2:
  62. x[0] = 20
  63. elif x[0] == 3:
  64. x[0] = 10
  65. elif x[0] == 4:
  66. x[0] = 20
  67. if x[1] == 1: # period in us
  68. x[1] = 240
  69. elif x[1] == 2:
  70. x[1] = 480
  71. elif x[1] == 3:
  72. x[1] = 960
  73. elif x[1] == 4:
  74. x[1] = 1920
  75. elif x[1] == 5:
  76. x[1] = 2880
  77. elif x[1] == 6:
  78. x[1] = 3840
  79. elif x[1] == 7:
  80. x[1] = 5760
  81. elif x[1] == 8:
  82. x[1] = 7680
  83. elif x[1] == 9:
  84. x[1] = 9600
  85. elif x[1] == 10:
  86. x[1] = 11520
  87. if x[2] == 1: # idc
  88. x[2] = 1.5
  89. elif x[2] == 2:
  90. x[2] = 2
  91. elif x[2] == 3:
  92. x[2] = 4
  93. elif x[2] == 4:
  94. x[2] = 8
  95. elif x[2] == 5:
  96. x[2] = 10
  97. if x[3] == 1: # time of pulses
  98. x[3] = 100 * x[1]
  99. elif x[3] == 2:
  100. x[3] = 200 * x[1]
  101. elif x[3] == 3:
  102. x[3] = 400 * x[1]
  103. elif x[3] == 4:
  104. x[3] = 600 * x[1]
  105. elif x[3] == 5:
  106. x[3] = 800 * x[1]
  107. nmes = len(ls_ls) * 5
  108. print(f"Num mes: {nmes}")
  109. res = 0
  110. cnt = 1
  111. y = np.array([])
  112. for x in ls_ls:
  113. delays_arr = np.array([])
  114. for i in range(0, 5):
  115. print(f'\nMeasure {cnt}-{i+1} (in {nmes}): {x}\n')
  116. print(f'Number: {round(x[3] / x[1])}')
  117. print(f'PW: {round(x[1] / x[2])}')
  118. try:
  119. res = subprocess.run(["python.exe", 'pulse_generator_console_logreg.py', str(x[1]), 'uS', str(round(x[1] / x[2])), 'uS', str(0), 'uS', str(2), 'uS', str(round(x[3] / x[1])), str(x[0])], stdout=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
  120. except subprocess.CalledProcessError as e:
  121. if res != 0:
  122. print(f"Error at Sync.exe! Return: {e.returncode}")
  123. sys.exit(1)
  124. try:
  125. res = subprocess.run(["Sync.exe", sync_filename, "--debug", "-p", str(port)], stdout=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
  126. except subprocess.CalledProcessError as e:
  127. if res != 0:
  128. print(f"Error at Sync.exe! Return: {e.returncode}")
  129. sys.exit(1)
  130. try:
  131. ser = serial.Serial("COM" + str(port), 9600)
  132. ser.write(bytes('e', 'utf-8'))
  133. except serial.SerialException as e:
  134. print(f"Error at serial port: {e}")
  135. sys.exit(1)
  136. sem = win32event.CreateSemaphore(None, 0, 1, "wait-semaphore-5d95950d-a278-4733-a041-ee9fb05ad4e4")
  137. if sem == None:
  138. print(f"Error at semaphore: cannot create!")
  139. win32event.CloseHandle(sem)
  140. sys.exit(1)
  141. if below_trigger:
  142. pargs = ["pico_test_00_second_copy.exe", adc_filename, "--below"] # Не ставьте --debug, будут очень мусорные логи на сотни мегабайт!
  143. else:
  144. pargs = ["pico_test_00_second_copy.exe", adc_filename]
  145. # Using Popen for asynchronous running
  146. try:
  147. picoproc = subprocess.Popen(pargs, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
  148. print(f"Pico process PID: {picoproc.pid}")
  149. except subprocess.SubprocessError as e:
  150. print(f"Error at Pico! Return: {e.returncode}")
  151. picoproc.kill()
  152. sys.exit(1)
  153. ret = win32event.WaitForSingleObject(sem, 20000)
  154. if ret == win32event.WAIT_TIMEOUT:
  155. print("Pico timeout!")
  156. win32event.ReleaseSemaphore(sem, 1)
  157. win32file.CloseHandle(sem)
  158. sys.exit(1)
  159. try:
  160. res = subprocess.run(["hackrftrans00.exe", "-t", rf_filename, "-f", str(round(3e6)), "-s", str(round(x[0] * 1e6)), "-a", str(amp), "-x", str(xgain)])
  161. except subprocess.CalledProcessError as e:
  162. if res != 0:
  163. print(f"Error at HackRF! Return: {e.returncode}")
  164. sys.exit(1)
  165. try:
  166. outs, errs = picoproc.communicate(timeout=15)
  167. except TimeoutExpired:
  168. picoproc.kill()
  169. outs, errs = proc.communicate()
  170. print(f"End of measurement. Loading CSV... \n")
  171. time.sleep(3)
  172. arr = load_csv('output\\data_fixed.csv')
  173. tarr = np.transpose(arr)
  174. envelope = np.abs(tarr[1])
  175. cutoff = 1000e3
  176. nyquist = 0.5 * pico_rate
  177. order = 5
  178. b, a = butter(order, cutoff / nyquist, btype='low')
  179. filt_envelope = filtfilt(b, a, envelope)
  180. startcut = round(0.05 * np.size(tarr[1]))
  181. endcut = round(0.5 * np.size(tarr[1]))
  182. demodulated_voltage = np.average(filt_envelope[startcut:endcut])
  183. print(f'Start cut: {startcut}')
  184. print(f'End cut: {endcut}')
  185. print(f'Demoodulated voltage: {demodulated_voltage}')
  186. i = startcut
  187. while filt_envelope[i-1] > demodulated_voltage * 0.5 and i < np.size(tarr[1]):
  188. i = i + 1
  189. delay = round((np.size(tarr[1]) - i) / 0.08)
  190. print(f'Delay: {delay} nS')
  191. delays_arr = np.append(delays_arr, [delay])
  192. win32file.CloseHandle(sem)
  193. ser.close()
  194. time.sleep(0.1)
  195. mean_delay = np.average(delays_arr)
  196. print(delays_arr)
  197. print(f'\nMean delay {x}: {mean_delay} nS')
  198. y = np.append(y, [mean_delay])
  199. with open('delays_new.txt', 'a', encoding='utf-8') as f:
  200. f.write(f'sr = {x[0]} MHz; period = {x[1]} uS; idc = {x[2]}; time = {x[3]} uS \n delay = {mean_delay} nS \n\n')
  201. f.close()
  202. cnt = cnt + 1
  203. reg = LinearRegression().fit(np.array(ls_ls), y)
  204. reg.score(np.array(ls_ls), y)
  205. print('Coef: ', reg.coef_)
  206. print('Intercept: ', reg.intercept_)
  207. with open('regression_updated.txt', 'w', encoding='utf-8') as f:
  208. f.write(f'sr_coef = {reg.coef_[0]}; period_coef = {reg.coef_[1]}; idc_coef = {reg.coef_[2]}; time_coef = {reg.coef_[3]} nS/uS \n intercept = {reg.intercept_} \n\n')
  209. f.close()