Files
SirRoboGarage/tools/elm_bench/extract_ring.py
T
SirStone 16c71c527a tools/elm_bench: ring label experiment — the ring label is NOT learnable
Gate question: can a ring-based label (a 2-D offset from the belief centre to
where a ray ring touches the enemy) be predicted from our own belief state?
extract_ring.py + bench_ring.nim answer it by MERGING the ring label into
samples_realistic.ndjson, so the ring label and the incumbent 1-D aim-error
label are scored on the SAME rows, the SAME features and the SAME round-group
folds. 8119 of 8676 DrussGT shot rows get a ring label.

Verdict: worse, not richer.

  * The spike's headline is an artifact. The belief is already accurate to
    under 3 px, so a belief-anchored ring touches the enemy on its FIRST ray
    step: ringK = 1.0000 for all 172723 extracted events. The "100% at power
    <= 1.5, 0.2% at power 3.0" pattern is just whether 1 * bulletSpeed fits
    inside the +-18 px belief-error ball. The literal ring label is the 1-tick
    belief extrapolation error, clipped to BotRadius.
  * Same-tick it scores better than the 1-D label (ELM/const 0.2628 vs 0.3629)
    but a single feature, beliefTgtLatVel, already gets -71.8 of the -73.7
    points: the model is re-deriving beliefTgtLatVel * age / beliefDist, i.e.
    its own inputs.
  * Under --prev it collapses to ratio 0.9819 (-1.8%). It depends MORE on the
    same-tick assumption than the 1-D label (-63.7% -> -1.0%), not less.
  * Repaired (--kintercept: k = round(believed range / bullet speed), mean k 42,
    no clipping, 60 px spread) the label is well posed and completely
    unpredictable: best feature +0.5%, best ELM -0.4%, best |corr| 0.09.

So: the belief-extrapolation error at intercept time is not a function of what
we believed, it is the opponent's unmodelled acceleration. Do not ship a ring
label. common_libs/guns/waveelm.nim is the right shape for the same idea and
is a different thing: it fires the ring from the SHOOTER, so the ring measures
an interception radius and bearing and the ELM learns a bias correction to it.
2026-10-05 22:59:41 +02:00

187 lines
7.6 KiB
Python

#!/usr/bin/env python3
"""Extract RING labels for every scan tick per enemy.
The ring (tools/ring_spike/spike.py) fires N rays simultaneously from the
shooter's BELIEF centre at bullet speed and takes the first contact with the
enemy circle. The label is the 2-D offset between that contact's enemy position
and the belief centre, dead-reckoned to the CONTACT tick:
Pstar = enemy TRUE position at tick fire+k (observer truth)
C = belief centre dead-reckoned to fire+k (what we believed then)
R = Pstar - C (px, the ring label)
decomposed in the shooter's frame at fire time:
radial = R . u (u = unit bearing C-S) range error
lateral = R . n (n = left of u) aim error
label = atan2(lateral, beliefDist) radians -- SAME UNITS AND SIGN
as the incumbent 1-D aim-error label, so the two are comparable
row-for-row.
Belief reconstruction and ring geometry are imported from spike.py (one
definition, no drift). Default is same-tick semantics (fire_tick = scan tick,
last scan with turn <= fire_tick), matching extract_realistic.py's default;
--prev is the strictly-prior variant (fire_tick = scan tick + 1, last scan with
turn < fire_tick), matching extract_realistic.py --prev.
usage: extract_ring.py [OUT.ndjson] [ROOT] [--prev] [--base FILE]
--base FILE merge into an existing samples_*.ndjson instead of emitting a
bare side table: every base row keeps its own features and
gains ringK/ringLat/ringRad/ringLatAng, `label` becomes the
ring label and `label1d` keeps the incumbent aim error.
"""
import glob, gzip, json, math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(REPO0 := os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")),
"tools", "ring_spike"))
from spike import collect, ring_contact, BOT_RADIUS
REPO = REPO0
def wrap(a):
while a > math.pi:
a -= TAU
while a < -math.pi:
a += TAU
return a
TAU = 2 * math.pi
def belief_centre(hist, ft, prev):
"""Same belief as extract_realistic.py: last two usable scans, then
dead-reckon with the two-point velocity to `ft`. Returns (cx, cy, age)."""
use = [h for h in hist if (h[0] < ft if prev else h[0] <= ft)]
if len(use) < 2:
return None
(t1, x1, y1), (t0, x0, y0) = use[-1], use[-2]
gap = t1 - t0
if gap <= 0:
return None
age = ft - t1
if age < 0:
return None
return (x1 + (x1 - x0) / gap * age, y1 + (y1 - y0) / gap * age, age)
def extract(path, tag, prev, spd, rays, rng, out, kint=False):
scans, true, names = collect(path)
n = 0
for rnd in sorted({k[0] for k in scans}):
bots = sorted({k[1] for k in scans if k[0] == rnd} |
{k[2] for k in scans if k[0] == rnd})
for s in bots:
for t in bots:
if s == t:
continue
h = scans.get((rnd, s, t), [])
if len(h) < 2:
continue
track = {turn: xy for (rr, bid, turn), xy in true.items()
if rr == rnd and bid == t}
for (st, _, _) in h:
ft = st + 1 if prev else st
bc = belief_centre(h, ft, prev)
if bc is None:
continue
Sp = true.get((rnd, s, ft))
if Sp is None:
continue
res = ring_contact((bc[0], bc[1]), track, ft, spd, rays, rng)
if res is None:
continue
_, k = res
Pstar = track.get(ft + k)
if Pstar is None:
continue
los = math.atan2(bc[1] - Sp[1], bc[0] - Sp[0])
de = math.hypot(bc[0] - Sp[0], bc[1] - Sp[1])
if kint:
# INTENDED ring tick: the bullet flight time, i.e. the tick
# at which a shot aimed at the belief would land. Fully
# observable (round(believed range / bullet speed)); used
# because the literal contact search degenerates to k=1
# (see README: the belief is already within BotRadius of
# the enemy, so ray step 1 always "hits").
k = max(1, int(round(de / spd)))
Pstar = track.get(ft + k)
if Pstar is None:
continue
ux, uy = math.cos(los), math.sin(los)
nx, ny = -uy, ux
rx, ry = Pstar[0] - bc[0], Pstar[1] - bc[1]
lat = rx * nx + ry * ny
rad = rx * ux + ry * uy
out.write(json.dumps({
"group": f"{tag}:{rnd}", "round": rnd, "tick": ft,
"shooter": names.get(s, str(s)),
"target": names.get(t, str(t)),
"ringK": k, "ringLat": lat, "ringRad": rad,
"ringMag": math.hypot(rx, ry),
"ringLatAng": math.atan2(lat, max(de, 1.0)),
"ringRadAng": math.atan2(rad, max(de, 1.0)),
"ringDist": de, "ringAge": bc[2],
}) + "\n")
n += 1
return n
def main():
here = os.path.dirname(os.path.abspath(__file__))
args = [a for a in sys.argv[1:] if not a.startswith("--")]
prev = "--prev" in sys.argv
kint = "--kintercept" in sys.argv
base = None
if "--base" in sys.argv:
base = sys.argv[sys.argv.index("--base") + 1]
args = [a for a in args if a != base]
dest = os.path.join(here, args[0] if args else "ring.ndjson")
root = os.path.abspath(args[1]) if len(args) > 1 else os.path.join(REPO, "data", "drussgt_raw")
spd = 10.0 # bullet power 1.0 -> 10 px/tick; spike: <=1.5 reaches 100%
rays = 360
rng = 800.0
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, prev, spd, rays, rng, out, kint)
total += k
print(f"{tag}/{os.path.basename(f)}: {k} ring contacts")
print("TOTAL", total, "->", dest)
if base:
bp = os.path.join(here, base)
side = {}
for line in open(dest):
j = json.loads(line)
side[(j["group"], j["round"], j["tick"], j["shooter"], j["target"])] = j
merged = os.path.join(here, dest + ".merged")
hit = 0
n = 0
with open(bp) as src, open(merged, "w") as out:
for line in src:
if not line.strip():
continue
j = json.loads(line)
key = (j["group"], j["round"], j["tick"], j["shooter"], j["target"])
r = side.get(key)
if r is None:
continue
hit += 1
n += 1
j["label1d"] = j["label"]
j["label"] = r["ringLatAng"]
for f in ("ringK", "ringLat", "ringRad", "ringMag",
"ringLatAng", "ringRadAng", "ringDist"):
j[f] = r[f]
out.write(json.dumps(j) + "\n")
print(f"MERGED {n} of {sum(1 for _ in open(bp))} base rows -> {merged}")
if __name__ == "__main__":
main()