279 lines
12 KiB
Nim
279 lines
12 KiB
Nim
## G8 OFFLINE BENCH (M7.5) — virtual-gun tournament vs the single guns.
|
|
## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8 (M7 + M7.5).
|
|
##
|
|
## Replays recorded trajectories (the archived M6 telemetry under
|
|
## `CHIMERA_G8_TELEMETRY`, default `/tmp/chimera_g4_run`) plus a deterministically
|
|
## SYNTHESIZED Dodger-v2 trajectory (the archetype's documented spec function run
|
|
## through the physics mirror), and, for every sampled origin tick, simulates the
|
|
## bullet each aim policy would have fired:
|
|
##
|
|
## * HEAD-ON — aim at the enemy's position at fire time (no lead);
|
|
## * ELM — the ELM gun's base: geometric intercept from observed velocity;
|
|
## * 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
|
|
## some flight tick before the wall. Aim slew and cadence are abstracted away: the
|
|
## comparison is a pure aim-policy hit rate on identical trajectories.
|
|
##
|
|
## Run: `nim c -r --hints:off -d:release tests/bench_g8.nim`
|
|
|
|
import std/[math, os, strutils, tables, algorithm, sequtils]
|
|
import chimera/dsl
|
|
import chimera/twinsim
|
|
import chimera/residual
|
|
import chimera/aimer
|
|
import chimera/physics
|
|
import chimera/virtual_guns
|
|
import dodger_spec
|
|
|
|
const
|
|
HitRadius* = 20.0 ## bot radius (18) + bullet radius (~2)
|
|
ElmPower* = 2.0 ## the ELM gun's fixed firepower
|
|
MaxFlight* = 80 ## ticks before a bullet is given up
|
|
Stride* = 4 ## origin-tick sampling stride (de-correlate)
|
|
MaxOrigins* = 220 ## origins sampled per telemetry file
|
|
TelDir* = "/tmp/chimera_g4_run"
|
|
|
|
type
|
|
Policy = enum
|
|
pHeadOn, pElm, pTwin, pVgun
|
|
|
|
Tally = object
|
|
hits, shots: int
|
|
|
|
proc hitRate(t: Tally): float64 =
|
|
if t.shots == 0: 0.0 else: 100.0 * float(t.hits) / float(t.shots)
|
|
|
|
proc parseNum(ln: string, key: string, default = 0.0): float64 =
|
|
let needle = "\"" & key & "\":"
|
|
let i = ln.find(needle)
|
|
if i < 0: return default
|
|
var j = i + needle.len
|
|
while j < ln.len and ln[j] in {' ', '\t'}: inc j
|
|
let s = j
|
|
while j < ln.len and (ln[j] in Digits or ln[j] in {'-', '+', '.', 'e', 'E'}): inc j
|
|
if j == s: return default
|
|
try: parseFloat(ln[s ..< j])
|
|
except ValueError: default
|
|
|
|
proc enemyMap(rec: Record): Table[int, tuple[x, y: float64]] =
|
|
for t in rec.ticks:
|
|
if t.scanned: result[t.tick] = (t.ex, t.ey)
|
|
|
|
proc simulateHit(sx, sy, bearing, power: float64, originTick: int,
|
|
emap: Table[int, tuple[x, y: float64]],
|
|
arenaW, arenaH: float64): bool =
|
|
## Fire from (sx,sy) at `bearing`/`power`; true if the bullet comes within
|
|
## HitRadius of the realized enemy position before leaving the arena.
|
|
let v = bulletSpeed(power)
|
|
var bx = sx
|
|
var by = sy
|
|
var b = bearing
|
|
for h in 1 .. MaxFlight:
|
|
bx += v * cos(b)
|
|
by += v * sin(b)
|
|
if bx < 0.0 or bx > arenaW or by < 0.0 or by > arenaH: return false
|
|
let e = emap.getOrDefault(originTick + h, (x: -1e9, y: -1e9))
|
|
if e.x > -1e8 and hypot(bx - e.x, by - e.y) <= HitRadius: return true
|
|
false
|
|
|
|
proc evalRecord(rec: Record, kernels: seq[Kernel],
|
|
arenaW, arenaH: float64,
|
|
v: var VirtualGunSet): Table[Policy, Tally] =
|
|
let emap = enemyMap(rec)
|
|
let rps = replay(rec, kernels)
|
|
# ONE aimer per record, trained online exactly like the live bot: at each
|
|
# sampled tick score the shots whose horizon has elapsed, THEN aim. A fresh
|
|
# per-origin aimer would never learn the bucket weights and would misrepresent
|
|
# the twin gun.
|
|
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
|
|
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 n >= MaxOrigins: break
|
|
inc n
|
|
a.resolve(rt.tick, rt.ex, rt.ey)
|
|
let dx = rt.ex - rt.ox
|
|
let dy = rt.ey - rt.oy
|
|
let head = arctan2(dy, dx)
|
|
let d = hypot(dx, dy)
|
|
let vx = rt.espeed * cos(degToRad(rt.edir))
|
|
let vy = rt.espeed * sin(degToRad(rt.edir))
|
|
let tof = d / bulletSpeed(ElmPower)
|
|
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,
|
|
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),
|
|
(pElm, elm, ElmPower),
|
|
(pTwin, twinBearing, twinPower),
|
|
(pVgun, vb, vp)]:
|
|
result.mgetOrPut(pol, Tally()).shots.inc
|
|
if simulateHit(rt.ox, rt.oy, bearing, power, rt.tick, emap, arenaW, arenaH):
|
|
result[pol].hits.inc
|
|
if aim.active: a.noteShot(aim, rt.tick)
|
|
proc synthesizeDodger(kernels: seq[Kernel]): Record =
|
|
## A deterministic Dodger-v2 record: our bot sits at (600,300); a wave is fired
|
|
## every 12 ticks; the enemy runs `dodgeDecision` through the physics mirror.
|
|
## Gives the bench a MOVING, DODGING opponent without Java.
|
|
const W = 800.0
|
|
const H = 600.0
|
|
let ox = 600.0
|
|
let oy = 300.0
|
|
var ex = 200.0
|
|
var ey = 300.0
|
|
var ehead = 0.0
|
|
var espeed = 0.0
|
|
var sign = 1.0
|
|
var wave = DodgeWave(originX: ox, originY: oy, fireTick: -1000,
|
|
bulletSpeed: 20.0 - 3.0 * ElmPower)
|
|
result.opponent = "Dodger"
|
|
result.round = 1
|
|
for tick in 1 .. 1400:
|
|
if tick mod 12 == 0:
|
|
wave = DodgeWave(originX: ox, originY: oy, fireTick: tick,
|
|
bulletSpeed: 20.0 - 3.0 * ElmPower)
|
|
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)
|
|
result.ticks.add TickRecord(tick: tick, scanned: true, ex: ex, ey: ey,
|
|
edir: ehead, espeed: espeed, eenergy: 100.0,
|
|
ox: ox, oy: oy, odir: 180.0, ospeed: 0.0)
|
|
|
|
proc addInto(dst: var Table[Policy, Tally], src: Table[Policy, Tally]) =
|
|
for pol, t in src:
|
|
dst.mgetOrPut(pol, Tally()).hits += t.hits
|
|
dst.mgetOrPut(pol, Tally()).shots += t.shots
|
|
|
|
proc main() =
|
|
let kernels = allKernels()
|
|
let dir = getEnv("CHIMERA_G8_TELEMETRY", TelDir)
|
|
var byOpp = initTable[string, seq[string]]()
|
|
if dirExists(dir):
|
|
for path in walkDirRec(dir):
|
|
if not path.endsWith(".jsonl"): continue
|
|
let base = path.extractFilename
|
|
let dash = base.rfind('-')
|
|
if dash <= 0: continue
|
|
byOpp.mgetOrPut(base[0 ..< dash], @[]).add path
|
|
|
|
var opps = toSeq(byOpp.keys)
|
|
opps.sort()
|
|
opps.add "Dodger"
|
|
|
|
var rows: seq[string]
|
|
var total: Table[Policy, Tally]
|
|
var winOverBest = 0
|
|
var winOverElm = 0
|
|
let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"]
|
|
var nOpp = 0
|
|
echo "opponent twin% elm% head% vgun% n"
|
|
for opp in opps:
|
|
var t: Table[Policy, Tally]
|
|
var v = initVirtualGuns() # one tournament per opponent
|
|
if opp == "Dodger":
|
|
t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0, v)
|
|
else:
|
|
let files = byOpp[opp]
|
|
var used = 0
|
|
for f in files:
|
|
if used >= 5: break
|
|
addInto(t, evalRecord(loadRecord(f), kernels, 800.0, 600.0, v))
|
|
inc used
|
|
let tw = t.getOrDefault(pTwin)
|
|
let el = t.getOrDefault(pElm)
|
|
let ho = t.getOrDefault(pHeadOn)
|
|
let vg = t.getOrDefault(pVgun)
|
|
addInto(total, t)
|
|
inc nOpp
|
|
# vgun >= the best single gun on this opponent
|
|
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),
|
|
align(formatFloat(tw.hitRate, ffDecimal, 1), 7),
|
|
align(formatFloat(el.hitRate, ffDecimal, 1), 7),
|
|
align(formatFloat(ho.hitRate, ffDecimal, 1), 7),
|
|
align(formatFloat(vg.hitRate, ffDecimal, 1), 7),
|
|
align($vg.shots, 6)
|
|
rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " &
|
|
formatFloat(el.hitRate, ffDecimal, 1) & " | " &
|
|
formatFloat(ho.hitRate, ffDecimal, 1) & " | " &
|
|
formatFloat(vg.hitRate, ffDecimal, 1) & " | " & $vg.shots & " |"
|
|
|
|
let passBest = winOverBest >= 6
|
|
let passElm = winOverElm == movers.len
|
|
let verdict = if passBest and passElm: "PASS" else: "FAIL"
|
|
echo "\nG8.5 offline: vgun >= best single gun on ", winOverBest, "/", nOpp,
|
|
" (bar >= 6); vgun >= ELM-base on ", winOverElm, "/", movers.len,
|
|
" movers; verdict ", verdict
|
|
echo "SUITE twin ", formatFloat(total[pTwin].hitRate, ffDecimal, 1),
|
|
"% elm ", formatFloat(total[pElm].hitRate, ffDecimal, 1),
|
|
"% head ", formatFloat(total[pHeadOn].hitRate, ffDecimal, 1),
|
|
"% vgun ", formatFloat(total[pVgun].hitRate, ffDecimal, 1), "%"
|
|
|
|
var md = "# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)\n\n"
|
|
md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized " &
|
|
"Dodger-v2; hit = bullet passes within " &
|
|
formatFloat(HitRadius, ffDecimal, 0) &
|
|
" units of the realized enemy position on its flight. Aim slew/cadence " &
|
|
"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"
|
|
md.add "\n**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 " &
|
|
$winOverBest & "/" & $nOpp & "; vgun >= ELM-base on " & $winOverElm &
|
|
"/" & $movers.len & " movers. **Verdict: " & verdict & ".**\n"
|
|
md.add "\n## Method / caveats\n\n"
|
|
md.add "* `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).\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, " &
|
|
"score-then-aim each sampled tick), spread-selected power.\n"
|
|
md.add "* `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.\n"
|
|
md.add "* 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.\n"
|
|
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8.md"
|
|
createDir(art.parentDir)
|
|
writeFile(art, md)
|
|
echo "Artifact: ", art
|
|
|
|
when isMainModule:
|
|
main()
|