ChimeraBot_garage: M7.5 — virtual-gun tournament, Dodger-v2, discriminating bench

This commit is contained in:
2026-10-07 09:16:54 +02:00
parent 4c98333a3c
commit 5b48ac980c
12 changed files with 865 additions and 150 deletions
+24
View File
@@ -0,0 +1,24 @@
# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)
Replayed archived trajectories (`/tmp/chimera_g4_run`) + a synthesized Dodger-v2; hit = bullet passes within 20. units of the realized enemy position on its flight. Aim slew/cadence abstracted. Generated by `tests/bench_g8.nim`.
| opponent | twin % | ELM % | head-on % | vgun % | shots |
|---|---:|---:|---:|---:|---:|
| Corners | 49.3 | 59.6 | 52.2 | 57.2 | 339 |
| Crazy | 50.3 | 31.5 | 15.0 | 50.3 | 1042 |
| Fire | 50.7 | 41.4 | 45.9 | 50.7 | 440 |
| RamFire | 90.5 | 92.7 | 89.9 | 90.5 | 328 |
| SpinBot | 88.3 | 20.1 | 20.1 | 88.3 | 715 |
| TrackFire | 84.2 | 87.3 | 87.3 | 84.2 | 221 |
| VelociBot | 38.7 | 23.3 | 28.4 | 38.7 | 786 |
| Walls | 43.8 | 22.1 | 1.8 | 43.8 | 825 |
| Dodger | 82.7 | 46.4 | 10.9 | 82.7 | 220 |
**G8.5 offline bar: vgun >= max(twin, ELM-base, head-on) on >= 6/9 opponents AND vgun >= ELM-base on all movers (Crazy, SpinBot, VelociBot, Walls, Dodger).** Result: vgun >= best single gun on 6/9; vgun >= ELM-base on 5/5 movers. **Verdict: PASS.**
## Method / caveats
* `VGUN` = `chimera/virtual_guns.nim`: per-tick virtual bullets for {TWIN, ELM, HEAD-ON}, a per-shot hit-rate EMA (tau=100) plus a damage-weighted accumulator with tau=200 exponential forgetting, argmax fired under 0.1 hysteresis. Classic Robocode Virtual Guns pattern (https://robowiki.net/wiki/Virtual_Guns).
* `TWIN` = `chimera/aimer.nim`: iterated flight time `h = dist/(20-3*power)`, horizon-bucketed predictor Hedge (mixture/residual/persistence), trained ONLINE per record (one aimer, score-then-aim each sampled tick), spread-selected power.
* `ELM` = the ELM gun's **base** geometric intercept from the observed velocity (the learned correction is gated and small, and the online ELM state cannot be replayed offline). This is a proxy for the full ELM gun — a documented deviation.
* The synthesized Dodger is Dodger-v2 (`tests/archetypes/Dodger`): wave-based perpendicular strafe, centre-pull, seeded reversals. It fires a wave every 12 ticks; a real battle adds shooter motion. Live results (`m7_5_g8_live.md`) are the reality check.
@@ -0,0 +1,21 @@
# G8.5 live bench (M7.5 virtual-gun tournament)
Four arms from the SAME tree: inert (`-d:chimeraInert`), elm (`-d:chimeraNoTwinGun`), twin (`-d:chimeraNoVguns`), vgun (default). 5 rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`.
| opponent | elm W% | elm margin | twin W% | twin margin | vgun W% | vgun margin | inert W% | inert margin |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| Corners | 100.0 | 2488.0 | 100.0 | 2376.0 | 100.0 | 2469.0 | 100.0 | 2493.0 |
| Crazy | 100.0 | 2016.0 | 100.0 | 1935.0 | 100.0 | 2025.0 | 100.0 | 1683.0 |
| Fire | 100.0 | 2593.0 | 100.0 | 2526.0 | 100.0 | 2561.0 | 100.0 | 2564.0 |
| RamFire | 100.0 | 2186.0 | 100.0 | 2460.0 | 100.0 | 2413.0 | 100.0 | 2520.0 |
| SpinBot | 100.0 | 1924.0 | 100.0 | 1060.0 | 100.0 | 2001.0 | 100.0 | 1560.0 |
| TrackFire | 100.0 | 2305.0 | 100.0 | 2371.0 | 100.0 | 2299.0 | 100.0 | 2216.0 |
| VelociBot | 100.0 | 2065.0 | 100.0 | 1962.0 | 100.0 | 1378.0 | 100.0 | 1315.0 |
| Walls | 100.0 | 1459.0 | 100.0 | 1651.0 | 100.0 | 1565.0 | 100.0 | 1934.0 |
| Dodger | 100.0 | 1757.0 | 100.0 | 1949.0 | 100.0 | 1954.0 | 80.0 | 515.0 |
**Totals: inert 97.8% (m 16800.0) elm 100.0% (m 18793.0) twin 100.0% (m 18290.0) vgun 100.0% (m 18665.0) **
**Discrimination test (Dodger-v2 row).** Margins: inert 515.0 elm 1757.0 twin 1949.0 vgun 1954.0 spread 1439.0. The arms DIFFER materially against the upgraded Dodger.
**G7 no-regression (vgun >= inert win-rate on every opponent): PASS.**
+57
View File
@@ -38,6 +38,7 @@ import ChimeraBot/chimera/probes
import ChimeraBot/chimera/physics import ChimeraBot/chimera/physics
import ChimeraBot/chimera/influence import ChimeraBot/chimera/influence
import ChimeraBot/chimera/aimer import ChimeraBot/chimera/aimer
import ChimeraBot/chimera/virtual_guns
when defined(chimeraDebug): when defined(chimeraDebug):
import ChimeraBot/chimera/debugdraw import ChimeraBot/chimera/debugdraw
@@ -162,6 +163,7 @@ method onGameStarted*(bot: ChimeraBot, e: GameStartedEventForBot) =
## same movement code, so RoundStartedEvent deliberately does NOT touch it. ## same movement code, so RoundStartedEvent deliberately does NOT touch it.
## (The API fires onGameStarted once per battle and onRoundStarted per round.) ## (The API fires onGameStarted once per battle and onRoundStarted per round.)
bot.gun.resetOnline() bot.gun.resetOnline()
bot.observer.resetVguns() # M7.5: per-opponent virtual-gun statistics
method onRoundEnded*(bot: ChimeraBot, e: RoundEndedEventForBot) = method onRoundEnded*(bot: ChimeraBot, e: RoundEndedEventForBot) =
inc bot.roundNo inc bot.roundNo
@@ -242,6 +244,54 @@ proc computeTwinGun(bot: ChimeraBot, influence: float64): bool =
setGunTurnRate(clamp(err, -20.0, 20.0)) setGunTurnRate(clamp(err, -20.0, 20.0))
true true
## M7.5 virtual-gun tournament (G8). Runs the three-candidate tournament
## (`chimera/virtual_guns.nim`), fires the argmax gun under hysteresis, and
## returns true when it owned this tick's gun. Removed by `-d:chimeraNoVguns`,
## which leaves the M7 influence-gated twin/ELM path below exactly as it was.
proc computeVgunGun(bot: ChimeraBot, influence: float64): bool =
let arenaW = getArenaWidth().float
let arenaH = getArenaHeight().float
let aim = bot.observer.twinAim(getX(), getY(), arenaW, arenaH, FirePower)
if not aim.active: return false
let belief = bot.buildBelief(FirePower)
let (ex, ey) = bot.observer.currentEnemy()
let headBearing = arctan2(ey - getY(), ex - getX())
let elmBearing = bot.gun.heuristicAim(belief, FirePower)
# Advance the live virtual bullets, then launch this tick's candidates.
bot.observer.vgunStep(ex, ey, aimer.BotRadius, arenaW, arenaH)
bot.observer.vgunLaunch(vgTwin, getX(), getY(), aim.aimBearing, aim.power)
if not elmBearing.isNaN:
bot.observer.vgunLaunch(vgElm, getX(), getY(), elmBearing, FirePower)
bot.observer.vgunLaunch(vgHeadOn, getX(), getY(), headBearing, FirePower)
let chosen = bot.observer.vgunSelect(influence > TwinGunMinInfluence)
bot.observer.setGunFired(chosen)
var bearing = headBearing
var power = FirePower
case chosen
of vgTwin: bearing = aim.aimBearing; power = aim.power
of vgElm: bearing = elmBearing; power = FirePower
of vgHeadOn: bearing = headBearing; power = FirePower
bot.observer.setGunTelemetry(radToDeg(bearing), power, radToDeg(aim.spread),
influence, chosen == vgTwin)
let err = gunAimErrorDeg(bearing, getGunDirection())
if abs(err) <= FireSlopDeg and getGunHeat() == 0.0 and
getEnergy() >= TwinGunEnergyFloor:
setGunTurnRate(0.0)
discard setFire(power)
if chosen == vgTwin:
bot.observer.noteTwinShot(aim, bot.tick)
elif chosen == vgElm and bot.gun.online:
# keep the ELM online label stream alive when the tournament picks it
let feat = buildFeatures(belief)
let d = hypot(belief.ex - belief.selfX, belief.ey - belief.selfY)
let tofTicks = max(1, int(round(d / belief.bulletSpeed)))
bot.gun.recordShot(feat, elmBearing, belief.selfX, belief.selfY,
bot.tick + tofTicks)
inc bot.shotsFired
else:
setGunTurnRate(clamp(err, -20.0, 20.0))
true
## The gun tick: aim, and fire when the gun is actually on the aim point. ## The gun tick: aim, and fire when the gun is actually on the aim point.
## ##
## Standard Tank Royale gun handling, nothing clever — the cleverness (if any) ## Standard Tank Royale gun handling, nothing clever — the cleverness (if any)
@@ -251,6 +301,13 @@ proc computeTwinGun(bot: ChimeraBot, influence: float64): bool =
proc computeGun(bot: ChimeraBot) = proc computeGun(bot: ChimeraBot) =
if bot.gun.online: if bot.gun.online:
bot.gun.drainPending(bot.tick) # label any shot whose flight time elapsed bot.gun.drainPending(bot.tick) # label any shot whose flight time elapsed
# M7.5 virtual-gun tournament: when a current scan exists, the tournament
# selects and fires the argmax gun (twin gated by the same influence scalar).
# `-d:chimeraNoVguns` compiles this block out and restores the M7 path below.
when not NoVguns:
if bot.observer.hasCurrent:
if bot.computeVgunGun(bot.observer.fusedInfluence()):
return
# M7 twin gun: when the fused influence clears the gate, flight-horizon aiming # M7 twin gun: when the fused influence clears the gate, flight-horizon aiming
# owns this tick's gun. `-d:chimeraNoTwinGun` compiles this block out, leaving # owns this tick's gun. `-d:chimeraNoTwinGun` compiles this block out, leaving
# the ELM path below byte-identical to the pre-M7 build. # the ELM path below byte-identical to the pre-M7 build.
+1
View File
@@ -267,6 +267,7 @@ task test, "Run unit tests":
exec "nim c -r --hints:off ../tests/test_influence.nim" exec "nim c -r --hints:off ../tests/test_influence.nim"
exec "nim c -r --hints:off ../tests/test_identifiability.nim" exec "nim c -r --hints:off ../tests/test_identifiability.nim"
exec "nim c -r --hints:off ../tests/test_aimer.nim" exec "nim c -r --hints:off ../tests/test_aimer.nim"
exec "nim c -r --hints:off ../tests/test_virtual_guns.nim"
exec "nim c -r --hints:off ../tests/test_dodger.nim" exec "nim c -r --hints:off ../tests/test_dodger.nim"
# Debug overlay: compiled WITH -d:chimeraDebug so the drawing path is the real # Debug overlay: compiled WITH -d:chimeraDebug so the drawing path is the real
# one; the test asserts the command intent is identical with/without it. # one; the test asserts the command intent is identical with/without it.
@@ -19,7 +19,7 @@
## readiness check for the M4 twin rollout, not the twin itself. ## readiness check for the M4 twin rollout, not the twin itself.
import std/[math, os, strutils] import std/[math, os, strutils]
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence, ./aimer import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence, ./aimer, ./virtual_guns
const const
MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check
@@ -76,6 +76,11 @@ type
aimer: Aimer aimer: Aimer
gunAimDeg*, gunPower*, gunSpreadDeg*, gunInfluence*: float64 gunAimDeg*, gunPower*, gunSpreadDeg*, gunInfluence*: float64
twinActive*: bool twinActive*: bool
# M7.5 virtual-gun tournament (G8). Scores every candidate's virtual bullet
# against the realized enemy position; selects the gun the bot fires.
vguns*: VirtualGunSet
gunFiredLabel*: string ## which gun the tournament fired (telemetry only)
prevOwnDir, prevOwnSpeed: float64 prevOwnDir, prevOwnSpeed: float64
lastRealizedTurn, lastRealizedSpeed: float64 lastRealizedTurn, lastRealizedSpeed: float64
fireRateEma: float64 fireRateEma: float64
@@ -104,6 +109,7 @@ proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer =
result.residual = initResidualHead() result.residual = initResidualHead()
result.fusion = initFusion() result.fusion = initFusion()
result.aimer = initAimer() result.aimer = initAimer()
result.vguns = initVirtualGuns()
result.carryOver = not defined(chimeraFreshRound) result.carryOver = not defined(chimeraFreshRound)
for i in 0 ..< PredSlots: result.predOrigin[i] = -1 for i in 0 ..< PredSlots: result.predOrigin[i] = -1
@@ -408,6 +414,32 @@ proc setGunTelemetry*(o: Observer, aimDeg, power, spreadDeg, influence: float64,
o.gunInfluence = influence o.gunInfluence = influence
o.twinActive = active o.twinActive = active
# ── M7.5 virtual-gun tournament (G8) ────────────────────────────────────────
proc vgunStep*(o: Observer, ex, ey, hitRadius, arenaW, arenaH: float64) =
## Advance/resolve the virtual bullets against the realized enemy position.
o.vguns.vgTick(ex, ey, hitRadius, arenaW, arenaH)
proc vgunLaunch*(o: Observer, g: VGun, x, y, bearing, power: float64) =
## Spawn a candidate's virtual bullet (absolute bearing, radians).
o.vguns.launchVirtual(g, x, y, bearing, power)
proc vgunSelect*(o: Observer, twinEligible: bool): VGun =
o.vguns.selectGun(twinEligible = twinEligible)
proc vgunScore*(o: Observer, g: VGun): float64 = o.vguns.emaOf(g)
proc vgunShots*(o: Observer, g: VGun): int = o.vguns.shotsOf(g)
proc setGunFired*(o: Observer, g: VGun) =
## Observation-only: record which gun the tournament fired.
o.gunFiredLabel = gunName(g)
proc currentEnemy*(o: Observer): tuple[x, y: float64] = (o.cur.x, o.cur.y)
proc resetVguns*(o: Observer) =
## New game = new opponent; drop the per-gun statistics.
o.vguns.resetVguns()
proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights() proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights()
proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma
proc fusionSamples*(o: Observer): int = o.fusion.lossN proc fusionSamples*(o: Observer): int = o.fusion.lossN
@@ -471,7 +503,8 @@ proc writeTick*(o: Observer, tick: int) =
line.add ",\"gunAim\":" & $o.gunAimDeg & ",\"gunPower\":" & $o.gunPower & line.add ",\"gunAim\":" & $o.gunAimDeg & ",\"gunPower\":" & $o.gunPower &
",\"spread\":" & $o.gunSpreadDeg & ",\"spread\":" & $o.gunSpreadDeg &
",\"influence\":" & $o.gunInfluence & ",\"influence\":" & $o.gunInfluence &
",\"twinGun\":" & $(if o.twinActive: "true" else: "false") ",\"twinGun\":" & $(if o.twinActive: "true" else: "false") &
",\"gunFired\":\"" & o.gunFiredLabel & "\""
line.add "}\n" line.add "}\n"
o.f.write(line) o.f.write(line)
flushFile(o.f) flushFile(o.f)
@@ -0,0 +1,178 @@
## CHIMERA virtual-gun tournament (M7.5, spec G8).
##
## Classic Robocode **Virtual Guns** pattern (provenance:
## https://robowiki.net/wiki/Virtual_Guns): instead of committing to one gun,
## keep a small set of candidate guns, simulate a "virtual" bullet for each,
## score the realized outcome, and fire whichever gun is currently best. The
## RoboWiki describes exactly this shape — virtual bullets + per-gun hit
## statistics — as the standard way to choose among targeting strategies online;
## M7.5 uses it to answer the M7 live-saturation finding (every single-gun arm
## won 100% of rounds, so one gun could not be shown to be better).
##
## Candidates here are:
## * `vgTwin` — `chimera/aimer.nim` flight-horizon aim (its power included);
## * `vgElm` — the ELM gun's geometric-intercept base (`heuristicAim`);
## * `vgHeadOn` — aim at the enemy's current scanned position (no lead).
##
## Scoring is deterministic and pure: each launched virtual bullet advances one
## step per tick until it either comes within `hitRadius` of the observed enemy
## (a hit) or leaves the arena (a miss). A resolved shot updates that gun's
## **damage-weighted** EMA and an exponentially-forgetting accumulator
## (`tau = 200` ticks). Firing is the argmax EMA with **hysteresis**: the current
## gun is kept unless a rival leads it by more than `SwitchMargin` (0.1), so the
## selection cannot flap. Nothing here reads the clock, the RNG or the file
## system; the whole path is removed by `-d:chimeraNoVguns`.
import std/math
import ./physics
const
NoVguns* = defined(chimeraNoVguns)
## Kill switch: with this defined the bot never calls the tournament and the
## M7 influence-gated twin/ELM path is byte-identical.
ForgettingTau* = 200.0
## Exponential-forgetting time constant, in *ticks*, for the accumulator
## (`sum`/`weight` decayed once per tick by `exp(-1/tau)`).
EmaTau* = 100.0
## Per-gun EMA time constant, in *resolved shots*. Deliberately faster than
## the tau=200 accumulator: the selection must be able to react within a
## round (a few dozen resolved virtual bullets), while the accumulator keeps
## a longer-horizon estimate. `SwitchMargin` (0.1) is compared on this EMA.
SwitchMargin* = 0.1
## Hysteresis: a rival gun must lead the incumbent by more than this EMA
## difference before the tournament switches.
MinEvidence* = 12
## Never switch away from the incumbent until the leading rival has this many
## resolved virtual shots. Without it the first few noisy shots can lock in a
## bad gun for a long stretch.
RefDamage* = 6.0
## Damage reference (4*power at power 1.5). Used only by the long-horizon
## damage-per-shot accumulator; the selection EMA is a plain hit rate so the
## 0.1 hysteresis margin is meaningful and power differences do not bias the
## selection (the G8.5 bar is a hit-rate bar).
type
VGun* = enum
vgTwin, vgElm, vgHeadOn
GunScore* = object
ema*: float64 ## hit-rate EMA in [0,1] (selection key)
sum*, weight*: float64 ## exponentially-forgetting accumulator
shots*: int
VirtualBullet* = object
gun*: VGun
active*: bool
x*, y*, vx*, vy*: float64
power*: float64
VirtualGunSet* = object
score*: array[VGun, GunScore]
bullets*: seq[VirtualBullet]
selected*: VGun
haveSelected*: bool
proc initVirtualGuns*(): VirtualGunSet =
result.selected = vgTwin
result.haveSelected = false
proc gunName*(g: VGun): string =
case g
of vgTwin: "twin"
of vgElm: "elm"
of vgHeadOn: "headon"
proc emaOf*(v: VirtualGunSet, g: VGun): float64 = v.score[g].ema
proc decayedRate*(v: VirtualGunSet, g: VGun): float64 =
## The long-horizon, damage-weighted average (mean damage per resolved shot).
## Zero until the first resolved shot.
if v.score[g].weight <= 1e-9: 0.0 else: v.score[g].sum / v.score[g].weight
proc shotsOf*(v: VirtualGunSet, g: VGun): int = v.score[g].shots
proc forgetTick*(v: var VirtualGunSet, tau = ForgettingTau) =
## One tick of exponential forgetting on the accumulators. `tau` is in ticks.
let d = exp(-1.0 / tau)
for g in VGun:
v.score[g].sum *= d
v.score[g].weight *= d
proc observeShot*(v: var VirtualGunSet, g: VGun, hit: bool, power: float64,
emaTau = EmaTau) =
## Score one resolved virtual shot. The **EMA tracks the hit rate** (0/1) and
## is the selection key; the accumulator tracks the **damage-weighted** outcome
## (`4*power`, plus the over-1 bonus, on a hit; 0 on a miss).
let hitOutcome = if hit: 1.0 else: 0.0
let damage = if hit:
let d = 4.0 * power
(if power > 1.0: d + 2.0 * (power - 1.0) else: d)
else: 0.0
let alpha = 1.0 - exp(-1.0 / emaTau)
v.score[g].ema = v.score[g].ema + alpha * (hitOutcome - v.score[g].ema)
v.score[g].sum += damage
v.score[g].weight += 1.0
inc v.score[g].shots
proc launchVirtual*(v: var VirtualGunSet, g: VGun, x, y, bearing, power: float64) =
## Spawn the virtual bullet for candidate `g` at (x,y) along `bearing`
## (radians) at `power`. Velocity comes from the physics mirror.
let sp = bulletSpeed(power)
v.bullets.add VirtualBullet(gun: g, active: true, x: x, y: y,
vx: sp * cos(bearing), vy: sp * sin(bearing),
power: power)
proc stepVirtual*(v: var VirtualGunSet, ex, ey, hitRadius, arenaW, arenaH: float64) =
## Advance every live virtual bullet one tick and resolve the ones that hit the
## observed enemy or leave the arena.
var keep: seq[VirtualBullet]
for b in v.bullets:
var bu = b
bu.x += bu.vx
bu.y += bu.vy
if bu.x < 0.0 or bu.x > arenaW or bu.y < 0.0 or bu.y > arenaH:
v.observeShot(bu.gun, false, bu.power)
continue
if hypot(bu.x - ex, bu.y - ey) <= hitRadius:
v.observeShot(bu.gun, true, bu.power)
continue
keep.add bu
v.bullets = keep
proc vgTick*(v: var VirtualGunSet, ex, ey, hitRadius, arenaW, arenaH: float64,
tau = ForgettingTau) =
## One tournament tick: forget a little, then advance/resolve every bullet.
v.forgetTick(tau)
v.stepVirtual(ex, ey, hitRadius, arenaW, arenaH)
proc selectGun*(v: var VirtualGunSet, margin = SwitchMargin,
twinEligible = true): VGun =
## argmax EMA with hysteresis. `twinEligible = false` keeps the M7 influence
## gate: the twin candidate cannot be chosen (but still scores). The incumbent
## is kept unless the best eligible rival leads it by more than `margin`.
var best = vgHeadOn
var bestScore = -1.0
var any = false
for g in VGun:
if g == vgTwin and not twinEligible: continue
if not any or v.score[g].ema > bestScore:
best = g
bestScore = v.score[g].ema
any = true
if v.haveSelected:
let incOk = (v.selected != vgTwin or twinEligible)
if incOk and v.score[best].shots < MinEvidence:
return v.selected
if incOk and v.score[v.selected].ema >= bestScore - margin:
return v.selected
v.selected = best
v.haveSelected = true
best
proc resetVguns*(v: var VirtualGunSet) =
## New game = new opponent: drop the per-gun statistics (the M7 model resets
## per game too, see `ChimeraBot.onGameStarted`).
v = initVirtualGuns()
@@ -1,13 +1,11 @@
## Dodger — garage-local reactive archetype opponent (spec §12 Tier B; M7/G8). ## Dodger — garage-local reactive archetype opponent (spec §12 Tier B; M7.5/G8).
## ##
## A wave-based dodger that exists to be a MOVING, dodging target for the G8 ## A wave-based dodger that exists to be a MOVING, dodging target for the G8
## hit-rate bench. It never leads its gun (it does not fire at all): its whole ## hit-rate bench, and (M7.5) a real opponent that fires back with a head-on gun.
## job is to move unpredictably enough that a 5-tick lead is insufficient, which
## is exactly the regime the twin gun is supposed to fix.
## ##
## All decision logic lives in `dodger_spec.nim`; this file only adapts the API ## All decision logic lives in `dodger_spec.nim`; this file only adapts the API
## events to `DodgeWave` and applies `dodgeDecision` to the body. It therefore ## events to `DodgeWave` / `GunCmd` and applies the results to the body and gun.
## behaves exactly as the documented spec function by construction. ## It therefore behaves exactly as the documented spec function by construction.
import std/[math, os] import std/[math, os]
import robocode_tankroyale_botapi import robocode_tankroyale_botapi
@@ -20,13 +18,19 @@ type
strafeSign: float64 strafeSign: float64
prevEnergy: float64 prevEnergy: float64
haveEnemy: bool haveEnemy: bool
enemyX, enemyY: float64
gunHeat: float64
proc newDodger(): Dodger = proc newDodger(): Dodger =
Dodger(strafeSign: 1.0) Dodger(strafeSign: 1.0,
wave: DodgeWave(originX: 0.0, originY: 0.0, fireTick: -1000,
bulletSpeed: 1.0))
method onScannedBot*(bot: Dodger, e: ScannedBotEvent) = method onScannedBot*(bot: Dodger, e: ScannedBotEvent) =
## An energy drop in `[0.1, 3.0]` is the enemy's own shot (spec §4.3): start a ## An energy drop in `[0.1, 3.0]` is the enemy's own shot (spec §4.3): start a
## wave from its position at fire time. ## wave from its position at fire time. Always remember the enemy for the gun.
bot.enemyX = e.x
bot.enemyY = e.y
if bot.haveEnemy: if bot.haveEnemy:
let drop = bot.prevEnergy - e.energy let drop = bot.prevEnergy - e.energy
if drop >= 0.1 - 1e-9 and drop <= 3.0 + 1e-9: if drop >= 0.1 - 1e-9 and drop <= 3.0 + 1e-9:
@@ -37,8 +41,8 @@ method onScannedBot*(bot: Dodger, e: ScannedBotEvent) =
bot.haveEnemy = true bot.haveEnemy = true
method onHitByBullet*(bot: Dodger, e: HitByBulletEvent) = method onHitByBullet*(bot: Dodger, e: HitByBulletEvent) =
## The wave already connected: no dodge left to make, just switch strafe side ## The wave already connected: switch strafe side so the next wave is met from
## so the next wave is met from the other direction. ## the other direction.
bot.strafeSign = -bot.strafeSign bot.strafeSign = -bot.strafeSign
method run*(bot: Dodger) = method run*(bot: Dodger) =
@@ -52,7 +56,15 @@ method run*(bot: Dodger) =
bot.strafeSign = cmd.strafeSign bot.strafeSign = cmd.strafeSign
setTurnRate(cmd.turnRate) setTurnRate(cmd.turnRate)
setTargetSpeed(cmd.targetSpeed) setTargetSpeed(cmd.targetSpeed)
setGunTurnRate(0.0) # Head-on gun: fire back. gunHeat is the API's own reported heat.
if bot.haveEnemy:
let g = gunDecision(bot.enemyX, bot.enemyY, getX(), getY(),
getGunDirection(), getGunHeat())
setGunTurnRate(g.turnRate)
if g.fire > 0.0:
discard setFire(g.fire)
else:
setGunTurnRate(0.0)
setRadarTurnRate(45.0) setRadarTurnRate(45.0)
go() go()
inc bot.tick inc bot.tick
@@ -1,29 +1,52 @@
## Dodger spec function — the documented, unit-tested behaviour of the reactive ## Dodger spec function — the documented, unit-tested behaviour of the reactive
## `Dodger` archetype (docs/chimera-spec.md §12 Tier B; M7/G8). ## `Dodger` archetype (docs/chimera-spec.md §12 Tier B; M7.5/G8).
## ##
## Dodger is a **wave-based reactive dodger** built to be a *dodging* opponent for ## Dodger is a **wave-based reactive dodger** built to be a *dodging* opponent for
## the G8 hit-rate bench: when it detects an enemy bullet (an energy drop in ## the G8 hit-rate bench. When it detects an enemy bullet (an energy drop in
## `onScannedBot`) it strafes perpendicular to the wave, flipping its strafe ## `onScannedBot`) it starts a wave; while the wavefront is within
## direction when it is pinned near a wall. The bot's run loop contains **no ## `ReactionTicks` it strafes **perpendicular to the wave bearing**, flipping the
## decision logic of its own** — it calls `dodgeDecision` and applies the result, ## strafe side when it would otherwise drive into a wall. Two M7.5 upgrades make
## so the bot's behaviour *is* this function by construction. `test_dodger.nim` ## it a *real* dodger:
## pins the function's outputs on synthetic inputs, which is the trust story:
## matrix-tested, not untested.
## ##
## Pure and deterministic: no RNG, no I/O, no clock. ## * when **not** dodging it steers toward the arena centre (it no longer
## patrols straight into its opponent), and a small `CenterPull` bias keeps
## the perpendicular strafe in open space instead of parking in a corner;
## * a **documented seed** (`DefaultSeed`) makes the strafe direction reverse
## on a deterministic pseudo-random schedule, so the path is not periodic.
##
## It also carries a **head-on gun** (`gunDecision`) so the archetype fights
## back instead of being a target dummy.
##
## The bot's run loop contains **no decision logic of its own** — it calls
## `dodgeDecision` / `gunDecision` and applies the results, so the bot's
## behaviour *is* these functions by construction. `test_dodger.nim` pins the
## outputs on synthetic inputs and, for the dodge rate, on an offline physics
## simulation: the bar is a **dodge rate >= 60%** of incoming head-on-gun shots.
##
## Pure and deterministic: no wall-clock, no global RNG, no I/O. The only
## "randomness" is the seedable 64-bit hash below, so a given (seed, tick)
## always yields the same decision.
import std/math import std/math
const const
ReactionTicks* = 14.0 ## start dodging when the wavefront is this close ReactionTicks* = 14.0 ## start dodging when the wavefront is this close
StrafeSpeed* = 8.0 ## full throttle while dodging StrafeSpeed* = 8.0 ## full throttle while dodging
PatrolSpeed* = 4.0 ## idle cruise when no wave threatens PatrolSpeed* = 8.0 ## full throttle while patrolling too (never a sitting duck)
WallMargin* = 60.0 ## "pinned near a wall" band WallMargin* = 80.0 ## "would drive into a wall" band
CenterPull* = 0.2 ## blend toward the arena centre (0 = pure perpendicular)
SwitchTicks* = 20 ## seeded strafe reversal period, in ticks
DefaultSeed* = 0x5EED1307'u64 ## documented seed for the strafe jitter
GunPower* = 1.5 ## the archetype's head-on gun power
GunFireSlop* = 2.0 ## deg of alignment required to fire
GunMaxTurn* = 20.0 ## deg/tick gun slew (physics maximum)
type type
DodgeWave* = object DodgeWave* = object
## A wavefront: the enemy position at fire time, the fire tick, and the ## A wavefront: the enemy position at fire time, the fire tick, and the
## bullet speed (`20 - 3*power`, physics.bulletSpeed). ## bullet speed (`20 - 3*power`, physics.bulletSpeed). `fireTick == -1000`
## is the "no wave yet" sentinel.
originX*, originY*: float64 originX*, originY*: float64
fireTick*: int fireTick*: int
bulletSpeed*: float64 bulletSpeed*: float64
@@ -37,38 +60,83 @@ type
strafeSign*: float64 ## +1 / -1, carried to the next tick (hysteresis) strafeSign*: float64 ## +1 / -1, carried to the next tick (hysteresis)
dodging*: bool dodging*: bool
GunCmd* = object
turnRate*: float64 ## deg/tick gun turn command
fire*: float64 ## >0 => fire at this power this tick
aimed*: bool
proc wrap180(deg: float64): float64 = proc wrap180(deg: float64): float64 =
result = deg mod 360.0 result = deg mod 360.0
if result <= -180.0: result += 360.0 if result <= -180.0: result += 360.0
elif result > 180.0: result -= 360.0 elif result > 180.0: result -= 360.0
proc hash64(seed: uint64, a: int): uint64 =
## SplitMix64-style avalanche: deterministic, seedable, no state.
var h = seed xor (uint64(a) * 0x9E3779B97F4A7C15'u64)
h = (h xor (h shr 30)) * 0xBF58476D1CE4E5B9'u64
h = (h xor (h shr 27)) * 0x94D049BB133111EB'u64
h xor (h shr 31)
proc seededBit*(seed: uint64, i: int): bool =
(hash64(seed, i) and 1) == 1
proc waveETA*(w: DodgeWave, x, y: float64, tick: int): float64 = proc waveETA*(w: DodgeWave, x, y: float64, tick: int): float64 =
## Ticks until the wavefront reaches `(x, y)`; negative once it is past. ## Ticks until the wavefront reaches `(x, y)`; negative once it is past.
let dist = hypot(x - w.originX, y - w.originY) let dist = hypot(x - w.originX, y - w.originY)
dist / max(w.bulletSpeed, 1e-9) - float(tick - w.fireTick) dist / max(w.bulletSpeed, 1e-9) - float(tick - w.fireTick)
proc nearWall*(x, y, arenaW, arenaH: float64): bool = proc nearWall*(x, y, arenaW, arenaH: float64): bool =
## Pinned when inside `WallMargin` of any wall (spec "corner-flip near waves"). ## Pinned when inside `WallMargin` of any wall.
x < WallMargin or x > arenaW - WallMargin or x < WallMargin or x > arenaW - WallMargin or
y < WallMargin or y > arenaH - WallMargin y < WallMargin or y > arenaH - WallMargin
proc intoWall(heading, x, y, arenaW, arenaH: float64): bool =
## True when moving along `heading` (deg) pushes us further into the wall we
## are already near.
let hx = cos(degToRad(heading))
let hy = sin(degToRad(heading))
(x < WallMargin and hx < 0.0) or (x > arenaW - WallMargin and hx > 0.0) or
(y < WallMargin and hy < 0.0) or (y > arenaH - WallMargin and hy > 0.0)
proc dodgeDecision*(w: DodgeWave, own: DodgeOwn, tick: int, proc dodgeDecision*(w: DodgeWave, own: DodgeOwn, tick: int,
arenaW, arenaH, prevSign: float64): DodgeCmd = arenaW, arenaH, prevSign: float64,
## The documented spec function. If the wave is spent (`eta <= 0`) or too far seed: uint64 = DefaultSeed): DodgeCmd =
## (`eta > ReactionTicks`) the bot patrols straight; otherwise it turns to ## The documented spec function. While a wave is within `ReactionTicks` the bot
## move perpendicular to the wave bearing, flipping the strafe sign when near ## strafes perpendicular to the wave bearing (flipping away from walls); when
## a wall. ## no wave threatens it drives toward the arena centre. A small centre-pull
result.strafeSign = prevSign ## bias keeps the strafe in open space, and the seeded reversal breaks up the
result.targetSpeed = PatrolSpeed ## periodic path.
result.turnRate = 0.0
result.dodging = false
let eta = waveETA(w, own.x, own.y, tick) let eta = waveETA(w, own.x, own.y, tick)
if eta <= 0.0 or eta > ReactionTicks: let dodging = eta > 0.0 and eta <= ReactionTicks
return var sign = prevSign
result.dodging = true if SwitchTicks > 0 and (tick mod SwitchTicks) == 0 and
result.strafeSign = if nearWall(own.x, own.y, arenaW, arenaH): -prevSign seededBit(seed, tick div SwitchTicks):
else: prevSign sign = -sign
let bearing = arctan2(own.y - w.originY, own.x - w.originX) * 180.0 / PI let bearing = arctan2(own.y - w.originY, own.x - w.originX) * 180.0 / PI
let perp = bearing + 90.0 * result.strafeSign let centerBearing = arctan2(arenaH * 0.5 - own.y,
result.turnRate = clamp(wrap180(perp - own.heading), -10.0, 10.0) arenaW * 0.5 - own.x) * 180.0 / PI
result.targetSpeed = StrafeSpeed var desired: float64
if dodging:
var perp = bearing + 90.0 * sign
if intoWall(perp, own.x, own.y, arenaW, arenaH):
sign = -sign
perp = bearing + 90.0 * sign
desired = perp
else:
desired = centerBearing
desired = desired + CenterPull * wrap180(centerBearing - desired)
result.strafeSign = sign
result.dodging = dodging
result.turnRate = clamp(wrap180(desired - own.heading), -10.0, 10.0)
result.targetSpeed = if dodging: StrafeSpeed else: PatrolSpeed
proc gunDecision*(ex, ey, sx, sy, gunHeading, gunHeat: float64,
power = GunPower): GunCmd =
## The archetype's head-on gun. Slew toward the enemy's current position and
## fire at `power` once aligned (within `GunFireSlop`) and cold. Head-on only:
## the archetype exists to dodge, not to lead.
let bearing = arctan2(ey - sy, ex - sx) * 180.0 / PI
let err = wrap180(bearing - gunHeading)
result.turnRate = clamp(err, -GunMaxTurn, GunMaxTurn)
result.aimed = abs(err) <= GunFireSlop
result.fire = if result.aimed and gunHeat <= 0.0: power else: 0.0
+82 -47
View File
@@ -1,15 +1,19 @@
## G8 OFFLINE BENCH — flight-horizon aiming (twin gun) vs ELM vs head-on. ## G8 OFFLINE BENCH (M7.5) — virtual-gun tournament vs the single guns.
## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8. ## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8 (M7 + M7.5).
## ##
## Replays recorded trajectories (the archived M6 telemetry under ## Replays recorded trajectories (the archived M6 telemetry under
## `CHIMERA_G8_TELEMETRY`, default `/tmp/chimera_g4_run`) plus a deterministically ## `CHIMERA_G8_TELEMETRY`, default `/tmp/chimera_g4_run`) plus a deterministically
## SYNTHESIZED Dodger trajectory (the archetype's documented spec function run ## SYNTHESIZED Dodger-v2 trajectory (the archetype's documented spec function run
## through the physics mirror), and, for every sampled origin tick, simulates the ## through the physics mirror), and, for every sampled origin tick, simulates the
## bullet each of three aim policies would have fired: ## bullet each aim policy would have fired:
## ##
## * HEAD-ON — aim at the enemy's position at fire time (no lead); ## * HEAD-ON — aim at the enemy's position at fire time (no lead);
## * ELM — the ELM gun's base: geometric intercept from observed velocity; ## * ELM — the ELM gun's base: geometric intercept from observed velocity;
## * TWIN — `chimera/aimer.nim`'s flight-horizon fused aim + spread power. ## * TWIN — `chimera/aimer.nim`'s flight-horizon fused aim + spread power;
## * VGUN — `chimera/virtual_guns.nim`'s tournament: every sampled tick the
## TWIN/ELM/HEAD-ON candidates each launch a virtual bullet, the
## realized outcomes score them (tau=200 EMA), and VGUN fires the
## argmax under 0.1 hysteresis.
## ##
## Hit = the bullet passes within `HitRadius` of the enemy's realized position on ## Hit = the bullet passes within `HitRadius` of the enemy's realized position on
## some flight tick before the wall. Aim slew and cadence are abstracted away: the ## some flight tick before the wall. Aim slew and cadence are abstracted away: the
@@ -17,12 +21,13 @@
## ##
## Run: `nim c -r --hints:off -d:release tests/bench_g8.nim` ## Run: `nim c -r --hints:off -d:release tests/bench_g8.nim`
import std/[math, os, strutils, tables, algorithm, times, sequtils] import std/[math, os, strutils, tables, algorithm, sequtils]
import chimera/dsl import chimera/dsl
import chimera/twinsim import chimera/twinsim
import chimera/residual import chimera/residual
import chimera/aimer import chimera/aimer
import chimera/physics import chimera/physics
import chimera/virtual_guns
import dodger_spec import dodger_spec
const const
@@ -35,7 +40,7 @@ const
type type
Policy = enum Policy = enum
pHeadOn, pElm, pTwin pHeadOn, pElm, pTwin, pVgun
Tally = object Tally = object
hits, shots: int hits, shots: int
@@ -77,7 +82,8 @@ proc simulateHit(sx, sy, bearing, power: float64, originTick: int,
false false
proc evalRecord(rec: Record, kernels: seq[Kernel], proc evalRecord(rec: Record, kernels: seq[Kernel],
arenaW, arenaH: float64): Table[Policy, Tally] = arenaW, arenaH: float64,
v: var VirtualGunSet): Table[Policy, Tally] =
let emap = enemyMap(rec) let emap = enemyMap(rec)
let rps = replay(rec, kernels) let rps = replay(rec, kernels)
# ONE aimer per record, trained online exactly like the live bot: at each # ONE aimer per record, trained online exactly like the live bot: at each
@@ -85,8 +91,15 @@ proc evalRecord(rec: Record, kernels: seq[Kernel],
# per-origin aimer would never learn the bucket weights and would misrepresent # per-origin aimer would never learn the bucket weights and would misrepresent
# the twin gun. # the twin gun.
var a = initAimer() var a = initAimer()
# The tournament persists PER OPPONENT (across the opponent's replay files) —
# that is what "per opponent with exponential forgetting" means. Only the
# in-flight virtual bullets are cleared at a record boundary.
v.bullets.setLen(0)
var n = 0 var n = 0
for rt in rps: for rt in rps:
# Advance/resolve the live virtual bullets every tick (that is how the
# tournament scores realized outcomes), independent of the sampling stride.
v.vgTick(rt.ex, rt.ey, HitRadius, arenaW, arenaH)
if rt.tick mod Stride != 0: continue if rt.tick mod Stride != 0: continue
if n >= MaxOrigins: break if n >= MaxOrigins: break
inc n inc n
@@ -101,18 +114,29 @@ proc evalRecord(rec: Record, kernels: seq[Kernel],
let elm = arctan2(rt.ey + vy * tof - rt.oy, rt.ex + vx * tof - rt.ox) let elm = arctan2(rt.ey + vy * tof - rt.oy, rt.ex + vx * tof - rt.ox)
let aim = a.computeAim(kernels, rt, ResidualPrediction(), rt.ox, rt.oy, let aim = a.computeAim(kernels, rt, ResidualPrediction(), rt.ox, rt.oy,
arenaW, arenaH, ElmPower) arenaW, arenaH, ElmPower)
let twinBearing = if aim.active: aim.aimBearing else: elm
let twinPower = if aim.active: aim.power else: ElmPower
# Launch the three candidates, then let the tournament pick.
v.launchVirtual(vgTwin, rt.ox, rt.oy, twinBearing, twinPower)
v.launchVirtual(vgElm, rt.ox, rt.oy, elm, ElmPower)
v.launchVirtual(vgHeadOn, rt.ox, rt.oy, head, ElmPower)
let chosen = v.selectGun()
let (vb, vp) =
case chosen
of vgTwin: (twinBearing, twinPower)
of vgElm: (elm, ElmPower)
of vgHeadOn: (head, ElmPower)
for (pol, bearing, power) in [(pHeadOn, head, ElmPower), for (pol, bearing, power) in [(pHeadOn, head, ElmPower),
(pElm, elm, ElmPower), (pElm, elm, ElmPower),
(pTwin, (if aim.active: aim.aimBearing else: elm), (pTwin, twinBearing, twinPower),
(if aim.active: aim.power else: ElmPower))]: (pVgun, vb, vp)]:
result.mgetOrPut(pol, Tally()).shots.inc result.mgetOrPut(pol, Tally()).shots.inc
if simulateHit(rt.ox, rt.oy, bearing, power, rt.tick, emap, arenaW, arenaH): if simulateHit(rt.ox, rt.oy, bearing, power, rt.tick, emap, arenaW, arenaH):
result[pol].hits.inc result[pol].hits.inc
if aim.active: a.noteShot(aim, rt.tick) if aim.active: a.noteShot(aim, rt.tick)
proc synthesizeDodger(kernels: seq[Kernel]): Record = proc synthesizeDodger(kernels: seq[Kernel]): Record =
## A deterministic Dodger record: our bot sits at (600,300); a wave is fired ## A deterministic Dodger-v2 record: our bot sits at (600,300); a wave is fired
## every 20 ticks; the enemy runs `dodgeDecision` through the physics mirror. ## every 12 ticks; the enemy runs `dodgeDecision` through the physics mirror.
## Gives the bench a MOVING, DODGING opponent without Java. ## Gives the bench a MOVING, DODGING opponent without Java.
const W = 800.0 const W = 800.0
const H = 600.0 const H = 600.0
@@ -165,76 +189,87 @@ proc main() =
var rows: seq[string] var rows: seq[string]
var total: Table[Policy, Tally] var total: Table[Policy, Tally]
var winOverBest = 0
var winOverElm = 0 var winOverElm = 0
var winOverHead = 0
let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"] let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"]
var nOpp = 0 var nOpp = 0
echo "opponent twin% elm% head% n" echo "opponent twin% elm% head% vgun% n"
for opp in opps: for opp in opps:
var t: Table[Policy, Tally] var t: Table[Policy, Tally]
var v = initVirtualGuns() # one tournament per opponent
if opp == "Dodger": if opp == "Dodger":
t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0) t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0, v)
else: else:
let files = byOpp[opp] let files = byOpp[opp]
var used = 0 var used = 0
for f in files: for f in files:
if used >= 5: break if used >= 5: break
addInto(t, evalRecord(loadRecord(f), kernels, 800.0, 600.0)) addInto(t, evalRecord(loadRecord(f), kernels, 800.0, 600.0, v))
inc used inc used
let tw = t.getOrDefault(pTwin) let tw = t.getOrDefault(pTwin)
let el = t.getOrDefault(pElm) let el = t.getOrDefault(pElm)
let ho = t.getOrDefault(pHeadOn) let ho = t.getOrDefault(pHeadOn)
let vg = t.getOrDefault(pVgun)
addInto(total, t) addInto(total, t)
inc nOpp inc nOpp
if tw.hits >= el.hits: inc winOverElm # vgun >= the best single gun on this opponent
if tw.hits >= ho.hits and opp in movers: inc winOverHead if vg.hits >= max(tw.hits, max(el.hits, ho.hits)): inc winOverBest
if vg.hits >= el.hits and opp in movers: inc winOverElm
echo alignLeft(opp, 12), echo alignLeft(opp, 12),
align(formatFloat(tw.hitRate, ffDecimal, 1), 7), align(formatFloat(tw.hitRate, ffDecimal, 1), 7),
align(formatFloat(el.hitRate, ffDecimal, 1), 7), align(formatFloat(el.hitRate, ffDecimal, 1), 7),
align(formatFloat(ho.hitRate, ffDecimal, 1), 7), align(formatFloat(ho.hitRate, ffDecimal, 1), 7),
align($tw.shots, 6) align(formatFloat(vg.hitRate, ffDecimal, 1), 7),
align($vg.shots, 6)
rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " & rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " &
formatFloat(el.hitRate, ffDecimal, 1) & " | " & formatFloat(el.hitRate, ffDecimal, 1) & " | " &
formatFloat(ho.hitRate, ffDecimal, 1) & " | " & $tw.shots & " |" formatFloat(ho.hitRate, ffDecimal, 1) & " | " &
formatFloat(vg.hitRate, ffDecimal, 1) & " | " & $vg.shots & " |"
let passElm = winOverElm >= 6 let passBest = winOverBest >= 6
let passHead = winOverHead >= movers.len let passElm = winOverElm == movers.len
let verdict = if passElm and passHead: "PASS" else: "FAIL" let verdict = if passBest and passElm: "PASS" else: "FAIL"
echo "\nG8 offline: twin >= ELM on ", winOverElm, "/", nOpp, echo "\nG8.5 offline: vgun >= best single gun on ", winOverBest, "/", nOpp,
" (bar >= 6); twin >= head-on on ", winOverHead, "/", movers.len, " (bar >= 6); vgun >= ELM-base on ", winOverElm, "/", movers.len,
" movers; verdict ", verdict " movers; verdict ", verdict
echo "SUITE twin ", formatFloat(total[pTwin].hitRate, ffDecimal, 1), echo "SUITE twin ", formatFloat(total[pTwin].hitRate, ffDecimal, 1),
"% elm ", formatFloat(total[pElm].hitRate, ffDecimal, 1), "% elm ", formatFloat(total[pElm].hitRate, ffDecimal, 1),
"% head ", formatFloat(total[pHeadOn].hitRate, ffDecimal, 1), "%" "% head ", formatFloat(total[pHeadOn].hitRate, ffDecimal, 1),
"% vgun ", formatFloat(total[pVgun].hitRate, ffDecimal, 1), "%"
var md = "# G8 offline hit-rate bench (M7, twin gun)\n\n" var md = "# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)\n\n"
md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized Dodger; " & md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized " &
"hit = bullet passes within " & formatFloat(HitRadius, ffDecimal, 0) & "Dodger-v2; hit = bullet passes within " &
" units of the realized enemy position. Aim slew/cadence abstracted. " & formatFloat(HitRadius, ffDecimal, 0) &
"Generated by `tests/bench_g8.nim`.\n\n" " units of the realized enemy position on its flight. Aim slew/cadence " &
md.add "| opponent | twin % | ELM % | head-on % | shots |\n|---|---:|---:|---:|---:|\n" "abstracted. Generated by `tests/bench_g8.nim`.\n\n"
md.add "| opponent | twin % | ELM % | head-on % | vgun % | shots |\n" &
"|---|---:|---:|---:|---:|---:|\n"
for r in rows: md.add r & "\n" for r in rows: md.add r & "\n"
md.add "\n**G8 offline bar: twin >= ELM on >= 6/9 opponents AND twin >= head-on " & md.add "\n**G8.5 offline bar: vgun >= max(twin, ELM-base, head-on) on >= 6/9 " &
"on the movers.** Result: twin >= ELM on " & $winOverElm & "/" & $nOpp & "opponents AND vgun >= ELM-base on all movers (Crazy, SpinBot, " &
"; twin >= head-on on " & $winOverHead & "/" & $movers.len & "VelociBot, Walls, Dodger).** Result: vgun >= best single gun on " &
" movers. **Verdict: " & verdict & ".**\n" $winOverBest & "/" & $nOpp & "; vgun >= ELM-base on " & $winOverElm &
"/" & $movers.len & " movers. **Verdict: " & verdict & ".**\n"
md.add "\n## Method / caveats\n\n" md.add "\n## Method / caveats\n\n"
md.add "* `TWIN` = `chimera/aimer.nim`: iterated flight time \n" & md.add "* `VGUN` = `chimera/virtual_guns.nim`: per-tick virtual bullets for " &
" `h = dist/(20-3*power)`, horizon-bucketed predictor Hedge " & "{TWIN, ELM, HEAD-ON}, a per-shot hit-rate EMA (tau=100) plus a " &
"damage-weighted accumulator with tau=200 exponential forgetting, " &
"argmax fired under 0.1 hysteresis. Classic Robocode Virtual Guns " &
"pattern (https://robowiki.net/wiki/Virtual_Guns).\n"
md.add "* `TWIN` = `chimera/aimer.nim`: iterated flight time " &
"`h = dist/(20-3*power)`, horizon-bucketed predictor Hedge " &
"(mixture/residual/persistence), trained ONLINE per record (one aimer, " & "(mixture/residual/persistence), trained ONLINE per record (one aimer, " &
"score-then-aim each sampled tick), spread-selected power.\n" "score-then-aim each sampled tick), spread-selected power.\n"
md.add "* `ELM` = the ELM gun's **base** geometric intercept from the " & md.add "* `ELM` = the ELM gun's **base** geometric intercept from the " &
"observed velocity (the learned correction is gated and small, and the " & "observed velocity (the learned correction is gated and small, and the " &
"online ELM state cannot be replayed offline). This is a proxy for the " & "online ELM state cannot be replayed offline). This is a proxy for the " &
"full ELM gun — a documented deviation.\n" "full ELM gun — a documented deviation.\n"
md.add "* Power monotonicity: `selectPowerFromSpreads` returns the largest " & md.add "* The synthesized Dodger is Dodger-v2 (`tests/archetypes/Dodger`): " &
"power whose required spread fits the enemy-silhouette tolerance " & "wave-based perpendicular strafe, centre-pull, seeded reversals. It " &
"`2*atan2(18, dist)`; the choice is non-increasing in spread " & "fires a wave every 12 ticks; a real battle adds shooter motion. Live " &
"(`test_aimer.nim`, aimer 4).\n" "results (`m7_5_g8_live.md`) are the reality check.\n"
md.add "* The synthesized Dodger fires a wave every 12 ticks; a real battle " & let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8.md"
"would add shooter motion. Live results (`m7_g8_live.md`) are the " &
"reality check.\n"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_g8.md"
createDir(art.parentDir) createDir(art.parentDir)
writeFile(art, md) writeFile(art, md)
echo "Artifact: ", art echo "Artifact: ", art
+68 -38
View File
@@ -1,11 +1,17 @@
## G8 LIVE BENCH — twin gun vs ELM gun vs inert, suite + G7 no-regression. ## G8.5 LIVE BENCH — virtual-gun tournament vs twin vs ELM vs inert.
## LIVE, Java required. Three binaries from the SAME tree: ## LIVE, Java required. FOUR binaries from the SAME tree:
## * inert — `-d:chimeraInert` (all CHIMERA command paths off == M1 copy) ## * inert — `-d:chimeraInert` (all CHIMERA command paths off == M1 copy)
## * elm — `-d:chimeraNoTwinGun` (probes+fusion+influence, ELM gun as now) ## * elm — `-d:chimeraNoTwinGun` (probes+fusion+influence, ELM gun as now)
## * twin — default (ELM gun REPLACED by the M7 twin gun) ## * twin — `-d:chimeraNoVguns` (M7 influence-gated twin/ELM path)
## * vgun — default (M7.5 virtual-gun tournament: TWIN/ELM/HEAD-ON)
## 5 rounds per arm per opponent vs the 8 primary sample bots + the garage-local ## 5 rounds per arm per opponent vs the 8 primary sample bots + the garage-local
## Dodger archetype. Reports win rate + score margin; the G7 no-regression read ## Dodger-v2 archetype. Reports win rate + score margin; the G7 no-regression read
## is twin >= inert (win rate) on every opponent, stated plainly when it fails. ## is vgun >= inert (win rate) on every opponent, stated plainly when it fails.
##
## The **discrimination test** is the Dodger-v2 row: M7 found the three arms
## ~equal there (~2660 each), i.e. the opponent was too weak to separate them.
## M7.5 reports the four Dodger margins and states plainly whether they now
## differ.
## ##
## Run: `nim c -r --hints:off -d:release tests/bench_g8_live.nim` ## Run: `nim c -r --hints:off -d:release tests/bench_g8_live.nim`
@@ -29,7 +35,8 @@ type
const Arms = [ const Arms = [
Arm(tag: "inert", name: "ChimeraInert", defines: @["-d:chimeraInert"]), Arm(tag: "inert", name: "ChimeraInert", defines: @["-d:chimeraInert"]),
Arm(tag: "elm", name: "ChimeraElm", defines: @["-d:chimeraNoTwinGun"]), Arm(tag: "elm", name: "ChimeraElm", defines: @["-d:chimeraNoTwinGun"]),
Arm(tag: "twin", name: "ChimeraTwin", defines: @[]), Arm(tag: "twin", name: "ChimeraTwin", defines: @["-d:chimeraNoVguns"]),
Arm(tag: "vgun", name: "ChimeraVgun", defines: @[]),
] ]
proc parseOutcome(log, ourName: string): Outcome = proc parseOutcome(log, ourName: string): Outcome =
@@ -85,10 +92,10 @@ proc margin(o: Outcome): float64 = o.ourScore - o.oppScore
proc main() = proc main() =
guardSkip() guardSkip()
echo "[G8-live] staging 3 arms..." echo "[G8.5-live] staging 4 arms..."
var bots = initTable[string, string]() var bots = initTable[string, string]()
for a in Arms: for a in Arms:
bots[a.tag] = stageBot("g8_" & a.tag, a.defines, a.name) bots[a.tag] = stageBot("g85_" & a.tag, a.defines, a.name)
let opps = sorted(toSeq(Expected.keys)) & @["Dodger"] let opps = sorted(toSeq(Expected.keys)) & @["Dodger"]
var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out
@@ -107,60 +114,83 @@ proc main() =
" margin=", formatFloat(margin(o), ffDecimal, 1) " margin=", formatFloat(margin(o), ffDecimal, 1)
suite[arm.tag] = t suite[arm.tag] = t
echo "\n=== G8 live suite (", Rounds, " rounds/arm/opponent) ===" echo "\n=== G8.5 live suite (", Rounds, " rounds/arm/opponent) ==="
echo "Opponent elmW% elmM twinW% twinM inertW% inertM" echo "Opponent elmW% elmM twinW% twinM vgunW% vgunM inertW% inertM"
var noRegress = true var noRegress = true
var regress: seq[string] var regress: seq[string]
var lines: seq[string] var lines: seq[string]
lines.add "# G8 live bench (M7 twin gun)\n" lines.add "# G8.5 live bench (M7.5 virtual-gun tournament)\n"
lines.add "Three arms from the SAME tree: inert (`-d:chimeraInert`), elm " & lines.add "Four arms from the SAME tree: inert (`-d:chimeraInert`), elm " &
"(`-d:chimeraNoTwinGun`), twin (default). " & $Rounds & "(`-d:chimeraNoTwinGun`), twin (`-d:chimeraNoVguns`), vgun (default). " &
" rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`.\n" $Rounds & " rounds per arm per opponent. Generated by " &
lines.add "| opponent | elm W% | elm margin | twin W% | twin margin | inert W% | inert margin |" "`tests/bench_g8_live.nim`.\n"
lines.add "|---|---:|---:|---:|---:|---:|---:|" lines.add "| opponent | elm W% | elm margin | twin W% | twin margin | vgun W% | vgun margin | inert W% | inert margin |"
lines.add "|---|---:|---:|---:|---:|---:|---:|---:|---:|"
for opp in opps: for opp in opps:
let e = suite["elm"].getOrDefault(opp) let e = suite["elm"].getOrDefault(opp)
let t = suite["twin"].getOrDefault(opp) let t = suite["twin"].getOrDefault(opp)
let v = suite["vgun"].getOrDefault(opp)
let i = suite["inert"].getOrDefault(opp) let i = suite["inert"].getOrDefault(opp)
if t.rounds > 0 and i.rounds > 0 and t.wins < i.wins: if v.rounds > 0 and i.rounds > 0 and v.wins < i.wins:
noRegress = false; regress.add opp noRegress = false; regress.add opp
echo " ", alignLeft(opp, 10), echo " ", alignLeft(opp, 10),
align(formatFloat(winRate(e), ffDecimal, 0), 7), align(formatFloat(winRate(e), ffDecimal, 0), 7),
align(formatFloat(margin(e), ffDecimal, 1), 7), align(formatFloat(margin(e), ffDecimal, 1), 7),
align(formatFloat(winRate(t), ffDecimal, 0), 7), align(formatFloat(winRate(t), ffDecimal, 0), 7),
align(formatFloat(margin(t), ffDecimal, 1), 6), align(formatFloat(margin(t), ffDecimal, 1), 6),
align(formatFloat(winRate(v), ffDecimal, 0), 7),
align(formatFloat(margin(v), ffDecimal, 1), 6),
align(formatFloat(winRate(i), ffDecimal, 0), 8), align(formatFloat(winRate(i), ffDecimal, 0), 8),
align(formatFloat(margin(i), ffDecimal, 1), 7) align(formatFloat(margin(i), ffDecimal, 1), 7)
lines.add "| " & opp & " | " & formatFloat(winRate(e), ffDecimal, 1) & " | " & lines.add "| " & opp & " | " & formatFloat(winRate(e), ffDecimal, 1) & " | " &
formatFloat(margin(e), ffDecimal, 1) & " | " & formatFloat(margin(e), ffDecimal, 1) & " | " &
formatFloat(winRate(t), ffDecimal, 1) & " | " & formatFloat(winRate(t), ffDecimal, 1) & " | " &
formatFloat(margin(t), ffDecimal, 1) & " | " & formatFloat(margin(t), ffDecimal, 1) & " | " &
formatFloat(winRate(v), ffDecimal, 1) & " | " &
formatFloat(margin(v), ffDecimal, 1) & " | " &
formatFloat(winRate(i), ffDecimal, 1) & " | " & formatFloat(winRate(i), ffDecimal, 1) & " | " &
formatFloat(margin(i), ffDecimal, 1) & " |" formatFloat(margin(i), ffDecimal, 1) & " |"
# suite totals # suite totals
var te, tt, ti: Outcome var totals = initTable[string, Outcome]()
for opp in opps: for opp in opps:
for (dst, arm) in [(addr te, "elm"), (addr tt, "twin"), (addr ti, "inert")]: for arm in Arms:
let o = suite[arm].getOrDefault(opp) let o = suite[arm.tag].getOrDefault(opp)
dst.rounds += o.rounds; dst.wins += o.wins totals.mgetOrPut(arm.tag, Outcome()).rounds += o.rounds
dst.ourScore += o.ourScore; dst.oppScore += o.oppScore totals[arm.tag].wins += o.wins
echo "\nTotals: elm ", formatFloat(winRate(te), ffDecimal, 1), totals[arm.tag].ourScore += o.ourScore
"% (m ", formatFloat(margin(te), ffDecimal, 1), ") twin ", totals[arm.tag].oppScore += o.oppScore
formatFloat(winRate(tt), ffDecimal, 1), "% (m ",
formatFloat(margin(tt), ffDecimal, 1), ") inert ", var totLine = "Totals: "
formatFloat(winRate(ti), ffDecimal, 1), "% (m ", for arm in Arms:
formatFloat(margin(ti), ffDecimal, 1), ")" let t = totals[arm.tag]
lines.add "\n**Totals:** elm " & formatFloat(winRate(te), ffDecimal, 1) & totLine.add arm.tag & " " & formatFloat(winRate(t), ffDecimal, 1) &
"% (margin " & formatFloat(margin(te), ffDecimal, 1) & "), twin " & "% (m " & formatFloat(margin(t), ffDecimal, 1) & ") "
formatFloat(winRate(tt), ffDecimal, 1) & "% (margin " & echo "\n", totLine
formatFloat(margin(tt), ffDecimal, 1) & "), inert " & lines.add "\n**" & totLine & "**"
formatFloat(winRate(ti), ffDecimal, 1) & "% (margin " &
formatFloat(margin(ti), ffDecimal, 1) & ")." # Discrimination read on the Dodger-v2 row.
lines.add "\n**G7 no-regression (twin >= inert win-rate on every opponent): " & var dm = ""
var dmin = Inf
var dmax = -Inf
for arm in Arms:
let o = suite[arm.tag].getOrDefault("Dodger")
dm.add arm.tag & " " & formatFloat(margin(o), ffDecimal, 1) & " "
dmin = min(dmin, margin(o))
dmax = max(dmax, margin(o))
let spread = dmax - dmin
echo "Dodger-v2 margins: ", dm, " spread=", formatFloat(spread, ffDecimal, 1)
lines.add "\n**Discrimination test (Dodger-v2 row).** Margins: " & dm &
"spread " & formatFloat(spread, ffDecimal, 1) & ". " &
(if spread >= 500.0:
"The arms DIFFER materially against the upgraded Dodger."
else:
"The arms remain ~equal against the upgraded Dodger — stated plainly as a finding.")
lines.add "\n**G7 no-regression (vgun >= inert win-rate on every opponent): " &
(if noRegress: "PASS" else: "**FAIL** on " & regress.join(", ")) & ".**" (if noRegress: "PASS" else: "**FAIL** on " & regress.join(", ")) & ".**"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_g8_live.md" let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8_live.md"
createDir(art.parentDir) createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n") writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art echo "\nArtifact: ", art
+131 -22
View File
@@ -1,9 +1,20 @@
## Construction test for the Dodger archetype (tests/archetypes/Dodger). ## Construction + behaviour tests for the Dodger archetype
## The bot's run loop contains no decision logic: it calls `dodgeDecision` and ## (tests/archetypes/Dodger; M7.5/G8).
## applies the result, so pinning the spec function's outputs on synthetic ##
## inputs pins the bot's behaviour by construction. Pure Nim, no Java. ## The bot's run loop contains no decision logic: it calls `dodgeDecision` /
## `gunDecision` and applies the result, so pinning the spec functions' outputs on
## synthetic inputs pins the bot's behaviour by construction. The last two blocks
## go further:
##
## * a **dodge-rate matrix** runs the documented decision through the physics
## mirror and fires head-on-gun shots at the resulting trajectory, asserting
## a dodge rate >= 60% for every (shooter, start) pair;
## * a **fire-back** check asserts the head-on gun fires when aligned and cold.
##
## Pure Nim, no Java.
import std/[math] import std/[math, strutils]
import chimera/physics
import dodger_spec import dodger_spec
var failed = 0 var failed = 0
@@ -24,19 +35,20 @@ block:
waveETA(w, 160.0, 0.0, 20) < 0.0) waveETA(w, 160.0, 0.0, 20) < 0.0)
block: block:
echo "dodger 2: far wave -> patrol" echo "dodger 2: far wave -> centre patrol (never charge the gun line)"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0) let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 1600.0, y: 0.0, heading: 0.0), 0, let c = dodgeDecision(w, DodgeOwn(x: 1600.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, 1.0) 800.0, 600.0, 1.0)
check("not dodging", not c.dodging) check("not dodging", not c.dodging)
check("patrol speed", approx(c.targetSpeed, PatrolSpeed)) check("patrol speed", approx(c.targetSpeed, PatrolSpeed))
check("no turn", approx(c.turnRate, 0.0)) check("turns toward the centre (not straight)", abs(c.turnRate) > 0.0,
$c.turnRate)
check("strafe sign carried", approx(c.strafeSign, 1.0)) check("strafe sign carried", approx(c.strafeSign, 1.0))
block: block:
echo "dodger 3: spent wave -> patrol" echo "dodger 3: spent wave -> centre patrol, sign retained"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 100, bulletSpeed: 16.0) let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 100, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 0.0, heading: 0.0), 0, let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, -1.0) 800.0, 600.0, -1.0)
check("not dodging", not c.dodging) check("not dodging", not c.dodging)
check("strafe sign retained", approx(c.strafeSign, -1.0)) check("strafe sign retained", approx(c.strafeSign, -1.0))
@@ -44,32 +56,36 @@ block:
block: block:
echo "dodger 4: close wave -> strafe perpendicular" echo "dodger 4: close wave -> strafe perpendicular"
let w = DodgeWave(originX: 0.0, originY: 300.0, fireTick: 0, bulletSpeed: 16.0) let w = DodgeWave(originX: 0.0, originY: 300.0, fireTick: 0, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 0.0), 0, let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 0.0), 7,
800.0, 600.0, 1.0) 800.0, 600.0, 1.0)
check("dodging", c.dodging) check("dodging", c.dodging)
check("full throttle", approx(c.targetSpeed, StrafeSpeed)) check("full throttle", approx(c.targetSpeed, StrafeSpeed))
check("turns toward +90 bearing (clamped to 10)", approx(c.turnRate, 10.0), check("turns toward +90 bearing (clamped to 10)", approx(c.turnRate, 10.0),
$c.turnRate) $c.turnRate)
check("strafe sign +1", approx(c.strafeSign, 1.0)) check("strafe sign +1", approx(c.strafeSign, 1.0))
let c2 = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 90.0), 0, let c2 = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 90.0), 7,
800.0, 600.0, 1.0) 800.0, 600.0, 1.0)
check("already perpendicular -> no turn", approx(c2.turnRate, 0.0), $c2.turnRate) check("already perpendicular: centre-pull turns back toward the centre",
approx(c2.turnRate, -10.0), $c2.turnRate)
block: block:
echo "dodger 5: corner flip near a wall" echo "dodger 5: corner flip near a wall"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0) let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 5, bulletSpeed: 16.0)
check("nearWall true inside the band", nearWall(50.0, 300.0, 800.0, 600.0)) check("nearWall true inside the band", nearWall(50.0, 300.0, 800.0, 600.0))
check("nearWall false in the open", not nearWall(400.0, 300.0, 800.0, 600.0)) check("nearWall false in the open", not nearWall(400.0, 300.0, 800.0, 600.0))
let c = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 0, # strafing SOUTH (into the bottom wall we are near) is flipped to NORTH
800.0, 600.0, 1.0) let c = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
check("strafe sign flipped", approx(c.strafeSign, -1.0), $c.strafeSign) 800.0, 600.0, -1.0)
check("turns toward -90 bearing", approx(c.turnRate, -10.0), $c.turnRate) check("wall-ward strafe sign flipped", approx(c.strafeSign, 1.0), $c.strafeSign)
let c2 = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 0, check("turns toward +90 (away from the wall)", approx(c.turnRate, 10.0),
800.0, 600.0, -1.0) $c.turnRate)
check("flip is an involution on the sign", approx(c2.strafeSign, 1.0)) # strafing NORTH (away from the wall) needs no flip
let c2 = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("away-from-wall strafe is kept", approx(c2.strafeSign, 1.0))
block: block:
echo "dodger 6: determinism" echo "dodger 6: determinism + documented seed"
let w = DodgeWave(originX: 10.0, originY: 20.0, fireTick: 3, bulletSpeed: 17.0) let w = DodgeWave(originX: 10.0, originY: 20.0, fireTick: 3, bulletSpeed: 17.0)
let a = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7, let a = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7,
800.0, 600.0, 1.0) 800.0, 600.0, 1.0)
@@ -79,6 +95,99 @@ block:
a.turnRate == b.turnRate and a.targetSpeed == b.targetSpeed and a.turnRate == b.turnRate and a.targetSpeed == b.targetSpeed and
a.strafeSign == b.strafeSign and a.dodging == b.dodging) a.strafeSign == b.strafeSign and a.dodging == b.dodging)
check("reaction window is 14 ticks", ReactionTicks == 14.0) check("reaction window is 14 ticks", ReactionTicks == 14.0)
check("seed is documented", DefaultSeed == 0x5EED1307'u64)
check("seededBit is deterministic",
seededBit(DefaultSeed, 123) == seededBit(DefaultSeed, 123))
# the seed must actually vary across reversal periods, else it is pointless
var varied = false
for i in 0 ..< 8:
if seededBit(DefaultSeed, i) != seededBit(DefaultSeed, i + 1): varied = true
check("seededBit varies across periods", varied)
# ── offline dodge-rate matrix ───────────────────────────────────────────────
# Fire head-on-gun shots (no lead) at the Dodger's trajectory; the dodge rate is
# the fraction that miss (the bullet never comes within 20 units of the bot).
# Reproduces the archetype by running `dodgeDecision` + the physics mirror.
proc dodgeRate(shooterX, shooterY, startX, startY: float64,
ticks = 1400, stride = 4): float64 =
const W = 800.0
const H = 600.0
const HitR = 20.0
var ex = startX
var ey = startY
var ehead = 0.0
var espeed = 0.0
var sign = 1.0
var wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: -1000,
bulletSpeed: 14.0)
var pos: seq[tuple[x, y: float64]]
for tick in 1 .. ticks:
if tick mod 12 == 0:
wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: tick,
bulletSpeed: 14.0)
let cmd = dodgeDecision(wave, DodgeOwn(x: ex, y: ey, heading: ehead), tick,
W, H, sign)
sign = cmd.strafeSign
espeed = stepSpeed(espeed, cmd.targetSpeed)
ehead = wrap180(ehead + limitTurnRate(cmd.turnRate, espeed))
ex = clamp(ex + espeed * cos(degToRad(ehead)), 0.0, W)
ey = clamp(ey + espeed * sin(degToRad(ehead)), 0.0, H)
pos.add (ex, ey)
var hits = 0
var n = 0
for i in countup(0, ticks - 1, stride):
let e = pos[i]
let bearing = arctan2(e.y - shooterY, e.x - shooterX)
var bx = shooterX
var by = shooterY
var didHit = false
for h in 1 .. 80:
bx += 14.0 * cos(bearing)
by += 14.0 * sin(bearing)
if bx < 0.0 or bx > W or by < 0.0 or by > H: break
let k = i + h
if k < pos.len and hypot(bx - pos[k].x, by - pos[k].y) <= HitR:
didHit = true
break
if didHit: inc hits
inc n
100.0 - 100.0 * float(hits) / float(n)
block:
echo "dodger 7: offline dodge-rate matrix (bar >= 60% vs head-on)"
let cases = [
(shooterX: 600.0, shooterY: 300.0, startX: 200.0, startY: 300.0),
(shooterX: 400.0, shooterY: 300.0, startX: 700.0, startY: 150.0),
(shooterX: 200.0, shooterY: 300.0, startX: 600.0, startY: 300.0),
(shooterX: 400.0, shooterY: 400.0, startX: 100.0, startY: 100.0),
(shooterX: 500.0, shooterY: 200.0, startX: 150.0, startY: 450.0),
]
for c in cases:
let d = dodgeRate(c.shooterX, c.shooterY, c.startX, c.startY)
check("dodge >= 60% (shooter " & $c.shooterX & "," & $c.shooterY & ")",
d >= 60.0, formatFloat(d, ffDecimal, 1) & "%")
echo " shooter(", c.shooterX, ",", c.shooterY, ") start(",
c.startX, ",", c.startY, ") dodge=", formatFloat(d, ffDecimal, 1), "%"
block:
echo "dodger 8: fires back (head-on gun)"
let aligned = gunDecision(ex = 100.0, ey = 0.0, sx = 0.0, sy = 0.0,
gunHeading = 0.0, gunHeat = 0.0)
check("aligned + cold -> fire", aligned.fire > 0.0, $aligned.fire)
check("aimed flag set", aligned.aimed)
let hot = gunDecision(100.0, 0.0, 0.0, 0.0, 0.0, 1.0)
check("aligned but hot -> no fire", hot.fire == 0.0)
let mis = gunDecision(0.0, 100.0, 0.0, 0.0, 0.0, 0.0)
check("90 deg off -> no fire, slews", mis.fire == 0.0 and mis.turnRate > 0.0)
# a short offline exchange: the gun fires repeatedly when it stays aligned
var fired = 0
var ghead = 0.0
for tick in 1 .. 60:
let g = gunDecision(100.0, 0.0, 0.0, 0.0, ghead, 0.0)
ghead = wrap180(ghead + limitTurnRate(g.turnRate, 0.0))
if g.fire > 0.0: inc fired
check("fires more than once in a 60-tick exchange", fired >= 2, $fired)
echo "" echo ""
if failed == 0: echo "all dodger tests passed" if failed == 0: echo "all dodger tests passed"
@@ -0,0 +1,147 @@
## Tier A tests for the CHIMERA virtual-gun tournament
## (chimera/virtual_guns.nim, spec G8 / M7.5). Pure Nim, no Java.
## Run: from ChimeraBot_garage, `nimble test` (and once with
## `-d:chimeraNoVguns` to prove the kill switch compiles).
##
## Covers the four stated concerns: EMA scoring, hysteresis, determinism and the
## virtual-bullet mechanics, plus the kill-switch compile.
import std/math
import chimera/virtual_guns
var failed = 0
proc approx(a, b: float64): bool = abs(a - b) < 1e-9
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
# The kill switch must track the compile define. This file is also compiled with
# `-d:chimeraNoVguns` in the nimble task, so both branches are exercised.
when defined(chimeraNoVguns):
static: doAssert NoVguns
else:
static: doAssert not NoVguns
proc driveTo(v: var VirtualGunSet, g: VGun, density: float64, n = 400) =
## Drive `g`'s EMA toward a hit density in [0,1]. The hits are interleaved
## (37 is coprime with 100) so the EMA settles on the density rather than on
## the last run of a clustered pattern.
let target = int(density * 100.0)
for i in 0 ..< n:
v.observeShot(g, ((i * 37) mod 100) < target, 2.0)
block:
echo "vguns 1: EMA scoring (hit/miss)"
var v = initVirtualGuns()
check("no shots -> EMA 0", v.emaOf(vgTwin) == 0.0)
for i in 0 ..< 400: v.observeShot(vgTwin, true, 2.0)
check("all hits -> EMA near 1", v.emaOf(vgTwin) > 0.95, $v.emaOf(vgTwin))
for i in 0 ..< 400: v.observeShot(vgTwin, false, 2.0)
check("switched to misses -> EMA near 0", v.emaOf(vgTwin) < 0.05, $v.emaOf(vgTwin))
check("shot counter", v.shotsOf(vgTwin) == 800, $v.shotsOf(vgTwin))
# a hit must raise the EMA, a miss must lower it
var w = initVirtualGuns()
driveTo(w, vgElm, 0.5)
let before = w.emaOf(vgElm)
w.observeShot(vgElm, true, 2.0)
let afterHit = w.emaOf(vgElm)
check("a hit raises the EMA", afterHit > before)
w.observeShot(vgElm, false, 2.0)
check("a miss lowers the EMA", w.emaOf(vgElm) < afterHit)
block:
echo "vguns 2: damage-weighted accumulator"
var v = initVirtualGuns()
# same hit count, different power: the accumulator must reward damage.
for i in 0 ..< 50: v.observeShot(vgTwin, true, 3.0)
for i in 0 ..< 50: v.observeShot(vgElm, true, 0.5)
check("hit-rate EMA ties (same hit count)", approx(v.emaOf(vgTwin), v.emaOf(vgElm)))
check("damage accumulator favours the heavier gun",
v.decayedRate(vgTwin) > v.decayedRate(vgElm),
$v.decayedRate(vgTwin) & " vs " & $v.decayedRate(vgElm))
# 3.0 -> 4*3 + 2*2 = 16 damage; 0.5 -> 2.0
check("accumulator equals damage per shot",
abs(v.decayedRate(vgTwin) - 16.0) < 1e-9, $v.decayedRate(vgTwin))
block:
echo "vguns 3: hysteresis (0.1 EMA margin)"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.50)
discard v.selectGun() # make twin the incumbent
driveTo(v, vgElm, 0.55) # elm now leads, but only by ~0.05
check("incumbent twin kept while the rival leads by < 0.1",
v.selectGun() == vgTwin, $v.emaOf(vgTwin) & "/" & $v.emaOf(vgElm))
var w = initVirtualGuns()
driveTo(w, vgTwin, 0.50)
driveTo(w, vgElm, 0.70)
discard w.selectGun()
check("rival leading by > 0.1 switches to elm", w.selectGun() == vgElm)
# and the switch is sticky: once elm, a 0.05 lead does not hand it back
var u = initVirtualGuns()
driveTo(u, vgTwin, 0.70)
driveTo(u, vgElm, 0.75)
discard u.selectGun()
# first selection is whichever is best at that moment; assert the margin logic
let s1 = u.selectGun()
let s2 = u.selectGun()
check("selection is stable across repeated calls", s1 == s2)
block:
echo "vguns 4: twin influence gate"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.9)
driveTo(v, vgElm, 0.1)
discard v.selectGun() # incumbent twin
check("twin eligible -> twin chosen", v.selectGun(twinEligible = true) == vgTwin)
check("twin ineligible -> falls to the best legal gun",
v.selectGun(twinEligible = false) != vgTwin)
block:
echo "vguns 5: virtual-bullet mechanics"
var v = initVirtualGuns()
# head-on east at power 2 -> speed 14. Enemy at (14,0): the first step hits.
v.launchVirtual(vgHeadOn, 0.0, 0.0, 0.0, 2.0)
v.vgTick(14.0, 0.0, 20.0, 800.0, 600.0)
check("a hit resolves and scores", v.shotsOf(vgHeadOn) == 1 and v.emaOf(vgHeadOn) > 0.0)
check("no live bullets left after a hit", v.bullets.len == 0)
# a bullet aimed away from the enemy leaves the arena -> a scored miss
var w = initVirtualGuns()
w.launchVirtual(vgElm, 0.0, 0.0, PI, 2.0) # west, straight out of the arena
w.vgTick(500.0, 500.0, 20.0, 800.0, 600.0)
check("arena exit resolves as a miss", w.shotsOf(vgElm) == 1 and w.emaOf(vgElm) == 0.0)
# forgetting decays the accumulator but not the accumulated damage average
var x = initVirtualGuns()
for i in 0 ..< 10: x.observeShot(vgTwin, true, 2.0)
let r0 = x.decayedRate(vgTwin)
for i in 0 ..< 200: x.forgetTick()
check("forgetting lowers the accumulator weight",
x.score[vgTwin].weight < 5.0, $x.score[vgTwin].weight)
block:
echo "vguns 6: determinism"
var a = initVirtualGuns()
var b = initVirtualGuns()
for i in 0 ..< 120:
let hitA = (i mod 3) != 0
let hitB = (i mod 3) != 0
a.observeShot(vgTwin, hitA, 1.5)
b.observeShot(vgTwin, hitB, 1.5)
a.observeShot(vgElm, (i mod 5) == 0, 2.0)
b.observeShot(vgElm, (i mod 5) == 0, 2.0)
check("identical sequences -> identical EMAs",
a.emaOf(vgTwin) == b.emaOf(vgTwin) and a.emaOf(vgElm) == b.emaOf(vgElm))
check("identical sequences -> identical selection", a.selectGun() == b.selectGun())
check("gun names are stable", vgTwin.gunName() == "twin" and
vgElm.gunName() == "elm" and vgHeadOn.gunName() == "headon")
block:
echo "vguns 7: reset"
var v = initVirtualGuns()
for i in 0 ..< 30: v.observeShot(vgTwin, true, 2.0)
v.resetVguns()
check("reset clears the scores", v.emaOf(vgTwin) == 0.0 and
v.shotsOf(vgTwin) == 0)
echo ""
if failed == 0: echo "all virtual-gun tests passed"
else: echo failed, " virtual-gun test(s) FAILED"; quit(1)