Files
SirRoboGarage/common_libs/tests/test_waveelm_ring.nim
T
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

332 lines
17 KiB
Nim

## test_waveelm_ring.nim — the SIMULATED EXPANDING RING, on its own terms.
##
## Everything here tests `ringFire` / `ringProbeCount` / the gun's scan-only ring,
## NOT the ELM on top of it (common_libs/tests/test_waveelm.nim covers that):
##
## (a) interception is GUARANTEED for an in-range enemy, across bearings, ranges
## and motion — the 100% claim, asserted rather than assumed;
## (b) the radius -> distance decoding is correct against known geometry;
## (c) N directions leave no angular gap wider than a bot at maximum range;
## (d) nothing is claimed for an enemy that is out of range (or unreachably
## fast, or behind a wall the ring cannot be said to have passed);
## (e) the ELM's bias correction converges OFFLINE on a synthetic bias;
## (f) edge cases: enemy at the shooter's own position, at maximum range, at
## zero velocity — no crash, no NaN, no unbounded loop;
## (g) SCAN-ONLY LEGITIMACY: the live ring's entire input is the selected scan
## plus the velocity derived from that same target's own last two scans.
##
## Run: nim c -r common_libs/tests/test_waveelm_ring.nim
import std/[math, strformat, sequtils]
import gun_harness/gun_interface
import guns/elm
import guns/waveelm
var failures = 0
var checks = 0
proc check(name: string, ok: bool) =
inc checks
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc fin(x: float): bool = classify(x) notin {fcNan, fcInf, fcNegInf}
proc mkState(tick: int, ex, ey, eh, es: float, id = 1,
sx = 400.0, sy = 300.0): WorldState =
WorldState(
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
selfX: sx, selfY: sy, arenaWidth: 800.0, arenaHeight: 600.0, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
type Traj = object
px, py: seq[float]
## A straight-line trajectory long enough for the slowest rung's flight.
proc trajLine(x0, y0, vx, vy: float, n: int): Traj =
result.px = newSeq[float](n)
result.py = newSeq[float](n)
for t in 0..<n:
result.px[t] = x0 + vx * t.float
result.py[t] = y0 + vy * t.float
# ── (c) the probe count ──────────────────────────────────────────────────────
proc testProbeCount() =
check &"probes: N = {RingProbes} is derived, not hardcoded",
RingProbes == ringProbeCount(RingRMax)
check &"probes: rMax = the {RingArenaW:.0f}x{RingArenaH:.0f} diagonal = {RingRMax:.1f} px",
abs(RingRMax - hypot(RingArenaW, RingArenaH)) < 1e-9
let gap = 2.0 * PI * RingRMax / RingProbes.float
check &"probes: angular gap at max range is {gap:.2f} px < BotRadius {BotRadius}",
gap < BotRadius
check "probes: the raw minimum N = 2*pi*rMax/BotRadius is 350 for 800x600",
int(ceil(2.0 * PI * 1000.0 / BotRadius)) == 350
check "probes: a bigger map yields more probes, a smaller one fewer",
ringProbeCount(2000.0) > RingProbes and
ringProbeCount(400.0) < RingProbes
check "probes: the gap is inside a bot at the SMALL map's diagonal too",
2.0 * PI * hypot(500.0, 300.0) / ringProbeCount(hypot(500.0, 300.0)).float < BotRadius
check "probes: a degenerate range still yields a usable probe count",
ringProbeCount(0.0) >= 60 and ringProbeCount(-5.0) >= 60
check "probes: the bearings cover the full circle without a seam",
abs(RingDirs[0]) < 1e-12 and
abs(RingDirs[RingProbes - 1] - 2.0 * PI * (RingProbes - 1).float /
RingProbes.float) < 1e-12
# the worst gap is between ADJACENT probes: no bearing has a wider one
var worst = 0.0
for i in 0..<RingProbes:
let a = RingDirs[i]
let b = RingDirs[(i + 1) mod RingProbes]
worst = max(worst, if i == RingProbes - 1: 2.0 * PI - a + b else: b - a)
check &"probes: the widest adjacent gap is {worst*RingRMax:.2f} px at max range",
worst * RingRMax < BotRadius
# ── (a) interception is guaranteed ───────────────────────────────────────────
proc testInterception() =
block: # static targets, every bearing, every range
var found = 0
var tried = 0
var worstRadial = 0.0
for deg in countup(0, 359, 3):
let a = degToRad(deg.float)
for r in [BotRadius, 50.0, 137.0, 300.0, 601.0, 900.0, RingRMax]:
let tj = trajLine(400.0 + r * cos(a), 300.0 + r * sin(a), 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 2.0, tj.px, tj.py, 0)
inc tried
if h.found:
inc found
worstRadial = max(worstRadial, abs(h.dist - r))
check &"ring: {found}/{tried} static interceptions (120 bearings x 7 ranges)",
found == tried
check &"ring: every measurement is within BotRadius of the true range (worst {worstRadial:.2f} px)",
worstRadial <= BotRadius
block: # a MOVING target, faster than the slowest rung, every bearing
var found = 0
var tried = 0
for deg in countup(0, 359, 11):
let a = degToRad(deg.float)
# every velocity is SLOWER than the 11 px/tick rung of this block, which is
# the condition for interception to be guaranteed at all (a target fleeing
# faster than the ring expands is physically unreachable — see
# testNoClaim / the "faster than the bullet" case below)
for (vx, vy) in [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0), (-7.0, 3.0)]:
let tj = trajLine(400.0 + 300.0 * cos(a), 300.0 + 300.0 * sin(a),
vx, vy, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
inc tried
if h.found: inc found
check &"ring: {found}/{tried} moving interceptions (33 bearings x 4 velocities)",
found == tried
block: # a target fleeing at close to the bullet's speed: the ring closes only
# `spd - v` px/tick, so whether it is reached inside the ring's reach is
# an arithmetic question, and the ring must answer it honestly in BOTH
# directions (caught -> contact; out of reach -> nothing claimed).
var caught = 0
var fled = 0
for vx in [-15.0, -12.0, 12.0, 15.0]:
let tj = trajLine(200.0, 300.0, vx, 0.0, 400)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
# The target starts 200 px WEST of the shooter, so vx > 0 is APPROACHING:
# the gap closes at (17 + vx) px/tick, and the contact is reachable only if
# the 200 px close within the ring's own reach (maxK = rMax/17 ticks).
let reachable = 200.0 / (17.0 + vx) <= RingRMax / 17.0
if h.found: inc caught
if not h.found and not reachable: inc fled
check &"ring: a target at vx={vx:.0f} px/tick -> " &
(if h.found: "intercepted" else: "correctly out of reach"),
h.found == reachable
check &"ring: the slow-flee cases are intercepted and the fast-flee ones are not",
caught == 3 and fled == 1
# ── (b) decoding ─────────────────────────────────────────────────────────────
proc testDecoding() =
for r in [60.0, 250.0, 640.0]:
for deg in countup(0, 350, 17):
let a = degToRad(deg.float)
let ex = 400.0 + r * cos(a)
let ey = 300.0 + r * sin(a)
let tj = trajLine(ex, ey, 0.0, 0.0, 300)
let h = ringFire(400.0, 300.0, 2.0, tj.px, tj.py, 0)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: decode at r={r:.0f} deg={deg} is within BotRadius of the target",
h.found and hypot(dx - ex, dy - ey) <= BotRadius
if not (h.found and hypot(dx - ex, dy - ey) <= BotRadius): break
# a moving target: the contact is its position at the FLIGHT TIME, which is the
# lead a bullet fired now must be given.
block:
let tj = trajLine(400.0, 300.0, 6.0, 0.0, 300)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
let k = float(h.tick)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: the decoding is the target's position at the contact tick " &
&"(k={k.int}, err={hypot(dx - tj.px[k.int], dy - tj.py[k.int]):.2f} px)",
h.found and hypot(dx - tj.px[k.int], dy - tj.py[k.int]) <= BotRadius
check "ring: the flight time is reported in ticks, not as an absolute tick",
h.tick > 0 and h.tick < 100 and fin(h.dist) and fin(h.bearing)
# ── (d) out of range, and the other "no" cases ───────────────────────────────
proc testNoClaim() =
block:
let tj = trajLine(400.0 + RingRMax + 250.0, 300.0, 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
check "ring: nothing is claimed past the ring's reach", not h.found
check "ring: a missed ring reports NaN distance, not a plausible number",
classify(h.dist) == fcNan and fin(h.missDist)
block:
# receding faster than the ring expands, starting inside the reach: the ring
# never catches it, and the ring says so.
let tj = trajLine(900.0, 300.0, 20.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
check "ring: a target outrunning the ring is NOT claimed", not h.found
block:
# the trajectory ends before contact
let tj = trajLine(600.0, 300.0, 0.0, 0.0, 2)
check "ring: a trajectory that ends early is not claimed",
not ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0).found
check "ring: a fire tick past the end of the trajectory is not claimed",
not ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 5).found
# ── (f) edge cases ───────────────────────────────────────────────────────────
proc testEdgeCases() =
block: # enemy ON the shooter
let tj = trajLine(400.0, 300.0, 0.0, 0.0, 100)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
check "edge: an enemy at the shooter's own position is contacted on tick 1",
h.found and h.tick == 1 and abs(h.dist - 17.0) < 1e-9
let (dx, dy) = ringDecode(h, 400.0, 300.0)
# it decodes to the first annulus (radius 17 px along bearing 0), not to the
# shooter's own point — the ring measures a DISC, and a disc of radius 18
# centred on the shooter is touched by the 17 px annulus.
check "edge: and it decodes to the touched annulus (17 px out), without NaN",
fin(dx) and fin(dy) and abs(hypot(dx - 400.0, dy - 300.0) - 17.0) < 1e-9
block: # zero velocity
let tj = trajLine(700.0, 300.0, 0.0, 0.0, 200)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
check "edge: a zero-velocity target is intercepted normally",
h.found and fin(h.dist) and fin(h.bearing) and fin(h.missDist)
block: # maximum range, both extremes of the ladder
for p in WavePowers:
let tj = trajLine(400.0 + RingRMax, 300.0, 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, p, tj.px, tj.py, 0)
check &"edge: a target at exactly rMax is intercepted on power {p}",
h.found and abs(h.dist - RingRMax) <= BotRadius
block: # non-finite input to the LIVE ring
var g = initWaveElmGun()
let nan = 0.0 / 0.0
let inf = 1.0 / 0.0
for bad in [nan, inf, -inf]:
let st = mkState(1, bad, bad, bad, bad)
let h = g.ringFireFromScan(st, bad, bad, 17.0)
check &"edge: a NaN/Inf scan makes the live ring claim nothing, not crash",
(not h.found) or (fin(h.dist) and fin(h.bearing))
let h0 = g.ringFireFromScan(mkState(1, 600.0, 300.0, 0.0, 5.0), 5.0, 0.0, 0.0)
check "edge: a zero bullet speed claims nothing", not h0.found
# ── (g) SCAN-ONLY LEGITIMACY ─────────────────────────────────────────────────
proc testScanOnly() =
## PROOF, not a promise: the live ring is fed a WorldState and reads the
## SELECTED SCAN. Every other enemy's information in `state.enemies` is
## replaced with garbage — and the ring's output does not move. If the ring
## were using omniscient positions (or any other enemy's), this fails.
var g1 = initWaveElmGun()
var g2 = initWaveElmGun()
var decoy1 = 700.0
var decoy2 = 120.0
for t in 0..<40:
let ex = 300.0 + 4.0 * t.float
var st1 = mkState(t, ex, 300.0, 0.0, 4.0, id = 1)
var st2 = mkState(t, ex, 300.0, 0.0, 4.0, id = 1)
# a second enemy, in two different places, with different velocities
st1.enemies.add EnemyInfo(id: 7, x: decoy1, y: 100.0, heading: 90.0,
speed: 9.0, energy: 100.0, lastSeenTick: t)
st2.enemies.add EnemyInfo(id: 7, x: decoy2, y: 500.0, heading: 270.0,
speed: 1.0, energy: 100.0, lastSeenTick: t)
discard g1.predict(st1, bulletSpeed(1.0))
discard g2.predict(st2, bulletSpeed(1.0))
decoy1 = (decoy1 + 9.0) mod 700.0
decoy2 = (decoy2 - 1.0).mod(700.0)
let r1 = g1.ringFor(1)
let r2 = g2.ringFor(1)
check "scan-only: the ring is byte-identical when every OTHER enemy moves",
r1.dist == r2.dist and r1.bear == r2.bear and r1.tick == r2.tick
# The tracked target is pinned by the rack (targetId), so the ring follows the
# PINNED enemy and not `enemies[0]` either.
block:
var g = initWaveElmGun()
for t in 0..<20:
var st = mkState(t, 300.0 + 3.0 * t.float, 200.0, 0.0, 3.0, id = 1)
st.enemies.add EnemyInfo(id: 9, x: 700.0, y: 100.0, heading: 0.0,
speed: 5.0, energy: 100.0, lastSeenTick: t)
g.targetId = 9
discard g.predict(st, bulletSpeed(1.0))
g.targetId = -1
check "scan-only: with the rack pinning id 9 the ring measures id 9's state",
g.ringFor(9).valid and not g.ringFor(1).valid
# ── (e) the ELM's bias correction converges offline ──────────────────────────
proc testElmConverges() =
## The gun, driven over a straight target (the only regime in which a
## constant-velocity base gets any supervision at all — see
## common_libs/tests/test_waveelm.nim `testSupervision`), with a constant
## systematic bias fed back as CONFIRMED hits. The learned correction must
## converge on it and stay there.
const Speed = 2.0
var g = initWaveElmGun()
var labels = 0
var misses = 0
let (biasX, biasY) = (6.0, -3.0)
for t in 0..<300:
let x = 150.0 + Speed * t.float
let st = mkState(t, x, 300.0, 0.0, Speed)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(1, int(round(g.ringFor(1).flight)))
let ax = 150.0 + Speed * (t + k).float + biasX
let ay = 300.0 + biasY
let res = hypot(pr.x - ax, pr.y - ay)
let hit = res <= BotRadius
if hit: inc labels else: inc misses
g.onResult(FeedbackEvent(prediction: pr, actualX: ax, actualY: ay,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(bulletSpeed(p)),
missDistance: res, hit: hit, confidence: pr.confidence))
echo &" offline convergence: {labels} labels, {misses} misses, " &
&"net samples {g.net.samples}, correction ({g.lastDx:.2f}, {g.lastDy:.2f}) " &
&"(true bias ({biasX}, {biasY}))"
check "elm: the ring supervises the net on a straight target (> 80% labels)",
labels.float / (labels + misses).float > 0.8
check &"elm: the correction converges on the {biasX:.0f}/{biasY:.0f} px bias (< 2 px)",
hypot(g.lastDx - biasX, g.lastDy - biasY) < 2.0
check "elm: no soft reset was needed on a clean stream", g.net.resets == 0
check "elm: the net is sane", g.net.isSane()
# ... and it STAYS there: a cold gun is strictly worse on the same tick.
var cold = initWaveElmGun()
let st = mkState(400, 150.0 + Speed * 400.0, 300.0, 0.0, Speed)
let warm = g.predict(st, bulletSpeed(2.0))
let (cx, cy) = ringDecode(g.ringFor(1), st.selfX, st.selfY)
discard cold.predict(st, bulletSpeed(2.0))
let cool = cold.predict(st, bulletSpeed(2.0))
check "elm: the converged gun aims closer to the biased truth than a cold one",
hypot(warm.x - (cx + biasX), warm.y - (cy + biasY)) <
hypot(cool.x - (cx + biasX), cool.y - (cy + biasY))
when isMainModule:
echo "── (c) probe count ──"; testProbeCount()
echo "── (a) interception ──"; testInterception()
echo "── (b) decoding ──"; testDecoding()
echo "── (d) out of range ──"; testNoClaim()
echo "── (f) edge cases ──"; testEdgeCases()
echo "── (g) scan-only ──"; testScanOnly()
echo "── (e) ELM offline ──"; testElmConverges()
if failures > 0:
echo "\n", failures, " of ", checks, " check(s) FAILED"
quit(1)
echo &"\nAll {checks} WaveElm-ring checks passed."