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

260 lines
11 KiB
Nim
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## CHIMERA probe scheduler — active causal probing (spec §9, milestone M5).
##
## One probe per ~25 ticks (range 20–30), survival-gated, camouflaged as ordinary
## movement noise, and selected by **expected posterior-entropy reduction** over a
## small set of candidate actions (sudden stop, reversal, speed modulation,
## direction flip). The counterfactual engine is `twinsim.rollout`: for each
## candidate we roll each of the top-K kernels forward under OUR candidate action
## and measure how far the kernels' predicted enemy reactions separate. The
## candidate that separates them most removes the most posterior entropy.
##
## Decision 2 (spec §9): probes MAY cost score. The budget is a cost ledger; the
## survival gate is what keeps the spend bounded — a probe that would get us shot
## is never issued.
##
## This module is pure and deterministic: no I/O, no clock, no RNG. Everything
## derives from the ReplayTick posterior and the ProbeContext, so reruns are
## byte-identical (pinned by tests/test_probes.nim).
##
## Behaviour kill switch: compile with `-d:chimeraNoProbes` and the bot never
## calls this scheduler (see ChimeraBot.nim), so the command path is byte-identical
## to the M1 exact-copy baseline.
import std/[math, algorithm]
import ./physics, ./dsl, ./twinsim
const
ProbesEnabled* = not defined(chimeraNoProbes)
## Compile-time kill switch. `-d:chimeraNoProbes` removes the probe advisory
## from the bot entirely (G6 ablation OFF arm; command path == M1 baseline).
DefaultInterval* = 25 ## nominal probe cadence, ticks (spec: 20–30)
MinInterval* = 20
MaxInterval* = 30
ProbeHorizon* = 5 ## ticks of enemy reaction we predict (matches G5)
TopKernels* = 3 ## hypotheses whose separation drives selection
LowEnergy* = 25.0 ## "our energy is low" gate threshold
WallMargin* = 25.0 ## "wall-pinned" band from any wall
HeatHot* = 0.5 ## "their gunHeat is (near) zero"
AimTol* = 30.0 ## body-heading proxy cone for "aimed at us"
ProbeSigma* = 6.0 ## likelihood width (units) when scoring separation
RoundSoftLimit* = 2000 ## assumed round length for the "nearly over" gate
type
ProbeKind* = enum
## Enum order is the deterministic tie-break (earlier wins).
pkSuddenStop, pkReversal, pkSpeedModulation, pkDirectionFlip
ProbeCandidate* = object
kind*: ProbeKind
turnRate*: float64
targetSpeed*: float64
GateState* = object
allow*: bool
reason*: string
ProbeContext* = object
## Everything the gate needs, all observable / estimated.
tick*: int
ourEnergy*: float64
ownX*, ownY*, ownSpeed*: float64
arenaW*, arenaH*: float64
enemyX*, enemyY*: float64
enemyGunHeat*: float64 ## from the ledger's fire channel (+ decay)
enemyAimedAtUs*: bool ## body-heading proxy; gun aim is unobservable
roundLimit*: int ## 0 disables the round-end gate
ProbeDecision* = object
trigger*: bool ## the budget fired this tick
candidate*: ProbeCandidate
gate*: GateState
entropyBefore*: float64
entropyAfter*: float64 ## expected, after the most informative probe
ProbeScheduler* = object
kernels*: seq[Kernel]
ticksSinceProbe*: int
interval*: int
probes*: int ## executed (allowed) probe count
# ── construction ─────────────────────────────────────────────────────────────
proc initProbeScheduler*(kernels: seq[Kernel],
interval = DefaultInterval): ProbeScheduler =
result.kernels = kernels
result.interval = clamp(interval, MinInterval, MaxInterval)
# ── survival gate (spec §9) ──────────────────────────────────────────────────
proc aimedAtUs*(ownX, ownY, enemyX, enemyY, enemyDir: float64,
tol = AimTol): bool =
## True when the enemy's BODY heading points within `tol` of us. Gun aim is not
## observable, so body heading is the proxy (guns that ride the body are the
## common case); this makes the gate conservative, never trigger-happy.
abs(wrap180(bearingTo(enemyX, enemyY, ownX, ownY) - enemyDir)) <= tol
proc survivalGate*(ctx: ProbeContext): GateState =
## Deny order is the spec's order, so the reason string is deterministic.
if ctx.ourEnergy < LowEnergy:
return GateState(allow: false, reason: "energy")
if ctx.enemyAimedAtUs and ctx.enemyGunHeat <= HeatHot:
return GateState(allow: false, reason: "enemy-hot-aimed")
if ctx.ownX < WallMargin or ctx.ownX > ctx.arenaW - WallMargin or
ctx.ownY < WallMargin or ctx.ownY > ctx.arenaH - WallMargin:
return GateState(allow: false, reason: "wall-pinned")
if ctx.roundLimit > 0 and ctx.roundLimit - ctx.tick < 2 * MaxInterval:
return GateState(allow: false, reason: "round-end")
GateState(allow: true, reason: "ok")
# ── candidates + camouflage ──────────────────────────────────────────────────
proc candidates*(ctx: ProbeContext): seq[ProbeCandidate] =
## Four plausible body actions. Magnitudes are deliberately modest so a probe
## reads as ordinary movement noise, not as a tell.
let cap = maxTurnRate(ctx.ownSpeed)
var rev = -ctx.ownSpeed
if abs(rev) < 1.0: rev = -3.0
rev = clamp(rev, -4.0, 4.0)
@[
ProbeCandidate(kind: pkSuddenStop, turnRate: 0.0, targetSpeed: 0.0),
ProbeCandidate(kind: pkReversal, turnRate: 0.0, targetSpeed: rev),
ProbeCandidate(kind: pkSpeedModulation, turnRate: 0.0,
targetSpeed: clamp(ctx.ownSpeed + 2.0,
MaxBackwardSpeed, MaxForwardSpeed)),
ProbeCandidate(kind: pkDirectionFlip, turnRate: min(4.0, cap),
targetSpeed: ctx.ownSpeed),
]
proc camouflage*(c: ProbeCandidate, ctx: ProbeContext): ProbeCandidate =
## Clamp a candidate into the physics envelope: an unachievable command would
## be both implausible and mispredicted by the twin's own rollout.
result.kind = c.kind
result.turnRate = clamp(c.turnRate, -maxTurnRate(ctx.ownSpeed),
maxTurnRate(ctx.ownSpeed))
result.targetSpeed = clamp(c.targetSpeed, MaxBackwardSpeed, MaxForwardSpeed)
proc plausible*(c: ProbeCandidate, ctx: ProbeContext): bool =
## Tests-only sanity predicate: camouflage output is always plausible.
abs(c.turnRate) <= maxTurnRate(ctx.ownSpeed) + 1e-9 and
c.targetSpeed >= MaxBackwardSpeed - 1e-9 and
c.targetSpeed <= MaxForwardSpeed + 1e-9
# ── entropy / information gain ───────────────────────────────────────────────
proc entropyOf*(w: openArray[float64]): float64 =
## Shannon entropy (nats) of a non-negative vector, normalized internally.
var s = 0.0
for x in w: s += x
if s <= 0.0: return 0.0
for x in w:
let p = x / s
if p > 0.0: result -= p * ln(p)
proc topIndices*(weights: openArray[float64], k: int): seq[int] =
## Indices of the k largest weights; ties broken by ascending index.
let w = @weights
var idx = newSeq[int](w.len)
for i in 0 ..< idx.len: idx[i] = i
idx.sort(proc(a, b: int): int =
let c = cmp(w[b], w[a])
if c != 0: c else: cmp(a, b))
for i in 0 ..< min(k, idx.len): result.add idx[i]
proc onehot(origin: ReplayTick, i: int): ReplayTick =
result = origin
result.weights = newSeq[float64](origin.weights.len)
result.weights[i] = 1.0
proc reactionFeature(kernels: seq[Kernel], origin: ReplayTick, idx: int,
cand: ProbeCandidate, horizon: int): seq[float64] =
## The enemy trajectory kernel `idx` predicts under OUR candidate action,
## flattened (x,y) per tick. This is the "reaction" the probe is choosing.
var plan = newSeq[PlanStep](horizon)
for h in 0 ..< horizon:
plan[h] = PlanStep(turnRate: cand.turnRate, targetSpeed: cand.targetSpeed)
let r = rollout(kernels, onehot(origin, idx), horizon, plan = plan)
for p in r.points:
result.add p.x
result.add p.y
proc expectedEntropyDrop*(kernels: seq[Kernel], origin: ReplayTick,
top: seq[int], cand: ProbeCandidate,
horizon = ProbeHorizon): float64 =
## Expected posterior-entropy reduction from issuing `cand`.
##
## Each top kernel j is treated as a possible truth: if j is true, the observed
## reaction is j's predicted trajectory, and the posterior after seeing it is
## `prior_i · N(feat_j | feat_i, σ)`. The expected drop is `Σ_j prior_j ·
## (H(prior) − H(post_j))`. Kernels that react differently to the same probe
## separate; kernels that react identically contribute nothing.
let k = top.len
if k == 0: return 0.0
var prior = newSeq[float64](k)
var s = 0.0
for j, idx in top:
prior[j] = max(0.0, origin.weights[idx])
s += prior[j]
if s <= 0.0: return 0.0
for j in 0 ..< k: prior[j] /= s
var feats = newSeq[seq[float64]](k)
for j, idx in top:
feats[j] = reactionFeature(kernels, origin, idx, cand, horizon)
let h0 = entropyOf(prior)
let twoSigma2 = 2.0 * ProbeSigma * ProbeSigma
var drop = 0.0
for j in 0 ..< k:
var post = newSeq[float64](k)
for i in 0 ..< k:
var d2 = 0.0
for m in 0 ..< feats[i].len:
let d = feats[i][m] - feats[j][m]
d2 += d * d
post[i] = prior[i] * exp(-d2 / twoSigma2)
drop += prior[j] * (h0 - entropyOf(post))
drop
# ── selection + budget ───────────────────────────────────────────────────────
proc chooseProbe*(kernels: seq[Kernel], origin: ReplayTick, ctx: ProbeContext,
horizon = ProbeHorizon): ProbeDecision =
## Pick the candidate with the largest expected entropy drop. Deterministic
## tie-break: earlier ProbeKind, then smaller action magnitude.
result.entropyBefore = entropyOf(origin.weights)
result.entropyAfter = result.entropyBefore
let top = topIndices(origin.weights, TopKernels)
var bestDrop = -Inf
var bestMag = Inf
var have = false
for cand in candidates(ctx):
let c = camouflage(cand, ctx)
let drop = expectedEntropyDrop(kernels, origin, top, c, horizon)
let mag = abs(c.turnRate) + abs(c.targetSpeed)
let better =
(not have) or drop > bestDrop + 1e-12 or
(abs(drop - bestDrop) <= 1e-12 and
(c.kind.ord < result.candidate.kind.ord or
(c.kind == result.candidate.kind and mag < bestMag)))
if better:
bestDrop = drop
bestMag = mag
result.candidate = c
have = true
if have: result.entropyAfter = result.entropyBefore - bestDrop
proc consider*(s: var ProbeScheduler, origin: ReplayTick,
ctx: ProbeContext): ProbeDecision =
## One tick of the scheduler. Increments the budget; once the interval has
## elapsed it always *triggers* (so the gate state is observable in telemetry),
## but the budget only resets when the gate ALLOWS the probe to be executed.
inc s.ticksSinceProbe
result.gate = survivalGate(ctx)
if s.ticksSinceProbe < s.interval:
return
result = chooseProbe(s.kernels, origin, ctx)
result.trigger = true
result.gate = survivalGate(ctx)
if result.gate.allow:
s.ticksSinceProbe = 0
inc s.probes