ChimeraBot_garage: M3 — observation sidecar + live identification benchmark (G3/G4, G5-metrics)

This commit is contained in:
2026-10-07 00:08:40 +02:00
parent c77541a6d7
commit 7e2dd3f559
6 changed files with 623 additions and 3 deletions
+32
View File
@@ -32,6 +32,8 @@ import ChimeraBot/modules/radar
import ChimeraBot/modules/tfil
import ChimeraBot/modules/ELM/elm_gun
import ChimeraBot/modules/ELM/elm_features
import ChimeraBot/chimera/observer
import ChimeraBot/chimera/dsl
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
## only what it scans, so this is a cap, not a limit
@@ -75,11 +77,22 @@ type ChimeraBot* = ref object of Bot
shotsFired: int ## diagnostics, reset on round end
roundNo: int ## bumped on every RoundEnded, so the shot log can be
## joined to a recording round
observer: Observer ## observation-only sidecar (§12 G3/G4 telemetry)
opponentLabel: string ## telemetry filename label (env, observation-only)
proc newChimeraBot*(): ChimeraBot =
result = ChimeraBot()
result.mover = initTFIL() # movement is programmed -> body/turret/gun BLACK
result.gun = initElmGun(priorScale = OnlinePriorScale) # hidden layer loaded, online
# Telemetry sink: throwaway output only ever lives in /tmp (garage rule).
# The env override is for scratch test dirs; the bots never read env for
# behaviour, only for this observation-log destination.
let telemetryDir = getEnv("CHIMERA_TELEMETRY_DIR", "/tmp/chimera_twin")
# The API's getBotName() is not populated (updateBotNames is never invoked), so
# the benchmark harness supplies the opponent token via env for the telemetry
# filename; it labels observations, it does not change behaviour.
result.opponentLabel = getEnv("CHIMERA_OPPONENT", "")
result.observer = initObserver(allKernels(), telemetryDir)
setRadarColor(WHITE) # overwritten by initRadar() before the first tick
method onScannedBot*(bot: ChimeraBot, e: ScannedBotEvent) =
@@ -91,6 +104,15 @@ method onScannedBot*(bot: ChimeraBot, e: ScannedBotEvent) =
onScanFull(bot.tick, e.x, e.y, getX(), getY()) # history the gun needs
if bot.gun.online:
bot.gun.noteEnemyAt(bot.tick, e.x, e.y) # delayed-label trace
# Observation sidecar: fold the scan stream into the intent ledger + posterior
# and record telemetry. Observation-only — it issues no command of any kind.
# `opponent` labels the telemetry file; when the harness did not supply a label
# it falls back to the (typically empty) API name lookup.
let opp = (if bot.opponentLabel.len > 0: bot.opponentLabel
else: getBotName(e.scannedBotId))
bot.observer.observeScan(bot.tick, e.x, e.y, e.direction, e.speed, e.energy,
getX(), getY(), opp,
getArenaWidth().float, getArenaHeight().float)
for i, ei in bot.enemies:
if ei.id == e.scannedBotId:
bot.enemies[i].x = e.x
@@ -111,6 +133,12 @@ method onHitByBullet*(bot: ChimeraBot, e: HitByBulletEvent) =
# "no fire" and the enemy's shot goes uncounted (see modules/tfil.nim, FireFix)
bot.mover.noteEnemyBulletHit(e.bullet.power)
method onRoundStarted*(bot: ChimeraBot, e: RoundStartedEvent) =
## Per-round reset of the identification posterior (uniform, as CHIMERA G4
## requires — e.g. Corners re-samples its start corner each round). The
## observation sidecar is the only consumer; no command changes.
bot.observer.startRound(e.roundNumber)
method onBulletHit*(bot: ChimeraBot, e: BulletHitBotEvent) =
bot.mover.noteDamageDealt(e.damage)
@@ -126,6 +154,9 @@ method onRoundEnded*(bot: ChimeraBot, e: RoundEndedEventForBot) =
bot.enemies = @[]
bot.shotsFired = 0
bot.mover.resetRound()
# close the round's telemetry file with the final kernel trace (observation
# sidecar only; no command paths are touched)
bot.observer.endRound()
method buildBelief(bot: ChimeraBot, power: float): GunBelief =
## Assemble what the gun is allowed to know. Everything here comes from our
@@ -249,6 +280,7 @@ method run*(bot: ChimeraBot) =
setTurnRate(turnRate)
bot.computeGun() # gun intent, also before go()
go()
bot.observer.writeTick(bot.tick) # observation telemetry, after go()
inc bot.tick
when isMainModule:
+1
View File
@@ -258,3 +258,4 @@ task test, "Run unit tests":
exec "nim c -r --hints:off ../tests/test_ledger.nim"
exec "nim c -r --hints:off ../tests/test_hedge.nim"
exec "nim c -r --hints:off ../tests/test_oracle_g1.nim"
exec "nim c -r --hints:off ../tests/test_observer.nim"
@@ -44,6 +44,9 @@ type
margin*: float64 ## wall proximity margin
segmentLen*: float64 ## wall-crawl segment length
zigzagTicks*: int ## Crazy-style periodic 180 flip interval
period*: int ## STOP_AND_GO oscillation period (VelociBot: 64)
fwdSpeed*: float64 ## STOP_AND_GO forward cruise speed (VelociBot: 4)
backSpeed*: float64 ## STOP_AND_GO backward cruise speed (VelociBot: -6)
corner*: int ## initial corner index (CORNER_RUN)
fireCooldown*: int ## min ticks between shots
rngClass*: int ## 0 = LCG, 1 = xorshift64, 2 = splitmix64
@@ -73,7 +76,8 @@ type
proc defaultParams*(): Params =
Params(range: 300.0, hysteresis: 60.0, dir: 1.0, speed: 6.0, margin: 40.0,
segmentLen: 200.0, zigzagTicks: 60, corner: 0, fireCooldown: 15,
rngClass: 0, seed: 0x2545F4914F6CDD1D'u64, arenaW: 800.0, arenaH: 600.0)
rngClass: 0, seed: 0x2545F4914F6CDD1D'u64, arenaW: 800.0, arenaH: 600.0,
period: 64, fwdSpeed: 4.0, backSpeed: -6.0)
proc defaultMemory*(p: Params): KernelMem =
KernelMem(phase: 0, counter: 0, latch: 1.0, startDir: 0.0,
@@ -136,10 +140,26 @@ proc stepOrbitLock(e: EnemyState, m: MyState, p: Params,
proc stepOrbitBallist(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: SpinBot (turn 10000, maxSpeed 5, forward 10000, fire(3) on scan).
result.turnRate = MaxTurnRate
## `setTurnRight(10000)` spins CLOCKWISE = negative turn rate, so the default
## registered instance carries `dir = -1`; a CCW spinner is a distinct kernel.
result.turnRate = MaxTurnRate * p.dir
result.targetSpeed = 5.0
result.fire = fireGate(e, p, 3.0)
# ── K4 STOP_AND_GO — VelociBot: periodic forward/back speed oscillation ────
proc stepStopAndGo(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: VelociBot (setTargetSpeed(4) at t%64==0, setTargetSpeed(-6) at
## t%64==32, turnRate 0, gun turn 15, fire(1) on scan). The commanded target
## speed is sticky in the API, so it stays +4 for the first half of the period
## and -6 for the second half; turn rate is 0 throughout (except brief
## hit/turn bursts, which the speed/turn channels barely weight).
result.turnRate = 0.0
let phase = e.tick mod p.period
result.targetSpeed = if phase < p.period div 2: p.fwdSpeed else: p.backSpeed
result.fire = fireGate(e, p, 1.0)
# ── ZIGZAG — Crazy: long forward runs + periodic 180 flips ──────────────────
proc stepZigzag(e: EnemyState, m: MyState, p: Params,
@@ -280,7 +300,9 @@ proc allKernels*(): seq[Kernel] =
let d = defaultParams()
@[
Kernel(name: "ORBIT_LOCK", step: stepOrbitLock, defaultParams: d),
Kernel(name: "ORBIT_BALLIST", step: stepOrbitBallist, defaultParams: d),
Kernel(name: "ORBIT_BALLIST", step: stepOrbitBallist,
defaultParams: block: (var q = d; q.dir = -1.0; q)), # SpinBot: CW
Kernel(name: "STOP_AND_GO", step: stepStopAndGo, defaultParams: d),
Kernel(name: "ZIGZAG", step: stepZigzag, defaultParams: d),
Kernel(name: "RAMMER", step: stepRammer, defaultParams: d),
Kernel(name: "CORNER_RUN", step: stepCornerRun, defaultParams: d),
@@ -0,0 +1,281 @@
## CHIMERA observation sidecar — ledger + Hedge posterior + telemetry.
##
## Source of truth: `docs/chimera-spec.md` §4 (intent ledger), §7 (Hedge), §12
## (G3 censoring budget, G4 identification). This module is **observation-only**:
## it consumes the scan stream the radar already produces and never issues a
## command. `ChimeraBot.nim` calls it from `onScannedBot` / the tick loop, purely
## for telemetry, so the bot's command behaviour is byte-identical with or
## without it.
##
## Per scan tick it folds the observable stream into a `LedgerObs`, scores every
## kernel's prediction with `oracle.intentLoss`, and updates the Hedge posterior
## (uniform at round start). Telemetry is one JSONL line per tick under
## `<telemetryDir>/<opponent>-<round>.jsonl`; throwaway output therefore lives in
## `/tmp` (garage rule). A `round_summary` line carries the final argmax, the
## censoring rate, scan-gap stats and the 5-tick prediction ADE/FDE.
##
## The 5-tick ADE/FDE is a **posterior-weighted enemy self-rollout** over the
## physics mirror (predicted enemy intents, no counterfactual plan) — the
## readiness check for the M4 twin rollout, not the twin itself.
import std/[math, os, strutils]
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle
const
MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check
PredSlots* = 8 ## ring size; > MaxHorizon so an origin survives its queries
type
Observer* = ref object
kernels: seq[Kernel]
hedge: Hedge
mems: seq[KernelMem]
cfg: HedgeConfig
telemetryDir: string
arenaW, arenaH: float64
havePrev: bool
prev: Scan
prevOwnX, prevOwnY: float64
haveCur: bool
cur: Scan
curOwnX, curOwnY: float64
scanTick: int ## tick of the most recent scan (-1 = none yet)
lastObs: LedgerObs
haveLastObs: bool
censored, ticks: int
gapMax, gapViolations: int
round: int
opponent: string
f: File
fileOpen: bool
## predictions: `predPos[(origin mod PredSlots)][h]` is the enemy position
## predicted `h` ticks after `origin`; `predOrigin` guards a slot's owner.
predPos: array[PredSlots, array[MaxHorizon + 1, tuple[x, y: float64]]]
predOrigin: array[PredSlots, int]
adeSum, fdeSum: float64
adeN, fdeN: int
# ── construction / round lifecycle ──────────────────────────────────────────
proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer =
new(result)
result.kernels = kernels
result.cfg = HedgeConfig()
result.hedge = initHedge(kernelNames(kernels), result.cfg)
result.mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len:
result.mems[i] = defaultMemory(kernels[i].defaultParams)
result.telemetryDir = telemetryDir
result.scanTick = -1
for i in 0 ..< PredSlots: result.predOrigin[i] = -1
proc resetRound(o: Observer) =
o.hedge = initHedge(kernelNames(o.kernels), o.cfg)
for i in 0 ..< o.kernels.len:
o.mems[i] = defaultMemory(o.kernels[i].defaultParams)
o.havePrev = false
o.haveCur = false
o.haveLastObs = false
o.censored = 0
o.ticks = 0
o.scanTick = -1
o.gapMax = 0
o.gapViolations = 0
o.adeSum = 0; o.adeN = 0
o.fdeSum = 0; o.fdeN = 0
for i in 0 ..< PredSlots: o.predOrigin[i] = -1
proc sanitize*(s: string): string =
## Filename-safe opponent token: collapse runs of non-alphanumerics to `_`.
var prevSep = false
for c in s:
if c.isAlphaNumeric:
result.add c
prevSep = false
elif not prevSep and result.len > 0:
result.add '_'
prevSep = true
while result.len > 0 and result[^1] == '_':
result.setLen(result.len - 1)
proc openTelemetry(o: Observer) =
if o.telemetryDir.len == 0 or o.fileOpen: return
createDir(o.telemetryDir)
let who = if o.opponent.len > 0: sanitize(o.opponent) else: "unknown"
let path = o.telemetryDir / (who & "-" & $o.round & ".jsonl")
o.f = open(path, fmWrite)
o.fileOpen = true
proc startRound*(o: Observer, round: int) =
## Called on `RoundStartedEvent`. Re-initialises the posterior UNIFORM, as
## the spec requires per round (Corners re-samples its start corner each round).
o.resetRound()
o.round = round # `opponent` is retained: it is per-BATTLE, not per-round
# ── ledger folding (observer-local fire rule) ───────────────────────────────
proc foldObs(prev, cur: Scan): LedgerObs =
## Turn + speed channels verbatim from `ledger`. Fire: only an energy drop
## inside `[0.1, 3.0]` can be the enemy's own shot; a larger drop is external
## damage (our bullet, a collision), so the fire channel stays UNOBSERVED
## rather than censoring a tick the enemy's intent is not ambiguous about.
result = turnRateInterval(prev, cur)
result.tick = cur.tick
let sp = targetSpeedInterval(prev.speed, cur.speed)
if sp.targetKnown:
result.targetSpeed = sp.targetSpeed
result.targetKnown = true
if sp.censored:
result.censored = true
let drop = prev.energy - cur.energy
if drop >= MinFirepower - IntervalEps and drop <= MaxFirepower + IntervalEps:
result.fire = drop
result.fireKnown = true
# ── 5-tick prediction (posterior-weighted enemy self-rollout) ───────────────
proc recordPrediction(o: Observer, s: Scan, ownX, ownY: float64) =
var mems = newSeq[KernelMem](o.kernels.len)
for i in 0 ..< o.kernels.len: mems[i] = o.mems[i]
var st = EnemyState(tick: s.tick, x: s.x, y: s.y, direction: s.direction,
speed: s.speed, energy: s.energy)
let my = MyState(x: ownX, y: ownY)
let slot = s.tick mod PredSlots
o.predOrigin[slot] = s.tick
for h in 1 .. MaxHorizon:
var intent: Intent
for i in 0 ..< o.kernels.len:
let it = o.kernels[i].step(st, my, o.kernels[i].defaultParams, mems[i])
intent.turnRate += o.hedge.weights[i] * it.turnRate
intent.targetSpeed += o.hedge.weights[i] * it.targetSpeed
let ns = stepSpeed(st.speed, intent.targetSpeed)
st.direction = wrap180(st.direction + limitTurnRate(intent.turnRate, ns))
st.speed = ns
st.x = clamp(st.x + ns * cos(degToRad(st.direction)), 0.0, o.arenaW)
st.y = clamp(st.y + ns * sin(degToRad(st.direction)), 0.0, o.arenaH)
st.tick = s.tick + h
o.predPos[slot][h] = (st.x, st.y)
proc scoreScan(o: Observer, s: Scan) =
for h in 1 .. MaxHorizon:
let org = s.tick - h
if org < 0: continue
let slot = org mod PredSlots
if o.predOrigin[slot] != org: continue
let p = o.predPos[slot][h]
let err = hypot(p.x - s.x, p.y - s.y)
o.adeSum += err; inc o.adeN
if h == MaxHorizon:
o.fdeSum += err; inc o.fdeN
# ── per-scan entry point ────────────────────────────────────────────────────
proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float64,
ownX, ownY: float64, opponent: string,
arenaW, arenaH: float64) =
## Consume one `ScannedBotEvent`. Observation-only: no command is ever issued.
if opponent.len > 0: o.opponent = opponent
if arenaW > 0: o.arenaW = arenaW
if arenaH > 0: o.arenaH = arenaH
if o.arenaW <= 0: o.arenaW = 800.0
if o.arenaH <= 0: o.arenaH = 600.0
o.scanTick = tick
if o.telemetryDir.len > 0 and not o.fileOpen: o.openTelemetry()
let s = Scan(tick: tick, x: x, y: y, direction: direction, speed: speed,
energy: energy)
if o.havePrev and o.prev.tick == tick:
o.cur = s; o.curOwnX = ownX; o.curOwnY = ownY; o.haveCur = true
return
o.scoreScan(s)
if o.havePrev:
let g = tick - o.prev.tick
if g > o.gapMax: o.gapMax = g
if g > 1: inc o.gapViolations
let obs = foldObs(o.prev, s)
o.lastObs = obs
o.haveLastObs = true
inc o.ticks
if obs.censored:
inc o.censored
else:
let e = EnemyState(tick: o.prev.tick, x: o.prev.x, y: o.prev.y,
direction: o.prev.direction, speed: o.prev.speed,
energy: o.prev.energy)
let my = MyState(x: o.prevOwnX, y: o.prevOwnY)
var losses = newSeq[float64](o.kernels.len)
for i in 0 ..< o.kernels.len:
let pred = o.kernels[i].step(e, my, o.kernels[i].defaultParams, o.mems[i])
losses[i] = intentLoss(pred, obs, s.speed)
o.hedge.update(losses)
o.prev = s; o.prevOwnX = ownX; o.prevOwnY = ownY; o.havePrev = true
o.cur = s; o.curOwnX = ownX; o.curOwnY = ownY; o.haveCur = true
o.recordPrediction(s, ownX, ownY)
# ── telemetry ───────────────────────────────────────────────────────────────
proc jsonInterval(iv: Interval): string =
"[" & $iv.lo & "," & $iv.hi & "]"
proc censorRate*(o: Observer): float64 =
if o.ticks == 0: 0.0 else: float(o.censored) / float(o.ticks)
proc argmaxName*(o: Observer): string = o.hedge.argmaxName()
proc posterior*(o: Observer, name: string): float64 = o.hedge.posterior(name)
proc entropy*(o: Observer): float64 = o.hedge.entropy()
proc writeTick*(o: Observer, tick: int) =
## One telemetry line per tick. Called after `go()`, so a scan dispatched by
## this tick is already folded in.
if not o.fileOpen: return
let scanned = o.scanTick == tick
var line = "{\"tick\":" & $tick & ",\"scan\":" & $scanned
if scanned and o.haveLastObs:
let ob = o.lastObs
if ob.turnKnown: line.add ",\"turnRateInterval\":" & jsonInterval(ob.turnRate)
if ob.targetKnown: line.add ",\"targetSpeedInterval\":" & jsonInterval(ob.targetSpeed)
if ob.fireKnown: line.add ",\"fireObs\":" & $ob.fire
line.add ",\"censor\":" & $ob.censored
line.add ",\"posteriorTop5\":["
let top = o.hedge.topK(5)
for i, kv in top:
if i > 0: line.add ","
line.add "{\"name\":\"" & kv.name & "\",\"w\":" & $kv.weight & "}"
line.add "],\"entropy\":" & $o.hedge.entropy()
line.add ",\"censorRate\":" & $o.censorRate()
line.add "}\n"
o.f.write(line)
flushFile(o.f)
proc endRound*(o: Observer) =
## Close the round's telemetry with the identified kernel trace and the
## G5-metrics readiness numbers (5-tick ADE / FDE).
if not o.fileOpen: return
let top = o.hedge.argmaxName()
var line = "{\"event\":\"round_summary\",\"round\":" & $o.round &
",\"opponent\":\"" & sanitize(o.opponent) & "\"" &
",\"finalKernel\":\"" & top & "\"" &
",\"finalPosterior\":" & $o.hedge.posterior(top) &
",\"ticks\":" & $o.ticks &
",\"censored\":" & $o.censored &
",\"censorRate\":" & $o.censorRate() &
",\"scanGapMax\":" & $o.gapMax &
",\"scanGapViolations\":" & $o.gapViolations &
",\"ade\":" & $(if o.adeN == 0: 0.0 else: o.adeSum / float(o.adeN)) &
",\"fde\":" & $(if o.fdeN == 0: 0.0 else: o.fdeSum / float(o.fdeN)) &
",\"n\":" & $o.adeN & "}\n"
o.f.write(line)
flushFile(o.f)
o.f.close()
o.fileOpen = false
+216
View File
@@ -0,0 +1,216 @@
## 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()
+68
View File
@@ -0,0 +1,68 @@
## Offline test for the observation sidecar (observer.nim): feeding it a
## synthetic oracle stream for a known kernel must drive the posterior to that
## kernel at high weight, and the telemetry writer must emit well-formed JSONL.
## No Java needed. Run: from ChimeraBot_garage, `nim c -r --path:tests tests/test_observer.nim`.
import std/[strutils, os]
import chimera/dsl
import chimera/oracle
import chimera/observer
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
let telemetryDir = getTempDir() / "chimera_observer_test" & $getCurrentProcessId()
removeDir(telemetryDir)
block:
echo "observer: identification over synthetic streams"
for i in 0 ..< kernels.len:
removeDir(telemetryDir)
let env = defaultEnv()
let o = initObserver(kernels, telemetryDir)
o.startRound(1)
# Replay the kernel's own oracle stream through observeScan.
let stream = generateOracle(kernels[i], kernels[i].defaultParams, env, 400)
for t in 0 ..< stream.scans.len:
let s = stream.scans[t]
o.observeScan(s.tick, s.x, s.y, s.direction, s.speed, s.energy,
env.myX, env.myY, kernels[i].name, env.arenaW, env.arenaH)
o.endRound()
let post = o.posterior(kernels[i].name)
check("posterior[" & kernels[i].name & "] >= 0.9", post >= 0.9,
"got " & $post)
check("argmax is " & kernels[i].name, o.argmaxName() == kernels[i].name,
"got " & o.argmaxName())
block:
echo "observer: telemetry files are well-formed (Crazy/ZIGZAG)"
removeDir(telemetryDir)
let env = defaultEnv()
let o = initObserver(kernels, telemetryDir)
o.startRound(1)
let stream = generateOracle(kernels[2], kernels[2].defaultParams, env, 120)
for t in 0 ..< stream.scans.len:
let s = stream.scans[t]
o.observeScan(s.tick, s.x, s.y, s.direction, s.speed, s.energy,
env.myX, env.myY, "Crazy", env.arenaW, env.arenaH)
o.writeTick(s.tick)
o.endRound()
let path = telemetryDir / "Crazy-1.jsonl"
check("telemetry file exists", fileExists(path), path)
if fileExists(path):
let lines = readFile(path).splitLines()
check("file has per-tick lines + summary", lines.len > 90,
"got " & $lines.len)
check("first line is a tick JSON", lines[0].startsWith("{\"tick\""))
var hasSummary = false
for ln in lines:
if ln.startsWith("{\"event\":\"round_summary\""): hasSummary = true
check("summary line present", hasSummary)
removeDir(telemetryDir)
echo ""
if failed == 0: echo "all observer tests passed"
else: echo failed, " observer test(s) FAILED"; quit(1)