64 Commits
Author SHA1 Message Date
SirStone 70b8ad0d49 chore: remove nim command (moved to Home Repo skill nim-mcp-tools) 2026-11-15 12:00:29 +01:00
SirStone 5b48ac980c ChimeraBot_garage: M7.5 — virtual-gun tournament, Dodger-v2, discriminating bench 2026-10-07 09:16:54 +02:00
SirStone 4c98333a3c docs: M7.5 virtual-gun tournament + Dodger-v2 rows 2026-10-07 08:57:51 +02:00
SirStone 8bf7152512 ChimeraBot_garage: M7 twin gun — flight-horizon aiming, spread-based power, aim-bias corrector, Dodger archetype 2026-10-07 08:44:37 +02:00
SirStone 53effb408c docs: G8 twin-gun results (offline PASS, live floor) + M7 close-out 2026-10-07 08:44:14 +02:00
SirStone 43b9ae912f docs: G8 twin-gun goal (flight-horizon aiming) + matrix 2026-10-07 08:35:40 +02:00
SirStone 051c4e733b ChimeraBot_garage: CHIMERA debug overlay (-d:chimeraDebug, observation-only) 2026-10-07 08:20:23 +02:00
SirStone f5c6967414 ChimeraBot_garage: G2 identifiability certificate + Walls diagnosis 2026-10-07 03:03:43 +02:00
SirStone 35fc0478c0 docs: G2 identifiability executed + dual-reading horizon verdict 2026-10-07 03:03:40 +02:00
SirStone 25badce948 ChimeraBot_garage: M6.5 — twinsim state-reconstruction fix + horizon sweep + final artifacts 2026-10-07 02:54:35 +02:00
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
SirStone 7632aaba06 docs: record the aim-capture blind spot - aim_fire only logs shots that passed setFire
j178 flagged it and it is real: the capture cannot show WHY a shot did not
happen (gun still hot, turret not aligned). A missing aim_fire record is
ambiguous, not a refusal. Docs only, no code change. Adds the TR_CAPTURE_AIM
row + a 'Known limitations' note to docs/env_reference.md section 8, and a
two-line pointer next to the knob in .env.example.
2026-09-27 18:53:59 +02:00
SirStone 208f4a9092 j177: aim capture - log what the model BELIEVED, not what it did
j176 could not attribute the 11.9 deg aim error at 450+ px: the corpus had
no gun id and no bot-side belief, so staleness was an inverse (unidentifiable)
problem and a good gun was indistinguishable from a bad one. Both are cheap to
log and impossible to recover later.

New default-off knob TR_CAPTURE_AIM (presence-only). It appends TWO record
kinds to the EXISTING TR_RECORD_WORLDSTATE file:

  aim_scan - one per onScannedBot, written BEFORE the tracker update, so it is
    the pre-update belief by construction: tick, raw scanned values
    (ex,ey,eh,es,ee), our own state (sx,sy,sh,ss), the gun in force, the
    PREVIOUS belief (bx,by,bh,bs,blst), the scan parity age = tick - blst,
    and the radar-lock context (rlock, rdir, lbear, boff).
  aim_fire - one per real shot: gun, power, the aim angle handed to setFire,
    the turret angle and the signed turret error, gunHeat, the predicted
    intercept (ax,ay) and implied TOF, and the exact WorldState the predictor
    consumed (ex,ey,eh,es,ee,sx,sy) with the tick it came from (lst).

Row builders live in a new pure module src/aim_capture.nim - no bot API, no
env reads - so the offline guard test and the live bot go through the SAME
builders and a field the test proves present is a field the bot writes.
Per-tick world-state rows also gain a `gun` id. offline_range.nim skips
aim_* lines (they carry no `ex`), so the annotations are inert to the replay.
No aim model changed.

Knob registered in env_report.nim (context field, effective-value emit) and
knownEnvNames(); documented in .env.example. Defaults OFF, diagnostic only,
never live-tested.

Verification (no battle, no Java, no server, no GUI):
  - default parity: per-gun shots/hits over 20026 ticks of
    tr_drussgt_vs_modularbot.jsonl byte-for-byte identical to the golden
    generated from the PRE-CHANGE tree (git archive 55e92bc); the golden was
    regenerated from that pre-change tree and re-diffed, so it is not
    self-referential. Boot [env] block of the pre- and post-change binaries is
    identical except pid/cmdline/build line and the new knob's own line.
  - test_aim_capture: ALL PASS (every aim_scan/aim_fire key present, plus the
    annotation-inertness replay).
  - guards: test_tfil_commit_env 159/0, test_env_report 25/0,
    test_tfil_ring_weights 24/0, test_vbullet_draw 30/0.
  - .env.example round-trip (env_report via the j172 harness): 210 effective
    values + 70 [x]/[modules] lines, 0 diffs, 0 dropped keys, 0 warnings.
  - clean `git archive HEAD` + nim c -d:release: [SuccessX].
2026-09-27 18:44:24 +02:00
pi 55e92bc5e0 docs: the range-vs-approach ceiling - melee unavailable vs DrussGT, the 16 deg is a lead-model number, pre-multiply premise dead 2026-09-27 15:05:14 +02:00
351 changed files with 78700 additions and 428 deletions
-175
View File
@@ -1,175 +0,0 @@
---
name: nim-mcp-tools
description: 'Use for Nim symbol navigation, diagnostics, and type resolution. MANDATORY: Use specialized MCP tools (nimFindSymbols, nimFindReferences, nimListSymbols, nimCheckFile, nimCheckProject, nimFindTypeDefinition) first; fall back to grep only on error or user confirmation.'
---
# Nim MCP Tools
## Core Mandate
AI agents MUST prefer specialized MCP tools over general-purpose instruments (grep, shell commands, `read_file` with manual parsing) for all Nim symbol-related and Nim diagnostics tasks. This is critical for:
1. **Token Efficiency**: MCP tools return structured, relevant data, avoiding large file reads or noisy grep outputs.
2. **Precision**: These tools understand Nim semantics (scopes, imports, overloads) which string-based search cannot.
## Activation Rule
If the user asks to find, rename, remove, audit, update, standardize naming, or fix issues/project of a Nim symbol or its usages, this skill MUST be used first and the workflow must start with the Nim MCP symbol tools.
If the user asks to check a single Nim file for errors, warnings, hints, diagnostics, issues, problems, or compiler feedback, this skill MUST be used first and the workflow must start with `nimCheckFile`.
If the user asks to check a Nim project for errors, warnings, hints, diagnostics, issues, problems, compiler feedback, or to "fix" it, this skill MUST be used first and the workflow must start with `nimCheckProject`.
If the user asks to determine where a symbol comes from, what type it is, what its fields are (including private ones), or resolve a symbol's type definition, this skill MUST be used first and the workflow must start with `nimFindTypeDefinition`.
This applies to requests phrased as:
- "find all usages/references of `Foo`"
- "remove all definitions of and references to `Foo`"
- "rename `Foo` everywhere"
- "standardize naming for `Foo`"
- "fix casing for all variables"
- "where is `Foo` defined?"
- "list the symbols in this Nim file/module"
- "check this file/module for errors"
- "show diagnostics for `foo.nim`"
- "check this project/workspace/repository/package for errors"
- "fix issues in this project"
- "fix the repo"
- "find Nim diagnostics in the current codebase"
- "show warnings and hints for this repo"
- "scan the current module tree for Nim issues"
- "what is the type of this symbol?"
- "what module/package does this type come from?"
- "what fields does this type have?"
- "is this a type alias or a concrete type?"
- "where is this type defined?"
Treat user wording such as **project**, **workspace**, **repository**, **repo**, **package**, **codebase**, **checkout**, and **module tree** as referring to the current Nim project context when they are asking for project-wide diagnostics.
Treat user wording such as **file**, **module** (when a concrete Nim file is identified), **source file**, and explicit `*.nim` paths as referring to single-file diagnostics when they are asking for diagnostics for one file.
Do **not** pair `nimFindSymbols`, `nimCheckFile`, or `nimCheckProject` with `grep`, `ripgrep`, or shell search "just to double-check". If the task is about a Nim symbol or Nim diagnostics, MCP tools own the search unless they have already failed.
## User Terminology vs MCP `kind`
Users may ask for symbol categories using looser or non-strict terminology. AI agents MUST map that wording to the exact Nim MCP `kind` values before filtering results from `nimListSymbols(...)` or `nimFindSymbols(...)`.
The MCP server returns Nim-oriented kind names derived from nimsuggest symbol kinds with the leading `sk` removed, such as `Const`, `EnumField`, `Field`, `Iterator`, `Converter`, `Let`, `Macro`, `Method`, `Proc`, `Template`, `Type`, `Var`, and `Func`.
Use these terminology mappings when interpreting user requests:
- **function** / **functions**: usually match `Func` and `Proc`
- **pure function** / **pure functions**: match `Func`
- **callable** / **routine**: may include `Func`, `Proc`, `Method`, `Iterator`, `Converter`, `Macro`, and `Template`
- **class** / **classes**: match `Type`
- **variable** / **variables**: match `Var` and `Let`
- **property** / **properties**: match `Field`
- **enum member** / **enum members**: match `EnumField`
- **constant** / **constants**: match `Const`
## When to Use
- **Finding References**: To rename a symbol, update a signature, or find usages.
- **Symbol Discovery**: To find where a symbol is defined by name.
- **Type Resolution**: To determine where a local symbol comes from (which module), what its type is, and what fields it has (including private ones).
- **Naming Standardization**: To fix casing or follow style guides across the project.
- **Fixing Project Issues**: To iteratively find and resolve all diagnostics in the project.
- **File Analysis**: To get an overview of all symbols in a file.
- **File Diagnostics**: To check one specific Nim file for errors, warnings, and hints.
- **Project Diagnostics**: To check the current Nim project for errors, warnings, and hints.
- **Debugging Type Mismatches**: When a diagnostic reveals a type mismatch, use `nimFindTypeDefinition` on both sides.
- **Code Generation / Refactoring**: Before generating code that interacts with a type, find its definition.
## Workflows
### 1. Find All References or Usages of a Symbol Name
Do NOT grep for the name.
1. Call `nimFindSymbols(query: "SymbolName")` to get exact `path`, `line`, and `column`.
2. For each relevant result, call `nimFindReferences(path, line, column)`.
3. Aggregate the results.
### 2. List All Symbols in a File
Do NOT read the whole file to find definitions.
1. Call `nimListSymbols(path: "path/to/file.nim")`.
2. If the user asked for a symbol category, filter by the MCP `kind` values.
3. Use the returned list to navigate or analyze the file structure.
### 3. Find Definitions
1. Call `nimFindSymbols(query: "query")`.
### 4. Resolve Type / Determine Origin of a Symbol
1. Call `nimFindTypeDefinition(path, line, column)` with the cursor positioned on the symbol of interest.
2. The result contains the definition `path`, `line`, `column`, `name`, `type`, and `kind`.
3. If the user needs to see the full definition, read the source at the returned path/line.
### 5. Debug Type Mismatch (Check + Type Definition)
1. Call `nimCheckFile(path)` to get the diagnostic with the exact error location.
2. For the reported location, call `nimFindTypeDefinition(path, line, column)` on the involved symbols.
3. Resolve the mismatch with the correct type or conversion.
### 6. Explore Object Structure (List Symbols + Type Definition)
1. Call `nimFindSymbols(query: "TypeName")` to locate the type definition.
2. Call `nimFindTypeDefinition(path, line, column)` on the type name to confirm the definition location.
3. Read the source at the definition location to enumerate all fields.
### 7. Check a Single Nim File for Diagnostics
1. Call `nimCheckFile(path: "path/to/file.nim")`.
2. Treat the result as the answer unless the user explicitly asked for broader validation.
3. Use the returned diagnostics to report errors, warnings, and hints for that file.
### 8. Check the Current Nim Project for Diagnostics
1. Call `nimCheckProject()`.
2. Use the returned diagnostics to report errors, warnings, and hints for the current Nim project context.
### 9. Standardize Naming
1. Iterate through the project files one by one.
2. For each file, call `nimListSymbols(path: "path/to/file.nim")`.
3. For each symbol found, call `nimFindReferences(path, line, column)`.
4. Standardize the definition and all identified reference sites to `camelCase`.
5. After a file has been processed, call `nimCheckFile(path: "path/to/file.nim")` to verify.
### 10. Fix Project Issues
1. Call `nimCheckProject()` to find all diagnostics in the project.
2. Analyze the diagnostics and resolve the identified issues.
3. Repeat steps 1 and 2 until `nimCheckProject()` returns no more issues.
4. **Limit**: If issues remain after 3 iterations, stop and prompt the user.
5. **Post-Fix Step**: Ask the user if they would like to check for naming consistency.
## Fallback Policy
1. **On Error**: If an MCP tool fails due to a technical error, fall back to `grep_search` or other general-purpose tools. State clearly that the MCP tool failed.
2. **On Empty Results**: If an MCP tool returns no results, do NOT automatically fall back to grep. Prompt the user first.
3. **Availability**: If MCP tools are unavailable, use general-purpose tools but inform the user.
## Critical Constraints
- **NO GREP BY DEFAULT**: Never use `grep`, `ripgrep`, or `grep_search` to find Nim symbols or references unless the MCP tools have explicitly errored out.
- **PROMPT ON EMPTY**: If MCP tools return nothing, ask the user before falling back to grep.
- **NO MANUAL PARSING**: Do not read large Nim files just to extract symbol locations; use `nimListSymbols` instead.
- **NO DIY FILE CHECKS**: Do not substitute manual inspection when `nimCheckFile` can return structured diagnostics.
- **NO DIY PROJECT CHECKS**: Do not substitute shelling out to ad-hoc Nim commands when `nimCheckProject` can return structured project diagnostics.
- **TOKEN CONSERVATION**: Minimize turns and context by using the most precise tool available.
## Anti-Patterns
- Calling `nimFindSymbols("Foo")` and then running `rg "Foo"` anyway.
- Using `rg` for "find all usages" when `nimFindReferences` is available.
- Reading multiple Nim files to manually enumerate definitions that `nimListSymbols` can return directly.
- Reading a Nim file to manually search for a type definition when `nimFindTypeDefinition` can resolve it precisely.
- Grepping for `type Foo* =` instead of using `nimFindTypeDefinition` or `nimFindSymbols`.
- Running `nimCheckProject()` when the user asked to check one specific Nim file.
- Manually reading or building a single Nim file first when `nimCheckFile` can return structured diagnostics.
- Running a manual project build or grep-based log scan first when `nimCheckProject` is available.
+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
+46
View File
@@ -0,0 +1,46 @@
# 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.
Debug overlay: run server with `--debug-mode` and bot with `./ChimeraBot.sh -d:chimeraDebug`.
## CHIMERA modules (M3.5 + M4)
`src/ChimeraBot/chimera/` holds the CHIMERA libraries —
`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).
+91
View File
@@ -0,0 +1,91 @@
# M6.5 G2 - kernel identifiability certificate
Source: `chimera/identifiability.nim` over the 12 registered v0.2 kernels (66 unordered pairs). Probe alphabet: the seven spec §9 probe types (noop, stop, reverse, speedmod, flip, distance, gun); canonical start set of 8 fixed scenarios; sequences searched to Lmax=6 by exhaustive depth-first enumeration. Separation is the total variation between the two kernels' per-tick joint `(turnRate,targetSpeed,fire)` intent distributions (discretized 1 deg / 1 unit / 0.1 firepower over the start set), averaged over the sequence; delta = 0.300 (spec silent, fixed here). Deterministic: fixed seed/order, byte-stable across runs (`tests/test_identifiability.nim`).
## Summary
| metric | value |
|---|---:|
| pairs examined | 66 |
| identifiable | 66 (100.0%) |
| UNIDENTIFIABLE | 0 |
| max L_ij needed | 1 |
| probe sequences searched | 117649 per pair (worst case) |
**UNIDENTIFIABLE pairs: none** — every kernel pair separates within Lmax.
## Per-pair certificate
| Ki | Kj | L_ij | separation | best probe prefix |
|---|---|---:|---:|---|
| ORBIT_LOCK | ORBIT_BALLIST | 1 | 1.000 | `noop` |
| ORBIT_LOCK | STOP_AND_GO | 1 | 1.000 | `noop` |
| ORBIT_LOCK | ZIGZAG | 1 | 1.000 | `noop` |
| ORBIT_LOCK | RAMMER | 1 | 1.000 | `noop` |
| ORBIT_LOCK | CORNER_RUN | 1 | 1.000 | `stop` |
| ORBIT_LOCK | WALLCRAWL | 1 | 1.000 | `stop` |
| ORBIT_LOCK | STATIC | 1 | 1.000 | `noop` |
| ORBIT_LOCK | STATIC_CORNER | 1 | 1.000 | `stop` |
| ORBIT_LOCK | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| ORBIT_LOCK | RANDOM_WALK_B | 1 | 1.000 | `stop` |
| ORBIT_LOCK | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | STOP_AND_GO | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | ZIGZAG | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RAMMER | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | CORNER_RUN | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | WALLCRAWL | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | STATIC | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | STATIC_CORNER | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| ORBIT_BALLIST | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| STOP_AND_GO | ZIGZAG | 1 | 1.000 | `noop` |
| STOP_AND_GO | RAMMER | 1 | 1.000 | `noop` |
| STOP_AND_GO | CORNER_RUN | 1 | 1.000 | `noop` |
| STOP_AND_GO | WALLCRAWL | 1 | 1.000 | `noop` |
| STOP_AND_GO | STATIC | 1 | 1.000 | `noop` |
| STOP_AND_GO | STATIC_CORNER | 1 | 1.000 | `noop` |
| STOP_AND_GO | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| STOP_AND_GO | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| STOP_AND_GO | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| ZIGZAG | RAMMER | 1 | 1.000 | `stop` |
| ZIGZAG | CORNER_RUN | 1 | 1.000 | `noop` |
| ZIGZAG | WALLCRAWL | 1 | 1.000 | `noop` |
| ZIGZAG | STATIC | 1 | 1.000 | `noop` |
| ZIGZAG | STATIC_CORNER | 1 | 1.000 | `noop` |
| ZIGZAG | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| ZIGZAG | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| ZIGZAG | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| RAMMER | CORNER_RUN | 1 | 1.000 | `noop` |
| RAMMER | WALLCRAWL | 1 | 1.000 | `noop` |
| RAMMER | STATIC | 1 | 1.000 | `noop` |
| RAMMER | STATIC_CORNER | 1 | 1.000 | `noop` |
| RAMMER | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| RAMMER | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| RAMMER | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| CORNER_RUN | WALLCRAWL | 1 | 1.000 | `distance` |
| CORNER_RUN | STATIC | 1 | 1.000 | `noop` |
| CORNER_RUN | STATIC_CORNER | 1 | 1.000 | `stop` |
| CORNER_RUN | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| CORNER_RUN | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| CORNER_RUN | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| WALLCRAWL | STATIC | 1 | 1.000 | `noop` |
| WALLCRAWL | STATIC_CORNER | 1 | 1.000 | `stop` |
| WALLCRAWL | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| WALLCRAWL | RANDOM_WALK_B | 1 | 1.000 | `stop` |
| WALLCRAWL | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| STATIC | STATIC_CORNER | 1 | 1.000 | `noop` |
| STATIC | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| STATIC | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| STATIC | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| STATIC_CORNER | RANDOM_WALK_A | 1 | 1.000 | `noop` |
| STATIC_CORNER | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| STATIC_CORNER | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| RANDOM_WALK_A | RANDOM_WALK_B | 1 | 1.000 | `noop` |
| RANDOM_WALK_A | RANDOM_WALK_C | 1 | 1.000 | `noop` |
| RANDOM_WALK_B | RANDOM_WALK_C | 1 | 1.000 | `noop` |
## Walls diagnosis (why twin/persistence >= 1.0 there)
Walls is the one MOVING opponent where the twin never beats a constant-velocity carry at any long horizon (twin/persistence 15.9 / 6.5 / 3.9 / 2.2 / **1.50** at h=1/5/10/25/50, `m6_5_horizonsweep.md`), and the sweep's own evidence explains it: over the archived M6.5 telemetry, 89.2% of Walls' 9356 scanned intent ticks carry a turn interval of ~0 deg (dead straight) and the remaining turns are saturated 90 deg corners (|turn| ~ 10 for most of them). Walls therefore moves in long straight wall-parallel segments between predictable 90 deg turns, and on a straight segment persistence IS near-optimal: constant velocity reproduces the realized path almost exactly, while the kernel mixture must (a) pay for re-committing after every regime change and (b) hit the exact corner tick. Missing that one turn tick injects a lateral error that persists for the whole following segment, which is why the twin's advantage only appears once the horizon is long enough for the turn to have been predicted and the error to amortize — and even at h=50 it is not enough to go below 1.0. The failure is persistence being strong on piecewise-straight motion, not a reconstruction or state bug (twinsim replay == oracle, byte-equal).
@@ -0,0 +1,65 @@
# M6.5 horizon sweep - twin vs persistence vs residual
Source: `/tmp/chimera_g6_on` (120 round files; 4 MOVING opponents). Horizons [1, 5, 10, 25, 50], ADE averaged over all scanned origins with >= 50 future ticks. Predictors: **twin** (kernel mixture), **persistence** (constant velocity), **residual** (mixture + online linear residual head).
## Per-opponent curves (ADE units, ratio = twin/persistence)
| opponent | horizon | origins | twin ADE | pers ADE | resid ADE | twin/pers | twinWin% |
|---|---:|---:|---:|---:|---:|---:|---:|
| Corners | 1 | 3224 | 0.757 | 0.055 | 0.570 | 13.815 | 2.0 |
| Corners | 5 | 3224 | 3.198 | 0.617 | 2.633 | 5.183 | 5.1 |
| Corners | 10 | 3224 | 6.949 | 2.296 | 6.242 | 3.027 | 8.8 |
| Corners | 25 | 3224 | 20.774 | 12.742 | 21.873 | 1.630 | 18.5 |
| Corners | 50 | 3224 | 48.492 | 40.554 | 55.928 | 1.196 | 25.1 |
| Crazy | 1 | 13786 | 2.613 | 0.623 | 0.997 | 4.192 | 14.1 |
| Crazy | 5 | 13786 | 9.664 | 2.863 | 4.699 | 3.375 | 14.5 |
| Crazy | 10 | 13786 | 20.676 | 8.234 | 12.307 | 2.511 | 19.6 |
| Crazy | 25 | 13786 | 59.287 | 41.281 | 49.445 | 1.436 | 37.6 |
| Crazy | 50 | 13786 | 118.345 | 120.728 | 125.943 | 0.980 | 55.8 |
| Fire | 1 | 4501 | 1.032 | 0.127 | 0.670 | 8.150 | 4.6 |
| Fire | 5 | 4501 | 3.233 | 1.302 | 2.923 | 2.484 | 14.1 |
| Fire | 10 | 4501 | 6.101 | 4.514 | 6.610 | 1.351 | 21.5 |
| Fire | 25 | 4501 | 14.642 | 19.974 | 20.571 | 0.733 | 36.6 |
| Fire | 50 | 4501 | 24.414 | 47.173 | 44.086 | 0.518 | 48.8 |
| RamFire | 1 | 2959 | 1.341 | 0.117 | 0.834 | 11.456 | 4.3 |
| RamFire | 5 | 2959 | 5.116 | 1.128 | 3.921 | 4.536 | 11.3 |
| RamFire | 10 | 2959 | 11.166 | 3.954 | 9.431 | 2.824 | 18.0 |
| RamFire | 25 | 2959 | 32.759 | 20.484 | 33.082 | 1.599 | 32.6 |
| RamFire | 50 | 2959 | 70.715 | 63.782 | 82.805 | 1.109 | 47.0 |
| SpinBot | 1 | 9812 | 0.545 | 0.557 | 0.579 | 0.979 | 95.7 |
| SpinBot | 5 | 9812 | 1.684 | 1.820 | 1.862 | 0.925 | 95.7 |
| SpinBot | 10 | 9812 | 3.046 | 3.564 | 3.542 | 0.855 | 96.1 |
| SpinBot | 25 | 9812 | 6.477 | 8.401 | 8.374 | 0.771 | 94.8 |
| SpinBot | 50 | 9812 | 11.386 | 12.609 | 13.611 | 0.903 | 84.9 |
| TrackFire | 1 | 2337 | 0.045 | 0.000 | 0.140 | inf | 0.0 |
| TrackFire | 5 | 2337 | 0.285 | 0.000 | 0.633 | inf | 0.0 |
| TrackFire | 10 | 2337 | 0.728 | 0.000 | 1.141 | inf | 0.0 |
| TrackFire | 25 | 2337 | 1.819 | 0.000 | 2.762 | inf | 0.0 |
| TrackFire | 50 | 2337 | 2.857 | 0.000 | 5.601 | inf | 0.0 |
| VelociBot | 1 | 6768 | 3.135 | 0.332 | 0.835 | 9.454 | 7.9 |
| VelociBot | 5 | 6768 | 9.880 | 1.823 | 3.577 | 5.420 | 9.1 |
| VelociBot | 10 | 6768 | 18.698 | 5.664 | 8.785 | 3.301 | 15.9 |
| VelociBot | 25 | 6768 | 42.583 | 30.214 | 32.866 | 1.409 | 36.5 |
| VelociBot | 50 | 6768 | 70.855 | 91.558 | 82.617 | 0.774 | 63.1 |
| Walls | 1 | 8606 | 1.553 | 0.098 | 0.428 | 15.911 | 2.3 |
| Walls | 5 | 8606 | 5.731 | 0.885 | 2.203 | 6.474 | 6.6 |
| Walls | 10 | 8606 | 12.533 | 3.197 | 6.203 | 3.921 | 11.5 |
| Walls | 25 | 8606 | 39.727 | 18.058 | 28.549 | 2.200 | 25.3 |
| Walls | 50 | 8606 | 93.296 | 62.078 | 91.258 | 1.503 | 37.9 |
## MOVING-subset roll-up
| horizon | twin ADE | pers ADE | resid ADE | twin/pers |
|---:|---:|---:|---:|---:|
| 1 | 1.949 | 0.440 | 0.738 | 4.431 |
| 5 | 6.824 | 1.983 | 3.239 | 3.441 |
| 10 | 14.096 | 5.500 | 8.141 | 2.563 |
| 25 | 38.771 | 25.953 | 31.611 | 1.494 |
| 50 | 77.637 | 75.490 | 82.478 | 1.028 |
## Verdict
- Horizons >= 10 with twin/persistence < 1.0 per moving opponent: Crazy:1, SpinBot:3, VelociBot:1, Walls:0.
- MOVING-subset roll-up twin/persistence: h10 2.563, h25 1.494, h50 1.028.
- Rule: **validated-conditionally** if twin/persistence < 1.0 on >= 3/4 moving opponents at >= 2 horizons >= 10; **falsified-on-suite** if the subset roll-up ratio is >= 1.0 at ALL horizons >= 10.
**Verdict: idea-falsified-on-suite.**
+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).
+24
View File
@@ -0,0 +1,24 @@
# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)
Replayed archived trajectories (`/tmp/chimera_g4_run`) + a synthesized Dodger-v2; hit = bullet passes within 20. units of the realized enemy position on its flight. Aim slew/cadence abstracted. Generated by `tests/bench_g8.nim`.
| opponent | twin % | ELM % | head-on % | vgun % | shots |
|---|---:|---:|---:|---:|---:|
| Corners | 49.3 | 59.6 | 52.2 | 57.2 | 339 |
| Crazy | 50.3 | 31.5 | 15.0 | 50.3 | 1042 |
| Fire | 50.7 | 41.4 | 45.9 | 50.7 | 440 |
| RamFire | 90.5 | 92.7 | 89.9 | 90.5 | 328 |
| SpinBot | 88.3 | 20.1 | 20.1 | 88.3 | 715 |
| TrackFire | 84.2 | 87.3 | 87.3 | 84.2 | 221 |
| VelociBot | 38.7 | 23.3 | 28.4 | 38.7 | 786 |
| Walls | 43.8 | 22.1 | 1.8 | 43.8 | 825 |
| Dodger | 82.7 | 46.4 | 10.9 | 82.7 | 220 |
**G8.5 offline bar: vgun >= max(twin, ELM-base, head-on) on >= 6/9 opponents AND vgun >= ELM-base on all movers (Crazy, SpinBot, VelociBot, Walls, Dodger).** Result: vgun >= best single gun on 6/9; vgun >= ELM-base on 5/5 movers. **Verdict: PASS.**
## Method / caveats
* `VGUN` = `chimera/virtual_guns.nim`: per-tick virtual bullets for {TWIN, ELM, HEAD-ON}, a per-shot hit-rate EMA (tau=100) plus a damage-weighted accumulator with tau=200 exponential forgetting, argmax fired under 0.1 hysteresis. Classic Robocode Virtual Guns pattern (https://robowiki.net/wiki/Virtual_Guns).
* `TWIN` = `chimera/aimer.nim`: iterated flight time `h = dist/(20-3*power)`, horizon-bucketed predictor Hedge (mixture/residual/persistence), trained ONLINE per record (one aimer, score-then-aim each sampled tick), spread-selected power.
* `ELM` = the ELM gun's **base** geometric intercept from the observed velocity (the learned correction is gated and small, and the online ELM state cannot be replayed offline). This is a proxy for the full ELM gun — a documented deviation.
* The synthesized Dodger is Dodger-v2 (`tests/archetypes/Dodger`): wave-based perpendicular strafe, centre-pull, seeded reversals. It fires a wave every 12 ticks; a real battle adds shooter motion. Live results (`m7_5_g8_live.md`) are the reality check.
@@ -0,0 +1,21 @@
# G8.5 live bench (M7.5 virtual-gun tournament)
Four arms from the SAME tree: inert (`-d:chimeraInert`), elm (`-d:chimeraNoTwinGun`), twin (`-d:chimeraNoVguns`), vgun (default). 5 rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`.
| opponent | elm W% | elm margin | twin W% | twin margin | vgun W% | vgun margin | inert W% | inert margin |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| Corners | 100.0 | 2488.0 | 100.0 | 2376.0 | 100.0 | 2469.0 | 100.0 | 2493.0 |
| Crazy | 100.0 | 2016.0 | 100.0 | 1935.0 | 100.0 | 2025.0 | 100.0 | 1683.0 |
| Fire | 100.0 | 2593.0 | 100.0 | 2526.0 | 100.0 | 2561.0 | 100.0 | 2564.0 |
| RamFire | 100.0 | 2186.0 | 100.0 | 2460.0 | 100.0 | 2413.0 | 100.0 | 2520.0 |
| SpinBot | 100.0 | 1924.0 | 100.0 | 1060.0 | 100.0 | 2001.0 | 100.0 | 1560.0 |
| TrackFire | 100.0 | 2305.0 | 100.0 | 2371.0 | 100.0 | 2299.0 | 100.0 | 2216.0 |
| VelociBot | 100.0 | 2065.0 | 100.0 | 1962.0 | 100.0 | 1378.0 | 100.0 | 1315.0 |
| Walls | 100.0 | 1459.0 | 100.0 | 1651.0 | 100.0 | 1565.0 | 100.0 | 1934.0 |
| Dodger | 100.0 | 1757.0 | 100.0 | 1949.0 | 100.0 | 1954.0 | 80.0 | 515.0 |
**Totals: inert 97.8% (m 16800.0) elm 100.0% (m 18793.0) twin 100.0% (m 18290.0) vgun 100.0% (m 18665.0) **
**Discrimination test (Dodger-v2 row).** Margins: inert 515.0 elm 1757.0 twin 1949.0 vgun 1954.0 spread 1439.0. The arms DIFFER materially against the upgraded Dodger.
**G7 no-regression (vgun >= inert win-rate on every opponent): PASS.**
+25
View File
@@ -0,0 +1,25 @@
# G8 offline hit-rate bench (M7, twin gun)
Replayed archived trajectories (`/tmp/chimera_g4_run`) + a synthesized Dodger; hit = bullet passes within 20. units of the realized enemy position. Aim slew/cadence abstracted. Generated by `tests/bench_g8.nim`.
| opponent | twin % | ELM % | head-on % | shots |
|---|---:|---:|---:|---:|
| Corners | 49.3 | 59.6 | 52.2 | 339 |
| Crazy | 50.3 | 31.5 | 15.0 | 1042 |
| Fire | 50.7 | 41.4 | 45.9 | 440 |
| RamFire | 90.5 | 92.7 | 89.9 | 328 |
| SpinBot | 88.3 | 20.1 | 20.1 | 715 |
| TrackFire | 84.2 | 87.3 | 87.3 | 221 |
| VelociBot | 38.7 | 23.3 | 28.4 | 786 |
| Walls | 43.8 | 22.1 | 1.8 | 825 |
| Dodger | 85.5 | 11.4 | 72.7 | 220 |
**G8 offline bar: twin >= ELM on >= 6/9 opponents AND twin >= head-on on the movers.** Result: twin >= ELM on 6/9; twin >= head-on on 5/5 movers. **Verdict: PASS.**
## Method / caveats
* `TWIN` = `chimera/aimer.nim`: iterated flight time
`h = dist/(20-3*power)`, horizon-bucketed predictor Hedge (mixture/residual/persistence), trained ONLINE per record (one aimer, score-then-aim each sampled tick), spread-selected power.
* `ELM` = the ELM gun's **base** geometric intercept from the observed velocity (the learned correction is gated and small, and the online ELM state cannot be replayed offline). This is a proxy for the full ELM gun — a documented deviation.
* Power monotonicity: `selectPowerFromSpreads` returns the largest power whose required spread fits the enemy-silhouette tolerance `2*atan2(18, dist)`; the choice is non-increasing in spread (`test_aimer.nim`, aimer 4).
* The synthesized Dodger fires a wave every 12 ticks; a real battle would add shooter motion. Live results (`m7_g8_live.md`) are the reality check.
@@ -0,0 +1,19 @@
# G8 live bench (M7 twin gun)
Three arms from the SAME tree: inert (`-d:chimeraInert`), elm (`-d:chimeraNoTwinGun`), twin (default). 5 rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`.
| opponent | elm W% | elm margin | twin W% | twin margin | inert W% | inert margin |
|---|---:|---:|---:|---:|---:|---:|
| Corners | 100.0 | 2538.0 | 100.0 | 2354.0 | 100.0 | 2477.0 |
| Crazy | 100.0 | 1779.0 | 100.0 | 2240.0 | 100.0 | 1746.0 |
| Fire | 100.0 | 2571.0 | 100.0 | 2494.0 | 100.0 | 2588.0 |
| RamFire | 100.0 | 2549.0 | 100.0 | 2545.0 | 100.0 | 2665.0 |
| SpinBot | 100.0 | 2085.0 | 100.0 | 1635.0 | 100.0 | 1086.0 |
| TrackFire | 100.0 | 2334.0 | 100.0 | 2337.0 | 100.0 | 2371.0 |
| VelociBot | 100.0 | 2100.0 | 100.0 | 1842.0 | 100.0 | 2141.0 |
| Walls | 100.0 | 1895.0 | 100.0 | 1788.0 | 100.0 | 1697.0 |
| Dodger | 100.0 | 2665.0 | 100.0 | 2662.0 | 100.0 | 2653.0 |
**Totals:** elm 100.0% (margin 20516.0), twin 100.0% (margin 19897.0), inert 100.0% (margin 19424.0).
**G7 no-regression (twin >= inert win-rate on every opponent): 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"
}
+492
View File
@@ -0,0 +1,492 @@
## 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
import ChimeraBot/chimera/aimer
import ChimeraBot/chimera/virtual_guns
when defined(chimeraDebug):
import ChimeraBot/chimera/debugdraw
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
## only what it scans, so this is a cap, not a limit
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 TwinGunMinInfluence = 0.5 ## M7/G8: fused influence above which the
## twin gun REPLACES the ELM gun that tick
const TwinGunEnergyFloor = 6.0 ## do not spend energy below this
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()
bot.observer.resetVguns() # M7.5: per-opponent virtual-gun statistics
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)
## M7 twin gun (G8): flight-horizon aiming, gated by the fusion influence and
## removed entirely by `-d:chimeraNoTwinGun`. Returns true when it handled this
## tick, so the ELM gun is skipped; false falls back to the ELM path unchanged.
proc computeTwinGun(bot: ChimeraBot, influence: float64): bool =
let aim = bot.observer.twinAim(getX(), getY(), getArenaWidth().float,
getArenaHeight().float, FirePower)
if not aim.active: return false
bot.observer.setGunTelemetry(radToDeg(aim.aimBearing), aim.power,
radToDeg(aim.spread), influence, true)
let err = gunAimErrorDeg(aim.aimBearing, getGunDirection())
# Fire window: half the silhouette width (the aim point is the CENTER of the
# target, so half-width is the lateral slop that still clips it), floored at
# the tight ELM slop. `aim.tolerance` is the full width per the G8 formula.
let slack = max(FireSlopDeg, radToDeg(aim.tolerance) * 0.5)
let cadenceOk = bot.tick - bot.observer.twinGunLastFire() >= cooldownTicks(aim.spread)
if abs(err) <= slack and getGunHeat() == 0.0 and cadenceOk and
getEnergy() >= TwinGunEnergyFloor:
setGunTurnRate(0.0)
discard setFire(aim.power)
bot.observer.noteTwinShot(aim, bot.tick)
inc bot.shotsFired
else:
setGunTurnRate(clamp(err, -20.0, 20.0))
true
## M7.5 virtual-gun tournament (G8). Runs the three-candidate tournament
## (`chimera/virtual_guns.nim`), fires the argmax gun under hysteresis, and
## returns true when it owned this tick's gun. Removed by `-d:chimeraNoVguns`,
## which leaves the M7 influence-gated twin/ELM path below exactly as it was.
proc computeVgunGun(bot: ChimeraBot, influence: float64): bool =
let arenaW = getArenaWidth().float
let arenaH = getArenaHeight().float
let aim = bot.observer.twinAim(getX(), getY(), arenaW, arenaH, FirePower)
if not aim.active: return false
let belief = bot.buildBelief(FirePower)
let (ex, ey) = bot.observer.currentEnemy()
let headBearing = arctan2(ey - getY(), ex - getX())
let elmBearing = bot.gun.heuristicAim(belief, FirePower)
# Advance the live virtual bullets, then launch this tick's candidates.
bot.observer.vgunStep(ex, ey, aimer.BotRadius, arenaW, arenaH)
bot.observer.vgunLaunch(vgTwin, getX(), getY(), aim.aimBearing, aim.power)
if not elmBearing.isNaN:
bot.observer.vgunLaunch(vgElm, getX(), getY(), elmBearing, FirePower)
bot.observer.vgunLaunch(vgHeadOn, getX(), getY(), headBearing, FirePower)
let chosen = bot.observer.vgunSelect(influence > TwinGunMinInfluence)
bot.observer.setGunFired(chosen)
var bearing = headBearing
var power = FirePower
case chosen
of vgTwin: bearing = aim.aimBearing; power = aim.power
of vgElm: bearing = elmBearing; power = FirePower
of vgHeadOn: bearing = headBearing; power = FirePower
bot.observer.setGunTelemetry(radToDeg(bearing), power, radToDeg(aim.spread),
influence, chosen == vgTwin)
let err = gunAimErrorDeg(bearing, getGunDirection())
if abs(err) <= FireSlopDeg and getGunHeat() == 0.0 and
getEnergy() >= TwinGunEnergyFloor:
setGunTurnRate(0.0)
discard setFire(power)
if chosen == vgTwin:
bot.observer.noteTwinShot(aim, bot.tick)
elif chosen == vgElm and bot.gun.online:
# keep the ELM online label stream alive when the tournament picks it
let feat = buildFeatures(belief)
let d = hypot(belief.ex - belief.selfX, belief.ey - belief.selfY)
let tofTicks = max(1, int(round(d / belief.bulletSpeed)))
bot.gun.recordShot(feat, elmBearing, belief.selfX, belief.selfY,
bot.tick + tofTicks)
inc bot.shotsFired
else:
setGunTurnRate(clamp(err, -20.0, 20.0))
true
## 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
# M7.5 virtual-gun tournament: when a current scan exists, the tournament
# selects and fires the argmax gun (twin gated by the same influence scalar).
# `-d:chimeraNoVguns` compiles this block out and restores the M7 path below.
when not NoVguns:
if bot.observer.hasCurrent:
if bot.computeVgunGun(bot.observer.fusedInfluence()):
return
# M7 twin gun: when the fused influence clears the gate, flight-horizon aiming
# owns this tick's gun. `-d:chimeraNoTwinGun` compiles this block out, leaving
# the ELM path below byte-identical to the pre-M7 build.
when not NoTwinGun:
if bot.observer.hasCurrent:
let infl = bot.observer.fusedInfluence()
if infl > TwinGunMinInfluence and bot.computeTwinGun(infl):
return
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
# Debug-overlay probe flash: persists ProbeFlashTicks after a probe triggers.
# Declared only under the debug define and never read by a command path.
when defined(chimeraDebug):
var probeFlash = 0
var probeFlashLabel = ""
var overlayTicks = 0
while isRunning():
# One radar command and one movement command per tick, unconditionally,
# BEFORE go() — so both are part of this tick's intent.
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:
when defined(chimeraDebug):
probeFlash = ProbeFlashTicks
probeFlashLabel = $decision.candidate.kind
bot.observer.writeProbeEvent(bot.tick, $decision.candidate.kind,
decision.gate.reason, decision.entropyBefore,
decision.entropyAfter, decision.candidate.turnRate,
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()
when defined(chimeraDebug):
# OBSERVATION-ONLY overlay: build the primitive list from observer state
# (pure) and hand it to the API's global SVG buffer. Ordering is the same
# as every other command: drawn here, before go(), so it travels with
# THIS tick's intent. No command setter is called, so the command path is
# byte-identical with or without the overlay.
var snap = OverlayInput(selfX: getX(), selfY: getY())
if bot.observer.hasCurrent:
let top = bot.observer.topKernel()
snap.kernelName = top.name
snap.kernelP = top.weight
snap.entropy = bot.observer.entropy()
let (ex, ey) = bot.observer.lastScanPos()
snap.enemyX = ex; snap.enemyY = ey; snap.haveEnemy = true
let fp = bot.observer.fusedPrediction()
if fp.horizon > 0 and fp.points.len > 0:
snap.pFire5 = fp.fireWithin
snap.predX = fp.points[^1].x
snap.predY = fp.points[^1].y
snap.havePred = true
snap.scanGap = bot.tick - bot.observer.scanTick()
snap.fresh = bot.observer.scanTick() == bot.tick - 1
snap.censored = bot.observer.lastCensored()
if probeFlash > 0:
snap.probeFlash = true
snap.probeLabel = probeFlashLabel
dec probeFlash
let prims = buildOverlay(snap)
renderOverlay(prims)
inc overlayTicks
# Observation-only runtime evidence that the overlay drew (stdout only,
# no command state touched). Quiet apart from the first and every 500th tick.
if overlayTicks == 1 or overlayTicks mod 500 == 0:
echo "[chimera-debug] overlay tick=", bot.tick, " prims=", prims.len,
" svg=", svgOutput().len
go()
bot.observer.writeTick(bot.tick) # observation telemetry, after go()
inc bot.tick
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)
+274
View File
@@ -0,0 +1,274 @@
# 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_replay_oracle.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"
exec "nim c -r --hints:off ../tests/test_identifiability.nim"
exec "nim c -r --hints:off ../tests/test_aimer.nim"
exec "nim c -r --hints:off ../tests/test_virtual_guns.nim"
exec "nim c -r --hints:off ../tests/test_dodger.nim"
# Debug overlay: compiled WITH -d:chimeraDebug so the drawing path is the real
# one; the test asserts the command intent is identical with/without it.
exec "nim c -r --hints:off -d:chimeraDebug ../tests/test_debugdraw.nim"
+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,335 @@
## CHIMERA twin gun — flight-horizon aiming (docs/chimera-spec.md, G8 / M7).
##
## The ELM gun (`modules/ELM/elm_gun.nim`) leads the enemy by one geometric
## dead-reckon with a learned correction trained on a 5-tick lookahead. A bullet
## at power `p` flies `dist / (20 - 3p)` ticks — 15 to 45 ticks across the legal
## power range — so on a dodging opponent the aim must target the enemy's
## **bullet-arrival position**, not a 5-tick extrapolation. That is what this
## module adds, in three pieces:
##
## 1. **Horizon-bucketed Hedge** over three predictors — the posterior-mixture
## twinsim rollout, the linear-residual trajectory and constant-velocity
## persistence. Buckets are `1-7 / 8-17 / 18-35 / 36-70` ticks. Each bucket's
## weights are updated online from the realized enemy position at the horizon
## that was actually used; every bucket starts uniform (neutral). This is the
## G8 extension of the M6 fusion (`fusion.nim`), which only knew `k = 5`.
## 2. **Iterated flight time** — `h = flightTime(dist, power)` is folded onto
## itself at most 3 times (`h -> fusedPositionAt(h) -> dist -> h`), with the
## result clipped to the arena and re-iterated when clipping moved it.
## 3. **Spread-based power selection** — the top-`k` (`k <= 4`) kernels by
## posterior are rolled to the flight horizon; the max pairwise angular spread
## of their predicted positions, seen from OUR position, must fit inside the
## enemy-silhouette angular tolerance `2*atan2(botRadius, dist)`. The largest
## power that fits is chosen. Plus an online **aim-bias corrector**: a
## distance-band x enemy-speed-band histogram of post-shot angular misses,
## applied as an angular offset, deterministic and persisted per match.
##
## Nothing here issues commands: `ChimeraBot.computeGun` reads `TwinAim` and
## drives the gun. The whole path is removed by `-d:chimeraNoTwinGun`, which
## restores the exact current ELM gun behaviour.
import std/[math, algorithm]
import ./physics, ./dsl, ./twinsim, ./residual, ./hedge, ./fusion
const
NoTwinGun* = defined(chimeraNoTwinGun)
## Kill switch: with this defined `ChimeraBot.computeGun` never calls the
## twin gun and the ELM path is byte-identical to the pre-M7 build.
BotRadius* = 18.0
## Enemy silhouette half-width used by the angular-tolerance formula. The
## spec does not define a value; 18 units is the Tank Royale bot radius
## convention used elsewhere in the repo.
FirePowers* = [3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.1]
## Candidate powers, DESCENDING. `selectPowerFromSpreads` searches this order
## so the chosen power is monotone non-increasing in the required spread.
NBuckets* = 4
BucketLo* = [1, 8, 18, 36]
BucketHi* = [7, 17, 35, 70]
MaxIter* = 3 ## flight-time/aim-point refinement iterations
MinorStep* = 1e-3 ## |h' - h| below this means converged (ticks)
TinySpreadDeg* = 0.5 ## spread below this allows the fast cadence
NormalCooldown* = 8 ## ticks between twin-gun shots (no spraying)
TinyCooldown* = 2
NDistBands* = 4
NSpeedBands* = 4
DistBandLo* = [0.0, 150.0, 300.0, 500.0]
SpeedBandLo* = [0.0, 2.0, 4.0, 6.0]
MaxBias* = 0.26 ## rad (~15 deg) cap on the learned aim bias
type
PredictorPoints* = object
## The three predictors' enemy position at one horizon, plus the per-kernel
## final positions and posterior weights the spread selector needs.
mix*: tuple[x, y: float64]
res*: tuple[x, y: float64]
pers*: tuple[x, y: float64]
samples*: seq[tuple[x, y: float64]]
weights*: seq[float64]
TwinAim* = object
## The twin gun's per-tick output.
active*: bool
aimBearing*: float64 ## absolute bearing (rad, 0 = east CCW) after bias
x*, y*: float64 ## the (clipped) aim point
power*: float64
spread*: float64 ## rad, max pairwise kernel disagreement at horizon
tolerance*: float64 ## rad, enemy silhouette width at the aim distance
horizon*: float64 ## ticks
baseBearing*: float64 ## bearing to the aim point BEFORE the bias offset
dist*: float64
enemySpeed*: float64
selfX*, selfY*: float64
# what a fired shot needs for delayed scoring / bias training
bucket*: int
mixPt*, resPt*, persPt*: tuple[x, y: float64]
PendingShot* = object
dueTick*: int
bucket*: int
selfX*, selfY*: float64
aimBearing*: float64
dist*, enemySpeed*: float64
mixPt*, resPt*, persPt*: tuple[x, y: float64]
Aimer* = ref object
bucket*: array[NBuckets, Hedge]
biasSum*: array[NDistBands, array[NSpeedBands, float64]]
biasN*: array[NDistBands, array[NSpeedBands, int]]
pending*: seq[PendingShot]
lastFireTick*: int
shots*: int
hits*: int
# ── pure helpers ────────────────────────────────────────────────────────────
proc wrapPi*(a: float64): float64 =
## Shortest signed angle in (-pi, pi], radians.
result = a
while result <= -PI: result += 2.0 * PI
while result > PI: result -= 2.0 * PI
proc flightTime*(dist, power: float64): float64 =
## Ticks a bullet travels `dist` units at `power`, per physics.bulletSpeed:
## `dist / (20 - 3*power)`. A zero/negative power would divide by 20; the
## physics clamp keeps the denominator in [11, 19.7].
let v = bulletSpeed(power)
if v <= 0.0: 0.0 else: dist / v
proc bucketIndex*(h: float64): int =
## Bucket containing horizon `h` (ticks). Values past the last bucket clamp.
let hi = int(ceil(h))
for i in 0 ..< NBuckets:
if hi <= BucketHi[i]: return i
NBuckets - 1
proc angularTolerance*(dist: float64, botRadius = BotRadius): float64 =
## Angular half... actually FULL width of the enemy silhouette at `dist`:
## `2 * atan2(botRadius, dist)`, radians. Closer targets subtend more angle.
if dist <= 1e-6: return PI
2.0 * arctan2(botRadius, dist)
proc selectPowerFromSpreads*(spreads: openArray[float64], tol: float64): float64 =
## `spreads[i]` is the required angular spread at `FirePowers[i]`'s flight
## horizon. FirePowers are DESCENDING, so the first index whose spread fits
## inside `tol` is the largest admissible power; if none fits, the smallest
## power. Monotone in `tol` and in a uniform scaling of `spreads`: a larger
## spread can only shrink the admissible set, whose maximum is therefore
## non-increasing.
let n = min(spreads.len, FirePowers.len)
for i in 0 ..< n:
if spreads[i] <= tol: return FirePowers[i]
if n == 0: FirePowers[^1] else: FirePowers[n - 1]
proc maxPairwiseSpread*(samples: openArray[tuple[x, y: float64]],
weights: openArray[float64],
selfX, selfY, k: float64): float64 =
## Max pairwise angular difference (rad) between the top-`k` kernels' predicted
## positions as seen from `(selfX, selfY)`. `k <= 4` per spec. Fewer than two
## usable samples => 0 (nothing to disagree about).
var pairs: seq[tuple[w: float64, x, y: float64]]
for i in 0 ..< samples.len:
let w = if i < weights.len: weights[i] else: 0.0
pairs.add (w, samples[i].x, samples[i].y)
pairs.sort(proc(a, b: tuple[w: float64, x, y: float64]): int = cmp(b.w, a.w))
let m = min(pairs.len, int(k))
var ang: seq[float64]
for i in 0 ..< m:
ang.add arctan2(pairs[i].y - selfY, pairs[i].x - selfX)
var best = 0.0
for i in 0 ..< ang.len:
for j in i + 1 ..< ang.len:
best = max(best, abs(wrapPi(ang[i] - ang[j])))
best
proc blend*(h: Hedge, mix, res, pers: tuple[x, y: float64]): tuple[x, y: float64] =
## Predictor mixture at one horizon, by the bucket's Hedge weights.
let wm = h.weights[0]
let wr = h.weights[1]
let wp = h.weights[2]
(wm * mix.x + wr * res.x + wp * pers.x,
wm * mix.y + wr * res.y + wp * pers.y)
proc clipToArena*(x, y, arenaW, arenaH: float64): tuple[x, y: float64, clipped: bool] =
let cx = clamp(x, 0.0, max(0.0, arenaW))
let cy = clamp(y, 0.0, max(0.0, arenaH))
(cx, cy, cx != x or cy != y)
proc distBand*(dist: float64): int =
for i in countdown(NDistBands - 1, 0):
if dist >= DistBandLo[i]: return i
0
proc speedBand*(speed: float64): int =
let s = abs(speed)
for i in countdown(NSpeedBands - 1, 0):
if s >= SpeedBandLo[i]: return i
0
# ── construction ────────────────────────────────────────────────────────────
proc initAimer*(): Aimer =
new(result)
for i in 0 ..< NBuckets:
result.bucket[i] = initHedge(PredictorNames)
result.lastFireTick = -1000
# ── predictor trajectories at a horizon ─────────────────────────────────────
proc pointAt*(kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, h: float64): PredictorPoints =
## Roll every predictor to horizon `h` and return their final points. The
## per-kernel samples and posterior weights feed the spread selector.
let k = max(1, int(round(h)))
let mix = rollout(kernels, origin, k)
result.samples = mix.samples
result.weights = origin.weights
if mix.points.len > 0:
result.mix = (mix.points[^1].x, mix.points[^1].y)
let resPts = residualTrajectory(origin, mix.points, rp, k)
if resPts.len > 0: result.res = (resPts[^1].x, resPts[^1].y)
let persPts = persistence(origin, k)
if persPts.len > 0: result.pers = (persPts[^1].x, persPts[^1].y)
proc fusedPositionAt*(a: Aimer, kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, h: float64): tuple[x, y: float64] =
## Horizon-bucketed predictor mixture at `h` (spec G8 `fusedPositionAt`).
let pp = pointAt(kernels, origin, rp, h)
blend(a.bucket[bucketIndex(h)], pp.mix, pp.res, pp.pers)
# ── the per-tick aim ────────────────────────────────────────────────────────
proc biasOffset*(a: Aimer, dist, enemySpeed: float64): float64 =
## Mean observed post-shot miss for this (distance band, speed band), clamped.
let db = distBand(dist)
let sb = speedBand(enemySpeed)
if a.biasN[db][sb] == 0: return 0.0
clamp(a.biasSum[db][sb] / float(a.biasN[db][sb]), -MaxBias, MaxBias)
proc computeAim*(a: Aimer, kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, selfX, selfY,
arenaW, arenaH: float64,
nominalPower = 2.0): TwinAim =
## Flight-horizon aim point + spread-selected power. Pure with respect to the
## world: `a` is only read (bucket weights, bias), never mutated here.
result.selfX = selfX
result.selfY = selfY
let range = hypot(origin.ex - selfX, origin.ey - selfY)
var h = flightTime(range, nominalPower)
var power = nominalPower
var pp = pointAt(kernels, origin, rp, h)
var pos = blend(a.bucket[bucketIndex(h)], pp.mix, pp.res, pp.pers)
var clip = clipToArena(pos.x, pos.y, arenaW, arenaH)
pos = (clip.x, clip.y)
var b = bucketIndex(h)
for it in 0 ..< MaxIter:
let aimDist = hypot(pos.x - selfX, pos.y - selfY)
let tol = angularTolerance(aimDist)
let spread0 = maxPairwiseSpread(pp.samples, pp.weights, selfX, selfY, 4.0)
# Spread at each candidate power's own flight horizon (lazy: break at the
# first admissible power, which is the largest because FirePowers descends).
var spreads: seq[float64]
for p in FirePowers:
let hp = flightTime(aimDist, p)
if abs(hp - h) < 0.5:
spreads.add spread0
else:
spreads.add maxPairwiseSpread(pointAt(kernels, origin, rp, hp).samples,
pp.weights, selfX, selfY, 4.0)
power = selectPowerFromSpreads(spreads, tol)
let h2 = flightTime(aimDist, power)
if abs(h2 - h) < MinorStep: break
h = h2
pp = pointAt(kernels, origin, rp, h)
b = bucketIndex(h)
pos = blend(a.bucket[b], pp.mix, pp.res, pp.pers)
let c = clipToArena(pos.x, pos.y, arenaW, arenaH)
pos = (c.x, c.y)
let aimDist = hypot(pos.x - selfX, pos.y - selfY)
let baseBearing = arctan2(pos.y - selfY, pos.x - selfX)
let bias = a.biasOffset(aimDist, origin.espeed)
result.active = true
result.bucket = b
result.mixPt = pp.mix
result.resPt = pp.res
result.persPt = pp.pers
result.x = pos.x
result.y = pos.y
result.power = power
result.spread = maxPairwiseSpread(pp.samples, pp.weights, selfX, selfY, 4.0)
result.tolerance = angularTolerance(aimDist)
result.horizon = h
result.baseBearing = baseBearing
result.dist = aimDist
result.enemySpeed = origin.espeed
result.aimBearing = wrapPi(baseBearing + bias)
proc cooldownTicks*(spreadRad: float64): int =
## Conservative cadence: the gun cannot spray. A tiny spread allows the fast
## cadence; otherwise at least `NormalCooldown` ticks between shots.
if radToDeg(spreadRad) <= TinySpreadDeg: TinyCooldown else: NormalCooldown
# ── online scoring / bias training ──────────────────────────────────────────
proc noteShot*(a: var Aimer, aim: TwinAim, tick: int) =
## Arm a fired twin-gun shot for delayed scoring. `dueTick` is the flight
## horizon used at fire time; the realized enemy position then trains BOTH the
## bucket's predictor Hedge and the segment bias histogram.
let due = tick + max(1, int(round(aim.horizon)))
if a.pending.len >= 64: a.pending.delete(0)
a.pending.add PendingShot(dueTick: due, bucket: aim.bucket,
selfX: aim.selfX, selfY: aim.selfY,
aimBearing: aim.aimBearing, dist: aim.dist,
enemySpeed: aim.enemySpeed,
mixPt: aim.mixPt, resPt: aim.resPt, persPt: aim.persPt)
a.lastFireTick = tick
inc a.shots
proc resolve*(a: var Aimer, tick: int, enemyX, enemyY: float64) =
## Called on every scan tick. Scores every pending shot whose horizon has
## elapsed against the realized enemy position: updates the bucket Hedge
## (distance-error loss per predictor) and the bias histogram (bearing miss).
var i = 0
while i < a.pending.len:
let p = a.pending[i]
if tick < p.dueTick:
inc i
continue
let dm = hypot(p.mixPt.x - enemyX, p.mixPt.y - enemyY)
let dr = hypot(p.resPt.x - enemyX, p.resPt.y - enemyY)
let dp = hypot(p.persPt.x - enemyX, p.persPt.y - enemyY)
a.bucket[p.bucket].update([dm / 100.0, dr / 100.0, dp / 100.0])
let actualBearing = arctan2(enemyY - p.selfY, enemyX - p.selfX)
let db = distBand(p.dist)
let sb = speedBand(p.enemySpeed)
a.biasSum[db][sb] += wrapPi(actualBearing - p.aimBearing)
inc a.biasN[db][sb]
if dm <= BotRadius: inc a.hits
a.pending.delete(i)
proc bucketWeights*(a: Aimer, b: int): seq[float64] =
a.bucket[b].weights
@@ -0,0 +1,139 @@
## CHIMERA debug overlay — observation-only SVG drawing.
##
## The bot API has **no** `setDebugGraphics` object to hand around. Debug
## graphics in `robocode_tankroyale_botapi` 1.0.7 are drawn with module-global
## procs that append to an internal SVG buffer:
##
## setStrokeColor / setFillColor / setStrokeWidth / setFont (style)
## drawLine, drawCircle, fillCircle, drawText, drawRectangle ... (geometry)
##
## `go()` serialises that buffer into `BotIntent.debugGraphics` via
## `graphics.svgOutput()` and then `clearGraphics()`s it, so anything drawn
## before `go()` reaches the viewer for THIS tick and costs nothing after.
##
## Everything here is OBSERVATION-ONLY:
## * `buildOverlay` is a PURE function of a plain snapshot — no API state, no
## clock, no RNG — so it is deterministic and directly unit-testable;
## * `renderOverlay` maps the primitives to the drawing procs above and never
## touches command state (target speed, turn rates, fire), so the command
## path is byte-identical with the overlay on or off (pinned by
## `tests/test_debugdraw.nim`).
##
## Cost gate: `renderOverlay` compiles to an empty stub unless `-d:chimeraDebug`
## is set, and `ChimeraBot.nim` does not even build the primitive list without
## the define. Budget: `MaxDebugPrims` primitives per tick.
import std/[math, strutils]
import robocode_tankroyale_botapi
const
OverlayEnabled* = defined(chimeraDebug)
MaxDebugPrims* = 10 ## hard per-tick budget (~10 requested)
ProbeFlashTicks* = 5 ## how long a probe marker persists
type
DKind* = enum dkText, dkLine, dkCircle, dkDot
DebugPrim* = object
## One drawable primitive. `rgba` packs 0xRRGGBBAA, the API Color layout.
kind*: DKind
x*, y*: float
x2*, y2*: float
r*: float
text*: string
rgba*: uint32
OverlayInput* = object
## Plain snapshot the bot assembles from the observer; the builder reads
## nothing else.
selfX*, selfY*: float
kernelName*: string
kernelP*: float
entropy*: float
pFire5*: float
enemyX*, enemyY*: float
haveEnemy*: bool
predX*, predY*: float
havePred*: bool
fresh*: bool
censored*: bool
scanGap*: int
probeLabel*: string
probeFlash*: bool
# Colours chosen distinct from tfilDebug's palette (which uses red bullets,
# #FF8800 auras, cyan enemies, green safe tiles): cyan identity, red fire,
# yellow probes, grey scan-health, spring-green counterfactual.
const
ColIdentity = 0x00FFFFFF'u32
ColProbe = 0xFFFF00FF'u32
ColScan = 0x808080FF'u32
ColPred = 0x00FF88FF'u32
proc fireRgba(p: float): uint32 =
## Fire-circle colour ramps toward full red as P rises; alpha rises too.
let t = clamp(p, 0.0, 1.0)
let g = uint32(200.0 * (1.0 - t))
let a = uint32(90.0 + 150.0 * t)
(0xFF'u32 shl 24) or (g shl 16) or a
proc buildOverlay*(inp: OverlayInput): seq[DebugPrim] =
## Pure, deterministic primitive builder. Fixed order: reruns on the same
## input are byte-identical (pinned by test_debugdraw).
if inp.kernelName.len > 0:
# (a) IDENTITY BLOCK — kernel + top-1 posterior + entropy, then P(fire5).
result.add DebugPrim(kind: dkText,
text: inp.kernelName & " " & $int(inp.kernelP * 100.0 + 0.5) &
"% H=" & formatFloat(inp.entropy, ffDecimal, 2),
x: inp.selfX + 20.0, y: inp.selfY + 34.0, rgba: ColIdentity)
result.add DebugPrim(kind: dkText,
text: "P(fire5)=" & $int(clamp(inp.pFire5, 0.0, 1.0) * 100.0 + 0.5) & "%",
x: inp.selfX + 20.0, y: inp.selfY + 20.0, rgba: ColIdentity)
if inp.haveEnemy:
# (b) FIRE PREDICTION — radius/opacity/colour encode fused P(fire within 5).
result.add DebugPrim(kind: dkCircle, x: inp.enemyX, y: inp.enemyY,
r: 20.0 + 60.0 * clamp(inp.pFire5, 0.0, 1.0),
rgba: fireRgba(inp.pFire5))
if inp.fresh and not inp.censored and inp.havePred and inp.haveEnemy:
# (c) COUNTERFACTUAL — enemy now -> fused 5-tick predicted position.
result.add DebugPrim(kind: dkLine, x: inp.enemyX, y: inp.enemyY,
x2: inp.predX, y2: inp.predY, rgba: ColPred)
result.add DebugPrim(kind: dkDot, x: inp.predX, y: inp.predY, r: 6.0,
rgba: (ColPred and 0xFFFFFF00'u32) or 0x80'u32)
if inp.probeFlash and inp.probeLabel.len > 0:
# (d) PROBE MARKER — type label + flash near our bot (persists ~5 ticks).
result.add DebugPrim(kind: dkText, text: "probe:" & inp.probeLabel,
x: inp.selfX - 40.0, y: inp.selfY + 48.0, rgba: ColProbe)
result.add DebugPrim(kind: dkDot, x: inp.selfX, y: inp.selfY, r: 10.0,
rgba: ColProbe)
if inp.scanGap > 1 or inp.censored:
# (e) SCAN HEALTH — rare grey tick when the stream is not clean.
result.add DebugPrim(kind: dkDot, x: inp.selfX - 18.0, y: inp.selfY + 48.0,
r: 4.0, rgba: ColScan)
if result.len > MaxDebugPrims:
result.setLen(MaxDebugPrims)
proc renderOverlay*(prims: openArray[DebugPrim]) =
## Map primitives to the API's global drawing procs. `Color` shares the
## 0xRRGGBBAA packing, so `Color(rgba)` is exact.
when defined(chimeraDebug):
for p in prims:
let c = Color(p.rgba)
case p.kind
of dkText:
setFillColor(c)
setFont("Arial", 11.0)
drawText(p.text, p.x, p.y)
of dkLine:
setStrokeColor(c)
setStrokeWidth(1.5)
drawLine(p.x, p.y, p.x2, p.y2)
of dkCircle:
setStrokeColor(c)
setStrokeWidth(1.5)
drawCircle(p.x, p.y, p.r)
of dkDot:
setFillColor(c)
fillCircle(p.x, p.y, p.r)
else:
discard
@@ -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,140 @@
## 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)
# The residual head is trained on `realized - capped(mixture command)` (M6.5),
# so cap the base before adding the correction: training/inference symmetry.
dir = wrap180(dir + limitTurnRate(baseTurn, sp) + rp.turn)
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,304 @@
## CHIMERA G2 — kernel identifiability certificate (spec §12, G2).
##
## For every unordered kernel pair `(Ki, Kj)` this module searches probe
## sequences over the spec §9 probe types (movement stop/reverse/speed-mod/flip,
## a DISTANCE burst, a GUN shot, and noop) up to `G2Lmax` ticks and scores how
## far the enemy-intent *distributions* the two kernels induce separate on a
## fixed canonical start-state set.
##
## Design (spec wording governs where it differs):
##
## * A probe sequence is a plan for OUR bot. Each kernel is rolled forward with
## `twinsim`'s physics (stepSpeed / limitTurnRate / wrap180) under that plan,
## from every state in `canonicalStarts()`. Our own action changes our
## `MyState` input, so the kernels' reactions — the counterfactual — change.
## * Separation at tick `t` is the **total variation** between the two kernels'
## empirical distributions over the joint discretized enemy intent
## `(turnRate, targetSpeed, fire)` across the canonical start states. The
## sequence score is the per-tick TV **averaged over the sequence**.
## * `sep[L]` is the best score over all sequences of length `<= L` (so it is
## monotone non-decreasing by construction). `L_ij` is the smallest `L` with
## `sep[L] >= G2Delta`; if none within `G2Lmax` the pair is UNIDENTIFIABLE.
##
## Determinism: fixed start set, fixed alphabet order, depth-first enumeration in
## that order, fixed discretization. Two runs are byte-identical (pinned by
## tests/test_identifiability.nim).
import std/[math, tables, strutils]
import ./physics, ./dsl, ./twinsim
const
G2Lmax* = 6
## longest probe sequence searched (spec: "length <= L", G2 kickoff Lmax=6).
G2Delta* = 0.3
## separation threshold `delta`. The spec leaves `delta` open, so we fix the
## total-variation bar at 0.3 (30% mass moved) and document it here.
G2KeyTurn = 1.0 ## intent discretization: 1 deg
G2KeySpeed = 1.0 ## 1 unit/tick
G2KeyFire = 0.1 ## 0.1 firepower (0 stays 0)
type
ProbeAction* = object
## One command for our bot. `repeatPrev` is the noop: keep the previous
## effective command instead of committing a new one.
label*: string
turnRate*: float64
targetSpeed*: float64
fire*: float64
repeatPrev*: bool
StartState* = object
## A canonical enemy/scenario state. Enemy fields first, then our fields.
ex*, ey*, edir*, espeed*, eenergy*: float64
ox*, oy*, odir*, ospeed*: float64
IntentKey* = tuple[turn, speed, fire: int]
PairResult* = object
ki*, kj*: string
identifiable*: bool
lStar*: int ## minimal separating length, 0 when unidentifiable
separation*: float64 ## best separation at `lStar`
prefix*: string ## best probe prefix (labels joined by "+")
PairCurve* = object
sep*: seq[float64] ## sep[L] for L in 1..maxLen (best over length <= L)
prefix*: seq[string] ## best prefix attaining sep[L]
# ── fixed canonical scenario set ────────────────────────────────────────────
proc canonicalStarts*(): seq[StartState] =
## Eight fixed scenarios spanning positions, headings, speeds and energies.
## Deterministic order; the distributions below are over THIS set.
@[
StartState(ex: 100.0, ey: 100.0, edir: 0.0, espeed: 4.0, eenergy: 100.0,
ox: 600.0, oy: 300.0, odir: 180.0, ospeed: 4.0),
StartState(ex: 700.0, ey: 500.0, edir: 90.0, espeed: 0.0, eenergy: 40.0,
ox: 200.0, oy: 300.0, odir: 0.0, ospeed: 0.0),
StartState(ex: 400.0, ey: 300.0, edir: 270.0, espeed: 6.0, eenergy: 100.0,
ox: 100.0, oy: 100.0, odir: 45.0, ospeed: 6.0),
StartState(ex: 50.0, ey: 550.0, edir: 180.0, espeed: -4.0, eenergy: 15.0,
ox: 700.0, oy: 100.0, odir: 225.0, ospeed: 2.0),
StartState(ex: 400.0, ey: 50.0, edir: 0.0, espeed: 8.0, eenergy: 100.0,
ox: 400.0, oy: 550.0, odir: 270.0, ospeed: 8.0),
StartState(ex: 400.0, ey: 550.0, edir: 90.0, espeed: 2.0, eenergy: 5.0,
ox: 400.0, oy: 50.0, odir: 90.0, ospeed: 4.0),
StartState(ex: 750.0, ey: 300.0, edir: 180.0, espeed: 3.0, eenergy: 100.0,
ox: 50.0, oy: 300.0, odir: 0.0, ospeed: 3.0),
StartState(ex: 200.0, ey: 200.0, edir: 315.0, espeed: -2.0, eenergy: 60.0,
ox: 600.0, oy: 400.0, odir: 135.0, ospeed: 5.0),
]
proc probeAlphabet*(): seq[ProbeAction] =
## The seven spec §9 probe types, in fixed deterministic order. `reverse` and
## `distance` are the full backward/forward bursts; `speedmod` is the gentle
## step; `flip` is a hard body turn; `gun` is a low-power shot (inert for the
## current kernels — no hit-response is modelled — kept for spec completeness).
@[
ProbeAction(label: "noop", turnRate: 0.0, targetSpeed: 0.0,
fire: 0.0, repeatPrev: true),
ProbeAction(label: "stop", turnRate: 0.0, targetSpeed: 0.0, fire: 0.0),
ProbeAction(label: "reverse", turnRate: 0.0, targetSpeed: MaxBackwardSpeed,
fire: 0.0),
ProbeAction(label: "speedmod", turnRate: 0.0, targetSpeed: 4.0, fire: 0.0),
ProbeAction(label: "flip", turnRate: MaxTurnRate, targetSpeed: 0.0, fire: 0.0),
ProbeAction(label: "distance", turnRate: 0.0, targetSpeed: MaxForwardSpeed,
fire: 0.0),
ProbeAction(label: "gun", turnRate: 0.0, targetSpeed: 0.0,
fire: MinFirepower),
]
# ── intent discretization + total variation ─────────────────────────────────
proc intentKey*(it: Intent): IntentKey =
## Discretize an intent to a joint histogram key. Fire 0 stays 0.
let f = if it.fire <= 0.0: 0.0 else: it.fire
(turn: int(round(clamp(it.turnRate, -MaxTurnRate, MaxTurnRate) / G2KeyTurn)),
speed: int(round(clamp(it.targetSpeed, MaxBackwardSpeed, MaxForwardSpeed) /
G2KeySpeed)),
fire: int(round(clamp(f, 0.0, 3.0) / G2KeyFire)))
proc totalVariation*(ki, kj: openArray[IntentKey]): float64 =
## TV between two empirical distributions over the union of keys.
if ki.len == 0 or kj.len == 0: return 0.0
var a = initCountTable[IntentKey]()
var b = initCountTable[IntentKey]()
for k in ki: a.inc k
for k in kj: b.inc k
let fa = 1.0 / float(ki.len)
let fb = 1.0 / float(kj.len)
var acc = 0.0
for k, c in a:
let other = b.getOrDefault(k)
acc += abs(float(c) * fa - float(other) * fb)
for k, c in b:
if k notin a:
acc += abs(float(c) * fb)
acc / 2.0
# ── single-kernel trace (for tests / inspection) ────────────────────────────
proc traceKernel*(k: Kernel, st: StartState,
plan: openArray[ProbeAction]): seq[Intent] =
## Roll one kernel forward under our plan and return its per-tick intent.
## Physics mirrors `twinsim.rollout`'s single-kernel path.
var e = EnemyState(tick: 0, x: st.ex, y: st.ey, direction: st.edir,
speed: st.espeed, energy: st.eenergy)
var mem = defaultMemory(k.defaultParams)
var myX = st.ox
var myY = st.oy
var myDir = st.odir
var mySpeed = st.ospeed
var gTurn = 0.0
var gSpeed = 0.0
for h in 0 ..< plan.len:
let a = plan[h]
let effTurn = if a.repeatPrev: gTurn else: a.turnRate
let effSpeed = if a.repeatPrev: gSpeed else: a.targetSpeed
gTurn = effTurn
gSpeed = effSpeed
mySpeed = stepSpeed(mySpeed, effSpeed)
myDir = wrap180(myDir + limitTurnRate(effTurn, mySpeed))
myX += mySpeed * cos(degToRad(myDir))
myY += mySpeed * sin(degToRad(myDir))
let it = k.step(e, MyState(x: myX, y: myY), k.defaultParams, mem)
let ns = stepSpeed(e.speed, it.targetSpeed)
e.direction = wrap180(e.direction + limitTurnRate(it.turnRate, ns))
e.speed = ns
e.x = clamp(e.x + ns * cos(degToRad(e.direction)), 0.0,
k.defaultParams.arenaW)
e.y = clamp(e.y + ns * sin(degToRad(e.direction)), 0.0,
k.defaultParams.arenaH)
e.tick = h + 1
result.add it
# ── exhaustive short-sequence search ────────────────────────────────────────
proc searchCurve(ki, kj: Kernel, starts: seq[StartState],
alphabet: seq[ProbeAction], maxLen: int): PairCurve =
## Depth-first search over sequences of length up to `maxLen`. Tracks the best
## per-tick-averaged separation at each exact depth, then takes the running
## maximum, so `sep[L]` is the best score over all sequences of length <= L.
let n = starts.len
result.sep = newSeq[float64](maxLen + 1)
result.prefix = newSeq[string](maxLen + 1)
var bestExact = newSeq[float64](maxLen + 1)
var bestSeq = newSeq[seq[string]](maxLen + 1)
for i in 0 .. maxLen: bestExact[i] = -1.0
var ei = newSeq[EnemyState](n)
var mi = newSeq[KernelMem](n)
var ej = newSeq[EnemyState](n)
var mj = newSeq[KernelMem](n)
var myX = newSeq[float64](n)
var myY = newSeq[float64](n)
var myDir = newSeq[float64](n)
var mySpeed = newSeq[float64](n)
for s in 0 ..< n:
let st = starts[s]
ei[s] = EnemyState(tick: 0, x: st.ex, y: st.ey, direction: st.edir,
speed: st.espeed, energy: st.eenergy)
ej[s] = ei[s]
mi[s] = defaultMemory(ki.defaultParams)
mj[s] = defaultMemory(kj.defaultParams)
myX[s] = st.ox
myY[s] = st.oy
myDir[s] = st.odir
mySpeed[s] = st.ospeed
var keysI = newSeq[IntentKey](n)
var keysJ = newSeq[IntentKey](n)
var path = newSeq[string](maxLen)
var gTurn = 0.0
var gSpeed = 0.0
proc rec(d: int; cumTV: float64) =
if d >= 1:
let avg = cumTV / float(d)
if avg > bestExact[d]:
bestExact[d] = avg
bestSeq[d] = path[0 ..< d]
if d == maxLen: return
for a in alphabet:
let effTurn = if a.repeatPrev: gTurn else: a.turnRate
let effSpeed = if a.repeatPrev: gSpeed else: a.targetSpeed
let oldTurn = gTurn
let oldSpeed = gSpeed
gTurn = effTurn
gSpeed = effSpeed
for s in 0 ..< n:
mySpeed[s] = stepSpeed(mySpeed[s], effSpeed)
myDir[s] = wrap180(myDir[s] + limitTurnRate(effTurn, mySpeed[s]))
myX[s] += mySpeed[s] * cos(degToRad(myDir[s]))
myY[s] += mySpeed[s] * sin(degToRad(myDir[s]))
let iti = ki.step(ei[s], MyState(x: myX[s], y: myY[s]),
ki.defaultParams, mi[s])
let itj = kj.step(ej[s], MyState(x: myX[s], y: myY[s]),
kj.defaultParams, mj[s])
let nsi = stepSpeed(ei[s].speed, iti.targetSpeed)
ei[s].direction = wrap180(ei[s].direction + limitTurnRate(iti.turnRate, nsi))
ei[s].speed = nsi
ei[s].x = clamp(ei[s].x + nsi * cos(degToRad(ei[s].direction)), 0.0,
ki.defaultParams.arenaW)
ei[s].y = clamp(ei[s].y + nsi * sin(degToRad(ei[s].direction)), 0.0,
ki.defaultParams.arenaH)
ei[s].tick = d + 1
let nsj = stepSpeed(ej[s].speed, itj.targetSpeed)
ej[s].direction = wrap180(ej[s].direction + limitTurnRate(itj.turnRate, nsj))
ej[s].speed = nsj
ej[s].x = clamp(ej[s].x + nsj * cos(degToRad(ej[s].direction)), 0.0,
kj.defaultParams.arenaW)
ej[s].y = clamp(ej[s].y + nsj * sin(degToRad(ej[s].direction)), 0.0,
kj.defaultParams.arenaH)
ej[s].tick = d + 1
keysI[s] = intentKey(iti)
keysJ[s] = intentKey(itj)
let tv = totalVariation(keysI, keysJ)
path[d] = a.label
rec(d + 1, cumTV + tv)
gTurn = oldTurn
gSpeed = oldSpeed
rec(0, 0.0)
# Running maximum over lengths: best score over sequences of length <= L.
var runBest = -1.0
var runPrefix = ""
for L in 1 .. maxLen:
if bestExact[L] > runBest:
runBest = bestExact[L]
runPrefix = bestSeq[L].join("+")
result.sep[L] = runBest
result.prefix[L] = runPrefix
proc kernelPairCurve*(ki, kj: Kernel, starts: seq[StartState],
alphabet: seq[ProbeAction],
maxLen = G2Lmax): PairCurve =
searchCurve(ki, kj, starts, alphabet, maxLen)
proc certifyPair*(ki, kj: Kernel, starts: seq[StartState],
alphabet: seq[ProbeAction],
maxLen = G2Lmax, delta = G2Delta): PairResult =
## Minimal separating length for one kernel pair, or UNIDENTIFIABLE.
result.ki = ki.name
result.kj = kj.name
let curve = kernelPairCurve(ki, kj, starts, alphabet, maxLen)
for L in 1 .. maxLen:
if curve.sep[L] >= delta:
result.identifiable = true
result.lStar = L
result.separation = curve.sep[L]
result.prefix = curve.prefix[L]
return
result.identifiable = false
result.lStar = 0
result.separation = curve.sep[maxLen]
result.prefix = curve.prefix[maxLen]
proc identifiabilityCertificate*(kernels: seq[Kernel],
starts = canonicalStarts(),
alphabet = probeAlphabet(),
maxLen = G2Lmax,
delta = G2Delta): seq[PairResult] =
## The 66-row certificate over every unordered kernel pair (Ki,Kj), i<j.
for i in 0 ..< kernels.len:
for j in i + 1 ..< kernels.len:
result.add certifyPair(kernels[i], kernels[j], starts, alphabet, maxLen, delta)
@@ -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,532 @@
## 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, ./aimer, ./virtual_guns
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
# M7 twin gun (G8): horizon-bucketed predictor Hedge + aim-bias corrector.
# Lives here because it is fed the same scan stream; it persists per match.
aimer: Aimer
gunAimDeg*, gunPower*, gunSpreadDeg*, gunInfluence*: float64
twinActive*: bool
# M7.5 virtual-gun tournament (G8). Scores every candidate's virtual bullet
# against the realized enemy position; selects the gun the bot fires.
vguns*: VirtualGunSet
gunFiredLabel*: string ## which gun the tournament fired (telemetry only)
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.aimer = initAimer()
result.vguns = initVirtualGuns()
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
# M7 twin gun: score any fired twin-gun shot whose flight horizon elapsed.
o.aimer.resolve(tick, x, y)
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, mixFireP = 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
# Fire is a Bernoulli channel: the fusion scores a PROBABILITY, and
# `intentLoss` already binarizes the kernel's predicted power. Using the
# weighted POWER here made `mixFire` ~= 1 wherever a high-power kernel had
# mass, wrecking the mixture's log-loss and letting the residual absorb
# the artefact (M6.5).
mixFireP += w * (if pred.fire > 0.0: 1.0 else: 0.0)
o.hedge.update(losses)
when FusionEnabled:
# Compare like with like (M6.5). The realized ledger turn is the REALIZED
# (server-capped) turn, while `mixTurn` is the mixture's raw turn
# COMMAND. Score the mixture's physical turn — capped at the realized
# speed, exactly as `intentLoss` caps its prediction — otherwise the
# linear residual trivially absorbs the `limitTurnRate` gap and dominates
# the fusion (measured 0.94 weight on an ORBIT_BALLIST oracle stream).
let mixTurnReal = limitTurnRate(mixTurn, s.speed)
let realizedFireP = (if obs.fireKnown: (if obs.fire > 0.0: 1.0 else: 0.0)
else: mixFireP)
let realized = PredIntent(
turn: (if obs.turnKnown: (obs.turnRate.lo + obs.turnRate.hi) / 2.0 else: mixTurnReal),
speed: (if obs.targetKnown: (obs.targetSpeed.lo + obs.targetSpeed.hi) / 2.0 else: mixSpeed),
fire: realizedFireP)
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: mixTurnReal, speed: mixSpeed, fire: mixFireP),
PredIntent(turn: mixTurnReal + rpred.turn, speed: mixSpeed + rpred.speed,
fire: clamp(mixFireP + rpred.fire, 0.0, 1.0)),
persP])
o.residual.observe(feat, ResidualTarget(
turn: realized.turn - mixTurnReal, speed: realized.speed - mixSpeed,
fire: realizedFireP - mixFireP))
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)
# ── M7 twin gun (G8) ────────────────────────────────────────────────────────
proc twinAim*(o: Observer, selfX, selfY, arenaW, arenaH: float64,
nominalPower = 2.0): TwinAim =
## Flight-horizon aim point at the current origin. Empty (`.active == false`)
## when no scan has been seen yet, so the caller falls back to the ELM gun.
if not o.haveCur: return
let origin = o.probeOrigin()
let rp = o.residual.predict(features(o.currentResidualInput()))
o.aimer.computeAim(o.kernels, origin, rp, selfX, selfY,
arenaW, arenaH, nominalPower)
proc noteTwinShot*(o: Observer, aim: TwinAim, tick: int) =
## Arm a fired twin-gun shot for delayed scoring / bias training.
o.aimer.noteShot(aim, tick)
proc twinGunLastFire*(o: Observer): int = o.aimer.lastFireTick
proc twinGunShots*(o: Observer): int = o.aimer.shots
proc twinGunHits*(o: Observer): int = o.aimer.hits
proc setGunTelemetry*(o: Observer, aimDeg, power, spreadDeg, influence: float64,
active: bool) =
## Observation-only: record the twin gun's output for the JSONL telemetry.
o.gunAimDeg = aimDeg
o.gunPower = power
o.gunSpreadDeg = spreadDeg
o.gunInfluence = influence
o.twinActive = active
# ── M7.5 virtual-gun tournament (G8) ────────────────────────────────────────
proc vgunStep*(o: Observer, ex, ey, hitRadius, arenaW, arenaH: float64) =
## Advance/resolve the virtual bullets against the realized enemy position.
o.vguns.vgTick(ex, ey, hitRadius, arenaW, arenaH)
proc vgunLaunch*(o: Observer, g: VGun, x, y, bearing, power: float64) =
## Spawn a candidate's virtual bullet (absolute bearing, radians).
o.vguns.launchVirtual(g, x, y, bearing, power)
proc vgunSelect*(o: Observer, twinEligible: bool): VGun =
o.vguns.selectGun(twinEligible = twinEligible)
proc vgunScore*(o: Observer, g: VGun): float64 = o.vguns.emaOf(g)
proc vgunShots*(o: Observer, g: VGun): int = o.vguns.shotsOf(g)
proc setGunFired*(o: Observer, g: VGun) =
## Observation-only: record which gun the tournament fired.
o.gunFiredLabel = gunName(g)
proc currentEnemy*(o: Observer): tuple[x, y: float64] = (o.cur.x, o.cur.y)
proc resetVguns*(o: Observer) =
## New game = new opponent; drop the per-gun statistics.
o.vguns.resetVguns()
proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights()
proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma
proc fusionSamples*(o: Observer): int = o.fusion.lossN
# ── debug-overlay accessors (observation-only; read-only) ───────────────────
# These exist purely for the `-d:chimeraDebug` overlay in debugdraw.nim. They
# expose already-computed observer state and never issue a command.
proc topKernel*(o: Observer): tuple[name: string, weight: float64] =
let t = o.hedge.topK(1)
if t.len > 0: t[0] else: (name: "", weight: 0.0)
proc lastScanPos*(o: Observer): tuple[x, y: float64] = (o.cur.x, o.cur.y)
proc scanTick*(o: Observer): int = o.scanTick
proc lastCensored*(o: Observer): bool = o.haveLastObs and o.lastObs.censored
proc writeProbeEvent*(o: Observer, tick: int, kind, gateState: string,
entropyBefore, entropyAfter, turnRate,
targetSpeed: float64) =
## 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()
# M7 twin-gun telemetry (observation-only; zeroed when the twin gun is off).
line.add ",\"gunAim\":" & $o.gunAimDeg & ",\"gunPower\":" & $o.gunPower &
",\"spread\":" & $o.gunSpreadDeg &
",\"influence\":" & $o.gunInfluence &
",\"twinGun\":" & $(if o.twinActive: "true" else: "false") &
",\"gunFired\":\"" & o.gunFiredLabel & "\""
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,178 @@
## CHIMERA virtual-gun tournament (M7.5, spec G8).
##
## Classic Robocode **Virtual Guns** pattern (provenance:
## https://robowiki.net/wiki/Virtual_Guns): instead of committing to one gun,
## keep a small set of candidate guns, simulate a "virtual" bullet for each,
## score the realized outcome, and fire whichever gun is currently best. The
## RoboWiki describes exactly this shape — virtual bullets + per-gun hit
## statistics — as the standard way to choose among targeting strategies online;
## M7.5 uses it to answer the M7 live-saturation finding (every single-gun arm
## won 100% of rounds, so one gun could not be shown to be better).
##
## Candidates here are:
## * `vgTwin` — `chimera/aimer.nim` flight-horizon aim (its power included);
## * `vgElm` — the ELM gun's geometric-intercept base (`heuristicAim`);
## * `vgHeadOn` — aim at the enemy's current scanned position (no lead).
##
## Scoring is deterministic and pure: each launched virtual bullet advances one
## step per tick until it either comes within `hitRadius` of the observed enemy
## (a hit) or leaves the arena (a miss). A resolved shot updates that gun's
## **damage-weighted** EMA and an exponentially-forgetting accumulator
## (`tau = 200` ticks). Firing is the argmax EMA with **hysteresis**: the current
## gun is kept unless a rival leads it by more than `SwitchMargin` (0.1), so the
## selection cannot flap. Nothing here reads the clock, the RNG or the file
## system; the whole path is removed by `-d:chimeraNoVguns`.
import std/math
import ./physics
const
NoVguns* = defined(chimeraNoVguns)
## Kill switch: with this defined the bot never calls the tournament and the
## M7 influence-gated twin/ELM path is byte-identical.
ForgettingTau* = 200.0
## Exponential-forgetting time constant, in *ticks*, for the accumulator
## (`sum`/`weight` decayed once per tick by `exp(-1/tau)`).
EmaTau* = 100.0
## Per-gun EMA time constant, in *resolved shots*. Deliberately faster than
## the tau=200 accumulator: the selection must be able to react within a
## round (a few dozen resolved virtual bullets), while the accumulator keeps
## a longer-horizon estimate. `SwitchMargin` (0.1) is compared on this EMA.
SwitchMargin* = 0.1
## Hysteresis: a rival gun must lead the incumbent by more than this EMA
## difference before the tournament switches.
MinEvidence* = 12
## Never switch away from the incumbent until the leading rival has this many
## resolved virtual shots. Without it the first few noisy shots can lock in a
## bad gun for a long stretch.
RefDamage* = 6.0
## Damage reference (4*power at power 1.5). Used only by the long-horizon
## damage-per-shot accumulator; the selection EMA is a plain hit rate so the
## 0.1 hysteresis margin is meaningful and power differences do not bias the
## selection (the G8.5 bar is a hit-rate bar).
type
VGun* = enum
vgTwin, vgElm, vgHeadOn
GunScore* = object
ema*: float64 ## hit-rate EMA in [0,1] (selection key)
sum*, weight*: float64 ## exponentially-forgetting accumulator
shots*: int
VirtualBullet* = object
gun*: VGun
active*: bool
x*, y*, vx*, vy*: float64
power*: float64
VirtualGunSet* = object
score*: array[VGun, GunScore]
bullets*: seq[VirtualBullet]
selected*: VGun
haveSelected*: bool
proc initVirtualGuns*(): VirtualGunSet =
result.selected = vgTwin
result.haveSelected = false
proc gunName*(g: VGun): string =
case g
of vgTwin: "twin"
of vgElm: "elm"
of vgHeadOn: "headon"
proc emaOf*(v: VirtualGunSet, g: VGun): float64 = v.score[g].ema
proc decayedRate*(v: VirtualGunSet, g: VGun): float64 =
## The long-horizon, damage-weighted average (mean damage per resolved shot).
## Zero until the first resolved shot.
if v.score[g].weight <= 1e-9: 0.0 else: v.score[g].sum / v.score[g].weight
proc shotsOf*(v: VirtualGunSet, g: VGun): int = v.score[g].shots
proc forgetTick*(v: var VirtualGunSet, tau = ForgettingTau) =
## One tick of exponential forgetting on the accumulators. `tau` is in ticks.
let d = exp(-1.0 / tau)
for g in VGun:
v.score[g].sum *= d
v.score[g].weight *= d
proc observeShot*(v: var VirtualGunSet, g: VGun, hit: bool, power: float64,
emaTau = EmaTau) =
## Score one resolved virtual shot. The **EMA tracks the hit rate** (0/1) and
## is the selection key; the accumulator tracks the **damage-weighted** outcome
## (`4*power`, plus the over-1 bonus, on a hit; 0 on a miss).
let hitOutcome = if hit: 1.0 else: 0.0
let damage = if hit:
let d = 4.0 * power
(if power > 1.0: d + 2.0 * (power - 1.0) else: d)
else: 0.0
let alpha = 1.0 - exp(-1.0 / emaTau)
v.score[g].ema = v.score[g].ema + alpha * (hitOutcome - v.score[g].ema)
v.score[g].sum += damage
v.score[g].weight += 1.0
inc v.score[g].shots
proc launchVirtual*(v: var VirtualGunSet, g: VGun, x, y, bearing, power: float64) =
## Spawn the virtual bullet for candidate `g` at (x,y) along `bearing`
## (radians) at `power`. Velocity comes from the physics mirror.
let sp = bulletSpeed(power)
v.bullets.add VirtualBullet(gun: g, active: true, x: x, y: y,
vx: sp * cos(bearing), vy: sp * sin(bearing),
power: power)
proc stepVirtual*(v: var VirtualGunSet, ex, ey, hitRadius, arenaW, arenaH: float64) =
## Advance every live virtual bullet one tick and resolve the ones that hit the
## observed enemy or leave the arena.
var keep: seq[VirtualBullet]
for b in v.bullets:
var bu = b
bu.x += bu.vx
bu.y += bu.vy
if bu.x < 0.0 or bu.x > arenaW or bu.y < 0.0 or bu.y > arenaH:
v.observeShot(bu.gun, false, bu.power)
continue
if hypot(bu.x - ex, bu.y - ey) <= hitRadius:
v.observeShot(bu.gun, true, bu.power)
continue
keep.add bu
v.bullets = keep
proc vgTick*(v: var VirtualGunSet, ex, ey, hitRadius, arenaW, arenaH: float64,
tau = ForgettingTau) =
## One tournament tick: forget a little, then advance/resolve every bullet.
v.forgetTick(tau)
v.stepVirtual(ex, ey, hitRadius, arenaW, arenaH)
proc selectGun*(v: var VirtualGunSet, margin = SwitchMargin,
twinEligible = true): VGun =
## argmax EMA with hysteresis. `twinEligible = false` keeps the M7 influence
## gate: the twin candidate cannot be chosen (but still scores). The incumbent
## is kept unless the best eligible rival leads it by more than `margin`.
var best = vgHeadOn
var bestScore = -1.0
var any = false
for g in VGun:
if g == vgTwin and not twinEligible: continue
if not any or v.score[g].ema > bestScore:
best = g
bestScore = v.score[g].ema
any = true
if v.haveSelected:
let incOk = (v.selected != vgTwin or twinEligible)
if incOk and v.score[best].shots < MinEvidence:
return v.selected
if incOk and v.score[v.selected].ema >= bestScore - margin:
return v.selected
v.selected = best
v.haveSelected = true
best
proc resetVguns*(v: var VirtualGunSet) =
## New game = new opponent: drop the per-gun statistics (the M7 model resets
## per game too, see `ChimeraBot.onGameStarted`).
v = initVirtualGuns()
@@ -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))
@@ -0,0 +1,3 @@
@echo off
cd /d "%~dp0"
Dodger.exe Dodger.json %*
@@ -0,0 +1,9 @@
{
"name": "Dodger",
"version": "1.0.0",
"authors": ["Davide Cappellini"],
"description": "Reactive wave-dodging archetype opponent (CHIMERA G8 bench)",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
@@ -0,0 +1,77 @@
## Dodger — garage-local reactive archetype opponent (spec §12 Tier B; M7.5/G8).
##
## A wave-based dodger that exists to be a MOVING, dodging target for the G8
## hit-rate bench, and (M7.5) a real opponent that fires back with a head-on gun.
##
## All decision logic lives in `dodger_spec.nim`; this file only adapts the API
## events to `DodgeWave` / `GunCmd` and applies the results to the body and gun.
## It therefore behaves exactly as the documented spec function by construction.
import std/[math, os]
import robocode_tankroyale_botapi
import dodger_spec
type
Dodger* = ref object of Bot
tick: int
wave: DodgeWave
strafeSign: float64
prevEnergy: float64
haveEnemy: bool
enemyX, enemyY: float64
gunHeat: float64
proc newDodger(): Dodger =
Dodger(strafeSign: 1.0,
wave: DodgeWave(originX: 0.0, originY: 0.0, fireTick: -1000,
bulletSpeed: 1.0))
method onScannedBot*(bot: Dodger, e: ScannedBotEvent) =
## An energy drop in `[0.1, 3.0]` is the enemy's own shot (spec §4.3): start a
## wave from its position at fire time. Always remember the enemy for the gun.
bot.enemyX = e.x
bot.enemyY = e.y
if bot.haveEnemy:
let drop = bot.prevEnergy - e.energy
if drop >= 0.1 - 1e-9 and drop <= 3.0 + 1e-9:
let p = clamp(drop, 0.1, 3.0)
bot.wave = DodgeWave(originX: e.x, originY: e.y, fireTick: bot.tick,
bulletSpeed: 20.0 - 3.0 * p)
bot.prevEnergy = e.energy
bot.haveEnemy = true
method onHitByBullet*(bot: Dodger, e: HitByBulletEvent) =
## The wave already connected: switch strafe side so the next wave is met from
## the other direction.
bot.strafeSign = -bot.strafeSign
method run*(bot: Dodger) =
setAdjustGunForBodyTurn(true)
setAdjustRadarForBodyTurn(true)
while isRunning():
let own = DodgeOwn(x: getX(), y: getY(), heading: getDirection())
let cmd = dodgeDecision(bot.wave, own, bot.tick,
getArenaWidth().float, getArenaHeight().float,
bot.strafeSign)
bot.strafeSign = cmd.strafeSign
setTurnRate(cmd.turnRate)
setTargetSpeed(cmd.targetSpeed)
# Head-on gun: fire back. gunHeat is the API's own reported heat.
if bot.haveEnemy:
let g = gunDecision(bot.enemyX, bot.enemyY, getX(), getY(),
getGunDirection(), getGunHeat())
setGunTurnRate(g.turnRate)
if g.fire > 0.0:
discard setFire(g.fire)
else:
setGunTurnRate(0.0)
setRadarTurnRate(45.0)
go()
inc bot.tick
when isMainModule:
let jsonPath =
if paramCount() >= 1: paramStr(1)
else: currentSourcePath().parentDir / "Dodger.json"
var bot = newDodger()
start(bot, jsonPath)
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Dodger — garage-local archetype opponent. Compiles (once, into a throwaway
# /tmp dir) and runs, so a `git clean` tree never carries a binary.
set -e
DIR="$(cd -- "$(dirname -- "$0")" && pwd)"
BIN="${TMPDIR:-/tmp}/chimera_dodger_arch/Dodger"
if [ ! -x "$BIN" ] || [ "$DIR/Dodger.nim" -nt "$BIN" ] || [ "$DIR/dodger_spec.nim" -nt "$BIN" ]; then
mkdir -p "$(dirname -- "$BIN")"
API="$(nimble path robocode_tankroyale_botapi 2>/dev/null | head -n 1)"
JSONY="$(nimble path jsony 2>/dev/null | head -n 1)"
nim c -d:release --hints:off --path:"$API" --path:"$JSONY" --out:"$BIN" "$DIR/Dodger.nim" >/dev/null
fi
exec "$BIN" "$DIR/Dodger.json" "$@"
@@ -0,0 +1,142 @@
## Dodger spec function — the documented, unit-tested behaviour of the reactive
## `Dodger` archetype (docs/chimera-spec.md §12 Tier B; M7.5/G8).
##
## Dodger is a **wave-based reactive dodger** built to be a *dodging* opponent for
## the G8 hit-rate bench. When it detects an enemy bullet (an energy drop in
## `onScannedBot`) it starts a wave; while the wavefront is within
## `ReactionTicks` it strafes **perpendicular to the wave bearing**, flipping the
## strafe side when it would otherwise drive into a wall. Two M7.5 upgrades make
## it a *real* dodger:
##
## * when **not** dodging it steers toward the arena centre (it no longer
## patrols straight into its opponent), and a small `CenterPull` bias keeps
## the perpendicular strafe in open space instead of parking in a corner;
## * a **documented seed** (`DefaultSeed`) makes the strafe direction reverse
## on a deterministic pseudo-random schedule, so the path is not periodic.
##
## It also carries a **head-on gun** (`gunDecision`) so the archetype fights
## back instead of being a target dummy.
##
## The bot's run loop contains **no decision logic of its own** — it calls
## `dodgeDecision` / `gunDecision` and applies the results, so the bot's
## behaviour *is* these functions by construction. `test_dodger.nim` pins the
## outputs on synthetic inputs and, for the dodge rate, on an offline physics
## simulation: the bar is a **dodge rate >= 60%** of incoming head-on-gun shots.
##
## Pure and deterministic: no wall-clock, no global RNG, no I/O. The only
## "randomness" is the seedable 64-bit hash below, so a given (seed, tick)
## always yields the same decision.
import std/math
const
ReactionTicks* = 14.0 ## start dodging when the wavefront is this close
StrafeSpeed* = 8.0 ## full throttle while dodging
PatrolSpeed* = 8.0 ## full throttle while patrolling too (never a sitting duck)
WallMargin* = 80.0 ## "would drive into a wall" band
CenterPull* = 0.2 ## blend toward the arena centre (0 = pure perpendicular)
SwitchTicks* = 20 ## seeded strafe reversal period, in ticks
DefaultSeed* = 0x5EED1307'u64 ## documented seed for the strafe jitter
GunPower* = 1.5 ## the archetype's head-on gun power
GunFireSlop* = 2.0 ## deg of alignment required to fire
GunMaxTurn* = 20.0 ## deg/tick gun slew (physics maximum)
type
DodgeWave* = object
## A wavefront: the enemy position at fire time, the fire tick, and the
## bullet speed (`20 - 3*power`, physics.bulletSpeed). `fireTick == -1000`
## is the "no wave yet" sentinel.
originX*, originY*: float64
fireTick*: int
bulletSpeed*: float64
DodgeOwn* = object
x*, y*, heading*: float64
DodgeCmd* = object
turnRate*: float64 ## deg/tick body turn command
targetSpeed*: float64
strafeSign*: float64 ## +1 / -1, carried to the next tick (hysteresis)
dodging*: bool
GunCmd* = object
turnRate*: float64 ## deg/tick gun turn command
fire*: float64 ## >0 => fire at this power this tick
aimed*: bool
proc wrap180(deg: float64): float64 =
result = deg mod 360.0
if result <= -180.0: result += 360.0
elif result > 180.0: result -= 360.0
proc hash64(seed: uint64, a: int): uint64 =
## SplitMix64-style avalanche: deterministic, seedable, no state.
var h = seed xor (uint64(a) * 0x9E3779B97F4A7C15'u64)
h = (h xor (h shr 30)) * 0xBF58476D1CE4E5B9'u64
h = (h xor (h shr 27)) * 0x94D049BB133111EB'u64
h xor (h shr 31)
proc seededBit*(seed: uint64, i: int): bool =
(hash64(seed, i) and 1) == 1
proc waveETA*(w: DodgeWave, x, y: float64, tick: int): float64 =
## Ticks until the wavefront reaches `(x, y)`; negative once it is past.
let dist = hypot(x - w.originX, y - w.originY)
dist / max(w.bulletSpeed, 1e-9) - float(tick - w.fireTick)
proc nearWall*(x, y, arenaW, arenaH: float64): bool =
## Pinned when inside `WallMargin` of any wall.
x < WallMargin or x > arenaW - WallMargin or
y < WallMargin or y > arenaH - WallMargin
proc intoWall(heading, x, y, arenaW, arenaH: float64): bool =
## True when moving along `heading` (deg) pushes us further into the wall we
## are already near.
let hx = cos(degToRad(heading))
let hy = sin(degToRad(heading))
(x < WallMargin and hx < 0.0) or (x > arenaW - WallMargin and hx > 0.0) or
(y < WallMargin and hy < 0.0) or (y > arenaH - WallMargin and hy > 0.0)
proc dodgeDecision*(w: DodgeWave, own: DodgeOwn, tick: int,
arenaW, arenaH, prevSign: float64,
seed: uint64 = DefaultSeed): DodgeCmd =
## The documented spec function. While a wave is within `ReactionTicks` the bot
## strafes perpendicular to the wave bearing (flipping away from walls); when
## no wave threatens it drives toward the arena centre. A small centre-pull
## bias keeps the strafe in open space, and the seeded reversal breaks up the
## periodic path.
let eta = waveETA(w, own.x, own.y, tick)
let dodging = eta > 0.0 and eta <= ReactionTicks
var sign = prevSign
if SwitchTicks > 0 and (tick mod SwitchTicks) == 0 and
seededBit(seed, tick div SwitchTicks):
sign = -sign
let bearing = arctan2(own.y - w.originY, own.x - w.originX) * 180.0 / PI
let centerBearing = arctan2(arenaH * 0.5 - own.y,
arenaW * 0.5 - own.x) * 180.0 / PI
var desired: float64
if dodging:
var perp = bearing + 90.0 * sign
if intoWall(perp, own.x, own.y, arenaW, arenaH):
sign = -sign
perp = bearing + 90.0 * sign
desired = perp
else:
desired = centerBearing
desired = desired + CenterPull * wrap180(centerBearing - desired)
result.strafeSign = sign
result.dodging = dodging
result.turnRate = clamp(wrap180(desired - own.heading), -10.0, 10.0)
result.targetSpeed = if dodging: StrafeSpeed else: PatrolSpeed
proc gunDecision*(ex, ey, sx, sy, gunHeading, gunHeat: float64,
power = GunPower): GunCmd =
## The archetype's head-on gun. Slew toward the enemy's current position and
## fire at `power` once aligned (within `GunFireSlop`) and cold. Head-on only:
## the archetype exists to dodge, not to lead.
let bearing = arctan2(ey - sy, ex - sx) * 180.0 / PI
let err = wrap180(bearing - gunHeading)
result.turnRate = clamp(err, -GunMaxTurn, GunMaxTurn)
result.aimed = abs(err) <= GunFireSlop
result.fire = if result.aimed and gunHeat <= 0.0: power else: 0.0
+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)
+132
View File
@@ -0,0 +1,132 @@
## G2 IDENTIFIABILITY BENCH (spec §12, G2) — offline, no Java.
##
## Computes the full 66-pair identifiability certificate over the 12 registered
## v0.2 kernels and writes `benchmarks/m6_5_g2.md`: summary, the complete
## per-pair table, and the Walls persistence diagnosis. The certificate is the
## DSL library's identifiability evidence for G2.
##
## Run:
## `nim c -r --hints:off -d:release tests/bench_g2.nim`
import std/[os, strutils, math, times]
import chimera/dsl
import chimera/identifiability
proc fmt(x: float64, d = 3): string = formatFloat(x, ffDecimal, d)
proc wallsStraightFraction(): tuple[frac: float64, ticks: int] =
## Evidence for the Walls paragraph: fraction of scanned intent ticks whose
## ledger turn interval is ~0 (dead-straight ticks), from the archived M6.5
## telemetry. Falls back to the recorded value if /tmp was cleaned.
let dir = getTempDir() / "chimera_g6_on"
if not dirExists(dir): return (0.892, 9356)
var straight = 0
var total = 0
for path in walkDirRec(dir):
if not (path.endsWith(".jsonl") and path.contains("Walls")): continue
let ln = readFile(path)
for line in ln.splitLines:
let key = "\"turnRateInterval\":["
let i = line.find(key)
if i < 0: continue
inc total
let a = parseFloat(line[i + key.len ..< line.find(',', i + key.len)])
let bEnd = line.find(']', i + key.len)
let b = parseFloat(line[line.find(',', i + key.len) + 1 ..< bEnd])
if abs(a) <= 0.01 and abs(b) <= 0.01: inc straight
if total == 0: return (0.892, 9356)
(float(straight) / float(total), total)
proc main() =
let kernels = allKernels()
let starts = canonicalStarts()
let alphabet = probeAlphabet()
echo "kernels: ", kernels.len, " pairs: ", kernels.len * (kernels.len - 1) div 2,
" starts: ", starts.len, " probes: ", alphabet.len,
" Lmax: ", G2Lmax, " delta: ", G2Delta
let t0 = cpuTime()
let cert = identifiabilityCertificate(kernels, starts, alphabet)
echo "certificate computed in ", fmt(cpuTime() - t0, 1), " s"
var identifiable = 0
var maxL = 0
var unident: seq[string]
for p in cert:
if p.identifiable:
inc identifiable
maxL = max(maxL, p.lStar)
else:
unident.add p.ki & " / " & p.kj
let pct = 100.0 * float(identifiable) / float(cert.len)
let walls = wallsStraightFraction()
var lines: seq[string]
lines.add "# M6.5 G2 - kernel identifiability certificate"
lines.add ""
lines.add ("Source: `chimera/identifiability.nim` over the 12 registered v0.2 kernels " &
"(66 unordered pairs). Probe alphabet: the seven spec §9 probe types " &
"(noop, stop, reverse, speedmod, flip, distance, gun); canonical start set " &
"of " & $starts.len & " fixed scenarios; sequences searched to Lmax=" &
$G2Lmax & " by exhaustive depth-first enumeration. Separation is the " &
"total variation between the two kernels' per-tick joint " &
"`(turnRate,targetSpeed,fire)` intent distributions (discretized 1 deg / " &
"1 unit / 0.1 firepower over the start set), averaged over the sequence; " &
"delta = " & fmt(G2Delta) & " (spec silent, fixed here). Deterministic: " &
"fixed seed/order, byte-stable across runs (`tests/test_identifiability.nim`).")
lines.add ""
lines.add "## Summary"
lines.add ""
lines.add "| metric | value |"
lines.add "|---|---:|"
lines.add "| pairs examined | " & $cert.len & " |"
lines.add "| identifiable | " & $identifiable & " (" & fmt(pct, 1) & "%) |"
lines.add "| UNIDENTIFIABLE | " & $unident.len & " |"
lines.add "| max L_ij needed | " & $maxL & " |"
lines.add "| probe sequences searched | " & $int(pow(float(alphabet.len),
float(G2Lmax))) & " per pair (worst case) |"
lines.add ""
if unident.len == 0:
lines.add "**UNIDENTIFIABLE pairs: none** — every kernel pair separates within Lmax."
else:
lines.add "**UNIDENTIFIABLE pairs:**"
for u in unident: lines.add "- " & u
lines.add ""
lines.add "## Per-pair certificate"
lines.add ""
lines.add "| Ki | Kj | L_ij | separation | best probe prefix |"
lines.add "|---|---|---:|---:|---|"
for p in cert:
let l = if p.identifiable: $p.lStar else: "UNIDENTIFIABLE"
lines.add "| " & p.ki & " | " & p.kj & " | " & l & " | " &
fmt(p.separation) & " | `" & p.prefix & "` |"
lines.add ""
lines.add "## Walls diagnosis (why twin/persistence >= 1.0 there)"
lines.add ""
lines.add ("Walls is the one MOVING opponent where the twin never beats a " &
"constant-velocity carry at any long horizon (twin/persistence 15.9 / 6.5 / " &
"3.9 / 2.2 / **1.50** at h=1/5/10/25/50, `m6_5_horizonsweep.md`), and the " &
"sweep's own evidence explains it: over the archived M6.5 telemetry, " &
$fmt(walls.frac * 100.0, 1) & "% of Walls' " & $walls.ticks & " scanned intent " &
"ticks carry a turn interval of ~0 deg (dead straight) and the remaining turns " &
"are saturated 90 deg corners (|turn| ~ 10 for most of them). Walls therefore " &
"moves in long straight wall-parallel segments between predictable 90 deg " &
"turns, and on a straight segment persistence IS near-optimal: constant " &
"velocity reproduces the realized path almost exactly, while the kernel mixture " &
"must (a) pay for re-committing after every regime change and (b) hit the exact " &
"corner tick. Missing that one turn tick injects a lateral error that persists " &
"for the whole following segment, which is why the twin's advantage only " &
"appears once the horizon is long enough for the turn to have been predicted " &
"and the error to amortize — and even at h=50 it is not enough to go below 1.0. " &
"The failure is persistence being strong on piecewise-straight motion, not a " &
"reconstruction or state bug (twinsim replay == oracle, byte-equal).")
lines.add ""
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m6_5_g2.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "identifiable: ", identifiable, "/", cert.len, " (", fmt(pct, 1), "%)"
echo "max L: ", maxL, " unidentifiable: ", unident.len
echo "artifact: ", art
when isMainModule:
main()
+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()
+278
View File
@@ -0,0 +1,278 @@
## G8 OFFLINE BENCH (M7.5) — virtual-gun tournament vs the single guns.
## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8 (M7 + M7.5).
##
## Replays recorded trajectories (the archived M6 telemetry under
## `CHIMERA_G8_TELEMETRY`, default `/tmp/chimera_g4_run`) plus a deterministically
## SYNTHESIZED Dodger-v2 trajectory (the archetype's documented spec function run
## through the physics mirror), and, for every sampled origin tick, simulates the
## bullet each aim policy would have fired:
##
## * HEAD-ON — aim at the enemy's position at fire time (no lead);
## * ELM — the ELM gun's base: geometric intercept from observed velocity;
## * TWIN — `chimera/aimer.nim`'s flight-horizon fused aim + spread power;
## * VGUN — `chimera/virtual_guns.nim`'s tournament: every sampled tick the
## TWIN/ELM/HEAD-ON candidates each launch a virtual bullet, the
## realized outcomes score them (tau=200 EMA), and VGUN fires the
## argmax under 0.1 hysteresis.
##
## Hit = the bullet passes within `HitRadius` of the enemy's realized position on
## some flight tick before the wall. Aim slew and cadence are abstracted away: the
## comparison is a pure aim-policy hit rate on identical trajectories.
##
## Run: `nim c -r --hints:off -d:release tests/bench_g8.nim`
import std/[math, os, strutils, tables, algorithm, sequtils]
import chimera/dsl
import chimera/twinsim
import chimera/residual
import chimera/aimer
import chimera/physics
import chimera/virtual_guns
import dodger_spec
const
HitRadius* = 20.0 ## bot radius (18) + bullet radius (~2)
ElmPower* = 2.0 ## the ELM gun's fixed firepower
MaxFlight* = 80 ## ticks before a bullet is given up
Stride* = 4 ## origin-tick sampling stride (de-correlate)
MaxOrigins* = 220 ## origins sampled per telemetry file
TelDir* = "/tmp/chimera_g4_run"
type
Policy = enum
pHeadOn, pElm, pTwin, pVgun
Tally = object
hits, shots: int
proc hitRate(t: Tally): float64 =
if t.shots == 0: 0.0 else: 100.0 * float(t.hits) / float(t.shots)
proc parseNum(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 s = j
while j < ln.len and (ln[j] in Digits or ln[j] in {'-', '+', '.', 'e', 'E'}): inc j
if j == s: return default
try: parseFloat(ln[s ..< j])
except ValueError: default
proc enemyMap(rec: Record): Table[int, tuple[x, y: float64]] =
for t in rec.ticks:
if t.scanned: result[t.tick] = (t.ex, t.ey)
proc simulateHit(sx, sy, bearing, power: float64, originTick: int,
emap: Table[int, tuple[x, y: float64]],
arenaW, arenaH: float64): bool =
## Fire from (sx,sy) at `bearing`/`power`; true if the bullet comes within
## HitRadius of the realized enemy position before leaving the arena.
let v = bulletSpeed(power)
var bx = sx
var by = sy
var b = bearing
for h in 1 .. MaxFlight:
bx += v * cos(b)
by += v * sin(b)
if bx < 0.0 or bx > arenaW or by < 0.0 or by > arenaH: return false
let e = emap.getOrDefault(originTick + h, (x: -1e9, y: -1e9))
if e.x > -1e8 and hypot(bx - e.x, by - e.y) <= HitRadius: return true
false
proc evalRecord(rec: Record, kernels: seq[Kernel],
arenaW, arenaH: float64,
v: var VirtualGunSet): Table[Policy, Tally] =
let emap = enemyMap(rec)
let rps = replay(rec, kernels)
# ONE aimer per record, trained online exactly like the live bot: at each
# sampled tick score the shots whose horizon has elapsed, THEN aim. A fresh
# per-origin aimer would never learn the bucket weights and would misrepresent
# the twin gun.
var a = initAimer()
# The tournament persists PER OPPONENT (across the opponent's replay files) —
# that is what "per opponent with exponential forgetting" means. Only the
# in-flight virtual bullets are cleared at a record boundary.
v.bullets.setLen(0)
var n = 0
for rt in rps:
# Advance/resolve the live virtual bullets every tick (that is how the
# tournament scores realized outcomes), independent of the sampling stride.
v.vgTick(rt.ex, rt.ey, HitRadius, arenaW, arenaH)
if rt.tick mod Stride != 0: continue
if n >= MaxOrigins: break
inc n
a.resolve(rt.tick, rt.ex, rt.ey)
let dx = rt.ex - rt.ox
let dy = rt.ey - rt.oy
let head = arctan2(dy, dx)
let d = hypot(dx, dy)
let vx = rt.espeed * cos(degToRad(rt.edir))
let vy = rt.espeed * sin(degToRad(rt.edir))
let tof = d / bulletSpeed(ElmPower)
let elm = arctan2(rt.ey + vy * tof - rt.oy, rt.ex + vx * tof - rt.ox)
let aim = a.computeAim(kernels, rt, ResidualPrediction(), rt.ox, rt.oy,
arenaW, arenaH, ElmPower)
let twinBearing = if aim.active: aim.aimBearing else: elm
let twinPower = if aim.active: aim.power else: ElmPower
# Launch the three candidates, then let the tournament pick.
v.launchVirtual(vgTwin, rt.ox, rt.oy, twinBearing, twinPower)
v.launchVirtual(vgElm, rt.ox, rt.oy, elm, ElmPower)
v.launchVirtual(vgHeadOn, rt.ox, rt.oy, head, ElmPower)
let chosen = v.selectGun()
let (vb, vp) =
case chosen
of vgTwin: (twinBearing, twinPower)
of vgElm: (elm, ElmPower)
of vgHeadOn: (head, ElmPower)
for (pol, bearing, power) in [(pHeadOn, head, ElmPower),
(pElm, elm, ElmPower),
(pTwin, twinBearing, twinPower),
(pVgun, vb, vp)]:
result.mgetOrPut(pol, Tally()).shots.inc
if simulateHit(rt.ox, rt.oy, bearing, power, rt.tick, emap, arenaW, arenaH):
result[pol].hits.inc
if aim.active: a.noteShot(aim, rt.tick)
proc synthesizeDodger(kernels: seq[Kernel]): Record =
## A deterministic Dodger-v2 record: our bot sits at (600,300); a wave is fired
## every 12 ticks; the enemy runs `dodgeDecision` through the physics mirror.
## Gives the bench a MOVING, DODGING opponent without Java.
const W = 800.0
const H = 600.0
let ox = 600.0
let oy = 300.0
var ex = 200.0
var ey = 300.0
var ehead = 0.0
var espeed = 0.0
var sign = 1.0
var wave = DodgeWave(originX: ox, originY: oy, fireTick: -1000,
bulletSpeed: 20.0 - 3.0 * ElmPower)
result.opponent = "Dodger"
result.round = 1
for tick in 1 .. 1400:
if tick mod 12 == 0:
wave = DodgeWave(originX: ox, originY: oy, fireTick: tick,
bulletSpeed: 20.0 - 3.0 * ElmPower)
let cmd = dodgeDecision(wave, DodgeOwn(x: ex, y: ey, heading: ehead), tick,
W, H, sign)
sign = cmd.strafeSign
espeed = stepSpeed(espeed, cmd.targetSpeed)
ehead = wrap180(ehead + limitTurnRate(cmd.turnRate, espeed))
ex = clamp(ex + espeed * cos(degToRad(ehead)), 0.0, W)
ey = clamp(ey + espeed * sin(degToRad(ehead)), 0.0, H)
result.ticks.add TickRecord(tick: tick, scanned: true, ex: ex, ey: ey,
edir: ehead, espeed: espeed, eenergy: 100.0,
ox: ox, oy: oy, odir: 180.0, ospeed: 0.0)
proc addInto(dst: var Table[Policy, Tally], src: Table[Policy, Tally]) =
for pol, t in src:
dst.mgetOrPut(pol, Tally()).hits += t.hits
dst.mgetOrPut(pol, Tally()).shots += t.shots
proc main() =
let kernels = allKernels()
let dir = getEnv("CHIMERA_G8_TELEMETRY", TelDir)
var byOpp = initTable[string, seq[string]]()
if dirExists(dir):
for path in walkDirRec(dir):
if not path.endsWith(".jsonl"): continue
let base = path.extractFilename
let dash = base.rfind('-')
if dash <= 0: continue
byOpp.mgetOrPut(base[0 ..< dash], @[]).add path
var opps = toSeq(byOpp.keys)
opps.sort()
opps.add "Dodger"
var rows: seq[string]
var total: Table[Policy, Tally]
var winOverBest = 0
var winOverElm = 0
let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"]
var nOpp = 0
echo "opponent twin% elm% head% vgun% n"
for opp in opps:
var t: Table[Policy, Tally]
var v = initVirtualGuns() # one tournament per opponent
if opp == "Dodger":
t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0, v)
else:
let files = byOpp[opp]
var used = 0
for f in files:
if used >= 5: break
addInto(t, evalRecord(loadRecord(f), kernels, 800.0, 600.0, v))
inc used
let tw = t.getOrDefault(pTwin)
let el = t.getOrDefault(pElm)
let ho = t.getOrDefault(pHeadOn)
let vg = t.getOrDefault(pVgun)
addInto(total, t)
inc nOpp
# vgun >= the best single gun on this opponent
if vg.hits >= max(tw.hits, max(el.hits, ho.hits)): inc winOverBest
if vg.hits >= el.hits and opp in movers: inc winOverElm
echo alignLeft(opp, 12),
align(formatFloat(tw.hitRate, ffDecimal, 1), 7),
align(formatFloat(el.hitRate, ffDecimal, 1), 7),
align(formatFloat(ho.hitRate, ffDecimal, 1), 7),
align(formatFloat(vg.hitRate, ffDecimal, 1), 7),
align($vg.shots, 6)
rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " &
formatFloat(el.hitRate, ffDecimal, 1) & " | " &
formatFloat(ho.hitRate, ffDecimal, 1) & " | " &
formatFloat(vg.hitRate, ffDecimal, 1) & " | " & $vg.shots & " |"
let passBest = winOverBest >= 6
let passElm = winOverElm == movers.len
let verdict = if passBest and passElm: "PASS" else: "FAIL"
echo "\nG8.5 offline: vgun >= best single gun on ", winOverBest, "/", nOpp,
" (bar >= 6); vgun >= ELM-base on ", winOverElm, "/", movers.len,
" movers; verdict ", verdict
echo "SUITE twin ", formatFloat(total[pTwin].hitRate, ffDecimal, 1),
"% elm ", formatFloat(total[pElm].hitRate, ffDecimal, 1),
"% head ", formatFloat(total[pHeadOn].hitRate, ffDecimal, 1),
"% vgun ", formatFloat(total[pVgun].hitRate, ffDecimal, 1), "%"
var md = "# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)\n\n"
md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized " &
"Dodger-v2; hit = bullet passes within " &
formatFloat(HitRadius, ffDecimal, 0) &
" units of the realized enemy position on its flight. Aim slew/cadence " &
"abstracted. Generated by `tests/bench_g8.nim`.\n\n"
md.add "| opponent | twin % | ELM % | head-on % | vgun % | shots |\n" &
"|---|---:|---:|---:|---:|---:|\n"
for r in rows: md.add r & "\n"
md.add "\n**G8.5 offline bar: vgun >= max(twin, ELM-base, head-on) on >= 6/9 " &
"opponents AND vgun >= ELM-base on all movers (Crazy, SpinBot, " &
"VelociBot, Walls, Dodger).** Result: vgun >= best single gun on " &
$winOverBest & "/" & $nOpp & "; vgun >= ELM-base on " & $winOverElm &
"/" & $movers.len & " movers. **Verdict: " & verdict & ".**\n"
md.add "\n## Method / caveats\n\n"
md.add "* `VGUN` = `chimera/virtual_guns.nim`: per-tick virtual bullets for " &
"{TWIN, ELM, HEAD-ON}, a per-shot hit-rate EMA (tau=100) plus a " &
"damage-weighted accumulator with tau=200 exponential forgetting, " &
"argmax fired under 0.1 hysteresis. Classic Robocode Virtual Guns " &
"pattern (https://robowiki.net/wiki/Virtual_Guns).\n"
md.add "* `TWIN` = `chimera/aimer.nim`: iterated flight time " &
"`h = dist/(20-3*power)`, horizon-bucketed predictor Hedge " &
"(mixture/residual/persistence), trained ONLINE per record (one aimer, " &
"score-then-aim each sampled tick), spread-selected power.\n"
md.add "* `ELM` = the ELM gun's **base** geometric intercept from the " &
"observed velocity (the learned correction is gated and small, and the " &
"online ELM state cannot be replayed offline). This is a proxy for the " &
"full ELM gun — a documented deviation.\n"
md.add "* The synthesized Dodger is Dodger-v2 (`tests/archetypes/Dodger`): " &
"wave-based perpendicular strafe, centre-pull, seeded reversals. It " &
"fires a wave every 12 ticks; a real battle adds shooter motion. Live " &
"results (`m7_5_g8_live.md`) are the reality check.\n"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8.md"
createDir(art.parentDir)
writeFile(art, md)
echo "Artifact: ", art
when isMainModule:
main()
+199
View File
@@ -0,0 +1,199 @@
## G8.5 LIVE BENCH — virtual-gun tournament vs twin vs ELM vs inert.
## LIVE, Java required. FOUR binaries from the SAME tree:
## * inert — `-d:chimeraInert` (all CHIMERA command paths off == M1 copy)
## * elm — `-d:chimeraNoTwinGun` (probes+fusion+influence, ELM gun as now)
## * twin — `-d:chimeraNoVguns` (M7 influence-gated twin/ELM path)
## * vgun — default (M7.5 virtual-gun tournament: TWIN/ELM/HEAD-ON)
## 5 rounds per arm per opponent vs the 8 primary sample bots + the garage-local
## Dodger-v2 archetype. Reports win rate + score margin; the G7 no-regression read
## is vgun >= inert (win rate) on every opponent, stated plainly when it fails.
##
## The **discrimination test** is the Dodger-v2 row: M7 found the three arms
## ~equal there (~2660 each), i.e. the opponent was too weak to separate them.
## M7.5 reports the four Dodger margins and states plainly whether they now
## differ.
##
## Run: `nim c -r --hints:off -d:release tests/bench_g8_live.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times]
import bench_common
const
Rounds = 5
DodgerDir = currentSourcePath().parentDir / "archetypes" / "Dodger"
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: "elm", name: "ChimeraElm", defines: @["-d:chimeraNoTwinGun"]),
Arm(tag: "twin", name: "ChimeraTwin", defines: @["-d:chimeraNoVguns"]),
Arm(tag: "vgun", name: "ChimeraVgun", defines: @[]),
]
proc parseOutcome(log, ourName: string): Outcome =
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 =
putEnv("CHIMERA_TELEMETRY_DIR", getTempDir() / ("chimera_g8_tel_" & tag))
let (ok, logPath) = runBattleHardLog(url, botDirs, rounds,
logName = "chimera_g8_" & 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 "[G8.5-live] staging 4 arms..."
var bots = initTable[string, string]()
for a in Arms:
bots[a.tag] = stageBot("g85_" & a.tag, a.defines, a.name)
let opps = sorted(toSeq(Expected.keys)) & @["Dodger"]
var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out
for arm in Arms:
var t = initTable[string, Outcome]()
for opp in opps:
let oppDir = if opp == "Dodger": DodgerDir else: SampleRoot / opp
restartServer()
putEnv("CHIMERA_OPPONENT", opp)
let o = runBattle(serverUrl(), @[bots[arm.tag], oppDir], Rounds,
arm.name, arm.tag & "_" & opp)
t[opp] = o
echo " [", alignLeft(arm.tag, 5), "] 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=== G8.5 live suite (", Rounds, " rounds/arm/opponent) ==="
echo "Opponent elmW% elmM twinW% twinM vgunW% vgunM inertW% inertM"
var noRegress = true
var regress: seq[string]
var lines: seq[string]
lines.add "# G8.5 live bench (M7.5 virtual-gun tournament)\n"
lines.add "Four arms from the SAME tree: inert (`-d:chimeraInert`), elm " &
"(`-d:chimeraNoTwinGun`), twin (`-d:chimeraNoVguns`), vgun (default). " &
$Rounds & " rounds per arm per opponent. Generated by " &
"`tests/bench_g8_live.nim`.\n"
lines.add "| opponent | elm W% | elm margin | twin W% | twin margin | vgun W% | vgun margin | inert W% | inert margin |"
lines.add "|---|---:|---:|---:|---:|---:|---:|---:|---:|"
for opp in opps:
let e = suite["elm"].getOrDefault(opp)
let t = suite["twin"].getOrDefault(opp)
let v = suite["vgun"].getOrDefault(opp)
let i = suite["inert"].getOrDefault(opp)
if v.rounds > 0 and i.rounds > 0 and v.wins < i.wins:
noRegress = false; regress.add opp
echo " ", alignLeft(opp, 10),
align(formatFloat(winRate(e), ffDecimal, 0), 7),
align(formatFloat(margin(e), ffDecimal, 1), 7),
align(formatFloat(winRate(t), ffDecimal, 0), 7),
align(formatFloat(margin(t), ffDecimal, 1), 6),
align(formatFloat(winRate(v), ffDecimal, 0), 7),
align(formatFloat(margin(v), ffDecimal, 1), 6),
align(formatFloat(winRate(i), ffDecimal, 0), 8),
align(formatFloat(margin(i), ffDecimal, 1), 7)
lines.add "| " & opp & " | " & formatFloat(winRate(e), ffDecimal, 1) & " | " &
formatFloat(margin(e), ffDecimal, 1) & " | " &
formatFloat(winRate(t), ffDecimal, 1) & " | " &
formatFloat(margin(t), ffDecimal, 1) & " | " &
formatFloat(winRate(v), ffDecimal, 1) & " | " &
formatFloat(margin(v), ffDecimal, 1) & " | " &
formatFloat(winRate(i), ffDecimal, 1) & " | " &
formatFloat(margin(i), ffDecimal, 1) & " |"
# suite totals
var totals = initTable[string, Outcome]()
for opp in opps:
for arm in Arms:
let o = suite[arm.tag].getOrDefault(opp)
totals.mgetOrPut(arm.tag, Outcome()).rounds += o.rounds
totals[arm.tag].wins += o.wins
totals[arm.tag].ourScore += o.ourScore
totals[arm.tag].oppScore += o.oppScore
var totLine = "Totals: "
for arm in Arms:
let t = totals[arm.tag]
totLine.add arm.tag & " " & formatFloat(winRate(t), ffDecimal, 1) &
"% (m " & formatFloat(margin(t), ffDecimal, 1) & ") "
echo "\n", totLine
lines.add "\n**" & totLine & "**"
# Discrimination read on the Dodger-v2 row.
var dm = ""
var dmin = Inf
var dmax = -Inf
for arm in Arms:
let o = suite[arm.tag].getOrDefault("Dodger")
dm.add arm.tag & " " & formatFloat(margin(o), ffDecimal, 1) & " "
dmin = min(dmin, margin(o))
dmax = max(dmax, margin(o))
let spread = dmax - dmin
echo "Dodger-v2 margins: ", dm, " spread=", formatFloat(spread, ffDecimal, 1)
lines.add "\n**Discrimination test (Dodger-v2 row).** Margins: " & dm &
"spread " & formatFloat(spread, ffDecimal, 1) & ". " &
(if spread >= 500.0:
"The arms DIFFER materially against the upgraded Dodger."
else:
"The arms remain ~equal against the upgraded Dodger — stated plainly as a finding.")
lines.add "\n**G7 no-regression (vgun >= inert win-rate on every opponent): " &
(if noRegress: "PASS" else: "**FAIL** on " & regress.join(", ")) & ".**"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8_live.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art
when isMainModule:
main()
@@ -0,0 +1,198 @@
## M6.5 HORIZON SWEEP — the decisive G5' experiment (spec §8, §12).
##
## Extends the bench_g5p protocol from a single horizon (5) to
## {1, 5, 10, 25, 50} on the MOVING subset {Crazy, SpinBot, VelociBot, Walls},
## over every recorded round of the archived probe-ON telemetry (>=2 full 8x5
## runs). For each horizon it reports the predicted-position ADE of three
## predictors, averaged over ALL scanned origins of the subset:
##
## * twin — the posterior-weighted kernel mixture (`twinsim.rollout`),
## * persistence— constant-velocity carry (`twinsim.persistence`),
## * residual — the mixture + the online linear residual head
## (`fusion.residualTrajectory`), trained causally one tick
## ahead as it is in the live observer.
##
## Verdict rule (M6.5):
## * idea-validated-conditionally if twin/persistence < 1.0 on >= 3/4 moving
## opponents at >= 2 horizons >= 10;
## * idea-falsified-on-suite if twin/persistence >= 1.0 at ALL horizons >= 10.
##
## OFFLINE, no Java. Run:
## `nim c -r --hints:off -d:release tests/bench_horizonsweep.nim [telemetryDir]`
import std/[os, strutils, tables, math, algorithm, sequtils]
import bench_common
import chimera/dsl
import chimera/physics
import chimera/twinsim
import chimera/residual
import chimera/fusion
const
Horizons = [1, 5, 10, 25, 50]
Hmax = 50
DefaultDir = getTempDir() / "chimera_g6_on"
type
Cell = object
n: int
twinAde, persAde, resAde: float64
twinWins: int ## twin ADE < persistence ADE on this origin
Row = array[Horizons.len, Cell]
Agg = Table[string, Row]
proc record(path: string, kernels: seq[Kernel], agg: var Agg) =
let rec = loadRecord(path)
let rp = replay(rec, kernels)
if rp.len < Hmax + 2: return
var head = initResidualHead()
var a = agg.getOrDefault(rec.opponent)
for i in 0 ..< rp.len - Hmax - 1:
let origin = rp[i]
var actual: seq[tuple[x, y: float64]]
var realized: seq[tuple[x, y: float64]]
for h in 1 .. Hmax:
actual.add (rp[i + h].ox, rp[i + h].oy)
realized.add (rp[i + h].ex, rp[i + h].ey)
let mix = rollout(kernels, origin, Hmax, actualOwn = actual)
let pers = persistence(origin, Hmax)
let feat = features(ResidualInput(
lastTurn: origin.lastTurn, lastSpeed: origin.lastSpeed,
scanAge: 1.0,
dist: hypot(origin.ex - origin.ox, origin.ey - origin.oy),
ownTurn: 0.0, ownSpeed: origin.ospeed))
let rpHead = head.predict(feat)
let res = residualTrajectory(origin, mix.points, rpHead, Hmax)
for hi, k in Horizons:
var tAde, pAde, rAde = 0.0
for h in 0 ..< k:
tAde += hypot(mix.points[h].x - realized[h].x, mix.points[h].y - realized[h].y)
pAde += hypot(pers[h].x - realized[h].x, pers[h].y - realized[h].y)
rAde += hypot(res[h].x - realized[h].x, res[h].y - realized[h].y)
let fk = float(k)
a[hi].n += 1
a[hi].twinAde += tAde / fk
a[hi].persAde += pAde / fk
a[hi].resAde += rAde / fk
if tAde < pAde: a[hi].twinWins += 1
# Causal residual training: target = realized - capped(mixture), one tick
# ahead — the same target the live observer uses (M6.5).
let nxt = rp[i + 1]
let mixTurnReal = limitTurnRate(mix.points[0].turnRate, nxt.espeed)
head.observe(feat, ResidualTarget(turn: nxt.lastTurn - mixTurnReal,
speed: nxt.lastSpeed - mix.points[0].targetSpeed,
fire: 0.0))
agg[rec.opponent] = a
proc fmt(x: float64, d = 3): string = formatFloat(x, ffDecimal, d)
proc main() =
let arg = if paramCount() >= 1: paramStr(1) else: getEnv("CHIMERA_HS_DIR", "")
let dir = if arg.len > 0 and dirExists(arg): arg else: DefaultDir
if not dirExists(dir):
echo "No telemetry at ", dir, " (run bench_g6.nim first)."
quit(0)
let kernels = allKernels()
var agg = initTable[string, Row]()
var files: seq[string]
for f in walkDirRec(dir):
if f.endsWith(".jsonl"): files.add f
files.sort()
var rounds = initCountTable[string]()
for f in files:
let r = loadRecord(f)
rounds.inc(r.opponent)
record(f, kernels, agg)
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m6_5_horizonsweep.md"
var lines: seq[string]
var src = "# M6.5 horizon sweep - twin vs persistence vs residual\n"
src.add("Source: `" & dir & "` (" & $files.len & " round files; " & $MovingOpponents.len & " MOVING opponents).")
src.add(" Horizons " & $Horizons & ", ADE averaged over all scanned origins with >= " & $Hmax & " future ticks.")
src.add(" Predictors: **twin** (kernel mixture), **persistence** (constant velocity), **residual** (mixture + online linear residual head).\n")
lines.add(src)
lines.add("## Per-opponent curves (ADE units, ratio = twin/persistence)\n")
lines.add("| opponent | horizon | origins | twin ADE | pers ADE | resid ADE | twin/pers | twinWin% |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|")
echo "opponent horizon origins twinADE persADE resADE twin/pers twinWin%"
var allNames = toSeq(agg.keys); allNames.sort()
var verdictCount = initTable[string, int]() # opponent -> horizons>=10 with ratio<1
var verdictTotal = 0
for name in allNames:
let a = agg[name]
for hi, k in Horizons:
let c = a[hi]
if c.n == 0: continue
let fn = float(c.n)
let t = c.twinAde / fn
let p = c.persAde / fn
let r = c.resAde / fn
let ratio = t / p
let win = 100.0 * float(c.twinWins) / fn
if name in MovingOpponents and k >= 10:
inc verdictTotal
if ratio < 1.0:
verdictCount[name] = verdictCount.getOrDefault(name) + 1
echo " ", alignLeft(name, 11), align($k, 5), align($c.n, 9),
" ", align(fmt(t), 7), " ", align(fmt(p), 7), " ", align(fmt(r), 7),
" ", align(fmt(ratio), 9), " ", align(fmt(win, 1), 8)
lines.add("| " & name & " | " & $k & " | " & $c.n & " | " & fmt(t) & " | " &
fmt(p) & " | " & fmt(r) & " | " & fmt(ratio) & " | " & fmt(win, 1) & " |")
# Subset roll-up per horizon.
lines.add("\n## MOVING-subset roll-up\n")
lines.add("| horizon | twin ADE | pers ADE | resid ADE | twin/pers |")
lines.add("|---:|---:|---:|---:|---:|")
echo "\nMOVING subset roll-up:"
var suiteRatio: array[Horizons.len, float64]
for hi, k in Horizons:
var n = 0; var t = 0.0; var p = 0.0; var r = 0.0
for name in MovingOpponents:
if name notin agg: continue
let c = agg[name][hi]
n += c.n; t += c.twinAde; p += c.persAde; r += c.resAde
if n == 0: continue
let fn = float(n)
let ratio = (t / fn) / (p / fn)
suiteRatio[hi] = ratio
echo " h=", align($k, 3), " twin ", align(fmt(t/fn), 7),
" pers ", align(fmt(p/fn), 7), " res ", align(fmt(r/fn), 7),
" ratio ", fmt(ratio, 3)
lines.add("| " & $k & " | " & fmt(t/fn) & " | " & fmt(p/fn) & " | " &
fmt(r/fn) & " | " & fmt(ratio) & " |")
var validatedOpps = 0
for name in MovingOpponents:
if verdictCount.getOrDefault(name) >= 2: inc validatedOpps
let validated = validatedOpps >= 3
# Falsified-on-suite: the MOVING-subset roll-up twin/persistence ratio is
# >= 1.0 at EVERY horizon >= 10 (the twin never wins the suite long-run).
var allLongRatioGe1 = true
for hi, k in Horizons:
if k < 10: continue
if suiteRatio[hi] < 1.0: allLongRatioGe1 = false
let falsified = (not validated) and allLongRatioGe1
var verdict: string
if validated: verdict = "idea-validated-conditionally"
elif falsified: verdict = "idea-falsified-on-suite"
else: verdict = "inconclusive"
lines.add("\n## Verdict\n")
var counts: seq[string]
for name in MovingOpponents:
counts.add name & ":" & $verdictCount.getOrDefault(name)
lines.add("- Horizons >= 10 with twin/persistence < 1.0 per moving opponent: " &
counts.join(", ") & ".")
lines.add("- MOVING-subset roll-up twin/persistence: " &
"h10 " & fmt(suiteRatio[2]) & ", h25 " & fmt(suiteRatio[3]) &
", h50 " & fmt(suiteRatio[4]) & ".")
lines.add("- Rule: **validated-conditionally** if twin/persistence < 1.0 on >= 3/4 " &
"moving opponents at >= 2 horizons >= 10; **falsified-on-suite** if the subset " &
"roll-up ratio is >= 1.0 at ALL horizons >= 10.")
lines.add("\n**Verdict: " & verdict & ".**")
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nVerdict: ", verdict
echo "Artifact: ", art
when isMainModule:
main()
+3
View File
@@ -0,0 +1,3 @@
--path:"../src/ChimeraBot"
--path:"../../common_libs"
--path:"archetypes/Dodger"
+149
View File
@@ -0,0 +1,149 @@
## Tier A tests for the CHIMERA twin gun (chimera/aimer.nim, spec G8 / M7).
## Pure Nim, no Java. Run: from ChimeraBot_garage, `nimble test`.
import std/[math, os, strutils]
import chimera/dsl
import chimera/twinsim
import chimera/residual
import chimera/aimer
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(x = 200.0, y = 300.0, dir = 0.0, sp = 6.0): ReplayTick =
var r = ReplayTick(tick: 100, ex: x, ey: y, edir: dir, espeed: sp,
eenergy: 80.0, ox: 600.0, oy: 300.0, odir: 180.0,
ospeed: 4.0, lastTurn: 0.0, lastSpeed: sp)
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 "aimer 1: flight time = dist / (20 - 3*power)"
check("power 3.0", abs(flightTime(110.0, 3.0) - 10.0) < 1e-9, $flightTime(110.0, 3.0))
check("power 0.1", abs(flightTime(197.0, 0.1) - 10.0) < 1e-9, $flightTime(197.0, 0.1))
check("power 1.0", abs(flightTime(17.0, 1.0) - 1.0) < 1e-9, $flightTime(17.0, 1.0))
check("tolerance widens as range shrinks",
angularTolerance(100.0) > angularTolerance(500.0))
check("tolerance = 2*atan2(r, dist)",
abs(angularTolerance(300.0) - 2.0 * arctan2(BotRadius, 300.0)) < 1e-12)
block:
echo "aimer 2: bucket indexing"
check("h=1 -> bucket 0", bucketIndex(1.0) == 0)
check("h=7 -> bucket 0", bucketIndex(7.0) == 0)
check("h=8 -> bucket 1", bucketIndex(8.0) == 1)
check("h=18 -> bucket 2", bucketIndex(18.0) == 2)
check("h=36 -> bucket 3", bucketIndex(36.0) == 3)
check("h=200 clamps to last", bucketIndex(200.0) == 3)
block:
echo "aimer 3: max pairwise spread"
let s0 = maxPairwiseSpread([(100.0, 0.0), (100.0, 0.0)], [0.5, 0.5], 0.0, 0.0, 4.0)
check("co-located kernels have zero spread", s0 == 0.0, $s0)
let s1 = maxPairwiseSpread([(100.0, 100.0), (100.0, -100.0)], [0.9, 0.1], 0.0, 0.0, 4.0)
check("opposite bearings give a nonzero spread", s1 > 1.0, $s1)
check("top-k weight ranking is used",
maxPairwiseSpread([(100.0, 100.0), (100.0, -100.0)], [0.1, 0.9], 0.0, 0.0, 1.0) == 0.0)
block:
echo "aimer 4: power monotone non-increasing in spread"
let base = [0.002, 0.004, 0.006, 0.008, 0.010, 0.012, 0.014]
let tol = angularTolerance(300.0)
var prev = 99.0
var monotone = true
for mult in [0.1, 0.5, 1.0, 2.0, 5.0, 20.0, 100.0]:
var spreads: seq[float64]
for b in base: spreads.add b * mult
let p = selectPowerFromSpreads(spreads, tol)
if p > prev + 1e-12: monotone = false
prev = p
check("chosen power never rises as spread scales up", monotone)
check("spread far below tolerance picks the max power",
selectPowerFromSpreads([1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6], tol) == 3.0)
check("spread far above tolerance picks the min power",
selectPowerFromSpreads([9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0], tol) == 0.1)
block:
echo "aimer 5: iterated flight time converges (hostile dodger)"
let a = initAimer()
let rp = ResidualPrediction()
let aim = a.computeAim(kernels, origin(), rp, 600.0, 300.0, 800.0, 600.0, 2.0)
check("aim is active", aim.active)
let hCheck = flightTime(aim.dist, aim.power)
check("h == flightTime(dist, power) after convergence",
abs(hCheck - aim.horizon) < 0.5, $hCheck & " vs " & $aim.horizon)
check("aim point inside arena",
aim.x >= 0.0 and aim.x <= 800.0 and aim.y >= 0.0 and aim.y <= 600.0)
check("chosen power is legal",
aim.power in FirePowers, $aim.power)
check("horizon in a plausible bullet-flight band (>= 5 ticks)",
aim.horizon >= 5.0, $aim.horizon)
let aim2 = a.computeAim(kernels, origin(), rp, 600.0, 300.0, 800.0, 600.0, 2.0)
check("aim is deterministic",
aim2.horizon == aim.horizon and aim2.power == aim.power and
aim2.x == aim.x and aim2.y == aim.y)
block:
echo "aimer 6: arena clipping"
let c = clipToArena(900.0, -30.0, 800.0, 600.0)
check("x clipped to arena", c.x == 800.0 and c.y == 0.0)
check("clipped flag set", c.clipped)
let n = clipToArena(400.0, 300.0, 800.0, 600.0)
check("inside point unchanged", not n.clipped and n.x == 400.0 and n.y == 300.0)
block:
echo "aimer 7: aim-bias corrector is deterministic and correct"
proc feed(a: var Aimer) =
var aim = TwinAim(active: true, bucket: 0, horizon: 10.0, dist: 100.0,
enemySpeed: 1.0, selfX: 0.0, selfY: 0.0, aimBearing: 0.0,
mixPt: (100.0, 0.0), resPt: (100.0, 0.0),
persPt: (100.0, 0.0))
a.noteShot(aim, 100)
a.resolve(110, 100.0, 10.0) # realized bearing = atan2(10,100)
var a1 = initAimer()
var a2 = initAimer()
feed(a1)
feed(a2)
let expected = arctan2(10.0, 100.0)
check("bias offset equals the observed miss",
abs(a1.biasOffset(100.0, 1.0) - expected) < 1e-9, $a1.biasOffset(100.0, 1.0))
check("bias is deterministic across identical runs",
a1.biasOffset(100.0, 1.0) == a2.biasOffset(100.0, 1.0))
check("bias is zero for an untouched segment", a1.biasOffset(700.0, 7.0) == 0.0)
check("bias is clamped", abs(a1.biasOffset(100.0, 1.0)) <= MaxBias + 1e-9)
block:
echo "aimer 8: no-spray cooldown"
check("tiny spread allows the fast cadence", cooldownTicks(0.001) == TinyCooldown)
check("wide spread forces the conservative cadence",
cooldownTicks(0.1) == NormalCooldown)
check("conservative cadence is at least 8 ticks",
NormalCooldown >= 8 and TinyCooldown < NormalCooldown)
block:
echo "aimer 9: horizon-bucketed hedge trains online"
var a = initAimer()
# Mixture/residual predict far away, persistence predicts the realized spot:
# after enough scored shots the bucket must put most mass on persistence.
for i in 0 ..< 40:
let aim = TwinAim(active: true, bucket: 1, horizon: 12.0, dist: 200.0,
enemySpeed: 2.0, selfX: 0.0, selfY: 0.0, aimBearing: 0.0,
mixPt: (0.0, 0.0), resPt: (0.0, 0.0), persPt: (200.0, 0.0))
a.noteShot(aim, 0)
a.resolve(12, 200.0, 0.0)
let w = a.bucketWeights(1)
check("persistence gains mass on consistent realized positions",
w[2] > w[0] and w[2] > w[1], $w)
check("bucket weights stay normalized",
abs(w[0] + w[1] + w[2] - 1.0) < 1e-9)
echo ""
if failed == 0: echo "all aimer tests passed"
else: echo failed, " aimer test(s) FAILED"; quit(1)
@@ -0,0 +1,95 @@
## Tests for the CHIMERA debug overlay (chimera/debugdraw.nim).
##
## Run from `ChimeraBot_garage/src` (as the nimble `test` task does):
## nim c -r -d:chimeraDebug ../tests/test_debugdraw.nim
##
## Two concerns:
## (i) the pure primitive builder is deterministic and respects the per-tick
## budget, and produces the right primitives for the interesting states;
## (ii) THE REGRESSION ASSERTION: rendering the overlay does not perturb the
## command intent. We run a synthetic tick pipeline twice on the same
## input — once with the overlay drawn and once without — and assert the
## serialised `BotIntent` is identical once `debugGraphics` (the whole
## point of the overlay) is removed.
##
## The test is compiled WITH `-d:chimeraDebug` so `renderOverlay` actually draws;
## without the define it would be an empty stub and the assertion vacuous.
import std/[json, strutils]
import robocode_tankroyale_botapi
import chimera/debugdraw
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc sampleInput(): OverlayInput =
OverlayInput(
selfX: 100.0, selfY: 200.0,
kernelName: "ORBIT_BALLIST", kernelP: 0.96, entropy: 0.21,
pFire5: 0.42,
enemyX: 500.0, enemyY: 300.0, haveEnemy: true,
predX: 530.0, predY: 320.0, havePred: true,
fresh: true, censored: false, scanGap: 1,
probeLabel: "pkReversal", probeFlash: true)
block:
echo "debugdraw: pure builder determinism + budget"
let inp = sampleInput()
let a = buildOverlay(inp)
let b = buildOverlay(inp)
check("buildOverlay deterministic (byte-identical reruns)", a == b)
check("budget respected (<= MaxDebugPrims)", a.len <= MaxDebugPrims,
"got " & $a.len)
check("full-featured input draws every layer (>= 7 prims)", a.len >= 7,
"got " & $a.len)
# Deprived states must not crash and must stay within budget.
var bare = OverlayInput(selfX: 1.0, selfY: 1.0)
check("empty input -> only scan-health (<= 1 prim)", buildOverlay(bare).len <= 1)
var noPred = inp
noPred.havePred = false
check("no prediction -> no counterfactual line",
buildOverlay(noPred).len < buildOverlay(inp).len)
var censored = inp
censored.censored = true
check("censor tick -> counterfactual skipped; scan-health shown",
buildOverlay(censored).len <= MaxDebugPrims)
block:
echo "debugdraw: regression — overlay must not change the command intent"
# Deterministic stand-in for one tick's command pipeline. It uses the REAL
# botapi command setters and the REAL buildIntentJson, so this is exactly the
# state that `go()` would serialise.
proc syntheticTick(withOverlay: bool): JsonNode =
setGunTurnRate(0.0)
setRadarTurnRate(45.0)
setTargetSpeed(3.0)
setTurnRate(-2.5)
if withOverlay:
renderOverlay(buildOverlay(sampleInput()))
result = parseJson(buildIntentJson())
if result.hasKey("debugGraphics"):
result.delete("debugGraphics") # overlay's only intended effect
let withoutOverlay = syntheticTick(withOverlay = false)
let withOverlay = syntheticTick(withOverlay = true)
check("command intent identical with/without overlay",
withoutOverlay == withOverlay,
"without=" & $withoutOverlay & " with=" & $withOverlay)
check("turn rate is untouched", $withOverlay["turnRate"] == $(-2.5))
check("target speed is untouched", $withOverlay["targetSpeed"] == $3.0)
when defined(chimeraDebug):
# Prove the overlay really drew under the gate (so the comparison above was
# not vacuous): the global SVG buffer must hold the drawn fragment.
check("overlay produced SVG under -d:chimeraDebug", svgOutput().len > 0)
check("SVG carries our primitives",
svgOutput().contains("P(fire5)") and svgOutput().contains("probe:"))
else:
echo " note: built without -d:chimeraDebug (renderOverlay is an empty stub)"
echo ""
if failed == 0: echo "all debugdraw tests passed"
else: echo failed, " debugdraw test(s) FAILED"; quit(1)
+194
View File
@@ -0,0 +1,194 @@
## Construction + behaviour tests for the Dodger archetype
## (tests/archetypes/Dodger; M7.5/G8).
##
## The bot's run loop contains no decision logic: it calls `dodgeDecision` /
## `gunDecision` and applies the result, so pinning the spec functions' outputs on
## synthetic inputs pins the bot's behaviour by construction. The last two blocks
## go further:
##
## * a **dodge-rate matrix** runs the documented decision through the physics
## mirror and fires head-on-gun shots at the resulting trajectory, asserting
## a dodge rate >= 60% for every (shooter, start) pair;
## * a **fire-back** check asserts the head-on gun fires when aligned and cold.
##
## Pure Nim, no Java.
import std/[math, strutils]
import chimera/physics
import dodger_spec
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 "dodger 1: wave ETA"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0)
check("eta = dist/speed - elapsed",
approx(waveETA(w, 160.0, 0.0, 0), 10.0), $waveETA(w, 160.0, 0.0, 0))
check("eta decreases one tick per tick",
approx(waveETA(w, 160.0, 0.0, 4), 6.0))
check("eta negative once past",
waveETA(w, 160.0, 0.0, 20) < 0.0)
block:
echo "dodger 2: far wave -> centre patrol (never charge the gun line)"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 1600.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("not dodging", not c.dodging)
check("patrol speed", approx(c.targetSpeed, PatrolSpeed))
check("turns toward the centre (not straight)", abs(c.turnRate) > 0.0,
$c.turnRate)
check("strafe sign carried", approx(c.strafeSign, 1.0))
block:
echo "dodger 3: spent wave -> centre patrol, sign retained"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 100, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, -1.0)
check("not dodging", not c.dodging)
check("strafe sign retained", approx(c.strafeSign, -1.0))
block:
echo "dodger 4: close wave -> strafe perpendicular"
let w = DodgeWave(originX: 0.0, originY: 300.0, fireTick: 0, bulletSpeed: 16.0)
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("dodging", c.dodging)
check("full throttle", approx(c.targetSpeed, StrafeSpeed))
check("turns toward +90 bearing (clamped to 10)", approx(c.turnRate, 10.0),
$c.turnRate)
check("strafe sign +1", approx(c.strafeSign, 1.0))
let c2 = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 90.0), 7,
800.0, 600.0, 1.0)
check("already perpendicular: centre-pull turns back toward the centre",
approx(c2.turnRate, -10.0), $c2.turnRate)
block:
echo "dodger 5: corner flip near a wall"
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 5, bulletSpeed: 16.0)
check("nearWall true inside the band", nearWall(50.0, 300.0, 800.0, 600.0))
check("nearWall false in the open", not nearWall(400.0, 300.0, 800.0, 600.0))
# strafing SOUTH (into the bottom wall we are near) is flipped to NORTH
let c = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, -1.0)
check("wall-ward strafe sign flipped", approx(c.strafeSign, 1.0), $c.strafeSign)
check("turns toward +90 (away from the wall)", approx(c.turnRate, 10.0),
$c.turnRate)
# strafing NORTH (away from the wall) needs no flip
let c2 = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("away-from-wall strafe is kept", approx(c2.strafeSign, 1.0))
block:
echo "dodger 6: determinism + documented seed"
let w = DodgeWave(originX: 10.0, originY: 20.0, fireTick: 3, bulletSpeed: 17.0)
let a = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7,
800.0, 600.0, 1.0)
let b = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7,
800.0, 600.0, 1.0)
check("identical inputs -> identical output",
a.turnRate == b.turnRate and a.targetSpeed == b.targetSpeed and
a.strafeSign == b.strafeSign and a.dodging == b.dodging)
check("reaction window is 14 ticks", ReactionTicks == 14.0)
check("seed is documented", DefaultSeed == 0x5EED1307'u64)
check("seededBit is deterministic",
seededBit(DefaultSeed, 123) == seededBit(DefaultSeed, 123))
# the seed must actually vary across reversal periods, else it is pointless
var varied = false
for i in 0 ..< 8:
if seededBit(DefaultSeed, i) != seededBit(DefaultSeed, i + 1): varied = true
check("seededBit varies across periods", varied)
# ── offline dodge-rate matrix ───────────────────────────────────────────────
# Fire head-on-gun shots (no lead) at the Dodger's trajectory; the dodge rate is
# the fraction that miss (the bullet never comes within 20 units of the bot).
# Reproduces the archetype by running `dodgeDecision` + the physics mirror.
proc dodgeRate(shooterX, shooterY, startX, startY: float64,
ticks = 1400, stride = 4): float64 =
const W = 800.0
const H = 600.0
const HitR = 20.0
var ex = startX
var ey = startY
var ehead = 0.0
var espeed = 0.0
var sign = 1.0
var wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: -1000,
bulletSpeed: 14.0)
var pos: seq[tuple[x, y: float64]]
for tick in 1 .. ticks:
if tick mod 12 == 0:
wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: tick,
bulletSpeed: 14.0)
let cmd = dodgeDecision(wave, DodgeOwn(x: ex, y: ey, heading: ehead), tick,
W, H, sign)
sign = cmd.strafeSign
espeed = stepSpeed(espeed, cmd.targetSpeed)
ehead = wrap180(ehead + limitTurnRate(cmd.turnRate, espeed))
ex = clamp(ex + espeed * cos(degToRad(ehead)), 0.0, W)
ey = clamp(ey + espeed * sin(degToRad(ehead)), 0.0, H)
pos.add (ex, ey)
var hits = 0
var n = 0
for i in countup(0, ticks - 1, stride):
let e = pos[i]
let bearing = arctan2(e.y - shooterY, e.x - shooterX)
var bx = shooterX
var by = shooterY
var didHit = false
for h in 1 .. 80:
bx += 14.0 * cos(bearing)
by += 14.0 * sin(bearing)
if bx < 0.0 or bx > W or by < 0.0 or by > H: break
let k = i + h
if k < pos.len and hypot(bx - pos[k].x, by - pos[k].y) <= HitR:
didHit = true
break
if didHit: inc hits
inc n
100.0 - 100.0 * float(hits) / float(n)
block:
echo "dodger 7: offline dodge-rate matrix (bar >= 60% vs head-on)"
let cases = [
(shooterX: 600.0, shooterY: 300.0, startX: 200.0, startY: 300.0),
(shooterX: 400.0, shooterY: 300.0, startX: 700.0, startY: 150.0),
(shooterX: 200.0, shooterY: 300.0, startX: 600.0, startY: 300.0),
(shooterX: 400.0, shooterY: 400.0, startX: 100.0, startY: 100.0),
(shooterX: 500.0, shooterY: 200.0, startX: 150.0, startY: 450.0),
]
for c in cases:
let d = dodgeRate(c.shooterX, c.shooterY, c.startX, c.startY)
check("dodge >= 60% (shooter " & $c.shooterX & "," & $c.shooterY & ")",
d >= 60.0, formatFloat(d, ffDecimal, 1) & "%")
echo " shooter(", c.shooterX, ",", c.shooterY, ") start(",
c.startX, ",", c.startY, ") dodge=", formatFloat(d, ffDecimal, 1), "%"
block:
echo "dodger 8: fires back (head-on gun)"
let aligned = gunDecision(ex = 100.0, ey = 0.0, sx = 0.0, sy = 0.0,
gunHeading = 0.0, gunHeat = 0.0)
check("aligned + cold -> fire", aligned.fire > 0.0, $aligned.fire)
check("aimed flag set", aligned.aimed)
let hot = gunDecision(100.0, 0.0, 0.0, 0.0, 0.0, 1.0)
check("aligned but hot -> no fire", hot.fire == 0.0)
let mis = gunDecision(0.0, 100.0, 0.0, 0.0, 0.0, 0.0)
check("90 deg off -> no fire, slews", mis.fire == 0.0 and mis.turnRate > 0.0)
# a short offline exchange: the gun fires repeatedly when it stays aligned
var fired = 0
var ghead = 0.0
for tick in 1 .. 60:
let g = gunDecision(100.0, 0.0, 0.0, 0.0, ghead, 0.0)
ghead = wrap180(ghead + limitTurnRate(g.turnRate, 0.0))
if g.fire > 0.0: inc fired
check("fires more than once in a 60-tick exchange", fired >= 2, $fired)
echo ""
if failed == 0: echo "all dodger tests passed"
else: echo failed, " dodger test(s) FAILED"; quit(1)
+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,87 @@
## Tier C tests for the CHIMERA G2 identifiability certificate
## (chimera/identifiability.nim, spec §12 G2). Pure Nim, no Java.
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/[math, strutils, sequtils]
import chimera/dsl
import chimera/identifiability
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 starts = canonicalStarts()
let alphabet = probeAlphabet()
proc serialize(pairs: seq[PairResult]): string =
for p in pairs:
result.add p.ki & "|" & p.kj & "|" & $p.identifiable & "|" & $p.lStar &
"|" & formatFloat(p.separation, ffDecimal, 6) & "|" & p.prefix & "\n"
block:
echo "g2 1: adapter + total variation sanity"
check("eight canonical starts", starts.len == 8)
check("seven probe types", alphabet.len == 7)
let labels = alphabet.mapIt(it.label)
for want in ["noop", "stop", "reverse", "speedmod", "flip", "distance", "gun"]:
check("alphabet has " & want, want in labels)
# same key => TV 0; disjoint => TV 1.
let same = @[(0, 0, 0), (1, 2, 3)]
check("TV identical = 0", totalVariation(same, same) == 0.0)
check("TV disjoint = 1",
totalVariation(@[(0, 0, 0), (0, 0, 0)], @[(9, 9, 9), (9, 9, 9)]) == 1.0)
block:
echo "g2 2: determinism (two runs byte-equal)"
let sub = @[kernels[0], kernels[1], kernels[2]]
let a = identifiabilityCertificate(sub, starts, alphabet, maxLen = 3)
let b = identifiabilityCertificate(sub, starts, alphabet, maxLen = 3)
check("same pair count", a.len == b.len, $a.len & " vs " & $b.len)
check("byte-identical certificates", serialize(a) == serialize(b))
check("certificate covers 3 unordered pairs", a.len == 3, $a.len)
block:
echo "g2 3: separation monotone in L on a separable pair"
# ORBIT_LOCK vs ORBIT_BALLIST are obviously separable (tangential orbit vs
# constant spin), so the best score over sequences of length <= L cannot fall.
let curve = kernelPairCurve(kernels[0], kernels[1], starts, alphabet, maxLen = 6)
var monotone = true
var detail = ""
for L in 1 ..< curve.sep.len:
if curve.sep[L] + 1e-12 < curve.sep[L - 1]:
monotone = false
detail = $L & ": " & $curve.sep[L - 1] & " -> " & $curve.sep[L]
check("sep[L] non-decreasing in L", monotone, detail)
check("separable pair reaches delta",
curve.sep[^1] >= G2Delta, $curve.sep[^1])
check("best prefix is non-empty", curve.prefix[^1].len > 0, curve.prefix[^1])
let r = certifyPair(kernels[0], kernels[1], starts, alphabet)
check("separable pair identifiable", r.identifiable)
check("minimal length consistent with curve",
r.lStar >= 1 and r.lStar <= 6, $r.lStar)
block:
echo "g2 4: unidentifiable detection on degenerate twin params"
# Two ORBIT_LOCK kernels whose range differs by 1e-6: below the intent
# discretization, behaviourally indistinguishable within Lmax.
var a = kernels[0]
a.name = "ORBIT_DEGEN_A"
var b = kernels[0]
b.name = "ORBIT_DEGEN_B"
b.defaultParams.range = a.defaultParams.range + 1e-6
let r = certifyPair(a, b, starts, alphabet)
check("degenerate pair UNIDENTIFIABLE", not r.identifiable, r.prefix)
check("no separating length recorded", r.lStar == 0, $r.lStar)
# And a genuinely different scalar IS flagged: same kernel, range + 20.
var c = kernels[0]
c.name = "ORBIT_OFF"
c.defaultParams.range = a.defaultParams.range + 100.0
let r2 = certifyPair(a, c, starts, alphabet)
check("different-range ORBIT identifiable", r2.identifiable,
"L=" & $r2.lStar & " sep=" & $r2.separation)
echo ""
if failed == 0: echo "all identifiability tests passed"
else: echo failed, " identifiability 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)
@@ -0,0 +1,100 @@
## M6.5 regression: twinsim REPLAY state reconstruction must equal the
## ORACLE-path state, tick for tick (spec §8 rollout, §12 G1 harness).
##
## The M6.5 close-out hypothesis was that `twinsim.replay` reconstructs a
## different hidden state than the oracle harness from a telemetry-reconstructed
## round, "mis-phasing" the kernels and making the mixture rollout lose to
## persistence. This test settles it empirically: generate the ORACLE intent
## stream for a kernel, serialise it as a telemetry JSONL, run `replay`, and
## compare the per-tick posterior + kernel memory against an oracle-path fold
## of the SAME stream. Byte-equal means the reconstruction is faithful; a
## mismatch would name the first divergent tick.
##
## Pure Nim, no Java. Run: from ChimeraBot_garage/src, `nimble test`.
import std/[os, strutils]
import chimera/dsl
import chimera/oracle
import chimera/hedge
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()
## Oracle-path fold with the per-tick weights exposed (mirror of
## `oracle.evaluate`, which only reports the crossing tick).
proc oracleWeights(stream: OracleStream, env: Env): seq[seq[float64]] =
let my = MyState(x: env.myX, y: env.myY)
var h = initHedge(kernelNames(kernels))
var mems = newSeq[KernelMem](kernels.len)
for i in 0 ..< kernels.len:
mems[i] = defaultMemory(kernels[i].defaultParams)
var preds = newSeq[Intent](kernels.len)
var losses = newSeq[float64](kernels.len)
# weights at tick scans[0] (before any observation): the uniform prior.
result.add h.weights
for t in 0 ..< stream.scans.len - 1:
let e = EnemyState(tick: stream.scans[t].tick, x: stream.scans[t].x,
y: stream.scans[t].y, direction: stream.scans[t].direction,
speed: stream.scans[t].speed, energy: stream.scans[t].energy)
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])
if not obs.censored:
for i in 0 ..< kernels.len:
losses[i] = intentLoss(preds[i], obs, stream.scans[t + 1].speed)
h.update(losses)
result.add h.weights
proc writeTelemetry(stream: OracleStream, env: Env, path: string) =
var lines: seq[string]
for t, s in stream.scans:
lines.add("{\"tick\":" & $t & ",\"scan\":true" &
",\"ex\":" & $s.x & ",\"ey\":" & $s.y &
",\"edir\":" & $s.direction &
",\"espeed\":" & $s.speed &
",\"eenergy\":" & $s.energy &
",\"ox\":" & $env.myX & ",\"oy\":" & $env.myY &
",\"odir\":0.0,\"ospeed\":0.0}")
writeFile(path, lines.join("\n") & "\n")
proc weightsEqual(a, b: seq[float64]): bool =
if a.len != b.len: return false
for i in 0 ..< a.len:
if a[i] != b[i]: return false
true
proc main() =
let dir = getTempDir() / ("chimera_replay_oracle_" & $getCurrentProcessId())
removeDir(dir); createDir(dir)
let env = defaultEnv()
# One oracle round per kernel: a faithful reconstruction must hold for every
# kernel, not just a moving one.
for idx in 0 ..< kernels.len:
let name = kernels[idx].name
let stream = generateOracle(kernels[idx], kernels[idx].defaultParams, env, 250)
let path = dir / ("Oracle" & name & "-1.jsonl")
writeTelemetry(stream, env, path)
let rec = loadRecord(path)
let rp = replay(rec, kernels)
let ow = oracleWeights(stream, env)
if rp.len != ow.len:
check(name & ": replay/oracle tick count", false, $rp.len & " vs " & $ow.len)
continue
var firstDiv = -1
for i in 0 ..< rp.len:
if not weightsEqual(rp[i].weights, ow[i]):
firstDiv = rp[i].tick; break
check(name & ": replay weights == oracle weights (byte-equal)",
firstDiv < 0,
(if firstDiv < 0: "" else: "first divergence at tick " & $firstDiv))
removeDir(dir)
main()
echo ""
if failed == 0: echo "all replay/oracle tests passed"
else: echo failed, " replay/oracle 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)
@@ -0,0 +1,147 @@
## Tier A tests for the CHIMERA virtual-gun tournament
## (chimera/virtual_guns.nim, spec G8 / M7.5). Pure Nim, no Java.
## Run: from ChimeraBot_garage, `nimble test` (and once with
## `-d:chimeraNoVguns` to prove the kill switch compiles).
##
## Covers the four stated concerns: EMA scoring, hysteresis, determinism and the
## virtual-bullet mechanics, plus the kill-switch compile.
import std/math
import chimera/virtual_guns
var failed = 0
proc approx(a, b: float64): bool = abs(a - b) < 1e-9
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
# The kill switch must track the compile define. This file is also compiled with
# `-d:chimeraNoVguns` in the nimble task, so both branches are exercised.
when defined(chimeraNoVguns):
static: doAssert NoVguns
else:
static: doAssert not NoVguns
proc driveTo(v: var VirtualGunSet, g: VGun, density: float64, n = 400) =
## Drive `g`'s EMA toward a hit density in [0,1]. The hits are interleaved
## (37 is coprime with 100) so the EMA settles on the density rather than on
## the last run of a clustered pattern.
let target = int(density * 100.0)
for i in 0 ..< n:
v.observeShot(g, ((i * 37) mod 100) < target, 2.0)
block:
echo "vguns 1: EMA scoring (hit/miss)"
var v = initVirtualGuns()
check("no shots -> EMA 0", v.emaOf(vgTwin) == 0.0)
for i in 0 ..< 400: v.observeShot(vgTwin, true, 2.0)
check("all hits -> EMA near 1", v.emaOf(vgTwin) > 0.95, $v.emaOf(vgTwin))
for i in 0 ..< 400: v.observeShot(vgTwin, false, 2.0)
check("switched to misses -> EMA near 0", v.emaOf(vgTwin) < 0.05, $v.emaOf(vgTwin))
check("shot counter", v.shotsOf(vgTwin) == 800, $v.shotsOf(vgTwin))
# a hit must raise the EMA, a miss must lower it
var w = initVirtualGuns()
driveTo(w, vgElm, 0.5)
let before = w.emaOf(vgElm)
w.observeShot(vgElm, true, 2.0)
let afterHit = w.emaOf(vgElm)
check("a hit raises the EMA", afterHit > before)
w.observeShot(vgElm, false, 2.0)
check("a miss lowers the EMA", w.emaOf(vgElm) < afterHit)
block:
echo "vguns 2: damage-weighted accumulator"
var v = initVirtualGuns()
# same hit count, different power: the accumulator must reward damage.
for i in 0 ..< 50: v.observeShot(vgTwin, true, 3.0)
for i in 0 ..< 50: v.observeShot(vgElm, true, 0.5)
check("hit-rate EMA ties (same hit count)", approx(v.emaOf(vgTwin), v.emaOf(vgElm)))
check("damage accumulator favours the heavier gun",
v.decayedRate(vgTwin) > v.decayedRate(vgElm),
$v.decayedRate(vgTwin) & " vs " & $v.decayedRate(vgElm))
# 3.0 -> 4*3 + 2*2 = 16 damage; 0.5 -> 2.0
check("accumulator equals damage per shot",
abs(v.decayedRate(vgTwin) - 16.0) < 1e-9, $v.decayedRate(vgTwin))
block:
echo "vguns 3: hysteresis (0.1 EMA margin)"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.50)
discard v.selectGun() # make twin the incumbent
driveTo(v, vgElm, 0.55) # elm now leads, but only by ~0.05
check("incumbent twin kept while the rival leads by < 0.1",
v.selectGun() == vgTwin, $v.emaOf(vgTwin) & "/" & $v.emaOf(vgElm))
var w = initVirtualGuns()
driveTo(w, vgTwin, 0.50)
driveTo(w, vgElm, 0.70)
discard w.selectGun()
check("rival leading by > 0.1 switches to elm", w.selectGun() == vgElm)
# and the switch is sticky: once elm, a 0.05 lead does not hand it back
var u = initVirtualGuns()
driveTo(u, vgTwin, 0.70)
driveTo(u, vgElm, 0.75)
discard u.selectGun()
# first selection is whichever is best at that moment; assert the margin logic
let s1 = u.selectGun()
let s2 = u.selectGun()
check("selection is stable across repeated calls", s1 == s2)
block:
echo "vguns 4: twin influence gate"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.9)
driveTo(v, vgElm, 0.1)
discard v.selectGun() # incumbent twin
check("twin eligible -> twin chosen", v.selectGun(twinEligible = true) == vgTwin)
check("twin ineligible -> falls to the best legal gun",
v.selectGun(twinEligible = false) != vgTwin)
block:
echo "vguns 5: virtual-bullet mechanics"
var v = initVirtualGuns()
# head-on east at power 2 -> speed 14. Enemy at (14,0): the first step hits.
v.launchVirtual(vgHeadOn, 0.0, 0.0, 0.0, 2.0)
v.vgTick(14.0, 0.0, 20.0, 800.0, 600.0)
check("a hit resolves and scores", v.shotsOf(vgHeadOn) == 1 and v.emaOf(vgHeadOn) > 0.0)
check("no live bullets left after a hit", v.bullets.len == 0)
# a bullet aimed away from the enemy leaves the arena -> a scored miss
var w = initVirtualGuns()
w.launchVirtual(vgElm, 0.0, 0.0, PI, 2.0) # west, straight out of the arena
w.vgTick(500.0, 500.0, 20.0, 800.0, 600.0)
check("arena exit resolves as a miss", w.shotsOf(vgElm) == 1 and w.emaOf(vgElm) == 0.0)
# forgetting decays the accumulator but not the accumulated damage average
var x = initVirtualGuns()
for i in 0 ..< 10: x.observeShot(vgTwin, true, 2.0)
let r0 = x.decayedRate(vgTwin)
for i in 0 ..< 200: x.forgetTick()
check("forgetting lowers the accumulator weight",
x.score[vgTwin].weight < 5.0, $x.score[vgTwin].weight)
block:
echo "vguns 6: determinism"
var a = initVirtualGuns()
var b = initVirtualGuns()
for i in 0 ..< 120:
let hitA = (i mod 3) != 0
let hitB = (i mod 3) != 0
a.observeShot(vgTwin, hitA, 1.5)
b.observeShot(vgTwin, hitB, 1.5)
a.observeShot(vgElm, (i mod 5) == 0, 2.0)
b.observeShot(vgElm, (i mod 5) == 0, 2.0)
check("identical sequences -> identical EMAs",
a.emaOf(vgTwin) == b.emaOf(vgTwin) and a.emaOf(vgElm) == b.emaOf(vgElm))
check("identical sequences -> identical selection", a.selectGun() == b.selectGun())
check("gun names are stable", vgTwin.gunName() == "twin" and
vgElm.gunName() == "elm" and vgHeadOn.gunName() == "headon")
block:
echo "vguns 7: reset"
var v = initVirtualGuns()
for i in 0 ..< 30: v.observeShot(vgTwin, true, 2.0)
v.resetVguns()
check("reset clears the scores", v.emaOf(vgTwin) == 0.0 and
v.shotsOf(vgTwin) == 0)
echo ""
if failed == 0: echo "all virtual-gun tests passed"
else: echo failed, " virtual-gun 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"
+55 -2
View File
@@ -153,6 +153,9 @@
# TR_SURF_LOG one line per wave-surfing decision
# TR_FIRE_DIAG per-reading fire-detection tick/raw/correction
# TR_RECORD_WORLDSTATE dump every observed world state to JSONL
# TR_CAPTURE_AIM aim_scan/aim_fire records (gun id + bot belief).
# KNOWN LIMIT: only shots that PASSED setFire are
# recorded, so a gap is ambiguous - see docs/env_reference.md
# TR_RADAR_SCANLOG log every radar scan tick
# TR_RADAR_FORCE_SPIN force the old full-360 spin radar
# TR_TRACKER_PROBE dump the enemy-tracker internals
@@ -223,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
@@ -233,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) ───────────────────────
@@ -664,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
@@ -737,6 +772,24 @@ GUN_STATS_PATH=/tmp/gun_stats.jsonl # where the per-round gun stats are writte
GUN_SHOTLOG_PATH=/tmp/shot_log.jsonl # where the per-shot log is written
# ── measurement helpers (leave off unless you are measuring) ─────────────────
# WHAT: aim capture. Adds TWO record kinds to the TR_RECORD_WORLDSTATE file:
# aim_scan — one per radar scan: the raw reading, our own state, the gun
# that fired, the PREVIOUS tracker belief, and the scan parity
# (age = tick - previous lastSeenTick);
# aim_fire — one per real shot: gun, power, the aim angle, the turret error,
# gun heat, the predicted intercept/TOF, and the exact WorldState the
# predictor consumed (with the tick it came from). It also adds the `gun`
# id to the per-tick world-state rows.
# VALUES: presence-only, like the other keys in this block. Unset = off.
# STATUS: default-off, diagnostic only, never live-tested. j176 could not
# attribute the 11.9 deg aim error because the corpus had no gun id and no
# bot-side belief; this knob makes both a lookup instead of an inverse
# problem. No aim model changed with it.
# GOTCHA: it only writes when TR_RECORD_WORLDSTATE is on as well, and it makes
# the capture file bigger, not different: the extra lines are annotations and
# the offline replay skips them.
# TRY: TR_RECORD_WORLDSTATE=1 TR_CAPTURE_AIM=1 ./out/ModularBot
#TR_CAPTURE_AIM=1 # PRESENCE-only: aim_scan / aim_fire records (needs TR_RECORD_WORLDSTATE)
#TR_RECORD_WORLDSTATE=1 # PRESENCE-only: dump every observed world state
#TR_RADAR_SCANLOG=1 # PRESENCE-only: log every radar scan tick
#TR_TRACKER_PROBE=1 # PRESENCE-only: dump the enemy-tracker's internal state
+97 -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
@@ -44,6 +46,7 @@ import movement_harness/bullet_shadows
import targeting/enemy_tracker
import targeting/target_selector
import env_report
import aim_capture
import vbullet_draw
import geo_overlay
@@ -69,6 +72,13 @@ const ShotLog = true
## can enable recording for just the battle it spawns by exporting the env var.
let RecordWorldState* = existsEnv("TR_RECORD_WORLDSTATE")
const WorldStateRecordPath = "/tmp/worldstate_record.jsonl"
## j177 aim capture: with TR_CAPTURE_AIM set, append two extra record kinds to
## the SAME world-state file — `aim_scan` (one per radar scan: the raw reading,
## our own state, the GUN, the previous belief and the scan parity) and
## `aim_fire` (one per firing decision: the gun, the power, the aim angle, the
## turret error, and the exact WorldState the predictor consumed). Off by
## default, so a normal run writes byte-for-byte what it wrote before.
let CaptureAim* = existsEnv("TR_CAPTURE_AIM")
## Radar measurement switches (all RUNTIME, read once at process start):
## TR_RADAR_FORCE_SPIN=1 force the melee radar to the old stateless full
## spin (always 45 deg/tick). This reproduces the
@@ -150,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
@@ -174,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
@@ -246,6 +275,8 @@ type
tmPattern: TmPatternGun
tmHorizon: TmHorizonGun
leadGain: LeadGainGun
knowledge: KnowledgeGun
waveElm: WaveElmGun
mover: TFILModule
ringMover: TFILRingModule
strafeMover: StrafeModule
@@ -477,6 +508,9 @@ proc recordWorldState(bot: ModularBot, ws: WorldState) =
"eid": tid,
}
if lst >= 0: row["lst"] = %lst
# j177: the gun in force when this state was built. Absent before j177,
# which made a per-gun decomposition of the aim error impossible.
if CaptureAim: row["gun"] = %bot.currentGun
try:
let f = open(WorldStateRecordPath, fmAppend)
f.writeLine($row)
@@ -616,6 +650,23 @@ proc recordRadarStats(bot: ModularBot) =
inc bot.arcWidthHist[min(11, int(width / 30.0))]
method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
# j177 aim capture: the belief we are about to REPLACE, and the fire site's
# state, recorded BEFORE the update. Written first so the record is the
# pre-update belief by construction, not by argument.
if CaptureAim:
var rec = AimScan(tick: bot.tick, eid: e.scannedBotId,
ex: e.x, ey: e.y, eh: e.direction, es: e.speed, ee: e.energy,
sx: getX(), sy: getY(), sh: getDirection(), ss: getSpeed(),
gun: bot.currentGun,
rlock: bot.radarMode == 0, rdir: getRadarDirection(),
bx: 0.0, by: 0.0, blst: -1)
if bot.enemyTracker.enemies.contains(e.scannedBotId):
let prev = bot.enemyTracker.enemies[e.scannedBotId]
rec.bx = prev.x; rec.by = prev.y; rec.bh = prev.heading
rec.bs = prev.speed; rec.blst = prev.lastSeenTick
rec.lbear = bearing(rec.bx, rec.by, rec.sx, rec.sy)
rec.boff = (bearing(rec.ex, rec.ey, rec.sx, rec.sy) - rec.rdir) mod 360.0
appendLine(WorldStateRecordPath, scanRow(rec))
bot.enemyTracker.update(e.scannedBotId, e.x, e.y, e.direction, e.speed, e.energy, bot.tick)
bot.hasContact = true
if RadarScanLog and bot.radarMeleeActive:
@@ -1288,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
@@ -1304,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]))
@@ -1330,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)
@@ -1353,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]]
@@ -1389,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:
@@ -1444,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)
@@ -1467,6 +1541,22 @@ method run*(bot: ModularBot) =
# Enqueue the selected gun so onBulletFired can stamp the server's bulletId.
# getEnergy() > power mirrors the server's "bot.energy <= firepower" reject.
if not floorBlocks and setFire(power) and getEnergy() > power:
# j177 aim capture: one `aim_fire` line per REAL shot, with the gun
# that fired and the exact WorldState the predictor consumed. This
# is the only place where `lst` is knowable, so it is the only place
# the scan parity of a firing decision can be recorded.
if CaptureAim:
let bspd = bulletSpeed(power)
appendLine(WorldStateRecordPath, fireRow(AimFire(
tick: bot.tick, eid: tid, gun: selectedGun, power: power,
aim: aimTarget, turret: gunDir, terr: normDelta, heat: gunHeat,
ax: pred.x, ay: pred.y, tof: (if bspd > 0: distPx / bspd else: 0.0),
ex: bot.lastState.enemyX, ey: bot.lastState.enemyY,
eh: bot.lastState.enemyHeading, es: bot.lastState.enemySpeed,
ee: bot.lastState.enemyEnergy,
sx: bot.lastState.selfX, sy: bot.lastState.selfY,
lst: (if tid >= 0 and bot.enemyTracker.enemies.contains(tid):
bot.enemyTracker.enemies[tid].lastSeenTick else: -1))))
bot.pendingFires.add(PendingShot(
gunId: selectedGun,
angleErr: abs(normDelta),
@@ -1516,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(),
@@ -1534,6 +1624,8 @@ when isMainModule:
tmPattern: initTmRadialGun(),
tmHorizon: initTmHorizonGun(),
leadGain: initLeadGainGun(),
knowledge: initKnowledgeGun(),
waveElm: initWaveElmGun(),
radar: RadarLockModule(),
meleeRadar: initAdaptiveMeleeRadar(),
mover: TFILModule(debugGraphics: DebugDrawOn),
@@ -1558,6 +1650,7 @@ when isMainModule:
vBulletDebugGun: getEnv(VBulletDebugGunEnv, ""),
vBulletDebugMax: VBulletDebugMax,
recordWorldState: RecordWorldState,
captureAim: CaptureAim,
geoDebug: GeoDebugOn,
debugDraw: DebugDrawOn,
radarForceSpin: RadarForceSpin,
+129
View File
@@ -0,0 +1,129 @@
## j177 aim capture — the two records that make the aim error ATTRIBUTABLE.
##
## j176 could not answer "why is the aim 11.9 deg off at 450+ px" because the
## corpus has neither the bot's own belief (staleness was an INVERSE problem,
## unidentifiable) nor the gun id (a good gun's contribution was
## indistinguishable from a bad one's). Both are cheap to log and impossible
## to recover later. This module builds the two JSON records; ModularBot.nim
## calls it and the lines go into the EXISTING world-state capture
## (`TR_RECORD_WORLDSTATE` file), so the offline tooling sees one stream.
##
## It is deliberately PURE (no bot API, no env reads): the bot passes plain
## floats, the offline guard test passes the recorded fixture, and both go
## through the SAME row builders — so a field that the test proves present is
## a field the live bot writes.
##
## Key convention: `e*` = the enemy, `s*` = us, `b*` = the enemy's PREVIOUS
## belief in the tracker (before this scan's update), `lst` = the tick that
## state came from. `age = tick - blst` is the scan PARITY, recorded rather
## than inferred.
import std/[json, os, math]
const
ScanRecordKey* = "aim_scan" ## wrapper key, sibling of "meta"/"end"
FireRecordKey* = "aim_fire"
type
AimScan* = object
## One `onScannedBot` event, as the bot saw it BEFORE the update.
tick*: int
eid*: int
ex*, ey*: float ## raw scanned values
eh*, es*: float ## scanned heading (= direction) and speed
ee*: float
sx*, sy*: float ## our state at the scan (the FIRE SITE)
sh*, ss*: float
gun*: int ## bot.currentGun — the gun that fired, not the rack slot
bx*, by*: float ## previous belief, BEFORE this scan's update
bh*, bs*: float
blst*: int ## previous lastSeenTick; -1 = never scanned before
rlock*: bool ## radar lock engaged (false = the melee radar)
rdir*: float ## 36 deg scan window centre (radar heading)
lbear*: float ## bearing the lock is chasing (believed target)
boff*: float ## scanned bearing - rdir: where in the window it landed
AimFire* = object
## One firing decision, as the model computed it.
tick*: int
eid*: int
gun*: int ## bot.currentGun = the gun that fired
power*: float
aim*: float ## the raw angle handed to setFire/turret
turret*: float ## getGunDirection() at the command
terr*: float ## signed turret error (aim - turret)
heat*: float ## getGunHeat() BEFORE firing
ax*, ay*: float ## the intercept the gun predicted
tof*: float ## implied time of flight, ticks
ex*, ey*: float ## the WorldState the predictor CONSUMED
eh*, es*: float
ee*: float
sx*, sy*: float
lst*: int ## which tick that enemy state came from (scan parity)
proc bearing*(x, y, fx, fy: float): float =
arctan2(y - fy, x - fx).radToDeg
proc scanRow*(s: AimScan): JsonNode =
## The `aim_scan` line. Every field is unconditional: a capture that
## silently omits a field is worse than no capture.
result = newJObject()
result[ScanRecordKey] = newJObject()
let b = result[ScanRecordKey]
b["tick"] = %s.tick
b["eid"] = %s.eid
b["ex"] = %s.ex
b["ey"] = %s.ey
b["eh"] = %s.eh
b["es"] = %s.es
b["ee"] = %s.ee
b["sx"] = %s.sx
b["sy"] = %s.sy
b["sh"] = %s.sh
b["ss"] = %s.ss
b["gun"] = %s.gun
b["bx"] = %s.bx
b["by"] = %s.by
b["bh"] = %s.bh
b["bs"] = %s.bs
b["blst"] = %s.blst
b["age"] = %(if s.blst >= 0: s.tick - s.blst else: -1)
b["rlock"] = %s.rlock
b["rdir"] = %s.rdir
b["lbear"] = %s.lbear
b["boff"] = %s.boff
proc fireRow*(f: AimFire): JsonNode =
## The `aim_fire` line.
result = newJObject()
result[FireRecordKey] = newJObject()
let b = result[FireRecordKey]
b["tick"] = %f.tick
b["eid"] = %f.eid
b["gun"] = %f.gun
b["power"] = %f.power
b["aim"] = %f.aim
b["turret"] = %f.turret
b["terr"] = %f.terr
b["heat"] = %f.heat
b["ax"] = %f.ax
b["ay"] = %f.ay
b["tof"] = %f.tof
b["ex"] = %f.ex
b["ey"] = %f.ey
b["eh"] = %f.eh
b["es"] = %f.es
b["ee"] = %f.ee
b["sx"] = %f.sx
b["sy"] = %f.sy
b["lst"] = %f.lst
proc appendLine*(path: string, row: JsonNode) =
## Append one JSONL line, fully guarded: a full disk or a bad path must
## never take the bot down (same contract as the existing recorders).
try:
let f = open(path, fmAppend)
f.writeLine($row)
f.close()
except CatchableError:
discard
+14 -1
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
@@ -52,6 +53,7 @@ type
vBulletDebugGun*: string
vBulletDebugMax*: int
recordWorldState*: bool
captureAim*: bool ## j177: aim_scan / aim_fire records, default off
geoDebug*: bool
debugDraw*: bool
radarForceSpin*: bool
@@ -245,6 +247,8 @@ proc printEffectiveValues(ctx: EnvReportContext) =
emit("TR_RESULT_LOG", onOff(ctx.resultLog), sourceOf("TR_RESULT_LOG"))
emit("TR_RECORD_WORLDSTATE", onOff(ctx.recordWorldState),
sourceOfPresence("TR_RECORD_WORLDSTATE"))
emit("TR_CAPTURE_AIM", onOff(ctx.captureAim),
sourceOfPresence("TR_CAPTURE_AIM"))
emit("TR_RADAR_FORCE_SPIN", onOff(ctx.radarForceSpin),
sourceOfPresence("TR_RADAR_FORCE_SPIN"))
emit("TR_RADAR_SCANLOG", onOff(ctx.radarScanLog),
@@ -466,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.
@@ -626,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,
@@ -657,7 +670,7 @@ proc knownEnvNames*(): seq[string] =
"GUN_SELECTOR_SHRINK", "GUN_SELECTOR_DWELL", "GUN_SELECTOR_MARGIN",
"GUN_SELECTOR_POINT_TIE", "GUN_SELECTOR_SEED",
"GUN_RACK_DISABLE", "GUN_STATS_PATH", "GUN_SHOTLOG_PATH",
"TR_MOVEMENT", "TR_MOVEMENT_LOG", "TR_RECORD_WORLDSTATE",
"TR_MOVEMENT", "TR_MOVEMENT_LOG", "TR_RECORD_WORLDSTATE", "TR_CAPTURE_AIM",
"TR_RADAR_FORCE_SPIN", "TR_RADAR_SCANLOG", "TR_RADAR_SCAN_LOG_PATH",
"TR_TRACKER_PROBE", "TR_TRACKER_PROBE_PATH", "TR_VBULLET_ADMIT_ONLY",
VBulletDebugEnv, VBulletDebugGunEnv, VBulletDebugMaxEnv,
+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)

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