ChimeraBot_garage: M5 — probe scheduler, advisory wiring, G6 ablation ON/OFF, G5 interventional eval

This commit is contained in:
2026-10-07 00:33:31 +02:00
parent da9a66aab8
commit 6a3ba390ee
10 changed files with 944 additions and 5 deletions
+181
View File
@@ -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()
+220
View File
@@ -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()
+24 -1
View File
@@ -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 ""
+143
View File
@@ -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)
+26
View File
@@ -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"