Files
SirStone f58d65d2e8 TMComposites gate: per-gun confidence faithful for 3 guns; no pair composes
Adds a per-sample intrinsic-confidence field (GunPrediction.confidence,
threaded through FeedbackEvent/VirtualBullet, populated by Pattern, DecayGF,
KNN, GuessFactor, Tsetlin, TMHorizon) and an offline recorder + analyzer that
reproduce the paper's Figure 2 per gun and its Eq-8 composite.

Measured on 3 held-out tr-bridge DrussGT battles (33k ticks, ~133k samples/gun):
- FAITHFUL: DecayGF (rho +0.133), KNN (+0.090), Pattern (+0.064, weak).
- GuessFactor is ANTI-faithful (rho -0.067); Tsetlin c_max is useless (0.001).
- No pair of guns specialises complementarily: the same gun dominates both
  high-confidence slices in every pair.
- Eq-8 alpha-normalised confidence-weighted composite: 18.41% vs Pattern
  20.45% (McNemar p=3.1e-126). Faithful-only variant 18.68%, still loses.
  Shuffle control passes weakly (composite > shuffle, p=4e-14) so ~0.7pp of
  competence is real but ~2pp short. Offline veto: design is dead.

See docs/tmcomposites_gate.md.
2026-09-25 22:04:39 +02:00

195 lines
8.1 KiB
Nim

## Guess-factor gun: statistical targeting via GF histogram.
## Bins: 31, ranging GF -1 (max CW escape) to +1 (max CCW escape).
## Learns from virtual bullet outcomes; queues one wave per (tick, power bin).
##
## Wave pairing is EXACT: a wave is stored in a ring slot keyed by
## (fireTick, powerBin) and `onResult` looks up the wave with the resolution
## event's `fireTick`, NOT the oldest queued wave. Under the shipped bmPath
## metric bullets leave the arena in non-FIFO order (the aim direction changes
## every tick), so FIFO pairing attached outcomes to the wrong wave. Measured
## over the committed DrussGT fixtures, FIFO mispaired 36.5% of resolutions
## (19.4% of which changed the recorded GF bin). See
## common_libs/tests/audit_wave_pairing.nim. The exact key is the same pattern
## guns/tsetlin.nim and guns/tm_selector.nim use.
import std/[math, strformat]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb # PowerBins: the four power bins the harness spawns
import guns/lead_forecast
const
GFBins = 31
GFPrior = 0.1
DebugGF* = false
WaveRingSlots = 1024
## (fireTick, powerBin) -> ring slot. Period = WaveRingSlots/bins = 256 ticks.
## A bmPath bullet leaves an 800x600 (Tank Royale max 1000x1000) arena within
## ~91 (128) ticks, so a live wave is never overwritten by a newer one.
## Identical sizing to tsetlin.nim's TM_TRACE_SLOTS.
type
Wave = object
fireX, fireY: float
fireBearing: float # atan2(enemyY-selfY, enemyX-selfX) at fire tick (rad)
fireTick: int # key part: tick the bullet was fired
bin: int # key part: power bin the bullet belonged to
alive: bool
# mea not stored — recomputed from FeedbackEvent.bulletPower at resolution time
GFGun* = object
bins: array[GFBins, float]
# Exact (fireTick, powerBin)-keyed ring. A resolved bullet is matched to the
# wave it actually fired, no matter how many other shots resolved first.
# Heap-backed (seq) so the gun value stays small on the stack — a 1024-slot
# inline array overflowed the default 8 MB stack in test_power_selection.
waves: seq[Wave]
waveStoredTick: array[len(vb.PowerBins), int] # last tick a wave was queued for this bin
vt: VelocityTracker # enemy velocity history (base selection)
cachedTick: int # last tick the velocity tracker was advanced
wavePushes*: int # total waves enqueued (== one per (tick, bin))
waveStarved*: int # onResult found no live wave for its (fireTick, bin)
# ── pairing integrity ───────────────────────────────────────────────────
waveResolved*: int # onResult calls that found their exact wave
waveMispaired*: int # ring-slot collision (impossible by design): the
# slot held a different fireTick
debugGraphics*: bool
proc initGFGun*(): GFGun =
result.debugGraphics = false
result.cachedTick = -1
result.waves = newSeq[Wave](WaveRingSlots)
for b in 0..<len(vb.PowerBins):
result.waveStoredTick[b] = -1
# Seed with a head-on prior: triangular bump at bin 15 (GF=0).
# Prevents the cold-start tie-break to GF=-1 (bin 0) that poisons early fitness.
let center = (GFBins - 1) div 2 # = 15
for i in 0..<GFBins:
let d = abs(i - center)
result.bins[i] = GFPrior + 0.5 / float(1 + d)
proc gfToIndex(gf: float): int {.inline.} =
clamp(int(round((gf + 1.0) * 0.5 * float(GFBins - 1))), 0, GFBins - 1)
proc indexToGF(idx: int): float {.inline.} =
float(idx) / float(GFBins - 1) * 2.0 - 1.0
proc peakBin*(g: GFGun): int =
var best = 0
for i in 1..<GFBins:
if g.bins[i] > g.bins[best]:
best = i
best
proc binForSpeed(spd: float): int {.inline.} =
## Map a virtual-bullet speed back to its power-bin index. All four bin speeds
## are exactly representable floats; the epsilon is belt-and-braces only.
for i in 0..<len(vb.PowerBins):
if abs(spd - bulletSpeed(vb.PowerBins[i])) < 1e-6:
return i
-1
proc binForPower(power: float): int {.inline.} =
## Map a FeedbackEvent.bulletPower back to its power-bin index.
for i in 0..<len(vb.PowerBins):
if abs(power - vb.PowerBins[i]) < 1e-6:
return i
-1
proc waveSlot(fireTick, binIdx: int): int {.inline.} =
## Exact (fireTick, powerBin) key -> ring slot (same scheme as tsetlin.nim).
((fireTick * len(vb.PowerBins)) + binIdx) mod WaveRingSlots
proc predict*(g: var GFGun, state: WorldState, bulletSpeed: float): GunPrediction =
if bulletSpeed <= 0.0:
return GunPrediction(x: state.enemyX, y: state.enemyY)
let mea = arcsin(clamp(8.0 / bulletSpeed, -1.0, 1.0))
# Base forecast: the GF learns the residual against a self-consistent base
# prediction, so the aim point sits at the radius the bullet actually travels
# to (see lead_forecast.nim for why this is required, and why the range is
# radial-fraction blended rather than a plain constant-velocity lead).
if state.tick != g.cachedTick:
g.cachedTick = state.tick
g.vt.observe(state)
let f = forecastRadialBlend(state, bulletSpeed, g.vt)
# Queue at most one wave per (tick, power bin). The fire site's extra predict()
# call for the selected bin lands on the same tick and reuses the queued wave.
let binIdx = binForSpeed(bulletSpeed)
if binIdx >= 0 and g.waveStoredTick[binIdx] != state.tick:
let slot = waveSlot(state.tick, binIdx)
g.waves[slot] = Wave(
fireX: state.selfX,
fireY: state.selfY,
fireBearing: f.bearing,
fireTick: state.tick,
bin: binIdx,
alive: true,
)
g.waveStoredTick[binIdx] = state.tick
inc g.wavePushes
let peak = g.peakBin()
let peakGF = indexToGF(peak)
let gfAngle = f.bearing + peakGF * mea
let px = state.selfX + cos(gfAngle) * f.dist
let py = state.selfY + sin(gfAngle) * f.dist
when DebugGF:
echo fmt"[gf-dbg] predict: peakGF={peakGF:.2f} peakBin={peak} mea={radToDeg(mea):.1f}° aimAngle={radToDeg(gfAngle):.1f}° tick={state.tick}"
GunPrediction(
x: clamp(px, BotRadius, state.arenaWidth - BotRadius),
y: clamp(py, BotRadius, state.arenaHeight - BotRadius),
# TMComposites Eq 4 analogue: the GF histogram is the class distribution over
# GF bins, so the class-sum max c_max is the peak bin's accumulated weight.
confidence: g.bins[peak],
)
proc onResult*(g: var GFGun, e: FeedbackEvent) =
## Called when a virtual bullet resolves. Look up the wave with this event's
## exact (fireTick, powerBin), compute the actual GF, and smooth-add it. A
## missing key is counted, never silently mislabelled.
let binIdx =
if e.powerBin >= 0 and e.powerBin < len(vb.PowerBins): e.powerBin
else: binForPower(e.bulletPower)
if binIdx < 0: return
let slot = waveSlot(e.fireTick, binIdx)
var w = addr g.waves[slot]
if not w.alive:
inc g.waveStarved
return
if w.fireTick != e.fireTick:
# Ring slot collision: impossible while the ring period exceeds max flight.
inc g.waveMispaired
inc g.waveStarved
return
inc g.waveResolved
# Recompute mea from the actual bullet power (correct per-bin, not the cached first-bin mea)
let speed = bulletSpeed(e.bulletPower)
let mea = arcsin(clamp(8.0 / speed, -1.0, 1.0))
# Compute actual bearing from fire position to where the enemy actually was
let actualDx = e.actualX - w.fireX
let actualDy = e.actualY - w.fireY
let actualBearing = arctan2(actualDy, actualDx)
var bearingDelta = actualBearing - w.fireBearing
# Normalize to [-PI, PI]
while bearingDelta > PI: bearingDelta -= 2.0*PI
while bearingDelta < -PI: bearingDelta += 2.0*PI
let gf = if mea > 1e-10: clamp(bearingDelta / mea, -1.0, 1.0) else: 0.0
let centerIdx = gfToIndex(gf)
when DebugGF:
echo fmt"[gf-dbg] onResult: fireBearing={radToDeg(w.fireBearing):.1f}° actualBearing={radToDeg(actualBearing):.1f}° delta={radToDeg(bearingDelta):.1f}° MEA={radToDeg(mea):.1f}° GF={gf:.2f} peakBin={centerIdx}"
# Triangular smoothing kernel over adjacent bins
for i in 0..<GFBins:
let dist = abs(i - centerIdx)
g.bins[i] += 1.0 / float(1 + dist)
w.alive = false