ChimeraBot_garage: CHIMERA debug overlay (-d:chimeraDebug, observation-only)
This commit is contained in:
@@ -23,6 +23,8 @@ 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.
|
||||
|
||||
Debug overlay: run server with `--debug-mode` and bot with `./ChimeraBot.sh -d:chimeraDebug`.
|
||||
|
||||
## CHIMERA modules (M3.5 + M4)
|
||||
|
||||
`src/ChimeraBot/chimera/` holds the CHIMERA libraries —
|
||||
|
||||
@@ -37,6 +37,8 @@ import ChimeraBot/chimera/dsl
|
||||
import ChimeraBot/chimera/probes
|
||||
import ChimeraBot/chimera/physics
|
||||
import ChimeraBot/chimera/influence
|
||||
when defined(chimeraDebug):
|
||||
import ChimeraBot/chimera/debugdraw
|
||||
|
||||
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
|
||||
## only what it scans, so this is a cap, not a limit
|
||||
@@ -278,6 +280,12 @@ method run*(bot: ChimeraBot) =
|
||||
setAdjustRadarForBodyTurn(true) # radar ignores body rotation
|
||||
setAdjustRadarForGunTurn(true) # radar ignores turret rotation too
|
||||
initRadar() # once: radar + scan turn BLACK = programmed
|
||||
# Debug-overlay probe flash: persists ProbeFlashTicks after a probe triggers.
|
||||
# Declared only under the debug define and never read by a command path.
|
||||
when defined(chimeraDebug):
|
||||
var probeFlash = 0
|
||||
var probeFlashLabel = ""
|
||||
var overlayTicks = 0
|
||||
while isRunning():
|
||||
# One radar command and one movement command per tick, unconditionally,
|
||||
# BEFORE go() — so both are part of this tick's intent.
|
||||
@@ -322,6 +330,9 @@ method run*(bot: ChimeraBot) =
|
||||
roundLimit: RoundSoftLimit)
|
||||
let decision = bot.probes.consider(porigin, ctx)
|
||||
if decision.trigger:
|
||||
when defined(chimeraDebug):
|
||||
probeFlash = ProbeFlashTicks
|
||||
probeFlashLabel = $decision.candidate.kind
|
||||
bot.observer.writeProbeEvent(bot.tick, $decision.candidate.kind,
|
||||
decision.gate.reason, decision.entropyBefore,
|
||||
decision.entropyAfter, decision.candidate.turnRate,
|
||||
@@ -338,6 +349,41 @@ method run*(bot: ChimeraBot) =
|
||||
setTurnRate(cmdTurn)
|
||||
if not probeFired:
|
||||
bot.computeGun() # gun intent, also before go()
|
||||
when defined(chimeraDebug):
|
||||
# OBSERVATION-ONLY overlay: build the primitive list from observer state
|
||||
# (pure) and hand it to the API's global SVG buffer. Ordering is the same
|
||||
# as every other command: drawn here, before go(), so it travels with
|
||||
# THIS tick's intent. No command setter is called, so the command path is
|
||||
# byte-identical with or without the overlay.
|
||||
var snap = OverlayInput(selfX: getX(), selfY: getY())
|
||||
if bot.observer.hasCurrent:
|
||||
let top = bot.observer.topKernel()
|
||||
snap.kernelName = top.name
|
||||
snap.kernelP = top.weight
|
||||
snap.entropy = bot.observer.entropy()
|
||||
let (ex, ey) = bot.observer.lastScanPos()
|
||||
snap.enemyX = ex; snap.enemyY = ey; snap.haveEnemy = true
|
||||
let fp = bot.observer.fusedPrediction()
|
||||
if fp.horizon > 0 and fp.points.len > 0:
|
||||
snap.pFire5 = fp.fireWithin
|
||||
snap.predX = fp.points[^1].x
|
||||
snap.predY = fp.points[^1].y
|
||||
snap.havePred = true
|
||||
snap.scanGap = bot.tick - bot.observer.scanTick()
|
||||
snap.fresh = bot.observer.scanTick() == bot.tick - 1
|
||||
snap.censored = bot.observer.lastCensored()
|
||||
if probeFlash > 0:
|
||||
snap.probeFlash = true
|
||||
snap.probeLabel = probeFlashLabel
|
||||
dec probeFlash
|
||||
let prims = buildOverlay(snap)
|
||||
renderOverlay(prims)
|
||||
inc overlayTicks
|
||||
# Observation-only runtime evidence that the overlay drew (stdout only,
|
||||
# no command state touched). Quiet apart from the first and every 500th tick.
|
||||
if overlayTicks == 1 or overlayTicks mod 500 == 0:
|
||||
echo "[chimera-debug] overlay tick=", bot.tick, " prims=", prims.len,
|
||||
" svg=", svgOutput().len
|
||||
go()
|
||||
bot.observer.writeTick(bot.tick) # observation telemetry, after go()
|
||||
inc bot.tick
|
||||
|
||||
@@ -266,3 +266,6 @@ task test, "Run unit tests":
|
||||
exec "nim c -r --hints:off ../tests/test_fusion.nim"
|
||||
exec "nim c -r --hints:off ../tests/test_influence.nim"
|
||||
exec "nim c -r --hints:off ../tests/test_identifiability.nim"
|
||||
# Debug overlay: compiled WITH -d:chimeraDebug so the drawing path is the real
|
||||
# one; the test asserts the command intent is identical with/without it.
|
||||
exec "nim c -r --hints:off -d:chimeraDebug ../tests/test_debugdraw.nim"
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
## CHIMERA debug overlay — observation-only SVG drawing.
|
||||
##
|
||||
## The bot API has **no** `setDebugGraphics` object to hand around. Debug
|
||||
## graphics in `robocode_tankroyale_botapi` 1.0.7 are drawn with module-global
|
||||
## procs that append to an internal SVG buffer:
|
||||
##
|
||||
## setStrokeColor / setFillColor / setStrokeWidth / setFont (style)
|
||||
## drawLine, drawCircle, fillCircle, drawText, drawRectangle ... (geometry)
|
||||
##
|
||||
## `go()` serialises that buffer into `BotIntent.debugGraphics` via
|
||||
## `graphics.svgOutput()` and then `clearGraphics()`s it, so anything drawn
|
||||
## before `go()` reaches the viewer for THIS tick and costs nothing after.
|
||||
##
|
||||
## Everything here is OBSERVATION-ONLY:
|
||||
## * `buildOverlay` is a PURE function of a plain snapshot — no API state, no
|
||||
## clock, no RNG — so it is deterministic and directly unit-testable;
|
||||
## * `renderOverlay` maps the primitives to the drawing procs above and never
|
||||
## touches command state (target speed, turn rates, fire), so the command
|
||||
## path is byte-identical with the overlay on or off (pinned by
|
||||
## `tests/test_debugdraw.nim`).
|
||||
##
|
||||
## Cost gate: `renderOverlay` compiles to an empty stub unless `-d:chimeraDebug`
|
||||
## is set, and `ChimeraBot.nim` does not even build the primitive list without
|
||||
## the define. Budget: `MaxDebugPrims` primitives per tick.
|
||||
|
||||
import std/[math, strutils]
|
||||
import robocode_tankroyale_botapi
|
||||
|
||||
const
|
||||
OverlayEnabled* = defined(chimeraDebug)
|
||||
MaxDebugPrims* = 10 ## hard per-tick budget (~10 requested)
|
||||
ProbeFlashTicks* = 5 ## how long a probe marker persists
|
||||
|
||||
type
|
||||
DKind* = enum dkText, dkLine, dkCircle, dkDot
|
||||
|
||||
DebugPrim* = object
|
||||
## One drawable primitive. `rgba` packs 0xRRGGBBAA, the API Color layout.
|
||||
kind*: DKind
|
||||
x*, y*: float
|
||||
x2*, y2*: float
|
||||
r*: float
|
||||
text*: string
|
||||
rgba*: uint32
|
||||
|
||||
OverlayInput* = object
|
||||
## Plain snapshot the bot assembles from the observer; the builder reads
|
||||
## nothing else.
|
||||
selfX*, selfY*: float
|
||||
kernelName*: string
|
||||
kernelP*: float
|
||||
entropy*: float
|
||||
pFire5*: float
|
||||
enemyX*, enemyY*: float
|
||||
haveEnemy*: bool
|
||||
predX*, predY*: float
|
||||
havePred*: bool
|
||||
fresh*: bool
|
||||
censored*: bool
|
||||
scanGap*: int
|
||||
probeLabel*: string
|
||||
probeFlash*: bool
|
||||
|
||||
# Colours chosen distinct from tfilDebug's palette (which uses red bullets,
|
||||
# #FF8800 auras, cyan enemies, green safe tiles): cyan identity, red fire,
|
||||
# yellow probes, grey scan-health, spring-green counterfactual.
|
||||
const
|
||||
ColIdentity = 0x00FFFFFF'u32
|
||||
ColProbe = 0xFFFF00FF'u32
|
||||
ColScan = 0x808080FF'u32
|
||||
ColPred = 0x00FF88FF'u32
|
||||
|
||||
proc fireRgba(p: float): uint32 =
|
||||
## Fire-circle colour ramps toward full red as P rises; alpha rises too.
|
||||
let t = clamp(p, 0.0, 1.0)
|
||||
let g = uint32(200.0 * (1.0 - t))
|
||||
let a = uint32(90.0 + 150.0 * t)
|
||||
(0xFF'u32 shl 24) or (g shl 16) or a
|
||||
|
||||
proc buildOverlay*(inp: OverlayInput): seq[DebugPrim] =
|
||||
## Pure, deterministic primitive builder. Fixed order: reruns on the same
|
||||
## input are byte-identical (pinned by test_debugdraw).
|
||||
if inp.kernelName.len > 0:
|
||||
# (a) IDENTITY BLOCK — kernel + top-1 posterior + entropy, then P(fire5).
|
||||
result.add DebugPrim(kind: dkText,
|
||||
text: inp.kernelName & " " & $int(inp.kernelP * 100.0 + 0.5) &
|
||||
"% H=" & formatFloat(inp.entropy, ffDecimal, 2),
|
||||
x: inp.selfX + 20.0, y: inp.selfY + 34.0, rgba: ColIdentity)
|
||||
result.add DebugPrim(kind: dkText,
|
||||
text: "P(fire5)=" & $int(clamp(inp.pFire5, 0.0, 1.0) * 100.0 + 0.5) & "%",
|
||||
x: inp.selfX + 20.0, y: inp.selfY + 20.0, rgba: ColIdentity)
|
||||
if inp.haveEnemy:
|
||||
# (b) FIRE PREDICTION — radius/opacity/colour encode fused P(fire within 5).
|
||||
result.add DebugPrim(kind: dkCircle, x: inp.enemyX, y: inp.enemyY,
|
||||
r: 20.0 + 60.0 * clamp(inp.pFire5, 0.0, 1.0),
|
||||
rgba: fireRgba(inp.pFire5))
|
||||
if inp.fresh and not inp.censored and inp.havePred and inp.haveEnemy:
|
||||
# (c) COUNTERFACTUAL — enemy now -> fused 5-tick predicted position.
|
||||
result.add DebugPrim(kind: dkLine, x: inp.enemyX, y: inp.enemyY,
|
||||
x2: inp.predX, y2: inp.predY, rgba: ColPred)
|
||||
result.add DebugPrim(kind: dkDot, x: inp.predX, y: inp.predY, r: 6.0,
|
||||
rgba: (ColPred and 0xFFFFFF00'u32) or 0x80'u32)
|
||||
if inp.probeFlash and inp.probeLabel.len > 0:
|
||||
# (d) PROBE MARKER — type label + flash near our bot (persists ~5 ticks).
|
||||
result.add DebugPrim(kind: dkText, text: "probe:" & inp.probeLabel,
|
||||
x: inp.selfX - 40.0, y: inp.selfY + 48.0, rgba: ColProbe)
|
||||
result.add DebugPrim(kind: dkDot, x: inp.selfX, y: inp.selfY, r: 10.0,
|
||||
rgba: ColProbe)
|
||||
if inp.scanGap > 1 or inp.censored:
|
||||
# (e) SCAN HEALTH — rare grey tick when the stream is not clean.
|
||||
result.add DebugPrim(kind: dkDot, x: inp.selfX - 18.0, y: inp.selfY + 48.0,
|
||||
r: 4.0, rgba: ColScan)
|
||||
if result.len > MaxDebugPrims:
|
||||
result.setLen(MaxDebugPrims)
|
||||
|
||||
proc renderOverlay*(prims: openArray[DebugPrim]) =
|
||||
## Map primitives to the API's global drawing procs. `Color` shares the
|
||||
## 0xRRGGBBAA packing, so `Color(rgba)` is exact.
|
||||
when defined(chimeraDebug):
|
||||
for p in prims:
|
||||
let c = Color(p.rgba)
|
||||
case p.kind
|
||||
of dkText:
|
||||
setFillColor(c)
|
||||
setFont("Arial", 11.0)
|
||||
drawText(p.text, p.x, p.y)
|
||||
of dkLine:
|
||||
setStrokeColor(c)
|
||||
setStrokeWidth(1.5)
|
||||
drawLine(p.x, p.y, p.x2, p.y2)
|
||||
of dkCircle:
|
||||
setStrokeColor(c)
|
||||
setStrokeWidth(1.5)
|
||||
drawCircle(p.x, p.y, p.r)
|
||||
of dkDot:
|
||||
setFillColor(c)
|
||||
fillCircle(p.x, p.y, p.r)
|
||||
else:
|
||||
discard
|
||||
@@ -373,6 +373,17 @@ proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights()
|
||||
proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma
|
||||
proc fusionSamples*(o: Observer): int = o.fusion.lossN
|
||||
|
||||
# ── debug-overlay accessors (observation-only; read-only) ───────────────────
|
||||
# These exist purely for the `-d:chimeraDebug` overlay in debugdraw.nim. They
|
||||
# expose already-computed observer state and never issue a command.
|
||||
proc topKernel*(o: Observer): tuple[name: string, weight: float64] =
|
||||
let t = o.hedge.topK(1)
|
||||
if t.len > 0: t[0] else: (name: "", weight: 0.0)
|
||||
|
||||
proc lastScanPos*(o: Observer): tuple[x, y: float64] = (o.cur.x, o.cur.y)
|
||||
proc scanTick*(o: Observer): int = o.scanTick
|
||||
proc lastCensored*(o: Observer): bool = o.haveLastObs and o.lastObs.censored
|
||||
|
||||
proc writeProbeEvent*(o: Observer, tick: int, kind, gateState: string,
|
||||
entropyBefore, entropyAfter, turnRate,
|
||||
targetSpeed: float64) =
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
## Tests for the CHIMERA debug overlay (chimera/debugdraw.nim).
|
||||
##
|
||||
## Run from `ChimeraBot_garage/src` (as the nimble `test` task does):
|
||||
## nim c -r -d:chimeraDebug ../tests/test_debugdraw.nim
|
||||
##
|
||||
## Two concerns:
|
||||
## (i) the pure primitive builder is deterministic and respects the per-tick
|
||||
## budget, and produces the right primitives for the interesting states;
|
||||
## (ii) THE REGRESSION ASSERTION: rendering the overlay does not perturb the
|
||||
## command intent. We run a synthetic tick pipeline twice on the same
|
||||
## input — once with the overlay drawn and once without — and assert the
|
||||
## serialised `BotIntent` is identical once `debugGraphics` (the whole
|
||||
## point of the overlay) is removed.
|
||||
##
|
||||
## The test is compiled WITH `-d:chimeraDebug` so `renderOverlay` actually draws;
|
||||
## without the define it would be an empty stub and the assertion vacuous.
|
||||
|
||||
import std/[json, strutils]
|
||||
import robocode_tankroyale_botapi
|
||||
import chimera/debugdraw
|
||||
|
||||
var failed = 0
|
||||
proc check(name: string, cond: bool, detail: string = "") =
|
||||
if cond: echo " ok ", name
|
||||
else: echo " FAIL ", name, " [", detail, "]"; inc failed
|
||||
|
||||
proc sampleInput(): OverlayInput =
|
||||
OverlayInput(
|
||||
selfX: 100.0, selfY: 200.0,
|
||||
kernelName: "ORBIT_BALLIST", kernelP: 0.96, entropy: 0.21,
|
||||
pFire5: 0.42,
|
||||
enemyX: 500.0, enemyY: 300.0, haveEnemy: true,
|
||||
predX: 530.0, predY: 320.0, havePred: true,
|
||||
fresh: true, censored: false, scanGap: 1,
|
||||
probeLabel: "pkReversal", probeFlash: true)
|
||||
|
||||
block:
|
||||
echo "debugdraw: pure builder determinism + budget"
|
||||
let inp = sampleInput()
|
||||
let a = buildOverlay(inp)
|
||||
let b = buildOverlay(inp)
|
||||
check("buildOverlay deterministic (byte-identical reruns)", a == b)
|
||||
check("budget respected (<= MaxDebugPrims)", a.len <= MaxDebugPrims,
|
||||
"got " & $a.len)
|
||||
check("full-featured input draws every layer (>= 7 prims)", a.len >= 7,
|
||||
"got " & $a.len)
|
||||
|
||||
# Deprived states must not crash and must stay within budget.
|
||||
var bare = OverlayInput(selfX: 1.0, selfY: 1.0)
|
||||
check("empty input -> only scan-health (<= 1 prim)", buildOverlay(bare).len <= 1)
|
||||
var noPred = inp
|
||||
noPred.havePred = false
|
||||
check("no prediction -> no counterfactual line",
|
||||
buildOverlay(noPred).len < buildOverlay(inp).len)
|
||||
var censored = inp
|
||||
censored.censored = true
|
||||
check("censor tick -> counterfactual skipped; scan-health shown",
|
||||
buildOverlay(censored).len <= MaxDebugPrims)
|
||||
|
||||
block:
|
||||
echo "debugdraw: regression — overlay must not change the command intent"
|
||||
# Deterministic stand-in for one tick's command pipeline. It uses the REAL
|
||||
# botapi command setters and the REAL buildIntentJson, so this is exactly the
|
||||
# state that `go()` would serialise.
|
||||
proc syntheticTick(withOverlay: bool): JsonNode =
|
||||
setGunTurnRate(0.0)
|
||||
setRadarTurnRate(45.0)
|
||||
setTargetSpeed(3.0)
|
||||
setTurnRate(-2.5)
|
||||
if withOverlay:
|
||||
renderOverlay(buildOverlay(sampleInput()))
|
||||
result = parseJson(buildIntentJson())
|
||||
if result.hasKey("debugGraphics"):
|
||||
result.delete("debugGraphics") # overlay's only intended effect
|
||||
|
||||
let withoutOverlay = syntheticTick(withOverlay = false)
|
||||
let withOverlay = syntheticTick(withOverlay = true)
|
||||
check("command intent identical with/without overlay",
|
||||
withoutOverlay == withOverlay,
|
||||
"without=" & $withoutOverlay & " with=" & $withOverlay)
|
||||
check("turn rate is untouched", $withOverlay["turnRate"] == $(-2.5))
|
||||
check("target speed is untouched", $withOverlay["targetSpeed"] == $3.0)
|
||||
|
||||
when defined(chimeraDebug):
|
||||
# Prove the overlay really drew under the gate (so the comparison above was
|
||||
# not vacuous): the global SVG buffer must hold the drawn fragment.
|
||||
check("overlay produced SVG under -d:chimeraDebug", svgOutput().len > 0)
|
||||
check("SVG carries our primitives",
|
||||
svgOutput().contains("P(fire5)") and svgOutput().contains("probe:"))
|
||||
else:
|
||||
echo " note: built without -d:chimeraDebug (renderOverlay is an empty stub)"
|
||||
|
||||
echo ""
|
||||
if failed == 0: echo "all debugdraw tests passed"
|
||||
else: echo failed, " debugdraw test(s) FAILED"; quit(1)
|
||||
Reference in New Issue
Block a user