74 lines
4.3 KiB
Python
74 lines
4.3 KiB
Python
# -*- coding: utf-8 -*-
|
||
# 圖 3.4 : Unity 內建輸入 vs Raw Input 的相鄰回報時間間隔直方圖
|
||
# 用法 : python plot_input_histogram.py <unity_probe.csv> <raw_probe.csv> [輸出.jpg] [滑鼠回報率Hz]
|
||
# 兩個 csv 來自 InputCompareProbe (Test 場景 F11 切換模式、F10 存到桌面),欄位 t,dx,dy
|
||
import sys, os
|
||
import numpy as np
|
||
import matplotlib
|
||
matplotlib.use('Agg')
|
||
import matplotlib.pyplot as plt
|
||
from matplotlib import font_manager
|
||
from matplotlib.ticker import FixedLocator, FixedFormatter, NullLocator
|
||
|
||
for name in ['Microsoft JhengHei', 'Noto Sans CJK TC', 'PingFang TC', 'Microsoft YaHei']:
|
||
if any(f.name == name for f in font_manager.fontManager.ttflist):
|
||
plt.rcParams['font.family'] = name; break
|
||
plt.rcParams['axes.unicode_minus'] = False
|
||
|
||
unity_path, raw_path = sys.argv[1], sys.argv[2]
|
||
out = sys.argv[3] if len(sys.argv) > 3 else os.path.join(os.path.dirname(os.path.abspath(unity_path)), 'fig3_4_input_histogram.jpg')
|
||
hz = float(sys.argv[4]) if len(sys.argv) > 4 else None
|
||
|
||
def gaps_ms(path):
|
||
t = np.loadtxt(path, delimiter=',', skiprows=1, usecols=0, ndmin=1)
|
||
if len(t) < 2:
|
||
sys.exit(f'{path} 沒有資料 : 這個模式沒錄到 (Unity 模式要先按 F11 切過去再移動滑鼠)')
|
||
t = np.sort(t)
|
||
return np.diff(t) * 1000.0
|
||
|
||
BAR = '#4C78A8'; INK = '#333333'; MUTED = '#777777'
|
||
lo, hi = 1e-3, 20.0
|
||
zero_pos = 10 ** -3.6 # 間隔 = 0 的回報畫在對數軸左邊一格獨立的長條 (對數軸放不下 0)
|
||
bins = np.logspace(np.log10(lo), np.log10(hi), 70)
|
||
|
||
data = [('Unity Input System (引擎內建)', gaps_ms(unity_path)), ('Windows Raw Input (本研究)', gaps_ms(raw_path))]
|
||
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), sharey=True)
|
||
for ax, (title, g) in zip(axes, data):
|
||
pct = 100.0 / len(g)
|
||
zero = g <= 0
|
||
ax.hist(np.clip(g[~zero], lo, hi), bins=bins, weights=np.full((~zero).sum(), pct), color=BAR, edgecolor='white', linewidth=0.3)
|
||
if zero.any():
|
||
ax.bar(zero_pos, zero.sum() * pct, width=zero_pos * 0.5, color=BAR, edgecolor='white', linewidth=0.3)
|
||
ax.set_xscale('log'); ax.set_xlim(10 ** -3.85, hi)
|
||
ticks = [zero_pos, 1e-3, 1e-2, 1e-1, 1, 10]
|
||
ax.xaxis.set_major_locator(FixedLocator(ticks)); ax.xaxis.set_major_formatter(FixedFormatter(['0', '0.001', '0.01', '0.1', '1', '10']))
|
||
ax.xaxis.set_minor_locator(NullLocator())
|
||
ax.axvline(10 ** -3.3, color=MUTED, linewidth=0.6) # 「= 0」與對數軸之間的分隔
|
||
ax.grid(axis='y', alpha=0.3, linewidth=0.5)
|
||
ax.set_title(title, fontsize=11, color=INK); ax.set_xlabel('相鄰回報的時間間隔 (ms,對數刻度)')
|
||
if hz:
|
||
ax.axvline(1000.0 / hz, color=INK, linestyle=':', linewidth=1)
|
||
ax.text(0.98, 0.95, f'事件數 {len(g) + 1:,}\n間隔中位數 {np.median(g):.3f} ms\n間隔 = 0 的比例 {100 * zero.mean():.0f}%\n< 0.01 ms 的比例 {100 * (g < 0.01).mean():.0f}%',
|
||
transform=ax.transAxes, ha='right', va='top', fontsize=9, color=INK,
|
||
bbox=dict(boxstyle='round,pad=0.4', facecolor='white', edgecolor='#999999', linewidth=0.6))
|
||
axes[0].set_ylabel('佔所有間隔的比例 (%)')
|
||
|
||
# Unity 那格標出兩群 : 同一幀內批次標記 (間隔 ≈ 0) 與幀與幀之間 (≈ 一幀)
|
||
g = data[0][1]; frame_gaps = g[g >= 0.1]
|
||
if len(frame_gaps):
|
||
fg = np.median(frame_gaps)
|
||
axes[0].annotate('同一幀內的回報\n被標上幾乎相同的時間', xy=(zero_pos * 1.4, 60), xytext=(4e-3, 55), fontsize=9, color=INK,
|
||
arrowprops=dict(arrowstyle='->', color=MUTED, linewidth=0.8))
|
||
axes[0].annotate(f'幀與幀之間\n(約 {fg:.1f} ms,即幀間隔)', xy=(fg, 6), xytext=(0.15, 25), fontsize=9, color=INK,
|
||
arrowprops=dict(arrowstyle='->', color=MUTED, linewidth=0.8))
|
||
if hz:
|
||
axes[1].annotate(f'{hz:.0f} Hz 的理論間隔\n{1000.0 / hz:.1f} ms (虛線)', xy=(1000.0 / hz, 40), xytext=(2e-2, 40), fontsize=9, color=INK,
|
||
arrowprops=dict(arrowstyle='->', color=MUTED, linewidth=0.8))
|
||
|
||
fig.tight_layout(); fig.savefig(out, dpi=200); plt.close(fig)
|
||
print('已存', out)
|
||
for title, g in data:
|
||
big = g[g >= 0.1]
|
||
print(f'{title} : 事件 {len(g) + 1},中位數 {np.median(g):.3f} ms,= 0 {100 * (g <= 0).mean():.1f}%,< 0.01 ms {100 * (g < 0.01).mean():.1f}%,'
|
||
f'≥ 0.1 ms 的間隔 {len(big)} 個 (中位數 {np.median(big) if len(big) else 0:.2f} ms)')
|