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.
733 lines
30 KiB
Python
733 lines
30 KiB
Python
#!/usr/bin/env python3
|
|
"""MEASURE: the gun-knowledge learned ANGULAR RESIDUAL vs the bare
|
|
`forecastLinear` base, over VIRTUAL BULLETS on the recorded corpus.
|
|
|
|
`measure_gk_residual.py` measured the residual on REAL FIRED SHOTS (~55k). This
|
|
script re-measures it on the thing the module actually learns from in battle:
|
|
VIRTUAL BULLETS. `gun_harness/virtual_bullets.nim` spawns one bullet per power
|
|
bin per gun per tick, so the knowledge gun gets 4 resolutions per tick against
|
|
the 1/tick a real shot gives it — the offline table was starved by ~63x.
|
|
|
|
WHAT IS SIMULATED (mirrors virtual_bullets.nim `bmPath` exactly)
|
|
---------------------------------------------------------------
|
|
PowerBins = [1.0, 1.5, 2.0, 3.0], bulletSpeed = 20 - 3p
|
|
every tick with a live target, per power bin:
|
|
aim = production base (forecastLinear, ABSOLUTE world bearing,
|
|
gkm.production_base) + residual from the table row
|
|
spawn a bullet at the shooter position, direction = aim, speed = v
|
|
advance it EVERY tick (spawn-then-tick, as the live bot does: the rack
|
|
calls spawnBullets before tickBullets on the same tick)
|
|
each tick: swept segment vs the RECORDED enemy position of that tick,
|
|
hit iff distPointToSegment(...) < BotRadius (18.0) [bmPath]
|
|
resolve ONLY at the wall, exactly once, recording hit or miss
|
|
on resolution: table update, crediting the usedBin on a hit
|
|
a bullet whose target dies, or that is in flight at a round boundary, is
|
|
dropped WITHOUT scoring (bmPath's dead-target branch, and
|
|
KnowledgeGun.onRoundBoundary clears `pending`, so a post-boundary feedback
|
|
updates nothing — and the corpus records the enemy every tick, so there is
|
|
no staleness gap to interpolate)
|
|
|
|
LEARNING POLICY
|
|
---------------
|
|
The epsilon-greedy policy is NOT in the shipped `gun_knowledge.nim` (that file
|
|
documents "The module itself never invents a random bin"); it is applied here
|
|
exactly as specified for this measurement:
|
|
row.attempts < --explore-attempts -> with p = --eps pick a UNIFORM
|
|
random residual bin, else the argmax. At or above the threshold: argmax.
|
|
Every resolution increments row.attempts, and `aim` increments it below the
|
|
trust threshold (exactly as the module's `inc gk.globalRows[key].attempts`
|
|
does). A shot taken with no residual (usedBin -1) is filed under bin 0, the
|
|
0 deg NULL, exactly as `update` does. The trust threshold that gates the
|
|
argmax is GK_GLOBAL_MIN_ATTEMPTS = 5 in both `aim` and `update`.
|
|
|
|
SPLIT: held out BY BATTLE, 2-fold, `run1..run7` = fold 0 and `run8..run14` =
|
|
fold 1, identical to measure_gk_residual.py. Every virtual bullet is tested
|
|
exactly once (each battle is in exactly one held-out fold).
|
|
|
|
ARMS
|
|
base residual 0, i.e. bare `forecastLinear`, through the same spawn/flight
|
|
learn residual from the table, frozen at test time
|
|
A tick whose learned residual is 0 has a byte-identical ray, so ONE flight is
|
|
simulated and credited to both arms (it IS the same bullet, not an average).
|
|
Every band/rms number is measured on the SAME set of held-out ticks.
|
|
|
|
KEY CONFIGS
|
|
full the production 15-bit key: band x space x turn x trend x heat x radial
|
|
(gun heat is not in the corpus -> pinned to quarter 0, so this key is
|
|
COARSER than in battle, never finer)
|
|
dt band x turn — the config that won the real-shot sweep (SWEEP F/J)
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import collections
|
|
import glob
|
|
import json
|
|
import math
|
|
import os
|
|
import random
|
|
import statistics
|
|
import sys
|
|
import time
|
|
from multiprocessing import Process, Pool
|
|
|
|
# reuse the previous script's PRODUCTION-AIM ports verbatim (one definition of
|
|
# forecastLinear / production_base / bandOf / spaceOf / the bin layout)
|
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
if _HERE not in sys.path:
|
|
sys.path.insert(0, _HERE)
|
|
_ARGV = sys.argv
|
|
sys.argv = [sys.argv[0]]
|
|
import measure_gk_residual as gkm # noqa: E402
|
|
sys.argv = _ARGV
|
|
|
|
ROOT = os.environ.get("GK_CORPUS", "/tmp/tfil_ab2/out")
|
|
|
|
GK_NBINS = 32
|
|
GK_NULL_BIN = 0
|
|
GK_MIN_BIN_HITS = 3
|
|
GK_GLOBAL_MIN_ATTEMPTS = 5
|
|
CENTRE = gkm.CENTRE # bin b -> residual degrees
|
|
|
|
BOT_RADIUS = 18.0
|
|
ARENA_W, ARENA_H = 800.0, 600.0
|
|
POWER_BINS = [1.0, 1.5, 2.0, 3.0]
|
|
SPEEDS = [20.0 - 3.0 * p for p in POWER_BINS] # 17.0 15.5 14.0 11.0
|
|
MAX_FLIGHT = 300
|
|
BAND_LAB = gkm.BAND_LAB
|
|
N_BAND = len(BAND_LAB)
|
|
|
|
GK_STRAIGHT, GK_RIGHT, GK_LEFT, GK_UNKNOWN = 0, 1, 2, 3
|
|
GK_ACCEL, GK_CONST, GK_DECEL = 0, 1, 2
|
|
GK_TURN_DEAD, GK_TREND_DEAD = 2.0, 0.05
|
|
VEL_WINDOW, RADIAL_WINDOW = 16, 32
|
|
|
|
ARM_BASE, ARM_BOTH, ARM_LEARN = 0, 2, 1
|
|
|
|
|
|
def key_of(band, space, turning, trend, rad, arm):
|
|
if arm == "full":
|
|
return ((((band * 3 + space) * 4 + turning) * 4 + trend) * 4 + 0) * 4 + rad
|
|
return band * 4 + turning
|
|
|
|
|
|
def nrows(arm):
|
|
return 5 * 3 * 4 * 4 * 4 * 4 if arm == "full" else 5 * 4
|
|
|
|
|
|
def best_residual(row):
|
|
"""Port of gun_knowledge.bestResidual: argmax over the bins clearing
|
|
GK_MIN_BIN_HITS, tie-broken toward the 0 deg NULL. Returns (deg, bin)."""
|
|
if row is None:
|
|
return 0.0, -1
|
|
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) < abs(best_b)):
|
|
best_h, best_b = h, b
|
|
if best_b < 0:
|
|
return 0.0, -1
|
|
return CENTRE[best_b], best_b
|
|
|
|
|
|
class Table:
|
|
def __init__(self, n):
|
|
self.n = n
|
|
self.att = [0] * n
|
|
self.hits = [None] * n
|
|
|
|
def row(self, k):
|
|
r = self.hits[k]
|
|
if r is None:
|
|
r = self.hits[k] = [0] * GK_NBINS
|
|
return r
|
|
|
|
def residual(self, k):
|
|
"""What `aim` returns for this row: below GK_GLOBAL_MIN_ATTEMPTS the
|
|
module returns the NULL residual (it only counts the attempt)."""
|
|
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
|
|
return 0.0, -1
|
|
return best_residual(self.hits[k])
|
|
|
|
def stats(self):
|
|
nz, trusted, s = 0, 0, 0.0
|
|
for k in range(self.n):
|
|
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
|
|
continue
|
|
trusted += 1
|
|
d, _ = best_residual(self.hits[k])
|
|
if d != 0.0:
|
|
nz += 1
|
|
s += abs(d)
|
|
return nz, trusted, (s / nz if nz else 0.0)
|
|
|
|
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
# corpus
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
_CACHE = {}
|
|
|
|
|
|
def battle_files(root):
|
|
out = []
|
|
for p in sorted(glob.glob(os.path.join(root, "*", "*.jsonl"))):
|
|
if p.endswith(".events.jsonl"):
|
|
continue
|
|
rj, ev = p + ".rounds.json", p[:-6] + ".events.jsonl"
|
|
if not (os.path.exists(rj) and os.path.exists(ev)):
|
|
continue
|
|
tag = os.path.basename(os.path.dirname(p)) + "/" + os.path.basename(p)[:-6]
|
|
out.append(dict(tag=tag, path=p, rj=rj, ev=ev,
|
|
fold=0 if int(tag.split("run")[1]) <= 7 else 1))
|
|
return out
|
|
|
|
|
|
def load_battle(bf):
|
|
rounds = json.load(open(bf["rj"]))["rounds"]
|
|
starts = [(r["startTick"], r["startTick"] + r["count"]) for r in rounds]
|
|
T, EX, EY, EH, ES, SX, SY, SE, EE = [], [], [], [], [], [], [], [], []
|
|
RND = []
|
|
r = 0
|
|
with open(bf["path"]) as f:
|
|
for line in f:
|
|
if '"tick"' not in line:
|
|
continue
|
|
o = json.loads(line)
|
|
while r + 1 < len(starts) and o["tick"] >= starts[r + 1][0]:
|
|
r += 1
|
|
RND.append(r)
|
|
T.append(o["tick"])
|
|
EX.append(o["ex"]); EY.append(o["ey"])
|
|
EH.append(o["eh"]); ES.append(o["es"])
|
|
SX.append(o["sx"]); SY.append(o["sy"])
|
|
SE.append(o["se"]); EE.append(o["ee"])
|
|
return dict(T=T, ex=EX, ey=EY, eh=EH, es=ES, sx=SX, sy=SY, se=SE, ee=EE,
|
|
rnd=RND, starts=starts)
|
|
|
|
|
|
def get_battle(bf):
|
|
b = _CACHE.get(bf["tag"])
|
|
if b is None:
|
|
b = _CACHE[bf["tag"]] = load_battle(bf)
|
|
return b
|
|
|
|
|
|
def cadence(bfs):
|
|
gaps = collections.Counter()
|
|
rows = 0
|
|
for bf in bfs:
|
|
prev = None
|
|
for line in open(bf["path"]):
|
|
if '"tick"' not in line:
|
|
continue
|
|
t = json.loads(line)["tick"]
|
|
rows += 1
|
|
if prev is not None:
|
|
gaps[t - prev] += 1
|
|
prev = t
|
|
return rows, gaps
|
|
|
|
|
|
def real_shots(bfs):
|
|
"""US (= the `s*` adversary, ModularBot) fired shots, by the same
|
|
energy-drop attribution measure_gk_residual.py uses."""
|
|
per_run = {}
|
|
for bf in bfs:
|
|
b = load_battle(bf)
|
|
pos = {t: i for i, t in enumerate(b["T"])}
|
|
votes = collections.defaultdict(collections.Counter)
|
|
|
|
def match(t, side, ev):
|
|
i, i1 = pos.get(t), pos.get(t + 1)
|
|
if i is None or i1 is None:
|
|
return False
|
|
if abs(b[side + "x"][i] - ev["x"]) > 0.02 or \
|
|
abs(b[side + "y"][i] - ev["y"]) > 0.02:
|
|
return False
|
|
ef = "ee" if side == "e" else "se"
|
|
return abs((b[ef][i] - b[ef][i1]) - ev["power"]) < 0.02
|
|
|
|
for ev in (json.loads(l) for l in open(bf["ev"]) if l.strip()):
|
|
if ev.get("type") != "fire":
|
|
continue
|
|
g = ev.get("tick", 0)
|
|
for t in range(g - 8, g + 9):
|
|
for side in ("e", "s"):
|
|
if match(t, side, ev):
|
|
votes[ev["owner"]][side] += 1
|
|
n = 0
|
|
for o, c in votes.items():
|
|
if c and c.most_common(1)[0][0] == gkm.US_SIDE:
|
|
n += sum(c.values())
|
|
per_run[bf["tag"]] = n
|
|
_CACHE.pop(bf["tag"], None)
|
|
return per_run
|
|
|
|
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
# the replay
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
class Acc:
|
|
__slots__ = ("n", "tk", "eb2", "eab", "el2", "eal", "hb", "nb", "hl", "nl",
|
|
"hd", "hbp", "hlp", "cov", "res")
|
|
|
|
def __init__(self):
|
|
for s in self.__slots__:
|
|
setattr(self, s, 0.0)
|
|
|
|
def add(self, o):
|
|
for s in self.__slots__:
|
|
setattr(self, s, getattr(self, s) + getattr(o, s))
|
|
|
|
def as_dict(self):
|
|
return {s: getattr(self, s) for s in self.__slots__}
|
|
|
|
|
|
def replay(b, arm, table, learn, thr, eps, rng, test):
|
|
"""One battle. learn=True: training replay (learns, scores nothing).
|
|
test=True: held-out replay, table frozen, base and learn flown side by side.
|
|
Returns (per-band Acc list, counters)."""
|
|
T, EX, EY, EH, ES = b["T"], b["ex"], b["ey"], b["eh"], b["es"]
|
|
SX, SY, SE, EE = b["sx"], b["sy"], b["se"], b["ee"]
|
|
rnd, starts = b["rnd"], b["starts"]
|
|
n = len(T)
|
|
|
|
acc = [Acc() for _ in range(N_BAND)]
|
|
c = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
|
|
explore=0, learn_hits=0)
|
|
|
|
a_fx, a_fy, a_ux, a_uy, a_tr, a_sp = [], [], [], [], [], []
|
|
a_hit, a_key, a_bn, a_arm, a_bd, a_pi = [], [], [], [], [], []
|
|
bh = [0.0] * (n + 1) # per spawn tick: did the BASE flight hit?
|
|
|
|
prev_t = -10
|
|
rr = -1
|
|
prev_ex = prev_ey = prev_eh = prev_es = 0.0
|
|
has_prev = False
|
|
rad_ring = [0.0] * VEL_WINDOW
|
|
rad_head = rad_count = 0
|
|
|
|
fB, band_of = gkm.production_base, gkm.band_of
|
|
space_of, wrap180 = gkm.space_of, gkm.wrap180
|
|
atan2d = math.degrees
|
|
R2 = BOT_RADIUS * BOT_RADIUS
|
|
|
|
for j in range(n):
|
|
t = T[j]
|
|
if rnd[j] != rr or t != prev_t + 1:
|
|
if a_fx:
|
|
c["round"] += len(a_fx)
|
|
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
|
|
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
|
|
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
|
|
rr = rnd[j]
|
|
has_prev = False
|
|
rad_count = rad_head = 0
|
|
prev_t = t
|
|
|
|
ex, ey, eh, es = EX[j], EY[j], EH[j], ES[j]
|
|
sx, sy = SX[j], SY[j]
|
|
e_alive = EE[j] > 0.0
|
|
s_alive = SE[j] > 0.0
|
|
end = starts[rr][1] if rr >= 0 else t
|
|
|
|
if e_alive and s_alive:
|
|
dx, dy = ex - sx, ey - sy
|
|
dist = math.sqrt(dx * dx + dy * dy)
|
|
if dist > 1e-6:
|
|
c["ticks"] += 1
|
|
if has_prev:
|
|
rate = wrap180(eh - prev_eh)
|
|
turning = GK_LEFT if rate > GK_TURN_DEAD else (
|
|
GK_RIGHT if rate < -GK_TURN_DEAD else GK_STRAIGHT)
|
|
dv = es - prev_es
|
|
trend = GK_ACCEL if dv > GK_TREND_DEAD else (
|
|
GK_DECEL if dv < -GK_TREND_DEAD else GK_CONST)
|
|
ddx, ddy = ex - prev_ex, ey - prev_ey
|
|
spd = math.sqrt(ddx * ddx + ddy * ddy)
|
|
frac = 0.0
|
|
if spd > 0.1:
|
|
frac = abs((ddx * (sx - ex) + ddy * (sy - ey)) / dist) / spd
|
|
rad_ring[rad_head] = frac
|
|
rad_head = (rad_head + 1) % VEL_WINDOW
|
|
if rad_count < VEL_WINDOW:
|
|
rad_count += 1
|
|
else:
|
|
turning = trend = GK_UNKNOWN
|
|
prev_ex, prev_ey, prev_eh, prev_es = ex, ey, eh, es
|
|
has_prev = True
|
|
rf = 0.0
|
|
if rad_count:
|
|
nn = min(RADIAL_WINDOW, rad_count)
|
|
s = 0.0
|
|
for i in range(nn):
|
|
s += rad_ring[(rad_head - 1 - i) % VEL_WINDOW]
|
|
rf = s / nn
|
|
band = band_of(dist)
|
|
sp = space_of(ex, ey, sx, sy)
|
|
rad = 0 if rf < 0.25 else 1 if rf < 0.5 else 2 if rf < 0.75 else 3
|
|
k = key_of(band, sp, turning, trend, rad, arm)
|
|
|
|
# ---- what aim() applies this tick ----
|
|
if learn:
|
|
if table.att[k] < thr:
|
|
res, ub = 0.0, -1
|
|
table.att[k] += 1
|
|
if eps > 0.0 and rng.random() < eps:
|
|
ub = rng.randrange(GK_NBINS)
|
|
res = CENTRE[ub]
|
|
c["explore"] += 1
|
|
else:
|
|
res, ub = best_residual(table.hits[k])
|
|
else:
|
|
res, ub = table.residual(k)
|
|
|
|
if test:
|
|
A = acc[band]
|
|
A.tk += 1
|
|
A.cov += 1.0 if res != 0.0 else 0.0
|
|
A.res += abs(res)
|
|
los = atan2d(math.atan2(dy, dx))
|
|
for bi in range(4):
|
|
A.n += 1
|
|
v = SPEEDS[bi]
|
|
kk = 1
|
|
kst = -1
|
|
while kk <= MAX_FLIGHT and t + kk < end and j + kk < n \
|
|
and T[j + kk] == t + kk:
|
|
qx = EX[j + kk] - sx
|
|
qy = EY[j + kk] - sy
|
|
if math.sqrt(qx * qx + qy * qy) <= v * kk:
|
|
kst = kk
|
|
break
|
|
kk += 1
|
|
if kst < 0:
|
|
c["skip"] += 1
|
|
continue
|
|
req = wrap180(atan2d(math.atan2(EY[j + kst] - sy,
|
|
EX[j + kst] - sx)) - los)
|
|
bl = wrap180(fB(ex, ey, eh, es, sx, sy, v) - los)
|
|
eb = wrap180(bl - req)
|
|
el = wrap180(bl + res - req)
|
|
A.eb2 += eb * eb
|
|
A.eab += abs(eb)
|
|
A.el2 += el * el
|
|
A.eal += abs(el)
|
|
|
|
# ---- spawnBullets ----
|
|
for bi in range(4):
|
|
v = SPEEDS[bi]
|
|
bse = fB(ex, ey, eh, es, sx, sy, v)
|
|
a_fx.append(sx); a_fy.append(sy)
|
|
a_tr.append(0.0); a_sp.append(v)
|
|
a_hit.append(False); a_key.append(k); a_bn.append(ub)
|
|
a_bd.append(band); a_pi.append(j)
|
|
a_ux.append(math.cos(math.radians(bse)))
|
|
a_uy.append(math.sin(math.radians(bse)))
|
|
if res != 0.0:
|
|
a_arm.append(ARM_BASE)
|
|
c["split"] += 1
|
|
a_fx.append(sx); a_fy.append(sy)
|
|
a_tr.append(0.0); a_sp.append(v)
|
|
a_hit.append(False); a_key.append(k); a_bn.append(ub)
|
|
a_bd.append(band); a_pi.append(j)
|
|
a_ux.append(math.cos(math.radians(bse + res)))
|
|
a_uy.append(math.sin(math.radians(bse + res)))
|
|
a_arm.append(ARM_LEARN)
|
|
else:
|
|
a_arm.append(ARM_BOTH)
|
|
c["shared"] += 1
|
|
|
|
# ---- tickBullets: advance every bullet one tick ----
|
|
if a_fx:
|
|
if not e_alive:
|
|
c["dead"] += len(a_fx)
|
|
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
|
|
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
|
|
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
|
|
else:
|
|
w = 0
|
|
for i in range(len(a_fx)):
|
|
sp = a_sp[i]
|
|
tr = a_tr[i] + sp
|
|
fx, fy = a_fx[i], a_fy[i]
|
|
ux, uy = a_ux[i], a_uy[i]
|
|
ddx = ex - fx
|
|
ddy = ey - fy
|
|
along = ux * ddx + uy * ddy
|
|
perp = -uy * ddx + ux * ddy
|
|
hit = a_hit[i]
|
|
if not hit and perp * perp < R2:
|
|
prev_d = tr - sp
|
|
if along > prev_d - BOT_RADIUS and along < tr + BOT_RADIUS:
|
|
seg = along - (prev_d if along < prev_d else
|
|
(tr if along > tr else along))
|
|
if seg * seg + perp * perp < R2:
|
|
hit = True
|
|
bx = fx + ux * tr
|
|
by = fy + uy * tr
|
|
if bx < 0.0 or bx > ARENA_W or by < 0.0 or by > ARENA_H:
|
|
c["resolved"] += 1
|
|
if learn:
|
|
k = a_key[i]
|
|
table.att[k] += 1
|
|
if hit:
|
|
b = a_bn[i]
|
|
table.row(k)[b if b >= 0 else GK_NULL_BIN] += 1
|
|
c["learn_hits"] += 1
|
|
else:
|
|
A = acc[a_bd[i]]
|
|
am = a_arm[i]
|
|
hv = 1.0 if hit else 0.0
|
|
if am == ARM_LEARN:
|
|
A.nl += 1
|
|
A.hl += hv
|
|
# PAIRED: the baseline flight for THIS spawn tick
|
|
A.hd += 1
|
|
A.hbp += bh[a_pi[i]]
|
|
A.hlp += hv
|
|
elif am == ARM_BOTH:
|
|
A.nb += 1; A.hb += hv
|
|
A.nl += 1; A.hl += hv
|
|
bh[a_pi[i]] = hv
|
|
else:
|
|
A.nb += 1; A.hb += hv
|
|
bh[a_pi[i]] = hv
|
|
continue
|
|
a_fx[w] = fx; a_fy[w] = fy; a_ux[w] = ux; a_uy[w] = uy
|
|
a_tr[w] = tr; a_sp[w] = sp; a_hit[w] = hit
|
|
a_key[w] = a_key[i]; a_bn[w] = a_bn[i]; a_arm[w] = a_arm[i]
|
|
a_bd[w] = a_bd[i]; a_pi[w] = a_pi[i]
|
|
w += 1
|
|
del a_fx[w:]; del a_fy[w:]; del a_ux[w:]; del a_uy[w:]
|
|
del a_tr[w:]; del a_sp[w:]; del a_hit[w:]
|
|
del a_key[w:]; del a_bn[w:]; del a_arm[w:]; del a_bd[w:]
|
|
del a_pi[w:]
|
|
c["inflight"] = len(a_fx)
|
|
return acc, c
|
|
|
|
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
# driver
|
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
_G = {}
|
|
|
|
|
|
def _test_one(bf):
|
|
b = get_battle(bf)
|
|
acc, c = replay(b, _G["arm"], _G["table"], False, 0, 0.0, None, True)
|
|
return bf["tag"], [a.as_dict() for a in acc], c
|
|
|
|
|
|
def run_config(arm, thr, eps, bfs, outdir):
|
|
t0 = time.time()
|
|
res = dict(arm=arm, thr=thr, eps=eps, folds=[])
|
|
for fold in (0, 1):
|
|
table = Table(nrows(arm))
|
|
rng = random.Random(1234 + fold)
|
|
ctr = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
|
|
ticks=0, explore=0, learn_hits=0, inflight=0)
|
|
for bf in bfs: # TRAINING: sequential, table evolves
|
|
if bf["fold"] == fold:
|
|
continue
|
|
_, c = replay(get_battle(bf), arm, table, True, thr, eps, rng, False)
|
|
for k in ctr:
|
|
ctr[k] += c[k]
|
|
nz, trusted, mean_abs = table.stats()
|
|
_G["arm"], _G["table"] = arm, table
|
|
with Pool(4) as pool: # TEST: frozen table, battles parallel
|
|
out = pool.map(_test_one, [bf for bf in bfs if bf["fold"] != fold])
|
|
pooled = [Acc() for _ in range(N_BAND)]
|
|
ctest = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
|
|
ticks=0, explore=0, learn_hits=0, inflight=0)
|
|
battles = []
|
|
for tag, bands, c in out:
|
|
A = []
|
|
for a in bands:
|
|
A.append(_mk(a))
|
|
pooled[len(A) - 1].add(A[-1])
|
|
for k in ctest:
|
|
ctest[k] += c[k]
|
|
tb = Acc()
|
|
for a in A:
|
|
tb.add(a)
|
|
battles.append(dict(tag=tag, n=tb.n, tk=tb.tk, eb2=tb.eb2, el2=tb.el2,
|
|
nb=tb.nb, hb=tb.hb, nl=tb.nl, hl=tb.hl,
|
|
hd=tb.hd, hbp=tb.hbp, hlp=tb.hlp,
|
|
cov=tb.cov, res=tb.res))
|
|
res["folds"].append(dict(fold=fold, nz=nz, trusted=trusted,
|
|
mean_abs=mean_abs, train=ctr, test=ctest,
|
|
bands=[a.as_dict() for a in pooled],
|
|
battles=battles))
|
|
_G.clear()
|
|
json.dump(res, open(os.path.join(outdir, "gk_%s_%d.json" % (arm, thr)), "w"))
|
|
return time.time() - t0
|
|
|
|
|
|
def rms(x):
|
|
return math.sqrt(x) if x >= 0 else float("nan")
|
|
|
|
|
|
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 report(cfg_path, real_n, rows, gaps, bfs):
|
|
r = json.load(open(cfg_path))
|
|
print("=" * 100)
|
|
print("CONFIG key=%s explore-attempts=%d eps=%.2f" % (r["arm"], r["thr"], r["eps"]))
|
|
tt = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
|
|
explore=0, learn_hits=0, inflight=0)
|
|
cte = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
|
|
explore=0, learn_hits=0, inflight=0)
|
|
for f in r["folds"]:
|
|
for k in tt:
|
|
tt[k] += f["train"][k]
|
|
cte[k] += f["test"][k]
|
|
ntr = len(bfs) // 2 * 2
|
|
print(" TRAINING (the %d held-in battles of each of the 2 folds, replayed"
|
|
" sequentially, table rebuilt per fold):" % (ntr // 2))
|
|
print(" virtual bullets spawned %d resolved %d in flight at battle end %d"
|
|
% (4 * tt["ticks"] + tt["split"], tt["resolved"], tt["inflight"]))
|
|
print(" dropped unscored: target dead %d, round boundary %d of which the"
|
|
" two arms flew ONE identical ray: %d" % (tt["dead"], tt["round"], tt["shared"]))
|
|
print(" resolutions credited as HITS: %d epsilon-greedy draws: %d"
|
|
% (tt["learn_hits"], tt["explore"]))
|
|
tot = [Acc() for _ in range(N_BAND)]
|
|
bl = []
|
|
for f in r["folds"]:
|
|
for i, a in enumerate(f["bands"]):
|
|
tot[i].add(_mk(a))
|
|
bl += f["battles"]
|
|
for f in r["folds"]:
|
|
print(" fold %d: rows above the trust threshold %d, with a NON-ZERO"
|
|
" argmax %d, mean |residual| of those %+.2f deg"
|
|
% (f["fold"], f["trusted"], f["nz"], f["mean_abs"]))
|
|
ntest = sum(b["tk"] for b in bl)
|
|
nvb = sum(b["nb"] for b in bl)
|
|
nvl = sum(b["nl"] for b in bl)
|
|
cov = sum(b["cov"] for b in bl)
|
|
rr = sum(b["res"] for b in bl)
|
|
print(" HELD-OUT (2-fold by battle, both folds pooled, every bullet tested once):")
|
|
print(" virtual bullets TESTED: base arm %d, learned arm %d"
|
|
" (%.1fx the %d real fired shots)" % (nvb, nvl, nvl / max(real_n, 1), real_n))
|
|
print(" held-out target ticks (both bots alive): %d x4 power bins = %d aim"
|
|
" decisions skipped (no interception before the round end): %d"
|
|
% (ntest, int(sum(a.n for a in tot)), cte["skip"]))
|
|
print(" held-out ticks carrying a NON-ZERO residual: %d (%.2f%%) mean"
|
|
" |residual| applied %.3f deg"
|
|
% (int(cov), 100.0 * cov / max(ntest, 1), rr / max(ntest, 1)))
|
|
print(" %-8s %9s %8s %8s %8s | %8s %8s %8s %8s | %10s"
|
|
% ("band", "aims", "rms_b", "mabs_b", "hit_b%", "rms_l", "mabs_l",
|
|
"hit_l%", "dhit_pp", "paired_n"))
|
|
for i, lab in enumerate(BAND_LAB):
|
|
a = tot[i]
|
|
if a.n <= 0:
|
|
continue
|
|
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
|
|
% (lab, int(a.n), rms(a.eb2 / a.n), a.eab / a.n, 100.0 * a.hb / max(a.nb, 1),
|
|
rms(a.el2 / a.n), a.eal / a.n, 100.0 * a.hl / max(a.nl, 1),
|
|
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
|
|
a = Acc()
|
|
for x in tot:
|
|
a.add(x)
|
|
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
|
|
% ("ALL", int(a.n), rms(a.eb2 / a.n), a.eab / a.n,
|
|
100.0 * a.hb / max(a.nb, 1), rms(a.el2 / a.n), a.eal / a.n,
|
|
100.0 * a.hl / max(a.nl, 1),
|
|
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
|
|
print(" PAIRED (only the ticks where the two arms flew DIFFERENT rays):"
|
|
" base %d/%d hit, learned %d/%d hit -> %+.3f pp"
|
|
% (int(a.hbp), int(a.hd), int(a.hlp), int(a.hd),
|
|
100.0 * (a.hlp - a.hbp) / max(a.hd, 1)))
|
|
# clustered, per-battle paired statistics
|
|
dh, de = [], []
|
|
for b in bl:
|
|
if b["hd"]:
|
|
dh.append((b["hlp"] - b["hbp"]) / b["hd"])
|
|
if b["n"]:
|
|
de.append((b["el2"] - b["eb2"]) / b["n"])
|
|
mh, sh = mean_sd(dh)
|
|
me, se = mean_sd(de)
|
|
th = mh / (sh / math.sqrt(len(dh))) if sh > 0 else 0.0
|
|
te = me / (se / math.sqrt(len(de))) if se > 0 else 0.0
|
|
print(" CLUSTERED by battle (%d battles): dHit %+0.3f pp (sd %0.3f, t=%+.2f)"
|
|
" dMeanSqErr %+8.2f deg2 (sd %8.2f, t=%+.2f)"
|
|
% (len(dh), 100 * mh, 100 * sh, th, me, se, te))
|
|
return r
|
|
|
|
|
|
def _mk(d):
|
|
a = Acc()
|
|
for s in Acc.__slots__:
|
|
setattr(a, s, d[s])
|
|
return a
|
|
|
|
|
|
def main():
|
|
import argparse
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--root", default=ROOT)
|
|
ap.add_argument("--arms", default="full,dt")
|
|
ap.add_argument("--thresholds", default="5,100")
|
|
ap.add_argument("--eps", type=float, default=0.25)
|
|
ap.add_argument("--limit", type=int, default=0, help="first N battles (smoke)")
|
|
ap.add_argument("--out", default="/tmp/gk_virtual")
|
|
a = ap.parse_args()
|
|
|
|
bfs = battle_files(a.root)
|
|
if a.limit:
|
|
bfs = bfs[:a.limit]
|
|
if not bfs:
|
|
print("NO CORPUS at %s" % a.root)
|
|
return 1
|
|
os.makedirs(a.out, exist_ok=True)
|
|
rows, gaps = cadence(bfs)
|
|
real = real_shots(bfs)
|
|
real_n = sum(real.values())
|
|
|
|
print("CORPUS %s" % a.root)
|
|
print(" battles: %d worldstate rows: %d" % (len(bfs), rows))
|
|
print(" TICK CADENCE: inter-row deltas %s"
|
|
% (dict(gaps) if gaps else "none (one row per tick, contiguous)"))
|
|
print(" -> NO interpolation needed: every tick is recorded, so a virtual"
|
|
" bullet's swept segment is tested against the enemy position of that"
|
|
" exact tick.")
|
|
print(" REAL fired shots by the US bot (energy-drop attribution): %d"
|
|
% real_n)
|
|
print(" power bins %s -> bullet speeds %s ; BotRadius %.1f ; arena %.0fx%.0f"
|
|
% (POWER_BINS, SPEEDS, BOT_RADIUS, ARENA_W, ARENA_H))
|
|
print()
|
|
|
|
arms = a.arms.split(",")
|
|
thrs = [int(x) for x in a.thresholds.split(",")]
|
|
procs = []
|
|
for arm in arms:
|
|
for thr in thrs:
|
|
p = Process(target=run_config,
|
|
args=(arm, thr, a.eps, bfs, a.out))
|
|
p.start()
|
|
procs.append(p)
|
|
for p in procs:
|
|
p.join()
|
|
if p.exitcode:
|
|
print("!! a config process exited %d" % p.exitcode)
|
|
print()
|
|
for arm in arms:
|
|
for thr in thrs:
|
|
f = os.path.join(a.out, "gk_%s_%d.json" % (arm, thr))
|
|
if os.path.exists(f):
|
|
report(f, real_n, rows, gaps, bfs)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|