diff --git a/ChimeraBot_garage/benchmarks/g1_oracle_table.md b/ChimeraBot_garage/benchmarks/g1_oracle_table.md new file mode 100644 index 0000000..aa8ea05 --- /dev/null +++ b/ChimeraBot_garage/benchmarks/g1_oracle_table.md @@ -0,0 +1,18 @@ +# G1 oracle-convergence table + +Auto-generated by `tests/test_oracle_g1.nim` (deterministic; regenerate with `nimble test`). T* = 300 ticks, threshold = 0.90, env = default synthetic arena (800x600, no sensor error). A PASS means posterior(kernel) reached the threshold within T*. + +| kernel | idTick | finalPosterior | censorRate | pass | +|---|---:|---:|---:|---| +| ORBIT_LOCK | 61 | 0.95170 | 0.0000 | PASS | +| ORBIT_BALLIST | 28 | 0.94312 | 0.0000 | PASS | +| STOP_AND_GO | 37 | 0.97779 | 0.0000 | PASS | +| ZIGZAG | 161 | 0.94407 | 0.0000 | PASS | +| RAMMER | 152 | 0.90926 | 0.0000 | PASS | +| CORNER_RUN | 99 | 0.90280 | 0.0000 | PASS | +| WALLCRAWL | 47 | 0.95033 | 0.0000 | PASS | +| STATIC | 27 | 0.97278 | 0.0000 | PASS | +| STATIC_CORNER | 68 | 0.80642 | 0.0000 | PASS | +| RANDOM_WALK_A | 19 | 0.97378 | 0.0000 | PASS | +| RANDOM_WALK_B | 14 | 0.96952 | 0.0000 | PASS | +| RANDOM_WALK_C | 14 | 0.97334 | 0.0000 | PASS | diff --git a/ChimeraBot_garage/src/ChimeraBot.nim b/ChimeraBot_garage/src/ChimeraBot.nim index bbb2588..23ed886 100644 --- a/ChimeraBot_garage/src/ChimeraBot.nim +++ b/ChimeraBot_garage/src/ChimeraBot.nim @@ -34,6 +34,7 @@ import ChimeraBot/modules/ELM/elm_gun import ChimeraBot/modules/ELM/elm_features import ChimeraBot/chimera/observer import ChimeraBot/chimera/dsl +import ChimeraBot/chimera/probes const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds ## only what it scans, so this is a cap, not a limit @@ -79,6 +80,8 @@ type ChimeraBot* = ref object of Bot ## joined to a recording round observer: Observer ## observation-only sidecar (§12 G3/G4 telemetry) opponentLabel: string ## telemetry filename label (env, observation-only) + probes: ProbeScheduler ## active causal probing (spec §9, M5); disabled by + ## -d:chimeraNoProbes (see ProbesEnabled) proc newChimeraBot*(): ChimeraBot = result = ChimeraBot() @@ -93,6 +96,8 @@ proc newChimeraBot*(): ChimeraBot = # filename; it labels observations, it does not change behaviour. result.opponentLabel = getEnv("CHIMERA_OPPONENT", "") result.observer = initObserver(allKernels(), telemetryDir) + when ProbesEnabled: + result.probes = initProbeScheduler(allKernels()) setRadarColor(WHITE) # overwritten by initRadar() before the first tick method onScannedBot*(bot: ChimeraBot, e: ScannedBotEvent) = @@ -277,8 +282,35 @@ method run*(bot: ChimeraBot) = commandRadar() bot.ageEnemies() # stale scans dropped before they paint heat let (speed, turnRate) = bot.mover.computeMove(bot.buildWorldState()) - setTargetSpeed(speed) - setTurnRate(turnRate) + # Probe advisory (spec §9, M5): past the budget interval AND when the + # survival gate allows, the commanded movement this tick becomes the chosen + # probe; otherwise the TFIL command is untouched. `-d:chimeraNoProbes` + # removes this block entirely (G6 ablation OFF arm). + var cmdSpeed = speed + var cmdTurn = turnRate + when ProbesEnabled: + if bot.observer.hasCurrent: + let porigin = bot.observer.probeOrigin() + let ctx = ProbeContext( + tick: bot.tick, ourEnergy: getEnergy(), + ownX: porigin.ox, ownY: porigin.oy, ownSpeed: porigin.ospeed, + arenaW: getArenaWidth().float, arenaH: getArenaHeight().float, + enemyX: porigin.ex, enemyY: porigin.ey, + enemyGunHeat: bot.observer.enemyGunHeat(), + enemyAimedAtUs: aimedAtUs(porigin.ox, porigin.oy, + porigin.ex, porigin.ey, porigin.edir), + roundLimit: RoundSoftLimit) + let decision = bot.probes.consider(porigin, ctx) + if decision.trigger: + bot.observer.writeProbeEvent(bot.tick, $decision.candidate.kind, + decision.gate.reason, decision.entropyBefore, + decision.entropyAfter, decision.candidate.turnRate, + decision.candidate.targetSpeed) + if decision.gate.allow: + cmdSpeed = decision.candidate.targetSpeed + cmdTurn = decision.candidate.turnRate + setTargetSpeed(cmdSpeed) + setTurnRate(cmdTurn) bot.computeGun() # gun intent, also before go() go() bot.observer.writeTick(bot.tick) # observation telemetry, after go() diff --git a/ChimeraBot_garage/src/ChimeraBot.nimble b/ChimeraBot_garage/src/ChimeraBot.nimble index 32e2b4e..9347eb7 100644 --- a/ChimeraBot_garage/src/ChimeraBot.nimble +++ b/ChimeraBot_garage/src/ChimeraBot.nimble @@ -260,3 +260,4 @@ task test, "Run unit tests": exec "nim c -r --hints:off ../tests/test_oracle_g1.nim" exec "nim c -r --hints:off ../tests/test_observer.nim" exec "nim c -r --hints:off ../tests/test_twinsim.nim" + exec "nim c -r --hints:off ../tests/test_probes.nim" diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim index 9ad0586..19ecc9f 100644 --- a/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim @@ -19,7 +19,7 @@ ## readiness check for the M4 twin rollout, not the twin itself. import std/[math, os, strutils] -import ./physics, ./ledger, ./dsl, ./hedge, ./oracle +import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim const MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check @@ -51,6 +51,8 @@ type censored, ticks: int gapMax, gapViolations: int + enemyHeat: float64 ## ledger-derived enemy gun-heat estimate (probe gate) + round: int opponent: string f: File @@ -76,6 +78,7 @@ proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer = result.mems[i] = defaultMemory(kernels[i].defaultParams) result.telemetryDir = telemetryDir result.scanTick = -1 + result.enemyHeat = 3.0 for i in 0 ..< PredSlots: result.predOrigin[i] = -1 proc resetRound(o: Observer) = @@ -92,6 +95,7 @@ proc resetRound(o: Observer) = o.gapViolations = 0 o.adeSum = 0; o.adeN = 0 o.fdeSum = 0; o.fdeN = 0 + o.enemyHeat = 3.0 ## round-start heat (spec §5) for i in 0 ..< PredSlots: o.predOrigin[i] = -1 proc sanitize*(s: string): string = @@ -211,6 +215,9 @@ proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float6 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: @@ -240,10 +247,39 @@ proc censorRate*(o: Observer): float64 = 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 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. + ## 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 diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/probes.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/probes.nim new file mode 100644 index 0000000..a6e31a0 --- /dev/null +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/probes.nim @@ -0,0 +1,259 @@ +## 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 diff --git a/ChimeraBot_garage/tests/bench_g5p.nim b/ChimeraBot_garage/tests/bench_g5p.nim new file mode 100644 index 0000000..65e6d39 --- /dev/null +++ b/ChimeraBot_garage/tests/bench_g5p.nim @@ -0,0 +1,181 @@ +## G5' interventional counterfactual eval (CHIMERA M5) — OFFLINE, no Java. +## +## Source: docs/chimera-spec.md §12 G5'. Reads the probe-ON telemetry that +## bench_g6.nim archived under /tmp/chimera_g6_on, replays the ledger + Hedge to +## recover the causal posterior, and for every tick that FOLLOWS an executed +## probe measures: +## * 5-tick enemy-reaction ADE of the twin mixture vs the persistence baseline +## (constant-velocity carry), under OUR ACTUAL recorded movement; +## * reaction-direction agreement: the angle between the predicted and the +## observed net enemy displacement over the window (<= 45 deg counts). +## +## Gates reported: +## * G5' bar: twin ADE <= persistence ADE on >= 70% of probe-following windows; +## * stretch row: >= 90% (reported, never the gate); +## * observational sanity floor: twin ADE <= 2x persistence ADE per opponent. +## +## Run: `nim c -r --hints:off -d:release tests/bench_g5p.nim [telemetryDir]` + +import std/[os, strutils, tables, math, algorithm, sequtils] +import chimera/dsl +import chimera/physics +import chimera/twinsim + +const Horizon = 5 +const DefaultDir = getTempDir() / "chimera_g6_on" +const DirAgreeDeg = 45.0 + +type + Agg = object + windows: int + twinAde, persAde: float64 + twinWins: int + dirTwinAgree, dirPersAgree, dirN: int + allWindows: int + allTwinAde, allPersAde: float64 + allTwinWins: int + +proc probeTicks(path: string): seq[int] = + ## Only EXECUTED probes (`gate:"ok"`) count as interventional windows: a + ## gate-blocked trigger issued no probe, so the following ticks are + ## observation-only and would silently re-import the M4 persistence-bias. + for ln in lines(path): + if ln.find("\"event\":\"probe\"") < 0: continue + if ln.find("\"gate\":\"ok\"") < 0: continue + let needle = "\"tick\":" + let i = ln.find(needle) + if i < 0: continue + var j = i + needle.len + while j < ln.len and ln[j] in {' ', '\t'}: inc j + let s = j + while j < ln.len and ln[j] in Digits: inc j + if j > s: result.add parseInt(ln[s ..< j]) + +proc netDir(sx, sy, ex, ey: float64): float64 = + ## Bearing of the displacement (sx,sy)->(ex,ey). + arctan2(ey - sy, ex - sx) * 180.0 / PI + +proc dirAgree(sx, sy, obsX, obsY, predX, predY: float64): bool = + let obsMag = hypot(obsX - sx, obsY - sy) + let predMag = hypot(predX - sx, predY - sy) + if obsMag <= 1.0: return predMag <= 5.0 + abs(wrap180(netDir(sx, sy, predX, predY) - netDir(sx, sy, obsX, obsY))) <= DirAgreeDeg + +proc record(path: string, kernels: seq[Kernel], agg: var Table[string, Agg]) = + let rec = loadRecord(path) + let probes = probeTicks(path) + if rec.ticks.len < Horizon + 1: return + let rp = replay(rec, kernels) + if rp.len < Horizon + 1: return + var a = agg.getOrDefault(rec.opponent) + # observational floor: every origin window in the same record + for i in 0 ..< rp.len - Horizon: + let origin = rp[i] + var actual: seq[tuple[x, y: float64]] + var realized: seq[tuple[x, y: float64]] + for h in 1 .. Horizon: + actual.add (rp[i + h].ox, rp[i + h].oy) + realized.add (rp[i + h].ex, rp[i + h].ey) + let twin = rollout(kernels, origin, Horizon, actualOwn = actual) + let pers = persistence(origin, Horizon) + var tAde, pAde = 0.0 + for h in 0 ..< Horizon: + tAde += hypot(twin.points[h].x - realized[h].x, + twin.points[h].y - realized[h].y) + pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y) + inc a.allWindows + a.allTwinAde += tAde / float(Horizon) + a.allPersAde += pAde / float(Horizon) + if tAde <= pAde: inc a.allTwinWins + # interventional windows: probe ticks only + var byTick = initTable[int, int]() + for i, r in rp: byTick[r.tick] = i + for p in probes: + if not byTick.hasKey(p): continue + let i = byTick[p] + if i + Horizon >= rp.len: continue + let origin = rp[i] + var actual: seq[tuple[x, y: float64]] + var realized: seq[tuple[x, y: float64]] + for h in 1 .. Horizon: + actual.add (rp[i + h].ox, rp[i + h].oy) + realized.add (rp[i + h].ex, rp[i + h].ey) + let twin = rollout(kernels, origin, Horizon, actualOwn = actual) + let pers = persistence(origin, Horizon) + var tAde, pAde = 0.0 + for h in 0 ..< Horizon: + tAde += hypot(twin.points[h].x - realized[h].x, + twin.points[h].y - realized[h].y) + pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y) + tAde /= float(Horizon); pAde /= float(Horizon) + inc a.windows + a.twinAde += tAde; a.persAde += pAde + if tAde <= pAde: inc a.twinWins + inc a.dirN + if dirAgree(origin.ex, origin.ey, realized[^1].x, realized[^1].y, + twin.points[^1].x, twin.points[^1].y): inc a.dirTwinAgree + if dirAgree(origin.ex, origin.ey, realized[^1].x, realized[^1].y, + pers[^1].x, pers[^1].y): inc a.dirPersAgree + agg[rec.opponent] = a + +proc main() = + let arg = if paramCount() >= 1: paramStr(1) else: getEnv("CHIMERA_G5P_DIR", "") + let dir = if arg.len > 0 and dirExists(arg): arg else: DefaultDir + if not dirExists(dir): + echo "No probe-ON telemetry at ", dir, " (run bench_g6.nim first)." + quit(0) + let kernels = allKernels() + var agg = initTable[string, Agg]() + var files: seq[string] + for f in walkDirRec(dir): + if f.endsWith(".jsonl"): files.add f + files.sort() + for f in files: record(f, kernels, agg) + + var totalWin, total = 0 + var totT, totP = 0.0 + var dirT, dirP, dirN = 0 + var floorBad = 0 + var names = toSeq(agg.keys); names.sort() + echo "G5' interventional (probe-following windows), horizon=", Horizon, + ", dir=", dir + echo "\nOpponent probes twinADE persADE margin twinWin% dirTwin% dirPers% obsFloor" + for name in names: + let a = agg[name] + if a.windows == 0: continue + let n = float(a.windows) + let win = 100.0 * float(a.twinWins) / n + totalWin += a.twinWins + total += a.windows + totT += a.twinAde; totP += a.persAde + dirT += a.dirTwinAgree; dirP += a.dirPersAgree; dirN += a.dirN + let floorOk = a.allPersAde > 0.0 and a.allTwinAde <= 2.0 * a.allPersAde + if not floorOk: inc floorBad + echo " ", alignLeft(name, 12), align($a.windows, 6), + " ", align(formatFloat(a.twinAde / n, ffDecimal, 3), 7), + " ", align(formatFloat(a.persAde / n, ffDecimal, 3), 7), + " ", align(formatFloat((a.persAde - a.twinAde) / n, ffDecimal, 3), 7), + " ", align(formatFloat(win, ffDecimal, 1), 8), + " ", align(formatFloat(100.0 * float(a.dirTwinAgree) / + float(max(1, a.dirN)), ffDecimal, 1), 8), + " ", align(formatFloat(100.0 * float(a.dirPersAgree) / + float(max(1, a.dirN)), ffDecimal, 1), 8), + " ", (if floorOk: "ok" else: "FAIL") + echo "\nInterventional twin-ADE <= persistence-ADE: ", totalWin, "/", total, + " = ", formatFloat(100.0 * float(totalWin) / float(max(1, total)), + ffDecimal, 1), "%" + echo "G5' bar (>= 70%): ", + (if totalWin * 10 >= total * 7: "PASS" else: "FAIL") + echo "Stretch row (>= 90%): ", + formatFloat(100.0 * float(totalWin) / float(max(1, total)), + ffDecimal, 1), "% ", + (if totalWin * 10 >= total * 9: "(met)" else: "(not met)") + echo "Reaction-direction agreement: twin ", + formatFloat(100.0 * float(dirT) / float(max(1, dirN)), ffDecimal, 1), + "%, persistence ", + formatFloat(100.0 * float(dirP) / float(max(1, dirN)), ffDecimal, 1), "%" + echo "Observational sanity floor (twinADE <= 2x persADE per opponent): ", + (if floorBad == 0: "PASS (all opponents)" else: "FAIL (" & $floorBad & ")") + +when isMainModule: + main() diff --git a/ChimeraBot_garage/tests/bench_g6.nim b/ChimeraBot_garage/tests/bench_g6.nim new file mode 100644 index 0000000..3c05312 --- /dev/null +++ b/ChimeraBot_garage/tests/bench_g6.nim @@ -0,0 +1,220 @@ +## G6 ablation ladder — probes ON vs OFF (CHIMERA M5). LIVE, Java required. +## +## Runs the same 8×5 pinned-opponent protocol (bench_g4's set) for both builds: +## * ON — default build, probe scheduler wired (spec §9) +## * OFF — `-d:chimeraNoProbes`, probe advisory removed (command path == M1 copy) +## repeated `Repeat` (default 3) full runs each, and reports the MEDIAN +## identification tick per opponent (spec G4: median over >= 3 runs, to survive +## the sample-bot spawn variance) plus the G6 pass bar: probes cut the median +## identification ticks by >= 20%. +## +## A round that never crosses the threshold is censored at its own tick count, +## so "never identified" cannot masquerade as a fast round; the identification +## rate is reported separately. +## +## ON telemetry is archived to /tmp/chimera_g6_on (input to bench_g5p.nim). +## Throwaway output only under /tmp. Run: +## `nim c -r --hints:off -d:release tests/bench_g6.nim` + +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_g6_stage" + Telemetry = getTempDir() / "chimera_twin" + OnDir = getTempDir() / "chimera_g6_on" + OffDir = getTempDir() / "chimera_g6_off" + Rounds = 5 + Repeat = 3 + Threshold = 0.8 + TargetTicks = 300 + MaxAttempts = 4 + +const Expected = { + "Crazy": "ZIGZAG", + "SpinBot": "ORBIT_BALLIST", + "RamFire": "STATIC", + "Corners": "STATIC", + "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 G6 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(tag: string, off: bool): string = + let botDir = StageDir / tag / "ChimeraBot" + removeDir(StageDir / tag) + createDir(botDir) + let bin = botDir / "ChimeraBot" + var cmd = "nim c -d:release --hints:off " + if off: cmd.add "-d:chimeraNoProbes " + cmd.add deps().join(" ") & " --out:\"" & bin & "\" " & + quoteShell(GarageSrc / "ChimeraBot.nim") + let (outp, code) = execCmdEx(cmd, options = {poEvalCommand}) + if code != 0 or not fileExists(bin): + quit("ChimeraBot (" & tag & ") 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]) + 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 weight(expected) >= Threshold, else -1 + sumTicks: int + identified: bool + +proc parseFile(path, expectedKernel: string): RoundStat = + result.idTick = -1 + for ln in readFile(path).splitLines(): + if ln.len == 0: continue + if ln.startsWith("{\"event\":\"round_summary\""): + result.sumTicks = extract(ln, "ticks").value.parseInt() + elif ln.startsWith("{\"tick\""): + 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 j < top.len and (top[j] in Digits or top[j] == '.'): inc j + let w = top[wI ..< j].parseFloat() + let tick = extract(ln, "tick").value.parseInt() + if w >= Threshold and (result.idTick < 0 or tick < result.idTick): + result.idTick = tick + result.identified = result.idTick > 0 + +proc median(xs: seq[int]): int = + if xs.len == 0: return -1 + var s = xs; s.sort() + s[s.len div 2] + +proc runArm(tag: string, off: bool): Table[string, seq[int]] = + let botDir = stageBot(tag, off) + removeDir(Telemetry) + let armDir = if off: OffDir else: OnDir + removeDir(armDir) + createDir(armDir) + ensureServer() + let url = getServerUrl() + for opp in sorted(toSeq(Expected.keys)): + putEnv("CHIMERA_OPPONENT", opp) + putEnv("CHIMERA_TELEMETRY_DIR", Telemetry) + let sampleBot = SampleRoot / opp + for run in 1 .. Repeat: + var ok = false + for attempt in 1 .. MaxAttempts: + removeDir(Telemetry) + sleep(1200) + try: + discard runBattleRunner(url, @[botDir, sampleBot], rounds = Rounds, + timeout = 300000) + ok = true + break + except CatchableError: + if attempt >= MaxAttempts: + echo " ", tag, " ", opp, " run", run, ": battle failed" + if not ok: continue + copyDir(Telemetry, armDir / (opp & "-run" & $run)) + # parse everything for this opponent + var ids: seq[int] + for f in walkDirRec(armDir): + if not f.endsWith(".jsonl"): continue + if not f.extractFilename.startsWith(opp & "-"): continue + let rs = parseFile(f, Expected[opp]) + if rs.sumTicks == 0: continue + ids.add (if rs.identified: rs.idTick else: rs.sumTicks) + result[opp] = ids + +proc stats(ids: seq[int]): tuple[med, rate: float64, n: int] = + if ids.len == 0: return (-1.0, 0.0, 0) + var identified = 0 + for x in ids: + if x <= TargetTicks: inc identified + (float(median(ids)), 100.0 * float(identified) / float(ids.len), ids.len) + +proc main() = + guardSkip() + echo "[G6] staging ON/OFF builds and running ", Repeat, " full runs each" + let on = runArm("on", false) + let off = runArm("off", true) + + echo "\nG6 identification ticks, median over ", Repeat, " runs x ", Rounds, + " rounds (censored rounds scored at their tick count)" + echo "Opponent onMed onID% offMed offID% cut%" + var pooledOn, pooledOff: seq[int] + var onPass, offPass = 0 + var comparable = 0 + var cutSum = 0.0 + var cutN = 0 + for opp in sorted(toSeq(Expected.keys)): + if not (opp in on and opp in off): continue + let so = stats(on[opp]) + let sf = stats(off[opp]) + if so.n == 0 or sf.n == 0: continue + pooledOn.add on[opp] + pooledOff.add off[opp] + inc comparable + if so.med <= TargetTicks: inc onPass + if sf.med <= TargetTicks: inc offPass + let cut = if sf.med > 0: 100.0 * (sf.med - so.med) / sf.med else: 0.0 + cutSum += cut; inc cutN + echo " ", alignLeft(opp, 12), + align($int(so.med), 6), " ", align(formatFloat(so.rate, ffDecimal, 0), 5), + " ", align($int(sf.med), 7), " ", align(formatFloat(sf.rate, ffDecimal, 0), 5), + " ", align(formatFloat(cut, ffDecimal, 1), 6) + let onAll = median(pooledOn) + let offAll = median(pooledOff) + let overall = if offAll > 0: 100.0 * float(offAll - onAll) / float(offAll) else: 0.0 + echo "\nPooled median ON = ", onAll, " ticks, OFF = ", offAll, " ticks" + echo "G6 probes cut median identification by ", formatFloat(overall, ffDecimal, 1), + "% (bar >= 20%): ", (if overall >= 20.0: "PASS" else: "FAIL") + echo "G4 median pass (ON, <= ", TargetTicks, "): ", onPass, "/", comparable, + " (OFF: ", offPass, "/", comparable, ")" + echo "Per-opponent cut mean = ", + formatFloat(if cutN > 0: cutSum / float(cutN) else: 0.0, ffDecimal, 1), "%" + echo "ON telemetry archived at ", OnDir, " (G5' input)" + +when isMainModule: + main() diff --git a/ChimeraBot_garage/tests/test_oracle_g1.nim b/ChimeraBot_garage/tests/test_oracle_g1.nim index f167a3b..0f3140b 100644 --- a/ChimeraBot_garage/tests/test_oracle_g1.nim +++ b/ChimeraBot_garage/tests/test_oracle_g1.nim @@ -7,7 +7,7 @@ ## ## Run: from ChimeraBot_garage/src, `nimble test`. -import std/[math, strutils] +import std/[math, strutils, os] import chimera/dsl import chimera/oracle @@ -26,6 +26,11 @@ block: echo "G1: oracle convergence over the M2 kernel set (T* = ", TStar, " ticks)" echo " ", align("kernel", 16), align("idTick", 8), align("posterior", 11), align("censor", 8) + # Persist the FULL 12-kernel table to a committed artifact, so the answer to + # "did every kernel converge?" no longer depends on log truncation (the M2/M3 + # reports lost rows to tail-cut logs). Deterministic: every column is a pure + # function of the kernel set + fixed oracle env. + var rows: seq[string] for i in 0 ..< kernels.len: let r = runG1(kernels, i, env, TStar) let idStr = if r.idTick < 0: " NEVER" else: align($r.idTick, 8) @@ -39,6 +44,24 @@ block: check("G1 " & r.kernel & " identified within T*", ok, "idTick=" & $r.idTick & " posterior=" & formatFloat(r.finalPosterior, ffDecimal, 4)) + rows.add "| " & r.kernel & " | " & + (if r.idTick < 0: "never" else: $r.idTick) & " | " & + formatFloat(r.finalPosterior, ffDecimal, 5) & " | " & + formatFloat(r.censorRate, ffDecimal, 4) & " | " & + (if ok: "PASS" else: "FAIL") & " |" + let artPath = currentSourcePath().parentDir.parentDir / + "benchmarks" / "g1_oracle_table.md" + createDir(artPath.parentDir) + writeFile(artPath, + "# G1 oracle-convergence table\n\n" & + "Auto-generated by `tests/test_oracle_g1.nim` (deterministic; regenerate with " & + "`nimble test`). T* = " & $TStar & " ticks, threshold = " & + formatFloat(Threshold, ffDecimal, 2) & ", env = default synthetic arena " & + "(800x600, no sensor error). A PASS means posterior(kernel) reached the " & + "threshold within T*.\n\n" & + "| kernel | idTick | finalPosterior | censorRate | pass |\n" & + "|---|---:|---:|---:|---|\n" & rows.join("\n") & "\n") + echo " table written: ", artPath block: echo "" diff --git a/ChimeraBot_garage/tests/test_probes.nim b/ChimeraBot_garage/tests/test_probes.nim new file mode 100644 index 0000000..844bdb0 --- /dev/null +++ b/ChimeraBot_garage/tests/test_probes.nim @@ -0,0 +1,143 @@ +## Tier A tests for the CHIMERA probe scheduler (chimera/probes.nim, spec §9). +## Pure Nim, no Java. Run: from ChimeraBot_garage/src, `nimble test`. + +import std/math +import chimera/dsl +import chimera/twinsim +import chimera/probes + +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() + +proc origin(): ReplayTick = + var r = ReplayTick(tick: 60, ex: 200.0, ey: 300.0, edir: 0.0, + espeed: 6.0, eenergy: 80.0, + ox: 600.0, oy: 300.0, odir: 180.0, ospeed: 4.0, + lastTurn: 0.0, lastSpeed: 6.0) + r.weights = newSeq[float64](kernels.len) + for i in 0 ..< kernels.len: r.weights[i] = 1.0 / float64(kernels.len) + r.mems = newSeq[KernelMem](kernels.len) + for i in 0 ..< kernels.len: r.mems[i] = defaultMemory(kernels[i].defaultParams) + r + +proc baseCtx(): ProbeContext = + ## All-clear context: mid-arena, healthy, enemy far and cold, not aimed. + ProbeContext(tick: 60, ourEnergy: 100.0, ownX: 400.0, ownY: 300.0, + ownSpeed: 4.0, arenaW: 800.0, arenaH: 600.0, + enemyX: 750.0, enemyY: 300.0, enemyGunHeat: 3.0, + enemyAimedAtUs: false, roundLimit: 2000) + +block: + echo "probes 1: survival-gate truth table" + var c = baseCtx() + check("all clear allows", survivalGate(c).allow) + check("all-clear reason", survivalGate(c).reason == "ok") + + c = baseCtx(); c.ourEnergy = 10.0 + check("low energy denies", not survivalGate(c).allow) + check("low energy reason", survivalGate(c).reason == "energy") + + c = baseCtx(); c.enemyAimedAtUs = true; c.enemyGunHeat = 0.0 + check("hot+aimed denies", not survivalGate(c).allow) + check("hot+aimed reason", survivalGate(c).reason == "enemy-hot-aimed") + c.enemyGunHeat = 2.0 + check("aimed but cold allows", survivalGate(c).allow) + + c = baseCtx(); c.ownX = 5.0 + check("wall-pinned denies", not survivalGate(c).allow) + check("wall-pinned reason", survivalGate(c).reason == "wall-pinned") + + c = baseCtx(); c.tick = 1980 + check("round-end denies", not survivalGate(c).allow) + check("round-end reason", survivalGate(c).reason == "round-end") + + # priority: energy checked before wall/heat + c = baseCtx(); c.ourEnergy = 5.0; c.ownX = 5.0; c.enemyAimedAtUs = true + c.enemyGunHeat = 0.0 + check("energy has gate priority", survivalGate(c).reason == "energy") + +block: + echo "probes 2: budget accounting" + var s = initProbeScheduler(kernels) + check("interval nominal 25", s.interval == 25) + var c = baseCtx() + var triggers = 0 + for t in 1 .. 25: + c.tick = t + if s.consider(origin(), c).trigger: inc triggers + check("first trigger exactly at interval", triggers == 1, $triggers) + check("counter reset after executed probe", s.ticksSinceProbe == 0) + check("one executed probe", s.probes == 1) + # next trigger must wait a full interval again + var before = false + for t in 26 .. 49: + c.tick = t + if s.consider(origin(), c).trigger: before = true + check("no trigger before next interval", not before) + c.tick = 50 + check("second trigger at 2*interval", s.consider(origin(), c).trigger) + check("two executed probes", s.probes == 2) + + # gate deny: trigger fires past the interval but the budget never resets + var d = initProbeScheduler(kernels) + var dc = baseCtx(); dc.ourEnergy = 5.0 + for t in 1 .. 25: + dc.tick = t + discard d.consider(origin(), dc) + check("gated tick still triggers", d.ticksSinceProbe == 25) + discard d.consider(origin(), dc) + check("gated: no executed probe", d.probes == 0) + check("gated: counter keeps growing", d.ticksSinceProbe == 26) + + check("interval clamped low", initProbeScheduler(kernels, 1).interval == 20) + check("interval clamped high", initProbeScheduler(kernels, 99).interval == 30) + +block: + echo "probes 3: entropy-selection determinism" + let o = origin() + let c = baseCtx() + let d1 = chooseProbe(kernels, o, c) + let d2 = chooseProbe(kernels, o, c) + check("same candidate kind", d1.candidate.kind == d2.candidate.kind) + check("same turn rate", d1.candidate.turnRate == d2.candidate.turnRate) + check("same target speed", d1.candidate.targetSpeed == d2.candidate.targetSpeed) + check("same entropyBefore", d1.entropyBefore == d2.entropyBefore) + check("same entropyAfter", d1.entropyAfter == d2.entropyAfter) + check("entropy does not increase", + d1.entropyAfter <= d1.entropyBefore + 1e-9, + $d1.entropyBefore & " -> " & $d1.entropyAfter) + # selection is information-driven: at least one candidate must separate the + # kernels, so a mixed posterior admits a strictly positive expected drop. + check("selection finds information", d1.entropyBefore - d1.entropyAfter > 0.0, + $(d1.entropyBefore - d1.entropyAfter)) + +block: + echo "probes 4: camouflage plausibility" + var c = baseCtx(); c.ownSpeed = 7.9 + for cand in candidates(c): + let cam = camouflage(cand, c) + check("in envelope " & $cam.kind, plausible(cam, c), + "turn=" & $cam.turnRate & " speed=" & $cam.targetSpeed) + c = baseCtx(); c.ownSpeed = 0.0 + var anySmall = false + for cand in candidates(c): + let cam = camouflage(cand, c) + check("in envelope at rest " & $cam.kind, plausible(cam, c)) + if abs(cam.targetSpeed) <= 8.0 and abs(cam.turnRate) <= 10.0: anySmall = true + check("probe magnitudes stay plausible", anySmall) + +block: + echo "probes 5: entropy closed form" + check("uniform n=4 entropy = ln4", + abs(entropyOf([0.25, 0.25, 0.25, 0.25]) - ln(4.0)) < 1e-12) + check("onehot entropy = 0", abs(entropyOf([1.0, 0.0, 0.0])) < 1e-12) + check("normalization-invariant", + abs(entropyOf([2.0, 2.0, 2.0, 2.0]) - ln(4.0)) < 1e-12) + +echo "" +if failed == 0: echo "all probe tests passed" +else: echo failed, " probe test(s) FAILED"; quit(1) diff --git a/ChimeraBot_garage/tests/test_twinsim.nim b/ChimeraBot_garage/tests/test_twinsim.nim index ce28ae2..469de20 100644 --- a/ChimeraBot_garage/tests/test_twinsim.nim +++ b/ChimeraBot_garage/tests/test_twinsim.nim @@ -89,6 +89,32 @@ block: $rec.fireRate()) removeDir(dir) +block: + echo "twinsim 5: probe-reaction prediction (single-kernel counterfactual)" + let o = origin() + var ramIdx = -1 + for i, k in kernels: + if k.name == "RAMMER": ramIdx = i + check("RAMMER kernel present", ramIdx >= 0) + var onehot = o + onehot.weights = newSeq[float64](kernels.len) + if ramIdx >= 0: onehot.weights[ramIdx] = 1.0 + var planStop = newSeq[PlanStep](5) # hold still + var planTurn = newSeq[PlanStep](5) # curve off the bearing + for i in 0 ..< 5: planTurn[i] = PlanStep(turnRate: 10.0, targetSpeed: 8.0) + let rStop = rollout(kernels, onehot, 5, plan = planStop) + let rFlee = rollout(kernels, onehot, 5, plan = planTurn) + var sep = 0.0 + for i in 0 ..< rStop.points.len: + sep = max(sep, hypot(rStop.points[i].x - rFlee.points[i].x, + rStop.points[i].y - rFlee.points[i].y)) + check("our probe action changes the predicted enemy reaction", sep > 0.01, + "separation " & $sep) + let rStop2 = rollout(kernels, onehot, 5, plan = planStop) + check("single-kernel probe rollout is deterministic", + rStop.points[^1].x == rStop2.points[^1].x and + rStop.points[^1].y == rStop2.points[^1].y) + removeDir(getTempDir() / ("chimera_twinsim_test" & $getCurrentProcessId())) echo "" if failed == 0: echo "all twinsim tests passed"