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