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.
548 lines
25 KiB
Nim
548 lines
25 KiB
Nim
## Offline tests for the WaveElm gun (common_libs/guns/waveelm.nim): the
|
|
## simulated expanding RING, the probe geometry, the polar bias learning and
|
|
## every guard path.
|
|
##
|
|
## Run: nim c -r --path:common_libs common_libs/tests/test_waveelm.nim
|
|
|
|
import std/[math, strformat, times, sequtils]
|
|
import gun_harness/gun_interface
|
|
import gun_harness/virtual_bullets as vb
|
|
import guns/elm
|
|
import guns/waveelm
|
|
import guns/linear
|
|
import gun_harness/offline_range
|
|
|
|
var failures = 0
|
|
proc check(name: string, ok: bool) =
|
|
if ok: echo "PASS: ", name
|
|
else: echo "FAIL: ", name; inc failures
|
|
|
|
# ── a local WorldState builder (offline_range's mkState is private) ───────────
|
|
|
|
proc mkState(tick: int, ex, ey, eh, es: float, sx = 100.0, sy = 300.0,
|
|
id = 1, w = 800.0, h = 600.0): WorldState =
|
|
WorldState(
|
|
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
|
|
selfX: sx, selfY: sy, selfSpeed: 0.0, selfHeading: 0.0,
|
|
selfRadarHeading: 0.0, selfEnergy: 100.0,
|
|
arenaWidth: w, arenaHeight: h, tick: tick,
|
|
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
|
|
energy: 100.0, lastSeenTick: tick)])
|
|
|
|
proc finite(p: GunPrediction): bool =
|
|
classify(p.x) notin {fcNan, fcInf, fcNegInf} and
|
|
classify(p.y) notin {fcNan, fcInf, fcNegInf} and
|
|
classify(p.confidence) notin {fcNan, fcInf, fcNegInf}
|
|
|
|
# ── the target the learning tests fly ─────────────────────────────────────────
|
|
#
|
|
# A STRAIGHT RUN at 2 px/tick (a realistic tickRate-limited bot speed) that fits
|
|
# inside the arena for the whole run, so it never bounces. Straight, and never
|
|
# bouncing, for two reasons that are properties of ANY constant-velocity lead —
|
|
# the ring's and the old intercept's alike:
|
|
# * a target that TURNS: the lead is straight, so the base is wrong by more
|
|
# than BotRadius for the whole flight, no shot is ever a confirmed hit, no
|
|
# label is ever produced, and the gun learns nothing (asserted explicitly in
|
|
# `testSupervision`, not hidden by feeding it synthetic hits);
|
|
# * a target that BOUNCES off a wall: the lead is straight through the wall.
|
|
const
|
|
TrajSpeed = 2.0
|
|
TrajX0 = 150.0
|
|
TrajY = 300.0
|
|
|
|
proc trajPos(tick: int): tuple[x, y, heading: float] =
|
|
(TrajX0 + TrajSpeed * tick.float, TrajY, 0.0)
|
|
|
|
proc traj(tick: int): WorldState =
|
|
let (x, y, hd) = trajPos(tick)
|
|
mkState(tick, x, y, hd, TrajSpeed)
|
|
|
|
const
|
|
TruthLag* = 4.0 ## the turret-lag model the bench uses: the aim solution that
|
|
## was actually used is `TruthLag` ticks stale, by this gain
|
|
TruthGain* = 1.0
|
|
|
|
proc biasedTruth(tick: int, biasX, biasY: float): tuple[x, y: float] =
|
|
## Where the bullet really arrives, under the turret-lag model the gun is
|
|
## built to absorb: the aim in force was the solution for the target
|
|
## `TruthLag` ticks ago, so the truth is displaced by that much motion on top
|
|
## of the constant systematic `bias`.
|
|
let now = traj(tick)
|
|
let past = traj(tick - int(TruthLag))
|
|
(now.enemyX + biasX + TruthGain * (now.enemyX - past.enemyX),
|
|
now.enemyY + biasY + TruthGain * (now.enemyY - past.enemyY))
|
|
|
|
proc orbitState(tick: int, degPerTick: float, radius: float): WorldState =
|
|
## A hard-turning target: the regime in which the constant-velocity base has no
|
|
## supervision at all.
|
|
let a = degToRad(tick.float * degPerTick)
|
|
mkState(tick, 400.0 + radius * cos(a), 300.0 + radius * sin(a),
|
|
tick.float * degPerTick, TrajSpeed)
|
|
|
|
const
|
|
TrainTicks* = 200 ## learnLoop drives ticks 0 ..< TrainTicks
|
|
HeldOutTick* = TrainTicks + 5 ## a tick the net was never trained on
|
|
|
|
# ── 1. the power ladder and the 20 - 3*power bullet-speed formula ──────────────
|
|
|
|
proc testLadder() =
|
|
check "ladder: bulletSpeed(1.0) == 17.0 (20 - 3*power)", bulletSpeed(1.0) == 17.0
|
|
check "ladder: bulletSpeed(2.0) == 14.0", bulletSpeed(2.0) == 14.0
|
|
check "ladder: bulletSpeed(3.0) == 11.0", bulletSpeed(3.0) == 11.0
|
|
|
|
var allDistinct = true
|
|
for i in 0..<WaveRungs:
|
|
for j in i + 1..<WaveRungs:
|
|
if abs(bulletSpeed(WavePowers[i]) - bulletSpeed(WavePowers[j])) < 1e-9:
|
|
allDistinct = false
|
|
check "ladder: every rung is a distinct bullet speed", allDistinct
|
|
var legal = true
|
|
for p in WavePowers:
|
|
if p > 3.0: legal = false
|
|
check "ladder: every power is legal for Tank Royale (<= 3.0)", legal
|
|
|
|
# A wave on a STATIONARY target: each rung's ring reaches a different radius,
|
|
# so the three rungs measure the target at three different flight times. The
|
|
# contact radius is the smallest multiple of the rung speed within BotRadius of
|
|
# the true distance.
|
|
let ex = 500.0
|
|
let ey = 300.0
|
|
let d = hypot(ex - 100.0, ey - 300.0)
|
|
var hits: seq[RingHit]
|
|
# a stationary target, sampled long enough for the slowest rung's flight
|
|
var px = newSeq[float](200)
|
|
var py = newSeq[float](200)
|
|
for t in 0..<200: px[t] = ex; py[t] = ey
|
|
for p in WavePowers:
|
|
hits.add ringFire(100.0, 300.0, p, px, py, 0)
|
|
check "wave: every rung's ring intercepts a stationary in-range target",
|
|
hits[0].found and hits[1].found and hits[2].found
|
|
var threeRungs = true
|
|
for i in 0..<3:
|
|
if abs(hits[i].dist - d) > BotRadius: threeRungs = false
|
|
check &"wave: the three rungs measure the SAME {d:.1f} px target (all within BotRadius)",
|
|
threeRungs
|
|
check "wave: three rungs, three distinct contact ticks (three flight times)",
|
|
hits[0].tick != hits[1].tick and hits[1].tick != hits[2].tick
|
|
check "wave: the fastest rung contacts first", hits[0].tick < hits[2].tick
|
|
|
|
# ── 2. the ring: probe geometry, interception, decoding ───────────────────────
|
|
|
|
proc ey0(): float = 300.0 ## a stationary target's y, for the out-of-range block
|
|
|
|
proc testRing() =
|
|
# N derivation: no angular gap wider than a bot at the arena diagonal.
|
|
check &"ring: N = {RingProbes} for rMax = {RingRMax:.0f} px (800x600 diagonal)",
|
|
RingProbes == ringProbeCount(RingRMax)
|
|
check &"ring: the gap at rMax is {2.0*PI*RingRMax/RingProbes.float:.2f} px, inside BotRadius {BotRadius}",
|
|
2.0 * PI * RingRMax / RingProbes.float < BotRadius
|
|
check "ring: N grows with the range assumption (bigger map -> more probes)",
|
|
ringProbeCount(2000.0) > RingProbes and
|
|
ringProbeCount(500.0) <= RingProbes
|
|
|
|
# Interception is guaranteed for an in-range target, at ANY bearing and range.
|
|
var found = 0
|
|
var tried = 0
|
|
for deg in countup(0, 359, 7):
|
|
let a = degToRad(deg.float)
|
|
for r in [50.0, 150.0, 300.0, 500.0, 700.0, 950.0]:
|
|
let ex = 400.0 + r * cos(a)
|
|
let ey = 300.0 + r * sin(a)
|
|
let n = int(ceil(r / 11.0)) + 2
|
|
var px = newSeq[float](n)
|
|
var py = newSeq[float](n)
|
|
for t in 0..<n: px[t] = ex; py[t] = ey
|
|
let h = ringFire(400.0, 300.0, 3.0, px, py, 0)
|
|
inc tried
|
|
if h.found: inc found
|
|
check &"ring: {found}/{tried} in-range interceptions across 52 bearings x 6 ranges",
|
|
found == tried
|
|
|
|
# Decoding: a contact at (radius, bearing) IS the target's position.
|
|
block:
|
|
let ex = 400.0 + 321.0 * cos(degToRad(37.0))
|
|
let ey = 300.0 + 321.0 * sin(degToRad(37.0))
|
|
var px = newSeq[float](60); var py = newSeq[float](60)
|
|
for t in 0..<60: px[t] = ex; py[t] = ey
|
|
let h = ringFire(400.0, 300.0, 2.0, px, py, 0)
|
|
let (dx, dy) = ringDecode(h, 400.0, 300.0)
|
|
check &"ring: decode(radius, bearing) lands within BotRadius of the target " &
|
|
&"({hypot(dx-ex, dy-ey):.2f} px)",
|
|
hypot(dx - ex, dy - ey) <= BotRadius
|
|
check "ring: the decoded bearing is the probe ray's bearing",
|
|
abs(h.bearing - degToRad(37.0)) <= PI / RingProbes.float
|
|
|
|
# Out of range: nothing is claimed.
|
|
block:
|
|
let ex = 400.0 + 1800.0
|
|
var px = newSeq[float](80); var py = newSeq[float](80)
|
|
for t in 0..<80: px[t] = ex; py[t] = ey0()
|
|
let h = ringFire(400.0, 300.0, 1.0, px, py, 0)
|
|
check "ring: no interception is claimed for an out-of-range target", not h.found
|
|
check "ring: an out-of-range contact reports NaN distance, not a number",
|
|
classify(h.dist) == fcNan
|
|
|
|
# Edge cases: no crash, no NaN, and an enemy ON the shooter is still hit (the
|
|
# first annulus at 17 px is inside the 18 px radius).
|
|
block:
|
|
var px = newSeq[float](200)
|
|
var py = newSeq[float](200)
|
|
for t in 0..<200: px[t] = 400.0; py[t] = 300.0
|
|
let h = ringFire(400.0, 300.0, 1.0, px, py, 0)
|
|
check "ring: an enemy at the shooter's own position is contacted, not NaN",
|
|
h.found and h.dist == bulletSpeed(1.0)
|
|
check "ring: a zero bullet speed (power 20/3) claims nothing",
|
|
not ringFire(400.0, 300.0, 20.0 / 3.0, px, py, 0).found
|
|
# a trajectory that ENDS before the ring can reach the enemy claims nothing
|
|
var fx = @[700.0, 700.0, 700.0]
|
|
var fy = @[300.0, 300.0, 300.0]
|
|
check "ring: a trajectory that runs out before contact claims nothing",
|
|
not ringFire(400.0, 300.0, 1.0, fx, fy, 0).found
|
|
|
|
# ── 3. ELM bias learning on a KNOWN systematic bias ───────────────────────────
|
|
#
|
|
# IMPORTANT — why the feedback is fed from the TRUE position and not from the
|
|
# prediction. The obvious driver (`actual = prediction + bias`) is a POSITIVE
|
|
# FEEDBACK LOOP under any implementation: the label is then `correction +
|
|
# bias`, so the net is trained to output strictly more than it just output, and
|
|
# it walks straight into the offset clamp. A real FeedbackEvent carries the
|
|
# enemy's actual position, which does not depend on what we aimed at, and that is
|
|
# what is fed here. (Measured: with the prediction-relative driver the net
|
|
# saturates at +-36 px within 40 ticks.)
|
|
|
|
proc learnLoop(g: var WaveElmGun, ticks: int, biasX, biasY: float,
|
|
feedHits = true, tick0 = 0): tuple[shots, hits: int] =
|
|
## Drive the gun over a moving target exactly as the harness would: one predict
|
|
## per rung per tick, then an event whose ACTUAL position is the target's TRUE
|
|
## position AT THE BULLET'S ARRIVAL (the ring's contact is a lead: it is the
|
|
## target's position `flight` ticks from now, which is where a bullet fired now
|
|
## lands) plus the systematic `bias`. `hit` is TRUE only when the target was
|
|
## inside BotRadius of the aim point — the virtual-bullet resolver's own
|
|
## criterion, and the reason a miss carries no label.
|
|
for i in 0..<ticks:
|
|
let t = tick0 + i
|
|
let st = traj(t)
|
|
for p in WavePowers:
|
|
let spd = bulletSpeed(p)
|
|
let pr = g.predict(st, spd)
|
|
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
|
|
let truth = biasedTruth(t + k, (if feedHits: biasX else: 0.0),
|
|
(if feedHits: biasY else: 0.0))
|
|
let (ax, ay) = truth
|
|
let res = hypot(pr.x - ax, pr.y - ay)
|
|
let hit = feedHits and res <= BotRadius
|
|
inc result.shots
|
|
if hit: inc result.hits
|
|
g.onResult(FeedbackEvent(
|
|
prediction: pr, actualX: ax, actualY: ay,
|
|
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
|
|
missDistance: res, hit: hit, confidence: pr.confidence))
|
|
|
|
## RMS aim error of the gun over a held-out window, and of the RAW ring
|
|
## reconstruction it sits on (bias 0). The ELM earns its place only if the
|
|
## second is strictly worse than the first.
|
|
proc heldOutRms(g: var WaveElmGun, fromTick, n: int, biasX, biasY: float): float =
|
|
## The aim is scored against where the bullet ARRIVES: the ring's contact is a
|
|
## LEAD, so scoring it against the target's current position would charge the
|
|
## gun for the lead it is supposed to apply.
|
|
var sq = 0.0
|
|
for t in fromTick..<(fromTick + n):
|
|
let st = traj(t)
|
|
for p in WavePowers:
|
|
let pr = g.predict(st, bulletSpeed(p))
|
|
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
|
|
let (tx, ty) = biasedTruth(t + k, biasX, biasY)
|
|
sq += (pr.x - tx) ^ 2 + (pr.y - ty) ^ 2
|
|
sqrt(sq / (n.float * WaveRungs.float))
|
|
|
|
proc rawRms(fromTick, n: int, biasX, biasY: float): float =
|
|
## Same window, same bias, but a gun that never learned anything: the aim is
|
|
## the bare ring reconstruction.
|
|
var g = initWaveElmGun()
|
|
var sq = 0.0
|
|
for t in fromTick..<(fromTick + n):
|
|
let st = traj(t)
|
|
for p in WavePowers:
|
|
let pr = g.predict(st, bulletSpeed(p))
|
|
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
|
|
let (tx, ty) = biasedTruth(t + k, biasX, biasY)
|
|
sq += (pr.x - tx) ^ 2 + (pr.y - ty) ^ 2
|
|
sqrt(sq / (n.float * WaveRungs.float))
|
|
|
|
proc testLearning() =
|
|
block:
|
|
var g = initWaveElmGun()
|
|
let cnt = learnLoop(g, TrainTicks, 5.0, 0.0)
|
|
echo &" trained={g.trainedShots} traceMisses={g.traceMisses} " &
|
|
&"rejected={g.rejectedShots} misses={g.missShots} netSamples={g.net.samples} " &
|
|
&"rings={g.ringContacts}/{g.ringFires} hits={cnt.hits}/{cnt.shots}"
|
|
check "learning: every CONFIRMED hit trained (no fabricated, no lost samples)",
|
|
g.trainedShots == cnt.hits and g.traceMisses == 0
|
|
check "learning: misses are counted and never trained",
|
|
g.missShots + g.trainedShots + g.rejectedShots == cnt.shots
|
|
check "learning: the ring fired and found a contact on essentially every tick",
|
|
g.ringContacts >= g.ringFires - 2 and g.ringFires > 0
|
|
check "learning: net is still sane after 200 RLS updates", g.net.isSane()
|
|
# HELD-OUT window: the net has never seen these ticks.
|
|
let base = rawRms(TrainTicks, 60, 5.0, 0.0)
|
|
let got = heldOutRms(g, TrainTicks, 60, 5.0, 0.0)
|
|
echo &" held-out aim RMS vs truth (bias 5 px + turret lag): ring alone {base:.2f} px -> with the ELM {got:.2f} px"
|
|
# An ABSOLUTE margin, not a percentage: the bare ring's error on a given tick
|
|
# is dominated by the annulus quantisation (+-spd/2), which the bias happens
|
|
# to cancel or double, so a ratio threshold measures the target's luck.
|
|
check &"learning: the ELM beats the bare ring reconstruction ({got:.2f} < {base:.2f} px)",
|
|
got < base - 0.5
|
|
# LABEL SURVIVAL, the number the directed design was killed for: only
|
|
# confirmed hits carry a label, so the survival rate IS the interception
|
|
# rate. The directed design measured 21.5%.
|
|
let surv = cnt.hits.float / cnt.shots.float
|
|
echo &" label survival = {surv*100:.1f}% (directed design measured 21.5%)"
|
|
check &"learning: label survival beats the directed design ({surv*100:.1f}% > 21.5%)",
|
|
surv > 0.215
|
|
block:
|
|
# A 2-D bias: the two outputs are independent, neither steals the other.
|
|
var g = initWaveElmGun()
|
|
discard learnLoop(g, TrainTicks, -4.0, 7.0)
|
|
let st = traj(HeldOutTick)
|
|
let pr = g.predict(st, bulletSpeed(2.0))
|
|
echo &" 2-D bias, held-out correction: ({g.lastDx:.3f}, {g.lastDy:.3f}), truth (-4, 7)"
|
|
check "learning: the 2-D correction points along the bias it was trained on",
|
|
(g.lastDx * -4.0 + g.lastDy * 7.0) > 0.0
|
|
let base = rawRms(TrainTicks, 60, -4.0, 7.0)
|
|
let got = heldOutRms(g, TrainTicks, 60, -4.0, 7.0)
|
|
echo &" held-out aim RMS vs truth (bias (-4,7) + turret lag): ring alone {base:.2f} px -> with the ELM {got:.2f} px"
|
|
check &"learning: the ELM beats the bare ring on a 2-D bias too ({got:.2f} < {base:.2f} px)",
|
|
got < base - 0.5
|
|
|
|
proc testSupervision() =
|
|
## THE STARVATION LIMITATION, asserted rather than hidden: on a target that
|
|
## turns hard every tick the ring's constant-velocity base is wrong by more
|
|
## than BotRadius for the whole flight, so not one shot is a confirmed hit and
|
|
## the net gets no labels. The directed design had the same failure (its
|
|
## measured label survival was 21.5%); the ring's failure is sharper, because
|
|
## its base error grows with the turn.
|
|
block: # the straight-line target DOES supervise
|
|
var g = initWaveElmGun()
|
|
let c = learnLoop(g, TrainTicks, 5.0, 0.0)
|
|
echo &" straight target: labels {c.hits}/{c.shots} ({c.hits*100/c.shots}%)"
|
|
check "supervision: the straight-line target supervises the net (> 80% labels)",
|
|
c.hits.float / c.shots.float > 0.8
|
|
block: # a hard turner does not, and that is a documented ceiling
|
|
var g = initWaveElmGun()
|
|
var shots = 0
|
|
var hits = 0
|
|
for t in 0..<TrainTicks:
|
|
let st = orbitState(t, 6.0, 48.0)
|
|
for p in WavePowers:
|
|
let pr = g.predict(st, bulletSpeed(p))
|
|
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
|
|
let truth = orbitState(t + k, 6.0, 48.0)
|
|
let res = hypot(pr.x - truth.enemyX, pr.y - truth.enemyY)
|
|
inc shots
|
|
if res <= BotRadius: inc hits
|
|
g.onResult(FeedbackEvent(prediction: pr, actualX: truth.enemyX,
|
|
actualY: truth.enemyY, bulletPower: p, fireTick: t,
|
|
powerBin: waveBinForSpeed(bulletSpeed(p)), missDistance: res,
|
|
hit: res <= BotRadius, confidence: pr.confidence))
|
|
echo &" 6 deg/tick orbit: labels {hits}/{shots}"
|
|
check "supervision: a 6 deg/tick orbit yields no usable labels (known ceiling)",
|
|
hits == 0 and g.trainedShots == 0
|
|
|
|
# ── 4. guard paths ────────────────────────────────────────────────────────────
|
|
|
|
proc testGuards() =
|
|
block:
|
|
# Implausibly large residual: a "hit" 500 px from the aim point is not this
|
|
# gun's model, so it must never reach beta.
|
|
var g = initWaveElmGun()
|
|
discard learnLoop(g, 60, 5.0, 0.0)
|
|
let before = g.trainedShots
|
|
let st = mkState(500, 400.0, 300.0, 0.0, 5.0)
|
|
let big = 500.0
|
|
for p in WavePowers:
|
|
let spd = bulletSpeed(p)
|
|
let pr = g.predict(st, spd)
|
|
# the label is (actual - ring reconstruction), so the residual is injected
|
|
# at the RECONSTRUCTION, not at the already-corrected aim point
|
|
let (bx, by) = ringDecode(g.ringFor(1), st.selfX, st.selfY)
|
|
g.onResult(FeedbackEvent(prediction: pr,
|
|
actualX: bx + big, actualY: by,
|
|
bulletPower: p, fireTick: 500, powerBin: waveBinForSpeed(spd),
|
|
hit: true, confidence: pr.confidence))
|
|
check &"guard: a {WaveMaxResidual:.0f} px residual is rejected ({big:.0f} px fed)",
|
|
g.trainedShots == before and g.rejectedShots == WaveRungs
|
|
check "guard: a residual exactly at the limit ({3.0*BotRadius:.0f} px) is still accepted",
|
|
(block:
|
|
var g2 = initWaveElmGun()
|
|
discard learnLoop(g2, 40, 0.0, 0.0)
|
|
let b2 = g2.trainedShots
|
|
for p in WavePowers:
|
|
let spd = bulletSpeed(p)
|
|
let pr = g2.predict(st, spd)
|
|
let (bx, by) = ringDecode(g2.ringFor(1), st.selfX, st.selfY)
|
|
let d = 3.0 * BotRadius - 0.001
|
|
g2.onResult(FeedbackEvent(prediction: pr,
|
|
actualX: bx + d, actualY: by,
|
|
bulletPower: p, fireTick: st.tick, powerBin: waveBinForSpeed(spd),
|
|
hit: true, confidence: pr.confidence))
|
|
g2.trainedShots > b2)
|
|
|
|
block:
|
|
# A MISS carries no label: it says the aim was wrong, not where.
|
|
var g = initWaveElmGun()
|
|
let c = learnLoop(g, 40, 0.0, 0.0, feedHits = false)
|
|
check "guard: misses are never trained on", g.trainedShots == 0
|
|
check "guard: misses are counted", g.missShots == c.shots
|
|
|
|
block:
|
|
# An orphaned event (no trace in the ring) must be counted, not fabricated.
|
|
var g = initWaveElmGun()
|
|
discard learnLoop(g, 10, 5.0, 0.0)
|
|
let st = mkState(77, 400.0, 300.0, 0.0, 5.0)
|
|
let pr = g.predict(st, bulletSpeed(2.0))
|
|
let before = g.trainedShots
|
|
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 3.0, actualY: pr.y,
|
|
bulletPower: 2.0, fireTick: 999999, powerBin: 2, hit: true,
|
|
confidence: pr.confidence)) # orphan: the trace lookup fails first
|
|
check "guard: an orphaned hit (unknown fireTick) is counted, not fabricated",
|
|
g.trainedShots == before and g.traceMisses == 1
|
|
|
|
block:
|
|
# A brand new gun, no history at all.
|
|
var g = initWaveElmGun()
|
|
let st = mkState(0, 500.0, 300.0, 45.0, 6.0)
|
|
let pr = g.predict(st, bulletSpeed(1.0))
|
|
check "guard: a fresh bot with no scan history predicts without crashing",
|
|
pr.finite and pr.x > 0.0 and pr.y > 0.0
|
|
check "guard: a fresh bot is not warmed up (needs 2 scans for a velocity)",
|
|
not g.isWarmedUp()
|
|
let st2 = mkState(1, 506.0, 300.0, 45.0, 6.0)
|
|
discard g.predict(st2, bulletSpeed(1.0))
|
|
check "guard: two scans make it warm", g.isWarmedUp()
|
|
|
|
block:
|
|
# NaN / Inf must never escape the gun, in the state or in the net.
|
|
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, 300.0, bad, bad)
|
|
for p in WavePowers:
|
|
let pr = g.predict(st, bulletSpeed(p))
|
|
if not pr.finite:
|
|
check &"guard: NaN/Inf in the state never escapes (bad={bad})", false
|
|
return
|
|
check "guard: NaN/Inf in the state never escapes the prediction", true
|
|
check "guard: features of a degenerate state are all finite",
|
|
(block:
|
|
let st = mkState(1, nan, nan, nan, nan)
|
|
let f = g.waveFeatures(st, 0.0, 0.0, 0.0)
|
|
var ok = true
|
|
for v in f:
|
|
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
|
|
ok)
|
|
|
|
# ── 5. Gun-concept conformance ────────────────────────────────────────────────
|
|
|
|
proc testGunConcept() =
|
|
var g = initWaveElmGun()
|
|
var x = 300.0
|
|
var y = 300.0
|
|
var sawDistinct = false
|
|
var last: seq[GunPrediction]
|
|
for t in 0..<12:
|
|
let st = mkState(t, x, y, 30.0, 6.0)
|
|
var preds: seq[GunPrediction]
|
|
for p in WavePowers: preds.add g.predict(st, bulletSpeed(p))
|
|
if last.len == preds.len and last.len > 0:
|
|
for i in 0..<preds.len:
|
|
if hypot(preds[i].x - last[i].x, preds[i].y - last[i].y) > 1.0:
|
|
sawDistinct = true
|
|
last = preds
|
|
for i, p in WavePowers:
|
|
let spd = bulletSpeed(p)
|
|
let pr = preds[i]
|
|
g.onResult(FeedbackEvent(prediction: pr,
|
|
actualX: pr.x + 6.0, actualY: pr.y - 2.0,
|
|
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
|
|
hit: true, confidence: pr.confidence))
|
|
x += 5.2
|
|
check "gun: predict/onResult are a valid Gun pair (isGun template)",
|
|
isGun(WaveElmGun)
|
|
check "gun: the ring-tracked aim moves as the target moves", sawDistinct
|
|
check "gun: the wave trained on every rung", g.trainedShots == 12 * WaveRungs
|
|
check "gun: net sane", g.net.isSane()
|
|
|
|
# ── 6. it produces a usable aim point on every rung of a straight target ─────
|
|
|
|
proc testAgainstLinear() =
|
|
## Same convention as the other offline gun tests: replaying a stream through
|
|
## the real VirtualTracker is the online hit rate. Compared against Linear as
|
|
## the closed-form baseline.
|
|
var states: seq[WorldState]
|
|
var x = 100.0
|
|
for t in 0..<240:
|
|
states.add mkState(t, x, 300.0, 0.0, 4.0)
|
|
x = (x + 4.0).clamp(BotRadius, 800.0 - BotRadius)
|
|
var meta = initMeta(source = "synthetic")
|
|
meta.adversary = "constant-velocity"
|
|
meta.note = "constant-velocity reference stream for WaveElm"
|
|
let fx = initFixture(states, meta)
|
|
let reps = replayFixture(fx, @[makeDriver("WaveElm", initWaveElmGun()),
|
|
makeDriver("Linear", LinearGun())])
|
|
echo &" {reps[0].name} {reps[0].hits}/{reps[0].shots} ({reps[0].hitRate()*100:.1f}%)" &
|
|
&" {reps[1].name} {reps[1].hits}/{reps[1].shots} ({reps[1].hitRate()*100:.1f}%)"
|
|
check "replay: the wave was actually shot at over the whole stream",
|
|
reps[0].shots > 100
|
|
check "replay: WaveElm is not worse than the closed-form Linear baseline",
|
|
reps[0].hitRate() >= reps[1].hitRate() - 0.02
|
|
|
|
# ── 7. REGRESSION: non-finite state must not hang the gun ────────────────────
|
|
|
|
proc testNonFiniteState() =
|
|
## enemyHeading = ±Inf used to hang the bot outright: the angle wrap was
|
|
## `while hdelta > 180: hdelta -= 360`, and `Inf - 360.0 == Inf`, so the body
|
|
## made no progress and the loop never left (100% CPU, no output). Every FLOAT
|
|
## field of the state is now non-finite in turn, and predict must both return
|
|
## promptly and return finite numbers.
|
|
var g = initWaveElmGun()
|
|
let nan = 0.0 / 0.0
|
|
for (label, bad) in [("NaN", nan), ("+Inf", 1.0 / 0.0), ("-Inf", -1.0 / 0.0)]:
|
|
for field in ["enemyX", "enemyY", "enemyHeading", "enemySpeed",
|
|
"selfX", "selfY", "arenaWidth", "arenaHeight"]:
|
|
var st = mkState(3, 420.0, 260.0, 35.0, 5.0)
|
|
case field
|
|
of "enemyX": st.enemyX = bad
|
|
of "enemyY": st.enemyY = bad
|
|
of "enemyHeading": st.enemyHeading = bad
|
|
of "enemySpeed": st.enemySpeed = bad
|
|
of "selfX": st.selfX = bad
|
|
of "selfY": st.selfY = bad
|
|
of "arenaWidth": st.arenaWidth = bad
|
|
else: st.arenaHeight = bad
|
|
var ok = true
|
|
let t0 = epochTime()
|
|
for p in WavePowers:
|
|
if not g.predict(st, bulletSpeed(p)).finite: ok = false
|
|
let f = g.waveFeatures(st, 1.0, 1.0, 30.0)
|
|
for v in f:
|
|
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
|
|
check &"nonfinite: {label} in {field} -> finite prediction and features",
|
|
ok
|
|
check &"nonfinite: {label} in {field} returns promptly",
|
|
epochTime() - t0 < 1.0
|
|
|
|
when isMainModule:
|
|
testLadder()
|
|
testRing()
|
|
testLearning()
|
|
testSupervision()
|
|
testGuards()
|
|
testGunConcept()
|
|
testAgainstLinear()
|
|
testNonFiniteState()
|
|
if failures > 0:
|
|
echo "\n", failures, " check(s) FAILED"
|
|
quit(1)
|
|
echo "\nAll WaveElm checks passed."
|