guns/elm.nim online sequential ELM (ridge/RLS), fixed random
hidden layer, one pass, no backprop
guns/waveelm.nim the WaveElm gun: a simulated omnidirectional expanding
ring of probes fired from the SHOOTER, where the ELM
learns a BIAS CORRECTION to the ring's reconstructed
position (predicting the position outright was measured
and refuted: it collapses on abrupt/burst movement)
guns/gun_knowledge.nim GUNK: a learned additive angular residual on top of
the self-consistent lead forecast. Only answers "which
absolute gun direction", nothing else
guns/docs/ the open-access OS-ELM / ELM reference set plus
fetch_papers.sh, which re-downloads it idempotently
Plus the matching test and measurement harnesses (test_waveelm*, test_elm,
test_gun_knowledge, test_knowledge_registration, gk_aim_probe,
measure_gk_{residual,virtual}.py) and the docs README with the citations.
1090 lines
49 KiB
Python
1090 lines
49 KiB
Python
#!/usr/bin/env python3
|
|
"""MEASURE: does gun_knowledge.nim's learned additive ANGULAR RESIDUAL beat the
|
|
bare `lead_forecast.forecastLinear` base, offline, on the recorded corpus?
|
|
|
|
NO bot, NO server, NO battle. Pure replay of /tmp/tfil_ab2/out/.
|
|
|
|
WHAT IS SIMULATED
|
|
-----------------
|
|
For every shot WE fire (ModularBot, the `s*` track in these tr-bridge corpora)
|
|
the script has, from the recorded truth:
|
|
|
|
O tank centre at the fire tick (== the bullet line origin)
|
|
p, v fired power, bullet speed v = 20 - 3p
|
|
E(k) the enemy's TRUE recorded position k ticks later
|
|
los bearing O -> E(0)
|
|
base `forecastLinear`'s predicted intercept bearing, expressed as a LEAD
|
|
over the LOS exactly the way `guns/lead_gain` / `gun_knowledge`
|
|
do it: base_lead = fc.bearing - los
|
|
required the lead a perfect gun would need: bearing O -> E(k*) minus los,
|
|
where k* is the AIM-INDEPENDENT interception tick (first k with
|
|
|E(k) - O| <= v*k -- it depends only on the truth and the bullet
|
|
speed, never on our aim, so it is not circular)
|
|
|
|
aim(b) los + base_lead + binCentre(b), for each of the 32 residual bins
|
|
hit(b) min over k of |E(k) - (O + v*k*u(aim(b)))| <= BOT_RADIUS(18)
|
|
|
|
err_base wrap(base_lead - required)
|
|
err_corr wrap(base_lead + residual - required)
|
|
|
|
The residual is learned the way `gun_knowledge` learns it -- a 3840-row table
|
|
keyed by keyOf(), argmax over 32 bins with the GK_MIN_BIN_HITS=3 floor and the
|
|
tie-break toward the centre bin -- but with TWO learning regimes, because they
|
|
answer different questions:
|
|
|
|
FULLINFO every bin is tried on every training shot, so every bin gets a hit
|
|
count. This is the CEILING of what the table could learn if the bot
|
|
explored. It is NOT what the shipped code does.
|
|
DEFECT the module EXACTLY AS IT SHIPPED BEFORE THE FIX -- 32 uniform cells
|
|
tiling [-30,+30] with bin 0 at -29.06 deg, and
|
|
`update(f, -1, hit)` clamping -1 into it. This is the regime that
|
|
measured 36.46 deg / 3.46% in the 450+ band, i.e. worse than doing
|
|
nothing.
|
|
FAITHFUL the module AS IT SHIPS NOW: `aim` starts at residual 0 and
|
|
`update` files every below-threshold shot under GK_NULL_BIN, whose
|
|
centre is exactly 0 deg. No exploration, so it never corrects.
|
|
|
|
SPLIT: held out BY BATTLE (never by shot -- shots inside one battle are
|
|
correlated through the enemy's state). Train on runs 1-7 of every arm, test on
|
|
runs 8-14, then swap and pool the test predictions (2-fold, every shot is
|
|
tested exactly once).
|
|
|
|
CAVEATS STATED IN THE OUTPUT, NOT HIDDEN:
|
|
* the corpus is CLOSED LOOP (the enemy dodges our real bullets) so an offline
|
|
counterfactual hit rate ranks the gun, it does not predict a live A/B
|
|
(docs/offline_harness_trust.md);
|
|
* gun heat is not recorded in the corpus -> the heat feature is pinned to
|
|
bin 0 (the key is therefore coarser than in a live battle, never finer);
|
|
* turn/trend come from the recorded per-tick TRUTH (a 1-tick gap), i.e. the
|
|
best case. `gkUnknown` behaviour is measured separately below, from the
|
|
recorded live scan cadence.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import collections
|
|
import glob
|
|
import json
|
|
import math
|
|
import os
|
|
import statistics
|
|
import subprocess
|
|
import sys
|
|
|
|
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
ROOT = sys.argv[1] if len(sys.argv) > 1 else "/tmp/tfil_ab2/out"
|
|
RAW = [] # every aligned US shot, before the truth filters
|
|
US_SIDE = "s" # tr-bridge: subject=DrussGT is e*, adversary=us is s*
|
|
BOT_RADIUS = 18.0
|
|
SPEED_A, SPEED_B = 20.0, 3.0
|
|
MAX_FLIGHT = 220
|
|
ARENA_W, ARENA_H = 800.0, 600.0
|
|
|
|
# lead_gain.nim LG_BAND_LO / LG_BAND_HI
|
|
BAND_LO = [0.0, 100.0, 200.0, 300.0, 450.0]
|
|
BAND_HI = [100.0, 200.0, 300.0, 450.0, 1.0e18]
|
|
BAND_LAB = ["0-100", "100-200", "200-300", "300-450", "450+"]
|
|
|
|
# gun_knowledge.nim
|
|
GK_NBINS = 32
|
|
GK_NULL_BIN = 0
|
|
GK_RES_LO, GK_RES_HI = -30.0, 30.0
|
|
GK_RES_W = 60.0 / 32.0 # 1.875, the step BELOW the null
|
|
GK_RES_POS_W = 2.0 # 2.000, the step ABOVE the null
|
|
GK_GLOBAL_MIN_ATTEMPTS = 5
|
|
GK_MIN_BIN_HITS = 3
|
|
GK_WALL_MARGIN = 60.0
|
|
GK_TURN_DEAD = 2.0
|
|
GK_TREND_DEAD = 0.05
|
|
GK_GAP_MAX = 6 # measured mean inter-scan gap 4.75
|
|
GK_NKEYS = 3840
|
|
RADIAL_WINDOW = 32
|
|
VEL_WINDOW = 16
|
|
|
|
|
|
def bin_centre(b):
|
|
"""Port of gun_knowledge.binCentre: bin 0 is the 0 deg NULL residual."""
|
|
if b == GK_NULL_BIN:
|
|
return 0.0
|
|
if b <= 16:
|
|
return -GK_RES_W * b
|
|
return GK_RES_POS_W * (b - 16)
|
|
|
|
|
|
CENTRE = [bin_centre(b) for b in range(GK_NBINS)]
|
|
|
|
# The 5-candidate residual layout used by the SIZE SWEEP below: bin 0 is the
|
|
# same 0 deg NULL, the other four are +/-15 and +/-30 deg (the ends of the same
|
|
# GK_RES_LO/HI span the 32-bin table covers). n == 32 keeps the production
|
|
# layout above, byte for byte.
|
|
def alt_centres(n):
|
|
if n == GK_NBINS:
|
|
return CENTRE
|
|
pairs = (n - 1) // 2
|
|
out = [0.0]
|
|
for i in range(1, pairs + 1):
|
|
m = GK_RES_HI * i / pairs
|
|
out.append(-m)
|
|
out.append(m)
|
|
return out[:n]
|
|
|
|
|
|
ALT5 = alt_centres(5)
|
|
COS_B = [math.cos(math.radians(c)) for c in CENTRE]
|
|
SIN_B = [math.sin(math.radians(c)) for c in CENTRE]
|
|
|
|
# THE LAYOUT AS IT WAS SHIPPED BEFORE THE FIX, kept so the DEFECT regime below
|
|
# can reproduce the 36.46 deg / 3.46% number from THIS script: 32 uniform cells
|
|
# tiling [-30, +30], so bin 0 sat at -29.06 deg instead of 0 deg, and
|
|
# `update(f, -1, hit)` clamped -1 into that bin.
|
|
GK_RES_W_OLD = (30.0 - -30.0) / GK_NBINS
|
|
CENTRE_OLD = [-30.0 + (b + 0.5) * GK_RES_W_OLD for b in range(GK_NBINS)]
|
|
|
|
|
|
def best_residual_old(row):
|
|
"""Port of the PRE-FIX bestResidual: tie-break toward the middle INDEX 16."""
|
|
best_b, best_h = -1, 0
|
|
for b in range(GK_NBINS):
|
|
h = row[b]
|
|
if h < GK_MIN_BIN_HITS:
|
|
continue
|
|
if h > best_h or (h == best_h and best_b >= 0 and
|
|
abs(b - GK_NBINS // 2) < abs(best_b - GK_NBINS // 2)):
|
|
best_h, best_b = h, b
|
|
return (0.0, -1) if best_b < 0 else (CENTRE_OLD[best_b], best_b)
|
|
|
|
|
|
def wrap180(x):
|
|
x = (x + 180.0) % 360.0 - 180.0
|
|
return x + 360.0 if x <= -180.0 else x
|
|
|
|
|
|
def band_of(r):
|
|
for i in range(len(BAND_LO)):
|
|
if BAND_LO[i] <= r < BAND_HI[i]:
|
|
return i
|
|
return len(BAND_LO) - 1
|
|
|
|
|
|
def q4(v):
|
|
return 0 if v < 0.25 else 1 if v < 0.5 else 2 if v < 0.75 else 3
|
|
|
|
|
|
def space_of(ex, ey, sx, sy):
|
|
gL, gR, gB, gT = ex, ARENA_W - ex, ey, ARENA_H - ey
|
|
sL, sR, sB, sT = sx, ARENA_W - sx, sy, ARENA_H - sy
|
|
n = 0
|
|
vert = horz = False
|
|
for gE, gS, isv in ((gL, sL, True), (gR, sR, True), (gB, sB, False), (gT, sT, False)):
|
|
if gE <= GK_WALL_MARGIN and gE < gS:
|
|
n += 1
|
|
if isv:
|
|
vert = True
|
|
else:
|
|
horz = True
|
|
return 0 if n == 0 else 1 if n == 1 else (2 if (vert and horz) else 1)
|
|
|
|
|
|
def forecast_linear(ex, ey, eh, es, sx, sy, v):
|
|
"""Verbatim port of guns/lead_forecast.forecastLinear. Returns (px, py)."""
|
|
d0 = math.hypot(ex - sx, ey - sy)
|
|
hr = math.radians(eh)
|
|
t = d0 / v if v > 0 else 0.0
|
|
px, py = ex, ey
|
|
for _ in range(5):
|
|
px = ex + math.cos(hr) * es * t
|
|
py = ey + math.sin(hr) * es * t
|
|
if v > 0:
|
|
t = math.hypot(px - sx, py - sy) / v
|
|
return px, py
|
|
|
|
|
|
def production_base(ex, ey, eh, es, sx, sy, v):
|
|
"""THE PRODUCTION AIM, as `guns/gun_knowledge.nim` computes it today:
|
|
|
|
forecastBase(f, gunHeading) = normalize180(radToDeg(forecastLinear(...).bearing))
|
|
aim = clamp(base + residual, -180, 180)
|
|
predict() = self + gkDist * (cos, sin)(aim)
|
|
|
|
The bot's own heading is NOT an input: the base is already an absolute
|
|
world bearing, and the caller (`ModularBot.nim:1501-1503`) does the
|
|
turret-relative subtraction itself. `gunHeading` is accepted and discarded.
|
|
Cross-checked against the real module by `cross_check_probe()`.
|
|
"""
|
|
bx, by = forecast_linear(ex, ey, eh, es, sx, sy, v)
|
|
return wrap180(math.degrees(math.atan2(by - sy, bx - sx)))
|
|
|
|
|
|
def buggy_base(sh, base_abs, los):
|
|
"""The PRE-FIX production aim, for the before/after column:
|
|
`normalize180(selfHeading + radToDeg(fc.bearing - los))` -- an absolute
|
|
heading plus a relative lead, i.e. `los`-independent of the forecast and
|
|
wrong by `gunHeading - los`."""
|
|
return wrap180(sh + (base_abs - los))
|
|
|
|
|
|
PROBE_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
"gk_aim_probe.nim")
|
|
|
|
|
|
def cross_check_probe(data, sample=400):
|
|
"""Build and run the Nim probe, assert the offline replay equals the real
|
|
`forecastBase`. Skips LOUDLY (never silently) if it cannot build."""
|
|
exe = "/tmp/gk_aim_probe"
|
|
build = subprocess.run(
|
|
["nim", "c", "--path:common_libs", "-o:" + exe, PROBE_SRC],
|
|
cwd=REPO, capture_output=True, text=True)
|
|
if build.returncode != 0:
|
|
print(" !! CROSS-CHECK SKIPPED: the nim probe did not build")
|
|
print(" " + build.stderr.strip().splitlines()[-1])
|
|
return
|
|
step = max(1, len(data) // sample)
|
|
sub = data[::step][:sample]
|
|
inp = "".join("%r %r %r %r %r %r %r\n" % (s["ex"], s["ey"], s["eh"], s["es"],
|
|
s["ox"], s["oy"], s["power"])
|
|
for s in sub)
|
|
out = subprocess.run([exe], input=inp, capture_output=True, text=True)
|
|
got = [float(x) for x in out.stdout.split()]
|
|
if len(got) != len(sub):
|
|
print(" !! CROSS-CHECK FAILED: %d of %d probe answers" % (len(got), len(sub)))
|
|
return
|
|
worst = max(abs(a - b) for a, b in
|
|
zip(got, [s["base_abs"] for s in sub]))
|
|
print(" nim probe vs offline replay on %d real situations: max |diff| = %.3e deg"
|
|
% (len(sub), worst))
|
|
print(" (0 means the measurement below replays the SHIPPED aim exactly;"
|
|
" the pre-fix formula on these same situations would differ by up to"
|
|
" 180 deg)")
|
|
if worst > 1e-9:
|
|
print(" !! CROSS-CHECK FAILED: the replay is NOT the production aim")
|
|
|
|
|
|
def key_of(band, space, turning, trend, heat, radial):
|
|
return ((((band * 3 + space) * 4 + turning) * 4 + trend) * 4 + heat) * 4 + radial
|
|
|
|
|
|
def best_residual(row):
|
|
"""Port of gun_knowledge.bestResidual (tie-break toward GK_NULL_BIN)."""
|
|
best_b, best_h = -1, 0
|
|
for b in range(GK_NBINS):
|
|
h = row[b]
|
|
if h < GK_MIN_BIN_HITS:
|
|
continue
|
|
if h > best_h or (h == best_h and best_b >= 0 and
|
|
abs(b - GK_NULL_BIN) < abs(best_b - GK_NULL_BIN)):
|
|
best_h, best_b = h, b
|
|
return (0.0, -1) if best_b < 0 else (CENTRE[best_b], best_b)
|
|
|
|
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
# corpus loading
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
def load_runs():
|
|
runs = []
|
|
for p in sorted(glob.glob(os.path.join(ROOT, "*", "*.jsonl"))):
|
|
if p.endswith(".events.jsonl"):
|
|
continue
|
|
ev_p, rj_p = p[:-6] + ".events.jsonl", p + ".rounds.json"
|
|
if not (os.path.exists(ev_p) and os.path.exists(rj_p)):
|
|
continue
|
|
rows = {}
|
|
with open(p) as f:
|
|
for line in f:
|
|
if '"tick"' not in line:
|
|
continue
|
|
o = json.loads(line)
|
|
if "ex" in o:
|
|
rows[o["tick"]] = o
|
|
rounds = json.load(open(rj_p))["rounds"]
|
|
start = {r["round"]: r["startTick"] for r in rounds}
|
|
count = {r["round"]: r["count"] for r in rounds}
|
|
evs = [json.loads(l) for l in open(ev_p) if l.strip()]
|
|
runs.append(dict(path=p, rows=rows, start=start, count=count, events=evs,
|
|
tag=os.path.basename(os.path.dirname(p)) + "/" +
|
|
os.path.basename(p)[:-6]))
|
|
return runs
|
|
|
|
|
|
def resolve_owner_side(run):
|
|
rows, start = run["rows"], run["start"]
|
|
votes = collections.defaultdict(collections.Counter)
|
|
|
|
def match(t, side, ev):
|
|
r, r1 = rows.get(t), rows.get(t + 1)
|
|
if r is None or r1 is None:
|
|
return False
|
|
if abs(r[side + "x"] - ev["x"]) > 0.02 or abs(r[side + "y"] - ev["y"]) > 0.02:
|
|
return False
|
|
ef = "ee" if side == "e" else "se"
|
|
return abs((r[ef] - r1[ef]) - ev["power"]) < 0.02
|
|
|
|
for ev in run["events"]:
|
|
if ev.get("type") != "fire":
|
|
continue
|
|
g = start.get(ev["round"], 0) + ev["tick"]
|
|
for t in range(g - 8, g + 9):
|
|
for side in ("e", "s"):
|
|
if match(t, side, ev):
|
|
votes[ev["owner"]][side] += 1
|
|
return {o: c.most_common(1)[0][0] for o, c in votes.items() if c}
|
|
|
|
|
|
def align(run, ev, side):
|
|
rows, start = run["rows"], run["start"]
|
|
g = start.get(ev["round"], 0) + ev["tick"]
|
|
best = None
|
|
for t in range(g - 8, g + 9):
|
|
r, r1 = rows.get(t), rows.get(t + 1)
|
|
if r is None or r1 is None:
|
|
continue
|
|
if abs(r[side + "x"] - ev["x"]) > 0.02 or abs(r[side + "y"] - ev["y"]) > 0.02:
|
|
continue
|
|
ef = "ee" if side == "e" else "se"
|
|
if abs((r[ef] - r1[ef]) - ev["power"]) >= 0.02:
|
|
continue
|
|
if best is None or abs(t - g) < abs(best - g):
|
|
best = t
|
|
return best
|
|
|
|
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
# per-shot extraction
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
def shots_of(run):
|
|
"""Yield one dict per US shot with everything the table and the metrics need."""
|
|
rows, start, count = run["rows"], run["start"], run["count"]
|
|
owner = resolve_owner_side(run)
|
|
n_our = n_noalign = 0
|
|
# per-tick enemy radial fraction (lead_forecast.VelocityTracker semantics)
|
|
rad_ring, rad_head, rad_count = [0.0] * VEL_WINDOW, 0, 0
|
|
prev = None
|
|
for ev in run["events"]:
|
|
if ev.get("type") != "fire" or owner.get(ev["owner"]) != US_SIDE:
|
|
continue
|
|
n_our += 1
|
|
t0 = align(run, ev, US_SIDE)
|
|
if t0 is None:
|
|
n_noalign += 1
|
|
continue
|
|
r0 = rows.get(t0)
|
|
if r0 is None:
|
|
continue
|
|
p = ev["power"]
|
|
# ---- raw accounting: EVERY aligned shot, before any filter ---------
|
|
RAW.append(dict(run=run["tag"],
|
|
dist=math.hypot(r0["ex"] - ev["x"], r0["ey"] - ev["y"]),
|
|
power=p))
|
|
rnd = ev["round"]
|
|
end = start[rnd] + count[rnd]
|
|
v = SPEED_A - SPEED_B * p
|
|
if v <= 0:
|
|
continue
|
|
ox, oy = ev["x"], ev["y"]
|
|
ex, ey, eh, es = r0["ex"], r0["ey"], r0["eh"], r0["es"]
|
|
dist = math.hypot(ex - ox, ey - oy)
|
|
if dist < 1e-6:
|
|
continue
|
|
los = math.degrees(math.atan2(ey - oy, ex - ox))
|
|
|
|
# --- the base: THE PRODUCTION AIM (absolute world bearing) ----------
|
|
base_abs = production_base(ex, ey, eh, es, ox, oy, v)
|
|
base_lead = wrap180(base_abs - los)
|
|
# the PRE-FIX production aim, for the before/after column
|
|
old_aim = buggy_base(r0["sh"], base_abs, los)
|
|
|
|
# --- aim-independent interception tick (ground truth) ---------------
|
|
kstar = None
|
|
for k in range(1, MAX_FLIGHT + 1):
|
|
t = t0 + k
|
|
if t >= end:
|
|
break
|
|
r = rows.get(t)
|
|
if r is None:
|
|
break
|
|
if math.hypot(r["ex"] - ox, r["ey"] - oy) <= v * k:
|
|
kstar = (k, r)
|
|
break
|
|
if kstar is None:
|
|
continue
|
|
kst, ea = kstar
|
|
required = wrap180(math.degrees(math.atan2(ea["ey"] - oy, ea["ex"] - ox)) - los)
|
|
|
|
# --- the counterfactual hit of every residual bin --------------------
|
|
kmax = min(MAX_FLIGHT, max(kst + 4, int((dist + 30.0) / v) + 3), end - t0)
|
|
fut = []
|
|
for k in range(1, kmax + 1):
|
|
r = rows.get(t0 + k)
|
|
if r is None:
|
|
break
|
|
fut.append((k, r["ex"] - ox, r["ey"] - oy))
|
|
if not fut:
|
|
continue
|
|
hit = [0] * GK_NBINS
|
|
hit0 = 0
|
|
hitOldAim = 0
|
|
for b in range(GK_NBINS + 1):
|
|
# the production aim: `predict()` puts the point at the enemy's
|
|
# CURRENT distance along (base + residual), so the counterfactual
|
|
# bullet flies along (base + residual) exactly.
|
|
th = base_abs + (0.0 if b == GK_NBINS else CENTRE[b])
|
|
ux, uy = math.cos(math.radians(th)), math.sin(math.radians(th))
|
|
hitb = 0
|
|
for (k, px, py) in fut:
|
|
bxx, byy = v * k * ux, v * k * uy
|
|
if math.hypot(px - bxx, py - byy) <= BOT_RADIUS:
|
|
hitb = 1
|
|
break
|
|
if b == GK_NBINS:
|
|
hit0 = hitb
|
|
else:
|
|
hit[b] = hitb
|
|
# the counterfactual hit of the PRE-FIX production aim
|
|
oux, ouy = math.cos(math.radians(old_aim)), math.sin(math.radians(old_aim))
|
|
for (k, px, py) in fut:
|
|
if math.hypot(px - v * k * oux, py - v * k * ouy) <= BOT_RADIUS:
|
|
hitOldAim = 1
|
|
break
|
|
# the same counterfactual against the PRE-FIX residual-bin LAYOUT, for
|
|
# DEFECT (orthogonal to the frame bug: this one uses the FIXED base)
|
|
hitOld = [0] * GK_NBINS
|
|
for b in range(GK_NBINS):
|
|
th = base_abs + CENTRE_OLD[b]
|
|
ux, uy = math.cos(math.radians(th)), math.sin(math.radians(th))
|
|
for (k, px, py) in fut:
|
|
if math.hypot(px - v * k * ux, py - v * k * uy) <= BOT_RADIUS:
|
|
hitOld[b] = 1
|
|
break
|
|
|
|
# --- the key's other features ---------------------------------------
|
|
# turn / trend from the recorded TRUTH one tick back (best case)
|
|
rp = rows.get(t0 - 1)
|
|
if rp is not None:
|
|
rate = wrap180(eh - rp["eh"]) / 1.0
|
|
turning = 2 if rate > GK_TURN_DEAD else (1 if rate < -GK_TURN_DEAD else 0)
|
|
dv = (es - rp["es"]) / 1.0
|
|
trend = 2 if dv > GK_TREND_DEAD else (1 if dv < -GK_TREND_DEAD else 0)
|
|
else:
|
|
turning, trend = 3, 3 # gkUnknown, the real cold-start state
|
|
# radialFrac over RADIAL_WINDOW ticks of recorded truth
|
|
if prev is not None and prev[0] == t0 - 1:
|
|
dx, dy = ex - prev[1], ey - prev[2]
|
|
spd = math.hypot(dx, dy)
|
|
if spd > 0.1 and dist > 1e-6:
|
|
f = abs((dx * (ox - ex) + dy * (oy - ey)) / dist) / spd
|
|
rad_ring[rad_head] = f
|
|
rad_head = (rad_head + 1) % VEL_WINDOW
|
|
if rad_count < VEL_WINDOW:
|
|
rad_count += 1
|
|
prev = (t0, ex, ey)
|
|
rf = 0.0
|
|
if rad_count:
|
|
n = min(RADIAL_WINDOW, rad_count)
|
|
rf = sum(rad_ring[(rad_head - 1 - i) % VEL_WINDOW] for i in range(n)) / n
|
|
space = space_of(ex, ey, ox, oy)
|
|
rad = q4(min(max(rf, 0.0), 1.0))
|
|
key = key_of(band_of(dist), space, turning, trend,
|
|
0, rad) # heat pinned to bin 0
|
|
|
|
# the same counterfactual against the 5-candidate sweep layout
|
|
hit5 = [hit0]
|
|
for c in ALT5[1:]:
|
|
th = base_abs + c
|
|
ux, uy = math.cos(math.radians(th)), math.sin(math.radians(th))
|
|
hitb = 0
|
|
for (k, px, py) in fut:
|
|
if math.hypot(px - v * k * ux, py - v * k * uy) <= BOT_RADIUS:
|
|
hitb = 1
|
|
break
|
|
hit5.append(hitb)
|
|
|
|
yield dict(run=run["tag"], tick=t0, power=p, dist=dist,
|
|
band=band_of(dist), key=key, hit=hit, hit0=hit0, hitOld=hitOld,
|
|
hit5=hit5, space=space, rad=rad,
|
|
hitOldAim=hitOldAim, base_abs=base_abs, old_aim=old_aim,
|
|
ex=ex, ey=ey, eh=eh, es=es, ox=ox, oy=oy, sh=r0["sh"],
|
|
err_base=wrap180(base_lead - required),
|
|
oracle=wrap180(required - base_lead),
|
|
kstar=kst, applied=wrap180(ev["dir"] - los),
|
|
turning=turning, trend=trend, lo=os, hi=os)
|
|
|
|
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
# KEY SIZE SWEEP
|
|
#
|
|
# One question: does the learned residual help at SMALLER table sizes? The 3840
|
|
# row key sees ~14 shots per row spread over 32 candidates = ~0.45 observations
|
|
# per candidate, so its argmax is noise. FULLINFO is the ceiling: every bin is
|
|
# tried on every training shot, so any dilution is REMOVED. If the signal is
|
|
# merely diluted, a coarser key (fewer rows, fewer candidates) must raise the
|
|
# held-out hit rate and/or lower the held-out rms. If it does not, the features
|
|
# carry no usable signal at ANY granularity.
|
|
#
|
|
# Same production base aim, same 2-fold by-battle split, same hit definition
|
|
# (min over k of |E(k) - bullet| <= 18), same atan(18/dist) per-band window.
|
|
# Coarser keys trade variance for BIAS -- a coarse row averages over situations
|
|
# that need different corrections -- so the sweep is a bias/variance trade, not
|
|
# a free win. The 20-observation bar is stated per config: a config whose rows
|
|
# do not carry >= 20 training observations PER CANDIDATE cannot estimate a hit
|
|
# rate and its argmax is not interpretable, no matter what the rms says.
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
SWEEP = [
|
|
# id, label, nbin, declared rows, key
|
|
("A", "full 6-feature key", 32, 5 * 3 * 4 * 4 * 4 * 4,
|
|
lambda s: key_of(s["band"], s["space"], s["turning"], s["trend"], 0, s["rad"])),
|
|
("B", "full 6-feature key", 5, 5 * 3 * 4 * 4 * 4 * 4,
|
|
lambda s: key_of(s["band"], s["space"], s["turning"], s["trend"], 0, s["rad"])),
|
|
("C", "distance only", 5, 5,
|
|
lambda s: s["band"]),
|
|
("D", "distance only", 32, 5,
|
|
lambda s: s["band"]),
|
|
("E", "distance + enemy-space", 5, 5 * 3,
|
|
lambda s: s["band"] * 3 + s["space"]),
|
|
("F", "distance + turn", 5, 5 * 4,
|
|
lambda s: s["band"] * 4 + s["turning"]),
|
|
("G", "distance + trend", 5, 5 * 4,
|
|
lambda s: s["band"] * 4 + s["trend"]),
|
|
("H", "distance + gun heat", 5, 5 * 4,
|
|
lambda s: s["band"] * 4 + 0), # heat is NOT recorded -> bin 0
|
|
("I", "distance + radialFrac", 5, 5 * 4,
|
|
lambda s: s["band"] * 4 + s["rad"]),
|
|
("J", "distance + turn", 32, 5 * 4,
|
|
lambda s: s["band"] * 4 + s["turning"]),
|
|
("K", "coarse 3-bin everywhere (full)", 5, 5 * 3 * 3 * 3 * 1 * 3,
|
|
lambda s: (((((s["band"] * 3 + min(s["space"], 2)) * 3 + min(s["turning"], 2)) * 3
|
|
+ min(s["trend"], 2)) * 1 + 0) * 3 + min(s["rad"] * 3 // 4, 2))),
|
|
]
|
|
|
|
SWEEP_MIN_OBS_PER_CAND = 20
|
|
|
|
|
|
def sweep_argmax(row, nbin):
|
|
"""`gun_knowledge.bestResidual` for an arbitrary candidate count.
|
|
|
|
Returns the argmax bin index, or -1 when no bin reached GK_MIN_BIN_HITS.
|
|
Bin 0 is the 0 deg NULL, so a return of 0 means 'learned: no correction'.
|
|
"""
|
|
best_b, best_h = -1, 0
|
|
for b in range(nbin):
|
|
h = row[b]
|
|
if h < GK_MIN_BIN_HITS:
|
|
continue
|
|
if h > best_h or (h == best_h and best_b >= 0 and abs(b) < abs(best_b)):
|
|
best_h, best_b = h, b
|
|
return best_b
|
|
|
|
|
|
def sweep_learn(train, keyf, nbin):
|
|
"""FULLINFO learning (perfect exploration) for an arbitrary key/candidate
|
|
count: every bin is tried on every training shot, so the hit counts are not
|
|
diluted by the gun only ever having tried the residual it already believed.
|
|
Returns {row: argmax bin} and the per-row attempt count."""
|
|
att, tbl, res = {}, {}, {}
|
|
for s in train:
|
|
k = keyf(s)
|
|
row = tbl.get(k)
|
|
if row is None:
|
|
row = tbl[k] = [0] * nbin
|
|
att[k] = 0
|
|
if att[k] >= GK_GLOBAL_MIN_ATTEMPTS:
|
|
res[k] = sweep_argmax(row, nbin)
|
|
att[k] += 1
|
|
hv = s["hit"] if nbin == GK_NBINS else s["hit5"]
|
|
for b in range(nbin):
|
|
row[b] += hv[b]
|
|
return res, att
|
|
|
|
|
|
def sweep_corr_hit(s, b, nbin, cent):
|
|
"""Counterfactual hit of the aim the table would apply: residual 0 (== the
|
|
base aim) for no row/bins 0..-1, else the candidate's own hit flag."""
|
|
if b is None or b <= 0:
|
|
return s["hit0"]
|
|
return (s["hit"] if nbin == GK_NBINS else s["hit5"])[b]
|
|
|
|
|
|
def mean_sd(xs):
|
|
if len(xs) < 2:
|
|
return (0.0, 0.0)
|
|
m = statistics.fmean(xs)
|
|
return (m, math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1)))
|
|
|
|
|
|
def main():
|
|
runs = load_runs()
|
|
print("CORPUS %s" % ROOT)
|
|
print(" battles (run files with sidecars): %d" % len(runs))
|
|
tot_rows = sum(len(r["rows"]) for r in runs)
|
|
tot_ev = sum(len(r["events"]) for r in runs)
|
|
tot_fire = sum(1 for r in runs for e in r["events"] if e.get("type") == "fire")
|
|
print(" worldstate rows: %d event records: %d fire events (both sides): %d"
|
|
% (tot_rows, tot_ev, tot_fire))
|
|
print()
|
|
|
|
data = []
|
|
n_fire_our = 0
|
|
for r in runs:
|
|
owner = resolve_owner_side(r)
|
|
n_fire_our += sum(1 for e in r["events"]
|
|
if e.get("type") == "fire" and owner.get(e["owner"]) == US_SIDE)
|
|
for s in shots_of(r):
|
|
s["fold"] = 0 if int(s["run"].split("run")[1]) <= 7 else 1
|
|
data.append(s)
|
|
print(" OUR fire events (energy-drop attribution): %d" % n_fire_our)
|
|
print(" USABLE shots (aligned, truth present, interception found): %d" % len(data))
|
|
print(" excluded (no align / no intercept / no future): %d"
|
|
% (n_fire_our - len(data)))
|
|
print()
|
|
|
|
print("PRODUCTION-PATH CROSS-CHECK (offline replay vs the real nim module)")
|
|
cross_check_probe(data)
|
|
print()
|
|
|
|
print("PER-BAND COUNTS")
|
|
print(" %-8s %12s %12s %12s" % ("band", "aligned raw", "usable", "held-out"))
|
|
for i, lab in enumerate(BAND_LAB):
|
|
raw = sum(1 for s in RAW if band_of(s["dist"]) == i)
|
|
n = sum(1 for s in data if s["band"] == i)
|
|
tr = sum(1 for s in data if s["band"] == i and s["fold"] == 0)
|
|
print(" %-8s %12d %12d %12d" % (lab, raw, n, n - tr))
|
|
print(" (aligned raw = every US fire event whose (x,y,power) matched a"
|
|
" recorded tick; usable = also has the truth forward to the"
|
|
" interception tick)")
|
|
print()
|
|
|
|
# ── the doc's own band counts, recomputed on BOTH sides ──────────────────
|
|
# docs/range_vs_approach_ceiling.md reports 0-100 n=24 767 / 300-450 n=11 372
|
|
# / 450+ n=23 275. Reproduce them with j167_probe.py's definition
|
|
# (T = round(20-3p); band on the distance from the OTHER tank to the fire
|
|
# origin) on each side separately, to show which tank those rows belong to.
|
|
print("SIDE CHECK — docs/range_vs_approach_ceiling.md's band table, recomputed"
|
|
" with j167_probe.py's own definition, per firing side")
|
|
docband = {0: [0, 0], 1: [0, 0], 2: [0, 0], 3: [0, 0], 4: [0, 0]}
|
|
for r in runs:
|
|
owner = resolve_owner_side(r)
|
|
rows, start, count = r["rows"], r["start"], r["count"]
|
|
for ev in r["events"]:
|
|
if ev.get("type") != "fire":
|
|
continue
|
|
side = owner.get(ev["owner"])
|
|
if side is None:
|
|
continue
|
|
other = "s" if side == "e" else "e"
|
|
t0 = align(r, ev, side)
|
|
if t0 is None or t0 not in rows:
|
|
continue
|
|
T = int(round(SPEED_A - SPEED_B * ev["power"]))
|
|
if T < 1 or t0 + T not in rows or t0 + T >= start[ev["round"]] + count[ev["round"]]:
|
|
continue
|
|
if rows[t0][other + "e"] <= 0.5 or rows[t0 + T][other + "e"] <= 0.5:
|
|
continue
|
|
rng = math.hypot(rows[t0][other + "x"] - ev["x"],
|
|
rows[t0][other + "y"] - ev["y"])
|
|
docband[band_of(rng)][0 if side == US_SIDE else 1] += 1
|
|
print(" %-8s %10s %10s" % ("band", "our(s*)", "DrussGT(e*)"))
|
|
for i, lab in enumerate(BAND_LAB):
|
|
print(" %-8s %10d %10d" % (lab, docband[i][0], docband[i][1]))
|
|
print(" (doc's table: 0-100 n=24767, 300-450 n=11372, 450+ n=23275, total"
|
|
" 60252 -- compare columns)")
|
|
print()
|
|
|
|
# gkUnknown exposure: what the key would carry if the enemy were NOT
|
|
# re-observed every tick. The corpus itself has no scan stream, so this is
|
|
# driven by the ONE live capture that does (see the report).
|
|
print("gkUnknown EXPOSURE under a constant scan gap (derived from the corpus"
|
|
" truth, not measured scan logs)")
|
|
for gap in (1, 2, 3, 5, 6, 7, 8):
|
|
unk = 0
|
|
for s in data:
|
|
if gap > GK_GAP_MAX:
|
|
unk += 1
|
|
elif s["turning"] == 3 or s["trend"] == 3:
|
|
unk += 1
|
|
rows_unk = 1 if gap > GK_GAP_MAX else 0
|
|
print(" gap=%d turn -> %s ; fraction of shots that would key gkUnknown: %.4f"
|
|
% (gap, "gkUnknown" if rows_unk else "straight/left/right", unk / len(data)))
|
|
print()
|
|
|
|
def learn(train, regime):
|
|
"""Return (residual_per_key, n_rows_with_nonzero_argmax).
|
|
|
|
FULLINFO every bin is tried on every training shot (the CEILING of what
|
|
the table could learn with perfect exploration).
|
|
DEFECT the module EXACTLY AS IT SHIPPED BEFORE THE FIX, replayed
|
|
sequentially: the uniform [-30,+30] layout where bin 0 sat
|
|
at -29.06 deg, `aim` returning (0.0, -1) below threshold and
|
|
`update` doing clamp(-1, 0, 31) = 0, so every no-correction
|
|
shot was filed at -29.06 deg and the argmax returned it
|
|
forever. This is the regime that produced 36.46 deg / 3.46%
|
|
in the 450+ band.
|
|
FAITHFUL the module AS IT SHIPS NOW, replayed sequentially in tick
|
|
order: `aim` returns (0.0, -1) below threshold, and
|
|
`update(f, usedBin, hit)` files that under GK_NULL_BIN = 0,
|
|
the 0 deg bin. The argmax can then only ever be pulled
|
|
TOWARD zero.
|
|
"""
|
|
att = [0] * GK_NKEYS
|
|
tbl = [None] * GK_NKEYS
|
|
res = [0.0] * GK_NKEYS
|
|
old = regime == "DEFECT"
|
|
|
|
def hit_at(s, r):
|
|
if r == 0.0:
|
|
return s["hit0"]
|
|
if old:
|
|
b = min(range(GK_NBINS), key=lambda j: abs(CENTRE_OLD[j] - r))
|
|
return s["hitOld"][b]
|
|
b = min(range(GK_NBINS), key=lambda j: abs(CENTRE[j] - r))
|
|
return s["hit"][b]
|
|
|
|
def argmax(row):
|
|
return best_residual_old(row) if old else best_residual(row)
|
|
|
|
for s in train:
|
|
k = s["key"]
|
|
if tbl[k] is None:
|
|
tbl[k] = [0] * GK_NBINS
|
|
if regime == "FULLINFO":
|
|
att[k] += 1
|
|
if att[k] >= GK_GLOBAL_MIN_ATTEMPTS:
|
|
res[k], _ = best_residual(tbl[k])
|
|
for b in range(GK_NBINS):
|
|
tbl[k][b] += s["hit"][b]
|
|
elif old: # DEFECT, sequential
|
|
if att[k] >= GK_GLOBAL_MIN_ATTEMPTS:
|
|
r, b = argmax(tbl[k])
|
|
else:
|
|
r, b = 0.0, -1
|
|
res[k] = r
|
|
att[k] += 1
|
|
tbl[k][max(b, 0)] += hit_at(s, r) # clamp(-1) -> bin 0
|
|
else: # FAITHFUL, sequential
|
|
if att[k] >= GK_GLOBAL_MIN_ATTEMPTS:
|
|
r, b = argmax(tbl[k])
|
|
else:
|
|
r, b = 0.0, -1
|
|
res[k] = r
|
|
att[k] += 1
|
|
tbl[k][GK_NULL_BIN if b < 0 else b] += hit_at(s, r)
|
|
used = sum(1 for k in range(GK_NKEYS) if res[k] != 0.0)
|
|
return res, used
|
|
|
|
def rms(xs):
|
|
return math.sqrt(sum(x * x for x in xs) / len(xs)) if xs else float("nan")
|
|
|
|
# ── the frame fix, measured THROUGH THE PRODUCTION AIM ───────────────────
|
|
# BEFORE = normalize180(selfHeading + (fc.bearing - los)), what `predict`
|
|
# returned when the knowledge gun fired (it is what the caller turned the
|
|
# turret to). AFTER = normalize180(radToDeg(fc.bearing)) + residual, i.e.
|
|
# the bare forecast plus whatever the table learned. BASELINE = the bare
|
|
# forecast with residual 0, which is the thing AFTER has to beat.
|
|
print("=" * 78)
|
|
print("PRODUCTION AIM, BEFORE vs AFTER THE FRAME FIX (counterfactual hit of"
|
|
" the angle `predict()` hands the caller, over every usable shot)")
|
|
print(" %-8s %7s | %10s %10s %10s | %8s %8s"
|
|
% ("band", "n", "BEFORE", "AFTER", "baseline", "rmsB", "rmsA"))
|
|
rows_bf = []
|
|
for i, lab in enumerate(BAND_LAB):
|
|
te = [s for s in data if s["band"] == i]
|
|
if not te:
|
|
continue
|
|
hb = [s["hitOldAim"] for s in te]
|
|
ha = [s["hit0"] for s in te] # AFTER with the null residual
|
|
eb = [wrap180(s["old_aim"] - s["base_abs"]) for s in te]
|
|
rows_bf.append((lab, len(te), 100.0 * statistics.fmean(hb),
|
|
100.0 * statistics.fmean(ha), rms(eb)))
|
|
print(" %-8s %7d | %9.2f%% %9.2f%% %9.2f%% | %8.2f %8.2f"
|
|
% (lab, len(te), 100.0 * statistics.fmean(hb),
|
|
100.0 * statistics.fmean(ha), 100.0 * statistics.fmean(ha),
|
|
rms(eb), 0.0))
|
|
if rows_bf:
|
|
n = sum(r[1] for r in rows_bf)
|
|
hb = statistics.fmean([r[2] for r in rows_bf for _ in range(r[1])])
|
|
ha = statistics.fmean([r[3] for r in rows_bf for _ in range(r[1])])
|
|
print(" %-8s %7d | %9.2f%% %9.2f%% %9.2f%%"
|
|
% ("ALL", n, hb, ha, ha))
|
|
print(" (BEFORE = the shipped pre-fix aim; its rmsA column is 0 by"
|
|
" construction because AFTER is an absolute world bearing and the"
|
|
" bot's heading cannot move it. rmsB is the angle error the frame bug"
|
|
" actually induced.)")
|
|
print()
|
|
|
|
for regime in ("FULLINFO", "DEFECT", "FAITHFUL"):
|
|
old = regime == "DEFECT"
|
|
CEN, HITS = (CENTRE_OLD, "hitOld") if old else (CENTRE, "hit")
|
|
|
|
def corrected_hit(s, r):
|
|
if r == 0.0:
|
|
return s["hit0"]
|
|
b = min(range(GK_NBINS), key=lambda j: abs(CEN[j] - r))
|
|
return s[HITS][b]
|
|
|
|
print("=" * 78)
|
|
print("REGIME %s (training on fold0, testing on fold1, then swapped)"
|
|
% regime)
|
|
res, used = learn([s for s in data if s["fold"] == 0], regime)
|
|
test = [s for s in data if s["fold"] == 1]
|
|
print(" rows above GK_GLOBAL_MIN_ATTEMPTS with a non-zero argmax: %d / %d"
|
|
% (used, sum(1 for s in data if s["fold"] == 0)))
|
|
print(" %-8s %7s | %-28s | %-28s | %s"
|
|
% ("band", "n", "baseline (forecastLinear)", "+ learned residual",
|
|
"oracle (required - base)"))
|
|
print(" %-8s %7s | %8s %8s %8s | %8s %8s %8s | %8s %8s"
|
|
% ("", "", "rms", "meanabs", "hit%", "rms", "meanabs", "hit%",
|
|
"rms", "meanabs"))
|
|
tol = {}
|
|
for i, lab in enumerate(BAND_LAB):
|
|
te = [s for s in test if s["band"] == i]
|
|
if not te:
|
|
continue
|
|
tol[lab] = statistics.fmean([math.degrees(math.atan(BOT_RADIUS / s["dist"]))
|
|
for s in te])
|
|
eb = [s["err_base"] for s in te]
|
|
ec = [wrap180(s["err_base"] + res[s["key"]]) for s in te]
|
|
hb = [s["hit0"] for s in te]
|
|
# hit of the ACTUAL corrected aim: nearest bin to the chosen residual
|
|
hc, ho = [], []
|
|
for s in te:
|
|
r = res[s["key"]]
|
|
hc.append(corrected_hit(s, r))
|
|
# oracle: the bin whose aim is closest to the required lead
|
|
bo = min(range(GK_NBINS), key=lambda j: abs(wrap180(s["oracle"] - CENTRE[j])))
|
|
ho.append(s["hit"][bo])
|
|
print(" %-8s %7d | %8.2f %8.2f %7.2f%% | %8.2f %8.2f %7.2f%% | %8.2f %8.2f"
|
|
% (lab, len(te), rms(eb), statistics.fmean(map(abs, eb)),
|
|
100.0 * statistics.fmean(hb),
|
|
rms(ec), statistics.fmean(map(abs, ec)),
|
|
100.0 * statistics.fmean(hc),
|
|
rms([wrap180(s["oracle"]) for s in te]),
|
|
statistics.fmean([abs(wrap180(s["oracle"])) for s in te])))
|
|
print(" hit half-window atan(18/dist) in this band: " +
|
|
", ".join("%s %.2f deg" % (k, v) for k, v in tol.items()))
|
|
print(" %-8s %8s %8s %10s %12s %12s" %
|
|
("band", "cover", "|res|", "rms delta", "b>c", "c>b"))
|
|
for i, lab in enumerate(BAND_LAB):
|
|
te = [s for s in test if s["band"] == i]
|
|
if not te:
|
|
continue
|
|
cov = [s for s in te if res[s["key"]] != 0.0]
|
|
bc = cb = 0
|
|
for s in te:
|
|
hb = s["hit0"]
|
|
hc = corrected_hit(s, res[s["key"]])
|
|
if hb and not hc:
|
|
bc += 1
|
|
elif hc and not hb:
|
|
cb += 1
|
|
eb = [s["err_base"] for s in te]
|
|
ec = [wrap180(s["err_base"] + res[s["key"]]) for s in te]
|
|
print(" %-8s %7.1f%% %8.2f %+10.2f %12d %12d" %
|
|
(lab, 100.0 * len(cov) / len(te),
|
|
statistics.fmean([abs(res[s["key"]]) for s in cov]) if cov else 0.0,
|
|
rms(ec) - rms(eb), bc, cb))
|
|
print(" (cover = %% of held-out shots whose key received a non-zero"
|
|
" residual; b>c / c>b = discordant hit pairs, the exact two-sided"
|
|
" binomial p on their sum is the hit-rate test)")
|
|
print()
|
|
|
|
# the actual applied lead, for reference against the doc's numbers
|
|
print("REFERENCE (what the recorded gun actually did), fold1 only")
|
|
for i, lab in enumerate(BAND_LAB):
|
|
te = [s for s in data if s["band"] == i and s["fold"] == 1]
|
|
if not te:
|
|
continue
|
|
ap = [s["applied"] for s in te]
|
|
print(" %-8s n=%6d applied-lead rms %8.2f meanabs %8.2f base-aim hit rate %6.2f%%"
|
|
% (lab, len(te), rms(ap), statistics.fmean(map(abs, ap)),
|
|
100.0 * statistics.fmean([float(s["hit0"]) for s in te])))
|
|
print()
|
|
print("NOTE: 'real hit rate' above is the counterfactual hit of the base aim"
|
|
" recomputed from the truth, not the server's hit/hitwall verdict.")
|
|
print()
|
|
|
|
# ───────────────────────── KEY SIZE SWEEP ─────────────────────────────────
|
|
print("=" * 78)
|
|
print("KEY SIZE SWEEP -- does the learned residual help at SMALLER tables?")
|
|
print(" FULLINFO (perfect exploration) throughout, so any dilution is")
|
|
print(" removed; only the key granularity and the candidate count change.")
|
|
print(" rows = declared key space; occupied = rows the corpus ever keys.")
|
|
print(" shots/row = corpus usable shots / occupied rows; obs/cand = that")
|
|
print(" divided by the candidate count (the number that must reach 20).")
|
|
print()
|
|
|
|
# concentration of the corpus over the key space, computed on ALL usable
|
|
# shots (the 2-fold split only ever trains on ~half of them)
|
|
sweep_results = []
|
|
for cid, label, nbin, declared, keyf in SWEEP:
|
|
cent = alt_centres(nbin)
|
|
counts = collections.Counter(keyf(s) for s in data)
|
|
occ = sorted(counts.values())
|
|
med = occ[len(occ) // 2] if occ else 0
|
|
trusted_rows = sum(1 for v in occ if v / nbin >= SWEEP_MIN_OBS_PER_CAND)
|
|
allshots = data
|
|
held_trusted = sum(1 for s in allshots
|
|
if counts[keyf(s)] / nbin >= SWEEP_MIN_OBS_PER_CAND)
|
|
|
|
# 2-fold by battle: learn on one half, test on the other, pool
|
|
pooled = []
|
|
res_used = []
|
|
for f in (0, 1):
|
|
res, att = sweep_learn([s for s in data if s["fold"] != f], keyf, nbin)
|
|
res_used.append((sum(1 for b in res.values() if b > 0), len(res)))
|
|
for s in data:
|
|
if s["fold"] != f:
|
|
continue
|
|
b = res.get(keyf(s), -1)
|
|
r = cent[b] if b and b > 0 else 0.0
|
|
pooled.append((s, wrap180(s["err_base"] + r), sweep_corr_hit(s, b, nbin, cent)))
|
|
|
|
# baseline + clustered stats over the same held-out pool
|
|
eb_all = [p[1] - p[0]["err_base"] for p in pooled]
|
|
del eb_all
|
|
eb = [p[0]["err_base"] for p in pooled]
|
|
ec = [p[1] for p in pooled]
|
|
hb = [p[0]["hit0"] for p in pooled]
|
|
hc = [p[2] for p in pooled]
|
|
rms_b, rms_c = rms(eb), rms(ec)
|
|
hit_b, hit_c = statistics.fmean(hb), statistics.fmean(hc)
|
|
cov = [p for p in pooled if p[2] != p[0]["hit0"] or True]
|
|
ncov = sum(1 for p in pooled if abs(p[1] - p[0]["err_base"]) > 1e-9)
|
|
bc = sum(1 for a, b_ in zip(hb, hc) if a and not b_)
|
|
cb = sum(1 for a, b_ in zip(hb, hc) if b_ and not a)
|
|
# per-battle paired deltas: the corpus is closed-loop clustered, so the
|
|
# honest test is a paired t over BATTIES, not over 55k shots
|
|
byrun = collections.defaultdict(lambda: ([], [], []))
|
|
for s, e2, h2 in pooled:
|
|
d = byrun[s["run"]]
|
|
d[0].append(h2 - s["hit0"])
|
|
d[1].append(e2 ** 2 - s["err_base"] ** 2)
|
|
d[2].append(1)
|
|
dh = [statistics.fmean(v[0]) for v in byrun.values() if v[2]]
|
|
de = [statistics.fmean(v[1]) for v in byrun.values() if v[2]]
|
|
mh, sh = mean_sd(dh)
|
|
me, se = mean_sd(de)
|
|
t_h = mh / (sh / math.sqrt(len(dh))) if sh > 0 else 0.0
|
|
t_e = me / (se / math.sqrt(len(de))) if se > 0 else 0.0
|
|
nb_ = len(dh)
|
|
|
|
print("-" * 78)
|
|
print("CONFIG %s %s [%d candidates at %s]" %
|
|
(cid, label, nbin,
|
|
", ".join("%.1f" % c for c in cent)))
|
|
print(" rows declared %6d occupied %5d shots/row mean %8.1f median %5d min %5d"
|
|
% (declared, len(occ), statistics.fmean(occ) if occ else 0.0, med,
|
|
occ[0] if occ else 0))
|
|
print(" obs per candidate: mean %6.2f min %6.2f | rows with >= %d obs/cand: %d / %d (%.1f%%)"
|
|
% (statistics.fmean([v / nbin for v in occ]) if occ else 0.0,
|
|
occ[0] / nbin if occ else 0.0, SWEEP_MIN_OBS_PER_CAND,
|
|
trusted_rows, len(occ),
|
|
100.0 * trusted_rows / len(occ) if occ else 0.0))
|
|
print(" held-out shots landing in a >= %d obs/cand row: %d / %d (%.1f%%)"
|
|
% (SWEEP_MIN_OBS_PER_CAND, held_trusted, len(allshots),
|
|
100.0 * held_trusted / len(allshots)))
|
|
print(" rows with a NON-ZERO argmax after training: fold0 %d / %d, fold1 %d / %d"
|
|
% (res_used[0][0], res_used[0][1], res_used[1][0], res_used[1][1]))
|
|
print(" POOLED held-out: rms %.2f -> %.2f (%+.2f) hit %.2f%% -> %.2f%% (%+.2f pp) cover %.1f%% b>c %d c>b %d"
|
|
% (rms_b, rms_c, rms_c - rms_b, 100 * hit_b, 100 * hit_c,
|
|
100 * (hit_c - hit_b), 100.0 * ncov / len(pooled), bc, cb))
|
|
print(" clustered by battle (%d battles): dHit %+0.3f pp (sd %0.3f, t=%+.2f) dMeanSqErr %+8.2f deg2 (t=%+.2f)"
|
|
% (nb_, 100 * mh, 100 * sh, t_h, me, t_e))
|
|
print(" %-8s %7s %9s %8s | %-16s | %-16s" %
|
|
("band", "n", "obs/cand", "cover%", "baseline rms/hit%", "learned rms/hit%"))
|
|
for i, lab in enumerate(BAND_LAB):
|
|
te = [p for p in pooled if p[0]["band"] == i]
|
|
if not te:
|
|
continue
|
|
rowsb = [p[0] for p in te]
|
|
rowkeys = set()
|
|
for s in rowsb:
|
|
rowkeys.add(keyf(s))
|
|
b_obs = statistics.fmean([counts[k] / nbin for k in rowkeys]) if rowkeys else 0.0
|
|
n_cov = sum(1 for p in te
|
|
if abs(p[1] - p[0]["err_base"]) > 1e-9)
|
|
e_b = [p[0]["err_base"] for p in te]
|
|
e_c = [p[1] for p in te]
|
|
h_b = [p[0]["hit0"] for p in te]
|
|
h_c = [p[2] for p in te]
|
|
print(" %-8s %7d %9.2f %7.1f%% | %7.2f %7.2f%% | %7.2f %7.2f%%"
|
|
% (lab, len(te), b_obs, 100.0 * n_cov / len(te),
|
|
rms(e_b), 100 * statistics.fmean(h_b),
|
|
rms(e_c), 100 * statistics.fmean(h_c)))
|
|
sweep_results.append(dict(id=cid, label=label, nbin=nbin, declared=declared,
|
|
occ=len(occ), obsc=statistics.fmean([v / nbin for v in occ]) if occ else 0.0,
|
|
minobs=occ[0] / nbin if occ else 0.0,
|
|
trusted=100.0 * trusted_rows / len(occ) if occ else 0.0,
|
|
heldok=100.0 * held_trusted / len(allshots),
|
|
nz=res_used[0][0] + res_used[1][0],
|
|
rmsb=rms_b, rmsc=rms_c, hitb=100 * hit_b,
|
|
hitc=100 * hit_c, cover=100.0 * ncov / len(pooled),
|
|
t=t_h, nb=nb_))
|
|
del cov
|
|
|
|
print("-" * 78)
|
|
print("SWEEP SUMMARY (pooled held-out, both folds)")
|
|
print(" %-3s %-30s %4s %6s %8s %8s %7s %7s %6s %6s %6s"
|
|
% ("id", "key", "cand", "rows", "obs/cand", "minobs", "rms", "drms",
|
|
"hit%", "dhit", "t/bat"))
|
|
for r in sweep_results:
|
|
print(" %-3s %-30s %4d %6d %8.2f %8.2f %7.2f %+7.2f %6.2f %+6.2f %+6.2f"
|
|
% (r["id"], r["label"], r["nbin"], r["occ"], r["obsc"], r["minobs"],
|
|
r["rmsc"], r["rmsc"] - r["rmsb"], r["hitc"], r["hitc"] - r["hitb"],
|
|
r["t"]))
|
|
print(" %-3s %-30s %4s %6s %8s %8s %7s %7s %6s %6s %6s"
|
|
% ("", "", "", "", ">=20obs", "held%", "nzrows", "cover%", "", "", ""))
|
|
for r in sweep_results:
|
|
print(" %-3s %-30s %4d %6d %8s %7.1f%% %7d %6.1f%%"
|
|
% (r["id"], r["label"], r["nbin"], r["occ"],
|
|
"YES" if r["heldok"] >= 80 else "no", r["heldok"],
|
|
r["nz"], r["cover"]))
|
|
print(" (a config is only TRUSTWORTHY where >= 80%% of held-out shots land in"
|
|
" a row carrying >= %d training observations per candidate; a config"
|
|
" with 0.2 obs/cand cannot estimate a hit rate and its rms is the"
|
|
" residual of an argmax over noise.)" % SWEEP_MIN_OBS_PER_CAND)
|
|
print()
|
|
|
|
# The headroom a residual table of ANY size could capture: the per-shot best
|
|
# counterfactual hit over the candidate set (an unattainable upper bound --
|
|
# no table can pick the right bin per shot) against the base aim. If the
|
|
# best-of-N is barely above the base, no argmax over that set can help.
|
|
print("-" * 78)
|
|
print("CANDIDATE-SET CEILING (all usable shots, per band)")
|
|
print(" base = residual 0; best-of-5 / best-of-32 = the per-shot MAX over"
|
|
" the candidate set (an upper bound no table can reach)")
|
|
print(" %-8s %7s | %8s %10s %10s | %9s %9s"
|
|
% ("band", "n", "base", "best-of-5", "best-of-32", "d5", "d32"))
|
|
for i, lab in enumerate(BAND_LAB):
|
|
te = [s for s in data if s["band"] == i]
|
|
if not te:
|
|
continue
|
|
b0 = statistics.fmean([float(s["hit0"]) for s in te])
|
|
b5 = statistics.fmean([max(s["hit5"]) for s in te])
|
|
b32 = statistics.fmean([max(s["hit"]) for s in te])
|
|
print(" %-8s %7d | %7.2f%% %9.2f%% %9.2f%% | %+8.2f %+8.2f"
|
|
% (lab, len(te), 100 * b0, 100 * b5, 100 * b32,
|
|
100 * (b5 - b0), 100 * (b32 - b0)))
|
|
print(" (a table learns ONE bin per row, not the per-shot max, so the"
|
|
" realistic gain is a fraction of this headroom at best)")
|
|
print()
|
|
print(" mean hit rate of EACH 5-candidate residual, per band (this is what"
|
|
" an argmax over candidates maximises;")
|
|
print(" the highest column IS the best a table with that candidate set and"
|
|
" one bin per row can do)")
|
|
print(" %-8s %7s | %s" % ("band", "n",
|
|
" ".join("%7.1f" % c for c in ALT5)))
|
|
for i, lab in enumerate(BAND_LAB):
|
|
te = [s for s in data if s["band"] == i]
|
|
if not te:
|
|
continue
|
|
per = [statistics.fmean([float(s["hit5"][b]) for s in te])
|
|
for b in range(len(ALT5))]
|
|
print(" %-8s %7d | %s best = %+.1f deg"
|
|
% (lab, len(te), " ".join("%6.2f%%" % (100 * v) for v in per),
|
|
ALT5[per.index(max(per))]))
|
|
print()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|