diff --git a/tools/elm_bench/extract_predict.py b/tools/elm_bench/extract_predict.py new file mode 100644 index 0000000..9ebf24d --- /dev/null +++ b/tools/elm_bench/extract_predict.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Movement-prediction corpus: LABEL = correction from the geometric intercept to +the enemy's TRUE impact point. + +This replaces the old opponent-bias label. The old label measured how far the +SHOOTER's shot landed from a correct intercept (the opponent's own aim error); +using that as our own correction is why the ELM added a constant +1.6..+11 deg +bias. The new label measures the TARGET's real motion deviation: + + base = plain geometric intercept bearing, solved from the target's CURRENT + scan-based position/velocity (the same `heuristicAim` the gun runs); + true = bearing to the target's ACTUAL position at the tick the bullet of + speed v reaches it, taken from the observer's true trajectory; + label = wrap(true - base). + +A target that holds a straight line gives label 0; a target that turns/accelerates +gives the correction a real movement-prediction gun must apply. Samples are built +with the shooter FIXED to DevControlBot (power 2, v = 14) so the shooter's own +state and the bullet speed match the live gun; the TARGET is the opponent whose +movement we want to learn. + +Output: samples_predict.ndjson, one row per sampled tick. + + python3 extract_predict.py [OUT.ndjson] [ROOT] [--stride N] [--shooter NAME] +""" +import glob, gzip, json, math, os, sys + +TAU = 2 * math.pi +W = 8 # motion-window length (scans), newest first +POWER = 2.0 +VB = 20.0 - 3.0 * POWER # physical bullet speed, = 14 + + +def wrap(a): + while a > math.pi: + a -= TAU + while a < -math.pi: + a += TAU + return a + + +def sample_std(v): + if len(v) < 2: + return 0.0 + m = sum(v) / len(v) + return math.sqrt(sum((x - m) ** 2 for x in v) / len(v)) + + +def extract(path, tag, out, shooter_name, stride): + ticks = [] + 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": + ticks.append(m) + + # true trajectory: (round, botId) -> {turn: (x, y)} + track = {} + names = {} + for m in ticks: + rnd, turn = m["roundNumber"], m["turnNumber"] + for b in m["botStates"]: + names[b["id"]] = b["name"] + track.setdefault((rnd, b["id"]), {})[turn] = (b["x"], b["y"]) + + def true_pos(rnd, bid, t): + tr = track[(rnd, bid)] + lo = math.floor(t) + if lo not in tr: + return None + if lo + 1 in tr: + f = t - lo + x0, y0 = tr[lo] + x1, y1 = tr[lo + 1] + return (x0 + (x1 - x0) * f, y0 + (y1 - y0) * f) + return tr[lo] + + n = 0 + for m in ticks: + rnd, turn = m["roundNumber"], m["turnNumber"] + if turn % stride != 0: + continue + bs = {b["id"]: b for b in m["botStates"]} + sids = [i for i, b in bs.items() if b["name"] == shooter_name and b["energy"] > 0] + if len(sids) != 1: + continue + sid = sids[0] + tid = [i for i in bs if i != sid and bs[i]["energy"] > 0] + if len(tid) != 1: + continue + tid = tid[0] + S = (bs[sid]["x"], bs[sid]["y"]) + tr = track.get((rnd, tid), {}) + # need a full window of true positions behind the fire tick + if len(tr) < W or any((turn - k) not in tr for k in range(1, W)): + continue + + win = [tr[turn - k] for k in range(W)] # newest first + winTick = [turn - k for k in range(W)] + ex, ey = win[0] + vx = (win[0][0] - win[1][0]) / float(winTick[0] - winTick[1]) + vy = (win[0][1] - win[1][1]) / float(winTick[0] - winTick[1]) + + # ---- base: geometric intercept from the scan belief (heuristicAim) ---- + d = math.hypot(ex - S[0], ey - S[1]) + tof = d / VB + bx, by = ex + vx * tof, ey + vy * tof + base = math.atan2(by - S[1], bx - S[0]) + + # ---- true impact: target's TRUE position when the bullet arrives ----- + t = d / VB + p = true_pos(rnd, tid, turn + t) + for _ in range(8): + if p is None: + break + t = math.hypot(p[0] - S[0], p[1] - S[1]) / VB + p = true_pos(rnd, tid, turn + t) + if p is None: + continue + true_ang = math.atan2(p[1] - S[1], p[0] - S[0]) + label = wrap(true_ang - base) + + # ---- features (target-motion-centric) -------------------------------- + ang = math.atan2(ey - S[1], ex - S[0]) # line-of-sight bearing + rel = wrap(ang - math.radians(bs[sid]["direction"])) + sp = math.hypot(vx, vy) + lat = -vx * math.sin(ang) + vy * math.cos(ang) + rad = vx * math.cos(ang) + vy * math.sin(ang) + losrate = lat / max(d, 1.0) + pred_err = wrap(base - ang) + disp = [] + speeds = [] + for k in range(W - 1): + gap = float(winTick[k] - winTick[k + 1]) + dx = (win[k][0] - win[k + 1][0]) / gap + dy = (win[k][1] - win[k + 1][1]) / gap + disp.append((dx, dy)) + speeds.append(math.hypot(dx, dy)) + # heading / turn of the newest two displacements + hx, hy = disp[0] + head = math.atan2(hy, hx) + phead = math.atan2(disp[1][1], disp[1][0]) + dtheta = wrap(head - phead) + curve = abs(dtheta) / max(sp, 1e-6) + + rec = { + "group": f"{names[tid]}:{tag}:{rnd}", + "target": names[tid], + "round": rnd, "tick": turn, "shooter": shooter_name, + "label": label, + "ownX": S[0], "ownY": S[1], + "ownHeading": math.radians(bs[sid]["direction"]), + "ownSpeed": abs(bs[sid]["speed"]), + "gunHeat": bs[sid].get("gunHeat", 0.0), + "power": POWER, "bulletSpeed": VB, + "ex": ex, "ey": ey, "vx": vx, "vy": vy, + "scanAge": 0.0, "scanGap": 1.0, + "winX": [p[0] for p in win], "winY": [p[1] for p in win], + "winTick": winTick, + # diagnostics + "dbg_speed": sp, "dbg_curve": curve, + } + out.write(json.dumps(rec) + "\n") + n += 1 + return n + + +def main(): + here = os.path.dirname(os.path.abspath(__file__)) + repo = os.path.abspath(os.path.join(here, "..", "..")) + args = [a for a in sys.argv[1:] if not a.startswith("--")] + stride = 5 + shooter = "DevControlBot" + for a in sys.argv[1:]: + if a.startswith("--stride"): + stride = int(a.split("=")[1]) if "=" in a else stride + if a.startswith("--shooter"): + shooter = a.split("=")[1] if "=" in a else shooter + dest = os.path.join(here, args[0] if args else "samples_predict.ndjson") + root = os.path.abspath(args[1]) if len(args) > 1 else os.path.join(repo, "data") + 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, out, shooter, stride) + print(f"{tag}/{os.path.basename(f)}: {k} samples") + total += k + print("TOTAL", total, "->", dest) + + +if __name__ == "__main__": + main() diff --git a/tools/elm_bench/extract_realistic.py b/tools/elm_bench/extract_realistic.py index 4fd2099..9d5a0c7 100644 --- a/tools/elm_bench/extract_realistic.py +++ b/tools/elm_bench/extract_realistic.py @@ -1,5 +1,14 @@ #!/usr/bin/env python3 -"""Extract aim-error samples with ONLY shooter-observable features. +"""DEPRECATED — the OPPONENT-AIM-BIAS label. DO NOT USE for the gun. + +This measures how far the SHOOTER's own shot landed from a correct intercept, +which is the opponent's aim error, not anything about the enemy's movement. +Using it as our own correction is exactly the bug that was removed: it taught the +gun to aim like the opponent, adding a constant +0.042 rad bias. The movement- +prediction replacement is extract_predict.py (label = true impact - geometric +intercept). Kept only so the old bench_realistic.nim experiments reproduce. + +Extract aim-error samples with ONLY shooter-observable features. Same LABEL as extract.py (ground truth correction, unchanged), same samples (same BulletFiredEvents), but every feature is derived from what the shooter diff --git a/tools/elm_bench/train_elm_gun.nim b/tools/elm_bench/train_elm_gun.nim deleted file mode 100644 index 84a45d0..0000000 --- a/tools/elm_bench/train_elm_gun.nim +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env nim c -r -# Train the aim-error ELM on the POOLED multi-opponent corpus and export the -# weights for the in-game gun. -# -# cd DevControlBot_garage/DevControlBot -# nim c -r ../../tools/elm_bench/train_elm_gun.nim -# -# Corpus: tools/elm_bench/gen/*.ndjson (the `*_prev.ndjson` variants are the -# strictly-prior-scan ablation and are NOT used — the live bot legitimately sees -# the same tick's scan it fires on). Features are rebuilt from each record's -# belief_* fields into a GunBelief and passed through the SAME buildFeatures the -# gun uses, so training and inference cannot diverge. -# -# Output: modules/ELM/elm_gun_weights.txt (plain text, documented in elm_gun.nim) - -import std/[algorithm, json, math, os, sequtils, strutils] -import modules/ELM/elm -import modules/ELM/elm_features - -const - HiddenDim = 128 - Lambda = 1e-2 # pooled training: the corpus is 9 opponents, so more - # regularisation than the single-opponent 1e-3 run - Decay = 1.0 # no forgetting: every shot of every opponent is a prior - Seed = 12345 - CorpusDir = "../../tools/elm_bench/gen" - OutFile = "modules/ELM/elm_gun_weights.txt" - -proc reconstruct(j: JsonNode): GunBelief = - ## Corpus belief_* fields -> the GunBelief the gun builds at runtime. - ## (Everything is stored body-relative in the corpus, so undo ownHeading to - ## get the absolute line-of-sight angle back.) - result.everScanned = j["beliefEverScanned"].getFloat > 0.5 - result.selfX = j["ownX"].getFloat - result.selfY = j["ownY"].getFloat - result.selfHeading = j["ownHeading"].getFloat - result.selfSpeed = j["ownSpeed"].getFloat - result.gunHeat = j["gunHeat"].getFloat - result.power = j["power"].getFloat - result.bulletSpeed = j["bulletSpeed"].getFloat # = power * 10 in this corpus - result.scanAge = j["beliefScanAge"].getFloat - result.scanGap = j["beliefScanGap"].getFloat - result.ownDisp = j["beliefDisp"].getFloat - let ang = j["beliefRelBearing"].getFloat + result.selfHeading - let de = j["beliefDist"].getFloat - result.ex = result.selfX + de * cos(ang) - result.ey = result.selfY + de * sin(ang) - let lat = j["beliefTgtLatVel"].getFloat - let rad = -j["beliefClosing"].getFloat # closing is -rad - result.vx = rad * cos(ang) - lat * sin(ang) - result.vy = rad * sin(ang) + lat * cos(ang) - -proc main() = - var e = initElm(ElmConfig(inputDim: FeatureDim, hiddenDim: HiddenDim, outputs: 1, - seed: Seed, lambda: Lambda, decay: Decay, refitEvery: 0)) - var n = 0 - var files = sorted(toSeq(walkFiles(CorpusDir / "*.ndjson"))) - var xs = newSeq[float64]() - var ts = newSeq[float64]() - for f in files: - if f.endsWith("_prev.ndjson"): continue - var k = 0 - for line in lines(f): - if line.len == 0: continue - let j = parseJson(line) - var x: seq[float64] = @[] - for v in buildFeatures(reconstruct(j)): x.add v - e.train(x, @[j["label"].getFloat]) - xs.add j["label"].getFloat - inc k - echo " ", f.extractFilename(), ": ", k, " samples" - n += k - e.refit() - let d = diagnostics(e) - echo "samples=", n, " trainRmse=", d.trainRmse - - var s2 = 0.0 - for i in 0 ..< xs.len: s2 += xs[i] * xs[i] - echo "label RMS (constant baseline) = ", sqrt(s2 / float64(xs.len)) - - let w = exportWeights(e) - var o = open(OutFile, fmWrite) - o.write("# DevControlBot ELM gun — exported ELM weights. Plain text, one matrix per line.\n") - o.write("# inputDim hiddenDim outputs lambda decay seed activation featureCount\n") - o.write("# ") - o.write(featureNames.join(" ")) - o.write("\n") - o.write(FeatureDim, " ", HiddenDim, " 1 ", Lambda, " ", Decay, " ", Seed, " tanh\n") - o.write("W ", w.W.len, "\n") - o.write(w.W.join(" "), "\n") - o.write("HS ", w.hs.len, "\n") - o.write(w.hs.join(" "), "\n") - o.write("BETA ", w.beta.len, "\n") - o.write(w.beta.join(" "), "\n") - o.write("TRAIN_RMSE ", d.trainRmse, "\n") - o.close() - echo "wrote ", OutFile - -main() \ No newline at end of file diff --git a/tools/elm_bench/train_predict.nim b/tools/elm_bench/train_predict.nim new file mode 100644 index 0000000..7151d4d --- /dev/null +++ b/tools/elm_bench/train_predict.nim @@ -0,0 +1,210 @@ +#!/usr/bin/env nim c -r +# Train + evaluate the MOVEMENT-PREDICTION ELM gun and export the weights. +# +# cd DevControlBot_garage/DevControlBot +# nim c -r ../../tools/elm_bench/train_predict.nim [NDJSON] +# +# Label: correction from the geometric intercept to the enemy's TRUE impact +# point (extract_predict.py). Baseline for non-regression is the PLAIN INTERCEPT, +# i.e. correction == 0, so "constant mean" is reported alongside and the zero +# predictor's RMSE is the number the ELM must beat. +# +# Output: modules/ELM/elm_gun_weights.txt + +import std/[algorithm, json, math, os, sequtils, strutils, strformat, tables] +import modules/ELM/elm +import modules/ELM/elm_features + +const + HiddenDim = 128 + Lambda = 1e-2 + Decay = 1.0 + Seed = 12345 + OutFile = "modules/ELM/elm_gun_weights.txt" + N_FOLD = 5 + +type Sample = object + group: string + target: string + y: float64 + x: array[FeatureDim, float64] + +proc reconstruct(j: JsonNode): GunBelief = + result.everScanned = true + result.selfX = j["ownX"].getFloat + result.selfY = j["ownY"].getFloat + result.selfHeading = j["ownHeading"].getFloat + result.selfSpeed = j["ownSpeed"].getFloat + result.power = j["power"].getFloat + result.bulletSpeed = j["bulletSpeed"].getFloat + result.scanAge = j["scanAge"].getFloat + result.scanGap = j["scanGap"].getFloat + result.ex = j["ex"].getFloat + result.ey = j["ey"].getFloat + result.vx = j["vx"].getFloat + result.vy = j["vy"].getFloat + let wx = j["winX"] + let wy = j["winY"] + let wt = j["winTick"] + result.winN = min(wx.len, WinCap) + for k in 0 ..< result.winN: + result.winX[k] = wx[k].getFloat + result.winY[k] = wy[k].getFloat + result.winTick[k] = wt[k].getInt + +proc load(path: string): seq[Sample] = + for line in lines(path): + if line.len == 0: continue + let j = parseJson(line) + var s: Sample + s.group = j["group"].getStr + s.target = j["target"].getStr + s.y = j["label"].getFloat + s.x = buildFeatures(reconstruct(j)) + result.add s + +type Metrics = object + rmse, mae, medae, mean: float64 + +proc metrics(pred: seq[float64], ys: seq[float64]): Metrics = + var s2, s1 = 0.0 + var ae = newSeq[float64](pred.len) + var m = 0.0 + for k in 0 ..< pred.len: + let d = pred[k] - ys[k] + s2 += d * d; s1 += abs(d); ae[k] = abs(d); m += pred[k] + result.rmse = sqrt(s2 / float64(pred.len)) + result.mae = s1 / float64(pred.len) + ae.sort() + result.medae = ae[ae.len div 2] + result.mean = m / float64(pred.len) + +proc fmtM(tag: string, m: Metrics): string = + fmt"{tag:<26} RMSE {m.rmse:.5f} MAE {m.mae:.5f} medAE {m.medae:.5f} predMean {m.mean:+.5f}" + +proc trainElm(tr: seq[Sample], hid: int, lam: float64, seed: int64): Elm = + result = initElm(ElmConfig(inputDim: FeatureDim, hiddenDim: hid, outputs: 1, + seed: seed, lambda: lam, decay: 1.0, refitEvery: 0)) + for s in tr: result.train(s.x.toSeq(), @[s.y]) + result.refit() + +proc main() = + let path = if paramCount() > 0: paramStr(1) else: "samples_predict.ndjson" + let all = load(path) + echo "== movement-prediction corpus ==" + echo " n = ", all.len, " featureDim = ", FeatureDim + var mu = 0.0 + var sd = 0.0 + for s in all: mu += s.y + mu /= float64(all.len) + for s in all: sd += (s.y - mu) * (s.y - mu) + sd = sqrt(sd / float64(all.len)) + echo fmt" label mean = {mu:+.5f} rad ({mu * 180 / PI:+.3f} deg) sd = {sd:.5f} rad ({sd * 180 / PI:.3f} deg)" + echo " (a well-centred movement label sits at ~0; the old opponent-bias label was +0.042 rad)" + + var groups: seq[string] + for s in all: + if s.group notin groups: groups.add s.group + var foldOf = initTable[string, int]() + for gi, g in groups: foldOf[g] = gi mod N_FOLD + var teIdx: array[N_FOLD, seq[int]] + var trIdx: array[N_FOLD, seq[int]] + for i, s in all: + for f in 0 ..< N_FOLD: + if foldOf[s.group] == f: teIdx[f].add i else: trIdx[f].add i + + # ---- baselines: zero (= plain intercept) and constant mean ---------------- + var allY: seq[float64] = @[] + for s in all: allY.add s.y + var pooledZero = newSeq[float64](all.len) + var pooledConst = newSeq[float64](all.len) + for f in 0 ..< N_FOLD: + var m = 0.0 + for i in trIdx[f]: m += all[i].y + m /= float64(trIdx[f].len) + for i in teIdx[f]: pooledConst[i] = m + let mZero = metrics(pooledZero, allY) + let mConst = metrics(pooledConst, allY) + echo "\n== baselines (pooled held-out, 5 round-group folds) ==" + echo fmtM("(a) plain intercept (0)", mZero) + echo fmtM("(b) constant mean", mConst) + echo fmt" label sd = {sd:.5f} rad" + + # ---- ELM config sweep (small) ---- + type Cfg = tuple[hid: int, lam: float64] + var cfgs: seq[Cfg] = @[(128, 1e-2)] + for h in [64, 256]: + cfgs.add (h, 1e-2) + + type Res = tuple[c: Cfg, m: Metrics, pred: seq[float64]] + var results: seq[Res] + for c in cfgs: + var pred = newSeq[float64](all.len) + for f in 0 ..< N_FOLD: + var tr: seq[Sample] = @[] + for i in trIdx[f]: tr.add all[i] + let e = trainElm(tr, c.hid, c.lam, 42) + for i in teIdx[f]: + pred[i] = infer(e, all[i].x.toOpenArray(0, FeatureDim - 1))[0] + let m = metrics(pred, allY) + results.add (c, m, pred) + echo fmt" H={c.hid:>4} lam={c.lam:>7.0e} RMSE {m.rmse:.5f} MAE {m.mae:.5f} medAE {m.medae:.5f} predMean {m.mean:+.5f}" + results.sort(proc(a, b: Res): int = cmp(a.m.rmse, b.m.rmse)) + let best = results[0] + echo "\n== best config ==" + echo fmtM(fmt"H={best.c.hid} lam={best.c.lam}", best.m) + echo fmt" vs plain intercept: RMSE {mZero.rmse:.5f} -> {best.m.rmse:.5f} ({100.0 * (1.0 - best.m.rmse / mZero.rmse):+.1f}%)" + echo fmt" vs constant mean : RMSE {mConst.rmse:.5f} -> {best.m.rmse:.5f}" + echo fmt" prediction mean (centering): {best.m.mean:+.5f} rad ({best.m.mean * 180 / PI:+.3f} deg) -- must be near 0" + + # ---- confidence gate: |pred| > tau else 0. Calibrate on held-out. ---------- + # The ELM must never be worse than the plain intercept, so we take the MOST + # CONSERVATIVE threshold that still strictly beats zero-correction on held-out + # data: the largest tau whose gated RMSE is below the plain-intercept RMSE. + # Corrections smaller than tau are exactly the geometric aim (correction 0). + echo "\n== gate: apply ELM correction only when |pred| > tau, else 0 ==" + echo " tau(rad) open% gateRMSE zeroRMSE verdict" + var bestTau = 0.0 + var bestR = best.m.rmse + var openAtBest = best.pred.len + for ci in 0 .. 24: + let tau = float(ci) * 0.05 + var gated = newSeq[float64](all.len) + var nOpen = 0 + for k in 0 ..< best.pred.len: + if abs(best.pred[k]) > tau: + gated[k] = best.pred[k]; inc nOpen + let gm = metrics(gated, allY) + # conservative: the largest round threshold that keeps the gated RMSE + # within 2% of the un-gated model, i.e. filters corrections for free. + if gm.rmse <= best.m.rmse * 1.02 and tau > bestTau: + bestTau = tau; bestR = gm.rmse; openAtBest = nOpen + if ci mod 3 == 0: + let verd = if gm.rmse < mZero.rmse: "better" else: "no better" + echo fmt" {tau:7.3f} {100.0 * float(nOpen) / float(best.pred.len):5.1f} {gm.rmse:9.5f} {mZero.rmse:9.5f} {verd}" + echo fmt" chosen (conservative, within 2% of ungated) tau = {bestTau:.3f} rad; gated RMSE {bestR:.5f} vs zero {mZero.rmse:.5f}" + if bestR >= mZero.rmse * 0.999: + echo " GATE NEVER OPENS: the ELM does not beat the plain intercept on held-out data." + bestTau = 1.0e9 + echo fmt" open-rate = {100.0 * float(openAtBest) / float(best.pred.len):.1f}%" + + # ---- fit full corpus, export ---- + let e = trainElm(all, best.c.hid, best.c.lam, Seed) + let w = exportWeights(e) + var o = open(OutFile, fmWrite) + o.write("# DevControlBot MOVEMENT-PREDICTION ELM gun weights. Plain text.\n") + o.write("# inputDim hiddenDim outputs lambda decay seed activation\n") + o.write("# ") + o.write(featureNames.join(" ")) + o.write("\n") + o.write(FeatureDim, " ", best.c.hid, " 1 ", best.c.lam, " ", Decay, " ", Seed, " tanh\n") + o.write("W ", w.W.len, "\n"); o.write(w.W.join(" "), "\n") + o.write("HS ", w.hs.len, "\n"); o.write(w.hs.join(" "), "\n") + o.write("BETA ", w.beta.len, "\n"); o.write(w.beta.join(" "), "\n") + o.write("TRAIN_RMSE ", diagnostics(e).trainRmse, "\n") + # gate threshold as a comment so the gun can read it (kept simple: parse line) + o.write("GATE_TAU ", bestTau, "\n") + o.close() + echo "\nwrote ", OutFile, " (hidden=", best.c.hid, ", lambda=", best.c.lam, ", gate_tau=", bestTau, ")" + +main()