DevControlBot: movement-prediction features, gate, radar scan window

Rewrite elm_features.nim as a 32-D enemy-motion vector (7 scan-to-scan
displacement legs, speed stats, heading/turn/curvature, plus the single-frame
geometry). Add a WinCap=8 scan buffer to radar.nim and feed it through
buildBelief. elm_gun.nim now uses the physical bullet speed for the feature
(was the power*10 corpus artifact) and applies the trained correction only when
|correction| > GATE_TAU; below it the gun keeps the exact geometric aim. Retrain
and export weights (H=256, gate_tau=0.1).
This commit is contained in:
2026-10-06 09:00:43 +02:00
parent 9f09204c40
commit 6a14b0ffd6
5 changed files with 152 additions and 127 deletions
@@ -126,6 +126,11 @@ method buildBelief(bot: DevControlBot, power: float): GunBelief =
result.ownDisp = ownDisp(getX(), getY())
result.scanAge = age
result.scanGap = scanGap()
result.winN = min(winN, WinCap)
for k in 0 ..< result.winN:
result.winX[k] = winX[k]
result.winY[k] = winY[k]
result.winTick[k] = winTick[k]
result.vx = vx
result.vy = vy
# dead-reckon: last seen position advanced by the estimated velocity
@@ -1,73 +1,44 @@
## 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.
## This is the MOVEMENT-PREDICTION gun's feature set. The label it is trained on
## is the correction from the plain geometric intercept to the enemy's TRUE
## impact position (`tools/elm_bench/extract_predict.py`), so the features are
## enemy-motion-centric: a window of recent scan-to-scan displacement vectors,
## plus the single-frame geometry the old gun used.
##
## 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.
## Every quantity comes from the shooter's own state and its ScannedBotEvent
## history (scans are exact, one per tick in game). No oracle.
##
## 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.
## Stdlib only, so the offline trainer and the in-game gun share it verbatim.
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
WinCap* = 8 ## motion window: scans kept, newest first
## Feature vector layout (FeatureDim = 32):
## 0..13 7 newest-to-oldest displacement vectors, each divided by its own
## tick gap and by 16 px/tick: [dx0,dy0, dx1,dy1, ... dx6,dy6]
## 14..16 newest speed, window mean speed, window speed sd (all /10)
## 17,18 sin/cos of the newest displacement heading
## 19,20 sin/cos of the turn rate (angle between the two newest legs)
## 21 curvature |dtheta| / speed, clamped to 1
## 22..24 belief distance /1000, sin/cos of the body-relative bearing
## 25 our own speed /10
## 26 bullet speed /20
## 27 believed time of flight /30
## 28 predErr: base-intercept bearing minus current bearing, /PI
## 29 target lateral velocity /10
## 30 closing speed /10
## 31 line-of-sight rate (lat vel / dist)
FeatureDim* = 32
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)
"dx0", "dy0", "dx1", "dy1", "dx2", "dy2", "dx3", "dy3",
"dx4", "dy4", "dx5", "dy5", "dx6", "dy6",
"speed", "speedMean", "speedSd",
"sinHead", "cosHead", "sinTurn", "cosTurn", "curve",
"dist", "sinRel", "cosRel", "ownSpeed", "bulletSpd", "tof",
"predErr", "tgtLatVel", "closing", "losRate",
]
type
@@ -82,16 +53,16 @@ type
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.
bulletSpeed*: float ## physical bullet speed, 20 - 3*power
power*: float ## the power we are about to (or did) fire at
gunHeat*: float
## motion window, newest first. winTick[k] is the tracker tick of the
## k-th newest scan; winX/winY the scanned position.
winX*, winY*: array[WinCap, float]
winTick*: array[WinCap, int]
winN*: int
proc wrapAngle(a: float): float =
proc wrapAngle*(a: float): float =
## wrap to (-pi, pi]
var r = a
while r > PI: r -= 2 * PI
@@ -99,37 +70,71 @@ proc wrapAngle(a: float): float =
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.
## The feature vector. Mirrors extract_predict.py exactly. All-zero 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 rel = wrapAngle(ang - b.selfHeading)
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 lat = -b.vx * sin(ang) + b.vy * cos(ang)
let rad = b.vx * cos(ang) + b.vy * sin(ang)
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)
let base = arctan2(py - b.selfY, px - b.selfX)
let predErr = wrapAngle(base - ang)
# --- motion window: displacement of leg k = scan k -> scan k+1 ---
var spdSum = 0.0
var spdSq = 0.0
var nLeg = 0
var head = 0.0
var dtheta = 0.0
if b.winN >= 2:
var dxs: array[WinCap - 1, float]
var dys: array[WinCap - 1, float]
for k in 0 ..< min(b.winN, WinCap) - 1:
let gap = float(max(b.winTick[k] - b.winTick[k + 1], 1))
let dx = (b.winX[k] - b.winX[k + 1]) / gap
let dy = (b.winY[k] - b.winY[k + 1]) / gap
dxs[k] = dx
dys[k] = dy
result[2 * k] = dx / 16.0
result[2 * k + 1] = dy / 16.0
let s = hypot(dx, dy)
spdSum += s
spdSq += s * s
inc nLeg
let nf = float(nLeg)
let sMean = spdSum / nf
head = arctan2(dys[0], dxs[0])
if nLeg >= 2:
let phead = arctan2(dys[1], dxs[1])
dtheta = wrapAngle(head - phead)
result[14] = sp / 10.0
result[15] = sMean / 10.0
result[16] = sqrt(max(spdSq / nf - sMean * sMean, 0.0)) / 10.0
result[17] = sin(head)
result[18] = cos(head)
result[19] = sin(dtheta)
result[20] = cos(dtheta)
result[21] = min(abs(dtheta) / max(sMean, 1e-6), 1.0)
else:
result[14] = sp / 10.0
result[15] = sp / 10.0
result[22] = de / 1000.0
result[23] = sin(rel)
result[24] = cos(rel)
result[25] = b.selfSpeed / 10.0
result[26] = b.bulletSpeed / 20.0
result[27] = tof / 30.0
result[28] = predErr / PI
result[29] = lat / 10.0
result[30] = -rad / 10.0
result[31] = lat / max(de, 1.0)
for i in 0 ..< FeatureDim:
if classify(result[i]) in {fcNan, fcInf, fcNegInf}: result[i] = 0.0
@@ -1,39 +1,36 @@
## The ELM GUN — a learned aim-error corrector, plus the geometric baseline it
## has to beat.
## The ELM GUN — a movement-prediction corrector on top of the geometric
## intercept.
##
## ## 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 ELM predicts the ENEMY'S FUTURE POSITION, expressed as a correction to
## the plain geometric intercept: at fire time the classic intercept gives a
## base aim point, the ELM estimates `trueImpactBearing - baseBearing` from the
## enemy's recent motion window, and the gun adds the two. That is a movement
## predictor, NOT the old opponent-aim-bias model (which measured how far the
## OTHER bot's shots missed and is deleted).
##
## ## The baseline
## ## The baseline and the gate
##
## `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.
## the last two scans, lead it by d/bulletSpeed. The learned correction is
## applied ONLY when `|correction| > gateTau`, the threshold calibrated on
## held-out folds (see `train_predict.nim`); below it the gun returns the exact
## geometric aim, so a small noisy nudge can never make the ELM worse than the
## baseline.
##
## ## 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:
## `tools/elm_bench/train_predict.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
## W <hiddenDim*inputDim values> hidden weights, ROW-major
## 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).
## BETA <(hiddenDim+1)*outputs vals> output weights, ROW-major
## TRAIN_RMSE <v> training RMSE at export time; diagnostic only, unused.
## GATE_TAU <v> correction magnitude below which correction is 0.
##
## It is a data file, not code: deleting it costs the bot its learned correction,
## nothing else.
@@ -70,6 +67,7 @@ type
ElmGun* = ref object
model*: Elm ## the loaded model (never refitted in-game)
loaded*: bool
gateTau*: float ## |correction| below this -> geometric aim
lastCorrection*: float ## last raw ELM output, rad — the calibration
## probe the battle harness reads
@@ -124,6 +122,7 @@ proc loadWeightsFile(g: ElmGun, path: string): bool =
of "HS": hs = readFloats(f, cfg.hiddenDim, path)
of "BETA": beta = readFloats(f, (cfg.hiddenDim + 1) * cfg.outputs, path)
of "TRAIN_RMSE": discard
of "GATE_TAU": g.gateTau = parts[1].parseFloat()
else:
# header row
cfg = ElmConfig(inputDim: parts[0].parseInt(), hiddenDim: parts[1].parseInt(),
@@ -168,10 +167,12 @@ proc elmCorrection*(g: ElmGun, b: GunBelief, power: float64 = FirePower): float
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
bb.bulletSpeed = 20.0 - 3.0 * power # physical speed, matches heuristicAim
let feat = buildFeatures(bb)
let corr = g.model.infer(feat.toSeq())[0]
g.lastCorrection = corr
if abs(corr) <= g.gateTau:
return 0.0 # gate closed: exact geometric aim
clamp(corr, -MaxAimShift, MaxAimShift)
proc predictAim*(g: ElmGun, b: GunBelief, power: float64 = FirePower,
File diff suppressed because one or more lines are too long
@@ -70,18 +70,31 @@ type ScanHistory* = object
x*, y*: float ## scanned position
ownX*, ownY*: float ## OUR position on that same tick (for own displacement)
const ScanWinCap* = 8 ## motion-window length kept for the ELM gun
var
scanTick*: int ## incremented once per commandRadar() call
lastScan*, prevScan*: ScanHistory
haveLast*, havePrev*: bool
## window of the most recent scans, newest at index 0 (ELM gun features)
winTick*: array[ScanWinCap, int]
winX*, winY*: array[ScanWinCap, float]
winN*: int
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.
## history (and the ELM motion window) instead of overwriting a single slot.
prevScan = lastScan
havePrev = haveLast
lastScan = ScanHistory(tick: tick, x: x, y: y, ownX: ownX, ownY: ownY)
haveLast = true
if winN > 0 and winTick[0] == tick:
winX[0] = x; winY[0] = y # same-tick rescans replace, do not shift
else:
for k in countdown(ScanWinCap - 1, 1):
winX[k] = winX[k - 1]; winY[k] = winY[k - 1]; winTick[k] = winTick[k - 1]
winX[0] = x; winY[0] = y; winTick[0] = tick
if winN < ScanWinCap: inc winN
proc scanAge*(now: int): float =
## Ticks since the last scan, or -1 when we have never scanned anything.