Files
SirStone 6d0dd987ca 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.
2026-10-05 22:42:39 +02:00

196 lines
7.6 KiB
Nim

#!/usr/bin/env nim c -r
# CROSS-OPPONENT generalization matrix.
#
# nim c -r --path:../../DevControlBot_garage/DevControlBot cross_opponent.nim -- \
# gen/DrussGT.ndjson gen/Dookious.ndjson ...
#
# For every ordered pair (A train, B test): train the ELM on ALL of A, test on
# ALL of B, 5 folds of B by round-group. Compare against
# - B's own constant baseline (its own training-fold mean)
# - B's self-trained ELM (train on B's other folds) = the per-opponent ceiling
# - pooled: train on A + B's other folds
# Feature set = the realistic ALL21 set from bench_realistic.nim.
import std/[math, os, strutils, strformat, algorithm, sequtils, tables, json]
import ../../DevControlBot_garage/DevControlBot/modules/ELM/elm
import std/[json, math, tables]
type
S = object
group: string
y: float64
dist: float64
age: float64
f: Table[string, float64]
proc load(path: string): seq[S] =
for line in lines(path):
if line.len == 0: continue
let j = parseJson(line)
var s: S
s.group = j["group"].getStr
s.y = j["label"].getFloat
s.dist = j["beliefDist"].getFloat
s.age = j["beliefScanAge"].getFloat
let age = max(s.age, 0.0)
let de = s.dist
let pred = j["beliefPredRelBearing"].getFloat
let rel = j["beliefRelBearing"].getFloat
s.f = ({
"dist": de / 1000.0,
"invDist": 1.0 / (1.0 + de / 100.0),
"sinRel": j["beliefSinRelBearing"].getFloat,
"cosRel": j["beliefCosRelBearing"].getFloat,
"tgtSpeed": j["beliefTgtSpeed"].getFloat / 10.0,
"bulletSpd": j["bulletSpeed"].getFloat / 20.0,
"scanAge": min(age, 30.0) / 30.0,
"logScan": math.ln(1.0 + min(age, 60.0)) / 4.0,
"everScanned": j["beliefEverScanned"].getFloat,
"scanGap": min(j["beliefScanGap"].getFloat, 30.0) / 30.0,
"sinPred": math.sin(pred),
"cosPred": math.cos(pred),
"predErr": j["beliefPredErr"].getFloat / PI,
"tgtLatVel": j["beliefTgtLatVel"].getFloat / 10.0,
"closing": j["beliefClosing"].getFloat / 10.0,
"losRate": j["beliefLosRate"].getFloat,
"tof": j["beliefTof"].getFloat / 30.0,
"gunHeat": j["gunHeat"].getFloat / 3.0,
"power": j["power"].getFloat / 3.0,
"ownSpeed": j["ownSpeed"].getFloat / 10.0,
"disp": j["beliefDisp"].getFloat / 100.0,
"round": j["round"].getFloat / 10.0,
"tick": j["tick"].getFloat / 1000.0,
"relSin": math.sin(rel),
}).toTable
result.add s
const NF = 5
let allSet = ["dist", "invDist", "sinRel", "cosRel", "tgtSpeed", "bulletSpd",
"scanAge", "logScan", "everScanned", "scanGap",
"sinPred", "cosPred", "predErr", "losRate", "tof", "closing",
"gunHeat", "power", "ownSpeed",
"disp", "round", "tick"].toSeq
proc vec(s: S): array[64, float64] =
for p, n in allSet: result[p] = s.f[n]
proc rmse(pred: seq[float64], te: seq[int], ys: seq[float64]): float64 =
var s2 = 0.0
for k, i in te:
let d = pred[k] - ys[i]
s2 += d * d
sqrt(s2 / float64(te.len))
type Corp = object
name: string
data: seq[S]
ys: seq[float64]
folds: array[NF, tuple[tr, te: seq[int]]]
var corps: seq[Corp]
for p in commandLineParams():
if not p.endsWith(".ndjson"): continue
let d = load(p)
var ys = newSeq[float64](d.len)
for i, s in d: ys[i] = s.y
var groups: seq[string]
for s in d:
if s.group notin groups: groups.add s.group
var fo = initTable[string, int]()
for gi, g in groups: fo[g] = gi mod NF
var c = Corp(name: p.splitFile().name.replace(".ndjson", ""), data: d, ys: ys)
for f in 0 ..< NF:
for i, s in d:
if fo[s.group] == f: c.folds[f].te.add i else: c.folds[f].tr.add i
corps.add c
echo fmt"corpora: {corps.len}, features {allSet.len}, H=128 lam=1e-2 decay=1.0"
for c in corps:
var m = 0.0
for y in c.ys: m += y
m /= float64(c.ys.len)
var sd = 0.0
for y in c.ys: sd += (y - m) * (y - m)
echo fmt" {c.name:<14} n={c.ys.len:<6} mean={m:+.4f} sd={sqrt(sd/float64(c.ys.len)):.4f} roundGroups={c.folds[0].tr.len + c.folds[0].te.len}"
echo "\n== per-opponent reference (5-fold by round-group on its own data) =="
echo " opponent constRMSE selfELM delta% (train on own other folds)"
for c in corps:
var pc, pe: seq[float64]
for f in 0 ..< NF:
var m = 0.0
for i in c.folds[f].tr: m += c.ys[i]
m /= float64(c.folds[f].tr.len)
var pr = newSeq[float64](c.folds[f].te.len)
for k in 0 ..< pr.len: pr[k] = m
pc.add rmse(pr, c.folds[f].te, c.ys)
let e2 = initElm(ElmConfig(inputDim: allSet.len, hiddenDim: 128, outputs: 1,
seed: 42, lambda: 1e-2, decay: 1.0, refitEvery: 0))
for i in c.folds[f].tr: train(e2, vec(c.data[i]).toOpenArray(0, allSet.len - 1), [c.ys[i]])
refit(e2)
var pr2 = newSeq[float64](c.folds[f].te.len)
for k, i in c.folds[f].te: pr2[k] = infer(e2, vec(c.data[i]).toOpenArray(0, allSet.len - 1))[0]
pe.add rmse(pr2, c.folds[f].te, c.ys)
let mc = pc.sum / float64(NF)
let me = pe.sum / float64(NF)
echo fmt" {c.name:<14} {mc:.4f} {me:.4f} {100*(me-mc)/mc:+.1f}%"
echo "\n== CROSS-OPPONENT MATRIX: train on row, test on column (held-out RMSE) =="
echo " rows = training corpus (ALL of it), cols = test corpus (its 5 folds pooled)"
var hdr = " train\\test "
for b in corps: hdr &= fmt"{b.name:>12}"
echo hdr
for a in corps:
var line = fmt" {a.name:<10}"
for b in corps:
var s2 = 0.0; var n = 0
for f in 0 ..< NF:
let e2 = initElm(ElmConfig(inputDim: allSet.len, hiddenDim: 128, outputs: 1,
seed: 42, lambda: 1e-2, decay: 1.0, refitEvery: 0))
for i, sa in a.data: train(e2, vec(sa).toOpenArray(0, allSet.len - 1), [a.ys[i]])
refit(e2)
for k, i in b.folds[f].te:
let d = infer(e2, vec(b.data[i]).toOpenArray(0, allSet.len - 1))[0] - b.ys[i]
s2 += d * d; inc n
line &= fmt"{sqrt(s2/float64(n)):>12.4f}"
echo line
echo "\n== same, but delta% vs THAT COLUMN's own constant baseline =="
echo " (positive = worse than just predicting the opponent's mean error)"
for a in corps:
var line = fmt" {a.name:<10}"
for b in corps:
var s2 = 0.0; var n = 0; var cst = 0.0
for f in 0 ..< NF:
var m = 0.0
for i in b.folds[f].tr: m += b.ys[i]
m /= float64(b.folds[f].tr.len)
let e2 = initElm(ElmConfig(inputDim: allSet.len, hiddenDim: 128, outputs: 1,
seed: 42, lambda: 1e-2, decay: 1.0, refitEvery: 0))
for i, sa in a.data: train(e2, vec(sa).toOpenArray(0, allSet.len - 1), [a.ys[i]])
refit(e2)
for k, i in b.folds[f].te:
let d = infer(e2, vec(b.data[i]).toOpenArray(0, allSet.len - 1))[0] - b.ys[i]
s2 += d * d; cst += (m - b.ys[i]) * (m - b.ys[i]); inc n
let r = sqrt(s2 / float64(n)); let rc = sqrt(cst / float64(n))
line &= fmt"{100.0*(r-rc)/rc:>11.1f}%"
echo line
echo "\n== POOLED: train on A + B's other folds, test on B's held-out fold =="
echo " train\\test " & corps.mapIt(fmt"{it.name:>12}").join(" ")
for a in corps:
var line = fmt" {a.name:<10}"
for b in corps:
var s2 = 0.0; var n = 0
for f in 0 ..< NF:
let e2 = initElm(ElmConfig(inputDim: allSet.len, hiddenDim: 128, outputs: 1,
seed: 42, lambda: 1e-2, decay: 1.0, refitEvery: 0))
for i, sa in a.data: train(e2, vec(sa).toOpenArray(0, allSet.len - 1), [a.ys[i]])
for i in b.folds[f].tr: train(e2, vec(b.data[i]).toOpenArray(0, allSet.len - 1), [b.ys[i]])
refit(e2)
for k, i in b.folds[f].te:
let d = infer(e2, vec(b.data[i]).toOpenArray(0, allSet.len - 1))[0] - b.ys[i]
s2 += d * d; inc n
line &= fmt"{sqrt(s2/float64(n)):>12.4f}"
echo line