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.ownDisp = ownDisp(getX(), getY())
result.scanAge = age result.scanAge = age
result.scanGap = scanGap() 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.vx = vx
result.vy = vy result.vy = vy
# dead-reckon: last seen position advanced by the estimated velocity # 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 ## 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. ## 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 ## This is the MOVEMENT-PREDICTION gun's feature set. The label it is trained on
## `tools/elm_bench/bench_realistic.nim`, which is itself a port of the belief ## is the correction from the plain geometric intercept to the enemy's TRUE
## computation in `tools/elm_bench/extract_realistic.py`. The offline corpus was ## impact position (`tools/elm_bench/extract_predict.py`), so the features are
## built from OBSERVER ground truth; this module rebuilds exactly the same ## enemy-motion-centric: a window of recent scan-to-scan displacement vectors,
## quantities from what the shooter legitimately knows: its own state plus its ## plus the single-frame geometry the old gun used.
## ScannedBotEvent history.
## ##
## Two features of the benchmark set are deliberately absent: `round` and `tick`. ## Every quantity comes from the shooter's own state and its ScannedBotEvent
## They are corpus bookkeeping (which round, how far into it) and are not ## history (scans are exact, one per tick in game). No oracle.
## 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) ## Stdlib only, so the offline trainer and the in-game gun share it verbatim.
## both use this, so it must stay pure stdlib + math.
import std/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 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* = [ featureNames* = [
"dist", # 0 belief distance / 1000 "dx0", "dy0", "dx1", "dy1", "dx2", "dy2", "dx3", "dy3",
"invDist", # 1 soft inverse distance 1/(1 + d/100) "dx4", "dy4", "dx5", "dy5", "dx6", "dy6",
"sinRel", # 2 sin of believed current bearing, body-relative "speed", "speedMean", "speedSd",
"cosRel", # 3 cos of the same "sinHead", "cosHead", "sinTurn", "cosTurn", "curve",
"tgtSpeed", # 4 estimated target speed / 10 "dist", "sinRel", "cosRel", "ownSpeed", "bulletSpd", "tof",
"bulletSpd", # 5 bullet speed / 20 "predErr", "tgtLatVel", "closing", "losRate",
"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 type
@@ -82,16 +53,16 @@ type
scanGap*: float ## ticks between the last two scans (0 if <2) scanGap*: float ## ticks between the last two scans (0 if <2)
ex*, ey*: float ## dead-reckoned target position NOW ex*, ey*: float ## dead-reckoned target position NOW
vx*, vy*: float ## estimated target velocity (px/tick) vx*, vy*: float ## estimated target velocity (px/tick)
bulletSpeed*: float ## THE CORPUS' bullet-speed field, which is bulletSpeed*: float ## physical bullet speed, 20 - 3*power
## `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 power*: float ## the power we are about to (or did) fire at
gunHeat*: float 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] ## wrap to (-pi, pi]
var r = a var r = a
while r > PI: r -= 2 * PI while r > PI: r -= 2 * PI
@@ -99,37 +70,71 @@ proc wrapAngle(a: float): float =
r r
proc buildFeatures*(b: GunBelief): array[FeatureDim, float64] = proc buildFeatures*(b: GunBelief): array[FeatureDim, float64] =
## The feature vector. Mirrors bench_realistic.nim exactly, including the ## The feature vector. Mirrors extract_predict.py exactly. All-zero when we
## all-zero vector when we have never scanned the target. ## have never scanned the target.
if not b.everScanned: if not b.everScanned:
return default(array[FeatureDim, float64]) return default(array[FeatureDim, float64])
let de = hypot(b.ex - b.selfX, b.ey - b.selfY) 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 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 sp = hypot(b.vx, b.vy)
let lat = -b.vx * sin(ang) + b.vy * cos(ang) ## + = target moves left let lat = -b.vx * sin(ang) + b.vy * cos(ang)
let rad = b.vx * cos(ang) + b.vy * sin(ang) ## + = target moves away let rad = b.vx * cos(ang) + b.vy * sin(ang)
let tof = de / b.bulletSpeed let tof = de / b.bulletSpeed
let px = b.ex + b.vx * tof let px = b.ex + b.vx * tof
let py = b.ey + b.vy * tof let py = b.ey + b.vy * tof
let pred = wrapAngle(arctan2(py - b.selfY, px - b.selfX) - b.selfHeading) let base = arctan2(py - b.selfY, px - b.selfX)
let predErr = wrapAngle(pred - rel) let predErr = wrapAngle(base - ang)
let gap = max(b.scanGap, 0.0)
result[0] = de / 1000.0 # --- motion window: displacement of leg k = scan k -> scan k+1 ---
result[1] = 1.0 / (1.0 + de / 100.0) var spdSum = 0.0
result[2] = sin(rel) var spdSq = 0.0
result[3] = cos(rel) var nLeg = 0
result[4] = sp / 10.0 var head = 0.0
result[5] = b.bulletSpeed / 20.0 var dtheta = 0.0
result[6] = 1.0 if b.winN >= 2:
result[7] = min(gap, 30.0) / 30.0 var dxs: array[WinCap - 1, float]
result[8] = sin(pred) var dys: array[WinCap - 1, float]
result[9] = cos(pred) for k in 0 ..< min(b.winN, WinCap) - 1:
result[10] = predErr / PI let gap = float(max(b.winTick[k] - b.winTick[k + 1], 1))
result[11] = lat / 10.0 let dx = (b.winX[k] - b.winX[k + 1]) / gap
result[12] = -rad / 10.0 let dy = (b.winY[k] - b.winY[k + 1]) / gap
result[13] = lat / max(de, 1.0) dxs[k] = dx
result[14] = tof / 30.0 dys[k] = dy
result[15] = b.power / 3.0 result[2 * k] = dx / 16.0
result[16] = b.selfSpeed / 10.0 result[2 * k + 1] = dy / 16.0
result[17] = sin(rel) 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 ## The ELM GUN — a movement-prediction corrector on top of the geometric
## has to beat. ## intercept.
## ##
## ## What it predicts ## ## What it predicts
## ##
## The ELM does NOT predict where the enemy is. It predicts the shooter's own ## The ELM predicts the ENEMY'S FUTURE POSITION, expressed as a correction to
## aim ERROR: `label = idealInterceptBearing - gunBearing` at the moment the shot ## the plain geometric intercept: at fire time the classic intercept gives a
## leaves the barrel. That is the quantity measured in the corpus and it is the ## base aim point, the ELM estimates `trueImpactBearing - baseBearing` from the
## right target because it composes with everything: the classic geometric ## enemy's recent motion window, and the gun adds the two. That is a movement
## intercept gives the aim point, the ELM says how far off that aim point the ## predictor, NOT the old opponent-aim-bias model (which measured how far the
## opponent's own habit puts it, and the bot adds the two. ## 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 ## `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 ## the last two scans, lead it by d/bulletSpeed. The learned correction is
## (deliberately) built from the SAME belief as the ELM, so the A/B in real ## applied ONLY when `|correction| > gateTau`, the threshold calibrated on
## battles isolates the learned correction and nothing else. ## 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 ## ## Weights file
## ##
## `elm_gun_weights.txt` next to this file, written by ## `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 ## # comment lines are ignored
## <inputDim> <hiddenDim> <outputs> <lambda> <decay> <seed> <activation> ## <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
## 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 ## HS <hiddenDim values> hidden-layer biases, b_j
## BETA <(hiddenDim+1)*outputs vals> output weights, ROW-major: outputs rows ## BETA <(hiddenDim+1)*outputs vals> output weights, ROW-major
## 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. ## 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, ## It is a data file, not code: deleting it costs the bot its learned correction,
## nothing else. ## nothing else.
@@ -70,6 +67,7 @@ type
ElmGun* = ref object ElmGun* = ref object
model*: Elm ## the loaded model (never refitted in-game) model*: Elm ## the loaded model (never refitted in-game)
loaded*: bool loaded*: bool
gateTau*: float ## |correction| below this -> geometric aim
lastCorrection*: float ## last raw ELM output, rad — the calibration lastCorrection*: float ## last raw ELM output, rad — the calibration
## probe the battle harness reads ## 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 "HS": hs = readFloats(f, cfg.hiddenDim, path)
of "BETA": beta = readFloats(f, (cfg.hiddenDim + 1) * cfg.outputs, path) of "BETA": beta = readFloats(f, (cfg.hiddenDim + 1) * cfg.outputs, path)
of "TRAIN_RMSE": discard of "TRAIN_RMSE": discard
of "GATE_TAU": g.gateTau = parts[1].parseFloat()
else: else:
# header row # header row
cfg = ElmConfig(inputDim: parts[0].parseInt(), hiddenDim: parts[1].parseInt(), 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 if not g.loaded or not b.everScanned: return NaN
var bb = b var bb = b
bb.power = power 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 feat = buildFeatures(bb)
let corr = g.model.infer(feat.toSeq())[0] let corr = g.model.infer(feat.toSeq())[0]
g.lastCorrection = corr g.lastCorrection = corr
if abs(corr) <= g.gateTau:
return 0.0 # gate closed: exact geometric aim
clamp(corr, -MaxAimShift, MaxAimShift) clamp(corr, -MaxAimShift, MaxAimShift)
proc predictAim*(g: ElmGun, b: GunBelief, power: float64 = FirePower, 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 x*, y*: float ## scanned position
ownX*, ownY*: float ## OUR position on that same tick (for own displacement) ownX*, ownY*: float ## OUR position on that same tick (for own displacement)
const ScanWinCap* = 8 ## motion-window length kept for the ELM gun
var var
scanTick*: int ## incremented once per commandRadar() call scanTick*: int ## incremented once per commandRadar() call
lastScan*, prevScan*: ScanHistory lastScan*, prevScan*: ScanHistory
haveLast*, havePrev*: bool 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) = proc onScanFull*(tick: int, x, y, ownX, ownY: float) =
## Full-history variant of `onScan`, called by the bot. Shifts the scan ## 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 prevScan = lastScan
havePrev = haveLast havePrev = haveLast
lastScan = ScanHistory(tick: tick, x: x, y: y, ownX: ownX, ownY: ownY) lastScan = ScanHistory(tick: tick, x: x, y: y, ownX: ownX, ownY: ownY)
haveLast = true 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 = proc scanAge*(now: int): float =
## Ticks since the last scan, or -1 when we have never scanned anything. ## Ticks since the last scan, or -1 when we have never scanned anything.