Files
SirRoboGarage/ChimeraBot_garage/tests/bench_g5p.nim
T

239 lines
10 KiB
Nim

## G5' v2 interventional counterfactual eval (CHIMERA M5.5) — OFFLINE, no Java.
##
## Source: docs/chimera-spec.md §12 G5' (v2 protocol). Reads the probe-ON
## telemetry archived by bench_g6.nim, replays the ledger + Hedge, and for every
## executed probe measures the 5-tick enemy-reaction prediction (twin mixture vs
## persistence baseline) under OUR ACTUAL recorded movement, plus
## reaction-direction agreement.
##
## Reported v2: (a) the MOVING subset {Crazy, SpinBot, VelociBot, Walls} — where
## persistence is NOT optimal by construction — and (b) the full suite. Bar:
## twin >= persistence on >= 70% of MOVING-subset windows. The STATIC subset
## {RamFire, Corners, TrackFire, Fire} gets a saturation analysis (why twin ~
## persistence by construction), one line per opponent.
##
## Run: `nim c -r --hints:off -d:release tests/bench_g5p.nim [telemetryDir]`
import std/[os, strutils, tables, math, algorithm, sequtils]
import bench_common
import chimera/dsl
import chimera/physics
import chimera/twinsim
const Horizon = 5
const DefaultDir = getTempDir() / "chimera_g6_on"
const DirAgreeDeg = 45.0
type
Agg = object
windows: int
twinAde, persAde: float64
twinWins: int
dirTwinAgree, dirPersAgree, dirN: int
allWindows: int
allTwinAde, allPersAde: float64
allTwinWins: int
speedSum: float64
speedN: int
slowN: int # scanned ticks with |enemy speed| < 0.5
type
Sub = object
windows, twinWins: int
twinAde, persAde: float64
dirTwin, dirPers, dirN: int
proc probeTicks(path: string): seq[int] =
## Only EXECUTED probes (`gate:"ok"`) count as interventional windows: a
## gate-blocked trigger issued no probe, so the following ticks are
## observation-only (the M4 persistence-bias trap).
for ln in lines(path):
if ln.find("\"event\":\"probe\"") < 0: continue
if ln.find("\"gate\":\"ok\"") < 0: continue
let needle = "\"tick\":"
let i = ln.find(needle)
if i < 0: continue
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: inc j
if j > s: result.add parseInt(ln[s ..< j])
proc netDir(sx, sy, ex, ey: float64): float64 =
arctan2(ey - sy, ex - sx) * 180.0 / PI
proc dirAgree(sx, sy, obsX, obsY, predX, predY: float64): bool =
let obsMag = hypot(obsX - sx, obsY - sy)
let predMag = hypot(predX - sx, predY - sy)
if obsMag <= 1.0: return predMag <= 5.0
abs(wrap180(netDir(sx, sy, predX, predY) - netDir(sx, sy, obsX, obsY))) <= DirAgreeDeg
proc record(path: string, kernels: seq[Kernel], agg: var Table[string, Agg]) =
let rec = loadRecord(path)
let probes = probeTicks(path)
if rec.ticks.len < Horizon + 1: return
let rp = replay(rec, kernels)
if rp.len < Horizon + 1: return
var a = agg.getOrDefault(rec.opponent)
# observational floor + static-saturation statistics over the same record
for i in 0 ..< rp.len - Horizon:
let origin = rp[i]
var actual: seq[tuple[x, y: float64]]
var realized: seq[tuple[x, y: float64]]
for h in 1 .. Horizon:
actual.add (rp[i + h].ox, rp[i + h].oy)
realized.add (rp[i + h].ex, rp[i + h].ey)
let twin = rollout(kernels, origin, Horizon, actualOwn = actual)
let pers = persistence(origin, Horizon)
var tAde, pAde = 0.0
for h in 0 ..< Horizon:
tAde += hypot(twin.points[h].x - realized[h].x,
twin.points[h].y - realized[h].y)
pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y)
inc a.allWindows
a.allTwinAde += tAde / float(Horizon)
a.allPersAde += pAde / float(Horizon)
if tAde <= pAde: inc a.allTwinWins
let sp = abs(origin.espeed)
a.speedSum += sp
inc a.speedN
if sp < 0.5: inc a.slowN
# interventional windows: probe ticks only
var byTick = initTable[int, int]()
for i, r in rp: byTick[r.tick] = i
for p in probes:
if not byTick.hasKey(p): continue
let i = byTick[p]
if i + Horizon >= rp.len: continue
let origin = rp[i]
var actual: seq[tuple[x, y: float64]]
var realized: seq[tuple[x, y: float64]]
for h in 1 .. Horizon:
actual.add (rp[i + h].ox, rp[i + h].oy)
realized.add (rp[i + h].ex, rp[i + h].ey)
let twin = rollout(kernels, origin, Horizon, actualOwn = actual)
let pers = persistence(origin, Horizon)
var tAde, pAde = 0.0
for h in 0 ..< Horizon:
tAde += hypot(twin.points[h].x - realized[h].x,
twin.points[h].y - realized[h].y)
pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y)
tAde /= float(Horizon); pAde /= float(Horizon)
inc a.windows
a.twinAde += tAde; a.persAde += pAde
if tAde <= pAde: inc a.twinWins
inc a.dirN
if dirAgree(origin.ex, origin.ey, realized[^1].x, realized[^1].y,
twin.points[^1].x, twin.points[^1].y): inc a.dirTwinAgree
if dirAgree(origin.ex, origin.ey, realized[^1].x, realized[^1].y,
pers[^1].x, pers[^1].y): inc a.dirPersAgree
agg[rec.opponent] = a
proc sub(agg: Table[string, Agg], names: seq[string]): Sub =
for name in names:
if name notin agg: continue
let a = agg[name]
result.windows += a.windows
result.twinWins += a.twinWins
result.twinAde += a.twinAde
result.persAde += a.persAde
result.dirTwin += a.dirTwinAgree
result.dirPers += a.dirPersAgree
result.dirN += a.dirN
proc main() =
let arg = if paramCount() >= 1: paramStr(1) else: getEnv("CHIMERA_G5P_DIR", "")
let dir = if arg.len > 0 and dirExists(arg): arg else: DefaultDir
if not dirExists(dir):
echo "No probe-ON telemetry at ", dir, " (run bench_g6.nim first)."
quit(0)
let kernels = allKernels()
var agg = initTable[string, Agg]()
var files: seq[string]
for f in walkDirRec(dir):
if f.endsWith(".jsonl"): files.add f
files.sort()
for f in files: record(f, kernels, agg)
var names = toSeq(agg.keys); names.sort()
var lines: seq[string]
lines.add("# G5' v2 interventional eval (M5.5)\n")
lines.add("Horizon 5, probe-following windows only. MOVING = " & MovingOpponents.join(", ") &
"; STATIC = " & StaticOpponents.join(", ") & ". Source: " & dir & ".\n")
echo "G5' v2 interventional (probe-following), horizon=", Horizon, ", dir=", dir
echo "\nOpponent probes twinADE persADE margin twinWin% dirTwin% dirPers%"
# per-opponent detail
lines.add("| opponent | probes | twinADE | persADE | margin | twinWin% | dirTwin% | dirPers% |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|")
for name in names:
let a = agg[name]
if a.windows == 0: continue
let n = float(a.windows)
let win = 100.0 * float(a.twinWins) / n
echo " ", alignLeft(name, 12), align($a.windows, 6),
" ", align(formatFloat(a.twinAde / n, ffDecimal, 3), 7),
" ", align(formatFloat(a.persAde / n, ffDecimal, 3), 7),
" ", align(formatFloat((a.persAde - a.twinAde) / n, ffDecimal, 3), 7),
" ", align(formatFloat(win, ffDecimal, 1), 8),
" ", align(formatFloat(100.0 * float(a.dirTwinAgree) / float(max(1, a.dirN)), ffDecimal, 1), 8),
" ", align(formatFloat(100.0 * float(a.dirPersAgree) / float(max(1, a.dirN)), ffDecimal, 1), 8)
lines.add "| " & name & " | " & $a.windows & " | " &
formatFloat(a.twinAde / n, ffDecimal, 3) & " | " &
formatFloat(a.persAde / n, ffDecimal, 3) & " | " &
formatFloat((a.persAde - a.twinAde) / n, ffDecimal, 3) & " | " &
formatFloat(win, ffDecimal, 1) & " | " &
formatFloat(100.0 * float(a.dirTwinAgree) / float(max(1, a.dirN)), ffDecimal, 1) & " | " &
formatFloat(100.0 * float(a.dirPersAgree) / float(max(1, a.dirN)), ffDecimal, 1) & " |"
let mov = sub(agg, MovingOpponents)
let full = sub(agg, toSeq(agg.keys))
let movWin = 100.0 * float(mov.twinWins) / float(max(1, mov.windows))
let fullWin = 100.0 * float(full.twinWins) / float(max(1, full.windows))
echo "\nMOVING subset: ", mov.windows, " windows, twinADE ",
formatFloat(mov.twinAde / float(max(1, mov.windows)), ffDecimal, 3),
" persADE ", formatFloat(mov.persAde / float(max(1, mov.windows)), ffDecimal, 3),
", twinWin ", formatFloat(movWin, ffDecimal, 1), "%",
" (bar >=70%: ", (if movWin >= 70.0: "PASS" else: "FAIL"), ")"
echo "FULL suite: ", full.windows, " windows, twinWin ",
formatFloat(fullWin, ffDecimal, 1), "%"
echo "MOVING dir agreement: twin ",
formatFloat(100.0 * float(mov.dirTwin) / float(max(1, mov.dirN)), ffDecimal, 1),
"%, persistence ",
formatFloat(100.0 * float(mov.dirPers) / float(max(1, mov.dirN)), ffDecimal, 1), "%"
lines.add "\n**MOVING subset**: " & $mov.windows & " windows, twinWin " &
formatFloat(movWin, ffDecimal, 1) & "% (bar >=70%: " &
(if movWin >= 70.0: "PASS" else: "FAIL") & "). **FULL suite**: " &
$full.windows & " windows, twinWin " & formatFloat(fullWin, ffDecimal, 1) & "%."
echo "\nSTATIC-subset saturation analysis (why twin ~ persistence by construction):"
lines.add("\n## STATIC-subset saturation\n")
for name in StaticOpponents:
if name notin agg: continue
let a = agg[name]
if a.windows == 0: continue
let n = float(a.windows)
let slowPct = 100.0 * float(a.slowN) / float(max(1, a.speedN))
let meanSp = a.speedSum / float(max(1, a.speedN))
let margin = (a.persAde - a.twinAde) / n
echo " ", name, ": mean |enemy speed| ", formatFloat(meanSp, ffDecimal, 2),
" u/tick, ", $int(slowPct + 0.5),
"% of scanned ticks < 0.5 u/tick -> the realized path is near-stationary",
" (persistence is exactly optimal at v=0), so the constant-velocity carry",
" and the twin's stationary/corner kernels coincide and the twin can only",
" match or lose; margin ", formatFloat(margin, ffDecimal, 3), "."
lines.add "- **" & name & "**: mean |enemy speed| " &
formatFloat(meanSp, ffDecimal, 2) & " u/tick, " & $int(slowPct + 0.5) &
"% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence " &
"(v~0) is exactly optimal and the twin's stationary/corner kernels coincide with " &
"it — the twin can only match or lose, never win (margin " &
formatFloat(margin, ffDecimal, 3) & ")."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g5p.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art
when isMainModule:
main()