Feasibility spike for a ring-based training label. N rays are fired simultaneously from the shooter's BELIEF centre at bullet speed; the label is a 2-D positional error from the belief centre to the contact point on the enemy circle (BotRadius 18 px). Belief is reconstructed with strict --prev semantics (a bot cannot act on a scan delivered at the end of tick T until T+1), so the spike already measures the label under the harder assumption. Also fixes a latent crash in ring_contact: the `last`-sample fallback was computed and then overwritten by an unconditional p[0], p[1], so any enemy track with a gap raised TypeError instead of falling back. Result is NOT what it first looks like -- see the ring-label section of tools/elm_bench/README.md. The contact search degenerates to k = 1 (the belief is already within BotRadius of the enemy), and the reported 100% hit rate at power <= 1.5 versus 0.2% at power 3.0 is an artifact of bullet speed versus the size of the belief error, not of ray geometry.
237 lines
10 KiB
Python
237 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""FEASIBILITY SPIKE: can a RING-based training label be extracted from the
|
|
corpora we ALREADY have?
|
|
|
|
Ring = N rays fired simultaneously from the shooter's BELIEF centre at bullet
|
|
speed; the first contact with the enemy circle (radius BotRadius=18px) is the
|
|
label: a 2-D positional-error vector from belief centre to hit point.
|
|
|
|
Belief is reconstructed exactly like tools/elm_bench/extract_realistic.py, but
|
|
STRICTLY from scans at turn < fire_tick (--prev semantics): a live bot cannot
|
|
act on a scan delivered at the end of tick T until tick T+1, so the fire tick
|
|
is scan_tick+1 and the belief is dead-reckoned `age` ticks from the prior scan.
|
|
|
|
Anchors: BELIEF (real) and TRUE (upper-bound reference).
|
|
Usage: spike.py [MAX_EVENTS_PER_FILE] [FILES...]
|
|
"""
|
|
import gzip, json, math, os, sys
|
|
def mean(x): return sum(x) / len(x)
|
|
def std(x):
|
|
if len(x) < 2: return 0.0
|
|
m = mean(x); return math.sqrt(sum((a - m) ** 2 for a in x) / (len(x) - 1))
|
|
def pct(x, p):
|
|
y = sorted(x); i = min(len(y) - 1, max(0, int(round(p / 100 * (len(y) - 1)))))
|
|
return y[i]
|
|
TAU = 2 * math.pi
|
|
|
|
BOT_RADIUS = 18.0 # common_libs/gun_harness/gun_interface.nim
|
|
REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
|
|
|
|
|
def read_ticks(path):
|
|
with gzip.open(path, "rt") as fh:
|
|
for line in fh:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
m = json.loads(line)
|
|
if m.get("type") == "TickEventForObserver":
|
|
yield m
|
|
|
|
|
|
def collect(path):
|
|
"""Per round: scans[(scanner,target)] = [(turn,x,y)], true[(bot,turn)] = xy,
|
|
names[botId] = bot name (samples_*.ndjson keys rows by NAME, not id)."""
|
|
scans, true, names = {}, {}, {}
|
|
for m in read_ticks(path):
|
|
rnd, turn = m["roundNumber"], 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"]))
|
|
for b in m["botStates"]:
|
|
true.setdefault((rnd, b["id"], turn), (b["x"], b["y"]))
|
|
names.setdefault(b["id"], b["name"])
|
|
return scans, true, names
|
|
|
|
|
|
def belief_at(hist, fire_tick):
|
|
"""extract_realistic.py belief, prev_only: last scan strictly before fire."""
|
|
prior = [h for h in hist if h[0] < fire_tick]
|
|
if len(prior) < 2:
|
|
return None
|
|
(t1, x1, y1), (t0, x0, y0) = prior[-1], prior[-2]
|
|
gap = t1 - t0
|
|
if gap <= 0:
|
|
return None
|
|
evx, evy = (x1 - x0) / gap, (y1 - y0) / gap
|
|
age = fire_tick - t1
|
|
return (x1 + evx * age, y1 + evy * age, evx, evy, age)
|
|
|
|
|
|
def ring_contact(centre, enemy_track, fire_tick, spd, rays, max_range):
|
|
"""Best (minimum-distance) ray/step contact with the enemy circle.
|
|
|
|
At a given step the distance from a ray point to the enemy is
|
|
d^2 = r^2 + E^2 - 2 r E cos(theta_i - phi), strictly increasing in the
|
|
angular deviation, so the closest ray to the enemy's bearing phi is the
|
|
minimiser -> exact, and O(steps) instead of O(steps*rays).
|
|
|
|
Returns (hit_point, k) or None.
|
|
"""
|
|
cx, cy = centre
|
|
step_ang = TAU / rays
|
|
kmax = int(max_range / spd)
|
|
best = None
|
|
last = enemy_track.get(fire_tick)
|
|
if last is None:
|
|
return None
|
|
for k in range(1, kmax + 1):
|
|
p = enemy_track.get(fire_tick + k)
|
|
if p is not None:
|
|
last = p
|
|
ex, ey = p if p is not None else last
|
|
dx, dy = ex - cx, ey - cy
|
|
E = math.hypot(dx, dy)
|
|
if E < 1e-9:
|
|
continue
|
|
phi = math.atan2(dy, dx)
|
|
# index of the ray nearest to phi
|
|
idx = int(round(phi / step_ang)) % rays
|
|
err = phi - idx * step_ang
|
|
r = k * spd
|
|
d = math.sqrt(max(0.0, r * r + E * E - 2 * r * E * math.cos(err)))
|
|
if d <= BOT_RADIUS and (best is None or d < best[0]):
|
|
th = idx * step_ang
|
|
best = (d, (cx + r * math.cos(th), cy + r * math.sin(th)), k)
|
|
if best is None:
|
|
return None
|
|
return best[1], best[2]
|
|
|
|
|
|
def main():
|
|
maxev = int(sys.argv[1]) if len(sys.argv) > 1 else 400
|
|
files = sys.argv[2:] or [os.path.join(REPO, "data/drussgt_raw/devcontrol",
|
|
"game-2026-10-04-21-28-48.battle.gz")]
|
|
POWERS = [0.5, 1.0, 1.5, 3.0]
|
|
RAYSETS = [90, 180, 360, 720]
|
|
RANGES = [400.0, 800.0]
|
|
|
|
events = [] # (fire_tick, belief, truepos, enemy_track, age)
|
|
for f in files:
|
|
scans, true, _names = collect(f)
|
|
rndset = sorted({k[0] for k in scans})
|
|
for rnd in rndset:
|
|
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), [])
|
|
track = {turn: xy for (rr, bid, turn), xy in true.items()
|
|
if rr == rnd and bid == t}
|
|
for (st, _, _) in h:
|
|
ft = st + 1 # act on the scan next tick
|
|
b = belief_at(h, ft)
|
|
tp = track.get(ft)
|
|
if b is None or tp is None:
|
|
continue
|
|
events.append((ft, b, tp, track, b[4]))
|
|
if len(events) >= maxev * len(files):
|
|
break
|
|
if len(events) >= maxev * len(files):
|
|
break
|
|
if len(events) >= maxev * len(files):
|
|
break
|
|
if len(events) >= maxev * len(files):
|
|
break
|
|
print(f"{os.path.basename(f)}: {len(events)} scan events pooled")
|
|
|
|
print(f"\n== scan events: {len(events)} ==")
|
|
ages = [e[4] for e in events]
|
|
print(f"belief age (ticks): mean={mean(ages):.2f} p50={pct(ages,50):.0f} "
|
|
f"p90={pct(ages,90):.0f} max={max(ages)}")
|
|
# belief error vs truth (the label magnitude we are trying to expose)
|
|
be = [math.dist((e[1][0], e[1][1]), e[2]) for e in events]
|
|
print(f"belief-vs-truth offset px: mean={mean(be):.2f} std={std(be):.2f} "
|
|
f"p50={pct(be,50):.2f} p90={pct(be,90):.2f} max={max(be):.2f}")
|
|
# engagement distance: from the SHOOTER's true pos (observer view, label-side only)
|
|
eng = []
|
|
for m in read_ticks(files[0]):
|
|
pass
|
|
|
|
rows = []
|
|
for anchor in ("BELIEF", "TRUE"):
|
|
for pw in POWERS:
|
|
spd = pw * 10.0
|
|
for rays in RAYSETS:
|
|
for rng in RANGES:
|
|
hits = 0
|
|
L1, L2, L3, L3n, ks = [], [], [], [], []
|
|
for (ft, b, tp, track, _a) in events:
|
|
c = (b[0], b[1]) if anchor == "BELIEF" else tp
|
|
res = ring_contact(c, track, ft, spd, rays, rng)
|
|
if res is None:
|
|
continue
|
|
hits += 1
|
|
H, k = res
|
|
ks.append(k)
|
|
Pstar = track.get(ft + k) # enemy TRUE pos at contact
|
|
if Pstar is None:
|
|
continue
|
|
# L1: literal design label -- hit point minus belief centre
|
|
L1.append(math.dist(H, c))
|
|
# L2: contact-point residual -- hit point minus true enemy centre
|
|
L2.append(math.dist(H, Pstar))
|
|
# L3: ring-exposed error -- belief dead-reckoned to contact
|
|
# tick vs the enemy's TRUE position at that tick
|
|
if anchor == "BELIEF":
|
|
# contact happens k TICKS after fire, not k*spd
|
|
bx = b[0] + b[2] * k
|
|
by = b[1] + b[3] * k
|
|
L3.append(math.dist((bx, by), Pstar))
|
|
if k <= 12:
|
|
L3n.append(math.dist((bx, by), Pstar))
|
|
def S(x):
|
|
return (mean(x) if x else 0.0, std(x) if x else 0.0,
|
|
pct(x, 50) if x else 0.0, pct(x, 90) if x else 0.0)
|
|
l1, l2, l3 = S(L1), S(L2), S(L3)
|
|
l3n = S(L3n)
|
|
rows.append((anchor, pw, rays, rng, hits / len(events), hits,
|
|
mean(ks) if ks else 0.0, l1, l2, l3, l3n))
|
|
|
|
print("\n== HIT RATE + LABEL DISTRIBUTIONS (px) ==")
|
|
print("L1 = hit_point - belief_centre (literal design label)")
|
|
print("L2 = hit_point - true_enemy_at_contact (contact-point residual)")
|
|
print("L3 = belief(dead-reckoned to contact) - true_enemy_at_contact (ring label)")
|
|
print("L3k<=12 = same, restricted to contacts within 12 ticks (belief still valid)")
|
|
print(f"{'anchor':7} {'pow':4} {'rays':5} {'range':6} {'hitrate':>8} {'kMean':>6} | "
|
|
f"{'L1mean':>7}{'L1std':>7} | {'L2mean':>7}{'L2std':>7} | {'L3mean':>7}{'L3std':>7}{'L3p90':>7} | {'L3k<=12':>7}{'sd':>7}")
|
|
for (a, pw, rays, rng, hr, n, km, l1, l2, l3, l3n) in rows:
|
|
print(f"{a:7} {pw:<4} {rays:<5} {rng:<6.0f} {hr*100:7.2f}% {km:6.2f} | "
|
|
f"{l1[0]:7.2f}{l1[1]:7.2f} | {l2[0]:7.2f}{l2[1]:7.2f} | "
|
|
f"{l3[0]:7.2f}{l3[1]:7.2f}{l3[2]:7.2f} | {l3n[0]:7.2f}{l3n[1]:7.2f}")
|
|
|
|
print("\n== 1-D AIM-ERROR LABEL COMPARISON (the incumbent label) ==")
|
|
sd = 1.1462
|
|
print(f" aim-error label: mean 0.1136 rad, std {sd} rad (circular; std>>pi/2 => pure noise)")
|
|
print(" translated to px of lateral miss at various engagement distances:")
|
|
for D in (200, 400, 600, 800):
|
|
print(f" dist {D:4d} px -> 1-sigma lateral {D*sd:7.1f} px, "
|
|
f"1-sigma angular {math.degrees(sd):6.1f} deg "
|
|
f"(BotRadius tolerance at {D}px = {math.degrees(math.atan(BOT_RADIUS/D)):5.2f} deg)")
|
|
|
|
print("\n== label yield ==")
|
|
for anchor in ("BELIEF", "TRUE"):
|
|
sub = [r for r in rows if r[0] == anchor and r[2] == 360]
|
|
if not sub:
|
|
continue
|
|
best = max(sub, key=lambda r: r[4])
|
|
print(f"{anchor}: best hitrate {best[4]*100:.2f}% at power {best[1]}, "
|
|
f"range {best[3]:.0f} -> {best[4]:.3f} labels per scan tick per enemy")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|