Files
SirRoboGarage/common_libs/tests/test_waveelm_flighttime.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

288 lines
12 KiB
Nim

## test_waveelm_flighttime.nim — regression test for the LEFT/RIGHT OVERSHOOT,
## against the RING base (common_libs/guns/waveelm.nim).
##
## BUG (fixed by WaveResolveFeatures): a shot fired at tick T resolves at
## T + flightTime (the ring's contact, 3-90 ticks, far longer than the RLS memory
## 1/(rho-1) ~ 12 ticks). onResult trained the label -- which describes the aim
## bias at the ARRIVAL tick -- on the FIRE-time features. The net was therefore
## fitted to a map that extrapolates the bias a whole flight time forward, and
## then applied it to fire-time features, where it would only have to read it off.
## A short-memory RLS fits the bias to the target's PAST motion and swings the
## correction sideways as the target strafes: the reported "continuously
## overshooting left and right".
##
## WHAT IS ASSERTED: with the feedback DELAYED by the real flight time, the
## gun's aim error measured PERPENDICULAR to the true offset direction (the
## lateral / left-right component, the one the user saw) collapses. The
## perpendicular component is the oscillation: an along-track error is just an
## under/over-lead, a lateral one is the aim crossing to the other side.
##
## THE IDEAL CORRECTOR (the ground truth of the aim) is now the RING
## RECONSTRUCTION plus the turret-lag bias — the same quantity the bench
## (bench_waveelm_temporal.nim) uses, with the ring's decoding standing in for
## the intercept solver that used to provide the base.
##
## Run: nim c -r common_libs/tests/test_waveelm_flighttime.nim
import std/[math, strformat]
import gun_harness/gun_interface
import guns/waveelm
const
Ticks = 240
SelfX = 100.0
SelfY = 300.0
AW = 800.0
AH = 600.0
Lag = 4
BurnIn = 60
SelfR = BotRadius
type
Regime = enum rSmooth, rAccel, rAbrupt
Traj = object
px, py, hx, hy, sp, ox, oy: seq[float]
Pending = object
resolveAt: int
pr: GunPrediction
truthX, truthY: float ## where the target really is when the bullet lands
fireTick: int
binIdx: int
power: float
Metrics = object
perp: float ## RMS lateral (perpendicular) gun-only error, px
along: float ## RMS along-track gun-only error, px
hit: float ## fraction of shots that landed inside BotRadius
proc regimeName(r: Regime): string =
case r
of rSmooth: "smooth"
of rAccel: "accel"
of rAbrupt: "abrupt"
proc buildTraj(r: Regime): Traj =
result.px = newSeq[float](Ticks); result.py = newSeq[float](Ticks)
result.hx = newSeq[float](Ticks); result.hy = newSeq[float](Ticks)
result.sp = newSeq[float](Ticks)
var x = 400.0
var y = 300.0
var cmd = degToRad(20.0)
var act = cmd
for t in 0..<Ticks:
var speed, turn: float
case r
of rSmooth: speed = 4.0; turn = 3.0
of rAccel:
speed = 2.5 + 0.013 * t.float
turn = 2.0 + 0.018 * t.float
of rAbrupt:
speed = (if t < 150: 4.5 else: 5.5)
turn = (if t < 150: 3.0 else: -3.0)
if speed > 10.0: speed = 10.0
act = degToRad(round(radToDeg(act)) * 1.0)
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
if x < 150 or x > AW - 150 or y < 150 or y > AH - 150:
cmd = arctan2(AH / 2 - y, AW / 2 - x)
else:
cmd = turn
let gain = proc(t: int): float =
case r
of rSmooth: 1.0
of rAccel: 0.9 + 0.0015 * t.float
of rAbrupt: (if t < 150: 1.0 else: 1.6)
result.ox = newSeq[float](Ticks); result.oy = newSeq[float](Ticks)
for t in 0..<Ticks:
let a = max(0, t - Lag)
result.ox[t] = gain(t) * (result.px[t] - result.px[a])
result.oy[t] = gain(t) * (result.py[t] - result.py[a])
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,
selfX: SelfX, selfY: SelfY, arenaWidth: AW, arenaHeight: AH, tick: t,
enemies: @[EnemyInfo(id: 1, x: x, y: y, energy: 100,
heading: radToDeg(arctan2(hy, hx)), speed: sp,
lastSeenTick: t)])
proc base(g: WaveElmGun, sx = SelfX, sy = SelfY): tuple[x, y: float] =
## THE RING RECONSTRUCTION: the gun's aim with NO learned correction. This is
## what the intercept solver used to provide and what the ELM's offset sits on.
ringDecode(g.ringFor(1), sx, sy)
## The live loop, faithfully: predict at tick t, the label comes back `flight`
## ticks later, and only a HIT is trained on.
proc run(r: Regime, resolveFeat: bool): Metrics =
let tj = buildTraj(r)
var g = initWaveElmGun(resolveFeat = resolveFeat)
var pend: seq[Pending] = @[]
var sqPerp = 0.0
var sqAlong = 0.0
var n = 0
var hits = 0
var shots = 0
for t in 0..<Ticks:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# the ring's own contact tick, clamped into the trajectory
let ring = g.ringFor(1)
let tof = if ring.valid: max(1, min(Ticks - 1, ring.flight.int))
else: 1
let ta = min(Ticks - 1, t + tof)
let (bx, by) = g.base()
let hitX = clamp(bx + tj.ox[ta], BotRadius, AW - BotRadius)
let hitY = clamp(by + tj.oy[ta], BotRadius, AH - BotRadius)
inc shots
# GUN-ONLY error: what the gun produced against what an IDEAL corrector
# would produce at the FIRE tick (ring reconstruction + bias(t)),
# decomposed along and across the true offset direction.
if t >= BurnIn:
let ix = clamp(bx + tj.ox[t], BotRadius, AW - BotRadius)
let iy = clamp(by + tj.oy[t], BotRadius, AH - BotRadius)
let um = hypot(tj.ox[t], tj.oy[t])
if um > 1.0:
let ex = pr.x - ix
let ey = pr.y - iy
sqAlong += ((ex * tj.ox[t] + ey * tj.oy[t]) / um) ^ 2
sqPerp += ((ex * -tj.oy[t] + ey * tj.ox[t]) / um) ^ 2
inc n
pend.add Pending(resolveAt: t + tof, pr: pr, truthX: hitX, truthY: hitY,
fireTick: t, binIdx: waveBinForSpeed(spd), power: p)
# HARNESS ORDER, and it matters: the bullets are resolved AFTER predict, so
# the flight-time feature refresh (which runs inside predict, for the traces
# due on THIS tick) has already rebuilt their features before onResult trains
# on them. Resolving before predict would silently test the un-refreshed path
# and make the A/B below a no-op.
var keep: seq[Pending] = @[]
for p in pend:
if p.resolveAt <= t:
let res = hypot(p.truthX - p.pr.x, p.truthY - p.pr.y)
let didHit = res <= BotRadius
if didHit: inc hits
g.onResult(FeedbackEvent(
prediction: p.pr, actualX: p.truthX, actualY: p.truthY,
bulletPower: p.power, fireTick: p.fireTick, powerBin: p.binIdx,
missDistance: res, hit: didHit, confidence: p.pr.confidence))
else:
keep.add p
pend = keep
if n > 0:
result.perp = sqrt(sqPerp / n.float)
result.along = sqrt(sqAlong / n.float)
result.hit = (if shots > 0: hits.float / shots.float else: 0.0)
# ── the assertions ───────────────────────────────────────────────────────────
var failures = 0
proc check(name: string, ok: bool, detail: string) =
if ok: echo " ok ", name, " — ", detail
else:
echo " FAIL ", name, " — ", detail
inc failures
block:
echo "── flight-time feature mismatch: lateral (left-right) aim error ──"
echo " (diagnostic A/B: the right column is the fix forced OFF, i.e. what"
echo " the gun did before; the ASSERTIONS below are on the SHIPPED default)"
for r in Regime:
let on = run(r, resolveFeat = WaveResolveFeatures)
let off = run(r, resolveFeat = false)
echo &" {regimeName(r):<7} default: perp={on.perp:6.2f} along={on.along:6.2f} hit={on.hit*100:6.2f}%" &
&" | fire-time feats (before): perp={off.perp:6.2f} along={off.along:6.2f} hit={off.hit*100:6.2f}%"
# The oscillation is the LATERAL component: an along-track error is just an
# under/over-lead, a lateral one is the aim crossing to the other side.
case r
of rSmooth: check("smooth: lateral error stays negligible",
on.perp < 1.0, &"{on.perp:.2f} px")
of rAccel: check("accel: lateral error under 8 px (was 10.9 px without the refresh)",
on.perp < 8.0, &"{on.perp:.2f} px")
of rAbrupt: check("abrupt: lateral error under 3 px (was 1.6 px without the refresh)",
on.perp < 3.0, &"{on.perp:.2f} px")
check(&"{regimeName(r)}: hit rate does not regress",
on.hit >= off.hit, &"{on.hit*100:.2f}% vs {off.hit*100:.2f}%")
check(&"{regimeName(r)}: the ring intercepts enough shots to supervise at all",
on.hit > 0.0, &"{on.hit*100:.2f}%")
block:
# The fix must be a NO-OP when the feedback is not delayed (the offline
# benchmark's shape): then the fire tick IS the label tick and there is nothing
# to realign.
echo "── no-op when the label arrives on the fire tick ──"
let r = rAccel
let tj = buildTraj(r)
var a = initWaveElmGun(resolveFeat = true)
var b = initWaveElmGun(resolveFeat = false)
for t in 0..<120:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pa = a.predict(st, spd)
let pb = b.predict(st, spd)
let (bx, by) = a.base()
let truthX = clamp(bx + tj.ox[t], BotRadius, AW - BotRadius)
let truthY = clamp(by + tj.oy[t], BotRadius, AH - BotRadius)
let ev = FeedbackEvent(
prediction: pa, actualX: truthX, actualY: truthY, bulletPower: p,
fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: hypot(truthX - pa.x, truthY - pa.y),
hit: true, confidence: pa.confidence)
a.onResult(ev)
b.onResult(FeedbackEvent(
prediction: pb, actualX: truthX, actualY: truthY,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: hypot(truthX - pb.x, truthY - pb.y),
hit: true, confidence: pb.confidence))
check("identical corrections when feedback is undelayed",
a.lastDx == b.lastDx and a.lastDy == b.lastDy,
&"({a.lastDx:.6f},{a.lastDy:.6f}) vs ({b.lastDx:.6f},{b.lastDy:.6f})")
block:
# the trace must still be FOUND at the arrival tick (the refresh must not
# break the (fireTick, binIdx) lookup) -- i.e. no label is lost to it.
echo "── probe bookkeeping survives the refresh ──"
let tj = buildTraj(rSmooth)
var g = initWaveElmGun()
var pend: seq[Pending] = @[]
var lost = 0
for t in 0..<Ticks:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
let ring = g.ringFor(1)
let tof = if ring.valid: max(1, min(Ticks - 1, ring.flight.int)) else: 1
let ta = min(Ticks - 1, t + tof)
let (bx, by) = g.base()
pend.add Pending(
resolveAt: t + tof, pr: pr,
truthX: clamp(bx + tj.ox[ta], BotRadius, AW - BotRadius),
truthY: clamp(by + tj.oy[ta], BotRadius, AH - BotRadius),
fireTick: t, binIdx: waveBinForSpeed(spd), power: p)
# resolve after predict, as the harness does (see the note in `run`)
var keep: seq[Pending] = @[]
for p in pend:
if p.resolveAt <= t:
let res = hypot(p.truthX - p.pr.x, p.truthY - p.pr.y)
let before = g.trainedShots
g.onResult(FeedbackEvent(
prediction: p.pr, actualX: p.truthX, actualY: p.truthY,
bulletPower: p.power, fireTick: p.fireTick, powerBin: p.binIdx,
missDistance: res, hit: res <= BotRadius, confidence: p.pr.confidence))
if g.trainedShots == before and res <= BotRadius: inc lost
else:
keep.add p
pend = keep
check("no confirmed hit lost to the trace lookup", lost == 0,
&"{lost} hits lost, {g.trainedShots} trained, {g.traceMisses} trace misses")
echo (if failures == 0: "\nALL OK" else: &"\n{failures} FAILURE(S)")
quit(if failures == 0: 0 else: 1)