#!/usr/bin/env python3 """Score recorded DevControlBot battles from the OBSERVER ground truth. python3 tools/elm_bench/score_battles.py /tmp/rec_Elm_DrussGT [...] For every recording it counts, per bot, the bullets it fired (BulletFiredEvent), how many of them hit a BOT (BulletHitBotEvent), and the damage those hits dealt (BulletHitBotEvent.damage). Nothing here uses the bot's own opinion: the observer 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 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. 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 from collections import defaultdict def wrap(a): while a > math.pi: a -= 2 * math.pi while a < -math.pi: a += 2 * math.pi 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): name_of = {} stats = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds_won=0, rounds=0, aim=[])) prev_turn = {} lastpos = {} # (round, botId) -> (turn, x, y) noncontig = 0 with gzip.open(path, "rt") as fh: for line in fh: if not line.strip(): continue m = json.loads(line) t = m.get("type") if t == "RoundEndedEventForObserver": for s in stats.values(): 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 rnd, turn = m["roundNumber"], m["turnNumber"] if prev_turn.get(rnd) not in (None, turn - 1): noncontig += 1 prev_turn[rnd] = turn pos = {} for b in m.get("botStates", []): name_of[b["id"]] = b["name"] pos[b["id"]] = (b["x"], b["y"]) for e in m.get("events", []): et = e.get("type") if et == "BulletFiredEvent": bu = e["bullet"] 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["hits"] += 1 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 def main(): rows = [] for d in sys.argv[1:]: files = sorted(glob.glob(os.path.join(d, "*.battle.gz"))) if not files: print("no recording in", d) continue tot = defaultdict(lambda: dict(fired=0, hits=0, dmg=0.0, rounds=0, rounds_won=0, aim=[])) noncontig = 0 for f in files: name_of, stats, nc = score(f) noncontig += nc for bid, s in stats.items(): n = name_of.get(bid, "?") for k in ("fired", "hits", "dmg", "rounds", "rounds_won"): tot[n][k] += s[k] tot[n]["aim"].extend(s["aim"]) variant, opponent = os.path.basename(d)[4:].split("_", 1) tag = "ELM" if variant == "Elm" else "geometric" for n, s in tot.items(): if n == "DevControlBot": rows.append((opponent, tag, s, noncontig)) rows.sort() 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: hr = 100.0 * s["hits"] / s["fired"] if s["fired"] else 0.0 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: 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__": main()