Files
SirRoboGarage/common_libs/tests/bench_waveelm_temporal.nim
SirStone 7505fbf089 common_libs/guns: WaveElm ring gun, GUNK knowledge gun, online ELM
guns/elm.nim          online sequential ELM (ridge/RLS), fixed random
                        hidden layer, one pass, no backprop
  guns/waveelm.nim      the WaveElm gun: a simulated omnidirectional expanding
                        ring of probes fired from the SHOOTER, where the ELM
                        learns a BIAS CORRECTION to the ring's reconstructed
                        position (predicting the position outright was measured
                        and refuted: it collapses on abrupt/burst movement)
  guns/gun_knowledge.nim  GUNK: a learned additive angular residual on top of
                        the self-consistent lead forecast. Only answers "which
                        absolute gun direction", nothing else
  guns/docs/            the open-access OS-ELM / ELM reference set plus
                        fetch_papers.sh, which re-downloads it idempotently

Plus the matching test and measurement harnesses (test_waveelm*, test_elm,
test_gun_knowledge, test_knowledge_registration, gk_aim_probe,
measure_gk_{residual,virtual}.py) and the docs README with the citations.
2026-10-05 22:43:22 +02:00

394 lines
18 KiB
Nim

## bench_waveelm_temporal.nim — OFFLINE A/B BENCHMARK for the temporal
## modelling of the online ELM gun (guns/waveelm.nim).
##
## WHAT IS MEASURED
## The gun's job is to predict a systematic aim OFFSET that is added to the
## RING RECONSTRUCTION (the base the directed design got from `intercept()`,
## now measured by the ring instead). So the quantity with a ground truth is the
## offset, not the aim point: each tick the harness rebuilds the SAME base the
## gun computed (identical inputs, `ringDecode` over the gun's own ring
## measurement) and compares
##
## error(t) = (gunPred(t) - ice(t)) - trueOffset(t)
##
## before any feedback arrives. That is the aim-offset estimator's prediction
## error, i.e. exactly what a hit/miss decides later. Two metrics:
## * RMS error (px) over the EVAL window (after burn-in)
## * hit rate: fraction of rung-shots whose residual is within BotRadius,
## counted over the WHOLE stream. The gun is only TRAINED on the hits, so
## hit rate is both the score and the amount of supervision available —
## a variant that predicts the offset badly gets fewer labels and can never
## recover. That is the real failure mode being benchmarked.
##
## THE GROUND TRUTH (see `truthOffset`)
## trueOffset(t) = G(t) * (pos(t) - pos(t-L)) + rad(t)
## i.e. "the aim solution that was actually used was L ticks stale, by a gain
## G". This is the turret lag / slew-rate model: the turret points at where the
## target WAS, the ring points at where it WILL be, and the gap is
## the sum of the last L displacements. It is a LINEAR functional of the recent
## displacement history, so any feature set that hands the net the last L
## displacements can represent it exactly — which is precisely the hypothesis
## under test. It is not a strawman: the gun's own doc says the label absorbs
## turret lag.
##
## THE THREE REGIMES (same bias functional form, different temporal character
## of the TARGET, so the estimator is identical and only the input differs)
## a) smooth : constant speed, smooth steady turn (turn-rate quantised,
## as a real bot's heading is), constant gain.
## b) accel : speed and turn rate both ramp with tick, so the offset
## envelope grows with the second derivative.
## c) abrupt : at t = AbruptTick the target flips its strafing direction
## (a 110 deg heading step) AND the gain steps 1.0 -> 1.6:
## the non-stationary case.
##
## Headroom, honestly: regime (a) is nearly linear in the features the gun
## already has, so (a) is expected to show little movement. The signal is in
## (b) and (c).
##
## Run: nim c -r common_libs/tests/bench_waveelm_temporal.nim
## NO battle server, NO runBattle, NO java: pure offline replay, ~1 s.
import std/[math, strformat, sequtils]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import guns/waveelm
const
BenchTicks* = 300 ## ticks per regime (3 regimes x 3 rungs per tick)
BenchBurnIn* = 60 ## ticks of warm-up excluded from the RMS
BenchSelfX* = 100.0
BenchSelfY* = 300.0
ArenaW = 800.0
ArenaH = 600.0
LagTicks* = 4 ## L: how stale the aim solution was
LongLagTicks* = 12 ## a staleness NO explicit lag window can represent
HeadStep = 1.0 ## deg: turn-rate limit of the target's heading
AbruptTick = 150
BenchSeeds = [42'i64, 7, 99] ## ELM/hidden-layer seeds averaged over
# ── the target trajectories ──────────────────────────────────────────────────
type Regime* = enum
rSmooth, rAccel, rAbrupt
proc regimeName*(r: Regime): string =
case r
of rSmooth: "smooth"
of rAccel: "accel"
of rAbrupt: "abrupt"
type Traj* = object
name*: string
px*, py*: seq[float] ## true position per tick
hx*, hy*: seq[float] ## true unit velocity direction per tick
sp*: seq[float] ## true speed per tick
ox*, oy*: seq[float] ## ground-truth systematic offset per tick
proc wrap180(x: float): float =
result = x
for _ in 0..<4:
if result > 180.0: result -= 360.0
elif result < -180.0: result += 360.0
else: break
proc buildTraj*(r: Regime, jitter: bool, lag = LagTicks): Traj =
## Forward integration of a turn-rate-LIMITED heading: the commanded heading
## turns smoothly, the actual heading is quantised to HeadStep deg. That
## quantisation is the tick-scale structure that makes the L-tick-averaged
## displacement different from the instantaneous one — it is what a lag
## window buys, and it is a real property of Tank Royale bots (they are
## commanded, not continuous).
result.name = regimeName(r)
result.px = newSeq[float](BenchTicks)
result.py = newSeq[float](BenchTicks)
result.hx = newSeq[float](BenchTicks)
result.hy = newSeq[float](BenchTicks)
result.sp = newSeq[float](BenchTicks)
var x = 400.0
var y = 300.0
var cmd = degToRad(20.0) ## commanded heading
var act = cmd ## actual (quantised) heading
## Irregular burst jitter: a seeded coin per tick, speed x0 or x2, mean x1.
## This is the tick-scale structure a lag window exists to filter: real bots
## do not glide at a constant px/tick (they are tickRate-limited, they stop
## and go, the radar only catches them on some ticks), so the instantaneous
## displacement is a poor estimator of the motion the bias was built from,
## while a 4-tick average is a good one. The seed is fixed, so the burst
## pattern is identical on every run.
var js = 0x2545F491'i64
for t in 0..<BenchTicks:
var speed, turn: float
case r
of rSmooth:
speed = 4.0
turn = 3.0 ## deg/tick, steady
of rAccel:
speed = 2.5 + 0.013 * t.float # 2.5 -> 6.4 px/tick
turn = 2.0 + 0.018 * t.float # 2.0 -> 7.3 deg/tick
of rAbrupt:
speed = if t < AbruptTick: 4.5 else: 5.5
turn = if t < AbruptTick: 3.0 else: -3.0
if jitter:
js = (js * 1103515245 + 12345) and 0x7FFFFFFF
speed *= (if ((js shr 12) and 1) == 0: 0.4 else: 1.6)
# Keep the target INSIDE the gun's solvable envelope. A target that
# outruns the slowest rung (bulletSpeed(3.0) = 11 px/tick) has NO
# intercept: t = |p + v t| / spd has no root, the fixed point diverges and
# the aim point leaves the arena — a geometry failure of the intercept
# solver, not a property of the offset estimator being benchmarked.
if speed > 10.0: speed = 10.0
act = degToRad(round(radToDeg(act) / HeadStep) * HeadStep)
result.px[t] = x
result.py[t] = y
result.hx[t] = cos(act)
result.hy[t] = sin(act)
result.sp[t] = speed
x += cos(cmd) * speed
y += sin(cmd) * speed
# Keep the run inside the arena. A hard position clamp here would fake a
# wall bounce (and a velocity that teleports), so instead the COMMANDED
# heading is steered back toward the centre before the border is reached.
if x < 150 or x > ArenaW - 150 or y < 150 or y > ArenaH - 150:
cmd = arctan2(ArenaH / 2.0 - y, ArenaW / 2.0 - x)
else:
cmd = degToRad(wrap180(radToDeg(cmd) + turn))
# ground truth: the aim solution was L ticks stale, scaled by the gain
let gain = proc(t: int): float =
case r
of rSmooth: 1.0
of rAccel: 0.9 + 0.0015 * t.float # the offset envelope grows
of rAbrupt: (if t < AbruptTick: 1.0 else: 1.6)
result.ox = newSeq[float](BenchTicks)
result.oy = newSeq[float](BenchTicks)
for t in 0..<BenchTicks:
let a = max(0, t - lag)
let (px, py) = (result.px[t], result.py[t])
let (qx, qy) = (result.px[a], result.py[a])
# the stale solution lags along the DISPLACEMENT VECTOR: what the turret
# was pointing at when the solution was made, minus where it is now, in the
# frame the offset is applied in. Summed displacement, scaled by the gain.
result.ox[t] = gain(t) * (px - qx)
result.oy[t] = gain(t) * (py - qy)
proc mkState*(t: int, x, y, hx, hy, sp: float): WorldState =
WorldState(
enemyX: x, enemyY: y,
enemyHeading: radToDeg(arctan2(hy, hx)), enemySpeed: sp, enemyEnergy: 100.0,
selfX: BenchSelfX, selfY: BenchSelfY, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: ArenaW, arenaHeight: ArenaH, tick: t,
enemies: @[EnemyInfo(id: 1, x: x, y: y, energy: 100.0,
heading: radToDeg(arctan2(hy, hx)), speed: sp,
lastSeenTick: t)])
# ── the benchmark ────────────────────────────────────────────────────────────
type
BenchResult* = object
rms*: float ## px, eval window
hitRate*: float ## whole stream
shots*: int
labels*: int ## samples that actually reached beta
rejected*: int ## samples the validity gate threw away
BenchCfg* = object
name*: string
seed*: int64
lagK*: int ## number of scan-to-scan displacements in the features
relm*: float ## RELM gain, 0.0 = no recurrence
hiddenDim*: int ## hidden nodes (the (C) capacity probe)
# ── the tunable axes (0 / negative = module default) ──────────────────
lambda*: float ## ridge
rho*: float ## forgetting factor
maxResidual*: float ## validity gate, negative = no gate
maxOffset*: float ## offset clamp, negative = no clamp
gateAdapt*: float ## adapting-gate factor, 0 = fixed gate
aimErr*: float ## px: turret error — the bullet flies to aimPoint +
## aimErr*rotating unit vector, so a CONFIRMED hit can
## carry a residual well outside BotRadius. 0 = the
## gun is perfect, in which case a hit implies
## |residual| <= BotRadius and WaveMaxResidual (>=
## BotRadius) can never bind at all.
proc runRegime*(r: Regime, cfg: BenchCfg, jitter: bool, seed: int64,
lag = LagTicks): BenchResult =
let tr = buildTraj(r, jitter, lag)
var g = initWaveElmGun(seed, lagK = cfg.lagK, relm = cfg.relm,
hiddenDim = if cfg.hiddenDim > 0: cfg.hiddenDim
else: WaveHiddenDim,
lambda = if cfg.lambda > 0: cfg.lambda else: WaveLambda,
rho = if cfg.rho > 0: cfg.rho else: WaveRho,
maxResidual = if cfg.maxResidual != 0: cfg.maxResidual
else: WaveMaxResidual,
maxOffset = if cfg.maxOffset != 0: cfg.maxOffset
else: WaveMaxOffset,
gateAdapt = cfg.gateAdapt)
var sq = 0.0
var n = 0
var hits = 0
var shots = 0
var labels = 0
for t in 0..<BenchTicks:
# the SAME velocity derivation the gun does: the displacement between the
# last two scans (one tick apart), else heading*speed before the 2nd scan.
let hdg = radToDeg(arctan2(tr.hy[t], tr.hx[t]))
var vx = cos(degToRad(hdg)) * tr.sp[t]
var vy = sin(degToRad(hdg)) * tr.sp[t]
if t >= 1:
vx = tr.px[t] - tr.px[t - 1]
vy = tr.py[t] - tr.py[t - 1]
let st = mkState(t, tr.px[t], tr.py[t], tr.hx[t], tr.hy[t], tr.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# THE BASE is the gun's own RING RECONSTRUCTION (what used to be the
# intercept solver's aim point): the measurement decoded into a position,
# with NO learned correction on it. Identical inputs, identical code path —
# the metric is the learner's error, not the base's.
let (bx, by) = ringDecode(g.ringFor(st.enemies[0].id),
BenchSelfX, BenchSelfY)
# The truth is clamped exactly as the gun clamps its own aim point, so
# that no metric can be inflated by an asymmetry between the two.
let truthX = clamp(bx + tr.ox[t], BotRadius, ArenaW - BotRadius)
let truthY = clamp(by + tr.oy[t], BotRadius, ArenaH - BotRadius)
let res = hypot(truthX - pr.x, truthY - pr.y)
inc shots
# The BULLET does not fly to the aim point: the turret was pointing
# somewhere else when the trigger broke. `aimErr` rotates slowly so every
# sample lands on a different residual, which is what lets a confirmed
# hit carry a residual LARGER than BotRadius — i.e. what the validity
# gate actually exists to filter.
let ea = cfg.aimErr * 0.7 * t.float
let hitX = pr.x + cfg.aimErr * cos(ea)
let hitY = pr.y + cfg.aimErr * sin(ea)
let didHit = hypot(truthX - hitX, truthY - hitY) <= BotRadius
if didHit: inc hits
if t >= BenchBurnIn:
sq += res * res
inc n
# Feed the shot back EXACTLY as the live loop does: the true target
# position, hit iff the residual is inside the hit circle. A miss is
# counted, never trained on — that is the gun's own guard 1.
let before = g.trainedShots
g.onResult(FeedbackEvent(
prediction: pr, actualX: truthX, actualY: truthY,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: res, hit: didHit, confidence: pr.confidence))
labels += g.trainedShots - before
if n > 0: result.rms = sqrt(sq / n.float)
result.hitRate = (if shots > 0: hits.float / shots.float else: 0.0)
result.shots = shots
result.labels = labels
result.rejected = g.rejectedShots
proc describeGroundTruth() =
echo "── ground truth ──"
echo &" L ticks stale, turn quantised to {HeadStep} deg"
for lag in [LagTicks, LongLagTicks]:
echo " --- L = " & $lag & " ticks" &
(if lag > WaveLagKMax: " (> WaveLagKMax = " & $WaveLagKMax &
": NO lag window can represent it exactly ---)" else: "")
for j in [false, true]:
for r in Regime:
let tr = buildTraj(r, j, lag)
var sq = 0.0
var hi = 0.0
var loV = Inf
var hiV = 0.0
for t in 0..<BenchTicks:
let m = hypot(tr.ox[t], tr.oy[t])
sq += m * m
hi = max(hi, m)
loV = min(loV, tr.sp[t]); hiV = max(hiV, tr.sp[t])
var loX = Inf
var hiX = 0.0
var loY = Inf
var hiY = 0.0
for t in 0..<BenchTicks:
loX = min(loX, tr.px[t]); hiX = max(hiX, tr.px[t])
loY = min(loY, tr.py[t]); hiY = max(hiY, tr.py[t])
echo &" {tr.name:<7} burst={j:<5} |offset| rms={sqrt(sq/BenchTicks.float):5.1f}" &
&" max={hi:5.1f} px speed {loV:.1f}..{hiV:.1f}" &
&" pos x {loX:.0f}..{hiX:.0f} y {loY:.0f}..{hiY:.0f}"
when isMainModule:
describeGroundTruth()
echo &"── benchmark (RMS px over t >= {BenchBurnIn}, hit rate over the stream," &
&" mean of {BenchSeeds.len} seeds) ──"
let cfgs = [
BenchCfg(name: "baseline lagK2", seed: 42, lagK: 2, relm: 0.0),
BenchCfg(name: "lagK4", seed: 42, lagK: 4, relm: 0.0),
BenchCfg(name: "lagK6", seed: 42, lagK: 6, relm: 0.0),
BenchCfg(name: "lagK8", seed: 42, lagK: 8, relm: 0.0),
BenchCfg(name: "relm0.3", seed: 42, lagK: 2, relm: 0.3),
BenchCfg(name: "relm0.6", seed: 42, lagK: 2, relm: 0.6),
BenchCfg(name: "lagK6+relm0.3", seed: 42, lagK: 6, relm: 0.3)]
var base: array[2, array[Regime, tuple[rms, hit: float]]]
for j in 0..1:
let jitter = j == 1
for r in Regime:
for ci, c in cfgs:
var sr = 0.0
var sh = 0.0
for sd in BenchSeeds:
let b = runRegime(r, c, jitter, sd)
sr += b.rms
sh += b.hitRate
sr /= BenchSeeds.len.float
sh /= BenchSeeds.len.float
if ci == 0: base[j][r] = (rms: sr, hit: sh)
let drms = 100.0 * (sr - base[j][r].rms) / max(1e-9, base[j][r].rms)
let dhit = 100.0 * (sh - base[j][r].hit) / max(1e-9, base[j][r].hit)
let jn = if jitter: "burst" else: "smooth"
echo &" {jn:<6} {regimeName(r):<7} {c.name:<14} rms={sr:7.3f}" &
&" ({drms:+6.1f}%) hit={sh*100:6.2f}% ({dhit:+6.1f}%)"
# ── the fair test for RECURRENCE ───────────────────────────────────────────
# With L = 4 the truth is a 4-tick window, which an explicit lag window can
# represent exactly and a recurrence has nothing left to add. Re-run with
# L = 12: longer than any window the feature map can carry (WaveLagKMax = 8),
# so the only way to build the quantity is to INTEGRATE over time — which is
# precisely what the RELM hidden state does. If recurrence is worth anything
# it has to show up here.
# ── (C) CAPACITY PROBE: is hidden capacity the bottleneck at all? ──────────
# Growing hidden nodes is the Igelnik & Jemcevski / Huang-Wang-Lan option. It
# is only worth it if more capacity moves the number, so measure that FIRST.
echo &"\n── (C) CAPACITY PROBE (long memory, burst) ──"
for hd in [8, 16, 32, 64]:
var sr = 0.0
var sh = 0.0
for r in Regime:
for sd in BenchSeeds:
let b = runRegime(r, BenchCfg(name: "h", seed: sd, lagK: 8, relm: 0.0,
hiddenDim: hd), true, sd, LongLagTicks)
sr += b.rms
sh += b.hitRate
sr /= ((ord(rAbrupt) - ord(rSmooth) + 1).float * BenchSeeds.len.float)
sh /= ((ord(rAbrupt) - ord(rSmooth) + 1).float * BenchSeeds.len.float)
echo &" hiddenDim={hd:<4} mean rms={sr:7.3f} mean hit={sh*100:6.2f}%"
echo &"\n── LONG MEMORY (L = {LongLagTicks} ticks > WaveLagKMax = {WaveLagKMax}) ──"
let lcfgs = [cfgs[0], cfgs[1], cfgs[3], cfgs[4], cfgs[6]]
var lbase: array[Regime, tuple[rms, hit: float]]
for r in Regime:
for ci, c in lcfgs:
var sr = 0.0
var sh = 0.0
for sd in BenchSeeds:
let b = runRegime(r, c, true, sd, LongLagTicks)
sr += b.rms
sh += b.hitRate
sr /= BenchSeeds.len.float
sh /= BenchSeeds.len.float
if ci == 0: lbase[r] = (rms: sr, hit: sh)
let drms = 100.0 * (sr - lbase[r].rms) / max(1e-9, lbase[r].rms)
let dhit = 100.0 * (sh - lbase[r].hit) / max(1e-9, lbase[r].hit)
echo &" burst {regimeName(r):<7} {c.name:<14} rms={sr:7.3f}" &
&" ({drms:+6.1f}%) hit={sh*100:6.2f}% ({dhit:+6.1f}%)"