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.
This commit is contained in:
2026-10-05 22:43:22 +02:00
parent 68c6af98dc
commit 7505fbf089
17 changed files with 8427 additions and 0 deletions
@@ -0,0 +1,393 @@
## 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}%)"
+24
View File
@@ -0,0 +1,24 @@
## Cross-check probe for `measure_gk_residual.py`: it prints the PRODUCTION aim
## base of `guns/gun_knowledge.nim` -- the exact angle `KnowledgeGun.predict`
## turns into its prediction point -- for every
## ex ey eh es sx sy power
## line on stdin, one float per line on stdout. The measurement script replays
## the aim offline and asserts that its replay equals THIS, so the offline
## numbers cannot silently drift away from the shipped code again.
##
## Build: nim c --path:common_libs common_libs/tests/gk_aim_probe.nim
## (the script builds it itself and skips the cross-check with a loud warning
## if the binary is missing).
import std/[os, strutils]
import guns/gun_knowledge
for line in stdin.lines:
let f = line.splitWhitespace()
if f.len < 7: continue
let feat = GkFeatures(
enemyX: parseFloat(f[0]), enemyY: parseFloat(f[1]),
enemyHeading: parseFloat(f[2]), enemySpeed: parseFloat(f[3]),
selfX: parseFloat(f[4]), selfY: parseFloat(f[5]),
power: parseFloat(f[6]), hasTarget: true)
echo forecastBase(feat, 0.0)
File diff suppressed because it is too large Load Diff
+732
View File
@@ -0,0 +1,732 @@
#!/usr/bin/env python3
"""MEASURE: the gun-knowledge learned ANGULAR RESIDUAL vs the bare
`forecastLinear` base, over VIRTUAL BULLETS on the recorded corpus.
`measure_gk_residual.py` measured the residual on REAL FIRED SHOTS (~55k). This
script re-measures it on the thing the module actually learns from in battle:
VIRTUAL BULLETS. `gun_harness/virtual_bullets.nim` spawns one bullet per power
bin per gun per tick, so the knowledge gun gets 4 resolutions per tick against
the 1/tick a real shot gives it — the offline table was starved by ~63x.
WHAT IS SIMULATED (mirrors virtual_bullets.nim `bmPath` exactly)
---------------------------------------------------------------
PowerBins = [1.0, 1.5, 2.0, 3.0], bulletSpeed = 20 - 3p
every tick with a live target, per power bin:
aim = production base (forecastLinear, ABSOLUTE world bearing,
gkm.production_base) + residual from the table row
spawn a bullet at the shooter position, direction = aim, speed = v
advance it EVERY tick (spawn-then-tick, as the live bot does: the rack
calls spawnBullets before tickBullets on the same tick)
each tick: swept segment vs the RECORDED enemy position of that tick,
hit iff distPointToSegment(...) < BotRadius (18.0) [bmPath]
resolve ONLY at the wall, exactly once, recording hit or miss
on resolution: table update, crediting the usedBin on a hit
a bullet whose target dies, or that is in flight at a round boundary, is
dropped WITHOUT scoring (bmPath's dead-target branch, and
KnowledgeGun.onRoundBoundary clears `pending`, so a post-boundary feedback
updates nothing — and the corpus records the enemy every tick, so there is
no staleness gap to interpolate)
LEARNING POLICY
---------------
The epsilon-greedy policy is NOT in the shipped `gun_knowledge.nim` (that file
documents "The module itself never invents a random bin"); it is applied here
exactly as specified for this measurement:
row.attempts < --explore-attempts -> with p = --eps pick a UNIFORM
random residual bin, else the argmax. At or above the threshold: argmax.
Every resolution increments row.attempts, and `aim` increments it below the
trust threshold (exactly as the module's `inc gk.globalRows[key].attempts`
does). A shot taken with no residual (usedBin -1) is filed under bin 0, the
0 deg NULL, exactly as `update` does. The trust threshold that gates the
argmax is GK_GLOBAL_MIN_ATTEMPTS = 5 in both `aim` and `update`.
SPLIT: held out BY BATTLE, 2-fold, `run1..run7` = fold 0 and `run8..run14` =
fold 1, identical to measure_gk_residual.py. Every virtual bullet is tested
exactly once (each battle is in exactly one held-out fold).
ARMS
base residual 0, i.e. bare `forecastLinear`, through the same spawn/flight
learn residual from the table, frozen at test time
A tick whose learned residual is 0 has a byte-identical ray, so ONE flight is
simulated and credited to both arms (it IS the same bullet, not an average).
Every band/rms number is measured on the SAME set of held-out ticks.
KEY CONFIGS
full the production 15-bit key: band x space x turn x trend x heat x radial
(gun heat is not in the corpus -> pinned to quarter 0, so this key is
COARSER than in battle, never finer)
dt band x turn — the config that won the real-shot sweep (SWEEP F/J)
"""
from __future__ import annotations
import collections
import glob
import json
import math
import os
import random
import statistics
import sys
import time
from multiprocessing import Process, Pool
# reuse the previous script's PRODUCTION-AIM ports verbatim (one definition of
# forecastLinear / production_base / bandOf / spaceOf / the bin layout)
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
_ARGV = sys.argv
sys.argv = [sys.argv[0]]
import measure_gk_residual as gkm # noqa: E402
sys.argv = _ARGV
ROOT = os.environ.get("GK_CORPUS", "/tmp/tfil_ab2/out")
GK_NBINS = 32
GK_NULL_BIN = 0
GK_MIN_BIN_HITS = 3
GK_GLOBAL_MIN_ATTEMPTS = 5
CENTRE = gkm.CENTRE # bin b -> residual degrees
BOT_RADIUS = 18.0
ARENA_W, ARENA_H = 800.0, 600.0
POWER_BINS = [1.0, 1.5, 2.0, 3.0]
SPEEDS = [20.0 - 3.0 * p for p in POWER_BINS] # 17.0 15.5 14.0 11.0
MAX_FLIGHT = 300
BAND_LAB = gkm.BAND_LAB
N_BAND = len(BAND_LAB)
GK_STRAIGHT, GK_RIGHT, GK_LEFT, GK_UNKNOWN = 0, 1, 2, 3
GK_ACCEL, GK_CONST, GK_DECEL = 0, 1, 2
GK_TURN_DEAD, GK_TREND_DEAD = 2.0, 0.05
VEL_WINDOW, RADIAL_WINDOW = 16, 32
ARM_BASE, ARM_BOTH, ARM_LEARN = 0, 2, 1
def key_of(band, space, turning, trend, rad, arm):
if arm == "full":
return ((((band * 3 + space) * 4 + turning) * 4 + trend) * 4 + 0) * 4 + rad
return band * 4 + turning
def nrows(arm):
return 5 * 3 * 4 * 4 * 4 * 4 if arm == "full" else 5 * 4
def best_residual(row):
"""Port of gun_knowledge.bestResidual: argmax over the bins clearing
GK_MIN_BIN_HITS, tie-broken toward the 0 deg NULL. Returns (deg, bin)."""
if row is None:
return 0.0, -1
best_b, best_h = -1, 0
for b in range(GK_NBINS):
h = row[b]
if h < GK_MIN_BIN_HITS:
continue
if h > best_h or (h == best_h and best_b >= 0 and abs(b) < abs(best_b)):
best_h, best_b = h, b
if best_b < 0:
return 0.0, -1
return CENTRE[best_b], best_b
class Table:
def __init__(self, n):
self.n = n
self.att = [0] * n
self.hits = [None] * n
def row(self, k):
r = self.hits[k]
if r is None:
r = self.hits[k] = [0] * GK_NBINS
return r
def residual(self, k):
"""What `aim` returns for this row: below GK_GLOBAL_MIN_ATTEMPTS the
module returns the NULL residual (it only counts the attempt)."""
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
return 0.0, -1
return best_residual(self.hits[k])
def stats(self):
nz, trusted, s = 0, 0, 0.0
for k in range(self.n):
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
continue
trusted += 1
d, _ = best_residual(self.hits[k])
if d != 0.0:
nz += 1
s += abs(d)
return nz, trusted, (s / nz if nz else 0.0)
# ─────────────────────────────────────────────────────────────────────────────
# corpus
# ─────────────────────────────────────────────────────────────────────────────
_CACHE = {}
def battle_files(root):
out = []
for p in sorted(glob.glob(os.path.join(root, "*", "*.jsonl"))):
if p.endswith(".events.jsonl"):
continue
rj, ev = p + ".rounds.json", p[:-6] + ".events.jsonl"
if not (os.path.exists(rj) and os.path.exists(ev)):
continue
tag = os.path.basename(os.path.dirname(p)) + "/" + os.path.basename(p)[:-6]
out.append(dict(tag=tag, path=p, rj=rj, ev=ev,
fold=0 if int(tag.split("run")[1]) <= 7 else 1))
return out
def load_battle(bf):
rounds = json.load(open(bf["rj"]))["rounds"]
starts = [(r["startTick"], r["startTick"] + r["count"]) for r in rounds]
T, EX, EY, EH, ES, SX, SY, SE, EE = [], [], [], [], [], [], [], [], []
RND = []
r = 0
with open(bf["path"]) as f:
for line in f:
if '"tick"' not in line:
continue
o = json.loads(line)
while r + 1 < len(starts) and o["tick"] >= starts[r + 1][0]:
r += 1
RND.append(r)
T.append(o["tick"])
EX.append(o["ex"]); EY.append(o["ey"])
EH.append(o["eh"]); ES.append(o["es"])
SX.append(o["sx"]); SY.append(o["sy"])
SE.append(o["se"]); EE.append(o["ee"])
return dict(T=T, ex=EX, ey=EY, eh=EH, es=ES, sx=SX, sy=SY, se=SE, ee=EE,
rnd=RND, starts=starts)
def get_battle(bf):
b = _CACHE.get(bf["tag"])
if b is None:
b = _CACHE[bf["tag"]] = load_battle(bf)
return b
def cadence(bfs):
gaps = collections.Counter()
rows = 0
for bf in bfs:
prev = None
for line in open(bf["path"]):
if '"tick"' not in line:
continue
t = json.loads(line)["tick"]
rows += 1
if prev is not None:
gaps[t - prev] += 1
prev = t
return rows, gaps
def real_shots(bfs):
"""US (= the `s*` adversary, ModularBot) fired shots, by the same
energy-drop attribution measure_gk_residual.py uses."""
per_run = {}
for bf in bfs:
b = load_battle(bf)
pos = {t: i for i, t in enumerate(b["T"])}
votes = collections.defaultdict(collections.Counter)
def match(t, side, ev):
i, i1 = pos.get(t), pos.get(t + 1)
if i is None or i1 is None:
return False
if abs(b[side + "x"][i] - ev["x"]) > 0.02 or \
abs(b[side + "y"][i] - ev["y"]) > 0.02:
return False
ef = "ee" if side == "e" else "se"
return abs((b[ef][i] - b[ef][i1]) - ev["power"]) < 0.02
for ev in (json.loads(l) for l in open(bf["ev"]) if l.strip()):
if ev.get("type") != "fire":
continue
g = ev.get("tick", 0)
for t in range(g - 8, g + 9):
for side in ("e", "s"):
if match(t, side, ev):
votes[ev["owner"]][side] += 1
n = 0
for o, c in votes.items():
if c and c.most_common(1)[0][0] == gkm.US_SIDE:
n += sum(c.values())
per_run[bf["tag"]] = n
_CACHE.pop(bf["tag"], None)
return per_run
# ─────────────────────────────────────────────────────────────────────────────
# the replay
# ─────────────────────────────────────────────────────────────────────────────
class Acc:
__slots__ = ("n", "tk", "eb2", "eab", "el2", "eal", "hb", "nb", "hl", "nl",
"hd", "hbp", "hlp", "cov", "res")
def __init__(self):
for s in self.__slots__:
setattr(self, s, 0.0)
def add(self, o):
for s in self.__slots__:
setattr(self, s, getattr(self, s) + getattr(o, s))
def as_dict(self):
return {s: getattr(self, s) for s in self.__slots__}
def replay(b, arm, table, learn, thr, eps, rng, test):
"""One battle. learn=True: training replay (learns, scores nothing).
test=True: held-out replay, table frozen, base and learn flown side by side.
Returns (per-band Acc list, counters)."""
T, EX, EY, EH, ES = b["T"], b["ex"], b["ey"], b["eh"], b["es"]
SX, SY, SE, EE = b["sx"], b["sy"], b["se"], b["ee"]
rnd, starts = b["rnd"], b["starts"]
n = len(T)
acc = [Acc() for _ in range(N_BAND)]
c = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0)
a_fx, a_fy, a_ux, a_uy, a_tr, a_sp = [], [], [], [], [], []
a_hit, a_key, a_bn, a_arm, a_bd, a_pi = [], [], [], [], [], []
bh = [0.0] * (n + 1) # per spawn tick: did the BASE flight hit?
prev_t = -10
rr = -1
prev_ex = prev_ey = prev_eh = prev_es = 0.0
has_prev = False
rad_ring = [0.0] * VEL_WINDOW
rad_head = rad_count = 0
fB, band_of = gkm.production_base, gkm.band_of
space_of, wrap180 = gkm.space_of, gkm.wrap180
atan2d = math.degrees
R2 = BOT_RADIUS * BOT_RADIUS
for j in range(n):
t = T[j]
if rnd[j] != rr or t != prev_t + 1:
if a_fx:
c["round"] += len(a_fx)
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
rr = rnd[j]
has_prev = False
rad_count = rad_head = 0
prev_t = t
ex, ey, eh, es = EX[j], EY[j], EH[j], ES[j]
sx, sy = SX[j], SY[j]
e_alive = EE[j] > 0.0
s_alive = SE[j] > 0.0
end = starts[rr][1] if rr >= 0 else t
if e_alive and s_alive:
dx, dy = ex - sx, ey - sy
dist = math.sqrt(dx * dx + dy * dy)
if dist > 1e-6:
c["ticks"] += 1
if has_prev:
rate = wrap180(eh - prev_eh)
turning = GK_LEFT if rate > GK_TURN_DEAD else (
GK_RIGHT if rate < -GK_TURN_DEAD else GK_STRAIGHT)
dv = es - prev_es
trend = GK_ACCEL if dv > GK_TREND_DEAD else (
GK_DECEL if dv < -GK_TREND_DEAD else GK_CONST)
ddx, ddy = ex - prev_ex, ey - prev_ey
spd = math.sqrt(ddx * ddx + ddy * ddy)
frac = 0.0
if spd > 0.1:
frac = abs((ddx * (sx - ex) + ddy * (sy - ey)) / dist) / spd
rad_ring[rad_head] = frac
rad_head = (rad_head + 1) % VEL_WINDOW
if rad_count < VEL_WINDOW:
rad_count += 1
else:
turning = trend = GK_UNKNOWN
prev_ex, prev_ey, prev_eh, prev_es = ex, ey, eh, es
has_prev = True
rf = 0.0
if rad_count:
nn = min(RADIAL_WINDOW, rad_count)
s = 0.0
for i in range(nn):
s += rad_ring[(rad_head - 1 - i) % VEL_WINDOW]
rf = s / nn
band = band_of(dist)
sp = space_of(ex, ey, sx, sy)
rad = 0 if rf < 0.25 else 1 if rf < 0.5 else 2 if rf < 0.75 else 3
k = key_of(band, sp, turning, trend, rad, arm)
# ---- what aim() applies this tick ----
if learn:
if table.att[k] < thr:
res, ub = 0.0, -1
table.att[k] += 1
if eps > 0.0 and rng.random() < eps:
ub = rng.randrange(GK_NBINS)
res = CENTRE[ub]
c["explore"] += 1
else:
res, ub = best_residual(table.hits[k])
else:
res, ub = table.residual(k)
if test:
A = acc[band]
A.tk += 1
A.cov += 1.0 if res != 0.0 else 0.0
A.res += abs(res)
los = atan2d(math.atan2(dy, dx))
for bi in range(4):
A.n += 1
v = SPEEDS[bi]
kk = 1
kst = -1
while kk <= MAX_FLIGHT and t + kk < end and j + kk < n \
and T[j + kk] == t + kk:
qx = EX[j + kk] - sx
qy = EY[j + kk] - sy
if math.sqrt(qx * qx + qy * qy) <= v * kk:
kst = kk
break
kk += 1
if kst < 0:
c["skip"] += 1
continue
req = wrap180(atan2d(math.atan2(EY[j + kst] - sy,
EX[j + kst] - sx)) - los)
bl = wrap180(fB(ex, ey, eh, es, sx, sy, v) - los)
eb = wrap180(bl - req)
el = wrap180(bl + res - req)
A.eb2 += eb * eb
A.eab += abs(eb)
A.el2 += el * el
A.eal += abs(el)
# ---- spawnBullets ----
for bi in range(4):
v = SPEEDS[bi]
bse = fB(ex, ey, eh, es, sx, sy, v)
a_fx.append(sx); a_fy.append(sy)
a_tr.append(0.0); a_sp.append(v)
a_hit.append(False); a_key.append(k); a_bn.append(ub)
a_bd.append(band); a_pi.append(j)
a_ux.append(math.cos(math.radians(bse)))
a_uy.append(math.sin(math.radians(bse)))
if res != 0.0:
a_arm.append(ARM_BASE)
c["split"] += 1
a_fx.append(sx); a_fy.append(sy)
a_tr.append(0.0); a_sp.append(v)
a_hit.append(False); a_key.append(k); a_bn.append(ub)
a_bd.append(band); a_pi.append(j)
a_ux.append(math.cos(math.radians(bse + res)))
a_uy.append(math.sin(math.radians(bse + res)))
a_arm.append(ARM_LEARN)
else:
a_arm.append(ARM_BOTH)
c["shared"] += 1
# ---- tickBullets: advance every bullet one tick ----
if a_fx:
if not e_alive:
c["dead"] += len(a_fx)
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
else:
w = 0
for i in range(len(a_fx)):
sp = a_sp[i]
tr = a_tr[i] + sp
fx, fy = a_fx[i], a_fy[i]
ux, uy = a_ux[i], a_uy[i]
ddx = ex - fx
ddy = ey - fy
along = ux * ddx + uy * ddy
perp = -uy * ddx + ux * ddy
hit = a_hit[i]
if not hit and perp * perp < R2:
prev_d = tr - sp
if along > prev_d - BOT_RADIUS and along < tr + BOT_RADIUS:
seg = along - (prev_d if along < prev_d else
(tr if along > tr else along))
if seg * seg + perp * perp < R2:
hit = True
bx = fx + ux * tr
by = fy + uy * tr
if bx < 0.0 or bx > ARENA_W or by < 0.0 or by > ARENA_H:
c["resolved"] += 1
if learn:
k = a_key[i]
table.att[k] += 1
if hit:
b = a_bn[i]
table.row(k)[b if b >= 0 else GK_NULL_BIN] += 1
c["learn_hits"] += 1
else:
A = acc[a_bd[i]]
am = a_arm[i]
hv = 1.0 if hit else 0.0
if am == ARM_LEARN:
A.nl += 1
A.hl += hv
# PAIRED: the baseline flight for THIS spawn tick
A.hd += 1
A.hbp += bh[a_pi[i]]
A.hlp += hv
elif am == ARM_BOTH:
A.nb += 1; A.hb += hv
A.nl += 1; A.hl += hv
bh[a_pi[i]] = hv
else:
A.nb += 1; A.hb += hv
bh[a_pi[i]] = hv
continue
a_fx[w] = fx; a_fy[w] = fy; a_ux[w] = ux; a_uy[w] = uy
a_tr[w] = tr; a_sp[w] = sp; a_hit[w] = hit
a_key[w] = a_key[i]; a_bn[w] = a_bn[i]; a_arm[w] = a_arm[i]
a_bd[w] = a_bd[i]; a_pi[w] = a_pi[i]
w += 1
del a_fx[w:]; del a_fy[w:]; del a_ux[w:]; del a_uy[w:]
del a_tr[w:]; del a_sp[w:]; del a_hit[w:]
del a_key[w:]; del a_bn[w:]; del a_arm[w:]; del a_bd[w:]
del a_pi[w:]
c["inflight"] = len(a_fx)
return acc, c
# ─────────────────────────────────────────────────────────────────────────────
# driver
# ─────────────────────────────────────────────────────────────────────────────
_G = {}
def _test_one(bf):
b = get_battle(bf)
acc, c = replay(b, _G["arm"], _G["table"], False, 0, 0.0, None, True)
return bf["tag"], [a.as_dict() for a in acc], c
def run_config(arm, thr, eps, bfs, outdir):
t0 = time.time()
res = dict(arm=arm, thr=thr, eps=eps, folds=[])
for fold in (0, 1):
table = Table(nrows(arm))
rng = random.Random(1234 + fold)
ctr = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
ticks=0, explore=0, learn_hits=0, inflight=0)
for bf in bfs: # TRAINING: sequential, table evolves
if bf["fold"] == fold:
continue
_, c = replay(get_battle(bf), arm, table, True, thr, eps, rng, False)
for k in ctr:
ctr[k] += c[k]
nz, trusted, mean_abs = table.stats()
_G["arm"], _G["table"] = arm, table
with Pool(4) as pool: # TEST: frozen table, battles parallel
out = pool.map(_test_one, [bf for bf in bfs if bf["fold"] != fold])
pooled = [Acc() for _ in range(N_BAND)]
ctest = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
ticks=0, explore=0, learn_hits=0, inflight=0)
battles = []
for tag, bands, c in out:
A = []
for a in bands:
A.append(_mk(a))
pooled[len(A) - 1].add(A[-1])
for k in ctest:
ctest[k] += c[k]
tb = Acc()
for a in A:
tb.add(a)
battles.append(dict(tag=tag, n=tb.n, tk=tb.tk, eb2=tb.eb2, el2=tb.el2,
nb=tb.nb, hb=tb.hb, nl=tb.nl, hl=tb.hl,
hd=tb.hd, hbp=tb.hbp, hlp=tb.hlp,
cov=tb.cov, res=tb.res))
res["folds"].append(dict(fold=fold, nz=nz, trusted=trusted,
mean_abs=mean_abs, train=ctr, test=ctest,
bands=[a.as_dict() for a in pooled],
battles=battles))
_G.clear()
json.dump(res, open(os.path.join(outdir, "gk_%s_%d.json" % (arm, thr)), "w"))
return time.time() - t0
def rms(x):
return math.sqrt(x) if x >= 0 else float("nan")
def mean_sd(xs):
if len(xs) < 2:
return 0.0, 0.0
m = statistics.fmean(xs)
return m, math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1))
def report(cfg_path, real_n, rows, gaps, bfs):
r = json.load(open(cfg_path))
print("=" * 100)
print("CONFIG key=%s explore-attempts=%d eps=%.2f" % (r["arm"], r["thr"], r["eps"]))
tt = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0, inflight=0)
cte = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0, inflight=0)
for f in r["folds"]:
for k in tt:
tt[k] += f["train"][k]
cte[k] += f["test"][k]
ntr = len(bfs) // 2 * 2
print(" TRAINING (the %d held-in battles of each of the 2 folds, replayed"
" sequentially, table rebuilt per fold):" % (ntr // 2))
print(" virtual bullets spawned %d resolved %d in flight at battle end %d"
% (4 * tt["ticks"] + tt["split"], tt["resolved"], tt["inflight"]))
print(" dropped unscored: target dead %d, round boundary %d of which the"
" two arms flew ONE identical ray: %d" % (tt["dead"], tt["round"], tt["shared"]))
print(" resolutions credited as HITS: %d epsilon-greedy draws: %d"
% (tt["learn_hits"], tt["explore"]))
tot = [Acc() for _ in range(N_BAND)]
bl = []
for f in r["folds"]:
for i, a in enumerate(f["bands"]):
tot[i].add(_mk(a))
bl += f["battles"]
for f in r["folds"]:
print(" fold %d: rows above the trust threshold %d, with a NON-ZERO"
" argmax %d, mean |residual| of those %+.2f deg"
% (f["fold"], f["trusted"], f["nz"], f["mean_abs"]))
ntest = sum(b["tk"] for b in bl)
nvb = sum(b["nb"] for b in bl)
nvl = sum(b["nl"] for b in bl)
cov = sum(b["cov"] for b in bl)
rr = sum(b["res"] for b in bl)
print(" HELD-OUT (2-fold by battle, both folds pooled, every bullet tested once):")
print(" virtual bullets TESTED: base arm %d, learned arm %d"
" (%.1fx the %d real fired shots)" % (nvb, nvl, nvl / max(real_n, 1), real_n))
print(" held-out target ticks (both bots alive): %d x4 power bins = %d aim"
" decisions skipped (no interception before the round end): %d"
% (ntest, int(sum(a.n for a in tot)), cte["skip"]))
print(" held-out ticks carrying a NON-ZERO residual: %d (%.2f%%) mean"
" |residual| applied %.3f deg"
% (int(cov), 100.0 * cov / max(ntest, 1), rr / max(ntest, 1)))
print(" %-8s %9s %8s %8s %8s | %8s %8s %8s %8s | %10s"
% ("band", "aims", "rms_b", "mabs_b", "hit_b%", "rms_l", "mabs_l",
"hit_l%", "dhit_pp", "paired_n"))
for i, lab in enumerate(BAND_LAB):
a = tot[i]
if a.n <= 0:
continue
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
% (lab, int(a.n), rms(a.eb2 / a.n), a.eab / a.n, 100.0 * a.hb / max(a.nb, 1),
rms(a.el2 / a.n), a.eal / a.n, 100.0 * a.hl / max(a.nl, 1),
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
a = Acc()
for x in tot:
a.add(x)
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
% ("ALL", int(a.n), rms(a.eb2 / a.n), a.eab / a.n,
100.0 * a.hb / max(a.nb, 1), rms(a.el2 / a.n), a.eal / a.n,
100.0 * a.hl / max(a.nl, 1),
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
print(" PAIRED (only the ticks where the two arms flew DIFFERENT rays):"
" base %d/%d hit, learned %d/%d hit -> %+.3f pp"
% (int(a.hbp), int(a.hd), int(a.hlp), int(a.hd),
100.0 * (a.hlp - a.hbp) / max(a.hd, 1)))
# clustered, per-battle paired statistics
dh, de = [], []
for b in bl:
if b["hd"]:
dh.append((b["hlp"] - b["hbp"]) / b["hd"])
if b["n"]:
de.append((b["el2"] - b["eb2"]) / b["n"])
mh, sh = mean_sd(dh)
me, se = mean_sd(de)
th = mh / (sh / math.sqrt(len(dh))) if sh > 0 else 0.0
te = me / (se / math.sqrt(len(de))) if se > 0 else 0.0
print(" CLUSTERED by battle (%d battles): dHit %+0.3f pp (sd %0.3f, t=%+.2f)"
" dMeanSqErr %+8.2f deg2 (sd %8.2f, t=%+.2f)"
% (len(dh), 100 * mh, 100 * sh, th, me, se, te))
return r
def _mk(d):
a = Acc()
for s in Acc.__slots__:
setattr(a, s, d[s])
return a
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--root", default=ROOT)
ap.add_argument("--arms", default="full,dt")
ap.add_argument("--thresholds", default="5,100")
ap.add_argument("--eps", type=float, default=0.25)
ap.add_argument("--limit", type=int, default=0, help="first N battles (smoke)")
ap.add_argument("--out", default="/tmp/gk_virtual")
a = ap.parse_args()
bfs = battle_files(a.root)
if a.limit:
bfs = bfs[:a.limit]
if not bfs:
print("NO CORPUS at %s" % a.root)
return 1
os.makedirs(a.out, exist_ok=True)
rows, gaps = cadence(bfs)
real = real_shots(bfs)
real_n = sum(real.values())
print("CORPUS %s" % a.root)
print(" battles: %d worldstate rows: %d" % (len(bfs), rows))
print(" TICK CADENCE: inter-row deltas %s"
% (dict(gaps) if gaps else "none (one row per tick, contiguous)"))
print(" -> NO interpolation needed: every tick is recorded, so a virtual"
" bullet's swept segment is tested against the enemy position of that"
" exact tick.")
print(" REAL fired shots by the US bot (energy-drop attribution): %d"
% real_n)
print(" power bins %s -> bullet speeds %s ; BotRadius %.1f ; arena %.0fx%.0f"
% (POWER_BINS, SPEEDS, BOT_RADIUS, ARENA_W, ARENA_H))
print()
arms = a.arms.split(",")
thrs = [int(x) for x in a.thresholds.split(",")]
procs = []
for arm in arms:
for thr in thrs:
p = Process(target=run_config,
args=(arm, thr, a.eps, bfs, a.out))
p.start()
procs.append(p)
for p in procs:
p.join()
if p.exitcode:
print("!! a config process exited %d" % p.exitcode)
print()
for arm in arms:
for thr in thrs:
f = os.path.join(a.out, "gk_%s_%d.json" % (arm, thr))
if os.path.exists(f):
report(f, real_n, rows, gaps, bfs)
return 0
if __name__ == "__main__":
sys.exit(main())
+227
View File
@@ -0,0 +1,227 @@
## Unit tests for the online sequential ELM (common_libs/guns/elm.nim).
##
## Covers what the guns actually rely on: fitting a known function, streaming
## convergence, the forgetting factor tracking a drifting target, the
## NaN/Inf guards, and seed reproducibility.
##
## Run: nim c -r common_libs/tests/test_elm.nim
import std/[math, random, strformat]
import guns/elm
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 rmse(net: ElmNet, samples: seq[tuple[x: seq[float], t: seq[float]]]): float =
## Prediction RMSE over a held-out sample set (net used read-only).
var s = 0.0
for smp in samples:
let p = net.predict(smp.x)
for o in 0..<net.outputDim: s += (p[o] - smp.t[o]) ^ 2
sqrt(s / (samples.len.float * net.outputDim.float))
# ── 1. linear fit y = 2x + 1, noisy ──────────────────────────────────────────
proc testLinearFit() =
block:
let n = 400
var rng = initRand(7)
var net = init(inputDim = 1, hiddenDim = 12, seed = 42)
for i in 0..<n:
let x = @[rand(rng, 1.0) * 2.0 - 1.0]
let t = @[2.0 * x[0] + 1.0 + (rand(rng, 1.0) * 2.0 - 1.0) * 0.02]
discard net.train(x, t)
var grid: seq[tuple[x: seq[float], t: seq[float]]] = @[]
for i in 0..<100:
let x = @[-1.0 + 2.0 * float(i) / 100.0]
grid.add((x: x, t: @[2.0 * x[0] + 1.0]))
let e = rmse(net, grid)
echo &" linear y=2x+1: grid RMSE = {e:.5f}"
check "linear: RMSE on [-1,1] grid < 0.05", e < 0.05
# ── 2. 2D input -> 2D output ───────────────────────────────────────────────
block:
let n = 600
var rng = initRand(11)
var net = init(inputDim = 2, hiddenDim = 20, seed = 7, outputDim = 2)
proc target(x: openArray[float]): seq[float] =
@[x[0] + 0.5 * x[1] - 1.0, -0.3 * x[0] + 2.0 * x[1] + 0.25]
for i in 0..<n:
let x = @[rand(rng, 1.0) * 2.0 - 1.0, rand(rng, 1.0) * 2.0 - 1.0]
var t = target(x)
for o in 0..<1:
t[o] += (rand(rng, 1.0) * 2.0 - 1.0) * 0.01
discard net.train(x, t)
var grid: seq[tuple[x: seq[float], t: seq[float]]] = @[]
for i in 0..<60:
let x = @[-1.0 + 2.0 * float(i) / 60.0, 1.0 - 2.0 * float(i) / 60.0]
grid.add((x: x, t: target(x)))
let e = rmse(net, grid)
echo &" 2D->2D: grid RMSE = {e:.5f}"
check "2D->2D: RMSE < 0.05", e < 0.05
# ── 3. online / streaming convergence ────────────────────────────────────────
proc testStreaming() =
## RLS is prequential: every sample is predicted once, then trained on. The
## net converges in a handful of samples (that is the point of RLS), so the
## trend has to be measured against the FIRST samples, not the first 100.
var rng = initRand(3)
var net = init(inputDim = 1, hiddenDim = 16, seed = 99)
var firstErr = 0.0
var headErr = 0.0
var tailErr = 0.0
var worstTail = 0.0
for i in 0..<600:
let x = @[rand(rng, 1.0) * 2.0 - 1.0]
let t = @[2.0 * x[0] + 1.0]
if i == 0: firstErr = (net.predict(x)[0] - t[0]) ^ 2 # untrained: predicts 0
discard net.train(x, t)
let err = (net.predict(x)[0] - t[0]) ^ 2
if i < 5:
headErr += err
elif i >= 500:
tailErr += err
worstTail = max(worstTail, err)
headErr /= 5.0
tailErr /= 100.0
echo &" streaming: 1st sample MSE = {firstErr:.6f}, first-5 MSE = {headErr:.6f}, " &
&"last-100 MSE = {tailErr:.6f}"
check "streaming: last-100 MSE << first-sample MSE (>=100x better)",
tailErr < firstErr / 100.0
check "streaming: running error keeps trending down (last-100 <= first-5)",
tailErr <= headErr
# Floor: ~2e-6 MSE is the lambda = 1e-3 ridge bias, not a learning failure.
check "streaming: last-100 MSE < 1e-4", tailErr < 1e-4
check "streaming: no single late sample worse than 100x the last-100 mean",
worstTail < tailErr * 100.0
# ── 4. forgetting factor tracks a drifting target ────────────────────────────
proc testForgetting() =
block:
## Target jumps sign/slope halfway through. Two numbers per net: the mean
## RMSE over all post-jump samples (transient included) and the tail RMSE
## (adaptation quality once it has settled). rho = 1 averages the whole
## history and never leaves the old function; rho > 1 must track.
let n = 800
proc drift(net: var ElmNet): tuple[mean, tail: float] =
var re = initRand(1)
var e2 = 0.0
var eTail = 0.0
for i in 0..<n:
let x = @[rand(re, 1.0) * 2.0 - 1.0]
let t = @[if i < n div 2: 2.0 * x[0] + 1.0 else: -1.5 * x[0] + 0.5]
discard net.train(x, t)
if i >= n div 2:
let e = (net.predict(x)[0] - t[0]) ^ 2
e2 += e
if i >= n - 200: eTail += e
(sqrt(e2 / float(n div 2)), sqrt(eTail / 200.0))
var plain = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.0)
var forget = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.02)
let ePlain = drift(plain)
let eForget = drift(forget)
echo &" drifting target, post-jump mean RMSE: rho=1.0 -> {ePlain.mean:.5f}, " &
&"rho=1.02 -> {eForget.mean:.5f}"
echo &" drifting target, post-jump TAIL RMSE: rho=1.0 -> {ePlain.tail:.5f}, " &
&"rho=1.02 -> {eForget.tail:.5f}"
check "forgetting: rho=1.02 halves the mean post-jump RMSE on a drifting target",
eForget.mean < ePlain.mean * 0.5
check "forgetting: rho=1.02 tracks the new target (tail RMSE >=20x better)",
eForget.tail < ePlain.tail / 20.0
check "forgetting: rho=1.02 settles on the new target (tail RMSE < 0.05)",
eForget.tail < 0.05
# ── 5. numerical guards ──────────────────────────────────────────────────────
proc testGuards() =
block:
var net = init(inputDim = 1, hiddenDim = 8, seed = 42)
for i in 0..<200:
let x = @[float(i) / 200.0 - 0.5]
discard net.train(x, @[2.0 * x[0]])
check "guards: net is sane after 200 clean updates", net.isSane()
# a NaN sample must be rejected without poisoning the net
let rejected = net.train(@[0.5], @[NaN])
check "guards: NaN target is rejected", not rejected
check "guards: net still sane after a rejected NaN sample", net.isSane()
check "guards: NaN input is rejected", not net.train(@[Inf], @[1.0])
check "guards: net still sane after Inf input", net.isSane()
# many updates with an extreme input: prediction must stay finite
var wild = init(inputDim = 1, hiddenDim = 8, seed = 42, rho = 1.01)
for i in 0..<5000:
let x = @[sin(float(i)) * 1e6]
discard wild.train(x, @[x[0]])
let p = wild.predict(x)
if p[0].classify in {fcNan, fcInf, fcNegInf}:
check "guards: prediction stays finite over 5000 wild updates", false
return
check "guards: prediction stays finite over 5000 wild updates",
classify(wild.predict(@[1.0])[0]) notin {fcNan, fcInf, fcNegInf}
# poisoned state is detected and reset away from
var broken = init(inputDim = 1, hiddenDim = 4, seed = 42)
discard broken.train(@[0.5], @[1.0])
broken.beta[0][0] = NaN
check "guards: isSane detects a poisoned beta", not broken.isSane()
check "guards: predict returns zeros instead of NaN",
broken.predict(@[0.5]) == @[0.0]
discard broken.train(@[0.5], @[1.0])
check "guards: training a poisoned net soft-resets it", broken.isSane() and
broken.resets > 0 and broken.samples == 1
broken.softReset()
check "guards: explicit softReset zeroes beta and P",
broken.samples == 0 and broken.beta[0][0] == 0.0 and
broken.P[0][0] == 1.0 / broken.lambda
# ── 6. seed reproducibility ──────────────────────────────────────────────────
proc testReproducible() =
block:
var a = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2)
var b = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2)
var c = init(inputDim = 2, hiddenDim = 12, seed = 4321, outputDim = 2)
var rng = initRand(17)
for i in 0..<50:
let x = @[rand(rng, 1.0), rand(rng, 1.0)]
let t = @[x[0] - x[1], 2.0 * x[0] + 3.0 * x[1]]
discard a.train(x, t)
discard b.train(x, t)
discard c.train(x, t)
let q = @[0.3, -0.7]
check "seed: same seed => identical predictions", a.predict(q) == b.predict(q)
check "seed: different seed => different predictions", a.predict(q) != c.predict(q)
check "activation: sigmoid option is actually used",
init(1, 12, seed = 1, act = eaSigmoid).act == eaSigmoid
var sg = init(inputDim = 1, hiddenDim = 12, seed = 1, act = eaSigmoid)
for i in 0..<300:
let x = @[float(i) / 300.0 - 0.5]
discard sg.train(x, @[2.0 * x[0]])
check "activation: sigmoid ELM also fits y=2x (RMSE < 0.05)",
rmse(sg, @[(x: @[-0.5], t: @[-1.0]), (x: @[0.5], t: @[1.0])]) < 0.05
proc main() =
echo "── linear fit ──"; testLinearFit()
echo "── streaming convergence ──"; testStreaming()
echo "── forgetting factor ──"; testForgetting()
echo "── numerical guards ──"; testGuards()
echo "── reproducibility ──"; testReproducible()
echo ""
if failures > 0:
echo &"{failures}/{checks} check(s) FAILED"
quit(1)
echo &"All {checks} ELM checks passed."
when isMainModule:
main()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,325 @@
## Registration guard for the KNOWLEDGE gun (rack id 17), the learned additive
## angular residual on top of the self-consistent lead forecast
## (`common_libs/guns/gun_knowledge.nim`).
##
## Mirrors `test_lead_gain_registration.nim`: no Java, no battle, no network
## build. Covers:
## * KNOWLEDGE is APPENDED at id 17 and every pre-existing id is byte-identical
## (a rack gun that renumbered would silently re-address every
## `tools/ab/arms_*.txt` config and every `gun_stats.jsonl` column);
## * it defaults to `off`, so the shipped rack still admits exactly Pattern;
## * `TR_RACK_KNOWLEDGE=...` is what admits it, in 1v1 and in melee, and the
## live `vBulletAdmitted` spawn gate honours the membership;
## * `initKnowledgeGun()` is LAZY (0 bytes before first use) and the whole
# aim+update path, EXPLORATION included, does NOT touch the global RNG, so
## a rack that admits it cannot perturb the selector's `rand` stream;
## * the gun implements the rack `Gun` concept, learns from its own feedback
## into the exact row that produced the angle, keeps its counts across a
## round boundary and persists them atomically.
##
## Run: nim c -r --path:common_libs common_libs/tests/test_knowledge_registration.nim
import std/[math, os, random, strutils, tables]
import gun_harness/virtual_bullets
import gun_harness/selector
import gun_harness/gun_interface
import guns/gun_knowledge
const
KnowledgeId = 17
PatternId = 5
LeadGainId = 16
## The rack as it was BEFORE this gun was appended. Pinned literal-by-literal:
## if a future edit shifts an id, this fails here instead of in a live battle.
PreRack = ["HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN",
"WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF",
"KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN"]
var failures = 0
proc check(name: string, ok: bool) =
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc clearRackEnv() =
for name in RackGunNames: delEnv("TR_RACK_" & name)
proc wsFor(tick: int, ex, ey, es, eh: float): WorldState =
WorldState(enemyX: ex, enemyY: ey, enemySpeed: es, enemyHeading: eh,
selfX: 0.0, selfY: 0.0, selfHeading: 0.0,
arenaWidth: 800.0, arenaHeight: 600.0, tick: tick)
# ── the rack table ───────────────────────────────────────────────────────────
proc testTable() =
check "rack: KNOWLEDGE is registered at id 17", RackGunNames[KnowledgeId] == "KNOWLEDGE"
check "rack: NumRackGuns grew to 18", NumRackGuns >= 18 and
RackGunNames.len == NumRackGuns
check "rack: KNOWLEDGE defaults to `off`", DefaultRackMembership[KnowledgeId] == rmOff
check "rack: the membership table has one entry per gun",
DefaultRackMembership.len == NumRackGuns
# No existing id moved, and no existing name changed. (`>` not `==`: guns
# appended AFTER KNOWLEDGE, e.g. WAVEELM at 18, do not move anything.)
var untouched = RackGunNames.len > PreRack.len
for i in 0 ..< PreRack.len:
if RackGunNames[i] != PreRack[i]: untouched = false
check "rack: every pre-existing id kept its name (KNOWLEDGE appended at the end)", untouched
var seen = initTable[string, bool]()
var allDistinct = true
for n in RackGunNames:
if n in seen: allDistinct = false
seen[n] = true
check "rack: all rack gun names are distinct", allDistinct
# Id 17 was free: no shipped gun occupied it. (It is the id the RETIRED ADE+SBC
# BITBRAIN gun briefly had; nothing addresses it any more — `TR_RACK_BITBRAIN`
# is LEADGAIN's legacy alias, pinned by test_lead_gain_legacy.nim.)
check "rack: KNOWLEDGE's id is in range for every per-gun table",
KnowledgeId < NumRackGuns
var onlyPattern = true
for i in 0..<RackGunNames.len:
let want = if i == PatternId: rmBoth else: rmOff
if DefaultRackMembership[i] != want: onlyPattern = false
check "rack: the shipped default is still the onlyPattern rack", onlyPattern
check "rack: the default rack admits only Pattern (1v1)",
admittedGuns(NumRackGuns, rm1v1, DefaultRackMembership) == @[PatternId]
check "rack: the default rack admits only Pattern (melee)",
admittedGuns(NumRackGuns, rmMelee, DefaultRackMembership) == @[PatternId]
check "gate: KNOWLEDGE is NOT spawned under the default rack",
not vBulletAdmitted(KnowledgeId, rm1v1, DefaultRackMembership, true)
check "gate: LEADGAIN is still NOT spawned under the default rack (no regression)",
not vBulletAdmitted(LeadGainId, rm1v1, DefaultRackMembership, true)
# ── the env override, per membership semantics ───────────────────────────────
proc testEnvOverride() =
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "both")
let m = loadRackMembership()
check "env: TR_RACK_KNOWLEDGE=both admits KNOWLEDGE",
m[KnowledgeId] == rmBoth and
vBulletAdmitted(KnowledgeId, rm1v1, m, true) and
vBulletAdmitted(KnowledgeId, rmMelee, m, true)
check "env: admitting KNOWLEDGE leaves Pattern as the only other member",
admittedGuns(NumRackGuns, rm1v1, m) == @[PatternId, KnowledgeId]
check "env: the legacy alias still selects LEADGAIN, not KNOWLEDGE",
m[LeadGainId] == rmOff
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "1v1")
let m1 = loadRackMembership()
check "env: =1v1 admits it in 1v1 only",
vBulletAdmitted(KnowledgeId, rm1v1, m1, true) and
not vBulletAdmitted(KnowledgeId, rmMelee, m1, true)
check "env: =1v1 leaves the melee rack as Pattern alone",
admittedGuns(NumRackGuns, rmMelee, m1) == @[PatternId]
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "melee")
let mM = loadRackMembership()
check "env: =melee admits it in melee only",
vBulletAdmitted(KnowledgeId, rmMelee, mM, true) and
not vBulletAdmitted(KnowledgeId, rm1v1, mM, true)
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "off")
let mOff = loadRackMembership()
check "env: =off is still the shipped behaviour",
mOff[KnowledgeId] == rmOff and
not vBulletAdmitted(KnowledgeId, rm1v1, mOff, true)
clearRackEnv()
# The gate's `admitOnly=false` escape hatch keeps every gun spawning.
check "gate: TR_VBULLET_ADMIT_ONLY=0 spawns KNOWLEDGE even when off",
vBulletAdmitted(KnowledgeId, rm1v1, DefaultRackMembership, false)
# ── lazy init and the global-RNG contract ────────────────────────────────────
proc testLazyAndRngClean() =
delEnv(GK_MEM_ENV)
var g = initKnowledgeGun()
check "lazy: constructing the gun does NOT build the 3840-row table (0 bytes)",
g.networkBytes == 0
check "lazy: unset TR_KNOWLEDGE_MEM is memory-only (no disk path)",
g.memPath.len == 0
check "lazy: the gun is a `Gun` (predict + onResult, the rack concept)",
isGun(KnowledgeGun)
var warm = initKnowledgeGun()
let ws = WorldState(enemyX: 300.0, enemyY: 200.0, enemySpeed: 3.0,
enemyHeading: 180.0, selfX: 0.0, selfY: 0.0,
selfHeading: 0.0, arenaWidth: 800.0, arenaHeight: 600.0,
tick: 1)
discard warm.predict(ws, bulletSpeed(1.0))
check "lazy: the table exists after the first predict",
warm.networkBytes == GK_NKEYS * sizeof(GkRow)
# Global RNG parity: constructing the gun must not consume global randomness.
# The 3840-row table is a plain `newSeq`/`initTable`; nothing in the module's
# init path draws, so the selector's `rand` stream is untouched.
randomize(1234)
let a = rand(1_000_000)
randomize(1234)
var g2 = initKnowledgeGun()
discard g2.networkBytes
let b = rand(1_000_000)
check "parity: initKnowledgeGun() does not perturb the global RNG", a == b
# ...and neither does the first USE of the table (the allocation + the first
# forecast), which is the moment a random draw would be most tempting.
randomize(1234)
let c = rand(1_000_000)
randomize(1234)
var g3 = initKnowledgeGun()
for t in 0 .. 5:
discard g3.predict(wsFor(t, 300.0 - 5.0 * t.float, 200.0, 3.0,
180.0 + 4.0 * t.float), bulletSpeed(1.0))
let d = rand(1_000_000)
check "parity: using the table does not perturb the global RNG either", c == d
# ...and EXPLORATION draws, but from the module's OWN LCG state
# (`GunKnowledge.rng`), never from the global one. The learner probes a
# uniform residual bin on an under-sampled row, so this is the check that
# actually covers the draw, over a whole learn/resolve loop.
randomize(1234)
let e = rand(1_000_000)
randomize(1234)
var g4 = initKnowledgeGun()
g4.targetId = 3
var explored = false
for t in 0 ..< 40:
let fired = g4.predict(wsFor(t, 300.0 - 4.0 * t.float, 200.0, 3.0,
180.0 + 3.0 * t.float),
bulletSpeed(PowerBins[0]))
g4.onResult(FeedbackEvent(prediction: fired, bulletPower: PowerBins[0],
fireTick: t, powerBin: 0, missDistance: 4.0,
hit: t mod 3 == 0, confidence: fired.confidence))
if g4.pending[0].usedBin != -1: explored = true
let h = rand(1_000_000)
check "parity: exploration (40 predict+onResult) does not touch global rand",
e == h
check "parity: that loop really did explore a non-null residual bin",
explored
# ── the gun learns, and the learning lands on the row that produced the angle ──
proc testLearning() =
delEnv(GK_MEM_ENV)
var g = initKnowledgeGun()
g.targetId = 3 # the caller names the opponent
check "learn: an unarmed gun still returns an aim point",
g.predict(wsFor(0, 300.0, 200.0, 3.0, 0.0), bulletSpeed(1.0)).x != 0.0
check "learn: the confidence carries the gkUnknown rate (0.0 = no data yet)",
g.unknownRate == 0.0
# Two ticks, so the track has a pair and the turn/trend features are known.
discard g.predict(wsFor(1, 297.0, 200.0, 3.0, 0.0), bulletSpeed(1.0))
check "learn: the gkUnknown rate is exposed for a live battle",
g.unknownRate >= 0.0 and g.unknownRate <= 1.0
# Fire the virtual bullet the way the harness does, and resolve it as a HIT.
# The row that produced the angle must be the row that learns.
let fired = g.predict(wsFor(2, 294.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0]))
g.onResult(FeedbackEvent(prediction: fired, bulletPower: PowerBins[0],
fireTick: 2, powerBin: 0, missDistance: 4.0,
hit: true, confidence: fired.confidence))
check "learn: onResult wrote an attempt into the table",
g.gk.featureCount > 0 and g.gk.unknownCount <= g.gk.featureCount
# A MISS resolving the same tick/bucket adds a second attempt and no hit.
let fired2 = g.predict(wsFor(3, 291.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0]))
g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0],
fireTick: 3, powerBin: 0, missDistance: 40.0,
hit: false, confidence: fired2.confidence))
check "learn: a miss resolves into the same per-power-bucket record",
g.gk.usedGlobalRows >= 1
# A feedback for a tick the gun never predicted (a stale / other-round bullet)
# must NOT create evidence: the row is only updated for the shot taken.
let before = g.gk.usedGlobalRows
g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0],
fireTick: 999, powerBin: 0, missDistance: 4.0,
hit: true, confidence: fired2.confidence))
check "learn: feedback for an unknown fire tick is dropped, not learned",
g.gk.usedGlobalRows == before
# The fallback chain has to REACH a threshold before it answers with a
# residual, so a cold gun must return the plain forecast (residual 0) and
# start COUNTING the situation so it can get there.
var fresh = initGunKnowledge(800.0, 600.0)
let fCold = fresh.featuresFor(wsFor(0, 300.0, 200.0, 3.0, 0.0), 3, 1.0, 0.0, 0.0)
let aCold = fresh.aim(fCold, 0.0)
check "learn: a cold table answers with no residual (the forecast alone)",
aCold.hasTarget and aCold.residual == 0.0 and
aCold.residualBin == -1 and aCold.source == gkSourceNone
check "learn: the cold answer still counts the situation for later",
fresh.usedGlobalRows == 1 and fresh.rowAttempts(fCold) == 1
# Round boundary: the counts SURVIVE (this gun's own capability), the
# per-round scan track does not.
let usedRows = g.gk.usedGlobalRows
g.onRoundBoundary()
check "persist: the learned rows survive a round boundary",
g.gk.usedGlobalRows == usedRows
check "persist: the per-round scan track is dropped at the boundary",
g.gk.tracks.len == 0
# ── on-disk persistence, at a round boundary ─────────────────────────────────
proc testPersistence() =
let path = getTempDir() / "gk_registration_table.bin"
if fileExists(path): removeFile(path)
defer:
if fileExists(path): removeFile(path)
var g = initKnowledgeGun(path)
check "persist: an explicit path is the memory path", g.memPath == path
g.targetId = 7
# 30 ticks of ONE steady situation (tangential move, constant heading and
# speed), so the SAME key accumulates 30 attempts: past the global threshold
# (5) and past the opponent one (20). Fewer ticks would leave every row below
# threshold and `prune` — correctly — would drop all of them at the save.
for t in 0 ..< 30:
discard g.predict(wsFor(t, 300.0, 200.0 + 0.5 * t.float, 3.0, 90.0),
bulletSpeed(PowerBins[0]))
let rows = g.gk.usedGlobalRows + g.gk.oppRows.len
g.onRoundBoundary() # first boundary: load (nothing) + prune + save
let saved = g.gk.usedGlobalRows + g.gk.oppRows.len
check "persist: the round boundary wrote the table", fileExists(path)
check "persist: the table holds learned rows after the prune", saved > 0
check "persist: prune drops the rows that never reached threshold", saved <= rows
# A fresh gun in a fresh process-equivalent state picks the table back up.
var g2 = initKnowledgeGun(path)
g2.ensureInit()
check "persist: a cold gun has no rows before the load",
g2.gk.usedGlobalRows == 0 and g2.gk.oppRows.len == 0
g2.onRoundBoundary() # loads, then round-trips
check "persist: the table came back off disk",
g2.gk.usedGlobalRows + g2.gk.oppRows.len == saved
# A truncated file is REJECTED (strict parser), never half-loaded.
let full = readFile(path)
writeFile(path, full[0 ..< full.len div 2])
var g3 = initKnowledgeGun(path)
g3.ensureInit()
check "persist: a truncated file is rejected and the table stays empty",
not g3.gk.load(path) and g3.gk.usedGlobalRows == 0
writeFile(path, full)
var g4 = initKnowledgeGun(path)
g4.ensureInit()
check "persist: the intact file is accepted again",
g4.gk.load(path) and g4.gk.usedGlobalRows + g4.gk.oppRows.len == saved
testTable()
testEnvOverride()
testLazyAndRngClean()
testLearning()
testPersistence()
if failures > 0:
echo "\n", failures, " check(s) FAILED"
quit(1)
echo "\nAll KNOWLEDGE registration checks passed."
+547
View File
@@ -0,0 +1,547 @@
## 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."
@@ -0,0 +1,287 @@
## 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)
@@ -0,0 +1,120 @@
## ONLINE REAL-BATTLE check for the WAVEELM gun (rack id 18,
## `common_libs/guns/waveelm.nim` — the online-ELM gun).
##
## It answers one question the offline suites cannot: does the LIVE ModularBot
## actually DISCOVER and USE the gun? Two short battles (3 rounds each, the
## `maxSpeed` default) force WAVEELM alone in the rack with env vars only —
## `TR_RACK_WAVEELM=both`, every other gun `off` — against the two shared
## adversaries: SittingDuck (passive) and OscillatorBot (fights back).
##
## Each battle is read from the bot's own per-round gun dump
## (`GUN_STATS_PATH`), and the gun is only "discovered and used" if the live
## loop SPAWNED virtual bullets for id 18 (vShots > 0) and the live selector
## SELECTED it (selected > 0).
##
## Run:
## TR_SERVER_JAR=... TR_BATTLE_RUNNER=... \
## nim c -r common_libs/tests/test_waveelm_rack_live.nim
##
## Skips (exit 0) when the TR JARs are absent, matching the other live tests.
import std/[os, json, strutils]
import test_framework/test_framework
import gun_harness/selector
import gun_harness/virtual_bullets
const
repoRoot = currentSourcePath().parentDir.parentDir.parentDir
modularBotDir = repoRoot / "ModularBot_garage"
adversariesDir = repoRoot / "common_libs" / "test_framework" / "adversaries"
statsPath = "/tmp/waveelm_rack_stats.jsonl"
const WaveElmId = 18
var failures = 0
proc check(name: string, ok: bool) =
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc lastRound(path: string): JsonNode =
result = nil
for line in lines(path):
let s = line.strip()
if s.len == 0: continue
let node = parseJson(s)
if node.hasKey("guns"): result = node
proc runOne(adversary: string) =
let advDir = adversariesDir / adversary
if not dirExists(advDir):
echo "Skipping: adversary not found: ", advDir
quit(0)
if fileExists(statsPath): removeFile(statsPath)
# Force the new gun alone: every other rack entry off, WAVEELM in both racks.
for i, name in RackGunNames:
putEnv("TR_RACK_" & name, if i == WaveElmId: "both" else: "off")
putEnv("GUN_STATS_PATH", statsPath)
defer:
for name in RackGunNames: delEnv("TR_RACK_" & name)
delEnv("GUN_STATS_PATH")
echo "=== live: ModularBot (only WAVEELM racked) vs ", adversary, ", 3 rounds ==="
let battle = runBattle(@[modularBotDir, advDir], rounds = 3)
for res in battle.results:
echo " ", res.name, " rank=", res.rank, " score=", res.totalScore
if not fileExists(statsPath):
echo "FAIL: no gun_stats dump at ", statsPath
inc failures
return
let round = lastRound(statsPath)
check adversary & ": gun_stats.jsonl has a round record", round != nil
if round == nil: return
var shots = 0
var selected = 0
var otherSelected = 0
for g in round["guns"]:
if g["id"].getInt() == WaveElmId:
shots = g["vShots"].getInt()
selected = g["selected"].getInt()
elif g["selected"].getInt() > 0:
otherSelected += g["selected"].getInt()
echo "gun ", WaveElmId, " (WaveElm): vShots=", shots, " selected=", selected,
" other-gun selections=", otherSelected
check adversary & ": the live loop SPAWNED virtual bullets for gun 18 (vShots > 0)",
shots > 0
check adversary & ": the live selector SELECTED gun 18 (selected > 0)",
selected > 0
check adversary & ": no other gun was selected while WAVEELM was forced alone",
otherSelected == 0
proc main() =
let serverJar = getEnv("TR_SERVER_JAR", "")
let runnerJar = getEnv("TR_BATTLE_RUNNER", "")
if serverJar.len == 0 or runnerJar.len == 0:
echo "Skipping: TR_SERVER_JAR / TR_BATTLE_RUNNER not set"
quit(0)
if not fileExists(serverJar) or not fileExists(runnerJar):
echo "Skipping: TR JARs not found (server=", serverJar, ", runner=", runnerJar, ")"
quit(0)
if not fileExists(modularBotDir / "src" / "ModularBot.nim"):
echo "Skipping: ModularBot source not found"
quit(0)
check "rack: WAVEELM is registered at id 18", RackGunNames[WaveElmId] == "WAVEELM"
check "rack: WAVEELM ships `off`, like every gun except Pattern",
ActiveRackMembership[WaveElmId] == rmOff
runOne("SittingDuck")
runOne("OscillatorBot")
if failures > 0:
echo "\n", failures, " check(s) FAILED"
quit(1)
echo "\nWaveElm live rack check passed."
when isMainModule:
main()
+331
View File
@@ -0,0 +1,331 @@
## 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."
+354
View File
@@ -0,0 +1,354 @@
## Offline tests for the TEMPORAL extensions of the WaveElm gun:
## (A) the lag-window feature map (guns/waveelm.nim, WaveLagK / waveFeatures)
## (B) the RELM recurrent hidden layer (guns/elm.nim, r / hPrev / predictStep)
## covered here, plus the per-enemy / per-episode state reset and the
## train-on-the-stored-activation path.
##
## Everything is offline and bounded: no server, no java, no runBattle, and
## every loop count is a small constant.
##
## Run: nim c -r common_libs/tests/test_waveelm_temporal.nim
import std/[math, strformat, tables]
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 allFinite(s: seq[float]): bool =
for v in s:
if not fin(v): return false
true
proc mkState(tick: int, ex, ey, eh, es: float, id = 1,
sx = 100.0, sy = 300.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: 800.0, arenaHeight: 600.0, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
# ── (A) the lag window ───────────────────────────────────────────────────────
proc testLagWindow() =
check "lag: waveInputDim(2) is the legacy 10", waveInputDim(2) == 10
check "lag: waveInputDim(4) == 10 + 2*(4-2)", waveInputDim(4) == 14
check "lag: waveInputDim(8) == 10 + 2*(8-2)", waveInputDim(8) == 22
check "lag: WaveTrackCap covers the longest window", WaveTrackCap >= WaveLagKMax + 1
check "lag: init clamps the window to [2, WaveLagKMax]",
initWaveElmGun(42, lagK = 1).lagK == 2 and
initWaveElmGun(42, lagK = 99).lagK == WaveLagKMax
block:
# A straight run of scans: one tick apart, +6 px in x each tick. Every
# window slot must hold THAT tick's displacement / 16 px.
var g = initWaveElmGun(42, lagK = 4)
check "lag: the net is as wide as the window", g.net.inputDim == 14
var f: seq[float]
for t in 0..<6:
let st = mkState(t, 300.0 + 6.0 * t.float, 300.0, 0.0, 6.0)
discard g.predict(st, 17.0)
f = g.waveFeatures(st, 6.0, 0.0, 30.0)
check "lag: the feature vector is exactly waveInputDim(4) long", f.len == 14
var ok = true
for k in 0..<4:
if abs(f[4 + 2 * k] - 6.0 / 16.0) > 1e-12: ok = false
if abs(f[5 + 2 * k] - 0.0) > 1e-12: ok = false
check &"lag: all 4 window slots hold their own displacement / 16 (t={6})", ok
check "lag: the staleness/flight slots moved to the end of the window",
abs(f[4 + 2 * 4] - 0.0) < 1e-12 and f[5 + 2 * 4] > 0.0
block:
# The base 8 features must not depend on the window: a lagK=4 gun fed the
# same scans must agree with a legacy lagK=2 gun on slots 0..7.
var g4 = initWaveElmGun(42, lagK = 4)
var g2 = initWaveElmGun(42, lagK = 2)
for t in 0..<5:
let st = mkState(t, 300.0 + 5.0 * t.float, 300.0 + t.float, 12.0, 5.0)
discard g4.predict(st, 17.0)
discard g2.predict(st, 17.0)
let f4 = g4.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
let f2 = g2.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
var same = true
for i in 0..<8:
if abs(f4[i] - f2[i]) > 1e-12: same = false
check "lag: the base features are unchanged by the window (slots 0..7)", same
block:
# Fewer scans than the window: the missing slots must be ZERO, not garbage.
var g = initWaveElmGun(42, lagK = 6)
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
let f = g.waveFeatures(mkState(0, 300.0, 300.0, 0.0, 5.0), 5.0, 0.0, 30.0)
check "lag: a window longer than the scan history reads zeros",
f.len == waveInputDim(6) and
(block:
var ok = true
for i in 0..<f.len:
if not fin(f[i]): ok = false
ok)
block:
# A late scan (gap = 2 ticks) must be normalised PER TICK, or the window
# silently measures the radar cadence instead of the target.
var g = initWaveElmGun(42, lagK = 2)
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
discard g.predict(mkState(2, 312.0, 300.0, 0.0, 6.0), 17.0) # 12 px in 2 ticks
let f = g.waveFeatures(mkState(2, 312.0, 300.0, 0.0, 6.0), 6.0, 0.0, 30.0)
check &"lag: a 2-tick gap is normalised to px/tick (6/16 = {6.0/16.0})",
abs(f[4] - 6.0 / 16.0) < 1e-12
# ── (B) the RELM recurrence ──────────────────────────────────────────────────
proc testRelm() =
block:
# Gain 0 must be EXACTLY the legacy feed-forward net: g = act(W x + b).
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
recurrentGain = 0.0)
check "relm: gain 0 leaves the net non-recurrent", not net.recurrent()
check "relm: gain 0 leaves every r_j at 0",
(block:
var ok = true
for v in net.r:
if v != 0.0: ok = false
ok)
let x = @[0.3, -0.7, 0.11]
var manual = newSeq[float](8)
for h in 0..<8:
var s = net.b[h]
for i in 0..<3: s += net.W[h][i] * x[i]
manual[h] = tanh(s)
check "relm: gain 0 reproduces act(W x + b) exactly", net.hidden(x) == manual
block:
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
recurrentGain = 0.5)
check "relm: gain > 0 makes the net recurrent", net.recurrent()
check "relm: every |r_j| is inside the contraction range [0, ElmRMax]",
(block:
var ok = true
for v in net.r:
if abs(v) > ElmRMax or abs(v) >= 1.0: ok = false
ok)
check "relm: the recurrence is seeded (not all identical gains)",
(block:
var varies = false
for i in 1..<net.r.len:
if net.r[i] != net.r[0]: varies = true
varies)
block:
# predict is READ-ONLY, predictStep ADVANCES the clock exactly once.
var net = init(inputDim = 2, hiddenDim = 6, seed = 7, outputDim = 1,
recurrentGain = 0.6)
let x = @[0.5, -0.2]
# beta starts at ZERO, so an untrained net predicts 0 whatever the state
# is: train it first or this test would be comparing 0.0 to 0.0.
for i in 0..<20:
let v = float(i) / 20.0
discard net.train(@[v, -v], @[2.0 * v])
let p1 = net.predict(x)
let p2 = net.predict(x)
check "relm: predict does not advance the hidden state", p1 == p2
discard net.predictStep(x)
let p3 = net.predict(x)
check "relm: predictStep advances the state (the next prediction differs)",
p1 != p3
block:
# STABILITY: the contraction argument says |h| <= 1 and no NaN, whatever
# the input does. Wild-but-plausible inputs first (20000 steps): nothing may
# blow up at all, not even a soft reset.
var net = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
var sane = true
var bounded = true
for i in 0..<20000:
let m = if i mod 2 == 0: 20.0 else: -20.0
let y = net.predictStep(@[m, sin(float(i) * 0.01) * m])
discard net.train(@[m, float(i mod 7).float], @[y[0]])
if not net.isSane() or not allFinite(y): sane = false
for h in net.hPrev:
if not fin(h) or abs(h) > 1.0: bounded = false
check "relm: 20000 steps of +-20 stay finite and sane", sane
check "relm: |h| never leaves tanh's range [-1, 1] (the clamp holds)", bounded
# The pre-existing RLS guard soft-resets on an ill-conditioned stream; what
# matters is whether the RECURRENCE causes MORE of them than the identical
# feed-forward loop does. Same seed, same inputs, only r_j differs.
var ff = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = 0.0)
for i in 0..<20000:
let m = if i mod 2 == 0: 20.0 else: -20.0
let y = ff.predictStep(@[m, sin(float(i) * 0.01) * m])
discard ff.train(@[m, float(i mod 7).float], @[y[0]])
echo &" soft resets on the same 20000 steps: RELM {net.resets}, " &
&"feed-forward {ff.resets}"
check "relm: the recurrence does not add a single soft reset",
net.resets <= ff.resets
# Absurd inputs (1e3) DO trip the pre-existing RLS blow-up guard, which
# soft-resets and carries on. What must hold is that the RECURRENCE does
# not diverge: the prediction stays finite and the state stays in range.
var net2 = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
var sane2 = true
var bounded2 = true
for i in 0..<20000:
let m = if i mod 2 == 0: 1.0e3 else: -1.0e3
let y = net2.predictStep(@[m, sin(float(i) * 0.01) * m])
discard net2.train(@[m, float(i mod 7).float], @[y[0]])
if not allFinite(y): sane2 = false
for h in net2.hPrev:
if not fin(h) or abs(h) > 1.0: bounded2 = false
check "relm: 20000 steps of +-1e3 stay finite", sane2
check "relm: the hidden state stays bounded even at +-1e3", bounded2
block:
# The RLS must still reject bad samples on the hidden-vector entry point.
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.4)
let g = net.hidden(@[0.5])
check "relm: trainHidden rejects a NaN hidden vector",
not net.trainHidden(@[NaN, 0.5, 0.5, 0.5], @[1.0])
check "relm: trainHidden rejects a NaN target", not net.trainHidden(g, @[NaN])
check "relm: the net survives both rejections", net.isSane() and net.samples == 0
block:
# A poisoned recurrence must be DETECTED, not propagated.
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
net.r[0] = NaN
check "relm: isSane detects a NaN recurrent gain", not net.isSane()
var net2 = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
net2.r[0] = 1.5
check "relm: isSane rejects a gain outside the contraction range",
not net2.isSane()
# ── per-enemy / per-episode state reset ──────────────────────────────────────
proc testStateReset() =
block:
# A new target is a new SEQUENCE: its first activation must be computed
# from h(0) = 0, not from whatever the previous target left behind.
var g = initWaveElmGun(42, lagK = 4, relm = 0.6)
var x = 300.0
for t in 0..<8:
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 1)
discard g.predict(st, 17.0)
x += 5.0
check "reset: the RELM state is non-zero after a run of ticks",
(block:
var live = false
for h in g.net.hPrev:
if h != 0.0: live = true
live)
# Same scan stream, new enemy id -> the first activation must equal the one
# a FRESH net would produce (i.e. the state really was cleared).
var h = initWaveElmGun(42, lagK = 4, relm = 0.6)
x = 300.0
for t in 0..<8:
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 2)
discard h.predict(st, 17.0)
x += 5.0
# The strongest form of the claim: after the id change, gun A (which has
# just been running another target) must produce BYTE-IDENTICAL aim points
# to a fresh gun B that has only ever seen the new target. Any residue of
# the old sequence — node state, learned beta, scan track — would break it.
let st4 = mkState(9, x, 300.0, 0.0, 5.0, id = 4)
var fresh = initWaveElmGun(42, lagK = 4, relm = 0.6)
var same = true
for p in WavePowers:
let a = h.predict(st4, bulletSpeed(p))
let b = fresh.predict(st4, bulletSpeed(p))
if a.x != b.x or a.y != b.y or a.confidence != b.confidence: same = false
check "reset: a new enemy id starts its sequence from h(0) = 0", same
check "reset: the target change was actually seen (tracks differ)",
h.tracks.hasKey(2) and h.tracks.hasKey(4)
block:
# Per-episode reset clears the state but KEEPS what was learned.
var g = initWaveElmGun(42, lagK = 2, relm = 0.5)
var x = 300.0
for t in 0..<30:
let st = mkState(t, x, 300.0, 0.0, 5.0)
let pr = g.predict(st, 17.0)
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 4.0,
actualY: pr.y, bulletPower: 1.0, fireTick: t, powerBin: 0,
hit: true, confidence: pr.confidence))
x += 5.0
let samples = g.net.samples
let learned = g.net.beta[0][0]
g.resetTemporalState()
var cleared = true
for v in g.net.hPrev:
if v != 0.0: cleared = false
check "reset: resetTemporalState zeroes h(t-1)", cleared
check "reset: it keeps the learned beta and the RLS state",
g.net.samples == samples and g.net.beta[0][0] == learned
check "reset: a RELM gun still trains on the stored activation",
samples == g.trainedShots
# ── end to end with everything on ────────────────────────────────────────────
proc testEndToEnd() =
var g = initWaveElmGun(42, lagK = 8, relm = 0.3)
var x = 200.0
var y = 300.0
var finite = true
for t in 0..<120:
let st = mkState(t, x, y, 30.0, 5.0)
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
if not (fin(pr.x) and fin(pr.y) and fin(pr.confidence)): finite = false
# resolve immediately, so every trace is trained on its own activation
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 3.0,
actualY: pr.y - 1.0, bulletPower: p, fireTick: t,
powerBin: waveBinForSpeed(spd), hit: true, confidence: pr.confidence))
x = (x + 5.0).clamp(BotRadius, 800.0 - BotRadius)
y = (y + 1.0).clamp(BotRadius, 600.0 - BotRadius)
check "e2e: lagK=8 + RELM 0.3 produces only finite aim points", finite
# A rung trains unless its trace lookup missed or the residual gate rejected it
# as implausible (this target accelerates across the arena, so the ring's
# constant-velocity base is not within 3*BotRadius of the truth every tick).
check &"e2e: every rung is accounted for (trained {g.trainedShots} + rejected " &
&"{g.rejectedShots} + misses {g.missShots} + traceMisses {g.traceMisses})",
g.trainedShots + g.rejectedShots + g.missShots + g.traceMisses == 120 * WaveRungs
check "e2e: the great majority of rungs train", g.trainedShots > (120 * WaveRungs) div 2
check "e2e: the net is still sane", g.net.isSane()
check "e2e: no soft reset was needed", g.net.resets == 0
# Degenerate state with every extension on must still not hang or leak NaN.
var h = initWaveElmGun(42, lagK = 8, relm = 0.9)
let nan = 0.0 / 0.0
var ok = true
for bad in [nan, 1.0 / 0.0, -1.0 / 0.0]:
let st = mkState(3, bad, bad, bad, bad, id = 7)
for p in WavePowers:
let pr = h.predict(st, bulletSpeed(p))
if not fin(pr.x): ok = false
let f = h.waveFeatures(st, bad, bad, bad)
for v in f:
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
check "e2e: NaN/Inf state never escapes with lagK=8 + RELM 0.9", ok
check "e2e: the net survives it", h.net.isSane()
when isMainModule:
echo "── (A) lag window ──"; testLagWindow()
echo "── (B) RELM ──"; testRelm()
echo "── state reset ──"; testStateReset()
echo "── end to end ──"; testEndToEnd()
if failures > 0:
echo "\n", failures, " of ", checks, " check(s) FAILED"
quit(1)
echo &"\nAll {checks} WaveElm-temporal checks passed."