Files
SirRoboGarage/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim
T

434 lines
18 KiB
Nim

## 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, ./twinsim, ./residual, ./fusion, ./influence
const
MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check
PredSlots* = 8 ## ring size; > MaxHorizon so an origin survives its queries
FusionEnabled* = not defined(chimeraNoFusion) and not defined(chimeraInert)
## M6 kill switches: `-d:chimeraNoFusion` drops the residual+fusion layer,
## `-d:chimeraInert` drops every CHIMERA command path (== M1 exact copy).
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
curOwnDir, curOwnSpeed: float64
scanTick: int ## tick of the most recent scan (-1 = none yet)
lastObs: LedgerObs
haveLastObs: bool
censored, ticks: int
gapMax, gapViolations: int
enemyHeat: float64 ## ledger-derived enemy gun-heat estimate (probe gate)
round: int
opponent: string
f: File
fileOpen: bool
# Cross-round posterior carry-over (M5.5; default on, `-d:chimeraFreshRound`
# restores the per-round reset).
carryOver*: bool
# M6 residual + fusion (spec §10). Observation-only training lives here
# because the ledger fold is already computed here; the influence overlay
# itself runs in the bot's command path.
residual: ResidualHead
fusion: Fusion
prevOwnDir, prevOwnSpeed: float64
lastRealizedTurn, lastRealizedSpeed: float64
fireRateEma: float64
## 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
result.enemyHeat = 3.0
result.residual = initResidualHead()
result.fusion = initFusion()
result.carryOver = not defined(chimeraFreshRound)
for i in 0 ..< PredSlots: result.predOrigin[i] = -1
proc resetRoundStats(o: Observer) =
## Per-round observables and counters, with NO touch to the posterior or the
## kernel memories. Cleared on every round start (carry-over keeps the latter).
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
o.enemyHeat = 3.0 ## round-start heat (spec §5)
o.prevOwnDir = 0.0; o.prevOwnSpeed = 0.0
o.lastRealizedTurn = 0.0; o.lastRealizedSpeed = 0.0
o.fireRateEma = 0.0
for i in 0 ..< PredSlots: o.predOrigin[i] = -1
proc resetRound(o: Observer) =
## Fresh-round ablation: uniform posterior + default kernel memories.
o.hedge = initHedge(kernelNames(o.kernels), o.cfg)
for i in 0 ..< o.kernels.len:
o.mems[i] = defaultMemory(o.kernels[i].defaultParams)
o.residual.reset()
o.fusion = initFusion()
o.resetRoundStats()
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`. With carry-over (default, M5.5) the posterior
## and kernel memories survive: the enemy is the same program across rounds, so
## identification compounds. Only RNG-derived memory is re-sampled (a per-round
## parameter such as Corners' start corner must not carry). With
## `-d:chimeraFreshRound` (`carryOver == false`) the posterior resets UNIFORM,
## which is the M3/M4 behaviour and the G6 carry-over ablation arm.
if o.carryOver:
o.resetRoundStats()
for i in 0 ..< o.kernels.len:
o.mems[i].rngState = o.kernels[i].defaultParams.seed
else:
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,
ownDir = 0.0, ownSpeed = 0.0) =
## Consume one `ScannedBotEvent`. Observation-only: no command is ever issued.
## `ownDir`/`ownSpeed` are recorded for offline plan simulation (twinsim); they
## default to 0 so callers that do not have them still compile unchanged.
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
o.curOwnDir = ownDir; o.curOwnSpeed = ownSpeed
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
# Enemy gun-heat estimate (probe gate, spec §5): a fired shot pins heat to
# `1 + power/5`; writeTick decays it one per tick. Observation-only.
if obs.fireKnown: o.enemyHeat = gunHeat(obs.fire)
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)
var mixTurn, mixSpeed, mixFire = 0.0
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)
let w = o.hedge.weights[i]
mixTurn += w * pred.turnRate
mixSpeed += w * pred.targetSpeed
mixFire += w * pred.fire
o.hedge.update(losses)
when FusionEnabled:
# Residual + fusion training (spec §10): learn the mixture's residual on
# THIS realized intent, then score the three predictors. Observation
# only — nothing here can change a command.
let realized = PredIntent(
turn: (if obs.turnKnown: (obs.turnRate.lo + obs.turnRate.hi) / 2.0 else: mixTurn),
speed: (if obs.targetKnown: (obs.targetSpeed.lo + obs.targetSpeed.hi) / 2.0 else: mixSpeed),
fire: (if obs.fireKnown: obs.fire else: mixFire))
let feat = features(ResidualInput(
lastTurn: o.lastRealizedTurn, lastSpeed: o.lastRealizedSpeed,
scanAge: float64(s.tick - o.prev.tick),
dist: hypot(o.prev.x - o.prevOwnX, o.prev.y - o.prevOwnY),
ownTurn: wrap180(ownDir - o.prevOwnDir), ownSpeed: o.prevOwnSpeed))
let rpred = o.residual.predict(feat)
let persP = PredIntent(turn: o.lastRealizedTurn,
speed: o.lastRealizedSpeed, fire: o.fireRateEma)
o.fusion.update(realized, [
PredIntent(turn: mixTurn, speed: mixSpeed, fire: mixFire),
PredIntent(turn: mixTurn + rpred.turn, speed: mixSpeed + rpred.speed,
fire: clamp(mixFire + rpred.fire, 0.0, 1.0)),
persP])
o.residual.observe(feat, ResidualTarget(
turn: realized.turn - mixTurn, speed: realized.speed - mixSpeed,
fire: realized.fire - mixFire))
o.lastRealizedTurn = realized.turn
o.lastRealizedSpeed = realized.speed
if obs.fireKnown:
let y = (if obs.fire > 0.0: 1.0 else: 0.0)
o.fireRateEma = 0.95 * o.fireRateEma + 0.05 * y
o.prevOwnDir = o.curOwnDir
o.prevOwnSpeed = o.curOwnSpeed
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.curOwnDir = ownDir; o.curOwnSpeed = ownSpeed
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 hasCurrent*(o: Observer): bool = o.haveCur
proc enemyGunHeat*(o: Observer): float64 = o.enemyHeat
proc probeOrigin*(o: Observer): ReplayTick =
## The current causal posterior + observed enemy/own state, as the probe
## scheduler's counterfactual origin. Read-only: `mems`/`weights` are copied.
result = ReplayTick(tick: o.cur.tick, ex: o.cur.x, ey: o.cur.y,
edir: o.cur.direction, espeed: o.cur.speed,
eenergy: o.cur.energy,
ox: o.curOwnX, oy: o.curOwnY,
odir: o.curOwnDir, ospeed: o.curOwnSpeed,
lastTurn: 0.0, lastSpeed: o.cur.speed)
result.weights = o.hedge.weights
result.mems = o.mems
proc currentResidualInput(o: Observer): ResidualInput =
## Feature inputs at the current origin (dense stream => scanAge 1).
ResidualInput(
lastTurn: o.lastRealizedTurn, lastSpeed: o.lastRealizedSpeed,
scanAge: 1.0,
dist: (if o.haveCur: hypot(o.cur.x - o.curOwnX, o.cur.y - o.curOwnY) else: 0.0),
ownTurn: 0.0,
ownSpeed: (if o.haveCur: o.curOwnSpeed else: 0.0))
proc fusedPrediction*(o: Observer, k = MaxHorizon): FusedPrediction =
## The fused 5-tick counterfactual prediction at the current origin (M6).
## Computed on demand; O(k * kernels) and allocation-light.
if not o.haveCur: return
let origin = o.probeOrigin()
let rp = o.residual.predict(features(o.currentResidualInput()))
o.fusion.fusedPrediction(o.kernels, origin, rp, k)
proc fusedInfluence*(o: Observer): float64 =
## Twin steering authority (0..1), ramped down by realized prediction loss.
influenceScalar(o.fusion.lossEma, o.fusion.lossN)
proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights()
proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma
proc fusionSamples*(o: Observer): int = o.fusion.lossN
proc writeProbeEvent*(o: Observer, tick: int, kind, gateState: string,
entropyBefore, entropyAfter, turnRate,
targetSpeed: float64) =
## One JSONL line per triggered probe (executed or gate-blocked). The
## interventional G5' eval keys off `event==="probe"` lines.
if not o.fileOpen: return
o.f.write("{\"event\":\"probe\",\"tick\":" & $tick &
",\"kind\":\"" & kind & "\",\"gate\":\"" & gateState &
"\",\"entropyBefore\":" & $entropyBefore &
",\"entropyAfter\":" & $entropyAfter &
",\"turnRate\":" & $turnRate &
",\"targetSpeed\":" & $targetSpeed & "}\n")
flushFile(o.f)
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. Also decays the enemy gun-heat estimate.
if o.enemyHeat > 0.0: o.enemyHeat = max(0.0, o.enemyHeat - 1.0)
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
# Raw enemy + own state, so the twin rollout (M4/twinsim) can be replayed
# OFFLINE from the telemetry alone, without re-running Java. Observation-only.
if scanned and o.haveCur:
line.add ",\"ex\":" & $o.cur.x & ",\"ey\":" & $o.cur.y &
",\"edir\":" & $o.cur.direction &
",\"espeed\":" & $o.cur.speed &
",\"eenergy\":" & $o.cur.energy
if o.haveCur:
line.add ",\"ox\":" & $o.curOwnX & ",\"oy\":" & $o.curOwnY &
",\"odir\":" & $o.curOwnDir & ",\"ospeed\":" & $o.curOwnSpeed
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