216 lines
8.2 KiB
Nim
216 lines
8.2 KiB
Nim
## G4 live-identification benchmark harness (CHIMERA M3).
|
|
##
|
|
## Runs headless 1v1 battles (server on a random port, tps=-1, `--enable-initial-
|
|
## position`) of the ChimeraBot observation sidecar against the 8 sample-bot
|
|
## ground-truth targets from `docs/chimera-spec.md` §12, parses the /tmp
|
|
## telemetry, and reports ticks-to-posterior>0.8 per expected kernel plus
|
|
## censoring rate and 5-tick ADE/FDE.
|
|
##
|
|
## Findings (per the DSL v0 defaults) are reported, not tuned away — a G4 miss is
|
|
## a design-level result to be analyzed, exactly as the milestone intends.
|
|
##
|
|
## Requires Java + the TR server/runner JARs + the unpacked Nim sample bots.
|
|
## Throwaway outputs (staged bot binary, telemetry) live only under /tmp.
|
|
## Run: `nim c -r --hints:off -d:release tests/bench_g4.nim` from ChimeraBot_garage.
|
|
|
|
import std/[os, osproc, strutils, sequtils, math, tables, algorithm]
|
|
import test_framework/server_manager
|
|
import test_framework/runner_process
|
|
|
|
const
|
|
SampleRoot = getEnv(
|
|
"TR_SAMPLE_BOTS",
|
|
"/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7")
|
|
GarageSrc = currentSourcePath().parentDir.parentDir / "src"
|
|
StageDir = getTempDir() / "chimera_g4_stage"
|
|
Telemetry = getTempDir() / "chimera_twin"
|
|
Archive = getTempDir() / "chimera_g4_run"
|
|
Rounds = 5 # enough ticks to observe 300 identification-capable ticks
|
|
Threshold = 0.8
|
|
TargetTicks = 300
|
|
MaxAttempts = 4
|
|
|
|
## expected kernel per ground-truth target (§12 verified mapping)
|
|
const Expected = {
|
|
"Crazy": "ZIGZAG",
|
|
"SpinBot": "ORBIT_BALLIST",
|
|
"RamFire": "RAMMER",
|
|
"Corners": "CORNER_RUN",
|
|
"Walls": "WALLCRAWL",
|
|
"TrackFire": "STATIC",
|
|
"Fire": "STATIC",
|
|
"VelociBot": "STOP_AND_GO",
|
|
}.toTable
|
|
|
|
proc guardSkip() =
|
|
let serverOk = fileExists(getEnv("TR_SERVER_JAR",
|
|
"/home/davide/Downloads/robocode-tankroyale/robocode-tankroyale-server.jar"))
|
|
let runnerOk = fileExists(getEnv("TR_BATTLE_RUNNER",
|
|
"/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"))
|
|
if not serverOk or not runnerOk or not dirExists(SampleRoot):
|
|
echo "Skipping G4 bench: TR_SERVER_JAR / TR_BATTLE_RUNNER / sample bots missing."
|
|
quit(0)
|
|
|
|
proc deps(): seq[string] =
|
|
for p in ["robocode_tankroyale_botapi", "jsony"]:
|
|
let (outp, _) = execCmdEx("nimble path " & p)
|
|
var line = ""
|
|
for l in outp.splitLines():
|
|
if l.len > 0: line = l; break
|
|
if line.len == 0:
|
|
quit("Cannot resolve dependency: " & p)
|
|
result.add "--path:" & line
|
|
|
|
proc stageBot(): string =
|
|
## Compile ChimeraBot into a throwaway /tmp dir with its json + boot script.
|
|
let botDir = StageDir / "ChimeraBot"
|
|
removeDir(StageDir)
|
|
createDir(botDir)
|
|
let bin = botDir / "ChimeraBot"
|
|
let deps = deps()
|
|
let (outp, code) = execCmdEx("nim c -d:release --hints:off " &
|
|
deps.join(" ") & " --out:\"" & bin & "\" " &
|
|
quoteShell(GarageSrc / "ChimeraBot.nim"), options = {poEvalCommand})
|
|
if code != 0 or not fileExists(bin):
|
|
quit("ChimeraBot compile failed:\n" & outp)
|
|
copyFile(GarageSrc / "ChimeraBot.json", botDir / "ChimeraBot.json")
|
|
writeFile(botDir / "ChimeraBot.sh",
|
|
"#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec \"./ChimeraBot\"\n")
|
|
let sh = botDir / "ChimeraBot.sh"
|
|
setFilePermissions(sh, getFilePermissions(sh) + {fpUserExec, fpGroupExec, fpOthersExec})
|
|
botDir
|
|
|
|
proc extract(line: string, key: string): tuple[found: bool, value: string] =
|
|
let needle = "\"" & key & "\":"
|
|
let i = line.find(needle)
|
|
if i < 0: return (false, "")
|
|
let rest = line[i + needle.len .. ^1]
|
|
var j = 0
|
|
while j < rest.len and rest[j] in {' ', '\t'}: inc j
|
|
if j < rest.len and rest[j] == '"':
|
|
let start = j + 1
|
|
var k = start
|
|
while k < rest.len and rest[k] != '"': inc k
|
|
return (true, rest[start ..< k])
|
|
# number
|
|
var k = j
|
|
while k < rest.len and (rest[k].isAlphaNumeric or rest[k] in {'.', '-', 'e', 'E'}):
|
|
inc k
|
|
return (true, rest[j ..< k])
|
|
|
|
type RoundStat = object
|
|
idTick: int # first tick posterior(expected) >= Threshold, else -1
|
|
sumTicks: int
|
|
sumCensorRate: float64
|
|
finalPosterior: float64
|
|
ade: float64
|
|
fde: float64
|
|
gapMax: int
|
|
gapViolations: int
|
|
|
|
proc parseFile(path, expectedKernel: string): RoundStat =
|
|
result.idTick = -1
|
|
let lines = readFile(path).splitLines()
|
|
for ln in lines:
|
|
if ln.len == 0: continue
|
|
if ln.startsWith("{\"event\":\"round_summary\""):
|
|
let _ = extract(ln, "finalPosterior").found
|
|
let p = extract(ln, "finalPosterior").value.parseFloat()
|
|
result.finalPosterior = p
|
|
let t = extract(ln, "ticks").value.parseInt()
|
|
result.sumTicks = t
|
|
result.sumCensorRate = extract(ln, "censorRate").value.parseFloat()
|
|
result.ade = extract(ln, "ade").value.parseFloat()
|
|
result.fde = extract(ln, "fde").value.parseFloat()
|
|
result.gapMax = extract(ln, "scanGapMax").value.parseInt()
|
|
result.gapViolations = extract(ln, "scanGapViolations").value.parseInt()
|
|
elif ln.startsWith("{\"tick\""):
|
|
let (tf, ts) = extract(ln, "tick")
|
|
if not tf: continue
|
|
let tick = ts.parseInt()
|
|
# posteriorTop5 payload: find expected kernel weight
|
|
let top = ln.substr(ln.find("posteriorTop5"))
|
|
let nameI = top.find("\"name\":\"" & expectedKernel & "\",\"w\":")
|
|
if nameI >= 0:
|
|
let wI = top.find("\"w\":", nameI) + len("\"w\":")
|
|
var j = wI
|
|
while top[j] in Digits or top[j] == '.': inc j
|
|
let w = top[wI ..< j].parseFloat()
|
|
if w >= Threshold and (result.idTick < 0 or tick < result.idTick):
|
|
result.idTick = tick
|
|
|
|
proc run() =
|
|
guardSkip()
|
|
echo "[G4] staging ChimeraBot -> ", StageDir
|
|
let botDir = stageBot()
|
|
|
|
removeDir(Telemetry)
|
|
removeDir(Archive)
|
|
createDir(Archive)
|
|
ensureServer()
|
|
let url = getServerUrl()
|
|
|
|
echo "\nOpponent Rounds idTicks(sum) idTick_best finalPost censorRate ade5 fde5 gapMax/viol"
|
|
var allTicks = 0
|
|
var passCount = 0
|
|
for opp in sorted(toSeq(Expected.keys)):
|
|
putEnv("CHIMERA_OPPONENT", opp)
|
|
putEnv("CHIMERA_TELEMETRY_DIR", Telemetry)
|
|
let sampleBot = SampleRoot / opp
|
|
var ok = false
|
|
# Flaky boot: the persistent server can race a battle start; retry.
|
|
for attempt in 1 .. MaxAttempts:
|
|
removeDir(Telemetry)
|
|
sleep(1500)
|
|
try:
|
|
discard runBattleRunner(url, @[botDir, sampleBot], rounds = Rounds,
|
|
timeout = 300000)
|
|
ok = true
|
|
break
|
|
except CatchableError:
|
|
if attempt >= MaxAttempts:
|
|
echo " ", opp, ": battle failed after ", MaxAttempts, " attempts"
|
|
if not ok: continue
|
|
if not dirExists(Archive): createDir(Archive)
|
|
copyDir(Telemetry, Archive / opp) # keep per-opponent telemetry for analysis
|
|
# aggregate best round + total ticks
|
|
let files = toSeq(walkFiles(Telemetry / "*.jsonl"))
|
|
var best = RoundStat(idTick: high(int), finalPosterior: 0.0,
|
|
ade: 0.0, fde: 0.0)
|
|
var roundTicks = 0
|
|
var any = false
|
|
for f in files:
|
|
let rs = parseFile(f, Expected[opp])
|
|
if rs.sumTicks == 0: continue
|
|
any = true
|
|
roundTicks += rs.sumTicks
|
|
if rs.idTick > 0 and rs.idTick < best.idTick:
|
|
best.idTick = rs.idTick
|
|
if rs.finalPosterior > best.finalPosterior:
|
|
best.finalPosterior = rs.finalPosterior
|
|
best.sumCensorRate = rs.sumCensorRate
|
|
best.ade = rs.ade
|
|
best.fde = rs.fde
|
|
best.gapMax = rs.gapMax
|
|
best.gapViolations = rs.gapViolations
|
|
if not any:
|
|
echo " ", opp, ": no telemetry produced"
|
|
continue
|
|
allTicks += roundTicks
|
|
let idStr = if best.idTick < 0 or best.idTick >= high(int): "-"
|
|
else: $best.idTick & (if best.idTick <= TargetTicks: "*" else: "")
|
|
let passed = best.idTick > 0 and best.idTick <= TargetTicks
|
|
if passed: inc passCount
|
|
echo " ", alignLeft(opp, 12), " ", align($Rounds, 4), " ",
|
|
align($roundTicks, 8), " ", align(idStr, 10), " ",
|
|
align($best.finalPosterior, 9), " ",
|
|
align($best.sumCensorRate, 7), " ",
|
|
align($best.ade, 6), " ", align($best.fde, 6), " ",
|
|
$best.gapMax & "/" & $best.gapViolations
|
|
|
|
echo "\nTotal identification-capable ticks observed: ", allTicks
|
|
echo "Passed (idTick<=300): ", passCount, "/", Expected.len
|
|
echo "Per-opponent telemetry archived at: ", Archive
|
|
|
|
when isMainModule:
|
|
run() |