## 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.. 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..= 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.. 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.. 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."