predict.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. def load_csv(file_path):
  16. try:
  17. with open(file_path, 'r', encoding='utf-8') as f:
  18. cleaned_lines = []
  19. for line in f:
  20. line = line.strip()
  21. if line.endswith(','):
  22. line = line[:-1]
  23. cleaned_lines.append(line)
  24. loaded_array = np.loadtxt(cleaned_lines, delimiter=',')
  25. if loaded_array.ndim == 1:
  26. loaded_array = loaded_array.reshape(-1, 1)
  27. return loaded_array
  28. except Exception as e:
  29. print(f"Could not load file:\n{e}")
  30. return -1
  31. freq = 3000000
  32. sample_rate = 2000000
  33. amp = 1
  34. xgain = 35
  35. rf_filename = "test_linreg.bin"
  36. port = 11
  37. adc_filename = "pico_params.xml"
  38. below_trigger = False
  39. sync_filename = "Sync_param.xml"
  40. pico_rate = 80e6
  41. ls_ls = [[2, 400, 2, 300, 120000],
  42. [2, 8000, 2, 200, 1600000],
  43. [2, 6000, 1.5, 200, 1200000],
  44. [8, 2000, 4, 300, 600000],
  45. [8, 1000, 10, 100, 100000],
  46. [8, 200, 2, 500, 100000],
  47. [20, 500, 4, 400, 200000],
  48. [20, 800, 8, 500, 400000],
  49. [20, 2000, 4, 50, 100000],
  50. [10, 5000, 5, 400, 2000000]]
  51. print(f"Num mes: {len(ls_ls) * 3}")
  52. res = 0
  53. y = np.array([])
  54. for x in ls_ls:
  55. delays_arr = np.array([])
  56. for i in range(0, 1):
  57. print(f'\nMeasure {i}: {x}\n')
  58. try:
  59. 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(x[3]), str(x[0])], stdout=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
  60. except subprocess.CalledProcessError as e:
  61. if res != 0:
  62. print(f"Error at Sync.exe! Return: {e.returncode}")
  63. sys.exit(1)
  64. try:
  65. res = subprocess.run(["Sync.exe", sync_filename, "--debug", "-p", str(port)], stdout=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
  66. except subprocess.CalledProcessError as e:
  67. if res != 0:
  68. print(f"Error at Sync.exe! Return: {e.returncode}")
  69. sys.exit(1)
  70. try:
  71. ser = serial.Serial("COM" + str(port), 9600)
  72. ser.write(bytes('e', 'utf-8'))
  73. except serial.SerialException as e:
  74. print(f"Error at serial port: {e}")
  75. sys.exit(1)
  76. sem = win32event.CreateSemaphore(None, 0, 1, "wait-semaphore-5d95950d-a278-4733-a041-ee9fb05ad4e4")
  77. if sem == None:
  78. print(f"Error at semaphore: cannot create!")
  79. win32event.CloseHandle(sem)
  80. sys.exit(1)
  81. if below_trigger:
  82. pargs = ["pico_test_00_second_copy.exe", adc_filename, "--below"] # Не ставьте --debug, будут очень мусорные логи на сотни мегабайт!
  83. else:
  84. pargs = ["pico_test_00_second_copy.exe", adc_filename]
  85. # Using Popen for asynchronous running
  86. try:
  87. picoproc = subprocess.Popen(pargs, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
  88. print(f"Pico process PID: {picoproc.pid}")
  89. except subprocess.SubprocessError as e:
  90. print(f"Error at Pico! Return: {e.returncode}")
  91. picoproc.kill()
  92. sys.exit(1)
  93. ret = win32event.WaitForSingleObject(sem, 20000)
  94. if ret == win32event.WAIT_TIMEOUT:
  95. print("Pico timeout!")
  96. win32event.ReleaseSemaphore(sem, 1)
  97. win32file.CloseHandle(sem)
  98. sys.exit(1)
  99. try:
  100. res = subprocess.run(["hackrftrans00.exe", "-t", rf_filename, "-f", str(round(3e6)), "-s", str(round(x[0] * 1e6)), "-a", str(amp), "-x", str(xgain)])
  101. except subprocess.CalledProcessError as e:
  102. if res != 0:
  103. print(f"Error at HackRF! Return: {e.returncode}")
  104. sys.exit(1)
  105. print(f"End of measurement. Loading CSV... \n")
  106. time.sleep(10)
  107. arr = load_csv('output\\data_fixed.csv')
  108. tarr = np.transpose(arr)
  109. envelope = np.abs(tarr[1])
  110. cutoff = 1000e3
  111. nyquist = 0.5 * pico_rate
  112. order = 5
  113. b, a = butter(order, cutoff / nyquist, btype='low')
  114. filt_envelope = filtfilt(b, a, envelope)
  115. startcut = round(0.05 * np.size(tarr[1]))
  116. endcut = round(0.5 * np.size(tarr[1]))
  117. demodulated_voltage = np.average(filt_envelope[startcut:endcut])
  118. print(f'Start cut: {startcut}')
  119. print(f'End cut: {endcut}')
  120. print(f'Demoodulated voltage: {demodulated_voltage}')
  121. i = startcut
  122. while filt_envelope[i] > demodulated_voltage * 0.5 and i < np.size(tarr[1]):
  123. i = i + 1
  124. delay = round((np.size(tarr[1]) - i) / 0.08)
  125. print(f'Delay: {delay} nS')
  126. delays_arr = np.append(delays_arr, [delay])
  127. y = (1474.443027 * x[0] - 262.072789 * x[1] / 1e3 - 647.769975 * x[2] + 39740.431031 * x[4] / 1e6 - 6852.33)
  128. print(f'Predicted delay: {y} nS')
  129. with open('predication.txt', 'a', encoding='utf-8') as f:
  130. f.write(f'sr = {x[0]} MHz; period = {x[1]} ms; idc = {x[2]}; time = {x[4] / 1e6} s;\ndelay = {delay} nS;\npredicted = {y} nS;\n\n')
  131. f.close()
  132. win32file.CloseHandle(sem)
  133. ser.close()
  134. time.sleep(0.1)