151 lines
4.8 KiB
Python
151 lines
4.8 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""phase 2 共用:路徑、常數、讀取回合、外掛修正整數化、瞄準片段。
|
||
|
||
與 phase 1(phase_1/scripts_1/mtd_common.py)的差別:
|
||
- 4 份錄製(people_1–4),`player` = 錄製編號,`person` = 實際玩家(people_2 與 people_4 是同一人)。
|
||
- 只用正式回合(排除 isWarmup),回合編號沿用檔名的 roundIndex(可能缺號),順序看 planIndex。
|
||
- 衍生資料放 phase_2/derived/,結果放 phase_2/results/。
|
||
"""
|
||
import json
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent # phase_2/
|
||
DATA = ROOT / 'data'
|
||
DERIVED = ROOT / 'derived'
|
||
RESULTS = ROOT / 'results'
|
||
COMMON = DERIVED / 'common'
|
||
PHASE1_RESULTS = ROOT.parent / 'phase_1' / 'results_1'
|
||
|
||
PLAYERS = {1: 'people_1', 2: 'people_2', 3: 'people_3', 4: 'people_4'}
|
||
PERSON = {1: 'A', 2: 'B', 3: 'C', 4: 'B'} # 跨玩家測試以 person 為單位
|
||
PERSONS = ['A', 'B', 'C']
|
||
REC_LABEL = {1: 'A 125Hz 40FPS', 2: 'B 125Hz', 3: 'C 1000Hz', 4: 'B 1000Hz'}
|
||
|
||
# 組別 -> 檔名。'0' 是純手(只有真實回報,不加外掛修正),當負對照
|
||
GROUPS = {
|
||
'0': 'g0_hand.csv',
|
||
'1': 'g1_engine.csv',
|
||
'2': 'g2_insert.csv',
|
||
'3': 'g3_spread.csv',
|
||
'3f': 'g3f_frameinsert.csv',
|
||
}
|
||
|
||
DEG_PER_COUNT = 0.022
|
||
AIM_FOV_DEG = 15.0
|
||
SEG_BREAK_S = 0.05
|
||
SYNTH_SPAN_S = 0.040
|
||
GRID_TOL_FRAC = 1 / 16 # 間隔「在格點上」的容許誤差 = 週期 × 1/16(125 Hz 時 = 0.5 ms,與 phase 1 相同)
|
||
N_FOLDS = 4 # 以區塊切分:fold = blockIndex // 2
|
||
|
||
MODEL_INPUT_COLS = frozenset({'t', 'dt', 'dx', 'dy', 'dx_deg', 'dy_deg', 'left'})
|
||
ROW_COLS = ['player', 'round', 'cheat', 'strength', 'frame', 't', 'dt', 'dx', 'dy',
|
||
'dx_deg', 'dy_deg', 'left', 'src', 'aim', 'seg']
|
||
|
||
|
||
def utf8_stdout():
|
||
try:
|
||
sys.stdout.reconfigure(encoding='utf-8')
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def group_path(g):
|
||
return DERIVED / GROUPS[g]
|
||
|
||
|
||
def load_config(player, idx):
|
||
with open(DATA / PLAYERS[player] / f'config_{idx}.json', encoding='utf-8-sig') as fh:
|
||
return json.load(fh)
|
||
|
||
|
||
def iter_rounds(player, include_warmup=False):
|
||
"""依 planIndex 排序,回傳正式回合的 roundIndex(檔名編號)。"""
|
||
folder = DATA / PLAYERS[player]
|
||
out = []
|
||
for p in folder.glob('config_*.json'):
|
||
idx = int(p.stem.split('_')[1])
|
||
c = load_config(player, idx)
|
||
if c.get('isWarmup') and not include_warmup:
|
||
continue
|
||
out.append((c['planIndex'], idx))
|
||
return [idx for _, idx in sorted(out)]
|
||
|
||
|
||
def load_round(player, idx):
|
||
folder = DATA / PLAYERS[player]
|
||
cfg = load_config(player, idx)
|
||
frames = pd.read_csv(folder / f'frames_{idx}.csv')
|
||
mouse = pd.read_csv(folder / f'mouse_{idx}.csv')
|
||
events = pd.read_csv(folder / f'events_{idx}.csv')
|
||
return cfg, frames, mouse, events
|
||
|
||
|
||
def carry_round(x):
|
||
"""浮點序列 -> 整數序列,餘數累積到下一個值(外掛只能送整數 count)。"""
|
||
x = np.asarray(x, dtype=np.float64)
|
||
out = np.zeros(len(x), dtype=np.int64)
|
||
resid = np.zeros(len(x))
|
||
acc = 0.0
|
||
for i, v in enumerate(x):
|
||
acc += v
|
||
e = np.floor(acc + 0.5)
|
||
acc -= e
|
||
out[i] = int(e)
|
||
resid[i] = acc
|
||
return out, resid
|
||
|
||
|
||
def frame_prev_t(frames):
|
||
t = frames['t'].to_numpy()
|
||
prev = np.empty_like(t)
|
||
prev[0] = t[0] - frames['dt'].to_numpy()[0]
|
||
prev[1:] = t[:-1]
|
||
return prev
|
||
|
||
|
||
def aim_segments(frames):
|
||
"""瞄準旗標與片段(有無輔助同一條規則,不用 assist_engaged)。"""
|
||
t = frames['t'].to_numpy()
|
||
prev = frame_prev_t(frames)
|
||
err = np.hypot(frames['truth_err_x'].to_numpy(), frames['truth_err_y'].to_numpy())
|
||
aim = (frames['truth_detected'].to_numpy() == 1) & (err <= AIM_FOV_DEG)
|
||
gap_break = (t - prev) > SEG_BREAK_S
|
||
aim &= ~gap_break
|
||
seg = np.full(len(t), -1, dtype=np.int64)
|
||
segs = []
|
||
f = 0
|
||
n = len(t)
|
||
while f < n:
|
||
if not aim[f]:
|
||
f += 1
|
||
continue
|
||
s = f
|
||
while f + 1 < n and aim[f + 1]:
|
||
f += 1
|
||
segs.append((s, f))
|
||
seg[s:f + 1] = len(segs) - 1
|
||
f += 1
|
||
return aim, seg, segs
|
||
|
||
|
||
def to_deg(counts, sens):
|
||
return np.asarray(counts, dtype=np.float64) * DEG_PER_COUNT * sens
|
||
|
||
|
||
def md_table(df, floatfmt='{:.3f}'):
|
||
cols = list(df.columns)
|
||
lines = ['| ' + ' | '.join(str(c) for c in cols) + ' |', '|' + '---|' * len(cols)]
|
||
for r in df.itertuples(index=False):
|
||
cells = []
|
||
for v in r:
|
||
if isinstance(v, (float, np.floating)):
|
||
cells.append('' if np.isnan(v) else floatfmt.format(v))
|
||
else:
|
||
cells.append(str(v))
|
||
lines.append('| ' + ' | '.join(cells) + ' |')
|
||
return '\n'.join(lines)
|