ChimeraBot_garage: M2 — intent ledger, DSL v0 kernels, Hedge posterior, G1 oracle tests

This commit is contained in:
2026-10-06 23:50:27 +02:00
parent 5de4b906af
commit c77541a6d7
11 changed files with 1102 additions and 0 deletions
+92
View File
@@ -0,0 +1,92 @@
## Tier A unit tests for the CHIMERA Hedge posterior (chimera/hedge.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/hedge
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc sum(h: Hedge): float64 =
for w in h.weights: result += w
block:
echo "test 1: uniform prior and normalization"
var h = initHedge(@["a", "b", "c", "d"])
check("sums to 1", abs(sum(h) - 1.0) < 1e-12, $sum(h))
check("entropy = ln N", abs(h.entropy() - ln(4.0)) < 1e-12, $h.entropy())
h.update(@[0.0, 1.0, 0.5, 2.0])
check("stays normalized after update", abs(sum(h) - 1.0) < 1e-12, $sum(h))
block:
echo "test 2: eta effect sign (sharper with larger eta)"
var slow = initHedge(@["good", "bad"])
var fast = initHedge(@["good", "bad"])
slow.cfg.eta = 0.5
fast.cfg.eta = 4.0
for i in 0 ..< 10:
slow.update(@[0.0, 1.0])
fast.update(@[0.0, 1.0])
check("both favour the good kernel", slow.posterior("good") > 0.5 and
fast.posterior("good") > 0.5)
check("larger eta is sharper",
fast.posterior("good") > slow.posterior("good"),
$fast.posterior("good") & " vs " & $slow.posterior("good"))
block:
echo "test 3: forgetting revives a switched kernel"
var h = initHedge(@["A", "B"])
for i in 0 ..< 200:
h.update(@[0.0, 1.0]) # A is right for a long time
let aHigh = h.posterior("A")
check("A dominates before the switch", aHigh > 0.9, $aHigh)
for i in 0 ..< 200:
h.update(@[1.0, 0.0]) # policy switches to B
check("B recovers after the switch", h.posterior("B") > 0.9,
$h.posterior("B"))
block:
echo "test 4: Fixed-Share mass floor w_i >= alpha*m_i"
var h = initHedge(@["a", "b", "c", "d"])
h.cfg.alpha = 0.05
for i in 0 ..< 500:
h.update(@[0.0, 100.0, 100.0, 100.0]) # crush b, c, d
let m = 1.0 / 4.0
var floored = true
for i in 0 ..< h.weights.len:
if h.weights[i] < h.cfg.alpha * m - 1e-12: floored = false
check("every weight respects the floor", floored, $h.weights)
# The floor a*m is exact pre-normalization; after renormalizing (Z <= 1) a
# crushed loser sits at or just above it.
check("loser mass sits at the floor",
h.posterior("b") >= 0.05 * m - 1e-12 and h.posterior("b") < 0.05 * m * 1.1,
$h.posterior("b"))
block:
echo "test 5: entropy and top-k sanity"
var h = initHedge(@["a", "b", "c"])
let top = h.topK(2)
check("top-k returns k entries", top.len == 2)
check("top-k sorted descending", top[0].weight >= top[1].weight)
for i in 0 ..< 200: h.update(@[0.0, 3.0, 3.0])
check("entropy collapses toward 0", h.entropy() < 0.5, $h.entropy())
check("argmax names the winner", h.argmaxName() == "a", h.argmaxName())
block:
echo "test 6: revision-safe clone / setWeights"
var h = initHedge(@["a", "b"])
h.update(@[0.0, 1.0])
let c = h.clone()
h.update(@[1.0, 0.0])
check("clone is independent", c.posterior("a") != h.posterior("a"))
var d = c.clone()
d.setWeights(@[3.0, 1.0])
check("setWeights normalizes", abs(sum(d) - 1.0) < 1e-12)
check("setWeights ratios preserved", abs(d.posterior("a") - 0.75) < 1e-12,
$d.posterior("a"))
echo ""
if failed == 0: echo "all hedge tests passed"
else: echo failed, " hedge test(s) FAILED"; quit(1)
+86
View File
@@ -0,0 +1,86 @@
## Tier A unit tests for the CHIMERA intent ledger (chimera/ledger.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/ledger
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc scan(tick: int, dir: float64, speed: float64,
energy = 100.0): Scan =
Scan(tick: tick, direction: dir, speed: speed, energy: energy)
block:
echo "test 1: turn-rate interval recovery"
# 5 deg/tick at speed 0 (cap 10): exactly recovered.
let o = turnRateInterval(scan(1, 10.0, 0.0), scan(2, 15.0, 0.0))
check("turn known", o.turnKnown)
check("interval contains 5", o.turnRate.contains(5.0))
check("interval tight (width ~ 2e-6)", o.turnRate.width() < 1e-5,
$o.turnRate.width())
# wrap across 0: -5 deg/tick.
let w = turnRateInterval(scan(1, 0.0, 0.0), scan(2, -5.0, 0.0))
check("wrap interval contains -5", w.turnRate.contains(-5.0))
# cap at speed 8 is 4 deg/tick: an observed 4 is at the boundary.
let c = turnRateInterval(scan(1, 0.0, 8.0), scan(2, 4.0, 8.0))
check("capped turn contains 4", c.turnRate.contains(4.0))
check("cap upper bound is 4", abs(c.turnRate.hi - 4.0) < 1e-6, $c.turnRate.hi)
block:
echo "test 2: scan gap is censored, never guessed"
let g = turnRateInterval(scan(1, 0.0, 3.0), scan(3, 5.0, 3.0))
check("censored", g.censored)
check("turn not known", not g.turnKnown)
block:
echo "test 3: target-speed interval inversion"
# from rest, target 5 realizes +1 next tick; consistent set is [1, 8].
let a = targetSpeedInterval(0.0, 1.0)
check("known", a.targetKnown)
check("contains 5", a.targetSpeed.contains(5.0))
# decel from 8 toward 3 clamps to 6: consistent set (0, 6].
let d = targetSpeedInterval(8.0, 6.0)
check("decel contains 3", d.targetSpeed.contains(3.0))
check("decel upper bound 6", abs(d.targetSpeed.hi - 6.0) < 1e-9, $d.targetSpeed.hi)
# exact meet: 8 -> 7 names target 7.
let e = targetSpeedInterval(8.0, 7.0)
check("meet names 7", e.targetSpeed.contains(7.0) and e.targetSpeed.width() < 1e-6,
$e.targetSpeed)
# crossing zero from 8 realizes +3 regardless of the negative target.
let x = targetSpeedInterval(8.0, 3.0)
check("crossing contains -5", x.targetSpeed.contains(-5.0))
check("crossing interval is [-8, 0]",
abs(x.targetSpeed.lo + 8.0) < 1e-9 and abs(x.targetSpeed.hi) < 1e-9,
$x.targetSpeed)
# impossible: +5 from rest is unphysical.
let imp = targetSpeedInterval(0.0, 5.0)
check("impossible step censored", imp.censored and not imp.targetKnown)
block:
echo "test 4: fire inference from energy drop"
let f = fireFromEnergyDrop(100.0, 97.5, 0.0)
check("known fire", f.fireKnown and abs(f.fire - 2.5) < 1e-9, $f.fire)
let none = fireFromEnergyDrop(100.0, 100.0, 0.0)
check("no drop -> not known", not none.fireKnown)
let amb = fireFromEnergyDrop(100.0, 98.0, 1.0)
check("known damage -> censored", amb.censored)
let bad = fireFromEnergyDrop(100.0, 90.0, 0.0)
check("out-of-range drop -> censored", bad.censored)
block:
echo "test 5: censoring-rate accounting"
var obs: seq[LedgerObs] = @[]
obs.add LedgerObs(censored: false)
obs.add LedgerObs(censored: true)
obs.add LedgerObs(censored: false)
obs.add LedgerObs(censored: true)
obs.add LedgerObs(censored: false)
check("2/5 censored", abs(censorRate(obs) - 0.4) < 1e-12, $censorRate(obs))
check("empty -> 0", censorRate(newSeq[LedgerObs](0)) == 0.0)
echo ""
if failed == 0: echo "all ledger tests passed"
else: echo failed, " ledger test(s) FAILED"; quit(1)
@@ -0,0 +1,56 @@
## G1 oracle-convergence test (spec §12 Tier C, G1).
##
## For every kernel K in the M2 set: generate K's exact oracle intent stream over
## the synthetic arena, replay it through the ledger + Hedge, and require
## posterior(K) >= 0.9 within T* = 300 ticks. A failure here indicts the
## inference layer (implementation bug) — it is reported, never hidden.
##
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/[math, strutils]
import chimera/dsl
import chimera/oracle
const TStar = 300
const Threshold = 0.9
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()
let env = defaultEnv()
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)
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)
echo " ", align(r.kernel, 16), idStr, " ", formatFloat(r.finalPosterior,
ffDecimal, 5), " ", formatFloat(r.censorRate, ffDecimal, 4)
let ok = r.idTick > 0 and r.idTick <= TStar and r.finalPosterior >= Threshold
check("G1 " & r.kernel & " identified within T*", ok,
"idTick=" & $r.idTick & " posterior=" & formatFloat(r.finalPosterior,
ffDecimal, 4))
block:
echo ""
echo "G1 determinism: identical reruns"
let a = runG1(kernels, 0, env, TStar)
let b = runG1(kernels, 0, env, TStar)
check("same idTick", a.idTick == b.idTick, $a.idTick & " vs " & $b.idTick)
check("same posterior", a.finalPosterior == b.finalPosterior)
let s1 = generateOracle(kernels[2], kernels[2].defaultParams, env, 100)
let s2 = generateOracle(kernels[2], kernels[2].defaultParams, env, 100)
var same = s1.scans.len == s2.scans.len
for i in 0 ..< min(s1.scans.len, s2.scans.len):
if s1.scans[i].x != s2.scans[i].x or s1.scans[i].direction != s2.scans[i].direction:
same = false
check("oracle stream is byte-identical", same)
echo ""
if failed == 0: echo "all G1 oracle tests passed"
else: echo failed, " G1 test(s) FAILED"; quit(1)
+72
View File
@@ -0,0 +1,72 @@
## Tier A unit tests for the CHIMERA physics mirror (chimera/physics.nim).
## Run: from ChimeraBot_garage/src, `nimble test` (or
## `nim c -r ../tests/test_physics.nim`).
##
## Ground truth: robocode-tankroyale server `rules/math.kt`. The exact fixtures
## below are hand-derived from that source, not from our own output.
import std/math
import chimera/physics
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc approx(a, b: float64): bool = abs(a - b) < 1e-9
block:
echo "test 1: stepSpeed truth table (calcNewBotSpeed)"
check("0 -> target 5 accelerates by 1", approx(stepSpeed(0.0, 5.0), 1.0),
$stepSpeed(0.0, 5.0))
check("0 -> target 0.5 snaps to target", approx(stepSpeed(0.0, 0.5), 0.5))
check("0 -> target -0.5 snaps to target", approx(stepSpeed(0.0, -0.5), -0.5))
check("3 -> target 8 accelerates by 1", approx(stepSpeed(3.0, 8.0), 4.0))
check("8 -> target 0.5 decelerates by 2", approx(stepSpeed(8.0, 0.5), 6.0))
check("8 -> target 7 meets it (diff -1)", approx(stepSpeed(8.0, 7.0), 7.0))
check("1 -> target 0.5 meets it", approx(stepSpeed(1.0, 0.5), 0.5))
# crossing-zero branch: v_new = (1 - v/2) * -1, a direct assignment
check("8 crossing to -5 -> +3", approx(stepSpeed(8.0, -5.0), 3.0))
check("3 crossing to -5 -> +0.5", approx(stepSpeed(3.0, -5.0), 0.5))
check("0.5 crossing to -5 -> -0.75", approx(stepSpeed(0.5, -5.0), -0.75))
check("2 crossing to -5 -> 0.0", approx(stepSpeed(2.0, -5.0), 0.0))
check("target 0 from 8 stops", approx(stepSpeed(8.0, 0.0), 0.0))
# odd symmetry handles negative current speeds
check("-3 -> target -8 accelerates by -1", approx(stepSpeed(-3.0, -8.0), -4.0))
check("-8 crossing to +5 -> -3", approx(stepSpeed(-8.0, 5.0), -3.0))
check("clamp at +8", approx(stepSpeed(8.0, 20.0), 8.0))
check("clamp at -8", approx(stepSpeed(-8.0, -20.0), -8.0))
block:
echo "test 2: maxTurnRate identities (calcMaxTurnRate)"
check("v=0 -> 10", approx(maxTurnRate(0.0), 10.0))
check("v=8 -> 4", approx(maxTurnRate(8.0), 4.0))
check("v=-8 -> 4", approx(maxTurnRate(-8.0), 4.0))
check("v=4 -> 7", approx(maxTurnRate(4.0), 7.0))
check("clamped above max speed", approx(maxTurnRate(100.0), 4.0))
check("limitTurnRate clamps", approx(limitTurnRate(50.0, 8.0), 4.0))
block:
echo "test 3: bullet speed/damage/heat fixtures"
check("bulletSpeed(0.1)=19.7", approx(bulletSpeed(0.1), 19.7))
check("bulletSpeed(1)=17", approx(bulletSpeed(1.0), 17.0))
check("bulletSpeed(3)=11", approx(bulletSpeed(3.0), 11.0))
check("bulletSpeed clamps p>3", approx(bulletSpeed(5.0), 11.0))
check("bulletDamage(1)=4", approx(bulletDamage(1.0), 4.0))
check("bulletDamage(2)=10", approx(bulletDamage(2.0), 10.0))
check("bulletDamage(3)=16", approx(bulletDamage(3.0), 16.0))
check("bulletDamage(0.5)=2", approx(bulletDamage(0.5), 2.0))
check("gunHeat(1)=1.2", approx(gunHeat(1.0), 1.2))
check("gunHeat(3)=1.6", approx(gunHeat(3.0), 1.6))
block:
echo "test 4: angles"
check("wrap180(370)=10", approx(wrap180(370.0), 10.0))
check("wrap180(-190)=170", approx(wrap180(-190.0), 170.0))
check("wrap180(180)=180", approx(wrap180(180.0), 180.0))
check("bearing east", approx(bearingTo(0.0, 0.0, 1.0, 0.0), 0.0))
check("bearing north", approx(bearingTo(0.0, 0.0, 0.0, 1.0), 90.0))
echo ""
if failed == 0: echo "all physics tests passed"
else: echo failed, " physics test(s) FAILED"; quit(1)