Files
2026-12-02 02:58:04 +08:00

254 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""時間窗切法、手工特徵(向量化)、序列張量。
- 窗以毫秒定義:每個瞄準片段 (t_start, t_end] 內,w0 = t_start + k·W/2,要求 w0 + W ≤ t_end,
片段短於 W 就丟棄。窗內的列 = t ∈ (w0, w0+W](與幀區間 (t_{f-1}, t_f] 同一個慣例)。
- 三組共用同一批窗(窗只由 segments.csv 決定)。
- 只有 MODEL_INPUT_COLS 的欄位會進到特徵/張量。
"""
import numpy as np
import pandas as pd
from mtd_common import COMMON, GRID_TOL_FRAC, MODEL_INPUT_COLS, group_path
WINDOWS_MS = [8, 16, 33, 50, 100, 200, 300, 500, 1000, 2000]
_BIG = 1e5 # 每回合時間軸的位移量(秒),讓整份資料可以一次 searchsorted
def load_segments():
return pd.read_csv(COMMON / 'segments.csv')
def load_rounds():
return pd.read_csv(COMMON / 'rounds.csv')
def round_code(player, rnd):
return np.asarray(player, dtype=np.int64) * 10000 + np.asarray(rnd, dtype=np.int64)
def code_player(code):
return np.asarray(code, dtype=np.int64) // 10000
def make_windows(segs, W_ms, min_seg_ms=None):
"""回傳窗表:player, round, seg, cheat, strength, w0, w1(秒)。"""
s = segs if min_seg_ms is None else segs[segs.duration_ms >= min_seg_ms]
d = s.duration_ms.to_numpy()
stride = W_ms / 2.0
n = np.where(d >= W_ms, np.floor((d - W_ms) / stride + 1e-9) + 1, 0).astype(np.int64)
rep = np.repeat(np.arange(len(s)), n)
k = np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)
w0 = s.t_start.to_numpy()[rep] + k * stride / 1000.0
out = pd.DataFrame({c: s[c].to_numpy()[rep] for c in ('player', 'round', 'seg', 'cheat', 'strength')})
out['w0'] = w0
out['w1'] = w0 + W_ms / 1000.0
return out
class GroupRows:
"""一組資料的列,依 (回合, t) 排序,方便一次切出所有窗。"""
def __init__(self, key, units='deg', rounds=None):
cols = ['player', 'round', 't', 'dx', 'dy', 'dx_deg', 'dy_deg', 'left']
assert set(cols) - {'player', 'round'} <= MODEL_INPUT_COLS
df = pd.read_csv(group_path(key), usecols=cols)
code = round_code(df.player, df['round'])
order = np.lexsort((df.t.to_numpy(), code))
df = df.iloc[order].reset_index(drop=True)
self.code = code[order]
uniq, self.rank = np.unique(self.code, return_inverse=True)
self.code_rank = dict(zip(uniq.tolist(), range(len(uniq))))
self.t = df.t.to_numpy()
self.key = self.rank * _BIG + self.t
if units == 'deg':
self.x, self.y = df.dx_deg.to_numpy(), df.dy_deg.to_numpy()
self.unit_scale = 0.02 # 序列模型 signed-log 的尺度(約一個 count 的角度)
else:
self.x, self.y = df.dx.to_numpy().astype(float), df.dy.to_numpy().astype(float)
self.unit_scale = 1.0
self.cx, self.cy = df.dx.to_numpy(), df.dy.to_numpy()
self.left = df.left.to_numpy().astype(float)
rounds = rounds if rounds is not None else load_rounds()
# 輪詢週期是裝置屬性(反作弊可由回報流估得),用來算間隔落在格點上的比例
per = dict(zip(round_code(rounds.player, rounds['round']).tolist(), rounds.poll_period_ms.to_numpy() / 1000))
self.period_by_code = per
def slice(self, wins):
"""回傳 Slice:每個窗的 [start, end) 與攤平的列索引。"""
rank = np.array([self.code_rank.get(c, -1) for c in round_code(wins.player, wins['round']).tolist()])
valid = rank >= 0
k0 = rank * _BIG + wins.w0.to_numpy()
k1 = rank * _BIG + wins.w1.to_numpy()
start = np.searchsorted(self.key, k0, side='right')
end = np.searchsorted(self.key, k1, side='right')
end = np.where(valid, end, start)
return Slice(self, wins, start, end)
class Slice:
def __init__(self, rows, wins, start, end):
self.rows, self.wins = rows, wins
self.n = (end - start).astype(np.int64)
self.nw = len(wins)
off = np.cumsum(self.n) - self.n
self.win_id = np.repeat(np.arange(self.nw), self.n)
self.pos = np.arange(self.n.sum()) - np.repeat(off, self.n)
self.idx = self.pos + np.repeat(start, self.n)
self.off = off
t = rows.t[self.idx]
prev_t = np.where(self.pos > 0, rows.t[np.maximum(self.idx - 1, 0)], wins.w0.to_numpy()[self.win_id])
self.gap = t - prev_t # 第一列 = t - w0
self.t = t
self.period = np.array([rows.period_by_code.get(c, 0.008)
for c in round_code(wins.player, wins['round']).tolist()])
def _segsum(win_id, v, nw):
return np.bincount(win_id, weights=v, minlength=nw)
def _segreduce(ufunc, v, sl, fill):
out = np.full(sl.nw, fill, dtype=float)
ne = sl.n > 0
if ne.any() and len(v):
out[ne] = ufunc.reduceat(v, sl.off[ne])
return out
def window_features(sl, use_dt=True):
"""每個窗的手工特徵(DataFrame)。時間類特徵以 't_' 開頭,關閉 Δt 時一起拿掉。"""
r, w, nw = sl.rows, sl.win_id, sl.nw
W = (sl.wins.w1 - sl.wins.w0).to_numpy()
x, y = r.x[sl.idx], r.y[sl.idx]
cx, cy = r.cx[sl.idx], r.cy[sl.idx]
left = r.left[sl.idx]
m = np.hypot(x, y)
n = sl.n.astype(float)
nz = np.maximum(n, 1)
F = {}
F['n_rows'] = n
sx, sy = _segsum(w, x, nw), _segsum(w, y, nw)
F['sum_x'], F['sum_y'] = sx, sy
path = _segsum(w, m, nw)
F['path'] = path
F['net'] = np.hypot(sx, sy)
F['straight'] = np.where(path > 0, F['net'] / np.maximum(path, 1e-12), 0)
F['mean_m'] = path / nz
for name, v in (('x', x), ('y', y), ('m', m)):
mu = _segsum(w, v, nw) / nz
F[f'std_{name}'] = np.sqrt(np.maximum(_segsum(w, v * v, nw) / nz - mu * mu, 0))
F['max_abs_x'] = _segreduce(np.maximum, np.abs(x), sl, 0)
F['max_abs_y'] = _segreduce(np.maximum, np.abs(y), sl, 0)
F['max_m'] = _segreduce(np.maximum, m, sl, 0)
zero = (cx == 0) & (cy == 0)
one = (np.maximum(np.abs(cx), np.abs(cy)) == 1)
F['frac_zero'] = _segsum(w, zero.astype(float), nw) / nz
F['frac_one'] = _segsum(w, one.astype(float), nw) / nz
F['frac_left'] = _segsum(w, left, nw) / nz
# 相鄰列的差(不用時間)
has_prev = sl.pos > 0
px = np.where(has_prev, r.x[np.maximum(sl.idx - 1, 0)], 0)
py = np.where(has_prev, r.y[np.maximum(sl.idx - 1, 0)], 0)
dd = np.where(has_prev, np.hypot(x - px, y - py), 0)
npair = np.maximum(_segsum(w, has_prev.astype(float), nw), 1)
F['mean_dd'] = _segsum(w, dd, nw) / npair
F['std_dd'] = np.sqrt(np.maximum(_segsum(w, dd * dd, nw) / npair - F['mean_dd'] ** 2, 0))
F['max_dd'] = _segreduce(np.maximum, dd, sl, 0)
pm = np.hypot(px, py)
both = has_prev & (m > 0) & (pm > 0)
cos = np.where(both, (x * px + y * py) / np.maximum(m * pm, 1e-12), 0)
nboth = _segsum(w, both.astype(float), nw)
F['mean_cos'] = np.where(nboth > 0, _segsum(w, cos, nw) / np.maximum(nboth, 1), 1)
F['frac_reverse'] = np.where(nboth > 0, _segsum(w, (both & (cos < 0)).astype(float), nw) / np.maximum(nboth, 1), 0)
# 列位移大小的 lag-1 相關(平均補償會讓同一幀內的列有共同偏移)
mm = _segsum(w, m, nw) / nz
dm = m - mm[w]
dpm = np.where(has_prev, pm - mm[w], 0)
cov = _segsum(w, np.where(has_prev, dm * dpm, 0), nw)
var = _segsum(w, dm * dm, nw)
F['ac1_m'] = np.where(var > 0, cov / np.maximum(var, 1e-12), 0)
if use_dt:
gap = sl.gap
P = sl.period[w]
F['t_rate'] = n / W
F['t_gap_mean'] = _segsum(w, gap, nw) / nz
F['t_gap_std'] = np.sqrt(np.maximum(_segsum(w, gap * gap, nw) / nz - F['t_gap_mean'] ** 2, 0))
F['t_gap_min'] = _segreduce(np.minimum, gap, sl, 0)
F['t_gap_max'] = _segreduce(np.maximum, gap, sl, 0)
resid = np.abs(gap - P * np.round(gap / P))
inner = sl.pos > 0
ninner = np.maximum(_segsum(w, inner.astype(float), nw), 1)
F['t_frac_offgrid'] = _segsum(w, (inner & (resid >= GRID_TOL_FRAC * P)).astype(float), nw) / ninner
F['t_mean_resid'] = _segsum(w, np.where(inner, resid, 0), nw) / ninner
F['t_frac_short'] = _segsum(w, (inner & (gap < 0.5 * P)).astype(float), nw) / ninner
F['t_frac_long'] = _segsum(w, (inner & (gap > 1.5 * P)).astype(float), nw) / ninner
first_gap = np.zeros(nw)
last_gap = W.copy()
ne = sl.n > 0
first_gap[ne] = sl.gap[sl.off[ne]]
last_gap[ne] = sl.wins.w1.to_numpy()[ne] - sl.t[sl.off[ne] + sl.n[ne] - 1]
F['t_first'] = first_gap / W
F['t_last'] = last_gap / W
v = m / np.maximum(gap, 1e-4)
F['t_speed_mean'] = _segsum(w, v, nw) / nz
F['t_speed_max'] = _segreduce(np.maximum, v, sl, 0)
pv = np.where(has_prev, pm / np.maximum(np.where(has_prev, sl.gap[np.maximum(np.arange(len(gap)) - 1, 0)], 1), 1e-4), 0)
acc = np.where(has_prev, np.abs(v - pv) / np.maximum(gap, 1e-4), 0)
F['t_acc_mean'] = _segsum(w, acc, nw) / npair
F['t_acc_max'] = _segreduce(np.maximum, acc, sl, 0)
return pd.DataFrame(F)
def context_features(ctx_rows, wins):
"""(--context 用)窗內遊戲情境的平均:準心誤差、目標可見度、後座力、玩家/敵人速度。"""
sl = ctx_rows.slice(wins)
w, nw = sl.win_id, sl.nw
nz = np.maximum(sl.n, 1)
F = {}
for name, arr in ctx_rows.extra.items():
F[f'ctx_{name}'] = _segsum(w, arr[sl.idx], nw) / nz
return pd.DataFrame(F)
class CtxRows(GroupRows):
"""frames_ctx.csv 當成「列」切窗(只給 --context 用)。"""
def __init__(self, rounds=None):
df = pd.read_csv(COMMON / 'frames_ctx.csv')
code = round_code(df.player, df['round'])
order = np.lexsort((df.t.to_numpy(), code))
df = df.iloc[order].reset_index(drop=True)
self.code = code[order]
uniq, self.rank = np.unique(self.code, return_inverse=True)
self.code_rank = dict(zip(uniq.tolist(), range(len(uniq))))
self.t = df.t.to_numpy()
self.key = self.rank * _BIG + self.t
self.extra = {
'err': np.hypot(df.truth_err_x, df.truth_err_y).to_numpy(),
'visible': df.truth_visible.to_numpy(),
'recoil_x': df.recoil_x.to_numpy(), 'recoil_y': df.recoil_y.to_numpy(),
'self_speed': np.hypot(df.vx, df.vz).to_numpy(), 'bot_speed': np.hypot(df.bvx, df.bvz).to_numpy(),
}
self.period_by_code = {}
def window_tensor(sl, use_dt=True, max_len=512):
"""序列張量 (N, L, C) 與 mask (N, L)、列數。通道:signed-log dx、dy、left、[間隔/週期]。"""
r = sl.rows
L = int(min(max(sl.n.max(initial=0), 1), max_len))
keep = sl.pos < L
w, p, idx = sl.win_id[keep], sl.pos[keep], sl.idx[keep]
C = 4 if use_dt else 3
X = np.zeros((sl.nw, L, C), dtype=np.float32)
M = np.zeros((sl.nw, L), dtype=np.float32)
s = r.unit_scale
X[w, p, 0] = np.sign(r.x[idx]) * np.log1p(np.abs(r.x[idx]) / s)
X[w, p, 1] = np.sign(r.y[idx]) * np.log1p(np.abs(r.y[idx]) / s)
X[w, p, 2] = r.left[idx]
if use_dt:
X[w, p, 3] = np.clip(sl.gap[keep] / sl.period[w], 0, 8)
M[w, p] = 1
logn = np.log1p(sl.n).astype(np.float32)
return X, M, logn