Firing wired in behind a compile-time A/B switch (-d:baselineGun): both guns go through the same predictAim() call and differ only by the learned correction, so the measured difference is attributable. radar.nim now keeps the two most recent scans (velocity, scan age, own displacement). Measured over 20 recorded rounds each vs DrussGT, CassiusClay, Komarious and Phoenix: the ELM gun LOSES to the geometric baseline on three of four opponents (Phoenix 51.0% vs 99.5% hit rate). README has the table, the diagnosis and the two in-game-only bugs measuring exposed (degrees/radians, and features whose in-game range lies outside the corpus).
194 lines
9.1 KiB
Nim
194 lines
9.1 KiB
Nim
## 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
|
|
## <inputDim> <hiddenDim> <outputs> <lambda> <decay> <seed> <activation>
|
|
## the header row, e.g. `22 128 1 0.01 1 12345 tanh`
|
|
## W <hiddenDim*inputDim values> hidden weights, ROW-major: hiddenDim
|
|
## rows of inputDim, pre-activation a_j . x
|
|
## HS <hiddenDim values> 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 <v> 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 |