API reference#

from awpy import Demo

demo = Demo("match.dem")
demo.load("kills", "damages", "shots")
print(demo.header["map_name"])
print(demo.stats.select("name", "kills", "deaths", "assists", "adr", "kast"))
print(demo.snapshots(seconds=1.0))

This page uses the installed package docstrings. See Datasets for columns, multipart queries, and Reference for definitions.

Parse CS2 recordings with Awpy Demo#

Open one demo or an ordered sequence of demo paths. Read datasets as Polars DataFrames. Single-file construction maps the file and checks its header. Multipart construction also checks round continuity and recording boundaries. Dataset access triggers decoding. Results are cached; Demo.load(...) combines compatible requests.

class awpy.Demo(path)#

Bases: object

Read one CS2 demo or ordered recordings of one map.

Parameters:

path – One string or path-like object, or a nonempty sequence in recording order.

Variables:
  • path – Source Path for a single recording. Access on a multipart demo raises ValueError.

  • paths – Source paths in recording order.

  • parts – Each source recording as a Demo.

  • headers – Header and playback metadata for each source recording.

Raises:
  • FileNotFoundError – If a file does not exist.

  • InvalidDemoError – If a file cannot be decoded as a supported CS2 demo.

  • ValueError – If a multipart selection is empty, incompatible, incomplete, or split during live play.

Notes

Single-file construction maps the file and checks its header. Multipart construction also validates round continuity and recording boundaries. Dataset properties decode on access and cache results. Multipart tables retain local ticks and include part. players and stats combine Steam IDs.

Examples

>>> from awpy import Demo
>>> demo = Demo("match.dem")
>>> demo.load("kills", "damages", "shots")
>>> print(demo.stats)
static available_datasets()#

List cached dataset names accepted by Demo.load.

Returns:

Supported dataset names as strings.

blinds#

Read cached CS2 flash victims, throwers, and durations.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

Reconstructed from pawn flash state and flashbang_detonate (so it works even on GOTV demos, which omit the player_blind event). Columns: tick, the resolved attacker_* (thrower) and victim_* (blinded player) steamid / name / side / x / y / z, and duration (blind seconds).

bomb#

Read cached CS2 bomb actions.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

chat#

Read cached CS2 chat messages.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

Decoded from SayText, SayText2, and SayTextChannel. Columns: tick, entity_index (the sender’s controller slot), name, message, and channel (e.g. Cstrike_Chat_All for all-chat, Cstrike_Chat_T / Cstrike_Chat_CT for team chat). Server-side (GOTV) demos often strip chat entirely — an empty frame is normal.

convars#

Read cached CS2 server console variables.

Returns:

dict[str, str].

Notes

Collected from the demo’s net_SetConVar messages; when a convar is set more than once, the last value wins.

damages#

Read cached CS2 player_hurt events and resolved participants.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

events#

Read the cached CS2 game-event mapping.

Returns:

The cached Events mapping.

Notes

Use demo.events.names to list names and demo.events[name] or attribute access to read a cached DataFrame:

demo.events.player_death
demo.events["player_ping"]
fires#

Read cached CS2 fire intervals.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

grenades#

Read cached CS2 grenade trajectories with observed start and end ticks.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

header#

Read cached CS2 header and playback metadata.

Returns:

The header dictionary. Multipart playback fields are retained in headers.

Notes

Keys: map_name, server_name, client_name, build_num, demo_version_name, game_directory, and (when available) playback_ticks, playback_frames, playback_time. Multipart playback fields are in headers instead.

headers#

Read header and playback metadata for each recording.

Returns:

One header dictionary for each source recording.

item_events#

Read cached CS2 item purchases, pickups, and drops.

Returns:

A Polars DataFrame with transaction tick, action, player, item, position, original owner, cost, and buy-zone state.

Notes

Transactions are reconstructed from inventory state, including demos without item_purchase events.

kills#

Read cached CS2 kills and resolved participants.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

is_trade marks a kill that avenges a teammate within 5.25 seconds. victim_traded marks the earlier death; stats count it as traded_deaths. Each kill trades only the earliest qualifying death. A kill can have both flags.

load(*datasets)#

Decode and cache selected Awpy datasets.

Parameters:

*datasets – Dataset names from available_datasets().

Raises:

ValueError – If any name is unknown, before decoding starts.

Notes

Compatible combat and projectile requests share passes. Stats reuse combat, round, and roster inputs. Already cached datasets are skipped.

parts#

Read each source recording as a Demo.

Returns:

Source Demo objects in supplied order.

path#

The single source path. For multipart recordings, use paths.

paths#

Read the source paths in recording order.

Returns:

Source Path objects in supplied order.

player_stats(include_knife_rounds=False)#

Read CS2 player statistics with optional knife rounds.

Parameters:

include_knife_rounds – Include rounds marked is_knife_round when true.

Returns:

A cached Polars scoreboard with one row per player.

Notes

Both variants reuse decoded inputs. The default is the same cached result as stats.

players#

Read the cached CS2 player roster.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

Columns: steamid, name, side, and team_clan_name. Bots have Steam ID 0. Side and team name are the last observed values. Team names come from CCSTeam and are null when not set.

round_economy#

Read cached CS2 team equipment values and buy types.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

One row per (round, side): round_num, side, equipment_value (the team’s total at freeze end), buy_type (pistol / eco / force / full), and n_players.

rounds#

Read cached CS2 round timings, winners, and end reasons.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

One row per round with round_num, start_tick, freeze_end_tick, end_tick, winner (team number), winner_side, reason, and reason_name. Reconstructed from CCSGameRules state, so it works on demos without round_start / round_end events.

seconds_to_tick(seconds)#

Convert recording seconds to the nearest local demo tick.

Parameters:

seconds – Finite seconds from recording start. Negative values are permitted.

Returns:

The nearest signed 32-bit tick.

Raises:

ValueError – If the value is nonfinite or outside the supported tick range.

shots#

Read cached CS2 shots with player and weapon state.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

Built in the same single pass as kills / damages / bomb / blinds.

smokes#

Read cached CS2 smoke intervals.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

snapshots(*, ticks=None, every=None, seconds=None, events=None, start_tick=None, end_tick=None, part=None)#

Read CS2 player state at selected local ticks.

Parameters:
  • ticks – One local demo tick or a sequence of local ticks.

  • every – Positive sampling stride in ticks. Do not combine with seconds.

  • seconds – Positive sampling interval in seconds. Do not combine with every.

  • events – One game-event name or a sequence of names whose ticks are selected.

  • start_tick – Inclusive lower bound. Alone with end_tick, select every tick in the window.

  • end_tick – Inclusive upper bound for the selected ticks.

  • part – Zero-based source recording. Required for multipart explicit ticks or windows.

Returns:

A Polars DataFrame with one row per active player and tick. See awpy.SNAPSHOT_PROPERTIES for fields. Multipart queries add part.

Raises:

ValueError – If selectors conflict, no selector is supplied, or a multipart local query has no part.

Notes

The window bounds the other selectors. One to four explicit ticks without other selectors use keyframe seeks. Other requests decode keyframe segments in parallel. Results are not cached.

Examples

>>> from awpy import Demo
>>> demo = Demo("match.dem")
>>> sampled = demo.snapshots(seconds=1.0)
>>> exact = demo.snapshots(ticks=[10000, 10100])
stats#

Read cached CS2 match statistics for each player.

Returns:

The cached Polars DataFrame. See the dataset guide for all columns.

Notes

Knife rounds are excluded. Includes kills, deaths, assists, headshots, openings, trades, multikills, KAST, ADR, clutches, and utility. clutch_1v1 through clutch_1v5 count wins by the opponent count when the clutch started. Their sum is clutches_won. See the dataset and reference guides for columns and definitions.

tick_rate#

Read the CS2 recording tick rate.

Returns:

Ticks per second from playback timing, or 64.0 when timing is unavailable.

Notes

Returns 64.0 when playback timing is unavailable.

tick_to_seconds(tick)#

Convert a local demo tick to seconds from recording start.

Parameters:

tick – Local signed demo tick.

Returns:

Seconds, using the demo tick rate.

ticks(props=None, players_only=True, *, part=None)#

Read selected networked CS2 properties at every recorded tick.

Parameters:
  • props – Raw field names or aliases. Defaults to X, Y, Z, health, armor, and team_num.

  • players_only – Merge each player pawn and controller when true; read all entities when false.

  • part – Zero-based source recording. Required for multipart explicit ticks or windows.

Returns:

A Polars DataFrame. Player rows include tick and steamid. Entity rows include tick, entity_id, entity_serial, and class_name. Multipart queries also include part.

Notes

Aliases include X, Y, Z, velocity_x, velocity_y, velocity_z, velocity, health, armor, team_num, name, and money. Types are Int64, Float64, Boolean, or String; mixed integers and floats use Float64. Use entity ID and serial together. Pawn fields and names can decode in parallel; other controller fields and all-entity queries use serial decoding. Results are not cached.

Read CS2 game events with Awpy Events#

Read game events by name when no dedicated dataset is available.

class awpy._awpy.Events#

Bases: object

Read recorded CS2 game events as cached Polars DataFrames.

Variables:
  • names – Sorted recorded event names.

  • counts – Event names mapped to occurrence counts.

Notes

Each frame contains tick and string-valued event fields. Participant fields such as attacker are user IDs. Dedicated datasets resolve Steam IDs. Multipart event frames also contain part.

Examples

>>> from awpy import Demo
>>> events = Demo("match.dem").events
>>> deaths = events["player_death"]
__contains__(key, /)#

Return bool(key in self).

__getitem__(key, /)#

Return self[key].

__iter__()#

Implement iter(self).

__len__()#

Return len(self).

counts#

Count each recorded CS2 game-event name.

Returns:

Event names mapped to occurrence counts.

names#

List recorded CS2 game-event names.

Returns:

Sorted event names present in the demo.

Check CS2 collision geometry with Awpy VisibilityChecker#

Check lines of sight against static collision geometry. Reuse the checker to avoid rebuilding its spatial index. See Visibility & map data.

class awpy.VisibilityChecker(source, *, version=None)#

Bases: object

Check CS2 line of sight against static collision geometry.

Parameters:
  • source – CS2 map name or local .mesh path. A Path is always a file path.

  • version – awpy-data ClientVersion for a map name. Omit to select the newest cached release; an empty cache selects the latest release.

Variables:
  • path – The loaded mesh path.

  • triangle_count – Number of collision triangles.

Raises:
  • FileNotFoundError – If the mesh file or map asset is missing.

  • ValueError – If the mesh is invalid or a version is combined with a file path.

Notes

Coordinates use Hammer units, with Z vertical. Missing map assets download through awpy.data. Reuse the checker to retain its spatial index. Smokes, moving doors, and bullet penetration are not modeled.

Examples

>>> from awpy import VisibilityChecker
>>> checker = VisibilityChecker("de_inferno")
>>> clear = checker.is_visible((-158.6, 819.1, 103.7), (1258.0, 455.5, 181.2))
is_occluded(a, b)#

Check whether static geometry blocks a CS2 line segment.

Parameters:
  • a – Start (x, y, z) in Hammer units.

  • b – End (x, y, z) in Hammer units.

Returns:

True if a collision triangle blocks the segment. The complement of is_visible.

is_occluded_many(a, b, *, threads=None)#

Check whether static geometry blocks each of many CS2 line segments.

Parameters:
  • a – Start (x, y, z) shared by every segment, or an (N, 3) array of starts.

  • b – Ends as an (N, 3) array, in Hammer units.

  • threads – Most threads to use, as for is_visible_many.

Returns:

A Boolean polars.Series named occluded, one value per segment. The complement of is_visible_many.

Raises:
  • ValueError – If a shape is wrong, a holds neither 1 nor N points, or threads is below 1.

  • TypeError – If the points are not float values.

  • RuntimeError – If a pool of threads threads cannot be created.

is_visible(a, b)#

Check whether static geometry leaves a CS2 line segment clear.

Parameters:
  • a – Start (x, y, z) in Hammer units.

  • b – End (x, y, z) in Hammer units.

Returns:

True if no collision triangle blocks the segment.

is_visible_many(a, b, *, threads=None)#

Check whether static geometry leaves each of many CS2 line segments clear.

Parameters:
  • a – Start (x, y, z) shared by every segment, or an (N, 3) array of starts.

  • b – Ends as an (N, 3) array, in Hammer units.

  • threads – Most threads to use. Omit to use a shared pool with a thread per core (RAYON_NUM_THREADS sets its size). Pass 1 inside a process pool that already uses every core.

Returns:

A Boolean polars.Series named visible, one value per segment. Each value equals is_visible on the same pair.

Raises:
  • ValueError – If a shape is wrong, a holds neither 1 nor N points, or threads is below 1.

  • TypeError – If the points are not float values.

  • RuntimeError – If a pool of threads threads cannot be created.

Notes

Points may be NumPy arrays or other buffers of float32 or float64 values, or sequences of (x, y, z) triples. float64 rounds to float32 as is_visible rounds Python floats. Inputs are copied, then the segments are checked in parallel with the GIL released.

Examples

>>> from awpy import VisibilityChecker
>>> checker = VisibilityChecker("de_inferno")
>>> eye = (-158.6, 819.1, 103.7)
>>> clear = checker.is_visible_many(eye, [(1258.0, 455.5, 181.2), (0.0, 0.0, 64.0)])
path#
triangle_count#

Number of triangles in the loaded mesh.

Query CS2 navigation meshes with Awpy NavMesh#

A map’s navigation mesh: the walkable areas and the graph connecting them. See Navigation meshes.

class awpy.NavMesh(source, *, version=None)#

Bases: object

Read CS2 navigation areas and query directed paths.

Parameters:
  • source – CS2 map name or local .nav path. A Path is always a file path.

  • version – awpy-data ClientVersion for a map name. Omit to select the newest cached release; an empty cache selects the latest release.

Variables:
  • path – The loaded navigation file path.

  • version – Navigation file format version.

  • sub_version – Navigation file format subversion.

  • is_analyzed – Whether the file contains analyzed bot-navigation data.

  • area_count – Number of navigation areas.

Raises:
  • FileNotFoundError – If the file or map asset is missing.

  • ValueError – If the navigation file is invalid or a version is combined with a file path.

Notes

World coordinates use Hammer units, with Z vertical. Missing map assets download through awpy.data. Keep the mesh for repeated queries. Navigation file versions differ from awpy-data release versions.

Examples

>>> from awpy import NavMesh
>>> nav = NavMesh("de_dust2")
>>> route = nav.find_path((-680.0, 1500.0, 0.0), (1200.0, 2400.0, 0.0))
__len__()#

Return len(self).

area(area_id)#

Read the complete geometry of one CS2 navigation area.

Parameters:

area_id – Navigation area ID.

Returns:

A NavArea dictionary, or None if the ID is absent.

area_count#

Number of areas in the mesh.

areas#

Read CS2 navigation area summaries as a Polars table.

Returns:

A Polars DataFrame with area ID, hull, flags, corner count, centroid, size, and neighbor count.

Notes

Use area(area_id) to read polygon corners and connected IDs.

find_area(point)#

Find the CS2 navigation area containing a world point.

Parameters:

point – World (x, y, z) in Hammer units.

Returns:

The area ID, or None if no area covers the point. Overlapping floors use the area height nearest the point Z.

find_path(start, end, *, weight='distance')#

Find a directed route through the CS2 navigation graph.

Parameters:
  • start – Start area ID or world (x, y, z) point.

  • end – End area ID or world (x, y, z) point.

  • weight – distance uses 3D centroid distances; hops uses area count; size uses adjacent area sizes.

Returns:

Area IDs from start through end. Empty if an endpoint has no area or no route exists.

Raises:

ValueError – If the weight is unknown.

is_analyzed#

Whether the mesh has been analyzed (bot-navigation data generated).

neighbors(area_id)#

List outgoing neighbors of one CS2 navigation area.

Parameters:

area_id – Navigation area ID.

Returns:

Distinct directly reachable area IDs.

path#
sub_version#

Nav-mesh sub-version.

version#

Nav-mesh major version (CS2 currently ships 36).

Estimate CS2 map control with Awpy#

Calculate map control from a demo. See Map control.

Estimate map control from player snapshots.

Models:

  • raycast: line of sight in any direction.

  • vision: line of sight within the horizontal field of view.

  • reachability: shortest travel distance over the nav graph.

Smokes block rays. Blinded players do not contribute to line-of-sight models. Fires block travel paths. Results estimate control, not exact player perception.

Use map_control() for a time series or map_control_at() for per-area labels. Assets are supplied by awpy.data.

awpy.map_control.LINE_OF_SIGHT_METHODS: frozenset[str] = frozenset({'raycast', 'vision'})#

Methods that cast rays through the collision mesh, and so need a VisibilityChecker.

class awpy.map_control.MapControlParams(eye_height: float = 64.0, crouch_eye_height: float = 46.0, target_height: float = 46.0, max_distance: float | None = None, contest_margin: float = 200.0, fov: float = 90.0, smoke_radius: float = 144.0, smoke_height: float = 60.0, fire_radius: float = 150.0, flash_threshold: float = 1.0)#

Bases: object

Set Awpy map-control inputs in Hammer units and degrees.

Variables:
  • eye_height (float) – Standing ray origin above the feet; default 64 Hammer units.

  • crouch_eye_height (float) – Crouched ray origin above the feet; default 46 Hammer units.

  • target_height (float) – Ray endpoint above a navigation area; default 46 Hammer units.

  • max_distance (float | None) – Maximum ray distance, or None for no limit.

  • contest_margin (float) – Maximum travel-distance difference for a contested area; default 200.

  • fov (float) – Horizontal field of view for vision; default 90 degrees. Values of 360 or more remove the limit.

  • smoke_radius (float) – Smoke sphere radius; default 144 Hammer units.

  • smoke_height (float) – Smoke sphere center above its landing point; default 60 Hammer units.

  • fire_radius (float) – Blocked ground radius around a fire; default 150 Hammer units.

  • flash_threshold (float) – Recorded flash onset duration above which a currently blinded player contributes no sight; default 1 second.

eye_height: float = 64.0#
crouch_eye_height: float = 46.0#
target_height: float = 46.0#
max_distance: float | None = None#
contest_margin: float = 200.0#
fov: float = 90.0#
smoke_radius: float = 144.0#
smoke_height: float = 60.0#
fire_radius: float = 150.0#
flash_threshold: float = 1.0#
awpy.map_control.Method#

Supported Awpy map-control methods.

alias of Literal[‘raycast’, ‘vision’, ‘reachability’]

awpy.map_control.map_control(demo: Demo, *, method: Method = 'vision', ticks: int | list[int] | None = None, every: int | None = None, seconds: float | None = None, events: str | list[str] | None = None, start_tick: int | None = None, end_tick: int | None = None, part: int | None = None, params: MapControlParams | None = None, map_name: str | None = None, version: int | None = None) → pl.DataFrame#

Estimate CS2 map control as a Polars time series.

Parameters:
  • demo – The Awpy demo whose player state is queried.

  • method – "raycast" for all-direction sight, "vision" for a horizontal field of view, or "reachability" for graph travel distance.

  • ticks – One local demo tick or a list of local ticks.

  • every – Positive sampling stride in ticks. Do not combine with seconds.

  • seconds – Positive sampling interval in seconds. Do not combine with every.

  • events – One game-event name or a list of names whose ticks are selected.

  • start_tick – Inclusive lower bound for the tick selection.

  • end_tick – Inclusive upper bound for the tick selection.

  • part – Zero-based recording index. Required for multipart local ticks or windows.

  • params – Model settings. Omit for MapControlParams defaults.

  • map_name – Override the map name in the demo header.

  • version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

One row per selected tick with method, ct, t, contested, neutral, and net_control. The first four fractions are weighted by area size and sum to 1. net_control is CT minus T. Multipart queries also include part.

Raises:

ValueError – If the method, tick selection, or map name is invalid.

Notes

Sight models account for static geometry, active smokes, and eligible flash state. Reachability accounts for active fires. These are control estimates, not exact player perception.

Examples

>>> from awpy import Demo
>>> from awpy.map_control import map_control
>>> result = map_control(Demo("match.dem"), seconds=1.0)
awpy.map_control.map_control_at(demo: Demo, tick: int, *, part: int | None = None, method: Method = 'vision', params: MapControlParams | None = None, map_name: str | None = None, version: int | None = None) → pl.DataFrame#

Estimate CS2 control for each navigation area at one tick.

Parameters:
  • demo – The Awpy demo whose player state is queried.

  • tick – Local demo tick to evaluate.

  • part – Zero-based recording index. Required for multipart local ticks or windows.

  • method – "raycast" for all-direction sight, "vision" for a horizontal field of view, or "reachability" for graph travel distance.

  • params – Model settings. Omit for MapControlParams defaults.

  • map_name – Override the map name in the demo header.

  • version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

A Polars DataFrame with area_id, control, ct, t, centroid_x, centroid_y, centroid_z, and size. Labels are ct, t, contested, or neutral. Multipart queries also include part.

Raises:

ValueError – If the method, tick selection, or map name is invalid.

Calculate Awpy map control from player observations#

Calculate map control from a nav mesh and player positions.

awpy._awpy.compute_map_control(nav, players, *, visibility=None, method='vision', smokes=[], fires=[], detail=True, eye_height=64.0, crouch_eye_height=46.0, target_height=46.0, max_distance=None, contest_margin=200.0, fov=90.0)#

Estimate CS2 map control from player observations.

Parameters:
  • nav – Loaded NavMesh.

  • players – Living-player tuples (x, y, z, side, crouched, blind, yaw). Coordinates use Hammer units. Yaw uses degrees and can be None.

  • visibility – Collision checker, required by raycast and vision.

  • method – raycast for all-direction sight, vision for horizontal field of view, or reachability for graph travel distance.

  • smokes – Active (x, y, z, radius) smoke spheres for both sight models.

  • fires – Active (x, y, z, radius) fire spheres for reachability.

  • detail – Include per-area arrays. Default true.

  • eye_height – Standing ray origin above the feet; default 64 Hammer units.

  • crouch_eye_height – Crouched ray origin above the feet; default 46 Hammer units.

  • target_height – Ray target above the area floor; default 46 Hammer units.

  • max_distance – Maximum ray distance in Hammer units, or None for no limit.

  • contest_margin – Travel-distance difference for contested areas; default 200 Hammer units.

  • fov – Horizontal field of view in degrees; default 90. Values of 360 or more, or missing yaw, remove the limit.

Returns:

A dictionary with ct_fraction, t_fraction, contested_fraction, neutral_fraction, and net_control. Detailed results also contain area_ids, control, ct, and t lists.

Raises:

ValueError – If the method is unknown or a sight model has no collision checker.

Predict CS2 round outcomes with Awpy#

Install awpy[win-prob] to predict round outcomes and calculate player WPA. For examples, see Predict CS2 round outcomes with Awpy.

Predict CS2 round outcomes with the optional awpy[win-prob] extra.

awpy.win_prob.ROUND_END_REASONS = ('bomb_defusal', 'ct_eliminated', 't_eliminated', 'bomb_exploded', 'time_ran_out')#

The round-end reasons that the model predicts.

class awpy.win_prob.RoundEndModel(model_id: str, score: Callable[[DataFrame], DataFrame])#

Bases: object

A fitted Kumo context that scores ticks from one or more demos.

Use load_model() to load a released context.

predict(demo: Demo, *, ticks: int | Sequence[int] | Series, part: int | None = None) → DataFrame#

Predict the round-end reason and the winning side at exact demo ticks.

Parameters:
  • demo – CS2 demo to score.

  • ticks – One tick or a sequence of ticks in the recording. Each tick must be from freeze end to the round decision, inclusive.

  • part – Zero-based recording index. Necessary for a multipart demo.

Returns:

One row for each requested tick, in input order. The columns are tick, round_num, predicted_round_end_reason, one probability for each reason in ROUND_END_REASONS, ct_win_probability, and t_win_probability. Probabilities are from 0 to 1.

Raises:

ValueError – If a tick is not valid, is not in live play, or has no player snapshot.

wpa(demo: Demo, *, round_num: int | None = None, part: int | None = None) → DataFrame#

Calculate player Win Probability Added (WPA) from damage and kills.

Parameters:
  • demo – CS2 demo to score.

  • round_num – Completed round to score. If None, score all completed rounds in the recording.

  • part – Zero-based recording index. Necessary for a multipart demo.

Returns:

The columns steamid (UInt64) and wpa (Float64), sorted by WPA. WPA is the sum of a player’s gains and losses in percentage points.

Raises:

ValueError – If the recording or the round is not available.

Notes

Compare the predictions at the end of each attack tick and of the tick before it. Count each enemy attacker and victim pair one time for each tick, also when a hit kills. The pairs that attack for the side that gains share the change equally. Add each share to the attacker and subtract it from the victim. Both players must have Steam IDs. Ignore a tick if one of the two ticks has no player snapshot.

awpy.win_prob.get_model(model: str = 'kumo-round-end/v1.0.0', *, force: bool = False) → Path#

Download a versioned Kumo context and verify its release checksum.

Parameters:
  • model – Model ID, for example kumo-round-end/v1.0.0.

  • force – If True, download the context also when it is in the cache.

Returns:

The path of the context Parquet file in the Awpy cache.

Raises:
  • ValueError – If the ID, manifest, or checksum is not valid.

  • FileNotFoundError – If the release or context does not exist.

  • OSError – If the download or the cache write fails.

awpy.win_prob.load_model(model: str = 'kumo-round-end/v1.0.0', *, device: str | None = None) → RoundEndModel#

Load a round-end model. Download its context if it is not in the cache.

Parameters:
  • model – Model ID, for example kumo-round-end/v1.0.0.

  • device – PyTorch device. The default is CUDA if it is available, or CPU.

Returns:

A model that is ready to score ticks. Keep it to use the fitted context again.

Raises:

ImportError – If the awpy[win-prob] dependencies are not installed.

Notes

If the pretrained Kumo checkpoint is not in the Hugging Face cache, also download the checkpoint.

Draw CS2 data with Awpy and matplotlib#

Radar rendering, game-state frames, heatmaps, and GIFs. Requires the plot extra — pip install 'awpy[plot]'. See Plotting.

Draw Counter-Strike 2 replay data with matplotlib and awpy-data.

Install the awpy[plot] extra. Map images and coordinate transforms come from awpy.data. Set version= to select an awpy-data release.

Use frame for player state, heatmap for position density, and gif for animations. Plot functions return matplotlib figures and axes for customization.

Examples

>>> from awpy import Demo, plot
>>> demo = Demo("match.dem")
>>> deaths = demo.kills.select("victim_x", "victim_y", "victim_z").rows()
>>> fig, ax = plot.heatmap(demo.header["map_name"], deaths, method="kde")
>>> fig.savefig("deaths.png")
awpy.plot.CONTESTED_COLOR = '#A855F7'#

Fill color for map-control areas held by both sides at once (see map_control()).

awpy.plot.NAV_COLOR = '#F5A524'#

Fill color for nav areas drawn by nav() — a muted amber that reads as “the walkable surface” without competing with the radar underneath.

awpy.plot.NAV_HIGHLIGHT_COLOR = '#22D3EE'#

Fill color for the areas passed as highlight to nav().

awpy.plot.RADAR_SIZE = 1024#

Side length, in pixels, of the awpy-data radar images.

awpy.plot.SMOKE_RADIUS = 144.0#

World-unit radii of a deployed smoke cloud and a molotov/incendiary fire.

awpy.plot.T_COLOR = '#EAB308'#

Default marker colors, keyed off Player.side.

class awpy.plot.Player(x: float, y: float, z: float = 0.0, side: str | None = None, hp: int | None = None, armor: int | None = None, yaw: float | None = None, label: str | None = None, color: str | None = None, has_bomb: bool = False)#

Bases: object

Set the drawing attributes for one CS2 player marker.

Variables:
  • x (float) – World X position in Hammer units.

  • y (float) – World Y position in Hammer units.

  • z (float) – World altitude in Hammer units; default 0.

  • side (str | None) – t or terrorist, or ct or counter-terrorist. Matching ignores case.

  • hp (int | None) – Health for the marker bar. Zero draws a dim death marker; None omits the bar.

  • armor (int | None) – Armor for the marker bar, or None to omit it.

  • yaw (float | None) – View direction in degrees, counterclockwise from positive X. None omits it.

  • label (str | None) – Text beside the marker, or None.

  • color (str | None) – Matplotlib color override, or None to use the side color.

  • has_bomb (bool) – Add a red border for the bomb carrier.

x: float#
y: float#
z: float = 0.0#
side: str | None = None#
hp: int | None = None#
armor: int | None = None#
yaw: float | None = None#
label: str | None = None#
color: str | None = None#
has_bomb: bool = False#
awpy.plot.frame(map_name: str, players: Iterable[Player], *, bomb: Sequence[float] | None = None, bomb_planted: bool = False, smokes: Iterable[Sequence[float]] | None = None, fires: Iterable[Sequence[float]] | None = None, grenades: Iterable[Sequence[float] | Mapping[str, Any]] | None = None, smoke_radius: float = 144.0, fire_radius: float = 150.0, version: int | None = None, lower: bool = False, off_level_alpha: float = 0.3, ax: Axes | None = None) → tuple[Figure, Axes]#

Draw CS2 players, bomb state, and projectiles with matplotlib.

Parameters:
  • map_name – CS2 map name.

  • players – Player markers. Set has_bomb=True on the bomb carrier.

  • bomb – World (x, y, z) bomb position, or None. Drawn as an orange diamond.

  • bomb_planted – Add a green border to the planted bomb.

  • smokes – World (x, y) or (x, y, z) centers of active smoke clouds.

  • fires – World (x, y) or (x, y, z) origins of active fires.

  • grenades – Projectile positions or mappings with pos or x/y/z fields. A mapping can set type or color. Include only rows at this tick.

  • smoke_radius – Smoke radius in Hammer units; default 144.

  • fire_radius – Fire radius in Hammer units; default 150.

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

  • lower – Draw the lower-level radar.

  • off_level_alpha – Opacity for markers on the other map level. Zero hides them.

  • ax – Existing matplotlib axes, or None to create a figure.

Returns:

The matplotlib (Figure, Axes) pair.

awpy.plot.frame_levels(map_name: str, players: Iterable[Player], *, bomb: Sequence[float] | None = None, bomb_planted: bool = False, version: int | None = None) → tuple[Figure, tuple[Axes, ...]]#

Draw CS2 player state on one panel per map level.

Parameters:
  • map_name – Map to draw, e.g. "de_nuke".

  • players – A Player per player to draw. Set has_bomb on the carrier to give its marker a red border.

  • bomb – World (x, y, z) of the bomb, drawn as an orange diamond.

  • bomb_planted – Give the bomb a green border to mark it planted and ticking.

  • version – awpy-data release to use (default: newest cached).

Returns:

The figure and axes tuple. Two-level maps return upper and lower panels; single-level maps return one panel.

awpy.plot.gif(map_name: str, frames: Sequence[Iterable[Player] | dict[str, Any]], path: str, *, fps: int = 2, version: int | None = None, lower: bool = False, dpi: int = 150) → None#

Save CS2 player-state frames as an animated GIF.

Parameters:
  • map_name – CS2 map name.

  • frames – One player iterable or frame keyword dictionary for each output frame.

  • path – Destination GIF file path.

  • fps – Frames per second.

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

  • lower – Draw the lower-level radar.

  • dpi – Render resolution in dots per inch.

awpy.plot.has_lower_level(map_name: str, *, version: int | None = None) → bool#

Check whether awpy-data defines a lower radar level.

Parameters:
  • map_name – CS2 map name, such as "de_inferno".

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

Returns:

Whether the map defines a lower section.

awpy.plot.heatmap(map_name: str, points: Iterable[Sequence[float]], *, method: Literal['hex', 'hist', 'kde'] = 'hex', bins: int = 48, cmap: str = 'magma', alpha: float = 0.8, bandwidth: float = 16.0, version: int | None = None, lower: bool = False, ax: Axes | None = None) → tuple[Figure, Axes]#

Draw CS2 position density over a radar image.

Parameters:
  • map_name – CS2 map name.

  • points – World (x, y) or (x, y, z) positions.

  • method – hex for hexagonal bins, hist for square bins, or kde for Gaussian smoothing.

  • bins – Grid resolution for hexagonal and square bins. Gaussian smoothing uses a fixed grid.

  • cmap – Matplotlib colormap name.

  • alpha – Overlay opacity from 0 to 1.

  • bandwidth – Gaussian smoothing width in radar pixels.

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

  • lower – Draw the lower-level radar.

  • ax – Existing matplotlib axes, or None to create a figure.

Returns:

The matplotlib (Figure, Axes) pair.

Raises:

ValueError – If the method is unknown.

Notes

Positions on another radar level are omitted with a warning. Use heatmap_levels to draw all levels.

awpy.plot.heatmap_levels(map_name: str, points: Iterable[Sequence[float]], *, method: Literal['hex', 'hist', 'kde'] = 'hex', bins: int = 48, cmap: str = 'magma', alpha: float = 0.8, bandwidth: float = 16.0, version: int | None = None) → tuple[Figure, tuple[Axes, ...]]#

Draw CS2 position density on one panel per map level.

Parameters:
  • map_name – CS2 map name.

  • points – World (x, y) or (x, y, z) positions.

  • method – hex for hexagonal bins, hist for square bins, or kde for Gaussian smoothing.

  • bins – Grid resolution for hexagonal and square bins. Gaussian smoothing uses a fixed grid.

  • cmap – Matplotlib colormap name.

  • alpha – Overlay opacity from 0 to 1.

  • bandwidth – Gaussian smoothing width in radar pixels.

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

Returns:

The figure and axes tuple, upper level first. A single-level map returns one panel.

Raises:

ValueError – If the method is unknown.

awpy.plot.is_lower_level(map_name: str, z: float, *, version: int | None = None) → bool#

Check whether a CS2 altitude belongs to the lower radar level.

Parameters:
  • map_name – CS2 map name, such as "de_inferno".

  • z – World altitude in Hammer units.

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

Returns:

Whether the altitude is in the lower section. False for a single-level map.

awpy.plot.map_control(demo: Demo, tick: int, *, method: Literal['raycast', 'vision', 'reachability'] = 'vision', params: MapControlParams | None = None, players: bool = True, occluders: bool = True, legend: bool = True, alpha: float = 0.5, version: int | None = None, map_name: str | None = None, lower: bool = False, ax: Axes | None = None) → tuple[Figure, Axes]#

Draw estimated CS2 map control at one demo tick.

Parameters:
  • demo – The parsed demo.

  • tick – The tick to draw.

  • method – "raycast", "vision", or "reachability" (see awpy.map_control).

  • params – Model parameters (defaults if omitted).

  • players – Overlay the players at the tick.

  • occluders – Draw the active smokes (vision) or fires (reachability).

  • legend – Draw a legend with each side’s share of the map.

  • alpha – Opacity of the area shading.

  • version – awpy-data release to use (default: newest cached).

  • map_name – Override the map (defaults to the demo header’s map).

  • lower – Draw the lower-level radar of a multi-level map.

  • ax – Draw onto an existing axes instead of creating a new figure.

Returns:

The matplotlib (Figure, Axes) pair.

awpy.plot.nav(map_name: str, *, highlight: Sequence[int] | None = None, version: int | None = None, lower: bool = False, alpha: float = 0.25, edge: bool = True, legend: bool = True, ax: Axes | None = None) → tuple[Figure, Axes]#

Draw CS2 navigation areas and selected routes.

Parameters:
  • map_name – Map to draw, e.g. "de_dust2".

  • highlight – Area ids to emphasize in a contrasting color, drawn above the rest. Pass the result of awpy.NavMesh.find_path() to show a route.

  • version – awpy-data release to use (default: newest cached).

  • lower – Draw the lower-level radar of a multi-level map. Areas are filtered to the level being drawn, so a two-level map needs one call per level (or use frame_levels()-style side-by-side axes).

  • alpha – Fill opacity of the areas.

  • edge – Outline each area, which is what makes the mesh legible as a mesh.

  • legend – Label the area count (and highlighted count, if any).

  • ax – Draw onto an existing axes instead of creating a new figure.

Returns:

The matplotlib (Figure, Axes) pair.

awpy.plot.pixel_to_world(map_name: str, point: Sequence[float], *, version: int | None = None) → tuple[float, float]#

Convert radar pixels to CS2 world coordinates.

Parameters:
  • map_name – CS2 map name, such as "de_inferno".

  • point – World or radar coordinates, as specified by the function.

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

Returns:

(x, y) in Hammer units.

awpy.plot.radar(map_name: str, *, version: int | None = None, lower: bool = False, ax: Axes | None = None) → tuple[Figure, Axes]#

Draw a CS2 radar image on matplotlib axes.

Parameters:
  • map_name – Map to draw, e.g. "de_inferno".

  • version – awpy-data release to use (default: newest cached).

  • lower – Draw the lower-level radar of a multi-level map.

  • ax – Draw onto an existing axes instead of creating a new figure.

Returns:

The matplotlib (Figure, Axes) pair, with hidden axes and radar-pixel coordinates.

awpy.plot.round_win_probability(demo: Demo, round_num: int, *, model: RoundEndModel | str = 'kumo-round-end/v1.0.0', part: int | None = None, step_seconds: float = 1.0, show_bomb_plants: bool = True, show_kills: bool = True, title: str | None = None, ax: Axes | None = None) → tuple[Figure, Axes]#

Plot the CT win probability through a completed CS2 round.

Parameters:
  • demo – CS2 demo to score.

  • round_num – Round number in the selected recording.

  • model – A loaded model, or the ID of a model to load.

  • part – Zero-based recording index. Necessary for a multipart demo.

  • step_seconds – Time between samples. Each kill, plant, and the round end also get a sample.

  • show_bomb_plants – Draw a solid red line at each completed plant.

  • show_kills – Put a dot in the victim’s team color at each enemy kill.

  • title – Plot title. The default is Round X | filename.

  • ax – Axes to draw on. If None, make a new figure.

Returns:

The matplotlib figure and axes.

Raises:

ValueError – If the round is not available or has no player snapshots.

Notes

Install awpy[win-prob,plot]. The line is CT blue above 50% and T gold below 50%. Time starts at freeze end. A tick without a player snapshot gets no sample.

awpy.plot.world_to_pixel(map_name: str, point: Sequence[float], *, version: int | None = None) → tuple[float, float]#

Convert CS2 world coordinates to radar pixels.

Parameters:
  • map_name – CS2 map name, such as "de_inferno".

  • point – World or radar coordinates, as specified by the function.

  • version – awpy-data ClientVersion. Omit to use the newest cached release; an empty cache selects the latest release.

Returns:

(px, py) pixels, with origin at the upper left and Y increasing downward.

Download CS2 map assets with awpy.data#

Download and cache awpy-data assets under ~/.awpy/<version>/. Set AWPY_DATA_DIR to change the root path. Accessors use the newest cached release unless version= is set. See Visibility & map data.

Download and cache versioned CS2 assets from awpy-data.

Assets include collision meshes, nav meshes, radar images, and coordinate tables. The cache is ~/.awpy/<ClientVersion>/. Set AWPY_DATA_DIR to change its root.

Path helpers download missing assets and return local paths. Set version= to select a release. Otherwise, use the newest cached release, or the latest release if the cache is empty. Use update() or awpy get to check for updates.

awpy.data.AWPY_DATA_DIR = PosixPath('/home/docs/.awpy')#

Root of the local asset cache. Read at call time, so tests (or callers) may reassign awpy.data.AWPY_DATA_DIR to redirect the cache.

awpy.data.DATA_REPO = 'pnxenopoulos/awpy-data'#

GitHub repository the assets are published from.

awpy.data.available_maps(version: int | None = None) → list[str]#

List CS2 maps in an awpy-data release.

Parameters:

version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

The map names from the release manifest.

Notes

A missing JSON file downloads on demand.

awpy.data.clear(version: int | None = None) → None#

Delete cached awpy-data assets.

Parameters:

version – ClientVersion to delete. Omit it to delete the entire asset cache.

Raises:

OSError – If the cache cannot be removed.

awpy.data.data_dir(version: int | None = None) → Path#

Get the local directory for an awpy-data release.

Parameters:

version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

The release path. This call does not create the directory or download assets.

awpy.data.latest_version() → str#

Read the latest awpy-data release tag from GitHub.

Returns:

The ClientVersion tag as a string.

Raises:
  • urllib.error.URLError – If the network or GitHub API request fails.

  • RuntimeError – If the response has no release tag.

Notes

The successful result is cached for this Python process.

awpy.data.local_versions() → list[str]#

List cached awpy-data version directories.

Returns:

Version names, oldest first; numeric names use numeric order.

awpy.data.manifest(version: int | None = None) → dict[str, Any]#

Read awpy-data release metadata.

Parameters:

version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

Version identifiers, map names, and per-file checksums as a dictionary.

Notes

A missing JSON file downloads on demand.

awpy.data.map_data(version: int | None = None) → dict[str, Any]#

Read CS2 world-to-radar transforms from awpy-data.

Parameters:

version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

Map names mapped to coordinate transforms and vertical sections.

Notes

A missing JSON file downloads on demand.

awpy.data.mesh_path(map_name: str, version: int | None = None) → Path#

Get a CS2 collision .mesh file from awpy-data.

Parameters:
  • map_name – CS2 map name, such as "de_inferno".

  • version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

The local file path. Collision geometry for VisibilityChecker.

Raises:
  • FileNotFoundError – If the selected release has no matching map asset.

  • urllib.error.URLError – If a required download fails.

Notes

Missing assets download on demand. Cached assets can be used offline.

awpy.data.nav_path(map_name: str, version: int | None = None) → Path#

Get a CS2 navigation .nav file from awpy-data.

Parameters:
  • map_name – CS2 map name, such as "de_inferno".

  • version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

The local file path. Walkable areas for NavMesh.

Raises:
  • FileNotFoundError – If the selected release has no matching map asset.

  • urllib.error.URLError – If a required download fails.

Notes

Missing assets download on demand. Cached assets can be used offline.

awpy.data.radar_path(map_name: str, version: int | None = None, *, lower: bool = False) → Path#

Get a CS2 radar .png file from awpy-data.

Parameters:
  • map_name – CS2 map name, such as "de_inferno".

  • version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

  • lower – Select the lower-level radar image for a map with multiple levels.

Returns:

The local file path. Radar background for awpy.plot.

Raises:
  • FileNotFoundError – If the selected release has no matching map asset.

  • urllib.error.URLError – If a required download fails.

Notes

Missing assets download on demand. Cached assets can be used offline.

awpy.data.resolve_version(version: int | None = None) → str#

Select an awpy-data release without downloading its assets.

Parameters:

version – awpy-data ClientVersion. Use the newest cached release when omitted; download the latest release if the cache is empty.

Returns:

The selected release tag as a string.

Notes

An explicit version does not make a network request. An empty cache can require a GitHub API request.

awpy.data.update(version: int | None = None, *, force: bool = False) → Path#

Download every asset for an awpy-data release.

Parameters:
  • version – ClientVersion to install. Omit it to query the latest GitHub release.

  • force – Delete this release cache and download it again.

Returns:

The local release directory.

Raises:
  • FileNotFoundError – If a required release asset does not exist.

  • urllib.error.URLError – If a required download fails.

Notes

This update operation checks the latest release when no version is supplied. Read helpers instead prefer the newest cached release.

List Awpy snapshot fields and CS2 events#

List snapshot properties and common game events without parsing a demo. Both catalogs are also available from awpy. Use demo.events.names for the events in a specific demo.

awpy.schema.SNAPSHOT_PROPERTIES: dict[str, str]#

Per-player snapshot feature name -> the CS2 network property it is read from.

Every key is a column of awpy.Demo.snapshots() (besides tick), and the value is the engine property — or the derivation, for computed ones like world position. The direct fields (health, money, the is_* flags, …) can also be passed to awpy.Demo.ticks(), either by these readable names or by their raw network names.

awpy.schema.GAME_EVENTS: dict[str, str]#

Common CS2 game event name -> a one-line description of what it means.

Not exhaustive: a demo may carry events that are not listed here. For what a particular demo contains, use demo.events.names (or demo.events.counts), and demo.events[name] to pull any of them as a DataFrame.

Handle Awpy parsing errors#

exception awpy.InvalidDemoError#

Bases: Exception