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