Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

294 lignes
11 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. .bin 波形文件 -> 时频曲线查看/出图工具(PLSR 项目用)
  4. 数据格式: 逻辑分析仪导出的单通道数字采样,每字节 1 个采样点;
  5. 电平 >= 阈值(默认128) 判为高(脉冲),否则为低。
  6. 频率定义: 每脉冲频率 = 采样率 / 脉冲周期;
  7. 周期 = 本脉冲高电平起点 -> 下一脉冲高电平起点;
  8. 最后一个脉冲无下一脉冲,按高电平宽度 x2 近似(50% 占空比)。
  9. 时间定义: 脉冲时间 = 高电平中点(与低电平/空闲段无关)。
  10. 用法:
  11. python bin_to_time_freq.py <bin文件> [采样率Hz] [选项]
  12. 示例:
  13. python bin_to_time_freq.py "Document/PLSR_document/波形/10段.bin" 6250000
  14. python bin_to_time_freq.py xxx.bin 6250000 --ymax=12000
  15. python bin_to_time_freq.py xxx.bin 6250000 --save=out.png
  16. python bin_to_time_freq.py xxx.bin 6250000 --selftest
  17. 选项:
  18. --thresh=128 电平阈值(默认128)
  19. --ymax=12000 频率轴上限(默认自适应)
  20. --save=路径 保存 PNG 后退出(不弹窗)
  21. --selftest 仅打印统计,不画图
  22. 交互(弹窗模式):
  23. 滚轮 缩放 X 轴(向上放大/向下缩小,以鼠标位置为中心)
  24. Ctrl+滚轮 缩放 Y 轴(以鼠标 Y 位置为中心)
  25. 左键拖拽 双向平移(上下左右跟随鼠标)
  26. 双击 复位到全图
  27. 鼠标悬停 高亮最近的点并显示其脉冲序号、时间与频率
  28. 依赖: pip install numpy matplotlib
  29. """
  30. import sys
  31. import os
  32. import numpy as np
  33. try:
  34. import matplotlib
  35. matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei']
  36. matplotlib.rcParams['axes.unicode_minus'] = False
  37. except Exception:
  38. pass
  39. def load_time_freq(path, fs, threshold=128):
  40. """读取 bin,返回 (t_sec, freq_hz, hi_width_sec, meta)。
  41. t_sec 以第一个脉冲为 0 时刻;hi_width 为每脉冲高电平宽度。"""
  42. data = np.fromfile(path, dtype=np.uint8)
  43. if data.size == 0:
  44. raise ValueError("文件为空: %s" % path)
  45. samples = (data >= threshold).astype(np.int8)
  46. # run 级压缩
  47. changes = np.flatnonzero(np.diff(samples) != 0) + 1
  48. starts = np.concatenate(([0], changes))
  49. ends = np.concatenate((changes, [len(samples)]))
  50. runs = np.column_stack((starts, ends, samples[starts]))
  51. # 脉冲 = 高电平 run,且其后紧跟低电平 run
  52. hi = np.flatnonzero(runs[:, 2] == 1)
  53. hi = hi[hi + 1 < len(runs)]
  54. lo_ok = runs[hi + 1, 2] == 0
  55. hi = hi[lo_ok]
  56. t_start = runs[hi, 0].astype(np.int64)
  57. hi_width = (runs[hi, 1] - runs[hi, 0]).astype(np.int64)
  58. # 周期:高到高;末脉冲按 2x 高电平宽度近似
  59. next_start = np.append(t_start[1:], [t_start[-1] + 2 * hi_width[-1]])
  60. period = next_start - t_start
  61. freq = fs / np.maximum(period, 1)
  62. # 时间:高电平中点,去起始偏移
  63. t_sec = (t_start + hi_width / 2.0) / fs
  64. t_sec = t_sec - t_sec[0]
  65. meta = {
  66. 'total_samples': int(len(samples)),
  67. 'duration': len(samples) / fs,
  68. 'pulses': int(len(freq)),
  69. 'offset_ms': t_start[0] / fs * 1000,
  70. }
  71. return t_sec, freq, hi_width / fs, meta
  72. def selftest(path, fs, thresh):
  73. import statistics
  74. t, freq, hi_w, meta = load_time_freq(path, fs, thresh)
  75. print("文件: %s" % path)
  76. print("总采样: %d (%.3f s @ %.2f MS/s)" % (meta['total_samples'], meta['duration'], fs / 1e6))
  77. print("起始采集偏移: %.1f ms" % meta['offset_ms'])
  78. print("脉冲总数: %d" % meta['pulses'])
  79. if meta['pulses']:
  80. print("频率 min=%.0f max=%.0f 中位=%.0f Hz" % (
  81. freq.min(), freq.max(), statistics.median(freq)))
  82. print("末脉冲: t=%.3f ms, 高电平 %.3f ms, %.0f Hz" % (
  83. t[-1] * 1000, hi_w[-1] * 1000, freq[-1]))
  84. print("波形活动时长: %.1f ms" % ((t[-1] + hi_w[-1] / 2) * 1000))
  85. def plot_show(path, fs, thresh, ymax, save_path=None):
  86. t, freq, hi_w, meta = load_time_freq(path, fs, thresh)
  87. import matplotlib.pyplot as plt
  88. from matplotlib.ticker import MaxNLocator
  89. fig, ax = plt.subplots(figsize=(15, 7))
  90. fig.subplots_adjust(bottom=0.10, top=0.92)
  91. # 全脉冲散点:复用 artist,重绘时按可见范围抽稀(大文件流畅)
  92. MAX_VISIBLE_POINTS = 5000 # 可见范围内最多绘制的点数,超过则等间隔抽稀
  93. (scatter,) = ax.plot([], [], '.', ms=1.5, color='C0', alpha=0.5, zorder=1)
  94. tx_ms = t * 1000
  95. x_full = tx_ms
  96. y_full = freq
  97. ax.set_xlim(0.0, (t[-1] + hi_w[-1]) * 1000 * 1.02)
  98. ax.set_ylim(0, ymax if ymax > 0 else freq.max() * 1.08)
  99. ax.set_title("%s 时频曲线(%d 脉冲,活动时长 %.0f ms)" % (
  100. os.path.basename(path), meta['pulses'],
  101. (t[-1] + hi_w[-1] / 2) * 1000))
  102. ax.set_xlabel("时间 (ms)")
  103. ax.set_ylabel("频率 (Hz)")
  104. # 更密的刻度
  105. ax.xaxis.set_major_locator(MaxNLocator(nbins=20))
  106. ax.yaxis.set_major_locator(MaxNLocator(nbins=15))
  107. ax.grid(True, which='major', alpha=0.35)
  108. ax.grid(True, which='minor', alpha=0.15)
  109. ax.minorticks_on()
  110. if save_path:
  111. fig.savefig(save_path, dpi=130)
  112. print("已保存: %s" % save_path)
  113. plt.close(fig)
  114. return
  115. # 交互:滚轮缩放 X(Ctrl+滚轮缩放 Y)/ 左键双向拖拽平移 / 双击复位 / 悬停高亮
  116. state = {'press_x': None, 'press_y': None,
  117. 'press_xlim': None, 'press_ylim': None}
  118. # 悬停高亮:一个红点标记 + 一个带框文本
  119. (hl_marker,) = ax.plot([], [], 'o', ms=9, mfc='red', mec='white',
  120. mew=1.0, zorder=5, visible=False)
  121. hl_text = ax.text(0, 0, '', fontsize=10, color='black',
  122. bbox=dict(boxstyle='round,pad=0.3', fc='yellow', ec='red', alpha=0.9),
  123. zorder=6, visible=False)
  124. hover_last = {'idx': -1, 'visible': False}
  125. # 可见范围内抽稀绘制散点(大文件性能优化)
  126. def update_scatter():
  127. x0, x1 = ax.get_xlim()
  128. mask = (x_full >= x0) & (x_full <= x1)
  129. n_vis = int(np.count_nonzero(mask))
  130. if n_vis > MAX_VISIBLE_POINTS:
  131. # 等间隔抽稀:取 n_vis 中的 MAX_VISIBLE_POINTS 个
  132. step = (n_vis + MAX_VISIBLE_POINTS - 1) // MAX_VISIBLE_POINTS
  133. idx = np.flatnonzero(mask)[::step]
  134. else:
  135. idx = np.flatnonzero(mask)
  136. scatter.set_data(x_full[idx], y_full[idx])
  137. def on_scroll(event):
  138. if event.inaxes is not ax or event.xdata is None:
  139. return
  140. zoom_in = event.button == 'up'
  141. factor = 1.0 / 1.5 if zoom_in else 1.5
  142. if event.key in ('control', 'ctrl'):
  143. # Ctrl+滚轮:缩放 Y 轴,以鼠标 Y 位置为锚点(锚点数据点不动)
  144. y0, y1 = ax.get_ylim()
  145. cy = event.ydata
  146. n0 = cy - (cy - y0) * factor
  147. n1 = cy + (y1 - cy) * factor
  148. if n1 - n0 < 1.0:
  149. return
  150. ax.set_ylim(n0, n1)
  151. else:
  152. # 普通滚轮:缩放 X 轴,以鼠标 X 位置为锚点(锚点数据点不动)
  153. x0, x1 = ax.get_xlim()
  154. n0 = event.xdata - (event.xdata - x0) * factor
  155. n1 = event.xdata + (x1 - event.xdata) * factor
  156. if n1 - n0 < 1e-6:
  157. return
  158. ax.set_xlim(n0, n1)
  159. update_scatter()
  160. fig.canvas.draw_idle()
  161. def on_press(event):
  162. if event.inaxes is ax and event.button == 1:
  163. state['press_x'] = event.xdata
  164. state['press_y'] = event.ydata
  165. state['press_xlim'] = ax.get_xlim()
  166. state['press_ylim'] = ax.get_ylim()
  167. def on_motion(event):
  168. if event.inaxes is not ax or event.xdata is None:
  169. return
  170. if state['press_x'] is not None:
  171. # 拖拽平移:X/Y 双向跟随鼠标
  172. x0, x1 = state['press_xlim']
  173. y0, y1 = state['press_ylim']
  174. dx = event.xdata - state['press_x']
  175. dy = event.ydata - state['press_y']
  176. ax.set_xlim(x0 - dx, x1 - dx)
  177. ax.set_ylim(y0 - dy, y1 - dy)
  178. update_scatter()
  179. fig.canvas.draw_idle()
  180. return
  181. # 悬停:找可见范围内距鼠标最近的脉冲点(屏幕像素距离 < 20px 才高亮)
  182. x0, x1 = ax.get_xlim()
  183. mask = (x_full >= x0) & (x_full <= x1)
  184. if not np.any(mask):
  185. if hover_last['visible']:
  186. hl_marker.set_visible(False)
  187. hl_text.set_visible(False)
  188. fig.canvas.draw_idle()
  189. hover_last['visible'] = False
  190. return
  191. px, py = ax.transData.transform(np.column_stack([x_full[mask], y_full[mask]])).T
  192. dist = np.hypot(px - event.x, py - event.y)
  193. k = int(np.argmin(dist))
  194. if dist[k] <= 20.0:
  195. idx = int(np.flatnonzero(mask)[k])
  196. hl_marker.set_data([x_full[idx]], [y_full[idx]])
  197. hl_text.set_text("脉冲 #%d\nt = %.3f ms\nf = %.0f Hz"
  198. % (idx + 1, x_full[idx], y_full[idx]))
  199. hl_text.set_position((x_full[idx] + (x1 - x0) * 0.01,
  200. y_full[idx] + (ax.get_ylim()[1] - ax.get_ylim()[0]) * 0.02))
  201. hl_marker.set_visible(True)
  202. hl_text.set_visible(True)
  203. if hover_last['idx'] != idx or not hover_last['visible']:
  204. fig.canvas.draw_idle()
  205. hover_last['idx'] = idx
  206. hover_last['visible'] = True
  207. else:
  208. if hover_last['visible']:
  209. hl_marker.set_visible(False)
  210. hl_text.set_visible(False)
  211. fig.canvas.draw_idle()
  212. hover_last['visible'] = False
  213. def on_release(event):
  214. state['press_x'] = None
  215. def on_double(event):
  216. if event.dblclick:
  217. ax.set_xlim(0.0, (t[-1] + hi_w[-1]) * 1000 * 1.02)
  218. ax.set_ylim(0, ymax if ymax > 0 else freq.max() * 1.08)
  219. update_scatter()
  220. fig.canvas.draw_idle()
  221. update_scatter()
  222. fig.canvas.mpl_connect('scroll_event', on_scroll)
  223. fig.canvas.mpl_connect('button_press_event', on_press)
  224. fig.canvas.mpl_connect('button_release_event', on_release)
  225. fig.canvas.mpl_connect('motion_notify_event', on_motion)
  226. fig.canvas.mpl_connect('button_press_event', on_double)
  227. print("打开窗口:滚轮缩放X / Ctrl+滚轮缩放Y / 左键双向拖拽平移 / 双击复位")
  228. print("脉冲 %d 个,活动时长 %.1f ms" % (
  229. meta['pulses'], (t[-1] + hi_w[-1] / 2) * 1000))
  230. plt.show()
  231. def main():
  232. args = [a for a in sys.argv[1:] if not a.startswith('--')]
  233. opts = {a.split('=', 1)[0]: (a.split('=', 1)[1] if '=' in a else True)
  234. for a in sys.argv[1:] if a.startswith('--')}
  235. if len(args) < 1 or '--help' in opts or '-h' in opts:
  236. print(__doc__)
  237. sys.exit(0)
  238. path = args[0]
  239. fs = float(args[1]) if len(args) > 1 else 6.25e6
  240. thresh = int(opts.get('--thresh', 128))
  241. ymax = float(opts.get('--ymax', 0))
  242. save_path = opts.get('--save', '')
  243. if not os.path.isfile(path):
  244. print("错误:文件不存在 - %s" % path)
  245. sys.exit(1)
  246. if '--selftest' in opts:
  247. selftest(path, fs, thresh)
  248. else:
  249. plot_show(path, fs, thresh, ymax, save_path or None)
  250. if __name__ == '__main__':
  251. main()