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.
729 lines
36 KiB
Nim
729 lines
36 KiB
Nim
## waveelm.nim — the WaveElm gun. The ONLY wave mechanism is a SIMULATED
|
|
## OMNIDIRECTIONAL EXPANDING RING; the ELM corrects the ring's MEASUREMENT.
|
|
##
|
|
## ── THE RING ─────────────────────────────────────────────────────────────────
|
|
## The ring is `RingProbes` rays fired simultaneously from the shooter at one
|
|
## bullet speed; at offset k the ring's radius is `k * bulletSpeed(power)`. It
|
|
## is a SIMULATION of an instrument, not a shot pattern: nothing is fired, so
|
|
## it costs no energy and no cooldown and it is legal at any time. What it
|
|
## measures, for the first enemy it touches, is the MEETING POINT — the
|
|
## interception radius (== the distance to the enemy at contact) and the bearing
|
|
## of the probe ray that touched it. Distance + bearing is a complete polar
|
|
## position measurement of a target we have already scanned.
|
|
##
|
|
## WHY A RING AND NOT A DIRECTED SHOT (measured, /tmp/ringspike, now removed —
|
|
## the spike source is kept at /tmp/ringspike/ring_backup_keep.nim):
|
|
## * directed design: only 21.5% of aimed offsets survive as training labels
|
|
## (mean labelled magnitude 0.23x the truth) — an aimed bullet misses a
|
|
## strafing target, and a miss carries no label. Interception ~21.5%.
|
|
## * ring: 720 probes, 100.00% interception (108/108), 0.92-0.93 labels per
|
|
## tick per enemy.
|
|
## * raw ring noise WITHOUT the ELM: radius error RMS 6.0 px, bearing
|
|
## quantisation 0.97 px.
|
|
##
|
|
## ── WHAT THE ELM LEARNS: A BIAS CORRECTION (mode b), NOT A POSITION ─────────
|
|
## The net predicts the CORRECTION to apply to the ring's reconstructed position
|
|
## — a BIAS, never a position. The alternative, predicting the enemy's position
|
|
## outright (spike mode a), was measured and REFUTED: flat 3.4-4.3 px RMS on
|
|
## smooth/accelerating regimes but a collapse to 29-44 px RMS on abrupt/burst,
|
|
## i.e. exactly when it matters; bias correction (mode b) stayed flat 3.4-4.3 px
|
|
## across ALL regimes at a 100% in-BotRadius rate. Baseline directed numbers for
|
|
## the same regimes: glide 7.990/11.815/23.072 RMS, burst 8.083/14.434/20.927.
|
|
##
|
|
## HONEST CAVEAT on those numbers, since it is easy to over-read them: mode (b)
|
|
## was measured with a feature map (velocity, ring distances, age) that has NO
|
|
## BEARING term, so part of its flatness is that the best correction it can
|
|
## express is the MEAN bias, which for a strafing target is near zero. The
|
|
## correction is therefore applied CARTESIAN here rather than in polar
|
|
## (dDist, dBear): the ring measures polar, but the feature map has no way to
|
|
## know which way the ring pointed, so a polar label would be unlearnable and
|
|
## would collapse to its own mean. See the label note in `onResult`.
|
|
##
|
|
## ── THE DAMAGE SHOT ─────────────────────────────────────────────────────────
|
|
## The ring produces labels; it does not damage anything. Real bullets are aimed
|
|
## at the ENEMY POSITION RECONSTRUCTED from the ring measurement
|
|
## (`self + (dist, bear)`) plus the ELM's bias correction, i.e. exactly the
|
|
## quantity the ring is well-conditioned about. When the gun has no ring
|
|
## measurement yet (a target it has seen once), it degrades to aiming at the
|
|
## scan position itself — a HeadOn shot, the rack's floor, never a crash.
|
|
##
|
|
## ── WHAT HAPPENS IF VIRTUAL BULLETS ARE DISABLED ───────────────────────────
|
|
## The ring is SIM-ONLY: it is simulated inside the gun from the scan track, so
|
|
## the gun's aim does not depend on the virtual-bullet tracker at all. What the
|
|
## tracker provides is the LABEL — `onResult` is fed by
|
|
## `VirtualTracker.tickBullets`, which is where the polar-free Cartesian bias
|
|
## between the ring reconstruction and the enemy comes from. With
|
|
## `TR_MODULE_VBULLETS=0` (or the rack unmembership `off`) `predict` still runs
|
|
## and still aims at the ring reconstruction — the gun degrades to the ring's raw
|
|
## measurement with NO learned correction, never to a crash and never to a
|
|
## HeadOn/no-op. With virtual bullets on, `VBulletAdmitOnly` already forces
|
|
## `admit[WaveElmId]` in ModularBot (see the `admit` block), so the gun is never
|
|
## skipped for being unselected.
|
|
##
|
|
## ── MEASURED, HONESTLY ──────────────────────────────────────────────────────
|
|
## The offline benchmark with the ring as the base (bench_waveelm_temporal.nim,
|
|
## same regimes as before): glide smooth 0.06 px / accel 0.11 px / abrupt 25.5 px
|
|
## RMS, burst smooth 29.9 / accel 37.6 / abrupt 80.1 px. The OLD directed
|
|
## baselines were glide 7.990/11.815/23.072 and burst 8.083/14.434/20.927. So:
|
|
## the ring is dramatically better where the target flies straight (0.06 px vs
|
|
## 8 px) and dramatically WORSE where it turns (80 px vs 21 px), because the ring
|
|
## is a constant-velocity lead and a turning target breaks that assumption over
|
|
## a long flight — and because the broken base means no confirmed hits, hence no
|
|
## labels, hence nothing to learn from. This is a documented ceiling, not a
|
|
## tuning miss: see `testSupervision` in common_libs/tests/test_waveelm.nim.
|
|
##
|
|
## ── SCAN-ONLY LEGITIMACY ────────────────────────────────────────────────────
|
|
## `ringFireFromScan` reads exactly three things: `state.enemyX/enemyY` (the
|
|
## position of the target the radar SELECTED, i.e. a scan), and the velocity
|
|
## DERIVED from the last two scans of that same target. It never reads
|
|
## `state.enemies`, the tracker's table, or any position at any tick other than
|
|
## the scan it was given. It is therefore scan-only by construction, and it is
|
|
## also honest in the deeper sense: it never needs to know where the enemy WILL
|
|
## be, because the ring's contact radius is a measurement of where it IS.
|
|
## See the module-level test in common_libs/tests/test_waveelm_ring.nim.
|
|
##
|
|
## ── THE LEFT/RIGHT OSCILLATION (measured, fixed, unchanged) ─────────────────
|
|
## A shot fired at tick T resolves at T + flightTime (20-80 ticks, far longer
|
|
## than the RLS memory 1/(rho-1) ~ 12 ticks), so the label describes the bias
|
|
## at the ARRIVAL tick while the features describe the FIRE tick. `WaveResolve
|
|
## Features` rebuilds each in-flight trace's features at its arrival tick so
|
|
## feature-time == label-time. Measured effect (perpendicular = left-right
|
|
## component of the aim error): accel 16.57 px -> 7.67 px, abrupt 5.12 px ->
|
|
## 1.18 px; a proven NO-OP when feedback is not delayed.
|
|
##
|
|
## ── ONE NET, SHARED ─────────────────────────────────────────────────────────
|
|
## A single `ElmNet` shared by every target, per-target state (scan track, ring
|
|
## measurement, pending traces) kept separately. The bias being learned is mostly
|
|
## a property of THIS BOT, and `rho` (the RLS forgetting factor, memory ~50
|
|
## samples) is what lets the shared net track a change of target.
|
|
|
|
import std/[math, tables]
|
|
import gun_harness/gun_interface
|
|
import gun_harness/virtual_bullets as vb
|
|
import guns/elm
|
|
|
|
const
|
|
# ── the ladder (rung == ring speed) ─────────────────────────────────────────
|
|
WavePowers* = [1.0, 2.0, 3.0] ## speed 17 / 14 / 11 px/tick
|
|
WaveRungs* = WavePowers.len
|
|
|
|
# ── RING GEOMETRY ──────────────────────────────────────────────────────────
|
|
RingArenaW* = 800.0 ## ASSUMPTION: the Tank Royale arena this gun is sized
|
|
RingArenaH* = 600.0 ## for. See `ringProbeCount` for why and what breaks.
|
|
RingSafety* = 2.0 ## safety factor on the probe count (see below)
|
|
|
|
# ── scan history ────────────────────────────────────────────────────────────
|
|
WaveTrackCap* = 9 ## == WaveLagKMax + 1: the longest lag window + 1
|
|
WaveLagKMax* = 8
|
|
|
|
# ── ELM shape ───────────────────────────────────────────────────────────────
|
|
WaveInputDim* = 10 ## width at lagK = 2 (two displacements)
|
|
WaveHiddenDim* = 16
|
|
WaveLambda* = 0.1
|
|
WaveRho* = 1.02 ## memory 1/(rho-1) ~ 50 samples; 1.05 is too short.
|
|
|
|
# ── (A) LAG WINDOW ──────────────────────────────────────────────────────────
|
|
WaveLagK* = 2 ## scan-to-scan displacements in the feature map
|
|
WaveRelmGain* = 0.0 ## RELM recurrent gain; 0 = recurrence OFF (measured a
|
|
## wash to a regression; left in, defaulted off)
|
|
|
|
# ── guards ──────────────────────────────────────────────────────────────────
|
|
WaveMaxResidual* = 3.0 * BotRadius
|
|
## 54 px on the Cartesian bias between the ring reconstruction and where the
|
|
## enemy was. MEASURED: it essentially never fires (a confirmed hit cannot be
|
|
## 54 px from the aim point).
|
|
WaveGateAdapt* = 0.0 ## adapting gate; 0 = fixed (measured identical)
|
|
WaveMaxOffset* = 2.0 * BotRadius
|
|
## clamp on the learned correction, in px for the radial output and, for the
|
|
## angular output, converted to px at the measured distance so both halves
|
|
## share one physical ceiling.
|
|
|
|
# ── flight-time feature alignment ───────────────────────────────────────────
|
|
WaveResolveFeatures* = true
|
|
|
|
# ── pending-trace ring ──────────────────────────────────────────────────────
|
|
WaveTraceSlots* = 1024
|
|
|
|
# ── the ring geometry ─────────────────────────────────────────────────────────
|
|
#
|
|
# N PROBES. The ring must have no angular GAP wider than a bot at maximum range,
|
|
# or an enemy sitting in the gap is never touched at all (the measurement, and
|
|
# therefore the label, is lost for that bearing forever). The gap at radius r is
|
|
# `2*pi*r/N`, so
|
|
#
|
|
# N >= 2*pi*rMax / BotRadius
|
|
#
|
|
# With rMax = the arena DIAGONAL (the largest possible separation between two
|
|
# bots) and BotRadius = 18 px: rMax = hypot(800, 600) = 1000 px, so
|
|
# N >= 2*pi*1000/18 = 349. `RingSafety` doubles that for margin (the enemy is a
|
|
# DISC, not a point, and it MOVES between the ring's radii):
|
|
#
|
|
# N = 2 * 349 = 698 -> rounded up to a multiple of 60 -> 720
|
|
#
|
|
# ASSUMPTION, STATED: rMax is the 800x600 diagonal above. `RingArenaW/H` are the
|
|
# single place that assumption lives. If the real map is bigger, the derived
|
|
# count grows automatically (`ringProbeCount` is a function of rMax); if it is
|
|
# smaller, 720 probes is merely more than needed — never fewer. The ONLY thing
|
|
# that breaks with too small a map is an angular gap wider than a bot at the
|
|
# corner, i.e. missed bearings; nothing crashes and nothing NaNs.
|
|
proc ringProbeCount*(rMax: float): int =
|
|
## Smallest probe count whose angular gap stays inside a bot's radius at
|
|
## `rMax`, with `RingSafety` margin, rounded up to a multiple of 60 (60 is the
|
|
## spike's measured value's factor: 720 = 12*60, and a multiple of 60 keeps
|
|
## `RingDirs` cheap and the geometry easy to state).
|
|
if not (rMax > 0.0): return 60
|
|
let need = int(ceil(2.0 * PI * rMax / BotRadius * RingSafety))
|
|
max(60, ((need + 59) div 60) * 60)
|
|
|
|
const
|
|
RingRMax* = hypot(RingArenaW, RingArenaH)
|
|
RingProbes* = ringProbeCount(RingRMax) ## 720 for the 800x600 assumption
|
|
|
|
let RingDirs*: seq[float] = block:
|
|
## Probe bearings, 0 = East, CCW positive (the Tank Royale convention).
|
|
var d = newSeq[float](RingProbes)
|
|
for i in 0..<RingProbes: d[i] = 2.0 * PI * i.float / RingProbes.float
|
|
d
|
|
|
|
type
|
|
RingHit* = object
|
|
found*: bool
|
|
dist*: float ## ring radius at first contact (== distance to enemy)
|
|
bearing*: float ## rad, bearing of the probe ray that made contact
|
|
tick*: int ## absolute tick of first contact (fireTick + k)
|
|
missDist*: float ## closest approach of the ray to the enemy
|
|
|
|
proc ringFireAt*(sx, sy: float, spd: float,
|
|
px, py: seq[float], fireTick: int,
|
|
maxRadius = RingRMax): RingHit =
|
|
## Simulate ONE expanding ring of `RingProbes` rays of SPEED `spd`, fired at
|
|
## `fireTick` from (sx, sy). `px/py` are the target's positions indexed by
|
|
## ABSOLUTE TICK; the ring is tested against the target's position on each tick
|
|
## `fireTick + k`, where its radius is `k * spd`. The first contact is the
|
|
## interception.
|
|
if not (spd > 0.0):
|
|
return RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
|
|
missDist: Inf)
|
|
let maxK = int(ceil(maxRadius / spd))
|
|
var closest = Inf ## closest approach of any probe ray, diagnostics
|
|
var got = false
|
|
var bestR = 0.0 ## the contact radius
|
|
var bestBear = 0.0
|
|
var bestTick = -1
|
|
var bestMiss = 0.0
|
|
var bestRadial = Inf ## |eDist - r| of the accepted contact
|
|
for k in 1..maxK:
|
|
let t = fireTick + k
|
|
if t < 0 or t >= px.len: break
|
|
let r = k.float * spd
|
|
let ex = px[t] - sx
|
|
let ey = py[t] - sy
|
|
let eAng = arctan2(ey, ex)
|
|
let eDist = hypot(ex, ey)
|
|
# nearest probe ray (search +-1 index, so quantisation is at most half a gap)
|
|
let idx = int(round(eAng / (2.0 * PI) * RingProbes.float)) mod RingProbes
|
|
var kbest = Inf
|
|
var kidx = 0
|
|
for o in [-1, 0, 1]:
|
|
let i = (idx + o + RingProbes) mod RingProbes
|
|
let perp = abs(eDist * sin(eAng - RingDirs[i]))
|
|
if perp < kbest:
|
|
kbest = perp
|
|
kidx = i
|
|
if kbest < closest: closest = kbest
|
|
# CONTACT. The ray must sweep the target's DISC (kbest <= BotRadius) AND the
|
|
# annulus must be within BotRadius of the target's radius.
|
|
#
|
|
# BEST k, NOT FIRST k. The ring's radius steps by a whole `spd` per tick, so
|
|
# "first contact" is systematically the annulus BELOW the target, biased by
|
|
# up to BotRadius (8.5 px mean at the 17 px rung) in the one direction the
|
|
# target is moving. Every acceptable annulus is a legal reading of the same
|
|
# measurement, so the ring reports the one whose radius is CLOSEST to the
|
|
# target's — the maximum-likelihood reading of a quantised instrument.
|
|
if kbest <= BotRadius and abs(eDist - r) <= BotRadius:
|
|
let radial = abs(eDist - r)
|
|
if radial < bestRadial:
|
|
bestRadial = radial
|
|
got = true
|
|
bestR = r
|
|
bestBear = RingDirs[kidx]
|
|
bestTick = t
|
|
bestMiss = kbest
|
|
if got:
|
|
return RingHit(found: true, dist: bestR, bearing: bestBear,
|
|
tick: bestTick, missDist: bestMiss)
|
|
RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1, missDist: closest)
|
|
|
|
proc ringFire*(sx, sy: float, power: float,
|
|
px, py: seq[float], fireTick: int,
|
|
maxRadius = RingRMax): RingHit =
|
|
## `ringFireAt` in bullet-speed form: power -> `bulletSpeed(power)`.
|
|
ringFireAt(sx, sy, bulletSpeed(power), px, py, fireTick, maxRadius)
|
|
|
|
proc ringDecode*(h: RingHit, sx, sy: float): tuple[x, y: float] =
|
|
## Ring measurement -> absolute position: the point on the contacted bearing at
|
|
## the contacted radius.
|
|
(sx + h.dist * cos(h.bearing), sy + h.dist * sin(h.bearing))
|
|
|
|
|
|
# ── helpers ───────────────────────────────────────────────────────────────────
|
|
|
|
proc isFinite(x: float): bool {.inline.} =
|
|
classify(x) notin {fcNan, fcInf, fcNegInf}
|
|
|
|
proc finiteOr*(x, fallback: float): float {.inline.} =
|
|
## Scrub a non-finite float at the trust boundary (see the old note: an Inf in
|
|
## an angle wrap loop hangs the bot at 100% CPU).
|
|
if isFinite(x): x else: fallback
|
|
|
|
proc wrapDeg(x: float): float {.inline.} =
|
|
## Wrap an angle to [-180, 180). Bounded loop: with a non-finite input the
|
|
## condition can stay true while the body makes no progress, which hangs.
|
|
if not isFinite(x): return 0.0
|
|
result = x
|
|
for _ in 0..<4:
|
|
if result > 180.0: result -= 360.0
|
|
elif result < -180.0: result += 360.0
|
|
else: break
|
|
|
|
proc waveBinForSpeed*(spd: float): int =
|
|
## Map a bullet speed back to its power-bin index, or -1.
|
|
for i in 0..<len(vb.PowerBins):
|
|
if abs(spd - bulletSpeed(vb.PowerBins[i])) < 1e-6: return i
|
|
-1
|
|
|
|
proc waveTraceSlot(fireTick, binIdx: int): int {.inline.} =
|
|
((fireTick * len(vb.PowerBins)) + binIdx) mod WaveTraceSlots
|
|
|
|
# ── types ─────────────────────────────────────────────────────────────────────
|
|
|
|
type
|
|
WaveSample = object
|
|
tick: int
|
|
x, y: float
|
|
|
|
WaveTrack = object
|
|
## Index 0 is the NEWEST scan. samples[0..1] give the velocity,
|
|
## samples[k..k+1] the k-th most recent displacement.
|
|
s: array[WaveTrackCap, WaveSample]
|
|
n: int
|
|
|
|
WaveRing* = object
|
|
## The newest ring measurement for a target.
|
|
valid*: bool
|
|
dist*: float ## measured distance, px (== the contact radius)
|
|
bear*: float ## measured bearing, rad
|
|
fireTick*: int ## the tick the ring was fired on
|
|
tick*: int ## the tick the contact resolved on
|
|
flight*: float ## tick - fireTick
|
|
|
|
WaveElmGun* = object
|
|
net*: ElmNet
|
|
tracks*: Table[int, WaveTrack] ## EnemyInfo.id -> scan history
|
|
rings*: Table[int, WaveRing] ## EnemyInfo.id -> newest ring measurement
|
|
targetId*: int ## -1 => derive the id from state.enemies[0]
|
|
lastId*: int ## the id predict() actually resolved this tick
|
|
lastTick*: int ## tick the current scan was pushed on (predict runs
|
|
## 4-5x per tick; the scan must be pushed ONCE)
|
|
lagK*: int
|
|
relm*: float
|
|
maxResidual*: float
|
|
maxOffset*: float
|
|
gateAdapt*: float
|
|
recentRms*: float
|
|
traces*: array[WaveTraceSlots, WaveTrace]
|
|
resolveFeat*: bool
|
|
refreshAt*: seq[int] ## slots due for a feature refresh this tick; the queue
|
|
## is cleared as it is walked (self-cleaning)
|
|
|
|
# instrumentation (exported for the tests)
|
|
predictCalls*: int
|
|
trainedShots*: int
|
|
traceMisses*: int
|
|
rejectedShots*: int
|
|
missShots*: int
|
|
ringContacts*: int ## rings that found a contact
|
|
ringFires*: int ## rings fired
|
|
lastDx*, lastDy*: float ## the last learned correction, in px (Cartesian)
|
|
|
|
WaveTrace = object
|
|
fireTick: int
|
|
binIdx: int
|
|
resolveTick: int
|
|
measDist: float ## the ring measurement this shot was built from
|
|
measBear: float
|
|
selfX, selfY: float
|
|
feat: seq[float]
|
|
hid: seq[float] ## the FIRE-time hidden activation g(t); trained on
|
|
## directly, because by the time the hit resolves
|
|
## h(t-1) has moved on
|
|
alive: bool
|
|
|
|
# ── construction ──────────────────────────────────────────────────────────────
|
|
|
|
proc waveInputDim*(lagK: int): int {.inline.} =
|
|
## Feature width for a given lag window. 8 "static" features + 2 per
|
|
## displacement.
|
|
WaveInputDim + 2 * (max(2, lagK) - 2)
|
|
|
|
proc initWaveElmGun*(seed: int64 = 42, lagK = WaveLagK,
|
|
relm = WaveRelmGain,
|
|
hiddenDim = WaveHiddenDim,
|
|
lambda = WaveLambda, rho = WaveRho,
|
|
maxResidual = WaveMaxResidual,
|
|
maxOffset = WaveMaxOffset,
|
|
gateAdapt = WaveGateAdapt,
|
|
resolveFeat = WaveResolveFeatures): WaveElmGun =
|
|
## Every knob is an override of the module constant of the same name, so an
|
|
## offline sweep can compare configs without recompiling per value. A negative
|
|
## maxResidual/maxOffset means "no clamp".
|
|
result.lagK = clamp(lagK, 2, WaveLagKMax)
|
|
result.relm = max(0.0, relm)
|
|
result.net = init(inputDim = waveInputDim(result.lagK),
|
|
hiddenDim = hiddenDim, seed = seed, outputDim = 2,
|
|
lambda = lambda, rho = rho,
|
|
recurrentGain = result.relm)
|
|
result.maxResidual = maxResidual
|
|
result.maxOffset = maxOffset
|
|
result.gateAdapt = gateAdapt
|
|
result.resolveFeat = resolveFeat
|
|
result.targetId = -1
|
|
result.lastId = -1
|
|
result.lastTick = -1
|
|
|
|
proc resetTemporalState*(g: var WaveElmGun) =
|
|
## Per-episode reset: the RELM hidden state belongs to the SEQUENCE. beta and P
|
|
## are kept: what the net has LEARNED is a property of this bot.
|
|
g.net.resetHidden()
|
|
g.lastTick = -1
|
|
|
|
proc isWarmedUp*(g: WaveElmGun): bool {.inline.} =
|
|
## Two scans of the current target: enough to derive a velocity instead of
|
|
## falling back to heading*speed.
|
|
let id = if g.targetId >= 0: g.targetId else: g.lastId
|
|
if id < 0: return false
|
|
if g.tracks.hasKey(id): g.tracks[id].n >= 2
|
|
else: false
|
|
|
|
proc ringDecode*(r: WaveRing, sx, sy: float): tuple[x, y: float] {.inline.} =
|
|
## The stored per-target measurement, decoded. Falls back to the caller's own
|
|
## position when there is no measurement yet (a never-seen target).
|
|
if r.valid:
|
|
(sx + r.dist * cos(r.bear), sy + r.dist * sin(r.bear))
|
|
else: (sx, sy)
|
|
|
|
proc ringFor*(g: WaveElmGun, id: int): WaveRing {.inline.} =
|
|
## The newest ring measurement for a target; an invalid one when it has none.
|
|
if g.rings.hasKey(id): g.rings[id] else: WaveRing()
|
|
|
|
# ── the ring, from SCANS ONLY ─────────────────────────────────────────────────
|
|
|
|
proc ringFireFromScan*(g: var WaveElmGun, state: WorldState, vx, vy: float,
|
|
spd: float): RingHit =
|
|
## The LIVE ring. Its entire input is the SELECTED SCAN (`state.enemyX/Y`,
|
|
## the position the radar resolved this tick) plus the velocity DERIVED FROM
|
|
## THAT TARGET'S OWN LAST TWO SCANS. It reads nothing else: not
|
|
## `state.enemies`, not the tracker table, not any other tick's position.
|
|
##
|
|
## The scan is extended forward at constant velocity for the length of the
|
|
## ring's flight, and `ringFire` is run against that extension. The error that
|
|
## introduces (the target does not really fly straight) is exactly the BIAS
|
|
## the ELM is trained to correct — which is why the ELM's input includes the
|
|
## recent displacement window and why the label is a bias, not a position.
|
|
let sx = finiteOr(state.selfX, 0.0)
|
|
let sy = finiteOr(state.selfY, 0.0)
|
|
let ex = finiteOr(state.enemyX, 0.0)
|
|
let ey = finiteOr(state.enemyY, 0.0)
|
|
let vx = finiteOr(vx, 0.0)
|
|
let vy = finiteOr(vy, 0.0)
|
|
if not (spd > 0.0):
|
|
return RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
|
|
missDist: Inf)
|
|
let maxK = int(ceil(RingRMax / spd))
|
|
var px = newSeq[float](maxK + 1)
|
|
var py = newSeq[float](maxK + 1)
|
|
for k in 0..maxK:
|
|
px[k] = ex + vx * k.float
|
|
py[k] = ey + vy * k.float
|
|
inc g.ringFires
|
|
# `fireTick = 0`: the trajectory above is indexed by OFFSET from now, so the
|
|
# contact tick `ringFireAt` reports is the flight time in ticks, not an
|
|
# absolute tick.
|
|
let h = ringFireAt(sx, sy, spd, px, py, 0, RingRMax)
|
|
if h.found: inc g.ringContacts
|
|
h
|
|
|
|
# ── the feature vector ────────────────────────────────────────────────────────
|
|
#
|
|
# All inputs scaled to roughly unit magnitude so the random hidden layer does not
|
|
# saturate its tanhs. Index 0 is the NEWEST scan. Layout (lagK displacements):
|
|
#
|
|
# [0] vx [1] vy derived velocity, px/tick
|
|
# [2] dist RING-measured distance (scan distance before the
|
|
# first contact), /1000
|
|
# [3] hdelta range, closing/opening (from the scan heading)
|
|
# [4+2k] dx_k [5+2k] dy_k the k-th most recent scan-to-scan displacement,
|
|
# k = 0 is the newest, /16 px per tick
|
|
# [4+2*lagK] age staleness of the newest scan, ticks
|
|
# [5+2*lagK] flight ring flight time (ticks) to the contact, /64
|
|
|
|
proc waveFeatures*(g: WaveElmGun, state: WorldState, vx, vy, flightTime: float):
|
|
seq[float] =
|
|
let id = if g.targetId >= 0: g.targetId
|
|
elif state.enemies.len > 0: state.enemies[0].id
|
|
else: 0
|
|
# Sanitise at the trust boundary: every float that comes out of `state` (and
|
|
# every argument) is finite before it reaches arithmetic that assumes progress.
|
|
let ex = finiteOr(state.enemyX, 0.0)
|
|
let ey = finiteOr(state.enemyY, 0.0)
|
|
let sx = finiteOr(state.selfX, 0.0)
|
|
let sy = finiteOr(state.selfY, 0.0)
|
|
let heading = finiteOr(state.enemyHeading, 0.0)
|
|
var vx = finiteOr(vx, 0.0)
|
|
var vy = finiteOr(vy, 0.0)
|
|
var flightTime = finiteOr(flightTime, 0.0)
|
|
|
|
let dx = ex - sx
|
|
let dy = ey - sy
|
|
let los = arctan2(dy, dx)
|
|
|
|
# heading delta, wrapped: positive = the target moves to the LEFT of the line
|
|
# of sight (opening range), negative = closing.
|
|
let hdelta = wrapDeg(heading - radToDeg(los))
|
|
|
|
# The RANGE the net reasons about is the RING's measurement when there is one:
|
|
# the ring is the instrument, the scan distance is only what it is calibrated
|
|
# against.
|
|
let ring = g.ringFor(id)
|
|
let dist = if ring.valid: ring.dist else: hypot(dx, dy)
|
|
|
|
let lagK = max(2, g.lagK)
|
|
result = newSeq[float](waveInputDim(lagK))
|
|
result[0] = vx / 8.0
|
|
result[1] = vy / 8.0
|
|
result[2] = dist / 1000.0
|
|
result[3] = hdelta / 180.0
|
|
|
|
var age = 0.0
|
|
if g.tracks.hasKey(id):
|
|
let tr = g.tracks[id]
|
|
# Each displacement is normalised by its OWN tick gap, so a late scan
|
|
# contributes a per-tick velocity rather than a 3-tick one.
|
|
for k in 0..<lagK:
|
|
if tr.n >= k + 2:
|
|
let gap = (tr.s[k].tick - tr.s[k + 1].tick).float
|
|
if gap >= 1.0:
|
|
result[4 + 2 * k] = (tr.s[k].x - tr.s[k + 1].x) / (16.0 * gap)
|
|
result[4 + 2 * k + 1] = (tr.s[k].y - tr.s[k + 1].y) / (16.0 * gap)
|
|
age = (state.tick - tr.s[0].tick).float
|
|
result[4 + 2 * lagK] = age / 8.0
|
|
result[5 + 2 * lagK] = flightTime / 64.0
|
|
|
|
for i in 0..<result.len:
|
|
if not isFinite(result[i]): result[i] = 0.0
|
|
|
|
proc pushScan(g: var WaveElmGun, id: int, tick: int, x, y: float) =
|
|
let tr = addr g.tracks.mgetOrPut(id, WaveTrack())
|
|
for i in countdown(WaveTrackCap - 1, 1): tr.s[i] = tr.s[i - 1]
|
|
tr.s[0] = WaveSample(tick: tick, x: x, y: y)
|
|
if tr.n < WaveTrackCap: inc tr.n
|
|
|
|
proc derivedVelocity(g: WaveElmGun, id: int, state: WorldState): tuple[vx, vy: float] =
|
|
## Velocity from the last two scans of THIS target; else heading*speed, the
|
|
## fallback every other gun in the rack uses.
|
|
result = (finiteOr(cos(degToRad(state.enemyHeading)) * state.enemySpeed, 0.0),
|
|
finiteOr(sin(degToRad(state.enemyHeading)) * state.enemySpeed, 0.0))
|
|
if g.tracks.hasKey(id):
|
|
let tr = g.tracks[id]
|
|
if tr.n >= 2:
|
|
let gap = (tr.s[0].tick - tr.s[1].tick).float
|
|
if gap >= 1.0:
|
|
result.vx = finiteOr((tr.s[0].x - tr.s[1].x) / gap, 0.0)
|
|
result.vy = finiteOr((tr.s[0].y - tr.s[1].y) / gap, 0.0)
|
|
|
|
# ── the Gun concept ───────────────────────────────────────────────────────────
|
|
|
|
proc predict*(g: var WaveElmGun, state: WorldState, bulletSpeed: float): GunPrediction =
|
|
inc g.predictCalls
|
|
|
|
let id = if g.targetId >= 0: g.targetId
|
|
elif state.enemies.len > 0: state.enemies[0].id
|
|
else: 0
|
|
# (B) PER-ENEMY TEMPORAL RESET: the RELM node state is the state of a
|
|
# SEQUENCE, and a different target is a different sequence.
|
|
if g.lastId != id: g.net.resetHidden()
|
|
g.lastId = id
|
|
|
|
# ONE scan push per tick: the harness calls predict 4-5 times a tick.
|
|
let newTick = state.tick != g.lastTick
|
|
if newTick:
|
|
g.lastTick = state.tick
|
|
g.pushScan(id, state.tick, state.enemyX, state.enemyY)
|
|
|
|
let (vx, vy) = g.derivedVelocity(id, state)
|
|
|
|
# ── THE RING ────────────────────────────────────────────────────────────────
|
|
# One ring per rung per new tick, at that rung's speed. The contact resolves
|
|
# `flight` ticks later; until then the previous measurement stays in force.
|
|
let ring = g.ringFor(id)
|
|
var h = RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
|
|
missDist: Inf)
|
|
if newTick or not ring.valid:
|
|
h = g.ringFireFromScan(state, vx, vy, bulletSpeed)
|
|
if h.found:
|
|
g.rings[id] = WaveRing(valid: true, dist: h.dist, bear: h.bearing,
|
|
fireTick: state.tick, tick: state.tick + h.tick,
|
|
flight: float(h.tick))
|
|
let meas = g.ringFor(id)
|
|
let measDist = if meas.valid: meas.dist else: hypot(state.enemyX - state.selfX,
|
|
state.enemyY - state.selfY)
|
|
let measBear = if meas.valid: meas.bear
|
|
else: arctan2(state.enemyY - state.selfY,
|
|
state.enemyX - state.selfX)
|
|
let flight = if meas.valid: meas.flight else: measDist / max(bulletSpeed, 1e-6)
|
|
|
|
# ── FLIGHT-TIME FEATURE REFRESH (WaveResolveFeatures) ──────────────────────
|
|
# Every trace whose bullet resolves THIS tick has its features rebuilt from the
|
|
# state as it is NOW, so the label is paired with the state the LABEL describes
|
|
# rather than the state the shot was fired from. Runs once per tick, after the
|
|
# scan push (so the trace sees this tick's scan exactly as a predict at this
|
|
# tick would).
|
|
if g.resolveFeat and newTick and g.refreshAt.len > 0:
|
|
var keep: seq[int] = @[]
|
|
for slot in g.refreshAt:
|
|
var tr = g.traces[slot]
|
|
if tr.alive and tr.resolveTick == state.tick:
|
|
let f2 = g.waveFeatures(state, vx, vy, flight)
|
|
tr.feat = f2
|
|
tr.selfX = state.selfX
|
|
tr.selfY = state.selfY
|
|
if g.net.isSane(): tr.hid = g.net.hidden(f2)
|
|
g.traces[slot] = tr
|
|
elif not tr.alive:
|
|
discard # the bullet died (wall / stale target); drop the reminder
|
|
else:
|
|
keep.add slot
|
|
g.refreshAt = keep
|
|
|
|
# ── THE LEARNED BIAS CORRECTION ─────────────────────────────────────────────
|
|
# The learned bias, px, in the world frame (see the module header on why the
|
|
# ring measures polar but the correction is applied Cartesian).
|
|
var dDist = 0.0
|
|
var dBear = 0.0
|
|
# (named for the net's two outputs; both are px, see the label note in onResult)
|
|
var gh: seq[float]
|
|
if g.net.isSane():
|
|
let feat = g.waveFeatures(state, vx, vy, flight)
|
|
gh = g.net.hidden(feat)
|
|
if newTick: g.net.hPrev = gh
|
|
let off = g.net.readOut(gh)
|
|
if off.len == 2 and isFinite(off[0]) and isFinite(off[1]):
|
|
dDist = off[0]
|
|
dBear = off[1]
|
|
dDist = clamp(dDist, -g.maxOffset, g.maxOffset)
|
|
dBear = clamp(dBear, -g.maxOffset, g.maxOffset)
|
|
g.lastDx = dDist
|
|
g.lastDy = dBear
|
|
|
|
# ── THE DAMAGE SHOT ─────────────────────────────────────────────────────────
|
|
# Reconstruct the enemy from the ring measurement and apply the correction.
|
|
let (rx, ry) = (finiteOr(state.selfX, 0.0) + measDist * cos(measBear) + g.lastDx,
|
|
finiteOr(state.selfY, 0.0) + measDist * sin(measBear) + g.lastDy)
|
|
var px = rx
|
|
var py = ry
|
|
if not (isFinite(px) and isFinite(py)):
|
|
# Degenerate input (a NaN/Inf crept in from a scan): the ONE point we know
|
|
# is finite is our own position.
|
|
px = state.selfX
|
|
py = state.selfY
|
|
px = clamp(px, BotRadius, max(BotRadius, state.arenaWidth - BotRadius))
|
|
py = clamp(py, BotRadius, max(BotRadius, state.arenaHeight - BotRadius))
|
|
if not (isFinite(px)): px = BotRadius
|
|
if not (isFinite(py)): py = BotRadius
|
|
|
|
# Pending trace: the ring measurement AND the hidden activation this shot was
|
|
# built from, so onResult can train on EXACTLY those inputs.
|
|
let binIdx = waveBinForSpeed(bulletSpeed)
|
|
if binIdx >= 0:
|
|
let feat = g.waveFeatures(state, vx, vy, flight)
|
|
let slot = waveTraceSlot(state.tick, binIdx)
|
|
let resolveTick = state.tick + max(1, int(round(flight)))
|
|
g.traces[slot] = WaveTrace(fireTick: state.tick, binIdx: binIdx,
|
|
resolveTick: resolveTick,
|
|
measDist: measDist, measBear: measBear,
|
|
selfX: state.selfX, selfY: state.selfY,
|
|
feat: feat, hid: gh, alive: true)
|
|
if g.resolveFeat and resolveTick > state.tick and resolveTick notin g.refreshAt:
|
|
g.refreshAt.add slot
|
|
|
|
GunPrediction(x: px, y: py,
|
|
# The correction's magnitude IS the gun's intrinsic per-sample
|
|
# confidence.
|
|
confidence: hypot(g.lastDx, g.lastDy))
|
|
|
|
proc onResult*(g: var WaveElmGun, e: FeedbackEvent) =
|
|
# ── guard 1: only CONFIRMED hits carry a label ──────────────────────────────
|
|
# A miss says the aim was wrong, not where it was wrong, so it is not a
|
|
# sample. It is counted, never trained on.
|
|
if not e.hit:
|
|
inc g.missShots
|
|
return
|
|
|
|
let binIdx = if e.powerBin >= 0 and e.powerBin < len(vb.PowerBins): e.powerBin
|
|
else: waveBinForSpeed(bulletSpeed(e.bulletPower))
|
|
if binIdx < 0:
|
|
inc g.traceMisses
|
|
return
|
|
|
|
# ── guard 3: we need the ring measurement this shot was built from; without
|
|
# the trace there is no sample, and fabricating one would train the net on a
|
|
# measurement that never existed ─────────────────────────────────────────────
|
|
let slot = waveTraceSlot(e.fireTick, binIdx)
|
|
if not g.traces[slot].alive or g.traces[slot].fireTick != e.fireTick or
|
|
g.traces[slot].binIdx != binIdx:
|
|
inc g.traceMisses
|
|
return
|
|
|
|
if not (isFinite(e.actualX) and isFinite(e.actualY)):
|
|
inc g.rejectedShots
|
|
return
|
|
|
|
# ── THE LABEL: the BIAS of the RING RECONSTRUCTION. It is the offset between
|
|
# where the ring SAYS the enemy is (its measurement decoded into a position,
|
|
# `tr.measDist/bear` — the "base") and where it actually was, rotated into the
|
|
# world frame. Cartesian, not polar, because the feature map carries velocity
|
|
# and range but NO bearing term: a polar label would be unlearnable (the net
|
|
# could not tell which way the ring was pointing) and would collapse to its
|
|
# own mean. This is the same quantity the old directed gun learned, with the
|
|
# intercept replaced by the ring's reconstruction as the base. ───────────────
|
|
let tr = g.traces[slot]
|
|
let (bx, by) = (tr.selfX + tr.measDist * cos(tr.measBear),
|
|
tr.selfY + tr.measDist * sin(tr.measBear))
|
|
let dX = e.actualX - bx
|
|
let dY = e.actualY - by
|
|
if not (isFinite(dX) and isFinite(dY)):
|
|
inc g.rejectedShots
|
|
return
|
|
|
|
# ── guard 2: the bias must be physically plausible, measured in PIXELS ──────
|
|
var gate = (if g.maxResidual < 0.0: Inf else: g.maxResidual)
|
|
if g.gateAdapt > 0.0:
|
|
gate = clamp(g.gateAdapt * max(g.recentRms, 1.0),
|
|
g.maxResidual * 0.5, g.maxResidual * 4.0)
|
|
let rmag = hypot(dX, dY)
|
|
if rmag > gate:
|
|
inc g.rejectedShots
|
|
return
|
|
g.recentRms = max(rmag, g.recentRms * 0.95)
|
|
|
|
if not g.net.isSane(): g.net.softReset()
|
|
# Train on the ACTIVATION that was fired, not on a freshly recomputed one: with
|
|
# the RELM recurrence on, hidden(feat) now runs against a later h(t-1).
|
|
let lab = @[dX, dY]
|
|
if tr.hid.len == g.net.hiddenDim:
|
|
discard g.net.trainHidden(tr.hid, lab)
|
|
else:
|
|
discard g.net.train(tr.feat, lab)
|
|
g.traces[slot].alive = false
|
|
inc g.trainedShots
|