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.
This commit is contained in:
2026-10-06 08:37:17 +02:00
parent 84ad673f4b
commit 9f37db7523
11 changed files with 438 additions and 15 deletions
+85
View File
@@ -470,3 +470,88 @@ target, not a bug. One thing to watch: `elmCorrection` rebuilds `bulletSpeed` as
`power*10` for the feature (the corpus convention), while the geometric intercept `power*10` for the feature (the corpus convention), while the geometric intercept
uses the physical `20 − 3*power`; the corpus does the same, so the feature is uses the physical `20 − 3*power`; the corpus does the same, so the feature is
consistent, but the two lead calculations are not the same number. consistent, but the two lead calculations are not the same number.
## Geometric gate
Non-regression gate the user set before the ELM may be judged against DrussGT:
**the ELM must match or beat the plain geometric gun against the three classic
geometric-movement bots** (Target = near-stationary, Walls = wall-hugger,
SpinBot = constant circular motion). Geometric guns are near-perfect against
geometric movement by construction, so this is a floor, not a target. Nothing
was tuned to pass it; no weights changed.
### Adversaries (added under `tr_bots/`)
The canonical Tank Royale Java samples, compiled in place against the vendored
bot API jar (`tank-royale/sample-bots/java/build/archive/lib/…-1.0.2.jar`) —
`tank-royale` itself is untouched. Each dir has `<Name>.java/.class/.json/.sh`:
| bot | source | path |
|---|---|---|
| Target | `sample-bots/java/build/archive/Target` | `tr_bots/Target/` |
| Walls | `sample-bots/java/build/archive/Walls` | `tr_bots/Walls/` |
| SpinBot | `sample-bots/java/build/archive/SpinBot` | `tr_bots/SpinBot/` |
All three boot and play 20 rounds; all six recordings verify CONTIGUOUS
(`python3 tools/raw_recorder/query.py <file>.battle.gz --verify`).
### Gate table — 20 rounds each, RawRecord observer ground truth
Builds: `nim c -d:release … -o DevElm` (default) and `-d:baselineGun`
(geometric). Damage is `BulletHitBotEvent.damage` summed over the recording;
`dmg/rd` divides by 20. Noise column is the per-round standard error of the mean.
| opponent | gun | shots | hits | hit% | damage | dmg/rd | won/rd |
|---|---|---|---|---|---|---|---|
| Target | geometric | 324 | 211 | 65.1% | 2110 | 105.5 ± 1.1 | 20/20 |
| Target | ELM | 562 | 209 | 37.2% | 2090 | 104.5 ± 1.1 | 20/20 |
| Walls | geometric | 605 | 152 | 25.1% | 1520 | 76.0 ± 1.8 | 20/20 |
| Walls | ELM | 772 | 27 | 3.5% | 270 | **13.5 ± 3.6** | 1/20 |
| SpinBot | geometric | 644 | 86 | 13.4% | 860 | 43.0 ± 7.6 | 0/20 |
| SpinBot | ELM | 585 | 22 | 3.8% | 220 | **11.0 ± 1.9** | 0/20 |
### Aim error at fire (degrees, vs the true geometric intercept)
Reference is the physical intercept (bullet speed `20 − 3·power`, constant-velocity
target taken from the observer's own positions); wrapping in (−180°,180°].
| opponent | gun | n | mean | median | sd | ≤1° | ≤5° | ≤10° |
|---|---|---|---|---|---|---|---|---|
| Target | geometric | 324 | +0.08 | +0.02 | 2.74 | 86% | 92% | 98% |
| Target | ELM | 562 | +0.42 | +2.06 | 8.86 | 11% | 59% | 91% |
| Walls | geometric | 605 | −1.48 | −4.56 | 7.30 | 15% | 33% | 87% |
| Walls | ELM | 772 | +13.52 | +11.49 | 11.52 | 3% | 19% | 42% |
| SpinBot | geometric | 644 | −0.19 | +0.38 | 3.91 | 29% | 85% | 98% |
| SpinBot | ELM | 585 | +1.95 | +4.02 | 16.10 | 3% | 17% | 29% |
The ELM's fitted bias (≈ +1.6° to +2° median, plus a much wider tail) is exactly
what the aim-error block shows: it systematically pushes an already-on-target
geometric shot off the intercept, and the correction grows (median +11.5° vs
Walls) when the target moves.
### Verdict
| opponent | geometric dmg/rd | ELM dmg/rd | delta | gate |
|---|---|---|---|---|
| Target | 105.5 ± 1.1 | 104.5 ± 1.1 | −1.0 (≈1 se) | **PASS** (within noise) |
| Walls | 76.0 ± 1.8 | 13.5 ± 3.6 | −62.5 | **FAIL** |
| SpinBot | 43.0 ± 7.6 | 11.0 ± 1.9 | −32.0 | **FAIL** |
The ELM passes only Target, and only because 104.5 vs 105.5 is inside the noise:
it lands the same number of hits (209 vs 211) by firing far more bullets (562 vs
324). Against Walls and SpinBot it fails decisively — damage/round is ~5.6× and
~3.9× worse, and the hit rate collapses (25.1%→3.5%, 13.4%→3.8%). This is a
non-regression failure, and it is the expected direction given the fitted bias.
### bulletSpeed convention — corpus vs live (job-42 follow-up)
**The corpus and the live feature builder agree: both use `power * 10`.**
`extract_realistic.py` writes `v = bu["power"] * 10.0`; `train_elm_gun.nim`
reconstructs `GunBelief.bulletSpeed` from that stored value; `elm_features.nim`
divides it by 20 for `bulletSpd` and derives `tof` from it; and
`elm_gun.elmCorrection` sets `bb.bulletSpeed = power * 10.0` before calling the
same `buildFeatures`. The geometric intercept separately uses the physical
`20 − 3·power`. So there is **no train/inference feature mismatch** — `power*10`
is a corpus artifact that both sides share, and it is not the physical bullet
speed. No change made: it is self-consistent, and changing it would be a
different model, not a bug fix.
+82 -15
View File
@@ -11,6 +11,16 @@ stream is the only source, which is the whole point of recording.
Hit RATE is hits / (fired - still in flight at the end of the round) is NOT Hit RATE is hits / (fired - still in flight at the end of the round) is NOT
attempted: a bullet still in flight when the round ends is counted in the attempted: a bullet still in flight when the round ends is counted in the
denominator as a miss, which is conservative but identical for both guns. denominator as a miss, which is conservative but identical for both guns.
Also reports, from the same stream:
* damage per round and rounds won (RoundEndedEventForObserver rank==1);
* the aim error at fire = wrap(bullet.direction - true geometric intercept
bearing), computed on the tick the BulletFiredEvent appears. The reference
is the physical intercept (bullet speed 20 - 3*power, constant-velocity
target from the observer's own positions), NOT the bearing to the target's
current position: for a moving target the current bearing differs from the
intercept by the whole lead angle, so it would measure the lead, not the
error. This is what explains any damage difference between the two guns.
""" """
import gzip, json, sys, glob, os, math import gzip, json, sys, glob, os, math
from collections import defaultdict from collections import defaultdict
@@ -24,35 +34,76 @@ def wrap(a):
return a return a
def intercept_bearing(sx, sy, tx, ty, vx, vy, vb):
"""Bearing from (sx,sy) to the constant-velocity intercept with a target
at (tx,ty) moving (vx,vy), for a bullet of speed vb. Fixed-point iteration
on t = |P - S| / vb."""
t = math.hypot(tx - sx, ty - sy) / vb if vb > 0 else 0.0
px, py = tx, ty
for _ in range(8):
px, py = tx + vx * t, ty + vy * t
t = math.hypot(px - sx, py - sy) / vb
return math.atan2(py - sy, px - sx)
def pct_within(errs, lim):
n = len(errs)
return 100.0 * sum(1 for e in errs if abs(e) <= lim) / n if n else 0.0
def score(path): def score(path):
name_of = {} name_of = {}
stats = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds_won=0, rounds=0)) stats = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds_won=0, rounds=0, aim=[]))
prev_turn = {} prev_turn = {}
lastpos = {} # (round, botId) -> (turn, x, y)
noncontig = 0 noncontig = 0
with gzip.open(path, "rt") as fh: with gzip.open(path, "rt") as fh:
for line in fh: for line in fh:
if not line.strip(): if not line.strip():
continue continue
m = json.loads(line) m = json.loads(line)
if m.get("type") != "TickEventForObserver": t = m.get("type")
if m.get("type") == "RoundEndedEventForObserver": if t == "RoundEndedEventForObserver":
for s in stats.values(): for s in stats.values():
s["rounds"] += 1 s["rounds"] += 1
for r in m.get("results", []):
if r.get("rank") == 1:
stats[r["id"]]["rounds_won"] += 1
continue
if t != "TickEventForObserver":
continue continue
rnd, turn = m["roundNumber"], m["turnNumber"] rnd, turn = m["roundNumber"], m["turnNumber"]
if prev_turn.get(rnd) not in (None, turn - 1): if prev_turn.get(rnd) not in (None, turn - 1):
noncontig += 1 noncontig += 1
prev_turn[rnd] = turn prev_turn[rnd] = turn
pos = {}
for b in m.get("botStates", []): for b in m.get("botStates", []):
name_of[b["id"]] = b["name"] name_of[b["id"]] = b["name"]
pos[b["id"]] = (b["x"], b["y"])
for e in m.get("events", []): for e in m.get("events", []):
t = e.get("type") et = e.get("type")
if t == "BulletFiredEvent": if et == "BulletFiredEvent":
stats[e["bullet"]["ownerId"]]["fired"] += 1 bu = e["bullet"]
elif t == "BulletHitBotEvent": oid = bu["ownerId"]
stats[oid]["fired"] += 1
others = [(i, p) for i, p in pos.items() if i != oid]
if len(others) == 1:
tid, (tx, ty) = others[0]
lp = lastpos.get((rnd, tid))
if lp is not None and lp[0] == turn - 1:
vx, vy = tx - lp[1], ty - lp[2]
else:
vx = vy = 0.0
vb = 20.0 - 3.0 * bu["power"]
ideal = intercept_bearing(bu["x"], bu["y"], tx, ty, vx, vy, vb)
err = wrap(math.radians(bu["direction"]) - ideal)
stats[oid]["aim"].append(math.degrees(err))
elif et == "BulletHitBotEvent":
s = stats[e["bullet"]["ownerId"]] s = stats[e["bullet"]["ownerId"]]
s["hits"] += 1 s["hits"] += 1
s["dmg"] += e.get("damage", 0.0) s["dmg"] += e.get("damage", 0.0)
for i, (x, y) in pos.items():
lastpos[(rnd, i)] = (turn, x, y)
return name_of, stats, noncontig return name_of, stats, noncontig
@@ -63,28 +114,44 @@ def main():
if not files: if not files:
print("no recording in", d) print("no recording in", d)
continue continue
tot = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds=0)) tot = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds=0, rounds_won=0, aim=[]))
noncontig = 0 noncontig = 0
for f in files: for f in files:
name_of, stats, nc = score(f) name_of, stats, nc = score(f)
noncontig += nc noncontig += nc
for bid, s in stats.items(): for bid, s in stats.items():
n = name_of.get(bid, "?") n = name_of.get(bid, "?")
for k in tot[n]: for k in ("fired", "hits", "dmg", "rounds", "rounds_won"):
tot[n][k] += s[k] tot[n][k] += s[k]
tot[n]["aim"].extend(s["aim"])
variant, opponent = os.path.basename(d)[4:].split("_", 1) variant, opponent = os.path.basename(d)[4:].split("_", 1)
tag = "ELM" if variant == "Elm" else "geometric"
for n, s in tot.items(): for n, s in tot.items():
tag = "ELM" if variant == "Elm" else "heuristic"
if n == "DevControlBot": if n == "DevControlBot":
rows.append((opponent, tag, s, noncontig)) rows.append((opponent, tag, s, noncontig))
rows.sort() rows.sort()
print(f"{'opponent':<14}{'gun':<11}{'shots':>7}{'hits':>7}{'hit%':>8}{'damage':>9}{'rounds':>8}") print(f"{'opponent':<12}{'gun':<11}{'shots':>7}{'hits':>7}{'hit%':>8}{'damage':>9}{'dmg/rd':>8}{'won/rd':>9}")
for opp, tag, s, nc in rows: for opp, tag, s, nc in rows:
hr = 100.0 * s["hits"] / s["fired"] if s["fired"] else 0.0 hr = 100.0 * s["hits"] / s["fired"] if s["fired"] else 0.0
print(f"{opp:<14}{tag:<11}{s['fired']:>7}{s['hits']:>7}{hr:>7.1f}%{s['dmg']:>9.0f}{s['rounds']:>8}") dpr = s["dmg"] / s["rounds"] if s["rounds"] else 0.0
won = f"{s['rounds_won']}/{s['rounds']}"
print(f"{opp:<12}{tag:<11}{s['fired']:>7}{s['hits']:>7}{hr:>7.1f}%{s['dmg']:>9.0f}{dpr:>8.1f}{won:>9}")
if nc: if nc:
print(f" !! {nc} turnNumber discontinuities") print(f" !! {nc} turnNumber discontinuities")
print()
print(f"{'opponent':<12}{'gun':<11}{'n':>6}{'mean':>8}{'median':>8}{'sd':>8}{'<=1d':>7}{'<=5d':>7}{'<=10d':>7}")
for opp, tag, s, nc in rows:
aim = s["aim"]
n = len(aim)
if not n:
continue
mean = sum(aim) / n
med = sorted(aim)[n // 2]
var = sum((a - mean) ** 2 for a in aim) / n
print(f"{opp:<12}{tag:<11}{n:>6}{mean:>7.2f}d{med:>7.2f}d{math.sqrt(var):>7.2f}d"
f"{pct_within(aim, 1):>6.0f}%{pct_within(aim, 5):>6.0f}%{pct_within(aim, 10):>6.0f}%")
if __name__ == "__main__": if __name__ == "__main__":
main() main()
+58
View File
@@ -0,0 +1,58 @@
import dev.robocode.tankroyale.botapi.*;
import dev.robocode.tankroyale.botapi.events.*;
import dev.robocode.tankroyale.botapi.graphics.Color;
// ------------------------------------------------------------------
// SpinBot
// ------------------------------------------------------------------
// A sample bot originally made for Robocode by Mathew Nelson.
//
// Continuously moves in a circle while firing at maximum power when
// detecting enemies.
// ------------------------------------------------------------------
public class SpinBot extends Bot {
// The main method starts our bot
public static void main(String[] args) {
new SpinBot().start();
}
// Called when a new round is started -> initialize and do some movement
@Override
public void run() {
setBodyColor(Color.BLUE);
setTurretColor(Color.BLUE);
setRadarColor(Color.BLACK);
setScanColor(Color.YELLOW);
// Repeat while the bot is running
while (isRunning()) {
// Tell the game that when we take move, we'll also want to turn right... a lot
setTurnRight(10_000);
// Limit our speed to 5
setMaxSpeed(5);
// Start moving (and turning)
forward(10_000);
}
}
// We scanned another bot -> fire hard!
@Override
public void onScannedBot(ScannedBotEvent e) {
fire(3);
}
// We hit another bot -> if it's our fault, we'll stop turning and moving,
// so we need to turn again to keep spinning.
@Override
public void onHitBot(HitBotEvent e) {
var direction = directionTo(e.getX(), e.getY());
var bearing = calcBearing(direction);
if (bearing > -10 && bearing < 10) {
fire(3);
}
if (e.isRammed()) {
turnRight(10);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "SpinBot",
"version": "1.0",
"authors": ["Mathew Nelson, Flemming N. Larsen"],
"description": "Continuously moves in a circle firing hard. Geometric 'SpinBot' sample.",
"homepage": "",
"countryCodes": ["us", "dk"],
"gameTypes": ["classic", "1v1"],
"platform": "JVM",
"programmingLang": "Java 11"
}
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Geometric-movement adversary: Tank Royale Java sample, run from source so the
# repo stays text-only. BOT_API_JAR points at the vendored bot API (override it
# if the checkout moves); the .json next to this script carries the identity.
cd "$(dirname "$0")"
export BOT_NAME="SpinBot"
export BOT_VERSION="1.0"
export BOT_AUTHORS="Mathew Nelson, Flemming N. Larsen"
export BOT_COUNTRY_CODES="us,dk"
export BOT_GAME_TYPES="classic,1v1"
export BOT_PLATFORM="JVM"
export BOT_PROG_LANG="Java 11"
exec java -cp "${BOT_API_JAR:-/home/davide/Projects/tank-royale/sample-bots/java/build/archive/lib/robocode-tankroyale-bot-api-1.0.2.jar}" SpinBot.java
+57
View File
@@ -0,0 +1,57 @@
import dev.robocode.tankroyale.botapi.*;
import dev.robocode.tankroyale.botapi.events.*;
import dev.robocode.tankroyale.botapi.graphics.Color;
// ------------------------------------------------------------------
// Target
// ------------------------------------------------------------------
// A sample bot originally made for Robocode by Mathew Nelson.
//
// A stationary robot that moves when its energy drops below a certain
// threshold. This robot demonstrates how to use custom events.
// ------------------------------------------------------------------
public class Target extends Bot {
int trigger; // Keeps track of when to move
// The main method starts our bot
public static void main(String[] args) {
new Target().start();
}
// Called when a new round is started -> initialize and do some movement
@Override
public void run() {
// Set colors
setBodyColor(Color.WHITE);
setTurretColor(Color.WHITE);
setRadarColor(Color.WHITE);
// Initially, we'll move when energy passes 80
trigger = 80;
// Add a custom event named "trigger-hit"
addCustomEvent(new Condition("trigger-hit") {
public boolean test() {
return getEnergy() <= trigger;
}
});
}
// A custom event occurred
@Override
public void onCustomEvent(CustomEvent e) {
// Check if our custom event "trigger-hit" went off
if (e.getCondition().getName().equals("trigger-hit")) {
// Adjust the trigger value, or else the event will fire again and again and again...
trigger -= 20;
// Print out energy level
System.out.println("Ouch, down to " + (int) (getEnergy() + .5) + " energy.");
// Move around a bit
turnRight(65);
forward(100);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "Target",
"version": "1.0",
"authors": ["Mathew Nelson, Flemming N. Larsen"],
"description": "Sits still. Moves every time energy drops by 20. Geometric 'Target' sample.",
"homepage": "",
"countryCodes": ["us", "dk"],
"gameTypes": ["classic", "1v1"],
"platform": "JVM",
"programmingLang": "Java 11"
}
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Geometric-movement adversary: Tank Royale Java sample, run from source so the
# repo stays text-only. BOT_API_JAR points at the vendored bot API (override it
# if the checkout moves); the .json next to this script carries the identity.
cd "$(dirname "$0")"
export BOT_NAME="Target"
export BOT_VERSION="1.0"
export BOT_AUTHORS="Mathew Nelson, Flemming N. Larsen"
export BOT_COUNTRY_CODES="us,dk"
export BOT_GAME_TYPES="classic,1v1"
export BOT_PLATFORM="JVM"
export BOT_PROG_LANG="Java 11"
exec java -cp "${BOT_API_JAR:-/home/davide/Projects/tank-royale/sample-bots/java/build/archive/lib/robocode-tankroyale-bot-api-1.0.2.jar}" Target.java
+84
View File
@@ -0,0 +1,84 @@
import dev.robocode.tankroyale.botapi.*;
import dev.robocode.tankroyale.botapi.events.*;
import dev.robocode.tankroyale.botapi.graphics.Color;
// ------------------------------------------------------------------
// Walls
// ------------------------------------------------------------------
// A sample bot originally made for Robocode by Mathew Nelson.
//
// This robot navigates around the perimeter of the battlefield with
// the gun pointed inward.
// ------------------------------------------------------------------
public class Walls extends Bot {
boolean peek; // Don't turn if there's a bot there
double moveAmount; // How much to move
// The main method starts our bot
public static void main(String[] args) {
new Walls().start();
}
// Called when a new round is started -> initialize and do some movement
@Override
public void run() {
// Set colors
setBodyColor(Color.BLACK);
setTurretColor(Color.BLACK);
setRadarColor(Color.ORANGE);
setBulletColor(Color.CYAN);
setScanColor(Color.CYAN);
// Initialize moveAmount to the maximum possible for the arena
moveAmount = Math.max(getArenaWidth(), getArenaHeight());
// Initialize peek to false
peek = false;
// turn to face a wall.
// `getDirection() % 90` means the remainder of getDirection() divided by 90.
turnRight(getDirection() % 90);
forward(moveAmount);
// Turn the gun to turn right 90 degrees.
peek = true;
turnGunLeft(90);
turnLeft(90);
// Main loop
while (isRunning()) {
// Peek before we turn when forward() completes.
peek = true;
// Move up the wall
forward(moveAmount);
// Don't peek now
peek = false;
// Turn to the next wall
turnLeft(90);
}
}
// We hit another bot -> move away a bit
@Override
public void onHitBot(HitBotEvent e) {
// If he's in front of us, set back up a bit.
var bearing = bearingTo(e.getX(), e.getY());
if (bearing > -90 && bearing < 90) {
back(100);
} else { // else he's in back of us, so set ahead a bit.
forward(100);
}
}
// We scanned another bot -> fire!
@Override
public void onScannedBot(ScannedBotEvent e) {
fire(2);
// Note that scan is called automatically when the bot is turning.
// By calling it manually here, we make sure we generate another scan event if there's a bot
// on the next wall, so that we do not start moving up it until it's gone.
if (peek) {
rescan();
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "Walls",
"version": "1.0",
"authors": ["Mathew Nelson, Flemming N. Larsen"],
"description": "Moves around the outer edge with the gun facing in. Geometric 'Walls' sample.",
"homepage": "",
"countryCodes": ["us", "dk"],
"gameTypes": ["classic", "1v1"],
"platform": "JVM",
"programmingLang": "Java 11"
}
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Geometric-movement adversary: Tank Royale Java sample, run from source so the
# repo stays text-only. BOT_API_JAR points at the vendored bot API (override it
# if the checkout moves); the .json next to this script carries the identity.
cd "$(dirname "$0")"
export BOT_NAME="Walls"
export BOT_VERSION="1.0"
export BOT_AUTHORS="Mathew Nelson, Flemming N. Larsen"
export BOT_COUNTRY_CODES="us,dk"
export BOT_GAME_TYPES="classic,1v1"
export BOT_PLATFORM="JVM"
export BOT_PROG_LANG="Java 11"
exec java -cp "${BOT_API_JAR:-/home/davide/Projects/tank-royale/sample-bots/java/build/archive/lib/robocode-tankroyale-bot-api-1.0.2.jar}" Walls.java