From c77541a6d73130a8d8fa3fa3bd1bc6713133e3ad Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Tue, 6 Oct 2026 23:50:27 +0200 Subject: [PATCH] =?UTF-8?q?ChimeraBot=5Fgarage:=20M2=20=E2=80=94=20intent?= =?UTF-8?q?=20ledger,=20DSL=20v0=20kernels,=20Hedge=20posterior,=20G1=20or?= =?UTF-8?q?acle=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ChimeraBot_garage/README.md | 8 + ChimeraBot_garage/src/ChimeraBot.nimble | 4 + .../src/ChimeraBot/chimera/dsl.nim | 298 ++++++++++++++++++ .../src/ChimeraBot/chimera/hedge.nim | 108 +++++++ .../src/ChimeraBot/chimera/ledger.nim | 148 +++++++++ .../src/ChimeraBot/chimera/oracle.nim | 140 ++++++++ .../src/ChimeraBot/chimera/physics.nim | 90 ++++++ ChimeraBot_garage/tests/test_hedge.nim | 92 ++++++ ChimeraBot_garage/tests/test_ledger.nim | 86 +++++ ChimeraBot_garage/tests/test_oracle_g1.nim | 56 ++++ ChimeraBot_garage/tests/test_physics.nim | 72 +++++ 11 files changed, 1102 insertions(+) create mode 100644 ChimeraBot_garage/src/ChimeraBot/chimera/dsl.nim create mode 100644 ChimeraBot_garage/src/ChimeraBot/chimera/hedge.nim create mode 100644 ChimeraBot_garage/src/ChimeraBot/chimera/ledger.nim create mode 100644 ChimeraBot_garage/src/ChimeraBot/chimera/oracle.nim create mode 100644 ChimeraBot_garage/src/ChimeraBot/chimera/physics.nim create mode 100644 ChimeraBot_garage/tests/test_hedge.nim create mode 100644 ChimeraBot_garage/tests/test_ledger.nim create mode 100644 ChimeraBot_garage/tests/test_oracle_g1.nim create mode 100644 ChimeraBot_garage/tests/test_physics.nim diff --git a/ChimeraBot_garage/README.md b/ChimeraBot_garage/README.md index 1043f95..76dabf9 100644 --- a/ChimeraBot_garage/README.md +++ b/ChimeraBot_garage/README.md @@ -22,3 +22,11 @@ cd ChimeraBot_garage/src && nimble test # unit tests `SERVER_URL` / `SERVER_SECRET` come from the environment; an optional `.env` beside the `.nimble` is loaded without ever overriding a preexisting variable. + +## CHIMERA modules (M2) + +`src/ChimeraBot/chimera/` holds the inert CHIMERA libraries implemented at M2 — +`physics.nim` (server-math mirror), `ledger.nim` (intent ledger), `dsl.nim` (the +v0 kernel library), `hedge.nim` (Hedge posterior) and `oracle.nim` (G1 harness). +They are **not wired into the run loop**: the bot still runs the exact +DevControlBot copy unchanged. They become live at M3. diff --git a/ChimeraBot_garage/src/ChimeraBot.nimble b/ChimeraBot_garage/src/ChimeraBot.nimble index df6367e..bce5e4f 100644 --- a/ChimeraBot_garage/src/ChimeraBot.nimble +++ b/ChimeraBot_garage/src/ChimeraBot.nimble @@ -254,3 +254,7 @@ task runBot, "Compile, run and clean up the bot": task test, "Run unit tests": exec "nim c -r --hints:off ../tests/test_elm.nim" exec "nim c -r --hints:off ../tests/test_online.nim" + exec "nim c -r --hints:off ../tests/test_physics.nim" + exec "nim c -r --hints:off ../tests/test_ledger.nim" + exec "nim c -r --hints:off ../tests/test_hedge.nim" + exec "nim c -r --hints:off ../tests/test_oracle_g1.nim" diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/dsl.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/dsl.nim new file mode 100644 index 0000000..d0dfa60 --- /dev/null +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/dsl.nim @@ -0,0 +1,298 @@ +## CHIMERA DSL v0 — the null-hypothesis kernel library. +## +## A *kernel* is a small deterministic state machine that maps the observable +## enemy state to one intent `(turnRate, targetSpeed, fire)`. Source of truth: +## `docs/chimera-spec.md` §6 (inventory) and §12 (the sample-bot behaviour table +## that fixes each kernel's provenance). +## +## M2 scope: the spec's K1/K5/K6/K7/K9/K10 kernels plus the SpinBot/Crazy +## variants (ORBIT_BALLIST, ZIGZAG). K2/K3/K4/K8 are deferred to M3 — they are +## not needed for G1 and are not registered here. +## +## Kernel memory is explicit (`KernelMem`), so a step is a pure function of +## `(observed state, caller state, params, memory)` and reruns are byte-identical. + +import std/math +import ./physics + +type + EnemyState* = object + ## What the twin can observe about the enemy on the current tick. + tick*: int + x*: float64 + y*: float64 + direction*: float64 + speed*: float64 + energy*: float64 + + MyState* = object + ## Our own position — the target of orbit/ram kernels. + x*: float64 + y*: float64 + + Intent* = object + turnRate*: float64 ## commanded body turn, deg/tick + targetSpeed*: float64 ## commanded target speed, units/tick + fire*: float64 ## fire power, 0 = no fire + + Params* = object + ## Generic parameter slots. Unused slots keep their defaults. + range*: float64 ## preferred orbit range (ORBIT_LOCK) + hysteresis*: float64 ## orbit hysteresis band (ORBIT_LOCK) + dir*: float64 ## +1 / -1 preferred tangential direction + speed*: float64 ## cruise speed + margin*: float64 ## wall proximity margin + segmentLen*: float64 ## wall-crawl segment length + zigzagTicks*: int ## Crazy-style periodic 180 flip interval + corner*: int ## initial corner index (CORNER_RUN) + fireCooldown*: int ## min ticks between shots + rngClass*: int ## 0 = LCG, 1 = xorshift64, 2 = splitmix64 + seed*: uint64 ## RNG seed + arenaW*: float64 + arenaH*: float64 + + KernelMem* = object + phase*: int + counter*: int + latch*: float64 + startDir*: float64 + segX*: float64 + segY*: float64 + rngState*: uint64 + + KernelStep* = proc(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent {.nimcall.} + + Kernel* = object + name*: string + step*: KernelStep + defaultParams*: Params + +# ── shared helpers ────────────────────────────────────────────────────────── + +proc defaultParams*(): Params = + Params(range: 300.0, hysteresis: 60.0, dir: 1.0, speed: 6.0, margin: 40.0, + segmentLen: 200.0, zigzagTicks: 60, corner: 0, fireCooldown: 15, + rngClass: 0, seed: 0x2545F4914F6CDD1D'u64, arenaW: 800.0, arenaH: 600.0) + +proc defaultMemory*(p: Params): KernelMem = + KernelMem(phase: 0, counter: 0, latch: 1.0, startDir: 0.0, + segX: 0.0, segY: 0.0, rngState: p.seed) + +proc dist(e: EnemyState, m: MyState): float64 = + hypot(m.x - e.x, m.y - e.y) + +proc nearWall(e: EnemyState, p: Params): bool = + e.x < p.margin or e.x > p.arenaW - p.margin or + e.y < p.margin or e.y > p.arenaH - p.margin + +proc nextRng*(state: var uint64, cls: int): uint64 = + ## Deterministic RNG classes (spec K7): A = LCG, B = xorshift64, C = splitmix64. + case cls + of 0: + state = state * 6364136223846793005'u64 + 1442695040888963407'u64 + of 1: + state = state xor (state shl 13) + state = state xor (state shr 7) + state = state xor (state shl 17) + else: + state += 0x9E3779B97F4A7C15'u64 + var z = state + z = (z xor (z shr 30)) * 0xBF58476D1CE4E5B9'u64 + z = (z xor (z shr 27)) * 0x94D049BB133111EB'u64 + return z xor (z shr 31) + state + +proc rngUnit(state: var uint64, cls: int): float64 = + ## Uniform in [0, 1) from the selected class. + float64(nextRng(state, cls) shr 11) / 9007199254740992.0 + +proc fireGate(e: EnemyState, p: Params, want: float64): float64 = + ## Cadence gate shared by all kernels: fire only every `fireCooldown` ticks. + if want <= 0.0 or p.fireCooldown <= 0: 0.0 + elif e.tick mod p.fireCooldown != 0: 0.0 + else: want + +# ── K1 ORBIT_LOCK — orbit with hysteresis direction lock ──────────────────── + +proc stepOrbitLock(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + let b = bearingTo(e.x, e.y, m.x, m.y) + let r = dist(e, m) + var desired: float64 + if r > p.range + p.hysteresis: + desired = b # too far: close in + elif r < p.range - p.hysteresis: + desired = wrap180(b + 180.0) # too close: back off + else: + desired = wrap180(b + 90.0 * p.dir) # tangential, latched direction + result.turnRate = clamp(wrap180(desired - e.direction), + -MaxTurnRate, MaxTurnRate) + result.targetSpeed = p.speed + result.fire = fireGate(e, p, 0.3) + +# ── K-spin ORBIT_BALLIST — SpinBot: constant spin at fixed speed ──────────── + +proc stepOrbitBallist(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + ## Sample: SpinBot (turn 10000, maxSpeed 5, forward 10000, fire(3) on scan). + result.turnRate = MaxTurnRate + result.targetSpeed = 5.0 + result.fire = fireGate(e, p, 3.0) + +# ── ZIGZAG — Crazy: long forward runs + periodic 180 flips ────────────────── + +proc stepZigzag(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + ## Sample: Crazy (forward 40000, turnRight 180, reverses on wall/ram). + result.targetSpeed = MaxForwardSpeed + result.fire = fireGate(e, p, 1.0) + if mem.phase == 0: + result.turnRate = 0.0 + inc mem.counter + if nearWall(e, p) or mem.counter >= p.zigzagTicks: + mem.phase = 1 + mem.startDir = e.direction + mem.counter = 0 + else: + result.turnRate = MaxTurnRate + if abs(wrap180(e.direction - mem.startDir)) >= 175.0: + mem.phase = 0 + mem.counter = 0 + +# ── K6 RAMMER — RamFire: approach the opponent and ram ────────────────────── + +proc stepRammer(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + ## Sample: RamFire (5 deg idle turn; on scan face target, forward(dist+5)). + let b = bearingTo(e.x, e.y, m.x, m.y) + let err = wrap180(b - e.direction) + result.turnRate = clamp(err, -MaxTurnRate, MaxTurnRate) + # `forward(dist+5)` in RamFire brakes as it closes, unlike Crazy's constant run. + result.targetSpeed = clamp(dist(e, m) / 50.0, 1.0, MaxForwardSpeed) + result.fire = fireGate(e, p, 3.0) + +# ── K5 CORNER_RUN — Corners: run to a corner and bounce ───────────────────── + +proc cornerXY(p: Params, idx: int): tuple[x, y: float64] = + case idx mod 4 + of 0: result = (0.0, 0.0) + of 1: result = (p.arenaW, 0.0) + of 2: result = (0.0, p.arenaH) + else: result = (p.arenaW, p.arenaH) + +proc stepCornerRun(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + ## Sample: Corners (run to a corner, then turn 90 and continue). + if mem.phase == 0 and mem.counter == 0: + mem.phase = p.corner # first use: honour the param slot + mem.counter = 1 + var target = cornerXY(p, mem.phase) + if hypot(target.x - e.x, target.y - e.y) < p.margin: + mem.phase = 3 - mem.phase # reached it: bounce to the opposite corner + target = cornerXY(p, mem.phase) + let b = bearingTo(e.x, e.y, target.x, target.y) + result.turnRate = clamp(wrap180(b - e.direction), -MaxTurnRate, MaxTurnRate) + result.targetSpeed = p.speed + result.fire = fireGate(e, p, 1.0) + +# ── K9 WALLCRAWL — Walls: align to a wall, crawl it in segments ───────────── + +proc normalHeading(wall: int): float64 = + case wall # heading pointing AT the wall + of 0: result = 180.0 # left + of 1: result = 0.0 # right + of 2: result = 270.0 # bottom + else: result = 90.0 # top + +proc alongHeading(wall: int, sgn: float64): float64 = + case wall + of 0, 1: result = (if sgn >= 0.0: 90.0 else: 270.0) # vertical walls + else: result = (if sgn >= 0.0: 0.0 else: 180.0) # horizontal walls + +proc stepWallCrawl(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + ## Sample: Walls (align to nearest wall, forward moveAmount, turnLeft 90 per + ## segment). `mem.phase` holds the current wall; `mem.latch` the crawl sign. + var wall = mem.phase + if wall < 0 or wall > 3: wall = 0 + let dists = [e.x, p.arenaW - e.x, e.y, p.arenaH - e.y] + var nearest = 0 + for i in 1 .. 3: + if dists[i] < dists[nearest]: nearest = i + var desired: float64 + if dists[nearest] > p.margin and abs(wrap180(normalHeading(nearest) - + e.direction)) < 90.0: + desired = normalHeading(nearest) # still approaching the wall + mem.phase = nearest + else: + wall = mem.phase + var travelled = hypot(e.x - mem.segX, e.y - mem.segY) + # First crawl tick from an unset segment start: anchor it. + if mem.segX == 0.0 and mem.segY == 0.0: + mem.segX = e.x; mem.segY = e.y + travelled = 0.0 + if travelled >= p.segmentLen: + mem.segX = e.x; mem.segY = e.y + mem.phase = (wall + 1) mod 4 + wall = mem.phase + desired = alongHeading(wall, mem.latch) + result.turnRate = clamp(wrap180(desired - e.direction), + -MaxTurnRate, MaxTurnRate) + result.targetSpeed = p.speed + result.fire = fireGate(e, p, 2.0) + +# ── K10 STATIC — TrackFire/Fire: stationary posture, gun-driven ──────────── + +proc stepStatic(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + ## Sample: TrackFire / Fire (sit still, turn gun, fire on alignment). + result.turnRate = 0.0 + result.targetSpeed = 0.0 + let b = bearingTo(e.x, e.y, m.x, m.y) + let aligned = abs(wrap180(b - e.direction)) < 10.0 + result.fire = fireGate(e, p, (if aligned: 3.0 else: 1.0)) + +# ── K7 RANDOM_WALK — pseudorandom turn/speed, classes A/B/C ───────────────── + +proc stepRandomWalkA(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + result.turnRate = (rngUnit(mem.rngState, 0) * 2.0 - 1.0) * MaxTurnRate + result.targetSpeed = (rngUnit(mem.rngState, 0) * 2.0 - 1.0) * MaxForwardSpeed + result.fire = fireGate(e, p, (if rngUnit(mem.rngState, 0) > 0.7: 1.0 else: 0.0)) + +proc stepRandomWalkB(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + result.turnRate = (rngUnit(mem.rngState, 1) * 2.0 - 1.0) * MaxTurnRate + result.targetSpeed = (rngUnit(mem.rngState, 1) * 2.0 - 1.0) * MaxForwardSpeed + result.fire = fireGate(e, p, (if rngUnit(mem.rngState, 1) > 0.7: 1.0 else: 0.0)) + +proc stepRandomWalkC(e: EnemyState, m: MyState, p: Params, + mem: var KernelMem): Intent = + result.turnRate = (rngUnit(mem.rngState, 2) * 2.0 - 1.0) * MaxTurnRate + result.targetSpeed = (rngUnit(mem.rngState, 2) * 2.0 - 1.0) * MaxForwardSpeed + result.fire = fireGate(e, p, (if rngUnit(mem.rngState, 2) > 0.7: 1.0 else: 0.0)) + +# ── registry ──────────────────────────────────────────────────────────────── + +proc allKernels*(): seq[Kernel] = + ## The M2 kernel set, in registry order. Hedge indexes match this order. + let d = defaultParams() + @[ + Kernel(name: "ORBIT_LOCK", step: stepOrbitLock, defaultParams: d), + Kernel(name: "ORBIT_BALLIST", step: stepOrbitBallist, defaultParams: d), + Kernel(name: "ZIGZAG", step: stepZigzag, defaultParams: d), + Kernel(name: "RAMMER", step: stepRammer, defaultParams: d), + Kernel(name: "CORNER_RUN", step: stepCornerRun, defaultParams: d), + Kernel(name: "WALLCRAWL", step: stepWallCrawl, defaultParams: d), + Kernel(name: "STATIC", step: stepStatic, defaultParams: d), + Kernel(name: "RANDOM_WALK_A", step: stepRandomWalkA, + defaultParams: block: (var q = d; q.rngClass = 0; q)), + Kernel(name: "RANDOM_WALK_B", step: stepRandomWalkB, + defaultParams: block: (var q = d; q.rngClass = 1; q)), + Kernel(name: "RANDOM_WALK_C", step: stepRandomWalkC, + defaultParams: block: (var q = d; q.rngClass = 2; q)), + ] + +proc kernelNames*(kernels: seq[Kernel]): seq[string] = + for k in kernels: result.add k.name diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/hedge.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/hedge.nim new file mode 100644 index 0000000..86da42a --- /dev/null +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/hedge.nim @@ -0,0 +1,108 @@ +## CHIMERA Hedge / EWA posterior over kernels. +## +## Source of truth: `docs/chimera-spec.md` §7. A weighted mixture (never argmax) +## updated in the full-information setting: every non-censored tick yields a +## realized intent, so we update every kernel with its loss. +## +## Two regularizers keep a wrong-but-resurrected kernel recoverable: +## * exponential forgetting `(1 - 1/τ)`, default `τ = 200` ticks; +## * Fixed-Share mixing toward the uniform distribution with coefficient `α`, +## which gives a strict mass floor `w_i ≥ α·m_i`. +## The spec writes the update as +## `w_i ← w_i·exp(-η·loss_i)·(1-1/τ) + α·(m_i - w_i)`; +## we implement the standard, numerically-safe ordering of the same two terms +## ((1-α) of the forgotten weight + α·m_i) so weights can never go negative and +## the floor is exact. `tests/test_hedge.nim` pins the behaviour. +## +## Loss-scale heuristic: raw per-tick losses are O(1) (normalized squared error +## plus a Bernoulli term). `lossScale` maps them into the spec's ~0.01–0.1 +## band before `η`, so a single `η` stays stable across kernels. + +import std/[math, algorithm] + +type + HedgeConfig* = object + eta*: float64 = 4.0 ## learning rate + tau*: float64 = 200.0 ## forgetting horizon, ticks + alpha*: float64 = 0.01 ## Fixed-Share mixing coefficient (mass floor) + lossScale*: float64 = 0.1 ## raw-loss -> spec ~0.01-0.1 band multiplier + + Hedge* = object + names*: seq[string] + weights*: seq[float64] + cfg*: HedgeConfig + revision*: int ## bumped on every mutation (revision-safe API) + +proc initHedge*(names: seq[string], cfg = HedgeConfig()): Hedge = + ## Uniform prior over the registered kernels. + result.names = names + result.weights = newSeq[float64](names.len) + for i in 0 ..< names.len: result.weights[i] = 1.0 / float64(names.len) + result.cfg = cfg + +proc normalize*(h: var Hedge) = + var s = 0.0 + for w in h.weights: s += w + if s > 0.0: + for i in 0 ..< h.weights.len: h.weights[i] /= s + +proc setWeights*(h: var Hedge, w: openArray[float64]) = + ## Revision-safe restore: length-checked, clamped non-negative, renormalized. + doAssert w.len == h.weights.len, "weight vector length mismatch" + var s = 0.0 + for x in w: + doAssert x >= 0.0, "negative weight" + s += x + doAssert s > 0.0, "zero-mass weight vector" + for i in 0 ..< h.weights.len: h.weights[i] = w[i] / s + inc h.revision + +proc clone*(h: Hedge): Hedge = + ## Deep copy for revision-safe experimentation. + result.names = h.names + result.weights = h.weights + result.cfg = h.cfg + result.revision = h.revision + +proc update*(h: var Hedge, rawLosses: openArray[float64]) = + ## One Hedge step. `rawLosses[i]` is the loss of kernel `i` on this tick. + ## Censored ticks must be skipped by the caller (spec §4.4) — this proc + ## assumes a full-information observation. + doAssert rawLosses.len == h.weights.len, "loss vector length mismatch" + let n = h.weights.len + let m = 1.0 / float64(n) # Fixed-Share target: uniform + let keep = 1.0 - 1.0 / h.cfg.tau # exponential forgetting + var w = newSeq[float64](n) + for i in 0 ..< n: + let forgotten = h.weights[i] * exp(-h.cfg.eta * h.cfg.lossScale * + rawLosses[i]) * keep + w[i] = (1.0 - h.cfg.alpha) * forgotten + h.cfg.alpha * m + h.weights = w + h.normalize() + inc h.revision + +proc posterior*(h: Hedge, name: string): float64 = + ## Weight of one kernel by name (0 when unknown). + for i in 0 ..< h.names.len: + if h.names[i] == name: return h.weights[i] + 0.0 + +proc topK*(h: Hedge, k: int): seq[tuple[name: string, weight: float64]] = + ## Kernels sorted by descending weight. + var idx = newSeq[int](h.names.len) + for i in 0 ..< idx.len: idx[i] = i + idx.sort(proc(a, b: int): int = cmp(h.weights[b], h.weights[a])) + for i in 0 ..< min(k, idx.len): + result.add (h.names[idx[i]], h.weights[idx[i]]) + +proc entropy*(h: Hedge): float64 = + ## Shannon entropy `-Σ w ln w` (nats); exact closed form, see tests. + for w in h.weights: + if w > 0.0: result -= w * ln(w) + +proc argmaxName*(h: Hedge): string = + ## Highest-weight kernel (diagnostics only — prediction uses the mixture). + var best = 0 + for i in 1 ..< h.weights.len: + if h.weights[i] > h.weights[best]: best = i + if h.names.len == 0: "" else: h.names[best] diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/ledger.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/ledger.nim new file mode 100644 index 0000000..072da72 --- /dev/null +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/ledger.nim @@ -0,0 +1,148 @@ +## CHIMERA intent ledger — the observable scan stream in, per-tick *intent +## intervals* out. Ambiguous ticks are marked CENSORED, never guessed. +## +## Source of truth: `docs/chimera-spec.md` §4. The ledger never imputes: a tick +## whose intent cannot be bounded is excluded from Hedge updates and counted in +## the censoring rate (spec §4.4, goal G3). +## +## Every inference is an interval because the wire only exposes realized state: +## the server clamps the body turn (`10 - 0.75|v|`, spec §4.1) and updates speed +## through the stateful `stepSpeed` rule (spec §4.2), so a realized value bounds +## the command rather than naming it. + +import std/math +import ./physics + +const + IntervalEps* = 1e-6 ## wrap/quantization slack for interval construction + +type + Scan* = object + ## One `ScannedBotEvent`-worth of enemy state. + tick*: int + x*: float64 + y*: float64 + direction*: float64 + speed*: float64 + energy*: float64 + + Interval* = object + lo*: float64 + hi*: float64 + + LedgerObs* = object + ## One tick's inferred intent. `*Known` is false when the channel was not + ## observed (or was censored); the interval is then meaningless. + tick*: int + turnRate*: Interval + turnKnown*: bool + targetSpeed*: Interval + targetKnown*: bool + fire*: float64 ## observed fire power, or 0 when `fireKnown` is false + fireKnown*: bool + censored*: bool + +proc contains*(iv: Interval, v: float64): bool = + ## True when `v` lies in the interval (with slack). + v >= iv.lo - IntervalEps and v <= iv.hi + IntervalEps + +proc width*(iv: Interval): float64 = iv.hi - iv.lo + +proc turnRateInterval*(prev, cur: Scan): LedgerObs = + ## Spec §4.1. `Δdir` between adjacent scans bounds the realized turn rate by + ## `[Δdir - ε, Δdir + ε] ∩ [-(10-0.75|v|), +(10-0.75|v|)]`, the cap computed at + ## the speed the turn was applied with (the server limits the turn AFTER the + ## speed update, so `cur.speed` is the right one). A scan gap ≥ 2 is CENSORED. + result.tick = cur.tick + if cur.tick - prev.tick != 1: + result.censored = true + return + let delta = wrap180(cur.direction - prev.direction) + let cap = maxTurnRate(cur.speed) + result.turnRate = Interval(lo: max(-cap, delta - IntervalEps), + hi: min(cap, delta + IntervalEps)) + result.turnKnown = true + +proc invertStepSpeed*(currentSpeed, newSpeed: float64): tuple[iv: Interval, ok: bool] = + ## Spec §4.2. Exact preimage of `stepSpeed(currentSpeed, ·)` at `newSpeed`: + ## the set of target speeds consistent with the observed realized speed. + ## Returns the convex hull; `ok = false` means the observation is impossible + ## (the tick must be censored). + var v = currentSpeed + var n = newSpeed + var negate = false + if v < 0.0: + v = -v; n = -n; negate = true # odd symmetry of stepSpeed + + var lo = Inf + var hi = -Inf + template add(a, b: float64) = + lo = min(lo, a); hi = max(hi, b) + + if abs(v) < IntervalEps: + # stepSpeed(0, t) = clamp(t, -1, 1) + if abs(n) <= 1.0 + IntervalEps: + if n >= 1.0 - IntervalEps: + add(1.0, MaxForwardSpeed) + elif n <= -1.0 + IntervalEps: + add(MaxBackwardSpeed, -1.0) + else: + add(n, n) + else: + let crossVal = v / 2.0 - 1.0 + if abs(n - crossVal) <= IntervalEps: + # crossing-zero branch: every target with the opposite sign gives crossVal + add(MaxBackwardSpeed, 0.0) + if abs(n) <= IntervalEps: + add(0.0, 0.0) + # same-sign branch: n = clamp(t, v-2, min(v+1, 8)) for t > 0 + let floorV = v - 2.0 + let ceilV = min(v + 1.0, MaxForwardSpeed) + if n >= max(0.0, floorV) - IntervalEps and n <= ceilV + IntervalEps: + if abs(n - ceilV) <= IntervalEps: + add(ceilV, MaxForwardSpeed) + elif abs(n - floorV) <= IntervalEps and floorV > 0.0: + add(0.0, floorV) + else: + add(n, n) + + if lo > hi: + return (Interval(lo: 0.0, hi: 0.0), false) + if negate: + return (Interval(lo: -hi, hi: -lo), true) + (Interval(lo: lo, hi: hi), true) + +proc targetSpeedInterval*(prevSpeed, newSpeed: float64): LedgerObs = + ## Spec §4.2 wrapper: interval of target speeds consistent with the realized + ## step, or CENSORED when the step is impossible. + let inv = invertStepSpeed(prevSpeed, newSpeed) + result.turnRate = Interval(lo: 0.0, hi: 0.0) + if inv.ok: + result.targetSpeed = inv.iv + result.targetKnown = true + else: + result.censored = true + +proc fireFromEnergyDrop*(prevEnergy, curEnergy, knownDamage: float64): LedgerObs = + ## Spec §4.3. Firing spends `power` energy at fire time. With no known incoming + ## damage the drop names the fire power directly; with known damage the drop is + ## ambiguous and the tick is CENSORED. + let drop = prevEnergy - curEnergy + if drop <= IntervalEps: + return # no drop: fireKnown stays false + if knownDamage > IntervalEps: + result.censored = true + return + if drop < MinFirepower - IntervalEps or drop > MaxFirepower + IntervalEps: + result.censored = true + return + result.fire = drop + result.fireKnown = true + +proc censorRate*(obs: openArray[LedgerObs]): float64 = + ## Spec §4.4 / G3: censored / total ticks. + if obs.len == 0: return 0.0 + var c = 0 + for o in obs: + if o.censored: inc c + c / obs.len diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/oracle.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/oracle.nim new file mode 100644 index 0000000..3fcf9d9 --- /dev/null +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/oracle.nim @@ -0,0 +1,140 @@ +## CHIMERA oracle harness — G1 machinery (spec §12 Tier C, G1). +## +## G1 asks a narrow question: is the *inference layer* correct? Feed the Hedge +## posterior the exact intent stream a known kernel emits over a deterministic +## synthetic arena (no sensor error), and the weight on that kernel must reach +## `≥ 0.9` within `T*` ticks. A G1 failure indicts the implementation, not the +## idea, so the harness reports identification ticks per kernel rather than +## hiding a miss behind a threshold. +## +## The oracle reuses the same `physics.nim` mirror the twin will use, so a +## ledger/hedge bug shows up here before any live battle. + +import std/[math] +import ./physics, ./ledger, ./dsl, ./hedge + +type + Env* = object + arenaW*, arenaH*: float64 + myX*, myY*: float64 + startX*, startY*, startDir*: float64 + + OracleStream* = object + scans*: seq[Scan] + intents*: seq[Intent] + + G1Result* = object + kernel*: string + idTick*: int ## tick posterior first reached threshold, -1 if never + finalPosterior*: float64 + censorRate*: float64 + ticks*: int + +proc defaultEnv*(): Env = + Env(arenaW: 800.0, arenaH: 600.0, myX: 620.0, myY: 300.0, + startX: 180.0, startY: 300.0, startDir: 0.0) + +proc toEnemyState(s: Scan): EnemyState = + EnemyState(tick: s.tick, x: s.x, y: s.y, direction: s.direction, + speed: s.speed, energy: s.energy) + +proc generateOracle*(kernel: Kernel, params: Params, env: Env, + ticks: int): OracleStream = + ## Roll `kernel` forward over the synthetic arena, emitting one scan at the + ## start of every tick and the intent it commands that tick. + var e = EnemyState(tick: 0, x: env.startX, y: env.startY, + direction: env.startDir, speed: 0.0, energy: 100.0) + let m = MyState(x: env.myX, y: env.myY) + var mem = defaultMemory(params) + for t in 0 ..< ticks: + result.scans.add Scan(tick: e.tick, x: e.x, y: e.y, direction: e.direction, + speed: e.speed, energy: e.energy) + let intent = kernel.step(e, m, params, mem) + result.intents.add intent + # Server tick order: speed update, then turn limited by the new speed. + let newSpeed = stepSpeed(e.speed, intent.targetSpeed) + let turn = limitTurnRate(intent.turnRate, newSpeed) + e.direction = wrap180(e.direction + turn) + e.speed = newSpeed + e.x += e.speed * cos(degToRad(e.direction)) + e.y += e.speed * sin(degToRad(e.direction)) + e.x = clamp(e.x, 0.0, env.arenaW) + e.y = clamp(e.y, 0.0, env.arenaH) + if intent.fire > 0.0: e.energy -= intent.fire + e.tick = t + 1 + +proc combineObs*(prev, cur: Scan): LedgerObs = + ## Fold the three ledger channels of one tick into a single observation. + result = turnRateInterval(prev, cur) + let sp = targetSpeedInterval(prev.speed, cur.speed) + if sp.targetKnown: + result.targetSpeed = sp.targetSpeed + result.targetKnown = true + let fire = fireFromEnergyDrop(prev.energy, cur.energy, 0.0) + if fire.fireKnown: + result.fire = fire.fire + result.fireKnown = true + if sp.censored or fire.censored: + result.censored = true + +proc intentLoss*(pred: Intent, obs: LedgerObs, speed: float64): float64 = + ## Raw per-tick Hedge loss (spec §7): normalized squared turn error (on the + ## *realized* turn the server would apply), normalized target-speed interval + ## error, and a fire Bernoulli term. Censored ticks score 0 (caller skips). + if obs.censored: return 0.0 + if obs.turnKnown: + let realized = limitTurnRate(pred.turnRate, speed) + var err = 0.0 + if realized < obs.turnRate.lo: err = obs.turnRate.lo - realized + elif realized > obs.turnRate.hi: err = realized - obs.turnRate.hi + result += (err / MaxTurnRate) ^ 2 + if obs.targetKnown: + var err = 0.0 + if pred.targetSpeed < obs.targetSpeed.lo: + err = obs.targetSpeed.lo - pred.targetSpeed + elif pred.targetSpeed > obs.targetSpeed.hi: + err = pred.targetSpeed - obs.targetSpeed.hi + result += (err / MaxForwardSpeed) ^ 2 + if obs.fireKnown: + let pf = (if pred.fire > 0.0: 1.0 else: 0.0) + let obsFire = (if obs.fire > 0.0: 1.0 else: 0.0) + result += (pf - obsFire) ^ 2 + +proc evaluate*(stream: OracleStream, kernels: seq[Kernel], targetIdx: int, + env: Env, threshold = 0.9, + cfg = HedgeConfig()): G1Result = + ## Replay the stream through the ledger + Hedge and report when the target + ## kernel's posterior crosses `threshold`. + let my = MyState(x: env.myX, y: env.myY) + var h = initHedge(kernelNames(kernels), cfg) + var mems = newSeq[KernelMem](kernels.len) + for i in 0 ..< kernels.len: + mems[i] = defaultMemory(kernels[i].defaultParams) + result.kernel = kernels[targetIdx].name + result.ticks = stream.scans.len + result.idTick = -1 + var obsAll: seq[LedgerObs] + var preds = newSeq[Intent](kernels.len) + var losses = newSeq[float64](kernels.len) + for t in 0 ..< stream.scans.len - 1: + let e = toEnemyState(stream.scans[t]) + for i in 0 ..< kernels.len: + preds[i] = kernels[i].step(e, my, kernels[i].defaultParams, mems[i]) + let obs = combineObs(stream.scans[t], stream.scans[t + 1]) + obsAll.add obs + if not obs.censored: + for i in 0 ..< kernels.len: + losses[i] = intentLoss(preds[i], obs, stream.scans[t + 1].speed) + h.update(losses) + if result.idTick < 0 and h.posterior(result.kernel) >= threshold: + result.idTick = t + 1 + result.finalPosterior = h.posterior(result.kernel) + result.censorRate = censorRate(obsAll) + +proc runG1*(kernels: seq[Kernel], targetIdx: int, env = defaultEnv(), + ticks = 300, threshold = 0.9, + cfg = HedgeConfig()): G1Result = + ## Convenience: generate the oracle stream for one kernel and evaluate it. + let params = kernels[targetIdx].defaultParams + let stream = generateOracle(kernels[targetIdx], params, env, ticks) + evaluate(stream, kernels, targetIdx, env, threshold, cfg) diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/physics.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/physics.nim new file mode 100644 index 0000000..67df38b --- /dev/null +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/physics.nim @@ -0,0 +1,90 @@ +## CHIMERA physics mirror — pure functions, no state, no I/O. +## +## A byte-faithful port of the Tank Royale server's movement maths. Source of +## truth: `robocode-tankroyale/server`, `rules/math.kt` (constants in +## `rules/rules.kt`). This mirror is the twin's ground truth: a mismatch silently +## poisons every downstream prediction, so every proc carries the source rule and +## is pinned by `tests/test_physics.nim`. +## +## ANGLES: 0 deg = east, counter-clockwise positive (Tank Royale standard). + +import std/math + +const + MaxForwardSpeed* = 8.0 ## rules.kt MAX_FORWARD_SPEED + MaxBackwardSpeed* = -8.0 ## rules.kt MAX_BACKWARD_SPEED + Acceleration* = 1.0 ## rules.kt ACCELERATION + Deceleration* = -2.0 ## rules.kt DECELERATION + MaxTurnRate* = 10.0 ## rules.kt MAX_TURN_RATE + MinFirepower* = 0.1 ## rules.kt MIN_FIREPOWER + MaxFirepower* = 3.0 ## rules.kt MAX_FIREPOWER + +proc clampSpeed*(v: float64): float64 = + ## rules/math.kt clampSpeed: clamp to [-8, +8]. + clamp(v, MaxBackwardSpeed, MaxForwardSpeed) + +proc clampFirepower*(p: float64): float64 = + ## rules/math.kt clampFirepower: clamp to [0.1, 3.0]. + clamp(p, MinFirepower, MaxFirepower) + +proc stepSpeed*(currentSpeed, targetSpeed: float64): float64 = + ## rules/math.kt calcNewBotSpeed, ported case for case. + ## + ## The update is asymmetric: accelerate by at most +1/tick, decelerate by at + ## most -2/tick, and a same-sign target is approached until it is met. When the + ## target crosses the sign of the current speed the server assigns the + ## crossing-zero value `(1 - currentSpeed/2) * -1` directly (not additively). + ## Negative current speeds are handled by odd symmetry. + if currentSpeed < 0.0: + return -stepSpeed(-currentSpeed, -targetSpeed) # odd symmetry + if currentSpeed > 0.0: + if sgn(currentSpeed) == sgn(targetSpeed): + let diff = targetSpeed - currentSpeed + if diff >= 0.0: + return min(currentSpeed + min(diff, Acceleration), MaxForwardSpeed) + else: + return max(currentSpeed + max(diff, Deceleration), MaxBackwardSpeed) + else: # crossing the speed of 0 + if targetSpeed == 0.0: + return 0.0 + let decelerationTime = currentSpeed / -Deceleration # = currentSpeed / 2 + return (1.0 - decelerationTime) * -Acceleration + else: # currentSpeed == 0 + let diff = targetSpeed + let acceleration = min(abs(diff), Acceleration) + if diff >= 0.0: + return min(currentSpeed + acceleration, MaxForwardSpeed) + else: + return max(currentSpeed - acceleration, MaxBackwardSpeed) + +proc maxTurnRate*(speed: float64): float64 = + ## rules/math.kt calcMaxTurnRate: `10 - 0.75 * |clampSpeed(speed)|`. + MaxTurnRate - 0.75 * abs(clampSpeed(speed)) + +proc limitTurnRate*(turnRate, speed: float64): float64 = + ## rules/math.kt limitTurnRate: clamp a commanded body turn to the speed cap. + clamp(turnRate, -maxTurnRate(speed), maxTurnRate(speed)) + +proc bulletSpeed*(firepower: float64): float64 = + ## rules/math.kt calcBulletSpeed: `20 - 3 * clampFirepower(p)`. + 20.0 - 3.0 * clampFirepower(firepower) + +proc bulletDamage*(firepower: float64): float64 = + ## rules/math.kt calcBulletDamage: `4*clamp(p)` plus `2*(p-1)` when `p > 1`. + result = 4.0 * clampFirepower(firepower) + if firepower > 1.0: + result += 2.0 * (firepower - 1.0) + +proc gunHeat*(firepower: float64): float64 = + ## rules/math.kt calcGunHeat: `1 + clampFirepower(p) / 5`. + 1.0 + clampFirepower(firepower) / 5.0 + +proc wrap180*(deg: float64): float64 = + ## Shortest signed angle in (-180, 180]. + result = deg mod 360.0 + if result <= -180.0: result += 360.0 + elif result > 180.0: result -= 360.0 + +proc bearingTo*(fromX, fromY, toX, toY: float64): float64 = + ## Compass-style bearing (deg, CCW from +x) from one point to another. + arctan2(toY - fromY, toX - fromX) * 180.0 / PI diff --git a/ChimeraBot_garage/tests/test_hedge.nim b/ChimeraBot_garage/tests/test_hedge.nim new file mode 100644 index 0000000..aa0475d --- /dev/null +++ b/ChimeraBot_garage/tests/test_hedge.nim @@ -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) diff --git a/ChimeraBot_garage/tests/test_ledger.nim b/ChimeraBot_garage/tests/test_ledger.nim new file mode 100644 index 0000000..49cbf70 --- /dev/null +++ b/ChimeraBot_garage/tests/test_ledger.nim @@ -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) diff --git a/ChimeraBot_garage/tests/test_oracle_g1.nim b/ChimeraBot_garage/tests/test_oracle_g1.nim new file mode 100644 index 0000000..086c228 --- /dev/null +++ b/ChimeraBot_garage/tests/test_oracle_g1.nim @@ -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) diff --git a/ChimeraBot_garage/tests/test_physics.nim b/ChimeraBot_garage/tests/test_physics.nim new file mode 100644 index 0000000..3a468ae --- /dev/null +++ b/ChimeraBot_garage/tests/test_physics.nim @@ -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)