ChimeraBot_garage: M7 twin gun — flight-horizon aiming, spread-based power, aim-bias corrector, Dodger archetype
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
## G8 OFFLINE BENCH — flight-horizon aiming (twin gun) vs ELM vs head-on.
|
||||
## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8.
|
||||
##
|
||||
## Replays recorded trajectories (the archived M6 telemetry under
|
||||
## `CHIMERA_G8_TELEMETRY`, default `/tmp/chimera_g4_run`) plus a deterministically
|
||||
## SYNTHESIZED Dodger trajectory (the archetype's documented spec function run
|
||||
## through the physics mirror), and, for every sampled origin tick, simulates the
|
||||
## bullet each of three aim policies 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.
|
||||
##
|
||||
## 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, times, sequtils]
|
||||
import chimera/dsl
|
||||
import chimera/twinsim
|
||||
import chimera/residual
|
||||
import chimera/aimer
|
||||
import chimera/physics
|
||||
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
|
||||
|
||||
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): 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()
|
||||
var n = 0
|
||||
for rt in rps:
|
||||
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)
|
||||
for (pol, bearing, power) in [(pHeadOn, head, ElmPower),
|
||||
(pElm, elm, ElmPower),
|
||||
(pTwin, (if aim.active: aim.aimBearing else: elm),
|
||||
(if aim.active: aim.power else: ElmPower))]:
|
||||
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 record: our bot sits at (600,300); a wave is fired
|
||||
## every 20 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 winOverElm = 0
|
||||
var winOverHead = 0
|
||||
let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"]
|
||||
var nOpp = 0
|
||||
echo "opponent twin% elm% head% n"
|
||||
for opp in opps:
|
||||
var t: Table[Policy, Tally]
|
||||
if opp == "Dodger":
|
||||
t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0)
|
||||
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))
|
||||
inc used
|
||||
let tw = t.getOrDefault(pTwin)
|
||||
let el = t.getOrDefault(pElm)
|
||||
let ho = t.getOrDefault(pHeadOn)
|
||||
addInto(total, t)
|
||||
inc nOpp
|
||||
if tw.hits >= el.hits: inc winOverElm
|
||||
if tw.hits >= ho.hits and opp in movers: inc winOverHead
|
||||
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($tw.shots, 6)
|
||||
rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " &
|
||||
formatFloat(el.hitRate, ffDecimal, 1) & " | " &
|
||||
formatFloat(ho.hitRate, ffDecimal, 1) & " | " & $tw.shots & " |"
|
||||
|
||||
let passElm = winOverElm >= 6
|
||||
let passHead = winOverHead >= movers.len
|
||||
let verdict = if passElm and passHead: "PASS" else: "FAIL"
|
||||
echo "\nG8 offline: twin >= ELM on ", winOverElm, "/", nOpp,
|
||||
" (bar >= 6); twin >= head-on on ", winOverHead, "/", 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), "%"
|
||||
|
||||
var md = "# G8 offline hit-rate bench (M7, twin gun)\n\n"
|
||||
md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized Dodger; " &
|
||||
"hit = bullet passes within " & formatFloat(HitRadius, ffDecimal, 0) &
|
||||
" units of the realized enemy position. Aim slew/cadence abstracted. " &
|
||||
"Generated by `tests/bench_g8.nim`.\n\n"
|
||||
md.add "| opponent | twin % | ELM % | head-on % | shots |\n|---|---:|---:|---:|---:|\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 " &
|
||||
"on the movers.** Result: twin >= ELM on " & $winOverElm & "/" & $nOpp &
|
||||
"; twin >= head-on on " & $winOverHead & "/" & $movers.len &
|
||||
" movers. **Verdict: " & verdict & ".**\n"
|
||||
md.add "\n## Method / caveats\n\n"
|
||||
md.add "* `TWIN` = `chimera/aimer.nim`: iterated flight time \n" &
|
||||
" `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 "* Power monotonicity: `selectPowerFromSpreads` returns the largest " &
|
||||
"power whose required spread fits the enemy-silhouette tolerance " &
|
||||
"`2*atan2(18, dist)`; the choice is non-increasing in spread " &
|
||||
"(`test_aimer.nim`, aimer 4).\n"
|
||||
md.add "* The synthesized Dodger fires a wave every 12 ticks; a real battle " &
|
||||
"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)
|
||||
writeFile(art, md)
|
||||
echo "Artifact: ", art
|
||||
|
||||
when isMainModule:
|
||||
main()
|
||||
Reference in New Issue
Block a user