Author SHA1 Message Date
SirStone 062f2f307c docs: M6.5 close-out (horizon sweep verdict, twinsim fix, final matrix) 2026-10-07 02:54:28 +02:00
SirStone 2d250487d4 ChimeraBot_garage: M6 — residual head, predictor fusion, fallback influence, G7 head-to-head 2026-10-07 02:45:41 +02:00
SirStone 1b10603f28 docs: M6 final-state (matrix rows + final status) 2026-10-07 02:45:12 +02:00
SirStone 6dd0b1c3cb ChimeraBot_garage: M5.5 — unified metrics, cross-round posterior carry, probe set v2, G5' v2 2026-10-07 02:27:11 +02:00
SirStone f9f3cd7576 docs: unify idTicks metric (per-round median/p90/id-fraction) + G4 pass = median<=300 AND id-fraction>=80% 2026-10-07 00:41:17 +02:00
SirStone 6a3ba390ee ChimeraBot_garage: M5 — probe scheduler, advisory wiring, G6 ablation ON/OFF, G5 interventional eval 2026-10-07 00:33:31 +02:00
SirStone da9a66aab8 docs: G5 re-spec (interventional) after M4 falsification; G4 median pass condition 2026-10-07 00:24:55 +02:00
SirStone da5f53c53f ChimeraBot_garage: M3.5+M4 — kernel library v0.2, live G4 re-bench, twinsim rollout + G5 eval 2026-10-07 00:21:48 +02:00
SirStone 7e2dd3f559 ChimeraBot_garage: M3 — observation sidecar + live identification benchmark (G3/G4, G5-metrics) 2026-10-07 00:08:40 +02:00
SirStone c77541a6d7 ChimeraBot_garage: M2 — intent ledger, DSL v0 kernels, Hedge posterior, G1 oracle tests 2026-10-06 23:50:27 +02:00
SirStone 5de4b906af docs: harness uses random server port (never default) 2026-10-06 23:45:14 +02:00
SirStone ce76550186 docs: CHIMERA spec revisions (sample-bots ground truth, resolved decisions, tps=-1) 2026-10-06 23:45:10 +02:00
SirStone 215731718a ChimeraBot_garage: bootstrap exact copy of DevControlBot (CHIMERA M1) 2026-10-06 23:25:06 +02:00
SirStone b6425ac7f2 tfil: hold the committed dodge while a bullet is within 15 tiles
Proposal #2 (active-dodge commit lock), milder half only: while a tracked
bullet is within LockRadiusTiles (15 x 36px), suppress the tile-crossing
replan so the committed dodge direction survives the crossing.  The 15-tick
dwell and the danger safety valve still apply.

A hard freeze until the bullet passed (no dwell expiry) was measured and
reverted: the bot parked on the committed tile and absorbed the shot
(damage taken/round 26.8 -> 53.9 over 12 opponents x 20 rounds).

Measured on 12 opponents x 40 rounds (RawRecord, verified CONTIGUOUS):
damage taken/round 30.8 -> 25.5, damage dealt/round 73.2 -> 72.1,
rounds won 358/480 -> 360/480.

Raising CommitTicks 15 -> 25 (proposal #3) measured harmful and was reverted.
Proposal #1 (speculative bullet on 'could fire') not implemented: TFIL already
spawns a tracked bullet from the same-tick energy drop, and speculation would
be a ~70% false-positive flood.
2026-10-06 20:14:35 +02:00
SirStone 7f0fbccec6 README: review fixes, scan-gap analysis, re-measurement (neutral) 2026-10-06 19:54:32 +02:00
SirStone 2fd2388f32 gun belief: bound dead reckoning, reject untrustworthy velocity samples
Cap dead-reckoning lead at MaxDeadReckonTicks (freeze at the last scan past
it) and return (0,0) from targetVelocity when the two scans it averages span
more than MaxVelGap ticks. computeGun now uses gunAimErrorDeg.
2026-10-06 19:54:25 +02:00
SirStone eb7f750a3f elm_gun: single aim computation, explicit deg/rad fire boundary + test
predictAim folded the learned correction into the bearing and derived x/y
once instead of recomputing them per branch. New gunAimErrorDeg carries the
degree unit in its name so the FireSlopDeg comparison cannot fall back to the
old degrees-vs-radians mix-up; test_online.nim adds a regression block for it.
2026-10-06 19:54:25 +02:00
SirStone 6bec6a41cd README: honest online-learning-gun results 2026-10-06 19:37:38 +02:00
SirStone 1c7083ab75 elm_bench: online-learning battle runner and analysis 2026-10-06 19:37:38 +02:00
SirStone 2e6735a8bd DevControlBot: reset online model on GameStarted, feed delayed labels 2026-10-06 19:37:38 +02:00
SirStone a62391d400 elm_gun: delayed-label online queue, novelty gate, neutral/prior start 2026-10-06 19:37:38 +02:00
SirStone 02c65036d8 ELM: online mode setters and per-opponent reset 2026-10-06 19:37:38 +02:00
SirStone d011a2bfed README: sample-bot gate — ELM vs intercept on 13 held-out Nim sample bots (null/negative) 2026-10-06 09:05:36 +02:00
SirStone cd4b53ec52 README: movement-prediction gun — label centring, gate, real-battle numbers
Replace the aim-error-ELM section with the movement-prediction gun: the
true-impact label and its centred distribution, the 32-D features, held-out
training (ELM -27.8% RMSE vs plain intercept, output mean -0.36 deg), the
|correction|>0.10 gate (61.4% open), and 20-round RawRecord results showing
damage/round up against DrussGT, CassiusClay, Komarious and Phoenix.
2026-10-06 09:00:45 +02:00
SirStone 6a14b0ffd6 DevControlBot: movement-prediction features, gate, radar scan window
Rewrite elm_features.nim as a 32-D enemy-motion vector (7 scan-to-scan
displacement legs, speed stats, heading/turn/curvature, plus the single-frame
geometry). Add a WinCap=8 scan buffer to radar.nim and feed it through
buildBelief. elm_gun.nim now uses the physical bullet speed for the feature
(was the power*10 corpus artifact) and applies the trained correction only when
|correction| > GATE_TAU; below it the gun keeps the exact geometric aim. Retrain
and export weights (H=256, gate_tau=0.1).
2026-10-06 09:00:43 +02:00
SirStone 9f09204c40 elm_bench: relabel to true-impact movement correction
Add extract_predict.py, which builds the movement-prediction corpus: for each
sampled tick with the shooter fixed to DevControlBot (power 2), the label is
wrap(trueImpactBearing - geometricInterceptBearing), solved against the
observer's true trajectory. Unlike the old opponent-aim-error label this is
centred near zero (mean -0.33 deg, sd 18.3 deg).

Add train_predict.nim: round-group 5-fold evaluation, baselines (plain
intercept / constant), small H x lambda sweep, prediction-mean centring check,
and a |correction|>tau gate calibrated on held-out folds, then export.

Delete the old train_elm_gun.nim (it wrote the live weights from the old label)
and mark extract_realistic.py deprecated.
2026-10-06 09:00:39 +02:00
SirStone d166d34706 cleanup: remove obsolete tr_bots/_salvage legacy-bot duplicate
The salvage dir (rescued from /tmp on 2026-08-04) is fully superseded by the
canonical legacy_bots/ tree: all 28 jars are byte-identical duplicates, the
tr_wrappers still hardcode dead /tmp paths, and portaudit/ was one-off analysis
of a /tmp tree that no longer exists. The shim, vendor/, booter and legacy_bots/
are untouched.
2026-10-06 08:52:54 +02:00
SirStone 5b4ad80f35 Move DrussGT into legacy_bots/ with standard layout
DrussGT now lives at legacy_bots/DrussGT/{DrussGT.jar,DrussGT.sh,DrussGT.json}
like the other legacy bots. Its jar is committed and recorded in
MANIFEST.sha256 (sha256 5dfc0595...). tr_bots/DrussGT is kept as a
compatibility symlink to ../legacy_bots/DrussGT for in-flight jobs.
The vendored copy under tools/robocode_shim/vendor/drussgt/ is untouched.
2026-10-06 08:49:02 +02:00
SirStone 61d834ac59 tr_bots: add 13 Nim sample bots as first battle opponents
Wrapper dirs (Name.sh + Name.json) referencing the prebuilt binaries in
Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7 read-only, plus
MyFirstTeam (team config). All 13 single bots smoke-tested with RawRecord
2 rounds and verified CONTIGUOUS via query.py --verify. See SAMPLE_BOTS.md.
2026-10-06 08:48:27 +02:00
SirStone 9dab21f231 Remove the geometric gate bots and its README section
The three geometric adversaries (Target, Walls, SpinBot) were force-added in
9f37db7 and are not needed: they were a one-off non-regression gate for the
old opponent-bias gun. Delete them and their README section. Keep the
score_battles.py damage/round + aim-error additions and the DrussGT bot.
2026-10-06 08:46:38 +02:00
SirStone 9f37db7523 Add geometric gate for ELM gun
Measure the ELM gun against the plain geometric gun on the three classic
geometric-movement bots (Target, Walls, SpinBot), 20 rounds each, RawRecord
observer ground truth. Verdict: ELM passes only Target (105.5 vs 104.5
dmg/round, within noise); fails Walls (13.5 vs 76.0) and SpinBot (11.0 vs
43.0). score_battles.py extended with damage/round, round wins and the
aim-error-at-fire distribution (vs the true geometric intercept).

Also confirms the corpus and live feature builder both use bulletSpeed =
power*10, so there is no train/inference feature mismatch.
2026-10-06 08:37:17 +02:00
SirStone 84ad673f4b README: gun plumbing diagnosis — baseline hits stationary, the ELM default misses 2026-10-06 08:28:15 +02:00
SirStone a024a2e32b DevControlBot: fix gun plumbing — detach from body turn, non-blocking fire, degree slop
The gun turn math is written for setAdjustGunForBodyTurn(true) (absolute bearing
-> normalizeRelativeAngle(bearing - getGunDirection())), but the flag was never
set: the gun inherited the body's turn. Set the three adjust flags.

Two firing bugs found while measuring the geometric baseline against a stationary
SittingDuck:
- computeGun called the BLOCKING fire(), which calls go() itself, and the run
  loop called go() again => every shot double-stepped the server. Use setFire.
- the fire slop compared a degrees error against degToRad(FireSlopDeg) = 0.052
  deg. Compare in degrees; 1 deg (3 deg fired mid-slew, up to 3 deg off).

Baseline vs stationary: 110/112 hits, aim error sd 0.04 deg.
2026-10-06 08:28:15 +02:00
SirStone dacb650692 DevControlBot: an ELM gun, its geometric baseline, and an honest null result
Firing wired in behind a compile-time A/B switch (-d:baselineGun): both guns go
through the same predictAim() call and differ only by the learned correction, so
the measured difference is attributable. radar.nim now keeps the two most recent
scans (velocity, scan age, own displacement).

Measured over 20 recorded rounds each vs DrussGT, CassiusClay, Komarious and
Phoenix: the ELM gun LOSES to the geometric baseline on three of four opponents
(Phoenix 51.0% vs 99.5% hit rate). README has the table, the diagnosis and the
two in-game-only bugs measuring exposed (degrees/radians, and features whose
in-game range lies outside the corpus).
2026-10-05 23:48:58 +02:00
SirStone 818bad50fd Train the aim-error ELM on the pooled 9-opponent corpus and export it
train_elm_gun.nim trains H=128, lambda=1e-2, decay=1.0 over every opponent in
tools/elm_bench/gen and writes modules/ELM/elm_gun_weights.txt (trainRmse 0.431
vs a constant baseline 0.933). Pooled is the point: the gun meets opponents it
was not fitted on.
2026-10-05 23:48:58 +02:00
SirStone a94c6131fd ELM engine: export/import weights for offline training
loadWeights/exportWeights move the three matrices in and out of a live ELM so a
model can be fitted offline and shipped as a data file.
2026-10-05 23:48:58 +02:00
SirStone 16c71c527a tools/elm_bench: ring label experiment — the ring label is NOT learnable
Gate question: can a ring-based label (a 2-D offset from the belief centre to
where a ray ring touches the enemy) be predicted from our own belief state?
extract_ring.py + bench_ring.nim answer it by MERGING the ring label into
samples_realistic.ndjson, so the ring label and the incumbent 1-D aim-error
label are scored on the SAME rows, the SAME features and the SAME round-group
folds. 8119 of 8676 DrussGT shot rows get a ring label.

Verdict: worse, not richer.

  * The spike's headline is an artifact. The belief is already accurate to
    under 3 px, so a belief-anchored ring touches the enemy on its FIRST ray
    step: ringK = 1.0000 for all 172723 extracted events. The "100% at power
    <= 1.5, 0.2% at power 3.0" pattern is just whether 1 * bulletSpeed fits
    inside the +-18 px belief-error ball. The literal ring label is the 1-tick
    belief extrapolation error, clipped to BotRadius.
  * Same-tick it scores better than the 1-D label (ELM/const 0.2628 vs 0.3629)
    but a single feature, beliefTgtLatVel, already gets -71.8 of the -73.7
    points: the model is re-deriving beliefTgtLatVel * age / beliefDist, i.e.
    its own inputs.
  * Under --prev it collapses to ratio 0.9819 (-1.8%). It depends MORE on the
    same-tick assumption than the 1-D label (-63.7% -> -1.0%), not less.
  * Repaired (--kintercept: k = round(believed range / bullet speed), mean k 42,
    no clipping, 60 px spread) the label is well posed and completely
    unpredictable: best feature +0.5%, best ELM -0.4%, best |corr| 0.09.

So: the belief-extrapolation error at intercept time is not a function of what
we believed, it is the opponent's unmodelled acceleration. Do not ship a ring
label. common_libs/guns/waveelm.nim is the right shape for the same idea and
is a different thing: it fires the ring from the SHOOTER, so the ring measures
an interception radius and bearing and the ELM learns a bias correction to it.
2026-10-05 22:59:41 +02:00
SirStone 8e6af386fc tools/elm_bench/README: activation sweep (tanh / relu / step)
Full 60-config grid per activation on the same features, folds and seed, so
the three runs are directly comparable (act_sweep.log):

  tanh (default)  0.4218 mean per-fold RMSE   (constant 1.1406)
  relu            0.4338  (+2.8%)
  step            0.7476  (+77.3%)

The activation only matters where there is nonlinear structure to expose: on
base 6 and on scan-age alone all three agree to 0.0002 and are all worthless.
tanh stays the default because it is never worse, and because every other
number in this README was produced with it.

Also records why there is no RBF/gaussian option: g(b*||x - a||) reads the
distance to a centre in input space, so it needs centre + width parameters,
its own init and its own Thm 2.2 validation - a different node architecture,
not a different nonlinearity. It would buy nothing here anyway: the signal is
one linear term in beliefPredErr.
2026-10-05 22:59:10 +02:00
SirStone fcaa7ba183 tools/raw_recorder + tr_bots/_salvage: recorder source and the legacy port
tools/raw_recorder/RawRecord.java + shadow/GameRecorder.java  the observer
    that writes the .battle.gz corpora in data/ (gitignored, regenerable)
  tools/raw_recorder/query.py, sample_outline.md               query helpers
    and the shape of a capture
  tr_bots/_salvage/                                           the port audit:
    portaudit/{methods,static}.py, shim/, and the tr_wrappers/*.json + *.sh
    for 29 rescued legacy bots, with legacy_bots/MANIFEST.sha256
2026-10-05 22:43:41 +02:00
SirStone e2d1968a77 Bots: env reporting, TFIL movement, gun selector and docs refresh
DevControlBot   DevControlBot.sh env-file handling and defines, tfil.nim
                  survival-movement rework, README
  ModularBot      .env.example, ModularBot.nim, env_report.nim, vbullet_draw.nim
  PPO_Bot         enemy_tracker.nim
  common_libs     gun_harness/selector.nim
  tests           env_report, lead_gain_legacy, rack_membership,
                  rack_stat_width, tm_pattern_registration adjustments
  docs            env_reference.md, goto-controller-algorithm.md
2026-10-05 22:43:30 +02:00
SirStone 7505fbf089 common_libs/guns: WaveElm ring gun, GUNK knowledge gun, online ELM
guns/elm.nim          online sequential ELM (ridge/RLS), fixed random
                        hidden layer, one pass, no backprop
  guns/waveelm.nim      the WaveElm gun: a simulated omnidirectional expanding
                        ring of probes fired from the SHOOTER, where the ELM
                        learns a BIAS CORRECTION to the ring's reconstructed
                        position (predicting the position outright was measured
                        and refuted: it collapses on abrupt/burst movement)
  guns/gun_knowledge.nim  GUNK: a learned additive angular residual on top of
                        the self-consistent lead forecast. Only answers "which
                        absolute gun direction", nothing else
  guns/docs/            the open-access OS-ELM / ELM reference set plus
                        fetch_papers.sh, which re-downloads it idempotently

Plus the matching test and measurement harnesses (test_waveelm*, test_elm,
test_gun_knowledge, test_knowledge_registration, gk_aim_probe,
measure_gk_{residual,virtual}.py) and the docs README with the citations.
2026-10-05 22:43:22 +02:00
SirStone 68c6af98dc gitignore: also cover ring_*.ndjson.merged 2026-10-05 22:43:07 +02:00
SirStone 8cc62ec825 tools/ring_spike: can a RING label be extracted from the corpora?
Feasibility spike for a ring-based training label. N rays are fired
simultaneously from the shooter's BELIEF centre at bullet speed; the label is
a 2-D positional error from the belief centre to the contact point on the enemy
circle (BotRadius 18 px). Belief is reconstructed with strict --prev
semantics (a bot cannot act on a scan delivered at the end of tick T until
T+1), so the spike already measures the label under the harder assumption.

Also fixes a latent crash in ring_contact: the `last`-sample fallback was
computed and then overwritten by an unconditional p[0], p[1], so any enemy
track with a gap raised TypeError instead of falling back.

Result is NOT what it first looks like -- see the ring-label section of
tools/elm_bench/README.md. The contact search degenerates to k = 1 (the belief
is already within BotRadius of the enemy), and the reported 100% hit rate at
power <= 1.5 versus 0.2% at power 3.0 is an artifact of bullet speed versus
the size of the belief error, not of ray geometry.
2026-10-05 22:42:53 +02:00
SirStone 6d0dd987ca tools/elm_bench: aim-error ELM benchmark suite + findings
Extractors, benchmarks and analysis for "can we predict an opponent's aim
error from our own belief state?". All labels come from BulletFiredEvents;
all features come only from the shooter's own state and its ScannedBotEvent
history (the target's true state is used for the label and never for a
feature, verified by a ground-truth-poisoning re-extraction).

  extract.py / extract_realistic.py   label + oracle features / realistic ones
  gen_analysis.py, analyse_realistic.py, audit_independent.py
  bench.nim, bench_realistic.nim, cross_opponent.nim, online.nim
  gen/*.ndjson                          the per-opponent sample tables
  README.md                             the write-up, ~1200 lines

Headline: DrussGT applies about 13% of the correct lead, and that 13% is
computable from one feature (beliefPredErr) as label ~ 0.8663*predErr +
0.0418. ELM ALL-21 pools to RMSE 0.4220 against a constant 1.1463 (-63%).
The network is not the finding; the single linear term is. Cross-opponent,
--prev leakage audit and an independent re-derivation are in the README.

The top-level samples_realistic*.ndjson are byte-identical to gen/DrussGT* and
are gitignored; gen/ is the authoritative copy.
2026-10-05 22:42:39 +02:00
SirStone 7598f7db4a ELM: pluggable hidden activation (tanh / relu / step)
ActivationKind (atanTanh default, atanRelu, atanStep) on ElmConfig, plus
applyActivation, activationName and parseActivation. The hidden units stay
pure additive nodes: every activation sees the same pre-activation s = a.x + b
and differs only in the scalar nonlinearity g.

tanh is unchanged and bit-identical to the previous version, so existing
callers cannot regress. Two init details are activation-aware, because relu and
step are dead for s <= 0: they get bias U[0,1] instead of U[-1,1], and hidden
weight scale 8/sqrt(inputDim) instead of 1/sqrt(inputDim) (at the tanh scale
the pre-activations barely straddle 0, the Gram matrix loses rank and Thm 2.2
interpolation fails outright).

No RBF option: g(b*||x - a||) reads the distance to a centre in input space,
which is a different node architecture (extra centre + width parameters, its
own init and its own Thm 2.2 validation), not a different g.

Adds tests/test_elm.nim (9 suites) and a `nimble test` task. All pass.
2026-10-05 22:42:12 +02:00
SirStone fe8b1eddff Add curated legacy Robocode roster (28 bots) and Tank Royale booter
Curated roster: 34 classic-Robocode archives were downloaded, measured in real
Tank Royale battles and curated to 28 usable bots, now in legacy_bots/<Name>/
(<Name>.jar + <Name>.json + <Name>.sh) with checksums in MANIFEST.sha256.
Six were dropped as NOT_USEFUL and deleted from tr_bots/_salvage/legacy_bots/
and tr_bots/_salvage/tr_wrappers/, with the rationale recorded in
legacy_bots/README.md and tools/robocode_shim/LEGACY_BOTS.md:

  - Nene, Seraphim  - Azuma-framework melee bots, completely inert (0 scans,
                      0 shots); getRobotRunnable() returns null so the shim has
                      no driver path for them.
  - Aurora          - fires 6 shots and crawls.
  - FloodMini, LightningBug, Aristocles - near-stationary turrets: they scan and
                      fire but land 0 hits and take 10+ hits every round.

DrussGT is the reference bot and is deliberately NOT in legacy_bots/: it lives in
tr_bots/DrussGT and is now vendored with its sources under
tools/robocode_shim/vendor/drussgt/.

Repo-relative paths replace /tmp: every <Name>.sh resolves the shim and the
vendor jars via $REPO (../..), and none hardcodes a server URL, a /tmp data
path, or anything under ~/Downloads. SERVER_URL/SERVER_SECRET come from the
environment, which the booter populates from its own -Dserver.url /
-Dsystem.secret system properties.

Booter: tools/booter/robocode-tankroyale-booter-0.35.5-all.jar, copied from a
local tank-royale build, plus a README covering the real CLI. Note the command
is `boot`; the upstream README's `run` is stale. Verified it discovers all 28
kept bots via both `dir` and `info`.

Licensing: every third-party jar here reads "not stated in jar", and DrussGT is
GPL. The repo owner has explicitly waived this - the repository is PRIVATE and
lives on their own LAN. Do not mirror or redistribute without revisiting that.

.gitignore flipped back to tracking legacy_bots/**/*.jar; an over-broad *.jar
rule already cost us the only copy of DrussGT.jar once.
2026-10-04 22:18:28 +02:00
SirStone 67d185880d DevControlBot 1.2.0: TFIL survival movement + universal battle runner
Ported "the floor is lava" (TFIL) movement into DevControlBot as a
self-contained module, DevControlBot/modules/tfil.nim. It has no runtime
dependency on common_libs/: the port is a standalone implementation,
parity-verified against the common_libs original over 2000 differential
ticks with zero divergences. Do not re-introduce the dependency and do
not edit the original to match.

Debug graphics (per-tile lava heat, tracked bullets and their danger
corridors, enemy core/aura, reachable hull, committed tile) are OFF by
default and compile-time gated behind -d:tfilDebug; see README.md for
the plain `nim c` invocation, since nimble runBot does not forward
compile flags.

Wired into DevControlBot.nim: movement computed between commandRadar()
and go(), fire-event tracking wired up, staleness handling for scanned
enemies, and body colour set to BLACK at init (movement and radar both
claim colour now).

Also adds tools/test_runner, a shared battle-test runner usable by any
garage, with an Observer adversary for quick floor checks.
2026-10-04 18:16:24 +02:00
SirStone de0dd50d6e Purge AGENTS.md of code explanation; keep inventory and diagrams
AGENTS.md is now an inventory of what exists plus the mermaid behaviour
diagrams — not a narration of the code. The source and its doc comments are
the carrier of truth for how the bot works; a prose retelling in AGENTS.md
only goes stale against them.

Removed: blocks that duplicated what the source already says, a stale line
that contradicted DevControlBot.sh's actual no-argument behaviour, and the
prior bug-fix history (which is a record of the past, not guidance for the
next change). 384 -> 238 lines.

Kept byte-identical: the behaviour diagrams, the rules (git, version/tag,
colour convention), the build and run commands, and the physics and
coordinates references.

Two constraints stay as one-liners, because they are the two ways this bot
has actually been broken: command the radar BEFORE go(), and keep all radar
logic in modules/radar.nim.
2026-10-04 16:55:05 +02:00
SirStone caa096d6c9 Add radar lock and melee sweep to DevControlBot
The bot now drives its radar every tick. It still never moves and never
fires: body, turret and gun stay white ("not programmed"), while the
radar paints itself black at init to mark itself as working.

- modules/radar.nim replaces the earlier multi-module radar design with a
  single module holding the whole of it: target memory, mode selection
  and both commands
- two commands, picked from the only fact the bot is sure of (the API's
  getEnemyCount()): one enemy plus a target in hand -> LOCK, servo onto
  its bearing; anything else -> SWEEP at 45 deg/tick, the radar's physics
  cap, a full revolution every 8 ticks
- the lock turns by 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.
  That crossing is what produces a fresh ScannedBotEvent every tick: a
  scan per tick, with no rescan to wait for. Turning by the bare error
  parks the radar on the bearing and the scans stop
- commandRadar() is called before go() on every path, so there is no idle
  branch to fall into and switching modes costs zero turns
- idea derived from ModularBot's radar (Apache-2.0) via common_libs/;
  common_libs/ is not edited in place
- AGENTS.md gains mermaid behaviour diagrams plus pointers to the physics
  and coordinate references
- version bumped to 1.1.0 in both DevControlBot.nimble and
  DevControlBot.json so the two agree

Compiled against robocode_tankroyale_botapi 1.0.7.
2026-10-04 16:22:42 +02:00
SirStone 305c3977a6 Add PLAN.md rule, garage .gitignore, remove hardcoded server port hint
- AGENTS.md: mark PLAN.md as user-owned (never modify; it stays tracked)
- move the .env ignore rule to the garage root so it covers any depth
- drop the hardcoded "port 7654" hint from the no-server message; the target
  is now reported from the resolved SERVER_URL. The 7654 fallback remains
  only as the upstream TR default.
2026-10-03 16:39:02 +02:00
SirStone 59fad00b5c Add DevControlBot garage: skeleton bot with release/debug build script
A minimal Tank Royale bot that boots and stands still. Body, gun and radar
are set to white once at init (team convention: white = not programmed yet);
the tick loop only calls go().

- DevControlBot/ holds the single bot module, its metadata JSON, the
  BotLauncher entry script and the nimble file
- DevControlBot.sh is a thin wrapper around the runBot nimble task:
  release build by default, --debug for the classic diagnostic build
- dependencies resolve at run time from the global nimble store via
  `nimble path`; optional .env (gitignored) supplies env vars such as
  SERVER_URL, with existing environment variables taking precedence
- build happens in a throwaway mktemp dir removed on exit; no artifacts
2026-10-03 16:32:27 +02:00
320 changed files with 74644 additions and 252 deletions
+47 -1
View File
@@ -56,7 +56,7 @@ common_libs/tests/test_tsetlin_live
common_libs/tests/test_tm_pattern_learning
# measurement tool binaries (no extension); sources are measure_*.nim
tr_bots/
tr_bots/*
# Measurement-tool binaries (extensionless; their .nim/.py/.txt sources stay tracked)
common_libs/tests/measure_tm_readapt
@@ -72,3 +72,49 @@ common_libs/tests/diag_tm_pattern_offline
# Primary source archive kept locally, NOT tracked (12 MB)
docs/BitBrain_C_code.zip
# raw_recorder build output
tools/raw_recorder/out/
tools/raw_recorder/shadow-classes/
# Legacy champion bot jars ARE committed: their license reads "not stated in
# jar" for every bot (see tools/robocode_shim/robots.json), but the repo owner
# has explicitly waived that concern — it is a PRIVATE repo on their own LAN.
# The jars are not reproducible from here, and an over-broad *.jar rule already
# cost us the only copy of DrussGT.jar once.
!legacy_bots/**/*.jar
legacy_bots/**/*.jar.*
# Raw recorded battle corpora (regenerable via tools/raw_recorder):
# data/drussgt_raw/ 26 MB, one 20 MB capture
# data/generalization_raw/ 34 MB, 8 opponent captures
# These are the INPUT to tools/elm_bench; committing the DERIVED samples
# (tools/elm_bench/gen/*.ndjson) is enough to rerun every experiment.
data/drussgt_raw/
data/generalization_raw/
# Research PDFs (60 MB). Regenerable: common_libs/guns/docs/fetch_papers.sh
# (same call as the BitBrain zip rule above).
docs/papers/*.pdf
# Root-level build output (garage builds go to *_garage/out/, this was not)
/out/
# Extensionless build artifacts
DevControlBot_garage/DevControlBot/DevControlBot
DevControlBot_garage/DevControlBot/modules/ELM/elm_tests
common_libs/guns/waveelm
common_libs/tests/measure_melee_strong_field
common_libs/tests/measure_tfil_arrival
common_libs/tests/measure_tfil_pick_defects
common_libs/tests/measure_tfil_picker_loss
tools/elm_bench/bench
tools/elm_bench/bench_realistic
tools/elm_bench/bench_ring
tools/elm_bench/cross_opponent
# Generated sample tables. The authoritative copies live in tools/elm_bench/gen/
# (committed); the top-level ones are the DrussGT extract, byte-identical.
tools/elm_bench/samples*.ndjson
tools/elm_bench/ring_*.ndjson
tools/elm_bench/ring_*.ndjson.merged
+2
View File
@@ -0,0 +1,2 @@
# User-authored environment variables (e.g. SERVER_URL) — never committed
.env
+44
View File
@@ -0,0 +1,44 @@
# 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.
## CHIMERA modules (M3.5 + M4)
`src/ChimeraBot/chimera/` holds the CHIMERA libraries —
`physics.nim` (server-math mirror), `ledger.nim` (intent ledger), `dsl.nim` (the
v0.2 kernel library, **12 kernels**: the M2 set plus `STATIC_CORNER`, the STATIC
corner-park mode, and adaptive/heat-gated v0.2 params), `hedge.nim` (Hedge
posterior), `oracle.nim` (G1 harness), `observer.nim` (observation sidecar) and
`twinsim.nim` (offline counterfactual rollout, M4).
`observer.nim` is wired into `ChimeraBot.nim` as an **observation-only** sidecar:
it folds the scan stream into the ledger + Hedge and writes JSONL telemetry to
`/tmp/chimera_twin` — it never issues a command, so the bot's behaviour is
byte-identical with or without it. `twinsim.nim` is **offline analysis only** at
M4 (nothing is wired into commands); it replays that telemetry and rolls the
posterior mixture forward under a candidate plan.
Benchmarks: `tests/bench_g4.nim` (live identification, G4) and
`tests/bench_g5.nim` (offline twin-vs-persistence rollout, G5). Both write only
to `/tmp`.
@@ -0,0 +1,18 @@
# G1 oracle-convergence table
Auto-generated by `tests/test_oracle_g1.nim` (deterministic; regenerate with `nimble test`). T* = 300 ticks, threshold = 0.90, env = default synthetic arena (800x600, no sensor error). A PASS means posterior(kernel) reached the threshold within T*.
| kernel | idTick | finalPosterior | censorRate | pass |
|---|---:|---:|---:|---|
| ORBIT_LOCK | 61 | 0.95170 | 0.0000 | PASS |
| ORBIT_BALLIST | 28 | 0.94312 | 0.0000 | PASS |
| STOP_AND_GO | 37 | 0.97779 | 0.0000 | PASS |
| ZIGZAG | 161 | 0.94407 | 0.0000 | PASS |
| RAMMER | 152 | 0.90926 | 0.0000 | PASS |
| CORNER_RUN | 99 | 0.90280 | 0.0000 | PASS |
| WALLCRAWL | 47 | 0.95033 | 0.0000 | PASS |
| STATIC | 27 | 0.97278 | 0.0000 | PASS |
| STATIC_CORNER | 68 | 0.80642 | 0.0000 | PASS |
| RANDOM_WALK_A | 19 | 0.97378 | 0.0000 | PASS |
| RANDOM_WALK_B | 14 | 0.96952 | 0.0000 | PASS |
| RANDOM_WALK_C | 14 | 0.97334 | 0.0000 | PASS |
+16
View File
@@ -0,0 +1,16 @@
# G4 unified idTicks (M5.5)
Metric: per round, round-relative tick at which `max_kernel posterior > 0.8`; median / p90 / id-fraction over all rounds. Pass = median <= 300 AND id% >= 80. 3 runs x 5 rounds. Generated by `tests/bench_g4.nim`.
| opponent | median | p90 | id-fraction% | expMedian | argmaxOk% | finalPost% | censor% | ade5 | pass |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---|
| Corners | 1 | 53 | 100.0 | 1 | 60.0 | 94.0 | 0.00 | 3.082 | PASS |
| Crazy | 36 | 127 | 100.0 | 73 | 66.7 | 60.3 | 0.00 | 8.307 | PASS |
| Fire | 1 | 19 | 100.0 | 1 | 100.0 | 96.6 | 0.00 | 2.942 | PASS |
| RamFire | 1 | 23 | 100.0 | 1 | 100.0 | 90.9 | 0.00 | 4.653 | PASS |
| SpinBot | 1 | 35 | 100.0 | 1 | 100.0 | 94.5 | 0.00 | 1.727 | PASS |
| TrackFire | 1 | 19 | 100.0 | 1 | 100.0 | 96.8 | 0.00 | 0.354 | PASS |
| VelociBot | 1 | 27 | 100.0 | 60 | 26.7 | 90.0 | 0.00 | 9.399 | PASS |
| Walls | 60 | 357 | 100.0 | 77 | 80.0 | 56.2 | 0.00 | 6.008 | PASS |
Pooled over 120 rounds: median 1, p90 73, id-fraction 100.0%. G4 pass: 8/8.
+23
View File
@@ -0,0 +1,23 @@
# G5' v2 interventional eval (M5.5)
Horizon 5, probe-following windows only. MOVING = Crazy, SpinBot, VelociBot, Walls; STATIC = RamFire, Corners, TrackFire, Fire. Source: /tmp/chimera_g6_on.
| opponent | probes | twinADE | persADE | margin | twinWin% | dirTwin% | dirPers% |
|---|---:|---:|---:|---:|---:|---:|---:|
| Corners | 153 | 2.734 | 0.539 | -2.196 | 3.9 | 90.2 | 97.4 |
| Crazy | 208 | 8.850 | 2.900 | -5.951 | 17.3 | 86.1 | 94.7 |
| Fire | 200 | 3.535 | 1.628 | -1.907 | 17.0 | 92.5 | 91.5 |
| RamFire | 100 | 3.866 | 1.729 | -2.137 | 10.0 | 81.0 | 94.0 |
| SpinBot | 201 | 1.770 | 1.901 | 0.131 | 94.5 | 100.0 | 98.5 |
| TrackFire | 91 | 0.198 | 0.000 | -0.198 | 0.0 | 98.9 | 100.0 |
| VelociBot | 196 | 9.434 | 2.110 | -7.323 | 11.2 | 77.0 | 93.9 |
| Walls | 219 | 5.944 | 1.398 | -4.546 | 10.0 | 88.6 | 93.6 |
**MOVING subset**: 824 windows, twinWin 32.8% (bar >=70%: FAIL). **FULL suite**: 1368 windows, twinWin 23.4%.
## STATIC-subset saturation
- **RamFire**: mean |enemy speed| 2.79 u/tick, 55% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -2.137).
- **Corners**: mean |enemy speed| 2.59 u/tick, 65% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -2.196).
- **TrackFire**: mean |enemy speed| 0.00 u/tick, 100% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -0.198).
- **Fire**: mean |enemy speed| 1.06 u/tick, 75% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence (v~0) is exactly optimal and the twin's stationary/corner kernels coincide with it — the twin can only match or lose, never win (margin -1.907).
+31
View File
@@ -0,0 +1,31 @@
# G6 ablation ladder (M5.5): probes x carry-over
Unified idTicks (round-relative, max posterior > 0.8), median over 3 runs x 5 rounds; id% = fraction of rounds identified. Arms: on = probes+carry, off = -probes, reset = -carry, offreset = both. Generated by `tests/bench_g6.nim`.
| opponent | on med | on id% | off med | off id% | reset med | reset id% | offreset med | offreset id% |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| Corners | 1 | 100.0 | 1 | 100.0 | 44 | 100.0 | 37 | 100.0 |
| Crazy | 16 | 100.0 | 30 | 100.0 | 34 | 100.0 | 65 | 100.0 |
| Fire | 1 | 100.0 | 1 | 100.0 | 19 | 100.0 | 17 | 100.0 |
| RamFire | 1 | 100.0 | 1 | 100.0 | 23 | 100.0 | 23 | 100.0 |
| SpinBot | 1 | 100.0 | 1 | 100.0 | 27 | 100.0 | 27 | 100.0 |
| TrackFire | 1 | 100.0 | 1 | 100.0 | 17 | 100.0 | 16 | 100.0 |
| VelociBot | 1 | 100.0 | 1 | 100.0 | 31 | 100.0 | 31 | 100.0 |
| Walls | 52 | 100.0 | 52 | 100.0 | 54 | 100.0 | 51 | 100.0 |
**MOVING-subset** pooled: on 1 (id 100.0%), off 6 (id 100.0%), reset 33 (id 100.0%), offreset 39 (id 100.0%). Probes cut = 83.3%, carry-over gain = 97.0%. **G6 bar (>=20% cut, MOVING-subset): PASS**.
**FULL-suite** pooled: on 1 (id 100.0%), off 1 (id 100.0%), reset 27 (id 100.0%), offreset 28 (id 100.0%). Probes cut = 0.0%, carry-over gain = 96.3%. **G6 bar (>=20% cut, FULL-suite): FAIL**.
## Run-to-run variance (M5.5 record, not auto-generated)
The MOVING-subset probe cut is **not stable across bench invocations**. Four
separate 4-arm runs (each 3 runs x 5 rounds per opponent) gave ON/OFF pooled
medians **17/15 (-13.3%)**, **13/17 (+23.5%)**, **13/2 (-550%)**, **1/6 (+83.3%)**.
The sign flips and the magnitude swings by two orders of magnitude; the median
across the four invocations is ON 13 vs OFF 10.5, i.e. **-24%**. Only the
carry-over effect is large and stable (reset->on gain 54.1 / 61.8 / 62.9 / 97.0%).
**Verdict: probes are still null — no robust >= 20% identification-speed cut
after probe set v2 (G6 probe rung FAIL).** Per the falsification matrix this
indicts the probe component-value claim, not the inference layer (G1 green).
+29
View File
@@ -0,0 +1,29 @@
# G7 head-to-head + no-regression floor (M6)
Three arms from the SAME tree: **inert** (`-d:chimeraInert`, == M1 exact copy), **full** (default: probes + fusion + influence), **noprobe** (`-d:chimeraNoProbes`: fusion + influence). Head-to-head: full vs inert mirror 1v1, 10 matches x 5 rounds. Suite: 5 rounds per arm per opponent vs the 8 primary sample bots. Generated by `tests/bench_g7.nim`.
## Head-to-head: full vs inert
| metric | value |
|---|---:|
| matches | 10 x 5 rounds |
| full win-rate | 54.0% |
| full survival | 40 / inert 39 |
| score margin (full-inert) | 1621.0 |
| **bar (>=50%)** | **PASS** |
## Suite no-regression floor (5 rounds per arm)
| opponent | full W% | full margin | full surv | inert W% | inert margin | inert surv | noProbe W% | noProbe margin |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| Corners | 100.0 | 2466.0 | 5 | 100.0 | 2477.0 | 5 | 100.0 | 2486.0 |
| Crazy | 100.0 | 1669.0 | 5 | 100.0 | 1867.0 | 5 | 100.0 | 1311.0 |
| Fire | 100.0 | 2620.0 | 5 | 100.0 | 2607.0 | 5 | 100.0 | 2583.0 |
| RamFire | 100.0 | 2468.0 | 5 | 100.0 | 2574.0 | 5 | 100.0 | 2556.0 |
| SpinBot | 100.0 | 1798.0 | 5 | 100.0 | 1618.0 | 5 | 100.0 | 1842.0 |
| TrackFire | 100.0 | 2349.0 | 5 | 100.0 | 2406.0 | 5 | 100.0 | 2414.0 |
| VelociBot | 80.0 | 1132.0 | 4 | 80.0 | 927.0 | 4 | 100.0 | 2005.0 |
| Walls | 100.0 | 1808.0 | 5 | 100.0 | 1912.0 | 5 | 100.0 | 1693.0 |
**No-regression (full >= inert on every opponent): PASS**.
Head-to-head win rate 54.0% (bar >=50%: PASS).
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"
}
+352
View File
@@ -0,0 +1,352 @@
## 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
import ChimeraBot/chimera/observer
import ChimeraBot/chimera/dsl
import ChimeraBot/chimera/probes
import ChimeraBot/chimera/physics
import ChimeraBot/chimera/influence
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
observer: Observer ## observation-only sidecar (§12 G3/G4 telemetry)
opponentLabel: string ## telemetry filename label (env, observation-only)
probes: ProbeScheduler ## active causal probing (spec §9, M5); disabled by
## -d:chimeraNoProbes (see ProbesEnabled)
proc newChimeraBot*(): ChimeraBot =
result = ChimeraBot()
result.mover = initTFIL() # movement is programmed -> body/turret/gun BLACK
result.gun = initElmGun(priorScale = OnlinePriorScale) # hidden layer loaded, online
# Telemetry sink: throwaway output only ever lives in /tmp (garage rule).
# The env override is for scratch test dirs; the bots never read env for
# behaviour, only for this observation-log destination.
let telemetryDir = getEnv("CHIMERA_TELEMETRY_DIR", "/tmp/chimera_twin")
# The API's getBotName() is not populated (updateBotNames is never invoked), so
# the benchmark harness supplies the opponent token via env for the telemetry
# filename; it labels observations, it does not change behaviour.
result.opponentLabel = getEnv("CHIMERA_OPPONENT", "")
result.observer = initObserver(allKernels(), telemetryDir)
when ProbesEnabled:
result.probes = initProbeScheduler(allKernels())
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
# Observation sidecar: fold the scan stream into the intent ledger + posterior
# and record telemetry. Observation-only — it issues no command of any kind.
# `opponent` labels the telemetry file; when the harness did not supply a label
# it falls back to the (typically empty) API name lookup.
let opp = (if bot.opponentLabel.len > 0: bot.opponentLabel
else: getBotName(e.scannedBotId))
bot.observer.observeScan(bot.tick, e.x, e.y, e.direction, e.speed, e.energy,
getX(), getY(), opp,
getArenaWidth().float, getArenaHeight().float,
getDirection(), getSpeed())
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 onRoundStarted*(bot: ChimeraBot, e: RoundStartedEvent) =
## Per-round reset of the identification posterior (uniform, as CHIMERA G4
## requires — e.g. Corners re-samples its start corner each round). The
## observation sidecar is the only consumer; no command changes.
bot.observer.startRound(e.roundNumber)
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()
# close the round's telemetry file with the final kernel trace (observation
# sidecar only; no command paths are touched)
bot.observer.endRound()
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())
# Probe advisory (spec §9, M5): past the budget interval AND when the
# survival gate allows, the commanded movement this tick becomes the chosen
# probe; otherwise the TFIL command is untouched. `-d:chimeraNoProbes`
# removes this block entirely (G6 ablation OFF arm).
var cmdSpeed = speed
var cmdTurn = turnRate
# CHIMERA influence overlay (spec §10, M6): a small tie-break on the TFIL
# command toward the fused-safest plan, never inside an active bullet dodge
# (reflexBusy). `-d:chimeraNoFusion` / `-d:chimeraInert` remove it entirely.
when FusionEnabled:
if bot.observer.hasCurrent:
let (sx, sy) = (getX(), getY())
let fused = bot.observer.fusedPrediction()
let adv = overlay(bot.observer.fusedInfluence(), speed, turnRate,
sx, sy, getDirection(), getSpeed(), fused,
bot.mover.dodgeActive(sx, sy))
if adv.applied:
cmdSpeed = adv.speed
cmdTurn = adv.turnRate
var probeFired = false
when ProbesEnabled:
if bot.observer.hasCurrent:
let porigin = bot.observer.probeOrigin()
let gunBearing = bearingTo(porigin.ox, porigin.oy,
porigin.ex, porigin.ey)
let ctx = ProbeContext(
tick: bot.tick, ourEnergy: getEnergy(),
ownX: porigin.ox, ownY: porigin.oy, ownSpeed: porigin.ospeed,
arenaW: getArenaWidth().float, arenaH: getArenaHeight().float,
enemyX: porigin.ex, enemyY: porigin.ey,
enemyGunHeat: bot.observer.enemyGunHeat(),
enemyAimedAtUs: aimedAtUs(porigin.ox, porigin.oy,
porigin.ex, porigin.ey, porigin.edir),
ourGunHeat: getGunHeat(),
ourGunAimed: abs(wrap180(gunBearing - getGunDirection())) <= 10.0,
roundLimit: RoundSoftLimit)
let decision = bot.probes.consider(porigin, ctx)
if decision.trigger:
bot.observer.writeProbeEvent(bot.tick, $decision.candidate.kind,
decision.gate.reason, decision.entropyBefore,
decision.entropyAfter, decision.candidate.turnRate,
decision.candidate.targetSpeed)
if decision.gate.allow:
cmdSpeed = decision.candidate.targetSpeed
cmdTurn = decision.candidate.turnRate
# GUN probe (M5.5): the probe IS the shot. Issued only when the
# camouflage gate kept it in the candidate set (cool + aligned).
if decision.candidate.fire > 0.0:
discard setFire(decision.candidate.fire)
probeFired = true
setTargetSpeed(cmdSpeed)
setTurnRate(cmdTurn)
if not probeFired:
bot.computeGun() # gun intent, also before go()
go()
bot.observer.writeTick(bot.tick) # observation telemetry, after 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)
+266
View File
@@ -0,0 +1,266 @@
# 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"
exec "nim c -r --hints:off ../tests/test_physics.nim"
exec "nim c -r --hints:off ../tests/test_ledger.nim"
exec "nim c -r --hints:off ../tests/test_hedge.nim"
exec "nim c -r --hints:off ../tests/test_oracle_g1.nim"
exec "nim c -r --hints:off ../tests/test_observer.nim"
exec "nim c -r --hints:off ../tests/test_twinsim.nim"
exec "nim c -r --hints:off ../tests/test_probes.nim"
exec "nim c -r --hints:off ../tests/test_residual.nim"
exec "nim c -r --hints:off ../tests/test_fusion.nim"
exec "nim c -r --hints:off ../tests/test_influence.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,389 @@
## CHIMERA DSL v0 — the null-hypothesis kernel library.
##
## A *kernel* is a small deterministic state machine that maps the observable
## enemy state to one intent `(turnRate, targetSpeed, fire)`. Source of truth:
## `docs/chimera-spec.md` §6 (inventory) and §12 (the sample-bot behaviour table
## that fixes each kernel's provenance).
##
## M2 scope: the spec's K1/K5/K6/K7/K9/K10 kernels plus the SpinBot/Crazy
## variants (ORBIT_BALLIST, ZIGZAG). K2/K3/K4/K8 are deferred to M3 — they are
## not needed for G1 and are not registered here.
##
## Kernel memory is explicit (`KernelMem`), so a step is a pure function of
## `(observed state, caller state, params, memory)` and reruns are byte-identical.
import std/math
import ./physics
type
EnemyState* = object
## What the twin can observe about the enemy on the current tick.
tick*: int
x*: float64
y*: float64
direction*: float64
speed*: float64
energy*: float64
MyState* = object
## Our own position — the target of orbit/ram kernels.
x*: float64
y*: float64
Intent* = object
turnRate*: float64 ## commanded body turn, deg/tick
targetSpeed*: float64 ## commanded target speed, units/tick
fire*: float64 ## fire power, 0 = no fire
Params* = object
## Generic parameter slots. Unused slots keep their defaults.
range*: float64 ## preferred orbit range (ORBIT_LOCK)
hysteresis*: float64 ## orbit hysteresis band (ORBIT_LOCK)
dir*: float64 ## +1 / -1 preferred tangential direction
speed*: float64 ## cruise speed
margin*: float64 ## wall proximity margin
segmentLen*: float64 ## wall-crawl segment length
zigzagTicks*: int ## Crazy-style periodic 180 flip interval
period*: int ## STOP_AND_GO oscillation period (VelociBot: 64)
fwdSpeed*: float64 ## STOP_AND_GO forward cruise speed (VelociBot: 4)
backSpeed*: float64 ## STOP_AND_GO backward cruise speed (VelociBot: -6)
corner*: int ## initial corner index (CORNER_RUN / STATIC corner mode)
fireCooldown*: int ## legacy slot, unused since v0.2 (fire is heat-gated)
rngClass*: int ## 0 = LCG, 1 = xorshift64, 2 = splitmix64
seed*: uint64 ## RNG seed
arenaW*: float64
arenaH*: float64
## v0.2 additions (M3.5). All default to the v0 behaviour so the existing
## kernels keep their semantics; only the newly registered instances and the
## kernels that opt in read them.
mode*: int ## STATIC: 0 = free (TrackFire/Fire), 1 = corner-park (Corners)
idleTurn*: float64 ## RAMMER idle-phase spin magnitude, deg/tick (RamFire: 5)
idleFraction*: float64 ## RAMMER idle-phase fraction of each cycle, 0..1
cycleTicks*: int ## RAMMER duty-cycle length; 0 = always approach
ramBoost*: float64 ## RAMMER approach speed margin (RamFire: forward(dist+5))
KernelMem* = object
phase*: int
counter*: int
latch*: float64
startDir*: float64
segX*: float64
segY*: float64
rngState*: uint64
heat*: float64 ## estimated enemy gun heat (starts at 3 each round)
KernelStep* = proc(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent {.nimcall.}
Kernel* = object
name*: string
step*: KernelStep
defaultParams*: Params
# ── shared helpers ──────────────────────────────────────────────────────────
proc defaultParams*(): Params =
Params(range: 300.0, hysteresis: 60.0, dir: 1.0, speed: 6.0, margin: 40.0,
segmentLen: 200.0, zigzagTicks: 60, corner: 0, fireCooldown: 15,
rngClass: 0, seed: 0x2545F4914F6CDD1D'u64, arenaW: 800.0, arenaH: 600.0,
period: 64, fwdSpeed: 4.0, backSpeed: -6.0,
mode: 0, idleTurn: 5.0, idleFraction: 0.0, cycleTicks: 0,
ramBoost: 5.0)
proc defaultMemory*(p: Params): KernelMem =
KernelMem(phase: 0, counter: 0, latch: 1.0, startDir: 0.0,
segX: 0.0, segY: 0.0, rngState: p.seed, heat: 3.0)
proc dist(e: EnemyState, m: MyState): float64 =
hypot(m.x - e.x, m.y - e.y)
proc nearWall(e: EnemyState, p: Params): bool =
e.x < p.margin or e.x > p.arenaW - p.margin or
e.y < p.margin or e.y > p.arenaH - p.margin
proc nextRng*(state: var uint64, cls: int): uint64 =
## Deterministic RNG classes (spec K7): A = LCG, B = xorshift64, C = splitmix64.
case cls
of 0:
state = state * 6364136223846793005'u64 + 1442695040888963407'u64
of 1:
state = state xor (state shl 13)
state = state xor (state shr 7)
state = state xor (state shl 17)
else:
state += 0x9E3779B97F4A7C15'u64
var z = state
z = (z xor (z shr 30)) * 0xBF58476D1CE4E5B9'u64
z = (z xor (z shr 27)) * 0x94D049BB133111EB'u64
return z xor (z shr 31)
state
proc rngUnit(state: var uint64, cls: int): float64 =
## Uniform in [0, 1) from the selected class.
float64(nextRng(state, cls) shr 11) / 9007199254740992.0
proc fireGate(mem: var KernelMem, want: float64): float64 =
## v0.2 cadence: the enemy can fire only at gun heat 0, and every shot resets
## heat to `1 + power/5` (physics.gunHeat). The ledger observes fire through
## the enemy's energy drop, so a heat-gated channel is what the G5 fire Brier
## scores against. Replaces the v0 artificial `fireCooldown` (kept, unused).
if mem.heat > 0.0:
mem.heat -= 1.0
if mem.heat < 0.0: mem.heat = 0.0
if want <= 0.0 or mem.heat > 0.0: return 0.0
mem.heat = gunHeat(want)
want
proc smartFirePower(distance, energy: float64): float64 =
## Corners' smartFire(distance) (§12 table): long range or low energy -> 1.
if distance > 200.0 or energy < 15.0: 1.0
elif distance > 50.0: 2.0
else: 3.0
proc ramFirePower(energy: float64): float64 =
## RamFire's onHitBot ladder, scaled by the enemy's remaining energy.
if energy > 16.0: 3.0
elif energy > 10.0: 2.0
elif energy > 4.0: 1.0
elif energy > 2.0: 0.5
elif energy > 0.4: 0.1
else: 0.0
# ── K1 ORBIT_LOCK — orbit with hysteresis direction lock ────────────────────
proc stepOrbitLock(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
let b = bearingTo(e.x, e.y, m.x, m.y)
let r = dist(e, m)
var desired: float64
if r > p.range + p.hysteresis:
desired = b # too far: close in
elif r < p.range - p.hysteresis:
desired = wrap180(b + 180.0) # too close: back off
else:
desired = wrap180(b + 90.0 * p.dir) # tangential, latched direction
result.turnRate = clamp(wrap180(desired - e.direction),
-MaxTurnRate, MaxTurnRate)
result.targetSpeed = p.speed
result.fire = fireGate(mem, 0.3)
# ── K-spin ORBIT_BALLIST — SpinBot: constant spin at fixed speed ────────────
proc stepOrbitBallist(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: SpinBot (turn 10000, maxSpeed 5, forward 10000, fire(3) on scan).
## `setTurnRight(10000)` spins CLOCKWISE = negative turn rate, so the default
## registered instance carries `dir = -1`; a CCW spinner is a distinct kernel.
result.turnRate = MaxTurnRate * p.dir
result.targetSpeed = 5.0
result.fire = fireGate(mem, 3.0) # SpinBot: fire(3) on scan
# ── K4 STOP_AND_GO — VelociBot: periodic forward/back speed oscillation ────
proc stepStopAndGo(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: VelociBot (setTargetSpeed(4) at t%64==0, setTargetSpeed(-6) at
## t%64==32, turnRate 0, gun turn 15, fire(1) on scan). The commanded target
## speed is sticky in the API, so it stays +4 for the first half of the period
## and -6 for the second half; turn rate is 0 throughout (except brief
## hit/turn bursts, which the speed/turn channels barely weight).
result.turnRate = 0.0
let phase = e.tick mod p.period
result.targetSpeed = if phase < p.period div 2: p.fwdSpeed else: p.backSpeed
result.fire = fireGate(mem, 1.0) # VelociBot: fire(1) on scan
# ── ZIGZAG — Crazy: long forward runs + periodic 180 flips ──────────────────
proc stepZigzag(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: Crazy (forward 40000, turnRight 180, reverses on wall/ram).
result.targetSpeed = MaxForwardSpeed
result.fire = fireGate(mem, 1.0) # Crazy: fire(1) on scan
if mem.phase == 0:
result.turnRate = 0.0
inc mem.counter
if nearWall(e, p) or mem.counter >= p.zigzagTicks:
mem.phase = 1
mem.startDir = e.direction
mem.counter = 0
else:
result.turnRate = MaxTurnRate
if abs(wrap180(e.direction - mem.startDir)) >= 175.0:
mem.phase = 0
mem.counter = 0
# ── K6 RAMMER — RamFire: approach the opponent and ram ──────────────────────
proc stepRammer(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: RamFire. Two phases, driven by the source text (verified in the
## cached 1.0.7 sample): the `run` loop commands `turnRight(5*turnDirection)`
## every tick, and `onScannedBot` sets `turnDirection` from the bearing sign
## then `forward(distanceTo+5)`. Net observable: a slow spin at ~5 deg/tick
## whose sign latches on the bearing, plus a full-speed charge toward us.
## `idleFraction`/`cycleTicks` split the idle spin from the approach burst;
## `cycleTicks == 0` (the registered default) keeps the approach only.
let b = bearingTo(e.x, e.y, m.x, m.y)
let err = wrap180(b - e.direction)
var idle = false
if p.cycleTicks > 0:
idle = (e.tick mod p.cycleTicks) < int(p.idleFraction * float(p.cycleTicks))
if idle:
result.turnRate = p.idleTurn * (if mem.latch >= 0.0: 1.0 else: -1.0)
result.targetSpeed = p.speed * 0.5
else:
mem.latch = (if err >= 0.0: 1.0 else: -1.0)
result.turnRate = clamp(err, -MaxTurnRate, MaxTurnRate)
# `forward(dist + ramBoost)` clamps to max speed at range; brakes only up close.
result.targetSpeed = clamp(dist(e, m) + p.ramBoost, 1.0, MaxForwardSpeed)
result.fire = fireGate(mem, ramFirePower(e.energy))
# ── K5 CORNER_RUN — Corners: run to a corner and bounce ─────────────────────
proc cornerXY(p: Params, idx: int): tuple[x, y: float64] =
case idx mod 4
of 0: result = (0.0, 0.0)
of 1: result = (p.arenaW, 0.0)
of 2: result = (0.0, p.arenaH)
else: result = (p.arenaW, p.arenaH)
proc stepCornerRun(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: Corners (run to a corner, then turn 90 and continue).
if mem.phase == 0 and mem.counter == 0:
mem.phase = p.corner # first use: honour the param slot
mem.counter = 1
var target = cornerXY(p, mem.phase)
if hypot(target.x - e.x, target.y - e.y) < p.margin:
mem.phase = 3 - mem.phase # reached it: bounce to the opposite corner
target = cornerXY(p, mem.phase)
let b = bearingTo(e.x, e.y, target.x, target.y)
result.turnRate = clamp(wrap180(b - e.direction), -MaxTurnRate, MaxTurnRate)
result.targetSpeed = p.speed
result.fire = fireGate(mem, smartFirePower(dist(e, m), e.energy))
# ── K9 WALLCRAWL — Walls: align to a wall, crawl it in segments ─────────────
proc normalHeading(wall: int): float64 =
case wall # heading pointing AT the wall
of 0: result = 180.0 # left
of 1: result = 0.0 # right
of 2: result = 270.0 # bottom
else: result = 90.0 # top
proc alongHeading(wall: int, sgn: float64): float64 =
case wall
of 0, 1: result = (if sgn >= 0.0: 90.0 else: 270.0) # vertical walls
else: result = (if sgn >= 0.0: 0.0 else: 180.0) # horizontal walls
proc stepWallCrawl(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: Walls (align to nearest wall, forward moveAmount, turnLeft 90 per
## segment). `mem.phase` holds the current wall; `mem.latch` the crawl sign.
var wall = mem.phase
if wall < 0 or wall > 3: wall = 0
let dists = [e.x, p.arenaW - e.x, e.y, p.arenaH - e.y]
var nearest = 0
for i in 1 .. 3:
if dists[i] < dists[nearest]: nearest = i
# Adaptive segment length: Walls crawls one `max(arenaW, arenaH)` cross per
# segment (verified in the cached 1.0.7 source), not a fixed 200. A caller can
# still override with a positive `segmentLen`; 0 means adaptive.
let segLen = if p.segmentLen > 0.0: p.segmentLen else: max(p.arenaW, p.arenaH)
var desired: float64
if dists[nearest] > p.margin and abs(wrap180(normalHeading(nearest) -
e.direction)) < 90.0:
desired = normalHeading(nearest) # still approaching the wall
mem.phase = nearest
else:
wall = mem.phase
var travelled = hypot(e.x - mem.segX, e.y - mem.segY)
# First crawl tick from an unset segment start: anchor it.
if mem.segX == 0.0 and mem.segY == 0.0:
mem.segX = e.x; mem.segY = e.y
travelled = 0.0
if travelled >= segLen:
mem.segX = e.x; mem.segY = e.y
mem.phase = (wall + 1) mod 4
wall = mem.phase
desired = alongHeading(wall, mem.latch)
result.turnRate = clamp(wrap180(desired - e.direction),
-MaxTurnRate, MaxTurnRate)
result.targetSpeed = p.speed
result.fire = fireGate(mem, 2.0) # Walls: fire(2) on scan
# ── K10 STATIC — TrackFire/Fire: stationary posture, gun-driven ────────────
proc stepStatic(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
## Sample: TrackFire / Fire (sit still, turn gun, fire on alignment).
## v0.2 `mode = 1` is the STATIC *corner-park* posture: the same kernel walks
## to its corner band first, then parks there and sweeps its gun — matching
## Corners (run to a corner, then `stop()` + `smartFire(distance)`, §12 table).
## The park phase activates on the near-corner band (`dist < margin`).
if p.mode == 1:
let target = cornerXY(p, p.corner)
if hypot(target.x - e.x, target.y - e.y) < p.margin:
result.turnRate = 0.0 # parked: body still, gun sweeps
result.targetSpeed = 0.0
else:
let b = bearingTo(e.x, e.y, target.x, target.y)
result.turnRate = clamp(wrap180(b - e.direction),
-MaxTurnRate, MaxTurnRate)
result.targetSpeed = p.speed
result.fire = fireGate(mem, smartFirePower(dist(e, m), e.energy))
return
result.turnRate = 0.0
result.targetSpeed = 0.0
let b = bearingTo(e.x, e.y, m.x, m.y)
let aligned = abs(wrap180(b - e.direction)) < 10.0
result.fire = fireGate(mem, (if aligned: 3.0 else: 1.0))
# ── K7 RANDOM_WALK — pseudorandom turn/speed, classes A/B/C ─────────────────
proc stepRandomWalkA(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
result.turnRate = (rngUnit(mem.rngState, 0) * 2.0 - 1.0) * MaxTurnRate
result.targetSpeed = (rngUnit(mem.rngState, 0) * 2.0 - 1.0) * MaxForwardSpeed
result.fire = fireGate(mem, (if rngUnit(mem.rngState, 0) > 0.7: 1.0 else: 0.0))
proc stepRandomWalkB(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
result.turnRate = (rngUnit(mem.rngState, 1) * 2.0 - 1.0) * MaxTurnRate
result.targetSpeed = (rngUnit(mem.rngState, 1) * 2.0 - 1.0) * MaxForwardSpeed
result.fire = fireGate(mem, (if rngUnit(mem.rngState, 1) > 0.7: 1.0 else: 0.0))
proc stepRandomWalkC(e: EnemyState, m: MyState, p: Params,
mem: var KernelMem): Intent =
result.turnRate = (rngUnit(mem.rngState, 2) * 2.0 - 1.0) * MaxTurnRate
result.targetSpeed = (rngUnit(mem.rngState, 2) * 2.0 - 1.0) * MaxForwardSpeed
result.fire = fireGate(mem, (if rngUnit(mem.rngState, 2) > 0.7: 1.0 else: 0.0))
# ── registry ────────────────────────────────────────────────────────────────
proc allKernels*(): seq[Kernel] =
## The M2 kernel set, in registry order. Hedge indexes match this order.
let d = defaultParams()
@[
Kernel(name: "ORBIT_LOCK", step: stepOrbitLock, defaultParams: d),
Kernel(name: "ORBIT_BALLIST", step: stepOrbitBallist,
defaultParams: block: (var q = d; q.dir = -1.0; q)), # SpinBot: CW
Kernel(name: "STOP_AND_GO", step: stepStopAndGo, defaultParams: d),
Kernel(name: "ZIGZAG", step: stepZigzag, defaultParams: d),
Kernel(name: "RAMMER", step: stepRammer, defaultParams: d),
Kernel(name: "CORNER_RUN", step: stepCornerRun, defaultParams: d),
Kernel(name: "WALLCRAWL", step: stepWallCrawl,
defaultParams: block: (var q = d; q.segmentLen = 0.0; q)), # adaptive
Kernel(name: "STATIC", step: stepStatic, defaultParams: d),
Kernel(name: "STATIC_CORNER", step: stepStatic,
defaultParams: block: (var q = d; q.mode = 1; q)), # Corners park
Kernel(name: "RANDOM_WALK_A", step: stepRandomWalkA,
defaultParams: block: (var q = d; q.rngClass = 0; q)),
Kernel(name: "RANDOM_WALK_B", step: stepRandomWalkB,
defaultParams: block: (var q = d; q.rngClass = 1; q)),
Kernel(name: "RANDOM_WALK_C", step: stepRandomWalkC,
defaultParams: block: (var q = d; q.rngClass = 2; q)),
]
proc kernelNames*(kernels: seq[Kernel]): seq[string] =
for k in kernels: result.add k.name
@@ -0,0 +1,138 @@
## CHIMERA predictor fusion — hedge over PREDICTORS (spec §10).
##
## Three predictors compete for the counterfactual rollout:
## * `mixture` — the posterior-weighted kernel mixture (twinsim `rollout`),
## * `residual` — the mixture with the online linear residual correction
## applied to each tick's predicted intent (`residual.nim`),
## * `persistence` — constant-velocity carry (`twinsim.persistence`).
##
## Weights are updated by realized-vs-predicted loss per channel (turn, speed,
## fire) using the same Hedge/EWA machinery as the kernel posterior
## (`hedge.nim`), so the two layers share one update contract. The fused
## prediction is the weight-blended 5-tick trajectory plus a fused `P(fire
## within k)`; `confidence` is the fusion's own weight concentration damped by
## its recent realised loss (a monotone, deterministic reliability scalar).
##
## Pure and deterministic: no I/O, no clock, no RNG.
import std/math
import ./physics, ./dsl, ./twinsim, ./residual, ./hedge
const
NPredictors* = 3
MixtureIdx* = 0
ResidualIdx* = 1
PersistenceIdx* = 2
PredictorNames* = @["mixture", "residual", "persistence"]
LossScale* = 2.0 ## loss -> confidence falloff scale
BetaDefault* = 0.05
type
PredIntent* = object
## One predictor's next-tick intent prediction, or the realized intent.
turn*, speed*, fire*: float64
FusedPrediction* = object
horizon*: int
points*: seq[tuple[x, y: float64]]
pFire*: seq[float64]
fireWithin*: float64 ## fused P(fire at least once in 1..k)
confidence*: float64 ## 0..1, deterministic reliability scalar
lossEma*: float64
Fusion* = object
hedge*: Hedge
lossEma*: float64
lossN*: int
beta*: float64
# ── construction ────────────────────────────────────────────────────────────
proc initFusion*(cfg = HedgeConfig()): Fusion =
result.hedge = initHedge(PredictorNames, cfg)
result.beta = BetaDefault
proc weights*(f: Fusion): seq[float64] = f.hedge.weights
# ── per-channel loss (realized vs predicted) ────────────────────────────────
proc channelLoss*(realized, pred: PredIntent): float64 =
## Smooth per-tick loss: normalised squared turn + speed error, plus a
## Bernoulli log-loss on the fire channel. Scale-free enough that a single
## Hedge learning rate stays stable.
let dt = (realized.turn - pred.turn) / 10.0
let ds = (realized.speed - pred.speed) / 8.0
var l = dt * dt + ds * ds
let p = clamp(pred.fire, 1e-3, 1.0 - 1e-3)
let y = if realized.fire > 0.0: 1.0 else: 0.0
l += -(y * ln(p) + (1.0 - y) * ln(1.0 - p))
l
proc update*(f: var Fusion, realized: PredIntent, preds: openArray[PredIntent]) =
## One fusion step: score every predictor on this tick's realized intent, move
## the weights, update the fused-loss EMA.
doAssert preds.len == NPredictors, "need exactly NPredictors predictions"
var losses: array[NPredictors, float64]
for i in 0 ..< NPredictors:
losses[i] = channelLoss(realized, preds[i])
f.hedge.update(losses)
var fl = 0.0
for i in 0 ..< NPredictors:
fl += f.hedge.weights[i] * losses[i]
if f.lossN == 0: f.lossEma = fl
else: f.lossEma = (1.0 - f.beta) * f.lossEma + f.beta * fl
inc f.lossN
proc confidence*(f: Fusion): float64 =
## Weight concentration damped by recent realized loss. Deterministic.
var wmax = 0.0
for w in f.hedge.weights: wmax = max(wmax, w)
let ema = if f.lossN == 0: 0.0 else: f.lossEma
clamp(wmax * exp(-ema / LossScale), 0.0, 1.0)
# ── residual trajectory + fused rollout ─────────────────────────────────────
proc residualTrajectory*(origin: ReplayTick, mix: seq[RolloutPoint],
rp: ResidualPrediction, k: int): seq[tuple[x, y: float64]] =
## Integrate the mixture's per-tick intent PLUS the residual correction from
## the enemy origin through the physics mirror. A distinct, deterministic
## predictor: same base as the mixture, corrected by what it systematically
## got wrong.
var dir = origin.edir
var sp = origin.espeed
var x = origin.ex
var y = origin.ey
for h in 0 ..< k:
let baseTurn = (if h < mix.len: mix[h].turnRate else: origin.lastTurn)
let baseSpeed = (if h < mix.len: mix[h].targetSpeed else: origin.lastSpeed)
let ts = clamp(baseSpeed + rp.speed, MaxBackwardSpeed, MaxForwardSpeed)
sp = stepSpeed(sp, ts)
dir = wrap180(dir + limitTurnRate(baseTurn + rp.turn, sp))
x += sp * cos(degToRad(dir))
y += sp * sin(degToRad(dir))
result.add (x, y)
proc fusedPrediction*(f: Fusion, kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, k = 5): FusedPrediction =
## The fused 5-tick counterfactual prediction used by the influence layer.
let mix = rollout(kernels, origin, k)
let resPts = residualTrajectory(origin, mix.points, rp, k)
let persPts = persistence(origin, k)
let wm = f.hedge.weights[MixtureIdx]
let wr = f.hedge.weights[ResidualIdx]
let wp = f.hedge.weights[PersistenceIdx]
result.horizon = k
var pNoFire = 1.0
for h in 0 ..< k:
let mx = wm * mix.points[h].x + wr * resPts[h].x + wp * persPts[h].x
let my = wm * mix.points[h].y + wr * resPts[h].y + wp * persPts[h].y
result.points.add (mx, my)
var pf = wm * mix.points[h].pFire
pf += wr * clamp(mix.points[h].pFire + rp.fire, 0.0, 1.0)
# persistence carries no fire model: contributes 0
let pfC = clamp(pf, 0.0, 1.0)
result.pFire.add pfC
pNoFire *= (1.0 - pfC)
result.fireWithin = 1.0 - pNoFire
result.confidence = f.confidence()
result.lossEma = f.lossEma
@@ -0,0 +1,108 @@
## CHIMERA Hedge / EWA posterior over kernels.
##
## Source of truth: `docs/chimera-spec.md` §7. A weighted mixture (never argmax)
## updated in the full-information setting: every non-censored tick yields a
## realized intent, so we update every kernel with its loss.
##
## Two regularizers keep a wrong-but-resurrected kernel recoverable:
## * exponential forgetting `(1 - 1/τ)`, default `τ = 200` ticks;
## * Fixed-Share mixing toward the uniform distribution with coefficient `α`,
## which gives a strict mass floor `w_i ≥ α·m_i`.
## The spec writes the update as
## `w_i ← w_i·exp(-η·loss_i)·(1-1/τ) + α·(m_i - w_i)`;
## we implement the standard, numerically-safe ordering of the same two terms
## ((1-α) of the forgotten weight + α·m_i) so weights can never go negative and
## the floor is exact. `tests/test_hedge.nim` pins the behaviour.
##
## Loss-scale heuristic: raw per-tick losses are O(1) (normalized squared error
## plus a Bernoulli term). `lossScale` maps them into the spec's ~0.01–0.1
## band before `η`, so a single `η` stays stable across kernels.
import std/[math, algorithm]
type
HedgeConfig* = object
eta*: float64 = 4.0 ## learning rate
tau*: float64 = 200.0 ## forgetting horizon, ticks
alpha*: float64 = 0.01 ## Fixed-Share mixing coefficient (mass floor)
lossScale*: float64 = 0.1 ## raw-loss -> spec ~0.01-0.1 band multiplier
Hedge* = object
names*: seq[string]
weights*: seq[float64]
cfg*: HedgeConfig
revision*: int ## bumped on every mutation (revision-safe API)
proc initHedge*(names: seq[string], cfg = HedgeConfig()): Hedge =
## Uniform prior over the registered kernels.
result.names = names
result.weights = newSeq[float64](names.len)
for i in 0 ..< names.len: result.weights[i] = 1.0 / float64(names.len)
result.cfg = cfg
proc normalize*(h: var Hedge) =
var s = 0.0
for w in h.weights: s += w
if s > 0.0:
for i in 0 ..< h.weights.len: h.weights[i] /= s
proc setWeights*(h: var Hedge, w: openArray[float64]) =
## Revision-safe restore: length-checked, clamped non-negative, renormalized.
doAssert w.len == h.weights.len, "weight vector length mismatch"
var s = 0.0
for x in w:
doAssert x >= 0.0, "negative weight"
s += x
doAssert s > 0.0, "zero-mass weight vector"
for i in 0 ..< h.weights.len: h.weights[i] = w[i] / s
inc h.revision
proc clone*(h: Hedge): Hedge =
## Deep copy for revision-safe experimentation.
result.names = h.names
result.weights = h.weights
result.cfg = h.cfg
result.revision = h.revision
proc update*(h: var Hedge, rawLosses: openArray[float64]) =
## One Hedge step. `rawLosses[i]` is the loss of kernel `i` on this tick.
## Censored ticks must be skipped by the caller (spec §4.4) — this proc
## assumes a full-information observation.
doAssert rawLosses.len == h.weights.len, "loss vector length mismatch"
let n = h.weights.len
let m = 1.0 / float64(n) # Fixed-Share target: uniform
let keep = 1.0 - 1.0 / h.cfg.tau # exponential forgetting
var w = newSeq[float64](n)
for i in 0 ..< n:
let forgotten = h.weights[i] * exp(-h.cfg.eta * h.cfg.lossScale *
rawLosses[i]) * keep
w[i] = (1.0 - h.cfg.alpha) * forgotten + h.cfg.alpha * m
h.weights = w
h.normalize()
inc h.revision
proc posterior*(h: Hedge, name: string): float64 =
## Weight of one kernel by name (0 when unknown).
for i in 0 ..< h.names.len:
if h.names[i] == name: return h.weights[i]
0.0
proc topK*(h: Hedge, k: int): seq[tuple[name: string, weight: float64]] =
## Kernels sorted by descending weight.
var idx = newSeq[int](h.names.len)
for i in 0 ..< idx.len: idx[i] = i
idx.sort(proc(a, b: int): int = cmp(h.weights[b], h.weights[a]))
for i in 0 ..< min(k, idx.len):
result.add (h.names[idx[i]], h.weights[idx[i]])
proc entropy*(h: Hedge): float64 =
## Shannon entropy `-Σ w ln w` (nats); exact closed form, see tests.
for w in h.weights:
if w > 0.0: result -= w * ln(w)
proc argmaxName*(h: Hedge): string =
## Highest-weight kernel (diagnostics only — prediction uses the mixture).
var best = 0
for i in 1 ..< h.weights.len:
if h.weights[i] > h.weights[best]: best = i
if h.names.len == 0: "" else: h.names[best]
@@ -0,0 +1,92 @@
## CHIMERA influence / fallback — how much the twin is allowed to steer us
## (spec §10 "Failure fallback" + §8 "predictive bullet avoidance").
##
## The twin's advice is a *tie-breaker*, never a reflex override. Two things
## happen here:
##
## 1. `influenceScalar` turns the fusion's realized-vs-predicted loss into a
## single 0..1 scalar: it ramps to 1 while the twin predicts well and to 0
## once the loss degrades past `BadLoss`. With no evidence it is 0 — the
## conservative choice, i.e. the bot degrades to DevControlBot behaviour.
## 2. `overlay` may nudge the EXISTING TFIL command (turn/speed) toward the
## candidate whose fused 5-tick rollout stays furthest from the predicted
## enemy path, weighting ticks by the fused fire probability. It only applies
## when the nudge clears a safety margin (`MinGain`), never touches a tick
## where TFIL's bullet-avoidance is active (`reflexBusy`), and can only
## change turn by <= `MaxTurnBias` deg and speed by <= `MaxSpeedDelta`.
##
## Pure and deterministic: no I/O, no clock, no RNG.
import std/math
import ./physics, ./fusion
const
GoodLoss* = 0.5 ## below this the twin is fully trusted
BadLoss* = 2.0 ## above this influence is 0 (degrade to baseline)
MinGain* = 3.0 ## units of extra clearance required to apply a nudge
MaxTurnBias* = 12.0 ## deg, hard cap on the overlay's turn adjustment
MaxSpeedDelta* = 2.0 ## units/tick, hard cap on the speed adjustment
type
InfluenceAdvisory* = object
influence*: float64 ## 0..1 twin steering authority
applied*: bool
speed*: float64 ## command after the overlay (== TFIL when not applied)
turnRate*: float64
gain*: float64 ## clearance improvement of the chosen nudge
proc influenceScalar*(lossEma: float64, samples: int): float64 =
## Loss-degradation ramp (spec §10). No samples => 0 (never steer blindly).
if samples <= 0: return 0.0
clamp((BadLoss - lossEma) / (BadLoss - GoodLoss), 0.0, 1.0)
proc overlay*(influence: float64,
tfilSpeed, tfilTurn: float64,
selfX, selfY, selfHeading, selfSpeed: float64,
fused: FusedPrediction,
reflexBusy: bool): InfluenceAdvisory =
## Overlay a small, safe correction on the TFIL command.
result.influence = influence
result.speed = tfilSpeed
result.turnRate = tfilTurn
if reflexBusy or influence <= 1e-6 or fused.points.len == 0:
return
let k = fused.points.len
# Safety score of a candidate (speed, turn): the fire-weighted minimum
# clearance from our own 5-tick rollout to the fused enemy path.
proc safety(speed, turn: float64): float64 =
var x = selfX
var y = selfY
var dir = selfHeading
var sp = selfSpeed
var best = Inf
for h in 0 ..< k:
sp = stepSpeed(sp, speed)
dir = wrap180(dir + limitTurnRate(turn, sp))
x += sp * cos(degToRad(dir))
y += sp * sin(degToRad(dir))
let d = hypot(x - fused.points[h].x, y - fused.points[h].y)
let w = 1.0 + (if h < fused.pFire.len: fused.pFire[h] else: 0.0)
best = min(best, d * w)
best
let base = safety(tfilSpeed, tfilTurn)
var bestGain = 0.0
var bestSpeed = tfilSpeed
var bestTurn = tfilTurn
for bias in [-MaxTurnBias, -MaxTurnBias * 0.5, MaxTurnBias * 0.5, MaxTurnBias]:
for dsp in [0.0, -MaxSpeedDelta, MaxSpeedDelta]:
let s = clamp(tfilSpeed + dsp, MaxBackwardSpeed, MaxForwardSpeed)
let t = tfilTurn + bias
let g = safety(s, t) - base
if g > bestGain + 1e-12:
bestGain = g
bestSpeed = s
bestTurn = t
if influence * bestGain >= MinGain:
result.speed = bestSpeed
result.turnRate = bestTurn
result.applied = true
result.gain = bestGain
@@ -0,0 +1,148 @@
## CHIMERA intent ledger — the observable scan stream in, per-tick *intent
## intervals* out. Ambiguous ticks are marked CENSORED, never guessed.
##
## Source of truth: `docs/chimera-spec.md` §4. The ledger never imputes: a tick
## whose intent cannot be bounded is excluded from Hedge updates and counted in
## the censoring rate (spec §4.4, goal G3).
##
## Every inference is an interval because the wire only exposes realized state:
## the server clamps the body turn (`10 - 0.75|v|`, spec §4.1) and updates speed
## through the stateful `stepSpeed` rule (spec §4.2), so a realized value bounds
## the command rather than naming it.
import std/math
import ./physics
const
IntervalEps* = 1e-6 ## wrap/quantization slack for interval construction
type
Scan* = object
## One `ScannedBotEvent`-worth of enemy state.
tick*: int
x*: float64
y*: float64
direction*: float64
speed*: float64
energy*: float64
Interval* = object
lo*: float64
hi*: float64
LedgerObs* = object
## One tick's inferred intent. `*Known` is false when the channel was not
## observed (or was censored); the interval is then meaningless.
tick*: int
turnRate*: Interval
turnKnown*: bool
targetSpeed*: Interval
targetKnown*: bool
fire*: float64 ## observed fire power, or 0 when `fireKnown` is false
fireKnown*: bool
censored*: bool
proc contains*(iv: Interval, v: float64): bool =
## True when `v` lies in the interval (with slack).
v >= iv.lo - IntervalEps and v <= iv.hi + IntervalEps
proc width*(iv: Interval): float64 = iv.hi - iv.lo
proc turnRateInterval*(prev, cur: Scan): LedgerObs =
## Spec §4.1. `Δdir` between adjacent scans bounds the realized turn rate by
## `[Δdir - ε, Δdir + ε] ∩ [-(10-0.75|v|), +(10-0.75|v|)]`, the cap computed at
## the speed the turn was applied with (the server limits the turn AFTER the
## speed update, so `cur.speed` is the right one). A scan gap ≥ 2 is CENSORED.
result.tick = cur.tick
if cur.tick - prev.tick != 1:
result.censored = true
return
let delta = wrap180(cur.direction - prev.direction)
let cap = maxTurnRate(cur.speed)
result.turnRate = Interval(lo: max(-cap, delta - IntervalEps),
hi: min(cap, delta + IntervalEps))
result.turnKnown = true
proc invertStepSpeed*(currentSpeed, newSpeed: float64): tuple[iv: Interval, ok: bool] =
## Spec §4.2. Exact preimage of `stepSpeed(currentSpeed, ·)` at `newSpeed`:
## the set of target speeds consistent with the observed realized speed.
## Returns the convex hull; `ok = false` means the observation is impossible
## (the tick must be censored).
var v = currentSpeed
var n = newSpeed
var negate = false
if v < 0.0:
v = -v; n = -n; negate = true # odd symmetry of stepSpeed
var lo = Inf
var hi = -Inf
template add(a, b: float64) =
lo = min(lo, a); hi = max(hi, b)
if abs(v) < IntervalEps:
# stepSpeed(0, t) = clamp(t, -1, 1)
if abs(n) <= 1.0 + IntervalEps:
if n >= 1.0 - IntervalEps:
add(1.0, MaxForwardSpeed)
elif n <= -1.0 + IntervalEps:
add(MaxBackwardSpeed, -1.0)
else:
add(n, n)
else:
let crossVal = v / 2.0 - 1.0
if abs(n - crossVal) <= IntervalEps:
# crossing-zero branch: every target with the opposite sign gives crossVal
add(MaxBackwardSpeed, 0.0)
if abs(n) <= IntervalEps:
add(0.0, 0.0)
# same-sign branch: n = clamp(t, v-2, min(v+1, 8)) for t > 0
let floorV = v - 2.0
let ceilV = min(v + 1.0, MaxForwardSpeed)
if n >= max(0.0, floorV) - IntervalEps and n <= ceilV + IntervalEps:
if abs(n - ceilV) <= IntervalEps:
add(ceilV, MaxForwardSpeed)
elif abs(n - floorV) <= IntervalEps and floorV > 0.0:
add(0.0, floorV)
else:
add(n, n)
if lo > hi:
return (Interval(lo: 0.0, hi: 0.0), false)
if negate:
return (Interval(lo: -hi, hi: -lo), true)
(Interval(lo: lo, hi: hi), true)
proc targetSpeedInterval*(prevSpeed, newSpeed: float64): LedgerObs =
## Spec §4.2 wrapper: interval of target speeds consistent with the realized
## step, or CENSORED when the step is impossible.
let inv = invertStepSpeed(prevSpeed, newSpeed)
result.turnRate = Interval(lo: 0.0, hi: 0.0)
if inv.ok:
result.targetSpeed = inv.iv
result.targetKnown = true
else:
result.censored = true
proc fireFromEnergyDrop*(prevEnergy, curEnergy, knownDamage: float64): LedgerObs =
## Spec §4.3. Firing spends `power` energy at fire time. With no known incoming
## damage the drop names the fire power directly; with known damage the drop is
## ambiguous and the tick is CENSORED.
let drop = prevEnergy - curEnergy
if drop <= IntervalEps:
return # no drop: fireKnown stays false
if knownDamage > IntervalEps:
result.censored = true
return
if drop < MinFirepower - IntervalEps or drop > MaxFirepower + IntervalEps:
result.censored = true
return
result.fire = drop
result.fireKnown = true
proc censorRate*(obs: openArray[LedgerObs]): float64 =
## Spec §4.4 / G3: censored / total ticks.
if obs.len == 0: return 0.0
var c = 0
for o in obs:
if o.censored: inc c
c / obs.len
@@ -0,0 +1,433 @@
## CHIMERA observation sidecar — ledger + Hedge posterior + telemetry.
##
## Source of truth: `docs/chimera-spec.md` §4 (intent ledger), §7 (Hedge), §12
## (G3 censoring budget, G4 identification). This module is **observation-only**:
## it consumes the scan stream the radar already produces and never issues a
## command. `ChimeraBot.nim` calls it from `onScannedBot` / the tick loop, purely
## for telemetry, so the bot's command behaviour is byte-identical with or
## without it.
##
## Per scan tick it folds the observable stream into a `LedgerObs`, scores every
## kernel's prediction with `oracle.intentLoss`, and updates the Hedge posterior
## (uniform at round start). Telemetry is one JSONL line per tick under
## `<telemetryDir>/<opponent>-<round>.jsonl`; throwaway output therefore lives in
## `/tmp` (garage rule). A `round_summary` line carries the final argmax, the
## censoring rate, scan-gap stats and the 5-tick prediction ADE/FDE.
##
## The 5-tick ADE/FDE is a **posterior-weighted enemy self-rollout** over the
## physics mirror (predicted enemy intents, no counterfactual plan) — the
## readiness check for the M4 twin rollout, not the twin itself.
import std/[math, os, strutils]
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence
const
MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check
PredSlots* = 8 ## ring size; > MaxHorizon so an origin survives its queries
FusionEnabled* = not defined(chimeraNoFusion) and not defined(chimeraInert)
## M6 kill switches: `-d:chimeraNoFusion` drops the residual+fusion layer,
## `-d:chimeraInert` drops every CHIMERA command path (== M1 exact copy).
type
Observer* = ref object
kernels: seq[Kernel]
hedge: Hedge
mems: seq[KernelMem]
cfg: HedgeConfig
telemetryDir: string
arenaW, arenaH: float64
havePrev: bool
prev: Scan
prevOwnX, prevOwnY: float64
haveCur: bool
cur: Scan
curOwnX, curOwnY: float64
curOwnDir, curOwnSpeed: float64
scanTick: int ## tick of the most recent scan (-1 = none yet)
lastObs: LedgerObs
haveLastObs: bool
censored, ticks: int
gapMax, gapViolations: int
enemyHeat: float64 ## ledger-derived enemy gun-heat estimate (probe gate)
round: int
opponent: string
f: File
fileOpen: bool
# Cross-round posterior carry-over (M5.5; default on, `-d:chimeraFreshRound`
# restores the per-round reset).
carryOver*: bool
# M6 residual + fusion (spec §10). Observation-only training lives here
# because the ledger fold is already computed here; the influence overlay
# itself runs in the bot's command path.
residual: ResidualHead
fusion: Fusion
prevOwnDir, prevOwnSpeed: float64
lastRealizedTurn, lastRealizedSpeed: float64
fireRateEma: float64
## predictions: `predPos[(origin mod PredSlots)][h]` is the enemy position
## predicted `h` ticks after `origin`; `predOrigin` guards a slot's owner.
predPos: array[PredSlots, array[MaxHorizon + 1, tuple[x, y: float64]]]
predOrigin: array[PredSlots, int]
adeSum, fdeSum: float64
adeN, fdeN: int
# ── construction / round lifecycle ──────────────────────────────────────────
proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer =
new(result)
result.kernels = kernels
result.cfg = HedgeConfig()
result.hedge = initHedge(kernelNames(kernels), result.cfg)
result.mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len:
result.mems[i] = defaultMemory(kernels[i].defaultParams)
result.telemetryDir = telemetryDir
result.scanTick = -1
result.enemyHeat = 3.0
result.residual = initResidualHead()
result.fusion = initFusion()
result.carryOver = not defined(chimeraFreshRound)
for i in 0 ..< PredSlots: result.predOrigin[i] = -1
proc resetRoundStats(o: Observer) =
## Per-round observables and counters, with NO touch to the posterior or the
## kernel memories. Cleared on every round start (carry-over keeps the latter).
o.havePrev = false
o.haveCur = false
o.haveLastObs = false
o.censored = 0
o.ticks = 0
o.scanTick = -1
o.gapMax = 0
o.gapViolations = 0
o.adeSum = 0; o.adeN = 0
o.fdeSum = 0; o.fdeN = 0
o.enemyHeat = 3.0 ## round-start heat (spec §5)
o.prevOwnDir = 0.0; o.prevOwnSpeed = 0.0
o.lastRealizedTurn = 0.0; o.lastRealizedSpeed = 0.0
o.fireRateEma = 0.0
for i in 0 ..< PredSlots: o.predOrigin[i] = -1
proc resetRound(o: Observer) =
## Fresh-round ablation: uniform posterior + default kernel memories.
o.hedge = initHedge(kernelNames(o.kernels), o.cfg)
for i in 0 ..< o.kernels.len:
o.mems[i] = defaultMemory(o.kernels[i].defaultParams)
o.residual.reset()
o.fusion = initFusion()
o.resetRoundStats()
proc sanitize*(s: string): string =
## Filename-safe opponent token: collapse runs of non-alphanumerics to `_`.
var prevSep = false
for c in s:
if c.isAlphaNumeric:
result.add c
prevSep = false
elif not prevSep and result.len > 0:
result.add '_'
prevSep = true
while result.len > 0 and result[^1] == '_':
result.setLen(result.len - 1)
proc openTelemetry(o: Observer) =
if o.telemetryDir.len == 0 or o.fileOpen: return
createDir(o.telemetryDir)
let who = if o.opponent.len > 0: sanitize(o.opponent) else: "unknown"
let path = o.telemetryDir / (who & "-" & $o.round & ".jsonl")
o.f = open(path, fmWrite)
o.fileOpen = true
proc startRound*(o: Observer, round: int) =
## Called on `RoundStartedEvent`. With carry-over (default, M5.5) the posterior
## and kernel memories survive: the enemy is the same program across rounds, so
## identification compounds. Only RNG-derived memory is re-sampled (a per-round
## parameter such as Corners' start corner must not carry). With
## `-d:chimeraFreshRound` (`carryOver == false`) the posterior resets UNIFORM,
## which is the M3/M4 behaviour and the G6 carry-over ablation arm.
if o.carryOver:
o.resetRoundStats()
for i in 0 ..< o.kernels.len:
o.mems[i].rngState = o.kernels[i].defaultParams.seed
else:
o.resetRound()
o.round = round # `opponent` is retained: it is per-BATTLE, not per-round
# ── ledger folding (observer-local fire rule) ───────────────────────────────
proc foldObs(prev, cur: Scan): LedgerObs =
## Turn + speed channels verbatim from `ledger`. Fire: only an energy drop
## inside `[0.1, 3.0]` can be the enemy's own shot; a larger drop is external
## damage (our bullet, a collision), so the fire channel stays UNOBSERVED
## rather than censoring a tick the enemy's intent is not ambiguous about.
result = turnRateInterval(prev, cur)
result.tick = cur.tick
let sp = targetSpeedInterval(prev.speed, cur.speed)
if sp.targetKnown:
result.targetSpeed = sp.targetSpeed
result.targetKnown = true
if sp.censored:
result.censored = true
let drop = prev.energy - cur.energy
if drop >= MinFirepower - IntervalEps and drop <= MaxFirepower + IntervalEps:
result.fire = drop
result.fireKnown = true
# ── 5-tick prediction (posterior-weighted enemy self-rollout) ───────────────
proc recordPrediction(o: Observer, s: Scan, ownX, ownY: float64) =
var mems = newSeq[KernelMem](o.kernels.len)
for i in 0 ..< o.kernels.len: mems[i] = o.mems[i]
var st = EnemyState(tick: s.tick, x: s.x, y: s.y, direction: s.direction,
speed: s.speed, energy: s.energy)
let my = MyState(x: ownX, y: ownY)
let slot = s.tick mod PredSlots
o.predOrigin[slot] = s.tick
for h in 1 .. MaxHorizon:
var intent: Intent
for i in 0 ..< o.kernels.len:
let it = o.kernels[i].step(st, my, o.kernels[i].defaultParams, mems[i])
intent.turnRate += o.hedge.weights[i] * it.turnRate
intent.targetSpeed += o.hedge.weights[i] * it.targetSpeed
let ns = stepSpeed(st.speed, intent.targetSpeed)
st.direction = wrap180(st.direction + limitTurnRate(intent.turnRate, ns))
st.speed = ns
st.x = clamp(st.x + ns * cos(degToRad(st.direction)), 0.0, o.arenaW)
st.y = clamp(st.y + ns * sin(degToRad(st.direction)), 0.0, o.arenaH)
st.tick = s.tick + h
o.predPos[slot][h] = (st.x, st.y)
proc scoreScan(o: Observer, s: Scan) =
for h in 1 .. MaxHorizon:
let org = s.tick - h
if org < 0: continue
let slot = org mod PredSlots
if o.predOrigin[slot] != org: continue
let p = o.predPos[slot][h]
let err = hypot(p.x - s.x, p.y - s.y)
o.adeSum += err; inc o.adeN
if h == MaxHorizon:
o.fdeSum += err; inc o.fdeN
# ── per-scan entry point ────────────────────────────────────────────────────
proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float64,
ownX, ownY: float64, opponent: string,
arenaW, arenaH: float64,
ownDir = 0.0, ownSpeed = 0.0) =
## Consume one `ScannedBotEvent`. Observation-only: no command is ever issued.
## `ownDir`/`ownSpeed` are recorded for offline plan simulation (twinsim); they
## default to 0 so callers that do not have them still compile unchanged.
if opponent.len > 0: o.opponent = opponent
if arenaW > 0: o.arenaW = arenaW
if arenaH > 0: o.arenaH = arenaH
if o.arenaW <= 0: o.arenaW = 800.0
if o.arenaH <= 0: o.arenaH = 600.0
o.scanTick = tick
if o.telemetryDir.len > 0 and not o.fileOpen: o.openTelemetry()
let s = Scan(tick: tick, x: x, y: y, direction: direction, speed: speed,
energy: energy)
if o.havePrev and o.prev.tick == tick:
o.cur = s; o.curOwnX = ownX; o.curOwnY = ownY; o.haveCur = true
o.curOwnDir = ownDir; o.curOwnSpeed = ownSpeed
return
o.scoreScan(s)
if o.havePrev:
let g = tick - o.prev.tick
if g > o.gapMax: o.gapMax = g
if g > 1: inc o.gapViolations
let obs = foldObs(o.prev, s)
o.lastObs = obs
o.haveLastObs = true
inc o.ticks
# Enemy gun-heat estimate (probe gate, spec §5): a fired shot pins heat to
# `1 + power/5`; writeTick decays it one per tick. Observation-only.
if obs.fireKnown: o.enemyHeat = gunHeat(obs.fire)
if obs.censored:
inc o.censored
else:
let e = EnemyState(tick: o.prev.tick, x: o.prev.x, y: o.prev.y,
direction: o.prev.direction, speed: o.prev.speed,
energy: o.prev.energy)
let my = MyState(x: o.prevOwnX, y: o.prevOwnY)
var losses = newSeq[float64](o.kernels.len)
var mixTurn, mixSpeed, mixFire = 0.0
for i in 0 ..< o.kernels.len:
let pred = o.kernels[i].step(e, my, o.kernels[i].defaultParams, o.mems[i])
losses[i] = intentLoss(pred, obs, s.speed)
let w = o.hedge.weights[i]
mixTurn += w * pred.turnRate
mixSpeed += w * pred.targetSpeed
mixFire += w * pred.fire
o.hedge.update(losses)
when FusionEnabled:
# Residual + fusion training (spec §10): learn the mixture's residual on
# THIS realized intent, then score the three predictors. Observation
# only — nothing here can change a command.
let realized = PredIntent(
turn: (if obs.turnKnown: (obs.turnRate.lo + obs.turnRate.hi) / 2.0 else: mixTurn),
speed: (if obs.targetKnown: (obs.targetSpeed.lo + obs.targetSpeed.hi) / 2.0 else: mixSpeed),
fire: (if obs.fireKnown: obs.fire else: mixFire))
let feat = features(ResidualInput(
lastTurn: o.lastRealizedTurn, lastSpeed: o.lastRealizedSpeed,
scanAge: float64(s.tick - o.prev.tick),
dist: hypot(o.prev.x - o.prevOwnX, o.prev.y - o.prevOwnY),
ownTurn: wrap180(ownDir - o.prevOwnDir), ownSpeed: o.prevOwnSpeed))
let rpred = o.residual.predict(feat)
let persP = PredIntent(turn: o.lastRealizedTurn,
speed: o.lastRealizedSpeed, fire: o.fireRateEma)
o.fusion.update(realized, [
PredIntent(turn: mixTurn, speed: mixSpeed, fire: mixFire),
PredIntent(turn: mixTurn + rpred.turn, speed: mixSpeed + rpred.speed,
fire: clamp(mixFire + rpred.fire, 0.0, 1.0)),
persP])
o.residual.observe(feat, ResidualTarget(
turn: realized.turn - mixTurn, speed: realized.speed - mixSpeed,
fire: realized.fire - mixFire))
o.lastRealizedTurn = realized.turn
o.lastRealizedSpeed = realized.speed
if obs.fireKnown:
let y = (if obs.fire > 0.0: 1.0 else: 0.0)
o.fireRateEma = 0.95 * o.fireRateEma + 0.05 * y
o.prevOwnDir = o.curOwnDir
o.prevOwnSpeed = o.curOwnSpeed
o.prev = s; o.prevOwnX = ownX; o.prevOwnY = ownY; o.havePrev = true
o.cur = s; o.curOwnX = ownX; o.curOwnY = ownY; o.haveCur = true
o.curOwnDir = ownDir; o.curOwnSpeed = ownSpeed
o.recordPrediction(s, ownX, ownY)
# ── telemetry ───────────────────────────────────────────────────────────────
proc jsonInterval(iv: Interval): string =
"[" & $iv.lo & "," & $iv.hi & "]"
proc censorRate*(o: Observer): float64 =
if o.ticks == 0: 0.0 else: float(o.censored) / float(o.ticks)
proc argmaxName*(o: Observer): string = o.hedge.argmaxName()
proc posterior*(o: Observer, name: string): float64 = o.hedge.posterior(name)
proc entropy*(o: Observer): float64 = o.hedge.entropy()
proc hasCurrent*(o: Observer): bool = o.haveCur
proc enemyGunHeat*(o: Observer): float64 = o.enemyHeat
proc probeOrigin*(o: Observer): ReplayTick =
## The current causal posterior + observed enemy/own state, as the probe
## scheduler's counterfactual origin. Read-only: `mems`/`weights` are copied.
result = ReplayTick(tick: o.cur.tick, ex: o.cur.x, ey: o.cur.y,
edir: o.cur.direction, espeed: o.cur.speed,
eenergy: o.cur.energy,
ox: o.curOwnX, oy: o.curOwnY,
odir: o.curOwnDir, ospeed: o.curOwnSpeed,
lastTurn: 0.0, lastSpeed: o.cur.speed)
result.weights = o.hedge.weights
result.mems = o.mems
proc currentResidualInput(o: Observer): ResidualInput =
## Feature inputs at the current origin (dense stream => scanAge 1).
ResidualInput(
lastTurn: o.lastRealizedTurn, lastSpeed: o.lastRealizedSpeed,
scanAge: 1.0,
dist: (if o.haveCur: hypot(o.cur.x - o.curOwnX, o.cur.y - o.curOwnY) else: 0.0),
ownTurn: 0.0,
ownSpeed: (if o.haveCur: o.curOwnSpeed else: 0.0))
proc fusedPrediction*(o: Observer, k = MaxHorizon): FusedPrediction =
## The fused 5-tick counterfactual prediction at the current origin (M6).
## Computed on demand; O(k * kernels) and allocation-light.
if not o.haveCur: return
let origin = o.probeOrigin()
let rp = o.residual.predict(features(o.currentResidualInput()))
o.fusion.fusedPrediction(o.kernels, origin, rp, k)
proc fusedInfluence*(o: Observer): float64 =
## Twin steering authority (0..1), ramped down by realized prediction loss.
influenceScalar(o.fusion.lossEma, o.fusion.lossN)
proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights()
proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma
proc fusionSamples*(o: Observer): int = o.fusion.lossN
proc writeProbeEvent*(o: Observer, tick: int, kind, gateState: string,
entropyBefore, entropyAfter, turnRate,
targetSpeed: float64) =
## One JSONL line per triggered probe (executed or gate-blocked). The
## interventional G5' eval keys off `event==="probe"` lines.
if not o.fileOpen: return
o.f.write("{\"event\":\"probe\",\"tick\":" & $tick &
",\"kind\":\"" & kind & "\",\"gate\":\"" & gateState &
"\",\"entropyBefore\":" & $entropyBefore &
",\"entropyAfter\":" & $entropyAfter &
",\"turnRate\":" & $turnRate &
",\"targetSpeed\":" & $targetSpeed & "}\n")
flushFile(o.f)
proc writeTick*(o: Observer, tick: int) =
## One telemetry line per tick. Called after `go()`, so a scan dispatched by
## this tick is already folded in. Also decays the enemy gun-heat estimate.
if o.enemyHeat > 0.0: o.enemyHeat = max(0.0, o.enemyHeat - 1.0)
if not o.fileOpen: return
let scanned = o.scanTick == tick
var line = "{\"tick\":" & $tick & ",\"scan\":" & $scanned
if scanned and o.haveLastObs:
let ob = o.lastObs
if ob.turnKnown: line.add ",\"turnRateInterval\":" & jsonInterval(ob.turnRate)
if ob.targetKnown: line.add ",\"targetSpeedInterval\":" & jsonInterval(ob.targetSpeed)
if ob.fireKnown: line.add ",\"fireObs\":" & $ob.fire
line.add ",\"censor\":" & $ob.censored
# Raw enemy + own state, so the twin rollout (M4/twinsim) can be replayed
# OFFLINE from the telemetry alone, without re-running Java. Observation-only.
if scanned and o.haveCur:
line.add ",\"ex\":" & $o.cur.x & ",\"ey\":" & $o.cur.y &
",\"edir\":" & $o.cur.direction &
",\"espeed\":" & $o.cur.speed &
",\"eenergy\":" & $o.cur.energy
if o.haveCur:
line.add ",\"ox\":" & $o.curOwnX & ",\"oy\":" & $o.curOwnY &
",\"odir\":" & $o.curOwnDir & ",\"ospeed\":" & $o.curOwnSpeed
line.add ",\"posteriorTop5\":["
let top = o.hedge.topK(5)
for i, kv in top:
if i > 0: line.add ","
line.add "{\"name\":\"" & kv.name & "\",\"w\":" & $kv.weight & "}"
line.add "],\"entropy\":" & $o.hedge.entropy()
line.add ",\"censorRate\":" & $o.censorRate()
line.add "}\n"
o.f.write(line)
flushFile(o.f)
proc endRound*(o: Observer) =
## Close the round's telemetry with the identified kernel trace and the
## G5-metrics readiness numbers (5-tick ADE / FDE).
if not o.fileOpen: return
let top = o.hedge.argmaxName()
var line = "{\"event\":\"round_summary\",\"round\":" & $o.round &
",\"opponent\":\"" & sanitize(o.opponent) & "\"" &
",\"finalKernel\":\"" & top & "\"" &
",\"finalPosterior\":" & $o.hedge.posterior(top) &
",\"ticks\":" & $o.ticks &
",\"censored\":" & $o.censored &
",\"censorRate\":" & $o.censorRate() &
",\"scanGapMax\":" & $o.gapMax &
",\"scanGapViolations\":" & $o.gapViolations &
",\"ade\":" & $(if o.adeN == 0: 0.0 else: o.adeSum / float(o.adeN)) &
",\"fde\":" & $(if o.fdeN == 0: 0.0 else: o.fdeSum / float(o.fdeN)) &
",\"n\":" & $o.adeN & "}\n"
o.f.write(line)
flushFile(o.f)
o.f.close()
o.fileOpen = false
@@ -0,0 +1,140 @@
## CHIMERA oracle harness — G1 machinery (spec §12 Tier C, G1).
##
## G1 asks a narrow question: is the *inference layer* correct? Feed the Hedge
## posterior the exact intent stream a known kernel emits over a deterministic
## synthetic arena (no sensor error), and the weight on that kernel must reach
## `≥ 0.9` within `T*` ticks. A G1 failure indicts the implementation, not the
## idea, so the harness reports identification ticks per kernel rather than
## hiding a miss behind a threshold.
##
## The oracle reuses the same `physics.nim` mirror the twin will use, so a
## ledger/hedge bug shows up here before any live battle.
import std/[math]
import ./physics, ./ledger, ./dsl, ./hedge
type
Env* = object
arenaW*, arenaH*: float64
myX*, myY*: float64
startX*, startY*, startDir*: float64
OracleStream* = object
scans*: seq[Scan]
intents*: seq[Intent]
G1Result* = object
kernel*: string
idTick*: int ## tick posterior first reached threshold, -1 if never
finalPosterior*: float64
censorRate*: float64
ticks*: int
proc defaultEnv*(): Env =
Env(arenaW: 800.0, arenaH: 600.0, myX: 620.0, myY: 300.0,
startX: 180.0, startY: 300.0, startDir: 0.0)
proc toEnemyState(s: Scan): EnemyState =
EnemyState(tick: s.tick, x: s.x, y: s.y, direction: s.direction,
speed: s.speed, energy: s.energy)
proc generateOracle*(kernel: Kernel, params: Params, env: Env,
ticks: int): OracleStream =
## Roll `kernel` forward over the synthetic arena, emitting one scan at the
## start of every tick and the intent it commands that tick.
var e = EnemyState(tick: 0, x: env.startX, y: env.startY,
direction: env.startDir, speed: 0.0, energy: 100.0)
let m = MyState(x: env.myX, y: env.myY)
var mem = defaultMemory(params)
for t in 0 ..< ticks:
result.scans.add Scan(tick: e.tick, x: e.x, y: e.y, direction: e.direction,
speed: e.speed, energy: e.energy)
let intent = kernel.step(e, m, params, mem)
result.intents.add intent
# Server tick order: speed update, then turn limited by the new speed.
let newSpeed = stepSpeed(e.speed, intent.targetSpeed)
let turn = limitTurnRate(intent.turnRate, newSpeed)
e.direction = wrap180(e.direction + turn)
e.speed = newSpeed
e.x += e.speed * cos(degToRad(e.direction))
e.y += e.speed * sin(degToRad(e.direction))
e.x = clamp(e.x, 0.0, env.arenaW)
e.y = clamp(e.y, 0.0, env.arenaH)
if intent.fire > 0.0: e.energy -= intent.fire
e.tick = t + 1
proc combineObs*(prev, cur: Scan): LedgerObs =
## Fold the three ledger channels of one tick into a single observation.
result = turnRateInterval(prev, cur)
let sp = targetSpeedInterval(prev.speed, cur.speed)
if sp.targetKnown:
result.targetSpeed = sp.targetSpeed
result.targetKnown = true
let fire = fireFromEnergyDrop(prev.energy, cur.energy, 0.0)
if fire.fireKnown:
result.fire = fire.fire
result.fireKnown = true
if sp.censored or fire.censored:
result.censored = true
proc intentLoss*(pred: Intent, obs: LedgerObs, speed: float64): float64 =
## Raw per-tick Hedge loss (spec §7): normalized squared turn error (on the
## *realized* turn the server would apply), normalized target-speed interval
## error, and a fire Bernoulli term. Censored ticks score 0 (caller skips).
if obs.censored: return 0.0
if obs.turnKnown:
let realized = limitTurnRate(pred.turnRate, speed)
var err = 0.0
if realized < obs.turnRate.lo: err = obs.turnRate.lo - realized
elif realized > obs.turnRate.hi: err = realized - obs.turnRate.hi
result += (err / MaxTurnRate) ^ 2
if obs.targetKnown:
var err = 0.0
if pred.targetSpeed < obs.targetSpeed.lo:
err = obs.targetSpeed.lo - pred.targetSpeed
elif pred.targetSpeed > obs.targetSpeed.hi:
err = pred.targetSpeed - obs.targetSpeed.hi
result += (err / MaxForwardSpeed) ^ 2
if obs.fireKnown:
let pf = (if pred.fire > 0.0: 1.0 else: 0.0)
let obsFire = (if obs.fire > 0.0: 1.0 else: 0.0)
result += (pf - obsFire) ^ 2
proc evaluate*(stream: OracleStream, kernels: seq[Kernel], targetIdx: int,
env: Env, threshold = 0.9,
cfg = HedgeConfig()): G1Result =
## Replay the stream through the ledger + Hedge and report when the target
## kernel's posterior crosses `threshold`.
let my = MyState(x: env.myX, y: env.myY)
var h = initHedge(kernelNames(kernels), cfg)
var mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len:
mems[i] = defaultMemory(kernels[i].defaultParams)
result.kernel = kernels[targetIdx].name
result.ticks = stream.scans.len
result.idTick = -1
var obsAll: seq[LedgerObs]
var preds = newSeq[Intent](kernels.len)
var losses = newSeq[float64](kernels.len)
for t in 0 ..< stream.scans.len - 1:
let e = toEnemyState(stream.scans[t])
for i in 0 ..< kernels.len:
preds[i] = kernels[i].step(e, my, kernels[i].defaultParams, mems[i])
let obs = combineObs(stream.scans[t], stream.scans[t + 1])
obsAll.add obs
if not obs.censored:
for i in 0 ..< kernels.len:
losses[i] = intentLoss(preds[i], obs, stream.scans[t + 1].speed)
h.update(losses)
if result.idTick < 0 and h.posterior(result.kernel) >= threshold:
result.idTick = t + 1
result.finalPosterior = h.posterior(result.kernel)
result.censorRate = censorRate(obsAll)
proc runG1*(kernels: seq[Kernel], targetIdx: int, env = defaultEnv(),
ticks = 300, threshold = 0.9,
cfg = HedgeConfig()): G1Result =
## Convenience: generate the oracle stream for one kernel and evaluate it.
let params = kernels[targetIdx].defaultParams
let stream = generateOracle(kernels[targetIdx], params, env, ticks)
evaluate(stream, kernels, targetIdx, env, threshold, cfg)
@@ -0,0 +1,90 @@
## CHIMERA physics mirror — pure functions, no state, no I/O.
##
## A byte-faithful port of the Tank Royale server's movement maths. Source of
## truth: `robocode-tankroyale/server`, `rules/math.kt` (constants in
## `rules/rules.kt`). This mirror is the twin's ground truth: a mismatch silently
## poisons every downstream prediction, so every proc carries the source rule and
## is pinned by `tests/test_physics.nim`.
##
## ANGLES: 0 deg = east, counter-clockwise positive (Tank Royale standard).
import std/math
const
MaxForwardSpeed* = 8.0 ## rules.kt MAX_FORWARD_SPEED
MaxBackwardSpeed* = -8.0 ## rules.kt MAX_BACKWARD_SPEED
Acceleration* = 1.0 ## rules.kt ACCELERATION
Deceleration* = -2.0 ## rules.kt DECELERATION
MaxTurnRate* = 10.0 ## rules.kt MAX_TURN_RATE
MinFirepower* = 0.1 ## rules.kt MIN_FIREPOWER
MaxFirepower* = 3.0 ## rules.kt MAX_FIREPOWER
proc clampSpeed*(v: float64): float64 =
## rules/math.kt clampSpeed: clamp to [-8, +8].
clamp(v, MaxBackwardSpeed, MaxForwardSpeed)
proc clampFirepower*(p: float64): float64 =
## rules/math.kt clampFirepower: clamp to [0.1, 3.0].
clamp(p, MinFirepower, MaxFirepower)
proc stepSpeed*(currentSpeed, targetSpeed: float64): float64 =
## rules/math.kt calcNewBotSpeed, ported case for case.
##
## The update is asymmetric: accelerate by at most +1/tick, decelerate by at
## most -2/tick, and a same-sign target is approached until it is met. When the
## target crosses the sign of the current speed the server assigns the
## crossing-zero value `(1 - currentSpeed/2) * -1` directly (not additively).
## Negative current speeds are handled by odd symmetry.
if currentSpeed < 0.0:
return -stepSpeed(-currentSpeed, -targetSpeed) # odd symmetry
if currentSpeed > 0.0:
if sgn(currentSpeed) == sgn(targetSpeed):
let diff = targetSpeed - currentSpeed
if diff >= 0.0:
return min(currentSpeed + min(diff, Acceleration), MaxForwardSpeed)
else:
return max(currentSpeed + max(diff, Deceleration), MaxBackwardSpeed)
else: # crossing the speed of 0
if targetSpeed == 0.0:
return 0.0
let decelerationTime = currentSpeed / -Deceleration # = currentSpeed / 2
return (1.0 - decelerationTime) * -Acceleration
else: # currentSpeed == 0
let diff = targetSpeed
let acceleration = min(abs(diff), Acceleration)
if diff >= 0.0:
return min(currentSpeed + acceleration, MaxForwardSpeed)
else:
return max(currentSpeed - acceleration, MaxBackwardSpeed)
proc maxTurnRate*(speed: float64): float64 =
## rules/math.kt calcMaxTurnRate: `10 - 0.75 * |clampSpeed(speed)|`.
MaxTurnRate - 0.75 * abs(clampSpeed(speed))
proc limitTurnRate*(turnRate, speed: float64): float64 =
## rules/math.kt limitTurnRate: clamp a commanded body turn to the speed cap.
clamp(turnRate, -maxTurnRate(speed), maxTurnRate(speed))
proc bulletSpeed*(firepower: float64): float64 =
## rules/math.kt calcBulletSpeed: `20 - 3 * clampFirepower(p)`.
20.0 - 3.0 * clampFirepower(firepower)
proc bulletDamage*(firepower: float64): float64 =
## rules/math.kt calcBulletDamage: `4*clamp(p)` plus `2*(p-1)` when `p > 1`.
result = 4.0 * clampFirepower(firepower)
if firepower > 1.0:
result += 2.0 * (firepower - 1.0)
proc gunHeat*(firepower: float64): float64 =
## rules/math.kt calcGunHeat: `1 + clampFirepower(p) / 5`.
1.0 + clampFirepower(firepower) / 5.0
proc wrap180*(deg: float64): float64 =
## Shortest signed angle in (-180, 180].
result = deg mod 360.0
if result <= -180.0: result += 360.0
elif result > 180.0: result -= 360.0
proc bearingTo*(fromX, fromY, toX, toY: float64): float64 =
## Compass-style bearing (deg, CCW from +x) from one point to another.
arctan2(toY - fromY, toX - fromX) * 180.0 / PI
@@ -0,0 +1,283 @@
## CHIMERA probe scheduler — active causal probing (spec §9, milestone M5).
##
## One probe per ~25 ticks (range 20–30), survival-gated, camouflaged as ordinary
## movement noise, and selected by **expected posterior-entropy reduction** over a
## small set of candidate actions (sudden stop, reversal, speed modulation,
## direction flip). The counterfactual engine is `twinsim.rollout`: for each
## candidate we roll each of the top-K kernels forward under OUR candidate action
## and measure how far the kernels' predicted enemy reactions separate. The
## candidate that separates them most removes the most posterior entropy.
##
## Decision 2 (spec §9): probes MAY cost score. The budget is a cost ledger; the
## survival gate is what keeps the spend bounded — a probe that would get us shot
## is never issued.
##
## This module is pure and deterministic: no I/O, no clock, no RNG. Everything
## derives from the ReplayTick posterior and the ProbeContext, so reruns are
## byte-identical (pinned by tests/test_probes.nim).
##
## Behaviour kill switch: compile with `-d:chimeraNoProbes` and the bot never
## calls this scheduler (see ChimeraBot.nim), so the command path is byte-identical
## to the M1 exact-copy baseline.
import std/[math, algorithm]
import ./physics, ./dsl, ./twinsim
const
ProbesEnabled* = not defined(chimeraNoProbes) and not defined(chimeraInert)
## Compile-time kill switch. `-d:chimeraNoProbes` removes the probe advisory
## from the bot entirely (G6 ablation OFF arm; command path == M1 baseline).
## `-d:chimeraInert` (M6) forces it off too: inert == the M1 exact copy.
DefaultInterval* = 25 ## nominal probe cadence, ticks (spec: 20–30)
MinInterval* = 20
MaxInterval* = 30
ProbeHorizon* = 5 ## ticks of enemy reaction we predict (matches G5)
TopKernels* = 3 ## hypotheses whose separation drives selection
LowEnergy* = 25.0 ## "our energy is low" gate threshold
WallMargin* = 25.0 ## "wall-pinned" band from any wall
HeatHot* = 0.5 ## "their gunHeat is (near) zero"
AimTol* = 30.0 ## body-heading proxy cone for "aimed at us"
ProbeSigma* = 6.0 ## likelihood width (units) when scoring separation
RoundSoftLimit* = 2000 ## assumed round length for the "nearly over" gate
type
ProbeKind* = enum
## Enum order is the deterministic tie-break (earlier wins).
pkSuddenStop, pkReversal, pkSpeedModulation, pkDirectionFlip,
pkDistance, pkGunShot
ProbeCandidate* = object
kind*: ProbeKind
turnRate*: float64
targetSpeed*: float64
fire*: float64 ## gun probe: the probe IS a low-power shot (0 else)
GateState* = object
allow*: bool
reason*: string
ProbeContext* = object
## Everything the gate needs, all observable / estimated.
tick*: int
ourEnergy*: float64
ownX*, ownY*, ownSpeed*: float64
arenaW*, arenaH*: float64
enemyX*, enemyY*: float64
enemyGunHeat*: float64 ## from the ledger's fire channel (+ decay)
enemyAimedAtUs*: bool ## body-heading proxy; gun aim is unobservable
ourGunHeat*: float64 ## our gun heat (gun probes need it at 0)
ourGunAimed*: bool ## our gun points at the enemy (camouflage)
roundLimit*: int ## 0 disables the round-end gate
ProbeDecision* = object
trigger*: bool ## the budget fired this tick
candidate*: ProbeCandidate
gate*: GateState
entropyBefore*: float64
entropyAfter*: float64 ## expected, after the most informative probe
ProbeScheduler* = object
kernels*: seq[Kernel]
ticksSinceProbe*: int
interval*: int
probes*: int ## executed (allowed) probe count
# ── construction ─────────────────────────────────────────────────────────────
proc initProbeScheduler*(kernels: seq[Kernel],
interval = DefaultInterval): ProbeScheduler =
result.kernels = kernels
result.interval = clamp(interval, MinInterval, MaxInterval)
# ── survival gate (spec §9) ──────────────────────────────────────────────────
proc aimedAtUs*(ownX, ownY, enemyX, enemyY, enemyDir: float64,
tol = AimTol): bool =
## True when the enemy's BODY heading points within `tol` of us. Gun aim is not
## observable, so body heading is the proxy (guns that ride the body are the
## common case); this makes the gate conservative, never trigger-happy.
abs(wrap180(bearingTo(enemyX, enemyY, ownX, ownY) - enemyDir)) <= tol
proc survivalGate*(ctx: ProbeContext): GateState =
## Deny order is the spec's order, so the reason string is deterministic.
if ctx.ourEnergy < LowEnergy:
return GateState(allow: false, reason: "energy")
if ctx.enemyAimedAtUs and ctx.enemyGunHeat <= HeatHot:
return GateState(allow: false, reason: "enemy-hot-aimed")
if ctx.ownX < WallMargin or ctx.ownX > ctx.arenaW - WallMargin or
ctx.ownY < WallMargin or ctx.ownY > ctx.arenaH - WallMargin:
return GateState(allow: false, reason: "wall-pinned")
if ctx.roundLimit > 0 and ctx.roundLimit - ctx.tick < 2 * MaxInterval:
return GateState(allow: false, reason: "round-end")
GateState(allow: true, reason: "ok")
# ── candidates + camouflage ──────────────────────────────────────────────────
proc gunProbeAllowed*(ctx: ProbeContext): bool =
## Camouflage gate for a GUN probe (M5.5): a shot is only plausible — and only
## useful as a probe — when our gun is cool and already pointing at the enemy,
## so the shot reads as the ELM gun firing anyway. Combined with
## `survivalGate` (energy / enemy-hot-aimed / wall), never fire when exposed.
ctx.ourGunHeat <= 0.0 and ctx.ourGunAimed and
ctx.ourEnergy >= LowEnergy and not ctx.enemyAimedAtUs
proc candidates*(ctx: ProbeContext): seq[ProbeCandidate] =
## Six plausible body/gun actions. Magnitudes are deliberate so a probe reads
## as ordinary noise, not a tell. Four movement probes, one DISTANCE probe
## (approach/retreat burst), and — when the gun gate allows — one GUN probe.
let cap = maxTurnRate(ctx.ownSpeed)
var rev = -ctx.ownSpeed
if abs(rev) < 1.0: rev = -3.0
rev = clamp(rev, -4.0, 4.0)
result = @[
ProbeCandidate(kind: pkSuddenStop, turnRate: 0.0, targetSpeed: 0.0),
ProbeCandidate(kind: pkReversal, turnRate: 0.0, targetSpeed: rev),
ProbeCandidate(kind: pkSpeedModulation, turnRate: 0.0,
targetSpeed: clamp(ctx.ownSpeed + 2.0,
MaxBackwardSpeed, MaxForwardSpeed)),
ProbeCandidate(kind: pkDirectionFlip, turnRate: min(4.0, cap),
targetSpeed: ctx.ownSpeed),
# DISTANCE probe: a strong range-changing burst (approach / retreat).
ProbeCandidate(kind: pkDistance, turnRate: 0.0,
targetSpeed: MaxForwardSpeed),
ProbeCandidate(kind: pkDistance, turnRate: 0.0,
targetSpeed: MaxBackwardSpeed),
]
if gunProbeAllowed(ctx):
result.add ProbeCandidate(kind: pkGunShot, turnRate: 0.0,
targetSpeed: ctx.ownSpeed, fire: MinFirepower)
proc camouflage*(c: ProbeCandidate, ctx: ProbeContext): ProbeCandidate =
## Clamp a candidate into the physics envelope: an unachievable command would
## be both implausible and mispredicted by the twin's own rollout.
result.kind = c.kind
result.turnRate = clamp(c.turnRate, -maxTurnRate(ctx.ownSpeed),
maxTurnRate(ctx.ownSpeed))
result.targetSpeed = clamp(c.targetSpeed, MaxBackwardSpeed, MaxForwardSpeed)
result.fire = c.fire
proc plausible*(c: ProbeCandidate, ctx: ProbeContext): bool =
## Tests-only sanity predicate: camouflage output is always plausible.
abs(c.turnRate) <= maxTurnRate(ctx.ownSpeed) + 1e-9 and
c.targetSpeed >= MaxBackwardSpeed - 1e-9 and
c.targetSpeed <= MaxForwardSpeed + 1e-9
# ── entropy / information gain ───────────────────────────────────────────────
proc entropyOf*(w: openArray[float64]): float64 =
## Shannon entropy (nats) of a non-negative vector, normalized internally.
var s = 0.0
for x in w: s += x
if s <= 0.0: return 0.0
for x in w:
let p = x / s
if p > 0.0: result -= p * ln(p)
proc topIndices*(weights: openArray[float64], k: int): seq[int] =
## Indices of the k largest weights; ties broken by ascending index.
let w = @weights
var idx = newSeq[int](w.len)
for i in 0 ..< idx.len: idx[i] = i
idx.sort(proc(a, b: int): int =
let c = cmp(w[b], w[a])
if c != 0: c else: cmp(a, b))
for i in 0 ..< min(k, idx.len): result.add idx[i]
proc onehot(origin: ReplayTick, i: int): ReplayTick =
result = origin
result.weights = newSeq[float64](origin.weights.len)
result.weights[i] = 1.0
proc reactionFeature(kernels: seq[Kernel], origin: ReplayTick, idx: int,
cand: ProbeCandidate, horizon: int): seq[float64] =
## The enemy trajectory kernel `idx` predicts under OUR candidate action,
## flattened (x,y) per tick. This is the "reaction" the probe is choosing.
var plan = newSeq[PlanStep](horizon)
for h in 0 ..< horizon:
plan[h] = PlanStep(turnRate: cand.turnRate, targetSpeed: cand.targetSpeed,
fire: cand.fire)
let r = rollout(kernels, onehot(origin, idx), horizon, plan = plan)
for p in r.points:
result.add p.x
result.add p.y
proc expectedEntropyDrop*(kernels: seq[Kernel], origin: ReplayTick,
top: seq[int], cand: ProbeCandidate,
horizon = ProbeHorizon): float64 =
## Expected posterior-entropy reduction from issuing `cand`.
##
## Each top kernel j is treated as a possible truth: if j is true, the observed
## reaction is j's predicted trajectory, and the posterior after seeing it is
## `prior_i · N(feat_j | feat_i, σ)`. The expected drop is `Σ_j prior_j ·
## (H(prior) − H(post_j))`. Kernels that react differently to the same probe
## separate; kernels that react identically contribute nothing.
let k = top.len
if k == 0: return 0.0
var prior = newSeq[float64](k)
var s = 0.0
for j, idx in top:
prior[j] = max(0.0, origin.weights[idx])
s += prior[j]
if s <= 0.0: return 0.0
for j in 0 ..< k: prior[j] /= s
var feats = newSeq[seq[float64]](k)
for j, idx in top:
feats[j] = reactionFeature(kernels, origin, idx, cand, horizon)
let h0 = entropyOf(prior)
let twoSigma2 = 2.0 * ProbeSigma * ProbeSigma
var drop = 0.0
for j in 0 ..< k:
var post = newSeq[float64](k)
for i in 0 ..< k:
var d2 = 0.0
for m in 0 ..< feats[i].len:
let d = feats[i][m] - feats[j][m]
d2 += d * d
post[i] = prior[i] * exp(-d2 / twoSigma2)
drop += prior[j] * (h0 - entropyOf(post))
drop
# ── selection + budget ───────────────────────────────────────────────────────
proc chooseProbe*(kernels: seq[Kernel], origin: ReplayTick, ctx: ProbeContext,
horizon = ProbeHorizon): ProbeDecision =
## Pick the candidate with the largest expected entropy drop. Deterministic
## tie-break: earlier ProbeKind, then smaller action magnitude.
result.entropyBefore = entropyOf(origin.weights)
result.entropyAfter = result.entropyBefore
let top = topIndices(origin.weights, TopKernels)
var bestDrop = -Inf
var bestMag = Inf
var have = false
for cand in candidates(ctx):
let c = camouflage(cand, ctx)
let drop = expectedEntropyDrop(kernels, origin, top, c, horizon)
let mag = abs(c.turnRate) + abs(c.targetSpeed)
let better =
(not have) or drop > bestDrop + 1e-12 or
(abs(drop - bestDrop) <= 1e-12 and
(c.kind.ord < result.candidate.kind.ord or
(c.kind == result.candidate.kind and mag < bestMag)))
if better:
bestDrop = drop
bestMag = mag
result.candidate = c
have = true
if have: result.entropyAfter = result.entropyBefore - bestDrop
proc consider*(s: var ProbeScheduler, origin: ReplayTick,
ctx: ProbeContext): ProbeDecision =
## One tick of the scheduler. Increments the budget; once the interval has
## elapsed it always *triggers* (so the gate state is observable in telemetry),
## but the budget only resets when the gate ALLOWS the probe to be executed.
inc s.ticksSinceProbe
result.gate = survivalGate(ctx)
if s.ticksSinceProbe < s.interval:
return
result = chooseProbe(s.kernels, origin, ctx)
result.trigger = true
result.gate = survivalGate(ctx)
if result.gate.allow:
s.ticksSinceProbe = 0
inc s.probes
@@ -0,0 +1,108 @@
## CHIMERA residual head — online linear correction for the posterior mixture.
##
## Source of truth: `docs/chimera-spec.md` §10. The DSL mixture is a compact
## approximation, so a small head absorbs its *systematic* mispredictions: it
## predicts the residual `realized - mixture_predicted` per channel (turn,
## targetSpeed, fire) from a fixed feature vector (last intents, scan age,
## distance, our last plan).
##
## Default: per-channel ridge-regularised online SGD, zero-initialised so runs
## are byte-identical (deterministic; no RNG). The 32-unit GRU upgrade path is
## reserved behind `-d:chimeraGRU` and is deliberately NOT implemented here — the
## flag currently selects the same linear head (see `UseGRU`), because the linear
## head is the M6 default and the GRU is an unproven cost we did not need.
##
## No I/O, no clock, no allocation: `observe` is O(NFeatures) and safe to call
## every scanned tick (well below µs at NFeatures = 6).
import std/math
const
NFeatures* = 6
## last enemy turn, last enemy targetSpeed, scan gap, distance,
## our last turn, our last speed.
UseGRU* = defined(chimeraGRU)
## Reserved upgrade path. The GRU is not implemented; when the flag is set
## the linear head is still what runs (documented deviation, M6).
type
ResidualInput* = object
## Everything the feature vector needs, all observable.
lastTurn*: float64 ## last realized enemy turn rate (deg/tick)
lastSpeed*: float64 ## last realized enemy target speed (units/tick)
scanAge*: float64 ## ticks since the previous scan (gap)
dist*: float64 ## our distance to the enemy (units)
ownTurn*: float64 ## our last commanded/observed body turn (deg/tick)
ownSpeed*: float64 ## our last realized speed (units/tick)
ResidualTarget* = object
## `realized - mixture_predicted`, per channel.
turn*, speed*, fire*: float64
ResidualPrediction* = object
turn*, speed*, fire*: float64
ResidualHead* = object
wTurn*, wSpeed*, wFire*: array[NFeatures, float64]
bTurn*, bSpeed*, bFire*: float64
lr*: float64
l2*: float64
samples*: int
# ── construction ────────────────────────────────────────────────────────────
proc initResidualHead*(lr = 0.05, l2 = 1e-4): ResidualHead =
## Zero weights, so two heads fed the same stream stay identical.
result.lr = lr
result.l2 = l2
proc reset*(h: var ResidualHead) =
## Back to the freshly-constructed state (keeps the configured lr/l2).
h = initResidualHead(h.lr, h.l2)
# ── features / prediction / update ──────────────────────────────────────────
proc features*(x: ResidualInput): array[NFeatures, float64] =
## Fixed, normalised feature vector, clamped to a sane band so an outlier
## observation can never blow the linear head up. Deterministic /
## allocation-free.
[clamp(x.lastTurn / 10.0, -4.0, 4.0),
clamp(x.lastSpeed / 8.0, -4.0, 4.0),
clamp(x.scanAge / 5.0, -4.0, 4.0),
clamp(x.dist / 800.0, 0.0, 4.0),
clamp(x.ownTurn / 10.0, -4.0, 4.0),
clamp(x.ownSpeed / 8.0, -4.0, 4.0)]
proc predict*(h: ResidualHead, f: array[NFeatures, float64]): ResidualPrediction =
var t = h.bTurn
var s = h.bSpeed
var fi = h.bFire
for i in 0 ..< NFeatures:
t += h.wTurn[i] * f[i]
s += h.wSpeed[i] * f[i]
fi += h.wFire[i] * f[i]
ResidualPrediction(turn: t, speed: s, fire: clamp(fi, -1.0, 1.0))
proc observe*(h: var ResidualHead, f: array[NFeatures, float64],
target: ResidualTarget) =
## One ridge-SGD step per channel. `target` is the residual the mixture missed.
template sgd(w: untyped, b: untyped, tgt: float64) =
var p = b
for i in 0 ..< NFeatures: p += w[i] * f[i]
let err = tgt - p
for i in 0 ..< NFeatures:
w[i] += h.lr * (err * f[i] - h.l2 * w[i])
b += h.lr * err
sgd(h.wTurn, h.bTurn, target.turn)
sgd(h.wSpeed, h.bSpeed, target.speed)
sgd(h.wFire, h.bFire, target.fire)
inc h.samples
proc meanSquaredLoss*(h: ResidualHead, f: array[NFeatures, float64],
target: ResidualTarget): float64 =
## Squared residual error of the current head on one sample (diagnostics/tests).
let p = h.predict(f)
let dt = target.turn - p.turn
let ds = target.speed - p.speed
let df = target.fire - p.fire
(dt * dt + ds * ds + df * df) / 3.0
@@ -0,0 +1,256 @@
## CHIMERA twin rollout — counterfactual core (spec §8, milestone M4).
##
## Given a recorded round (raw per-tick telemetry, §Observer) and a candidate
## plan for our next `k` ticks, `rollout()` advances the posterior-weight MIXTURE
## of kernels (never the argmax, spec §7) through the physics mirror: one step
## per horizon tick, each kernel carrying its own predicted enemy state and
## `KernelMem`, combined by posterior weight into a predicted enemy-intent
## trajectory, a per-kernel next-position distribution, and a fire-timing
## estimate `P(fire)`.
##
## The module is deliberately OFFLINE and side-effect free: it reads the JSONL
## the observation sidecar wrote (`/tmp/chimera_twin` / `/tmp/chimera_g4_run`),
## re-runs the ledger + Hedge over the raw states to recover the per-tick
## posterior, and never touches the bot. Nothing here is wired into commands at
## M4 — integration is M5+.
import std/[math, os, strutils, sequtils]
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle
type
TickRecord* = object
## One telemetry tick. Only scanned ticks carry enemy state.
tick*: int
scanned*: bool
ex*, ey*, edir*, espeed*, eenergy*: float64
ox*, oy*, odir*, ospeed*: float64
fireObs*: float64
fireKnown*: bool
Record* = object
opponent*: string
round*: int
ticks*: seq[TickRecord]
PlanStep* = object
## Our candidate command for one future tick.
turnRate*, targetSpeed*, fire*: float64
RolloutPoint* = object
tick*: int
x*, y*: float64 ## mixture-predicted enemy position
pFire*: float64 ## mixture P(enemy fires this tick)
turnRate*: float64 ## mixture-predicted enemy turn rate (deg/tick)
targetSpeed*: float64 ## mixture-predicted enemy target speed (units/tick)
Rollout* = object
horizon*: int
points*: seq[RolloutPoint]
samples*: seq[tuple[x, y: float64]] ## per-kernel final position (distribution)
fireWithin*: float64 ## P(fire at least once in 1..k)
ReplayTick* = object
## A scanned tick with the recovered posterior + kernel memory at that tick.
tick*: int
ex*, ey*, edir*, espeed*, eenergy*: float64
ox*, oy*, odir*, ospeed*: float64
lastTurn*, lastSpeed*: float64 ## last observed intent (persistence baseline)
weights*: seq[float64]
mems*: seq[KernelMem]
# ── telemetry parsing ───────────────────────────────────────────────────────
proc numField(ln: string, key: string, default = 0.0): float64 =
let needle = "\"" & key & "\":"
let i = ln.find(needle)
if i < 0: return default
var j = i + needle.len
while j < ln.len and ln[j] in {' ', '\t'}: inc j
let start = j
while j < ln.len and (ln[j] in Digits or ln[j] in {'-', '+', '.', 'e', 'E'}):
inc j
if j == start: return default
try: parseFloat(ln[start ..< j])
except ValueError: default
proc boolField(ln: string, key: string, default = false): bool =
let needle = "\"" & key & "\":"
let i = ln.find(needle)
if i < 0: return default
ln[i + needle.len .. ^1].strip.startsWith("true")
proc loadRecord*(path: string): Record =
## Parse one JSONL telemetry file. The filename is `<opponent>-<round>.jsonl`.
let base = path.extractFilename
if base.len > 0:
let dash = base.rfind('-')
if dash > 0:
result.opponent = base[0 ..< dash]
result.round = parseInt(base[dash + 1 ..< base.len - 6])
for ln in lines(path):
if not ln.startsWith("{\"tick\""): continue
var t = TickRecord(tick: int(numField(ln, "tick")))
t.scanned = boolField(ln, "scan")
if t.scanned:
t.ex = numField(ln, "ex"); t.ey = numField(ln, "ey")
t.edir = numField(ln, "edir"); t.espeed = numField(ln, "espeed")
t.eenergy = numField(ln, "eenergy")
t.ox = numField(ln, "ox"); t.oy = numField(ln, "oy")
t.odir = numField(ln, "odir"); t.ospeed = numField(ln, "ospeed")
if ln.find("\"fireObs\":") >= 0:
t.fireObs = numField(ln, "fireObs"); t.fireKnown = true
result.ticks.add t
proc loadDir*(dir: string): seq[Record] =
## Recursively load every `.jsonl` under `dir` (flat or per-opponent subdirs).
for path in walkDirRec(dir):
if path.endsWith(".jsonl"): result.add loadRecord(path)
# ── offline replay: recover the per-tick posterior ──────────────────────────
proc foldObs(prev, cur: TickRecord): LedgerObs =
## Same fold the observer uses: turn + speed intervals, fire from an energy
## drop in [0.1, 3.0]; anything else leaves the fire channel unobserved.
result = turnRateInterval(
Scan(tick: prev.tick, direction: prev.edir, speed: prev.espeed),
Scan(tick: cur.tick, direction: cur.edir, speed: cur.espeed))
result.tick = cur.tick
let sp = targetSpeedInterval(prev.espeed, cur.espeed)
if sp.targetKnown:
result.targetSpeed = sp.targetSpeed
result.targetKnown = true
if sp.censored: result.censored = true
let drop = prev.eenergy - cur.eenergy
if drop >= MinFirepower - IntervalEps and drop <= MaxFirepower + IntervalEps:
result.fire = drop
result.fireKnown = true
proc replay*(rec: Record, kernels: seq[Kernel],
cfg = HedgeConfig()): seq[ReplayTick] =
## Re-run ledger + Hedge over the recorded raw states. Emits one entry per
## scanned tick. The posterior at a tick folds EVERY observation up to and
## including that tick, so a rollout from it is causal.
var h = initHedge(kernelNames(kernels), cfg)
var mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len: mems[i] = defaultMemory(kernels[i].defaultParams)
var prev: TickRecord
var havePrev = false
var lastTurn = 0.0
var lastSpeed = 0.0
for t in rec.ticks:
if not t.scanned: continue
if havePrev:
let obs = foldObs(prev, t)
if not obs.censored:
let e = EnemyState(tick: prev.tick, x: prev.ex, y: prev.ey,
direction: prev.edir, speed: prev.espeed,
energy: prev.eenergy)
let my = MyState(x: prev.ox, y: prev.oy)
var losses = newSeq[float64](kernels.len)
for i in 0 ..< kernels.len:
let pred = kernels[i].step(e, my, kernels[i].defaultParams, mems[i])
losses[i] = intentLoss(pred, obs, t.espeed)
h.update(losses)
if obs.turnKnown: lastTurn = (obs.turnRate.lo + obs.turnRate.hi) / 2.0
if obs.targetKnown: lastSpeed = (obs.targetSpeed.lo + obs.targetSpeed.hi) / 2.0
var rp = ReplayTick(tick: t.tick, ex: t.ex, ey: t.ey, edir: t.edir,
espeed: t.espeed, eenergy: t.eenergy,
ox: t.ox, oy: t.oy, odir: t.odir, ospeed: t.ospeed,
lastTurn: lastTurn, lastSpeed: lastSpeed)
rp.weights = h.weights
rp.mems = mems
result.add rp
prev = t
havePrev = true
# ── rollout ─────────────────────────────────────────────────────────────────
proc rollout*(kernels: seq[Kernel], origin: ReplayTick, k: int,
plan: seq[PlanStep] = @[],
actualOwn: seq[tuple[x, y: float64]] = @[]): Rollout =
## Roll the posterior mixture forward `k` ticks.
##
## * `plan` — our candidate commands (turnRate/targetSpeed). When `actualOwn`
## is empty, our own state is advanced with the physics mirror under `plan`,
## so changing the plan changes the kernels' `MyState` input and therefore
## the prediction (the counterfactual).
## * `actualOwn` — replay OUR ACTUAL recorded positions (G5 mode); the plan is
## then ignored for movement.
result.horizon = k
let n = kernels.len
var est = newSeq[EnemyState](n)
for i in 0 ..< n:
est[i] = EnemyState(tick: origin.tick, x: origin.ex, y: origin.ey,
direction: origin.edir, speed: origin.espeed,
energy: origin.eenergy)
var mems = origin.mems
var myX = origin.ox
var myY = origin.oy
var myDir = origin.odir
var mySpeed = origin.ospeed
const eps = 1e-9
var pNoFire = 1.0
for h in 1 .. k:
if actualOwn.len >= h:
myX = actualOwn[h - 1].x
myY = actualOwn[h - 1].y
else:
let p = (if plan.len >= h: plan[h - 1] else: PlanStep())
mySpeed = stepSpeed(mySpeed, p.targetSpeed)
myDir = wrap180(myDir + limitTurnRate(p.turnRate, mySpeed))
myX += mySpeed * cos(degToRad(myDir))
myY += mySpeed * sin(degToRad(myDir))
let my = MyState(x: myX, y: myY)
var mx = 0.0
var myY2 = 0.0
var pf = 0.0
var mixTurn = 0.0
var mixSpeed = 0.0
for i in 0 ..< n:
let it = kernels[i].step(est[i], my, kernels[i].defaultParams, mems[i])
let ns = stepSpeed(est[i].speed, it.targetSpeed)
est[i].direction = wrap180(est[i].direction +
limitTurnRate(it.turnRate, ns))
est[i].speed = ns
est[i].x = clamp(est[i].x + ns * cos(degToRad(est[i].direction)),
0.0, kernels[i].defaultParams.arenaW)
est[i].y = clamp(est[i].y + ns * sin(degToRad(est[i].direction)),
0.0, kernels[i].defaultParams.arenaH)
est[i].tick = origin.tick + h
let w = if i < origin.weights.len: origin.weights[i] else: 0.0
mx += w * est[i].x
myY2 += w * est[i].y
mixTurn += w * it.turnRate
mixSpeed += w * it.targetSpeed
if it.fire > eps: pf += w
result.points.add RolloutPoint(tick: origin.tick + h, x: mx, y: myY2, pFire: pf,
turnRate: mixTurn, targetSpeed: mixSpeed)
pNoFire *= (1.0 - min(1.0, pf))
for i in 0 ..< n: result.samples.add (est[i].x, est[i].y)
result.fireWithin = 1.0 - pNoFire
# ── persistence baseline (spec G5) ──────────────────────────────────────────
proc persistence*(origin: ReplayTick, k: int): seq[tuple[x, y: float64]] =
## Predict the enemy repeats its LAST observed intent (turn rate and target
## speed interval midpoints) for `k` ticks through the physics mirror.
var e = EnemyState(tick: origin.tick, x: origin.ex, y: origin.ey,
direction: origin.edir, speed: origin.espeed,
energy: origin.eenergy)
for h in 1 .. k:
let ns = stepSpeed(e.speed, origin.lastSpeed)
e.direction = wrap180(e.direction + limitTurnRate(origin.lastTurn, ns))
e.speed = ns
e.x += ns * cos(degToRad(e.direction))
e.y += ns * sin(degToRad(e.direction))
result.add (e.x, e.y)
proc fireRate*(rec: Record): float64 =
## Empirical per-tick enemy fire rate (scanned ticks).
var fires = 0
var n = 0
for t in rec.ticks:
if not t.scanned: continue
inc n
if t.fireKnown and t.fireObs > 0.0: inc fires
if n == 0: 0.0 else: float(fires) / float(n)
@@ -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,811 @@
## 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 dodgeActive*(m: TfilModule, selfX, selfY: float): bool =
## Public read-only view of the bullet-avoidance reflex, for the CHIMERA
## influence overlay: while a tracked bullet is locked, TFIL is mid-dodge and
## the overlay must not touch the command (M6 spec §10).
m.bulletLock(selfX, selfY)
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))
+303
View File
@@ -0,0 +1,303 @@
## Shared benchmark plumbing for the M5.5 unified identification metric.
##
## Source of truth: `docs/chimera-spec.md` §12 G4/G6 (M5.5 metric unification).
## `idTicks` is defined ONE way everywhere: per round, the ROUND-RELATIVE tick
## at which `max_kernel posterior > 0.8` first holds. Per opponent the benches
## report median / p90 / id-fraction over ALL rounds in the protocol. Whether the
## argmax equals the expected kernel is a separate diagnostic column.
##
## Live battles need Java + the TR server/runner JARs + the unpacked Nim sample
## bots; callers must guard-skip when absent. Throwaway output lives under /tmp.
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times, net, streams]
const
RunnerJar* = "/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"
RunnerDir* = currentSourcePath().parentDir.parentDir / ".." / "tools" / "battle_runner"
ServerJar* = "/home/davide/Downloads/robocode-tankroyale/robocode-tankroyale-server.jar"
# ── restartable server (the shared test server degrades after many battles,
# hanging some opponents; benches therefore own and recycle the server) ────
var serverProc: Process = nil
var serverPort = 0
proc findFreePort(): int =
let s = newSocket()
s.bindAddr(Port(0))
let (_, port) = s.getLocalAddr()
s.close()
port.int
proc restartServer*() =
if serverProc != nil:
serverProc.terminate()
sleep(300)
if serverProc.peekExitCode() == -1: serverProc.kill()
serverProc.close()
serverProc = nil
serverPort = findFreePort()
serverProc = startProcess("java", args = @["-jar",
getEnv("TR_SERVER_JAR", ServerJar), "--port", $serverPort,
"--enable-initial-position", "--tps", "-1"],
options = {poUsePath, poStdErrToStdOut})
let deadline = epochTime() + 20.0
var ready = false
while epochTime() < deadline:
var line: string
if not serverProc.outputStream.readLine(line): break
if "Starting server on port" in line:
ready = true
break
if not ready:
quit("TR server did not start")
proc serverUrl*(): string = "ws://localhost:" & $serverPort
proc killStaleBots*() =
## SIGKILL any lingering runner/bot from a timed-out battle. The bracket
## patterns keep pkill from matching this process's own command line.
discard execCmdEx("pkill -9 -f '[T]estBattleRunner' 2>/dev/null")
discard execCmdEx("pkill -9 -f '[C]himeraBot' 2>/dev/null")
const
SampleRoot* = getEnv(
"TR_SAMPLE_BOTS",
"/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7")
GarageSrc* = currentSourcePath().parentDir.parentDir / "src"
Threshold* = 0.8 ## unified identification threshold (spec G4)
TargetTicks* = 300 ## unified G4 tick budget
MaxAttempts* = 4
## The 8 behavior-diverse ground-truth targets and the kernel each is expected
## to identify (§12 verified mapping; v0.2 STATIC refinement documented in
## bench_g4's history).
const Expected* = {
"Crazy": "ZIGZAG",
"SpinBot": "ORBIT_BALLIST",
"RamFire": "STATIC",
"Corners": "STATIC",
"Walls": "WALLCRAWL",
"TrackFire": "STATIC",
"Fire": "STATIC",
"VelociBot": "STOP_AND_GO",
}.toTable
## G5' v2 subsets (M5.5): persistence is not optimal for the MOVING set.
const MovingOpponents* = @["Crazy", "SpinBot", "VelociBot", "Walls"]
const StaticOpponents* = @["RamFire", "Corners", "TrackFire", "Fire"]
proc guardSkip*() =
let serverOk = fileExists(getEnv("TR_SERVER_JAR", ServerJar))
let runnerOk = fileExists(getEnv("TR_BATTLE_RUNNER", RunnerJar))
if not serverOk or not runnerOk or not dirExists(SampleRoot):
echo "Skipping bench: TR_SERVER_JAR / TR_BATTLE_RUNNER / sample bots missing."
quit(0)
proc runBattleHardLog*(serverUrl: string, botDirs: seq[string], rounds: int,
timeoutMs = 90000, maxSpeed = true,
logName = "chimera_runner"): tuple[ok: bool, logPath: string] =
## Hard-timeout battle that KEEPS the runner log, for benches that need the
## per-round results (G7). `battle_runner`'s TestBattleRunner emits JSON lines.
let jar = getEnv("TR_BATTLE_RUNNER", RunnerJar)
let classDir = getEnv("TR_BATTLE_RUNNER_DIR", RunnerDir)
let logf = getTempDir() / (logName & ".log")
var args = "--server-url " & quoteShell(serverUrl) &
" --rounds " & $rounds &
" --bot-dirs " & quoteShell(botDirs.join(","))
if maxSpeed: args.add " --max-speed"
let hardSec = int(timeoutMs div 1000) + 5
let cmd = "timeout -s KILL " & $hardSec & " java -cp " &
quoteShell(classDir & ":" & jar) &
" TestBattleRunner " & args & " > " & quoteShell(logf) & " 2>&1"
let p = startProcess("sh", args = @["-c", cmd], options = {poUsePath})
let deadline = epochTime() + float(timeoutMs) / 1000.0
var done = false
while epochTime() < deadline:
if p.peekExitCode() != -1:
done = true
break
sleep(100)
if not done:
p.terminate()
sleep(200)
if p.peekExitCode() == -1: p.kill()
p.close()
return (false, logf)
result = (p.peekExitCode() == 0, logf)
p.close()
proc runBattleHard*(serverUrl: string, botDirs: seq[string], rounds: int,
timeoutMs = 90000, maxSpeed = true): bool =
## Hard-timeout battle: `test_framework.runBattleRunner` can block forever when
## the Java runner stops emitting output while still alive, so benches use this
## wrapper (shell redirect to a log, poll, then kill). Battles normally take
## 1-3 s, so 90 s is generous and bounds a hang.
runBattleHardLog(serverUrl, botDirs, rounds, timeoutMs, maxSpeed).ok
proc deps*(): seq[string] =
for p in ["robocode_tankroyale_botapi", "jsony"]:
let (outp, _) = execCmdEx("nimble path " & p)
var line = ""
for l in outp.splitLines():
if l.len > 0: line = l; break
if line.len == 0: quit("Cannot resolve dependency: " & p)
result.add "--path:" & line
proc stageBot*(tag: string, defines: seq[string] = @[], name = "ChimeraBot"): string =
## Compile ChimeraBot into a throwaway /tmp dir with a json + boot script. The
## optional `name` gives a distinct identity so two staged arms can fight in
## one battle (G7 head-to-head); the default "ChimeraBot" keeps the older
## benches byte-identical.
let root = getTempDir() / ("chimera_stage_" & tag)
let botDir = root / name
removeDir(root)
createDir(botDir)
let bin = botDir / "ChimeraBot"
var cmd = "nim c -d:release --hints:off "
for d in defines: cmd.add d & " "
cmd.add deps().join(" ") & " --out:\"" & bin & "\" " &
quoteShell(GarageSrc / "ChimeraBot.nim")
let (outp, code) = execCmdEx(cmd, options = {poEvalCommand})
if code != 0 or not fileExists(bin):
quit("ChimeraBot (" & tag & ") compile failed:\n" & outp)
# Identity JSON: rename only the `name` field, then launch with it explicitly
# (the binary's compile-time default is the garage ChimeraBot.json).
var js = readFile(GarageSrc / "ChimeraBot.json")
js = js.replace("\"ChimeraBot\"", "\"" & name & "\"")
writeFile(botDir / (name & ".json"), js)
writeFile(botDir / (name & ".sh"),
"#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec \"./ChimeraBot\" \"" &
name & ".json\"\n")
let sh = botDir / (name & ".sh")
setFilePermissions(sh, getFilePermissions(sh) + {fpUserExec, fpGroupExec, fpOthersExec})
botDir
proc extract*(line: string, key: string): tuple[found: bool, value: string] =
let needle = "\"" & key & "\":"
let i = line.find(needle)
if i < 0: return (false, "")
let rest = line[i + needle.len .. ^1]
var j = 0
while j < rest.len and rest[j] in {' ', '\t'}: inc j
if j < rest.len and rest[j] == '"':
let start = j + 1
var k = start
while k < rest.len and rest[k] != '"': inc k
return (true, rest[start ..< k])
var k = j
while k < rest.len and (rest[k].isAlphaNumeric or rest[k] in {'.', '-', 'e', 'E'}):
inc k
return (true, rest[j ..< k])
proc topWeights(line: string): seq[tuple[name: string, w: float64]] =
## Parse the `posteriorTop5` array entries `{"name":"X","w":W}` in order.
let start = line.find("\"posteriorTop5\":")
if start < 0: return
let seg = line[start .. ^1]
var i = 0
while true:
let ni = seg.find("\"name\":\"", i)
if ni < 0: break
let ns = ni + len("\"name\":\"")
var ne = ns
while ne < seg.len and seg[ne] != '"': inc ne
let name = seg[ns ..< ne]
let wi = seg.find("\"w\":", ne)
if wi < 0: break
var j = wi + len("\"w\":")
while j < seg.len and (seg[j] in Digits or seg[j] in {'.', '-', 'e', 'E'}): inc j
var w = 0.0
try: w = parseFloat(seg[wi + len("\"w\":") ..< j])
except ValueError: w = 0.0
result.add (name, w)
i = j
type
RoundStat* = object
idTick*: int ## round-relative tick max posterior first > Threshold
expIdTick*: int ## same for the EXPECTED kernel (diagnostic)
argmaxCorrect*: bool ## at the crossing tick, argmax == expected kernel
identified*: bool
sumTicks*: int
censorRate*: float64
finalPosterior*: float64
finalKernel*: string
ade*, fde*: float64
gapMax*, gapViolations*: int
proc parseFile*(path, expectedKernel: string): RoundStat =
## Unified idTicks parse. Round-relative: the first tick line of the round is
## tick 1, so carry-over can identify at round start.
result.idTick = -1
result.expIdTick = -1
result.argmaxCorrect = false
var t0 = -1
for ln in readFile(path).splitLines():
if ln.len == 0: continue
if ln.startsWith("{\"event\":\"round_summary\""):
result.finalPosterior = extract(ln, "finalPosterior").value.parseFloat()
result.finalKernel = extract(ln, "finalKernel").value
result.sumTicks = extract(ln, "ticks").value.parseInt()
result.censorRate = extract(ln, "censorRate").value.parseFloat()
result.ade = extract(ln, "ade").value.parseFloat()
result.fde = extract(ln, "fde").value.parseFloat()
result.gapMax = extract(ln, "scanGapMax").value.parseInt()
result.gapViolations = extract(ln, "scanGapViolations").value.parseInt()
elif ln.startsWith("{\"tick\""):
let (tf, ts) = extract(ln, "tick")
if not tf: continue
let tick = ts.parseInt()
if t0 < 0: t0 = tick
let rel = tick - t0 + 1
let tw = topWeights(ln)
if tw.len == 0: continue
var maxW = 0.0
var maxName = ""
var expW = 0.0
for (name, w) in tw:
if w > maxW:
maxW = w; maxName = name
if name == expectedKernel and w > expW: expW = w
if result.idTick < 0 and maxW > Threshold:
result.idTick = rel
result.argmaxCorrect = maxName == expectedKernel
if result.expIdTick < 0 and expW > Threshold:
result.expIdTick = rel
result.identified = result.idTick > 0
proc p90*(xs: seq[int]): int =
if xs.len == 0: return -1
var s = xs
s.sort()
s[max(0, int(ceil(0.9 * float(s.len))) - 1)]
proc medianIndex*(xs: seq[int]): int =
if xs.len == 0: return -1
var s = xs
s.sort()
s[s.len div 2]
type
IdStats* = object
median*: int
p90*: int
idFraction*: float64 ## % of rounds identified
n*: int
proc idStats*(ids: seq[int]): IdStats =
## `ids[i]` is the round idTick, or -1 when the round never identified.
if ids.len == 0: return IdStats(median: -1, p90: -1, idFraction: 0.0, n: 0)
var identified: seq[int]
for x in ids:
if x > 0: identified.add x
result.n = ids.len
result.median = medianIndex(identified)
result.p90 = p90(identified)
result.idFraction = 100.0 * float(identified.len) / float(ids.len)
proc fmt*(s: IdStats): string =
## `med p90 id%` columns, `-` for an empty set.
let m = if s.median < 0: "-" else: $s.median
let p = if s.p90 < 0: "-" else: $s.p90
align(m, 6) & align(p, 6) & align(formatFloat(s.idFraction, ffDecimal, 0), 6)
+135
View File
@@ -0,0 +1,135 @@
## G4 live-identification benchmark — unified M5.5 metric.
##
## Runs `Repeat` full `Rounds`-round battles per ground-truth opponent against
## the ChimeraBot observation sidecar (server on a random port, tps=-1), and
## reports the UNIFIED idTicks metric per opponent: median / p90 / id-fraction
## over ALL rounds in the protocol (every round of every run).
##
## Metric (spec §12, M5.5): per round, the round-relative tick at which
## `max_kernel posterior > 0.8`. argmax correctness is a diagnostic only.
## Pass condition: median <= 300 AND id-fraction >= 80% over >= 3 full 8x5 runs.
##
## Findings are reported, never tuned away. Requires Java + JARs + sample bots.
## Run: `nim c -r --hints:off -d:release tests/bench_g4.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm]
import bench_common
import test_framework/server_manager
const
Repeat = 3
Rounds = 5
Telemetry = getTempDir() / "chimera_twin"
Archive = getTempDir() / "chimera_g4_run"
type
Acc = object
ids: seq[int] # per-round unified idTick (-1 = never)
expIds: seq[int]
correct: int # rounds where argmaxCorrect
finalPost, censor, ade, fde: float64
rounds: int
gapMax, gapViol: int
proc run() =
guardSkip()
let botDir = stageBot("g4")
removeDir(Telemetry)
removeDir(Archive)
createDir(Archive)
var acc = initTable[string, Acc]()
for opp in sorted(toSeq(Expected.keys)):
restartServer()
var url = serverUrl()
putEnv("CHIMERA_OPPONENT", opp)
putEnv("CHIMERA_TELEMETRY_DIR", Telemetry)
let sampleBot = SampleRoot / opp
var a: Acc
for run in 1 .. Repeat:
var ok = false
for attempt in 1 .. MaxAttempts:
removeDir(Telemetry)
sleep(500)
if runBattleHard(url, @[botDir, sampleBot], Rounds, 90000):
ok = true
break
echo " ", opp, " run", run, " attempt", attempt, ": battle failed/timeout"
killStaleBots()
restartServer()
url = serverUrl()
if not ok: continue
let runDir = Archive / (opp & "-run" & $run)
copyDir(Telemetry, runDir)
for f in toSeq(walkFiles(runDir / "*.jsonl")):
let rs = parseFile(f, Expected[opp])
if rs.sumTicks == 0: continue
inc a.rounds
a.ids.add(if rs.identified: rs.idTick else: -1)
a.expIds.add(if rs.expIdTick > 0: rs.expIdTick else: -1)
if rs.argmaxCorrect: inc a.correct
a.finalPost += rs.finalPosterior
a.censor += rs.censorRate
a.ade += rs.ade
a.fde += rs.fde
a.gapMax = max(a.gapMax, rs.gapMax)
a.gapViol += rs.gapViolations
if a.rounds > 0: acc[opp] = a
echo "\n=== G4 unified idTicks (M5.5): ", Repeat, " runs x ", Rounds,
" rounds per opponent ==="
echo "Opponent med p90 id% expMed argmaxOk% finalPost% censor% ade5 gapMax/viol"
var lines: seq[string]
lines.add("# G4 unified idTicks (M5.5)\n")
lines.add("Metric: per round, round-relative tick at which `max_kernel posterior > 0.8`; " &
"median / p90 / id-fraction over all rounds. Pass = median <= 300 AND id% >= 80. " &
$Repeat & " runs x " & $Rounds & " rounds. Generated by `tests/bench_g4.nim`.\n")
lines.add("| opponent | median | p90 | id-fraction% | expMedian | argmaxOk% | finalPost% | censor% | ade5 | pass |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|---:|---|")
var passed = 0
var comparable = 0
var pooled: seq[int]
for opp in sorted(toSeq(Expected.keys)):
if opp notin acc: continue
let a = acc[opp]
let s = idStats(a.ids)
let se = idStats(a.expIds)
let n = float(a.rounds)
let correctPct = 100.0 * float(a.correct) / n
let pass = s.median > 0 and s.median <= TargetTicks and s.idFraction >= 80.0
inc comparable
if pass: inc passed
pooled.add a.ids
echo " ", alignLeft(opp, 12), s.fmt,
align($(if se.median < 0: "-" else: $se.median), 7),
align(formatFloat(correctPct, ffDecimal, 0), 10),
align(formatFloat(a.finalPost / n * 100.0, ffDecimal, 0), 11),
align(formatFloat(a.censor / n * 100.0, ffDecimal, 1), 8),
align(formatFloat(a.ade / n, ffDecimal, 2), 6), " ",
$a.gapMax & "/" & $a.gapViol
lines.add "| " & opp & " | " & $(if s.median < 0: -1 else: s.median) & " | " &
$(if s.p90 < 0: -1 else: s.p90) & " | " &
formatFloat(s.idFraction, ffDecimal, 1) & " | " &
$(if se.median < 0: -1 else: se.median) & " | " &
formatFloat(correctPct, ffDecimal, 1) & " | " &
formatFloat(a.finalPost / n * 100.0, ffDecimal, 1) & " | " &
formatFloat(a.censor / n * 100.0, ffDecimal, 2) & " | " &
formatFloat(a.ade / n, ffDecimal, 3) & " | " &
(if pass: "PASS" else: "FAIL") & " |"
let ps = idStats(pooled)
echo "\nPooled (all ", pooled.len, " rounds): median ", ps.median,
" p90 ", ps.p90, " id% ", formatFloat(ps.idFraction, ffDecimal, 1)
echo "G4 pass (median<=300 AND id%>=80): ", passed, "/", comparable,
" over ", Repeat, " full 8x5 runs"
lines.add "\nPooled over " & $pooled.len & " rounds: median " & $ps.median &
", p90 " & $ps.p90 & ", id-fraction " &
formatFloat(ps.idFraction, ffDecimal, 1) & "%. G4 pass: " & $passed & "/" &
$comparable & "."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g4.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "Artifact: ", art
echo "Telemetry archived at: ", Archive
when isMainModule:
run()
+146
View File
@@ -0,0 +1,146 @@
## G5 counterfactual evaluation (CHIMERA M4) — OFFLINE, no Java.
##
## Reads the raw per-tick telemetry the G4 bench left under /tmp, replays the
## ledger + Hedge to recover the causal per-tick posterior, and for every origin
## tick computes:
## (a) the TWIN 5-tick rollout under OUR ACTUAL recorded movement, vs the
## realized enemy positions -> position ADE / FDE;
## (b) the PERSISTENCE baseline (enemy repeats its last observed intent);
## (c) per-record and per-opponent aggregates, reported verbatim;
## (d) fire-channel Brier: twin P(fire within 5 ticks) vs the observed
## energy-drop fire events; persistence baseline = empirical fire rate.
##
## G5 bar (spec §12): twin ADE <= persistence ADE on >= 90% of scenarios.
## Losing scenarios are listed, not hidden (honesty clause).
##
## Run: `nim c -r --hints:off -d:release tests/bench_g5.nim [telemetryDir]`
import std/[os, strutils, tables, math, algorithm, sequtils]
import chimera/dsl
import chimera/twinsim
const Horizon = 5
const DefaultDir = getTempDir() / "chimera_g4_run"
const FlatDir = getTempDir() / "chimera_twin"
type
Agg = object
scenarios: int
twinAde, persAde, twinFde, persFde: float64
twinBrier, persBrier: float64
twinWins: int
confScen: int ## origins with max posterior >= 0.8
confTwinAde, confPersAde: float64
confWins: int
proc pickDir(arg: string): string =
if arg.len > 0 and dirExists(arg): return arg
if dirExists(DefaultDir): return DefaultDir
if dirExists(FlatDir): return FlatDir
""
proc main() =
let arg = if paramCount() >= 1: paramStr(1) else: getEnv("CHIMERA_G5_DIR", "")
let dir = pickDir(arg)
if dir.len == 0:
echo "No telemetry dir found (set CHIMERA_G5_DIR or pass a path)."
quit(0)
let kernels = allKernels()
let files = loadDir(dir).sortedByIt(it.opponent & "-" & $it.round)
if files.len == 0:
echo "No .jsonl records under ", dir
quit(0)
var agg = initTable[string, Agg]()
var totalScen, totalWins = 0
var losers: seq[string]
for rec in files:
let rp = replay(rec, kernels)
if rp.len < Horizon + 1: continue
let rate = rec.fireRate()
let persFire = 1.0 - pow(1.0 - rate, float(Horizon))
var a = agg.getOrDefault(rec.opponent)
for i in 0 ..< rp.len - Horizon:
let origin = rp[i]
var actual: seq[tuple[x, y: float64]]
var realized: seq[tuple[x, y: float64]]
var obsFire = false
for h in 1 .. Horizon:
actual.add (rp[i + h].ox, rp[i + h].oy)
realized.add (rp[i + h].ex, rp[i + h].ey)
# observed fire events live in the raw record, aligned by tick
for h in 1 .. Horizon:
for t in rec.ticks:
if t.tick == rp[i + h].tick and t.fireKnown and t.fireObs > 0.0:
obsFire = true
let twin = rollout(kernels, origin, Horizon, actualOwn = actual)
let pers = persistence(origin, Horizon)
var tAde, pAde = 0.0
for h in 0 ..< Horizon:
tAde += hypot(twin.points[h].x - realized[h].x,
twin.points[h].y - realized[h].y)
pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y)
tAde /= float(Horizon); pAde /= float(Horizon)
let tFde = hypot(twin.points[^1].x - realized[^1].x,
twin.points[^1].y - realized[^1].y)
let pFde = hypot(pers[^1].x - realized[^1].x,
pers[^1].y - realized[^1].y)
inc a.scenarios
a.twinAde += tAde; a.persAde += pAde
a.twinFde += tFde; a.persFde += pFde
a.twinBrier += (twin.fireWithin - (if obsFire: 1.0 else: 0.0)) ^ 2
a.persBrier += (persFire - (if obsFire: 1.0 else: 0.0)) ^ 2
if tAde <= pAde: inc a.twinWins
inc totalScen
if tAde <= pAde: inc totalWins
else: losers.add rec.opponent & "#" & $rec.round & "@" & $origin.tick
# confident regime: the posterior has actually concentrated
var maxW = 0.0
for w in origin.weights: maxW = max(maxW, w)
if maxW >= 0.8:
inc a.confScen
a.confTwinAde += tAde; a.confPersAde += pAde
if tAde <= pAde: inc a.confWins
agg[rec.opponent] = a
echo "G5 twin-vs-persistence (", dir, "), horizon=", Horizon,
", scenarios=", totalScen
echo "\nOpponent scen twinADE persADE margin twinFDE persFDE twinBr persBr twinWin%"
var names = toSeq(agg.keys); names.sort()
for name in names:
let a = agg[name]
if a.scenarios == 0: continue
let n = float(a.scenarios)
echo " ", alignLeft(name, 12), align($a.scenarios, 5),
" ", align(formatFloat(a.twinAde / n, ffDecimal, 3), 7),
" ", align(formatFloat(a.persAde / n, ffDecimal, 3), 7),
" ", align(formatFloat((a.persAde - a.twinAde) / n, ffDecimal, 3), 7),
" ", align(formatFloat(a.twinFde / n, ffDecimal, 3), 8),
" ", align(formatFloat(a.persFde / n, ffDecimal, 3), 7),
" ", align(formatFloat(a.twinBrier / n, ffDecimal, 4), 7),
" ", align(formatFloat(a.persBrier / n, ffDecimal, 4), 7),
" ", align(formatFloat(100.0 * float(a.twinWins) / n, ffDecimal, 1), 8)
echo "\nConfidence-conditioned (max posterior >= 0.8):"
echo "Opponent confScen twinADE persADE margin twinWin%"
for name in names:
let a = agg[name]
if a.confScen == 0: continue
let n = float(a.confScen)
echo " ", alignLeft(name, 12), align($a.confScen, 6),
" ", align(formatFloat(a.confTwinAde / n, ffDecimal, 3), 7),
" ", align(formatFloat(a.confPersAde / n, ffDecimal, 3), 7),
" ", align(formatFloat((a.confPersAde - a.confTwinAde) / n, ffDecimal, 3), 7),
" ", align(formatFloat(100.0 * float(a.confWins) / n, ffDecimal, 1), 8)
echo "\nG5 bar: twin ADE <= persistence ADE on ", totalWins, "/", totalScen,
" = ", formatFloat(100.0 * float(totalWins) / float(max(1, totalScen)),
ffDecimal, 1), "%"
echo "G5 (>= 90%): ", (if totalWins * 10 >= totalScen * 9: "PASS" else: "FAIL")
if losers.len > 0:
echo "Losing scenarios (", losers.len, "):"
for i in 0 ..< min(20, losers.len): echo " ", losers[i]
if losers.len > 20: echo " ... ", losers.len - 20, " more"
when isMainModule:
main()
+238
View File
@@ -0,0 +1,238 @@
## G5' v2 interventional counterfactual eval (CHIMERA M5.5) — OFFLINE, no Java.
##
## Source: docs/chimera-spec.md §12 G5' (v2 protocol). Reads the probe-ON
## telemetry archived by bench_g6.nim, replays the ledger + Hedge, and for every
## executed probe measures the 5-tick enemy-reaction prediction (twin mixture vs
## persistence baseline) under OUR ACTUAL recorded movement, plus
## reaction-direction agreement.
##
## Reported v2: (a) the MOVING subset {Crazy, SpinBot, VelociBot, Walls} — where
## persistence is NOT optimal by construction — and (b) the full suite. Bar:
## twin >= persistence on >= 70% of MOVING-subset windows. The STATIC subset
## {RamFire, Corners, TrackFire, Fire} gets a saturation analysis (why twin ~
## persistence by construction), one line per opponent.
##
## Run: `nim c -r --hints:off -d:release tests/bench_g5p.nim [telemetryDir]`
import std/[os, strutils, tables, math, algorithm, sequtils]
import bench_common
import chimera/dsl
import chimera/physics
import chimera/twinsim
const Horizon = 5
const DefaultDir = getTempDir() / "chimera_g6_on"
const DirAgreeDeg = 45.0
type
Agg = object
windows: int
twinAde, persAde: float64
twinWins: int
dirTwinAgree, dirPersAgree, dirN: int
allWindows: int
allTwinAde, allPersAde: float64
allTwinWins: int
speedSum: float64
speedN: int
slowN: int # scanned ticks with |enemy speed| < 0.5
type
Sub = object
windows, twinWins: int
twinAde, persAde: float64
dirTwin, dirPers, dirN: int
proc probeTicks(path: string): seq[int] =
## Only EXECUTED probes (`gate:"ok"`) count as interventional windows: a
## gate-blocked trigger issued no probe, so the following ticks are
## observation-only (the M4 persistence-bias trap).
for ln in lines(path):
if ln.find("\"event\":\"probe\"") < 0: continue
if ln.find("\"gate\":\"ok\"") < 0: continue
let needle = "\"tick\":"
let i = ln.find(needle)
if i < 0: continue
var j = i + needle.len
while j < ln.len and ln[j] in {' ', '\t'}: inc j
let s = j
while j < ln.len and ln[j] in Digits: inc j
if j > s: result.add parseInt(ln[s ..< j])
proc netDir(sx, sy, ex, ey: float64): float64 =
arctan2(ey - sy, ex - sx) * 180.0 / PI
proc dirAgree(sx, sy, obsX, obsY, predX, predY: float64): bool =
let obsMag = hypot(obsX - sx, obsY - sy)
let predMag = hypot(predX - sx, predY - sy)
if obsMag <= 1.0: return predMag <= 5.0
abs(wrap180(netDir(sx, sy, predX, predY) - netDir(sx, sy, obsX, obsY))) <= DirAgreeDeg
proc record(path: string, kernels: seq[Kernel], agg: var Table[string, Agg]) =
let rec = loadRecord(path)
let probes = probeTicks(path)
if rec.ticks.len < Horizon + 1: return
let rp = replay(rec, kernels)
if rp.len < Horizon + 1: return
var a = agg.getOrDefault(rec.opponent)
# observational floor + static-saturation statistics over the same record
for i in 0 ..< rp.len - Horizon:
let origin = rp[i]
var actual: seq[tuple[x, y: float64]]
var realized: seq[tuple[x, y: float64]]
for h in 1 .. Horizon:
actual.add (rp[i + h].ox, rp[i + h].oy)
realized.add (rp[i + h].ex, rp[i + h].ey)
let twin = rollout(kernels, origin, Horizon, actualOwn = actual)
let pers = persistence(origin, Horizon)
var tAde, pAde = 0.0
for h in 0 ..< Horizon:
tAde += hypot(twin.points[h].x - realized[h].x,
twin.points[h].y - realized[h].y)
pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y)
inc a.allWindows
a.allTwinAde += tAde / float(Horizon)
a.allPersAde += pAde / float(Horizon)
if tAde <= pAde: inc a.allTwinWins
let sp = abs(origin.espeed)
a.speedSum += sp
inc a.speedN
if sp < 0.5: inc a.slowN
# interventional windows: probe ticks only
var byTick = initTable[int, int]()
for i, r in rp: byTick[r.tick] = i
for p in probes:
if not byTick.hasKey(p): continue
let i = byTick[p]
if i + Horizon >= rp.len: continue
let origin = rp[i]
var actual: seq[tuple[x, y: float64]]
var realized: seq[tuple[x, y: float64]]
for h in 1 .. Horizon:
actual.add (rp[i + h].ox, rp[i + h].oy)
realized.add (rp[i + h].ex, rp[i + h].ey)
let twin = rollout(kernels, origin, Horizon, actualOwn = actual)
let pers = persistence(origin, Horizon)
var tAde, pAde = 0.0
for h in 0 ..< Horizon:
tAde += hypot(twin.points[h].x - realized[h].x,
twin.points[h].y - realized[h].y)
pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y)
tAde /= float(Horizon); pAde /= float(Horizon)
inc a.windows
a.twinAde += tAde; a.persAde += pAde
if tAde <= pAde: inc a.twinWins
inc a.dirN
if dirAgree(origin.ex, origin.ey, realized[^1].x, realized[^1].y,
twin.points[^1].x, twin.points[^1].y): inc a.dirTwinAgree
if dirAgree(origin.ex, origin.ey, realized[^1].x, realized[^1].y,
pers[^1].x, pers[^1].y): inc a.dirPersAgree
agg[rec.opponent] = a
proc sub(agg: Table[string, Agg], names: seq[string]): Sub =
for name in names:
if name notin agg: continue
let a = agg[name]
result.windows += a.windows
result.twinWins += a.twinWins
result.twinAde += a.twinAde
result.persAde += a.persAde
result.dirTwin += a.dirTwinAgree
result.dirPers += a.dirPersAgree
result.dirN += a.dirN
proc main() =
let arg = if paramCount() >= 1: paramStr(1) else: getEnv("CHIMERA_G5P_DIR", "")
let dir = if arg.len > 0 and dirExists(arg): arg else: DefaultDir
if not dirExists(dir):
echo "No probe-ON telemetry at ", dir, " (run bench_g6.nim first)."
quit(0)
let kernels = allKernels()
var agg = initTable[string, Agg]()
var files: seq[string]
for f in walkDirRec(dir):
if f.endsWith(".jsonl"): files.add f
files.sort()
for f in files: record(f, kernels, agg)
var names = toSeq(agg.keys); names.sort()
var lines: seq[string]
lines.add("# G5' v2 interventional eval (M5.5)\n")
lines.add("Horizon 5, probe-following windows only. MOVING = " & MovingOpponents.join(", ") &
"; STATIC = " & StaticOpponents.join(", ") & ". Source: " & dir & ".\n")
echo "G5' v2 interventional (probe-following), horizon=", Horizon, ", dir=", dir
echo "\nOpponent probes twinADE persADE margin twinWin% dirTwin% dirPers%"
# per-opponent detail
lines.add("| opponent | probes | twinADE | persADE | margin | twinWin% | dirTwin% | dirPers% |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|")
for name in names:
let a = agg[name]
if a.windows == 0: continue
let n = float(a.windows)
let win = 100.0 * float(a.twinWins) / n
echo " ", alignLeft(name, 12), align($a.windows, 6),
" ", align(formatFloat(a.twinAde / n, ffDecimal, 3), 7),
" ", align(formatFloat(a.persAde / n, ffDecimal, 3), 7),
" ", align(formatFloat((a.persAde - a.twinAde) / n, ffDecimal, 3), 7),
" ", align(formatFloat(win, ffDecimal, 1), 8),
" ", align(formatFloat(100.0 * float(a.dirTwinAgree) / float(max(1, a.dirN)), ffDecimal, 1), 8),
" ", align(formatFloat(100.0 * float(a.dirPersAgree) / float(max(1, a.dirN)), ffDecimal, 1), 8)
lines.add "| " & name & " | " & $a.windows & " | " &
formatFloat(a.twinAde / n, ffDecimal, 3) & " | " &
formatFloat(a.persAde / n, ffDecimal, 3) & " | " &
formatFloat((a.persAde - a.twinAde) / n, ffDecimal, 3) & " | " &
formatFloat(win, ffDecimal, 1) & " | " &
formatFloat(100.0 * float(a.dirTwinAgree) / float(max(1, a.dirN)), ffDecimal, 1) & " | " &
formatFloat(100.0 * float(a.dirPersAgree) / float(max(1, a.dirN)), ffDecimal, 1) & " |"
let mov = sub(agg, MovingOpponents)
let full = sub(agg, toSeq(agg.keys))
let movWin = 100.0 * float(mov.twinWins) / float(max(1, mov.windows))
let fullWin = 100.0 * float(full.twinWins) / float(max(1, full.windows))
echo "\nMOVING subset: ", mov.windows, " windows, twinADE ",
formatFloat(mov.twinAde / float(max(1, mov.windows)), ffDecimal, 3),
" persADE ", formatFloat(mov.persAde / float(max(1, mov.windows)), ffDecimal, 3),
", twinWin ", formatFloat(movWin, ffDecimal, 1), "%",
" (bar >=70%: ", (if movWin >= 70.0: "PASS" else: "FAIL"), ")"
echo "FULL suite: ", full.windows, " windows, twinWin ",
formatFloat(fullWin, ffDecimal, 1), "%"
echo "MOVING dir agreement: twin ",
formatFloat(100.0 * float(mov.dirTwin) / float(max(1, mov.dirN)), ffDecimal, 1),
"%, persistence ",
formatFloat(100.0 * float(mov.dirPers) / float(max(1, mov.dirN)), ffDecimal, 1), "%"
lines.add "\n**MOVING subset**: " & $mov.windows & " windows, twinWin " &
formatFloat(movWin, ffDecimal, 1) & "% (bar >=70%: " &
(if movWin >= 70.0: "PASS" else: "FAIL") & "). **FULL suite**: " &
$full.windows & " windows, twinWin " & formatFloat(fullWin, ffDecimal, 1) & "%."
echo "\nSTATIC-subset saturation analysis (why twin ~ persistence by construction):"
lines.add("\n## STATIC-subset saturation\n")
for name in StaticOpponents:
if name notin agg: continue
let a = agg[name]
if a.windows == 0: continue
let n = float(a.windows)
let slowPct = 100.0 * float(a.slowN) / float(max(1, a.speedN))
let meanSp = a.speedSum / float(max(1, a.speedN))
let margin = (a.persAde - a.twinAde) / n
echo " ", name, ": mean |enemy speed| ", formatFloat(meanSp, ffDecimal, 2),
" u/tick, ", $int(slowPct + 0.5),
"% of scanned ticks < 0.5 u/tick -> the realized path is near-stationary",
" (persistence is exactly optimal at v=0), so the constant-velocity carry",
" and the twin's stationary/corner kernels coincide and the twin can only",
" match or lose; margin ", formatFloat(margin, ffDecimal, 3), "."
lines.add "- **" & name & "**: mean |enemy speed| " &
formatFloat(meanSp, ffDecimal, 2) & " u/tick, " & $int(slowPct + 0.5) &
"% of scanned ticks < 0.5 u/tick. Near-stationary realized path, so persistence " &
"(v~0) is exactly optimal and the twin's stationary/corner kernels coincide with " &
"it — the twin can only match or lose, never win (margin " &
formatFloat(margin, ffDecimal, 3) & ")."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g5p.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art
when isMainModule:
main()
+153
View File
@@ -0,0 +1,153 @@
## G6 ablation ladder — probes x carry-over (CHIMERA M5.5). LIVE, Java required.
##
## Four arms over the same 8x5 pinned-opponent protocol, using the UNIFIED
## idTicks metric (round-relative, max posterior > 0.8; median/p90/id-fraction
## over all rounds):
## * on — probes ON, cross-round carry-over ON (default build)
## * off — probes OFF, carry-over ON (-d:chimeraNoProbes)
## * reset — probes ON, fresh-round reset ON (-d:chimeraFreshRound)
## * offreset — probes OFF, fresh-round reset ON (both defines)
##
## Primary G6 read: probes must cut the MOVING-subset median identification
## ticks by >= 20% (`on` vs `off`), reported for the full suite too. The
## carry-over effect is `on` vs `reset`.
##
## ON telemetry archived to /tmp/chimera_g6_on (input to bench_g5p.nim).
## Run: `nim c -r --hints:off -d:release tests/bench_g6.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times]
import bench_common
import test_framework/server_manager
const
Rounds = 5
Repeat = 3
Telemetry = getTempDir() / "chimera_twin"
ArmTags = ["on", "off", "reset", "offreset"]
proc armDefines(tag: string): seq[string] =
case tag
of "on": @[]
of "off": @["-d:chimeraNoProbes"]
of "reset": @["-d:chimeraFreshRound"]
else: @["-d:chimeraNoProbes", "-d:chimeraFreshRound"]
proc runArm(tag: string): Table[string, seq[int]] =
let botDir = stageBot("g6_" & tag, armDefines(tag))
removeDir(Telemetry)
let armDir = getTempDir() / ("chimera_g6_" & tag)
removeDir(armDir)
createDir(armDir)
for opp in sorted(toSeq(Expected.keys)):
restartServer()
var url = serverUrl()
putEnv("CHIMERA_OPPONENT", opp)
putEnv("CHIMERA_TELEMETRY_DIR", Telemetry)
let sampleBot = SampleRoot / opp
var ids: seq[int]
for run in 1 .. Repeat:
var ok = false
let t0 = epochTime()
for attempt in 1 .. MaxAttempts:
removeDir(Telemetry)
sleep(500)
if runBattleHard(url, @[botDir, sampleBot], Rounds, 90000):
ok = true
break
echo " ", tag, " ", opp, " run", run, " attempt", attempt,
": battle failed/timeout"
killStaleBots()
restartServer()
url = serverUrl()
echo " [", tag, "] ", opp, " run", run, " ok=", ok, " in ",
formatFloat(epochTime() - t0, ffDecimal, 1), "s (attempts used)"
if not ok: continue
let runDir = armDir / (opp & "-run" & $run)
copyDir(Telemetry, runDir)
for f in toSeq(walkFiles(runDir / "*.jsonl")):
let rs = parseFile(f, Expected[opp])
if rs.sumTicks == 0: continue
ids.add(if rs.identified: rs.idTick else: -1)
result[opp] = ids
proc pooled(arm: Table[string, seq[int]], opps: seq[string]): seq[int] =
for opp in opps:
if opp in arm: result.add arm[opp]
proc cutPct(onMed, offMed: int): float64 =
if offMed <= 0: 0.0 else: 100.0 * float(offMed - onMed) / float(offMed)
proc main() =
guardSkip()
echo "[G6] 4 arms x ", Repeat, " runs x ", Rounds, " rounds"
var tabs = initTable[string, Table[string, seq[int]]]()
for tag in ArmTags:
tabs[tag] = runArm(tag)
echo "\n=== G6 arms: unified idTicks median / id-fraction% (", Repeat,
" runs x ", Rounds, " rounds) ==="
echo "Opponent on med id% off med id% reset med id% offreset med id%"
var lines: seq[string]
lines.add("# G6 ablation ladder (M5.5): probes x carry-over\n")
lines.add("Unified idTicks (round-relative, max posterior > 0.8), median over " &
$Repeat & " runs x " & $Rounds & " rounds; id% = fraction of rounds identified. " &
"Arms: on = probes+carry, off = -probes, reset = -carry, offreset = both. " &
"Generated by `tests/bench_g6.nim`.\n")
lines.add("| opponent | on med | on id% | off med | off id% | reset med | reset id% | offreset med | offreset id% |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|---:|")
for opp in sorted(toSeq(Expected.keys)):
var cells: seq[string]
var textLine = " " & alignLeft(opp, 12)
var row = "| " & opp & " |"
for tag in ArmTags:
if opp in tabs[tag]:
let s = idStats(tabs[tag][opp])
let m = if s.median < 0: "-" else: $s.median
textLine.add align(m, 8) & align(formatFloat(s.idFraction, ffDecimal, 0), 5)
row.add " " & m & " | " & formatFloat(s.idFraction, ffDecimal, 1) & " |"
else:
textLine.add align("-", 8) & align("-", 5)
row.add " - | - |"
echo textLine
lines.add row
let full = @["Crazy", "SpinBot", "RamFire", "Corners", "Walls",
"TrackFire", "Fire", "VelociBot"]
echo ""
echo "Metric on off reset offreset"
for (label, opps) in [("MOVING-subset", MovingOpponents), ("FULL-suite", full)]:
var st: Table[string, IdStats]
for tag in ArmTags:
st[tag] = idStats(pooled(tabs[tag], opps))
echo alignLeft(label, 18),
align($st["on"].median, 7), align($st["off"].median, 8),
align($st["reset"].median, 8), align($st["offreset"].median, 10),
" (id%: ", formatFloat(st["on"].idFraction, ffDecimal, 0), "/",
formatFloat(st["off"].idFraction, ffDecimal, 0), "/",
formatFloat(st["reset"].idFraction, ffDecimal, 0), "/",
formatFloat(st["offreset"].idFraction, ffDecimal, 0), ")"
let cut = cutPct(st["on"].median, st["off"].median)
let carryGain = if st["reset"].median > 0:
100.0 * float(st["reset"].median - st["on"].median) / float(st["reset"].median)
else: 0.0
echo " probes cut (off->on) = ", formatFloat(cut, ffDecimal, 1),
"% carry-over gain (reset->on) = ", formatFloat(carryGain, ffDecimal, 1), "%"
lines.add "\n**" & label & "** pooled: on " & $st["on"].median & " (id " &
formatFloat(st["on"].idFraction, ffDecimal, 1) & "%), off " &
$st["off"].median & " (id " & formatFloat(st["off"].idFraction, ffDecimal, 1) &
"%), reset " & $st["reset"].median & " (id " &
formatFloat(st["reset"].idFraction, ffDecimal, 1) & "%), offreset " &
$st["offreset"].median & " (id " &
formatFloat(st["offreset"].idFraction, ffDecimal, 1) & "%). Probes cut = " &
formatFloat(cut, ffDecimal, 1) & "%, carry-over gain = " &
formatFloat(carryGain, ffDecimal, 1) & "%. **G6 bar (>=20% cut, " & label & "): " &
(if cut >= 20.0: "PASS" else: "FAIL") & "**."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g6.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "Artifact: ", art
echo "ON telemetry archived at ", getTempDir() / "chimera_g6_on"
when isMainModule:
main()
+203
View File
@@ -0,0 +1,203 @@
## G7 head-to-head + no-regression floor (CHIMERA M6). LIVE, Java required.
##
## Three binaries built from the SAME tree:
## * inert — `-d:chimeraInert` == the M1 exact copy (all CHIMERA off)
## * full — default (probes + fusion + influence)
## * noprobe — `-d:chimeraNoProbes` (fusion + influence, no probes)
##
## Head-to-head: full vs inert mirror 1v1, `H2HN` matches x `H2HRounds`.
## Bar: head-to-head win-rate >= 50% (exact, reported).
##
## Suite no-regression floor: each arm vs the 8 primary sample bots,
## `Rounds` rounds each. Bar: full >= inert on EVERY opponent (win rate), with
## survival and score margin reported; the full-minus-probes arm isolates the
## probe cost.
##
## A full < inert anywhere is reported plainly as a falsification, never hidden.
## Run: `nim c -r --hints:off -d:release tests/bench_g7.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times]
import bench_common
const
Rounds = 5
H2HN = 10 # head-to-head mirror matches
H2HRounds = 5 # rounds per head-to-head match
type
Outcome = object
rounds, wins: int
ourScore, oppScore: float64
ourSurv, oppSurv: int
Arm = object
tag, name: string
defines: seq[string]
const Arms = [
Arm(tag: "inert", name: "ChimeraInert", defines: @["-d:chimeraInert"]),
Arm(tag: "full", name: "ChimeraFull", defines: @[]),
Arm(tag: "noprobe", name: "ChimeraNoProbe", defines: @["-d:chimeraNoProbes"]),
]
proc parseOutcome(log, ourName: string): Outcome =
## Aggregate a battle's JSONL runner output. A failed battle (no round_ended)
## yields rounds == 0.
for ln in log.splitLines():
if ln.len == 0 or ln.find("\"event\":\"round_ended\"") < 0: continue
inc result.rounds
let ri = ln.find("\"results\":[")
if ri < 0: continue
let oi = ln.find('[', ri)
let ci = ln.find(']', ri)
if oi < 0 or ci < 0 or ci <= oi: continue
let seg = ln[oi + 1 ..< ci]
var j = 0
var ourScoreV = -1.0
var theirScoreV = -1.0
var ourSurvF, theirSurvF = false
while j < seg.len:
let s = seg.find('{', j)
if s < 0: break
let e = seg.find('}', s)
if e < 0: break
let obj = seg[s + 1 ..< e]
let (found, name) = extract(obj, "name")
let (sf, score) = extract(obj, "score")
let (vf, surv) = extract(obj, "survived")
if found and sf and vf:
if name == ourName:
ourScoreV = score.parseFloat()
ourSurvF = surv == "true"
else:
theirScoreV = score.parseFloat()
theirSurvF = surv == "true"
j = e + 1
if ourScoreV >= 0.0 and theirScoreV >= 0.0:
result.ourScore += ourScoreV
result.oppScore += theirScoreV
if ourScoreV > theirScoreV: inc result.wins
if ourSurvF: inc result.ourSurv
if theirSurvF: inc result.oppSurv
proc runBattle(url: string, botDirs: seq[string], rounds: int,
ourName, tag: string): Outcome =
## Launch one battle, route telemetry to a throwaway dir, parse and return.
putEnv("CHIMERA_TELEMETRY_DIR", getTempDir() / ("chimera_g7_tel_" & tag))
let (ok, logPath) = runBattleHardLog(url, botDirs, rounds,
logName = "chimera_g7_" & tag)
if not ok: return Outcome()
parseOutcome(readFile(logPath), ourName)
proc winRate(o: Outcome): float64 =
if o.rounds == 0: 0.0 else: 100.0 * float(o.wins) / float(o.rounds)
proc margin(o: Outcome): float64 = o.ourScore - o.oppScore
proc main() =
guardSkip()
echo "[G7] staging 3 arms: " & Arms.mapIt(it.tag &
"=" & (if it.defines.len == 0: "(default)" else: it.defines.join(","))).join(" ")
var bots = initTable[string, string]()
for a in Arms:
bots[a.tag] = stageBot("g7_" & a.tag, a.defines, a.name)
var lines: seq[string]
lines.add("# G7 head-to-head + no-regression floor (M6)\n")
lines.add("Three arms from the SAME tree: **inert** (`-d:chimeraInert`, == M1 " &
"exact copy), **full** (default: probes + fusion + influence), " &
"**noprobe** (`-d:chimeraNoProbes`: fusion + influence). Head-to-head: " &
"full vs inert mirror 1v1, " & $H2HN & " matches x " & $H2HRounds &
" rounds. Suite: " & $Rounds & " rounds per arm per opponent vs the 8 " &
"primary sample bots. Generated by `tests/bench_g7.nim`.\n")
# ── head-to-head ──────────────────────────────────────────────────────────
restartServer()
var url = serverUrl()
var h2h: Outcome
echo "\n[G7] head-to-head full vs inert, ", H2HN, " matches x ", H2HRounds, " rounds"
for m in 1 .. H2HN:
var o: Outcome
for attempt in 1 .. MaxAttempts:
removeDir(getTempDir() / "chimera_g7_h2h_tel"); sleep(300)
o = runBattle(url, @[bots["full"], bots["inert"]], H2HRounds,
"ChimeraFull", "h2h")
if o.rounds > 0: break
echo " h2h match ", m, " attempt ", attempt, ": retry"
killStaleBots(); restartServer(); url = serverUrl()
h2h.wins += o.wins; h2h.rounds += o.rounds
h2h.ourScore += o.ourScore; h2h.oppScore += o.oppScore
h2h.ourSurv += o.ourSurv; h2h.oppSurv += o.oppSurv
echo " match ", m, " -> ", o.rounds, " rounds, full wins ", o.wins
let h2hWin = winRate(h2h)
echo "\n[G7] head-to-head: full win ", formatFloat(h2hWin, ffDecimal, 1),
"% over ", h2h.rounds, " rounds, margin ", formatFloat(margin(h2h), ffDecimal, 1),
", survival full ", h2h.ourSurv, " vs inert ", h2h.oppSurv
echo " G7 head-to-head bar (>=50%): ", (if h2hWin >= 50.0: "PASS" else: "FAIL")
lines.add "## Head-to-head: full vs inert\n"
lines.add "| metric | value |"
lines.add "|---|---:|"
lines.add "| matches | " & $H2HN & " x " & $H2HRounds & " rounds |"
lines.add "| full win-rate | " & formatFloat(h2hWin, ffDecimal, 1) & "% |"
lines.add "| full survival | " & $h2h.ourSurv & " / inert " & $h2h.oppSurv & " |"
lines.add "| score margin (full-inert) | " & formatFloat(margin(h2h), ffDecimal, 1) & " |"
lines.add "| **bar (>=50%)** | " & (if h2hWin >= 50.0: "**PASS**" else: "**FAIL**") & " |"
# ── suite no-regression ───────────────────────────────────────────────────
let opps = sorted(toSeq(Expected.keys))
var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out
for arm in Arms:
var t = initTable[string, Outcome]()
for opp in opps:
restartServer()
putEnv("CHIMERA_OPPONENT", opp)
let o = runBattle(serverUrl(), @[bots[arm.tag], SampleRoot / opp], Rounds,
arm.name, arm.tag & "_" & opp)
t[opp] = o
echo " [", arm.tag, "] vs ", alignLeft(opp, 10), " rounds=", o.rounds,
" winRate=", formatFloat(winRate(o), ffDecimal, 0), "%",
" margin=", formatFloat(margin(o), ffDecimal, 1)
suite[arm.tag] = t
echo "\n=== G7 suite no-regression (", Rounds, " rounds/arm/opponent) ==="
echo "Opponent fullW% fullM fullS inertW% inertM inertS noprW% noprM"
lines.add "\n## Suite no-regression floor (" & $Rounds & " rounds per arm)\n"
lines.add "| opponent | full W% | full margin | full surv | inert W% | inert margin | inert surv | noProbe W% | noProbe margin |"
lines.add "|---|---:|---:|---:|---:|---:|---:|---:|---:|"
var allOk = true
var failedOpps: seq[string]
for opp in opps:
let f = suite["full"].getOrDefault(opp)
let i = suite["inert"].getOrDefault(opp)
let n = suite["noprobe"].getOrDefault(opp)
let okRow = (f.rounds > 0 and i.rounds > 0) and (f.wins >= i.wins)
if not okRow: allOk = false; failedOpps.add opp
echo " ", alignLeft(opp, 10),
align(formatFloat(winRate(f), ffDecimal, 0), 7),
align(formatFloat(margin(f), ffDecimal, 1), 6),
align($f.ourSurv, 6),
align(formatFloat(winRate(i), ffDecimal, 0), 8),
align(formatFloat(margin(i), ffDecimal, 1), 6),
align($i.ourSurv, 6),
align(formatFloat(winRate(n), ffDecimal, 0), 7),
" ", formatFloat(margin(n), ffDecimal, 1)
lines.add "| " & opp & " | " & formatFloat(winRate(f), ffDecimal, 1) & " | " &
formatFloat(margin(f), ffDecimal, 1) & " | " & $f.ourSurv & " | " &
formatFloat(winRate(i), ffDecimal, 1) & " | " &
formatFloat(margin(i), ffDecimal, 1) & " | " & $i.ourSurv & " | " &
formatFloat(winRate(n), ffDecimal, 1) & " | " &
formatFloat(margin(n), ffDecimal, 1) & " |"
lines.add "\n**No-regression (full >= inert on every opponent): " &
(if allOk: "PASS" else: "**FAIL** on " & failedOpps.join(", ")) & "**. "
lines.add "Head-to-head win rate " & formatFloat(h2hWin, ffDecimal, 1) &
"% (bar >=50%: " & (if h2hWin >= 50.0: "PASS" else: "FAIL") & ")."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m6_g7.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art
when isMainModule:
main()
+2
View File
@@ -0,0 +1,2 @@
--path:"../src/ChimeraBot"
--path:"../../common_libs"
+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 @@
## Tier A unit tests for CHIMERA predictor fusion (chimera/fusion.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/[math, sequtils]
import chimera/dsl
import chimera/hedge
import chimera/twinsim
import chimera/residual
import chimera/fusion
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc sum(f: Fusion): float64 =
for w in f.weights(): result += w
let kernels = allKernels()
proc demoOrigin(): ReplayTick =
let h = initHedge(kernelNames(kernels))
result = ReplayTick(tick: 10, ex: 200.0, ey: 300.0, edir: 0.0, espeed: 4.0,
eenergy: 100.0, ox: 600.0, oy: 300.0, odir: 180.0,
ospeed: 3.0, lastTurn: 0.0, lastSpeed: 4.0)
result.weights = h.weights
for k in kernels: result.mems.add defaultMemory(k.defaultParams)
block:
echo "test 1: weights normalize"
var f = initFusion()
check("uniform start sums to 1", abs(sum(f) - 1.0) < 1e-12)
for i in 0 ..< 20:
f.update(PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
[PredIntent(turn: 9.0, speed: -8.0, fire: 1.0),
PredIntent(turn: 5.0, speed: 0.0, fire: 0.5),
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0)])
check("stays normalized after updates", abs(sum(f) - 1.0) < 1e-12)
block:
echo "test 2: persistence sanity (the consistently-right predictor wins)"
var f = initFusion()
for i in 0 ..< 300:
f.update(PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
[PredIntent(turn: 9.0, speed: -8.0, fire: 1.0), # mixture: bad
PredIntent(turn: 5.0, speed: 0.0, fire: 0.5), # residual: bad
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0)]) # persistence: good
check("persistence weight dominates", f.weights()[PersistenceIdx] > 0.9,
$f.weights())
check("confidence is in range", f.confidence() >= 0.0 and f.confidence() <= 1.0,
$f.confidence())
block:
echo "test 3: fused rollout shape + fire/confidence smoke"
let origin = demoOrigin()
var f = initFusion()
for i in 0 ..< 50:
f.update(PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
[PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0)])
var head = initResidualHead()
let rp = head.predict(features(ResidualInput(lastSpeed: 4.0, scanAge: 1.0,
dist: 400.0)))
let fp = f.fusedPrediction(kernels, origin, rp, 5)
check("horizon points = 5", fp.points.len == 5 and fp.pFire.len == 5,
$fp.points.len)
check("fireWithin in [0,1]", fp.fireWithin >= 0.0 and fp.fireWithin <= 1.0,
$fp.fireWithin)
check("confidence in [0,1]", fp.confidence >= 0.0 and fp.confidence <= 1.0)
check("all points finite",
fp.points.allIt(it.x == it.x and abs(it.x) < 1e9 and
it.y == it.y and abs(it.y) < 1e9))
block:
echo "test 4: determinism (same state => same fused prediction)"
let origin = demoOrigin()
var f1 = initFusion()
var f2 = initFusion()
for i in 0 ..< 30:
let r = PredIntent(turn: 1.0, speed: 2.0, fire: 0.0)
f1.update(r, [r, r, r])
f2.update(r, [r, r, r])
let a = f1.fusedPrediction(kernels, origin, ResidualPrediction(), 5)
let b = f2.fusedPrediction(kernels, origin, ResidualPrediction(), 5)
var same = a.points.len == b.points.len
for i in 0 ..< a.points.len:
if a.points[i].x != b.points[i].x or a.points[i].y != b.points[i].y:
same = false
check("bit-identical fused trajectories", same)
echo ""
if failed == 0: echo "all fusion tests passed"
else: echo failed, " fusion test(s) FAILED"; quit(1)
+92
View File
@@ -0,0 +1,92 @@
## Tier A unit tests for the CHIMERA Hedge posterior (chimera/hedge.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/hedge
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc sum(h: Hedge): float64 =
for w in h.weights: result += w
block:
echo "test 1: uniform prior and normalization"
var h = initHedge(@["a", "b", "c", "d"])
check("sums to 1", abs(sum(h) - 1.0) < 1e-12, $sum(h))
check("entropy = ln N", abs(h.entropy() - ln(4.0)) < 1e-12, $h.entropy())
h.update(@[0.0, 1.0, 0.5, 2.0])
check("stays normalized after update", abs(sum(h) - 1.0) < 1e-12, $sum(h))
block:
echo "test 2: eta effect sign (sharper with larger eta)"
var slow = initHedge(@["good", "bad"])
var fast = initHedge(@["good", "bad"])
slow.cfg.eta = 0.5
fast.cfg.eta = 4.0
for i in 0 ..< 10:
slow.update(@[0.0, 1.0])
fast.update(@[0.0, 1.0])
check("both favour the good kernel", slow.posterior("good") > 0.5 and
fast.posterior("good") > 0.5)
check("larger eta is sharper",
fast.posterior("good") > slow.posterior("good"),
$fast.posterior("good") & " vs " & $slow.posterior("good"))
block:
echo "test 3: forgetting revives a switched kernel"
var h = initHedge(@["A", "B"])
for i in 0 ..< 200:
h.update(@[0.0, 1.0]) # A is right for a long time
let aHigh = h.posterior("A")
check("A dominates before the switch", aHigh > 0.9, $aHigh)
for i in 0 ..< 200:
h.update(@[1.0, 0.0]) # policy switches to B
check("B recovers after the switch", h.posterior("B") > 0.9,
$h.posterior("B"))
block:
echo "test 4: Fixed-Share mass floor w_i >= alpha*m_i"
var h = initHedge(@["a", "b", "c", "d"])
h.cfg.alpha = 0.05
for i in 0 ..< 500:
h.update(@[0.0, 100.0, 100.0, 100.0]) # crush b, c, d
let m = 1.0 / 4.0
var floored = true
for i in 0 ..< h.weights.len:
if h.weights[i] < h.cfg.alpha * m - 1e-12: floored = false
check("every weight respects the floor", floored, $h.weights)
# The floor a*m is exact pre-normalization; after renormalizing (Z <= 1) a
# crushed loser sits at or just above it.
check("loser mass sits at the floor",
h.posterior("b") >= 0.05 * m - 1e-12 and h.posterior("b") < 0.05 * m * 1.1,
$h.posterior("b"))
block:
echo "test 5: entropy and top-k sanity"
var h = initHedge(@["a", "b", "c"])
let top = h.topK(2)
check("top-k returns k entries", top.len == 2)
check("top-k sorted descending", top[0].weight >= top[1].weight)
for i in 0 ..< 200: h.update(@[0.0, 3.0, 3.0])
check("entropy collapses toward 0", h.entropy() < 0.5, $h.entropy())
check("argmax names the winner", h.argmaxName() == "a", h.argmaxName())
block:
echo "test 6: revision-safe clone / setWeights"
var h = initHedge(@["a", "b"])
h.update(@[0.0, 1.0])
let c = h.clone()
h.update(@[1.0, 0.0])
check("clone is independent", c.posterior("a") != h.posterior("a"))
var d = c.clone()
d.setWeights(@[3.0, 1.0])
check("setWeights normalizes", abs(sum(d) - 1.0) < 1e-12)
check("setWeights ratios preserved", abs(d.posterior("a") - 0.75) < 1e-12,
$d.posterior("a"))
echo ""
if failed == 0: echo "all hedge tests passed"
else: echo failed, " hedge test(s) FAILED"; quit(1)
@@ -0,0 +1,79 @@
## Tier A unit tests for the CHIMERA influence / fallback layer
## (chimera/influence.nim). Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/fusion
import chimera/influence
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc fusedPath(points: seq[tuple[x, y: float64]], pFire = 0.4): FusedPrediction =
result.horizon = points.len
result.points = points
for _ in points: result.pFire.add pFire
result.fireWithin = 0.8
result.confidence = 0.7
block:
echo "test 1: influence ramp"
check("no samples => no influence", influenceScalar(0.0, 0) == 0.0)
check("low loss => full influence", influenceScalar(0.1, 5) == 1.0)
check("high loss => zero influence", influenceScalar(5.0, 5) == 0.0)
let mid = influenceScalar((GoodLoss + BadLoss) / 2.0, 5)
check("mid loss => mid influence", abs(mid - 0.5) < 1e-9, $mid)
check("monotone decreasing",
influenceScalar(0.6, 1) >= influenceScalar(0.7, 1) and
influenceScalar(0.7, 1) >= influenceScalar(0.8, 1))
block:
echo "test 2: reflex gate — never touch an active bullet dodge"
let fp = fusedPath(@[(60.0, 100.0), (60.0, 130.0), (60.0, 160.0)])
let adv = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, reflexBusy = true)
check("not applied while dodging", not adv.applied)
check("command untouched", adv.speed == 6.0 and adv.turnRate == 0.0)
block:
echo "test 3: zero influence => no steering"
let fp = fusedPath(@[(60.0, 100.0), (60.0, 130.0), (60.0, 160.0)])
let adv = overlay(0.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, reflexBusy = false)
check("not applied", not adv.applied)
check("command untouched", adv.speed == 6.0 and adv.turnRate == 0.0)
block:
echo "test 4: steering toward safety + safe margins"
# Collision course: our straight path (heading north through x=100) runs
# straight into the fused predicted enemy (a stationary point at y=130), so
# any turn buys clearance before we arrive.
let fp = fusedPath(@[(100.0, 130.0), (100.0, 130.0), (100.0, 130.0),
(100.0, 130.0), (100.0, 130.0)])
let adv = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, reflexBusy = false)
check("applied when it improves clearance", adv.applied, $adv.gain)
check("turns away from the predicted path", adv.turnRate < 0.0, $adv.turnRate)
check("turn within cap", abs(adv.turnRate - 0.0) <= MaxTurnBias + 1e-9,
$adv.turnRate)
check("speed within cap", abs(adv.speed - 6.0) <= MaxSpeedDelta + 1e-9,
$adv.speed)
block:
echo "test 5: no nudge when the baseline is already safe"
let far = fusedPath(@[(100.0, 10000.0), (100.0, 10030.0), (100.0, 10060.0)])
let adv = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, far,
reflexBusy = false)
check("not applied (gain below margin)", not adv.applied, $adv.gain)
block:
echo "test 6: determinism"
let fp = fusedPath(@[(100.0, 130.0), (100.0, 130.0), (100.0, 130.0),
(100.0, 130.0), (100.0, 130.0)])
let a = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, false)
let b = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, false)
check("bit-identical advisory",
a.speed == b.speed and a.turnRate == b.turnRate and
a.applied == b.applied and a.gain == b.gain)
echo ""
if failed == 0: echo "all influence tests passed"
else: echo failed, " influence test(s) FAILED"; quit(1)
+86
View File
@@ -0,0 +1,86 @@
## Tier A unit tests for the CHIMERA intent ledger (chimera/ledger.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/ledger
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc scan(tick: int, dir: float64, speed: float64,
energy = 100.0): Scan =
Scan(tick: tick, direction: dir, speed: speed, energy: energy)
block:
echo "test 1: turn-rate interval recovery"
# 5 deg/tick at speed 0 (cap 10): exactly recovered.
let o = turnRateInterval(scan(1, 10.0, 0.0), scan(2, 15.0, 0.0))
check("turn known", o.turnKnown)
check("interval contains 5", o.turnRate.contains(5.0))
check("interval tight (width ~ 2e-6)", o.turnRate.width() < 1e-5,
$o.turnRate.width())
# wrap across 0: -5 deg/tick.
let w = turnRateInterval(scan(1, 0.0, 0.0), scan(2, -5.0, 0.0))
check("wrap interval contains -5", w.turnRate.contains(-5.0))
# cap at speed 8 is 4 deg/tick: an observed 4 is at the boundary.
let c = turnRateInterval(scan(1, 0.0, 8.0), scan(2, 4.0, 8.0))
check("capped turn contains 4", c.turnRate.contains(4.0))
check("cap upper bound is 4", abs(c.turnRate.hi - 4.0) < 1e-6, $c.turnRate.hi)
block:
echo "test 2: scan gap is censored, never guessed"
let g = turnRateInterval(scan(1, 0.0, 3.0), scan(3, 5.0, 3.0))
check("censored", g.censored)
check("turn not known", not g.turnKnown)
block:
echo "test 3: target-speed interval inversion"
# from rest, target 5 realizes +1 next tick; consistent set is [1, 8].
let a = targetSpeedInterval(0.0, 1.0)
check("known", a.targetKnown)
check("contains 5", a.targetSpeed.contains(5.0))
# decel from 8 toward 3 clamps to 6: consistent set (0, 6].
let d = targetSpeedInterval(8.0, 6.0)
check("decel contains 3", d.targetSpeed.contains(3.0))
check("decel upper bound 6", abs(d.targetSpeed.hi - 6.0) < 1e-9, $d.targetSpeed.hi)
# exact meet: 8 -> 7 names target 7.
let e = targetSpeedInterval(8.0, 7.0)
check("meet names 7", e.targetSpeed.contains(7.0) and e.targetSpeed.width() < 1e-6,
$e.targetSpeed)
# crossing zero from 8 realizes +3 regardless of the negative target.
let x = targetSpeedInterval(8.0, 3.0)
check("crossing contains -5", x.targetSpeed.contains(-5.0))
check("crossing interval is [-8, 0]",
abs(x.targetSpeed.lo + 8.0) < 1e-9 and abs(x.targetSpeed.hi) < 1e-9,
$x.targetSpeed)
# impossible: +5 from rest is unphysical.
let imp = targetSpeedInterval(0.0, 5.0)
check("impossible step censored", imp.censored and not imp.targetKnown)
block:
echo "test 4: fire inference from energy drop"
let f = fireFromEnergyDrop(100.0, 97.5, 0.0)
check("known fire", f.fireKnown and abs(f.fire - 2.5) < 1e-9, $f.fire)
let none = fireFromEnergyDrop(100.0, 100.0, 0.0)
check("no drop -> not known", not none.fireKnown)
let amb = fireFromEnergyDrop(100.0, 98.0, 1.0)
check("known damage -> censored", amb.censored)
let bad = fireFromEnergyDrop(100.0, 90.0, 0.0)
check("out-of-range drop -> censored", bad.censored)
block:
echo "test 5: censoring-rate accounting"
var obs: seq[LedgerObs] = @[]
obs.add LedgerObs(censored: false)
obs.add LedgerObs(censored: true)
obs.add LedgerObs(censored: false)
obs.add LedgerObs(censored: true)
obs.add LedgerObs(censored: false)
check("2/5 censored", abs(censorRate(obs) - 0.4) < 1e-12, $censorRate(obs))
check("empty -> 0", censorRate(newSeq[LedgerObs](0)) == 0.0)
echo ""
if failed == 0: echo "all ledger tests passed"
else: echo failed, " ledger test(s) FAILED"; quit(1)
+99
View File
@@ -0,0 +1,99 @@
## Offline test for the observation sidecar (observer.nim): feeding it a
## synthetic oracle stream for a known kernel must drive the posterior to that
## kernel at high weight, and the telemetry writer must emit well-formed JSONL.
## No Java needed. Run: from ChimeraBot_garage, `nim c -r --path:tests tests/test_observer.nim`.
import std/[strutils, os]
import chimera/dsl
import chimera/oracle
import chimera/observer
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
let telemetryDir = getTempDir() / "chimera_observer_test" & $getCurrentProcessId()
removeDir(telemetryDir)
block:
echo "observer: identification over synthetic streams"
for i in 0 ..< kernels.len:
removeDir(telemetryDir)
let env = defaultEnv()
let o = initObserver(kernels, telemetryDir)
o.startRound(1)
# Replay the kernel's own oracle stream through observeScan.
let stream = generateOracle(kernels[i], kernels[i].defaultParams, env, 400)
var idTick = -1
var crossArgmax = ""
for t in 0 ..< stream.scans.len:
let s = stream.scans[t]
o.observeScan(s.tick, s.x, s.y, s.direction, s.speed, s.energy,
env.myX, env.myY, kernels[i].name, env.arenaW, env.arenaH)
if idTick < 0 and o.posterior(kernels[i].name) >= 0.9:
idTick = t
crossArgmax = o.argmaxName()
o.endRound()
let post = o.posterior(kernels[i].name)
# Spec G1 wording: REACH >= 0.9 within the horizon (see test_oracle_g1 for
# why final posterior is reported but not asserted for degenerate pairs).
check("posterior[" & kernels[i].name & "] crossed 0.9", idTick >= 0,
"never crossed; final " & $post)
check("argmax is " & kernels[i].name & " when it crossed",
crossArgmax == kernels[i].name, "got " & crossArgmax)
block:
echo "observer: cross-round posterior carry-over (M5.5)"
removeDir(telemetryDir)
let env = defaultEnv()
let o = initObserver(kernels, "")
o.startRound(1)
let stream = generateOracle(kernels[2], kernels[2].defaultParams, env, 300)
for t in 0 ..< stream.scans.len:
let s = stream.scans[t]
o.observeScan(s.tick, s.x, s.y, s.direction, s.speed, s.energy,
env.myX, env.myY, "ZIGZAG", env.arenaW, env.arenaH)
let top = o.argmaxName()
let carried = o.posterior(top)
check("round 1 identified (> 0.8)", carried > 0.8,
$top & " = " & $carried)
o.startRound(2)
check("carry-over keeps the posterior across rounds",
o.posterior(top) == carried, $carried & " -> " & $o.posterior(top))
o.carryOver = false
o.startRound(3)
check("fresh-round ablation resets to uniform",
abs(o.posterior(top) - 1.0 / float64(kernels.len)) < 1e-12,
$o.posterior(top))
block:
echo "observer: telemetry files are well-formed (Crazy/ZIGZAG)"
removeDir(telemetryDir)
let env = defaultEnv()
let o = initObserver(kernels, telemetryDir)
o.startRound(1)
let stream = generateOracle(kernels[2], kernels[2].defaultParams, env, 120)
for t in 0 ..< stream.scans.len:
let s = stream.scans[t]
o.observeScan(s.tick, s.x, s.y, s.direction, s.speed, s.energy,
env.myX, env.myY, "Crazy", env.arenaW, env.arenaH)
o.writeTick(s.tick)
o.endRound()
let path = telemetryDir / "Crazy-1.jsonl"
check("telemetry file exists", fileExists(path), path)
if fileExists(path):
let lines = readFile(path).splitLines()
check("file has per-tick lines + summary", lines.len > 90,
"got " & $lines.len)
check("first line is a tick JSON", lines[0].startsWith("{\"tick\""))
var hasSummary = false
for ln in lines:
if ln.startsWith("{\"event\":\"round_summary\""): hasSummary = true
check("summary line present", hasSummary)
removeDir(telemetryDir)
echo ""
if failed == 0: echo "all observer tests passed"
else: echo failed, " observer 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"
@@ -0,0 +1,83 @@
## G1 oracle-convergence test (spec §12 Tier C, G1).
##
## For every kernel K in the M2 set: generate K's exact oracle intent stream over
## the synthetic arena, replay it through the ledger + Hedge, and require
## posterior(K) >= 0.9 within T* = 300 ticks. A failure here indicts the
## inference layer (implementation bug) — it is reported, never hidden.
##
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/[math, strutils, os]
import chimera/dsl
import chimera/oracle
const TStar = 300
const Threshold = 0.9
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
let env = defaultEnv()
block:
echo "G1: oracle convergence over the M2 kernel set (T* = ", TStar, " ticks)"
echo " ", align("kernel", 16), align("idTick", 8), align("posterior", 11),
align("censor", 8)
# Persist the FULL 12-kernel table to a committed artifact, so the answer to
# "did every kernel converge?" no longer depends on log truncation (the M2/M3
# reports lost rows to tail-cut logs). Deterministic: every column is a pure
# function of the kernel set + fixed oracle env.
var rows: seq[string]
for i in 0 ..< kernels.len:
let r = runG1(kernels, i, env, TStar)
let idStr = if r.idTick < 0: " NEVER" else: align($r.idTick, 8)
echo " ", align(r.kernel, 16), idStr, " ", formatFloat(r.finalPosterior,
ffDecimal, 5), " ", formatFloat(r.censorRate, ffDecimal, 4)
# Spec G1 wording: the weight must REACH >= 0.9 within T*. We report the
# final posterior separately: a kernel that is observationally equivalent to
# another once in a steady state (e.g. STATIC_CORNER vs STATIC after the
# corner park) can cross 0.9 during its distinctive phase and then decay.
let ok = r.idTick > 0 and r.idTick <= TStar
check("G1 " & r.kernel & " identified within T*", ok,
"idTick=" & $r.idTick & " posterior=" & formatFloat(r.finalPosterior,
ffDecimal, 4))
rows.add "| " & r.kernel & " | " &
(if r.idTick < 0: "never" else: $r.idTick) & " | " &
formatFloat(r.finalPosterior, ffDecimal, 5) & " | " &
formatFloat(r.censorRate, ffDecimal, 4) & " | " &
(if ok: "PASS" else: "FAIL") & " |"
let artPath = currentSourcePath().parentDir.parentDir /
"benchmarks" / "g1_oracle_table.md"
createDir(artPath.parentDir)
writeFile(artPath,
"# G1 oracle-convergence table\n\n" &
"Auto-generated by `tests/test_oracle_g1.nim` (deterministic; regenerate with " &
"`nimble test`). T* = " & $TStar & " ticks, threshold = " &
formatFloat(Threshold, ffDecimal, 2) & ", env = default synthetic arena " &
"(800x600, no sensor error). A PASS means posterior(kernel) reached the " &
"threshold within T*.\n\n" &
"| kernel | idTick | finalPosterior | censorRate | pass |\n" &
"|---|---:|---:|---:|---|\n" & rows.join("\n") & "\n")
echo " table written: ", artPath
block:
echo ""
echo "G1 determinism: identical reruns"
let a = runG1(kernels, 0, env, TStar)
let b = runG1(kernels, 0, env, TStar)
check("same idTick", a.idTick == b.idTick, $a.idTick & " vs " & $b.idTick)
check("same posterior", a.finalPosterior == b.finalPosterior)
let s1 = generateOracle(kernels[2], kernels[2].defaultParams, env, 100)
let s2 = generateOracle(kernels[2], kernels[2].defaultParams, env, 100)
var same = s1.scans.len == s2.scans.len
for i in 0 ..< min(s1.scans.len, s2.scans.len):
if s1.scans[i].x != s2.scans[i].x or s1.scans[i].direction != s2.scans[i].direction:
same = false
check("oracle stream is byte-identical", same)
echo ""
if failed == 0: echo "all G1 oracle tests passed"
else: echo failed, " G1 test(s) FAILED"; quit(1)
+72
View File
@@ -0,0 +1,72 @@
## Tier A unit tests for the CHIMERA physics mirror (chimera/physics.nim).
## Run: from ChimeraBot_garage/src, `nimble test` (or
## `nim c -r ../tests/test_physics.nim`).
##
## Ground truth: robocode-tankroyale server `rules/math.kt`. The exact fixtures
## below are hand-derived from that source, not from our own output.
import std/math
import chimera/physics
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc approx(a, b: float64): bool = abs(a - b) < 1e-9
block:
echo "test 1: stepSpeed truth table (calcNewBotSpeed)"
check("0 -> target 5 accelerates by 1", approx(stepSpeed(0.0, 5.0), 1.0),
$stepSpeed(0.0, 5.0))
check("0 -> target 0.5 snaps to target", approx(stepSpeed(0.0, 0.5), 0.5))
check("0 -> target -0.5 snaps to target", approx(stepSpeed(0.0, -0.5), -0.5))
check("3 -> target 8 accelerates by 1", approx(stepSpeed(3.0, 8.0), 4.0))
check("8 -> target 0.5 decelerates by 2", approx(stepSpeed(8.0, 0.5), 6.0))
check("8 -> target 7 meets it (diff -1)", approx(stepSpeed(8.0, 7.0), 7.0))
check("1 -> target 0.5 meets it", approx(stepSpeed(1.0, 0.5), 0.5))
# crossing-zero branch: v_new = (1 - v/2) * -1, a direct assignment
check("8 crossing to -5 -> +3", approx(stepSpeed(8.0, -5.0), 3.0))
check("3 crossing to -5 -> +0.5", approx(stepSpeed(3.0, -5.0), 0.5))
check("0.5 crossing to -5 -> -0.75", approx(stepSpeed(0.5, -5.0), -0.75))
check("2 crossing to -5 -> 0.0", approx(stepSpeed(2.0, -5.0), 0.0))
check("target 0 from 8 stops", approx(stepSpeed(8.0, 0.0), 0.0))
# odd symmetry handles negative current speeds
check("-3 -> target -8 accelerates by -1", approx(stepSpeed(-3.0, -8.0), -4.0))
check("-8 crossing to +5 -> -3", approx(stepSpeed(-8.0, 5.0), -3.0))
check("clamp at +8", approx(stepSpeed(8.0, 20.0), 8.0))
check("clamp at -8", approx(stepSpeed(-8.0, -20.0), -8.0))
block:
echo "test 2: maxTurnRate identities (calcMaxTurnRate)"
check("v=0 -> 10", approx(maxTurnRate(0.0), 10.0))
check("v=8 -> 4", approx(maxTurnRate(8.0), 4.0))
check("v=-8 -> 4", approx(maxTurnRate(-8.0), 4.0))
check("v=4 -> 7", approx(maxTurnRate(4.0), 7.0))
check("clamped above max speed", approx(maxTurnRate(100.0), 4.0))
check("limitTurnRate clamps", approx(limitTurnRate(50.0, 8.0), 4.0))
block:
echo "test 3: bullet speed/damage/heat fixtures"
check("bulletSpeed(0.1)=19.7", approx(bulletSpeed(0.1), 19.7))
check("bulletSpeed(1)=17", approx(bulletSpeed(1.0), 17.0))
check("bulletSpeed(3)=11", approx(bulletSpeed(3.0), 11.0))
check("bulletSpeed clamps p>3", approx(bulletSpeed(5.0), 11.0))
check("bulletDamage(1)=4", approx(bulletDamage(1.0), 4.0))
check("bulletDamage(2)=10", approx(bulletDamage(2.0), 10.0))
check("bulletDamage(3)=16", approx(bulletDamage(3.0), 16.0))
check("bulletDamage(0.5)=2", approx(bulletDamage(0.5), 2.0))
check("gunHeat(1)=1.2", approx(gunHeat(1.0), 1.2))
check("gunHeat(3)=1.6", approx(gunHeat(3.0), 1.6))
block:
echo "test 4: angles"
check("wrap180(370)=10", approx(wrap180(370.0), 10.0))
check("wrap180(-190)=170", approx(wrap180(-190.0), 170.0))
check("wrap180(180)=180", approx(wrap180(180.0), 180.0))
check("bearing east", approx(bearingTo(0.0, 0.0, 1.0, 0.0), 0.0))
check("bearing north", approx(bearingTo(0.0, 0.0, 0.0, 1.0), 90.0))
echo ""
if failed == 0: echo "all physics tests passed"
else: echo failed, " physics test(s) FAILED"; quit(1)
+173
View File
@@ -0,0 +1,173 @@
## Tier A tests for the CHIMERA probe scheduler (chimera/probes.nim, spec §9).
## Pure Nim, no Java. Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/dsl
import chimera/twinsim
import chimera/probes
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
proc origin(): ReplayTick =
var r = ReplayTick(tick: 60, ex: 200.0, ey: 300.0, edir: 0.0,
espeed: 6.0, eenergy: 80.0,
ox: 600.0, oy: 300.0, odir: 180.0, ospeed: 4.0,
lastTurn: 0.0, lastSpeed: 6.0)
r.weights = newSeq[float64](kernels.len)
for i in 0 ..< kernels.len: r.weights[i] = 1.0 / float64(kernels.len)
r.mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len: r.mems[i] = defaultMemory(kernels[i].defaultParams)
r
proc baseCtx(): ProbeContext =
## All-clear context: mid-arena, healthy, enemy far and cold, not aimed.
ProbeContext(tick: 60, ourEnergy: 100.0, ownX: 400.0, ownY: 300.0,
ownSpeed: 4.0, arenaW: 800.0, arenaH: 600.0,
enemyX: 750.0, enemyY: 300.0, enemyGunHeat: 3.0,
enemyAimedAtUs: false, roundLimit: 2000)
block:
echo "probes 1: survival-gate truth table"
var c = baseCtx()
check("all clear allows", survivalGate(c).allow)
check("all-clear reason", survivalGate(c).reason == "ok")
c = baseCtx(); c.ourEnergy = 10.0
check("low energy denies", not survivalGate(c).allow)
check("low energy reason", survivalGate(c).reason == "energy")
c = baseCtx(); c.enemyAimedAtUs = true; c.enemyGunHeat = 0.0
check("hot+aimed denies", not survivalGate(c).allow)
check("hot+aimed reason", survivalGate(c).reason == "enemy-hot-aimed")
c.enemyGunHeat = 2.0
check("aimed but cold allows", survivalGate(c).allow)
c = baseCtx(); c.ownX = 5.0
check("wall-pinned denies", not survivalGate(c).allow)
check("wall-pinned reason", survivalGate(c).reason == "wall-pinned")
c = baseCtx(); c.tick = 1980
check("round-end denies", not survivalGate(c).allow)
check("round-end reason", survivalGate(c).reason == "round-end")
# priority: energy checked before wall/heat
c = baseCtx(); c.ourEnergy = 5.0; c.ownX = 5.0; c.enemyAimedAtUs = true
c.enemyGunHeat = 0.0
check("energy has gate priority", survivalGate(c).reason == "energy")
block:
echo "probes 2: budget accounting"
var s = initProbeScheduler(kernels)
check("interval nominal 25", s.interval == 25)
var c = baseCtx()
var triggers = 0
for t in 1 .. 25:
c.tick = t
if s.consider(origin(), c).trigger: inc triggers
check("first trigger exactly at interval", triggers == 1, $triggers)
check("counter reset after executed probe", s.ticksSinceProbe == 0)
check("one executed probe", s.probes == 1)
# next trigger must wait a full interval again
var before = false
for t in 26 .. 49:
c.tick = t
if s.consider(origin(), c).trigger: before = true
check("no trigger before next interval", not before)
c.tick = 50
check("second trigger at 2*interval", s.consider(origin(), c).trigger)
check("two executed probes", s.probes == 2)
# gate deny: trigger fires past the interval but the budget never resets
var d = initProbeScheduler(kernels)
var dc = baseCtx(); dc.ourEnergy = 5.0
for t in 1 .. 25:
dc.tick = t
discard d.consider(origin(), dc)
check("gated tick still triggers", d.ticksSinceProbe == 25)
discard d.consider(origin(), dc)
check("gated: no executed probe", d.probes == 0)
check("gated: counter keeps growing", d.ticksSinceProbe == 26)
check("interval clamped low", initProbeScheduler(kernels, 1).interval == 20)
check("interval clamped high", initProbeScheduler(kernels, 99).interval == 30)
block:
echo "probes 3: entropy-selection determinism"
let o = origin()
let c = baseCtx()
let d1 = chooseProbe(kernels, o, c)
let d2 = chooseProbe(kernels, o, c)
check("same candidate kind", d1.candidate.kind == d2.candidate.kind)
check("same turn rate", d1.candidate.turnRate == d2.candidate.turnRate)
check("same target speed", d1.candidate.targetSpeed == d2.candidate.targetSpeed)
check("same entropyBefore", d1.entropyBefore == d2.entropyBefore)
check("same entropyAfter", d1.entropyAfter == d2.entropyAfter)
check("entropy does not increase",
d1.entropyAfter <= d1.entropyBefore + 1e-9,
$d1.entropyBefore & " -> " & $d1.entropyAfter)
# selection is information-driven: at least one candidate must separate the
# kernels, so a mixed posterior admits a strictly positive expected drop.
check("selection finds information", d1.entropyBefore - d1.entropyAfter > 0.0,
$(d1.entropyBefore - d1.entropyAfter))
block:
echo "probes 4: camouflage plausibility"
var c = baseCtx(); c.ownSpeed = 7.9
for cand in candidates(c):
let cam = camouflage(cand, c)
check("in envelope " & $cam.kind, plausible(cam, c),
"turn=" & $cam.turnRate & " speed=" & $cam.targetSpeed)
c = baseCtx(); c.ownSpeed = 0.0
var anySmall = false
for cand in candidates(c):
let cam = camouflage(cand, c)
check("in envelope at rest " & $cam.kind, plausible(cam, c))
if abs(cam.targetSpeed) <= 8.0 and abs(cam.turnRate) <= 10.0: anySmall = true
check("probe magnitudes stay plausible", anySmall)
block:
echo "probes 6: probe set v2 (distance + gun, M5.5)"
var c = baseCtx()
check("gunProbeAllowed false when not aimed", not gunProbeAllowed(c))
var kinds: set[ProbeKind] = {}
var gunFire = 0.0
for cand in candidates(c):
kinds.incl cand.kind
if cand.kind == pkGunShot: gunFire = cand.fire
check("distance candidate present", pkDistance in kinds)
check("gun candidate absent when not aimed", pkGunShot notin kinds)
c.ourGunHeat = 0.0; c.ourGunAimed = true
check("gunProbeAllowed true when cool+aimed", gunProbeAllowed(c))
kinds = {}; gunFire = 0.0
for cand in candidates(c):
kinds.incl cand.kind
if cand.kind == pkGunShot: gunFire = cand.fire
check("gun candidate present when cool+aimed", pkGunShot in kinds)
check("gun probe IS a shot (low power)", gunFire > 0.0, $gunFire)
check("all six probe types selectable", kinds.len == 6, $kinds)
var d = baseCtx(); d.ourGunHeat = 0.0; d.ourGunAimed = true; d.enemyAimedAtUs = true
check("gunProbeAllowed false when enemy aimed at us", not gunProbeAllowed(d))
var e = baseCtx(); e.ourGunHeat = 1.0; e.ourGunAimed = true
check("gunProbeAllowed false when our gun hot", not gunProbeAllowed(e))
let dec = chooseProbe(kernels, origin(), c)
check("chooseProbe deterministic over v2 set",
dec.candidate.kind == chooseProbe(kernels, origin(), c).candidate.kind)
check("entropy selection covers v2 set (non-increasing entropy)",
dec.entropyAfter <= dec.entropyBefore + 1e-9)
block:
echo "probes 5: entropy closed form"
check("uniform n=4 entropy = ln4",
abs(entropyOf([0.25, 0.25, 0.25, 0.25]) - ln(4.0)) < 1e-12)
check("onehot entropy = 0", abs(entropyOf([1.0, 0.0, 0.0])) < 1e-12)
check("normalization-invariant",
abs(entropyOf([2.0, 2.0, 2.0, 2.0]) - ln(4.0)) < 1e-12)
echo ""
if failed == 0: echo "all probe tests passed"
else: echo failed, " probe test(s) FAILED"; quit(1)
+76
View File
@@ -0,0 +1,76 @@
## Tier A unit tests for the CHIMERA residual head (chimera/residual.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/residual
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc finite(x: float64): bool = x == x and abs(x) < 1e12
block:
echo "test 1: online determinism"
var a = initResidualHead()
var b = initResidualHead()
let f = features(ResidualInput(lastTurn: 3.0, lastSpeed: -2.0, scanAge: 1.0,
dist: 250.0, ownTurn: 4.0, ownSpeed: 5.0))
for i in 0 ..< 50:
let t = ResidualTarget(turn: 0.1 * float(i mod 5), speed: -0.05,
fire: 0.001 * float(i))
a.observe(f, t)
b.observe(f, t)
let pa = a.predict(f)
let pb = b.predict(f)
check("identical heads agree bit-for-bit",
pa.turn == pb.turn and pa.speed == pb.speed and pa.fire == pb.fire)
check("samples counted", a.samples == 50, $a.samples)
block:
echo "test 2: monotone improvement on a synthetic residual stream"
# Deterministic stream: target.turn = a linear function of the features.
var head = initResidualHead()
var state = 0x12345678'u64
proc u01(): float64 =
state = state * 6364136223846793005'u64 + 1442695040888963407'u64
float64(state shr 11) / 9007199254740992.0
var firstSum, lastSum = 0.0
for i in 0 ..< 2000:
let inp = ResidualInput(lastTurn: (u01() * 2.0 - 1.0) * 10.0,
lastSpeed: (u01() * 2.0 - 1.0) * 8.0,
scanAge: 1.0 + u01() * 3.0,
dist: u01() * 800.0,
ownTurn: (u01() * 2.0 - 1.0) * 10.0,
ownSpeed: (u01() * 2.0 - 1.0) * 8.0)
let ff = features(inp)
# true residual: 0.2*f0 + 0.1*f1 - 0.3*f4
let tgt = ResidualTarget(turn: 0.2 * ff[0] + 0.1 * ff[1] - 0.3 * ff[4],
speed: 0.0, fire: 0.0)
let l = head.meanSquaredLoss(ff, tgt)
if i < 100: firstSum += l
if i >= 1900: lastSum += l
head.observe(ff, tgt)
check("early loss > late loss (learns)", lastSum < firstSum,
$lastSum & " vs " & $firstSum)
block:
echo "test 3: no crash / finite on degenerate input"
var head = initResidualHead()
let zeros: array[NFeatures, float64] = default(array[NFeatures, float64])
head.observe(zeros, ResidualTarget())
let big = features(ResidualInput(dist: 1e9, lastTurn: 1e9, ownSpeed: -1e9))
head.observe(big, ResidualTarget(turn: 1e9, speed: -1e9, fire: 1.0))
let p = head.predict(big)
check("prediction is finite", finite(p.turn) and finite(p.speed) and finite(p.fire))
check("fire prediction clamped to [-1,1]", p.fire >= -1.0 and p.fire <= 1.0,
$p.fire)
var empty = initResidualHead()
empty.reset()
check("reset zeroes samples", empty.samples == 0 and
empty.predict(zeros).turn == 0.0)
echo ""
if failed == 0: echo "all residual tests passed"
else: echo failed, " residual test(s) FAILED"; quit(1)
+121
View File
@@ -0,0 +1,121 @@
## Tier A tests for the CHIMERA twin rollout (chimera/twinsim.nim, spec §8).
## Pure Nim, no Java. Run: from ChimeraBot_garage/src, `nimble test`.
import std/[math, os, strutils]
import chimera/dsl
import chimera/twinsim
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
let kernels = allKernels()
proc origin(): ReplayTick =
var r = ReplayTick(tick: 100, ex: 200.0, ey: 300.0, edir: 0.0,
espeed: 6.0, eenergy: 80.0,
ox: 600.0, oy: 300.0, odir: 180.0, ospeed: 4.0,
lastTurn: 0.0, lastSpeed: 6.0)
r.weights = newSeq[float64](kernels.len)
for i in 0 ..< kernels.len: r.weights[i] = 1.0 / float64(kernels.len)
r.mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len: r.mems[i] = defaultMemory(kernels[i].defaultParams)
r
block:
echo "twinsim 1: determinism"
let a = rollout(kernels, origin(), 5)
let b = rollout(kernels, origin(), 5)
var same = a.points.len == b.points.len
for i in 0 ..< min(a.points.len, b.points.len):
if a.points[i].x != b.points[i].x or a.points[i].pFire != b.points[i].pFire:
same = false
check("byte-identical rerun", same)
check("fireWithin deterministic", a.fireWithin == b.fireWithin)
block:
echo "twinsim 2: plan-difference effect (our plan changes the prediction)"
let planA = newSeq[PlanStep](5) # hold still
var planB = newSeq[PlanStep](5)
for i in 0 ..< 5: planB[i] = PlanStep(turnRate: 0.0, targetSpeed: 8.0)
let ra = rollout(kernels, origin(), 5, plan = planA)
let rb = rollout(kernels, origin(), 5, plan = planB)
var maxSep = 0.0
for i in 0 ..< ra.points.len:
maxSep = max(maxSep, hypot(ra.points[i].x - rb.points[i].x,
ra.points[i].y - rb.points[i].y))
check("different own plans separate the twin prediction", maxSep > 0.05,
"max separation " & $maxSep)
block:
echo "twinsim 3: k-horizon growth and distribution shape"
for k in [1, 5, 10]:
let r = rollout(kernels, origin(), k)
check("k=" & $k & " yields k points", r.points.len == k)
check("k=" & $k & " one sample per kernel", r.samples.len == kernels.len)
check("k=" & $k & " fireWithin in [0,1]",
r.fireWithin >= 0.0 and r.fireWithin <= 1.0, $r.fireWithin)
let r5 = rollout(kernels, origin(), 5)
let r10 = rollout(kernels, origin(), 10)
# A longer horizon can only add opportunities to fire.
check("fireWithin non-decreasing in k", r10.fireWithin >= r5.fireWithin,
$r5.fireWithin & " -> " & $r10.fireWithin)
block:
echo "twinsim 4: telemetry parse + offline replay"
let dir = getTempDir() / ("chimera_twinsim_test" & $getCurrentProcessId())
removeDir(dir)
createDir(dir)
const rows = [
"""{"tick":1,"scan":true,"turnRateInterval":[0.0,0.0],"targetSpeedInterval":[1.0,1.0],"censor":false,"ex":200.0,"ey":300.0,"edir":0.0,"espeed":1.0,"eenergy":100.0,"ox":600.0,"oy":300.0,"odir":180.0,"ospeed":0.0,"posteriorTop5":[]}""",
"""{"tick":2,"scan":true,"turnRateInterval":[0.0,0.0],"targetSpeedInterval":[2.0,2.0],"censor":false,"fireObs":1.0,"ex":201.0,"ey":300.0,"edir":0.0,"espeed":2.0,"eenergy":99.0,"ox":600.0,"oy":300.0,"odir":180.0,"ospeed":0.0,"posteriorTop5":[]}""",
"""{"tick":3,"scan":true,"turnRateInterval":[0.0,0.0],"targetSpeedInterval":[3.0,3.0],"censor":false,"ex":202.0,"ey":300.0,"edir":0.0,"espeed":3.0,"eenergy":99.0,"ox":600.0,"oy":300.0,"odir":180.0,"ospeed":0.0,"posteriorTop5":[]}""",
"""{"event":"round_summary","round":1}""" & "\n"]
let path = dir / "Toy-1.jsonl"
writeFile(path, rows.join("\n"))
let rec = loadRecord(path)
check("opponent parsed", rec.opponent == "Toy", rec.opponent)
check("round parsed", rec.round == 1, $rec.round)
check("scanned ticks parsed", rec.ticks.len == 3, $rec.ticks.len)
check("fire tick flagged", rec.ticks[1].fireKnown and rec.ticks[1].fireObs == 1.0)
let rp = replay(rec, kernels)
check("replay one entry per scan", rp.len == 3, $rp.len)
check("posterior rows match kernel count", rp[0].weights.len == kernels.len)
# persistence runs and yields k points
let persist = persistence(rp[2], 5)
check("persistence yields k points", persist.len == 5)
check("fireRate counted", abs(rec.fireRate() - 1.0 / 3.0) < 1e-9,
$rec.fireRate())
removeDir(dir)
block:
echo "twinsim 5: probe-reaction prediction (single-kernel counterfactual)"
let o = origin()
var ramIdx = -1
for i, k in kernels:
if k.name == "RAMMER": ramIdx = i
check("RAMMER kernel present", ramIdx >= 0)
var onehot = o
onehot.weights = newSeq[float64](kernels.len)
if ramIdx >= 0: onehot.weights[ramIdx] = 1.0
var planStop = newSeq[PlanStep](5) # hold still
var planTurn = newSeq[PlanStep](5) # curve off the bearing
for i in 0 ..< 5: planTurn[i] = PlanStep(turnRate: 10.0, targetSpeed: 8.0)
let rStop = rollout(kernels, onehot, 5, plan = planStop)
let rFlee = rollout(kernels, onehot, 5, plan = planTurn)
var sep = 0.0
for i in 0 ..< rStop.points.len:
sep = max(sep, hypot(rStop.points[i].x - rFlee.points[i].x,
rStop.points[i].y - rFlee.points[i].y))
check("our probe action changes the predicted enemy reaction", sep > 0.01,
"separation " & $sep)
let rStop2 = rollout(kernels, onehot, 5, plan = planStop)
check("single-kernel probe rollout is deterministic",
rStop.points[^1].x == rStop2.points[^1].x and
rStop.points[^1].y == rStop2.points[^1].y)
removeDir(getTempDir() / ("chimera_twinsim_test" & $getCurrentProcessId()))
echo ""
if failed == 0: echo "all twinsim tests passed"
else: echo failed, " twinsim test(s) FAILED"; quit(1)
+2
View File
@@ -0,0 +1,2 @@
# User-authored environment variables (e.g. SERVER_URL) — never committed
.env
+252
View File
@@ -0,0 +1,252 @@
# DevControlBot — Garage Agent Guide
> ## ⚠️ READ THIS FIRST — THIS GARAGE IS *INTENTIONALLY* NOT THE ROOT TEMPLATE
>
> **The layout and format described in the repo-root [`../../AGENTS.md`](../../AGENTS.md)
> template do NOT apply to `DevControlBot_garage/`.** The root template documents a
> `src/<bot>.nim` / `tests/` / `out/` convention for garages. **This garage deviates
> from it on purpose and must stay that way.**
>
> **Do NOT, even to "fix" a perceived inconsistency:**
> - create `src/` or `out/`, or put anything inside `DevControlBot/` for testing
> (the one exception is the intended `DevControlBot_garage/tests/`, see
> "Layout of this folder" — it does not exist yet, create it only when the
> first test is actually written)
> - add a `config.nims`, `nimble.paths`, `--path` flags, or a vendor/ directory
> - restructure `DevControlBot/` to match the root template
>
> Builds go to a `mktemp -d` throwaway dir that is removed on exit — nothing is
> ever written here. The root `AGENTS.md` and its folder conventions are for the
> **other** garages; here it is context only (issue tracker, Nim conventions), and
> is **NOT a layout contract for this folder**. If the root template and this file
> disagree about layout, **this file wins.**
> ## ⚠️ DO NOT TOUCH `PLAN.md`
>
> **[`PLAN.md`](PLAN.md) is the user's personal working notes file.** The user
> maintains it and edits it exclusively.
>
> - Agents must **NEVER** modify, rewrite, reformat, move, delete or commit
> changes to `PLAN.md` — unless the user explicitly asks in that conversation.
> - Reading it is **not** assumed or expected; do not open it by default.
> - It **IS** tracked in git and is intended to be committed (deliberately added
> in commit `59fad00b`). Do **NOT** gitignore it and do **NOT**
> `git rm --cached` it.
## Start here
The code is the source of truth; this file is an inventory of what exists and how
the pieces interact — not a description of what the code does. If the two
disagree, the code wins and this file is stale.
The human-facing description lives in [README.md](README.md). Repo-wide rules live
in [`../../AGENTS.md`](../../AGENTS.md) (issue tracker, Nim conventions, test
framework) — read it for that context, but note again: **its folder-layout
template does not govern this garage.**
## Conventions
### Git rule for this garage
- **EVERYTHING** under `DevControlBot_garage/` gets committed — sources, modules,
docs, `PLAN.md` — **unless it is explicitly listed in a `.gitignore`**.
- This includes files that look like scratch or generated output, and files an agent
did not create: if not gitignored, they belong in the commit.
- Do not silently leave a file untracked, and do **not** add entries to
`.gitignore` to avoid committing something. The only things that stay out are
those the user has deliberately gitignored (e.g. `.env`).
### Version bumps and tags — the user's decision
Agents **MUST NOT** bump the version in `DevControlBot.nimble` or
`DevControlBot.json`, and **MUST NOT** create git tags. A version bump and its tag
are honoured **only** when the user explicitly asks in that conversation; a bump is
never a side effect of ordinary work or of a commit. Never amend, rewrite or retag
an existing commit or tag.
### Scope and colour
- This bot's code lives **only** inside `DevControlBot_garage/`. Do not edit other
garages to make this bot work, and do not reuse another bot's game logic
without explicit permission; shared, bot-agnostic code belongs in
`common_libs/`, and only with permission.
- The bot **moves** (bullet-avoidance mover, see "Layout of this folder") but
still **does not fire**: hit tracking exists, the gun does not.
- Team colour convention: **white = not programmed, black = programmed and
running**. The bot is **fully black**: movement (initTFIL) claims body, turret
and gun, the radar (initRadar) claims the radar and its scan arc.
- Provenance: ModularBot / common_libs (Davide Cappellini, Apache-2.0).
### Constraints worth remembering
Not explanations — real invariants that broke things when violated:
- **Command the radar BEFORE `go()`** — a real bug the other way round. Movement is
computed in the same slot, between `commandRadar()` and `go()`.
- **Movement is self-contained.** `modules/tfil.nim` is a port of
`common_libs/movements/the_floor_is_lava.nim` with **no runtime dependency on
`common_libs/`** — do not add one, and do not edit the original to match.
- All radar logic is `modules/radar.nim`, in one piece. Do not split it back into
harness/lock/melee modules.
## Layout of this folder
```
DevControlBot_garage/
├── AGENTS.md # this file
├── README.md # human-facing description
├── PLAN.md # the user's own notes — never edit (see header)
├── .gitignore # ignores .env
├── DevControlBot/
│ ├── DevControlBot.nim # bot type + entry point (isMainModule)
│ ├── DevControlBot.json # bot metadata
│ ├── DevControlBot.nimble # single task: runBot
│ ├── DevControlBot.sh # BotLauncher entry point (thin wrapper)
│ ├── .env # OPTIONAL local config; secrets, never commit
│ └── modules/
│ ├── radar.nim # all radar logic
│ └── tfil.nim # all movement logic ("the floor is lava")
└── tests/ # INTENDED, does not exist yet — create it on
# the first real test
```
- `DevControlBot/` holds only what the bot needs to run.
- `tests/` is a sibling of `DevControlBot/`, never inside it, and holds **test
code worth keeping**: drivers, harnesses, reusable battle/probe scripts.
- **Throwaway output does NOT go here or anywhere in the repo — it goes to
`/tmp`**: logs, temporary binaries, dumps, telemetry, scratch output.
- No `out/`, no binaries, no `nimbledeps/` here. Builds are throwaway by design.
## Build and run
Use the folder task, never raw `nim c`:
```sh
cd DevControlBot_garage/DevControlBot
nimble runBot # quiet release build + run
```
Or via the wrapper, which works from any cwd:
```sh
./DevControlBot/DevControlBot.sh # bundled metadata
./DevControlBot/DevControlBot.sh my.json # first positional arg, must end in .json
./DevControlBot/DevControlBot.sh --debug # classic debug build (hints + diagnostics)
./DevControlBot/DevControlBot.sh --help # usage, exits 0 without building
```
- **No arguments means RUN, not usage.** Usage prints only for `-h` / `--help`.
There is no `--json` flag; a first positional ending in `.json` overrides the
metadata, anything else is forwarded to the bot verbatim.
- **Gotcha:** `nimble runBot` must run from `DevControlBot/` (where the
`.nimble` lives); from `DevControlBot_garage/` it fails with
`Could not find a file with a .nimble extension...`. `compile`/`build` are
reserved Nimble builtin names — hence `runBot`.
- **Config is environment-only.** The bot API's `start()` reads `SERVER_URL` /
`SERVER_SECRET` itself; **never add env-reading code to `DevControlBot.nim`.**
The optional `.env` (loaded by the `runBot` task, `$DEVCONTROLBOT_ENV_FILE`
overrides the path) is local-runs-only and **never overrides a variable already
present in the environment** — the BotLauncher's values always win. Never print
its values, never `set -x`, never commit it.
- **Debug graphics are OFF by default** and compile-time gated behind
`-d:tfilDebug`; `nimble runBot` does **not** forward compile flags, so draw them
with a plain `nim c -d:tfilDebug ...` (into a `/tmp` output path) and run that.
- Dependency setup is `nimble install robocode_tankroyale_botapi`; dependencies
come from the global nimble store. Do not vendor, do not add
`nimble.paths` / `nimble develop`.
- Without a game server at `SERVER_URL` the run fails with
`[start] Cannot connect ... Connection refused`. That is expected locally, not a
bug.
- Exit codes are distinct because BotLauncher branches on them: `0` clean,
`1` no server (expected), `2` dependency missing, `3` compile failure,
anything else = the bot's own code.
## Tests
There are **no tests yet** — no `tests/` directory and no `test` task; `nimble test`
does not exist. When the first test is written, follow the repo-wide convention in
[`../../AGENTS.md`](../../AGENTS.md) and
`common_libs/test_framework/README.md`: `tests/config.nims` with
`--path:"../../common_libs"`, one `test<concern>.nim` per concern, a `test` task
in the `.nimble`, and a guard-first block so tests pass with no Java present.
## Coordinates & angles (source: robocode.dev/articles/coordinates-and-angles.html)
Source: https://robocode.dev/articles/coordinates-and-angles.html (Tank Royale docs)
- Cartesian coordinate system; (0, 0) is the bottom-left corner of the arena.
- Y up is implied by the origin being bottom-left (page never states it explicitly); X east is confirmed via the angle rules below.
- Angles follow classic trig (unlike original Robocode, whose 0/360 was north and 90 east).
- 0°/360° = east; 90° = north; 180° = west; 270° = south.
- Positive angles go counterclockwise; turning right decreases the angle (clockwise).
- Full turn = 360°.
- NOT stated on this page: distance formula, bearing/angle-between-two-points formula, angle normalization/wrapping, worked example numbers.
## Behaviour diagrams
**CURRENT STATE, not a design sketch.** These describe the code as it is today.
**Diagram 1 — one tick. Owned by `DevControlBot/DevControlBot.nim` (`run`, lines
34-40), `DevControlBot/modules/radar.nim` (`onScan`, `commandRadar`) and
`DevControlBot/modules/tfil.nim` (`computeMove`) — update this diagram when any of
those files changes.** The ordering is the whole point: the commands are issued
BEFORE `go()` so they travel with this tick's intent, and events arrive AFTER, so
a scan or an incoming bullet can only ever steer the NEXT tick.
```mermaid
sequenceDiagram
participant Run as run loop
participant Radar as radar.nim
participant Bot as bot + API
participant Srv as server
Run->>Radar: commandRadar<br/># one command, every tick, no idle branch
Radar-->>Bot: setRadarTurnRate<br/>LOCK turn + 5deg overshoot,<br/>or +45deg sweep
Run->>Bot: go<br/># intent sent here, FIRST
Bot->>Srv: tick intent<br/>radar turn + move,<br/>no fire
Srv-->>Bot: tick result<br/>+ pending ScannedBotEvent
Bot->>Radar: onScannedBot -> onScan x, y<br/># AFTER go: remembers only
Radar-->>Radar: target position stored,<br/>tick counter reset
Note over Run,Radar: that remembered target is used<br/>by the NEXT commandRadar
```
**Diagram 2 — radar behaviour. Owned by `DevControlBot/modules/radar.nim`
(`commandRadar`, lines 70-81) — update this diagram when that file changes.**
SWEEP is not a separate lifecycle: it is the same single command the lock
replaces, so switching costs no ticks.
```mermaid
stateDiagram-v2
[*] --> SWEEP
state "SWEEP<br/>360 sweep at 45 deg/tick,<br/>full revolution every 8 ticks" as SWEEP
state "LOCKED<br/>servo onto target bearing<br/>PLUS 5 deg overshoot" as LOCKED
SWEEP --> LOCKED: "getEnemyCount is 1<br/>AND target seen within<br/>FreshScanTurns 1"
LOCKED --> SWEEP: "enemy count is not 1,<br/>or target stale beyond 10 ticks,<br/>or lost"
LOCKED --> LOCKED: "scan every tick<br/>because the radar crosses<br/>the bearing"
```
The 5 deg overshoot is the reason the lock works: the radar sweeps ACROSS the
bearing instead of parking on it, so a fresh `ScannedBotEvent` arrives every
tick. Turning by the bare error, or holding at rate 0 inside a deadzone, stops
the scans and loses the target until a sweep re-finds it. Never replace the
overshoot with a deadzone hold.
## Physics (source: robocode.dev/articles/physics.html)
Source: https://robocode.dev/articles/physics.html (Tank Royale docs)
- Turns/rounds 1-based; each round restarts at turn 1. Distance units: floating-point double.
- Acceleration: +1 unit/turn; deceleration: 2 units/turn (braking 2x faster than accelerating).
- Speed: v = a * t; max speed 8 units/turn. Velocity direction == bot heading.
- Distance: d = v * t.
- Rotation in degrees. Base max turn rate: 10 - 3/4*|v| deg/turn (10 deg/turn standing still; 4 deg/turn at max speed 8).
- Gun rotation max 20 deg/turn (added to bot's current rate).
- Radar rotation max 45 deg/turn (added to gun's current rate).
- Firepower: min 0.1, max 3; energy cost subtracted from bot energy.
- Bullet damage: 4 * firepower, plus 2 * (firepower - 1) if firepower > 1.
- Bullet speed: 20 - 3 * firepower units/turn (19.7 at fp 0.1; 11 at fp 3); constant per shot.
- Gun heat gain: 1 + firepower/5. Cannot fire while heat > 0. Gun starts at heat 3 each round.
- Energy gain on bullet hit: 3 * firepower.
- Collision with bot/wall stops the bot, except when moving away from the bot that hit it.
- Bot-vs-bot collision: 0.6 damage to each.
- Ramming (moving forward into another bot): both take damage; rammer gets ramming kill bonus. Wall damage: |v|/2 - 1, clamped at 0 if negative.
- NOT stated on this page: coordinate system/axes/units, Y up or down, angle origin & clockwise/CCW sense, distance/bearing formulas, angle normalization/wrapping, max energy, per-turn energy regain from inactivity.
@@ -0,0 +1,9 @@
{
"name": "DevControlBot",
"version": "1.2.0",
"authors": ["Davide Cappellini"],
"description": "Control skeleton bot — does nothing, bright colors",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
@@ -0,0 +1,261 @@
## DevControlBot — 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 modules/radar
import modules/tfil
import modules/ELM/elm_gun
import 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 DevControlBot* = 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 newDevControlBot*(): DevControlBot =
result = DevControlBot()
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: DevControlBot, 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: DevControlBot, 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: DevControlBot, e: BulletHitBotEvent) =
bot.mover.noteDamageDealt(e.damage)
method onGameStarted*(bot: DevControlBot, 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: DevControlBot, e: RoundEndedEventForBot) =
inc bot.roundNo
bot.enemies = @[]
bot.shotsFired = 0
bot.mover.resetRound()
method buildBelief(bot: DevControlBot, 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: DevControlBot) =
# 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: DevControlBot): 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: DevControlBot) =
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: DevControlBot) =
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 DevControlBot/DevControlBot.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 / "DevControlBot.json"
var bot = newDevControlBot()
start(bot, jsonPath)
@@ -0,0 +1,256 @@
# Package
version = "1.2.0"
author = "Davide Cappellini"
description = "DevControlBot — 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 DevControlBot.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 $DEVCONTROLBOT_STATUS_FILE,
# which DevControlBot.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.
#
# DevControlBot.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="${DEVCONTROLBOT_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 "[devcontrolbot] COMPILE BLOCKED: dependency '$pkg' is not installed." >&2
echo "[devcontrolbot] fix with: nimble install $pkg" >&2
die $EXIT_NO_DEPS
fi
echo "[devcontrolbot] dependency $pkg -> $pkgdir"
DEPS="$DEPS '--path:$pkgdir'"
done
# Build mode: $DEVCONTROLBOT_DEBUG is set to "debug" by DevControlBot.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="${DEVCONTROLBOT_DEBUG:-release}"
# Compile-time Nim defines, stripped from the caller's argv by DevControlBot.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="${DEVCONTROLBOT_DEFINES:-}"
if [ -n "$DEFINES" ]; then
echo "[devcontrolbot] compile-time defines: $DEFINES"
fi
BUILD_DIR="$(mktemp -d "${TMPDIR:-/tmp}/devcontrolbot.XXXXXX")"
BINARY="$BUILD_DIR/DevControlBot"
# ---- 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 DevControlBot.sh, so it applies both
# to `./DevControlBot.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.
# - $DEVCONTROLBOT_ENV_FILE overrides the default path (".env" next to the
# .nimble, which is the cwd because DevControlBot.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 ./DevControlBot.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="${DEVCONTROLBOT_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 "[devcontrolbot] env file loaded: $ENV_FILE (names added:${ENV_ADDED:- none}; values never printed)"
echo "[devcontrolbot] variables already in the environment win and were left untouched"
else
echo "[devcontrolbot] 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 "[devcontrolbot] 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 "[devcontrolbot] compiling DevControlBot.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" DevControlBot.nim >"$LOG" 2>&1
compile_rc=$?
cat "$LOG"
else
echo "[devcontrolbot] compiling DevControlBot.nim -> $BINARY"
eval nim c -d:release $DEFINES --hints:off $DEPS --out:"$BINARY" DevControlBot.nim >"$LOG" 2>&1
compile_rc=$?
fi
if [ $compile_rc -ne 0 ]; then
if [ "$BUILD_MODE" != "debug" ]; then
echo "[devcontrolbot] --- compiler output ---" >&2
cat "$LOG" >&2
echo "[devcontrolbot] --- end compiler output ---" >&2
fi
echo "[devcontrolbot] COMPILE FAILED (nim c exited $compile_rc) — errors above." >&2
die $EXIT_COMPILE
fi
rm -f "$LOG"
if [ "$BUILD_MODE" = "debug" ]; then
echo "[devcontrolbot] build ok (debug)"
else
echo "[devcontrolbot] 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 "[devcontrolbot] using caller-supplied metadata: $1"
"$BINARY" "$@"
else
# NOTE: no `exec` here: the shell must survive so the EXIT trap can clean up.
echo "[devcontrolbot] running $BINARY DevControlBot.json $*"
"$BINARY" DevControlBot.json "$@"
fi
bot_rc=$?
if [ $bot_rc -ne 0 ]; then
echo "[devcontrolbot] 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 "[devcontrolbot] No game server on ${SERVER_URL:-ws://localhost:7654} (SERVER_URL)." >&2
echo "[devcontrolbot] Start the Tank Royale server, or point SERVER_URL at a running one." >&2
else
echo "[devcontrolbot] 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) & " devcontrolbot " & 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 DevControlBot.
#
# Thin wrapper: all build/run/cleanup logic lives in the `runBot` nimble task
# of DevControlBot.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: DevControlBot.sh [--debug] [-d:<define>[=<value>]]... [<metadata.json>] [extra args]
#
# (no args) RELEASE build + run with the bundled DevControlBot.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 $DEVCONTROLBOT_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 $DEVCONTROLBOT_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 DevControlBot.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 DEVCONTROLBOT_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 DEVCONTROLBOT_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}/devcontrolbot.status.XXXXXX")"
export DEVCONTROLBOT_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 `DevControlBot/`), or `nim c -r tests/test_elm.nim` from `DevControlBot_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 (DevControlBot.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 DevControlBot.
##
## 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))
+6
View File
@@ -0,0 +1,6 @@
1. Create a tidy Bot garage folder
2. Make inside a folder ready to be exported and shared with others
3. Create a basic bot with all white colors and does nothing else
4. make a nice runnable in bash script fro the RT official launcher
5. add nice radars: 1vs1 and melee
5. decide the gun to develop
+768
View File
@@ -0,0 +1,768 @@
# DevControlBot
Control skeleton bot: it boots, participates in the battle, and drives **no
movement and no gun**. The radar is the only driven part.
All radar logic is **one module**, `modules/radar.nim` (90 lines including its
comments; two procs, three variables, three constants). `run()` just calls
`commandRadar()`.
**Two commands, one decision.** Exactly one enemy alive *and* a target in hand ->
**lock** (servo onto the target's bearing). Anything else -> **sweep** at
`MaxRadarTurn` = 45 deg/tick, the radar's physical cap, i.e. a full revolution
every 8 turns. The sweep does double duty and needs no separate "melee" mode: it
is both the search when no target is in hand and the right answer for 2+ enemies
(a full revolution re-scans every enemy as fast as the physics allow, and locking
one of several is worthless). The choice is made from the API's
`getEnemyCount()` (bot.nim:166, from `tick.botState.enemyCount`, bot.nim:1295;
field at schemas.nim:134) every tick — the server's alive count, so it cannot
drift and it shrinks by itself when an enemy dies. No counter, no seen-id set, no
mode enum, no dispatch table.
**There is never a tick without a command.** `commandRadar()` ends in
`setRadarTurnRate(...)` on *every* path — the sweep is not a state the lock falls
back *into*, it is the single command the lock replaces. Switching costs zero
turns, in either direction, by construction.
**The lock works because of the 5° overshoot.** The commanded rate is the delta
from the radar's *current* heading to the target's bearing, plus 5° **past** it
in the direction of the turn, clamped to ±45. So the radar sweeps *across* the
bearing every tick instead of settling on it — which is what produces a fresh
`ScannedBotEvent` every tick. (Turning by the bare error, or holding inside a
deadzone, parks the radar on the bearing: the scans stop and the target has to be
re-found by the sweep, which is the delay this design removes. The `setRescan()`
trick this used to need is unnecessary here — the radar is never idle.) The
bearing is recomputed from the target's remembered **absolute position** each
tick, so the lock keeps correcting a target, and a radar, that have moved.
**Lost-target safety.** `scanlessTicks` counts the ticks since the target was last
scanned (reset by every scan) and `FreshScanTurns = 10` is how long a remembered
target stays usable — one sweep revolution plus slack. This can never throw a
good lock away: a working lock re-scans its target *every* tick, so the counter
never gets past ~1. It only bites on a target unseen for a while, where locking
would slew blindly at a stale point; the sweep re-finds it within one revolution
instead. The target is then dropped and the sweep resumes on the same tick.
`onScannedBot` is a one-liner — `onScan(e.x, e.y)` — and issues no command:
`go()` sends the tick's intent *before* dispatching the pending events, so
commanding first means the command is part of THIS tick's intent, while
`onScannedBot` only feeds the next one.
Angles are **0° = east, positive = counter-clockwise = turn LEFT**: proven from
the installed API — `directionTo` is `180 * arctan2(dy, dx) / PI`
(utils.nim:146-165, its "0 = North" doc comment contradicts its own code), and
`setTurnRadarLeft` sets a positive rate while `setTurnRadarRight` is
`setTurnRadarLeft(-degrees)` (bot.nim:1062-1070).
**Provenance.** The design is ModularBot's (Davide Cappellini, Apache-2.0), i.e.
`common_libs/radar_lock/radar_lock.nim` (`doRadar`, which is where the overshoot
comes from) and `common_libs/radars/melee_scan.nim`, picked per tick exactly this
way in `ModularBot.nim`: `let targetMode = if getEnemyCount() == 1: 0 else: 1`.
`common_libs/` is never edited in place.
**Measured** (1 round each, RadarSpy observer; scans/turn, idle = turns with no
radar command, max gap = longest run of turns without a scan):
| battle | version | scans/turn | idle turns | max scan gap |
|---|---|---|---|---|
| 1v1 Walls | before | 0.513 | **391 / 509** | **33 turns** |
| 1v1 Walls | now | **0.960** | **0** | **1 turn** |
| vs 2 adversaries | before | 0.256 | 0 | 8 |
| vs 2 adversaries | now | 0.278 | 0 | 8 |
| vs 2 adversaries (3 bots, mixed) | before | 0.462 | 233 | 32 |
| vs 2 adversaries (3 bots, mixed) | now | 0.548–0.644 | **0** | **8** |
The 2-enemy rows are identical by construction (both versions issue the same
45 deg/tick sweep). When the count drops to 1 mid-round the new radar is
acquiring again within 6 turns and never parks; the old one took 29 turns and
sat at rate 0 for 26 of them.
The radar keeps moving forever: sweeping at full rate until an enemy is
scanned, servoing onto it while it is the only one alive, spinning at the cap as
soon as a second one is alive, and dropping straight back to the lock when one of
them dies. All of it is in `DevControlBot/modules/radar.nim`.
Body, turret, gun and radar all start plain **white**, which by team convention
means "not programmed yet". The radar then claims its **own** colours when it
starts working: `initRadar()` (`DevControlBot/modules/radar.nim`) paints the radar
and the scan arc **black** — black = "programmed and running" — while
body/turret/gun stay white (this bot never moves and never fires). Colors are set
**once** (startup + radar init), never inside the tick loop.
## Layout
```
DevControlBot_garage/
├── AGENTS.md
├── README.md
└── DevControlBot/
├── DevControlBot.nim # bot type + entry point (isMainModule)
├── DevControlBot.json # bot metadata
├── DevControlBot.nimble # the single `runBot` task
├── DevControlBot.sh # BotLauncher entry point
└── .env # OPTIONAL local config (secrets; never commit)
```
There is no `src/`, no `tests/`, no `out/`, no `config.nim`, no `nimble.paths`
and no vendor directory. `DevControlBot.nim` is both the bot implementation and
the program entry point.
## Dependencies
Only two, both installed **globally** with Nimble and resolved from the global
package store — nothing vendored, no `nimble.paths`, no `nimble develop`:
- `robocode_tankroyale_botapi >= 1.0.7` (the renamed `tankroyale_botapi`)
- `jsony >= 1.1.5`
```sh
nimble install robocode_tankroyale_botapi
```
The `runBot` task asks Nimble where each of those packages actually lives
(`nimble path <pkg>`) and passes explicit `--path:` flags to `nim c`. This is
required because the compiler's own `nimblepath="$home/.nimble/pkgs2/"` only
works when `$HOME` is set — with an empty environment (`env -i`, Nix build
sandbox, CI) the packages are otherwise not on the search path. If a package is
not installed, the build stops with `run: nimble install <pkg>` instead of a
compiler error.
## Run
```sh
./DevControlBot/DevControlBot.sh
```
`DevControlBot.sh` is the **BotLauncher entry point**. It is a thin wrapper: it
locates itself, `chdir`s to the directory holding the `.nimble` file, forwards
arguments and signals to `nimble runBot`, and propagates the real exit code.
All build/run/cleanup logic lives in the `runBot` task of `DevControlBot.nimble`,
which creates a throwaway `mktemp -d` build dir, compiles there, runs, and always
removes the dir via an `EXIT`/`INT`/`TERM` trap. **Nothing is left behind** — this
bot never creates an `out/` directory.
`runBot` also accepts a metadata path: **as the first positional argument**. If it
ends in `.json` it is used instead of the bundled `DevControlBot.json`; there is
no `--json` flag (an argument that does not end in `.json` is forwarded to the bot
as-is).
```sh
./DevControlBot/DevControlBot.sh # bundled metadata (default)
./DevControlBot/DevControlBot.sh /path/to/my.json # alt metadata
./DevControlBot/DevControlBot.sh --debug /path/to/my.json # alt metadata, debug build
```
With **no arguments at all** the wrapper does *not* print usage: it performs a
quiet RELEASE build and runs the bot with the bundled `DevControlBot.json`,
exactly as if that path had been passed. Usage is printed **only** for an
explicit `-h` / `--help` (exit 0, nothing is built).
## Configuration comes from the environment — the API's own mechanism
No configuration code exists in `DevControlBot.nim`, and none is needed. The
bot API reads its own environment variables inside `start()`:
| variable | read at | default |
|---|---|---|
| `SERVER_URL` | `robocode_tankroyale_botapi.nim:424` (documented at `:396`) | `ws://localhost:7654` |
| `SERVER_SECRET` | `robocode_tankroyale_botapi.nim:425` | `""` |
| `BOT_NAME`, `BOT_VERSION`, `BOT_AUTHORS`, … | `bot_info.nim:117-130`, used only when no JSON is found | see that file |
This is the supported mechanism the official BotLauncher uses: it puts those
variables in the bot's process environment before starting the binary. So the
only thing the build/run wrapper does is make sure the variables are *present*
in the bot's environment for local runs.
## Optional `.env` (a convenience for local runs only)
`DevControlBot/.env` is **optional**, and in this checkout it is empty (0 bytes):
it sets no `SERVER_URL` and no port at all. So no `.env` disabling or editing is
needed to run against the Tank Royale GUI, whose default port is 7654 — the same
as the API default below. If it is absent nothing happens: no error,
no warning beyond one informational line, the run behaves exactly as before and
the API defaults apply. It is not required, not generated, and not committed.
When present it is loaded by the **`runBot` task**, not by `DevControlBot.sh`, so
it applies identically to `./DevControlBot.sh` and to a direct `nimble runBot`
and the wrapper stays a thin wrapper. Properties:
- **Format:** plain `NAME=value` and `export NAME=value` lines; blank lines and
`#` comments ignored; anything that is not a simple `NAME=value` identifier
assignment is ignored (a `.env` can never smuggle in a command).
- **CRLF tolerant:** `CR` characters are stripped, so a Windows-edited file does
not turn the value into `bar\r`.
- **Nothing is ever printed.** Only the *names* taken from the file are reported,
never a value, and `set -x` is not used.
- **Overridable path:** `$DEVCONTROLBOT_ENV_FILE` points the loader at a
different file (useful for testing).
### Precedence: the environment always wins
A variable **already present in the environment is never overridden** by the
`.env` file. This matters because the official BotLauncher's values must win:
if a `.env` sitting in the checkout could overwrite them, this convenience would
silently break a real BotLauncher run.
The `.env` file is therefore **not** simply sourced — sourcing it would do the
opposite, because an assignment in a sourced file overwrites an already-exported
variable of the same name. Instead 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 possibly empty*, not merely
non-empty), and only the still-unset names are then exported with `set -a` and
sourced. The filtering is what implements the precedence.
```sh
SERVER_URL=ws://host:1234 ./DevControlBot.sh # shell wins, .env ignored for SERVER_URL
./DevControlBot.sh # .env supplies SERVER_URL
```
`.env` contains secrets, so it must never be committed; see the note in
[AGENTS.md](AGENTS.md) about the root `.gitignore`.
## Build modes: release by default, `--debug` for the classic build
| invocation | build | output |
|---|---|---|
| `DevControlBot.sh …` (default) | `nim c -d:release --hints:off` | quiet: dependency lines, one `build ok (release)`, one `running` line |
| `DevControlBot.sh --debug …` | plain `nim c` | classic diagnostics: `Hint: used config file …`, dot-progress line, `DEBUG BUILD` hint |
### Debug graphics (TFIL heat field & decisions)
Off in the default build. Turn on with the `tfilDebug` define:
```
cd DevControlBot && nim c -d:release -d:tfilDebug \
--path:"$(nimble path robocode_tankroyale_botapi | head -1)" \
--path:"$(nimble path jsony | head -1)" DevControlBot.nim
```
Drawn each tick as an SVG overlay by the client: per-tile lava heat (colour ramp
+ value), tracked bullets and their danger corridors, enemy core/aura, the
reachable hull, blocked vs safe tiles, the committed tile, the bot's own tile
and the target line.
`--debug` is stripped by the wrapper wherever it appears in the arguments (a
repeated `--debug` is harmless) and is handed to the `runBot` task via the
exported env var `$DEVCONTROLBOT_DEBUG` (`debug` / `release`) rather than as a
task argument: an env var can never be mistaken for a bot argument, cannot
collide with the `$DEVCONTROLBOT_STATUS_FILE` exit-code mechanism, and leaves the
task's argument parsing untouched. Every other argument is forwarded verbatim.
In release mode the compiler's stdout/stderr is captured to a log and replayed
**only if the build fails**, so a failed build is always loud in both modes while
a successful release build stays short (10 lines including the no-server report,
vs 16 with `--debug`). `--help` / `-h` prints usage and exits 0 **without
building**; no arguments does the opposite — it builds and runs.
The bot needs a running Tank Royale server at `SERVER_URL` (the API's documented
default is `ws://localhost:7654`); without one the run fails with
`[start] Cannot connect to <SERVER_URL>` and exits 1 (expected during local
verification).
## Failure reporting and exit codes
Nimble's `exec` raises a NimScript exception — stack trace, escaped copy of the
whole script — for *any* non-zero exit, which made "no game server" look like a
catastrophic build crash. The `runBot` shell therefore always exits 0 and writes
the real code to the status file named by `$DEVCONTROLBOT_STATUS_FILE`, which
`DevControlBot.sh` exports and then re-exits with. The real code is preserved,
not masked.
| exit | meaning |
|---|---|
| `0` | clean run |
| `1` | bot could not connect to the game server at `SERVER_URL` (expected locally) |
| `2` | a dependency is not installed — `nimble install <pkg>` |
| `3` | compilation failed — the compiler's own errors are printed above |
| other | the bot's own exit code (runtime crash, bad metadata) |
Each mode prints its own short line, e.g.
```
[start] Cannot connect to ws://localhost:7654: Connection refused
[devcontrolbot] bot exited with code 1.
[devcontrolbot] No game server on ws://localhost:7654 (SERVER_URL).
[devcontrolbot] Start the Tank Royale server, or point SERVER_URL at a running one.
```
No `Exception raised during nimble script execution`, no stack trace, no source
dump. `nimble runBot` run directly (no status file) keeps the old behaviour and
still raises.
Interrupt handling is unchanged: SIGINT/SIGTERM are forwarded, the build dir is
removed by the `EXIT` trap and the wrapper exits 143 (SIGTERM) / 130 (SIGINT).
## Gotcha: `nimble runBot` must be run from `DevControlBot/`
The `.nimble` file lives in `DevControlBot/`, so the task is only visible from
there:
```sh
cd DevControlBot && nimble runBot # works
cd DevControlBot_garage && nimble runBot
# Error: Could not find a file with a .nimble extension inside the specified
# directory: .../DevControlBot_garage
```
`DevControlBot.sh` handles this for you by `cd`-ing itself. Note also that
`compile`/`build` are reserved Nimble builtin names — hence the `runBot` name.
## Test
There are **no tests** in this garage. The `test` task and the `tests/` directory
were removed along with the old build layout; see
## Movement-prediction gun
The gun predicts **where the enemy will actually be when the bullet arrives**.
The old model predicted the opponent's aim error (how far *their* shots missed a
correct intercept); using that as our own correction made the gun aim like the
opponent, which is why it added a constant +1.6°..+11.5° bias and lost to the
plain geometric gun. That path is deleted (`train_elm_gun.nim` removed,
`extract_realistic.py` marked deprecated). The base geometric intercept is still
the base lead (`heuristicAim`); the ELM now refines it with a movement
prediction.
### The label
For every sampled tick (shooter fixed to DevControlBot, power 2, bullet speed
`20 - 3*2 = 14`, so shooter state and bullet speed match the live gun):
* **base** = the plain geometric intercept bearing from the enemy's current
scan-based position/velocity (the same `heuristicAim`);
* **true** = bearing to the enemy's ACTUAL position at the tick the bullet
reaches it, solved by fixed-point iteration against the observer's true
trajectory;
* **label** = `wrap(true - base)`.
Generated by `tools/elm_bench/extract_predict.py` (stride 5) over
`data/drussgt_raw` + `data/generalization_raw` into `samples_predict.ndjson`
(53 980 samples, 9 opponents, gitignored and reproducible).
| | mean | sd | p5 | median | p95 |
|---|---|---|---|---|---|
| label | **-0.329°** | 18.322° | -32.68° | -0.35° | +32.81° |
**Centred near zero.** The old opponent-bias label had a large systematic offset
(+0.042 rad = +2.4°); this one does not (-0.006 rad = -0.33°). On a target that
holds its line the label is 0; only real turning/acceleration moves it.
### Features (`elm_features.nim`, 32-D)
Enemy-motion-centric: 7 newest-to-oldest scan-to-scan displacement vectors (each
divided by its own tick gap, /16), newest/mean/sd speed, heading sin/cos, turn
rate sin/cos, curvature, plus the single-frame geometry (distance, relative
bearing, own speed, bullet speed, time of flight, `predErr`, lateral velocity,
closing speed, LOS rate). The motion window (`WinCap = 8`) is fed from
`modules/radar.nim`'s new scan buffer. One definition is shared verbatim by the
trainer and the gun.
### Training (`train_predict.nim`, 5 round-group folds, pooled held-out)
| model | RMSE | MAE | medAE | predMean |
|---|---|---|---|---|
| plain intercept (correction 0) | 0.31983 | 0.23227 | 0.15208 | 0 |
| constant mean | 0.31978 | 0.23219 | 0.15173 | -0.00577 |
| ELM H=256 λ=1e-2 | **0.23101** | **0.18174** | **0.14966** | **-0.00631** |
| ELM H=128 λ=1e-2 | 0.23934 | 0.19052 | 0.15856 | -0.00630 |
The ELM beats the plain intercept by **-27.8% RMSE** and beats a constant by the
same. Its output mean is **-0.0063 rad (-0.36°)** — the centring failure of the
old model is gone. (H=64: RMSE 0.24895.)
### Confidence gate
The correction is applied only when `|correction| > GATE_TAU`, else the gun
returns the exact geometric aim. `GATE_TAU = 0.10 rad (5.7°)`, the largest
0.05-grid threshold whose gated RMSE stays within 2% of the un-gated model:
**open-rate 61.4%**, gated RMSE 0.23348 (-27.0% vs the intercept). The offline
optimum is `tau = 0` (the model helps at every magnitude), so the gate is a
conservative filter for the small/noisy corrections, not a performance device.
### Real battles — 20 rounds each, RawRecord observer ground truth, all CONTIGUOUS
Damage per round is primary. `won/rd` = rounds where DevControlBot ranked first.
| opponent | gun | shots | hits | hit% | damage | dmg/rd | won/rd |
|---|---|---|---|---|---|---|---|
| DrussGT | geometric | 547 | 6 | 1.1% | 60 | 3.0 | 0/20 |
| DrussGT | ELM-gated | 656 | 16 | 2.4% | 160 | **8.0** | 0/20 |
| CassiusClay | geometric | 357 | 1 | 0.3% | 10 | 0.5 | 0/20 |
| CassiusClay | ELM-gated | 427 | 14 | 3.3% | 140 | **7.0** | 0/20 |
| Komarious | geometric | 356 | 29 | 8.1% | 290 | 14.5 | 0/20 |
| Komarious | ELM-gated | 550 | 95 | 17.3% | 950 | **47.5** | **10/20** |
| Phoenix | geometric | 350 | 3 | 0.9% | 30 | 1.5 | 0/20 |
| Phoenix | ELM-gated | 447 | 8 | 1.8% | 80 | **4.0** | 0/20 |
Damage per *shot* also rises (DrussGT 0.11 -> 0.24, Komarious 0.81 -> 1.73):
the gain is accuracy, not just volume.
Aim error at fire versus the **TRUE impact point** (deg; reference solved against
the observer's true trajectory, so lead is not counted as error — this is not the
constant-velocity reference printed by `score_battles.py`):
| opponent | gun | n | mean | median | sd |
|---|---|---|---|---|---|
| DrussGT | geometric | 542 | -2.56 | -12.13 | 33.96 |
| DrussGT | ELM-gated | 647 | -4.27 | -9.24 | **23.39** |
| CassiusClay | geometric | 341 | -1.70 | -3.56 | 40.64 |
| CassiusClay | ELM-gated | 413 | -2.96 | -6.20 | **29.11** |
| Komarious | geometric | 352 | 0.62 | -1.61 | 23.49 |
| Komarious | ELM-gated | 529 | -2.66 | -2.05 | **12.96** |
| Phoenix | geometric | 331 | 0.92 | 5.38 | 41.55 |
| Phoenix | ELM-gated | 426 | -1.91 | 0.10 | **28.38** |
The ELM cuts the aim-error spread by 30-45% against every opponent.
### Bottom line
**Yes — with the movement label the ELM now beats the plain intercept in real
battles**, on damage/round against all four opponents (2.7x..14x), with a higher
hit rate, more damage per shot, one 10/20 round win vs Komarious, and a
30-45% smaller true-impact aim-error spread. The old model's fatal constant bias
is gone (predMean -0.36° vs +2.4°).
Honest caveats: these four opponents are *in* the pooled training corpus (same
bots, different recording), so this is not a held-out-opponent generalisation
claim; the absolute hit rate against DrussGT is still only 2.4%. The gain is
real but the gun is still weak.
### Files and reproduction
| file | what |
|---|---|
| `DevControlBot/modules/ELM/elm_features.nim` | the 32-D enemy-motion feature vector (shared trainer/gun) |
| `DevControlBot/modules/ELM/elm_gun.nim` | geometric `heuristicAim`, ELM correction, gate, weights loader |
| `DevControlBot/modules/radar.nim` | scan buffer (window of the last 8 scans) |
| `DevControlBot/modules/ELM/elm_gun_weights.txt` | exported weights + `GATE_TAU` |
| `tools/elm_bench/extract_predict.py` | relabel: true-impact correction corpus |
| `tools/elm_bench/train_predict.nim` | 5-fold eval, baselines, gate calibration, export |
```sh
cd DevControlBot_garage/DevControlBot
python3 ../../tools/elm_bench/extract_predict.py /tmp/samples_predict.ndjson \
../../data --stride=5
nim c -r --hints:off --path:. ../../tools/elm_bench/train_predict.nim /tmp/samples_predict.ndjson
nim c -d:release --out:/tmp/DevElm DevControlBot.nim # ELM-gated gun
nim c -d:release -d:baselineGun --out:/tmp/DevBase DevControlBot.nim # intercept only
# battles: java -cp tools/raw_recorder/out:$RUNNER_JAR RawRecord \
# --dir /tmp/rec --rounds 20 --bot <DevElm dir> --bot <opponent dir>
python3 tools/elm_bench/score_battles.py /tmp/rec_Elm_DrussGT /tmp/rec_Base_DrussGT
```
## Sample-bot gate (held-out opponents)
**Question.** The movement-prediction ELM beat the geometric intercept by
2.7x–14x on DrussGT, CassiusClay, Komarious and Phoenix — but all four are *in*
the pooled training corpus. Do the gains survive on bots the model has never
trained on? This is the first genuine held-out-opponent test.
**Method.** The 13 runnable Nim sample bots from `tr_bots/` (`SAMPLE_BOTS.md`;
`MyFirstTeam` skipped, it is a team container). Each fought both arms for 10
rounds, RawRecord observer ground truth: `Base` = `-d:baselineGun` (pure
intercept), `ELM` = default build. The ELM arm additionally carries
`-d:gunLog`, a logging-only define that changes no gun behaviour, so the raw
per-shot corrections (and therefore the gate state) could be read. All 26
recordings `query.py --verify`: **CONTIGUOUS, no drops, no dups**. Build:
`nim c -d:release [-d:baselineGun|-d:gunLog]`.
### Damage per round (primary)
Most sample bots are so weak that both arms kill them every round, so this
metric saturates at the ~100–110 dmg/rd ceiling. The un-saturated rows are the
moving/beatable bots (Crazy, MyFirstBot, MyFirstLeader, SpinBot, Walls).
| sample bot | intercept dmg/rd | ELM dmg/rd | delta | won/rd int / ELM |
|---|---:|---:|---:|---:|
| Corners | 93 | 93 | 0 | 10/10 / 10/10 |
| Crazy | 64 | 73 | **+9** | 10/10 / 10/10 |
| Fire | 105 | 105 | 0 | 10/10 / 10/10 |
| MyFirstBot | 74 | 90 | **+16** | 10/10 / 8/10 |
| MyFirstDroid | 110 | 110 | 0 | 10/10 / 10/10 |
| MyFirstLeader | 70 | 42 | **−28** | 10/10 / 9/10 |
| PaintingBot | 85 | 85 | 0 | 10/10 / 10/10 |
| RamFire | 98 | 99 | **+1** | 10/10 / 10/10 |
| SpinBot | 45 | 43 | **−2** | 4/10 / 0/10 |
| Target | 105 | 108 | **+3** | 10/10 / 10/10 |
| TrackFire | 105 | 92 | **−13** | 10/10 / 10/10 |
| VelociBot | 100 | 98 | **−2** | 9/10 / 9/10 |
| Walls | 63 | 59 | **−4** | 10/10 / 10/10 |
**ELM beats intercept on 4/13, ties 4/13, loses on 5/13. Median delta 0.0
dmg/rd; mean delta −1.5.** Pooled over all 13: intercept 11170 damage / 3728
shots / 30.0% hits; ELM 10970 / 3688 / 29.7% — the ELM is **1.8% worse in
aggregate**.
### Gate open-rate per battle
Gate open = `|correction| > GATE_TAU (0.10 rad)` at an actual shot (read from
the `-d:gunLog` stream).
| sample bot | shots | gate open | rate |
|---|---:|---:|---:|
| Corners | 284 | 173 | 60.9% |
| Crazy | 344 | 267 | 77.6% |
| Fire | 226 | 57 | 25.2% |
| MyFirstBot | 467 | 149 | 31.9% |
| **MyFirstDroid** | **116** | **0** | **0.0%** |
| MyFirstLeader | 484 | 321 | 66.3% |
| PaintingBot | 434 | 188 | 43.3% |
| RamFire | 121 | 44 | 36.4% |
| SpinBot | 592 | 343 | 57.9% |
| Target | 173 | 31 | 17.9% |
| TrackFire | 111 | 15 | 13.5% |
| VelociBot | 396 | 213 | 53.8% |
| Walls | 610 | 472 | 77.4% |
| **all** | **4358** | **2273** | **52.2%** |
The gate opened in 12 of 13 battles (52.2% overall, versus the 61.4% calibration
figure). **Against MyFirstDroid the gate never opened: that ELM arm is
bit-for-bit the intercept arm**, which is why its damage, hits and aim spread
are identical. Every other battle genuinely exercised the correction.
### Comparison with the in-training legacy result (memorization check)
| test | opponents | improved | median delta | verdict |
|---|---|---:|---:|---|
| legacy (in training corpus) | DrussGT, CassiusClay, Komarious, Phoenix | **4/4** | +5.75 dmg/rd (2.7x–14x) | large, consistent gain |
| sample bots (held out) | 13 Nim samples | **4/13** | **0 dmg/rd** | no gain |
On bots it was trained on, the ELM improved every opponent by a large factor; on
bots it has never seen, it is a coin flip that trends slightly negative. **The
legacy gains do not transfer. The most parsimonious reading is that a
substantial part of the legacy result was memorization of those four opponents'
motion, not a general movement-prediction skill.** This echoes the earlier
offline finding that the label law is ≈ `0.87 × lead` — an opponent-shape
idiosyncrasy captured by the corpus, not a universal correction.
### Trivial-bot sanity (stationary / near-stationary cases)
* **Target** (stationary until damaged): intercept 105 → ELM 108 dmg/rd. Not a
regression, but the gain is within the saturation ceiling.
* **Walls** (stationary): intercept 63 → ELM 59 dmg/rd, **−4**. This is the red
flag the gate design is supposed to prevent. Walls does not move, so the true
correction is ~0, yet the gate opens on **77.4%** of shots and the ELM *adds*
a correction: aim spread goes 9.93° → 10.45° sd. The correction is not
trustworthy on stationary targets, and `GATE_TAU` is too low to catch it.
### Bottom line
**No — on bots it has never trained on, the movement-prediction ELM does not
beat the plain geometric intercept.** It wins 4 of 13 sample bots, ties 4,
loses 5, with a median delta of exactly 0 and an aggregate damage 1.8% *below*
the baseline. The large in-training gains reported above are therefore not
evidence of general movement prediction. Two concrete defects are visible: the
gate admits corrections against stationary targets (Walls), and one entire
battle (MyFirstDroid) never opened the gate at all. A null-to-negative held-out
result this clean says the current ELM should not be shipped as an improvement;
the next step is to make the gate/correction honest on non-moving targets before
re-measuring held-out opponents. 10 rounds per bot means the ~±4 dmg/rd rows are
noisy — but no amount of extra rounds turns a median of 0 into a win.
## Online-learning gun
The previous section is the null result that motivates this one: the
**pretrained** cross-opponent model does not generalise (4/13 held-out wins,
aggregate 1.8% worse). This section is the paradigm change it points to —
**learn the opponent in front of you during the battle**, and reset only when
the opponent changes.
### Reset event: `GameStartedEventForBot`, never `RoundStartedEvent`
In Tank Royale a **battle is many rounds against the same opponent**, and that
opponent's movement code does not change between rounds. The bot API delivers
both events distinctly (`onGameStarted` / `onRoundStarted`,
`schemas.nim:202/212`), and the API starts `run()` on the first
`RoundStartedEvent` while firing `onGameStarted` once per battle before it. So
`DevControlBot.onGameStarted` calls `resetOnline()` and `onRoundStarted` does
**nothing**: the model, the pending queue and the gate persist across every
round of a battle and are wiped exactly once, at the start of a new opponent.
(The mean online sample count grows 36 → 642 across the round buckets below,
which is the runtime proof the reset is per-battle, not per-round.)
### Online learning with delayed labels
The label is the same validated one (`wrap(trueImpactBearing -
geometricInterceptBearing)`, `extract_predict.py`). At fire time the true impact
position does not exist yet — it is only knowable once the bullet's flight time
has elapsed. So at every shot the bot enqueues a `PendingShot(feat, base,
selfX, selfY, dueTick = fireTick + round(range / bulletSpeed))`. Each tick
`drainPending(nowTick)` resolves every shot with `dueTick <= nowTick`: it reads
the enemy's **actual** position from a rolling per-tick enemy trace (kept in
`elm_gun.noteEnemyAt`, the nearest trace sample within 3 ticks), computes
`label = wrap(bearing(selfFire -> truePos) - base)`, and feeds one sample to the
ELM (the engine's `decay=0.999`, `refitEvery=25`, the tuning the earlier online
work validated). The queue is keyed by `dueTick`; nothing is trained before the
bullet would have arrived, so there is no future leakage.
### Neutral vs weak prior
Both start from the **same frozen hidden layer** (the pretrained `W`/`hs`); they
differ only in the output layer at `GameStartedEventForBot`:
* **neutral** (`priorScale = 0`, the default): zero `beta`, learns purely online.
* **weak prior** (`-d:elmPrior`): the pooled pretrained `beta`, scaled by 0.1.
Over the 9 held-out sample bots they are **tied within noise**: neutral 88.3
dmg/rd, weak-prior 88.9 (base 70.1). The weak prior is a touch better on the
hard movers (MyFirstLeader 103.5 vs 95.5, MyFirstBot 83.0 vs 76.5) and a touch
worse on the near-stationary ones (VelociBot 83.5 vs 87.0, Walls 68.0 vs 74.0).
Neither is a clear winner; the default is **neutral**, because starting from a
prior that was shown not to generalise risks importing exactly the bias the gate
is meant to catch, and the neutral model reaches the same place within a round.
### Novelty gate: never worse than the intercept by construction
The correction is applied only if **all** of these hold, else the gun returns the
exact geometric aim:
1. `nOnline >= OnlineMinSamples (12)` — no signal at all until the model has seen
real samples for *this* opponent;
2. `modelErr < 0.95 * zeroErr` — the model's **held-out-style** error must beat
what always aiming at the intercept costs. `feedSample` scores the *current*
model against each new label **before** training on it (EMA α = 0.08), so
`modelErr` is a genuine online held-out error and `zeroErr` is the
zero-correction baseline;
3. `|correction| > GATE_TAU (0.10 rad)` — the existing magnitude filter.
`modelErr` only starts moving after the first closed-form refit (25 samples), so
the gate opens conservatively. Measured open-rate (shots where a nonzero
correction was applied), logged with `-d:gunLog`:
| arm | r1–2 | r3–4 | r5–10 | r11–15 | r16–20 |
|---|---:|---:|---:|---:|---:|
| Online open-rate | 36% | 60% | 69% | 68% | 72% |
| Online mean samples | 36 | 110 | 271 | 449 | 642 |
| Prior open-rate | 58% | 64% | 62% | 62% | 56% |
The gate **opens later in the battle** — that is the online learning becoming
genuine signal for the opponent in front of it.
### Damage per round — 20 rounds each, RawRecord ground truth, all CONTIGUOUS
36 recordings (12 opponents × 3 arms), each `query.py --verify` = CONTIGUOUS.
Arms: **Base** = `-d:baselineGun` (pure intercept), **Online** = default
(neutral, online), **Prior** = `-d:elmPrior`. `Δ` is Online − Base.
| opponent | kind | Base | Online | Prior | Δ Online |
|---|---|---:|---:|---:|---:|
| Corners | held-out | 94.0 | 96.5 | 96.0 | +2.5 |
| Crazy | held-out | 58.0 | 72.5 | 76.0 | **+14.5** |
| MyFirstBot | held-out | 49.0 | 76.5 | 83.0 | **+27.5** |
| MyFirstLeader | held-out | 25.0 | 95.5 | 103.5 | **+70.5** |
| SpinBot | held-out | 36.0 | 91.0 | 85.5 | **+55.0** |
| Target | held-out | 103.5 | 102.5 | 103.5 | −1.0 |
| TrackFire | held-out | 99.0 | 99.5 | 101.5 | +0.5 |
| VelociBot | held-out | 95.5 | 87.0 | 83.5 | −8.5 |
| Walls | held-out | 71.0 | 74.0 | 68.0 | +3.0 |
| Komarious | legacy | 21.0 | 33.0 | 27.0 | **+12.0** |
| Phoenix | legacy | 3.5 | 7.5 | 7.0 | +4.0 |
| DrussGT | legacy | 5.5 | 10.5 | 16.5 | +5.0 |
Pooled: held-out 9 bots **70.1 → 88.3 dmg/rd (+26%)**, hit rate 23.5% → 33.0%;
legacy 3 bots **10.0 → 17.0 (+70%)**, 4.6% → 6.6%. Online wins **7/9 held-out**,
loses 2 (Target −1.0, VelociBot −8.5 — both already near the saturation ceiling
at ~95–103 dmg/rd). Note this is a **single 20-round recording per pair**, so the
± few-dmg rows are noisy; the large rows are not.
### The round-index curve — does it improve WITHIN a battle?
Pooled damage/round by round index (clean, log-free builds):
| arm | r1–2 | r3–4 | r5–10 | r11–15 | r16–20 |
|---|---:|---:|---:|---:|---:|
| Base | 65.9 | 74.7 | 67.8 | 69.8 | 65.4 |
| Online | 71.7 | 84.8 | 82.3 | 75.5 | 75.3 |
| Δ Online | +5.8 | +10.0 | +14.6 | +5.7 | +9.9 |
| Δ Prior | +1.4 | +8.8 | +12.5 | +10.2 | +7.6 |
**Yes, the gain grows with rounds seen**, peaking at +14.6 dmg/rd in rounds 5–10
while the gate open-rate climbs 36% → 72% and the model accumulates 36 → 642
samples for the same opponent. The r11–20 rows are noisier (bots die faster once
the gun lands, shortening rounds), but the direction is exactly the online
paradigm working.
### Bottom line
**Yes — online learning beats the plain geometric intercept on opponents it has
never seen.** On 9 held-out Nim sample bots it is +26% aggregate damage/round
(88.3 vs 70.1), higher hit rate (33.0% vs 23.5%), and the advantage grows across
rounds of the same battle (+5.8 → +14.6 dmg/rd as the gate opens). This is the
opposite of the pretrained model's null/negative result above: the model that
does **not** generalise from a corpus does fine when it trains on the opponent
in front of it. Two honest caveats: (1) the two losing rows are opponents the
intercept already kills at ~100 dmg/rd, so there is little headroom and the
losses are within noise; (2) neutral and weak-prior starts are statistically
indistinguishable here, so the win is the **online adaptation**, not the prior.
Reproduce:
```sh
# build the three arms (Base / Online / Prior)
bash tools/elm_bench/run_online_battles.sh Corners Crazy ... Walls Komarious Phoenix DrussGT
python3 tools/elm_bench/analyse_online.py /tmp/gun_exp_clean
```
## Code-review fixes to the online gun
A review flagged five issues in an earlier revision of `elm_gun.nim` /
`radar.nim` / `DevControlBot.nim`. Each was re-checked against the current
code; three held, two were already handled by the rewrite. The three fixes are
behaviour-preserving by construction and were re-measured on the same 9
held-out sample bots.
### What was actually wrong (and what was not)
| # | claim | verdict |
|---|---|---|
| 1 | stale velocity in dead reckoning (unbounded extrapolation) | **confirmed** — `heuristicAim` advanced `b.ex/b.ey` by `vx*age` with no cap |
| 2 | `scanGap()` recorded but never checked | **confirmed literal / partly refuted** — it *is* dead state, but "training on the belief is wrong" is false: delayed-label training is correct. Only extreme gaps are suspect |
| 3 | aim x/y recomputed twice | **confirmed** — baseline and ELM branches each did `cos/sin` |
| 4 | deg/rad landmine at the fire boundary | **refuted as a bug, confirmed as a robustness gap** — the earlier fix already compares degrees to `FireSlopDeg`; it just lacked a named unit + test |
| 5 | inherent 1-tick radar lag | **confirmed, not a bug** — `buildBelief`/`heuristicAim` dead-reckon by `scanAge`, and delayed labels are keyed by `dueTick`; the lag is accounted for |
### The fixes
1. **Bounded dead reckoning** (`DevControlBot.nim`, `MaxDeadReckonTicks = 4`):
`lead = min(age, MaxDeadReckonTicks)` before advancing the last scan. Past a
few ticks a constant-velocity guess diverges; the belief now freezes at the
last seen position instead of running away. Also
**untrustworthy velocity samples** (`radar.nim`, `MaxVelGap = 3`):
`targetVelocity()` returns `(0,0)` when the two scans it averages span more
than 3 ticks, matching the corpus's one-tick-delta convention.
2. **Single coordinate computation** (`elm_gun.nim`, `predictAim`): the learned
correction is folded into one `aim` bearing, then `x`/`y` are derived from
it exactly once.
3. **Explicit unit boundary** (`elm_gun.nim`, `gunAimErrorDeg` + `DevControlBot`
`computeGun`): the one rad→deg conversion now lives in a proc whose *name*
carries the degree unit, replicated API-free so `elm_gun` stays stdlib-only.
`test_online.nim` gains a regression block: a known bearing yields the known
turn command, and the historical `degToRad(FireSlopDeg)` mix-up would reject
a shot that is exactly `FireSlopDeg` off.
### Does the guard actually fire?
Measured from the RawRecord streams: the radar lock re-scans on **99.1%** of
ticks (`scanGap == 1`; 90 923 vs 603 wider gaps over 9 opponents). Shots taken
with a stale belief (>= 2 ticks since the scan) are ~5% of all shots and hit at
~10% versus 36.8% for fresh ones — the stale shots mostly miss, but they are too
rare for the cap to move the aggregate. The guard bites on ~2–3% of shots.
### Re-measurement (3 replicates x 20 rounds per opponent, all CONTIGUOUS)
`OLD` = pre-fix code rebuilt from `HEAD`; `NEW` = with the three fixes. The
single-run protocol in the section above is noisy, so the table is pooled over
60 rounds/opponent.
| arm | OLD dmg/rd | NEW dmg/rd | OLD hit | NEW hit |
|---|---:|---:|---:|---:|
| Base (intercept) | 71.3 | 72.0 | 24.3% | 24.8% |
| Online | 90.3 | 89.7 | 34.9% | 34.1% |
| Δ Online | +19.0 (+26.7%) | +17.6 (+24.5%) | +10.6pp | +9.3pp |
| wins vs Base | 8/9 | 7/9 | | |
The documented single-run baseline (70.1 / 88.3 / 23.5→33.0% / 7-of-9) sits
exactly between the two pooled columns. **Bottom line: the fixes are neutral**
— every row moves by <1 dmg/rd, well inside run-to-run variance. They remove a
latent failure mode without paying for it; they do not improve the gun because
the radar keeps the belief fresh in practice.
+1
View File
@@ -0,0 +1 @@
--path:"../DevControlBot"
+251
View File
@@ -0,0 +1,251 @@
## Unit tests for the ELM module (DevControlBot/modules/ELM/elm.nim).
## Run from DevControlBot_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)
@@ -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 DevControlBot_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"
+34 -2
View File
@@ -226,6 +226,8 @@ TR_RACK_TMSELECT=off # Tsetlin machine used as the shot selector
TR_RACK_TMPATTERN=off # Tsetlin machine used as a pattern matcher
TR_RACK_TMHORIZON=off # horizon Tsetlin automata gun
TR_RACK_LEADGAIN=off # per-range-band learned lead-gain corrector
TR_RACK_KNOWLEDGE=off # learned angular-residual corrector on the lead forecast
TR_RACK_WAVEELM=off # online-ELM learned (x,y) offset on the analytic intercept
# Give every named gun a fixed share of the turns instead of ranking them.
# e.g. TR_RACK_SHARE=PATTERN:60%,HEADON:40% (GUN:weight, comma separated,
# the % sign is optional). Empty = the ranking selector. GOTCHA: every gun you
@@ -236,8 +238,9 @@ TR_RACK_SHARE=
# Drop whole guns by rack id (comma separated, e.g. 16). Empty = keep them all.
# Ids: 0 HEADON 1 LINEAR 2 TSETLIN 3 CIRCULAR 4 GUESSFACTOR 5 PATTERN
# 6 WALLBOUNCE 7 ACCEL 8 STOPSHOT 9 DISPLACE 10 AVGLEAD 11 DECAYGF 12 KNN
# 13 TMSELECT 14 TMPATTERN 15 TMHORIZON 16 LEADGAIN. A disabled gun never even
# spawns a virtual bullet, so its fitness stays empty and it cannot be picked.
# 13 TMSELECT 14 TMPATTERN 15 TMHORIZON 16 LEADGAIN 17 KNOWLEDGE 18 WAVEELM.
# A disabled gun never even spawns a virtual bullet, so its fitness stays empty
# and it cannot be picked.
GUN_RACK_DISABLE=
# ── gun selector (which admitted gun fires this tick) ───────────────────────
@@ -667,6 +670,35 @@ TR_LEADGAIN_ADAPT=32 # NO-OP: the old adapt interval, no longer used
TR_LEADGAIN_CALIB=512 # NO-OP: the old calibration interval, no longer used
TR_LEADGAIN_SEED=20240921 # NO-OP: the old seed, no longer used
# KNOWLEDGE (rack id 17) — the learned additive angular residual on top of the
# self-consistent lead forecast. It answers only the aim angle: no power, no
# fire decision, no target picking.
TR_KNOWLEDGE_MEM= # path of the learned table; EMPTY = memory only
# (nothing is ever written to disk). Set to e.g.
# /tmp/gun_knowledge.bin to persist across battles.
# WAVEELM (rack id 18) — the online-ELM gun. Analytic bullet/target intercept
# (self-consistent flight time) plus a learned (x, y) offset from a recursive
# least-squares ELM trained on the real-shot feedback. Admitted by the rack line
# above only; this gun has NO env knobs of its own — see below.
#
# OFF BY DEFAULT (shipped, like every gun except PATTERN). To enable:
# TR_RACK_WAVEELM=both (also: 1v1 | melee; aliases any/empty->both,
# single/lock->1v1, only1v1->1v1,
# multi/onlymelee->melee, none/disabled/disable->off)
# UNRECOGNISED value warns on stderr and falls back to `both` (GOTCHA: a typo
# ADDS the gun to the rack, it never turns it off).
# FORCED SHARE: TR_RACK_SHARE=WAVEELM:50,PATTERN:50 works, but only if
# WAVEELM is admitted above — a share naming an `off` gun is refused.
# NOTHING TO TUNE FROM HERE: WaveLambda (0.1 ridge), WaveRho (1.02 forgetting),
# WaveIters (20 intercept iterations), WaveMaxResidual, WaveMaxOffset,
# WaveTraceSlots and the ELM seed (42) are `const`s in
# common_libs/guns/waveelm.nim — changing them needs a REBUILD, not an env var.
# No TR_WAVEELME_* variable exists; there is no persisted memory path either
# (the ELM is rebuilt from scratch every battle, unlike KNOWLEDGE).
# Per-shot behaviour for every admitted gun is logged by the shared stats writer
# (GUN_STATS_PATH below).
# PATTERN — the shipped gun, the only one the rack admits.
TR_PATTERN_LEN=10 # ticks of movement history used as the search key
TR_PATTERN_DEPTH=500 # how far back the history scan may reach
+52 -4
View File
@@ -1,5 +1,5 @@
## ModularBot — plugin gun architecture tracer bullet.
## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5), WallBounceGun (6), AccelGun (7), StopShotGun (8), DisplacementGun (9), AveragedLeadGun (10), DecayGFGun (11), KNNGun (12), TmSelectorGun (13), TmPatternGun (14), TmHorizonGun (15), LeadGainGun (16), BitbrainNetGun (17) via GunHarness.
## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5), WallBounceGun (6), AccelGun (7), StopShotGun (8), DisplacementGun (9), AveragedLeadGun (10), DecayGFGun (11), KNNGun (12), TmSelectorGun (13), TmPatternGun (14), TmHorizonGun (15), LeadGainGun (16), KnowledgeGun (17), WaveElmGun (18) via GunHarness.
## Radar: RadarLockModule (1v1) / AdaptiveMeleeRadarModule (2+ enemies), auto-switched per tick.
## Movement: OscillatorModule (perpendicular strafing).
@@ -31,6 +31,8 @@ import guns/tm_selector
import guns/tm_pattern
import guns/tm_horizon
import guns/lead_gain
import guns/gun_knowledge
import guns/waveelm
import movements/phantom_meteor
import movements/rammer
import movements/ram_decision
@@ -158,7 +160,7 @@ let ResultLog* =
block:
let v = getEnv("TR_RESULT_LOG", "1").strip().toLowerAscii()
not (v == "0" or v == "false" or v == "no" or v == "off")
const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern", "WallBounce", "Accel", "StopShot", "Displace", "AvgLead", "DecayGF", "KNN", "TMSelect", "TMPattern", "TMHorizon", "LeadGain"]
const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern", "WallBounce", "Accel", "StopShot", "Displace", "AvgLead", "DecayGF", "KNN", "TMSelect", "TMPattern", "TMHorizon", "LeadGain", "Knowledge", "WaveElm"]
## Rack id of the new TM pattern gun. It defaults to `TR_RACK_TMPATTERN=off`;
## unlike the other guns, its virtual-bullet spawn is gated on rack admission
@@ -182,6 +184,25 @@ const TmHorizonId = 15
## (backward compatibility; see `gun_harness/selector`).
const LeadGainId = 16
## Rack id of KNOWLEDGE, the learned additive angular residual on top of the
## self-consistent lead forecast (`common_libs/guns/gun_knowledge.nim`). It is
## APPENDED at the end of the rack, so no existing id moved and every
## `tools/ab/arms_*.txt` config still addresses the gun it was written for. It
## ships `TR_RACK_KNOWLEDGE=off`, like every gun except Pattern, and its
## virtual-bullet spawn is gated on rack admission (`vBulletAdmitted`), so the
## shipped default never spawns it and the shared tracker ring head — hence every
## other gun's learning order — is byte-for-byte unchanged. Unlike the rest of
## the rack it may also touch disk (`TR_KNOWLEDGE_MEM`), which is another reason
## it stays out of the default rack.
const KnowledgeId = 17
## Rack id of WAVEELM, the online-ELM gun (`common_libs/guns/waveelm.nim`): an
## analytic intercept plus a learned per-tick (x, y) offset trained by an
## online sequential ELM on its OWN virtual-bullet feedback. APPENDED at the end
## of the rack, so no existing id moved. Ships `TR_RACK_WAVEELM=off`, like every
## gun except Pattern, and its virtual-bullet spawn is gated on rack admission.
const WaveElmId = 18
## ── virtual-bullet debug overlay (TR_VBULLET_DEBUG*) ───────────────────────
## OFF by default: the shipped bot draws nothing. When on, the tracker's
## virtual bullets are overlaid so the training signal the selector learns
@@ -254,6 +275,8 @@ type
tmPattern: TmPatternGun
tmHorizon: TmHorizonGun
leadGain: LeadGainGun
knowledge: KnowledgeGun
waveElm: WaveElmGun
mover: TFILModule
ringMover: TFILRingModule
strafeMover: StrafeModule
@@ -1316,6 +1339,8 @@ method run*(bot: ModularBot) =
var tmpPreds: array[len(PowerBins), GunPrediction]
var tmhPreds: array[len(PowerBins), GunPrediction]
var lgPreds: array[len(PowerBins), GunPrediction]
var gkPreds: array[len(PowerBins), GunPrediction]
var wePreds: array[len(PowerBins), GunPrediction]
# ── TR_VBULLET_ADMIT_ONLY gate ──────────────────────────────────────
# Rack membership used to filter only SELECTION, so every unselected gun
# still ran predict()+spawnBullets() each tick to feed a fitness table the
@@ -1332,7 +1357,8 @@ method run*(bot: ModularBot) =
admit[gi] = ModuleVBullets and
vBulletAdmitted(gi, bot.rackMode, ActiveRackMembership,
VBulletAdmitOnly or gi == TmPatternId or
gi == TmHorizonId or gi == LeadGainId)
gi == TmHorizonId or gi == LeadGainId or
gi == KnowledgeId or gi == WaveElmId)
for i in 0..<len(PowerBins):
if admit[0]: headsUp[i] = bot.headOn.predict(bot.lastState, bulletSpeed(PowerBins[i]))
if admit[1]: linPreds[i] = bot.linear.predict(bot.lastState, bulletSpeed(PowerBins[i]))
@@ -1358,6 +1384,18 @@ method run*(bot: ModularBot) =
# LEADGAIN: Pattern base, lead scaled by a per-band learned gain.
if admit[LeadGainId]:
lgPreds[i] = bot.leadGain.predict(bot.lastState, bulletSpeed(PowerBins[i]))
# KNOWLEDGE: forecast base + a learned additive residual. It is told WHO
# it is aiming at (target selection stays with enemy_tracker/target_
# selector) and how hot the turret is, and answers only the aim angle.
if admit[KnowledgeId]:
bot.knowledge.gunHeat = getGunHeat()
bot.knowledge.targetId = tid
gkPreds[i] = bot.knowledge.predict(bot.lastState, bulletSpeed(PowerBins[i]))
# WAVEELM: analytic intercept + a learned (x, y) offset from the online
# ELM. It is told WHO it aims at, so its per-enemy scan tracks line up.
if admit[WaveElmId]:
bot.waveElm.targetId = tid
wePreds[i] = bot.waveElm.predict(bot.lastState, bulletSpeed(PowerBins[i]))
if admit[0]: bot.tracker.spawnBullets(0, headsUp, bot.lastState, tid)
if admit[1] and not gunDisabled(1): bot.tracker.spawnBullets(1, linPreds, bot.lastState, tid)
@@ -1381,6 +1419,10 @@ method run*(bot: ModularBot) =
bot.tracker.spawnBullets(TmHorizonId, tmhPreds, bot.lastState, tid)
if admit[LeadGainId] and not gunDisabled(LeadGainId):
bot.tracker.spawnBullets(LeadGainId, lgPreds, bot.lastState, tid)
if admit[KnowledgeId] and not gunDisabled(KnowledgeId):
bot.tracker.spawnBullets(KnowledgeId, gkPreds, bot.lastState, tid)
if admit[WaveElmId] and not gunDisabled(WaveElmId):
bot.tracker.spawnBullets(WaveElmId, wePreds, bot.lastState, tid)
# Build slim enemy table for tickBullets
var enemyPositions: Table[int, tuple[x, y: float, lastSeenTick: int, alive: bool]]
@@ -1417,6 +1459,8 @@ method run*(bot: ModularBot) =
of TmPatternId: bot.tmPattern.onResult(fe)
of TmHorizonId: bot.tmHorizon.onResult(fe)
of LeadGainId: bot.leadGain.onResult(fe)
of KnowledgeId: bot.knowledge.onResult(fe)
of WaveElmId: bot.waveElm.onResult(fe)
else: discard
if fe.hit: inc bot.virtualHits else: inc bot.virtualMiss
if DebugDrawOn and VBulletDebugOn:
@@ -1472,6 +1516,8 @@ method run*(bot: ModularBot) =
of TmPatternId: bot.tmPattern.predict(bot.lastState, bulletSpeed(power))
of TmHorizonId: bot.tmHorizon.predict(bot.lastState, bulletSpeed(power))
of LeadGainId: bot.leadGain.predict(bot.lastState, bulletSpeed(power))
of KnowledgeId: bot.knowledge.predict(bot.lastState, bulletSpeed(power))
of WaveElmId: bot.waveElm.predict(bot.lastState, bulletSpeed(power))
else: bot.headOn.predict(bot.lastState, bulletSpeed(power))
let aimTarget = aimAngle(getX(), getY(), pred.x, pred.y)
@@ -1560,7 +1606,7 @@ proc seedSelectorRng() =
when isMainModule:
var bot = ModularBot(
tracker: vb.initTracker(NumRackGuns), # 0: HeadOn, 1: Linear, 2: Tsetlin, 3: Circular, 4: GuessFactor, 5: Pattern, 6: WallBounce, 7: Accel, 8: StopShot, 9: Displace, 10: AvgLead, 11: DecayGF, 12: KNN, 13: TMSelect, 14: TMPattern, 15: TMHorizon, 16: LeadGain
tracker: vb.initTracker(NumRackGuns), # 0: HeadOn, 1: Linear, 2: Tsetlin, 3: Circular, 4: GuessFactor, 5: Pattern, 6: WallBounce, 7: Accel, 8: StopShot, 9: Displace, 10: AvgLead, 11: DecayGF, 12: KNN, 13: TMSelect, 14: TMPattern, 15: TMHorizon, 16: LeadGain, 17: Knowledge, 18: WaveElm
headOn: HeadOnGun(),
linear: LinearGun(),
circular: CircularGun(),
@@ -1578,6 +1624,8 @@ when isMainModule:
tmPattern: initTmRadialGun(),
tmHorizon: initTmHorizonGun(),
leadGain: initLeadGainGun(),
knowledge: initKnowledgeGun(),
waveElm: initWaveElmGun(),
radar: RadarLockModule(),
meleeRadar: initAdaptiveMeleeRadar(),
mover: TFILModule(debugGraphics: DebugDrawOn),
+10
View File
@@ -34,6 +34,7 @@ import movements/learned_surfer
import guns/tm_horizon
import guns/lead_gain
import guns/pattern_matcher
import guns/gun_knowledge
import vbullet_draw
import geo_overlay
@@ -469,6 +470,14 @@ proc printEffectiveValues(ctx: EnvReportContext) =
if dep.len > 0: emit("legacy TR_BITBRAIN_* aliases honoured", "yes", "legacy")
else: emit("legacy TR_BITBRAIN_* aliases honoured", "no", "default")
# ── KNOWLEDGE, the learned residual gun (rack id 17) ──────────────────────
# One knob: where its learned table lives. Unset = memory only, i.e. nothing
# is ever written to disk. The table is allocated on FIRST USE, so this line
# reports the configured path, not a live table.
let gkMem = getEnv(GK_MEM_ENV, "").strip()
emit("TR_KNOWLEDGE_MEM", if gkMem.len > 0: gkMem else: "(unset -> memory only)",
sourceOf(GK_MEM_ENV))
# ── Pattern match-shape + radial knobs ────────────────────────────────────
# These are resolved lazily inside `predict` (which has not run at boot), so
# unless something already forced them we report the raw env value and say so.
@@ -629,6 +638,7 @@ proc knownEnvNames*(): seq[string] =
TMH_SHIFT_ENV, TMH_BIG_MULT_ENV, TMH_LOG_ENV, TMH_RESET_ON_TARGET_ENV,
TMH_WINDOW_ENV, TMH_RESET_DROP_ENV, TMH_NSTATES_ENV, TMH_ACCURVE_ENV,
TMH_RETRAIN_EVERY_ENV, TMH_EPOCHS_ENV,
GK_MEM_ENV,
LG_MEM_ENV, LG_GAINS_ENV, LG_N_ENV, LG_NADE_ENV, LG_RANGE_ENV, LG_LOG_ENV,
LG_MIN_OBS_ENV, LG_WARMUP_ENV, LG_ADAPT_ENV, LG_CALIB_ENV, LG_DECAY_ENV,
LG_DECAY_FRAC_ENV, LG_SEED_ENV, LG_RESET_ON_TARGET_ENV,
+2
View File
@@ -100,6 +100,8 @@ proc gunColors*(gunId: int): tuple[turret, bullet: string] =
of 14: ("#AAFF00", "#CCFF66") # TMPattern — lime
of 15: ("#00AAFF", "#66CCFF") # TMHorizon — sky
of 16: ("#FF1493", "#FF69B4") # LEADGAIN — deep pink
of 17: ("#8B4513", "#D2691E") # KNOWLEDGE — saddle brown
of 18: ("#7B68EE", "#9370DB") # WAVEELM — medium slate blue
else: ("#FFFFFF", "#FFFFFF")
proc gunTurretColor*(gunId: int): string = gunColors(gunId).turret
+7 -6
View File
@@ -1,7 +1,8 @@
## Enemy tracker — deterministic radar lock + dead reckoning for PPO_Bot.
## No bot API imports; takes plain floats.
## Takes plain floats; only the SDK radar constants are used.
import std/math
import tankroyale_botapi/constants
type
EnemyState* = object
@@ -75,14 +76,14 @@ proc normalizeRelative(angle: float64): float64 {.inline.} =
proc getRadarTurnRate*(tracker: var EnemyTracker;
botX, botY, botDirection, radarDirection: float64): float64 =
## Returns radar turn rate (degrees/tick, positive = right).
## Before contact: full 45° sweep.
## Before contact: full-speed sweep.
## After contact: lock with overshoot; widen if stale.
if not tracker.hasContact:
return 45.0
return MAX_RADAR_TURN_RATE
if tracker.current.ticksSinceLastScan >= 8:
# Lost lock — widen sweep
return 45.0
return MAX_RADAR_TURN_RATE
# Bearing from radar to enemy.
# Tank Royale radar directions use standard math convention (0=east, CCW+).
@@ -94,7 +95,7 @@ proc getRadarTurnRate*(tracker: var EnemyTracker;
# Width Lock: overshoot proportional to arctan(36 / distance)
let distance = sqrt(dx * dx + dy * dy)
let extraTurn = min(arctan(36.0 / distance) * 180.0 / PI, 45.0)
let extraTurn = min(arctan(36.0 / distance) * 180.0 / PI, MAX_RADAR_TURN_RATE)
if radarTurn < 0.0: radarTurn -= extraTurn
else: radarTurn += extraTurn
result = radarTurn.clamp(-45.0, 45.0)
result = radarTurn.clamp(-MAX_RADAR_TURN_RATE, MAX_RADAR_TURN_RATE)
+14 -4
View File
@@ -22,6 +22,10 @@ import virtual_bullets
# TR_RACK_KNN=off -> removed from both racks
# TR_RACK_TMPATTERN=off (shipped default for the new TM pattern gun)
# TR_RACK_LEADGAIN=both -> the per-range-band lead-gain corrector (id 16)
# TR_RACK_KNOWLEDGE=both -> the learned residual gun (id 17); it is a
# persistence-carrying gun, so the shipped default
# is `off` and it only ever touches disk when a
# caller admits it
#
# SHIPPED DEFAULT IS `onlyPattern`: Pattern (id 5) is admitted in both racks and
# every other gun is `off`. This is a deliberate, measured decision, not a
@@ -45,10 +49,11 @@ import virtual_bullets
# transition the radar uses.
const
RackGunNames*: array[17, string] = [
RackGunNames*: array[19, string] = [
"HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN",
"WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF",
"KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN"]
"KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN", "KNOWLEDGE",
"WAVEELM"]
RackEnvPrefix* = "TR_RACK_"
## THE rack size, derived from `RackGunNames`. Every per-gun-indexed array and
## loop in the bot and in the harness MUST be sized with this, never with a
@@ -74,7 +79,7 @@ const
## it never spawns a virtual bullet unless explicitly enabled, so the shared
## VirtualTracker ring head — and every other gun's learning order — is
## unchanged.
DefaultRackMembership*: array[17, RackMembership] = [
DefaultRackMembership*: array[19, RackMembership] = [
rmOff, # 0 HEADON — off (measured: worst over-selected gun)
rmOff, # 1 LINEAR — off
rmOff, # 2 TSETLIN — off
@@ -91,7 +96,12 @@ const
rmOff, # 13 TMSELECT — off
rmOff, # 14 TMPATTERN — off (already shipped off; TM pattern gun)
rmOff, # 15 TMHORIZON — off (horizon-based TM corrector; expected to lose)
rmOff] # 16 LEADGAIN — off (per-range-band lead-gain corrector)
rmOff, # 16 LEADGAIN — off (per-range-band lead-gain corrector)
rmOff, # 17 KNOWLEDGE — off (learned additive angular residual on top of
# the self-consistent lead forecast; see
# `guns/gun_knowledge.nim`)
rmOff] # 18 WAVEELM — off (online-ELM learned offset on the analytic
# intercept; see `guns/waveelm.nim`)
## NOTE: the table is registered in the SAME commit as the gun id and the live
## wiring, so `TR_RACK_LEADGAIN=both` (or the legacy `TR_RACK_BITBRAIN=both`)
## are the ONLY things that admit that gun, and an unset environment is
+199
View File
@@ -0,0 +1,199 @@
# OS-ELM reference papers — audit, downloads, and update-rule notes
Audit date: 2026-08-22, extended 2026-10-02 (all identifiers re-fetched from arxiv.org,
api.crossref.org, api.openalex.org and doi.org — nothing here is trusted from a previous pass).
Re-download everything open access with:
```bash
./fetch_papers.sh # idempotent; exits non-zero and deletes any non-PDF
```
## CITATION NOTES — read this first
Three of the fourteen claimed citations were wrong, and one does not exist at all.
| Claim | Reality |
|---|---|
| `10.1109/TSMCS.2011.616645` — "Huang/Zhu/Zhou 2011–2012 ELM survey" | **DOES NOT EXIST.** `doi.org` returns **404**; absent from Crossref *and* OpenAlex. No paper carries this DOI. Do not cite it. |
| "Extreme Learning Machine: A Review and New Trends", Huang, IEEE T-SMC-B **42(2):513–529, 2012** | **WRONG TITLE + WRONG AUTHORS.** Those exact pages belong to `10.1109/TSMCB.2011.2168604` = *"Extreme Learning Machine for Regression and Multiclass Classification"*, **Huang, Zhou, Ding & Zhang** (4 authors, not 1). A Crossref title search for "…A Review and New Trends" returns **no such article**. Treat the title as fabricated. The likely intended real review is *"Trends in extreme learning machines: A review"*, `10.1016/j.neunet.2014.10.001` (Neural Networks 61:32–48, 2015). |
| `10.1007/s10922-025-09976-3` — "Shwaysh et al., Ensemble RELM, **J Real-Time Image Proc 2025**" | **WRONG VENUE.** It is *Journal of Network and Systems Management* **34(1), 2025** — an intrusion-detection paper. First author Shwaysh is correct. |
| `10.1007/s11042-021-11008-7` — "A review on extreme learning machine" | **TYPO, DOES NOT RESOLVE (404).** The correct DOI is **`10.1007/s11042-021-11007-7`** (11007, not 11008). |
Two more were near-misses rather than errors:
* **`arXiv:2512.21777` is REAL**, despite the "implausible number" flag. Submitted 2025-12-25, and the title matches almost verbatim (it spells out "Extreme Learning Machine"). Confirmed twice: `arxiv.org/abs/2512.21777` and the arXiv API. Not hallucinated.
* **`arXiv:2504.09028`** has a different title than claimed. It is *"Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing"*; the OSOS-ELM / one-sided-Jacobi content is real (it's in the abstract), only the title was misremembered.
One more non-existent citation, found on a later pass (audit date 2026-10-02):
* **"Extreme Learning Machines: A Survey", Huang / Zhu / Zhou, IEEE T-SMC-B 42(3):486–497 (2012)" — NOT DISCOVERABLE.** There is no such article. Crossref's full, *gap-free* inventory of T-SMC-B vol. 42 shows issue 2 runs 294–580 and issue 3 starts at 581, so pages 486–497 cannot be in either. The range 486–497 sits **inside** a different article, 42(2):482–500 = *"An Adaptive Differential Evolution Algorithm With Novel Mutation and Crossover Strategies for Global Numerical Optimization"* (`10.1109/TSMCB.2011.2167966`, Islam, Das, Ghosh, Roy, Suganthan), verified independently in OpenAlex. The genuine ELM article in issue 2 is 513–529 (`10.1109/TSMCB.2011.2168604`), the one already audited above. No DOI was found for a Huang/Zhu/Zhou survey; a `prefix:10.1109` Crossref title sweep and an OpenAlex title sweep both return nothing. **Do not cite 42(3):486–497.** Use `10.1007/s13042-011-0019-y` instead — it is the real, verifiable 2011 ELM survey, and it is now in this directory.
One open-access status correction:
* **`10.1007/s11042-021-11007-7` is listed as hybrid OA by OpenAlex, but its PDF cannot be fetched from here** — `link.springer.com/.../11007-7.pdf` answers `200 text/html` (a ~3 KB bot-challenge page), not a PDF. The green-OA copy at `ntu.edu.sg/.../ELM-Unified-Learning.pdf` now 404s. So it is listed as **not downloaded** below. MDPI likewise 403s on `www.mdpi.com/.../pdf`; `mdpi-res.com` works, which is what `fetch_papers.sh` uses.
## Audit table
| Claimed citation | Verdict | Correct identifier / real paper |
|---|---|---|
| arXiv:2512.21777 — "Online Learning ELM with Low-Complexity Predictive Plasticity Rule and FPGA Implementation" | **VERIFIED** (title differs only by spelling out "Extreme Learning Machine") | Zang, Li, Li — arXiv:2512.21777, 2025-12-25 |
| arXiv:2504.09028 — "…One-Sided Jacobi Rotation OSOS-ELM" | **VERIFIED (content)** / title wrong | Real title "Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing", Zang, Li, Li, 2025-04-12 |
| arXiv:2505.08129 — Liu & Cao, "High-order Regularization…" | **VERIFIED** | "High-order Regularization for Machine Learning and Learning-based Control", arXiv:2505.08129, 2025-05-13 |
| 10.1109/IJCNN.2017.7966094 — Park & Kim, "Online recurrent ELM … time-series prediction" | **VERIFIED** | Park Jin-Man & Kim Jong-Hwan, IJCNN 2017, **pp. 1983–1990** |
| 10.1002/er.8514 — Gu & Wang, BASO-optimized RELM | **VERIFIED** (full title longer) | "A beetle antennae search optimized recurrent extreme learning machine for battery state of charge estimation", *Int J Energy Res* **46(13):19190–19205, 2022** — BASO = Beetle Antennae Search Optimization |
| 10.1007/s10922-025-09976-3 — Shwaysh et al., J Real-Time Image Proc 2025 | **WRONG (venue)** | Shwaysh et al., *Journal of Network and Systems Management* **34(1), 2025**, "…Ensemble Recurrent Extreme Learning Machine for Enhanced Network Intrusion Detection Systems" |
| 10.3390/app7030217 — Lu, Huang, Lu, "Adaptive-Weight OS-ELM for time series", Appl Sci 7:217, 2017 | **VERIFIED** | "Time Series Prediction Based on Adaptive Weight Online Sequential Extreme Learning Machine", Lu Junjie, Huang Jinquan, Lu Feng, *Appl Sci* **7(3):217, 2017** — gold OA |
| 10.1016/j.neucom.2012.02.003 — Zhao, Wang, Park, forgetting mechanism | **VERIFIED** | *Neurocomputing* **87:79–89, 2012** |
| 10.1016/j.neucom.2009.02.013 — Lan, Soh, Huang, Ensemble of OSELM | **VERIFIED** | *Neurocomputing* **72(13–15):3391–3395, 2009** |
| 10.1109/TSMCS.2011.616645 — ELM survey DOI | **NOT FOUND** | 404 at doi.org, absent from Crossref and OpenAlex. No such DOI |
| 10.1109/tsmcb.2011.2168604 — Huang, "ELM: A Review and New Trends", 42(2):513–529 | **WRONG** | Same DOI = "Extreme Learning Machine for Regression and Multiclass Classification", Huang, **Zhou, Ding, Zhang**, T-SMC-B 42(2):513–529, 2012 |
| 10.1007/s13042-011-0019-y — Huang, Lan, Wang, "ELM: A Review", IJMLC 2(2):107–122 | **VERIFIED, author order wrong** | Crossref: **Huang, Wang, Lan** — "Extreme learning machines: a survey", *Int J Mach Learn Cybern* **2(2):107–122, 2011** |
| 10.1016/j.neunet.2017.04.001 — Yang et al., RL mean-p-power ELM | **VERIFIED, year off by one** | Yang, Ye, Rong, Chen, "Recursive least mean p-power Extreme Learning Machine", *Neural Networks* **91:22–33, 2017** (not 2018 — 2018 is the issue-print year) |
| 10.1109/codit.2018.8394791 — "A Survey of Online Sequential ELM", CoDIT 2018 | **VERIFIED, authors missing** | **Zhang Senyue, Tan Wenan, Li Yibo**, CoDIT 2018, **pp. 45–50** |
| `…/s11042-021-11008-7.pdf` | **NOT FOUND (typo)** | Correct: `…/s11042-021-11007-7.pdf` — Wang, Lu, Wang, Zhang, "A review on extreme learning machine", *Multimed Tools Appl* **81(29):41611–41660, 2021** |
## Downloaded (open access)
Files in this directory, all verified with `file` as real PDFs.
### zang_2025_predictive_plasticity_elm_fpga.pdf
*Online Learning Extreme Learning Machine with Low-Complexity Predictive Plasticity Rule and FPGA Implementation* — Zhenya Zang, Xingda Li, David Day Uei Li. arXiv:2512.21777, submitted 2025-12-25.
<https://arxiv.org/abs/2512.21777> · PDF: <https://arxiv.org/pdf/2512.21777>
Replaces the ELM's one-shot matrix inverse with a local, biologically inspired
predictive-plasticity rule: weights change only on prediction error, and each
update is a sparse vector addition gated by a binary firing mask. Training cost
drops from O(M³) to O(M) in hidden nodes M, at a reported accuracy cost of 3.6 %
train / 2.0 % test, and is demonstrated on an FPGA. **Update rule: predictive
plasticity (spike/error-gated local delta) — not RLS.** The most interesting
paper here for a real-time aiming loop: it is the only one whose whole point is
O(M) per-sample cost with no inverse.
### zang_2025_osos_elm_single_photon.pdf
*Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing* — Zhenya Zang, Xingda Li, David Day Uei Li. arXiv:2504.09028, submitted 2025-04-12.
<https://arxiv.org/abs/2504.09028> · PDF: <https://arxiv.org/pdf/2504.09028>
The hardware sibling of the above: an **OSOS-ELM** whose per-sample
inverse-covariance update is restructured as a **one-sided Jacobi rotation**, so
the RLS algebra becomes a sequence of rank-1 updates with no square matrix to
factor or invert. Evaluated against plain OS-ELM across hidden/input/output sizes
(comparable accuracy, better hardware efficiency) and implemented on a Xilinx
ZCU104 (multi-task ARM cores + pipelined logic fabric) and on a Jetson Xavier NX
GPU, with three single-photon case studies. **Update rule: one-sided Jacobi
rotation RLS (OSOS-ELM).** Same authors and line of work as the entry above.
### liu_2025_high_order_regularization.pdf
*High-order Regularization for Machine Learning and Learning-based Control* — Xinghua Liu, Ming Cao. arXiv:2505.08129, submitted 2025-05-13.
<https://arxiv.org/abs/2505.08129> · PDF: <https://arxiv.org/pdf/2505.08129>
Generalises L2 ridge regularisation to a **high-order (matrix) regulariser**,
framing regularisation as an inverse-map approximation with an explicitly
computable error bound; L2 appears as the special first-order case. The authors
prove convergence, give lower/upper error bounds, and show the solution is a
contraction whose generalisation is maximised by a suitable regulariser matrix.
Includes an **incremental** HR solution for regularised ELM, plus an RL
value-approximation case study. **Update rule: none per se — it is the
regularisation term itself; supplies the incremental-solution framing that makes
the ridge `lambda` in an online ELM meaningful.** Relevant to `common_libs/guns/elm.nim`,
which currently uses a scalar `lambda`.
### lu_2017_adaptive_weight_oselm.pdf
*Time Series Prediction Based on Adaptive Weight Online Sequential Extreme Learning Machine* — Junjie Lu, Jinquan Huang, Feng Lu. *Applied Sciences* 7(3):217, 2017.
<https://doi.org/10.3390/app7030217> · PDF: <https://mdpi-res.com/d_attachment/applsci/applsci-07-00217/article_deploy/applsci-07-00217.pdf>
Plain OS-ELM on a fixed random hidden layer, but each hidden node's contribution
is re-weighted per sample so that nodes which keep losing prediction error are
down-weighted, which stabilises long non-stationary time-series runs. Reports
improved forecasting accuracy over vanilla OS-ELM on public time-series
benchmarks. **Update rule: recursive least squares (OS-ELM RLS) + per-node adaptive
sample weighting.** This is the closest published match to what
`common_libs/guns/elm.nim` already implements.
## Manually supplied (paywalled — user-provided)
One paper here was **not** fetched by `fetch_papers.sh`: it is closed-access
(`oa_status: closed`, no legal OA copy anywhere) and was supplied by hand.
### huang_wang_lan_2011_elm_survey.pdf
*Extreme learning machines: a survey* — **Guang-Bin Huang, Dian Hui Wang, Yuan Lan**,
*International Journal of Machine Learning and Cybernetics* **2(2):107–122, 2011**.
DOI **`10.1007/s13042-011-0019-y`** — <https://doi.org/10.1007/s13042-011-0019-y>
Verified against both Crossref and OpenAlex (they agree on title, author order,
volume, issue and page range). The file is the **complete version of record**,
602314 bytes, md5 `547b4311cdb610fdf348d08107205907`, 16 pages = exactly the
printed range 107–122; the Springer DOI is printed on the title page and every
page footer reads `Int. J. Mach. Learn. & Cyber. (2011) 2:107–122`. Author order
is **Huang, Wang, Lan** (some citations wrongly give Huang, Lan, Wang).
Note the bibliographic trap this paper sits in: it is frequently mis-attributed
to *Neurocomputing* 75 (2011) 3051–3060. No such Neurocomputing article exists —
a Crossref sweep of every 2011 Neurocomputing paper by this trio returns only
the ELM2010 editorial (`10.1016/j.neucom.2011.03.030`, 74(16):2411–2412). It is
also unrelated to the phantom "IEEE T-SMC-B 42(3):486–497" survey above.
Content: the canonical ELM survey — the batch closed-form solution
`β = (HᵀH + λI)⁻¹HᵀT`, the universal-approximation theorem for SLFNs with
randomly generated hidden nodes, kernel ELM, and the full taxonomy of variants
including the OS-ELM/online-sequential family. **No single update rule** — it is
the map of the rules cited throughout this file.
## Paywalled (not downloaded, cited for reference)
OpenAlex reports `oa_status: closed` for all of these; no legal PDF exists to fetch.
* **Park Jin-Man, Kim Jong-Hwan**, "Online recurrent extreme learning machine and its application to time-series prediction", *IJCNN 2017*, pp. 1983–1990. <https://doi.org/10.1109/IJCNN.2017.7966094> — **update rule: recurrent ELM** (ELM hidden layer fed back over time).
* **Gu Tianyu, Wang Dongqing**, "A beetle antennae search optimized recurrent extreme learning machine for battery state of charge estimation", *Int J Energy Res* 46(13):19190–19205, 2022. <https://doi.org/10.1002/er.8514> — **update rule: recurrent ELM, hyper-parameters tuned by BASO** (beetle antennae search metaheuristic). BASO tunes the network, it is not a per-sample online rule.
* **Shwaysh Mustafa Muslih** et al., "…Ensemble Recurrent Extreme Learning Machine for Enhanced Network Intrusion Detection Systems", *J Network Syst Manage* 34(1), 2025. <https://doi.org/10.1007/s10922-025-09976-3> — **update rule: ensemble** of RELM members (combined with autoencoder feature selection).
* **Zhao Jianwei, Wang Zhihui, Park Dong Sun**, "Online sequential extreme learning machine with forgetting mechanism", *Neurocomputing* 87:79–89, 2012. <https://doi.org/10.1016/j.neucom.2012.02.003> — **update rule: RLS + forgetting factor.** The canonical source for the `rho` knob; `elm.nim` already cites it.
* **Lan Yuan, Soh Yeng Chai, Huang Guang-Bin**, "Ensemble of online sequential extreme learning machine", *Neurocomputing* 72(13–15):3391–3395, 2009. <https://doi.org/10.1016/j.neucom.2009.02.013> — **update rule: ensemble** of independently trained OS-ELMs.
* **Huang Guang-Bin, Zhou Hongming, Ding Xiaojian, Zhang Rui**, "Extreme Learning Machine for Regression and Multiclass Classification", *IEEE T-SMC-B* 42(2):513–529, 2012. <https://doi.org/10.1109/TSMCB.2011.2168604> — **update rule: none** (batch ELM; the closed-form ridge solution β = (HᵀH + λI)⁻¹HᵀT).
* **Yang Jing, Ye Feng, Rong Hai-Jun, Chen Badong**, "Recursive least mean p-power Extreme Learning Machine", *Neural Networks* 91:22–33, 2017. <https://doi.org/10.1016/j.neunet.2017.04.001> — **update rule: recursive least mean p-power (RLMP).** Like RLS but the gain is powered to *p* and normalised by the power of the activation, trading exactness for robustness — the right shape for noisy, drift-prone inputs.
* **Zhang Senyue, Tan Wenan, Li Yibo**, "A Survey of Online Sequential Extreme Learning Machine", *CoDIT 2018*, pp. 45–50. <https://doi.org/10.1109/CODIT.2018.8394791> — **survey** of the OS-ELM family; the map of the rules above.
* **Wang Jian, Lu Siyuan, Wang Shui-Hua, Zhang Yu-Dong**, "A review on extreme learning machine", *Multimed Tools Appl* 81(29):41611–41660, 2021. <https://doi.org/10.1007/s11042-021-11007-7> — open access in principle, but **bot-blocked from this machine** (see CITATION NOTES). **survey**, no single rule.
## Core OS-ELM RLS equations (plain text)
Hidden layer is drawn once and frozen: `H = [g₁ … g_M]` with `g_j = act(W_j x + b_j)`.
Output weights `β` (M×C) start at zero; `P` starts at `P₀ = (1/η) I`. No epochs, one pass.
Per sample `(x_t, y_t)`, with `g_t = act(W x_t + b_t)`:
```
g_t = act(W x_t + b_t) # frozen random hidden map
# optional forgetting factor (Zhao, Wang & Park 2012) — do this FIRST:
# P <- P / rho rho = 1 → plain RLS, rho > 1 → old data decays
# NOTE: divide rho**2 into lambda below to keep the steady-state noise floor sane.
K_t = P g_t / (lambda + g_t^T P g_t) # gain vector, no matrix inverse
beta_t = beta_{t-1} + K_t (y_t - g_t^T beta_{t-1}) # rank-1 weight correction
P_t = (I - K_t g_t^T) P_{t-1} # downdate the inverse correlation
```
Read `K_t` as: "how much of the current inverse correlation points along this
sample's hidden activation". `beta_t` only ever moves by a rank-1 step, so the
per-sample cost is O(M·C) plus one O(M²) downdate — versus the batch ELM's
O(M³) inverse. `P` is the inverse of `Σ_i g_i g_iᵀ + λI`, so the fixed point of
the recursion is exactly the ridge solution `β = (HᵀH + λI)⁻¹HᵀT`; RLS is that
solution, computed incrementally.
Variants referenced above:
* **Forgetting factor** (Zhao 2012) — insert `P ← P/ρ` before the update so the
fixed point becomes a exponentially-weighted least squares fit. `ρ = 1` is
exactly the equations above.
* **Ensemble** (Lan 2009, Shwaysh 2025) — run `N` independent copies (different
random hidden draws, different seeds) and average their outputs. Cost `N×`,
variance down.
* **Mean-p-power** (Yang 2017) — replace the gain with a powered, normalised
form: `K_t = P g_t / (lambda + ‖g_t‖_p^p)` style denominators, which caps the
influence of outlier activations instead of trusting them exactly.
* **One-sided Jacobi** (Zang 2025) — restructure `P`'s update as an explicit
sweep of one-sided Jacobi rotations so each step is a rank-1 rotation rather
than a matrix product; same fixed point, better pipelining on FPGA.
* **Predictive plasticity** (Zang 2025) — drop RLS entirely; `Δw ∝ (err) ⊙ mask`
on error only, O(M).
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Re-download the open-access OS-ELM / ELM reference PDFs.
# Idempotent: skips files that already exist and are genuine PDFs.
# Fails loudly (exit 1) if a download does not yield a real PDF.
#
# Only papers verified open access in CITATION NOTES (see README.md) are listed.
# Paywalled items are deliberately absent - there is nothing to fetch.
#
# huang_wang_lan_2011_elm_survey.pdf (10.1007/s13042-011-0019-y, IJMLC 2(2):107-122)
# is paywalled with no OA copy and is deliberately NOT in this list: adding a
# publisher URL here would just curl a bot-challenge page. It was supplied by
# hand - see README.md "Manually supplied". This script only ever writes or
# removes the filenames listed below, so that file is never touched.
set -uo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
UA='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
mkdir -p "$DIR"
# name|url
PAPERS=(
"zang_2025_predictive_plasticity_elm_fpga.pdf|https://arxiv.org/pdf/2512.21777"
"zang_2025_osos_elm_single_photon.pdf|https://arxiv.org/pdf/2504.09028"
"liu_2025_high_order_regularization.pdf|https://arxiv.org/pdf/2505.08129"
"lu_2017_adaptive_weight_oselm.pdf|https://mdpi-res.com/d_attachment/applsci/applsci-07-00217/article_deploy/applsci-07-00217.pdf"
)
fail=0
for entry in "${PAPERS[@]}"; do
name="${entry%%|*}"; url="${entry#*|}"; out="$DIR/$name"
if [ -s "$out" ] && file -b "$out" | grep -q '^PDF'; then
echo "SKIP $name (already present, $(stat -c%s "$out") bytes)"
continue
fi
# MDPI blocks plain /pdf with a Referer-less request; arXiv does not care.
echo "GET $name <- $url"
if ! curl -fL -A "$UA" -H 'Referer: https://www.mdpi.com/' -H 'Accept: application/pdf,*/*' \
--retry 3 --retry-delay 2 -o "$out" "$url"; then
echo "FAIL $name (curl error)" >&2; rm -f "$out"; fail=1; continue
fi
if ! file -b "$out" | grep -q '^PDF'; then
echo "FAIL $name: not a PDF ($(file -b "$out"))" >&2
rm -f "$out"; fail=1; continue
fi
echo "OK $name ($(stat -c%s "$out") bytes)"
done
[ "$fail" -eq 0 ] || { echo "one or more downloads failed" >&2; exit 1; }
echo "all open-access papers present in $DIR"
+356
View File
@@ -0,0 +1,356 @@
## ELM — Extreme Learning Machine, ONLINE SEQUENTIAL variant (ridge / RLS).
##
## Fixed random hidden layer (weights + biases drawn ONCE from a seeded RNG,
## never trained) and output weights `beta` solved by recursive least squares as
## samples arrive. This is NOT gradient descent: no backprop, no epochs, one
## pass over the data.
##
## Per sample, with g = act(W x + b) the hidden activation:
## g = act(W x + b)
## P = rho P - rho^2 (P g)(g^T P) / (1 + rho g^T P g)
## beta = beta + (P_new g) (t - g^T beta)
## with P0 = I/lambda, so P is exactly (sum_i rho^{i-n} g_i g_i^T + lambda I)^-1
## and beta is the ridge solution beta = (H^T H + lambda I)^-1 H^T T solved in
## closed form at every step — no gradient descent, no epochs, one pass.
## rho = 1 is textbook ridge RLS (K = P g / (1 + g^T P g)); rho > 1 is the
## FORGETTING FACTOR of Zhao, Wang & Park, Neurocomputing 87:79-89 (2012) —
## it decays the accumulated information matrix (M <- M/rho) so the net tracks
## a non-stationary target instead of averaging over its whole history.
## Its effective memory is about 1/(rho - 1) samples.
##
## Two sign/placement traps this file got wrong first and now documents, because
## both fail silently (they train, they just never track a drift):
## * scale P UP by rho after the update, not down — scaling it down makes M
## grow with rho, i.e. rho > 1 AMPLIFIES the past and freezes the net;
## * the K gain must be P_new * g (post-update), not P_old * g: only the
## former preserves the invariant above once rho != 1.
##
## ── (OPTIONAL) RECURRENCE — the RELM hidden layer ───────────────────────────
## h_j(t) = act(sum_k W_jk x_k(t) + b_j + r_j * h_j(t-1))
## Park Jin-Man & Kim Jong-Hwan, "Online recurrent extreme learning machine for
## time-series prediction", IJCNN 2017 pp. 1983-1990, doi 10.1109/IJCNN.2017.7966094
## (citation verified in guns/docs/README.md; the PDF itself is NOT in
## guns/docs/, so the exact equation above is the STANDARD recurrent-ELM form
## taken on the citation's word, not a transcription — flagged as an assumption
## rather than passed off as verified).
##
## WHAT IT BUYS, MEASURED: nothing. The one caller that uses it,
## guns/waveelm.nim, sweeps it over synthetic target sequences
## (common_libs/tests/bench_waveelm_temporal.nim, 3 regimes x 2 motion styles x
## 3 seeds) and it lands between -1.4% and +4.7% on RMS error and between
## -4.6% and +9.7% on hit rate — noise around zero, both on its own and on top
## of the lag window, INCLUDING a case built specifically to favour it (a ground
## truth with a 12-tick memory, longer than any explicit window the feature map
## can carry, where only integrating over time can build the quantity: -0.2% to
## -1.4% RMS). It is therefore OFF by default (`recurrentGain = 0.0`), where it
## is not merely slow but BYTE-IDENTICAL to the feed-forward net: r_j = 0 makes
## the recurrent term vanish and `hidden` skips it entirely.
##
## WHY IT IS SAFE ANYWAY (the three things a recurrence can break):
## 1. DIVERGENCE. Every r_j is clamped to |r_j| <= ElmRMax = 0.9 < 1, and with
## act' <= 1 the map h -> act(a + r h) is a contraction, so h has a unique
## bounded fixed point for ANY input and cannot run away. `isSane` also
## checks |r_j| < 1 and every h_j for finiteness, so a poisoned recurrence
## is detected rather than propagated.
## 2. STATE LEAK. The node state is the state of a SEQUENCE, not of the net:
## `resetHidden` clears it and keeps beta/P (what was LEARNED survives, the
## sequence does not), and guns/waveelm.nim calls it when the resolved
## target id changes and exposes `resetTemporalState` for a new round.
## 3. MIS-ALIGNED LABELS. A gun's label arrives dozens of ticks after the
## shot, so re-running `hidden(x)` at training time would fit a DIFFERENT
## function (the node state has moved on). `trainHidden` therefore takes the
## activation the shot actually used, and the gun stores it in the probe
## trace. Also: the caller owns the clock — `hidden` and `predict` are
## read-only, only `predictStep` advances, so a gun probing four bullet
## speeds per tick steps the recurrence once per TICK, not once per probe.
##
## The tests for all of the above are common_libs/tests/test_waveelm_temporal.nim.
##
## Dependency-light on purpose: std/math + std/random only, so a gun plugin can
## import it without dragging in a network stack. Deliberately implements NO Gun
## interface — the caller feeds features in and reads predictions out.
##
## Coordinate/gun conventions of gun_harness/gun_interface.nim apply to callers,
## not here: nothing in this file knows about degrees or bullets.
import std/[math, random]
type
ElmActivation* = enum
## Hidden nonlinearity. tanh (default) is the usual ELM choice; sigmoid is
## offered because the original ELM paper used it and some targets are
## better served by a (0,1) squashing.
eaTanh
eaSigmoid
ElmNet* = object
inputDim*: int
hiddenDim*: int
outputDim*: int
act*: ElmActivation
lambda*: float ## ridge regularisation: beta = (H^T H + lambda I)^-1 H^T T
rho*: float ## forgetting factor, >= 1.0 (1.0 = no forgetting)
W*: seq[seq[float]] ## hiddenDim x inputDim, fixed after init
b*: seq[float] ## hiddenDim, fixed after init
r*: seq[float] ## hiddenDim, RELM recurrent gain per node; all-zero
## (the default) means NO recurrence at all
hPrev*: seq[float] ## hiddenDim, the hidden layer's own state h(t-1)
beta*: seq[seq[float]] ## hiddenDim x outputDim, learned
P*: seq[seq[float]] ## hiddenDim x hiddenDim inverse correlation, learned
samples*: int ## successful updates since init (or last reset)
resets*: int ## numerical blowups that forced a soft reset
const
ElmRMax* = 0.9
## HARD clamp on every recurrent gain r_j.
## WHY: with |r| < 1 the map h -> act(a + r*h) is a CONTRACTION whenever
## act' is bounded by 1 (max tanh' = 1, max sigmoid' = 1/4), so the recurrence
## has a unique BOUNDED fixed point for ANY input and provably cannot
## diverge. That clamp is what buys the guarantee, rather than hoping the
## seeded gains happen to be tame: a runaway hidden vector would feed NaN
## straight into the RLS and blow up P. 0.9 keeps a uniform margin below 1
## and still buys a ~10-sample memory (0.9^10 = 0.35).
# ── helpers ───────────────────────────────────────────────────────────────────
proc isFinite(x: float): bool {.inline.} =
classify(x) notin {fcNan, fcInf, fcNegInf}
proc allFinite(m: seq[seq[float]]): bool =
for row in m:
for v in row:
if not isFinite(v): return false
true
proc allFinite(v: seq[float]): bool =
for x in v:
if not isFinite(x): return false
true
proc zeroMat(rows, cols: int): seq[seq[float]] =
result = newSeq[seq[float]](rows)
for i in 0..<rows: result[i] = newSeq[float](cols)
proc matVec(m: seq[seq[float]], v: openArray[float]): seq[float] =
## m * v, rectangular m allowed (only P*g is used today; P is square).
result = newSeq[float](m.len)
for i in 0..<m.len:
var s = 0.0
for j in 0..<min(m[i].len, v.len): s += m[i][j] * v[j]
result[i] = s
proc dot(a, b: openArray[float]): float {.inline.} =
for i in 0..<a.len: result += a[i] * b[i]
proc applyAct(net: ElmNet, v: float): float {.inline.} =
case net.act
of eaTanh: tanh(v)
of eaSigmoid: 1.0 / (1.0 + exp(-v))
# ── construction ──────────────────────────────────────────────────────────────
proc init*(inputDim, hiddenDim: int, seed: int64 = 42, outputDim = 1,
act = eaTanh, lambda = 1e-3, rho = 1.0,
recurrentGain = 0.0): ElmNet =
## Fixed hidden layer drawn from a seeded RNG, so the whole net is
## reproducible: same seed => same predictions.
##
## `recurrentGain` > 0 turns on the RELM hidden layer (Park Jin-Man & Kim
## Jong-Hwan, "Online recurrent extreme learning machine for time-series
## prediction", IJCNN 2017 pp. 1983-1990, doi 10.1109/IJCNN.2017.7966094):
## h_j(t) = act(sum_k W_jk x_k(t) + b_j + r_j * h_j(t-1))
## each hidden node feeds its OWN previous activation back into itself, which
## is what turns the feature map into a function of the SEQUENCE rather than
## of the current sample alone. (ASSUMPTION, documented honestly: the exact
## paper formulation could not be read from here — the PDF is not in
## guns/docs/ — so this is the standard recurrent-ELM form; the citation is
## verified in guns/docs/README.md.)
## The r_j are drawn from the SAME seeded RNG as W and b, in the same call
## order, so one seed still reproduces the entire net. Signs are symmetric:
## half the nodes remember forwards and half backwards, which is what lets a
## signed oscillatory quantity (a rotating aim bias) be represented.
## 0.0 (the default) leaves every r_j at 0 and the net is byte-identical to
## the plain feed-forward ELM: h_j(t) = act(W_j x + b_j), no state at all.
doAssert inputDim > 0 and hiddenDim > 0 and outputDim > 0
doAssert lambda > 0.0
var rng = initRand(seed)
result.inputDim = inputDim
result.hiddenDim = hiddenDim
result.outputDim = outputDim
result.act = act
result.lambda = lambda
result.rho = max(1.0, rho) # < 1 would amplify old samples; clamp, don't fail
result.W = newSeq[seq[float]](hiddenDim)
for h in 0..<hiddenDim:
result.W[h] = newSeq[float](inputDim)
for i in 0..<inputDim:
# Uniform in [-1,1] scaled by 1/sqrt(inputDim) keeps W x in a range tanh
# does not saturate on. (No randn in std/random; uniform is fine here.)
result.W[h][i] = (rand(rng, 1.0) * 2.0 - 1.0) / sqrt(float(inputDim))
result.b.add(rand(rng, 1.0) * 2.0 - 1.0)
var rj = 0.0
if recurrentGain > 0.0:
rj = clamp(recurrentGain * (rand(rng, 1.0) * 2.0 - 1.0), -ElmRMax, ElmRMax)
result.r.add(rj)
result.hPrev = newSeq[float](hiddenDim)
result.beta = zeroMat(hiddenDim, outputDim)
result.P = zeroMat(hiddenDim, hiddenDim)
# P0 = I/lambda: with no data yet the information matrix is exactly the ridge
# lambda*I, and the update below maintains P = (S + lambda*I)^-1. Anything else
# here (I, or I/lambda with the other denominator) silently stops the
# recursion from being the ridge solution.
for i in 0..<hiddenDim: result.P[i][i] = 1.0 / result.lambda
# ── numerics guard ─────────────────────────────────────────────────────────────
proc isSane*(net: ElmNet): bool =
## False as soon as any weight, bias or inverse-correlation entry is
## NaN/Inf — i.e. the RLS recursion has blown up — and false for a net that
## was never `init`ed (zero dims: every allFinite check vacuously passes, and
## the first `hidden` call would trip `x.len == inputDim` inside the gun).
if net.inputDim <= 0 or net.hiddenDim <= 0 or net.outputDim <= 0: return false
if net.W.len != net.hiddenDim or net.beta.len != net.hiddenDim or
net.P.len != net.hiddenDim or net.b.len != net.hiddenDim or
net.r.len != net.hiddenDim or net.hPrev.len != net.hiddenDim:
return false
if not allFinite(net.b): return false
if not allFinite(net.r): return false
if not allFinite(net.hPrev): return false
for rj in net.r:
if abs(rj) >= 1.0: return false # outside the contraction range
if not allFinite(net.beta): return false
allFinite(net.P)
proc resetHidden*(net: var ElmNet) =
## Drop the hidden layer's own state (h(t-1) -> 0) WITHOUT touching anything
## the RLS has learned. The recurrence belongs to a SEQUENCE: a new target,
## a new round or a re-acquired scan track is a new sequence, and carrying
## the old node states into it makes the first few predictions of the new
## sequence wrong for reasons that have nothing to do with beta.
net.hPrev = newSeq[float](net.hiddenDim)
proc softReset*(net: var ElmNet) =
## Drop everything learned; keep the fixed hidden layer (it is a pure
## function of the seed, so re-deriving it would change the net's identity).
net.beta = zeroMat(net.hiddenDim, net.outputDim)
net.P = zeroMat(net.hiddenDim, net.hiddenDim)
for i in 0..<net.hiddenDim: net.P[i][i] = 1.0 / net.lambda
net.samples = 0
net.resetHidden() # h(t-1) is state too: a reset net starts at h(0)=0
inc net.resets
proc recurrent*(net: ElmNet): bool {.inline.} =
## Is any hidden node recurrent? (All-zero r is the plain feed-forward ELM,
## and this is the flag that skips the recurrent term in the inner loop.)
for rj in net.r:
if rj != 0.0: return true
false
# ── forward / update ──────────────────────────────────────────────────────────
proc hidden*(net: ElmNet, x: openArray[float]): seq[float] =
## g = act(W x + b + r . h_prev), length hiddenDim. READ-ONLY: it reads the
## current state and never advances it, so the CALLER owns the clock. With
## every r_j = 0 (the default) the recurrent term is skipped entirely and
## this is the textbook feed-forward g.
doAssert x.len == net.inputDim
let rec = net.recurrent()
result = newSeq[float](net.hiddenDim)
for h in 0..<net.hiddenDim:
var s = net.b[h]
for i in 0..<net.inputDim: s += net.W[h][i] * x[i]
if rec: s += net.r[h] * net.hPrev[h]
result[h] = net.applyAct(s)
proc readOut*(net: ElmNet, g: openArray[float]): seq[float] =
## y = g^T beta, length outputDim. Returns zeros if the net went non-finite,
## so a caller can never propagate NaN into the gun's aim.
result = newSeq[float](net.outputDim)
for o in 0..<net.outputDim:
var s = 0.0
for h in 0..<net.hiddenDim: s += g[h] * net.beta[h][o]
result[o] = s
if not isFinite(s): return newSeq[float](net.outputDim)
proc predict*(net: ElmNet, x: openArray[float]): seq[float] =
## y = g(t)^T beta at the CURRENT state, WITHOUT advancing it. Kept
## immutable so a read-only caller (an evaluation sweep, a test) can use it;
## the gun, which owns the clock, calls `predictStep`.
if not net.isSane(): return newSeq[float](net.outputDim)
net.readOut(net.hidden(x))
proc predictStep*(net: var ElmNet, x: openArray[float]): seq[float] =
## One step of the SEQUENCE: y = g(t)^T beta, then h(t-1) <- g(t).
## The caller MUST advance exactly once per time step: a gun that probes four
## bullet speeds per tick has to call this once per TICK, not once per probe,
## or the node state runs at the probe rate instead of the tick rate.
if not net.isSane(): return newSeq[float](net.outputDim)
let g = net.hidden(x)
result = net.readOut(g)
if not net.isSane():
net.resetHidden() # blew up mid-step: drop the state, keep beta
return newSeq[float](net.outputDim)
net.hPrev = g
proc trainHidden*(net: var ElmNet, g: openArray[float],
t: openArray[float]): bool =
## One RLS step on an ALREADY COMPUTED hidden vector. A caller that owns a
## sequence (the gun stores the g of the shot it fired) must use this: the
## label belongs to the activation that actually produced it, and by the time
## a hit resolves (dozens of ticks later) `hidden(x)` would now be computed
## from a DIFFERENT h(t-1), i.e. it would train a different function.
## Returns false (leaving the net sane but untouched) if the sample is
## rejected, and true after a successful update — including the case where the
## step blew up and `softReset` was forced; check `resets` for that.
doAssert g.len == net.hiddenDim
doAssert t.len == net.outputDim
if net.P.len != net.hiddenDim or net.beta.len != net.hiddenDim:
net.softReset()
if not net.isSane(): net.softReset()
for v in g:
if not isFinite(v): return false
for v in t:
if not isFinite(v): return false
let Pg = matVec(net.P, g)
# rho enters here too: M = P^-1 becomes M/rho + g g^T this step.
let denom = 1.0 + net.rho * dot(g, Pg)
if not isFinite(denom) or denom <= 0.0:
net.softReset()
return true # consumed, but as a reset
# P = rho P - rho^2 (P g)(g^T P) / (1 + rho g^T P g)
# = rho (I - K g^T) P with K = P_new g — the subtracted term is
# K_i * (g^T P)_j = Pg[i]*Pg[j], NOT g[j]*P[i][j] (a different, wrong recursion).
var k = newSeq[float](net.hiddenDim)
for i in 0..<net.hiddenDim:
for j in 0..<net.hiddenDim:
net.P[i][j] = (net.P[i][j] - net.rho * Pg[i] * Pg[j] / denom) * net.rho
var ki = 0.0
for j in 0..<net.hiddenDim: ki += net.P[i][j] * g[j]
k[i] = ki
# beta += K (t - g^T beta), K = P_new g
for o in 0..<net.outputDim:
var pred = 0.0
for h in 0..<net.hiddenDim: pred += g[h] * net.beta[h][o]
let e = t[o] - pred
for h in 0..<net.hiddenDim: net.beta[h][o] += k[h] * e
inc net.samples
if not net.isSane():
net.softReset()
return true
true
proc train*(net: var ElmNet, x: openArray[float], t: openArray[float]): bool =
## Convenience wrapper: g = hidden(x) at the CURRENT state, then one RLS step.
## Fine for a batch/streaming learner; a sequence learner that can go back in
## time (the gun, whose label arrives long after the shot) must use
## `predictStep` + `trainHidden` instead.
doAssert x.len == net.inputDim
for v in x:
if not isFinite(v): return false # reject at the trust boundary, not
# after tanh has saturated it to 1.0
let g = net.hidden(x)
net.trainHidden(g, t)
File diff suppressed because it is too large Load Diff
+728
View File
@@ -0,0 +1,728 @@
## waveelm.nim — the WaveElm gun. The ONLY wave mechanism is a SIMULATED
## OMNIDIRECTIONAL EXPANDING RING; the ELM corrects the ring's MEASUREMENT.
##
## ── THE RING ─────────────────────────────────────────────────────────────────
## The ring is `RingProbes` rays fired simultaneously from the shooter at one
## bullet speed; at offset k the ring's radius is `k * bulletSpeed(power)`. It
## is a SIMULATION of an instrument, not a shot pattern: nothing is fired, so
## it costs no energy and no cooldown and it is legal at any time. What it
## measures, for the first enemy it touches, is the MEETING POINT — the
## interception radius (== the distance to the enemy at contact) and the bearing
## of the probe ray that touched it. Distance + bearing is a complete polar
## position measurement of a target we have already scanned.
##
## WHY A RING AND NOT A DIRECTED SHOT (measured, /tmp/ringspike, now removed —
## the spike source is kept at /tmp/ringspike/ring_backup_keep.nim):
## * directed design: only 21.5% of aimed offsets survive as training labels
## (mean labelled magnitude 0.23x the truth) — an aimed bullet misses a
## strafing target, and a miss carries no label. Interception ~21.5%.
## * ring: 720 probes, 100.00% interception (108/108), 0.92-0.93 labels per
## tick per enemy.
## * raw ring noise WITHOUT the ELM: radius error RMS 6.0 px, bearing
## quantisation 0.97 px.
##
## ── WHAT THE ELM LEARNS: A BIAS CORRECTION (mode b), NOT A POSITION ─────────
## The net predicts the CORRECTION to apply to the ring's reconstructed position
## — a BIAS, never a position. The alternative, predicting the enemy's position
## outright (spike mode a), was measured and REFUTED: flat 3.4-4.3 px RMS on
## smooth/accelerating regimes but a collapse to 29-44 px RMS on abrupt/burst,
## i.e. exactly when it matters; bias correction (mode b) stayed flat 3.4-4.3 px
## across ALL regimes at a 100% in-BotRadius rate. Baseline directed numbers for
## the same regimes: glide 7.990/11.815/23.072 RMS, burst 8.083/14.434/20.927.
##
## HONEST CAVEAT on those numbers, since it is easy to over-read them: mode (b)
## was measured with a feature map (velocity, ring distances, age) that has NO
## BEARING term, so part of its flatness is that the best correction it can
## express is the MEAN bias, which for a strafing target is near zero. The
## correction is therefore applied CARTESIAN here rather than in polar
## (dDist, dBear): the ring measures polar, but the feature map has no way to
## know which way the ring pointed, so a polar label would be unlearnable and
## would collapse to its own mean. See the label note in `onResult`.
##
## ── THE DAMAGE SHOT ─────────────────────────────────────────────────────────
## The ring produces labels; it does not damage anything. Real bullets are aimed
## at the ENEMY POSITION RECONSTRUCTED from the ring measurement
## (`self + (dist, bear)`) plus the ELM's bias correction, i.e. exactly the
## quantity the ring is well-conditioned about. When the gun has no ring
## measurement yet (a target it has seen once), it degrades to aiming at the
## scan position itself — a HeadOn shot, the rack's floor, never a crash.
##
## ── WHAT HAPPENS IF VIRTUAL BULLETS ARE DISABLED ───────────────────────────
## The ring is SIM-ONLY: it is simulated inside the gun from the scan track, so
## the gun's aim does not depend on the virtual-bullet tracker at all. What the
## tracker provides is the LABEL — `onResult` is fed by
## `VirtualTracker.tickBullets`, which is where the polar-free Cartesian bias
## between the ring reconstruction and the enemy comes from. With
## `TR_MODULE_VBULLETS=0` (or the rack unmembership `off`) `predict` still runs
## and still aims at the ring reconstruction — the gun degrades to the ring's raw
## measurement with NO learned correction, never to a crash and never to a
## HeadOn/no-op. With virtual bullets on, `VBulletAdmitOnly` already forces
## `admit[WaveElmId]` in ModularBot (see the `admit` block), so the gun is never
## skipped for being unselected.
##
## ── MEASURED, HONESTLY ──────────────────────────────────────────────────────
## The offline benchmark with the ring as the base (bench_waveelm_temporal.nim,
## same regimes as before): glide smooth 0.06 px / accel 0.11 px / abrupt 25.5 px
## RMS, burst smooth 29.9 / accel 37.6 / abrupt 80.1 px. The OLD directed
## baselines were glide 7.990/11.815/23.072 and burst 8.083/14.434/20.927. So:
## the ring is dramatically better where the target flies straight (0.06 px vs
## 8 px) and dramatically WORSE where it turns (80 px vs 21 px), because the ring
## is a constant-velocity lead and a turning target breaks that assumption over
## a long flight — and because the broken base means no confirmed hits, hence no
## labels, hence nothing to learn from. This is a documented ceiling, not a
## tuning miss: see `testSupervision` in common_libs/tests/test_waveelm.nim.
##
## ── SCAN-ONLY LEGITIMACY ────────────────────────────────────────────────────
## `ringFireFromScan` reads exactly three things: `state.enemyX/enemyY` (the
## position of the target the radar SELECTED, i.e. a scan), and the velocity
## DERIVED from the last two scans of that same target. It never reads
## `state.enemies`, the tracker's table, or any position at any tick other than
## the scan it was given. It is therefore scan-only by construction, and it is
## also honest in the deeper sense: it never needs to know where the enemy WILL
## be, because the ring's contact radius is a measurement of where it IS.
## See the module-level test in common_libs/tests/test_waveelm_ring.nim.
##
## ── THE LEFT/RIGHT OSCILLATION (measured, fixed, unchanged) ─────────────────
## A shot fired at tick T resolves at T + flightTime (20-80 ticks, far longer
## than the RLS memory 1/(rho-1) ~ 12 ticks), so the label describes the bias
## at the ARRIVAL tick while the features describe the FIRE tick. `WaveResolve
## Features` rebuilds each in-flight trace's features at its arrival tick so
## feature-time == label-time. Measured effect (perpendicular = left-right
## component of the aim error): accel 16.57 px -> 7.67 px, abrupt 5.12 px ->
## 1.18 px; a proven NO-OP when feedback is not delayed.
##
## ── ONE NET, SHARED ─────────────────────────────────────────────────────────
## A single `ElmNet` shared by every target, per-target state (scan track, ring
## measurement, pending traces) kept separately. The bias being learned is mostly
## a property of THIS BOT, and `rho` (the RLS forgetting factor, memory ~50
## samples) is what lets the shared net track a change of target.
import std/[math, tables]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import guns/elm
const
# ── the ladder (rung == ring speed) ─────────────────────────────────────────
WavePowers* = [1.0, 2.0, 3.0] ## speed 17 / 14 / 11 px/tick
WaveRungs* = WavePowers.len
# ── RING GEOMETRY ──────────────────────────────────────────────────────────
RingArenaW* = 800.0 ## ASSUMPTION: the Tank Royale arena this gun is sized
RingArenaH* = 600.0 ## for. See `ringProbeCount` for why and what breaks.
RingSafety* = 2.0 ## safety factor on the probe count (see below)
# ── scan history ────────────────────────────────────────────────────────────
WaveTrackCap* = 9 ## == WaveLagKMax + 1: the longest lag window + 1
WaveLagKMax* = 8
# ── ELM shape ───────────────────────────────────────────────────────────────
WaveInputDim* = 10 ## width at lagK = 2 (two displacements)
WaveHiddenDim* = 16
WaveLambda* = 0.1
WaveRho* = 1.02 ## memory 1/(rho-1) ~ 50 samples; 1.05 is too short.
# ── (A) LAG WINDOW ──────────────────────────────────────────────────────────
WaveLagK* = 2 ## scan-to-scan displacements in the feature map
WaveRelmGain* = 0.0 ## RELM recurrent gain; 0 = recurrence OFF (measured a
## wash to a regression; left in, defaulted off)
# ── guards ──────────────────────────────────────────────────────────────────
WaveMaxResidual* = 3.0 * BotRadius
## 54 px on the Cartesian bias between the ring reconstruction and where the
## enemy was. MEASURED: it essentially never fires (a confirmed hit cannot be
## 54 px from the aim point).
WaveGateAdapt* = 0.0 ## adapting gate; 0 = fixed (measured identical)
WaveMaxOffset* = 2.0 * BotRadius
## clamp on the learned correction, in px for the radial output and, for the
## angular output, converted to px at the measured distance so both halves
## share one physical ceiling.
# ── flight-time feature alignment ───────────────────────────────────────────
WaveResolveFeatures* = true
# ── pending-trace ring ──────────────────────────────────────────────────────
WaveTraceSlots* = 1024
# ── the ring geometry ─────────────────────────────────────────────────────────
#
# N PROBES. The ring must have no angular GAP wider than a bot at maximum range,
# or an enemy sitting in the gap is never touched at all (the measurement, and
# therefore the label, is lost for that bearing forever). The gap at radius r is
# `2*pi*r/N`, so
#
# N >= 2*pi*rMax / BotRadius
#
# With rMax = the arena DIAGONAL (the largest possible separation between two
# bots) and BotRadius = 18 px: rMax = hypot(800, 600) = 1000 px, so
# N >= 2*pi*1000/18 = 349. `RingSafety` doubles that for margin (the enemy is a
# DISC, not a point, and it MOVES between the ring's radii):
#
# N = 2 * 349 = 698 -> rounded up to a multiple of 60 -> 720
#
# ASSUMPTION, STATED: rMax is the 800x600 diagonal above. `RingArenaW/H` are the
# single place that assumption lives. If the real map is bigger, the derived
# count grows automatically (`ringProbeCount` is a function of rMax); if it is
# smaller, 720 probes is merely more than needed — never fewer. The ONLY thing
# that breaks with too small a map is an angular gap wider than a bot at the
# corner, i.e. missed bearings; nothing crashes and nothing NaNs.
proc ringProbeCount*(rMax: float): int =
## Smallest probe count whose angular gap stays inside a bot's radius at
## `rMax`, with `RingSafety` margin, rounded up to a multiple of 60 (60 is the
## spike's measured value's factor: 720 = 12*60, and a multiple of 60 keeps
## `RingDirs` cheap and the geometry easy to state).
if not (rMax > 0.0): return 60
let need = int(ceil(2.0 * PI * rMax / BotRadius * RingSafety))
max(60, ((need + 59) div 60) * 60)
const
RingRMax* = hypot(RingArenaW, RingArenaH)
RingProbes* = ringProbeCount(RingRMax) ## 720 for the 800x600 assumption
let RingDirs*: seq[float] = block:
## Probe bearings, 0 = East, CCW positive (the Tank Royale convention).
var d = newSeq[float](RingProbes)
for i in 0..<RingProbes: d[i] = 2.0 * PI * i.float / RingProbes.float
d
type
RingHit* = object
found*: bool
dist*: float ## ring radius at first contact (== distance to enemy)
bearing*: float ## rad, bearing of the probe ray that made contact
tick*: int ## absolute tick of first contact (fireTick + k)
missDist*: float ## closest approach of the ray to the enemy
proc ringFireAt*(sx, sy: float, spd: float,
px, py: seq[float], fireTick: int,
maxRadius = RingRMax): RingHit =
## Simulate ONE expanding ring of `RingProbes` rays of SPEED `spd`, fired at
## `fireTick` from (sx, sy). `px/py` are the target's positions indexed by
## ABSOLUTE TICK; the ring is tested against the target's position on each tick
## `fireTick + k`, where its radius is `k * spd`. The first contact is the
## interception.
if not (spd > 0.0):
return RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
missDist: Inf)
let maxK = int(ceil(maxRadius / spd))
var closest = Inf ## closest approach of any probe ray, diagnostics
var got = false
var bestR = 0.0 ## the contact radius
var bestBear = 0.0
var bestTick = -1
var bestMiss = 0.0
var bestRadial = Inf ## |eDist - r| of the accepted contact
for k in 1..maxK:
let t = fireTick + k
if t < 0 or t >= px.len: break
let r = k.float * spd
let ex = px[t] - sx
let ey = py[t] - sy
let eAng = arctan2(ey, ex)
let eDist = hypot(ex, ey)
# nearest probe ray (search +-1 index, so quantisation is at most half a gap)
let idx = int(round(eAng / (2.0 * PI) * RingProbes.float)) mod RingProbes
var kbest = Inf
var kidx = 0
for o in [-1, 0, 1]:
let i = (idx + o + RingProbes) mod RingProbes
let perp = abs(eDist * sin(eAng - RingDirs[i]))
if perp < kbest:
kbest = perp
kidx = i
if kbest < closest: closest = kbest
# CONTACT. The ray must sweep the target's DISC (kbest <= BotRadius) AND the
# annulus must be within BotRadius of the target's radius.
#
# BEST k, NOT FIRST k. The ring's radius steps by a whole `spd` per tick, so
# "first contact" is systematically the annulus BELOW the target, biased by
# up to BotRadius (8.5 px mean at the 17 px rung) in the one direction the
# target is moving. Every acceptable annulus is a legal reading of the same
# measurement, so the ring reports the one whose radius is CLOSEST to the
# target's — the maximum-likelihood reading of a quantised instrument.
if kbest <= BotRadius and abs(eDist - r) <= BotRadius:
let radial = abs(eDist - r)
if radial < bestRadial:
bestRadial = radial
got = true
bestR = r
bestBear = RingDirs[kidx]
bestTick = t
bestMiss = kbest
if got:
return RingHit(found: true, dist: bestR, bearing: bestBear,
tick: bestTick, missDist: bestMiss)
RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1, missDist: closest)
proc ringFire*(sx, sy: float, power: float,
px, py: seq[float], fireTick: int,
maxRadius = RingRMax): RingHit =
## `ringFireAt` in bullet-speed form: power -> `bulletSpeed(power)`.
ringFireAt(sx, sy, bulletSpeed(power), px, py, fireTick, maxRadius)
proc ringDecode*(h: RingHit, sx, sy: float): tuple[x, y: float] =
## Ring measurement -> absolute position: the point on the contacted bearing at
## the contacted radius.
(sx + h.dist * cos(h.bearing), sy + h.dist * sin(h.bearing))
# ── helpers ───────────────────────────────────────────────────────────────────
proc isFinite(x: float): bool {.inline.} =
classify(x) notin {fcNan, fcInf, fcNegInf}
proc finiteOr*(x, fallback: float): float {.inline.} =
## Scrub a non-finite float at the trust boundary (see the old note: an Inf in
## an angle wrap loop hangs the bot at 100% CPU).
if isFinite(x): x else: fallback
proc wrapDeg(x: float): float {.inline.} =
## Wrap an angle to [-180, 180). Bounded loop: with a non-finite input the
## condition can stay true while the body makes no progress, which hangs.
if not isFinite(x): return 0.0
result = x
for _ in 0..<4:
if result > 180.0: result -= 360.0
elif result < -180.0: result += 360.0
else: break
proc waveBinForSpeed*(spd: float): int =
## Map a bullet speed back to its power-bin index, or -1.
for i in 0..<len(vb.PowerBins):
if abs(spd - bulletSpeed(vb.PowerBins[i])) < 1e-6: return i
-1
proc waveTraceSlot(fireTick, binIdx: int): int {.inline.} =
((fireTick * len(vb.PowerBins)) + binIdx) mod WaveTraceSlots
# ── types ─────────────────────────────────────────────────────────────────────
type
WaveSample = object
tick: int
x, y: float
WaveTrack = object
## Index 0 is the NEWEST scan. samples[0..1] give the velocity,
## samples[k..k+1] the k-th most recent displacement.
s: array[WaveTrackCap, WaveSample]
n: int
WaveRing* = object
## The newest ring measurement for a target.
valid*: bool
dist*: float ## measured distance, px (== the contact radius)
bear*: float ## measured bearing, rad
fireTick*: int ## the tick the ring was fired on
tick*: int ## the tick the contact resolved on
flight*: float ## tick - fireTick
WaveElmGun* = object
net*: ElmNet
tracks*: Table[int, WaveTrack] ## EnemyInfo.id -> scan history
rings*: Table[int, WaveRing] ## EnemyInfo.id -> newest ring measurement
targetId*: int ## -1 => derive the id from state.enemies[0]
lastId*: int ## the id predict() actually resolved this tick
lastTick*: int ## tick the current scan was pushed on (predict runs
## 4-5x per tick; the scan must be pushed ONCE)
lagK*: int
relm*: float
maxResidual*: float
maxOffset*: float
gateAdapt*: float
recentRms*: float
traces*: array[WaveTraceSlots, WaveTrace]
resolveFeat*: bool
refreshAt*: seq[int] ## slots due for a feature refresh this tick; the queue
## is cleared as it is walked (self-cleaning)
# instrumentation (exported for the tests)
predictCalls*: int
trainedShots*: int
traceMisses*: int
rejectedShots*: int
missShots*: int
ringContacts*: int ## rings that found a contact
ringFires*: int ## rings fired
lastDx*, lastDy*: float ## the last learned correction, in px (Cartesian)
WaveTrace = object
fireTick: int
binIdx: int
resolveTick: int
measDist: float ## the ring measurement this shot was built from
measBear: float
selfX, selfY: float
feat: seq[float]
hid: seq[float] ## the FIRE-time hidden activation g(t); trained on
## directly, because by the time the hit resolves
## h(t-1) has moved on
alive: bool
# ── construction ──────────────────────────────────────────────────────────────
proc waveInputDim*(lagK: int): int {.inline.} =
## Feature width for a given lag window. 8 "static" features + 2 per
## displacement.
WaveInputDim + 2 * (max(2, lagK) - 2)
proc initWaveElmGun*(seed: int64 = 42, lagK = WaveLagK,
relm = WaveRelmGain,
hiddenDim = WaveHiddenDim,
lambda = WaveLambda, rho = WaveRho,
maxResidual = WaveMaxResidual,
maxOffset = WaveMaxOffset,
gateAdapt = WaveGateAdapt,
resolveFeat = WaveResolveFeatures): WaveElmGun =
## Every knob is an override of the module constant of the same name, so an
## offline sweep can compare configs without recompiling per value. A negative
## maxResidual/maxOffset means "no clamp".
result.lagK = clamp(lagK, 2, WaveLagKMax)
result.relm = max(0.0, relm)
result.net = init(inputDim = waveInputDim(result.lagK),
hiddenDim = hiddenDim, seed = seed, outputDim = 2,
lambda = lambda, rho = rho,
recurrentGain = result.relm)
result.maxResidual = maxResidual
result.maxOffset = maxOffset
result.gateAdapt = gateAdapt
result.resolveFeat = resolveFeat
result.targetId = -1
result.lastId = -1
result.lastTick = -1
proc resetTemporalState*(g: var WaveElmGun) =
## Per-episode reset: the RELM hidden state belongs to the SEQUENCE. beta and P
## are kept: what the net has LEARNED is a property of this bot.
g.net.resetHidden()
g.lastTick = -1
proc isWarmedUp*(g: WaveElmGun): bool {.inline.} =
## Two scans of the current target: enough to derive a velocity instead of
## falling back to heading*speed.
let id = if g.targetId >= 0: g.targetId else: g.lastId
if id < 0: return false
if g.tracks.hasKey(id): g.tracks[id].n >= 2
else: false
proc ringDecode*(r: WaveRing, sx, sy: float): tuple[x, y: float] {.inline.} =
## The stored per-target measurement, decoded. Falls back to the caller's own
## position when there is no measurement yet (a never-seen target).
if r.valid:
(sx + r.dist * cos(r.bear), sy + r.dist * sin(r.bear))
else: (sx, sy)
proc ringFor*(g: WaveElmGun, id: int): WaveRing {.inline.} =
## The newest ring measurement for a target; an invalid one when it has none.
if g.rings.hasKey(id): g.rings[id] else: WaveRing()
# ── the ring, from SCANS ONLY ─────────────────────────────────────────────────
proc ringFireFromScan*(g: var WaveElmGun, state: WorldState, vx, vy: float,
spd: float): RingHit =
## The LIVE ring. Its entire input is the SELECTED SCAN (`state.enemyX/Y`,
## the position the radar resolved this tick) plus the velocity DERIVED FROM
## THAT TARGET'S OWN LAST TWO SCANS. It reads nothing else: not
## `state.enemies`, not the tracker table, not any other tick's position.
##
## The scan is extended forward at constant velocity for the length of the
## ring's flight, and `ringFire` is run against that extension. The error that
## introduces (the target does not really fly straight) is exactly the BIAS
## the ELM is trained to correct — which is why the ELM's input includes the
## recent displacement window and why the label is a bias, not a position.
let sx = finiteOr(state.selfX, 0.0)
let sy = finiteOr(state.selfY, 0.0)
let ex = finiteOr(state.enemyX, 0.0)
let ey = finiteOr(state.enemyY, 0.0)
let vx = finiteOr(vx, 0.0)
let vy = finiteOr(vy, 0.0)
if not (spd > 0.0):
return RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
missDist: Inf)
let maxK = int(ceil(RingRMax / spd))
var px = newSeq[float](maxK + 1)
var py = newSeq[float](maxK + 1)
for k in 0..maxK:
px[k] = ex + vx * k.float
py[k] = ey + vy * k.float
inc g.ringFires
# `fireTick = 0`: the trajectory above is indexed by OFFSET from now, so the
# contact tick `ringFireAt` reports is the flight time in ticks, not an
# absolute tick.
let h = ringFireAt(sx, sy, spd, px, py, 0, RingRMax)
if h.found: inc g.ringContacts
h
# ── the feature vector ────────────────────────────────────────────────────────
#
# All inputs scaled to roughly unit magnitude so the random hidden layer does not
# saturate its tanhs. Index 0 is the NEWEST scan. Layout (lagK displacements):
#
# [0] vx [1] vy derived velocity, px/tick
# [2] dist RING-measured distance (scan distance before the
# first contact), /1000
# [3] hdelta range, closing/opening (from the scan heading)
# [4+2k] dx_k [5+2k] dy_k the k-th most recent scan-to-scan displacement,
# k = 0 is the newest, /16 px per tick
# [4+2*lagK] age staleness of the newest scan, ticks
# [5+2*lagK] flight ring flight time (ticks) to the contact, /64
proc waveFeatures*(g: WaveElmGun, state: WorldState, vx, vy, flightTime: float):
seq[float] =
let id = if g.targetId >= 0: g.targetId
elif state.enemies.len > 0: state.enemies[0].id
else: 0
# Sanitise at the trust boundary: every float that comes out of `state` (and
# every argument) is finite before it reaches arithmetic that assumes progress.
let ex = finiteOr(state.enemyX, 0.0)
let ey = finiteOr(state.enemyY, 0.0)
let sx = finiteOr(state.selfX, 0.0)
let sy = finiteOr(state.selfY, 0.0)
let heading = finiteOr(state.enemyHeading, 0.0)
var vx = finiteOr(vx, 0.0)
var vy = finiteOr(vy, 0.0)
var flightTime = finiteOr(flightTime, 0.0)
let dx = ex - sx
let dy = ey - sy
let los = arctan2(dy, dx)
# heading delta, wrapped: positive = the target moves to the LEFT of the line
# of sight (opening range), negative = closing.
let hdelta = wrapDeg(heading - radToDeg(los))
# The RANGE the net reasons about is the RING's measurement when there is one:
# the ring is the instrument, the scan distance is only what it is calibrated
# against.
let ring = g.ringFor(id)
let dist = if ring.valid: ring.dist else: hypot(dx, dy)
let lagK = max(2, g.lagK)
result = newSeq[float](waveInputDim(lagK))
result[0] = vx / 8.0
result[1] = vy / 8.0
result[2] = dist / 1000.0
result[3] = hdelta / 180.0
var age = 0.0
if g.tracks.hasKey(id):
let tr = g.tracks[id]
# Each displacement is normalised by its OWN tick gap, so a late scan
# contributes a per-tick velocity rather than a 3-tick one.
for k in 0..<lagK:
if tr.n >= k + 2:
let gap = (tr.s[k].tick - tr.s[k + 1].tick).float
if gap >= 1.0:
result[4 + 2 * k] = (tr.s[k].x - tr.s[k + 1].x) / (16.0 * gap)
result[4 + 2 * k + 1] = (tr.s[k].y - tr.s[k + 1].y) / (16.0 * gap)
age = (state.tick - tr.s[0].tick).float
result[4 + 2 * lagK] = age / 8.0
result[5 + 2 * lagK] = flightTime / 64.0
for i in 0..<result.len:
if not isFinite(result[i]): result[i] = 0.0
proc pushScan(g: var WaveElmGun, id: int, tick: int, x, y: float) =
let tr = addr g.tracks.mgetOrPut(id, WaveTrack())
for i in countdown(WaveTrackCap - 1, 1): tr.s[i] = tr.s[i - 1]
tr.s[0] = WaveSample(tick: tick, x: x, y: y)
if tr.n < WaveTrackCap: inc tr.n
proc derivedVelocity(g: WaveElmGun, id: int, state: WorldState): tuple[vx, vy: float] =
## Velocity from the last two scans of THIS target; else heading*speed, the
## fallback every other gun in the rack uses.
result = (finiteOr(cos(degToRad(state.enemyHeading)) * state.enemySpeed, 0.0),
finiteOr(sin(degToRad(state.enemyHeading)) * state.enemySpeed, 0.0))
if g.tracks.hasKey(id):
let tr = g.tracks[id]
if tr.n >= 2:
let gap = (tr.s[0].tick - tr.s[1].tick).float
if gap >= 1.0:
result.vx = finiteOr((tr.s[0].x - tr.s[1].x) / gap, 0.0)
result.vy = finiteOr((tr.s[0].y - tr.s[1].y) / gap, 0.0)
# ── the Gun concept ───────────────────────────────────────────────────────────
proc predict*(g: var WaveElmGun, state: WorldState, bulletSpeed: float): GunPrediction =
inc g.predictCalls
let id = if g.targetId >= 0: g.targetId
elif state.enemies.len > 0: state.enemies[0].id
else: 0
# (B) PER-ENEMY TEMPORAL RESET: the RELM node state is the state of a
# SEQUENCE, and a different target is a different sequence.
if g.lastId != id: g.net.resetHidden()
g.lastId = id
# ONE scan push per tick: the harness calls predict 4-5 times a tick.
let newTick = state.tick != g.lastTick
if newTick:
g.lastTick = state.tick
g.pushScan(id, state.tick, state.enemyX, state.enemyY)
let (vx, vy) = g.derivedVelocity(id, state)
# ── THE RING ────────────────────────────────────────────────────────────────
# One ring per rung per new tick, at that rung's speed. The contact resolves
# `flight` ticks later; until then the previous measurement stays in force.
let ring = g.ringFor(id)
var h = RingHit(found: false, dist: NaN, bearing: 0.0, tick: -1,
missDist: Inf)
if newTick or not ring.valid:
h = g.ringFireFromScan(state, vx, vy, bulletSpeed)
if h.found:
g.rings[id] = WaveRing(valid: true, dist: h.dist, bear: h.bearing,
fireTick: state.tick, tick: state.tick + h.tick,
flight: float(h.tick))
let meas = g.ringFor(id)
let measDist = if meas.valid: meas.dist else: hypot(state.enemyX - state.selfX,
state.enemyY - state.selfY)
let measBear = if meas.valid: meas.bear
else: arctan2(state.enemyY - state.selfY,
state.enemyX - state.selfX)
let flight = if meas.valid: meas.flight else: measDist / max(bulletSpeed, 1e-6)
# ── FLIGHT-TIME FEATURE REFRESH (WaveResolveFeatures) ──────────────────────
# Every trace whose bullet resolves THIS tick has its features rebuilt from the
# state as it is NOW, so the label is paired with the state the LABEL describes
# rather than the state the shot was fired from. Runs once per tick, after the
# scan push (so the trace sees this tick's scan exactly as a predict at this
# tick would).
if g.resolveFeat and newTick and g.refreshAt.len > 0:
var keep: seq[int] = @[]
for slot in g.refreshAt:
var tr = g.traces[slot]
if tr.alive and tr.resolveTick == state.tick:
let f2 = g.waveFeatures(state, vx, vy, flight)
tr.feat = f2
tr.selfX = state.selfX
tr.selfY = state.selfY
if g.net.isSane(): tr.hid = g.net.hidden(f2)
g.traces[slot] = tr
elif not tr.alive:
discard # the bullet died (wall / stale target); drop the reminder
else:
keep.add slot
g.refreshAt = keep
# ── THE LEARNED BIAS CORRECTION ─────────────────────────────────────────────
# The learned bias, px, in the world frame (see the module header on why the
# ring measures polar but the correction is applied Cartesian).
var dDist = 0.0
var dBear = 0.0
# (named for the net's two outputs; both are px, see the label note in onResult)
var gh: seq[float]
if g.net.isSane():
let feat = g.waveFeatures(state, vx, vy, flight)
gh = g.net.hidden(feat)
if newTick: g.net.hPrev = gh
let off = g.net.readOut(gh)
if off.len == 2 and isFinite(off[0]) and isFinite(off[1]):
dDist = off[0]
dBear = off[1]
dDist = clamp(dDist, -g.maxOffset, g.maxOffset)
dBear = clamp(dBear, -g.maxOffset, g.maxOffset)
g.lastDx = dDist
g.lastDy = dBear
# ── THE DAMAGE SHOT ─────────────────────────────────────────────────────────
# Reconstruct the enemy from the ring measurement and apply the correction.
let (rx, ry) = (finiteOr(state.selfX, 0.0) + measDist * cos(measBear) + g.lastDx,
finiteOr(state.selfY, 0.0) + measDist * sin(measBear) + g.lastDy)
var px = rx
var py = ry
if not (isFinite(px) and isFinite(py)):
# Degenerate input (a NaN/Inf crept in from a scan): the ONE point we know
# is finite is our own position.
px = state.selfX
py = state.selfY
px = clamp(px, BotRadius, max(BotRadius, state.arenaWidth - BotRadius))
py = clamp(py, BotRadius, max(BotRadius, state.arenaHeight - BotRadius))
if not (isFinite(px)): px = BotRadius
if not (isFinite(py)): py = BotRadius
# Pending trace: the ring measurement AND the hidden activation this shot was
# built from, so onResult can train on EXACTLY those inputs.
let binIdx = waveBinForSpeed(bulletSpeed)
if binIdx >= 0:
let feat = g.waveFeatures(state, vx, vy, flight)
let slot = waveTraceSlot(state.tick, binIdx)
let resolveTick = state.tick + max(1, int(round(flight)))
g.traces[slot] = WaveTrace(fireTick: state.tick, binIdx: binIdx,
resolveTick: resolveTick,
measDist: measDist, measBear: measBear,
selfX: state.selfX, selfY: state.selfY,
feat: feat, hid: gh, alive: true)
if g.resolveFeat and resolveTick > state.tick and resolveTick notin g.refreshAt:
g.refreshAt.add slot
GunPrediction(x: px, y: py,
# The correction's magnitude IS the gun's intrinsic per-sample
# confidence.
confidence: hypot(g.lastDx, g.lastDy))
proc onResult*(g: var WaveElmGun, e: FeedbackEvent) =
# ── guard 1: only CONFIRMED hits carry a label ──────────────────────────────
# A miss says the aim was wrong, not where it was wrong, so it is not a
# sample. It is counted, never trained on.
if not e.hit:
inc g.missShots
return
let binIdx = if e.powerBin >= 0 and e.powerBin < len(vb.PowerBins): e.powerBin
else: waveBinForSpeed(bulletSpeed(e.bulletPower))
if binIdx < 0:
inc g.traceMisses
return
# ── guard 3: we need the ring measurement this shot was built from; without
# the trace there is no sample, and fabricating one would train the net on a
# measurement that never existed ─────────────────────────────────────────────
let slot = waveTraceSlot(e.fireTick, binIdx)
if not g.traces[slot].alive or g.traces[slot].fireTick != e.fireTick or
g.traces[slot].binIdx != binIdx:
inc g.traceMisses
return
if not (isFinite(e.actualX) and isFinite(e.actualY)):
inc g.rejectedShots
return
# ── THE LABEL: the BIAS of the RING RECONSTRUCTION. It is the offset between
# where the ring SAYS the enemy is (its measurement decoded into a position,
# `tr.measDist/bear` — the "base") and where it actually was, rotated into the
# world frame. Cartesian, not polar, because the feature map carries velocity
# and range but NO bearing term: a polar label would be unlearnable (the net
# could not tell which way the ring was pointing) and would collapse to its
# own mean. This is the same quantity the old directed gun learned, with the
# intercept replaced by the ring's reconstruction as the base. ───────────────
let tr = g.traces[slot]
let (bx, by) = (tr.selfX + tr.measDist * cos(tr.measBear),
tr.selfY + tr.measDist * sin(tr.measBear))
let dX = e.actualX - bx
let dY = e.actualY - by
if not (isFinite(dX) and isFinite(dY)):
inc g.rejectedShots
return
# ── guard 2: the bias must be physically plausible, measured in PIXELS ──────
var gate = (if g.maxResidual < 0.0: Inf else: g.maxResidual)
if g.gateAdapt > 0.0:
gate = clamp(g.gateAdapt * max(g.recentRms, 1.0),
g.maxResidual * 0.5, g.maxResidual * 4.0)
let rmag = hypot(dX, dY)
if rmag > gate:
inc g.rejectedShots
return
g.recentRms = max(rmag, g.recentRms * 0.95)
if not g.net.isSane(): g.net.softReset()
# Train on the ACTIVATION that was fired, not on a freshly recomputed one: with
# the RELM recurrence on, hidden(feat) now runs against a later h(t-1).
let lab = @[dX, dY]
if tr.hid.len == g.net.hiddenDim:
discard g.net.trainHidden(tr.hid, lab)
else:
discard g.net.train(tr.feat, lab)
g.traces[slot].alive = false
inc g.trainedShots
@@ -0,0 +1,393 @@
## bench_waveelm_temporal.nim — OFFLINE A/B BENCHMARK for the temporal
## modelling of the online ELM gun (guns/waveelm.nim).
##
## WHAT IS MEASURED
## The gun's job is to predict a systematic aim OFFSET that is added to the
## RING RECONSTRUCTION (the base the directed design got from `intercept()`,
## now measured by the ring instead). So the quantity with a ground truth is the
## offset, not the aim point: each tick the harness rebuilds the SAME base the
## gun computed (identical inputs, `ringDecode` over the gun's own ring
## measurement) and compares
##
## error(t) = (gunPred(t) - ice(t)) - trueOffset(t)
##
## before any feedback arrives. That is the aim-offset estimator's prediction
## error, i.e. exactly what a hit/miss decides later. Two metrics:
## * RMS error (px) over the EVAL window (after burn-in)
## * hit rate: fraction of rung-shots whose residual is within BotRadius,
## counted over the WHOLE stream. The gun is only TRAINED on the hits, so
## hit rate is both the score and the amount of supervision available —
## a variant that predicts the offset badly gets fewer labels and can never
## recover. That is the real failure mode being benchmarked.
##
## THE GROUND TRUTH (see `truthOffset`)
## trueOffset(t) = G(t) * (pos(t) - pos(t-L)) + rad(t)
## i.e. "the aim solution that was actually used was L ticks stale, by a gain
## G". This is the turret lag / slew-rate model: the turret points at where the
## target WAS, the ring points at where it WILL be, and the gap is
## the sum of the last L displacements. It is a LINEAR functional of the recent
## displacement history, so any feature set that hands the net the last L
## displacements can represent it exactly — which is precisely the hypothesis
## under test. It is not a strawman: the gun's own doc says the label absorbs
## turret lag.
##
## THE THREE REGIMES (same bias functional form, different temporal character
## of the TARGET, so the estimator is identical and only the input differs)
## a) smooth : constant speed, smooth steady turn (turn-rate quantised,
## as a real bot's heading is), constant gain.
## b) accel : speed and turn rate both ramp with tick, so the offset
## envelope grows with the second derivative.
## c) abrupt : at t = AbruptTick the target flips its strafing direction
## (a 110 deg heading step) AND the gain steps 1.0 -> 1.6:
## the non-stationary case.
##
## Headroom, honestly: regime (a) is nearly linear in the features the gun
## already has, so (a) is expected to show little movement. The signal is in
## (b) and (c).
##
## Run: nim c -r common_libs/tests/bench_waveelm_temporal.nim
## NO battle server, NO runBattle, NO java: pure offline replay, ~1 s.
import std/[math, strformat, sequtils]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import guns/waveelm
const
BenchTicks* = 300 ## ticks per regime (3 regimes x 3 rungs per tick)
BenchBurnIn* = 60 ## ticks of warm-up excluded from the RMS
BenchSelfX* = 100.0
BenchSelfY* = 300.0
ArenaW = 800.0
ArenaH = 600.0
LagTicks* = 4 ## L: how stale the aim solution was
LongLagTicks* = 12 ## a staleness NO explicit lag window can represent
HeadStep = 1.0 ## deg: turn-rate limit of the target's heading
AbruptTick = 150
BenchSeeds = [42'i64, 7, 99] ## ELM/hidden-layer seeds averaged over
# ── the target trajectories ──────────────────────────────────────────────────
type Regime* = enum
rSmooth, rAccel, rAbrupt
proc regimeName*(r: Regime): string =
case r
of rSmooth: "smooth"
of rAccel: "accel"
of rAbrupt: "abrupt"
type Traj* = object
name*: string
px*, py*: seq[float] ## true position per tick
hx*, hy*: seq[float] ## true unit velocity direction per tick
sp*: seq[float] ## true speed per tick
ox*, oy*: seq[float] ## ground-truth systematic offset per tick
proc wrap180(x: float): float =
result = x
for _ in 0..<4:
if result > 180.0: result -= 360.0
elif result < -180.0: result += 360.0
else: break
proc buildTraj*(r: Regime, jitter: bool, lag = LagTicks): Traj =
## Forward integration of a turn-rate-LIMITED heading: the commanded heading
## turns smoothly, the actual heading is quantised to HeadStep deg. That
## quantisation is the tick-scale structure that makes the L-tick-averaged
## displacement different from the instantaneous one — it is what a lag
## window buys, and it is a real property of Tank Royale bots (they are
## commanded, not continuous).
result.name = regimeName(r)
result.px = newSeq[float](BenchTicks)
result.py = newSeq[float](BenchTicks)
result.hx = newSeq[float](BenchTicks)
result.hy = newSeq[float](BenchTicks)
result.sp = newSeq[float](BenchTicks)
var x = 400.0
var y = 300.0
var cmd = degToRad(20.0) ## commanded heading
var act = cmd ## actual (quantised) heading
## Irregular burst jitter: a seeded coin per tick, speed x0 or x2, mean x1.
## This is the tick-scale structure a lag window exists to filter: real bots
## do not glide at a constant px/tick (they are tickRate-limited, they stop
## and go, the radar only catches them on some ticks), so the instantaneous
## displacement is a poor estimator of the motion the bias was built from,
## while a 4-tick average is a good one. The seed is fixed, so the burst
## pattern is identical on every run.
var js = 0x2545F491'i64
for t in 0..<BenchTicks:
var speed, turn: float
case r
of rSmooth:
speed = 4.0
turn = 3.0 ## deg/tick, steady
of rAccel:
speed = 2.5 + 0.013 * t.float # 2.5 -> 6.4 px/tick
turn = 2.0 + 0.018 * t.float # 2.0 -> 7.3 deg/tick
of rAbrupt:
speed = if t < AbruptTick: 4.5 else: 5.5
turn = if t < AbruptTick: 3.0 else: -3.0
if jitter:
js = (js * 1103515245 + 12345) and 0x7FFFFFFF
speed *= (if ((js shr 12) and 1) == 0: 0.4 else: 1.6)
# Keep the target INSIDE the gun's solvable envelope. A target that
# outruns the slowest rung (bulletSpeed(3.0) = 11 px/tick) has NO
# intercept: t = |p + v t| / spd has no root, the fixed point diverges and
# the aim point leaves the arena — a geometry failure of the intercept
# solver, not a property of the offset estimator being benchmarked.
if speed > 10.0: speed = 10.0
act = degToRad(round(radToDeg(act) / HeadStep) * HeadStep)
result.px[t] = x
result.py[t] = y
result.hx[t] = cos(act)
result.hy[t] = sin(act)
result.sp[t] = speed
x += cos(cmd) * speed
y += sin(cmd) * speed
# Keep the run inside the arena. A hard position clamp here would fake a
# wall bounce (and a velocity that teleports), so instead the COMMANDED
# heading is steered back toward the centre before the border is reached.
if x < 150 or x > ArenaW - 150 or y < 150 or y > ArenaH - 150:
cmd = arctan2(ArenaH / 2.0 - y, ArenaW / 2.0 - x)
else:
cmd = degToRad(wrap180(radToDeg(cmd) + turn))
# ground truth: the aim solution was L ticks stale, scaled by the gain
let gain = proc(t: int): float =
case r
of rSmooth: 1.0
of rAccel: 0.9 + 0.0015 * t.float # the offset envelope grows
of rAbrupt: (if t < AbruptTick: 1.0 else: 1.6)
result.ox = newSeq[float](BenchTicks)
result.oy = newSeq[float](BenchTicks)
for t in 0..<BenchTicks:
let a = max(0, t - lag)
let (px, py) = (result.px[t], result.py[t])
let (qx, qy) = (result.px[a], result.py[a])
# the stale solution lags along the DISPLACEMENT VECTOR: what the turret
# was pointing at when the solution was made, minus where it is now, in the
# frame the offset is applied in. Summed displacement, scaled by the gain.
result.ox[t] = gain(t) * (px - qx)
result.oy[t] = gain(t) * (py - qy)
proc mkState*(t: int, x, y, hx, hy, sp: float): WorldState =
WorldState(
enemyX: x, enemyY: y,
enemyHeading: radToDeg(arctan2(hy, hx)), enemySpeed: sp, enemyEnergy: 100.0,
selfX: BenchSelfX, selfY: BenchSelfY, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: ArenaW, arenaHeight: ArenaH, tick: t,
enemies: @[EnemyInfo(id: 1, x: x, y: y, energy: 100.0,
heading: radToDeg(arctan2(hy, hx)), speed: sp,
lastSeenTick: t)])
# ── the benchmark ────────────────────────────────────────────────────────────
type
BenchResult* = object
rms*: float ## px, eval window
hitRate*: float ## whole stream
shots*: int
labels*: int ## samples that actually reached beta
rejected*: int ## samples the validity gate threw away
BenchCfg* = object
name*: string
seed*: int64
lagK*: int ## number of scan-to-scan displacements in the features
relm*: float ## RELM gain, 0.0 = no recurrence
hiddenDim*: int ## hidden nodes (the (C) capacity probe)
# ── the tunable axes (0 / negative = module default) ──────────────────
lambda*: float ## ridge
rho*: float ## forgetting factor
maxResidual*: float ## validity gate, negative = no gate
maxOffset*: float ## offset clamp, negative = no clamp
gateAdapt*: float ## adapting-gate factor, 0 = fixed gate
aimErr*: float ## px: turret error — the bullet flies to aimPoint +
## aimErr*rotating unit vector, so a CONFIRMED hit can
## carry a residual well outside BotRadius. 0 = the
## gun is perfect, in which case a hit implies
## |residual| <= BotRadius and WaveMaxResidual (>=
## BotRadius) can never bind at all.
proc runRegime*(r: Regime, cfg: BenchCfg, jitter: bool, seed: int64,
lag = LagTicks): BenchResult =
let tr = buildTraj(r, jitter, lag)
var g = initWaveElmGun(seed, lagK = cfg.lagK, relm = cfg.relm,
hiddenDim = if cfg.hiddenDim > 0: cfg.hiddenDim
else: WaveHiddenDim,
lambda = if cfg.lambda > 0: cfg.lambda else: WaveLambda,
rho = if cfg.rho > 0: cfg.rho else: WaveRho,
maxResidual = if cfg.maxResidual != 0: cfg.maxResidual
else: WaveMaxResidual,
maxOffset = if cfg.maxOffset != 0: cfg.maxOffset
else: WaveMaxOffset,
gateAdapt = cfg.gateAdapt)
var sq = 0.0
var n = 0
var hits = 0
var shots = 0
var labels = 0
for t in 0..<BenchTicks:
# the SAME velocity derivation the gun does: the displacement between the
# last two scans (one tick apart), else heading*speed before the 2nd scan.
let hdg = radToDeg(arctan2(tr.hy[t], tr.hx[t]))
var vx = cos(degToRad(hdg)) * tr.sp[t]
var vy = sin(degToRad(hdg)) * tr.sp[t]
if t >= 1:
vx = tr.px[t] - tr.px[t - 1]
vy = tr.py[t] - tr.py[t - 1]
let st = mkState(t, tr.px[t], tr.py[t], tr.hx[t], tr.hy[t], tr.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# THE BASE is the gun's own RING RECONSTRUCTION (what used to be the
# intercept solver's aim point): the measurement decoded into a position,
# with NO learned correction on it. Identical inputs, identical code path —
# the metric is the learner's error, not the base's.
let (bx, by) = ringDecode(g.ringFor(st.enemies[0].id),
BenchSelfX, BenchSelfY)
# The truth is clamped exactly as the gun clamps its own aim point, so
# that no metric can be inflated by an asymmetry between the two.
let truthX = clamp(bx + tr.ox[t], BotRadius, ArenaW - BotRadius)
let truthY = clamp(by + tr.oy[t], BotRadius, ArenaH - BotRadius)
let res = hypot(truthX - pr.x, truthY - pr.y)
inc shots
# The BULLET does not fly to the aim point: the turret was pointing
# somewhere else when the trigger broke. `aimErr` rotates slowly so every
# sample lands on a different residual, which is what lets a confirmed
# hit carry a residual LARGER than BotRadius — i.e. what the validity
# gate actually exists to filter.
let ea = cfg.aimErr * 0.7 * t.float
let hitX = pr.x + cfg.aimErr * cos(ea)
let hitY = pr.y + cfg.aimErr * sin(ea)
let didHit = hypot(truthX - hitX, truthY - hitY) <= BotRadius
if didHit: inc hits
if t >= BenchBurnIn:
sq += res * res
inc n
# Feed the shot back EXACTLY as the live loop does: the true target
# position, hit iff the residual is inside the hit circle. A miss is
# counted, never trained on — that is the gun's own guard 1.
let before = g.trainedShots
g.onResult(FeedbackEvent(
prediction: pr, actualX: truthX, actualY: truthY,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: res, hit: didHit, confidence: pr.confidence))
labels += g.trainedShots - before
if n > 0: result.rms = sqrt(sq / n.float)
result.hitRate = (if shots > 0: hits.float / shots.float else: 0.0)
result.shots = shots
result.labels = labels
result.rejected = g.rejectedShots
proc describeGroundTruth() =
echo "── ground truth ──"
echo &" L ticks stale, turn quantised to {HeadStep} deg"
for lag in [LagTicks, LongLagTicks]:
echo " --- L = " & $lag & " ticks" &
(if lag > WaveLagKMax: " (> WaveLagKMax = " & $WaveLagKMax &
": NO lag window can represent it exactly ---)" else: "")
for j in [false, true]:
for r in Regime:
let tr = buildTraj(r, j, lag)
var sq = 0.0
var hi = 0.0
var loV = Inf
var hiV = 0.0
for t in 0..<BenchTicks:
let m = hypot(tr.ox[t], tr.oy[t])
sq += m * m
hi = max(hi, m)
loV = min(loV, tr.sp[t]); hiV = max(hiV, tr.sp[t])
var loX = Inf
var hiX = 0.0
var loY = Inf
var hiY = 0.0
for t in 0..<BenchTicks:
loX = min(loX, tr.px[t]); hiX = max(hiX, tr.px[t])
loY = min(loY, tr.py[t]); hiY = max(hiY, tr.py[t])
echo &" {tr.name:<7} burst={j:<5} |offset| rms={sqrt(sq/BenchTicks.float):5.1f}" &
&" max={hi:5.1f} px speed {loV:.1f}..{hiV:.1f}" &
&" pos x {loX:.0f}..{hiX:.0f} y {loY:.0f}..{hiY:.0f}"
when isMainModule:
describeGroundTruth()
echo &"── benchmark (RMS px over t >= {BenchBurnIn}, hit rate over the stream," &
&" mean of {BenchSeeds.len} seeds) ──"
let cfgs = [
BenchCfg(name: "baseline lagK2", seed: 42, lagK: 2, relm: 0.0),
BenchCfg(name: "lagK4", seed: 42, lagK: 4, relm: 0.0),
BenchCfg(name: "lagK6", seed: 42, lagK: 6, relm: 0.0),
BenchCfg(name: "lagK8", seed: 42, lagK: 8, relm: 0.0),
BenchCfg(name: "relm0.3", seed: 42, lagK: 2, relm: 0.3),
BenchCfg(name: "relm0.6", seed: 42, lagK: 2, relm: 0.6),
BenchCfg(name: "lagK6+relm0.3", seed: 42, lagK: 6, relm: 0.3)]
var base: array[2, array[Regime, tuple[rms, hit: float]]]
for j in 0..1:
let jitter = j == 1
for r in Regime:
for ci, c in cfgs:
var sr = 0.0
var sh = 0.0
for sd in BenchSeeds:
let b = runRegime(r, c, jitter, sd)
sr += b.rms
sh += b.hitRate
sr /= BenchSeeds.len.float
sh /= BenchSeeds.len.float
if ci == 0: base[j][r] = (rms: sr, hit: sh)
let drms = 100.0 * (sr - base[j][r].rms) / max(1e-9, base[j][r].rms)
let dhit = 100.0 * (sh - base[j][r].hit) / max(1e-9, base[j][r].hit)
let jn = if jitter: "burst" else: "smooth"
echo &" {jn:<6} {regimeName(r):<7} {c.name:<14} rms={sr:7.3f}" &
&" ({drms:+6.1f}%) hit={sh*100:6.2f}% ({dhit:+6.1f}%)"
# ── the fair test for RECURRENCE ───────────────────────────────────────────
# With L = 4 the truth is a 4-tick window, which an explicit lag window can
# represent exactly and a recurrence has nothing left to add. Re-run with
# L = 12: longer than any window the feature map can carry (WaveLagKMax = 8),
# so the only way to build the quantity is to INTEGRATE over time — which is
# precisely what the RELM hidden state does. If recurrence is worth anything
# it has to show up here.
# ── (C) CAPACITY PROBE: is hidden capacity the bottleneck at all? ──────────
# Growing hidden nodes is the Igelnik & Jemcevski / Huang-Wang-Lan option. It
# is only worth it if more capacity moves the number, so measure that FIRST.
echo &"\n── (C) CAPACITY PROBE (long memory, burst) ──"
for hd in [8, 16, 32, 64]:
var sr = 0.0
var sh = 0.0
for r in Regime:
for sd in BenchSeeds:
let b = runRegime(r, BenchCfg(name: "h", seed: sd, lagK: 8, relm: 0.0,
hiddenDim: hd), true, sd, LongLagTicks)
sr += b.rms
sh += b.hitRate
sr /= ((ord(rAbrupt) - ord(rSmooth) + 1).float * BenchSeeds.len.float)
sh /= ((ord(rAbrupt) - ord(rSmooth) + 1).float * BenchSeeds.len.float)
echo &" hiddenDim={hd:<4} mean rms={sr:7.3f} mean hit={sh*100:6.2f}%"
echo &"\n── LONG MEMORY (L = {LongLagTicks} ticks > WaveLagKMax = {WaveLagKMax}) ──"
let lcfgs = [cfgs[0], cfgs[1], cfgs[3], cfgs[4], cfgs[6]]
var lbase: array[Regime, tuple[rms, hit: float]]
for r in Regime:
for ci, c in lcfgs:
var sr = 0.0
var sh = 0.0
for sd in BenchSeeds:
let b = runRegime(r, c, true, sd, LongLagTicks)
sr += b.rms
sh += b.hitRate
sr /= BenchSeeds.len.float
sh /= BenchSeeds.len.float
if ci == 0: lbase[r] = (rms: sr, hit: sh)
let drms = 100.0 * (sr - lbase[r].rms) / max(1e-9, lbase[r].rms)
let dhit = 100.0 * (sh - lbase[r].hit) / max(1e-9, lbase[r].hit)
echo &" burst {regimeName(r):<7} {c.name:<14} rms={sr:7.3f}" &
&" ({drms:+6.1f}%) hit={sh*100:6.2f}% ({dhit:+6.1f}%)"
+24
View File
@@ -0,0 +1,24 @@
## Cross-check probe for `measure_gk_residual.py`: it prints the PRODUCTION aim
## base of `guns/gun_knowledge.nim` -- the exact angle `KnowledgeGun.predict`
## turns into its prediction point -- for every
## ex ey eh es sx sy power
## line on stdin, one float per line on stdout. The measurement script replays
## the aim offline and asserts that its replay equals THIS, so the offline
## numbers cannot silently drift away from the shipped code again.
##
## Build: nim c --path:common_libs common_libs/tests/gk_aim_probe.nim
## (the script builds it itself and skips the cross-check with a loud warning
## if the binary is missing).
import std/[os, strutils]
import guns/gun_knowledge
for line in stdin.lines:
let f = line.splitWhitespace()
if f.len < 7: continue
let feat = GkFeatures(
enemyX: parseFloat(f[0]), enemyY: parseFloat(f[1]),
enemyHeading: parseFloat(f[2]), enemySpeed: parseFloat(f[3]),
selfX: parseFloat(f[4]), selfY: parseFloat(f[5]),
power: parseFloat(f[6]), hasTarget: true)
echo forecastBase(feat, 0.0)
File diff suppressed because it is too large Load Diff
+732
View File
@@ -0,0 +1,732 @@
#!/usr/bin/env python3
"""MEASURE: the gun-knowledge learned ANGULAR RESIDUAL vs the bare
`forecastLinear` base, over VIRTUAL BULLETS on the recorded corpus.
`measure_gk_residual.py` measured the residual on REAL FIRED SHOTS (~55k). This
script re-measures it on the thing the module actually learns from in battle:
VIRTUAL BULLETS. `gun_harness/virtual_bullets.nim` spawns one bullet per power
bin per gun per tick, so the knowledge gun gets 4 resolutions per tick against
the 1/tick a real shot gives it — the offline table was starved by ~63x.
WHAT IS SIMULATED (mirrors virtual_bullets.nim `bmPath` exactly)
---------------------------------------------------------------
PowerBins = [1.0, 1.5, 2.0, 3.0], bulletSpeed = 20 - 3p
every tick with a live target, per power bin:
aim = production base (forecastLinear, ABSOLUTE world bearing,
gkm.production_base) + residual from the table row
spawn a bullet at the shooter position, direction = aim, speed = v
advance it EVERY tick (spawn-then-tick, as the live bot does: the rack
calls spawnBullets before tickBullets on the same tick)
each tick: swept segment vs the RECORDED enemy position of that tick,
hit iff distPointToSegment(...) < BotRadius (18.0) [bmPath]
resolve ONLY at the wall, exactly once, recording hit or miss
on resolution: table update, crediting the usedBin on a hit
a bullet whose target dies, or that is in flight at a round boundary, is
dropped WITHOUT scoring (bmPath's dead-target branch, and
KnowledgeGun.onRoundBoundary clears `pending`, so a post-boundary feedback
updates nothing — and the corpus records the enemy every tick, so there is
no staleness gap to interpolate)
LEARNING POLICY
---------------
The epsilon-greedy policy is NOT in the shipped `gun_knowledge.nim` (that file
documents "The module itself never invents a random bin"); it is applied here
exactly as specified for this measurement:
row.attempts < --explore-attempts -> with p = --eps pick a UNIFORM
random residual bin, else the argmax. At or above the threshold: argmax.
Every resolution increments row.attempts, and `aim` increments it below the
trust threshold (exactly as the module's `inc gk.globalRows[key].attempts`
does). A shot taken with no residual (usedBin -1) is filed under bin 0, the
0 deg NULL, exactly as `update` does. The trust threshold that gates the
argmax is GK_GLOBAL_MIN_ATTEMPTS = 5 in both `aim` and `update`.
SPLIT: held out BY BATTLE, 2-fold, `run1..run7` = fold 0 and `run8..run14` =
fold 1, identical to measure_gk_residual.py. Every virtual bullet is tested
exactly once (each battle is in exactly one held-out fold).
ARMS
base residual 0, i.e. bare `forecastLinear`, through the same spawn/flight
learn residual from the table, frozen at test time
A tick whose learned residual is 0 has a byte-identical ray, so ONE flight is
simulated and credited to both arms (it IS the same bullet, not an average).
Every band/rms number is measured on the SAME set of held-out ticks.
KEY CONFIGS
full the production 15-bit key: band x space x turn x trend x heat x radial
(gun heat is not in the corpus -> pinned to quarter 0, so this key is
COARSER than in battle, never finer)
dt band x turn — the config that won the real-shot sweep (SWEEP F/J)
"""
from __future__ import annotations
import collections
import glob
import json
import math
import os
import random
import statistics
import sys
import time
from multiprocessing import Process, Pool
# reuse the previous script's PRODUCTION-AIM ports verbatim (one definition of
# forecastLinear / production_base / bandOf / spaceOf / the bin layout)
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
_ARGV = sys.argv
sys.argv = [sys.argv[0]]
import measure_gk_residual as gkm # noqa: E402
sys.argv = _ARGV
ROOT = os.environ.get("GK_CORPUS", "/tmp/tfil_ab2/out")
GK_NBINS = 32
GK_NULL_BIN = 0
GK_MIN_BIN_HITS = 3
GK_GLOBAL_MIN_ATTEMPTS = 5
CENTRE = gkm.CENTRE # bin b -> residual degrees
BOT_RADIUS = 18.0
ARENA_W, ARENA_H = 800.0, 600.0
POWER_BINS = [1.0, 1.5, 2.0, 3.0]
SPEEDS = [20.0 - 3.0 * p for p in POWER_BINS] # 17.0 15.5 14.0 11.0
MAX_FLIGHT = 300
BAND_LAB = gkm.BAND_LAB
N_BAND = len(BAND_LAB)
GK_STRAIGHT, GK_RIGHT, GK_LEFT, GK_UNKNOWN = 0, 1, 2, 3
GK_ACCEL, GK_CONST, GK_DECEL = 0, 1, 2
GK_TURN_DEAD, GK_TREND_DEAD = 2.0, 0.05
VEL_WINDOW, RADIAL_WINDOW = 16, 32
ARM_BASE, ARM_BOTH, ARM_LEARN = 0, 2, 1
def key_of(band, space, turning, trend, rad, arm):
if arm == "full":
return ((((band * 3 + space) * 4 + turning) * 4 + trend) * 4 + 0) * 4 + rad
return band * 4 + turning
def nrows(arm):
return 5 * 3 * 4 * 4 * 4 * 4 if arm == "full" else 5 * 4
def best_residual(row):
"""Port of gun_knowledge.bestResidual: argmax over the bins clearing
GK_MIN_BIN_HITS, tie-broken toward the 0 deg NULL. Returns (deg, bin)."""
if row is None:
return 0.0, -1
best_b, best_h = -1, 0
for b in range(GK_NBINS):
h = row[b]
if h < GK_MIN_BIN_HITS:
continue
if h > best_h or (h == best_h and best_b >= 0 and abs(b) < abs(best_b)):
best_h, best_b = h, b
if best_b < 0:
return 0.0, -1
return CENTRE[best_b], best_b
class Table:
def __init__(self, n):
self.n = n
self.att = [0] * n
self.hits = [None] * n
def row(self, k):
r = self.hits[k]
if r is None:
r = self.hits[k] = [0] * GK_NBINS
return r
def residual(self, k):
"""What `aim` returns for this row: below GK_GLOBAL_MIN_ATTEMPTS the
module returns the NULL residual (it only counts the attempt)."""
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
return 0.0, -1
return best_residual(self.hits[k])
def stats(self):
nz, trusted, s = 0, 0, 0.0
for k in range(self.n):
if self.att[k] < GK_GLOBAL_MIN_ATTEMPTS:
continue
trusted += 1
d, _ = best_residual(self.hits[k])
if d != 0.0:
nz += 1
s += abs(d)
return nz, trusted, (s / nz if nz else 0.0)
# ─────────────────────────────────────────────────────────────────────────────
# corpus
# ─────────────────────────────────────────────────────────────────────────────
_CACHE = {}
def battle_files(root):
out = []
for p in sorted(glob.glob(os.path.join(root, "*", "*.jsonl"))):
if p.endswith(".events.jsonl"):
continue
rj, ev = p + ".rounds.json", p[:-6] + ".events.jsonl"
if not (os.path.exists(rj) and os.path.exists(ev)):
continue
tag = os.path.basename(os.path.dirname(p)) + "/" + os.path.basename(p)[:-6]
out.append(dict(tag=tag, path=p, rj=rj, ev=ev,
fold=0 if int(tag.split("run")[1]) <= 7 else 1))
return out
def load_battle(bf):
rounds = json.load(open(bf["rj"]))["rounds"]
starts = [(r["startTick"], r["startTick"] + r["count"]) for r in rounds]
T, EX, EY, EH, ES, SX, SY, SE, EE = [], [], [], [], [], [], [], [], []
RND = []
r = 0
with open(bf["path"]) as f:
for line in f:
if '"tick"' not in line:
continue
o = json.loads(line)
while r + 1 < len(starts) and o["tick"] >= starts[r + 1][0]:
r += 1
RND.append(r)
T.append(o["tick"])
EX.append(o["ex"]); EY.append(o["ey"])
EH.append(o["eh"]); ES.append(o["es"])
SX.append(o["sx"]); SY.append(o["sy"])
SE.append(o["se"]); EE.append(o["ee"])
return dict(T=T, ex=EX, ey=EY, eh=EH, es=ES, sx=SX, sy=SY, se=SE, ee=EE,
rnd=RND, starts=starts)
def get_battle(bf):
b = _CACHE.get(bf["tag"])
if b is None:
b = _CACHE[bf["tag"]] = load_battle(bf)
return b
def cadence(bfs):
gaps = collections.Counter()
rows = 0
for bf in bfs:
prev = None
for line in open(bf["path"]):
if '"tick"' not in line:
continue
t = json.loads(line)["tick"]
rows += 1
if prev is not None:
gaps[t - prev] += 1
prev = t
return rows, gaps
def real_shots(bfs):
"""US (= the `s*` adversary, ModularBot) fired shots, by the same
energy-drop attribution measure_gk_residual.py uses."""
per_run = {}
for bf in bfs:
b = load_battle(bf)
pos = {t: i for i, t in enumerate(b["T"])}
votes = collections.defaultdict(collections.Counter)
def match(t, side, ev):
i, i1 = pos.get(t), pos.get(t + 1)
if i is None or i1 is None:
return False
if abs(b[side + "x"][i] - ev["x"]) > 0.02 or \
abs(b[side + "y"][i] - ev["y"]) > 0.02:
return False
ef = "ee" if side == "e" else "se"
return abs((b[ef][i] - b[ef][i1]) - ev["power"]) < 0.02
for ev in (json.loads(l) for l in open(bf["ev"]) if l.strip()):
if ev.get("type") != "fire":
continue
g = ev.get("tick", 0)
for t in range(g - 8, g + 9):
for side in ("e", "s"):
if match(t, side, ev):
votes[ev["owner"]][side] += 1
n = 0
for o, c in votes.items():
if c and c.most_common(1)[0][0] == gkm.US_SIDE:
n += sum(c.values())
per_run[bf["tag"]] = n
_CACHE.pop(bf["tag"], None)
return per_run
# ─────────────────────────────────────────────────────────────────────────────
# the replay
# ─────────────────────────────────────────────────────────────────────────────
class Acc:
__slots__ = ("n", "tk", "eb2", "eab", "el2", "eal", "hb", "nb", "hl", "nl",
"hd", "hbp", "hlp", "cov", "res")
def __init__(self):
for s in self.__slots__:
setattr(self, s, 0.0)
def add(self, o):
for s in self.__slots__:
setattr(self, s, getattr(self, s) + getattr(o, s))
def as_dict(self):
return {s: getattr(self, s) for s in self.__slots__}
def replay(b, arm, table, learn, thr, eps, rng, test):
"""One battle. learn=True: training replay (learns, scores nothing).
test=True: held-out replay, table frozen, base and learn flown side by side.
Returns (per-band Acc list, counters)."""
T, EX, EY, EH, ES = b["T"], b["ex"], b["ey"], b["eh"], b["es"]
SX, SY, SE, EE = b["sx"], b["sy"], b["se"], b["ee"]
rnd, starts = b["rnd"], b["starts"]
n = len(T)
acc = [Acc() for _ in range(N_BAND)]
c = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0)
a_fx, a_fy, a_ux, a_uy, a_tr, a_sp = [], [], [], [], [], []
a_hit, a_key, a_bn, a_arm, a_bd, a_pi = [], [], [], [], [], []
bh = [0.0] * (n + 1) # per spawn tick: did the BASE flight hit?
prev_t = -10
rr = -1
prev_ex = prev_ey = prev_eh = prev_es = 0.0
has_prev = False
rad_ring = [0.0] * VEL_WINDOW
rad_head = rad_count = 0
fB, band_of = gkm.production_base, gkm.band_of
space_of, wrap180 = gkm.space_of, gkm.wrap180
atan2d = math.degrees
R2 = BOT_RADIUS * BOT_RADIUS
for j in range(n):
t = T[j]
if rnd[j] != rr or t != prev_t + 1:
if a_fx:
c["round"] += len(a_fx)
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
rr = rnd[j]
has_prev = False
rad_count = rad_head = 0
prev_t = t
ex, ey, eh, es = EX[j], EY[j], EH[j], ES[j]
sx, sy = SX[j], SY[j]
e_alive = EE[j] > 0.0
s_alive = SE[j] > 0.0
end = starts[rr][1] if rr >= 0 else t
if e_alive and s_alive:
dx, dy = ex - sx, ey - sy
dist = math.sqrt(dx * dx + dy * dy)
if dist > 1e-6:
c["ticks"] += 1
if has_prev:
rate = wrap180(eh - prev_eh)
turning = GK_LEFT if rate > GK_TURN_DEAD else (
GK_RIGHT if rate < -GK_TURN_DEAD else GK_STRAIGHT)
dv = es - prev_es
trend = GK_ACCEL if dv > GK_TREND_DEAD else (
GK_DECEL if dv < -GK_TREND_DEAD else GK_CONST)
ddx, ddy = ex - prev_ex, ey - prev_ey
spd = math.sqrt(ddx * ddx + ddy * ddy)
frac = 0.0
if spd > 0.1:
frac = abs((ddx * (sx - ex) + ddy * (sy - ey)) / dist) / spd
rad_ring[rad_head] = frac
rad_head = (rad_head + 1) % VEL_WINDOW
if rad_count < VEL_WINDOW:
rad_count += 1
else:
turning = trend = GK_UNKNOWN
prev_ex, prev_ey, prev_eh, prev_es = ex, ey, eh, es
has_prev = True
rf = 0.0
if rad_count:
nn = min(RADIAL_WINDOW, rad_count)
s = 0.0
for i in range(nn):
s += rad_ring[(rad_head - 1 - i) % VEL_WINDOW]
rf = s / nn
band = band_of(dist)
sp = space_of(ex, ey, sx, sy)
rad = 0 if rf < 0.25 else 1 if rf < 0.5 else 2 if rf < 0.75 else 3
k = key_of(band, sp, turning, trend, rad, arm)
# ---- what aim() applies this tick ----
if learn:
if table.att[k] < thr:
res, ub = 0.0, -1
table.att[k] += 1
if eps > 0.0 and rng.random() < eps:
ub = rng.randrange(GK_NBINS)
res = CENTRE[ub]
c["explore"] += 1
else:
res, ub = best_residual(table.hits[k])
else:
res, ub = table.residual(k)
if test:
A = acc[band]
A.tk += 1
A.cov += 1.0 if res != 0.0 else 0.0
A.res += abs(res)
los = atan2d(math.atan2(dy, dx))
for bi in range(4):
A.n += 1
v = SPEEDS[bi]
kk = 1
kst = -1
while kk <= MAX_FLIGHT and t + kk < end and j + kk < n \
and T[j + kk] == t + kk:
qx = EX[j + kk] - sx
qy = EY[j + kk] - sy
if math.sqrt(qx * qx + qy * qy) <= v * kk:
kst = kk
break
kk += 1
if kst < 0:
c["skip"] += 1
continue
req = wrap180(atan2d(math.atan2(EY[j + kst] - sy,
EX[j + kst] - sx)) - los)
bl = wrap180(fB(ex, ey, eh, es, sx, sy, v) - los)
eb = wrap180(bl - req)
el = wrap180(bl + res - req)
A.eb2 += eb * eb
A.eab += abs(eb)
A.el2 += el * el
A.eal += abs(el)
# ---- spawnBullets ----
for bi in range(4):
v = SPEEDS[bi]
bse = fB(ex, ey, eh, es, sx, sy, v)
a_fx.append(sx); a_fy.append(sy)
a_tr.append(0.0); a_sp.append(v)
a_hit.append(False); a_key.append(k); a_bn.append(ub)
a_bd.append(band); a_pi.append(j)
a_ux.append(math.cos(math.radians(bse)))
a_uy.append(math.sin(math.radians(bse)))
if res != 0.0:
a_arm.append(ARM_BASE)
c["split"] += 1
a_fx.append(sx); a_fy.append(sy)
a_tr.append(0.0); a_sp.append(v)
a_hit.append(False); a_key.append(k); a_bn.append(ub)
a_bd.append(band); a_pi.append(j)
a_ux.append(math.cos(math.radians(bse + res)))
a_uy.append(math.sin(math.radians(bse + res)))
a_arm.append(ARM_LEARN)
else:
a_arm.append(ARM_BOTH)
c["shared"] += 1
# ---- tickBullets: advance every bullet one tick ----
if a_fx:
if not e_alive:
c["dead"] += len(a_fx)
a_fx.clear(); a_fy.clear(); a_ux.clear(); a_uy.clear()
a_tr.clear(); a_sp.clear(); a_hit.clear(); a_key.clear()
a_bn.clear(); a_arm.clear(); a_bd.clear(); a_pi.clear()
else:
w = 0
for i in range(len(a_fx)):
sp = a_sp[i]
tr = a_tr[i] + sp
fx, fy = a_fx[i], a_fy[i]
ux, uy = a_ux[i], a_uy[i]
ddx = ex - fx
ddy = ey - fy
along = ux * ddx + uy * ddy
perp = -uy * ddx + ux * ddy
hit = a_hit[i]
if not hit and perp * perp < R2:
prev_d = tr - sp
if along > prev_d - BOT_RADIUS and along < tr + BOT_RADIUS:
seg = along - (prev_d if along < prev_d else
(tr if along > tr else along))
if seg * seg + perp * perp < R2:
hit = True
bx = fx + ux * tr
by = fy + uy * tr
if bx < 0.0 or bx > ARENA_W or by < 0.0 or by > ARENA_H:
c["resolved"] += 1
if learn:
k = a_key[i]
table.att[k] += 1
if hit:
b = a_bn[i]
table.row(k)[b if b >= 0 else GK_NULL_BIN] += 1
c["learn_hits"] += 1
else:
A = acc[a_bd[i]]
am = a_arm[i]
hv = 1.0 if hit else 0.0
if am == ARM_LEARN:
A.nl += 1
A.hl += hv
# PAIRED: the baseline flight for THIS spawn tick
A.hd += 1
A.hbp += bh[a_pi[i]]
A.hlp += hv
elif am == ARM_BOTH:
A.nb += 1; A.hb += hv
A.nl += 1; A.hl += hv
bh[a_pi[i]] = hv
else:
A.nb += 1; A.hb += hv
bh[a_pi[i]] = hv
continue
a_fx[w] = fx; a_fy[w] = fy; a_ux[w] = ux; a_uy[w] = uy
a_tr[w] = tr; a_sp[w] = sp; a_hit[w] = hit
a_key[w] = a_key[i]; a_bn[w] = a_bn[i]; a_arm[w] = a_arm[i]
a_bd[w] = a_bd[i]; a_pi[w] = a_pi[i]
w += 1
del a_fx[w:]; del a_fy[w:]; del a_ux[w:]; del a_uy[w:]
del a_tr[w:]; del a_sp[w:]; del a_hit[w:]
del a_key[w:]; del a_bn[w:]; del a_arm[w:]; del a_bd[w:]
del a_pi[w:]
c["inflight"] = len(a_fx)
return acc, c
# ─────────────────────────────────────────────────────────────────────────────
# driver
# ─────────────────────────────────────────────────────────────────────────────
_G = {}
def _test_one(bf):
b = get_battle(bf)
acc, c = replay(b, _G["arm"], _G["table"], False, 0, 0.0, None, True)
return bf["tag"], [a.as_dict() for a in acc], c
def run_config(arm, thr, eps, bfs, outdir):
t0 = time.time()
res = dict(arm=arm, thr=thr, eps=eps, folds=[])
for fold in (0, 1):
table = Table(nrows(arm))
rng = random.Random(1234 + fold)
ctr = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
ticks=0, explore=0, learn_hits=0, inflight=0)
for bf in bfs: # TRAINING: sequential, table evolves
if bf["fold"] == fold:
continue
_, c = replay(get_battle(bf), arm, table, True, thr, eps, rng, False)
for k in ctr:
ctr[k] += c[k]
nz, trusted, mean_abs = table.stats()
_G["arm"], _G["table"] = arm, table
with Pool(4) as pool: # TEST: frozen table, battles parallel
out = pool.map(_test_one, [bf for bf in bfs if bf["fold"] != fold])
pooled = [Acc() for _ in range(N_BAND)]
ctest = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0,
ticks=0, explore=0, learn_hits=0, inflight=0)
battles = []
for tag, bands, c in out:
A = []
for a in bands:
A.append(_mk(a))
pooled[len(A) - 1].add(A[-1])
for k in ctest:
ctest[k] += c[k]
tb = Acc()
for a in A:
tb.add(a)
battles.append(dict(tag=tag, n=tb.n, tk=tb.tk, eb2=tb.eb2, el2=tb.el2,
nb=tb.nb, hb=tb.hb, nl=tb.nl, hl=tb.hl,
hd=tb.hd, hbp=tb.hbp, hlp=tb.hlp,
cov=tb.cov, res=tb.res))
res["folds"].append(dict(fold=fold, nz=nz, trusted=trusted,
mean_abs=mean_abs, train=ctr, test=ctest,
bands=[a.as_dict() for a in pooled],
battles=battles))
_G.clear()
json.dump(res, open(os.path.join(outdir, "gk_%s_%d.json" % (arm, thr)), "w"))
return time.time() - t0
def rms(x):
return math.sqrt(x) if x >= 0 else float("nan")
def mean_sd(xs):
if len(xs) < 2:
return 0.0, 0.0
m = statistics.fmean(xs)
return m, math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1))
def report(cfg_path, real_n, rows, gaps, bfs):
r = json.load(open(cfg_path))
print("=" * 100)
print("CONFIG key=%s explore-attempts=%d eps=%.2f" % (r["arm"], r["thr"], r["eps"]))
tt = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0, inflight=0)
cte = dict(split=0, shared=0, resolved=0, dead=0, round=0, skip=0, ticks=0,
explore=0, learn_hits=0, inflight=0)
for f in r["folds"]:
for k in tt:
tt[k] += f["train"][k]
cte[k] += f["test"][k]
ntr = len(bfs) // 2 * 2
print(" TRAINING (the %d held-in battles of each of the 2 folds, replayed"
" sequentially, table rebuilt per fold):" % (ntr // 2))
print(" virtual bullets spawned %d resolved %d in flight at battle end %d"
% (4 * tt["ticks"] + tt["split"], tt["resolved"], tt["inflight"]))
print(" dropped unscored: target dead %d, round boundary %d of which the"
" two arms flew ONE identical ray: %d" % (tt["dead"], tt["round"], tt["shared"]))
print(" resolutions credited as HITS: %d epsilon-greedy draws: %d"
% (tt["learn_hits"], tt["explore"]))
tot = [Acc() for _ in range(N_BAND)]
bl = []
for f in r["folds"]:
for i, a in enumerate(f["bands"]):
tot[i].add(_mk(a))
bl += f["battles"]
for f in r["folds"]:
print(" fold %d: rows above the trust threshold %d, with a NON-ZERO"
" argmax %d, mean |residual| of those %+.2f deg"
% (f["fold"], f["trusted"], f["nz"], f["mean_abs"]))
ntest = sum(b["tk"] for b in bl)
nvb = sum(b["nb"] for b in bl)
nvl = sum(b["nl"] for b in bl)
cov = sum(b["cov"] for b in bl)
rr = sum(b["res"] for b in bl)
print(" HELD-OUT (2-fold by battle, both folds pooled, every bullet tested once):")
print(" virtual bullets TESTED: base arm %d, learned arm %d"
" (%.1fx the %d real fired shots)" % (nvb, nvl, nvl / max(real_n, 1), real_n))
print(" held-out target ticks (both bots alive): %d x4 power bins = %d aim"
" decisions skipped (no interception before the round end): %d"
% (ntest, int(sum(a.n for a in tot)), cte["skip"]))
print(" held-out ticks carrying a NON-ZERO residual: %d (%.2f%%) mean"
" |residual| applied %.3f deg"
% (int(cov), 100.0 * cov / max(ntest, 1), rr / max(ntest, 1)))
print(" %-8s %9s %8s %8s %8s | %8s %8s %8s %8s | %10s"
% ("band", "aims", "rms_b", "mabs_b", "hit_b%", "rms_l", "mabs_l",
"hit_l%", "dhit_pp", "paired_n"))
for i, lab in enumerate(BAND_LAB):
a = tot[i]
if a.n <= 0:
continue
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
% (lab, int(a.n), rms(a.eb2 / a.n), a.eab / a.n, 100.0 * a.hb / max(a.nb, 1),
rms(a.el2 / a.n), a.eal / a.n, 100.0 * a.hl / max(a.nl, 1),
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
a = Acc()
for x in tot:
a.add(x)
print(" %-8s %9d %8.2f %8.2f %8.2f | %8.2f %8.2f %8.2f %+8.2f | %10d"
% ("ALL", int(a.n), rms(a.eb2 / a.n), a.eab / a.n,
100.0 * a.hb / max(a.nb, 1), rms(a.el2 / a.n), a.eal / a.n,
100.0 * a.hl / max(a.nl, 1),
100.0 * (a.hl / max(a.nl, 1) - a.hb / max(a.nb, 1)), int(a.hd)))
print(" PAIRED (only the ticks where the two arms flew DIFFERENT rays):"
" base %d/%d hit, learned %d/%d hit -> %+.3f pp"
% (int(a.hbp), int(a.hd), int(a.hlp), int(a.hd),
100.0 * (a.hlp - a.hbp) / max(a.hd, 1)))
# clustered, per-battle paired statistics
dh, de = [], []
for b in bl:
if b["hd"]:
dh.append((b["hlp"] - b["hbp"]) / b["hd"])
if b["n"]:
de.append((b["el2"] - b["eb2"]) / b["n"])
mh, sh = mean_sd(dh)
me, se = mean_sd(de)
th = mh / (sh / math.sqrt(len(dh))) if sh > 0 else 0.0
te = me / (se / math.sqrt(len(de))) if se > 0 else 0.0
print(" CLUSTERED by battle (%d battles): dHit %+0.3f pp (sd %0.3f, t=%+.2f)"
" dMeanSqErr %+8.2f deg2 (sd %8.2f, t=%+.2f)"
% (len(dh), 100 * mh, 100 * sh, th, me, se, te))
return r
def _mk(d):
a = Acc()
for s in Acc.__slots__:
setattr(a, s, d[s])
return a
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--root", default=ROOT)
ap.add_argument("--arms", default="full,dt")
ap.add_argument("--thresholds", default="5,100")
ap.add_argument("--eps", type=float, default=0.25)
ap.add_argument("--limit", type=int, default=0, help="first N battles (smoke)")
ap.add_argument("--out", default="/tmp/gk_virtual")
a = ap.parse_args()
bfs = battle_files(a.root)
if a.limit:
bfs = bfs[:a.limit]
if not bfs:
print("NO CORPUS at %s" % a.root)
return 1
os.makedirs(a.out, exist_ok=True)
rows, gaps = cadence(bfs)
real = real_shots(bfs)
real_n = sum(real.values())
print("CORPUS %s" % a.root)
print(" battles: %d worldstate rows: %d" % (len(bfs), rows))
print(" TICK CADENCE: inter-row deltas %s"
% (dict(gaps) if gaps else "none (one row per tick, contiguous)"))
print(" -> NO interpolation needed: every tick is recorded, so a virtual"
" bullet's swept segment is tested against the enemy position of that"
" exact tick.")
print(" REAL fired shots by the US bot (energy-drop attribution): %d"
% real_n)
print(" power bins %s -> bullet speeds %s ; BotRadius %.1f ; arena %.0fx%.0f"
% (POWER_BINS, SPEEDS, BOT_RADIUS, ARENA_W, ARENA_H))
print()
arms = a.arms.split(",")
thrs = [int(x) for x in a.thresholds.split(",")]
procs = []
for arm in arms:
for thr in thrs:
p = Process(target=run_config,
args=(arm, thr, a.eps, bfs, a.out))
p.start()
procs.append(p)
for p in procs:
p.join()
if p.exitcode:
print("!! a config process exited %d" % p.exitcode)
print()
for arm in arms:
for thr in thrs:
f = os.path.join(a.out, "gk_%s_%d.json" % (arm, thr))
if os.path.exists(f):
report(f, real_n, rows, gaps, bfs)
return 0
if __name__ == "__main__":
sys.exit(main())
+227
View File
@@ -0,0 +1,227 @@
## Unit tests for the online sequential ELM (common_libs/guns/elm.nim).
##
## Covers what the guns actually rely on: fitting a known function, streaming
## convergence, the forgetting factor tracking a drifting target, the
## NaN/Inf guards, and seed reproducibility.
##
## Run: nim c -r common_libs/tests/test_elm.nim
import std/[math, random, strformat]
import guns/elm
var failures = 0
var checks = 0
proc check(name: string, ok: bool) =
inc checks
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc rmse(net: ElmNet, samples: seq[tuple[x: seq[float], t: seq[float]]]): float =
## Prediction RMSE over a held-out sample set (net used read-only).
var s = 0.0
for smp in samples:
let p = net.predict(smp.x)
for o in 0..<net.outputDim: s += (p[o] - smp.t[o]) ^ 2
sqrt(s / (samples.len.float * net.outputDim.float))
# ── 1. linear fit y = 2x + 1, noisy ──────────────────────────────────────────
proc testLinearFit() =
block:
let n = 400
var rng = initRand(7)
var net = init(inputDim = 1, hiddenDim = 12, seed = 42)
for i in 0..<n:
let x = @[rand(rng, 1.0) * 2.0 - 1.0]
let t = @[2.0 * x[0] + 1.0 + (rand(rng, 1.0) * 2.0 - 1.0) * 0.02]
discard net.train(x, t)
var grid: seq[tuple[x: seq[float], t: seq[float]]] = @[]
for i in 0..<100:
let x = @[-1.0 + 2.0 * float(i) / 100.0]
grid.add((x: x, t: @[2.0 * x[0] + 1.0]))
let e = rmse(net, grid)
echo &" linear y=2x+1: grid RMSE = {e:.5f}"
check "linear: RMSE on [-1,1] grid < 0.05", e < 0.05
# ── 2. 2D input -> 2D output ───────────────────────────────────────────────
block:
let n = 600
var rng = initRand(11)
var net = init(inputDim = 2, hiddenDim = 20, seed = 7, outputDim = 2)
proc target(x: openArray[float]): seq[float] =
@[x[0] + 0.5 * x[1] - 1.0, -0.3 * x[0] + 2.0 * x[1] + 0.25]
for i in 0..<n:
let x = @[rand(rng, 1.0) * 2.0 - 1.0, rand(rng, 1.0) * 2.0 - 1.0]
var t = target(x)
for o in 0..<1:
t[o] += (rand(rng, 1.0) * 2.0 - 1.0) * 0.01
discard net.train(x, t)
var grid: seq[tuple[x: seq[float], t: seq[float]]] = @[]
for i in 0..<60:
let x = @[-1.0 + 2.0 * float(i) / 60.0, 1.0 - 2.0 * float(i) / 60.0]
grid.add((x: x, t: target(x)))
let e = rmse(net, grid)
echo &" 2D->2D: grid RMSE = {e:.5f}"
check "2D->2D: RMSE < 0.05", e < 0.05
# ── 3. online / streaming convergence ────────────────────────────────────────
proc testStreaming() =
## RLS is prequential: every sample is predicted once, then trained on. The
## net converges in a handful of samples (that is the point of RLS), so the
## trend has to be measured against the FIRST samples, not the first 100.
var rng = initRand(3)
var net = init(inputDim = 1, hiddenDim = 16, seed = 99)
var firstErr = 0.0
var headErr = 0.0
var tailErr = 0.0
var worstTail = 0.0
for i in 0..<600:
let x = @[rand(rng, 1.0) * 2.0 - 1.0]
let t = @[2.0 * x[0] + 1.0]
if i == 0: firstErr = (net.predict(x)[0] - t[0]) ^ 2 # untrained: predicts 0
discard net.train(x, t)
let err = (net.predict(x)[0] - t[0]) ^ 2
if i < 5:
headErr += err
elif i >= 500:
tailErr += err
worstTail = max(worstTail, err)
headErr /= 5.0
tailErr /= 100.0
echo &" streaming: 1st sample MSE = {firstErr:.6f}, first-5 MSE = {headErr:.6f}, " &
&"last-100 MSE = {tailErr:.6f}"
check "streaming: last-100 MSE << first-sample MSE (>=100x better)",
tailErr < firstErr / 100.0
check "streaming: running error keeps trending down (last-100 <= first-5)",
tailErr <= headErr
# Floor: ~2e-6 MSE is the lambda = 1e-3 ridge bias, not a learning failure.
check "streaming: last-100 MSE < 1e-4", tailErr < 1e-4
check "streaming: no single late sample worse than 100x the last-100 mean",
worstTail < tailErr * 100.0
# ── 4. forgetting factor tracks a drifting target ────────────────────────────
proc testForgetting() =
block:
## Target jumps sign/slope halfway through. Two numbers per net: the mean
## RMSE over all post-jump samples (transient included) and the tail RMSE
## (adaptation quality once it has settled). rho = 1 averages the whole
## history and never leaves the old function; rho > 1 must track.
let n = 800
proc drift(net: var ElmNet): tuple[mean, tail: float] =
var re = initRand(1)
var e2 = 0.0
var eTail = 0.0
for i in 0..<n:
let x = @[rand(re, 1.0) * 2.0 - 1.0]
let t = @[if i < n div 2: 2.0 * x[0] + 1.0 else: -1.5 * x[0] + 0.5]
discard net.train(x, t)
if i >= n div 2:
let e = (net.predict(x)[0] - t[0]) ^ 2
e2 += e
if i >= n - 200: eTail += e
(sqrt(e2 / float(n div 2)), sqrt(eTail / 200.0))
var plain = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.0)
var forget = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.02)
let ePlain = drift(plain)
let eForget = drift(forget)
echo &" drifting target, post-jump mean RMSE: rho=1.0 -> {ePlain.mean:.5f}, " &
&"rho=1.02 -> {eForget.mean:.5f}"
echo &" drifting target, post-jump TAIL RMSE: rho=1.0 -> {ePlain.tail:.5f}, " &
&"rho=1.02 -> {eForget.tail:.5f}"
check "forgetting: rho=1.02 halves the mean post-jump RMSE on a drifting target",
eForget.mean < ePlain.mean * 0.5
check "forgetting: rho=1.02 tracks the new target (tail RMSE >=20x better)",
eForget.tail < ePlain.tail / 20.0
check "forgetting: rho=1.02 settles on the new target (tail RMSE < 0.05)",
eForget.tail < 0.05
# ── 5. numerical guards ──────────────────────────────────────────────────────
proc testGuards() =
block:
var net = init(inputDim = 1, hiddenDim = 8, seed = 42)
for i in 0..<200:
let x = @[float(i) / 200.0 - 0.5]
discard net.train(x, @[2.0 * x[0]])
check "guards: net is sane after 200 clean updates", net.isSane()
# a NaN sample must be rejected without poisoning the net
let rejected = net.train(@[0.5], @[NaN])
check "guards: NaN target is rejected", not rejected
check "guards: net still sane after a rejected NaN sample", net.isSane()
check "guards: NaN input is rejected", not net.train(@[Inf], @[1.0])
check "guards: net still sane after Inf input", net.isSane()
# many updates with an extreme input: prediction must stay finite
var wild = init(inputDim = 1, hiddenDim = 8, seed = 42, rho = 1.01)
for i in 0..<5000:
let x = @[sin(float(i)) * 1e6]
discard wild.train(x, @[x[0]])
let p = wild.predict(x)
if p[0].classify in {fcNan, fcInf, fcNegInf}:
check "guards: prediction stays finite over 5000 wild updates", false
return
check "guards: prediction stays finite over 5000 wild updates",
classify(wild.predict(@[1.0])[0]) notin {fcNan, fcInf, fcNegInf}
# poisoned state is detected and reset away from
var broken = init(inputDim = 1, hiddenDim = 4, seed = 42)
discard broken.train(@[0.5], @[1.0])
broken.beta[0][0] = NaN
check "guards: isSane detects a poisoned beta", not broken.isSane()
check "guards: predict returns zeros instead of NaN",
broken.predict(@[0.5]) == @[0.0]
discard broken.train(@[0.5], @[1.0])
check "guards: training a poisoned net soft-resets it", broken.isSane() and
broken.resets > 0 and broken.samples == 1
broken.softReset()
check "guards: explicit softReset zeroes beta and P",
broken.samples == 0 and broken.beta[0][0] == 0.0 and
broken.P[0][0] == 1.0 / broken.lambda
# ── 6. seed reproducibility ──────────────────────────────────────────────────
proc testReproducible() =
block:
var a = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2)
var b = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2)
var c = init(inputDim = 2, hiddenDim = 12, seed = 4321, outputDim = 2)
var rng = initRand(17)
for i in 0..<50:
let x = @[rand(rng, 1.0), rand(rng, 1.0)]
let t = @[x[0] - x[1], 2.0 * x[0] + 3.0 * x[1]]
discard a.train(x, t)
discard b.train(x, t)
discard c.train(x, t)
let q = @[0.3, -0.7]
check "seed: same seed => identical predictions", a.predict(q) == b.predict(q)
check "seed: different seed => different predictions", a.predict(q) != c.predict(q)
check "activation: sigmoid option is actually used",
init(1, 12, seed = 1, act = eaSigmoid).act == eaSigmoid
var sg = init(inputDim = 1, hiddenDim = 12, seed = 1, act = eaSigmoid)
for i in 0..<300:
let x = @[float(i) / 300.0 - 0.5]
discard sg.train(x, @[2.0 * x[0]])
check "activation: sigmoid ELM also fits y=2x (RMSE < 0.05)",
rmse(sg, @[(x: @[-0.5], t: @[-1.0]), (x: @[0.5], t: @[1.0])]) < 0.05
proc main() =
echo "── linear fit ──"; testLinearFit()
echo "── streaming convergence ──"; testStreaming()
echo "── forgetting factor ──"; testForgetting()
echo "── numerical guards ──"; testGuards()
echo "── reproducibility ──"; testReproducible()
echo ""
if failures > 0:
echo &"{failures}/{checks} check(s) FAILED"
quit(1)
echo &"All {checks} ELM checks passed."
when isMainModule:
main()
+1 -1
View File
@@ -73,7 +73,7 @@ proc testKnownNames() =
check "known set has no duplicates", known.len == s.len
check "known set only holds TR_*/GUN_* names",
known.allIt(it.startsWith("TR_") or it.startsWith("GUN_"))
check "known set covers all 17 rack names",
check "known set covers every rack name (width derived, not a literal)",
RackGunNames.allIt((RackEnvPrefix & it) in s)
for name in ["TR_MOVEMENT", "TR_POWER_ENERGY_MIN", "TR_TMHORIZON_NSTATES",
"GUN_VBULLET_METRIC", "TR_ENV_REPORT", "GUN_SELECTOR_SEED",
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,325 @@
## Registration guard for the KNOWLEDGE gun (rack id 17), the learned additive
## angular residual on top of the self-consistent lead forecast
## (`common_libs/guns/gun_knowledge.nim`).
##
## Mirrors `test_lead_gain_registration.nim`: no Java, no battle, no network
## build. Covers:
## * KNOWLEDGE is APPENDED at id 17 and every pre-existing id is byte-identical
## (a rack gun that renumbered would silently re-address every
## `tools/ab/arms_*.txt` config and every `gun_stats.jsonl` column);
## * it defaults to `off`, so the shipped rack still admits exactly Pattern;
## * `TR_RACK_KNOWLEDGE=...` is what admits it, in 1v1 and in melee, and the
## live `vBulletAdmitted` spawn gate honours the membership;
## * `initKnowledgeGun()` is LAZY (0 bytes before first use) and the whole
# aim+update path, EXPLORATION included, does NOT touch the global RNG, so
## a rack that admits it cannot perturb the selector's `rand` stream;
## * the gun implements the rack `Gun` concept, learns from its own feedback
## into the exact row that produced the angle, keeps its counts across a
## round boundary and persists them atomically.
##
## Run: nim c -r --path:common_libs common_libs/tests/test_knowledge_registration.nim
import std/[math, os, random, strutils, tables]
import gun_harness/virtual_bullets
import gun_harness/selector
import gun_harness/gun_interface
import guns/gun_knowledge
const
KnowledgeId = 17
PatternId = 5
LeadGainId = 16
## The rack as it was BEFORE this gun was appended. Pinned literal-by-literal:
## if a future edit shifts an id, this fails here instead of in a live battle.
PreRack = ["HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN",
"WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF",
"KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN"]
var failures = 0
proc check(name: string, ok: bool) =
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc clearRackEnv() =
for name in RackGunNames: delEnv("TR_RACK_" & name)
proc wsFor(tick: int, ex, ey, es, eh: float): WorldState =
WorldState(enemyX: ex, enemyY: ey, enemySpeed: es, enemyHeading: eh,
selfX: 0.0, selfY: 0.0, selfHeading: 0.0,
arenaWidth: 800.0, arenaHeight: 600.0, tick: tick)
# ── the rack table ───────────────────────────────────────────────────────────
proc testTable() =
check "rack: KNOWLEDGE is registered at id 17", RackGunNames[KnowledgeId] == "KNOWLEDGE"
check "rack: NumRackGuns grew to 18", NumRackGuns >= 18 and
RackGunNames.len == NumRackGuns
check "rack: KNOWLEDGE defaults to `off`", DefaultRackMembership[KnowledgeId] == rmOff
check "rack: the membership table has one entry per gun",
DefaultRackMembership.len == NumRackGuns
# No existing id moved, and no existing name changed. (`>` not `==`: guns
# appended AFTER KNOWLEDGE, e.g. WAVEELM at 18, do not move anything.)
var untouched = RackGunNames.len > PreRack.len
for i in 0 ..< PreRack.len:
if RackGunNames[i] != PreRack[i]: untouched = false
check "rack: every pre-existing id kept its name (KNOWLEDGE appended at the end)", untouched
var seen = initTable[string, bool]()
var allDistinct = true
for n in RackGunNames:
if n in seen: allDistinct = false
seen[n] = true
check "rack: all rack gun names are distinct", allDistinct
# Id 17 was free: no shipped gun occupied it. (It is the id the RETIRED ADE+SBC
# BITBRAIN gun briefly had; nothing addresses it any more — `TR_RACK_BITBRAIN`
# is LEADGAIN's legacy alias, pinned by test_lead_gain_legacy.nim.)
check "rack: KNOWLEDGE's id is in range for every per-gun table",
KnowledgeId < NumRackGuns
var onlyPattern = true
for i in 0..<RackGunNames.len:
let want = if i == PatternId: rmBoth else: rmOff
if DefaultRackMembership[i] != want: onlyPattern = false
check "rack: the shipped default is still the onlyPattern rack", onlyPattern
check "rack: the default rack admits only Pattern (1v1)",
admittedGuns(NumRackGuns, rm1v1, DefaultRackMembership) == @[PatternId]
check "rack: the default rack admits only Pattern (melee)",
admittedGuns(NumRackGuns, rmMelee, DefaultRackMembership) == @[PatternId]
check "gate: KNOWLEDGE is NOT spawned under the default rack",
not vBulletAdmitted(KnowledgeId, rm1v1, DefaultRackMembership, true)
check "gate: LEADGAIN is still NOT spawned under the default rack (no regression)",
not vBulletAdmitted(LeadGainId, rm1v1, DefaultRackMembership, true)
# ── the env override, per membership semantics ───────────────────────────────
proc testEnvOverride() =
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "both")
let m = loadRackMembership()
check "env: TR_RACK_KNOWLEDGE=both admits KNOWLEDGE",
m[KnowledgeId] == rmBoth and
vBulletAdmitted(KnowledgeId, rm1v1, m, true) and
vBulletAdmitted(KnowledgeId, rmMelee, m, true)
check "env: admitting KNOWLEDGE leaves Pattern as the only other member",
admittedGuns(NumRackGuns, rm1v1, m) == @[PatternId, KnowledgeId]
check "env: the legacy alias still selects LEADGAIN, not KNOWLEDGE",
m[LeadGainId] == rmOff
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "1v1")
let m1 = loadRackMembership()
check "env: =1v1 admits it in 1v1 only",
vBulletAdmitted(KnowledgeId, rm1v1, m1, true) and
not vBulletAdmitted(KnowledgeId, rmMelee, m1, true)
check "env: =1v1 leaves the melee rack as Pattern alone",
admittedGuns(NumRackGuns, rmMelee, m1) == @[PatternId]
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "melee")
let mM = loadRackMembership()
check "env: =melee admits it in melee only",
vBulletAdmitted(KnowledgeId, rmMelee, mM, true) and
not vBulletAdmitted(KnowledgeId, rm1v1, mM, true)
clearRackEnv()
putEnv("TR_RACK_KNOWLEDGE", "off")
let mOff = loadRackMembership()
check "env: =off is still the shipped behaviour",
mOff[KnowledgeId] == rmOff and
not vBulletAdmitted(KnowledgeId, rm1v1, mOff, true)
clearRackEnv()
# The gate's `admitOnly=false` escape hatch keeps every gun spawning.
check "gate: TR_VBULLET_ADMIT_ONLY=0 spawns KNOWLEDGE even when off",
vBulletAdmitted(KnowledgeId, rm1v1, DefaultRackMembership, false)
# ── lazy init and the global-RNG contract ────────────────────────────────────
proc testLazyAndRngClean() =
delEnv(GK_MEM_ENV)
var g = initKnowledgeGun()
check "lazy: constructing the gun does NOT build the 3840-row table (0 bytes)",
g.networkBytes == 0
check "lazy: unset TR_KNOWLEDGE_MEM is memory-only (no disk path)",
g.memPath.len == 0
check "lazy: the gun is a `Gun` (predict + onResult, the rack concept)",
isGun(KnowledgeGun)
var warm = initKnowledgeGun()
let ws = WorldState(enemyX: 300.0, enemyY: 200.0, enemySpeed: 3.0,
enemyHeading: 180.0, selfX: 0.0, selfY: 0.0,
selfHeading: 0.0, arenaWidth: 800.0, arenaHeight: 600.0,
tick: 1)
discard warm.predict(ws, bulletSpeed(1.0))
check "lazy: the table exists after the first predict",
warm.networkBytes == GK_NKEYS * sizeof(GkRow)
# Global RNG parity: constructing the gun must not consume global randomness.
# The 3840-row table is a plain `newSeq`/`initTable`; nothing in the module's
# init path draws, so the selector's `rand` stream is untouched.
randomize(1234)
let a = rand(1_000_000)
randomize(1234)
var g2 = initKnowledgeGun()
discard g2.networkBytes
let b = rand(1_000_000)
check "parity: initKnowledgeGun() does not perturb the global RNG", a == b
# ...and neither does the first USE of the table (the allocation + the first
# forecast), which is the moment a random draw would be most tempting.
randomize(1234)
let c = rand(1_000_000)
randomize(1234)
var g3 = initKnowledgeGun()
for t in 0 .. 5:
discard g3.predict(wsFor(t, 300.0 - 5.0 * t.float, 200.0, 3.0,
180.0 + 4.0 * t.float), bulletSpeed(1.0))
let d = rand(1_000_000)
check "parity: using the table does not perturb the global RNG either", c == d
# ...and EXPLORATION draws, but from the module's OWN LCG state
# (`GunKnowledge.rng`), never from the global one. The learner probes a
# uniform residual bin on an under-sampled row, so this is the check that
# actually covers the draw, over a whole learn/resolve loop.
randomize(1234)
let e = rand(1_000_000)
randomize(1234)
var g4 = initKnowledgeGun()
g4.targetId = 3
var explored = false
for t in 0 ..< 40:
let fired = g4.predict(wsFor(t, 300.0 - 4.0 * t.float, 200.0, 3.0,
180.0 + 3.0 * t.float),
bulletSpeed(PowerBins[0]))
g4.onResult(FeedbackEvent(prediction: fired, bulletPower: PowerBins[0],
fireTick: t, powerBin: 0, missDistance: 4.0,
hit: t mod 3 == 0, confidence: fired.confidence))
if g4.pending[0].usedBin != -1: explored = true
let h = rand(1_000_000)
check "parity: exploration (40 predict+onResult) does not touch global rand",
e == h
check "parity: that loop really did explore a non-null residual bin",
explored
# ── the gun learns, and the learning lands on the row that produced the angle ──
proc testLearning() =
delEnv(GK_MEM_ENV)
var g = initKnowledgeGun()
g.targetId = 3 # the caller names the opponent
check "learn: an unarmed gun still returns an aim point",
g.predict(wsFor(0, 300.0, 200.0, 3.0, 0.0), bulletSpeed(1.0)).x != 0.0
check "learn: the confidence carries the gkUnknown rate (0.0 = no data yet)",
g.unknownRate == 0.0
# Two ticks, so the track has a pair and the turn/trend features are known.
discard g.predict(wsFor(1, 297.0, 200.0, 3.0, 0.0), bulletSpeed(1.0))
check "learn: the gkUnknown rate is exposed for a live battle",
g.unknownRate >= 0.0 and g.unknownRate <= 1.0
# Fire the virtual bullet the way the harness does, and resolve it as a HIT.
# The row that produced the angle must be the row that learns.
let fired = g.predict(wsFor(2, 294.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0]))
g.onResult(FeedbackEvent(prediction: fired, bulletPower: PowerBins[0],
fireTick: 2, powerBin: 0, missDistance: 4.0,
hit: true, confidence: fired.confidence))
check "learn: onResult wrote an attempt into the table",
g.gk.featureCount > 0 and g.gk.unknownCount <= g.gk.featureCount
# A MISS resolving the same tick/bucket adds a second attempt and no hit.
let fired2 = g.predict(wsFor(3, 291.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0]))
g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0],
fireTick: 3, powerBin: 0, missDistance: 40.0,
hit: false, confidence: fired2.confidence))
check "learn: a miss resolves into the same per-power-bucket record",
g.gk.usedGlobalRows >= 1
# A feedback for a tick the gun never predicted (a stale / other-round bullet)
# must NOT create evidence: the row is only updated for the shot taken.
let before = g.gk.usedGlobalRows
g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0],
fireTick: 999, powerBin: 0, missDistance: 4.0,
hit: true, confidence: fired2.confidence))
check "learn: feedback for an unknown fire tick is dropped, not learned",
g.gk.usedGlobalRows == before
# The fallback chain has to REACH a threshold before it answers with a
# residual, so a cold gun must return the plain forecast (residual 0) and
# start COUNTING the situation so it can get there.
var fresh = initGunKnowledge(800.0, 600.0)
let fCold = fresh.featuresFor(wsFor(0, 300.0, 200.0, 3.0, 0.0), 3, 1.0, 0.0, 0.0)
let aCold = fresh.aim(fCold, 0.0)
check "learn: a cold table answers with no residual (the forecast alone)",
aCold.hasTarget and aCold.residual == 0.0 and
aCold.residualBin == -1 and aCold.source == gkSourceNone
check "learn: the cold answer still counts the situation for later",
fresh.usedGlobalRows == 1 and fresh.rowAttempts(fCold) == 1
# Round boundary: the counts SURVIVE (this gun's own capability), the
# per-round scan track does not.
let usedRows = g.gk.usedGlobalRows
g.onRoundBoundary()
check "persist: the learned rows survive a round boundary",
g.gk.usedGlobalRows == usedRows
check "persist: the per-round scan track is dropped at the boundary",
g.gk.tracks.len == 0
# ── on-disk persistence, at a round boundary ─────────────────────────────────
proc testPersistence() =
let path = getTempDir() / "gk_registration_table.bin"
if fileExists(path): removeFile(path)
defer:
if fileExists(path): removeFile(path)
var g = initKnowledgeGun(path)
check "persist: an explicit path is the memory path", g.memPath == path
g.targetId = 7
# 30 ticks of ONE steady situation (tangential move, constant heading and
# speed), so the SAME key accumulates 30 attempts: past the global threshold
# (5) and past the opponent one (20). Fewer ticks would leave every row below
# threshold and `prune` — correctly — would drop all of them at the save.
for t in 0 ..< 30:
discard g.predict(wsFor(t, 300.0, 200.0 + 0.5 * t.float, 3.0, 90.0),
bulletSpeed(PowerBins[0]))
let rows = g.gk.usedGlobalRows + g.gk.oppRows.len
g.onRoundBoundary() # first boundary: load (nothing) + prune + save
let saved = g.gk.usedGlobalRows + g.gk.oppRows.len
check "persist: the round boundary wrote the table", fileExists(path)
check "persist: the table holds learned rows after the prune", saved > 0
check "persist: prune drops the rows that never reached threshold", saved <= rows
# A fresh gun in a fresh process-equivalent state picks the table back up.
var g2 = initKnowledgeGun(path)
g2.ensureInit()
check "persist: a cold gun has no rows before the load",
g2.gk.usedGlobalRows == 0 and g2.gk.oppRows.len == 0
g2.onRoundBoundary() # loads, then round-trips
check "persist: the table came back off disk",
g2.gk.usedGlobalRows + g2.gk.oppRows.len == saved
# A truncated file is REJECTED (strict parser), never half-loaded.
let full = readFile(path)
writeFile(path, full[0 ..< full.len div 2])
var g3 = initKnowledgeGun(path)
g3.ensureInit()
check "persist: a truncated file is rejected and the table stays empty",
not g3.gk.load(path) and g3.gk.usedGlobalRows == 0
writeFile(path, full)
var g4 = initKnowledgeGun(path)
g4.ensureInit()
check "persist: the intact file is accepted again",
g4.gk.load(path) and g4.gk.usedGlobalRows + g4.gk.oppRows.len == saved
testTable()
testEnvOverride()
testLazyAndRngClean()
testLearning()
testPersistence()
if failures > 0:
echo "\n", failures, " check(s) FAILED"
quit(1)
echo "\nAll KNOWLEDGE registration checks passed."
+2 -2
View File
@@ -164,8 +164,8 @@ proc testDefaultParity() =
let want = if i == 5: rmBoth else: rmOff
if m[i] != want: onlyPattern = false
check "parity: a clean env still loads the shipped onlyPattern rack", onlyPattern
check "parity: the rack is still 17 guns at id 16 = LEADGAIN",
RackGunNames.len == 17 and RackGunNames[LeadGainId] == "LEADGAIN"
check "parity: the rack is still one entry per gun and id 16 = LEADGAIN",
RackGunNames.len == NumRackGuns and RackGunNames[LeadGainId] == "LEADGAIN"
var g = initLeadGainGun()
check "parity: a clean env resolves the shipped candidate set",
g.cands == @[0.0, 0.25, 0.5, 0.75, 1.0] and g.memMode == lgPerRound
+7 -6
View File
@@ -158,14 +158,14 @@ proc testDefaultsOnlyPattern() =
DefaultRackMembership[12] == rmOff and DefaultRackMembership[13] == rmOff and
DefaultRackMembership[14] == rmOff
check "defaults: the default rack admits ONLY Pattern in 1v1",
admittedGuns(17, rm1v1, DefaultRackMembership) == @[PatternId]
admittedGuns(NumRackGuns, rm1v1, DefaultRackMembership) == @[PatternId]
check "defaults: the default rack admits ONLY Pattern in melee",
admittedGuns(17, rmMelee, DefaultRackMembership) == @[PatternId]
admittedGuns(NumRackGuns, rmMelee, DefaultRackMembership) == @[PatternId]
let loaded = loadRackMembership()
check "defaults: with a clean environment loadRackMembership() == shipped table",
loaded == DefaultRackMembership
check "defaults: RackGunNames covers the shipped 17-gun rack",
RackGunNames.len == 17 and DefaultRackMembership.len == 17
check "defaults: RackGunNames covers the shipped rack (width derived, not a literal)",
RackGunNames.len == NumRackGuns and DefaultRackMembership.len == NumRackGuns
proc testFloorRespectsAdmission() =
## The FLOOR path (`bestRate <= 0` or below the floor rate) historically fell
@@ -213,14 +213,15 @@ proc testRevertOverrideRestoresFullRack() =
if m[i] != want: full = false
check "revert: the documented one-liner restores the all-`both` full rack", full
check "revert: 1v1 rack admits every gun again (TMPATTERN excluded)",
admittedGuns(17, rm1v1, m) == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16]
admittedGuns(NumRackGuns, rm1v1, m) ==
@[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18]
clearRackEnv()
# The ADE+SBC gun (old rack id 17) is RETIRED, so `TR_RACK_BITBRAIN` is now
# unambiguously LEADGAIN's old name: alone, it admits LEADGAIN and nothing else.
putEnv("TR_RACK_BITBRAIN", "both")
let mLegacy = loadRackMembership()
check "revert: the legacy TR_RACK_BITBRAIN alone selects LEADGAIN (16) only",
mLegacy[16] == rmBoth and admittedGuns(17, rm1v1, mLegacy) == @[5, 16]
mLegacy[16] == rmBoth and admittedGuns(NumRackGuns, rm1v1, mLegacy) == @[5, 16]
clearRackEnv()
proc testEnvOverrides() =
+13 -10
View File
@@ -14,8 +14,9 @@
## The fix derives every gun-indexed width from `NumRackGuns` (== `len(RackGunNames)`).
## This test is the guard that would have caught it:
##
## A. rack table — `NumRackGuns` is 17, 17 DISTINCT names, and the
## membership table and the legacy alias target are in range;
## A. rack table — `NumRackGuns` is one entry per gun, DISTINCT names, and
## the membership table and the legacy alias target are in
## range;
## B. source shape — `ModularBot.nim` contains NO literal width/loop bound
## narrower than `NumRackGuns` for the gun-indexed
## accounting, and sizes them with `NumRackGuns`;
@@ -26,10 +27,12 @@
## D. live (opt-in) — with a rack that admits ONLY the newest id, the bot
## selects it, fires and lands hits (skipped without JARs).
##
## The ADE+SBC gun (rack id 17) was later RETIRED, so the rack is back to 17 and
## the newest id is LEADGAIN (16). The guard is unchanged in shape and in
## strength: C3 now proves the fix survives a rack that grows again, which is
## the general form of the bug that shipped.
## The ADE+SBC gun (rack id 17) was later RETIRED, so the rack went back to 17
## with LEADGAIN (16) as the newest id. KNOWLEDGE now occupies id 17 again, so
## the newest id is asserted as a DERIVED value (`NumRackGuns - 1`), never a
## literal: the guard is unchanged in shape and in strength, and C3 still proves
## the fix survives a rack that grows again, which is the general form of the bug
## that shipped.
##
## Run: nim c -r common_libs/tests/test_rack_stat_width.nim
## Live: TR_SERVER_JAR=... TR_BATTLE_RUNNER=... nim c -r common_libs/tests/test_rack_stat_width.nim
@@ -47,7 +50,7 @@ const
adversaryDir = repoRoot / "common_libs" / "test_framework" / "adversaries" / "SittingDuck"
statsPath = "/tmp/rack_stat_width_stats.jsonl"
PatternId = 5
NewestId = NumRackGuns - 1 ## 16 (LEADGAIN), the newest rack id
NewestId = NumRackGuns - 1 ## the newest rack id (KNOWLEDGE)
LegacyLeadGainId = 16
var failures = 0
@@ -59,7 +62,7 @@ proc check(name: string, ok: bool) =
proc testRackTable() =
check "A1: NumRackGuns is derived from RackGunNames",
NumRackGuns == RackGunNames.len and NumRackGuns == 17
NumRackGuns == RackGunNames.len and NumRackGuns > 0
check "A2: rack membership table has one entry per gun",
DefaultRackMembership.len == NumRackGuns
var seen = initTable[string, bool]()
@@ -176,9 +179,9 @@ proc testAccounting() =
check "C3: a rack one gun WIDER is still fully covered by the NumRackGuns width",
grownOk and grown[NumRackGuns] == 1
# The legacy namespace: TR_RACK_BITBRAIN is now unambiguously LEADGAIN's old
# The legacy namespace: TR_RACK_BITBRAIN is unambiguously LEADGAIN's old
# name (the ADE+SBC gun that briefly owned it was retired), so it always
# admits LEADGAIN (16) — the newest id — and nothing else.
# admits LEADGAIN (16) — and nothing else, not the gun that reused id 17.
for n in RackGunNames: delEnv("TR_RACK_" & n)
delEnv("TR_BITBRAIN_NET")
putEnv("TR_RACK_BITBRAIN", "both")
@@ -62,7 +62,8 @@ proc seedOldRack(t: var VirtualTracker, targetId: int) =
# ── registration table ────────────────────────────────────────────────────────
proc testTable() =
check "rack: RackGunNames has 17 entries", RackGunNames.len == 17
check "rack: RackGunNames has one entry per rack gun (width derived)",
RackGunNames.len == NumRackGuns
check "rack: the new gun is named TMPATTERN at id 14",
RackGunNames[TmPatternId] == "TMPATTERN"
check "rack: the new gun defaults to `off`",
+547
View File
@@ -0,0 +1,547 @@
## Offline tests for the WaveElm gun (common_libs/guns/waveelm.nim): the
## simulated expanding RING, the probe geometry, the polar bias learning and
## every guard path.
##
## Run: nim c -r --path:common_libs common_libs/tests/test_waveelm.nim
import std/[math, strformat, times, sequtils]
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import guns/elm
import guns/waveelm
import guns/linear
import gun_harness/offline_range
var failures = 0
proc check(name: string, ok: bool) =
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
# ── a local WorldState builder (offline_range's mkState is private) ───────────
proc mkState(tick: int, ex, ey, eh, es: float, sx = 100.0, sy = 300.0,
id = 1, w = 800.0, h = 600.0): WorldState =
WorldState(
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
selfX: sx, selfY: sy, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: w, arenaHeight: h, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
proc finite(p: GunPrediction): bool =
classify(p.x) notin {fcNan, fcInf, fcNegInf} and
classify(p.y) notin {fcNan, fcInf, fcNegInf} and
classify(p.confidence) notin {fcNan, fcInf, fcNegInf}
# ── the target the learning tests fly ─────────────────────────────────────────
#
# A STRAIGHT RUN at 2 px/tick (a realistic tickRate-limited bot speed) that fits
# inside the arena for the whole run, so it never bounces. Straight, and never
# bouncing, for two reasons that are properties of ANY constant-velocity lead —
# the ring's and the old intercept's alike:
# * a target that TURNS: the lead is straight, so the base is wrong by more
# than BotRadius for the whole flight, no shot is ever a confirmed hit, no
# label is ever produced, and the gun learns nothing (asserted explicitly in
# `testSupervision`, not hidden by feeding it synthetic hits);
# * a target that BOUNCES off a wall: the lead is straight through the wall.
const
TrajSpeed = 2.0
TrajX0 = 150.0
TrajY = 300.0
proc trajPos(tick: int): tuple[x, y, heading: float] =
(TrajX0 + TrajSpeed * tick.float, TrajY, 0.0)
proc traj(tick: int): WorldState =
let (x, y, hd) = trajPos(tick)
mkState(tick, x, y, hd, TrajSpeed)
const
TruthLag* = 4.0 ## the turret-lag model the bench uses: the aim solution that
## was actually used is `TruthLag` ticks stale, by this gain
TruthGain* = 1.0
proc biasedTruth(tick: int, biasX, biasY: float): tuple[x, y: float] =
## Where the bullet really arrives, under the turret-lag model the gun is
## built to absorb: the aim in force was the solution for the target
## `TruthLag` ticks ago, so the truth is displaced by that much motion on top
## of the constant systematic `bias`.
let now = traj(tick)
let past = traj(tick - int(TruthLag))
(now.enemyX + biasX + TruthGain * (now.enemyX - past.enemyX),
now.enemyY + biasY + TruthGain * (now.enemyY - past.enemyY))
proc orbitState(tick: int, degPerTick: float, radius: float): WorldState =
## A hard-turning target: the regime in which the constant-velocity base has no
## supervision at all.
let a = degToRad(tick.float * degPerTick)
mkState(tick, 400.0 + radius * cos(a), 300.0 + radius * sin(a),
tick.float * degPerTick, TrajSpeed)
const
TrainTicks* = 200 ## learnLoop drives ticks 0 ..< TrainTicks
HeldOutTick* = TrainTicks + 5 ## a tick the net was never trained on
# ── 1. the power ladder and the 20 - 3*power bullet-speed formula ──────────────
proc testLadder() =
check "ladder: bulletSpeed(1.0) == 17.0 (20 - 3*power)", bulletSpeed(1.0) == 17.0
check "ladder: bulletSpeed(2.0) == 14.0", bulletSpeed(2.0) == 14.0
check "ladder: bulletSpeed(3.0) == 11.0", bulletSpeed(3.0) == 11.0
var allDistinct = true
for i in 0..<WaveRungs:
for j in i + 1..<WaveRungs:
if abs(bulletSpeed(WavePowers[i]) - bulletSpeed(WavePowers[j])) < 1e-9:
allDistinct = false
check "ladder: every rung is a distinct bullet speed", allDistinct
var legal = true
for p in WavePowers:
if p > 3.0: legal = false
check "ladder: every power is legal for Tank Royale (<= 3.0)", legal
# A wave on a STATIONARY target: each rung's ring reaches a different radius,
# so the three rungs measure the target at three different flight times. The
# contact radius is the smallest multiple of the rung speed within BotRadius of
# the true distance.
let ex = 500.0
let ey = 300.0
let d = hypot(ex - 100.0, ey - 300.0)
var hits: seq[RingHit]
# a stationary target, sampled long enough for the slowest rung's flight
var px = newSeq[float](200)
var py = newSeq[float](200)
for t in 0..<200: px[t] = ex; py[t] = ey
for p in WavePowers:
hits.add ringFire(100.0, 300.0, p, px, py, 0)
check "wave: every rung's ring intercepts a stationary in-range target",
hits[0].found and hits[1].found and hits[2].found
var threeRungs = true
for i in 0..<3:
if abs(hits[i].dist - d) > BotRadius: threeRungs = false
check &"wave: the three rungs measure the SAME {d:.1f} px target (all within BotRadius)",
threeRungs
check "wave: three rungs, three distinct contact ticks (three flight times)",
hits[0].tick != hits[1].tick and hits[1].tick != hits[2].tick
check "wave: the fastest rung contacts first", hits[0].tick < hits[2].tick
# ── 2. the ring: probe geometry, interception, decoding ───────────────────────
proc ey0(): float = 300.0 ## a stationary target's y, for the out-of-range block
proc testRing() =
# N derivation: no angular gap wider than a bot at the arena diagonal.
check &"ring: N = {RingProbes} for rMax = {RingRMax:.0f} px (800x600 diagonal)",
RingProbes == ringProbeCount(RingRMax)
check &"ring: the gap at rMax is {2.0*PI*RingRMax/RingProbes.float:.2f} px, inside BotRadius {BotRadius}",
2.0 * PI * RingRMax / RingProbes.float < BotRadius
check "ring: N grows with the range assumption (bigger map -> more probes)",
ringProbeCount(2000.0) > RingProbes and
ringProbeCount(500.0) <= RingProbes
# Interception is guaranteed for an in-range target, at ANY bearing and range.
var found = 0
var tried = 0
for deg in countup(0, 359, 7):
let a = degToRad(deg.float)
for r in [50.0, 150.0, 300.0, 500.0, 700.0, 950.0]:
let ex = 400.0 + r * cos(a)
let ey = 300.0 + r * sin(a)
let n = int(ceil(r / 11.0)) + 2
var px = newSeq[float](n)
var py = newSeq[float](n)
for t in 0..<n: px[t] = ex; py[t] = ey
let h = ringFire(400.0, 300.0, 3.0, px, py, 0)
inc tried
if h.found: inc found
check &"ring: {found}/{tried} in-range interceptions across 52 bearings x 6 ranges",
found == tried
# Decoding: a contact at (radius, bearing) IS the target's position.
block:
let ex = 400.0 + 321.0 * cos(degToRad(37.0))
let ey = 300.0 + 321.0 * sin(degToRad(37.0))
var px = newSeq[float](60); var py = newSeq[float](60)
for t in 0..<60: px[t] = ex; py[t] = ey
let h = ringFire(400.0, 300.0, 2.0, px, py, 0)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: decode(radius, bearing) lands within BotRadius of the target " &
&"({hypot(dx-ex, dy-ey):.2f} px)",
hypot(dx - ex, dy - ey) <= BotRadius
check "ring: the decoded bearing is the probe ray's bearing",
abs(h.bearing - degToRad(37.0)) <= PI / RingProbes.float
# Out of range: nothing is claimed.
block:
let ex = 400.0 + 1800.0
var px = newSeq[float](80); var py = newSeq[float](80)
for t in 0..<80: px[t] = ex; py[t] = ey0()
let h = ringFire(400.0, 300.0, 1.0, px, py, 0)
check "ring: no interception is claimed for an out-of-range target", not h.found
check "ring: an out-of-range contact reports NaN distance, not a number",
classify(h.dist) == fcNan
# Edge cases: no crash, no NaN, and an enemy ON the shooter is still hit (the
# first annulus at 17 px is inside the 18 px radius).
block:
var px = newSeq[float](200)
var py = newSeq[float](200)
for t in 0..<200: px[t] = 400.0; py[t] = 300.0
let h = ringFire(400.0, 300.0, 1.0, px, py, 0)
check "ring: an enemy at the shooter's own position is contacted, not NaN",
h.found and h.dist == bulletSpeed(1.0)
check "ring: a zero bullet speed (power 20/3) claims nothing",
not ringFire(400.0, 300.0, 20.0 / 3.0, px, py, 0).found
# a trajectory that ENDS before the ring can reach the enemy claims nothing
var fx = @[700.0, 700.0, 700.0]
var fy = @[300.0, 300.0, 300.0]
check "ring: a trajectory that runs out before contact claims nothing",
not ringFire(400.0, 300.0, 1.0, fx, fy, 0).found
# ── 3. ELM bias learning on a KNOWN systematic bias ───────────────────────────
#
# IMPORTANT — why the feedback is fed from the TRUE position and not from the
# prediction. The obvious driver (`actual = prediction + bias`) is a POSITIVE
# FEEDBACK LOOP under any implementation: the label is then `correction +
# bias`, so the net is trained to output strictly more than it just output, and
# it walks straight into the offset clamp. A real FeedbackEvent carries the
# enemy's actual position, which does not depend on what we aimed at, and that is
# what is fed here. (Measured: with the prediction-relative driver the net
# saturates at +-36 px within 40 ticks.)
proc learnLoop(g: var WaveElmGun, ticks: int, biasX, biasY: float,
feedHits = true, tick0 = 0): tuple[shots, hits: int] =
## Drive the gun over a moving target exactly as the harness would: one predict
## per rung per tick, then an event whose ACTUAL position is the target's TRUE
## position AT THE BULLET'S ARRIVAL (the ring's contact is a lead: it is the
## target's position `flight` ticks from now, which is where a bullet fired now
## lands) plus the systematic `bias`. `hit` is TRUE only when the target was
## inside BotRadius of the aim point — the virtual-bullet resolver's own
## criterion, and the reason a miss carries no label.
for i in 0..<ticks:
let t = tick0 + i
let st = traj(t)
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let truth = biasedTruth(t + k, (if feedHits: biasX else: 0.0),
(if feedHits: biasY else: 0.0))
let (ax, ay) = truth
let res = hypot(pr.x - ax, pr.y - ay)
let hit = feedHits and res <= BotRadius
inc result.shots
if hit: inc result.hits
g.onResult(FeedbackEvent(
prediction: pr, actualX: ax, actualY: ay,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: res, hit: hit, confidence: pr.confidence))
## RMS aim error of the gun over a held-out window, and of the RAW ring
## reconstruction it sits on (bias 0). The ELM earns its place only if the
## second is strictly worse than the first.
proc heldOutRms(g: var WaveElmGun, fromTick, n: int, biasX, biasY: float): float =
## The aim is scored against where the bullet ARRIVES: the ring's contact is a
## LEAD, so scoring it against the target's current position would charge the
## gun for the lead it is supposed to apply.
var sq = 0.0
for t in fromTick..<(fromTick + n):
let st = traj(t)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let (tx, ty) = biasedTruth(t + k, biasX, biasY)
sq += (pr.x - tx) ^ 2 + (pr.y - ty) ^ 2
sqrt(sq / (n.float * WaveRungs.float))
proc rawRms(fromTick, n: int, biasX, biasY: float): float =
## Same window, same bias, but a gun that never learned anything: the aim is
## the bare ring reconstruction.
var g = initWaveElmGun()
var sq = 0.0
for t in fromTick..<(fromTick + n):
let st = traj(t)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let (tx, ty) = biasedTruth(t + k, biasX, biasY)
sq += (pr.x - tx) ^ 2 + (pr.y - ty) ^ 2
sqrt(sq / (n.float * WaveRungs.float))
proc testLearning() =
block:
var g = initWaveElmGun()
let cnt = learnLoop(g, TrainTicks, 5.0, 0.0)
echo &" trained={g.trainedShots} traceMisses={g.traceMisses} " &
&"rejected={g.rejectedShots} misses={g.missShots} netSamples={g.net.samples} " &
&"rings={g.ringContacts}/{g.ringFires} hits={cnt.hits}/{cnt.shots}"
check "learning: every CONFIRMED hit trained (no fabricated, no lost samples)",
g.trainedShots == cnt.hits and g.traceMisses == 0
check "learning: misses are counted and never trained",
g.missShots + g.trainedShots + g.rejectedShots == cnt.shots
check "learning: the ring fired and found a contact on essentially every tick",
g.ringContacts >= g.ringFires - 2 and g.ringFires > 0
check "learning: net is still sane after 200 RLS updates", g.net.isSane()
# HELD-OUT window: the net has never seen these ticks.
let base = rawRms(TrainTicks, 60, 5.0, 0.0)
let got = heldOutRms(g, TrainTicks, 60, 5.0, 0.0)
echo &" held-out aim RMS vs truth (bias 5 px + turret lag): ring alone {base:.2f} px -> with the ELM {got:.2f} px"
# An ABSOLUTE margin, not a percentage: the bare ring's error on a given tick
# is dominated by the annulus quantisation (+-spd/2), which the bias happens
# to cancel or double, so a ratio threshold measures the target's luck.
check &"learning: the ELM beats the bare ring reconstruction ({got:.2f} < {base:.2f} px)",
got < base - 0.5
# LABEL SURVIVAL, the number the directed design was killed for: only
# confirmed hits carry a label, so the survival rate IS the interception
# rate. The directed design measured 21.5%.
let surv = cnt.hits.float / cnt.shots.float
echo &" label survival = {surv*100:.1f}% (directed design measured 21.5%)"
check &"learning: label survival beats the directed design ({surv*100:.1f}% > 21.5%)",
surv > 0.215
block:
# A 2-D bias: the two outputs are independent, neither steals the other.
var g = initWaveElmGun()
discard learnLoop(g, TrainTicks, -4.0, 7.0)
let st = traj(HeldOutTick)
let pr = g.predict(st, bulletSpeed(2.0))
echo &" 2-D bias, held-out correction: ({g.lastDx:.3f}, {g.lastDy:.3f}), truth (-4, 7)"
check "learning: the 2-D correction points along the bias it was trained on",
(g.lastDx * -4.0 + g.lastDy * 7.0) > 0.0
let base = rawRms(TrainTicks, 60, -4.0, 7.0)
let got = heldOutRms(g, TrainTicks, 60, -4.0, 7.0)
echo &" held-out aim RMS vs truth (bias (-4,7) + turret lag): ring alone {base:.2f} px -> with the ELM {got:.2f} px"
check &"learning: the ELM beats the bare ring on a 2-D bias too ({got:.2f} < {base:.2f} px)",
got < base - 0.5
proc testSupervision() =
## THE STARVATION LIMITATION, asserted rather than hidden: on a target that
## turns hard every tick the ring's constant-velocity base is wrong by more
## than BotRadius for the whole flight, so not one shot is a confirmed hit and
## the net gets no labels. The directed design had the same failure (its
## measured label survival was 21.5%); the ring's failure is sharper, because
## its base error grows with the turn.
block: # the straight-line target DOES supervise
var g = initWaveElmGun()
let c = learnLoop(g, TrainTicks, 5.0, 0.0)
echo &" straight target: labels {c.hits}/{c.shots} ({c.hits*100/c.shots}%)"
check "supervision: the straight-line target supervises the net (> 80% labels)",
c.hits.float / c.shots.float > 0.8
block: # a hard turner does not, and that is a documented ceiling
var g = initWaveElmGun()
var shots = 0
var hits = 0
for t in 0..<TrainTicks:
let st = orbitState(t, 6.0, 48.0)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(0, int(round(g.ringFor(st.enemies[0].id).flight)))
let truth = orbitState(t + k, 6.0, 48.0)
let res = hypot(pr.x - truth.enemyX, pr.y - truth.enemyY)
inc shots
if res <= BotRadius: inc hits
g.onResult(FeedbackEvent(prediction: pr, actualX: truth.enemyX,
actualY: truth.enemyY, bulletPower: p, fireTick: t,
powerBin: waveBinForSpeed(bulletSpeed(p)), missDistance: res,
hit: res <= BotRadius, confidence: pr.confidence))
echo &" 6 deg/tick orbit: labels {hits}/{shots}"
check "supervision: a 6 deg/tick orbit yields no usable labels (known ceiling)",
hits == 0 and g.trainedShots == 0
# ── 4. guard paths ────────────────────────────────────────────────────────────
proc testGuards() =
block:
# Implausibly large residual: a "hit" 500 px from the aim point is not this
# gun's model, so it must never reach beta.
var g = initWaveElmGun()
discard learnLoop(g, 60, 5.0, 0.0)
let before = g.trainedShots
let st = mkState(500, 400.0, 300.0, 0.0, 5.0)
let big = 500.0
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# the label is (actual - ring reconstruction), so the residual is injected
# at the RECONSTRUCTION, not at the already-corrected aim point
let (bx, by) = ringDecode(g.ringFor(1), st.selfX, st.selfY)
g.onResult(FeedbackEvent(prediction: pr,
actualX: bx + big, actualY: by,
bulletPower: p, fireTick: 500, powerBin: waveBinForSpeed(spd),
hit: true, confidence: pr.confidence))
check &"guard: a {WaveMaxResidual:.0f} px residual is rejected ({big:.0f} px fed)",
g.trainedShots == before and g.rejectedShots == WaveRungs
check "guard: a residual exactly at the limit ({3.0*BotRadius:.0f} px) is still accepted",
(block:
var g2 = initWaveElmGun()
discard learnLoop(g2, 40, 0.0, 0.0)
let b2 = g2.trainedShots
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g2.predict(st, spd)
let (bx, by) = ringDecode(g2.ringFor(1), st.selfX, st.selfY)
let d = 3.0 * BotRadius - 0.001
g2.onResult(FeedbackEvent(prediction: pr,
actualX: bx + d, actualY: by,
bulletPower: p, fireTick: st.tick, powerBin: waveBinForSpeed(spd),
hit: true, confidence: pr.confidence))
g2.trainedShots > b2)
block:
# A MISS carries no label: it says the aim was wrong, not where.
var g = initWaveElmGun()
let c = learnLoop(g, 40, 0.0, 0.0, feedHits = false)
check "guard: misses are never trained on", g.trainedShots == 0
check "guard: misses are counted", g.missShots == c.shots
block:
# An orphaned event (no trace in the ring) must be counted, not fabricated.
var g = initWaveElmGun()
discard learnLoop(g, 10, 5.0, 0.0)
let st = mkState(77, 400.0, 300.0, 0.0, 5.0)
let pr = g.predict(st, bulletSpeed(2.0))
let before = g.trainedShots
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 3.0, actualY: pr.y,
bulletPower: 2.0, fireTick: 999999, powerBin: 2, hit: true,
confidence: pr.confidence)) # orphan: the trace lookup fails first
check "guard: an orphaned hit (unknown fireTick) is counted, not fabricated",
g.trainedShots == before and g.traceMisses == 1
block:
# A brand new gun, no history at all.
var g = initWaveElmGun()
let st = mkState(0, 500.0, 300.0, 45.0, 6.0)
let pr = g.predict(st, bulletSpeed(1.0))
check "guard: a fresh bot with no scan history predicts without crashing",
pr.finite and pr.x > 0.0 and pr.y > 0.0
check "guard: a fresh bot is not warmed up (needs 2 scans for a velocity)",
not g.isWarmedUp()
let st2 = mkState(1, 506.0, 300.0, 45.0, 6.0)
discard g.predict(st2, bulletSpeed(1.0))
check "guard: two scans make it warm", g.isWarmedUp()
block:
# NaN / Inf must never escape the gun, in the state or in the net.
var g = initWaveElmGun()
let nan = 0.0 / 0.0
let inf = 1.0 / 0.0
for bad in [nan, inf, -inf]:
let st = mkState(1, bad, 300.0, bad, bad)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
if not pr.finite:
check &"guard: NaN/Inf in the state never escapes (bad={bad})", false
return
check "guard: NaN/Inf in the state never escapes the prediction", true
check "guard: features of a degenerate state are all finite",
(block:
let st = mkState(1, nan, nan, nan, nan)
let f = g.waveFeatures(st, 0.0, 0.0, 0.0)
var ok = true
for v in f:
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
ok)
# ── 5. Gun-concept conformance ────────────────────────────────────────────────
proc testGunConcept() =
var g = initWaveElmGun()
var x = 300.0
var y = 300.0
var sawDistinct = false
var last: seq[GunPrediction]
for t in 0..<12:
let st = mkState(t, x, y, 30.0, 6.0)
var preds: seq[GunPrediction]
for p in WavePowers: preds.add g.predict(st, bulletSpeed(p))
if last.len == preds.len and last.len > 0:
for i in 0..<preds.len:
if hypot(preds[i].x - last[i].x, preds[i].y - last[i].y) > 1.0:
sawDistinct = true
last = preds
for i, p in WavePowers:
let spd = bulletSpeed(p)
let pr = preds[i]
g.onResult(FeedbackEvent(prediction: pr,
actualX: pr.x + 6.0, actualY: pr.y - 2.0,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
hit: true, confidence: pr.confidence))
x += 5.2
check "gun: predict/onResult are a valid Gun pair (isGun template)",
isGun(WaveElmGun)
check "gun: the ring-tracked aim moves as the target moves", sawDistinct
check "gun: the wave trained on every rung", g.trainedShots == 12 * WaveRungs
check "gun: net sane", g.net.isSane()
# ── 6. it produces a usable aim point on every rung of a straight target ─────
proc testAgainstLinear() =
## Same convention as the other offline gun tests: replaying a stream through
## the real VirtualTracker is the online hit rate. Compared against Linear as
## the closed-form baseline.
var states: seq[WorldState]
var x = 100.0
for t in 0..<240:
states.add mkState(t, x, 300.0, 0.0, 4.0)
x = (x + 4.0).clamp(BotRadius, 800.0 - BotRadius)
var meta = initMeta(source = "synthetic")
meta.adversary = "constant-velocity"
meta.note = "constant-velocity reference stream for WaveElm"
let fx = initFixture(states, meta)
let reps = replayFixture(fx, @[makeDriver("WaveElm", initWaveElmGun()),
makeDriver("Linear", LinearGun())])
echo &" {reps[0].name} {reps[0].hits}/{reps[0].shots} ({reps[0].hitRate()*100:.1f}%)" &
&" {reps[1].name} {reps[1].hits}/{reps[1].shots} ({reps[1].hitRate()*100:.1f}%)"
check "replay: the wave was actually shot at over the whole stream",
reps[0].shots > 100
check "replay: WaveElm is not worse than the closed-form Linear baseline",
reps[0].hitRate() >= reps[1].hitRate() - 0.02
# ── 7. REGRESSION: non-finite state must not hang the gun ────────────────────
proc testNonFiniteState() =
## enemyHeading = ±Inf used to hang the bot outright: the angle wrap was
## `while hdelta > 180: hdelta -= 360`, and `Inf - 360.0 == Inf`, so the body
## made no progress and the loop never left (100% CPU, no output). Every FLOAT
## field of the state is now non-finite in turn, and predict must both return
## promptly and return finite numbers.
var g = initWaveElmGun()
let nan = 0.0 / 0.0
for (label, bad) in [("NaN", nan), ("+Inf", 1.0 / 0.0), ("-Inf", -1.0 / 0.0)]:
for field in ["enemyX", "enemyY", "enemyHeading", "enemySpeed",
"selfX", "selfY", "arenaWidth", "arenaHeight"]:
var st = mkState(3, 420.0, 260.0, 35.0, 5.0)
case field
of "enemyX": st.enemyX = bad
of "enemyY": st.enemyY = bad
of "enemyHeading": st.enemyHeading = bad
of "enemySpeed": st.enemySpeed = bad
of "selfX": st.selfX = bad
of "selfY": st.selfY = bad
of "arenaWidth": st.arenaWidth = bad
else: st.arenaHeight = bad
var ok = true
let t0 = epochTime()
for p in WavePowers:
if not g.predict(st, bulletSpeed(p)).finite: ok = false
let f = g.waveFeatures(st, 1.0, 1.0, 30.0)
for v in f:
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
check &"nonfinite: {label} in {field} -> finite prediction and features",
ok
check &"nonfinite: {label} in {field} returns promptly",
epochTime() - t0 < 1.0
when isMainModule:
testLadder()
testRing()
testLearning()
testSupervision()
testGuards()
testGunConcept()
testAgainstLinear()
testNonFiniteState()
if failures > 0:
echo "\n", failures, " check(s) FAILED"
quit(1)
echo "\nAll WaveElm checks passed."
@@ -0,0 +1,287 @@
## test_waveelm_flighttime.nim — regression test for the LEFT/RIGHT OVERSHOOT,
## against the RING base (common_libs/guns/waveelm.nim).
##
## BUG (fixed by WaveResolveFeatures): a shot fired at tick T resolves at
## T + flightTime (the ring's contact, 3-90 ticks, far longer than the RLS memory
## 1/(rho-1) ~ 12 ticks). onResult trained the label -- which describes the aim
## bias at the ARRIVAL tick -- on the FIRE-time features. The net was therefore
## fitted to a map that extrapolates the bias a whole flight time forward, and
## then applied it to fire-time features, where it would only have to read it off.
## A short-memory RLS fits the bias to the target's PAST motion and swings the
## correction sideways as the target strafes: the reported "continuously
## overshooting left and right".
##
## WHAT IS ASSERTED: with the feedback DELAYED by the real flight time, the
## gun's aim error measured PERPENDICULAR to the true offset direction (the
## lateral / left-right component, the one the user saw) collapses. The
## perpendicular component is the oscillation: an along-track error is just an
## under/over-lead, a lateral one is the aim crossing to the other side.
##
## THE IDEAL CORRECTOR (the ground truth of the aim) is now the RING
## RECONSTRUCTION plus the turret-lag bias — the same quantity the bench
## (bench_waveelm_temporal.nim) uses, with the ring's decoding standing in for
## the intercept solver that used to provide the base.
##
## Run: nim c -r common_libs/tests/test_waveelm_flighttime.nim
import std/[math, strformat]
import gun_harness/gun_interface
import guns/waveelm
const
Ticks = 240
SelfX = 100.0
SelfY = 300.0
AW = 800.0
AH = 600.0
Lag = 4
BurnIn = 60
SelfR = BotRadius
type
Regime = enum rSmooth, rAccel, rAbrupt
Traj = object
px, py, hx, hy, sp, ox, oy: seq[float]
Pending = object
resolveAt: int
pr: GunPrediction
truthX, truthY: float ## where the target really is when the bullet lands
fireTick: int
binIdx: int
power: float
Metrics = object
perp: float ## RMS lateral (perpendicular) gun-only error, px
along: float ## RMS along-track gun-only error, px
hit: float ## fraction of shots that landed inside BotRadius
proc regimeName(r: Regime): string =
case r
of rSmooth: "smooth"
of rAccel: "accel"
of rAbrupt: "abrupt"
proc buildTraj(r: Regime): Traj =
result.px = newSeq[float](Ticks); result.py = newSeq[float](Ticks)
result.hx = newSeq[float](Ticks); result.hy = newSeq[float](Ticks)
result.sp = newSeq[float](Ticks)
var x = 400.0
var y = 300.0
var cmd = degToRad(20.0)
var act = cmd
for t in 0..<Ticks:
var speed, turn: float
case r
of rSmooth: speed = 4.0; turn = 3.0
of rAccel:
speed = 2.5 + 0.013 * t.float
turn = 2.0 + 0.018 * t.float
of rAbrupt:
speed = (if t < 150: 4.5 else: 5.5)
turn = (if t < 150: 3.0 else: -3.0)
if speed > 10.0: speed = 10.0
act = degToRad(round(radToDeg(act)) * 1.0)
result.px[t] = x; result.py[t] = y
result.hx[t] = cos(act); result.hy[t] = sin(act); result.sp[t] = speed
x += cos(cmd) * speed
y += sin(cmd) * speed
if x < 150 or x > AW - 150 or y < 150 or y > AH - 150:
cmd = arctan2(AH / 2 - y, AW / 2 - x)
else:
cmd = turn
let gain = proc(t: int): float =
case r
of rSmooth: 1.0
of rAccel: 0.9 + 0.0015 * t.float
of rAbrupt: (if t < 150: 1.0 else: 1.6)
result.ox = newSeq[float](Ticks); result.oy = newSeq[float](Ticks)
for t in 0..<Ticks:
let a = max(0, t - Lag)
result.ox[t] = gain(t) * (result.px[t] - result.px[a])
result.oy[t] = gain(t) * (result.py[t] - result.py[a])
proc mkState(t: int, x, y, hx, hy, sp: float): WorldState =
WorldState(
enemyX: x, enemyY: y,
enemyHeading: radToDeg(arctan2(hy, hx)), enemySpeed: sp, enemyEnergy: 100,
selfX: SelfX, selfY: SelfY, arenaWidth: AW, arenaHeight: AH, tick: t,
enemies: @[EnemyInfo(id: 1, x: x, y: y, energy: 100,
heading: radToDeg(arctan2(hy, hx)), speed: sp,
lastSeenTick: t)])
proc base(g: WaveElmGun, sx = SelfX, sy = SelfY): tuple[x, y: float] =
## THE RING RECONSTRUCTION: the gun's aim with NO learned correction. This is
## what the intercept solver used to provide and what the ELM's offset sits on.
ringDecode(g.ringFor(1), sx, sy)
## The live loop, faithfully: predict at tick t, the label comes back `flight`
## ticks later, and only a HIT is trained on.
proc run(r: Regime, resolveFeat: bool): Metrics =
let tj = buildTraj(r)
var g = initWaveElmGun(resolveFeat = resolveFeat)
var pend: seq[Pending] = @[]
var sqPerp = 0.0
var sqAlong = 0.0
var n = 0
var hits = 0
var shots = 0
for t in 0..<Ticks:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
# the ring's own contact tick, clamped into the trajectory
let ring = g.ringFor(1)
let tof = if ring.valid: max(1, min(Ticks - 1, ring.flight.int))
else: 1
let ta = min(Ticks - 1, t + tof)
let (bx, by) = g.base()
let hitX = clamp(bx + tj.ox[ta], BotRadius, AW - BotRadius)
let hitY = clamp(by + tj.oy[ta], BotRadius, AH - BotRadius)
inc shots
# GUN-ONLY error: what the gun produced against what an IDEAL corrector
# would produce at the FIRE tick (ring reconstruction + bias(t)),
# decomposed along and across the true offset direction.
if t >= BurnIn:
let ix = clamp(bx + tj.ox[t], BotRadius, AW - BotRadius)
let iy = clamp(by + tj.oy[t], BotRadius, AH - BotRadius)
let um = hypot(tj.ox[t], tj.oy[t])
if um > 1.0:
let ex = pr.x - ix
let ey = pr.y - iy
sqAlong += ((ex * tj.ox[t] + ey * tj.oy[t]) / um) ^ 2
sqPerp += ((ex * -tj.oy[t] + ey * tj.ox[t]) / um) ^ 2
inc n
pend.add Pending(resolveAt: t + tof, pr: pr, truthX: hitX, truthY: hitY,
fireTick: t, binIdx: waveBinForSpeed(spd), power: p)
# HARNESS ORDER, and it matters: the bullets are resolved AFTER predict, so
# the flight-time feature refresh (which runs inside predict, for the traces
# due on THIS tick) has already rebuilt their features before onResult trains
# on them. Resolving before predict would silently test the un-refreshed path
# and make the A/B below a no-op.
var keep: seq[Pending] = @[]
for p in pend:
if p.resolveAt <= t:
let res = hypot(p.truthX - p.pr.x, p.truthY - p.pr.y)
let didHit = res <= BotRadius
if didHit: inc hits
g.onResult(FeedbackEvent(
prediction: p.pr, actualX: p.truthX, actualY: p.truthY,
bulletPower: p.power, fireTick: p.fireTick, powerBin: p.binIdx,
missDistance: res, hit: didHit, confidence: p.pr.confidence))
else:
keep.add p
pend = keep
if n > 0:
result.perp = sqrt(sqPerp / n.float)
result.along = sqrt(sqAlong / n.float)
result.hit = (if shots > 0: hits.float / shots.float else: 0.0)
# ── the assertions ───────────────────────────────────────────────────────────
var failures = 0
proc check(name: string, ok: bool, detail: string) =
if ok: echo " ok ", name, " — ", detail
else:
echo " FAIL ", name, " — ", detail
inc failures
block:
echo "── flight-time feature mismatch: lateral (left-right) aim error ──"
echo " (diagnostic A/B: the right column is the fix forced OFF, i.e. what"
echo " the gun did before; the ASSERTIONS below are on the SHIPPED default)"
for r in Regime:
let on = run(r, resolveFeat = WaveResolveFeatures)
let off = run(r, resolveFeat = false)
echo &" {regimeName(r):<7} default: perp={on.perp:6.2f} along={on.along:6.2f} hit={on.hit*100:6.2f}%" &
&" | fire-time feats (before): perp={off.perp:6.2f} along={off.along:6.2f} hit={off.hit*100:6.2f}%"
# The oscillation is the LATERAL component: an along-track error is just an
# under/over-lead, a lateral one is the aim crossing to the other side.
case r
of rSmooth: check("smooth: lateral error stays negligible",
on.perp < 1.0, &"{on.perp:.2f} px")
of rAccel: check("accel: lateral error under 8 px (was 10.9 px without the refresh)",
on.perp < 8.0, &"{on.perp:.2f} px")
of rAbrupt: check("abrupt: lateral error under 3 px (was 1.6 px without the refresh)",
on.perp < 3.0, &"{on.perp:.2f} px")
check(&"{regimeName(r)}: hit rate does not regress",
on.hit >= off.hit, &"{on.hit*100:.2f}% vs {off.hit*100:.2f}%")
check(&"{regimeName(r)}: the ring intercepts enough shots to supervise at all",
on.hit > 0.0, &"{on.hit*100:.2f}%")
block:
# The fix must be a NO-OP when the feedback is not delayed (the offline
# benchmark's shape): then the fire tick IS the label tick and there is nothing
# to realign.
echo "── no-op when the label arrives on the fire tick ──"
let r = rAccel
let tj = buildTraj(r)
var a = initWaveElmGun(resolveFeat = true)
var b = initWaveElmGun(resolveFeat = false)
for t in 0..<120:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pa = a.predict(st, spd)
let pb = b.predict(st, spd)
let (bx, by) = a.base()
let truthX = clamp(bx + tj.ox[t], BotRadius, AW - BotRadius)
let truthY = clamp(by + tj.oy[t], BotRadius, AH - BotRadius)
let ev = FeedbackEvent(
prediction: pa, actualX: truthX, actualY: truthY, bulletPower: p,
fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: hypot(truthX - pa.x, truthY - pa.y),
hit: true, confidence: pa.confidence)
a.onResult(ev)
b.onResult(FeedbackEvent(
prediction: pb, actualX: truthX, actualY: truthY,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(spd),
missDistance: hypot(truthX - pb.x, truthY - pb.y),
hit: true, confidence: pb.confidence))
check("identical corrections when feedback is undelayed",
a.lastDx == b.lastDx and a.lastDy == b.lastDy,
&"({a.lastDx:.6f},{a.lastDy:.6f}) vs ({b.lastDx:.6f},{b.lastDy:.6f})")
block:
# the trace must still be FOUND at the arrival tick (the refresh must not
# break the (fireTick, binIdx) lookup) -- i.e. no label is lost to it.
echo "── probe bookkeeping survives the refresh ──"
let tj = buildTraj(rSmooth)
var g = initWaveElmGun()
var pend: seq[Pending] = @[]
var lost = 0
for t in 0..<Ticks:
let st = mkState(t, tj.px[t], tj.py[t], tj.hx[t], tj.hy[t], tj.sp[t])
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
let ring = g.ringFor(1)
let tof = if ring.valid: max(1, min(Ticks - 1, ring.flight.int)) else: 1
let ta = min(Ticks - 1, t + tof)
let (bx, by) = g.base()
pend.add Pending(
resolveAt: t + tof, pr: pr,
truthX: clamp(bx + tj.ox[ta], BotRadius, AW - BotRadius),
truthY: clamp(by + tj.oy[ta], BotRadius, AH - BotRadius),
fireTick: t, binIdx: waveBinForSpeed(spd), power: p)
# resolve after predict, as the harness does (see the note in `run`)
var keep: seq[Pending] = @[]
for p in pend:
if p.resolveAt <= t:
let res = hypot(p.truthX - p.pr.x, p.truthY - p.pr.y)
let before = g.trainedShots
g.onResult(FeedbackEvent(
prediction: p.pr, actualX: p.truthX, actualY: p.truthY,
bulletPower: p.power, fireTick: p.fireTick, powerBin: p.binIdx,
missDistance: res, hit: res <= BotRadius, confidence: p.pr.confidence))
if g.trainedShots == before and res <= BotRadius: inc lost
else:
keep.add p
pend = keep
check("no confirmed hit lost to the trace lookup", lost == 0,
&"{lost} hits lost, {g.trainedShots} trained, {g.traceMisses} trace misses")
echo (if failures == 0: "\nALL OK" else: &"\n{failures} FAILURE(S)")
quit(if failures == 0: 0 else: 1)
@@ -0,0 +1,120 @@
## ONLINE REAL-BATTLE check for the WAVEELM gun (rack id 18,
## `common_libs/guns/waveelm.nim` — the online-ELM gun).
##
## It answers one question the offline suites cannot: does the LIVE ModularBot
## actually DISCOVER and USE the gun? Two short battles (3 rounds each, the
## `maxSpeed` default) force WAVEELM alone in the rack with env vars only —
## `TR_RACK_WAVEELM=both`, every other gun `off` — against the two shared
## adversaries: SittingDuck (passive) and OscillatorBot (fights back).
##
## Each battle is read from the bot's own per-round gun dump
## (`GUN_STATS_PATH`), and the gun is only "discovered and used" if the live
## loop SPAWNED virtual bullets for id 18 (vShots > 0) and the live selector
## SELECTED it (selected > 0).
##
## Run:
## TR_SERVER_JAR=... TR_BATTLE_RUNNER=... \
## nim c -r common_libs/tests/test_waveelm_rack_live.nim
##
## Skips (exit 0) when the TR JARs are absent, matching the other live tests.
import std/[os, json, strutils]
import test_framework/test_framework
import gun_harness/selector
import gun_harness/virtual_bullets
const
repoRoot = currentSourcePath().parentDir.parentDir.parentDir
modularBotDir = repoRoot / "ModularBot_garage"
adversariesDir = repoRoot / "common_libs" / "test_framework" / "adversaries"
statsPath = "/tmp/waveelm_rack_stats.jsonl"
const WaveElmId = 18
var failures = 0
proc check(name: string, ok: bool) =
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc lastRound(path: string): JsonNode =
result = nil
for line in lines(path):
let s = line.strip()
if s.len == 0: continue
let node = parseJson(s)
if node.hasKey("guns"): result = node
proc runOne(adversary: string) =
let advDir = adversariesDir / adversary
if not dirExists(advDir):
echo "Skipping: adversary not found: ", advDir
quit(0)
if fileExists(statsPath): removeFile(statsPath)
# Force the new gun alone: every other rack entry off, WAVEELM in both racks.
for i, name in RackGunNames:
putEnv("TR_RACK_" & name, if i == WaveElmId: "both" else: "off")
putEnv("GUN_STATS_PATH", statsPath)
defer:
for name in RackGunNames: delEnv("TR_RACK_" & name)
delEnv("GUN_STATS_PATH")
echo "=== live: ModularBot (only WAVEELM racked) vs ", adversary, ", 3 rounds ==="
let battle = runBattle(@[modularBotDir, advDir], rounds = 3)
for res in battle.results:
echo " ", res.name, " rank=", res.rank, " score=", res.totalScore
if not fileExists(statsPath):
echo "FAIL: no gun_stats dump at ", statsPath
inc failures
return
let round = lastRound(statsPath)
check adversary & ": gun_stats.jsonl has a round record", round != nil
if round == nil: return
var shots = 0
var selected = 0
var otherSelected = 0
for g in round["guns"]:
if g["id"].getInt() == WaveElmId:
shots = g["vShots"].getInt()
selected = g["selected"].getInt()
elif g["selected"].getInt() > 0:
otherSelected += g["selected"].getInt()
echo "gun ", WaveElmId, " (WaveElm): vShots=", shots, " selected=", selected,
" other-gun selections=", otherSelected
check adversary & ": the live loop SPAWNED virtual bullets for gun 18 (vShots > 0)",
shots > 0
check adversary & ": the live selector SELECTED gun 18 (selected > 0)",
selected > 0
check adversary & ": no other gun was selected while WAVEELM was forced alone",
otherSelected == 0
proc main() =
let serverJar = getEnv("TR_SERVER_JAR", "")
let runnerJar = getEnv("TR_BATTLE_RUNNER", "")
if serverJar.len == 0 or runnerJar.len == 0:
echo "Skipping: TR_SERVER_JAR / TR_BATTLE_RUNNER not set"
quit(0)
if not fileExists(serverJar) or not fileExists(runnerJar):
echo "Skipping: TR JARs not found (server=", serverJar, ", runner=", runnerJar, ")"
quit(0)
if not fileExists(modularBotDir / "src" / "ModularBot.nim"):
echo "Skipping: ModularBot source not found"
quit(0)
check "rack: WAVEELM is registered at id 18", RackGunNames[WaveElmId] == "WAVEELM"
check "rack: WAVEELM ships `off`, like every gun except Pattern",
ActiveRackMembership[WaveElmId] == rmOff
runOne("SittingDuck")
runOne("OscillatorBot")
if failures > 0:
echo "\n", failures, " check(s) FAILED"
quit(1)
echo "\nWaveElm live rack check passed."
when isMainModule:
main()
+331
View File
@@ -0,0 +1,331 @@
## test_waveelm_ring.nim — the SIMULATED EXPANDING RING, on its own terms.
##
## Everything here tests `ringFire` / `ringProbeCount` / the gun's scan-only ring,
## NOT the ELM on top of it (common_libs/tests/test_waveelm.nim covers that):
##
## (a) interception is GUARANTEED for an in-range enemy, across bearings, ranges
## and motion — the 100% claim, asserted rather than assumed;
## (b) the radius -> distance decoding is correct against known geometry;
## (c) N directions leave no angular gap wider than a bot at maximum range;
## (d) nothing is claimed for an enemy that is out of range (or unreachably
## fast, or behind a wall the ring cannot be said to have passed);
## (e) the ELM's bias correction converges OFFLINE on a synthetic bias;
## (f) edge cases: enemy at the shooter's own position, at maximum range, at
## zero velocity — no crash, no NaN, no unbounded loop;
## (g) SCAN-ONLY LEGITIMACY: the live ring's entire input is the selected scan
## plus the velocity derived from that same target's own last two scans.
##
## Run: nim c -r common_libs/tests/test_waveelm_ring.nim
import std/[math, strformat, sequtils]
import gun_harness/gun_interface
import guns/elm
import guns/waveelm
var failures = 0
var checks = 0
proc check(name: string, ok: bool) =
inc checks
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc fin(x: float): bool = classify(x) notin {fcNan, fcInf, fcNegInf}
proc mkState(tick: int, ex, ey, eh, es: float, id = 1,
sx = 400.0, sy = 300.0): WorldState =
WorldState(
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
selfX: sx, selfY: sy, arenaWidth: 800.0, arenaHeight: 600.0, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
type Traj = object
px, py: seq[float]
## A straight-line trajectory long enough for the slowest rung's flight.
proc trajLine(x0, y0, vx, vy: float, n: int): Traj =
result.px = newSeq[float](n)
result.py = newSeq[float](n)
for t in 0..<n:
result.px[t] = x0 + vx * t.float
result.py[t] = y0 + vy * t.float
# ── (c) the probe count ──────────────────────────────────────────────────────
proc testProbeCount() =
check &"probes: N = {RingProbes} is derived, not hardcoded",
RingProbes == ringProbeCount(RingRMax)
check &"probes: rMax = the {RingArenaW:.0f}x{RingArenaH:.0f} diagonal = {RingRMax:.1f} px",
abs(RingRMax - hypot(RingArenaW, RingArenaH)) < 1e-9
let gap = 2.0 * PI * RingRMax / RingProbes.float
check &"probes: angular gap at max range is {gap:.2f} px < BotRadius {BotRadius}",
gap < BotRadius
check "probes: the raw minimum N = 2*pi*rMax/BotRadius is 350 for 800x600",
int(ceil(2.0 * PI * 1000.0 / BotRadius)) == 350
check "probes: a bigger map yields more probes, a smaller one fewer",
ringProbeCount(2000.0) > RingProbes and
ringProbeCount(400.0) < RingProbes
check "probes: the gap is inside a bot at the SMALL map's diagonal too",
2.0 * PI * hypot(500.0, 300.0) / ringProbeCount(hypot(500.0, 300.0)).float < BotRadius
check "probes: a degenerate range still yields a usable probe count",
ringProbeCount(0.0) >= 60 and ringProbeCount(-5.0) >= 60
check "probes: the bearings cover the full circle without a seam",
abs(RingDirs[0]) < 1e-12 and
abs(RingDirs[RingProbes - 1] - 2.0 * PI * (RingProbes - 1).float /
RingProbes.float) < 1e-12
# the worst gap is between ADJACENT probes: no bearing has a wider one
var worst = 0.0
for i in 0..<RingProbes:
let a = RingDirs[i]
let b = RingDirs[(i + 1) mod RingProbes]
worst = max(worst, if i == RingProbes - 1: 2.0 * PI - a + b else: b - a)
check &"probes: the widest adjacent gap is {worst*RingRMax:.2f} px at max range",
worst * RingRMax < BotRadius
# ── (a) interception is guaranteed ───────────────────────────────────────────
proc testInterception() =
block: # static targets, every bearing, every range
var found = 0
var tried = 0
var worstRadial = 0.0
for deg in countup(0, 359, 3):
let a = degToRad(deg.float)
for r in [BotRadius, 50.0, 137.0, 300.0, 601.0, 900.0, RingRMax]:
let tj = trajLine(400.0 + r * cos(a), 300.0 + r * sin(a), 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 2.0, tj.px, tj.py, 0)
inc tried
if h.found:
inc found
worstRadial = max(worstRadial, abs(h.dist - r))
check &"ring: {found}/{tried} static interceptions (120 bearings x 7 ranges)",
found == tried
check &"ring: every measurement is within BotRadius of the true range (worst {worstRadial:.2f} px)",
worstRadial <= BotRadius
block: # a MOVING target, faster than the slowest rung, every bearing
var found = 0
var tried = 0
for deg in countup(0, 359, 11):
let a = degToRad(deg.float)
# every velocity is SLOWER than the 11 px/tick rung of this block, which is
# the condition for interception to be guaranteed at all (a target fleeing
# faster than the ring expands is physically unreachable — see
# testNoClaim / the "faster than the bullet" case below)
for (vx, vy) in [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0), (-7.0, 3.0)]:
let tj = trajLine(400.0 + 300.0 * cos(a), 300.0 + 300.0 * sin(a),
vx, vy, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
inc tried
if h.found: inc found
check &"ring: {found}/{tried} moving interceptions (33 bearings x 4 velocities)",
found == tried
block: # a target fleeing at close to the bullet's speed: the ring closes only
# `spd - v` px/tick, so whether it is reached inside the ring's reach is
# an arithmetic question, and the ring must answer it honestly in BOTH
# directions (caught -> contact; out of reach -> nothing claimed).
var caught = 0
var fled = 0
for vx in [-15.0, -12.0, 12.0, 15.0]:
let tj = trajLine(200.0, 300.0, vx, 0.0, 400)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
# The target starts 200 px WEST of the shooter, so vx > 0 is APPROACHING:
# the gap closes at (17 + vx) px/tick, and the contact is reachable only if
# the 200 px close within the ring's own reach (maxK = rMax/17 ticks).
let reachable = 200.0 / (17.0 + vx) <= RingRMax / 17.0
if h.found: inc caught
if not h.found and not reachable: inc fled
check &"ring: a target at vx={vx:.0f} px/tick -> " &
(if h.found: "intercepted" else: "correctly out of reach"),
h.found == reachable
check &"ring: the slow-flee cases are intercepted and the fast-flee ones are not",
caught == 3 and fled == 1
# ── (b) decoding ─────────────────────────────────────────────────────────────
proc testDecoding() =
for r in [60.0, 250.0, 640.0]:
for deg in countup(0, 350, 17):
let a = degToRad(deg.float)
let ex = 400.0 + r * cos(a)
let ey = 300.0 + r * sin(a)
let tj = trajLine(ex, ey, 0.0, 0.0, 300)
let h = ringFire(400.0, 300.0, 2.0, tj.px, tj.py, 0)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: decode at r={r:.0f} deg={deg} is within BotRadius of the target",
h.found and hypot(dx - ex, dy - ey) <= BotRadius
if not (h.found and hypot(dx - ex, dy - ey) <= BotRadius): break
# a moving target: the contact is its position at the FLIGHT TIME, which is the
# lead a bullet fired now must be given.
block:
let tj = trajLine(400.0, 300.0, 6.0, 0.0, 300)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
let k = float(h.tick)
let (dx, dy) = ringDecode(h, 400.0, 300.0)
check &"ring: the decoding is the target's position at the contact tick " &
&"(k={k.int}, err={hypot(dx - tj.px[k.int], dy - tj.py[k.int]):.2f} px)",
h.found and hypot(dx - tj.px[k.int], dy - tj.py[k.int]) <= BotRadius
check "ring: the flight time is reported in ticks, not as an absolute tick",
h.tick > 0 and h.tick < 100 and fin(h.dist) and fin(h.bearing)
# ── (d) out of range, and the other "no" cases ───────────────────────────────
proc testNoClaim() =
block:
let tj = trajLine(400.0 + RingRMax + 250.0, 300.0, 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
check "ring: nothing is claimed past the ring's reach", not h.found
check "ring: a missed ring reports NaN distance, not a plausible number",
classify(h.dist) == fcNan and fin(h.missDist)
block:
# receding faster than the ring expands, starting inside the reach: the ring
# never catches it, and the ring says so.
let tj = trajLine(900.0, 300.0, 20.0, 0.0, 400)
let h = ringFire(400.0, 300.0, 3.0, tj.px, tj.py, 0)
check "ring: a target outrunning the ring is NOT claimed", not h.found
block:
# the trajectory ends before contact
let tj = trajLine(600.0, 300.0, 0.0, 0.0, 2)
check "ring: a trajectory that ends early is not claimed",
not ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0).found
check "ring: a fire tick past the end of the trajectory is not claimed",
not ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 5).found
# ── (f) edge cases ───────────────────────────────────────────────────────────
proc testEdgeCases() =
block: # enemy ON the shooter
let tj = trajLine(400.0, 300.0, 0.0, 0.0, 100)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
check "edge: an enemy at the shooter's own position is contacted on tick 1",
h.found and h.tick == 1 and abs(h.dist - 17.0) < 1e-9
let (dx, dy) = ringDecode(h, 400.0, 300.0)
# it decodes to the first annulus (radius 17 px along bearing 0), not to the
# shooter's own point — the ring measures a DISC, and a disc of radius 18
# centred on the shooter is touched by the 17 px annulus.
check "edge: and it decodes to the touched annulus (17 px out), without NaN",
fin(dx) and fin(dy) and abs(hypot(dx - 400.0, dy - 300.0) - 17.0) < 1e-9
block: # zero velocity
let tj = trajLine(700.0, 300.0, 0.0, 0.0, 200)
let h = ringFire(400.0, 300.0, 1.0, tj.px, tj.py, 0)
check "edge: a zero-velocity target is intercepted normally",
h.found and fin(h.dist) and fin(h.bearing) and fin(h.missDist)
block: # maximum range, both extremes of the ladder
for p in WavePowers:
let tj = trajLine(400.0 + RingRMax, 300.0, 0.0, 0.0, 400)
let h = ringFire(400.0, 300.0, p, tj.px, tj.py, 0)
check &"edge: a target at exactly rMax is intercepted on power {p}",
h.found and abs(h.dist - RingRMax) <= BotRadius
block: # non-finite input to the LIVE ring
var g = initWaveElmGun()
let nan = 0.0 / 0.0
let inf = 1.0 / 0.0
for bad in [nan, inf, -inf]:
let st = mkState(1, bad, bad, bad, bad)
let h = g.ringFireFromScan(st, bad, bad, 17.0)
check &"edge: a NaN/Inf scan makes the live ring claim nothing, not crash",
(not h.found) or (fin(h.dist) and fin(h.bearing))
let h0 = g.ringFireFromScan(mkState(1, 600.0, 300.0, 0.0, 5.0), 5.0, 0.0, 0.0)
check "edge: a zero bullet speed claims nothing", not h0.found
# ── (g) SCAN-ONLY LEGITIMACY ─────────────────────────────────────────────────
proc testScanOnly() =
## PROOF, not a promise: the live ring is fed a WorldState and reads the
## SELECTED SCAN. Every other enemy's information in `state.enemies` is
## replaced with garbage — and the ring's output does not move. If the ring
## were using omniscient positions (or any other enemy's), this fails.
var g1 = initWaveElmGun()
var g2 = initWaveElmGun()
var decoy1 = 700.0
var decoy2 = 120.0
for t in 0..<40:
let ex = 300.0 + 4.0 * t.float
var st1 = mkState(t, ex, 300.0, 0.0, 4.0, id = 1)
var st2 = mkState(t, ex, 300.0, 0.0, 4.0, id = 1)
# a second enemy, in two different places, with different velocities
st1.enemies.add EnemyInfo(id: 7, x: decoy1, y: 100.0, heading: 90.0,
speed: 9.0, energy: 100.0, lastSeenTick: t)
st2.enemies.add EnemyInfo(id: 7, x: decoy2, y: 500.0, heading: 270.0,
speed: 1.0, energy: 100.0, lastSeenTick: t)
discard g1.predict(st1, bulletSpeed(1.0))
discard g2.predict(st2, bulletSpeed(1.0))
decoy1 = (decoy1 + 9.0) mod 700.0
decoy2 = (decoy2 - 1.0).mod(700.0)
let r1 = g1.ringFor(1)
let r2 = g2.ringFor(1)
check "scan-only: the ring is byte-identical when every OTHER enemy moves",
r1.dist == r2.dist and r1.bear == r2.bear and r1.tick == r2.tick
# The tracked target is pinned by the rack (targetId), so the ring follows the
# PINNED enemy and not `enemies[0]` either.
block:
var g = initWaveElmGun()
for t in 0..<20:
var st = mkState(t, 300.0 + 3.0 * t.float, 200.0, 0.0, 3.0, id = 1)
st.enemies.add EnemyInfo(id: 9, x: 700.0, y: 100.0, heading: 0.0,
speed: 5.0, energy: 100.0, lastSeenTick: t)
g.targetId = 9
discard g.predict(st, bulletSpeed(1.0))
g.targetId = -1
check "scan-only: with the rack pinning id 9 the ring measures id 9's state",
g.ringFor(9).valid and not g.ringFor(1).valid
# ── (e) the ELM's bias correction converges offline ──────────────────────────
proc testElmConverges() =
## The gun, driven over a straight target (the only regime in which a
## constant-velocity base gets any supervision at all — see
## common_libs/tests/test_waveelm.nim `testSupervision`), with a constant
## systematic bias fed back as CONFIRMED hits. The learned correction must
## converge on it and stay there.
const Speed = 2.0
var g = initWaveElmGun()
var labels = 0
var misses = 0
let (biasX, biasY) = (6.0, -3.0)
for t in 0..<300:
let x = 150.0 + Speed * t.float
let st = mkState(t, x, 300.0, 0.0, Speed)
for p in WavePowers:
let pr = g.predict(st, bulletSpeed(p))
let k = max(1, int(round(g.ringFor(1).flight)))
let ax = 150.0 + Speed * (t + k).float + biasX
let ay = 300.0 + biasY
let res = hypot(pr.x - ax, pr.y - ay)
let hit = res <= BotRadius
if hit: inc labels else: inc misses
g.onResult(FeedbackEvent(prediction: pr, actualX: ax, actualY: ay,
bulletPower: p, fireTick: t, powerBin: waveBinForSpeed(bulletSpeed(p)),
missDistance: res, hit: hit, confidence: pr.confidence))
echo &" offline convergence: {labels} labels, {misses} misses, " &
&"net samples {g.net.samples}, correction ({g.lastDx:.2f}, {g.lastDy:.2f}) " &
&"(true bias ({biasX}, {biasY}))"
check "elm: the ring supervises the net on a straight target (> 80% labels)",
labels.float / (labels + misses).float > 0.8
check &"elm: the correction converges on the {biasX:.0f}/{biasY:.0f} px bias (< 2 px)",
hypot(g.lastDx - biasX, g.lastDy - biasY) < 2.0
check "elm: no soft reset was needed on a clean stream", g.net.resets == 0
check "elm: the net is sane", g.net.isSane()
# ... and it STAYS there: a cold gun is strictly worse on the same tick.
var cold = initWaveElmGun()
let st = mkState(400, 150.0 + Speed * 400.0, 300.0, 0.0, Speed)
let warm = g.predict(st, bulletSpeed(2.0))
let (cx, cy) = ringDecode(g.ringFor(1), st.selfX, st.selfY)
discard cold.predict(st, bulletSpeed(2.0))
let cool = cold.predict(st, bulletSpeed(2.0))
check "elm: the converged gun aims closer to the biased truth than a cold one",
hypot(warm.x - (cx + biasX), warm.y - (cy + biasY)) <
hypot(cool.x - (cx + biasX), cool.y - (cy + biasY))
when isMainModule:
echo "── (c) probe count ──"; testProbeCount()
echo "── (a) interception ──"; testInterception()
echo "── (b) decoding ──"; testDecoding()
echo "── (d) out of range ──"; testNoClaim()
echo "── (f) edge cases ──"; testEdgeCases()
echo "── (g) scan-only ──"; testScanOnly()
echo "── (e) ELM offline ──"; testElmConverges()
if failures > 0:
echo "\n", failures, " of ", checks, " check(s) FAILED"
quit(1)
echo &"\nAll {checks} WaveElm-ring checks passed."
+354
View File
@@ -0,0 +1,354 @@
## Offline tests for the TEMPORAL extensions of the WaveElm gun:
## (A) the lag-window feature map (guns/waveelm.nim, WaveLagK / waveFeatures)
## (B) the RELM recurrent hidden layer (guns/elm.nim, r / hPrev / predictStep)
## covered here, plus the per-enemy / per-episode state reset and the
## train-on-the-stored-activation path.
##
## Everything is offline and bounded: no server, no java, no runBattle, and
## every loop count is a small constant.
##
## Run: nim c -r common_libs/tests/test_waveelm_temporal.nim
import std/[math, strformat, tables]
import gun_harness/gun_interface
import guns/elm
import guns/waveelm
var failures = 0
var checks = 0
proc check(name: string, ok: bool) =
inc checks
if ok: echo "PASS: ", name
else: echo "FAIL: ", name; inc failures
proc fin(x: float): bool =
classify(x) notin {fcNan, fcInf, fcNegInf}
proc allFinite(s: seq[float]): bool =
for v in s:
if not fin(v): return false
true
proc mkState(tick: int, ex, ey, eh, es: float, id = 1,
sx = 100.0, sy = 300.0): WorldState =
WorldState(
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
selfX: sx, selfY: sy, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: 800.0, arenaHeight: 600.0, tick: tick,
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
energy: 100.0, lastSeenTick: tick)])
# ── (A) the lag window ───────────────────────────────────────────────────────
proc testLagWindow() =
check "lag: waveInputDim(2) is the legacy 10", waveInputDim(2) == 10
check "lag: waveInputDim(4) == 10 + 2*(4-2)", waveInputDim(4) == 14
check "lag: waveInputDim(8) == 10 + 2*(8-2)", waveInputDim(8) == 22
check "lag: WaveTrackCap covers the longest window", WaveTrackCap >= WaveLagKMax + 1
check "lag: init clamps the window to [2, WaveLagKMax]",
initWaveElmGun(42, lagK = 1).lagK == 2 and
initWaveElmGun(42, lagK = 99).lagK == WaveLagKMax
block:
# A straight run of scans: one tick apart, +6 px in x each tick. Every
# window slot must hold THAT tick's displacement / 16 px.
var g = initWaveElmGun(42, lagK = 4)
check "lag: the net is as wide as the window", g.net.inputDim == 14
var f: seq[float]
for t in 0..<6:
let st = mkState(t, 300.0 + 6.0 * t.float, 300.0, 0.0, 6.0)
discard g.predict(st, 17.0)
f = g.waveFeatures(st, 6.0, 0.0, 30.0)
check "lag: the feature vector is exactly waveInputDim(4) long", f.len == 14
var ok = true
for k in 0..<4:
if abs(f[4 + 2 * k] - 6.0 / 16.0) > 1e-12: ok = false
if abs(f[5 + 2 * k] - 0.0) > 1e-12: ok = false
check &"lag: all 4 window slots hold their own displacement / 16 (t={6})", ok
check "lag: the staleness/flight slots moved to the end of the window",
abs(f[4 + 2 * 4] - 0.0) < 1e-12 and f[5 + 2 * 4] > 0.0
block:
# The base 8 features must not depend on the window: a lagK=4 gun fed the
# same scans must agree with a legacy lagK=2 gun on slots 0..7.
var g4 = initWaveElmGun(42, lagK = 4)
var g2 = initWaveElmGun(42, lagK = 2)
for t in 0..<5:
let st = mkState(t, 300.0 + 5.0 * t.float, 300.0 + t.float, 12.0, 5.0)
discard g4.predict(st, 17.0)
discard g2.predict(st, 17.0)
let f4 = g4.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
let f2 = g2.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
var same = true
for i in 0..<8:
if abs(f4[i] - f2[i]) > 1e-12: same = false
check "lag: the base features are unchanged by the window (slots 0..7)", same
block:
# Fewer scans than the window: the missing slots must be ZERO, not garbage.
var g = initWaveElmGun(42, lagK = 6)
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
let f = g.waveFeatures(mkState(0, 300.0, 300.0, 0.0, 5.0), 5.0, 0.0, 30.0)
check "lag: a window longer than the scan history reads zeros",
f.len == waveInputDim(6) and
(block:
var ok = true
for i in 0..<f.len:
if not fin(f[i]): ok = false
ok)
block:
# A late scan (gap = 2 ticks) must be normalised PER TICK, or the window
# silently measures the radar cadence instead of the target.
var g = initWaveElmGun(42, lagK = 2)
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
discard g.predict(mkState(2, 312.0, 300.0, 0.0, 6.0), 17.0) # 12 px in 2 ticks
let f = g.waveFeatures(mkState(2, 312.0, 300.0, 0.0, 6.0), 6.0, 0.0, 30.0)
check &"lag: a 2-tick gap is normalised to px/tick (6/16 = {6.0/16.0})",
abs(f[4] - 6.0 / 16.0) < 1e-12
# ── (B) the RELM recurrence ──────────────────────────────────────────────────
proc testRelm() =
block:
# Gain 0 must be EXACTLY the legacy feed-forward net: g = act(W x + b).
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
recurrentGain = 0.0)
check "relm: gain 0 leaves the net non-recurrent", not net.recurrent()
check "relm: gain 0 leaves every r_j at 0",
(block:
var ok = true
for v in net.r:
if v != 0.0: ok = false
ok)
let x = @[0.3, -0.7, 0.11]
var manual = newSeq[float](8)
for h in 0..<8:
var s = net.b[h]
for i in 0..<3: s += net.W[h][i] * x[i]
manual[h] = tanh(s)
check "relm: gain 0 reproduces act(W x + b) exactly", net.hidden(x) == manual
block:
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
recurrentGain = 0.5)
check "relm: gain > 0 makes the net recurrent", net.recurrent()
check "relm: every |r_j| is inside the contraction range [0, ElmRMax]",
(block:
var ok = true
for v in net.r:
if abs(v) > ElmRMax or abs(v) >= 1.0: ok = false
ok)
check "relm: the recurrence is seeded (not all identical gains)",
(block:
var varies = false
for i in 1..<net.r.len:
if net.r[i] != net.r[0]: varies = true
varies)
block:
# predict is READ-ONLY, predictStep ADVANCES the clock exactly once.
var net = init(inputDim = 2, hiddenDim = 6, seed = 7, outputDim = 1,
recurrentGain = 0.6)
let x = @[0.5, -0.2]
# beta starts at ZERO, so an untrained net predicts 0 whatever the state
# is: train it first or this test would be comparing 0.0 to 0.0.
for i in 0..<20:
let v = float(i) / 20.0
discard net.train(@[v, -v], @[2.0 * v])
let p1 = net.predict(x)
let p2 = net.predict(x)
check "relm: predict does not advance the hidden state", p1 == p2
discard net.predictStep(x)
let p3 = net.predict(x)
check "relm: predictStep advances the state (the next prediction differs)",
p1 != p3
block:
# STABILITY: the contraction argument says |h| <= 1 and no NaN, whatever
# the input does. Wild-but-plausible inputs first (20000 steps): nothing may
# blow up at all, not even a soft reset.
var net = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
var sane = true
var bounded = true
for i in 0..<20000:
let m = if i mod 2 == 0: 20.0 else: -20.0
let y = net.predictStep(@[m, sin(float(i) * 0.01) * m])
discard net.train(@[m, float(i mod 7).float], @[y[0]])
if not net.isSane() or not allFinite(y): sane = false
for h in net.hPrev:
if not fin(h) or abs(h) > 1.0: bounded = false
check "relm: 20000 steps of +-20 stay finite and sane", sane
check "relm: |h| never leaves tanh's range [-1, 1] (the clamp holds)", bounded
# The pre-existing RLS guard soft-resets on an ill-conditioned stream; what
# matters is whether the RECURRENCE causes MORE of them than the identical
# feed-forward loop does. Same seed, same inputs, only r_j differs.
var ff = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = 0.0)
for i in 0..<20000:
let m = if i mod 2 == 0: 20.0 else: -20.0
let y = ff.predictStep(@[m, sin(float(i) * 0.01) * m])
discard ff.train(@[m, float(i mod 7).float], @[y[0]])
echo &" soft resets on the same 20000 steps: RELM {net.resets}, " &
&"feed-forward {ff.resets}"
check "relm: the recurrence does not add a single soft reset",
net.resets <= ff.resets
# Absurd inputs (1e3) DO trip the pre-existing RLS blow-up guard, which
# soft-resets and carries on. What must hold is that the RECURRENCE does
# not diverge: the prediction stays finite and the state stays in range.
var net2 = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
var sane2 = true
var bounded2 = true
for i in 0..<20000:
let m = if i mod 2 == 0: 1.0e3 else: -1.0e3
let y = net2.predictStep(@[m, sin(float(i) * 0.01) * m])
discard net2.train(@[m, float(i mod 7).float], @[y[0]])
if not allFinite(y): sane2 = false
for h in net2.hPrev:
if not fin(h) or abs(h) > 1.0: bounded2 = false
check "relm: 20000 steps of +-1e3 stay finite", sane2
check "relm: the hidden state stays bounded even at +-1e3", bounded2
block:
# The RLS must still reject bad samples on the hidden-vector entry point.
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.4)
let g = net.hidden(@[0.5])
check "relm: trainHidden rejects a NaN hidden vector",
not net.trainHidden(@[NaN, 0.5, 0.5, 0.5], @[1.0])
check "relm: trainHidden rejects a NaN target", not net.trainHidden(g, @[NaN])
check "relm: the net survives both rejections", net.isSane() and net.samples == 0
block:
# A poisoned recurrence must be DETECTED, not propagated.
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
net.r[0] = NaN
check "relm: isSane detects a NaN recurrent gain", not net.isSane()
var net2 = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
net2.r[0] = 1.5
check "relm: isSane rejects a gain outside the contraction range",
not net2.isSane()
# ── per-enemy / per-episode state reset ──────────────────────────────────────
proc testStateReset() =
block:
# A new target is a new SEQUENCE: its first activation must be computed
# from h(0) = 0, not from whatever the previous target left behind.
var g = initWaveElmGun(42, lagK = 4, relm = 0.6)
var x = 300.0
for t in 0..<8:
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 1)
discard g.predict(st, 17.0)
x += 5.0
check "reset: the RELM state is non-zero after a run of ticks",
(block:
var live = false
for h in g.net.hPrev:
if h != 0.0: live = true
live)
# Same scan stream, new enemy id -> the first activation must equal the one
# a FRESH net would produce (i.e. the state really was cleared).
var h = initWaveElmGun(42, lagK = 4, relm = 0.6)
x = 300.0
for t in 0..<8:
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 2)
discard h.predict(st, 17.0)
x += 5.0
# The strongest form of the claim: after the id change, gun A (which has
# just been running another target) must produce BYTE-IDENTICAL aim points
# to a fresh gun B that has only ever seen the new target. Any residue of
# the old sequence — node state, learned beta, scan track — would break it.
let st4 = mkState(9, x, 300.0, 0.0, 5.0, id = 4)
var fresh = initWaveElmGun(42, lagK = 4, relm = 0.6)
var same = true
for p in WavePowers:
let a = h.predict(st4, bulletSpeed(p))
let b = fresh.predict(st4, bulletSpeed(p))
if a.x != b.x or a.y != b.y or a.confidence != b.confidence: same = false
check "reset: a new enemy id starts its sequence from h(0) = 0", same
check "reset: the target change was actually seen (tracks differ)",
h.tracks.hasKey(2) and h.tracks.hasKey(4)
block:
# Per-episode reset clears the state but KEEPS what was learned.
var g = initWaveElmGun(42, lagK = 2, relm = 0.5)
var x = 300.0
for t in 0..<30:
let st = mkState(t, x, 300.0, 0.0, 5.0)
let pr = g.predict(st, 17.0)
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 4.0,
actualY: pr.y, bulletPower: 1.0, fireTick: t, powerBin: 0,
hit: true, confidence: pr.confidence))
x += 5.0
let samples = g.net.samples
let learned = g.net.beta[0][0]
g.resetTemporalState()
var cleared = true
for v in g.net.hPrev:
if v != 0.0: cleared = false
check "reset: resetTemporalState zeroes h(t-1)", cleared
check "reset: it keeps the learned beta and the RLS state",
g.net.samples == samples and g.net.beta[0][0] == learned
check "reset: a RELM gun still trains on the stored activation",
samples == g.trainedShots
# ── end to end with everything on ────────────────────────────────────────────
proc testEndToEnd() =
var g = initWaveElmGun(42, lagK = 8, relm = 0.3)
var x = 200.0
var y = 300.0
var finite = true
for t in 0..<120:
let st = mkState(t, x, y, 30.0, 5.0)
for p in WavePowers:
let spd = bulletSpeed(p)
let pr = g.predict(st, spd)
if not (fin(pr.x) and fin(pr.y) and fin(pr.confidence)): finite = false
# resolve immediately, so every trace is trained on its own activation
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 3.0,
actualY: pr.y - 1.0, bulletPower: p, fireTick: t,
powerBin: waveBinForSpeed(spd), hit: true, confidence: pr.confidence))
x = (x + 5.0).clamp(BotRadius, 800.0 - BotRadius)
y = (y + 1.0).clamp(BotRadius, 600.0 - BotRadius)
check "e2e: lagK=8 + RELM 0.3 produces only finite aim points", finite
# A rung trains unless its trace lookup missed or the residual gate rejected it
# as implausible (this target accelerates across the arena, so the ring's
# constant-velocity base is not within 3*BotRadius of the truth every tick).
check &"e2e: every rung is accounted for (trained {g.trainedShots} + rejected " &
&"{g.rejectedShots} + misses {g.missShots} + traceMisses {g.traceMisses})",
g.trainedShots + g.rejectedShots + g.missShots + g.traceMisses == 120 * WaveRungs
check "e2e: the great majority of rungs train", g.trainedShots > (120 * WaveRungs) div 2
check "e2e: the net is still sane", g.net.isSane()
check "e2e: no soft reset was needed", g.net.resets == 0
# Degenerate state with every extension on must still not hang or leak NaN.
var h = initWaveElmGun(42, lagK = 8, relm = 0.9)
let nan = 0.0 / 0.0
var ok = true
for bad in [nan, 1.0 / 0.0, -1.0 / 0.0]:
let st = mkState(3, bad, bad, bad, bad, id = 7)
for p in WavePowers:
let pr = h.predict(st, bulletSpeed(p))
if not fin(pr.x): ok = false
let f = h.waveFeatures(st, bad, bad, bad)
for v in f:
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
check "e2e: NaN/Inf state never escapes with lagK=8 + RELM 0.9", ok
check "e2e: the net survives it", h.net.isSane()
when isMainModule:
echo "── (A) lag window ──"; testLagWindow()
echo "── (B) RELM ──"; testRelm()
echo "── state reset ──"; testStateReset()
echo "── end to end ──"; testEndToEnd()
if failures > 0:
echo "\n", failures, " of ", checks, " check(s) FAILED"
quit(1)
echo &"\nAll {checks} WaveElm-temporal checks passed."
+697
View File
@@ -0,0 +1,697 @@
# CHIMERA — Online Neuro-Symbolic Opponent Policy-Twin with Active Causal Probing and Counterfactual Rollout (Tank Royale 1v1)
Status: design spec (M0). Nothing in this document is implemented yet, and nothing
outside this document is created by the run that produced it. CHIMERA is a plan,
not a description of code.
---
## 1. Summary & Novelty Statement
CHIMERA is an **online neuro-symbolic algorithm** that learns (clones) an opponent's
decision *policy* inside a live Robocode Tank Royale 1v1 match. Its purpose is to
answer a **counterfactual query**: *if I do X next tick, what will the enemy do for
the next 5 ticks?* The bot answers that query by running a **policy twin** — a
small executable model of the enemy's decision function — forward against the
server's physics model, under our candidate action.
The design combines three ingredients that each exist in game-AI literature but
have not, to our knowledge, been combined in Robocode / Tank Royale:
1. **An online DSL-level opponent policy-twin** — the enemy is modeled as a program
in a small domain-specific language of movement/gun/radar kernels, not as a black
box. Kernels are concrete, human-readable and fast (a 50–200 op program runs in
~1–10 µs in native Nim).
2. **Active causal probing** — the bot deliberately chooses probes whose outcome
*separates* competing hypotheses, spending a small score budget to buy
identifiability evidence.
3. **Counterfactual rollout within one match** — the twin is rolled forward 1/5/10
ticks under our candidate plan and used directly to steer behavior (predictive
bullet avoidance, position choice), never off-line.
### Honesty caveats
- This is **domain-first novelty**, not "new to game AI." Every component has
well-known ancestors; we claim the *combination in Robocode/Tank Royale* is new.
- The Robocode wiki has **zero pages** on counterfactual / opponent / imitation
modeling. It is community-edited and may under-report private bots, so "no prior
work" is an inference from public sources, not a proof.
### Related work (and why each falls short for this task)
| Work | What it does | Why it is not CHIMERA |
|---|---|---|
| **TRACE 2025** (arXiv:2503.00761) | Counterfactual probing of a reactive agent, offline, VLM-based | Offline and LLM/VLM-scale; not an in-match 30 ms budget |
| **M2I** (CVPR 2022) | Influencer → reactor decomposition | Multi-agent prediction, not control; no probing |
| **Tang 2020** (RHEA+OM) | Online opponent modeling inside a planning loop | Evolutionary planner, no explicit DSL twin, heavy compute |
| **DOMAC 2022** | Policy-conditioned opponent model | Offline/centralized training, not online 1v1 |
| **L2E 2021** | Learning to exploit | Needs pretraining corpus; exploits but does not identify |
| **OPS-DeMo 2024** | Online opponent-policy switch detection | Detects switch, does not simulate counterfactually |
| **HOP 2024, MBOM 2021** | Opponent modeling in poker/board settings | Discrete turn-based; different observability |
| **Classic Robocode: GuessFactor, Dynamic Clustering, Pattern Matching (MogBot), Play It Forward** | Predict the enemy's *future position* statistically | Position models, not policy twins; no counterfactual "if I do X" |
| **Wave Surfing** | The closest prior counterfactual | Frozen gun model + scalar danger field; not an enemy decision twin |
| **Lu 2022 zero-sum αβ** | Adversarial planning | Position estimate only, no learned policy |
---
## 2. Problem Formalization
**Setting.** Two bots, one arena, server-authoritative. We are bot A; the opponent
is bot B. The match is a sequence of discrete ticks. Each tick we send one intent
(body turn rate, target speed, gun turn rate and/or fire, radar turn rate) and
receive events describing what happened.
### Observable set
From `ScannedBotEvent` the *only* fields visible are:
```
{ scannedByBotId, scannedBotId, energy, x, y, direction, speed }
```
Everything about the enemy's internal command is **hidden**:
| Quantity | Visible? | Source of estimate |
|---|---|---|
| enemy x, y, direction, speed, energy | yes (on scan) | `ScannedBotEvent` |
| enemy turnRate | **no** | inferred from `direction` deltas |
| enemy targetSpeed | **no** | inferred (stateful) from `speed` |
| enemy gun direction, radar direction | **no** | not observable |
| enemy gunHeat | **no** | inferred from fire events |
| enemy fire decision | partial | `HitByBulletEvent` carries `bullet{ownerId,power,x,y,direction}` + damage |
| own x, y, direction, speed, energy, gunHeat | yes | own tick `botState` |
| own bullets | yes | `bulletStates` = **own bullets only** |
The own tick event carries the full own `botState` **including `gunHeat`**. Radar
radius is 1200; a scan arrives only when our own radar beam covers the enemy.
### Enemy intent vector
Define the per-tick enemy **intent** as
```
u_B(t) = ( turnRate_B(t) ∈ [-10,10],
targetSpeed_B(t) ∈ [-8,8],
fire_B(t) ∈ {0} ∪ [0.1, 3.0] )
```
This is the same control vector the API accepts; `turnRate` and `targetSpeed` are
continuous, `fire` is a rounded power (the server exposes no fire rate).
### Counterfactual query
Given the current twin posterior over enemy programs, our candidate plan
`ourPlan[1..k]`, and the believed enemy hidden state, define:
```
rollout(ourPlan, k) -> distribution over (u_B(t+1..t+k), enemy state trajectory)
```
The success metrics attached to a rollout at horizon `k` (twin-predicted enemy
position vs. realized, over held-out ticks) are:
- **ADE** — average displacement error over the horizon, in units.
- **FDE** — final displacement error, in units.
- **Fire-channel Brier score / log-loss** — calibration of the predicted
`P(fire)` per tick.
- **Identification ticks** — ticks until the posterior mass on the true kernel
exceeds threshold (see §12, G4).
---
## 3. Sensor Layer (precondition for everything)
CHIMERA assumes a **dense enemy stream**: at least one scan per tick while
tracking. This already exists as a solved component in `DevControlBot_garage`:
- Radar state machine: **SWEEP** (360° at +45°/tick, full revolution every 8 ticks)
→ **LOCK** (servo onto target bearing **plus a 5° overshoot**).
- The 5° overshoot is the mechanism: the radar *sweeps across* the bearing rather
than parking on it, so a fresh `ScannedBotEvent` arrives every tick.
- Turning by the bare bearing error, or holding at rate 0 inside a deadzone,
**stops the scans**; this is a recorded invariant and must never be reintroduced.
- SWEEP → LOCK requires `enemyCount == 1` and a target seen within
`FreshScanTurns`; LOCK → SWEEP on lost/stale (>10 ticks) or count ≠ 1.
**Dense-stream invariant:** while locked, the scan gap must satisfy `gap ≤ 1` tick.
CHIMERA's intent ledger (§4) consumes this stream; a `gap ≥ 2` tick causes
censoring, not guessing.
**Command-order invariant:** `commandRadar()` must be issued **before** `go()`, so
the radar command travels with this tick's intent. Movement is computed in the same
slot. This ordering is a real bug that is already fixed in the copy source.
---
## 4. Intent Ledger
The ledger converts the observable scan stream into per-tick intent *intervals*
(and, where ambiguous, a **CENSORED** mark). It never guesses.
### 4.1 turnRate inference
From consecutive scans:
```
Δdir = wrap180(dir(t) - dir(t-1))
```
- The physical bound is `|turnRate| ≤ 10 − 0.75·|speed|` (at the observed speed).
This yields the **interval** `[Δdir − ε, Δdir + ε] ∩ [−(10−0.75|v|), +(10−0.75|v|)]`,
with `ε` a small wrap/quantization slack.
- If successive scans are not adjacent ticks (gap), the tick is **CENSORED**.
### 4.2 targetSpeed inference (stateful)
`setTargetSpeed` is continuous; the wire exposes only realized `speed`. The
server's speed update is a sign-aware accelerate/decelerate rule (accel +1,
decel −2 per tick), with the special crossing-zero case. The ledger carries a
**speed-regime memory** and applies the three-case update verbatim:
```
case 1: v_prev == 0 -> v_new = clamp(targetSpeed, -1, +1)
case 2: sign(targetSpeed) == sign(v_prev)-> v_new = v_prev + sign(v_prev) (accelerate, step 1)
case 3: otherwise (crossing zero) -> v_new = v_prev + (1 - v_prev/2)·(-1) (brake, step 2)
```
(the exact server form is `(1 − v/2)·(−1)` applied to the sign-aware update; the
twin's step function must be unit-tested against this truth table, §12 Tier A).
Because the rule is stateful, the realized speed only bounds `targetSpeed`; the
ledger emits the interval of targetSpeeds consistent with `(v_prev, v_new)`.
### 4.3 Fire inference
- `HitByBulletEvent` carries `bullet{ownerId, power, ...}`. If `ownerId == B` and
the damage is consistent with `4·p + 2·(p − 1)` for `p > 1` (else `4·p`), we
record `fire_B(t) ≈ p`.
- Enemy **energy** drop across a tick corroborates a fire even when the bullet
has not yet connected (energy is spent at fire time), subject to cost
`= power`.
- Any residual ambiguity (multi-bullet, collision, wall damage overlapping) marks
the tick **CENSORED**.
### 4.4 Censoring
Ambiguous ticks are **excluded from Hedge updates** (no imputation, no guess).
The ledger exposes a **censoring rate** = censored / total ticks; this is tracked
and reported (§12, G3).
---
## 5. Enemy Hidden-State Tracker
The twin needs a belief over enemy internals that the wire never provides:
- **Estimated gunHeat.** Round starts at heat 3. On a fired shot, heat resets to
`1 + power/5`. Between shots, heat is a deterministic function of ticks elapsed.
Fire is only legal at heat `== 0`; the tracker maintains `gunHeatEstimate` and a
"can fire now" boolean, used by the probe gate (§9) and the twin's fire channel.
- **Enemy-view-of-us.** The enemy can only react to us when *their* radar covers
us. Their radar state is unknown, so the tracker keeps a **scan-age** estimate:
ticks since the enemy could plausibly have last seen us (bounded by radar rate
45°/tick and beam geometry). Kernels that key off "sees me" are only evaluable
when this belief is confident; otherwise the tick is down-weighted.
- **Speed-regime memory.** Persisted across ticks so the stateful speed rule (§4.2)
is invertible and the twin's propagation is exact.
---
## 6. DSL (Twin Program Language)
A twin is a **program** over observable input built from a small kernel library.
Grammar sketch:
```
Program := SensorDecl* Predicate* Action* Compose* ProfileSlot*
Sensor := sample(energy|x|y|direction|speed|scanAge|gunHeatEst|dist|bearing)
Predicate := cmp(Sensor, const) | and/or/not(Predicate) | true
Action := setTargetSpeed(expr) | setTurnRate(expr) | fire(power) | idle
Compose := mix(field (weighted), profile slot, loop counter)
Loop := repeat n | while(Predicate) max n | phase(t) % m
```
### Kernel inventory v0 (null-hypothesis set)
| # | Kernel | Essence |
|---|---|---|
| K1 | `orbit-with-hysteresis` (lock) | hold tangential orbit at a preferred range; hysteresis band prevents flip-flop |
| K2 | `anti-gravity field mix` | sum of repulsive force vectors (walls, bullets, enemy) → turn |
| K3 | `wave-perpendicular evasion` | move perpendicular to the incoming bullet wave |
| K4 | `stop-and-go` | alternate burst/stop; exploits acceleration rules |
| K5 | `corner-run` | run to a corner and bounce |
| K6 | `rammer` | drive straight at us |
| K7 | `RNG walk` (4 RNG classes) | pseudorandom turn/speed under LCG / xorshift / MT / hash-seeded classes |
| K8 | `mirror/shadow` | the **null hypothesis** program — do nothing adaptive; used as a fallback prior |
| K9 | `wall-crawl` | align to a wall, crawl it in segments (sample: Walls) |
| K10 | `static` | stationary posture + dedicated gun-purpose module (sample: TrackFire, Fire) |
Parameter slots per kernel: thresholds, preferred directions, RNG seeds, ranges.
Program size budget: **≤ 200 ops**.
---
## 7. Inference — Hedge Posterior over Kernels
The twin posterior is a weighted mixture over kernels `K1..KN` (N = 10–100),
updated online with **Hedge** (full-information setting — we always observe the
realized intent, when not censored, so EXP3 / partial feedback is unnecessary).
### Loss per tick
- **Δheading squared error** on the turn channel.
- **targetSpeed interval log-likelihood** (interval observation → log of the
probability the kernel's predicted speed lies in the ledger interval).
- **Fire Bernoulli log-loss** on `fire_B ∈ {0, p}`.
`Δloss` is scaled to ~0.01–0.1 range so that the learning rate `η` is stable.
### Update
```
w_i(t+1) = w_i(t) · exp(-η · loss_i(t)) · (1 - 1/τ) + a·(m_i - w_i(t))
```
with exponential forgetting `τ = 200` ticks default (range 50–500) and a
**Fixed-Share** term `m_i` that guarantees a mass floor `a > 0`, so a wrong-but-
resurrected kernel can recover. Update is **O(N) per tick** (sub-millisecond at
N ≤ 100).
### Prediction
The twin predicts with the **weighted mixture**, never the argmax — the marginal
distribution is what the counterfactual query needs, and it also smooths the
early-match phase where no kernel dominates.
### Round carry-over (M5.5 amendment)
The enemy bot is the **same program across the rounds of a match**, so the
posterior (and the kernel memories' internal state) is **carried across rounds**
instead of reset to uniform each round: identification compounds across rounds.
**"Round carry-over adopted at M5.5 (user-delegated decision): identification
compounds across rounds; ablation flag kept."** The ablation flag
`-d:chimeraFreshRound` restores the per-round uniform reset (G6 arm).
RNG-derived kernel-memory state is re-sampled at each round start, because a
per-round sampled parameter (e.g. Corners' `randomize()` start corner) must not
be carried.
---
## 8. Twin Rollout (Counterfactual Core)
`simulate(ourPlan[k], k=1..5)` performs:
1. **Physics step mirror.** A pure-Nim reimplementation of the server's 13-step
update order (double precision, `eps = 1e-6`), covering: max speed ±8; accel +1,
decel −2; sign-aware crossing-zero formula; max body turn `10 − 0.75·|v|`; gun 20;
radar 45; bullet speed `20 − 3·power`; damage `4p + 2(p−1)` if `p>1`; heat
`1 + p/5`; round-start heat 3; fire only at heat 0; bot-bot collision stops both
(0.6 dmg each) unless the mover is moving away; wall damage `|v|/2 − 1`.
**This mirror is unit-tested against server math truth tables (§12 Tier A)** —
a mismatch silently poisons every downstream claim.
2. **Hidden-state propagation.** §5 tracker advanced in lockstep.
3. **Output.** A distribution over the enemy's next intents per tick plus a
**fire-time estimate** (`P(fire)` per future tick).
**Use case — predictive bullet avoidance:** before committing a movement, roll the
twin forward under our candidate plan; if the twin's fire estimate spikes on ticks
where our plan sits on the enemy's gun line, the plan is penalized. This is the
concrete payoff that distinguishes CHIMERA's counterfactual from Wave Surfing's
frozen danger field.
---
## 9. Probe Scheduler
**Budget.** 1 probe per 20–30 ticks.
**Survival gating** (no probe when any holds):
- our energy is low;
- their `gunHeat` is (near) zero **and** they are aimed at us;
- we are wall-pinned.
**Camouflage.** Probe actions must be plausible as ordinary movement noise, so a
kernel-based opponent cannot detect the probe and switch policy.
**Probe set v2 (M5.5).** The candidate set covers **six probe types**: four
movement probes (sudden stop, reversal, speed modulation, direction flip), a
**GUN probe** (a low-power shot at the enemy — the probe *is* the shot, aimed to
trigger dodging/hit-response branches such as Fire's reverse-on-hit; never
issued with low energy, a hot/unaligned gun, or an enemy positioned to punish)
and a **DISTANCE probe** (approach/retreat burst — a strong target-speed step
that changes our bearing/range trajectory and triggers RamFire/Corners-like
geometry branches). Entropy-drop selection is extended to all six types.
**Information gain.** Rank candidate probes by **estimated posterior entropy
reduction** — expected drop of `H(posterior)` from the predicted separation of
hypotheses (§12, G2 uses the same notion offline).
**Decision 2 (codified):** probes **MAY cost score** (Option A). The probe budget
is a tunable **cost ledger** for the future: we buy identifiability with a small
amount of match score, and the scheduler never probes when survival gating fires.
---
## 10. Residual Head & Fusion
The DSL is a compact approximation; a **residual head** absorbs systematic
mispredictions:
- **Linear residual** (default) — per-kernel affine correction of `(turnRate,
targetSpeed)`.
- **32-unit GRU residual** (upgrade path) — online SGD at millisecond scale.
**Fusion.** The final prediction is a convex combination of the DSL-mixture
prediction and the residual model, weight tuned by realized prediction loss.
**Failure fallback (hard requirement).** If the realized-vs-predicted loss
degrades beyond thresholds, CHIMERA ramps its influence to **zero** and the bot
degrades to DevControlBot behavior. The learning system is therefore **never worse
than the copy it started from** (§12, G7).
---
## 11. Garage Plan (explanatory only — nothing created yet)
Working name: **ChimeraBot** (Decision 1 — kept; see Resolved decisions §1).
```
ChimeraBot_garage/ # follows the ROOT template, NOT DevControlBot_garage's
├── src/
│ ├── chimerabot.nim # bot type + entry point (isMainModule)
│ ├── chimerabot.json # bot metadata (name field = ChimeraBot)
│ ├── chimerabot.nimble # task: runBot
│ ├── chimerabot.sh # BotLauncher wrapper
│ ├── config.nim
│ └── chimerabot/
│ ├── twin/ # physics mirror + rollout
│ ├── ledger/ # intent ledger + hidden-state tracker
│ ├── probes/ # probe scheduler
│ └── dsl/ # kernel library + Hedge
├── tests/ # config.nims --path:"../../common_libs"
├── out/ # compiled binaries
└── AGENTS.md
```
**EXACT COPY clause.** Phase 0 behavior is **identical to DevControlBot**:
- movement is a port-independent copy of `tfil.nim`, **no runtime dependency on
`common_libs/`** — do not add one, do not edit the original;
- radar reuses the same 5°-overshoot lock design, all radar logic in **one module**;
- firing: the source copy already carries the **ELM gun** (`ELM/elm_gun.nim`,
`elm_gun_weights.txt`, firing via `computeGun`/`setFire`) — **live fire exists
from M1**; "Phase 0 never fires" is withdrawn (see Resolved decisions §3).
- identity rename only: file names, bot name, `.json` name field, wrapper script
name. The nimble task **stays `runBot`** (tasks are per-nimble, so no conflict
with other garages; only the script name changes).
**House rules carried over:** `SERVER_URL` / `SERVER_SECRET` are read by the API's
`start()`, never by bot code; `.env` is optional and never committed; every file
under a garage is committed unless gitignored; **no version bumps or tags by
agents**; `DevControlBot_garage/PLAN.md` is untouched and **no `PLAN.md` is created
for the new garage**; throwaway output goes to `/tmp` only.
---
## 12. Test Plan — the centerpiece
Three tiers, each with explicit PASS conditions, followed by the Falsification
Matrix that answers the core requirement: *if the bot is not learning, prove
whether the idea was wrong or the implementation.*
### Tier A — Unit (pure Nim, no Java)
| Area | Test | PASS condition |
|---|---|---|
| Physics mirror | speed-step truth table incl. crossing-zero; accel +1 / decel −2; clamp ±8 | exact match to server math |
| Physics mirror | turn-rate cap identities `10 − 0.75·|v|`; gun 20; radar 45; bullet speed `20−3p`; damage; heat `1+p/5` | exact |
| Intent ledger | synthetic streams with known `(turnRate, targetSpeed)` | exact turn-rate recovery; targetSpeed interval **contains** truth and width ≤ bound |
| Hedge | normalization, `η` bounds, forgetting revives a correct kernel | `Σw = 1`; revived weight rises |
| Hedge | Fixed-Share mass floor | `w_i ≥ a·m_i` for all i |
| DSL | determinism (same seed+input ⇒ same output); size budget | byte-identical reruns; ≤200 ops |
| Probes | gate truth table (survival states ⇒ allow/deny) | matches spec |
| Entropy | posterior entropy computation | exact closed-form value |
### Tier B — Integration (`common_libs/test_framework`, guard-first skip)
Guard first (`TR_SERVER_JAR` / `TR_BATTLE_RUNNER` unset ⇒ skip, exit 0), then:
- Battles vs. the **official Nim sample bots** as the **primary ground-truth suite**
(see "Benchmark opponents" below). The six repo adversaries are optional extra
diversity only — **NON-LOAD-BEARING, not ground truth**.
- **At least 3 scripted ARCHETYPE opponents written for this garage**, implementing
DSL kernels **1:1** — supplementary **scripted ground truth**, secondary to the
official suite: each emits its kernel's behavior exactly, so a correct posterior
must converge to it.
- **Twin telemetry recorded to `/tmp`** (garage rule: throwaway output lives only
in `/tmp`).
- `tests/config.nims`: `--path:"../../common_libs"`; one `test<concern>.nim` per
concern; a `test` task in the `.nimble`.
**Harness server port (user decision, recorded M2).** The harness always starts
its server on a **random free port**, never the default 7654: `SERVER_URL =
ws://127.0.0.1:<random-port>`. This also avoids the localhost→`::1` connect hang.
### Benchmark opponents — primary ground-truth suite
**Local binaries.** The official Nim sample bots are unpacked locally at
`/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7/` — a
**binary-only** distribution: 13 ELF bots + 1 team, each a folder holding
`<Bot>`, `<Bot>.sh`, `<Bot>.cmd`, `<Bot>.json`. Each bot is launched through its
`.sh` wrapper with `SERVER_URL` (+`SERVER_SECRET`) set; the API's `start()` reads
those env vars itself, not bot code.
**Ground-truth sources.** github `SirStone/robocode_tankroyale_botapi`,
`sample_bots/` — **not** `robocode-dev/tank-royale` (no Nim samples; 404s).
Available: `Corners, Crazy, Fire, MyFirstBot, MyFirstDroid, MyFirstLeader,
MyFirstTeam, PaintingBot, RamFire, SpinBot, Target, TrackFire, VelociBot, Walls`.
No SittingDuck / Walli in the Nim set.
**Verified kernel mapping (behavior table)** — ground truth for DSL identification:
| Bot | Behavior (from source) | Randomness |
|---|---|---|
| Crazy | forward 40000 + 180° turn zigzag; gun idle, radar rides gun; fire(1) on scan; reverses on wall/ram | **none** |
| SpinBot | turn 10000 + maxSpeed 5 + forward 10000 (circling); fire(3) on scan; small turn on ram | none |
| RamFire | 5°/tick idle turn; on scan faces target, forward(dist+5), rescan(); fire scaled by enemy energy on ram | none |
| Corners | run to a corner, turnGunLeft(90)/forward, sweep gun ±3, stop + smartFire(dist) on scan; start corner picked stochastically | **uses std/random + randomize() + rand(3)** |
| Walls | align to nearest wall, forward moveAmount, turnLeft 90 per segment, gun inward, fire(2) on scan, rescan() when peeking | none |
| TrackFire | sits still, turnGunRight(10); on scan align gun, fire ≤3 when aligned & heat 0, rescan() | none |
| Fire | sits still, turnGunRight(5); fire(3) if dist<50 & energy>50 else 1; dodge by reversing on hit-by-bullet | none |
**Kernel-inventory additions (DSL v0).** The table adds two kernels to §6:
**WALL-CRAWL** (Walls) — wall-aligned segment crawling; and **STATIC**
(TrackFire / Fire) — stationary posture + a dedicated gun-purpose module. Corners
is the **stochastic-origin case**: `randomize()` in `main` varies the start corner
per match, so the RNG machinery (K7) must handle **per-round sampled params**
(re-sample each round). Crazy/SpinBot are orbit/turn-set variants confirming
existing kernels.
**Version caveat / M3 kickoff checkpoint.** The local binaries tag **1.0.7**;
GitHub `main` sources may differ from that tag. Verify tag↔code correspondence
(`.json` provenance credits author Davide Cappellini) **before benchmarking** — an
M3 gate (§13).
**Repo adversaries (SittingDuck, OscillatorBot, ConstantSpinner, PatternMover,
RandomMover, WaveSurfer).** Optional extra diversity only — **NON-LOAD-BEARING,
untrusted for ground truth** (created, never properly tested). Only official Nim
samples carry ground-truth weight.
### Tier C — Mathematical falsification goals (G1..G7)
**G1 — ORACLE CONVERGENCE.** Feed the posterior the *oracle* intent stream
generated by kernel K (offline, exact, no sensor error). The Hedge weight on K
must reach **≥ 0.9** within `T*` ticks (`T*` stated per kernel). *If G1 fails, the
inference-layer implementation is buggy; the idea is exonerated.*
**G2 — IDENTIFIABILITY.** For every kernel pair `(Ki, Kj)` there exists a probe
sequence of length `≤ L` inducing enemy-intent distributions separated by
`≥ δ` (KL or total variation), computed by exhaustive short-sequence simulation
over the DSL. *If G2 fails, the DSL/library design is insufficient — an idea-level
failure, not a code bug.*
**G3 — CENSORING BUDGET.** Censored ticks ≤ **15%** across the benchmark suite.
*Higher ⇒ observability problem (data path), not induction.*
**G4 — LIVE IDENTIFICATION.** Against the official sample-bot primary suite, a
set of **behavior-diverse targets** reach posterior ≥ 0.8 within **300 ticks**
(10 s @ TPS 30) in pinned-initial-position battles.
**Metric unification (M5.5, binding).** `idTicks` is defined ONE way everywhere:
per round, the **round-relative** tick at which `max_kernel posterior > 0.8`
first holds — the posterior has committed to *some* kernel. Correctness of that
kernel (does the argmax equal the expected kernel?) is reported as a separate
diagnostic column, never absorbed into the metric. Per opponent the bench reports
**median**, **p90** and **id-fraction** (% of rounds identified) over ALL rounds
in the protocol. The old M3.5 "best round / total ticks" aggregation is retired.
**G4 pass condition: median ≤ 300 ticks AND id-fraction ≥ 80% over ≥ 3 full
8×5 runs** (24 rounds/opponent), not a single run. Primary identification set
(**8 most behavior-diverse** from the verified table): **{Crazy, SpinBot,
RamFire, Corners, Walls, TrackFire, Fire, MyFirstBot or VelociBot}**. **Corners is
the mandatory stochastic case** (its `randomize()` start-corner must be handled as
per-round sampled params). Excluded: PaintingBot (debug-painting only),
MyFirstTeam/Droid/Leader (team bots — no 1v1), `Target` (likely a static target
— verify at M3). *Failure with G1–G3 green ⇒ the idea is wrong: single-stream
induction is insufficient.*
**G5' — INTERVENTIONAL COUNTERFACTUALS.** Measured on the ticks that FOLLOW an
executed probe (the *interventional* scenario set — the only ticks where our own
action was chosen to separate the hypotheses), the twin mixture's 5-tick
enemy-reaction prediction must beat the persistence baseline (constant-velocity
carry) on **≥ 70%** of probe-following scenarios. The bar is interventional on
purpose: the twin's claim is "*if I do X, the enemy does Y*", and that claim is
only testable where X was actually chosen to separate the hypotheses. A **≥ 90%**
agreement is reported as a separate **stretch** row, never as the gate.
**G5' v2 protocol (M5.5, binding).** Results are reported separately for
**(a) the MOVING subset {Crazy, SpinBot, VelociBot, Walls}** — where
constant-velocity persistence is *not* optimal by construction — and **(b) the
full suite**. Per opponent: twin vs persistence interventional 5-tick ADE after an
executed probe, plus reaction-direction agreement. **Bar: twin ≥ persistence on
≥ 70% of MOVING-subset scenarios.** The **STATIC subset {RamFire, Corners,
TrackFire, Fire}** is reported with a **saturation analysis** (one line per static
opponent: why twin ≈ persistence by construction).
**Observational sanity floor.** Independently of the interventional bar, the
twin's 5-tick ADE must stay **≤ 2× the persistence ADE per opponent** on the full
observational set — a regression guard, not a superiority claim.
**M4 falsification (recorded verbatim).** The M4 observational eval (twin 5-tick
rollout vs persistence over ALL recorded origin ticks) had twin ADE ≤ persistence
ADE on only **20.1%** of scenarios, against the original **≥ 90%** bar — a plain
falsification of G5 *as originally stated*. Diagnosis: the observational protocol
is persistence-favourable. Over a short 5-tick horizon a constant-velocity carry
tracks the realized enemy path closely, while the twin pays for a mixture that
must re-commit after each regime change; and on an observation-only run our own
movement is itself a reaction to the enemy, so the "counterfactual" is not
intervened on at all. The result indicts the *observation-only measurement*, not
the interventional claim, which M5 tests directly.
**M3.5-vs-G6 aggregation discrepancy (recorded verbatim, M5.5).** M3.5 reported
"8/8 ≤ 300 ticks" using a **different aggregation** than G6's per-round medians:
per-opponent total/best-round ticks versus per-round medians. Under the G6
per-round aggregation the same bots show Corners 445, Crazy 2439, and an
identification fraction of only 13–40% of rounds. The "8/8" claim therefore did
not survive re-aggregation; M5.5 unifies the metric so the discrepancy cannot
recur.
**G6 — ABLATION LADDER.** `full CHIMERA ≥ (−probe) ≥ (−residual) ≥ fallback` in
identification speed; probes must cut **median** identification ticks by **≥ 20%**
(median over ≥ 3 full runs, to survive the G4 spawn-variance), under the unified
idTicks metric and measured on the **MOVING subset** as the primary read. M5.5
runs the four-way probe × carry-over arms (`full`, `−probe`, `+freshRound`,
`−probe+freshRound`); the `−residual` and `fallback` rungs arrive at M6.
*Failure (still null after probe v2) ⇒ a component-value claim is wrong.*
**G7 — NO-REGRESSION FLOOR.** ChimeraBot ≥ exact-copy DevControlBot behavior in
head-to-head and against the primary benchmark suite (official sample bots) as
well as the optional repo adversaries as extra diversity (win rate / score
bounds), i.e. learning never makes it worse when the twin is uncertain.
### Falsification Matrix
| Goal | Boundary | Failure proves |
|---|---|---|
| G1 | offline oracle | **implementation bug** (inference layer) |
| G2 | DSL/none | **library design insufficient** (idea-level) |
| G3 | data path | **observability problem** |
| G4 | go/no-go | **idea invalid** (single-stream induction insufficient) |
| G5' | interventional usefulness | **twin not decision-useful under its own actions** (idea-level) |
| G5' (M6.5 horizon sweep) | observational, horizons 1–50 | **twin loses to persistence at every long horizon** (idea-level) |
| Twinsim reconstruction (M6.5) | replay path == oracle path | **implementation bug** if they diverged — they do not (byte-equal): the M6.5 hypothesis is falsified |
| Fusion mixer (M6.5) | oracle-data predictor race | **fusion correctness bug** (command vs realized space; power-as-probability) when the residual wins on clean oracle data |
| G6 | components | **component value claims wrong** |
| G7 | safety floor | **fallback/fusion correctness bug** |
The matrix is the answer to *"if the bot is not learning, can we prove whether the
idea was wrong or the implementation?"*: G1/G3/G7 failures indict the build;
G2/G4/G5/G6 failures indict the idea or its components.
### Final status M0–M6 (recorded at M6, §13 milestone close-out)
Each goal: PASS / FAIL / UNPROVEN with the recorded numbers and the caveat.
Source artifacts: `benchmarks/g1_oracle_table.md`, `benchmarks/m5_5_g4.md`,
`benchmarks/m5_5_g5p.md`, `benchmarks/m5_5_g6.md`, `benchmarks/m6_g7.md`.
| Goal | Verdict | Recorded numbers + caveat |
|---|---:|---|
| G1 | **PASS** | 12/12 kernels identify ≤ 300 ticks; finalPost ≥ 0.90 (`g1_oracle_table.md`). In practice most identify in ≤ 161 ticks. |
| G2 | **UNPROVEN** | No dedicated separated-identification probe-sequence bench was executed; kernel-pair separability is not directly scored (only the G1 single-stream path is). |
| G3 | **PASS** | Censoring rate 0.00% across the G4/G6 sample-bot suite; well under the 15% budget. |
| G4 | **PASS** | 8/8 primary targets, every pooled median ≤ 300 ticks (5 of 8 median = 1) and id-fraction 100% over 3×5 runs (`m5_5_g4.md`). Caveat: argmax-vs-expected correctness is partial (Corners 60%, Crazy 67%, VelociBot 27%) on statics — the posterior commits to *a* static kernel, not always the right one. |
| G5' | **FAIL** | Interventional bar not met: MOVING-subset twinWin 32.8% vs ≥ 70% (FULL 23.4%); STATIC subset saturates (persistence ≈ optimal at v=0), so the twin can only match/lose there (`m5_5_g5p.md`). Caveat: this is the interventional G5' v2 protocol; per-opponent SpinBot shows 94.5% twinWin, so it is opponent-dependent, not uniformly dead. |
| G6 | **FAIL** (probe rung) / **PASS** (carry-over) | Probes give no robust ≥ 20% median id-cut on the MOVING subset — the cut sign flips and swings −550%…+83% across four 4-arm invocations (`m5_5_g6.md`). Probe component value claim is not supported. Carry-over is large and stable (reset→on gain 54–97%) → PASS. |
| G7 | **PASS** (safety floor, stated bar) | Head-to-head full-vs-inert win-rate **54.0%** over 10×5 rounds (bar ≥ 50%), survival 40/39, score margin +1621 (`m6_g7.md`). No-regression: full ≥ inert win-rate on **all 8** suite opponents. **Caveat (plain):** full's per-opponent *score margin* is smaller than inert's on 5 of 8 opponents (Corners, Crazy, RamFire, TrackFire, Walls) with equal win-rates, and full-minus-probes reached 100% on VelociBot where both full and inert got 80% — so CHIMERA is not worse by win-rate but is **not measurably better** against this suite; the fallback/fusion never degrades survival. |
### Final status — M6.5 additions (close-out)
| Item | Verdict | Recorded numbers + caveat |
|---|---:|---|
| Twinsim state reconstruction | **FALSIFIED (as a hypothesis)** | `tests/test_replay_oracle.nim`: oracle-generated telemetry replayed through `twinsim.replay()` yields the per-tick posterior + kernel-memory state **byte-equal** to the oracle path for all 12 kernels; on live telemetry (Crazy round 1) the replay posterior equals the recorded live posterior for 1396/1396 ticks (entropy and argmax identical). The state reconstruction was already faithful — no twinsim change was needed. |
| Fusion mixer | **FIXED (implementation bugs)** | The residual head dominated because (1) the fusion scored the mixture's raw turn *command* against the server-capped *realized* turn (mean turn error 3.38 raw vs 0.09 capped — the residual absorbed the `limitTurnRate` gap) and (2) fire was fed as a weighted *power* (≈1.0 wherever a high-power kernel had mass) into a Bernoulli log-loss whose channel then dominated the fusion. Fixed in `observer.nim` (cap the mixture turn; use a binarized fire probability) and `fusion.nim` (`residualTrajectory` caps the base before adding the correction). |
| Fusion smoke (ORBIT_BALLIST oracle) | **FALSIFIED (residual not marginal)** | Fusion weights before fix: mixture 0.022 / residual 0.943 / persistence 0.036. After fix: mixture **0.117** / residual **0.804** / persistence 0.079. The fix lifted the mixture but the linear residual STILL wins on clean oracle data — §10's "residual absorbs systematic mispredictions" holds only because the residual is a second full predictor, not a correction. Recorded as a falsification row. |
| Horizon sweep G5' | **FALSIFIED-ON-SUITE** | MOVING subset {Crazy, SpinBot, VelociBot, Walls}, horizons {1,5,10,25,50}, 3 full 8x5 runs (`benchmarks/m6_5_horizonsweep.md`). Origin-weighted twin/persistence ADE ratio: **4.43 / 3.44 / 2.56 / 1.49 / 1.03** at h=1/5/10/25/50 — >= 1.0 at every horizon >= 10. Per opponent at h=50: Crazy 0.98, SpinBot 0.90, VelociBot 0.77 (below 1) but Walls 1.50. The "validated-conditionally" rule (>= 3/4 moving opponents below 1 at >= 2 long horizons) fails: only SpinBot clears 2 long horizons (SpinBot 3, Crazy 1, VelociBot 1, Walls 0). Caveat: the failure narrows with horizon (h=1 ratio 4.43 -> h=50 ratio 1.03), so the twin's dynamics are not futile — they are simply not yet better than a constant-velocity carry on this suite. |
**Plain-language verdict (M6.5 close-out).** The inference layer stays sound
(G1/G3/G4 green) and the safety floor holds (G7). The M6.5 close-out killed the
last hope that the M5.5 G5' failure was a *reconstruction* artefact: `twinsim`
`replay()` reproduces the oracle per-tick state byte-equal for all 12 kernels and
matches the live recorded posterior on real telemetry, so the twin loses to
persistence because of what it predicts, not because it is fed the wrong state.
Two genuine fusion implementation bugs were found and fixed along the way (the
mixture's turn command was scored against the server-capped realized turn, and
fire was fed as a power rather than a probability), but the decisive horizon
sweep is unambiguous: on the MOVING subset, over 3 full 8x5 runs, the
twin/persistence ADE ratio is 4.43 / 3.44 / 2.56 / 1.49 / **1.03** at horizons
1/5/10/25/50 — never below 1.0 at any horizon >= 10. Only at h=50 do three of the
four moving opponents individually flip below 1 (Crazy 0.98, SpinBot 0.90,
VelociBot 0.77); Walls (1.50) and the origin-weighted suite keep the ratio above
1. The residual head still beats the mixture even on a clean ORBIT_BALLIST oracle
stream (weight 0.80 vs 0.12 after the fixes), so the residual is not a marginal
correction as §10 assumes. The honest read: CHIMERA's counterfactual rollout is
**falsified on this suite**; the parts that make the idea special (interventional
prediction, probing) are unproven or falsified at their stated bars, and the only
green results are the inference layer and the no-regression floor it did not need
to earn.
**Plain-language verdict (M6).** The inference layer is sound (G1/G3/G4 green: the
posterior identifies every sample-bot kernel fast, at zero censor cost, and the
future-handicap fallback keeps the bot no worse than its copy by win rate). Two
idea-level claims did **not** hold up: the interventional counterfactual
(G5') and the probe value (G6). The M6 residual/fusion/influence layer is green
on its safety floor (G7 PASS) but shows no measurable *benefit* yet — the sample
suite is too easy (full, inert and no-probe all win ~100% of rounds, differing
only by score margin), so the honest read is: CHIMERA has not been shown to make
this bot better, and the parts that make the idea special (interventional
prediction, probing) remain unproven or falsified at their stated bars.
---
## 13. Milestones
- **M0 — Spec** (this document).
- **M1 — Garage bootstrap + exact copy + Tier A units green.**
- **M2 — Intent ledger + oracle tests (G1).**
- **M3 — DSL + Hedge + identification benchmark (G2, G4).** Two M3 gates:
(a) verify the local sample-bots **1.0.7** tag against GitHub `main` sources;
(b) verify `tps=-1` behaviour against the installed server (Resolved decisions
§2). Nothing is benchmarked until both are done.
- **M4 — Twin rollout + counterfactual metrics (G5).**
- **M5 — Probes (G3, G6).**
- **M6 — Fusion + residual + fallback (G7).** Implemented: `residual.nim`
(online linear head; 32-GRU behind `-d:chimeraGRU`, not enabled),
`fusion.nim` (hedge over mixture/residual/persistence predictors),
`influence.nim` (loss-ramped 0..1 overlay on the TFIL command, never inside a
bullet dodge). Ablations `-d:chimeraNoFusion` / `-d:chimeraInert`. Tier A
tests (`test_residual/fusion/influence`) green; G7 head-to-head + suite PASS
on the stated bar (margins caveat above).
### Resolved decisions
| # | Question → resolution |
|---|---|
| 1 | **Name: keep `ChimeraBot`** (user decision — no rename). |
| 2 | **Benchmarks run at MAX TURN RATE / FPS.** `tps = -1` is **valid**: the installed `robocode-tankroyale-server.jar` CLI (`--tps`) defines range **`[-1..999]`** where **`-1` = maximum TPS** and `0` = paused; `applyVisualDelay` sleeps only when `tps > 0`, so `-1` runs unthrottled (see M3 gate (b)). Use `tps=-1` for CI/benchmarks. |
| 3 | **Live fire IS in scope.** Fact-check: the M1 exact-copy bootstrap **already includes the ELM gun** (`ELM/elm_gun.nim`, `elm_gun_weights.txt`; fires via `computeGun` / `setFire`) — **live fire exists from M1**, so the `DevControlBot_garage/AGENTS.md` "never fires" claim is stale vs. code. CHIMERA upgrades: **fire-timing prediction via the twin at M4**; the ELM gun remains as a **fusion baseline component (do not remove)**. |
| 4 | **Probe cost: keep default 1 probe per 20–30 ticks (nominal 25),** survival-gated; tune only on G6/G7 evidence. |
| 5 | **`T*` per kernel (G1): provisional uniform `T* = 300` ticks** until the kernel library freezes; any failure is re-estimated with diagnosis before an idea-level verdict. |
+9 -3
View File
@@ -399,14 +399,14 @@ tank.
| variable | default | what it does |
|---|---|---|
| `TR_RACK_<GUN>` | `PATTERN=both`, all other 15 guns `off` | membership: `both` \| `1v1` \| `melee` \| `off` |
| `TR_RACK_<GUN>` | `PATTERN=both`, all other 17 guns `off` | membership: `both` \| `1v1` \| `melee` \| `off` |
| `GUN_RACK_DISABLE` | empty | comma-separated gun **ids** to remove entirely (older mechanism; the gun never even spawns virtual bullets) |
| `GUN_STATS_PATH` | `/tmp/gun_stats.jsonl` | where the per-round per-gun stats are written |
| `GUN_SHOTLOG_PATH` | `/tmp/shot_log.jsonl` | where the per-shot JSONL is written |
`<GUN>` names (ids 0-15, `selector.nim:52`):
`<GUN>` names (ids 0-17, `selector.nim:RackGunNames`):
`HEADON LINEAR TSETLIN CIRCULAR GUESSFACTOR PATTERN WALLBOUNCE ACCEL STOPSHOT
DISPLACE AVGLEAD DECAYGF KNN TMSELECT TMPATTERN TMHORIZON`.
DISPLACE AVGLEAD DECAYGF KNN TMSELECT TMPATTERN TMHORIZON LEADGAIN KNOWLEDGE`.
Shipped default membership (`selector.nim:DefaultRackMembership`):
@@ -420,6 +420,8 @@ Shipped default membership (`selector.nim:DefaultRackMembership`):
| **PATTERN** | **both** | TMSELECT | off |
| WALLBOUNCE | off | TMPATTERN | off |
| ACCEL | off | TMHORIZON | off |
| STOPSHOT | off | LEADGAIN | off |
| KNOWLEDGE | off | | |
`TR_RACK_<GUN>` accepts aliases: `both`/`any`/empty → both;
`1v1`/`single`/`lock` → 1v1; `melee`/`multi` → melee;
@@ -429,6 +431,10 @@ to `both`** (`selector.nim:parseRackMembership`).
The `1v1`/`melee` split is driven by **server truth**, `getEnemyCount()`:
`== 1` → 1v1 rack, `> 1` → melee rack (`virtual_bullets.rackMode`).
| variable | default | what it does |
|---|---|---|
| `TR_KNOWLEDGE_MEM` | empty (memory only) | path of the learned table `KNOWLEDGE` (id 17) loads at the first round boundary and re-saves (atomically, after a prune) at every boundary. Unset = nothing is ever written to disk. |
**Empty-set fallback:** if every gun is filtered out for a mode, the *selector*
falls back to the **full rack** so it can never end up with no gun
(`admittedGuns`, `virtual_bullets.nim`). Note this fallback is on *selection*;
+14 -2
View File
@@ -48,8 +48,20 @@ is smooth but limited to 4°/tick at top speed.
### Coordinate system
North = 0°, clockwise. `directionTo` in `utils.nim` returns a bearing in
`[0, 360)`. `bearingTo` returns a signed relative bearing in `(-180, 180]`.
East = 0°, North = 90°, positive angles increase counter-clockwise (Y increases
upward, so the arena's bottom edge is Y = 0). `directionTo` in `utils.nim`
returns a bearing in `[0, 360)`. `bearingTo` returns a signed relative bearing in
`(-180, 180]`.
> **Note — the SDK's own doc comments are wrong here.** `bot.nim:183/187/191`,
> `utils.nim:68` and the examples at `utils.nim:159-161` and `~197` all claim
> "0 = North, 90 = East". The **implementation is authoritative**, not the
> comments: `utils.nim:162` computes
> `normalizeAbsoluteAngle(180.0 * arctan2(toY - fromY, toX - fromX) / PI)`, i.e.
> plain `arctan2(dy, dx)`, and `bot.nim:178` puts the arena's bottom edge at
> `Y = 0`. Running the SDK's own `directionTo` (robocode_tankroyale_botapi
> 1.0.7) returns `0.0` for East and `90.0` for North, and `bearingTo` agrees.
> Do not "fix" this section back to the commented convention.
---
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More