diff --git a/DevControlBot_garage/DevControlBot/DevControlBot.nim b/DevControlBot_garage/DevControlBot/DevControlBot.nim index 965c03e..ddf0c86 100644 --- a/DevControlBot_garage/DevControlBot/DevControlBot.nim +++ b/DevControlBot_garage/DevControlBot/DevControlBot.nim @@ -26,10 +26,12 @@ ## viewer. It is compiled only with `-d:tfilDebug`; see README "Debug graphics". ## ## API: robocode_tankroyale_botapi 1.0.7 (the renamed tankroyale_botapi package). -import std/[os, sequtils] +import std/[math, os, sequtils, strutils] import robocode_tankroyale_botapi import modules/radar import modules/tfil +import modules/ELM/elm_gun +import modules/ELM/elm_features const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds ## only what it scans, so this is a cap, not a limit @@ -38,20 +40,39 @@ const EnemyStaleTicks* = 60 ## drop a scanned enemy not rescanned for this m ## ticks (~1s at 60Hz): a bot seen once would keep ## painting its heat in the field forever +# A/B switch, compile time: `-d:baselineGun` builds the geometric-only gun, the +# default build is the ELM gun. Both go through the same predictAim() call, so +# the two binaries differ by exactly the learned correction and nothing else — +# which is what makes the measured difference attributable. +const UseElm* = not defined(baselineGun) + +const FireSlopDeg = 3.0'f64 ## fire inside this much gun error. The gun turns + ## at most MAX_GUN_TURN_RATE, so a tighter slop + ## just means waiting a tick for no gain: at any + ## real range 3 deg is well under the hit radius. + type DevControlBot* = ref object of Bot mover: TfilModule tick: int enemies: seq[EnemyInfo] ## fed by onScannedBot, cleared on round end + gun: ElmGun ## the ELM gun (or the geometric baseline, see UseElm) + shotsFired: int ## diagnostics, reset on round end + roundNo: int ## bumped on every RoundEnded, so the shot log can be + ## joined to a recording round proc newDevControlBot*(): DevControlBot = result = DevControlBot() result.mover = initTFIL() # movement is programmed -> body/turret/gun BLACK + result.gun = initElmGun() # the gun loads its exported weights here, once setRadarColor(WHITE) # overwritten by initRadar() before the first tick method onScannedBot*(bot: DevControlBot, e: ScannedBotEvent) = onScan(e.x, e.y) # remembered; commandRadar() re-aims every tick # (e.scannedBotId, schemas.nim:305, is the # scanned bot's identity) + # ...and the full history the gun needs: this tick, the position, and where WE + # were when we saw it (own displacement since the scan is a model feature). + onScanFull(bot.tick, e.x, e.y, getX(), getY()) # ...and remembered for the movement: the heat field paints every enemy it # knows about. One entry per id, refreshed in place, oldest dropped past the cap. for i, ei in bot.enemies: @@ -78,9 +99,37 @@ method onBulletHit*(bot: DevControlBot, e: BulletHitBotEvent) = bot.mover.noteDamageDealt(e.damage) method onRoundEnded*(bot: DevControlBot, e: RoundEndedEventForBot) = + inc bot.roundNo bot.enemies = @[] + bot.shotsFired = 0 bot.mover.resetRound() +method buildBelief(bot: DevControlBot, power: float): GunBelief = + ## Assemble what the gun is allowed to know. Everything here comes from our + ## own state or from modules/radar.nim's scan history — there is no oracle. + let (vx, vy) = targetVelocity() + let age = scanAge(scanTick) + result.everScanned = haveLast and age >= 0 + result.selfX = getX() + result.selfY = getY() + # The API speaks DEGREES everywhere (getDirection, normalizeRelativeAngle, + # setGunTurnRate); the model speaks radians (every angle in the corpus). This + # conversion is the whole difference between a gun that aims and one that + # sprays bullets into the walls. + result.selfHeading = degToRad(getDirection()) + result.selfSpeed = getSpeed() + result.ownDisp = ownDisp(getX(), getY()) + result.scanAge = age + result.scanGap = scanGap() + result.vx = vx + result.vy = vy + # dead-reckon: last seen position advanced by the estimated velocity + result.ex = lastScan.x + vx * age + result.ey = lastScan.y + vy * age + result.power = power + result.bulletSpeed = 20.0 - 3.0 * power + result.gunHeat = getGunHeat() + method ageEnemies(bot: DevControlBot) = # heat field is only as good as the freshest scans; stale entries stay # plausible-looking but poison the grid, so they go @@ -93,6 +142,46 @@ method buildWorldState(bot: DevControlBot): WorldState = arenaWidth: getArenaWidth().float, arenaHeight: getArenaHeight().float, tick: bot.tick, enemies: bot.enemies) +## The gun tick: aim, and fire when the gun is actually on the aim point. +## +## Standard Tank Royale gun handling, nothing clever — the cleverness (if any) +## lives entirely inside predictAim(). Order is the API's: set the gun turn rate, +## fire only when the gun is both COOLED (getGunHeat() == 0) and ON the aim, and +## do it before go() so the shot is part of this tick's intent. +proc computeGun(bot: DevControlBot) = + let belief = bot.buildBelief(FirePower) + let aim = bot.gun.predictAim(belief, FirePower, UseElm) + let baseAim = bot.gun.heuristicAim(belief, FirePower) + if aim.aim.isNaN: + setGunTurnRate(0.0) + return + when defined(gunDebug): + if bot.tick mod 20 == 0: + echo "[gun] t=", bot.tick, " self=(", getX(), ",", getY(), ") lastScan=(", lastScan.x, ",", lastScan.y, + ") age=", scanAge(scanTick), ") aimDeg=", radToDeg(aim.aim), + " corr=", aim.correction, " gunDeg=", getGunDirection() + let err = normalizeRelativeAngle(radToDeg(aim.aim) - getGunDirection()) + if abs(err) <= degToRad(FireSlopDeg): + if getGunHeat() == 0.0: + fire(FirePower) + inc bot.shotsFired + when defined(gunLog): + # One line per shot: what the gun THOUGHT. The truth (the aim error it + # actually made) is computed offline from the observer recording, which + # is the only place ground truth exists. Format: + # round,tick,predCorrection,baseAimDeg,finalAimDeg,gunDeg + let path = getEnv("ELM_GUN_LOG", "") + if path.len > 0: + let f = open(path, fmAppend) + defer: f.close() + f.write($bot.roundNo & "," & $bot.tick & "," & $aim.correction & "," & + $(radToDeg(baseAim)) & "," & $(radToDeg(aim.aim)) & "," & + $(getGunDirection()) & "," & + buildFeatures(belief).mapIt($it).join(" ") & "\n") + setGunTurnRate(0.0) + else: + setGunTurnRate(err) + method run*(bot: DevControlBot) = initRadar() # once: radar + scan turn BLACK = programmed while isRunning(): @@ -103,6 +192,7 @@ method run*(bot: DevControlBot) = let (speed, turnRate) = bot.mover.computeMove(bot.buildWorldState()) setTargetSpeed(speed) setTurnRate(turnRate) + bot.computeGun() # gun intent, also before go() go() inc bot.tick diff --git a/DevControlBot_garage/DevControlBot/modules/ELM/elm_features.nim b/DevControlBot_garage/DevControlBot/modules/ELM/elm_features.nim new file mode 100644 index 0000000..9c57ebb --- /dev/null +++ b/DevControlBot_garage/DevControlBot/modules/ELM/elm_features.nim @@ -0,0 +1,135 @@ +## The ELM gun's FEATURE VECTOR — one definition, shared by the offline trainer +## and the in-game gun, so the model can never drift from its inputs. +## +## It is a line-by-line port of the feature block of +## `tools/elm_bench/bench_realistic.nim`, which is itself a port of the belief +## computation in `tools/elm_bench/extract_realistic.py`. The offline corpus was +## built from OBSERVER ground truth; this module rebuilds exactly the same +## quantities from what the shooter legitimately knows: its own state plus its +## ScannedBotEvent history. +## +## Two features of the benchmark set are deliberately absent: `round` and `tick`. +## They are corpus bookkeeping (which round, how far into it) and are not +## observable as themselves in-game — the bot's tick counter would stand in for +## `tick` and nothing for `round`, so keeping them would train on a feature the +## runtime cannot reproduce. Dropping two of 24 costs little and keeps the +## offline and online feature spaces identical, which is the whole point. +## +## No import of the bot API: the trainer (Nim, offline) and the gun (in-game) +## both use this, so it must stay pure stdlib + math. + +import std/math + +## ## The four features that were CUT, and why (measured, not guessed) +## +## `scanAge`, `logScan`, `disp` and `gunHeat` are the corpus' four stale-belief +## features, and in game they are structurally OUT OF DOMAIN, not merely shifted: +## +## feature corpus (9 legacy bots) DevControlBot in game +## scanAge 0 .. 0.033 (0-1 ticks) 0.067 .. 0.333 (2-10 ticks) +## logScan 0 .. 0.173 0.275 .. 0.599 +## disp 0 .. 0.080 (<= 8px) 0 .. 0.635 (up to 63px) +## gunHeat 0.343 .. 0.533 (always warm) 0.0 (always cooled) +## +## The corpus is ~97% same-tick shots by bots moving slowly; this bot fires when +## ITS GUN IS COOLED, several ticks after a scan, at up to 8px/tick. A tanh ELM +## extrapolates violently outside its training box: with those four features in, +## 95% of in-game shots returned the clamp (|correction| >= 0.5 rad) and the gun +## was WORSE than the geometric baseline it is supposed to improve on. Without +## them the model stays inside the trained box and the remaining 18 features are +## all geometry the bot really does know. +## +## So: they are gone, and the honest cost is recorded here — a bot that fires on +## the tick it scans (gunHeat unconstrained, age 0) can put them back and +## retrain. + +const + FeatureDim* = 18 ## length of the vector `buildFeatures` returns + featureNames* = [ + "dist", # 0 belief distance / 1000 + "invDist", # 1 soft inverse distance 1/(1 + d/100) + "sinRel", # 2 sin of believed current bearing, body-relative + "cosRel", # 3 cos of the same + "tgtSpeed", # 4 estimated target speed / 10 + "bulletSpd", # 5 bullet speed / 20 + "everScanned", # 6 1.0 if we have ever scanned the target + "scanGap", # 7 ticks between the last two scans, clamped /30 + "sinPred", # 8 sin of the believed INTERCEPT bearing + "cosPred", # 9 cos of the same + "predErr", # 10 wrap(pred - rel) / PI <-- the feature that carries + # the signal (see README: a single + # linear feature on it gives -61% + # of the -62.6% the whole ELM gives) + "tgtLatVel", # 11 lateral target velocity (left-positive) / 10 + "closing", # 12 closing speed / 10 + "losRate", # 13 lateral velocity / distance, rad per tick + "tof", # 14 believed time of flight / 30 + "power", # 15 shot power / 3 + "ownSpeed", # 16 our speed / 10 + "relSin", # 17 sin of the believed current bearing (duplicate of 2, + # kept because the benchmark carried it) + ] + +type + GunBelief* = object + ## Everything the gun needs, all of it legitimately observable. + everScanned*: bool + selfX*, selfY*: float ## our position NOW + selfHeading*: float ## our body heading, radians (0 = east, CCW +) + selfSpeed*: float + ownDisp*: float ## how far WE moved since the last scan (px) + scanAge*: float ## ticks since the last scan + scanGap*: float ## ticks between the last two scans (0 if <2) + ex*, ey*: float ## dead-reckoned target position NOW + vx*, vy*: float ## estimated target velocity (px/tick) + bulletSpeed*: float ## THE CORPUS' bullet-speed field, which is + ## `power * 10` (extract_realistic.py: `v = + ## bu["power"] * 10.0`) and NOT the physical + ## 20 - 3*power. Reproduced verbatim so the + ## feature means the same thing offline and in + ## game; only `tof` is derived from it. + power*: float ## the power we are about to (or did) fire at + gunHeat*: float + +proc wrapAngle(a: float): float = + ## wrap to (-pi, pi] + var r = a + while r > PI: r -= 2 * PI + while r <= -PI: r += 2 * PI + r + +proc buildFeatures*(b: GunBelief): array[FeatureDim, float64] = + ## The feature vector. Mirrors bench_realistic.nim exactly, including the + ## all-zero vector when we have never scanned the target. + if not b.everScanned: + return default(array[FeatureDim, float64]) + let de = hypot(b.ex - b.selfX, b.ey - b.selfY) + let ang = arctan2(b.ey - b.selfY, b.ex - b.selfX) ## line-of-sight bearing + let rel = wrapAngle(ang - b.selfHeading) ## believed current bearing + let sp = hypot(b.vx, b.vy) + let lat = -b.vx * sin(ang) + b.vy * cos(ang) ## + = target moves left + let rad = b.vx * cos(ang) + b.vy * sin(ang) ## + = target moves away + let tof = de / b.bulletSpeed + let px = b.ex + b.vx * tof + let py = b.ey + b.vy * tof + let pred = wrapAngle(arctan2(py - b.selfY, px - b.selfX) - b.selfHeading) + let predErr = wrapAngle(pred - rel) + let gap = max(b.scanGap, 0.0) + result[0] = de / 1000.0 + result[1] = 1.0 / (1.0 + de / 100.0) + result[2] = sin(rel) + result[3] = cos(rel) + result[4] = sp / 10.0 + result[5] = b.bulletSpeed / 20.0 + result[6] = 1.0 + result[7] = min(gap, 30.0) / 30.0 + result[8] = sin(pred) + result[9] = cos(pred) + result[10] = predErr / PI + result[11] = lat / 10.0 + result[12] = -rad / 10.0 + result[13] = lat / max(de, 1.0) + result[14] = tof / 30.0 + result[15] = b.power / 3.0 + result[16] = b.selfSpeed / 10.0 + result[17] = sin(rel) \ No newline at end of file diff --git a/DevControlBot_garage/DevControlBot/modules/ELM/elm_gun.nim b/DevControlBot_garage/DevControlBot/modules/ELM/elm_gun.nim new file mode 100644 index 0000000..0bbf302 --- /dev/null +++ b/DevControlBot_garage/DevControlBot/modules/ELM/elm_gun.nim @@ -0,0 +1,194 @@ +## The ELM GUN — a learned aim-error corrector, plus the geometric baseline it +## has to beat. +## +## ## What it predicts +## +## The ELM does NOT predict where the enemy is. It predicts the shooter's own +## aim ERROR: `label = idealInterceptBearing - gunBearing` at the moment the shot +## leaves the barrel. That is the quantity measured in the corpus and it is the +## right target because it composes with everything: the classic geometric +## intercept gives the aim point, the ELM says how far off that aim point the +## opponent's own habit puts it, and the bot adds the two. +## +## ## The baseline +## +## `heuristicAim` is the plain geometric intercept — dead-reckon the target from +## the last two scans, lead it by d/bulletSpeed. No learning, no correction, and +## (deliberately) built from the SAME belief as the ELM, so the A/B in real +## battles isolates the learned correction and nothing else. +## +## ## Weights file +## +## `elm_gun_weights.txt` next to this file, written by +## `tools/elm_bench/train_elm_gun.nim`. Plain text, one matrix per line, flat: +## +## # comment lines are ignored +## +## the header row, e.g. `22 128 1 0.01 1 12345 tanh` +## W hidden weights, ROW-major: hiddenDim +## rows of inputDim, pre-activation a_j . x +## HS hidden-layer biases, b_j +## BETA <(hiddenDim+1)*outputs vals> output weights, ROW-major: outputs rows +## of hiddenDim+1. The LAST entry of a row is +## the output-layer bias — the ELM carries +## it as a constant 1.0 column, not a +## separate parameter (elm.nim). +## TRAIN_RMSE training RMSE at export time; diagnostic only, unused. +## +## It is a data file, not code: deleting it costs the bot its learned correction, +## nothing else. +## +## ## In-game honesty +## +## Nothing here reads a ground truth. `GunBelief` is assembled by the caller +## from the bot's own state and its own scan history, and `buildFeatures` +## (elm_features.nim) is the same function the trainer fed the corpus through. + +import std/[math, os, sequtils, strutils] +import ./elm +import ./elm_features + +const + DefaultWeightsFile* = "elm_gun_weights.txt" ## next to THIS source file + FirePower* = 2.0'f64 ## The corpus is dominated by + ## mid-power shots (1.95 is + ## its mode, 2795 rows; power 3.0 + ## has 61), and `power` / + ## `bulletSpd` ARE model + ## features, so firing at 2.0 + ## keeps the in-game feature + ## distribution inside the + ## trained one. Damage per hit + ## is 8 instead of 12. + MaxAimShift* = 0.5 ## rad. The learned correction is clamped: the fit law is + ## label ~= 0.87 * predErr + 0.04 rad, but a 0.5 rad + ## correction is already a full miss at any range, and an + ## unclamped outlier on a stale belief would point the + ## gun into the wall. + +type + ElmGun* = ref object + model*: Elm ## the loaded model (never refitted in-game) + loaded*: bool + lastCorrection*: float ## last raw ELM output, rad — the calibration + ## probe the battle harness reads + + GunAim* = object + aim*: float ## ABSOLUTE bearing (rad) to point the gun at + x*, y*: float ## the same point as absolute coordinates + ## (GunPrediction's contract, see + ## common_libs/gun_harness/gun_interface.nim) + confidence*: float ## 0.0 = no signal: this is a deterministic + ## geometric aim, it casts no composite vote + correction*: float ## the learned part, 0 for the baseline + +proc defaultWeightsPath(): string = + ## Resolved at compile time from this file's own location, so the current + ## working directory at bot start does not matter. + currentSourcePath().parentDir / DefaultWeightsFile + +proc readFloats(f: File, n: int, path: string): seq[float64] = + ## `n` space-separated floats, spread over as many lines as needed. + result = newSeq[float64](n) + var got = 0 + var line: string + while got < n: + if f.readLine(line) == false: + echo "[elm_gun] ", path, ": truncated, wanted ", n, " floats, got ", got + return @[] + for t in line.strip().splitWhitespace(): + if got >= n: break + result[got] = t.parseFloat() + inc got + if got < n: return @[] + +proc loadWeightsFile(g: ElmGun, path: string): bool = + ## Parse the format above into the live ELM. Returns false (and says why) + ## instead of raising: a bot with no gun is still a working bot, and the + ## harness must be able to report "ELM unavailable" rather than crash. + if not fileExists(path): + echo "[elm_gun] no weights at ", path, " — gun disabled" + return false + var cfg: ElmConfig + var haveCfg = false + var w, hs, beta: seq[float64] + var f = open(path, fmRead) + defer: f.close() + var line: string + while f.readLine(line): + let t = line.strip() + if t.len == 0 or t.startsWith("#"): continue + let parts = t.splitWhitespace() + case parts[0] + of "W": w = readFloats(f, cfg.hiddenDim * cfg.inputDim, path) + of "HS": hs = readFloats(f, cfg.hiddenDim, path) + of "BETA": beta = readFloats(f, (cfg.hiddenDim + 1) * cfg.outputs, path) + of "TRAIN_RMSE": discard + else: + # header row + cfg = ElmConfig(inputDim: parts[0].parseInt(), hiddenDim: parts[1].parseInt(), + outputs: parts[2].parseInt(), lambda: parts[3].parseFloat(), + decay: parts[4].parseFloat(), seed: parseBiggestInt(parts[5]).int64, + activation: parseActivation(parts[6]), refitEvery: 0) + haveCfg = true + continue + # a matrix tag: an empty read means the file was truncated mid-matrix + if (parts[0] == "W" and w.len == 0) or (parts[0] == "HS" and hs.len == 0) or + (parts[0] == "BETA" and beta.len == 0): return false + if not haveCfg or w.len == 0 or hs.len == 0 or beta.len == 0: + echo "[elm_gun] ", path, ": incomplete weight file — gun disabled" + return false + if cfg.inputDim != FeatureDim: + echo "[elm_gun] ", path, ": trained for ", cfg.inputDim, " features, this ", + "build has ", FeatureDim, " — gun disabled" + return false + g.model = initElm(cfg) + g.model.loadWeights(ElmWeights(W: w, hs: hs, beta: beta)) + g.loaded = true + true + +proc initElmGun*(path: string = ""): ElmGun = + ## Build the gun and load its weights. `loaded` says whether the learned + ## correction is available; a caller may fall back to the heuristic. + new(result) + discard loadWeightsFile(result, if path.len > 0: path else: defaultWeightsPath()) + +proc heuristicAim*(gun: ElmGun, b: GunBelief, power: float64 = FirePower): float = + ## Baseline A: plain geometric intercept, no learning. Returns the ABSOLUTE + ## bearing to aim at, or NaN when there is no belief at all. + if not b.everScanned: return NaN + let v = 20.0 - 3.0 * power + let d = hypot(b.ex - b.selfX, b.ey - b.selfY) + let tof = d / v # one iteration, exact for a constant bullet speed + arctan2(b.ey + b.vy * tof - b.selfY, b.ex + b.vx * tof - b.selfX) + +proc elmCorrection*(g: ElmGun, b: GunBelief, power: float64 = FirePower): float = + ## The ELM's predicted aim error in radians, clamped to +-MaxAimShift. + ## NaN when the model is unavailable or we have never scanned anything. + if not g.loaded or not b.everScanned: return NaN + var bb = b + bb.power = power + bb.bulletSpeed = power * 10.0 # the corpus' convention, see elm_features.nim + let feat = buildFeatures(bb) + let corr = g.model.infer(feat.toSeq())[0] + g.lastCorrection = corr + clamp(corr, -MaxAimShift, MaxAimShift) + +proc predictAim*(g: ElmGun, b: GunBelief, power: float64 = FirePower, + useElm: bool = true): GunAim = + ## The gun's per-tick output, GunPrediction-shaped. `useElm = false` is the + ## pure-heuristic baseline; it is the same call with the learned term switched + ## off, so the two differ by exactly one thing. + let base = heuristicAim(g, b, power) + if base.isNaN: return GunAim(aim: NaN, confidence: 0.0) + let d = hypot(b.ex - b.selfX, b.ey - b.selfY) + result = GunAim(aim: base, x: b.selfX + d * cos(base), y: b.selfY + d * sin(base), + confidence: 0.0) + if not useElm or not g.loaded: return + let corr = elmCorrection(g, b, power) + if corr.isNaN: return + result.aim = base + corr + result.x = b.selfX + d * cos(result.aim) + result.y = b.selfY + d * sin(result.aim) + result.confidence = abs(corr) + result.correction = corr \ No newline at end of file diff --git a/DevControlBot_garage/DevControlBot/modules/radar.nim b/DevControlBot_garage/DevControlBot/modules/radar.nim index 3d75aa0..47139b1 100644 --- a/DevControlBot_garage/DevControlBot/modules/radar.nim +++ b/DevControlBot_garage/DevControlBot/modules/radar.nim @@ -58,9 +58,57 @@ var targetSeen: bool scanlessTicks: int +# ── scan history (added for the ELM gun) ───────────────────────────────────── +# The gun needs THREE things the plain radar throws away: the previous scan (to +# estimate the target's velocity), how many ticks ago the last scan was (the +# dead-reckoning age), and how far WE moved in between (one of the 22 features). +# The above variables alone cannot express any of them, so the two most recent +# scans are kept here. Two is enough — a velocity from exactly two samples is +# all the corpus model was fitted with (extract_realistic.py uses hist[-2..-1]). +type ScanHistory* = object + tick*: int ## tracker tick of the scan (scanlessTicks-free counter) + x*, y*: float ## scanned position + ownX*, ownY*: float ## OUR position on that same tick (for own displacement) + +var + scanTick*: int ## incremented once per commandRadar() call + lastScan*, prevScan*: ScanHistory + haveLast*, havePrev*: bool + +proc onScanFull*(tick: int, x, y, ownX, ownY: float) = + ## Full-history variant of `onScan`, called by the bot. Shifts the scan + ## history instead of overwriting a single slot. + prevScan = lastScan + havePrev = haveLast + lastScan = ScanHistory(tick: tick, x: x, y: y, ownX: ownX, ownY: ownY) + haveLast = true + +proc scanAge*(now: int): float = + ## Ticks since the last scan, or -1 when we have never scanned anything. + if not haveLast: -1.0 else: float(now - lastScan.tick) + +proc scanGap*(): float = + ## Ticks between the last two scans; 0 when there is no earlier scan (a + ## zero gap is what the corpus uses for "velocity unknown"). + if not (haveLast and havePrev): 0.0 else: float(lastScan.tick - prevScan.tick) + +proc targetVelocity*(): tuple[vx, vy: float] = + ## px/tick, from the last two scans. (0,0) when there is no gap to measure + ## over — the corpus uses the same convention. + if not (haveLast and havePrev): return (0.0, 0.0) + let gap = lastScan.tick - prevScan.tick + if gap <= 0: return (0.0, 0.0) + ((lastScan.x - prevScan.x) / float(gap), (lastScan.y - prevScan.y) / float(gap)) + +proc ownDisp*(selfX, selfY: float): float = + ## How far WE have moved since the last scan (0 if we never scanned). + if not haveLast: 0.0 else: hypot(selfX - lastScan.ownX, selfY - lastScan.ownY) + proc onScan*(x, y: float) = ## Remember a scanned bot as the target. Issues no command: `onScannedBot` ## runs AFTER go() has already sent this tick's intent. + ## Kept for backward compatibility: it drives the radar's own lock, and the + ## bot calls `onScanFull` when it also wants the history. targetX = x targetY = y targetSeen = true @@ -80,6 +128,7 @@ proc initRadar*() = proc commandRadar*() = ## Command the radar for THIS tick. Called from run() before go(). + inc scanTick if targetSeen: inc scanlessTicks if getEnemyCount() == 1 and targetSeen and scanlessTicks <= FreshScanTurns: var turn = normalizeRelativeAngle( diff --git a/DevControlBot_garage/README.md b/DevControlBot_garage/README.md index 44bf3aa..38c3c9c 100644 --- a/DevControlBot_garage/README.md +++ b/DevControlBot_garage/README.md @@ -311,4 +311,114 @@ cd DevControlBot_garage && nimble runBot There are **no tests** in this garage. The `test` task and the `tests/` directory were removed along with the old build layout; see -[AGENTS.md](AGENTS.md) for the convention to follow when tests are added. \ No newline at end of file +[AGENTS.md](AGENTS.md) for the convention to follow when tests are added. +## The ELM gun (learned aim-error correction) — and an honest null result + +The bot used to never fire. It now fires, and the gun is an **ELM that predicts +the shooter's own aim error**, not a target position: the classic geometric +intercept produces the aim point, the ELM says how far off it the shot habitually +lands, and the two are added. + +### Files + +| file | what | +|---|---| +| `DevControlBot/modules/ELM/elm_features.nim` | THE feature vector — one definition, used by both the trainer and the gun. 18 features, all derived from our own state + scan history. | +| `DevControlBot/modules/ELM/elm_gun.nim` | the gun: weights loader, `heuristicAim` (the baseline), `predictAim` | +| `DevControlBot/modules/ELM/elm_gun_weights.txt` | exported weights, plain text, format documented at the top of `elm_gun.nim` | +| `DevControlBot/modules/radar.nim` | scan history added: previous scan, tick, and our own position at scan time (needed for velocity / age / displacement) | +| `tools/elm_bench/train_elm_gun.nim` | trains on the pooled 9-opponent corpus, exports the weights | +| `tools/elm_bench/score_battles.py` | scores recordings from the OBSERVER ground truth | + +### Reproduce + +```sh +# 1. train + export (~1.5 s) +cd DevControlBot_garage/DevControlBot +nim c -r --path:. ../../tools/elm_bench/train_elm_gun.nim + +# 2. build the two A/B guns (the define switches the learned term off) +nim c -d:release -o /tmp/DevElm DevControlBot.nim # ELM gun +nim c -d:release -d:baselineGun -o /tmp/DevBase DevControlBot.nim # geometric only + +# 3. battles (a bot dir needs .json + .sh + the binary, all +# named after the DIRECTORY; RawRecord needs its --dir to exist) +cd tools/raw_recorder +JAR=.../robocode-tankroyale-runner.jar +java -cp out:$JAR RawRecord --dir /tmp/rec_Elm_DrussGT --rounds 20 \ + --bot /tmp/bots/DevElm --bot /tmp/tr_bots/DrussGT + +# 4. score from the recording's ground truth +python3 tools/elm_bench/score_battles.py /tmp/rec_* +``` + +### The caveat that was known before the first battle + +The offline benchmark this model comes from beats a constant baseline by -62.6% +RMSE, but **one single linear feature, `beliefPredErr`, gives -61.1% of it**: the +whole ELM buys ~1.5 points over one fitted coefficient. The fit law is +`label ~= 0.87 * beliefPredErr + 0.042 rad`, i.e. "the opponent applies ~13% of +the lead it should". It also collapses under strictly-prior scans (97.3% of the +corpus shots scan on the tick they fire). Expect a small effect, not a good gun. + +### RESULTS — ELM gun vs geometric baseline, 20 real rounds each + +Hit rate from `BulletFiredEvent` / `BulletHitBotEvent` in the RawRecord streams +(observer ground truth, every recording verified CONTIGUOUS). A bullet still in +flight at round end counts as a miss. + +| opponent | gun | shots | hits | hit % | bullet damage | +|---|---|---|---|---|---| +| DrussGT | ELM | 324 | 8 | **2.5%** | 80 | +| DrussGT | geometric | 345 | 6 | **1.7%** | 60 | +| CassiusClay | ELM | 102 | 1 | **1.0%** | 10 | +| CassiusClay | geometric | 49 | 4 | **8.2%** | 40 | +| Komarious | ELM | 121 | 5 | **4.1%** | 50 | +| Komarious | geometric | 147 | 12 | **8.2%** | 120 | +| Phoenix | ELM | 143 | 73 | **51.0%** | 730 | +| Phoenix | geometric | 185 | 184 | **99.5%** | 1840 | + +### Verdict: no, it does not beat the heuristic. It loses, badly. + +Three of four opponents get worse. The fourth (Phoenix, near-stationary) is the +tell: against a target that barely moves, the geometric intercept is already +almost perfect, and the model's fitted **+0.042 rad bias alone** pushes a +near-miss over the edge — 99.5% -> 51.0%. That is the whole model doing exactly +what it was fitted to do (the in-game median correction is 0.046 rad, matching +the fitted intercept), and it is still the wrong thing to do: the corpus's +"the opponent under-leads" habit belongs to legacy bots that lead imperfectly, +and it is a *bias*, not an advantage. Against an opponent that leads correctly +the correction is a pure error. + +The one case where ELM wins (DrussGT, 2.5% vs 1.7%) is a single extra hit out of +~330 shots: noise, n too small to claim. + +### Two bugs found by measuring (both were invisible offline) + +1. **Feature-domain shift.** `scanAge`, `logScan`, `disp` and `gunHeat` are + structurally out of domain in game (the corpus is 97% same-tick shots by + slowly-moving legacy bots with a warm gun; this bot fires when its gun is + COOLED, 2-10 ticks after a scan, at up to 8 px/tick). With them the tanh + model extrapolated and 95% of in-game shots returned the clamp, spraying + bullets into walls. They were cut; the measured ranges are tabulated in + `elm_features.nim`. This is a real cost, not a free win: the model is now + blind to how stale its belief is. +2. **Units.** The API speaks degrees and the model speaks radians. Mixing them + made the gun fire at random; the conversions are now explicit in + `DevControlBot.nim`. + +Also worth knowing: `bulletSpeed` in the corpus is `power * 10`, NOT the physical +`20 - 3*power` (an artifact of `extract_realistic.py`). The gun reproduces the +corpus convention verbatim in the *feature*, and uses the physical speed in the +geometric intercept. + +### Calibration — not measured, and here is why + +`elm_gun` exposes `lastCorrection` and the bot can log one line per shot +(`-d:gunLog`, `ELM_GUN_LOG=file.csv`). The *truth* has to come from the +recording, and the join failed: `bot.tick` counts loop iterations (~15.5k in a +round the observer numbers to 2.8k), so a shot's tick cannot be mapped to an +observer `turnNumber` without a per-round ratio that was not worth measuring. +What IS known: the in-game correction distribution is healthy (mean 0.030 rad, +median 0.046, 1% at the clamp), i.e. the model is operating in the regime it was +fitted in and is not saturating — it is simply wrong for this opponent class. diff --git a/tools/elm_bench/score_battles.py b/tools/elm_bench/score_battles.py new file mode 100644 index 0000000..fcd39ef --- /dev/null +++ b/tools/elm_bench/score_battles.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Score recorded DevControlBot battles from the OBSERVER ground truth. + + python3 tools/elm_bench/score_battles.py /tmp/rec_Elm_DrussGT [...] + +For every recording it counts, per bot, the bullets it fired (BulletFiredEvent), +how many of them hit a BOT (BulletHitBotEvent), and the damage those hits dealt +(BulletHitBotEvent.damage). Nothing here uses the bot's own opinion: the observer +stream is the only source, which is the whole point of recording. + +Hit RATE is hits / (fired - still in flight at the end of the round) is NOT +attempted: a bullet still in flight when the round ends is counted in the +denominator as a miss, which is conservative but identical for both guns. +""" +import gzip, json, sys, glob, os, math +from collections import defaultdict + + +def wrap(a): + while a > math.pi: + a -= 2 * math.pi + while a < -math.pi: + a += 2 * math.pi + return a + + +def score(path): + name_of = {} + stats = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds_won=0, rounds=0)) + prev_turn = {} + noncontig = 0 + with gzip.open(path, "rt") as fh: + for line in fh: + if not line.strip(): + continue + m = json.loads(line) + if m.get("type") != "TickEventForObserver": + if m.get("type") == "RoundEndedEventForObserver": + for s in stats.values(): + s["rounds"] += 1 + continue + rnd, turn = m["roundNumber"], m["turnNumber"] + if prev_turn.get(rnd) not in (None, turn - 1): + noncontig += 1 + prev_turn[rnd] = turn + for b in m.get("botStates", []): + name_of[b["id"]] = b["name"] + for e in m.get("events", []): + t = e.get("type") + if t == "BulletFiredEvent": + stats[e["bullet"]["ownerId"]]["fired"] += 1 + elif t == "BulletHitBotEvent": + s = stats[e["bullet"]["ownerId"]] + s["hits"] += 1 + s["dmg"] += e.get("damage", 0.0) + return name_of, stats, noncontig + + +def main(): + rows = [] + for d in sys.argv[1:]: + files = sorted(glob.glob(os.path.join(d, "*.battle.gz"))) + if not files: + print("no recording in", d) + continue + tot = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds=0)) + noncontig = 0 + for f in files: + name_of, stats, nc = score(f) + noncontig += nc + for bid, s in stats.items(): + n = name_of.get(bid, "?") + for k in tot[n]: + tot[n][k] += s[k] + variant, opponent = os.path.basename(d)[4:].split("_", 1) + for n, s in tot.items(): + tag = "ELM" if variant == "Elm" else "heuristic" + if n == "DevControlBot": + rows.append((opponent, tag, s, noncontig)) + rows.sort() + print(f"{'opponent':<14}{'gun':<11}{'shots':>7}{'hits':>7}{'hit%':>8}{'damage':>9}{'rounds':>8}") + for opp, tag, s, nc in rows: + hr = 100.0 * s["hits"] / s["fired"] if s["fired"] else 0.0 + print(f"{opp:<14}{tag:<11}{s['fired']:>7}{s['hits']:>7}{hr:>7.1f}%{s['dmg']:>9.0f}{s['rounds']:>8}") + if nc: + print(f" !! {nc} turnNumber discontinuities") + + +if __name__ == "__main__": + main() \ No newline at end of file