Examples#
These scripts take a demo path. CI tests them with a demo. Source files are in examples.
python scoreboard.py match.dem
For inline snippets of individual datasets and columns, see Datasets; for plotting recipes, see Plotting.
scoreboard.py — start here#
Round-by-round results plus an end-of-match scoreboard, both teams in one table.
Touches rounds, stats, and players, and uses demo.tick_rate to report
round lengths in seconds.
"""Print a match's rounds and an end-of-match scoreboard.
The "hello world" of demo parsing: what happened each round, and how each player
did over the whole match. Both teams are shown in one table (no side split), the
way a post-match scoreboard reads.
Knife rounds are left out entirely. A knife round is a side-decider played with
melee only; it does not count toward the score, so including it would inflate
kills and skew every per-round average. ``demo.stats`` already excludes them, and
this script drops them from the round table too.
Usage:
python scoreboard.py match.dem
"""
from __future__ import annotations
import argparse
from pathlib import Path
import polars as pl
from awpy import Demo
# (header, stats column). Kept in one place so the header row and the values can
# never fall out of step.
COLUMNS: tuple[tuple[str, str], ...] = (
("K", "kills"),
("D", "deaths"),
("A", "assists"),
("HS", "headshot_kills"),
("FA", "flash_assists"),
("TR", "traded_deaths"),
("CL", "clutches_won"),
("ADR", "adr"),
("KAST", "kast"),
)
def print_rounds(demo: Demo) -> None:
"""One line per round: who won, how, and how long it took."""
every_round = demo.rounds.sort("round_num")
rounds = every_round.filter(~pl.col("is_knife_round"))
skipped = every_round.height - rounds.height
print(f"\nRounds ({rounds.height})")
print("-" * 58)
print(f"{'#':>3} {'winner':<18} {'reason':<24} {'time':>6}")
for row in rounds.iter_rows(named=True):
# Round length in seconds, from the tick rate the demo reports.
start = row["freeze_end_tick"] or row["start_tick"]
seconds = (row["end_tick"] - start) / demo.tick_rate if start else 0.0
print(
f"{row['round_num']:>3} {row['winner_side']:<18} "
f"{row['reason_name']:<24} {seconds:>5.0f}s"
)
if skipped:
print(f"\n({skipped} knife round(s) excluded)")
def print_scoreboard(demo: Demo) -> None:
"""Both teams in one table, sorted by kills."""
stats = demo.stats
# Team names come from the roster; tournament servers set them, so this is
# null on casual matchmaking and the column is simply left out.
roster = demo.players.select("steamid", "side", "team_clan_name")
board = stats.join(roster, on="steamid", how="left").sort("kills", descending=True)
named = board.drop_nulls("team_clan_name").height > 0
team_width = 10 if named else 0
print(f"\nScoreboard ({stats['rounds_played'][0]} rounds)")
print("-" * (26 + team_width + 6 * len(COLUMNS)))
header = f"{'player':<16}" + (f"{'team':<{team_width}}" if named else "")
header += "".join(f"{head:>6}" for head, _ in COLUMNS)
print(header)
for row in board.iter_rows(named=True):
line = f"{row['name'][:15]:<16}"
if named:
line += f"{(row['team_clan_name'] or '')[:9]:<{team_width}}"
for _, column in COLUMNS:
value = row[column]
# ADR and KAST are rates; everything else is a count.
line += f"{value:>6.1f}" if isinstance(value, float) else f"{value:>6}"
print(line)
print("\nK/D/A=kills/deaths/assists HS=headshot kills FA=flash assists")
print("TR=traded deaths CL=clutches won ADR=avg damage/round KAST=%")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("demo", type=Path, help="path to a .dem file")
args = parser.parse_args()
demo = Demo(args.demo)
print(f"{demo.header['map_name']} ({demo.tick_rate:.0f} tick)")
print_rounds(demo)
print_scoreboard(demo)
if __name__ == "__main__":
main()
Output on a professional match:
de_inferno (64 tick)
Rounds (17)
----------------------------------------------------------
# winner reason time
1 terrorist terrorists_win 72s
2 terrorist terrorists_win 129s
3 terrorist target_bombed 122s
...
Scoreboard (17 rounds)
------------------------------------------------------------------------
player team K D A HS FA TR CL ADR KAST
buda BESTIA 16 13 1 12 0 4 0 88.6 76.5
decenty Imperial 16 7 2 11 0 1 2 92.9 70.6
vini Imperial 14 10 6 7 2 3 1 76.8 76.5
chelo Imperial 12 12 4 6 0 4 0 90.4 70.6
saadzin Imperial 12 11 3 5 2 3 0 71.4 70.6
trades.py — who refrags for whom#
Pair is_trade and victim_traded kills to count which players avenge each other.
"""Who trades for whom, from the kills dataset's trade flags.
A *trade* is a kill that avenges a teammate killed moments earlier (within 5.25
seconds). ``demo.kills`` marks both halves of that exchange:
* ``is_trade`` — this kill **is** the revenge.
* ``victim_traded`` — this kill's victim **was** avenged.
Pairing them up turns a flat kill list into a directed graph: who reliably picks
up refrags for whom, and whose deaths tend to go unanswered. That pairing is the
interesting part, and it is not something any single column gives you.
Usage:
python trades.py match.dem
"""
from __future__ import annotations
import argparse
from collections import deque
from pathlib import Path
import polars as pl
from awpy import Demo
TRADE_WINDOW_SECONDS = 5.25
def trade_pairs(demo: Demo) -> pl.DataFrame:
"""Pair each trade kill with its earliest eligible, unmatched death."""
window = round(TRADE_WINDOW_SECONDS * demo.tick_rate)
pending: dict[int, deque[tuple[int, str | None, str | None]]] = {}
pairs: list[tuple[int, str | None, str | None]] = []
for row in demo.kills.sort("tick", maintain_order=True).iter_rows(named=True):
tick = row["tick"]
if row["is_trade"] and (queue := pending.get(row["victim_steamid"])):
while queue and tick - queue[0][0] > window:
queue.popleft()
for index, (died_tick, name, side) in enumerate(queue):
if died_tick < tick and side == row["attacker_side"]:
pairs.append((tick, row["attacker_name"], name))
del queue[index]
break
if row["victim_traded"]:
pending.setdefault(row["attacker_steamid"], deque()).append(
(tick, row["victim_name"], row["victim_side"])
)
return pl.DataFrame(
pairs,
schema={"tick": pl.Int32, "trader_name": pl.String, "avenged_name": pl.String},
orient="row",
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("demo", type=Path, help="path to a .dem file")
args = parser.parse_args()
demo = Demo(args.demo)
kills = demo.kills
n_trades = int(kills["is_trade"].sum())
n_traded = int(kills["victim_traded"].sum())
print(f"{demo.header['map_name']}: {kills.height} kills")
print(f" {n_trades} trade kills avenging {n_traded} deaths")
print(" (each trade kill avenges one death)")
# Per player: how often their death gets answered.
print("\nDeaths avenged")
print("-" * 44)
print(f"{'player':<16} {'deaths':>7} {'traded':>7} {'rate':>7}")
per_victim = (
kills.group_by("victim_name")
.agg(deaths=pl.len(), traded=pl.col("victim_traded").sum())
.with_columns(rate=pl.col("traded") / pl.col("deaths"))
.sort("rate", descending=True)
)
for row in per_victim.iter_rows(named=True):
name = row["victim_name"] or "<unresolved>"
print(f"{name[:15]:<16} {row['deaths']:>7} {row['traded']:>7} {row['rate']:>6.0%}")
# Who does the refragging.
print("\nTrade kills made")
print("-" * 28)
per_trader = (
kills.filter(pl.col("is_trade"))
.group_by("attacker_name")
.len()
.sort("len", descending=True)
)
for row in per_trader.iter_rows(named=True):
print(f"{(row['attacker_name'] or '?')[:15]:<16} {row['len']:>7}")
# The graph: trader -> teammate they avenged.
pairs = trade_pairs(demo)
print(f"\nTrade pairs ({pairs.height} reconstructed)")
print("-" * 48)
top = pairs.group_by("trader_name", "avenged_name").len().sort("len", descending=True).head(15)
for row in top.iter_rows(named=True):
print(f"{row['trader_name'][:15]:<16} -> {row['avenged_name'][:15]:<16} {row['len']:>4}")
if __name__ == "__main__":
main()
The trade flags identify same-team pairs:
Trade pairs (20 reconstructed)
------------------------------------------------
decenty -> saadzin 2
noway -> chelo 2
vini -> chelo 2
tomaszin -> buda 2
economy.py — does forcing work?#
Joins demo.round_economy to demo.rounds for win rate by buy type, overall and
per side. Use multiple matches before drawing conclusions.
"""Win rate by buy type — does forcing actually work?
Joins ``demo.round_economy`` (each team's equipment value at freeze end, and its
buy classification) to ``demo.rounds`` (who won) to answer the question every
analyst asks first: how often does each kind of buy convert into a round?
One match is far too small a sample to conclude anything — the point here is the
join, which is the reusable part. Run it over a directory of demos (see
``batch_parse.py``) before believing any of the numbers.
Usage:
python economy.py match.dem
"""
from __future__ import annotations
import argparse
from pathlib import Path
import polars as pl
from awpy import Demo
# Cheapest to richest, so the output reads in a sensible order rather than
# alphabetically.
BUY_ORDER = ["pistol", "eco", "force", "full"]
def rounds_with_economy(demo: Demo) -> pl.DataFrame:
"""One row per (round, side) with that team's buy and whether they won it."""
rounds = demo.rounds.filter(~pl.col("is_knife_round")).select("round_num", "winner_side")
return (
demo.round_economy.join(rounds, on="round_num", how="inner")
.with_columns(won=pl.col("side") == pl.col("winner_side"))
.with_columns(
# Sort key for the buy-type ordering above; unknown types sort last.
buy_rank=pl.col("buy_type").replace_strict(
{name: i for i, name in enumerate(BUY_ORDER)}, default=len(BUY_ORDER)
)
)
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("demo", type=Path, help="path to a .dem file")
args = parser.parse_args()
demo = Demo(args.demo)
economy = rounds_with_economy(demo)
print(f"{demo.header['map_name']}: {economy['round_num'].n_unique()} rounds\n")
print("Win rate by buy type")
print("-" * 52)
print(f"{'buy':<10} {'rounds':>7} {'won':>5} {'win%':>7} {'avg $':>9}")
by_buy = (
economy.group_by("buy_type", "buy_rank")
.agg(
rounds=pl.len(),
won=pl.col("won").sum(),
equipment=pl.col("equipment_value").mean(),
)
.sort("buy_rank")
)
for row in by_buy.iter_rows(named=True):
rate = row["won"] / row["rounds"]
print(
f"{row['buy_type']:<10} {row['rounds']:>7} {row['won']:>5} "
f"{rate:>6.0%} {row['equipment']:>9,.0f}"
)
print("\nWin rate by buy type and side")
print("-" * 52)
print(f"{'buy':<10} {'side':<18} {'rounds':>7} {'won':>5} {'win%':>7}")
by_side = (
economy.group_by("buy_type", "buy_rank", "side")
.agg(rounds=pl.len(), won=pl.col("won").sum())
.sort("buy_rank", "side")
)
for row in by_side.iter_rows(named=True):
rate = row["won"] / row["rounds"]
print(
f"{row['buy_type']:<10} {row['side']:<18} "
f"{row['rounds']:>7} {row['won']:>5} {rate:>6.0%}"
)
# Eco rounds a team somehow won are worth watching back.
upsets = economy.filter(pl.col("won") & pl.col("buy_type").is_in(["eco", "pistol"]))
if upsets.height:
print("\nRounds won on a pistol/eco buy: ", end="")
print(", ".join(str(n) for n in sorted(upsets["round_num"].to_list())))
if __name__ == "__main__":
main()
clutch_reel.py — from stats to video#
Find clutches from round kills, sample player positions, and render GIFs.
Requires pip install 'awpy[plot]'.
"""Find the match's clutch rounds and render each one as an animated GIF.
Chains three parts of Awpy together:
1. ``demo.stats`` says who played clutches, but not *when* — so the rounds are
located by replaying each round's kills and finding the moment one side drops
to a single living player.
2. ``demo.snapshots`` reconstructs everyone's position and health across that
window.
3. ``awpy.plot.gif`` draws it on the map's radar.
Requires the plot extra: ``pip install 'awpy[plot]'``.
Usage:
python clutch_reel.py match.dem --out clutches/
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from pathlib import Path
import polars as pl
from awpy import Demo
from awpy.plot import Player, gif
SIDES = ("terrorist", "counter-terrorist")
# One frame per this many ticks. 32 is ~2 frames/second on a 64-tick demo — enough
# to follow a fight without producing a huge GIF.
FRAME_STRIDE = 32
@dataclass
class Clutch:
"""A 1-vs-many situation located in the demo."""
round_num: int
tick: int
"""The tick the player was left alone."""
name: str
side: str
opponents: int
won: bool
@property
def label(self) -> str:
outcome = "won" if self.won else "lost"
return f"r{self.round_num:02d}-{self.name}-1v{self.opponents}-{outcome}"
def find_clutches(demo: Demo) -> list[Clutch]:
"""Locate every clutch, with the tick it began.
Walks each round's kills and tracks who is still alive per side. The roster is
taken from the players who appear anywhere in the round's events plus the
match roster, so a player who never fires a shot still counts as alive.
"""
rounds = demo.rounds.filter(~pl.col("is_knife_round")).sort("round_num")
kills = demo.kills.sort("tick")
roster = demo.players.filter(pl.col("steamid") > 0)
names = dict(zip(roster["steamid"], roster["name"], strict=True))
found: list[Clutch] = []
for row in rounds.iter_rows(named=True):
start = row["freeze_end_tick"] or row["start_tick"]
end = row["official_end_tick"] or row["end_tick"]
if start is None:
continue
in_round = kills.filter((pl.col("tick") >= start) & (pl.col("tick") <= end))
# Alive per side at the round's start: everyone seen on that side this
# round, whether they killed, died, or were merely shot at.
alive: dict[str, set[int]] = {}
for side in SIDES:
members = set(
in_round.filter(pl.col("attacker_side") == side)["attacker_steamid"]
) | set(in_round.filter(pl.col("victim_side") == side)["victim_steamid"])
alive[side] = {m for m in members if m}
recorded: set[str] = set()
for kill in in_round.iter_rows(named=True):
side, victim = kill["victim_side"], kill["victim_steamid"]
if side not in alive or victim not in alive[side]:
continue
alive[side].discard(victim)
if side in recorded:
continue
other = SIDES[1 - SIDES.index(side)]
# Exactly one left, with enemies still up: a clutch begins here.
if len(alive[side]) == 1 and alive[other]:
survivor = next(iter(alive[side]))
recorded.add(side)
found.append(
Clutch(
round_num=row["round_num"],
tick=kill["tick"],
name=names.get(survivor, str(survivor)),
side=side,
opponents=len(alive[other]),
won=row["winner_side"] == side,
)
)
return found
def render(demo: Demo, clutch: Clutch, out_dir: Path) -> Path:
"""Draw one clutch from the moment it began to the end of the round."""
round_row = demo.rounds.filter(pl.col("round_num") == clutch.round_num).row(0, named=True)
end = round_row["end_tick"]
snaps = demo.snapshots(every=FRAME_STRIDE, start_tick=clutch.tick, end_tick=end)
frames = []
for _, group in snaps.sort("tick").group_by("tick", maintain_order=True):
frames.append(
[
Player(
x=r["x"],
y=r["y"],
z=r["z"],
yaw=r["yaw"],
hp=r["health"],
armor=r["armor"],
side=r["side"],
label=r["name"],
has_bomb=r["has_bomb"],
)
for r in group.iter_rows(named=True)
]
)
path = out_dir / f"{clutch.label}.gif"
gif(demo.header["map_name"], frames, str(path))
return path
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("demo", type=Path, help="path to a .dem file")
parser.add_argument("--out", type=Path, default=Path("clutches"), help="output directory")
parser.add_argument(
"--won-only", action="store_true", help="only render clutches that were won"
)
parser.add_argument("--limit", type=int, default=None, help="render at most N clutches")
args = parser.parse_args()
demo = Demo(args.demo)
clutches = find_clutches(demo)
if args.won_only:
clutches = [c for c in clutches if c.won]
if args.limit is not None:
clutches = clutches[: args.limit]
print(f"{demo.header['map_name']}: {len(clutches)} clutch situation(s)")
for c in clutches:
outcome = "won " if c.won else "lost"
print(f" round {c.round_num:>2} {c.name:<14} 1v{c.opponents} {outcome} tick {c.tick}")
# Cross-check against the aggregate, which counts these independently.
tallied = int(demo.stats["clutches_played"].sum())
if not args.won_only and args.limit is None and tallied != len(clutches):
print(f" note: demo.stats reports {tallied} — see reference docs on rosters")
if not clutches:
return
args.out.mkdir(parents=True, exist_ok=True)
print(f"\nRendering to {args.out}/ ...")
for c in clutches:
print(f" {render(demo, c, args.out).name}")
if __name__ == "__main__":
main()
batch_parse.py — a folder of demos to Parquet#
Write one Parquet file per dataset and include the source demo in each row.
Completed demos remain available if the run stops.
Use pl.scan_parquet to query results without parsing again.
"""Parse a directory of demos into one Parquet dataset per table.
The workflow most analysis actually starts from: turn a folder of ``.dem`` files
into columnar files you can query without re-parsing anything. Each output table
gains a ``demo`` column (the file stem) so rows stay attributable once the matches
are stacked together.
Parsing is the expensive step and it is CPU-bound inside Rust, so demos are
processed one at a time and written incrementally — a failure partway through
leaves the demos already done on disk.
Usage:
python batch_parse.py demos/ --out parquet/
python batch_parse.py demos/ --out parquet/ --tables rounds kills stats
"""
from __future__ import annotations
import argparse
import time
from pathlib import Path
import polars as pl
from awpy import Demo
# Dataset name -> how to pull it off a Demo. All of these are cached properties
# built in one shared pass, so asking for several costs little more than one.
TABLES: dict[str, str] = {
"rounds": "rounds",
"kills": "kills",
"damages": "damages",
"bomb": "bomb",
"shots": "shots",
"grenades": "grenades",
"stats": "stats",
"players": "players",
"round_economy": "round_economy",
}
def parse_one(path: Path, tables: list[str]) -> dict[str, pl.DataFrame]:
"""Every requested table for one demo, tagged with the demo's name."""
demo = Demo(path)
out: dict[str, pl.DataFrame] = {}
for name in tables:
frame: pl.DataFrame = getattr(demo, TABLES[name])
# Tag first so the column order is stable across demos.
out[name] = frame.select(
pl.lit(path.stem).alias("demo"),
pl.lit(demo.header["map_name"]).alias("map_name"),
pl.all(),
)
return out
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("demos", type=Path, help="directory of .dem files")
parser.add_argument("--out", type=Path, default=Path("parquet"), help="output directory")
parser.add_argument(
"--tables",
nargs="+",
choices=sorted(TABLES),
default=["rounds", "kills", "stats"],
help="which datasets to export (default: rounds kills stats)",
)
args = parser.parse_args()
paths = sorted(args.demos.glob("*.dem"))
if not paths:
raise SystemExit(f"no .dem files in {args.demos}")
args.out.mkdir(parents=True, exist_ok=True)
collected: dict[str, list[pl.DataFrame]] = {name: [] for name in args.tables}
failed: list[tuple[Path, str]] = []
for i, path in enumerate(paths, 1):
size_mb = path.stat().st_size / 1e6
print(f"[{i}/{len(paths)}] {path.name} ({size_mb:.0f} MB)... ", end="", flush=True)
started = time.monotonic()
try:
for name, frame in parse_one(path, args.tables).items():
collected[name].append(frame)
except Exception as exc: # a corrupt or truncated demo shouldn't stop the run
print(f"FAILED ({exc})")
failed.append((path, str(exc)))
continue
print(f"{time.monotonic() - started:.1f}s")
# Write after each demo, so an interrupted run still leaves usable output.
for name, frames in collected.items():
if frames:
pl.concat(frames, how="diagonal_relaxed").write_parquet(
args.out / f"{name}.parquet"
)
print(f"\nWrote {len(args.tables)} table(s) to {args.out}/")
for name, frames in collected.items():
if frames:
rows = sum(f.height for f in frames)
print(f" {name}.parquet {rows:,} rows from {len(frames)} demo(s)")
if failed:
print(f"\n{len(failed)} demo(s) failed:")
for path, error in failed:
print(f" {path.name}: {error}")
print("\nQuery it without re-parsing:")
print(f' pl.scan_parquet("{args.out}/kills.parquet").group_by("demo").len().collect()')
if __name__ == "__main__":
main()