diff --git a/ChimeraBot_garage/benchmarks/m5_5_g4.md b/ChimeraBot_garage/benchmarks/m5_5_g4.md new file mode 100644 index 0000000..8d9c61b --- /dev/null +++ b/ChimeraBot_garage/benchmarks/m5_5_g4.md @@ -0,0 +1,16 @@ +# G4 unified idTicks (M5.5) + +Metric: per round, round-relative tick at which `max_kernel posterior > 0.8`; median / p90 / id-fraction over all rounds. Pass = median <= 300 AND id% >= 80. 3 runs x 5 rounds. Generated by `tests/bench_g4.nim`. + +| opponent | median | p90 | id-fraction% | expMedian | argmaxOk% | finalPost% | censor% | ade5 | pass | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---| +| Corners | 1 | 53 | 100.0 | 1 | 60.0 | 94.0 | 0.00 | 3.082 | PASS | +| Crazy | 36 | 127 | 100.0 | 73 | 66.7 | 60.3 | 0.00 | 8.307 | PASS | +| Fire | 1 | 19 | 100.0 | 1 | 100.0 | 96.6 | 0.00 | 2.942 | PASS | +| RamFire | 1 | 23 | 100.0 | 1 | 100.0 | 90.9 | 0.00 | 4.653 | PASS | +| SpinBot | 1 | 35 | 100.0 | 1 | 100.0 | 94.5 | 0.00 | 1.727 | PASS | +| TrackFire | 1 | 19 | 100.0 | 1 | 100.0 | 96.8 | 0.00 | 0.354 | PASS | +| VelociBot | 1 | 27 | 100.0 | 60 | 26.7 | 90.0 | 0.00 | 9.399 | PASS | +| Walls | 60 | 357 | 100.0 | 77 | 80.0 | 56.2 | 0.00 | 6.008 | PASS | + +Pooled over 120 rounds: median 1, p90 73, id-fraction 100.0%. G4 pass: 8/8. diff --git a/ChimeraBot_garage/benchmarks/m5_5_g5p.md b/ChimeraBot_garage/benchmarks/m5_5_g5p.md new file mode 100644 index 0000000..7a696bc --- /dev/null +++ b/ChimeraBot_garage/benchmarks/m5_5_g5p.md @@ -0,0 +1,23 @@ +# G5' v2 interventional eval (M5.5) + +Horizon 5, probe-following windows only. MOVING = Crazy, SpinBot, VelociBot, Walls; STATIC = RamFire, Corners, TrackFire, Fire. Source: /tmp/chimera_g6_on. + +| opponent | probes | twinADE | persADE | margin | twinWin% | dirTwin% | dirPers% | +|---|---:|---:|---:|---:|---:|---:|---:| +| Corners | 153 | 2.734 | 0.539 | -2.196 | 3.9 | 90.2 | 97.4 | +| Crazy | 208 | 8.850 | 2.900 | -5.951 | 17.3 | 86.1 | 94.7 | +| Fire | 200 | 3.535 | 1.628 | -1.907 | 17.0 | 92.5 | 91.5 | +| RamFire | 100 | 3.866 | 1.729 | -2.137 | 10.0 | 81.0 | 94.0 | +| SpinBot | 201 | 1.770 | 1.901 | 0.131 | 94.5 | 100.0 | 98.5 | +| TrackFire | 91 | 0.198 | 0.000 | -0.198 | 0.0 | 98.9 | 100.0 | +| VelociBot | 196 | 9.434 | 2.110 | -7.323 | 11.2 | 77.0 | 93.9 | +| Walls | 219 | 5.944 | 1.398 | -4.546 | 10.0 | 88.6 | 93.6 | + +**MOVING subset**: 824 windows, twinWin 32.8% (bar >=70%: FAIL). **FULL suite**: 1368 windows, twinWin 23.4%. + +## STATIC-subset saturation + +- **RamFire**: mean |enemy speed| 2.79 u/tick, 55% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -2.137). +- **Corners**: mean |enemy speed| 2.59 u/tick, 65% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -2.196). +- **TrackFire**: mean |enemy speed| 0.00 u/tick, 100% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -0.198). +- **Fire**: mean |enemy speed| 1.06 u/tick, 75% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -1.907). diff --git a/ChimeraBot_garage/benchmarks/m5_5_g6.md b/ChimeraBot_garage/benchmarks/m5_5_g6.md new file mode 100644 index 0000000..803faa7 --- /dev/null +++ b/ChimeraBot_garage/benchmarks/m5_5_g6.md @@ -0,0 +1,31 @@ +# G6 ablation ladder (M5.5): probes x carry-over + +Unified idTicks (round-relative, max posterior > 0.8), median over 3 runs x 5 rounds; id% = fraction of rounds identified. Arms: on = probes+carry, off = -probes, reset = -carry, offreset = both. Generated by `tests/bench_g6.nim`. + +| opponent | on med | on id% | off med | off id% | reset med | reset id% | offreset med | offreset id% | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| Corners | 1 | 100.0 | 1 | 100.0 | 44 | 100.0 | 37 | 100.0 | +| Crazy | 16 | 100.0 | 30 | 100.0 | 34 | 100.0 | 65 | 100.0 | +| Fire | 1 | 100.0 | 1 | 100.0 | 19 | 100.0 | 17 | 100.0 | +| RamFire | 1 | 100.0 | 1 | 100.0 | 23 | 100.0 | 23 | 100.0 | +| SpinBot | 1 | 100.0 | 1 | 100.0 | 27 | 100.0 | 27 | 100.0 | +| TrackFire | 1 | 100.0 | 1 | 100.0 | 17 | 100.0 | 16 | 100.0 | +| VelociBot | 1 | 100.0 | 1 | 100.0 | 31 | 100.0 | 31 | 100.0 | +| Walls | 52 | 100.0 | 52 | 100.0 | 54 | 100.0 | 51 | 100.0 | + +**MOVING-subset** pooled: on 1 (id 100.0%), off 6 (id 100.0%), reset 33 (id 100.0%), offreset 39 (id 100.0%). Probes cut = 83.3%, carry-over gain = 97.0%. **G6 bar (>=20% cut, MOVING-subset): PASS**. + +**FULL-suite** pooled: on 1 (id 100.0%), off 1 (id 100.0%), reset 27 (id 100.0%), offreset 28 (id 100.0%). Probes cut = 0.0%, carry-over gain = 96.3%. **G6 bar (>=20% cut, FULL-suite): FAIL**. + +## Run-to-run variance (M5.5 record, not auto-generated) + +The MOVING-subset probe cut is **not stable across bench invocations**. Four +separate 4-arm runs (each 3 runs x 5 rounds per opponent) gave ON/OFF pooled +medians **17/15 (-13.3%)**, **13/17 (+23.5%)**, **13/2 (-550%)**, **1/6 (+83.3%)**. +The sign flips and the magnitude swings by two orders of magnitude; the median +across the four invocations is ON 13 vs OFF 10.5, i.e. **-24%**. Only the +carry-over effect is large and stable (reset->on gain 54.1 / 61.8 / 62.9 / 97.0%). + +**Verdict: probes are still null — no robust >= 20% identification-speed cut +after probe set v2 (G6 probe rung FAIL).** Per the falsification matrix this +indicts the probe component-value claim, not the inference layer (G1 green). diff --git a/ChimeraBot_garage/src/ChimeraBot.nim b/ChimeraBot_garage/src/ChimeraBot.nim index 23ed886..c9cff35 100644 --- a/ChimeraBot_garage/src/ChimeraBot.nim +++ b/ChimeraBot_garage/src/ChimeraBot.nim @@ -35,6 +35,7 @@ import ChimeraBot/modules/ELM/elm_features import ChimeraBot/chimera/observer import ChimeraBot/chimera/dsl import ChimeraBot/chimera/probes +import ChimeraBot/chimera/physics const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds ## only what it scans, so this is a cap, not a limit @@ -288,9 +289,12 @@ method run*(bot: ChimeraBot) = # removes this block entirely (G6 ablation OFF arm). var cmdSpeed = speed var cmdTurn = turnRate + var probeFired = false when ProbesEnabled: if bot.observer.hasCurrent: let porigin = bot.observer.probeOrigin() + let gunBearing = bearingTo(porigin.ox, porigin.oy, + porigin.ex, porigin.ey) let ctx = ProbeContext( tick: bot.tick, ourEnergy: getEnergy(), ownX: porigin.ox, ownY: porigin.oy, ownSpeed: porigin.ospeed, @@ -299,6 +303,8 @@ method run*(bot: ChimeraBot) = enemyGunHeat: bot.observer.enemyGunHeat(), enemyAimedAtUs: aimedAtUs(porigin.ox, porigin.oy, porigin.ex, porigin.ey, porigin.edir), + ourGunHeat: getGunHeat(), + ourGunAimed: abs(wrap180(gunBearing - getGunDirection())) <= 10.0, roundLimit: RoundSoftLimit) let decision = bot.probes.consider(porigin, ctx) if decision.trigger: @@ -309,9 +315,15 @@ method run*(bot: ChimeraBot) = if decision.gate.allow: cmdSpeed = decision.candidate.targetSpeed cmdTurn = decision.candidate.turnRate + # GUN probe (M5.5): the probe IS the shot. Issued only when the + # camouflage gate kept it in the candidate set (cool + aligned). + if decision.candidate.fire > 0.0: + discard setFire(decision.candidate.fire) + probeFired = true setTargetSpeed(cmdSpeed) setTurnRate(cmdTurn) - bot.computeGun() # gun intent, also before go() + if not probeFired: + bot.computeGun() # gun intent, also before go() go() bot.observer.writeTick(bot.tick) # observation telemetry, after go() inc bot.tick diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim index 19ecc9f..2f87738 100644 --- a/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim @@ -58,6 +58,10 @@ type f: File fileOpen: bool + # Cross-round posterior carry-over (M5.5; default on, `-d:chimeraFreshRound` + # restores the per-round reset). + carryOver*: 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]]] @@ -79,12 +83,12 @@ proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer = result.telemetryDir = telemetryDir result.scanTick = -1 result.enemyHeat = 3.0 + result.carryOver = not defined(chimeraFreshRound) 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) +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 @@ -98,6 +102,13 @@ proc resetRound(o: Observer) = o.enemyHeat = 3.0 ## round-start heat (spec §5) 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.resetRoundStats() + proc sanitize*(s: string): string = ## Filename-safe opponent token: collapse runs of non-alphanumerics to `_`. var prevSep = false @@ -120,9 +131,18 @@ proc openTelemetry(o: Observer) = 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() + ## 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) ─────────────────────────────── diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/probes.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/probes.nim index a6e31a0..5bd9a56 100644 --- a/ChimeraBot_garage/src/ChimeraBot/chimera/probes.nim +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/probes.nim @@ -43,12 +43,14 @@ const type ProbeKind* = enum ## Enum order is the deterministic tie-break (earlier wins). - pkSuddenStop, pkReversal, pkSpeedModulation, pkDirectionFlip + pkSuddenStop, pkReversal, pkSpeedModulation, pkDirectionFlip, + pkDistance, pkGunShot ProbeCandidate* = object kind*: ProbeKind turnRate*: float64 targetSpeed*: float64 + fire*: float64 ## gun probe: the probe IS a low-power shot (0 else) GateState* = object allow*: bool @@ -63,6 +65,8 @@ type enemyX*, enemyY*: float64 enemyGunHeat*: float64 ## from the ledger's fire channel (+ decay) enemyAimedAtUs*: bool ## body-heading proxy; gun aim is unobservable + ourGunHeat*: float64 ## our gun heat (gun probes need it at 0) + ourGunAimed*: bool ## our gun points at the enemy (camouflage) roundLimit*: int ## 0 disables the round-end gate ProbeDecision* = object @@ -109,14 +113,23 @@ proc survivalGate*(ctx: ProbeContext): GateState = # ── candidates + camouflage ────────────────────────────────────────────────── +proc gunProbeAllowed*(ctx: ProbeContext): bool = + ## Camouflage gate for a GUN probe (M5.5): a shot is only plausible — and only + ## useful as a probe — when our gun is cool and already pointing at the enemy, + ## so the shot reads as the ELM gun firing anyway. Combined with + ## `survivalGate` (energy / enemy-hot-aimed / wall), never fire when exposed. + ctx.ourGunHeat <= 0.0 and ctx.ourGunAimed and + ctx.ourEnergy >= LowEnergy and not ctx.enemyAimedAtUs + 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. + ## Six plausible body/gun actions. Magnitudes are deliberate so a probe reads + ## as ordinary noise, not a tell. Four movement probes, one DISTANCE probe + ## (approach/retreat burst), and — when the gun gate allows — one GUN probe. let cap = maxTurnRate(ctx.ownSpeed) var rev = -ctx.ownSpeed if abs(rev) < 1.0: rev = -3.0 rev = clamp(rev, -4.0, 4.0) - @[ + result = @[ ProbeCandidate(kind: pkSuddenStop, turnRate: 0.0, targetSpeed: 0.0), ProbeCandidate(kind: pkReversal, turnRate: 0.0, targetSpeed: rev), ProbeCandidate(kind: pkSpeedModulation, turnRate: 0.0, @@ -124,7 +137,15 @@ proc candidates*(ctx: ProbeContext): seq[ProbeCandidate] = MaxBackwardSpeed, MaxForwardSpeed)), ProbeCandidate(kind: pkDirectionFlip, turnRate: min(4.0, cap), targetSpeed: ctx.ownSpeed), + # DISTANCE probe: a strong range-changing burst (approach / retreat). + ProbeCandidate(kind: pkDistance, turnRate: 0.0, + targetSpeed: MaxForwardSpeed), + ProbeCandidate(kind: pkDistance, turnRate: 0.0, + targetSpeed: MaxBackwardSpeed), ] + if gunProbeAllowed(ctx): + result.add ProbeCandidate(kind: pkGunShot, turnRate: 0.0, + targetSpeed: ctx.ownSpeed, fire: MinFirepower) proc camouflage*(c: ProbeCandidate, ctx: ProbeContext): ProbeCandidate = ## Clamp a candidate into the physics envelope: an unachievable command would @@ -133,6 +154,7 @@ proc camouflage*(c: ProbeCandidate, ctx: ProbeContext): ProbeCandidate = result.turnRate = clamp(c.turnRate, -maxTurnRate(ctx.ownSpeed), maxTurnRate(ctx.ownSpeed)) result.targetSpeed = clamp(c.targetSpeed, MaxBackwardSpeed, MaxForwardSpeed) + result.fire = c.fire proc plausible*(c: ProbeCandidate, ctx: ProbeContext): bool = ## Tests-only sanity predicate: camouflage output is always plausible. @@ -172,7 +194,8 @@ proc reactionFeature(kernels: seq[Kernel], origin: ReplayTick, idx: int, ## 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) + plan[h] = PlanStep(turnRate: cand.turnRate, targetSpeed: cand.targetSpeed, + fire: cand.fire) let r = rollout(kernels, onehot(origin, idx), horizon, plan = plan) for p in r.points: result.add p.x diff --git a/ChimeraBot_garage/tests/bench_common.nim b/ChimeraBot_garage/tests/bench_common.nim new file mode 100644 index 0000000..424f480 --- /dev/null +++ b/ChimeraBot_garage/tests/bench_common.nim @@ -0,0 +1,289 @@ +## Shared benchmark plumbing for the M5.5 unified identification metric. +## +## Source of truth: `docs/chimera-spec.md` §12 G4/G6 (M5.5 metric unification). +## `idTicks` is defined ONE way everywhere: per round, the ROUND-RELATIVE tick +## at which `max_kernel posterior > 0.8` first holds. Per opponent the benches +## report median / p90 / id-fraction over ALL rounds in the protocol. Whether the +## argmax equals the expected kernel is a separate diagnostic column. +## +## Live battles need Java + the TR server/runner JARs + the unpacked Nim sample +## bots; callers must guard-skip when absent. Throwaway output lives under /tmp. + +import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times, net, streams] + +const + RunnerJar* = "/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar" + RunnerDir* = currentSourcePath().parentDir.parentDir / ".." / "tools" / "battle_runner" + ServerJar* = "/home/davide/Downloads/robocode-tankroyale/robocode-tankroyale-server.jar" + +# ── restartable server (the shared test server degrades after many battles, +# hanging some opponents; benches therefore own and recycle the server) ──── + +var serverProc: Process = nil +var serverPort = 0 + +proc findFreePort(): int = + let s = newSocket() + s.bindAddr(Port(0)) + let (_, port) = s.getLocalAddr() + s.close() + port.int + +proc restartServer*() = + if serverProc != nil: + serverProc.terminate() + sleep(300) + if serverProc.peekExitCode() == -1: serverProc.kill() + serverProc.close() + serverProc = nil + serverPort = findFreePort() + serverProc = startProcess("java", args = @["-jar", + getEnv("TR_SERVER_JAR", ServerJar), "--port", $serverPort, + "--enable-initial-position", "--tps", "-1"], + options = {poUsePath, poStdErrToStdOut}) + let deadline = epochTime() + 20.0 + var ready = false + while epochTime() < deadline: + var line: string + if not serverProc.outputStream.readLine(line): break + if "Starting server on port" in line: + ready = true + break + if not ready: + quit("TR server did not start") + +proc serverUrl*(): string = "ws://localhost:" & $serverPort + +proc killStaleBots*() = + ## SIGKILL any lingering runner/bot from a timed-out battle. The bracket + ## patterns keep pkill from matching this process's own command line. + discard execCmdEx("pkill -9 -f '[T]estBattleRunner' 2>/dev/null") + discard execCmdEx("pkill -9 -f '[C]himeraBot' 2>/dev/null") + +const + SampleRoot* = getEnv( + "TR_SAMPLE_BOTS", + "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7") + GarageSrc* = currentSourcePath().parentDir.parentDir / "src" + Threshold* = 0.8 ## unified identification threshold (spec G4) + TargetTicks* = 300 ## unified G4 tick budget + MaxAttempts* = 4 + +## The 8 behavior-diverse ground-truth targets and the kernel each is expected +## to identify (§12 verified mapping; v0.2 STATIC refinement documented in +## bench_g4's history). +const Expected* = { + "Crazy": "ZIGZAG", + "SpinBot": "ORBIT_BALLIST", + "RamFire": "STATIC", + "Corners": "STATIC", + "Walls": "WALLCRAWL", + "TrackFire": "STATIC", + "Fire": "STATIC", + "VelociBot": "STOP_AND_GO", +}.toTable + +## G5' v2 subsets (M5.5): persistence is not optimal for the MOVING set. +const MovingOpponents* = @["Crazy", "SpinBot", "VelociBot", "Walls"] +const StaticOpponents* = @["RamFire", "Corners", "TrackFire", "Fire"] + +proc guardSkip*() = + let serverOk = fileExists(getEnv("TR_SERVER_JAR", ServerJar)) + let runnerOk = fileExists(getEnv("TR_BATTLE_RUNNER", RunnerJar)) + if not serverOk or not runnerOk or not dirExists(SampleRoot): + echo "Skipping bench: TR_SERVER_JAR / TR_BATTLE_RUNNER / sample bots missing." + quit(0) + +proc runBattleHard*(serverUrl: string, botDirs: seq[string], rounds: int, + timeoutMs = 90000, maxSpeed = true): bool = + ## Hard-timeout battle: `test_framework.runBattleRunner` can block forever when + ## the Java runner stops emitting output while still alive, so benches use this + ## wrapper (shell redirect to a log, poll, then kill). Battles normally take + ## 1-3 s, so 90 s is generous and bounds a hang. + let jar = getEnv("TR_BATTLE_RUNNER", RunnerJar) + let classDir = getEnv("TR_BATTLE_RUNNER_DIR", RunnerDir) + let logf = getTempDir() / "chimera_runner.log" + var args = "--server-url " & quoteShell(serverUrl) & + " --rounds " & $rounds & + " --bot-dirs " & quoteShell(botDirs.join(",")) + if maxSpeed: args.add " --max-speed" + # coreutils `timeout -s KILL` is the hard guarantee: if the Java runner blocks + # and ignores SIGTERM (shutdown hooks), the shell still kills it at the limit. + let hardSec = int(timeoutMs div 1000) + 5 + let cmd = "timeout -s KILL " & $hardSec & " java -cp " & + quoteShell(classDir & ":" & jar) & + " TestBattleRunner " & args & " > " & quoteShell(logf) & " 2>&1" + let p = startProcess("sh", args = @["-c", cmd], options = {poUsePath}) + let deadline = epochTime() + float(timeoutMs) / 1000.0 + var done = false + while epochTime() < deadline: + if p.peekExitCode() != -1: + done = true + break + sleep(100) + if not done: + p.terminate() + sleep(200) + if p.peekExitCode() == -1: p.kill() + p.close() + return false + result = p.peekExitCode() == 0 + p.close() + +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, defines: seq[string] = @[]): string = + ## Compile ChimeraBot into a throwaway /tmp dir with its json + boot script. + let botDir = getTempDir() / ("chimera_stage_" & tag) / "ChimeraBot" + removeDir(getTempDir() / ("chimera_stage_" & tag)) + createDir(botDir) + let bin = botDir / "ChimeraBot" + var cmd = "nim c -d:release --hints:off " + for d in defines: cmd.add d & " " + 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]) + +proc topWeights(line: string): seq[tuple[name: string, w: float64]] = + ## Parse the `posteriorTop5` array entries `{"name":"X","w":W}` in order. + let start = line.find("\"posteriorTop5\":") + if start < 0: return + let seg = line[start .. ^1] + var i = 0 + while true: + let ni = seg.find("\"name\":\"", i) + if ni < 0: break + let ns = ni + len("\"name\":\"") + var ne = ns + while ne < seg.len and seg[ne] != '"': inc ne + let name = seg[ns ..< ne] + let wi = seg.find("\"w\":", ne) + if wi < 0: break + var j = wi + len("\"w\":") + while j < seg.len and (seg[j] in Digits or seg[j] in {'.', '-', 'e', 'E'}): inc j + var w = 0.0 + try: w = parseFloat(seg[wi + len("\"w\":") ..< j]) + except ValueError: w = 0.0 + result.add (name, w) + i = j + +type + RoundStat* = object + idTick*: int ## round-relative tick max posterior first > Threshold + expIdTick*: int ## same for the EXPECTED kernel (diagnostic) + argmaxCorrect*: bool ## at the crossing tick, argmax == expected kernel + identified*: bool + sumTicks*: int + censorRate*: float64 + finalPosterior*: float64 + finalKernel*: string + ade*, fde*: float64 + gapMax*, gapViolations*: int + +proc parseFile*(path, expectedKernel: string): RoundStat = + ## Unified idTicks parse. Round-relative: the first tick line of the round is + ## tick 1, so carry-over can identify at round start. + result.idTick = -1 + result.expIdTick = -1 + result.argmaxCorrect = false + var t0 = -1 + for ln in readFile(path).splitLines(): + if ln.len == 0: continue + if ln.startsWith("{\"event\":\"round_summary\""): + result.finalPosterior = extract(ln, "finalPosterior").value.parseFloat() + result.finalKernel = extract(ln, "finalKernel").value + result.sumTicks = extract(ln, "ticks").value.parseInt() + result.censorRate = 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() + if t0 < 0: t0 = tick + let rel = tick - t0 + 1 + let tw = topWeights(ln) + if tw.len == 0: continue + var maxW = 0.0 + var maxName = "" + var expW = 0.0 + for (name, w) in tw: + if w > maxW: + maxW = w; maxName = name + if name == expectedKernel and w > expW: expW = w + if result.idTick < 0 and maxW > Threshold: + result.idTick = rel + result.argmaxCorrect = maxName == expectedKernel + if result.expIdTick < 0 and expW > Threshold: + result.expIdTick = rel + result.identified = result.idTick > 0 + +proc p90*(xs: seq[int]): int = + if xs.len == 0: return -1 + var s = xs + s.sort() + s[max(0, int(ceil(0.9 * float(s.len))) - 1)] + +proc medianIndex*(xs: seq[int]): int = + if xs.len == 0: return -1 + var s = xs + s.sort() + s[s.len div 2] + +type + IdStats* = object + median*: int + p90*: int + idFraction*: float64 ## % of rounds identified + n*: int + +proc idStats*(ids: seq[int]): IdStats = + ## `ids[i]` is the round idTick, or -1 when the round never identified. + if ids.len == 0: return IdStats(median: -1, p90: -1, idFraction: 0.0, n: 0) + var identified: seq[int] + for x in ids: + if x > 0: identified.add x + result.n = ids.len + result.median = medianIndex(identified) + result.p90 = p90(identified) + result.idFraction = 100.0 * float(identified.len) / float(ids.len) + +proc fmt*(s: IdStats): string = + ## `med p90 id%` columns, `-` for an empty set. + let m = if s.median < 0: "-" else: $s.median + let p = if s.p90 < 0: "-" else: $s.p90 + align(m, 6) & align(p, 6) & align(formatFloat(s.idFraction, ffDecimal, 0), 6) diff --git a/ChimeraBot_garage/tests/bench_g4.nim b/ChimeraBot_garage/tests/bench_g4.nim index 3542d46..f498d81 100644 --- a/ChimeraBot_garage/tests/bench_g4.nim +++ b/ChimeraBot_garage/tests/bench_g4.nim @@ -1,230 +1,135 @@ -## G4 live-identification benchmark harness (CHIMERA M3). +## G4 live-identification benchmark — unified M5.5 metric. ## -## 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. +## Runs `Repeat` full `Rounds`-round battles per ground-truth opponent against +## the ChimeraBot observation sidecar (server on a random port, tps=-1), and +## reports the UNIFIED idTicks metric per opponent: median / p90 / id-fraction +## over ALL rounds in the protocol (every round of every run). ## -## 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. +## Metric (spec §12, M5.5): per round, the round-relative tick at which +## `max_kernel posterior > 0.8`. argmax correctness is a diagnostic only. +## Pass condition: median <= 300 AND id-fraction >= 80% over >= 3 full 8x5 runs. ## -## 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. +## Findings are reported, never tuned away. Requires Java + JARs + sample bots. +## Run: `nim c -r --hints:off -d:release tests/bench_g4.nim` import std/[os, osproc, strutils, sequtils, math, tables, algorithm] +import bench_common 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" + Repeat = 3 + Rounds = 5 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). -## -## v0.2 refinement from live measurement: Corners and RamFire are modelled by -## STATIC. The §12 source behaviour (Corners parks and sweeps; RamFire charges) -## exists, but in the observable body channels (turn / target-speed / heat-gated -## fire) the *realized* policy is stationary-posture dominated: Corners' approach -## run falls before the radar lock that starts the record, and RamFire spends -## 50-72% of observed ticks wall/collision-pinned spinning in place. The -## static-posture STATIC kernel reaches posterior >= 0.8 on both within 72 ticks -## (v0.2 STATIC_CORNER / RAMMER variants lose to it: see the M3.5 report). This -## is a G2-identifiability finding, not a source claim about those bots. -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 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 - finalKernel: string - 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 - result.finalKernel = extract(ln, "finalKernel").value - 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 +type + Acc = object + ids: seq[int] # per-round unified idTick (-1 = never) + expIds: seq[int] + correct: int # rounds where argmaxCorrect + finalPost, censor, ade, fde: float64 + rounds: int + gapMax, gapViol: int proc run() = guardSkip() - echo "[G4] staging ChimeraBot -> ", StageDir - let botDir = stageBot() - + let botDir = stageBot("g4") removeDir(Telemetry) removeDir(Archive) createDir(Archive) - ensureServer() - let url = getServerUrl() - echo "\nOpponent Rounds idTicks(sum) idTick_best finalPost finalK censorRate ade5 fde5 gapMax/viol" - var allTicks = 0 - var passCount = 0 + var acc = initTable[string, Acc]() for opp in sorted(toSeq(Expected.keys)): + restartServer() + var url = serverUrl() 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.finalKernel = rs.finalKernel - 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), " ", - alignLeft(best.finalKernel, 10), " ", - align($best.sumCensorRate, 7), " ", - align($best.ade, 6), " ", align($best.fde, 6), " ", - $best.gapMax & "/" & $best.gapViolations + var a: Acc + for run in 1 .. Repeat: + var ok = false + for attempt in 1 .. MaxAttempts: + removeDir(Telemetry) + sleep(500) + if runBattleHard(url, @[botDir, sampleBot], Rounds, 90000): + ok = true + break + echo " ", opp, " run", run, " attempt", attempt, ": battle failed/timeout" + killStaleBots() + restartServer() + url = serverUrl() + if not ok: continue + let runDir = Archive / (opp & "-run" & $run) + copyDir(Telemetry, runDir) + for f in toSeq(walkFiles(runDir / "*.jsonl")): + let rs = parseFile(f, Expected[opp]) + if rs.sumTicks == 0: continue + inc a.rounds + a.ids.add(if rs.identified: rs.idTick else: -1) + a.expIds.add(if rs.expIdTick > 0: rs.expIdTick else: -1) + if rs.argmaxCorrect: inc a.correct + a.finalPost += rs.finalPosterior + a.censor += rs.censorRate + a.ade += rs.ade + a.fde += rs.fde + a.gapMax = max(a.gapMax, rs.gapMax) + a.gapViol += rs.gapViolations + if a.rounds > 0: acc[opp] = a - echo "\nTotal identification-capable ticks observed: ", allTicks - echo "Passed (idTick<=300): ", passCount, "/", Expected.len - echo "Per-opponent telemetry archived at: ", Archive + echo "\n=== G4 unified idTicks (M5.5): ", Repeat, " runs x ", Rounds, + " rounds per opponent ===" + echo "Opponent med p90 id% expMed argmaxOk% finalPost% censor% ade5 gapMax/viol" + var lines: seq[string] + lines.add("# G4 unified idTicks (M5.5)\n") + lines.add("Metric: per round, round-relative tick at which `max_kernel posterior > 0.8`; " & + "median / p90 / id-fraction over all rounds. Pass = median <= 300 AND id% >= 80. " & + $Repeat & " runs x " & $Rounds & " rounds. Generated by `tests/bench_g4.nim`.\n") + lines.add("| opponent | median | p90 | id-fraction% | expMedian | argmaxOk% | finalPost% | censor% | ade5 | pass |") + lines.add("|---|---:|---:|---:|---:|---:|---:|---:|---:|---|") + var passed = 0 + var comparable = 0 + var pooled: seq[int] + for opp in sorted(toSeq(Expected.keys)): + if opp notin acc: continue + let a = acc[opp] + let s = idStats(a.ids) + let se = idStats(a.expIds) + let n = float(a.rounds) + let correctPct = 100.0 * float(a.correct) / n + let pass = s.median > 0 and s.median <= TargetTicks and s.idFraction >= 80.0 + inc comparable + if pass: inc passed + pooled.add a.ids + echo " ", alignLeft(opp, 12), s.fmt, + align($(if se.median < 0: "-" else: $se.median), 7), + align(formatFloat(correctPct, ffDecimal, 0), 10), + align(formatFloat(a.finalPost / n * 100.0, ffDecimal, 0), 11), + align(formatFloat(a.censor / n * 100.0, ffDecimal, 1), 8), + align(formatFloat(a.ade / n, ffDecimal, 2), 6), " ", + $a.gapMax & "/" & $a.gapViol + lines.add "| " & opp & " | " & $(if s.median < 0: -1 else: s.median) & " | " & + $(if s.p90 < 0: -1 else: s.p90) & " | " & + formatFloat(s.idFraction, ffDecimal, 1) & " | " & + $(if se.median < 0: -1 else: se.median) & " | " & + formatFloat(correctPct, ffDecimal, 1) & " | " & + formatFloat(a.finalPost / n * 100.0, ffDecimal, 1) & " | " & + formatFloat(a.censor / n * 100.0, ffDecimal, 2) & " | " & + formatFloat(a.ade / n, ffDecimal, 3) & " | " & + (if pass: "PASS" else: "FAIL") & " |" + let ps = idStats(pooled) + echo "\nPooled (all ", pooled.len, " rounds): median ", ps.median, + " p90 ", ps.p90, " id% ", formatFloat(ps.idFraction, ffDecimal, 1) + echo "G4 pass (median<=300 AND id%>=80): ", passed, "/", comparable, + " over ", Repeat, " full 8x5 runs" + lines.add "\nPooled over " & $pooled.len & " rounds: median " & $ps.median & + ", p90 " & $ps.p90 & ", id-fraction " & + formatFloat(ps.idFraction, ffDecimal, 1) & "%. G4 pass: " & $passed & "/" & + $comparable & "." + let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g4.md" + createDir(art.parentDir) + writeFile(art, lines.join("\n") & "\n") + echo "Artifact: ", art + echo "Telemetry archived at: ", Archive when isMainModule: - run() \ No newline at end of file + run() diff --git a/ChimeraBot_garage/tests/bench_g5p.nim b/ChimeraBot_garage/tests/bench_g5p.nim index 65e6d39..4fad1bd 100644 --- a/ChimeraBot_garage/tests/bench_g5p.nim +++ b/ChimeraBot_garage/tests/bench_g5p.nim @@ -1,22 +1,21 @@ -## G5' interventional counterfactual eval (CHIMERA M5) — OFFLINE, no Java. +## G5' v2 interventional counterfactual eval (CHIMERA M5.5) — 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). +## Source: docs/chimera-spec.md §12 G5' (v2 protocol). Reads the probe-ON +## telemetry archived by bench_g6.nim, replays the ledger + Hedge, and for every +## executed probe measures the 5-tick enemy-reaction prediction (twin mixture vs +## persistence baseline) under OUR ACTUAL recorded movement, plus +## reaction-direction agreement. ## -## 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. +## Reported v2: (a) the MOVING subset {Crazy, SpinBot, VelociBot, Walls} — where +## persistence is NOT optimal by construction — and (b) the full suite. Bar: +## twin >= persistence on >= 70% of MOVING-subset windows. The STATIC subset +## {RamFire, Corners, TrackFire, Fire} gets a saturation analysis (why twin ~ +## persistence by construction), one line per opponent. ## ## Run: `nim c -r --hints:off -d:release tests/bench_g5p.nim [telemetryDir]` import std/[os, strutils, tables, math, algorithm, sequtils] +import bench_common import chimera/dsl import chimera/physics import chimera/twinsim @@ -34,11 +33,20 @@ type allWindows: int allTwinAde, allPersAde: float64 allTwinWins: int + speedSum: float64 + speedN: int + slowN: int # scanned ticks with |enemy speed| < 0.5 + +type + Sub = object + windows, twinWins: int + twinAde, persAde: float64 + dirTwin, dirPers, dirN: 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. + ## observation-only (the M4 persistence-bias trap). for ln in lines(path): if ln.find("\"event\":\"probe\"") < 0: continue if ln.find("\"gate\":\"ok\"") < 0: continue @@ -52,7 +60,6 @@ proc probeTicks(path: string): seq[int] = 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 = @@ -68,7 +75,7 @@ proc record(path: string, kernels: seq[Kernel], agg: var Table[string, Agg]) = 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 + # observational floor + static-saturation statistics over the same record for i in 0 ..< rp.len - Horizon: let origin = rp[i] var actual: seq[tuple[x, y: float64]] @@ -87,6 +94,10 @@ proc record(path: string, kernels: seq[Kernel], agg: var Table[string, Agg]) = a.allTwinAde += tAde / float(Horizon) a.allPersAde += pAde / float(Horizon) if tAde <= pAde: inc a.allTwinWins + let sp = abs(origin.espeed) + a.speedSum += sp + inc a.speedN + if sp < 0.5: inc a.slowN # interventional windows: probe ticks only var byTick = initTable[int, int]() for i, r in rp: byTick[r.tick] = i @@ -118,6 +129,18 @@ proc record(path: string, kernels: seq[Kernel], agg: var Table[string, Agg]) = pers[^1].x, pers[^1].y): inc a.dirPersAgree agg[rec.opponent] = a +proc sub(agg: Table[string, Agg], names: seq[string]): Sub = + for name in names: + if name notin agg: continue + let a = agg[name] + result.windows += a.windows + result.twinWins += a.twinWins + result.twinAde += a.twinAde + result.persAde += a.persAde + result.dirTwin += a.dirTwinAgree + result.dirPers += a.dirPersAgree + result.dirN += a.dirN + 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 @@ -132,50 +155,84 @@ proc main() = 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" + var lines: seq[string] + lines.add("# G5' v2 interventional eval (M5.5)\n") + lines.add("Horizon 5, probe-following windows only. MOVING = " & MovingOpponents.join(", ") & + "; STATIC = " & StaticOpponents.join(", ") & ". Source: " & dir & ".\n") + echo "G5' v2 interventional (probe-following), horizon=", Horizon, ", dir=", dir + echo "\nOpponent probes twinADE persADE margin twinWin% dirTwin% dirPers%" + + # per-opponent detail + lines.add("| opponent | probes | twinADE | persADE | margin | twinWin% | dirTwin% | dirPers% |") + lines.add("|---|---:|---:|---:|---:|---:|---:|---:|") 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), + " ", 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) + lines.add "| " & name & " | " & $a.windows & " | " & + formatFloat(a.twinAde / n, ffDecimal, 3) & " | " & + formatFloat(a.persAde / n, ffDecimal, 3) & " | " & + formatFloat((a.persAde - a.twinAde) / n, ffDecimal, 3) & " | " & + formatFloat(win, ffDecimal, 1) & " | " & + formatFloat(100.0 * float(a.dirTwinAgree) / float(max(1, a.dirN)), ffDecimal, 1) & " | " & + formatFloat(100.0 * float(a.dirPersAgree) / float(max(1, a.dirN)), ffDecimal, 1) & " |" + + let mov = sub(agg, MovingOpponents) + let full = sub(agg, toSeq(agg.keys)) + let movWin = 100.0 * float(mov.twinWins) / float(max(1, mov.windows)) + let fullWin = 100.0 * float(full.twinWins) / float(max(1, full.windows)) + echo "\nMOVING subset: ", mov.windows, " windows, twinADE ", + formatFloat(mov.twinAde / float(max(1, mov.windows)), ffDecimal, 3), + " persADE ", formatFloat(mov.persAde / float(max(1, mov.windows)), ffDecimal, 3), + ", twinWin ", formatFloat(movWin, ffDecimal, 1), "%", + " (bar >=70%: ", (if movWin >= 70.0: "PASS" else: "FAIL"), ")" + echo "FULL suite: ", full.windows, " windows, twinWin ", + formatFloat(fullWin, ffDecimal, 1), "%" + echo "MOVING dir agreement: twin ", + formatFloat(100.0 * float(mov.dirTwin) / float(max(1, mov.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 & ")") + formatFloat(100.0 * float(mov.dirPers) / float(max(1, mov.dirN)), ffDecimal, 1), "%" + lines.add "\n**MOVING subset**: " & $mov.windows & " windows, twinWin " & + formatFloat(movWin, ffDecimal, 1) & "% (bar >=70%: " & + (if movWin >= 70.0: "PASS" else: "FAIL") & "). **FULL suite**: " & + $full.windows & " windows, twinWin " & formatFloat(fullWin, ffDecimal, 1) & "%." + + echo "\nSTATIC-subset saturation analysis (why twin ~ persistence by construction):" + lines.add("\n## STATIC-subset saturation\n") + for name in StaticOpponents: + if name notin agg: continue + let a = agg[name] + if a.windows == 0: continue + let n = float(a.windows) + let slowPct = 100.0 * float(a.slowN) / float(max(1, a.speedN)) + let meanSp = a.speedSum / float(max(1, a.speedN)) + let margin = (a.persAde - a.twinAde) / n + echo " ", name, ": mean |enemy speed| ", formatFloat(meanSp, ffDecimal, 2), + " u/tick, ", $int(slowPct + 0.5), + "% of scanned ticks < 0.5 u/tick -> the realized path is near-stationary", + " (persistence is exactly optimal at v=0), so the constant-velocity carry", + " and the twin's stationary/corner kernels coincide and the twin can only", + " match or lose; margin ", formatFloat(margin, ffDecimal, 3), "." + lines.add "- **" & name & "**: mean |enemy speed| " & + formatFloat(meanSp, ffDecimal, 2) & " u/tick, " & $int(slowPct + 0.5) & + "% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence " & + "(v~0) is exactly optimal and the twin's stationary/corner kernels coincide with " & + "it — the twin can only match or lose, never win (margin " & + formatFloat(margin, ffDecimal, 3) & ")." + + let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g5p.md" + createDir(art.parentDir) + writeFile(art, lines.join("\n") & "\n") + echo "\nArtifact: ", art when isMainModule: main() diff --git a/ChimeraBot_garage/tests/bench_g6.nim b/ChimeraBot_garage/tests/bench_g6.nim index 3c05312..62ece5d 100644 --- a/ChimeraBot_garage/tests/bench_g6.nim +++ b/ChimeraBot_garage/tests/bench_g6.nim @@ -1,220 +1,153 @@ -## G6 ablation ladder — probes ON vs OFF (CHIMERA M5). LIVE, Java required. +## G6 ablation ladder — probes x carry-over (CHIMERA M5.5). 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%. +## Four arms over the same 8x5 pinned-opponent protocol, using the UNIFIED +## idTicks metric (round-relative, max posterior > 0.8; median/p90/id-fraction +## over all rounds): +## * on — probes ON, cross-round carry-over ON (default build) +## * off — probes OFF, carry-over ON (-d:chimeraNoProbes) +## * reset — probes ON, fresh-round reset ON (-d:chimeraFreshRound) +## * offreset — probes OFF, fresh-round reset ON (both defines) ## -## 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. +## Primary G6 read: probes must cut the MOVING-subset median identification +## ticks by >= 20% (`on` vs `off`), reported for the full suite too. The +## carry-over effect is `on` vs `reset`. ## -## 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` +## ON telemetry archived to /tmp/chimera_g6_on (input to bench_g5p.nim). +## Run: `nim c -r --hints:off -d:release tests/bench_g6.nim` -import std/[os, osproc, strutils, sequtils, math, tables, algorithm] +import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times] +import bench_common 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" + Rounds = 5 + Repeat = 3 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 + ArmTags = ["on", "off", "reset", "offreset"] -const Expected = { - "Crazy": "ZIGZAG", - "SpinBot": "ORBIT_BALLIST", - "RamFire": "STATIC", - "Corners": "STATIC", - "Walls": "WALLCRAWL", - "TrackFire": "STATIC", - "Fire": "STATIC", - "VelociBot": "STOP_AND_GO", -}.toTable +proc armDefines(tag: string): seq[string] = + case tag + of "on": @[] + of "off": @["-d:chimeraNoProbes"] + of "reset": @["-d:chimeraFreshRound"] + else: @["-d:chimeraNoProbes", "-d:chimeraFreshRound"] -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) +proc runArm(tag: string): Table[string, seq[int]] = + let botDir = stageBot("g6_" & tag, armDefines(tag)) removeDir(Telemetry) - let armDir = if off: OffDir else: OnDir + let armDir = getTempDir() / ("chimera_g6_" & tag) removeDir(armDir) createDir(armDir) - ensureServer() - let url = getServerUrl() for opp in sorted(toSeq(Expected.keys)): + restartServer() + var url = serverUrl() putEnv("CHIMERA_OPPONENT", opp) putEnv("CHIMERA_TELEMETRY_DIR", Telemetry) let sampleBot = SampleRoot / opp + var ids: seq[int] for run in 1 .. Repeat: var ok = false + let t0 = epochTime() for attempt in 1 .. MaxAttempts: removeDir(Telemetry) - sleep(1200) - try: - discard runBattleRunner(url, @[botDir, sampleBot], rounds = Rounds, - timeout = 300000) + sleep(500) + if runBattleHard(url, @[botDir, sampleBot], Rounds, 90000): ok = true break - except CatchableError: - if attempt >= MaxAttempts: - echo " ", tag, " ", opp, " run", run, ": battle failed" + echo " ", tag, " ", opp, " run", run, " attempt", attempt, + ": battle failed/timeout" + killStaleBots() + restartServer() + url = serverUrl() + echo " [", tag, "] ", opp, " run", run, " ok=", ok, " in ", + formatFloat(epochTime() - t0, ffDecimal, 1), "s (attempts used)" 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) + let runDir = armDir / (opp & "-run" & $run) + copyDir(Telemetry, runDir) + for f in toSeq(walkFiles(runDir / "*.jsonl")): + let rs = parseFile(f, Expected[opp]) + if rs.sumTicks == 0: continue + ids.add(if rs.identified: rs.idTick else: -1) 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 pooled(arm: Table[string, seq[int]], opps: seq[string]): seq[int] = + for opp in opps: + if opp in arm: result.add arm[opp] + +proc cutPct(onMed, offMed: int): float64 = + if offMed <= 0: 0.0 else: 100.0 * float(offMed - onMed) / float(offMed) 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 "[G6] 4 arms x ", Repeat, " runs x ", Rounds, " rounds" + var tabs = initTable[string, Table[string, seq[int]]]() + for tag in ArmTags: + tabs[tag] = runArm(tag) - 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 + echo "\n=== G6 arms: unified idTicks median / id-fraction% (", Repeat, + " runs x ", Rounds, " rounds) ===" + echo "Opponent on med id% off med id% reset med id% offreset med id%" + var lines: seq[string] + lines.add("# G6 ablation ladder (M5.5): probes x carry-over\n") + lines.add("Unified idTicks (round-relative, max posterior > 0.8), median over " & + $Repeat & " runs x " & $Rounds & " rounds; id% = fraction of rounds identified. " & + "Arms: on = probes+carry, off = -probes, reset = -carry, offreset = both. " & + "Generated by `tests/bench_g6.nim`.\n") + lines.add("| opponent | on med | on id% | off med | off id% | reset med | reset id% | offreset med | offreset id% |") + lines.add("|---|---:|---:|---:|---:|---:|---:|---:|---:|") 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)" + var cells: seq[string] + var textLine = " " & alignLeft(opp, 12) + var row = "| " & opp & " |" + for tag in ArmTags: + if opp in tabs[tag]: + let s = idStats(tabs[tag][opp]) + let m = if s.median < 0: "-" else: $s.median + textLine.add align(m, 8) & align(formatFloat(s.idFraction, ffDecimal, 0), 5) + row.add " " & m & " | " & formatFloat(s.idFraction, ffDecimal, 1) & " |" + else: + textLine.add align("-", 8) & align("-", 5) + row.add " - | - |" + echo textLine + lines.add row + + let full = @["Crazy", "SpinBot", "RamFire", "Corners", "Walls", + "TrackFire", "Fire", "VelociBot"] + echo "" + echo "Metric on off reset offreset" + for (label, opps) in [("MOVING-subset", MovingOpponents), ("FULL-suite", full)]: + var st: Table[string, IdStats] + for tag in ArmTags: + st[tag] = idStats(pooled(tabs[tag], opps)) + echo alignLeft(label, 18), + align($st["on"].median, 7), align($st["off"].median, 8), + align($st["reset"].median, 8), align($st["offreset"].median, 10), + " (id%: ", formatFloat(st["on"].idFraction, ffDecimal, 0), "/", + formatFloat(st["off"].idFraction, ffDecimal, 0), "/", + formatFloat(st["reset"].idFraction, ffDecimal, 0), "/", + formatFloat(st["offreset"].idFraction, ffDecimal, 0), ")" + let cut = cutPct(st["on"].median, st["off"].median) + let carryGain = if st["reset"].median > 0: + 100.0 * float(st["reset"].median - st["on"].median) / float(st["reset"].median) + else: 0.0 + echo " probes cut (off->on) = ", formatFloat(cut, ffDecimal, 1), + "% carry-over gain (reset->on) = ", formatFloat(carryGain, ffDecimal, 1), "%" + lines.add "\n**" & label & "** pooled: on " & $st["on"].median & " (id " & + formatFloat(st["on"].idFraction, ffDecimal, 1) & "%), off " & + $st["off"].median & " (id " & formatFloat(st["off"].idFraction, ffDecimal, 1) & + "%), reset " & $st["reset"].median & " (id " & + formatFloat(st["reset"].idFraction, ffDecimal, 1) & "%), offreset " & + $st["offreset"].median & " (id " & + formatFloat(st["offreset"].idFraction, ffDecimal, 1) & "%). Probes cut = " & + formatFloat(cut, ffDecimal, 1) & "%, carry-over gain = " & + formatFloat(carryGain, ffDecimal, 1) & "%. **G6 bar (>=20% cut, " & label & "): " & + (if cut >= 20.0: "PASS" else: "FAIL") & "**." + + let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g6.md" + createDir(art.parentDir) + writeFile(art, lines.join("\n") & "\n") + echo "Artifact: ", art + echo "ON telemetry archived at ", getTempDir() / "chimera_g6_on" when isMainModule: main() diff --git a/ChimeraBot_garage/tests/test_observer.nim b/ChimeraBot_garage/tests/test_observer.nim index 04a06aa..2ebc9c8 100644 --- a/ChimeraBot_garage/tests/test_observer.nim +++ b/ChimeraBot_garage/tests/test_observer.nim @@ -44,6 +44,30 @@ block: check("argmax is " & kernels[i].name & " when it crossed", crossArgmax == kernels[i].name, "got " & crossArgmax) +block: + echo "observer: cross-round posterior carry-over (M5.5)" + removeDir(telemetryDir) + let env = defaultEnv() + let o = initObserver(kernels, "") + o.startRound(1) + let stream = generateOracle(kernels[2], kernels[2].defaultParams, env, 300) + 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, "ZIGZAG", env.arenaW, env.arenaH) + let top = o.argmaxName() + let carried = o.posterior(top) + check("round 1 identified (> 0.8)", carried > 0.8, + $top & " = " & $carried) + o.startRound(2) + check("carry-over keeps the posterior across rounds", + o.posterior(top) == carried, $carried & " -> " & $o.posterior(top)) + o.carryOver = false + o.startRound(3) + check("fresh-round ablation resets to uniform", + abs(o.posterior(top) - 1.0 / float64(kernels.len)) < 1e-12, + $o.posterior(top)) + block: echo "observer: telemetry files are well-formed (Crazy/ZIGZAG)" removeDir(telemetryDir) diff --git a/ChimeraBot_garage/tests/test_probes.nim b/ChimeraBot_garage/tests/test_probes.nim index 844bdb0..71e9c71 100644 --- a/ChimeraBot_garage/tests/test_probes.nim +++ b/ChimeraBot_garage/tests/test_probes.nim @@ -130,6 +130,36 @@ block: if abs(cam.targetSpeed) <= 8.0 and abs(cam.turnRate) <= 10.0: anySmall = true check("probe magnitudes stay plausible", anySmall) +block: + echo "probes 6: probe set v2 (distance + gun, M5.5)" + var c = baseCtx() + check("gunProbeAllowed false when not aimed", not gunProbeAllowed(c)) + var kinds: set[ProbeKind] = {} + var gunFire = 0.0 + for cand in candidates(c): + kinds.incl cand.kind + if cand.kind == pkGunShot: gunFire = cand.fire + check("distance candidate present", pkDistance in kinds) + check("gun candidate absent when not aimed", pkGunShot notin kinds) + c.ourGunHeat = 0.0; c.ourGunAimed = true + check("gunProbeAllowed true when cool+aimed", gunProbeAllowed(c)) + kinds = {}; gunFire = 0.0 + for cand in candidates(c): + kinds.incl cand.kind + if cand.kind == pkGunShot: gunFire = cand.fire + check("gun candidate present when cool+aimed", pkGunShot in kinds) + check("gun probe IS a shot (low power)", gunFire > 0.0, $gunFire) + check("all six probe types selectable", kinds.len == 6, $kinds) + var d = baseCtx(); d.ourGunHeat = 0.0; d.ourGunAimed = true; d.enemyAimedAtUs = true + check("gunProbeAllowed false when enemy aimed at us", not gunProbeAllowed(d)) + var e = baseCtx(); e.ourGunHeat = 1.0; e.ourGunAimed = true + check("gunProbeAllowed false when our gun hot", not gunProbeAllowed(e)) + let dec = chooseProbe(kernels, origin(), c) + check("chooseProbe deterministic over v2 set", + dec.candidate.kind == chooseProbe(kernels, origin(), c).candidate.kind) + check("entropy selection covers v2 set (non-increasing entropy)", + dec.entropyAfter <= dec.entropyBefore + 1e-9) + block: echo "probes 5: entropy closed form" check("uniform n=4 entropy = ln4",