tools/elm_bench: aim-error ELM benchmark suite + findings
Extractors, benchmarks and analysis for "can we predict an opponent's aim error from our own belief state?". All labels come from BulletFiredEvents; all features come only from the shooter's own state and its ScannedBotEvent history (the target's true state is used for the label and never for a feature, verified by a ground-truth-poisoning re-extraction). extract.py / extract_realistic.py label + oracle features / realistic ones gen_analysis.py, analyse_realistic.py, audit_independent.py bench.nim, bench_realistic.nim, cross_opponent.nim, online.nim gen/*.ndjson the per-opponent sample tables README.md the write-up, ~1200 lines Headline: DrussGT applies about 13% of the correct lead, and that 13% is computable from one feature (beliefPredErr) as label ~ 0.8663*predErr + 0.0418. ELM ALL-21 pools to RMSE 0.4220 against a constant 1.1463 (-63%). The network is not the finding; the single linear term is. Cross-opponent, --prev leakage audit and an independent re-derivation are in the README. The top-level samples_realistic*.ndjson are byte-identical to gen/DrussGT* and are gitignored; gen/ is the authoritative copy.
This commit is contained in:
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract aim-error samples with ONLY shooter-observable features.
|
||||
|
||||
Same LABEL as extract.py (ground truth correction, unchanged), same samples
|
||||
(same BulletFiredEvents), but every feature is derived from what the shooter
|
||||
legitimately knows at fire time:
|
||||
|
||||
* its OWN true state at fire time (position, gun bearing, energy, gunHeat) --
|
||||
a bot always has this;
|
||||
* the ScannedBotEvent history it has received for the target: position,
|
||||
heading and speed at each scan tick. That is the real observation.
|
||||
|
||||
The target's true position/velocity at fire time is used ONLY for the label,
|
||||
never for a feature.
|
||||
|
||||
Output: samples_realistic.ndjson (same schema + belief_* fields).
|
||||
"""
|
||||
import glob, gzip, json, math, os, sys
|
||||
|
||||
TAU = 2 * math.pi
|
||||
|
||||
|
||||
def wrap(a):
|
||||
while a > math.pi:
|
||||
a -= TAU
|
||||
while a < -math.pi:
|
||||
a += TAU
|
||||
return a
|
||||
|
||||
|
||||
def extract(path, tag, out, prev_only=False):
|
||||
ticks = []
|
||||
with gzip.open(path, "rt") as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if line:
|
||||
m = json.loads(line)
|
||||
if m.get("type") == "TickEventForObserver":
|
||||
ticks.append(m)
|
||||
|
||||
pos = {} # (round, botId) -> true pos at previous tick (for the LABEL only)
|
||||
scans = {} # (round, scannerId, targetId) -> list of (turn, x, y, heading, speed)
|
||||
selfpos = {} # (round, botId) -> list of (turn, x, y) own track
|
||||
n = 0
|
||||
for m in ticks:
|
||||
rnd = m["roundNumber"]
|
||||
turn = m["turnNumber"]
|
||||
for ev in m.get("events", []):
|
||||
if ev["type"] == "ScannedBotEvent":
|
||||
scans.setdefault(
|
||||
(rnd, ev["scannedByBotId"], ev["scannedBotId"]), []
|
||||
).append((turn, ev["x"], ev["y"],
|
||||
math.radians(ev["direction"]), ev["speed"]))
|
||||
|
||||
bs = {b["id"]: b for b in m["botStates"]}
|
||||
for bid, b in bs.items():
|
||||
selfpos.setdefault((rnd, bid), []).append((turn, b["x"], b["y"]))
|
||||
|
||||
for e in [e for e in m.get("events", []) if e["type"] == "BulletFiredEvent"]:
|
||||
bu = e["bullet"]
|
||||
owner = bu["ownerId"]
|
||||
sb = bs.get(owner)
|
||||
if sb is None:
|
||||
continue
|
||||
tgt = [b for b in m["botStates"] if b["id"] != owner and b["energy"] > 0]
|
||||
if not tgt:
|
||||
continue
|
||||
tb = tgt[0]
|
||||
S = (sb["x"], sb["y"])
|
||||
T = (tb["x"], tb["y"])
|
||||
p0 = pos.get((rnd, tb["id"]))
|
||||
vel = (T[0] - p0[0], T[1] - p0[1]) if p0 else (0.0, 0.0)
|
||||
v = bu["power"] * 10.0
|
||||
d = math.dist(S, T)
|
||||
tf = d / v
|
||||
Tp = (T[0] + vel[0] * tf, T[1] + vel[1] * tf)
|
||||
d = math.dist(S, Tp)
|
||||
tf = d / v
|
||||
ideal = math.atan2(Tp[1] - S[1], Tp[0] - S[0])
|
||||
g = math.radians(bu["direction"])
|
||||
label = wrap(ideal - g)
|
||||
|
||||
# ---------------- shooter's belief ----------------
|
||||
hist = scans.get((rnd, owner, tb["id"]), [])
|
||||
myTrack = selfpos.get((rnd, owner), [])
|
||||
rec = {
|
||||
"group": f"{tag}:{rnd}",
|
||||
"round": rnd,
|
||||
"tick": turn,
|
||||
"shooter": sb["name"],
|
||||
"target": tb["name"],
|
||||
"label": label,
|
||||
# own true state (legitimately observable by the bot itself)
|
||||
"ownHeading": math.radians(sb["direction"]),
|
||||
"ownGunBearing": g,
|
||||
"ownSpeed": sb["speed"],
|
||||
"ownX": S[0], "ownY": S[1],
|
||||
"gunHeat": sb.get("gunHeat", 0.0),
|
||||
"power": bu["power"],
|
||||
"bulletSpeed": v,
|
||||
# oracle ones kept ONLY for reference in the scan-age analysis
|
||||
"oracleDist": d,
|
||||
"oracleRelBearing": wrap(ideal - math.radians(sb["direction"])),
|
||||
}
|
||||
|
||||
if not hist:
|
||||
rec.update({
|
||||
"beliefEverScanned": 0.0,
|
||||
"beliefScanAge": -1.0,
|
||||
"beliefRelBearing": 0.0,
|
||||
"beliefSinRelBearing": 0.0,
|
||||
"beliefCosRelBearing": 0.0,
|
||||
"beliefDist": 0.0,
|
||||
"beliefInvDist": 0.0,
|
||||
"beliefTgtSpeed": 0.0,
|
||||
"beliefTgtLatVel": 0.0,
|
||||
"beliefClosing": 0.0,
|
||||
"beliefLosRate": 0.0,
|
||||
"beliefTof": 0.0,
|
||||
"beliefPredRelBearing": 0.0,
|
||||
"beliefSinPredRelBearing": 0.0,
|
||||
"beliefCosPredRelBearing": 0.0,
|
||||
"beliefPredErr": 0.0,
|
||||
"beliefDisp": 0.0,
|
||||
"beliefScanGap": 0.0,
|
||||
})
|
||||
else:
|
||||
prior = [h for h in hist if h[0] < turn]
|
||||
# default: the latest scan, including one in the SAME tick as the
|
||||
# shot (a bot issues scan+fire together). --prev: strictly prior.
|
||||
histUse = prior if prev_only else hist
|
||||
turn_s, xs, ys, hs, ss = histUse[-1]
|
||||
age = float(turn - turn_s)
|
||||
rec["prevOnly"] = 1.0 if prior else 0.0
|
||||
rec["prevAge"] = age
|
||||
if len(hist) >= 2:
|
||||
t0, x0, y0, _, _ = hist[-2]
|
||||
gap = float(turn_s - t0)
|
||||
ev = ((xs - x0) / gap, (ys - y0) / gap) if gap > 0 else (0.0, 0.0)
|
||||
else:
|
||||
gap, ev = 0.0, (0.0, 0.0)
|
||||
# dead-reckoned target position at fire time
|
||||
ex, ey = xs + ev[0] * age, ys + ev[1] * age
|
||||
de = math.dist(S, (ex, ey))
|
||||
rel = wrap(math.atan2(ey - S[1], ex - S[0]) - rec["ownHeading"])
|
||||
los = math.atan2(ey - S[1], ex - S[0])
|
||||
sp = math.hypot(*ev)
|
||||
lat = -ev[0] * math.sin(los) + ev[1] * math.cos(los)
|
||||
rad = ev[0] * math.cos(los) + ev[1] * math.sin(los)
|
||||
tof = de / v
|
||||
px, py = ex + ev[0] * tof, ey + ev[1] * tof
|
||||
pred = wrap(math.atan2(py - S[1], px - S[0]) - rec["ownHeading"])
|
||||
predErr = wrap(pred - rel)
|
||||
# how far the shooter has itself moved since the scan
|
||||
disp = 0.0
|
||||
if myTrack and myTrack[-1][0] == turn:
|
||||
dxs, dys = S[0] - myTrack[-2][1], S[1] - myTrack[-2][2] \
|
||||
if len(myTrack) >= 2 else (0.0, 0.0)
|
||||
disp = math.hypot(dxs, dys)
|
||||
rec.update({
|
||||
"beliefEverScanned": 1.0,
|
||||
"beliefScanAge": age,
|
||||
"beliefRelBearing": rel,
|
||||
"beliefSinRelBearing": math.sin(rel),
|
||||
"beliefCosRelBearing": math.cos(rel),
|
||||
"beliefDist": de,
|
||||
"beliefInvDist": 1.0 / max(de, 1.0),
|
||||
"beliefTgtSpeed": sp,
|
||||
"beliefTgtLatVel": lat,
|
||||
"beliefClosing": -rad,
|
||||
"beliefLosRate": lat / max(de, 1.0),
|
||||
"beliefTof": tof,
|
||||
"beliefPredRelBearing": pred,
|
||||
"beliefSinPredRelBearing": math.sin(pred),
|
||||
"beliefCosPredRelBearing": math.cos(pred),
|
||||
"beliefPredErr": predErr,
|
||||
"beliefDisp": disp,
|
||||
"beliefScanGap": gap,
|
||||
})
|
||||
out.write(json.dumps(rec) + "\n")
|
||||
n += 1
|
||||
|
||||
for bid, b in bs.items():
|
||||
pos[(rnd, bid)] = (b["x"], b["y"])
|
||||
return n
|
||||
|
||||
|
||||
def main():
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
repo = os.path.abspath(os.path.join(here, "..", ".."))
|
||||
# usage: extract_realistic.py [OUT.ndjson] [ROOT] [--prev]
|
||||
# ROOT is any directory searched recursively for *.battle.gz; each capture's
|
||||
# tag is its path relative to ROOT (so round-groups stay opponent-separated).
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
prev_only = "--prev" in sys.argv
|
||||
dest = os.path.join(here, args[0] if args else "samples_realistic.ndjson")
|
||||
root = os.path.abspath(args[1]) if len(args) > 1 else os.path.join(repo, "data", "drussgt_raw")
|
||||
files = sorted(glob.glob(os.path.join(root, "**", "*.battle.gz"), recursive=True))
|
||||
total = 0
|
||||
with open(dest, "w") as out:
|
||||
for f in files:
|
||||
tag = os.path.relpath(os.path.dirname(f), root).replace(os.sep, ":")
|
||||
k = extract(f, tag, out, prev_only)
|
||||
print(f"{tag}/{os.path.basename(f)}: {k} shots")
|
||||
total += k
|
||||
print("TOTAL", total, "->", dest)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user