ChimeraBot_garage: bootstrap exact copy of DevControlBot (CHIMERA M1)

This commit is contained in:
2026-10-06 23:25:06 +02:00
parent b6425ac7f2
commit 215731718a
17 changed files with 3011 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
# User-authored environment variables (e.g. SERVER_URL) — never committed
.env
+24
View File
@@ -0,0 +1,24 @@
# ChimeraBot
ChimeraBot is an **exact behavioral copy of DevControlBot** at bootstrap: same
run loop, same radar (commanded before `go()`), same TFIL survival movement,
same ELM gun, same full-**black** team colours (white = not programmed,
black = programmed and running). The fork exists to host **CHIMERA**
experiments; see [`../docs/chimera-spec.md`](../docs/chimera-spec.md).
The faithful-copy reference is `DevControlBot_garage/DevControlBot/`: any
divergence from that source is a bug until an experiment deliberately changes it.
Sources live in `src/` (`ChimeraBot.nim`, `.json`, `.nimble`, `.sh`,
`ChimeraBot/modules/`); unit tests in `tests/`; `out/` is reserved and builds
stay throwaway (`mktemp -d`).
## Run
```sh
cd ChimeraBot_garage/src && nimble runBot # release build + run
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.
View File
+9
View File
@@ -0,0 +1,9 @@
{
"name": "ChimeraBot",
"version": "1.0.0",
"authors": ["Davide Cappellini"],
"description": "Control skeleton bot — does nothing, bright colors",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
+261
View File
@@ -0,0 +1,261 @@
## ChimeraBot — control skeleton: boots, drives the radar every tick and keeps
## itself alive with the TFIL survival movement. It never fires.
##
## Team convention: white means "not programmed yet". Each module claims its own
## colours when its init runs, and nothing paints white after that: initTFIL()
## (constructor) paints body, turret and gun BLACK — movement is programmed —
## and initRadar() (first line of run) paints the radar and the scan arc BLACK.
## The bot therefore ends up fully BLACK. Colors are applied once, never per tick.
##
## This module is both the bot type and the program entry point (see isMainModule
## below). All radar logic lives in modules/radar.nim; the bot keeps no state.
##
## The run loop drives the radar: commandRadar() is called BEFORE go() every
## tick, so the command is part of the tick's intent and is sent by THIS go().
## The order matters — go() sends the intent first and dispatches the pending
## events last, so onScannedBot only feeds the NEXT tick.
##
## Movement: modules/tfil.nim ("The Floor Is Lava"), vendored into this folder so
## the bot depends on nothing but the API. It is asked for a command every tick,
## BEFORE go(), exactly like the radar, and the result is applied with
## setTargetSpeed/setTurnRate — same contract as ModularBot's mover.
##
## Debug graphics: TFIL's drawing needs NO plumbing here. The API's graphics
## procs are global; the SVG buffer is flushed and cleared by the API after every
## tick, so anything drawn before `go()` (i.e. inside computeMove) reaches the
## viewer. It is compiled only with `-d:tfilDebug`; see README "Debug graphics".
##
## API: robocode_tankroyale_botapi 1.0.7 (the renamed tankroyale_botapi package).
import std/[math, os, sequtils, strutils]
import robocode_tankroyale_botapi
import ChimeraBot/modules/radar
import ChimeraBot/modules/tfil
import ChimeraBot/modules/ELM/elm_gun
import ChimeraBot/modules/ELM/elm_features
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
## only what it scans, so this is a cap, not a limit
const EnemyStaleTicks* = 60 ## drop a scanned enemy not rescanned for this many
## ticks (~1s at 60Hz): a bot seen once would keep
## painting its heat in the field forever
const MaxDeadReckonTicks* = 4 ## How far a constant-velocity guess may be
## extrapolated past the last scan. The radar
## lock re-scans almost every tick, so this only
## bites when the target is genuinely lost: past
## it, freeze at the last seen position rather
## than let old vx/vy run the aim away.
# A/B switch, compile time: `-d:baselineGun` builds the geometric-only gun, the
# default build is the ELM gun. Both go through the same predictAim() call, so
# the two binaries differ by exactly the learned correction and nothing else —
# which is what makes the measured difference attributable.
const UseElm* = not defined(baselineGun)
# Online-start variant: default = neutral (zero output weights).
# `-d:elmPrior` = weak pooled prior (pretrained beta scaled by 0.1).
const OnlinePriorScale* = (when defined(elmPrior): 0.1 else: 0.0)
const FireSlopDeg = 1.0'f64 ## fire inside this much gun error, in
## DEGREES (the API's unit).
##
## Was 3.0 but compared against radians
## (`degToRad(FireSlopDeg)` = 0.052 deg): fixing
## the unit made the gun fire mid-slew, up to
## 3 deg off, and cost hits. 1 deg is tight
## enough that the shot is on target while
## still firing the tick after a correction.
type ChimeraBot* = ref object of Bot
mover: TfilModule
tick: int
enemies: seq[EnemyInfo] ## fed by onScannedBot, cleared on round end
gun: ElmGun ## the ELM gun (or the geometric baseline, see UseElm)
shotsFired: int ## diagnostics, reset on round end
roundNo: int ## bumped on every RoundEnded, so the shot log can be
## joined to a recording round
proc newChimeraBot*(): ChimeraBot =
result = ChimeraBot()
result.mover = initTFIL() # movement is programmed -> body/turret/gun BLACK
result.gun = initElmGun(priorScale = OnlinePriorScale) # hidden layer loaded, online
setRadarColor(WHITE) # overwritten by initRadar() before the first tick
method onScannedBot*(bot: ChimeraBot, e: ScannedBotEvent) =
onScan(e.x, e.y) # remembered; commandRadar() re-aims every tick
# (e.scannedBotId, schemas.nim:305, is the
# scanned bot's identity)
# ...and the full history the gun needs: this tick, the position, and where WE
# were when we saw it (own displacement since the scan is a model feature).
onScanFull(bot.tick, e.x, e.y, getX(), getY()) # history the gun needs
if bot.gun.online:
bot.gun.noteEnemyAt(bot.tick, e.x, e.y) # delayed-label trace
for i, ei in bot.enemies:
if ei.id == e.scannedBotId:
bot.enemies[i].x = e.x
bot.enemies[i].y = e.y
bot.enemies[i].heading = e.direction
bot.enemies[i].speed = e.speed
bot.enemies[i].energy = e.energy
bot.enemies[i].lastSeenTick = bot.tick
return
if bot.enemies.len >= MaxScannedEnemies:
bot.enemies.delete(0)
bot.enemies.add EnemyInfo(id: e.scannedBotId, x: e.x, y: e.y,
heading: e.direction, speed: e.speed, energy: e.energy,
lastSeenTick: bot.tick)
method onHitByBullet*(bot: ChimeraBot, e: HitByBulletEvent) =
# an enemy bullet hit us -> tell the fire tracker, else the same tick reads as
# "no fire" and the enemy's shot goes uncounted (see modules/tfil.nim, FireFix)
bot.mover.noteEnemyBulletHit(e.bullet.power)
method onBulletHit*(bot: ChimeraBot, e: BulletHitBotEvent) =
bot.mover.noteDamageDealt(e.damage)
method onGameStarted*(bot: ChimeraBot, e: GameStartedEventForBot) =
## A new game = a new opponent. This is the ONLY reset point for the online
## model: within a battle the same opponent fights round after round with the
## same movement code, so RoundStartedEvent deliberately does NOT touch it.
## (The API fires onGameStarted once per battle and onRoundStarted per round.)
bot.gun.resetOnline()
method onRoundEnded*(bot: ChimeraBot, e: RoundEndedEventForBot) =
inc bot.roundNo
bot.enemies = @[]
bot.shotsFired = 0
bot.mover.resetRound()
method buildBelief(bot: ChimeraBot, power: float): GunBelief =
## Assemble what the gun is allowed to know. Everything here comes from our
## own state or from modules/radar.nim's scan history — there is no oracle.
let (vx, vy) = targetVelocity()
let age = scanAge(scanTick)
result.everScanned = haveLast and age >= 0
result.selfX = getX()
result.selfY = getY()
# The API speaks DEGREES everywhere (getDirection, normalizeRelativeAngle,
# setGunTurnRate); the model speaks radians (every angle in the corpus). This
# conversion is the whole difference between a gun that aims and one that
# sprays bullets into the walls.
result.selfHeading = degToRad(getDirection())
result.selfSpeed = getSpeed()
result.ownDisp = ownDisp(getX(), getY())
result.scanAge = age
result.scanGap = scanGap()
result.winN = min(winN, WinCap)
for k in 0 ..< result.winN:
result.winX[k] = winX[k]
result.winY[k] = winY[k]
result.winTick[k] = winTick[k]
result.vx = vx
result.vy = vy
# dead-reckon: last seen position advanced by the estimated velocity, but no
# farther than a constant-velocity guess stays credible (see the const).
let lead = min(age, float(MaxDeadReckonTicks))
result.ex = lastScan.x + vx * lead
result.ey = lastScan.y + vy * lead
result.power = power
result.bulletSpeed = 20.0 - 3.0 * power
result.gunHeat = getGunHeat()
method ageEnemies(bot: ChimeraBot) =
# heat field is only as good as the freshest scans; stale entries stay
# plausible-looking but poison the grid, so they go
bot.enemies = bot.enemies.filterIt(it.lastSeenTick >= bot.tick - EnemyStaleTicks)
method buildWorldState(bot: ChimeraBot): WorldState =
WorldState(selfX: getX(), selfY: getY(),
selfSpeed: getSpeed(), selfHeading: getDirection(),
selfRadarHeading: getRadarDirection(), selfEnergy: getEnergy(),
arenaWidth: getArenaWidth().float, arenaHeight: getArenaHeight().float,
tick: bot.tick, enemies: bot.enemies)
## The gun tick: aim, and fire when the gun is actually on the aim point.
##
## Standard Tank Royale gun handling, nothing clever — the cleverness (if any)
## lives entirely inside predictAim(). Order is the API's: set the gun turn rate,
## fire only when the gun is both COOLED (getGunHeat() == 0) and ON the aim, and
## do it before go() so the shot is part of this tick's intent.
proc computeGun(bot: ChimeraBot) =
if bot.gun.online:
bot.gun.drainPending(bot.tick) # label any shot whose flight time elapsed
let belief = bot.buildBelief(FirePower)
let feat = buildFeatures(belief)
let aim = bot.gun.predictAim(belief, FirePower, UseElm)
let baseAim = bot.gun.heuristicAim(belief, FirePower)
if aim.aim.isNaN:
setGunTurnRate(0.0)
return
when defined(gunDebug):
if bot.tick mod 20 == 0:
echo "[gun] t=", bot.tick, " self=(", getX(), ",", getY(), ") lastScan=(", lastScan.x, ",", lastScan.y,
") age=", scanAge(scanTick), ") aimDeg=", radToDeg(aim.aim),
" corr=", aim.correction, " gunDeg=", getGunDirection()
let err = gunAimErrorDeg(aim.aim, getGunDirection())
# `err` is DEGREES: gunAimErrorDeg is the single rad->deg conversion point and
# its name carries the unit, so `<= FireSlopDeg` can only compare degrees with
# degrees. (The old code compared a degree error against degToRad(FireSlopDeg)
# i.e. 0.052 deg of slop, and withheld fire far past the target.)
if abs(err) <= FireSlopDeg:
# Park the gun: the pending correction from the previous tick is applied
# AFTER firing (TurnProcessor fires before executeBotIntents), so it would
# only over-rotate the gun on the NEXT turn. Zeroing it keeps the gun on the
# aim point while it holds fire.
setGunTurnRate(0.0)
if getGunHeat() == 0.0:
# Non-blocking. `fire()` is the BLOCKING variant: it calls go() itself, so
# the outer loop's go() ran a second, empty turn - the bot double-stepped
# the server on every shot, desyncing tick/scan bookkeeping from the game.
discard setFire(FirePower)
inc bot.shotsFired
if bot.gun.online:
# Enqueue a delayed label: the true impact position is only knowable
# once tof ticks of flight have passed (keyed by dueTick).
let d = hypot(belief.ex - belief.selfX, belief.ey - belief.selfY)
let tofTicks = max(1, int(round(d / belief.bulletSpeed)))
bot.gun.recordShot(feat, baseAim, belief.selfX, belief.selfY,
bot.tick + tofTicks)
when defined(gunLog):
# One line per shot. Columns:
# round,tick,predCorrection,baseAimDeg,finalAimDeg,gunDeg,
# nOnline,gateOpen,modelErr,zeroErr,<32 features>
let path = getEnv("ELM_GUN_LOG", "")
if path.len > 0:
let f = open(path, fmAppend)
defer: f.close()
f.write($bot.roundNo & "," & $bot.tick & "," & $aim.correction & "," &
$(radToDeg(baseAim)) & "," & $(radToDeg(aim.aim)) & "," &
$(getGunDirection()) & "," & $bot.gun.nOnline & "," &
(if bot.gun.gateOpen: "1" else: "0") & "," &
$bot.gun.modelErr & "," & $bot.gun.zeroErr & "," &
feat.mapIt($it).join(" ") & "\n")
else:
setGunTurnRate(err)
method run*(bot: ChimeraBot) =
setAdjustGunForBodyTurn(true) # turret ignores body rotation
setAdjustRadarForBodyTurn(true) # radar ignores body rotation
setAdjustRadarForGunTurn(true) # radar ignores turret rotation too
initRadar() # once: radar + scan turn BLACK = programmed
while isRunning():
# One radar command and one movement command per tick, unconditionally,
# BEFORE go() — so both are part of this tick's intent.
commandRadar()
bot.ageEnemies() # stale scans dropped before they paint heat
let (speed, turnRate) = bot.mover.computeMove(bot.buildWorldState())
setTargetSpeed(speed)
setTurnRate(turnRate)
bot.computeGun() # gun intent, also before go()
go()
inc bot.tick
when isMainModule:
# argv[1] may override the metadata file (used by ChimeraBot/ChimeraBot.sh);
# otherwise the JSON next to this source, resolved at compile time so any cwd works.
let jsonPath =
if paramCount() >= 1: paramStr(1)
else: currentSourcePath().parentDir / "ChimeraBot.json"
var bot = newChimeraBot()
start(bot, jsonPath)
+256
View File
@@ -0,0 +1,256 @@
# Package
version = "1.0.0"
author = "Davide Cappellini"
description = "ChimeraBot — control-skeleton bot that does nothing but show up bright"
license = "MIT"
srcDir = "."
bin = @[]
# Dependencies
# Installed globally with `nimble install`; nothing is vendored locally and
# no nimble.paths / vendor/ is used. `runBot` resolves each package's real
# location at run time with `nimble path` and passes explicit --path: flags,
# so the build does not rely on $HOME or on the compiler's bundled nimblepath.
requires "nim >= 2.0.0"
requires "robocode_tankroyale_botapi >= 1.0.7"
requires "jsony >= 1.1.5"
# The build-and-run logic lives here, not in ChimeraBot.sh.
#
# NimScript cannot install signal handlers, so the temp build dir is owned by a
# small POSIX shell program (below) that Nimble executes via `exec` (which goes
# through the shell). That program traps EXIT/INT/TERM and always removes the
# throwaway build dir, including when compilation fails or the run is
# interrupted. Nothing is ever written to a persistent out/ directory.
#
# `exec` turns ANY non-zero exit into a NimScript exception, which prints a
# stack trace plus an escaped copy of the whole script. That is nonsense for the
# expected "no game server at SERVER_URL" outcome. So the shell always exits 0 and
# hands the real code back through the file named by $CHIMERABOT_STATUS_FILE,
# which ChimeraBot.sh exports and then re-exits with. Direct `nimble runBot`
# (no such variable) keeps the old behaviour: the shell exits with the real code
# and Nimble raises.
#
# ChimeraBot.sh is a thin wrapper: it locates itself, chdirs here so Nimble
# finds this file, forwards caller args, calls `runBot` and forwards signals.
import std/os
const
runScript = """
# Resolve the globally-installed dependencies at run time. Plain `nim c` only
# finds them when $HOME is set (the Nim distribution's nim.cfg carries
# `nimblepath="$home/.nimble/pkgs2/"`), which is NOT true in bare environments
# (env -i, nix build sandboxes, CI). `nimble path` is the reliable,
# cwd-independent way to ask for their real location.
# Distinct exit codes, so a caller can tell the failure modes apart.
EXIT_NO_SERVER=1 # bot could not connect to the game server (expected)
EXIT_NO_DEPS=2 # a dependency is not installed
EXIT_COMPILE=3 # compilation failed
STATUS_FILE="${CHIMERABOT_STATUS_FILE:-}"
# report <code>: write the real exit code to the status file. Returns 1 when
# there is no status file, i.e. the caller wants it as the shell's own code.
report() {
[ -n "$STATUS_FILE" ] || return 1
printf '%s\n' "$1" > "$STATUS_FILE"
}
# die <code>: finish with <code> as the run's real result — quietly (exit 0,
# the status file carries the code) or, with no listener, by exiting with it.
die() {
if report "$1"; then exit 0; else exit "$1"; fi
}
DEPS=""
for pkg in robocode_tankroyale_botapi jsony; do
pkgdir="$(nimble path "$pkg" 2>/dev/null | head -n 1)"
if [ -z "$pkgdir" ] || [ ! -d "$pkgdir" ]; then
echo "[chimerabot] COMPILE BLOCKED: dependency '$pkg' is not installed." >&2
echo "[chimerabot] fix with: nimble install $pkg" >&2
die $EXIT_NO_DEPS
fi
echo "[chimerabot] dependency $pkg -> $pkgdir"
DEPS="$DEPS '--path:$pkgdir'"
done
# Build mode: $CHIMERABOT_DEBUG is set to "debug" by ChimeraBot.sh when
# the caller passed --debug; anything else (including an unset variable, i.e. a
# direct `nimble runBot`) means release. Release is the quiet default.
BUILD_MODE="${CHIMERABOT_DEBUG:-release}"
# Compile-time Nim defines, stripped from the caller's argv by ChimeraBot.sh
# and handed over here as a space-separated string. They MUST be stripped: this
# task forwards its own argv to the BOT BINARY, so a -d: arg left there would be
# consumed as the bot's argv and never reach the compiler. Applied to BOTH build
# modes on purpose: defines are independent of optimisation level, so -d:tfilDebug
# debug graphics are wanted in a release build too. Empty when the caller passed
# none, which leaves the compile lines exactly as they were.
DEFINES="${CHIMERABOT_DEFINES:-}"
if [ -n "$DEFINES" ]; then
echo "[chimerabot] compile-time defines: $DEFINES"
fi
BUILD_DIR="$(mktemp -d "${TMPDIR:-/tmp}/chimerabot.XXXXXX")"
BINARY="$BUILD_DIR/ChimeraBot"
# ---- optional .env ------------------------------------------------------------
# Configuration reaches the bot through the ENVIRONMENT, not through any code
# of ours: robocode_tankroyale_botapi's start() reads SERVER_URL and
# SERVER_SECRET (robocode_tankroyale_botapi.nim:424-425, documented at :396-397)
# and loadBotInfo() reads BOT_NAME / BOT_VERSION / ... from the environment when
# the JSON is absent (bot_info.nim:117-130). That is the documented, supported
# mechanism the official BotLauncher uses, so the only thing we do here is make
# those variables PRESENT in the bot's process environment for local runs.
#
# Loaded HERE, in the runBot task, and not in ChimeraBot.sh, so it applies both
# to `./ChimeraBot.sh` and to a direct `nimble runBot` (one implementation, and
# the wrapper stays a thin wrapper).
# - optional: a missing file is not an error, nothing is printed but a note,
# the bot just uses the API defaults.
# - CRLF-tolerant: CRs are stripped so a Windows-edited file does not end up
# with the value "bar\r".
# - both `FOO=bar` and `export FOO=bar` styles.
# - never echoed, never `set -x`: only the file NAME is reported.
# - $CHIMERABOT_ENV_FILE overrides the default path (".env" next to the
# .nimble, which is the cwd because ChimeraBot.sh chdirs there).
#
# PRECEDENCE — CRITICAL. The .env file must NEVER override a variable that is
# already present in the environment: the official BotLauncher's values (and the
# caller's explicit `FOO=bar ./ChimeraBot.sh`) must always win, otherwise this
# convenience file could silently break a BotLauncher run. Sourcing the file
# directly would do the opposite, because an assignment in a sourced file
# overwrites an already-exported variable of the same name. So the file is
# FILTERED line by line: a `NAME=value` line is dropped when NAME is already set
# in the environment (tested with `[ -n "${NAME+x}" ]`, i.e. set-but-maybe-empty,
# not non-empty), and only the remaining, still-unset names are sourced with
# `set -a`. The filtering is what implements the precedence, not the source order.
ENV_FILE="${CHIMERABOT_ENV_FILE:-.env}"
if [ -f "$ENV_FILE" ]; then
ENV_RAW="$BUILD_DIR/env.raw"
ENV_KEEP="$BUILD_DIR/env.keep"
ENV_ADDED=""
# CRLF tolerance: drop the CRs, keep everything else verbatim.
tr -d '\r' < "$ENV_FILE" > "$ENV_RAW"
: > "$ENV_KEEP"
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in
''|\#*) continue ;; # blank / comment
export\ *|export=*) line="${line#export }" ;;
esac
name="${line%%=*}"
# Only plain NAME=value assignments; anything else is ignored, so the file
# can never smuggle in commands. `name` is validated as an identifier
# BEFORE being used in the eval below.
printf '%s' "$name" | grep -q '^[A-Za-z_][A-Za-z_0-9]*$' || continue
# PRECEDENCE: skip if the variable already exists in the environment.
if eval "[ -n \"\${$name+x}\" ]"; then
continue
fi
printf '%s\n' "$line" >> "$ENV_KEEP"
ENV_ADDED="$ENV_ADDED $name"
done < "$ENV_RAW"
if [ -n "$ENV_ADDED" ]; then
set -a
. "$ENV_KEEP"
set +a
fi
rm -f "$ENV_RAW" "$ENV_KEEP"
# Variable NAMES only, never values.
echo "[chimerabot] env file loaded: $ENV_FILE (names added:${ENV_ADDED:- none}; values never printed)"
echo "[chimerabot] variables already in the environment win and were left untouched"
else
echo "[chimerabot] no env file at $ENV_FILE (optional, using API defaults)"
fi
cleanup() {
rc=$?
trap - EXIT INT TERM
rm -rf "$BUILD_DIR"
if [ -d "$BUILD_DIR" ]; then
echo "[chimerabot] cleanup failed: $BUILD_DIR still present" >&2
exit 1
fi
exit $rc
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# Release: hints and the progress/dot lines are noise, so the compiler output is
# captured to a log and only shown if the build fails (errors are ALWAYS shown).
# Debug: classic build, full compiler output (config-file hints, diagnostics).
LOG="$BUILD_DIR/build.log"
if [ "$BUILD_MODE" = "debug" ]; then
echo "[chimerabot] compiling ChimeraBot.nim (DEBUG BUILD) -> $BINARY"
# `eval` re-parses $DEPS and $DEFINES so the embedded quotes do the word
# splitting: the dependency paths survive spaces, without relying on glob or
# brace expansion. $DEFINES holds only whole -d:name[=value] words (the wrapper
# rejects whitespace and shell metacharacters).
# No pipe: POSIX sh has no PIPESTATUS, and `nim | tee` would report tee's
# status, not the compiler's. Buffer first, then replay the log verbatim.
eval nim c $DEFINES $DEPS --out:"$BINARY" ChimeraBot.nim >"$LOG" 2>&1
compile_rc=$?
cat "$LOG"
else
echo "[chimerabot] compiling ChimeraBot.nim -> $BINARY"
eval nim c -d:release $DEFINES --hints:off $DEPS --out:"$BINARY" ChimeraBot.nim >"$LOG" 2>&1
compile_rc=$?
fi
if [ $compile_rc -ne 0 ]; then
if [ "$BUILD_MODE" != "debug" ]; then
echo "[chimerabot] --- compiler output ---" >&2
cat "$LOG" >&2
echo "[chimerabot] --- end compiler output ---" >&2
fi
echo "[chimerabot] COMPILE FAILED (nim c exited $compile_rc) — errors above." >&2
die $EXIT_COMPILE
fi
rm -f "$LOG"
if [ "$BUILD_MODE" = "debug" ]; then
echo "[chimerabot] build ok (debug)"
else
echo "[chimerabot] build ok (release)"
fi
# The bot reads argv[1] as its metadata JSON path. If the caller already
# supplied a JSON, use that instead of the bundled one.
if [ -n "${1:-}" ] && [ "${1##*.}" = "json" ]; then
echo "[chimerabot] using caller-supplied metadata: $1"
"$BINARY" "$@"
else
# NOTE: no `exec` here: the shell must survive so the EXIT trap can clean up.
echo "[chimerabot] running $BINARY ChimeraBot.json $*"
"$BINARY" ChimeraBot.json "$@"
fi
bot_rc=$?
if [ $bot_rc -ne 0 ]; then
echo "[chimerabot] bot exited with code $bot_rc." >&2
if [ $bot_rc -eq $EXIT_NO_SERVER ]; then
# The Tank Royale client answers a refused connection with this exact
# exit code, so it means "no server", not "broken bot".
echo "[chimerabot] No game server on ${SERVER_URL:-ws://localhost:7654} (SERVER_URL)." >&2
echo "[chimerabot] Start the Tank Royale server, or point SERVER_URL at a running one." >&2
else
echo "[chimerabot] The bot ran but failed at runtime (crash or bad metadata)." >&2
fi
fi
die $bot_rc
"""
task runBot, "Compile, run and clean up the bot":
# Nimble passes every CLI argument here (its own flags, then the task name,
# then the caller's arguments). Ours are the ones after the task name.
var args = ""
var seen = false
for a in commandLineParams():
if seen:
if args != "": args = args & " "
args = args & quoteShell(a)
elif a == "runBot":
seen = true
exec "sh -c " & quoteShell(runScript) & " chimerabot " & args
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"
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env bash
# BotLauncher entry point for ChimeraBot.
#
# Thin wrapper: all build/run/cleanup logic lives in the `runBot` nimble task
# of ChimeraBot.nimble. This script only locates itself, moves next to the
# .nimble so Nimble finds it, forwards caller arguments, calls the task and
# propagates the real exit code. Signals are forwarded to Nimble so the task's
# own EXIT/INT/TERM cleanup always runs.
#
# Usage: ChimeraBot.sh [--debug] [-d:<define>[=<value>]]... [<metadata.json>] [extra args]
#
# (no args) RELEASE build + run with the bundled ChimeraBot.json
# (no flag) RELEASE build (nim c -d:release), quiet output
# --debug classic DEBUG build (plain nim c): compiler hints + diagnostics
# -d:foo compile-time Nim define. ANY number, in any position, in EITHER
# build mode: --debug only changes optimisation/hints, defines are
# independent of it, so `-d:tfilDebug` debug graphics work in a
# release build too. Accepted forms: -d:foo and -d:foo=bar.
#
# --debug is a build-mode flag for this wrapper only: it is stripped here and
# never reaches the bot binary or nimble's task arguments. It travels to the
# runBot task as $CHIMERABOT_DEBUG (exported), because an env var cannot be
# confused with a bot argument, cannot collide with the status file mechanism
# and keeps the task's argument parsing untouched. Repeated --debug is harmless.
#
# -d: args travel the same way, as $CHIMERABOT_DEFINES. They MUST be stripped
# here: the runBot task forwards its own argv to the BOT BINARY, so a -d: arg
# would otherwise become the bot's argv and never reach the compiler. Matching is
# the anchored glob `-d:*` (whole-argument, starts with -d:), so a value that
# merely contains "-d:" inside another word ("x-d:y", "--debug-d:x") is NOT a
# define and is forwarded verbatim. Anything that is neither --debug, -h/--help
# nor a -d: arg still reaches the bot binary exactly as before.
#
# Configuration (SERVER_URL, SERVER_SECRET, ...) is NOT handled here at all: the
# API's start() reads those from the environment, and the optional .env file is
# loaded by the runBot task, so it also works with a direct `nimble runBot`.
set -uo pipefail
set -m # job control: the background job gets its own process group
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
usage() {
cat <<EOF
Usage: $(basename "$0") [--debug] [-d:<define>[=<value>]]... [<metadata.json>] [extra args for the bot]
--debug classic debug build: shows compiler hints and diagnostics
(default is a quiet RELEASE build, nim c -d:release)
-d:foo, -d:foo=bar Nim compile-time define, passed to `nim c`. Repeatable.
Independent of --debug: defines apply in BOTH build modes,
so `-d:tfilDebug` debug graphics also work in a release
build. Only whole args starting with -d: are treated as
defines; everything else is forwarded to the bot binary.
-h,--help show this help
Examples:
$(basename "$0") # release build + run, bundled ChimeraBot.json
$(basename "$0") my.json # release build + run with custom metadata
$(basename "$0") -h # this help
$(basename "$0") --debug # debug build
$(basename "$0") --debug my.json # debug build with custom metadata
$(basename "$0") -d:tfilDebug # release build with TFIL debug graphics
$(basename "$0") --debug -d:tfilDebug # debug build, also with debug graphics
$(basename "$0") -d:danger -d:logLevel=2 my.json
EOF
}
# Split caller args: --debug and -d: defines are consumed here, everything else
# is forwarded verbatim. The defines end up in a single space-separated string
# because the compiler line is `eval`ed (like $DEPS) to survive paths with spaces.
BUILD_MODE=release
DEFINES=""
FORWARDED=()
for a in "$@"; do
case "$a" in
--debug) BUILD_MODE=debug ;;
-d:*)
# TRUST BOUNDARY: the string is eval'ed by the runBot task, so a define
# carrying whitespace, quotes, $, ` or ; could inject shell. Reject it
# loudly instead of passing it on. Legal Nim defines (-d:foo, -d:foo=bar)
# contain none of these.
case "$a" in
*[[:space:]\"\'\$\;\`\\]*)
echo "$(basename "$0"): invalid define '$a'" >&2
echo " expected -d:name or -d:name=value with no spaces or shell characters" >&2
exit 1 ;;
esac
DEFINES="$DEFINES $a" ;;
*) FORWARDED+=("$a") ;;
esac
done
set -- ${FORWARDED+"${FORWARDED[@]}"}
# No arguments is the normal case: build and run with the bundled metadata.
# Usage is printed ONLY for an explicit -h/--help.
case "${1:-}" in
-h|--help) usage; exit 0 ;;
esac
export CHIMERABOT_DEBUG="$BUILD_MODE"
# Leading space trimmed: empty when the caller passed no -d: arg, and the runBot
# task's compile lines are then byte-identical to a run without this feature.
export CHIMERABOT_DEFINES="${DEFINES# }"
# The runBot task's shell always exits 0 (otherwise Nimble raises a NimScript
# exception with a stack trace and a dump of the whole script) and writes the
# bot's real exit code here instead. We read it back and exit with it, so
# BotLauncher still sees the faithful status: 1 = no game server at SERVER_URL,
# 2 = a dependency is missing, 3 = compile failure, anything else = the bot's
# own code, 0 = clean run.
STATUS_FILE="$(mktemp "${TMPDIR:-/tmp}/chimerabot.status.XXXXXX")"
export CHIMERABOT_STATUS_FILE="$STATUS_FILE"
trap 'rm -f "$STATUS_FILE"' EXIT
# Forward to the whole job process group (nimble + the shell it spawned) so the
# task's own EXIT/INT/TERM cleanup runs. No cleanup logic here.
forward() { kill -s "$1" -- "-$NIMBLE_PID" 2>/dev/null; }
trap 'forward TERM' TERM
trap 'forward INT' INT
nimble runBot ${1+"$@"} &
NIMBLE_PID=$!
wait "$NIMBLE_PID"
rc=$?
trap - TERM INT
# Prefer the code the run actually produced; fall back to Nimble's own status if
# the task died before it could report (e.g. Nimble itself failed).
real_rc="$(head -n 1 "$STATUS_FILE" 2>/dev/null | tr -d '[:space:]')"
[ -n "$real_rc" ] || real_rc=$rc
exit "$real_rc"
@@ -0,0 +1,150 @@
# ELM — Extreme Learning Machine
`modules/ELM/elm.nim`. Single hidden layer, `tanh` activation by default (pluggable
via `activation*`, see below), **closed-form** output layer. Bot-agnostic: stdlib
only (`math`, `random`, `strutils`), `float64` throughout, own Cholesky — no
LAPACK, no `linearalgebra`, nothing to install.
## Usage
```nim
import modules/ELM/elm
var e = initElm(ElmConfig(
inputDim: 6, hiddenDim: 64, outputs: 2,
seed: 42, lambda: 1e-6, decay: 0.98, refitEvery: 1))
e.train(x, t) # one sample; refits per refitEvery
let y = e.infer(x) # current output, no refit
e.refit() # force a refit
e.reset() # drop samples, zero beta, keep the hidden layer
echo diagnostics(e).trainRmse
```
Tests: `nimble test` (from `ChimeraBot/`), or `nim c -r tests/test_elm.nim` from `ChimeraBot_garage/`
## Activation (`activation*` on `ElmConfig`)
The hidden units are **pure additive** nodes — every activation sees the same
pre-activation `s = a·x + b` and differs only in the scalar nonlinearity `g`:
| `ActivationKind` | `g(s)` |
|------------------|-------------------------------------------------|
| `atanTanh` (default) | `tanh(s)` |
| `atanRelu` | `max(0, s)` |
| `atanStep` | `1.0 if s > 0 else 0.0` |
```nim
var e = initElm(ElmConfig(..., activation: atanRelu))
let y = applyActivation(atanStep, 0.3) # pure, also exported standalone
```
**The default is `atanTanh` and is unchanged**: the hidden-weight scale, the bias
range and every tuned constant are bit-identical to the previous version for
tanh, so existing callers cannot regress. `parseActivation*(string)` is provided
for config/CLI use and raises `ValueError` on an unknown name.
Two hidden-init details are activation-aware, because tanh is the only
scale-robust option (it is curved everywhere, so any spread of
pre-activations gives independent features):
- **bias range**: tanh gets `U[-1,1]` (two-sided, as always). relu/step are dead
for `s <= 0`, so they get `U[0,1]` — otherwise about half the units start dead
and contribute a constant column.
- **weight scale**: relu/step get `8.0 / sqrt(inputDim)` instead of
`1 / sqrt(inputDim)`. relu is curved only at its kink and step only at its
jump, both at `s = 0`; at the tanh scale the pre-activations barely straddle 0
and the units degenerate into linear/constant features, the Gram matrix loses
rank and Thm 2.2 interpolation fails outright (measured with 20 samples in 20
nodes: `trainRmse` 1.1e-01 relu, 3.6e-01 step at the tanh scale; 4.0e-12 and
2.3e-13 at scale 8). See `activationWeightScale` in `elm.nim`.
Consequence to keep in mind: relu/step are unbounded or piecewise constant, so
the output weights they need are large and the shipped near-zero `lambda` does not
regularise them — on `test_elm.nim` test 8 (`lambda = 1e-8`) held-out MSE is
`1.1e-06` tanh, `3.5e-02` relu, `8.4e-02` step. The activation is a plain `g`
swap, but `lambda` is a co-tuning knob for the one-sided ones.
### Why there is no RBF/gaussian option
The classic RBF-ELM hidden unit is `g(b·‖x − a‖)`: the activation reads the
**distance to a centre in input space**, so the hidden layer stores centres plus
per-node widths (and normally picks the width from the data). That is a different
node architecture, not a different `g`, and it cannot be expressed by swapping
`s` for `‖x − a‖` in this additive bank without changing what `W` and `hs` mean,
how they are initialised, and the conditioning argument in `initElm`. It is
deliberately **not** forced in here: adding it would need a separate
`hiddenKind` field with its own init and its own Thm 2.2 validation.
## How it works
The hidden layer is drawn **once** at `initElm` from a seeded RNG and is never
trained. That is the ELM: with a random nonlinear feature map the problem on top
of it is convex, so the output layer is a linear solve instead of gradient
descent (Huang, Wang & Lan 2011).
* hidden weights `W[L][inputDim] ~ U[-1,1] * 1/sqrt(inputDim)`
* hidden biases `b[L] ~ U[-1,1]` — offsets, **not** scaled. They put the `tanh`
units across their nonlinear range; without them the features collapse onto
nearly the same direction and exact interpolation is lost to float64 round-off.
* every `train()` call solves
minimise sum_i w_i * ||a_i . beta - t_i||^2 + lambda * ||beta_pen||^2
over the accumulated samples, accumulating `G = sum w_i a_i a_i^T` and
`C = sum w_i a_i t_i^T`, then `beta = (G + lambda*diag(penalty))^-1 C` via
Cholesky.
## The bias is a column, not a parameter
`a_i` is the **augmented** hidden vector `[h_1 .. h_L, 1.0]`. The output bias is
the last column of `a`, and the ridge penalty diagonal is
```
penalty[p] = 1 for p < L (weights)
penalty[L] = 0 (the bias)
```
so the bias column is **never shrunk toward zero**. With `lambda = 1e4` the slope
is crushed (that is what the penalty is for) and the model still returns the
target's constant offset intact. `tests/test_elm.nim` test 3 asserts exactly that.
## Forgetting without discarding
Every stored sample carries a weight. `train()` first multiplies every stored
weight by `decay` (rho, default 0.98), then stores the new sample with weight 1.
Old data is never thrown away, only forgotten — a wave surfer, not a circular
buffer. `decay = 1.0` disables forgetting; with `decay = 0.5`, one sample carries
the weight of 50 samples added before it down to ~3%.
Refit policy (`refitEvery`):
| value | behaviour in `train()` |
|---|---|
| `0` | **never** refit — accumulate only. The caller must call `refit()` explicitly. This is the batched-training mode: feed N samples, then refit once (cost `O(N·L²)` instead of `O(N²·L²)`). |
| `1` | refit on every `train()` call (live/online mode). |
| `>1` | refit once every `N` train() calls. |
**This is a behaviour change.** Earlier versions treated `<= 1` as "refit on
every call", so `refitEvery = 0` did *not* mean "don't refit" — it silently
refit the whole accumulated buffer on every `train()` call. Callers relying on
the old meaning must change `0` to `1`.
## Measured test numbers
Nim 2.2.4, float64:
| test | measured | asserted |
|---|---|---|
| 1. Thm 2.2 interpolation, L = N = 20, lambda = 0 | `trainRmse = 5.19e-10` | `< 1e-8` |
| 2. `sin(3x)+0.5cos(2y)`, 200 train / 100 held out, L = 64 | `MSE = 1.07e-06` | `< 1e-3` |
| 3. bias not penalised, `lambda = 1e4`, target `5 + 0.1x` | `f(0.25) = 4.9906` | offset within 0.05 of 5.0 |
| 4. decay 0.5 vs 1.0 | `-2.878` vs `0.412`, `trainRmse 0.623` vs `1.110` | differ, 0.5 follows B |
| 5. same seed | identical outputs | — |
| 6. dim mismatch | `ValueError` | — |
## Known ceiling
`G` is rebuilt from scratch on every refit, so cost is `O(n * L^2)` per refit and
`n` grows without bound. For a long-running bot, bound `n` (ring buffer) or use a
larger `refitEvery`.
@@ -0,0 +1,370 @@
## ELM — Extreme Learning Machine, single hidden layer, tanh activation.
##
## The hidden layer's weights and biases are drawn ONCE at init from a seeded
## RNG and are NEVER trained. That is the whole point of an ELM: with a random
## nonlinear feature map the regression on top of it is convex, so the output
## layer can be solved in closed form instead of by gradient descent
## (Huang / Wang / Lan 2011).
##
## ## What is solved
##
## minimise sum_i w_i * ||a_i . beta - t_i||^2 + lambda * ||beta_pen||^2
##
## where a_i is the AUGMENTED hidden vector [h_1 .. h_L, 1.0] and w_i is the
## (age-decayed) sample weight. Accumulating
##
## G = sum_i w_i a_i a_i^T (L+1 x L+1)
## C = sum_i w_i a_i t_i^T (L+1 x M)
##
## gives beta = (G + lambda*diag(penalty))^-1 C, solved by Cholesky.
##
## ## Bias handling (deliberate, see README)
##
## The output-layer bias is NOT a separate parameter: it is the last column of
## `a`, a constant 1.0 feature. The ridge penalty diagonal is therefore 1 for
## the first L entries and 0 for the last one, so the bias column is NEVER
## shrunk toward zero — with a large lambda the model still reproduces a large
## constant offset exactly. (The hidden layer has no bias at all; the random
## feature map is homogeneous plus the output bias, which is enough.)
##
## ## Recency weighting
##
## Every stored sample keeps a weight; adding a new sample of weight w first
## multiplies every stored weight by `decay` (rho), then stores the new one.
## Old data is never discarded, only forgotten — a wave surfer, not a
## circular buffer. `decay = 1.0` disables forgetting entirely.
##
## ## Activation
##
## The hidden layer is a bank of PURE ADDITIVE nodes, i.e. every activation
## takes the same pre-activation `s = a . x + b` and differs only in the scalar
## nonlinearity g applied to it:
##
## tanh g(s) = tanh(s) bounded, smooth, always differentiable
## relu g(s) = max(0, s) bounded below only, unbounded above
## step g(s) = 1.0 if s > 0 else 0.0 piecewise constant (a sign/ramp test)
##
## The node form is deliberately NOT varied: ELM theory only needs g to be
## non-polynomial (almost everywhere differentiable) for the random hidden
## layer to be dense in the target space, so a plain g swap is the whole
## experimental knob. tanh is the default and the only activation the shipped
## configuration was ever tuned with, so existing callers are bit-identical.
##
## NOT here: RBF/gaussian nodes. The classic RBF-ELM hidden unit is
## g(b * ||x - a||), i.e. the activation reads the DISTANCE TO A CENTRE in
## input space, not an affine form. That is a different node architecture
## (centres + widths, with a data-dependent width scale), not a different g,
## and it does not fit this additive bank. See README.md.
##
## Stdlib only, float64 throughout, own Cholesky (no LAPACK dependency).
import std/[math, random, strutils]
type
ActivationKind* = enum
## Which nonlinearity the hidden nodes apply to their affine pre-activation.
## The string values are what `activationName*` returns.
atanTanh = "tanh"
atanRelu = "relu"
atanStep = "step"
ElmConfig* = object
inputDim*, hiddenDim*, outputs*: int
seed*: int64
activation*: ActivationKind # default: atanTanh
lambda*: float64 # ridge penalty on the weights, >= 0
decay*: float64 # sample-weight decay per added sample (rho), in (0,1]
refitEvery*: int # 0 => never refit in train(); 1 => every train();
# >1 => every N train() calls. With 0 the caller
# must call refit() explicitly (batched training).
Elm* = ref object
cfg: ElmConfig
W: seq[float64] # hiddenDim * inputDim, row-major
hs: seq[float64] # hiddenDim, hidden-layer biases
beta: seq[float64] # (hiddenDim+1) * outputs
samples: seq[float64] # n * inputDim inputs
targets: seq[float64] # n * outputs targets
weights: seq[float64] # n sample weights
n: int
sinceRefit: int
diag: ElmDiag
ElmDiag* = object
nSamples*: int
trainRmse*: float64 # weighted RMS of residual at last refit
lastBetaNorm*: float64
const defaultDecay* = 0.98
const defaultLambda* = 1e-6
# Hidden-weight scale per activation, RELATIVE to the shipped 1/sqrt(inputDim).
# tanh is scale-robust: it is curved everywhere, so any spread of pre-activations
# gives rich, near-independent features (hence 1.0 = exactly the shipped init).
# relu is curved only at its kink s=0 and step only at its jump s=0, so with the
# tanh scale the pre-activations barely straddle 0, the units behave like plain
# linear/constant features, the Gram matrix drops rank and Thm 2.2 interpolation
# is lost (measured at scale 1.0: trainRmse 1.1e-1 relu, 3.6e-1 step with 20
# samples in 20 nodes). A wider spread puts the kinks through the data cloud,
# where they can actually cut it.
proc activationWeightScale(kind: ActivationKind): float64 =
case kind
of atanTanh: 1.0
of atanRelu: 8.0
of atanStep: 8.0
# ── activation ──────────────────────────────────────────────────────────────
proc applyActivation*(kind: ActivationKind, x: float64): float64 =
## Pure scalar nonlinearity shared by every hidden node. float64 in, float64
## out, no state, no allocation — safe to call in the innermost refit loop.
##
## atanTanh tanh(x) the original, and the default
## atanRelu max(0, x) linear above 0, flat below
## atanStep 1.0 if x > 0 else 0.0 a hard sign/ramp test
##
## All three are non-polynomial and differentiable almost everywhere, which
## is the only property the ELM interpolation guarantee actually needs. They
## differ in how they distribute gradient/curvature: tanh saturates on both
## sides, relu on one, step on neither (it is piecewise constant, so its
## "gradient" is zero a.e. and lives entirely in its jumps).
case kind
of atanTanh: tanh(x)
of atanRelu: max(0.0, x)
of atanStep: (if x > 0.0: 1.0 else: 0.0)
proc activationName*(kind: ActivationKind): string {.inline.} =
## Short human-readable tag, used in logs and benchmark headers.
$kind
proc parseActivation*(s: string): ActivationKind =
## Case-insensitive name -> kind. Raises ValueError on an unknown name so a
## typo in a config/CLI flag fails loudly instead of silently falling back.
case s.toLowerAscii()
of "tanh": atanTanh
of "relu": atanRelu
of "step": atanStep
else: raise newException(ValueError, "elm: unknown activation '" & s &
"' (expected tanh | relu | step)")
# ── init ────────────────────────────────────────────────────────────────────
proc initElm*(cfg: ElmConfig): Elm =
## Build an ELM. Hidden weights ~ U[-1,1] * 1/sqrt(inputDim).
doAssert cfg.inputDim > 0 and cfg.hiddenDim > 0 and cfg.outputs > 0
new(result)
result.cfg = cfg
if result.cfg.decay <= 0: result.cfg.decay = defaultDecay
if result.cfg.lambda < 0: result.cfg.lambda = defaultLambda
let scale = activationWeightScale(cfg.activation) / sqrt(float64(cfg.inputDim))
var rng = initRand(int(cfg.seed))
result.W = newSeq[float64](cfg.hiddenDim * cfg.inputDim)
for i in 0 ..< result.W.len:
result.W[i] = (rand(rng, 1.0) - 0.5) * 2.0 * scale
# Hidden biases are offsets, not dot products, so they are NOT scaled by
# 1/sqrt(inputDim): they span the whole [-1,1] range, which is what puts the
# tanh units across their nonlinear region and keeps the Gram matrix well
# conditioned (without them the pre-activations are tiny, tanh is effectively
# linear, the features collapse onto nearly the same direction and the exact
# interpolation of Thm 2.2 is lost to float64 round-off).
#
# The bias RANGE is activation-aware, and only for the one-sided activations.
# tanh is two-sided, so [-1,1] straddles its whole nonlinear region and is
# kept EXACTLY as it always was (the default path is bit-identical). relu and
# step are dead for s <= 0: with a symmetric bias ~half the units would start
# dead on inputs near 0 and contribute a constant (relu) or constant zero
# (step) column, so the Gram matrix loses rank and Thm 2.2 interpolation
# fails outright (measured: 20 samples in 20 nodes, trainRmse 0.16 relu /
# 0.41 step). A positive bias range [0,1] puts every unit on its active side.
result.hs = newSeq[float64](cfg.hiddenDim)
let twoSided = result.cfg.activation == atanTanh
for i in 0 ..< result.hs.len:
result.hs[i] = (if twoSided: rand(rng, 1.0) * 2.0 - 1.0
else: rand(rng, 1.0))
result.beta = newSeq[float64]((cfg.hiddenDim + 1) * cfg.outputs)
proc hiddenOf(e: Elm, x: openArray[float64]): seq[float64] =
## Random features `g(a_j . x + b_j)` per `cfg.activation`, appended with
## the constant 1.0 bias column.
let d = e.cfg.inputDim
let L = e.cfg.hiddenDim
result = newSeq[float64](L + 1)
var j = 0
while j < L:
var s = e.hs[j]
for i in 0 ..< d:
s += e.W[j * d + i] * x[i]
result[j] = applyActivation(e.cfg.activation, s)
inc j
result[L] = 1.0
# ── Cholesky: A = L L^T, then solve A x = b (in place) ──────────────────────
proc cholesky(a: var seq[float64], n: int): seq[float64] =
## Lower-triangular factor. Throws ValueError if A is not positive definite.
result = newSeq[float64](n * n)
for i in 0 ..< n:
for j in 0 .. i:
var s = a[i * n + j]
for k in 0 ..< j:
s -= result[i * n + k] * result[j * n + k]
if i == j:
if s <= 0.0:
raise newException(ValueError, "elm: normal matrix not positive definite")
result[i * n + j] = sqrt(s)
else:
result[i * n + j] = s / result[j * n + j]
proc cholSolve(l: seq[float64], n: int, b: seq[float64], m: int): seq[float64] =
## Forward then back substitution, column by column (b is n x m, row-major).
result = newSeq[float64](n * m)
var y = newSeq[float64](n)
for c in 0 ..< m:
for i in 0 ..< n:
var s = b[i * m + c]
for k in 0 ..< i:
s -= l[i * n + k] * y[k]
y[i] = s / l[i * n + i]
for i in countdown(n - 1, 0):
var s = y[i]
for k in i + 1 ..< n:
s -= l[k * n + i] * result[k * m + c]
result[i * m + c] = s / l[i * n + i]
# ── refit ───────────────────────────────────────────────────────────────────
proc refit*(e: Elm) =
## Solve the weighted ridge system over all accumulated samples.
let L = e.cfg.hiddenDim
let n1 = L + 1 # augmented dimension, bias column included
let M = e.cfg.outputs
var G = newSeq[float64](n1 * n1)
var C = newSeq[float64](n1 * M)
var wsum = 0.0
var a: seq[float64]
for i in 0 ..< e.n:
a = e.hiddenOf(e.samples.toOpenArray(i * e.cfg.inputDim, i * e.cfg.inputDim + e.cfg.inputDim - 1))
let w = e.weights[i]
if w == 0.0: continue
wsum += w
for p in 0 ..< n1:
for q in 0 ..< n1:
G[p * n1 + q] += w * a[p] * a[q]
for m in 0 ..< M:
C[p * M + m] += w * a[p] * e.targets[i * M + m]
# Ridge: 1 on the weights, 0 on the bias column (last) — the bias is never
# shrunk. The jitter is a RELATIVE 1e-15 of the largest diagonal, so it keeps
# a lambda = 0 model Cholesky-able on a machine that rounds a zero pivot to
# -1e-18, without leaking a fixed absolute offset into the solution (an
# absolute floor would cost ~floor*||beta||, and ||beta|| is large whenever the
# random features are collinear).
var dmax = 0.0
for p in 0 ..< n1:
dmax = max(dmax, G[p * n1 + p])
for p in 0 ..< n1:
G[p * n1 + p] += e.cfg.lambda * (if p < L: 1.0 else: 0.0) + 1e-15 * dmax
if wsum <= 0.0:
return
e.beta = cholSolve(cholesky(G, n1), n1, C, M)
# weighted RMS of the residual ||a.beta - t||
var res = 0.0
for i in 0 ..< e.n:
a = e.hiddenOf(e.samples.toOpenArray(i * e.cfg.inputDim, i * e.cfg.inputDim + e.cfg.inputDim - 1))
for m in 0 ..< M:
var p = 0.0
for q in 0 ..< n1:
p += a[q] * e.beta[q * M + m]
let d = p - e.targets[i * M + m]
res += e.weights[i] * d * d
var bn = 0.0
for v in e.beta: bn += v * v
e.diag.trainRmse = sqrt(res / (wsum * float64(M)))
e.diag.lastBetaNorm = sqrt(bn)
e.diag.nSamples = e.n
e.sinceRefit = 0
# ── train / infer ───────────────────────────────────────────────────────────
proc train*(e: Elm, x: openArray[float64], t: openArray[float64]) =
## Add one sample (weight 1) after ageing every stored sample by `decay`,
## then refit per the policy.
if x.len != e.cfg.inputDim:
raise newException(ValueError, "elm: input dim mismatch: got " & $x.len &
", expected " & $e.cfg.inputDim)
if t.len != e.cfg.outputs:
raise newException(ValueError, "elm: output dim mismatch: got " & $t.len &
", expected " & $e.cfg.outputs)
for i in 0 ..< e.n:
e.weights[i] *= e.cfg.decay
e.samples.add(x)
e.targets.add(t)
e.weights.add(1.0)
inc e.n
inc e.sinceRefit
# refitEvery == 0 means "accumulate only": the caller owns the refit and
# calls refit() itself. Refitting here on every call is O(n^2*L^2) over a
# batch, which is how the original <=1 check made a 7k-sample training run
# take hours.
if e.cfg.refitEvery == 1 or (e.cfg.refitEvery > 1 and e.sinceRefit >= e.cfg.refitEvery):
e.refit()
proc infer*(e: Elm, x: openArray[float64]): seq[float64] =
## Current output for x. Uses the last fitted beta; no refit.
if x.len != e.cfg.inputDim:
raise newException(ValueError, "elm: input dim mismatch: got " & $x.len &
", expected " & $e.cfg.inputDim)
let a = e.hiddenOf(x)
let n1 = e.cfg.hiddenDim + 1
result = newSeq[float64](e.cfg.outputs)
for m in 0 ..< e.cfg.outputs:
var p = 0.0
for q in 0 ..< n1:
p += a[q] * e.beta[q * e.cfg.outputs + m]
result[m] = p
proc setOnlineParams*(e: Elm, decay: float64, refitEvery: int) =
## Switch a loaded (or fresh) model into ONLINE mode: set the per-sample
## forgetting factor and the refit cadence. Kept as a proc because `cfg` is
## private; the offline loader fixes decay=1.0/refitEvery=0 (batch), the
## in-game gun overrides both here.
if decay > 0.0 and decay <= 1.0: e.cfg.decay = decay
if refitEvery >= 0: e.cfg.refitEvery = refitEvery
proc reset*(e: Elm) =
## Drop all samples and zero the output layer. The hidden layer is NOT redrawn:
## it is the frozen, seeded part of the model.
e.samples.setLen(0)
e.targets.setLen(0)
e.weights.setLen(0)
e.n = 0
e.sinceRefit = 0
for i in 0 ..< e.beta.len: e.beta[i] = 0.0
e.diag = ElmDiag()
# ── offline weight export / load ────────────────────────────────────────────
# An ELM trained offline has no use for its sample store: only the three
# matrices matter (hidden W, hidden biases hs, output beta). These two procs
# move them in and out of a live model so a trained model can be shipped as a
# data file and loaded at bot startup instead of being retrained in-game.
type ElmWeights* = object
W*: seq[float64] ## hiddenDim * inputDim, row-major
hs*: seq[float64] ## hiddenDim
beta*: seq[float64] ## (hiddenDim+1) * outputs
proc exportWeights*(e: Elm): ElmWeights =
ElmWeights(W: e.W, hs: e.hs, beta: e.beta)
proc loadWeights*(e: Elm, w: ElmWeights) =
## Overwrite the matrices. Sizes must match the config exactly.
doAssert w.W.len == e.cfg.hiddenDim * e.cfg.inputDim
doAssert w.hs.len == e.cfg.hiddenDim
doAssert w.beta.len == (e.cfg.hiddenDim + 1) * e.cfg.outputs
e.W = w.W
e.hs = w.hs
e.beta = w.beta
e.diag.trainRmse = NaN # stale: the model is no longer the one that was fitted
e.diag.lastBetaNorm = NaN
proc diagnostics*(e: Elm): ElmDiag =
e.diag
@@ -0,0 +1,140 @@
## The ELM gun's FEATURE VECTOR — one definition, shared by the offline trainer
## and the in-game gun, so the model can never drift from its inputs.
##
## This is the MOVEMENT-PREDICTION gun's feature set. The label it is trained on
## is the correction from the plain geometric intercept to the enemy's TRUE
## impact position (`tools/elm_bench/extract_predict.py`), so the features are
## enemy-motion-centric: a window of recent scan-to-scan displacement vectors,
## plus the single-frame geometry the old gun used.
##
## Every quantity comes from the shooter's own state and its ScannedBotEvent
## history (scans are exact, one per tick in game). No oracle.
##
## Stdlib only, so the offline trainer and the in-game gun share it verbatim.
import std/math
const
WinCap* = 8 ## motion window: scans kept, newest first
## Feature vector layout (FeatureDim = 32):
## 0..13 7 newest-to-oldest displacement vectors, each divided by its own
## tick gap and by 16 px/tick: [dx0,dy0, dx1,dy1, ... dx6,dy6]
## 14..16 newest speed, window mean speed, window speed sd (all /10)
## 17,18 sin/cos of the newest displacement heading
## 19,20 sin/cos of the turn rate (angle between the two newest legs)
## 21 curvature |dtheta| / speed, clamped to 1
## 22..24 belief distance /1000, sin/cos of the body-relative bearing
## 25 our own speed /10
## 26 bullet speed /20
## 27 believed time of flight /30
## 28 predErr: base-intercept bearing minus current bearing, /PI
## 29 target lateral velocity /10
## 30 closing speed /10
## 31 line-of-sight rate (lat vel / dist)
FeatureDim* = 32
featureNames* = [
"dx0", "dy0", "dx1", "dy1", "dx2", "dy2", "dx3", "dy3",
"dx4", "dy4", "dx5", "dy5", "dx6", "dy6",
"speed", "speedMean", "speedSd",
"sinHead", "cosHead", "sinTurn", "cosTurn", "curve",
"dist", "sinRel", "cosRel", "ownSpeed", "bulletSpd", "tof",
"predErr", "tgtLatVel", "closing", "losRate",
]
type
GunBelief* = object
## Everything the gun needs, all of it legitimately observable.
everScanned*: bool
selfX*, selfY*: float ## our position NOW
selfHeading*: float ## our body heading, radians (0 = east, CCW +)
selfSpeed*: float
ownDisp*: float ## how far WE moved since the last scan (px)
scanAge*: float ## ticks since the last scan
scanGap*: float ## ticks between the last two scans (0 if <2)
ex*, ey*: float ## dead-reckoned target position NOW
vx*, vy*: float ## estimated target velocity (px/tick)
bulletSpeed*: float ## physical bullet speed, 20 - 3*power
power*: float ## the power we are about to (or did) fire at
gunHeat*: float
## motion window, newest first. winTick[k] is the tracker tick of the
## k-th newest scan; winX/winY the scanned position.
winX*, winY*: array[WinCap, float]
winTick*: array[WinCap, int]
winN*: int
proc wrapAngle*(a: float): float =
## wrap to (-pi, pi]
var r = a
while r > PI: r -= 2 * PI
while r <= -PI: r += 2 * PI
r
proc buildFeatures*(b: GunBelief): array[FeatureDim, float64] =
## The feature vector. Mirrors extract_predict.py exactly. All-zero when we
## have never scanned the target.
if not b.everScanned:
return default(array[FeatureDim, float64])
let de = hypot(b.ex - b.selfX, b.ey - b.selfY)
let ang = arctan2(b.ey - b.selfY, b.ex - b.selfX) ## line-of-sight bearing
let rel = wrapAngle(ang - b.selfHeading)
let sp = hypot(b.vx, b.vy)
let lat = -b.vx * sin(ang) + b.vy * cos(ang)
let rad = b.vx * cos(ang) + b.vy * sin(ang)
let tof = de / b.bulletSpeed
let px = b.ex + b.vx * tof
let py = b.ey + b.vy * tof
let base = arctan2(py - b.selfY, px - b.selfX)
let predErr = wrapAngle(base - ang)
# --- motion window: displacement of leg k = scan k -> scan k+1 ---
var spdSum = 0.0
var spdSq = 0.0
var nLeg = 0
var head = 0.0
var dtheta = 0.0
if b.winN >= 2:
var dxs: array[WinCap - 1, float]
var dys: array[WinCap - 1, float]
for k in 0 ..< min(b.winN, WinCap) - 1:
let gap = float(max(b.winTick[k] - b.winTick[k + 1], 1))
let dx = (b.winX[k] - b.winX[k + 1]) / gap
let dy = (b.winY[k] - b.winY[k + 1]) / gap
dxs[k] = dx
dys[k] = dy
result[2 * k] = dx / 16.0
result[2 * k + 1] = dy / 16.0
let s = hypot(dx, dy)
spdSum += s
spdSq += s * s
inc nLeg
let nf = float(nLeg)
let sMean = spdSum / nf
head = arctan2(dys[0], dxs[0])
if nLeg >= 2:
let phead = arctan2(dys[1], dxs[1])
dtheta = wrapAngle(head - phead)
result[14] = sp / 10.0
result[15] = sMean / 10.0
result[16] = sqrt(max(spdSq / nf - sMean * sMean, 0.0)) / 10.0
result[17] = sin(head)
result[18] = cos(head)
result[19] = sin(dtheta)
result[20] = cos(dtheta)
result[21] = min(abs(dtheta) / max(sMean, 1e-6), 1.0)
else:
result[14] = sp / 10.0
result[15] = sp / 10.0
result[22] = de / 1000.0
result[23] = sin(rel)
result[24] = cos(rel)
result[25] = b.selfSpeed / 10.0
result[26] = b.bulletSpeed / 20.0
result[27] = tof / 30.0
result[28] = predErr / PI
result[29] = lat / 10.0
result[30] = -rad / 10.0
result[31] = lat / max(de, 1.0)
for i in 0 ..< FeatureDim:
if classify(result[i]) in {fcNan, fcInf, fcNegInf}: result[i] = 0.0
@@ -0,0 +1,345 @@
## The ELM GUN — a movement-prediction corrector on top of the geometric
## intercept.
##
## ## What it predicts
##
## The ELM predicts the ENEMY'S FUTURE POSITION, expressed as a correction to
## the plain geometric intercept: at fire time the classic intercept gives a
## base aim point, the ELM estimates `trueImpactBearing - baseBearing` from the
## enemy's recent motion window, and the gun adds the two. That is a movement
## predictor, NOT the old opponent-aim-bias model (which measured how far the
## OTHER bot's shots missed and is deleted).
##
## ## The baseline and the gate
##
## `heuristicAim` is the plain geometric intercept — dead-reckon the target from
## the last two scans, lead it by d/bulletSpeed. The learned correction is
## applied ONLY when `|correction| > gateTau`, the threshold calibrated on
## held-out folds (see `train_predict.nim`); below it the gun returns the exact
## geometric aim, so a small noisy nudge can never make the ELM worse than the
## baseline.
##
## ## Weights file
##
## `elm_gun_weights.txt` next to this file, written by
## `tools/elm_bench/train_predict.nim`. Plain text, one matrix per line, flat:
##
## # comment lines are ignored
## <inputDim> <hiddenDim> <outputs> <lambda> <decay> <seed> <activation>
## W <hiddenDim*inputDim values> hidden weights, ROW-major
## HS <hiddenDim values> hidden-layer biases, b_j
## BETA <(hiddenDim+1)*outputs vals> output weights, ROW-major
## TRAIN_RMSE <v> training RMSE at export time; diagnostic only, unused.
## GATE_TAU <v> correction magnitude below which correction is 0.
##
## It is a data file, not code: deleting it costs the bot its learned correction,
## nothing else.
##
## ## In-game honesty
##
## Nothing here reads a ground truth. `GunBelief` is assembled by the caller
## from the bot's own state and its own scan history, and `buildFeatures`
## (elm_features.nim) is the same function the trainer fed the corpus through.
import std/[math, os, sequtils, strutils]
import ./elm
import ./elm_features
const
DefaultWeightsFile* = "elm_gun_weights.txt" ## next to THIS source file
FirePower* = 2.0'f64 ## The corpus is dominated by
## mid-power shots (1.95 is
## its mode, 2795 rows; power 3.0
## has 61), and `power` /
## `bulletSpd` ARE model
## features, so firing at 2.0
## keeps the in-game feature
## distribution inside the
## trained one. Damage per hit
## is 8 instead of 12.
MaxAimShift* = 0.5 ## rad. The learned correction is clamped: the fit law is
## label ~= 0.87 * predErr + 0.04 rad, but a 0.5 rad
## correction is already a full miss at any range, and an
## unclamped outlier on a stale belief would point the
## gun into the wall.
## ── ONLINE LEARNING knobs (see README "Online-learning gun") ────────────
OnlineDecay* = 0.999 ## forgetting within the battle (reused tuning)
OnlineRefitEvery* = 25 ## shots between closed-form refits (reused tuning)
OnlineMinSamples* = 12 ## gate stays CLOSED below this many online samples
GateRatio* = 0.95 ## gate opens only when modelErr < ratio * zeroErr
OnlineEmaAlpha* = 0.08 ## EMA memory for the held-out gate error (~12 samples)
TraceCap* = 256 ## per-tick enemy position history for delayed labels
TraceTolTicks* = 3 ## label lookup tolerance: nearest scan within this
MaxPending* = 64 ## fired-but-unresolved shots kept at once
type
ElmGun* = ref object
model*: Elm ## the model, trained ONLINE during the battle
loaded*: bool
gateTau*: float ## |correction| below this -> geometric aim
lastCorrection*: float ## last raw ELM output, rad — the calibration
## probe the battle harness reads
## ── online state ──────────────────────────────────────────────────────
online*: bool ## true: feed delayed-label samples in-game
priorBeta*: seq[float64] ## the loaded output layer, BEFORE scaling
priorScale*: float64 ## 0.0 = neutral start; >0 = weak-prior start
pending*: seq[PendingShot] ## fired shots whose true impact is not due yet
traceTick*: seq[int] ## per-tick enemy positions (delayed labels)
traceX*, traceY*: seq[float64]
nOnline*: int ## samples resolved for THIS opponent
modelErr*: float64 ## EMA of (model pred - label)^2, held-out style
zeroErr*: float64 ## EMA of label^2 = zero-correction error
gateOpen*: bool ## novelty gate: correction applied only if true
PendingShot* = object
## One fired shot waiting for its label. Keyed by `dueTick`.
feat*: array[FeatureDim, float64]
base*: float64 ## geometric intercept bearing at fire time
selfX*, selfY*: float64 ## our position at fire time
dueTick*: int ## fire tick + time-of-flight in ticks
GunAim* = object
aim*: float ## ABSOLUTE bearing (rad) to point the gun at
x*, y*: float ## the same point as absolute coordinates
## (GunPrediction's contract, see
## common_libs/gun_harness/gun_interface.nim)
confidence*: float ## 0.0 = no signal: this is a deterministic
## geometric aim, it casts no composite vote
correction*: float ## the learned part, 0 for the baseline
proc defaultWeightsPath(): string =
## Resolved at compile time from this file's own location, so the current
## working directory at bot start does not matter.
currentSourcePath().parentDir / DefaultWeightsFile
proc readFloats(f: File, n: int, path: string): seq[float64] =
## `n` space-separated floats, spread over as many lines as needed.
result = newSeq[float64](n)
var got = 0
var line: string
while got < n:
if f.readLine(line) == false:
echo "[elm_gun] ", path, ": truncated, wanted ", n, " floats, got ", got
return @[]
for t in line.strip().splitWhitespace():
if got >= n: break
result[got] = t.parseFloat()
inc got
if got < n: return @[]
proc loadWeightsFile(g: ElmGun, path: string): bool =
## Parse the format above into the live ELM. Returns false (and says why)
## instead of raising: a bot with no gun is still a working bot, and the
## harness must be able to report "ELM unavailable" rather than crash.
if not fileExists(path):
echo "[elm_gun] no weights at ", path, " — gun disabled"
return false
var cfg: ElmConfig
var haveCfg = false
var w, hs, beta: seq[float64]
var f = open(path, fmRead)
defer: f.close()
var line: string
while f.readLine(line):
let t = line.strip()
if t.len == 0 or t.startsWith("#"): continue
let parts = t.splitWhitespace()
case parts[0]
of "W": w = readFloats(f, cfg.hiddenDim * cfg.inputDim, path)
of "HS": hs = readFloats(f, cfg.hiddenDim, path)
of "BETA": beta = readFloats(f, (cfg.hiddenDim + 1) * cfg.outputs, path)
of "TRAIN_RMSE": discard
of "GATE_TAU": g.gateTau = parts[1].parseFloat()
else:
# header row
cfg = ElmConfig(inputDim: parts[0].parseInt(), hiddenDim: parts[1].parseInt(),
outputs: parts[2].parseInt(), lambda: parts[3].parseFloat(),
decay: parts[4].parseFloat(), seed: parseBiggestInt(parts[5]).int64,
activation: parseActivation(parts[6]), refitEvery: 0)
haveCfg = true
continue
# a matrix tag: an empty read means the file was truncated mid-matrix
if (parts[0] == "W" and w.len == 0) or (parts[0] == "HS" and hs.len == 0) or
(parts[0] == "BETA" and beta.len == 0): return false
if not haveCfg or w.len == 0 or hs.len == 0 or beta.len == 0:
echo "[elm_gun] ", path, ": incomplete weight file — gun disabled"
return false
if cfg.inputDim != FeatureDim:
echo "[elm_gun] ", path, ": trained for ", cfg.inputDim, " features, this ",
"build has ", FeatureDim, " — gun disabled"
return false
g.model = initElm(cfg)
g.model.loadWeights(ElmWeights(W: w, hs: hs, beta: beta))
g.loaded = true
true
proc initElmGun*(path: string = "", priorScale: float64 = 0.0): ElmGun =
## Build the gun and load its hidden layer + output prior. `priorScale = 0`
## starts NEUTRAL (zero output weights, learns purely online); `priorScale > 0`
## starts from the pooled pretrained `beta` scaled down by that factor. The
## hidden layer is always the pretrained one so the two arms share W/hs and
## differ only in the output-layer starting point.
new(result)
result.priorScale = priorScale
result.online = true
if not loadWeightsFile(result, if path.len > 0: path else: defaultWeightsPath()):
return
# Online mode: reuse the held-out-validated decay/refit tuning instead of the
# batch defaults the weights file was exported with (decay 1.0 / refit 0).
result.model.setOnlineParams(OnlineDecay, OnlineRefitEvery)
result.priorBeta = result.model.exportWeights().beta
if priorScale == 0.0:
result.model.reset() # neutral: zero beta, no samples
else:
var b = newSeq[float64](result.priorBeta.len)
for i in 0 ..< b.len: b[i] = result.priorBeta[i] * priorScale
let w = result.model.exportWeights()
result.model.loadWeights(ElmWeights(W: w.W, hs: w.hs, beta: b))
proc resetOnline*(g: ElmGun) =
## New opponent => drop every online sample and restore the starting output
## layer (neutral, or the scaled pooled prior). Hidden W/hs are never redrawn.
g.pending.setLen(0)
g.traceTick.setLen(0)
g.traceX.setLen(0)
g.traceY.setLen(0)
g.nOnline = 0
g.modelErr = 0.0
g.zeroErr = 0.0
g.gateOpen = false
g.model.reset()
if g.priorScale > 0.0 and g.priorBeta.len > 0:
var b = newSeq[float64](g.priorBeta.len)
for i in 0 ..< b.len: b[i] = g.priorBeta[i] * g.priorScale
let w = g.model.exportWeights()
g.model.loadWeights(ElmWeights(W: w.W, hs: w.hs, beta: b))
proc noteEnemyAt*(g: ElmGun, tick: int, x, y: float64) =
## Append one observed enemy position to the trace that delayed labels read.
g.traceTick.add tick
g.traceX.add x
g.traceY.add y
if g.traceTick.len > TraceCap:
g.traceTick.delete(0)
g.traceX.delete(0)
g.traceY.delete(0)
proc tracePos(g: ElmGun, dueTick: int): tuple[ok: bool, x, y: float64] =
## Nearest traced enemy position to `dueTick`, within TraceTolTicks.
var best = TraceTolTicks + 1
for i in 0 ..< g.traceTick.len:
let dt = abs(g.traceTick[i] - dueTick)
if dt < best:
best = dt
result = (true, g.traceX[i], g.traceY[i])
proc updateGate(g: ElmGun) =
## Novelty gate. Closed until enough ONLINE samples exist, then open only while
## the model predicts the true correction better than assuming zero. Being
## closed means the exact geometric intercept — never worse than baseline.
if g.nOnline < OnlineMinSamples:
g.gateOpen = false
else:
g.gateOpen = g.modelErr < GateRatio * g.zeroErr
proc feedSample*(g: ElmGun, feat: openArray[float64], label: float64) =
## One resolved delayed-label sample. The CURRENT model is scored against the
## label BEFORE it trains on it, so `modelErr` is a genuine held-out error, and
## `zeroErr` is what always aiming at the plain intercept would have cost.
if g.nOnline > 0:
let pred = g.model.infer(feat)[0]
let e = pred - label
let a = OnlineEmaAlpha
g.modelErr = (1.0 - a) * g.modelErr + a * e * e
g.zeroErr = (1.0 - a) * g.zeroErr + a * label * label
g.model.train(feat, @[label])
inc g.nOnline
g.updateGate()
proc recordShot*(g: ElmGun, feat: array[FeatureDim, float64], base, selfX,
selfY: float64, dueTick: int) =
## Enqueue a fired shot; its label only exists `tof` ticks from now.
if g.pending.len >= MaxPending:
g.pending.delete(0)
g.pending.add PendingShot(feat: feat, base: base, selfX: selfX, selfY: selfY,
dueTick: dueTick)
proc drainPending*(g: ElmGun, nowTick: int) =
## Resolve (or drop) every shot whose flight time has elapsed. Reads the
## enemy's actual position from the trace and trains on
## wrap(trueImpactBearing - geometricInterceptBearing), the validated label.
var i = 0
while i < g.pending.len:
let p = g.pending[i]
if nowTick < p.dueTick:
inc i
continue
let tp = g.tracePos(p.dueTick)
if tp.ok:
let trueBearing = arctan2(tp.y - p.selfY, tp.x - p.selfX)
g.feedSample(p.feat, wrapAngle(trueBearing - p.base))
g.pending.delete(i)
proc heuristicAim*(gun: ElmGun, b: GunBelief, power: float64 = FirePower): float =
## Baseline A: plain geometric intercept, no learning. Returns the ABSOLUTE
## bearing to aim at, or NaN when there is no belief at all.
if not b.everScanned: return NaN
let v = 20.0 - 3.0 * power
let d = hypot(b.ex - b.selfX, b.ey - b.selfY)
let tof = d / v # one iteration, exact for a constant bullet speed
arctan2(b.ey + b.vy * tof - b.selfY, b.ex + b.vx * tof - b.selfX)
proc elmCorrection*(g: ElmGun, b: GunBelief, power: float64 = FirePower): float =
## The ELM's predicted aim error in radians, clamped to +-MaxAimShift.
## NaN when the model is unavailable or we have never scanned anything.
if not g.loaded or not b.everScanned: return NaN
if g.online and not g.gateOpen:
return 0.0 # novelty gate closed: exact intercept
var bb = b
bb.power = power
bb.bulletSpeed = 20.0 - 3.0 * power # physical speed, matches heuristicAim
let feat = buildFeatures(bb)
let corr = g.model.infer(feat.toSeq())[0]
g.lastCorrection = corr
if abs(corr) <= g.gateTau:
return 0.0 # gate closed: exact geometric aim
clamp(corr, -MaxAimShift, MaxAimShift)
proc predictAim*(g: ElmGun, b: GunBelief, power: float64 = FirePower,
useElm: bool = true): GunAim =
## The gun's per-tick output, GunPrediction-shaped. `useElm = false` is the
## pure-heuristic baseline; it is the same call with the learned term switched
## off, so the two differ by exactly one thing.
let base = heuristicAim(g, b, power)
if base.isNaN: return GunAim(aim: NaN, confidence: 0.0)
# One bearing, ONE coordinate computation: fold the learned term (when the
# model is active and returns a number) into `aim` first, then derive x/y
# from the final bearing exactly once. The old version recomputed x/y for the
# baseline and again for the ELM aim, which is how the two could drift apart.
var aim = base
if useElm and g.loaded:
let corr = elmCorrection(g, b, power)
if not corr.isNaN:
aim = base + corr
result.confidence = abs(corr)
result.correction = corr
let d = hypot(b.ex - b.selfX, b.ey - b.selfY)
result.aim = aim
result.x = b.selfX + d * cos(aim)
result.y = b.selfY + d * sin(aim)
proc gunAimErrorDeg*(aimRad, gunDirDeg: float): float =
## Short-way gun error in DEGREES between a predicted ABSOLUTE bearing
## (`aimRad`, radians, 0 = east CCW+) and the gun's current heading
## (`gunDirDeg`, degrees — the API's unit).
##
## THE single rad->deg conversion point at the fire-decision boundary. The
## name carries the output unit, so `abs(gunAimErrorDeg(...)) <= FireSlopDeg`
## can only ever compare degrees against degrees. The historical bug compared
## a degree error against `degToRad(FireSlopDeg)`, i.e. 0.052 deg of slop.
## Matches the API's `normalizeRelativeAngle` ([-180, 180)) without pulling
## the API into this stdlib-only module.
result = (radToDeg(aimRad) - gunDirDeg) mod 360.0
if result >= 180.0: result -= 360.0
elif result < -180.0: result += 360.0
File diff suppressed because one or more lines are too long
@@ -0,0 +1,161 @@
## The radar — one module, the whole of it. No movement, no gun.
##
## Every tick `commandRadar()` issues EXACTLY ONE radar command, before `go()`,
## on every path. There is no "idle" branch: the 360 sweep is not a mode we
## fall back INTO, it is the command the other branch replaces. That is why
## switching costs zero turns.
##
## TWO commands, chosen by the only fact the bot knows for sure:
##
## exactly one enemy alive + a target in hand -> LOCK (servo onto its bearing)
## anything else -> SWEEP (45 deg/tick, the cap,
## a full revolution every 8 ticks)
##
## The sweep does double duty and needs no separate "melee" mode: it is both the
## search for a target we do not have yet and the right answer for 2+ enemies
## (a full revolution re-scans every enemy 8x sooner than any narrowed sweep,
## and locking one of several is worthless).
##
## Derived from ModularBot's radar (Davide Cappellini, Apache-2.0), i.e. from
## common_libs/radar_lock/radar_lock.nim (`doRadar`) and common_libs/radars/
## melee_scan.nim, which ModularBot picks between per tick in exactly this way
## (`let targetMode = if getEnemyCount() == 1: 0 else: 1` — ModularBot.nim, the
## "Auto-switch radar based on the SERVER's live enemy count" block). The one
## idea taken from it is the OVERSHOOT, and it is the whole reason the lock
## works: the rate is the delta to the target's bearing plus 5 deg PAST it, so
## the radar crosses the bearing every tick instead of settling on it — which
## is exactly what produces a fresh ScannedBotEvent every tick. Turning by the
## bare error (or holding inside a deadzone) parks the radar on the bearing and
## the scans stop; the target then has to be re-found by the sweep, which is the
## delay this replaces. common_libs/ is never edited in place.
##
## ANGLES: 0° = east, positive = counter-clockwise, so positive = a LEFT turn
## (proof in ../README.md; the API's own doc comment claiming "0 = North" for
## `directionTo` contradicts its code and is wrong).
import std/math
import robocode_tankroyale_botapi
const
MaxRadarTurn* = 45.0 # deg/tick, the radar's hard cap (the sweep)
OvershootDeg* = 5.0 # how far past the target's bearing the lock aims;
# guarantees the bearing is swept every tick
FreshScanTurns* = 1 # how many ticks a remembered target stays usable.
# The 5 deg overshoot makes the lock CROSS the
# target's bearing every tick, so a fresh
# ScannedBotEvent arrives every tick and this
# counter never gets past 1. Hence one tick without a
# scan means the target has genuinely left the radar
# cone: there is nothing left to wait for, sweeping
# re-finds it faster than a stale lock could.
# The target in hand: the position of the last bot we scanned. Absolute
# position, not a remembered bearing, so the delta is recomputed against the
# radar's CURRENT heading every tick and the lock keeps correcting a target
# that (and a radar that) has moved since the scan.
var
targetX, targetY: float
targetSeen: bool
scanlessTicks: int
# ── scan history (added for the ELM gun) ─────────────────────────────────────
# The gun needs THREE things the plain radar throws away: the previous scan (to
# estimate the target's velocity), how many ticks ago the last scan was (the
# dead-reckoning age), and how far WE moved in between (one of the 22 features).
# The above variables alone cannot express any of them, so the two most recent
# scans are kept here. Two is enough — a velocity from exactly two samples is
# all the corpus model was fitted with (extract_realistic.py uses hist[-2..-1]).
type ScanHistory* = object
tick*: int ## tracker tick of the scan (scanlessTicks-free counter)
x*, y*: float ## scanned position
ownX*, ownY*: float ## OUR position on that same tick (for own displacement)
const ScanWinCap* = 8 ## motion-window length kept for the ELM gun
const MaxVelGap* = 3 ## ticks. Two scans farther apart than this give a
## velocity that averages over too much motion to be
## trusted; the corpus velocity is a one-tick delta,
## so anything much wider is a different estimator and
## worse than not extrapolating at all.
var
scanTick*: int ## incremented once per commandRadar() call
lastScan*, prevScan*: ScanHistory
haveLast*, havePrev*: bool
## window of the most recent scans, newest at index 0 (ELM gun features)
winTick*: array[ScanWinCap, int]
winX*, winY*: array[ScanWinCap, float]
winN*: int
proc onScanFull*(tick: int, x, y, ownX, ownY: float) =
## Full-history variant of `onScan`, called by the bot. Shifts the scan
## history (and the ELM motion window) instead of overwriting a single slot.
prevScan = lastScan
havePrev = haveLast
lastScan = ScanHistory(tick: tick, x: x, y: y, ownX: ownX, ownY: ownY)
haveLast = true
if winN > 0 and winTick[0] == tick:
winX[0] = x; winY[0] = y # same-tick rescans replace, do not shift
else:
for k in countdown(ScanWinCap - 1, 1):
winX[k] = winX[k - 1]; winY[k] = winY[k - 1]; winTick[k] = winTick[k - 1]
winX[0] = x; winY[0] = y; winTick[0] = tick
if winN < ScanWinCap: inc winN
proc scanAge*(now: int): float =
## Ticks since the last scan, or -1 when we have never scanned anything.
if not haveLast: -1.0 else: float(now - lastScan.tick)
proc scanGap*(): float =
## Ticks between the last two scans; 0 when there is no earlier scan (a
## zero gap is what the corpus uses for "velocity unknown").
if not (haveLast and havePrev): 0.0 else: float(lastScan.tick - prevScan.tick)
proc targetVelocity*(): tuple[vx, vy: float] =
## px/tick, from the last two scans. (0,0) when there is no gap to measure
## over or the gap is too wide to be a trustworthy one-tick estimate — the
## corpus uses the same (0,0) convention for "velocity unknown".
if not (haveLast and havePrev): return (0.0, 0.0)
let gap = lastScan.tick - prevScan.tick
if gap <= 0 or gap > MaxVelGap: return (0.0, 0.0)
((lastScan.x - prevScan.x) / float(gap), (lastScan.y - prevScan.y) / float(gap))
proc ownDisp*(selfX, selfY: float): float =
## How far WE have moved since the last scan (0 if we never scanned).
if not haveLast: 0.0 else: hypot(selfX - lastScan.ownX, selfY - lastScan.ownY)
proc onScan*(x, y: float) =
## Remember a scanned bot as the target. Issues no command: `onScannedBot`
## runs AFTER go() has already sent this tick's intent.
## Kept for backward compatibility: it drives the radar's own lock, and the
## bot calls `onScanFull` when it also wants the history.
targetX = x
targetY = y
targetSeen = true
scanlessTicks = 0
proc initRadar*() =
## Called ONCE, before the first tick: the radar is now programmed and working,
## so it claims its own colours — radar and scan arc go BLACK.
## COLOUR CONVENTION: white = "not programmed yet", black = "programmed and
## running". The bot starts all WHITE (ChimeraBot.nim); the radar paints
## ITSELF black the moment it takes control, and body/turret/gun stay white
## forever (they are still unprogrammed — this bot never moves, never fires).
## Set once here, never per tick: the colour never changes, so re-sending it
## every tick would only cost intent bandwidth.
setRadarColor(BLACK)
setScanColor(BLACK)
proc commandRadar*() =
## Command the radar for THIS tick. Called from run() before go().
inc scanTick
if targetSeen: inc scanlessTicks
if getEnemyCount() == 1 and targetSeen and scanlessTicks <= FreshScanTurns:
var turn = normalizeRelativeAngle(
directionTo(getX(), getY(), targetX, targetY) - getRadarDirection())
if turn < 0.0: turn -= OvershootDeg
else: turn += OvershootDeg
setRadarTurnRate(turn.clamp(-MaxRadarTurn, MaxRadarTurn))
return
targetSeen = false # nothing usable to lock on: sweep
setRadarTurnRate(MaxRadarTurn)
@@ -0,0 +1,805 @@
## TFIL — "The Floor Is Lava" survival movement, vendored into ChimeraBot.
##
## Ported from `common_libs/movements/the_floor_is_lava.nim` (the authoritative
## implementation) with its DEFAULT behaviour, kept byte-for-byte. Self-contained
## on purpose: this bot folder never imports from `common_libs`, so the harness
## types (WorldState / EnemyInfo / MoveCommand) and the enemy-fire detector are
## inlined here rather than imported.
##
## WHAT WAS DROPPED (all of it default-OFF or diagnostic-only in the source, so
## the shipped decision path is unchanged):
## * the whole `TR_TFIL_*` / `TR_FIRE_*` env-port surface (knobs baked in as
## consts below with the source's defaults): TILE_REPLAN, COMMIT_TICKS, NO_REV,
## COMMIT_LOG, COMMIT_ARRIVAL, COMMIT_MARGIN, NOREV_SPEED, TURN_BIAS,
## TURN_REF_DEG, DANGER_THRESHOLD, DIAG, GEO_MODE/GEO_TAU, ARRIVE_TICKS,
## HOLD_WHEN_TRAPPED, HOLD_MAX_TICKS, HEAT_TIME/TAU/POWER_GAIN,
## CORRIDOR_TICKS, CORRIDOR_HEAT, WALL_HOTNESS/RADIANCE, BULLET_CORE/AURA,
## PILLAR_ON, FIRE_DIAG, FIRE_FIX (always on here), FIRE_LAG (always 0 here).
## Consequences, all of them no-ops at the defaults: the time-indexed heat
## model and the damage-proportional magnitude scale are OFF (every heat is
## exactly the flat one), corridors run to the wall, the virtual centre pillar
## is absent (0/0), the pick is a UNIFORM draw (no turn / no-rev / geometry
## tilt), no arrival bound, no bounded hold, no commit diagnostics.
## * debug graphics — restored below, but behind ` ` (off by default,
## since the SVG payload costs time every tick).
## * the pure bookkeeping fields (loss histogram, lastPick*, log-only vars).
##
## ANGLES: 0 deg = east, counter-clockwise positive (Tank Royale standard).
import std/[math, random]
import robocode_tankroyale_botapi
import robocode_tankroyale_botapi/color # graphics comes re-exported by the import above
## ── Debug graphics ──────────────────────────────────────────────────────────
## OFF by default: the drawing is a real per-tick cost (an SVG buffer sent to
## the server) and nothing else needs it. Turn it ON at compile time:
## nim c -d:tfilDebug ...
## or `nimble runBot -d:tfilDebug`. Everything below is inside
## `when defined(tfilDebug)`, so the OFF build contains none of it.
##
## The API has no Graphics object to hand around: the procs are global, the SVG
## buffer is drained and flushed by the API after every tick. `computeMove` runs
## before `go()`, which is exactly where drawing belongs.
# ── Harness types (vendored from gun_harness/movement_interface) ─────────────
type
EnemyInfo* = object
id*: int
x*, y*: float
heading*, speed*, energy*: float
lastSeenTick*: int
WorldState* = object
enemyX*, enemyY*: float
enemySpeed*, enemyHeading*: float
selfX*, selfY*: float
selfSpeed*, selfHeading*: float
selfRadarHeading*: float
selfEnergy*: float
enemyEnergy*: float
arenaWidth*, arenaHeight*: float
tick*: int
enemies*: seq[EnemyInfo]
MoveCommand* = tuple[speed: float, turnRate: float]
## speed: target speed in px/tick (clamped to +-8 by the bot API);
## turnRate: body turn rate in degrees/tick.
# ── Tunables (source defaults, baked in) ────────────────────────────────────
const
GridSize = 36.0
MaxSpeed = 8.0
BulletCoreRadiusMin = 9.0 ## core radius at power 0.1
BulletCoreRadiusMax = 54.0 ## core radius at power 3.0
BulletAuraExtMin = 36.0 ## aura extension at power 3.0 (slow)
BulletAuraExtMax = 54.0 ## aura extension at power 0.1 (fast)
BulletCoreHeat = 10.0 ## lava per bullet-overlapping tile
BulletAuraHeat = 5.0 ## lava for aura ring tiles
EnemyCoreRadius = 18.0 ## half of 36px body
EnemyAuraRadius = 54.0 ## 18 + 36
EnemyCoreHeat = 40.0 ## lava per tile overlapping the enemy body circle
EnemyAuraHeat = 10.0 ## lava per tile in the enemy aura ring
CorridorHeat = 20.0 ## lava per corridor-overlapping tile
WallHotness = 30.0 ## peak wall radiance
WallRadiance = 10.0 ## wall radiance falloff
CommitTicks = 15 ## ticks to commit to a dodge point
MinCommitTicks = 5 ## must commit this long before a danger replan
LockRadiusTiles = 15.0 ## freeze the committed dodge while a tracked
## bullet is this many tiles away or closer
DangerReplanThreshold = 25.0 ## replan on serious threats only (bullet core)
CoolestLevels = 2 ## how many distinct lava values count as "cool"
MaxTrackedBullets = 20 ## hard cap on tracked bullets
PathSampleStep = 18.0 ## ~half a tile
PathDangerThreshold = 10.0 ## max lava on path; above = unsafe
ArriveRadius = 18.0 ## "we are on the committed tile"
HullTicks = 50 ## reachable-hull planning horizon
FireFix = true ## corrected energy-drop detection
proc bulletRadii(power: float): tuple[core, aura: float] =
let t = (power - 0.1) / 2.9
let core = BulletCoreRadiusMin + t * (BulletCoreRadiusMax - BulletCoreRadiusMin)
let auraExt = BulletAuraExtMax - t * (BulletAuraExtMax - BulletAuraExtMin)
(core, core + auraExt)
# ── Enemy-fire detector (vendored from movement_harness/fire_tracker) ────────
#
# One enemy energy reading in, the confirmed fire powers out. Two server facts
# are corrected for: `BULLET_HIT_ENERGY_GAIN_FACTOR = 3` (an ENEMY bullet hitting
# US raises the SHOOTER's energy by 3*power and masks its own shot) and our own
# same-tick damage to the enemy (pushes the delta above the power cap). The
# corrections are staged one scan late because the server emits the hit event on
# turn N but applies the energy change to the reading of turn N+1.
type
FireTracker = object
prevEnergy*: seq[tuple[id: int, energy: float]]
hitBonusPending: float
dealtPending: float
hitBonusIncoming: float
dealtIncoming: float
proc initFireTracker*(): FireTracker =
FireTracker(prevEnergy: @[])
proc reset*(t: var FireTracker) =
t.prevEnergy = @[]
t.hitBonusPending = 0.0
t.dealtPending = 0.0
t.hitBonusIncoming = 0.0
t.dealtIncoming = 0.0
proc prevEnergyGet(t: FireTracker, id: int): float =
for e in t.prevEnergy:
if e.id == id: return e.energy
100.0
proc prevEnergySet(t: var FireTracker, id: int, energy: float) =
for i in 0..<t.prevEnergy.len:
if t.prevEnergy[i].id == id:
t.prevEnergy[i].energy = energy
return
t.prevEnergy.add((id: id, energy: energy))
proc noteEnemyBulletHit*(t: var FireTracker, power: float) {.inline.} =
## `onHitByBullet` -> `e.bullet.power`.
t.hitBonusIncoming += 3.0 * power
proc noteDamageDealt*(t: var FireTracker, damage: float) {.inline.} =
## `onBulletHit` -> `e.damage`.
t.dealtIncoming += damage
proc detect*(t: var FireTracker, id: int, energy: float, lo, hi: float): seq[float] =
let prev = t.prevEnergyGet(id)
let raw = prev - energy
var drop = raw + t.hitBonusPending - t.dealtPending
t.prevEnergySet(id, energy)
if drop > hi:
# Never silently drop a too-large delta: split it into the fewest waves each
# <= 3.0 — some heat beats none.
let n = int(ceil(drop / 3.0))
let p = drop / n.float
result = newSeq[float](n)
for i in 0..<n: result[i] = p
elif drop >= lo and drop <= hi:
result = @[drop]
proc endScan*(t: var FireTracker) =
## Rotate the event corrections one slot: the events noted since the previous
## `endScan` become the corrections applied by the NEXT scan.
t.hitBonusPending = t.hitBonusIncoming
t.dealtPending = t.dealtIncoming
t.hitBonusIncoming = 0.0
t.dealtIncoming = 0.0
# ── The mover ───────────────────────────────────────────────────────────────
type
TrackedBullet = object
x, y: float
velX, velY: float ## speed * cos(heading), speed * sin(heading)
power: float
age: int ## ticks alive; die if > 200
ScoredTile = tuple[col, row: int; pathMaxHeat: float]
CorridorGeom = object
dx, dy: float ## unit heading
px, py: float ## unit perpendicular
tMin: float ## distance to wall
bx, by: float ## bullet origin
TfilModule* = object
cols, rows: int
marginX, marginY: float
arenaWidth, arenaHeight: float
lava: seq[float] ## flat row-major, index = row*cols + col
bullets: seq[TrackedBullet]
fire: FireTracker
commitTarget: tuple[x, y: float] ## world coords of the committed dodge point
commitTicks: int ## ticks remaining on the commitment
commitLava: float ## lava at commit time (spike detection)
blockedTile: tuple[col, row: int; active: bool] ## excluded from the next pick
cachedHull: seq[tuple[x, y: float]]
cachedInsideTiles: seq[tuple[col, row: int]]
callCount: int ## computeMove call count; 0 = never called
lastBotX, lastBotY: float ## position at the last call (gap detection)
lastTileCol, lastTileRow: int ## grid tile at the last call (tile replan)
proc initTFIL*(): TfilModule =
# COLOUR CONVENTION: white = "not programmed yet", black = "programmed and
# running". Survival movement IS programmed, so this init claims the body's
# own colours: body, turret and gun go BLACK (radar claims its own pair in
# radar.nim). Set once here, never per tick.
setBodyColor(BLACK)
setTurretColor(BLACK)
setGunColor(BLACK)
TfilModule(cols: 0, rows: 0, fire: initFireTracker())
proc resetRound*(m: var TfilModule) =
m.bullets = @[]
m.fire.reset()
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
m.blockedTile = (col: 0, row: 0, active: false)
m.callCount = 0
m.lastBotX = 0.0
m.lastBotY = 0.0
m.lastTileCol = 0
m.lastTileRow = 0
proc removeBulletNear*(m: var TfilModule, x, y: float) =
## Mark the tracked bullet closest to (x,y) within one tile as dead (used when
## OUR bullet destroys one of theirs before we see it).
var bestIdx = -1
var bestD2 = GridSize * GridSize ## tolerance squared
for i, b in m.bullets:
let dx = b.x - x
let dy = b.y - y
let d2 = dx * dx + dy * dy
if d2 < bestD2:
bestD2 = d2
bestIdx = i
if bestIdx >= 0:
m.bullets.del(bestIdx)
proc initGrid(m: var TfilModule, arenaWidth, arenaHeight: float) =
m.cols = int(arenaWidth / GridSize)
m.rows = int(arenaHeight / GridSize)
m.marginX = (arenaWidth - m.cols.float * GridSize) / 2.0
m.marginY = (arenaHeight - m.rows.float * GridSize) / 2.0
m.arenaWidth = arenaWidth
m.arenaHeight = arenaHeight
m.lava = newSeq[float](m.cols * m.rows)
proc lavaAt(m: TfilModule, col, row: int): float {.inline.} =
m.lava[row * m.cols + col]
proc tileAt(m: TfilModule, wx, wy: float): tuple[col, row: int] =
(col: clamp(int((wx - m.marginX) / GridSize), 0, m.cols - 1),
row: clamp(int((wy - m.marginY) / GridSize), 0, m.rows - 1))
proc noteEnemyBulletHit*(m: var TfilModule, power: float) =
## `onHitByBullet` -> the shooter's `3*power` bonus correction.
when FireFix:
m.fire.noteEnemyBulletHit(power)
proc noteDamageDealt*(m: var TfilModule, damage: float) =
## `onBulletHit` -> our same-tick damage to the enemy correction.
when FireFix:
m.fire.noteDamageDealt(damage)
proc spawnTrackedWave(m: var TfilModule, ws: WorldState, ei: EnemyInfo, power: float) =
## One tracked bullet for a confirmed fire of `power`: linear prediction of our
## position at arrival becomes the aim heading.
let speed = 20.0 - 3.0 * power
let dx = ws.selfX - ei.x
let dy = ws.selfY - ei.y
let travelTime = sqrt(dx * dx + dy * dy) / speed
let hRad = ws.selfHeading * PI / 180.0
let predX = ws.selfX + ws.selfSpeed * cos(hRad) * travelTime
let predY = ws.selfY + ws.selfSpeed * sin(hRad) * travelTime
let heading = arctan2(predY - ei.y, predX - ei.x)
if m.bullets.len >= MaxTrackedBullets:
m.bullets.del(0) ## ponytail: drop the oldest; fine for a 20-bullet cap
m.bullets.add TrackedBullet(x: ei.x, y: ei.y,
velX: speed * cos(heading),
velY: speed * sin(heading),
power: power, age: 0)
proc detectFires(m: var TfilModule, ws: WorldState) =
## Check every enemy for an energy drop; spawn a tracked wave per confirmed fire.
for ei in ws.enemies:
for p in m.fire.detect(ei.id, ei.energy, 0.09, 3.01):
m.spawnTrackedWave(ws, ei, p)
m.fire.endScan()
proc bulletLock(m: TfilModule, selfX, selfY: float): bool =
## True while any tracked bullet is within LockRadiusTiles of us: an active
## dodge, during which the committed tile is frozen (proposal #2).
let r2 = (LockRadiusTiles * GridSize) * (LockRadiusTiles * GridSize)
for b in m.bullets:
let dx = selfX - b.x
let dy = selfY - b.y
if dx * dx + dy * dy <= r2: return true
proc advanceBullets(m: var TfilModule, selfX, selfY: float) =
## Advance positions and reap bullets that passed us, left the arena, or are
## too old.
var i = 0
while i < m.bullets.len:
var b = m.bullets[i]
b.x += b.velX
b.y += b.velY
b.age += 1
let dx = selfX - b.x
let dy = selfY - b.y
let passed = b.velX * dx + b.velY * dy < 0.0 ## dot < 0: moving away
let outOfBounds =
b.x < 0.0 or b.x > m.arenaWidth or b.y < 0.0 or b.y > m.arenaHeight
if passed or outOfBounds or b.age > 200:
m.bullets.del(i)
else:
m.bullets[i] = b
inc i
proc corridorGeom(b: TrackedBullet, arenaWidth, arenaHeight: float): CorridorGeom =
## `tMin` is the corridor length: the distance to the wall along the heading.
## Unset (0.0) -> zero-speed bullet, skipped by the caller.
let speed = sqrt(b.velX * b.velX + b.velY * b.velY)
if speed < 0.001: return
let dx = b.velX / speed
let dy = b.velY / speed
var tMin = Inf
if dx > 0.0: tMin = min(tMin, (arenaWidth - b.x) / dx)
elif dx < 0.0: tMin = min(tMin, (0.0 - b.x) / dx)
if dy > 0.0: tMin = min(tMin, (arenaHeight - b.y) / dy)
elif dy < 0.0: tMin = min(tMin, (0.0 - b.y) / dy)
CorridorGeom(dx: dx, dy: dy, px: -dy, py: dx, tMin: tMin, bx: b.x, by: b.y)
proc pointInHull(px, py: float, hull: seq[(float, float)]): bool =
## Crossing-number test against the hull polygon.
var inside = false
var j = hull.high
for i in 0..hull.high:
if ((hull[i][1] > py) != (hull[j][1] > py)) and
(px < (hull[j][0] - hull[i][0]) * (py - hull[i][1]) / (hull[j][1] - hull[i][1]) + hull[i][0]):
inside = not inside
j = i
inside
proc computeReachableHull(x0, y0, heading0, speed0,
arenaW, arenaH: float, ticks: int): seq[(float, float)] =
## Simulate `ticks` ticks at various turn rates / target speeds, then gift-wrap
## the convex hull of the final positions.
const TargetSpeeds = [8.0, 4.0, -4.0, -8.0]
const NumRates = 11
var pts: seq[(float, float)]
pts.add (x0, y0) ## always reachable: stay
for tSpeed in TargetSpeeds:
let mtr = 10.0 - 0.75 * abs(tSpeed) ## max turn rate at the target speed
for ri in 0..<NumRates:
let turnRate = -mtr + (2.0 * mtr / (NumRates - 1).float) * ri.float
var x = x0
var y = y0
var h = heading0
var spd = speed0
for _ in 0..<ticks:
if spd < tSpeed: spd = min(spd + 1.0, tSpeed)
elif spd > tSpeed: spd = max(spd - 1.0, tSpeed)
spd = clamp(spd, -MaxSpeed, MaxSpeed)
let curMtr = 10.0 - 0.75 * abs(spd)
h += clamp(turnRate, -curMtr, curMtr)
let hr = h * PI / 180.0
x = clamp(x + spd * cos(hr), 0.0, arenaW)
y = clamp(y + spd * sin(hr), 0.0, arenaH)
pts.add (x, y)
# Gift-wrap from the leftmost (then lowest) point.
var startIdx = 0
for i in 1..<pts.len:
if pts[i][0] < pts[startIdx][0] or
(pts[i][0] == pts[startIdx][0] and pts[i][1] < pts[startIdx][1]):
startIdx = i
var hull: seq[(float, float)]
var cur = startIdx
while true:
hull.add pts[cur]
var next = 0
for i in 1..<pts.len:
if next == cur:
next = i
continue
let ax = pts[next][0] - pts[cur][0]
let ay = pts[next][1] - pts[cur][1]
let bx = pts[i][0] - pts[cur][0]
let by = pts[i][1] - pts[cur][1]
if ax * by - ay * bx < 0.0: ## i is more counterclockwise
next = i
cur = next
if cur == startIdx: break
hull
proc pathMaxHeat(m: TfilModule, fx, fy, tx, ty: float): float =
## MAX lava on the straight-line segment (fx,fy) -> (tx,ty), sampled every ~half
## a tile. A single hot tile on the path (corridor, bullet core, enemy aura)
## makes the whole path unsafe.
let ddx = tx - fx
let ddy = ty - fy
let lineDist = sqrt(ddx * ddx + ddy * ddy)
if lineDist <= 0.1: return 0.0
let steps = max(1, int(lineDist / PathSampleStep))
var h = 0.0
for si in 0..steps:
let frac = si.float / steps.float
let (sc, sr) = m.tileAt(fx + ddx * frac, fy + ddy * frac)
h = max(h, m.lavaAt(sc, sr))
h
proc paintBulletHeat(m: var TfilModule, b: TrackedBullet) =
## Core circle and aura ring around one tracked bullet.
let (coreR, auraR) = bulletRadii(b.power)
let bx = b.x
let by = b.y
let coreR2 = coreR * coreR
let auraR2 = auraR * auraR
let colMin = max(0, int(floor((bx - auraR - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((bx + auraR - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((by - auraR - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((by + auraR - m.marginY) / GridSize)))
for row in rowMin..rowMax:
let y0 = m.marginY + row.float * GridSize
let nearY = clamp(by, y0, y0 + GridSize)
let dy = nearY - by
let dy2 = dy * dy
for col in colMin..colMax:
let x0 = m.marginX + col.float * GridSize
let dx = clamp(bx, x0, x0 + GridSize) - bx
let d2 = dx * dx + dy2
let idx = row * m.cols + col
if d2 <= coreR2: m.lava[idx] += BulletCoreHeat
elif d2 <= auraR2: m.lava[idx] += BulletAuraHeat
proc paintCorridorHeat(m: var TfilModule, b: TrackedBullet) =
## The rotated rectangle from the bullet to the arena wall, auraR wide.
let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight)
if cg.tMin == 0.0: return ## zero-speed bullet
let (_, auraR) = bulletRadii(b.power)
let wx = cg.bx + cg.dx * cg.tMin
let wy = cg.by + cg.dy * cg.tMin
let c0x = cg.bx + cg.px * auraR; let c0y = cg.by + cg.py * auraR
let c1x = cg.bx - cg.px * auraR; let c1y = cg.by - cg.py * auraR
let c2x = wx - cg.px * auraR; let c2y = wy - cg.py * auraR
let c3x = wx + cg.px * auraR; let c3y = wy + cg.py * auraR
let colMin = max(0, int(floor((min(min(c0x, c1x), min(c2x, c3x)) - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((max(max(c0x, c1x), max(c2x, c3x)) - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((min(min(c0y, c1y), min(c2y, c3y)) - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((max(max(c0y, c1y), max(c2y, c3y)) - m.marginY) / GridSize)))
for row in rowMin..rowMax:
let cy = m.marginY + (row.float + 0.5) * GridSize
let relY = cy - cg.by
let along0 = relY * cg.dy
let perp0 = relY * cg.py
for col in colMin..colMax:
let cx = m.marginX + (col.float + 0.5) * GridSize
let relX = cx - cg.bx
let along = along0 + relX * cg.dx
let perp = perp0 + relX * cg.px
if along >= 0.0 and along <= cg.tMin and perp >= -auraR and perp <= auraR:
m.lava[row * m.cols + col] += CorridorHeat
proc paintEnemyHeat(m: var TfilModule, ei: EnemyInfo) =
## Enemy core (18px) and aura ring (54px), same pattern as the bullets.
let ex = ei.x
let ey = ei.y
let colMin = max(0, int(floor((ex - EnemyAuraRadius - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((ex + EnemyAuraRadius - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((ey - EnemyAuraRadius - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((ey + EnemyAuraRadius - m.marginY) / GridSize)))
let coreR2 = EnemyCoreRadius * EnemyCoreRadius
let auraR2 = EnemyAuraRadius * EnemyAuraRadius
for row in rowMin..rowMax:
let y0 = m.marginY + row.float * GridSize
let dy = clamp(ey, y0, y0 + GridSize) - ey
let dy2 = dy * dy
for col in colMin..colMax:
let x0 = m.marginX + col.float * GridSize
let dx = clamp(ex, x0, x0 + GridSize) - ex
let d2 = dx * dx + dy2
let idx = row * m.cols + col
if d2 <= coreR2: m.lava[idx] += EnemyCoreHeat
elif d2 <= auraR2: m.lava[idx] += EnemyAuraHeat
proc paintWallHeat(m: var TfilModule) =
## Additive wall radiance: hottest along the border, falling off inwards.
for row in 0..<m.rows:
let vert = max(0.0, WallHotness - row.float * WallRadiance) +
max(0.0, WallHotness - (m.rows - 1 - row).float * WallRadiance)
for col in 0..<m.cols:
let heat = vert +
max(0.0, WallHotness - col.float * WallRadiance) +
max(0.0, WallHotness - (m.cols - 1 - col).float * WallRadiance)
m.lava[row * m.cols + col] += heat
proc collectCoolestTiles(m: var TfilModule): seq[tuple[col, row: int]] =
## The tiles inside the reachable hull whose lava is one of the `CoolestLevels`
## coolest DISTINCT values present there.
var distinctVals: seq[float]
for t in m.cachedInsideTiles:
let v = m.lavaAt(t.col, t.row)
var found = false
for dv in distinctVals:
if dv == v:
found = true
break
if not found:
distinctVals.add v
# ascending insertion sort — N is small
for i in 1..<distinctVals.len:
let key = distinctVals[i]
var j = i - 1
while j >= 0 and distinctVals[j] > key:
distinctVals[j + 1] = distinctVals[j]
dec j
distinctVals[j + 1] = key
result = @[]
let numLevels = min(CoolestLevels, distinctVals.len)
for t in m.cachedInsideTiles:
let v = m.lavaAt(t.col, t.row)
for li in 0..<numLevels:
if v == distinctVals[li]:
result.add t
break
when defined(tfilDebug):
proc drawHeatField(m: TfilModule, ws: WorldState) =
## The lava field per tile (colour ramp + value text), the tracked bullets'
## core/aura circles, their danger corridors and the enemies' core/aura.
var maxLava = 0.0
for v in m.lava:
if v > maxLava: maxLava = v
setFont("Arial", 10.0)
for row in 0..<m.rows:
for col in 0..<m.cols:
let val = m.lava[row * m.cols + col]
if val == 0.0: continue
let t = if maxLava > 0.0: val / maxLava else: 0.0
let heatColor = fromRgb(255'u8, uint8(255.0 * (1.0 - t)), 0'u8)
let x0 = m.marginX + col.float * GridSize
let y0 = m.marginY + row.float * GridSize
setStrokeColor(heatColor)
setStrokeWidth(1.0)
drawRectangle(x0, y0, GridSize, GridSize)
setFillColor(heatColor)
drawText($int(val), x0 + 12.0, y0 + 22.0)
# Tracked bullets: red core outline + filled centre, orange aura ring.
for b in m.bullets:
let (coreR, auraR) = bulletRadii(b.power)
setStrokeColor(RED)
setStrokeWidth(1.0)
setFillColor(RED)
drawCircle(b.x, b.y, coreR)
fillCircle(b.x, b.y, 3.0)
setStrokeColor(fromHex("#FF8800"))
drawCircle(b.x, b.y, auraR)
# Danger corridor: the rotated rectangle from each bullet to the arena wall.
setStrokeColor(fromHex("#AAAAAA"))
setStrokeWidth(1.0)
for b in m.bullets:
let (_, auraR) = bulletRadii(b.power)
let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight)
if cg.tMin == 0.0: continue
let wx = cg.bx + cg.dx * cg.tMin
let wy = cg.by + cg.dy * cg.tMin
drawPolygon(@[
(cg.bx + cg.px * auraR, cg.by + cg.py * auraR),
(cg.bx - cg.px * auraR, cg.by - cg.py * auraR),
(wx - cg.px * auraR, wy - cg.py * auraR),
(wx + cg.px * auraR, wy + cg.py * auraR),
])
# Enemies: cyan body core, green aura ring.
setStrokeColor(fromHex("#00FFFF"))
setStrokeWidth(1.5)
for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyCoreRadius)
setStrokeColor(fromHex("#00CC00"))
setStrokeWidth(1.0)
for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyAuraRadius)
proc drawDecision(m: TfilModule, ws: WorldState,
scoredTiles, safeTiles: seq[ScoredTile]) =
## What the planner actually did: reachable hull, the tiles whose path is
## blocked, the safe set, the tile it committed to, its own tile, and the
## committed-target line.
if m.cachedHull.len >= 3:
let hullPts = block:
var s: seq[(float, float)]
for p in m.cachedHull: s.add (p.x, p.y)
s
setStrokeColor(fromHex("#336699"))
setStrokeWidth(1.0)
drawPolygon(hullPts)
setStrokeColor(fromHex("#006666"))
setStrokeWidth(1.0)
for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: continue
if t in safeTiles: continue ## promoted into the safe set: drawn cyan below
drawRectangle(m.marginX + t.col.float * GridSize,
m.marginY + t.row.float * GridSize, GridSize, GridSize)
setStrokeColor(fromHex("#00FFFF"))
setStrokeWidth(2.0)
for t in safeTiles:
drawRectangle(m.marginX + t.col.float * GridSize,
m.marginY + t.row.float * GridSize, GridSize, GridSize)
let (chosenCol, chosenRow) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
setStrokeColor(fromHex("#00FF00"))
setStrokeWidth(2.5)
drawRectangle(m.marginX + chosenCol.float * GridSize,
m.marginY + chosenRow.float * GridSize, GridSize, GridSize)
let (botCol, botRow) = m.tileAt(ws.selfX, ws.selfY)
setStrokeColor(fromHex("#0088FF"))
setStrokeWidth(2.5)
drawRectangle(m.marginX + botCol.float * GridSize,
m.marginY + botRow.float * GridSize, GridSize, GridSize)
setStrokeColor(fromHex("#00FF00"))
setStrokeWidth(1.5)
drawLine(ws.selfX, ws.selfY, m.commitTarget.x, m.commitTarget.y)
proc computeMove*(m: var TfilModule, ws: WorldState): MoveCommand =
if m.cols == 0:
m.initGrid(ws.arenaWidth, ws.arenaHeight)
# Soft reset: a position gap (a rammer moved us across ticks) invalidates the
# commitment, the cached hull and every tracked bullet. 12px is above the 8px
# single-tick maximum, so normal motion never trips it.
let jumpDist = sqrt((ws.selfX - m.lastBotX)^2 + (ws.selfY - m.lastBotY)^2)
let jumped = (m.callCount > 0) and (jumpDist > 12.0)
if jumped:
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
m.bullets = @[]
m.blockedTile = (col: 0, row: 0, active: false)
# Re-snapshot prevEnergy: energy changes during ramming are not fires.
m.fire.prevEnergy = @[]
for ei in ws.enemies:
m.fire.prevEnergySet(ei.id, ei.energy)
# Per-tick: advance existing bullets, detect new fires
m.advanceBullets(ws.selfX, ws.selfY)
m.detectFires(ws)
# Active-dodge lock: while a tracked bullet is within LockRadiusTiles we stop
# the tile-crossing replan, so the committed dodge direction survives the
# crossing. The 15-tick dwell still expires and the safety valve still fires
# (a hard freeze until the bullet passed measured far worse: the bot parked and
# ate the shot).
let locked = m.bulletLock(ws.selfX, ws.selfY)
# Tile-change replan: crossing a tile boundary cancels the commitment,
# unless we are mid-dodge (locked).
if (not jumped) and (not locked) and (m.callCount > 0) and (m.commitTicks > 0):
let curTileCol = clamp(int((ws.selfX - m.marginX) / GridSize), 0, m.cols - 1)
let curTileRow = clamp(int((ws.selfY - m.marginY) / GridSize), 0, m.rows - 1)
if curTileCol != m.lastTileCol or curTileRow != m.lastTileRow:
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
# Recompute the lava field from scratch
for i in 0..<m.lava.len: m.lava[i] = 0.0
for b in m.bullets: m.paintBulletHeat(b)
for b in m.bullets: m.paintCorridorHeat(b)
for ei in ws.enemies: m.paintEnemyHeat(ei)
m.paintWallHeat()
when defined(tfilDebug):
drawHeatField(m, ws)
# ── Tile-based dodge system ────────────────────────────────────────────────
# Hull + inside-tiles: recomputed only on a replan tick (commitTicks == 0).
if m.commitTicks == 0:
m.cachedHull = computeReachableHull(ws.selfX, ws.selfY, ws.selfHeading,
ws.selfSpeed, m.arenaWidth,
m.arenaHeight, HullTicks)
m.cachedInsideTiles = @[]
if m.cachedHull.len >= 3:
for row in 0..<m.rows:
let cy = m.marginY + (row.float + 0.5) * GridSize
for col in 0..<m.cols:
let cx = m.marginX + (col.float + 0.5) * GridSize
if pointInHull(cx, cy, m.cachedHull):
m.cachedInsideTiles.add (col: col, row: row)
# Score each cool tile by the MAX lava on the straight-line path from the bot.
var scoredTiles: seq[ScoredTile]
for t in m.collectCoolestTiles():
let tx = m.marginX + (t.col.float + 0.5) * GridSize
let ty = m.marginY + (t.row.float + 0.5) * GridSize
scoredTiles.add (col: t.col, row: t.row,
pathMaxHeat: pathMaxHeat(m, ws.selfX, ws.selfY, tx, ty))
# ascending by path heat — insertion sort, small N
for i in 1..<scoredTiles.len:
let key = scoredTiles[i]
var j = i - 1
while j >= 0 and scoredTiles[j].pathMaxHeat > key.pathMaxHeat:
scoredTiles[j + 1] = scoredTiles[j]
dec j
scoredTiles[j + 1] = key
# Absolute threshold filter: safe = path max lava <= PathDangerThreshold.
# Fallback: if fewer than two tiles survive, promote the least-hot blocked ones.
var safeTiles: seq[ScoredTile]
for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: safeTiles.add t
if safeTiles.len < 2:
# Promote the least-hot blocked tiles until there are two (scoredTiles is
# sorted ascending, so the first hot ones are the coolest of the hot).
for t in scoredTiles:
if safeTiles.len >= 2: break
if t.pathMaxHeat > PathDangerThreshold: safeTiles.add t
# Commitment logic: a fixed 15-tick dwell, cancellable by our own tile crossing
# (above) or by the committed tile getting genuinely dangerous (the safety
# valve, only after the minimum dwell).
if m.commitTicks > 0:
if CommitTicks - m.commitTicks >= MinCommitTicks:
let (cc, cr) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
if m.lavaAt(cc, cr) > m.commitLava + DangerReplanThreshold:
m.blockedTile = (col: cc, row: cr, active: true)
m.commitTicks = 0
if m.commitTicks > 0:
dec m.commitTicks
if m.commitTicks == 0 and safeTiles.len > 0:
# Never re-pick the tile we just blocked ourselves with; if that empties the
# pool, the block is ignored (being cornered beats being stuck).
var candidates: seq[ScoredTile]
for t in safeTiles:
if m.blockedTile.active and t.col == m.blockedTile.col and t.row == m.blockedTile.row:
continue
candidates.add t
if candidates.len == 0: candidates = safeTiles
## A uniform draw: the randomness in this pick is load-bearing (a
## deterministic argmin measured worse).
let ct = candidates[rand(candidates.high)]
m.commitTarget = (x: m.marginX + (ct.col.float + 0.5) * GridSize,
y: m.marginY + (ct.row.float + 0.5) * GridSize)
m.commitTicks = CommitTicks
m.commitLava = m.lavaAt(ct.col, ct.row)
m.blockedTile.active = false
when defined(tfilDebug):
drawDecision(m, ws, scoredTiles, safeTiles)
# Update the position snapshot and call counter for next gap/tile detection
m.lastBotX = ws.selfX
m.lastBotY = ws.selfY
m.lastTileCol = clamp(int((ws.selfX - m.marginX) / GridSize), 0, m.cols - 1)
m.lastTileRow = clamp(int((ws.selfY - m.marginY) / GridSize), 0, m.rows - 1)
m.callCount += 1
# ── Steering ────────────────────────────────────────────────────────────────
# `speed: 0.0` is how this module says "stop": the already-at-target case below
# returns the same command. The gun is not here — `computeMove` never touches
# fire, so a held tick still fires exactly as every other tick.
let stepDx = m.commitTarget.x - ws.selfX
let stepDy = m.commitTarget.y - ws.selfY
let dist2 = stepDx * stepDx + stepDy * stepDy
if dist2 < ArriveRadius * ArriveRadius:
return (speed: 0.0, turnRate: 0.0)
let targetBearing = arctan2(stepDy, stepDx) * 180.0 / PI
var delta = targetBearing - ws.selfHeading
while delta > 180.0: delta -= 360.0
while delta < -180.0: delta += 360.0
let maxTurnRate = 10.0 - 0.75 * abs(ws.selfSpeed)
if abs(delta) <= 90.0:
result = (speed: MaxSpeed, turnRate: clamp(delta, -maxTurnRate, maxTurnRate))
else:
let flipped = if delta > 0.0: delta - 180.0 else: delta + 180.0
result = (speed: -MaxSpeed, turnRate: clamp(flipped, -maxTurnRate, maxTurnRate))
+1
View File
@@ -0,0 +1 @@
--path:"../src/ChimeraBot"
+251
View File
@@ -0,0 +1,251 @@
## Unit tests for the ELM module (ChimeraBot/modules/ELM/elm.nim).
## Run from ChimeraBot_garage/: nim c -r tests/test_elm.nim
## (`import modules/ELM/elm` resolves via tests/config.nims)
import std/[math, random, strutils]
import modules/ELM/elm
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond:
echo " ok ", name, (if detail.len > 0: " [" & detail & "]" else: "")
else:
echo " FAIL ", name, " [", detail, "]"
inc failed
proc target(x, y: float64): float64 = sin(3 * x) + 0.5 * cos(2 * y)
# ── 1. Theorem 2.2: L = N samples must be interpolated exactly ──────────────
block test1:
echo "test 1: interpolation (Huang 2011, Thm 2.2)"
var rng = initRand(42)
let d = 5
let N = 20 # N samples, L = 20 hidden nodes >= N
var e = initElm(ElmConfig(inputDim: d, hiddenDim: N, outputs: 2,
seed: 7, lambda: 0.0, decay: 1.0, refitEvery: 1))
for i in 0 ..< N:
var x = newSeq[float64](d)
var t = newSeq[float64](2)
for k in 0 ..< d: x[k] = rand(rng, 2.0) - 1.0
t[0] = target(x[0], x[1]); t[1] = 0.3 * x[2]
e.train(x, t)
let rmse = diagnostics(e).trainRmse
echo " measured trainRmse = ", rmse
check("trainRmse < 1e-8", rmse < 1e-8, formatFloat(rmse, ffScientific, 3))
# ── 2. Generalisation on a nonlinear function ───────────────────────────────
block test2:
echo "test 2: generalisation sin(3x)+0.5*cos(2y), 200 train / 100 held-out"
var rng = initRand(11)
var e = initElm(ElmConfig(inputDim: 2, hiddenDim: 64, outputs: 1,
seed: 3, lambda: 1e-8, decay: 1.0, refitEvery: 1))
for i in 0 ..< 200:
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
e.train(x, @[target(x[0], x[1])])
var se = 0.0
for i in 0 ..< 100:
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
let d = e.infer(x)[0] - target(x[0], x[1])
se += d * d
let mse = se / 100.0
# Threshold 1e-3, chosen from the measured value (~3e-4): ~3x headroom, tight
# enough that a broken hidden layer or an un-penalised-shared bias fails.
echo " measured held-out MSE = ", formatFloat(mse, ffScientific, 3)
check("held-out MSE < 1e-3", mse < 1e-3, formatFloat(mse, ffScientific, 3))
# ── 3. Large constant offset survives a large ridge ─────────────────────────
block test3:
echo "test 3: bias column is not penalised"
var e = initElm(ElmConfig(inputDim: 1, hiddenDim: 32, outputs: 1,
seed: 5, lambda: 1e4, decay: 1.0, refitEvery: 1))
var rng = initRand(1)
for i in 0 ..< 64:
let x = @[rand(rng, 2.0) - 1.0]
e.train(x, @[5.0 + 0.1 * x[0]])
let p = e.infer(@[0.25])[0]
# lambda = 1e4 kills the slope term (that is what the penalty is FOR), but the
# 5.0 offset must survive it untouched, because the bias column carries a zero
# penalty diagonal. A penalised bias would give ~0 here (5.0 is pushed to 0 by
# the same factor as the weights).
echo " measured f(0.25) = ", formatFloat(p, ffDecimal, 6), " (offset ~5.0 + shrunk slope)"
check("offset survives lambda=1e4", abs(p - 5.0) < 0.05, formatFloat(p, ffDecimal, 6))
check("offset not shrunk toward 0", abs(p) > 4.5)
# ── 4. Decay forgets; decay=1.0 keeps the old fit ───────────────────────────
block test4:
echo "test 4: forgetting via sample-weight decay"
proc fit(decay: float64): tuple[f0: float64, rmse: float64] =
var e = initElm(ElmConfig(inputDim: 1, hiddenDim: 32, outputs: 1,
seed: 9, lambda: 1e-6, decay: decay, refitEvery: 1))
var rng = initRand(100)
for i in 0 ..< 50:
let x = @[rand(rng, 2.0) - 1.0]
e.train(x, @[1.0])
for i in 0 ..< 5:
let x = @[rand(rng, 2.0) - 1.0]
e.train(x, @[-3.0])
(e.infer(@[0.0])[0], diagnostics(e).trainRmse)
let fast = fit(0.5)
let fk = fit(1.0)
let forget = fast.f0
let keep = fk.f0
echo " forgetting f(0) = ", formatFloat(forget, ffDecimal, 4),
", no-decay f(0) = ", formatFloat(keep, ffDecimal, 4),
" (trainRmse ", formatFloat(fk.rmse, ffScientific, 2), ")"
# Sanity on the fit itself: the best constant over the (weighted) samples is
# an exact solution for two-valued targets, so trainRmse must equal the RMSE
# of the weighted mean. The tanh features can do better than a constant (they
# vary with x), so this is a floor, not an equality.
proc bestConst(ws, ts: seq[float64]): tuple[mean: float64, rmse: float64] =
var sw = 0.0; var sst = 0.0
for i in 0 ..< ws.len: sw += ws[i] * ts[i]
let m = sw / float64(ws.len)
var acc = 0.0
for i in 0 ..< ws.len: acc += ws[i] * (m - ts[i]) * (m - ts[i])
(m, sqrt(acc / float64(ws.len)))
var wA = newSeq[float64](55)
var tAB = newSeq[float64](55)
for i in 0 ..< 50:
wA[i] = 1.0
tAB[i] = 1.0
for i in 50 ..< 55:
wA[i] = 1.0
tAB[i] = -3.0
let bcKeep = bestConst(wA, tAB)
var wF = newSeq[float64](55)
for i in 0 ..< 50: wF[i] = pow(0.5, 5.0)
for i in 50 ..< 55: wF[i] = 1.0
let bcForget = bestConst(wF, tAB)
check("no-decay fit beats a constant", fk.rmse <= bcKeep.rmse + 1e-6,
formatFloat(fk.rmse, ffDecimal, 4) & " vs " & formatFloat(bcKeep.rmse, ffDecimal, 4))
check("forgetting fit beats a constant", fast.rmse <= bcForget.rmse + 1e-6,
formatFloat(fast.rmse, ffDecimal, 4) & " vs " & formatFloat(bcForget.rmse, ffDecimal, 4))
# The real forgetting evidence: A now contributes ~1/32 of the total weight, so
# the fit is essentially B's, and its weighted residual collapses.
check("old data stops dominating the loss", fast.rmse < 0.7 * fk.rmse,
formatFloat(fast.rmse, ffDecimal, 4) & " vs " & formatFloat(fk.rmse, ffDecimal, 4))
check("decay=0.5 follows pattern B", abs(forget + 3.0) < 0.25,
formatFloat(forget, ffDecimal, 4))
# No decay: all 50 A samples keep weight 1, the 5 B samples too, so the
# least-squares constant over the SAMPLES is the weighted mean
# (50*1 + 5*(-3)) / 55 = 0.636 -- old data still dominates. f(0) is an
# interpolation between samples (ridge 1e-6 leaves a flat direction), so it is
# asserted to sit near the combined mean rather than anywhere near B's -3.
check("decay=1.0 keeps A in the mix", abs(keep - 0.636) < abs(keep + 3.0) + 0.6,
formatFloat(keep, ffDecimal, 4))
check("decay=1.0 is nowhere near B", abs(keep + 3.0) > 1.5)
check("the two differ", abs(forget - keep) > 1.0)
# ── 5. Same seed => same model ──────────────────────────────────────────────
block test5:
echo "test 5: seed determinism"
var a = initElm(ElmConfig(inputDim: 3, hiddenDim: 16, outputs: 2,
seed: 1234, lambda: 1e-3, decay: 1.0, refitEvery: 1))
var b = a
var rng = initRand(5)
for i in 0 ..< 30:
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
a.train(x, @[x[0] * x[1], x[2]])
for i in 0 ..< 30:
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
b.train(x, @[x[0] * x[1], x[2]])
var same = true
for i in 0 ..< 2:
same = same and a.infer(@[0.1 * float64(i), 0.2, -0.3]) ==
b.infer(@[0.1 * float64(i), 0.2, -0.3])
check("identical outputs", same)
# ── 6. Dimension mismatch raises ValueError ─────────────────────────────────
block test6:
echo "test 6: dimension validation"
var e = initElm(ElmConfig(inputDim: 3, hiddenDim: 8, outputs: 1))
var raised = ""
try: discard e.infer(@[1.0, 2.0])
except ValueError as ex: raised = ex.msg
check("infer raises ValueError", raised.len > 0, raised)
raised = ""
try: e.train(@[1.0, 2.0, 3.0], @[1.0, 2.0])
except ValueError as ex: raised = ex.msg
check("train raises ValueError on target mismatch", raised.len > 0, raised)
# ── 7. Activation: Thm 2.2 interpolation holds for every activation ─────────
block test7:
echo "test 7: interpolation for tanh / relu / step"
for kind in [atanTanh, atanRelu, atanStep]:
var rng = initRand(42)
let d = 5
let N = 20
var e = initElm(ElmConfig(inputDim: d, hiddenDim: N, outputs: 2, seed: 7,
lambda: 0.0, decay: 1.0, refitEvery: 1,
activation: kind))
for i in 0 ..< N:
var x = newSeq[float64](d)
var t = newSeq[float64](2)
for k in 0 ..< d: x[k] = rand(rng, 2.0) - 1.0
t[0] = target(x[0], x[1]); t[1] = 0.3 * x[2]
e.train(x, t)
let rmse = diagnostics(e).trainRmse
echo " ", activationName(kind), ": trainRmse = ", formatFloat(rmse, ffScientific, 3)
check(activationName(kind) & " interpolates 20 samples in 20 nodes",
rmse < 1e-8, formatFloat(rmse, ffScientific, 3))
# ── 8. Activation: same targets fit comparably well (held-out) ─────────────
block test8:
echo "test 8: generalisation across activations, 200 train / 100 held-out"
var errs: seq[tuple[n: string, mse: float64]] = @[]
for kind in [atanTanh, atanRelu, atanStep]:
var rng = initRand(11)
var e = initElm(ElmConfig(inputDim: 2, hiddenDim: 64, outputs: 1, seed: 3,
lambda: 1e-8, decay: 1.0, refitEvery: 1,
activation: kind))
for i in 0 ..< 200:
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
e.train(x, @[target(x[0], x[1])])
var se = 0.0
for i in 0 ..< 100:
let x = @[rand(rng, 2.0) - 1.0, rand(rng, 2.0) - 1.0]
let dd = e.infer(x)[0] - target(x[0], x[1])
se += dd * dd
let mse = se / 100.0
errs.add (activationName(kind), mse)
echo " ", activationName(kind), ": held-out MSE = ", formatFloat(mse, ffScientific, 3)
# Per-activation absolute bar, NOT "as good as tanh": the measured values are
# tanh 1.07e-06, relu 3.5e-02, step 8.4e-02, against a target sd of ~1.0, so
# a bar of 1e-1 demands every activation beat "predict the training mean" by
# 10x and would fail a broken hidden layer (~1.0), while NOT asserting the
# null result this experiment is measuring. The 2-4 orders of magnitude gap
# between tanh and the one-sided activations at lambda=1e-8 is a real finding,
# reported rather than hidden by a tuned threshold: relu/step features are
# unbounded/ill-conditioned, so the output weights they need are large and the
# shipped near-zero ridge does not control them. Re-tuning lambda is exactly
# what the benchmark sweep does.
for er in errs:
check(er.n & " generalises (held-out MSE < 0.1, i.e. 10x better than a constant)",
er.mse < 1e-1, formatFloat(er.mse, ffScientific, 3))
# ── 9. applyActivation is pure and matches its definition ──────────────────
block test9:
echo "test 9: applyActivation"
check("tanh", applyActivation(atanTanh, 0.5) == tanh(0.5) and
applyActivation(atanTanh, -0.5) == tanh(-0.5))
check("relu", applyActivation(atanRelu, 0.5) == 0.5 and
applyActivation(atanRelu, -0.5) == 0.0)
check("step", applyActivation(atanStep, 0.5) == 1.0 and
applyActivation(atanStep, -0.5) == 0.0 and
applyActivation(atanStep, 0.0) == 0.0)
check("parse round-trips", parseActivation("ReLU") == atanRelu and
parseActivation("tanh") == atanTanh and
parseActivation("STEP") == atanStep)
var raised = false
try: discard parseActivation("swish")
except ValueError: raised = true
check("parse rejects unknown", raised)
check("default is tanh", ElmConfig(inputDim: 1, hiddenDim: 1, outputs: 1).activation == atanTanh)
echo ""
if failed == 0:
echo "all tests passed"
else:
echo failed, " test(s) FAILED"
quit(1)
+94
View File
@@ -0,0 +1,94 @@
## Unit tests for the ONLINE-learning gun (elm_gun.nim): the delayed-label
## queue, the novelty gate, and the per-opponent reset.
## Run: nim c -r tests/test_online.nim (from ChimeraBot_garage/)
import std/math
import modules/ELM/elm_gun
import modules/ELM/elm_features
import modules/ELM/elm # for Elm.infer in the assertions
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
# ── 1. neutral start: no prior, gate closed ─────────────────────────────────
block:
echo "test 1: neutral start"
let g = initElmGun(priorScale = 0.0)
check("weights loaded", g.loaded)
check("prior stored", g.priorBeta.len > 0)
check("nOnline == 0", g.nOnline == 0)
check("gate closed at start", not g.gateOpen)
# ── 2. online learning opens the gate once it beats zero ────────────────────
block:
echo "test 2: online learning closes then opens the novelty gate"
let g = initElmGun(priorScale = 0.0)
let feat = newSeq[float64](FeatureDim) # constant feature vector
for i in 0 ..< 60:
g.feedSample(feat, 0.3) # constant true correction
check("accumulated samples", g.nOnline == 60)
check("model beats zero (modelErr < zeroErr)", g.modelErr < g.zeroErr,
$g.modelErr & " vs " & $g.zeroErr)
check("gate OPEN after learning", g.gateOpen)
let corr = g.model.infer(feat)[0]
check("correction near label", abs(corr - 0.3) < 0.1, $corr)
# ── 3. a model that cannot beat zero keeps the gate shut ────────────────────
block:
echo "test 3: no-signal data keeps the gate closed"
let g = initElmGun(priorScale = 0.0)
let feat = newSeq[float64](FeatureDim)
for i in 0 ..< 40:
g.feedSample(feat, 0.0) # label is exactly zero
check("gate stays closed on zero labels", not g.gateOpen)
# ── 4. delayed-label queue: keyed by dueTick, needs the trace ───────────────
block:
echo "test 4: pending queue resolves at dueTick"
let g = initElmGun(priorScale = 0.0)
let feat: array[FeatureDim, float64] = default(array[FeatureDim, float64])
let due = 50
g.noteEnemyAt(due, 100.0, 0.0) # target straight ahead of (0,0)
g.recordShot(feat, 0.0, 0.0, 0.0, due) # base bearing 0, due at tick 50
g.drainPending(due - 1)
check("nothing resolved before dueTick", g.nOnline == 0 and g.pending.len == 1)
g.drainPending(due)
check("resolved at dueTick", g.nOnline == 1 and g.pending.len == 0)
# ── 5. reset returns to the neutral start ───────────────────────────────────
block:
echo "test 5: resetOnline clears per-opponent state"
let g = initElmGun(priorScale = 0.0)
let feat = newSeq[float64](FeatureDim)
for i in 0 ..< 60: g.feedSample(feat, 0.3)
g.noteEnemyAt(1, 1.0, 1.0)
g.recordShot(default(array[FeatureDim, float64]), 0.0, 0.0, 0.0, 5)
g.resetOnline()
check("nOnline cleared", g.nOnline == 0)
check("gate closed after reset", not g.gateOpen)
check("pending cleared", g.pending.len == 0)
check("trace cleared", g.traceTick.len == 0)
# ── 6. deg/rad fire boundary (regression: the FireSlopDeg mix-up) ───────────
block:
echo "test 6: gun-aim error is DEGREES at the fire boundary"
# aim 0 rad = east; gun at +1 deg -> short-way error -1 deg, NOT -0.0175.
check("1 deg off gives a -1 deg error",
abs(gunAimErrorDeg(0.0, 1.0) + 1.0) < 1e-9, $gunAimErrorDeg(0.0, 1.0))
# short way round: gun 350 deg from an east(0) aim is +10 deg to reach it.
check("350 deg wraps to +10 deg",
abs(gunAimErrorDeg(0.0, 350.0) - 10.0) < 1e-6, $gunAimErrorDeg(0.0, 350.0))
# THE historical bug: a degree error compared against degToRad(FireSlopDeg)
# (radians) admitted only 0.052 deg. At exactly FireSlopDeg degrees off, the
# degrees-vs-degrees predicate admits the shot; the radian mix-up rejects it.
const slop = 1.0'f64
let err = gunAimErrorDeg(0.0, slop) # exactly `slop` degrees off
check("|err| <= FireSlopDeg admits the boundary", abs(err) <= slop, $err)
check("the radian mix-up would REJECT it", abs(err) > degToRad(slop), $err)
if failed > 0:
echo "\n", failed, " check(s) FAILED"
quit(1)
echo "\nall online checks passed"