Cell 7: 100% avoiding grenade parsing by using parse_ticks only
import glob
import numpy as np
from awpy import Demo
1) Tick‑level props guaranteed by demoparser2 for CS2 1v1 demos
feature_cols = [
"X", # world X
"Y", # world Y
"Z", # world Z
"pitch", # look up/down
"yaw", # look left/right
"health", # hit points
"is_airborne", # in the air?
]
button bit‑mask constants for label extraction
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
for path in demo_files:
dem = Demo(path)
try:
# ⚡️ ONLY parse tick data → never touches grenades or rounds
tick_df = dem.parse_ticks(player_props=feature_cols + ["buttons"])
df = tick_df.to_pandas()
except Exception as e:
print(f"⚠️ Skipping {path}: parse_ticks() error → {e}")
continue
# 3) Check for missing columns
missing = [c for c in feature_cols + ["buttons"] if c not in df.columns]
if missing:
print(f"⚠️ Skipping {path}: missing {missing}")
continue
# 4) Build feature matrix (drop the buttons column)
feats = df[feature_cols].astype(np.float32, copy=False).to_numpy()
# 5) Decode the buttons bitmask into a single action label
btn = df["buttons"].astype(int).to_numpy()
actions = np.zeros(len(btn), dtype=np.int64)
# priority: shoot > forward > left > right
actions[btn & IN_ATTACK > 0] = 4
actions[btn & IN_FORWARD > 0] = 1
actions[btn & IN_MOVELEFT > 0] = 2
actions[btn & IN_MOVERIGHT > 0] = 3
all_X.append(feats)
all_Y.append(actions)
6) Concatenate across all demos
if not all_X:
raise RuntimeError("No demos parsed successfully—check errors above.")
X = np.concatenate(all_X, axis=0) # shape = [total_ticks, len(feature_cols)]
Y = np.concatenate(all_Y, axis=0) # shape = [total_ticks,]
print("✔️ X shape:", X.shape, " Y shape:", Y.shape)
print(X)
Assistant
Okay, I understand the Python code you've provided. It's designed to parse Counter-Strike 2 (CS2) demo files, extract player movement and action data at the tick level, and prepare it for use in a machine learning model. The code prioritizes speed and avoids grenade parsing to prevent errors, focusing solely on tick data.
Here's a breakdown of what the code does, along with some potential improvements and considerations:
1. Imports and Feature Definition:
It imports necessary libraries: glob for finding files, numpy for numerical operations, and awpy for demo parsing.
feature_cols: Defines the player properties to extract from each tick (X, Y, Z coordinates, pitch, yaw, health, and airborne status).
Button Bitmasks: Defines constants for decoding the "buttons" bitmask, representing player actions like shooting, moving forward, left, and right.
2. Demo File Discovery:
glob.glob("*.dem"): Finds all files with the .dem extension in the current directory.
Prints the list of found demo files.
3. Demo Parsing Loop:
The code iterates through each demo file found.
dem = Demo(path): Creates an awpy.Demo object for the current demo file.
tick_df = dem.parse_ticks(player_props=feature_cols + ["buttons"]): This is the key part. It uses awpy's parse_ticks function to extract data at the tick level. Crucially, it only parses tick data and avoids parsing grenades or rounds, which can sometimes cause errors. The specified player_props argument ensures that only the desired player properties (including "buttons") are extracted, further optimizing the parsing process.
Error Handling: Includes a try...except block to catch potential errors during parsing. If an error occurs, it prints an error message and skips to the next demo file.
Converts the tick data to Pandas DataFrame using to_pandas().
Missing Column Check: Checks if all required columns (feature_cols + "buttons") are present in the DataFrame. If any are missing, it prints a warning and skips the demo.
4. Feature Matrix and Action Label Extraction:
Feature Matrix Creation: Extracts the features defined in feature_cols from the DataFrame and converts them into a NumPy array (feats). The data type is explicitly set to for efficiency.
np.float32
Action Label Decoding:
Extracts the "buttons" column as a NumPy array of integers (btn).
Creates an array actions to store the decoded action labels.
Decodes the button bitmask to determine the player's action. It uses a priority system: shoot > forward > left > right.
If the IN_ATTACK bit is set, the action is labeled as 4 (shoot).
Otherwise, if the IN_FORWARD bit is set, the action is labeled as 1 (forward).
And so on for left and right.
If no relevant bits are set, the action remains 0 (no action).
5. Data Aggregation:
The extracted features (feats) and action labels (actions) are appended to the all_X and all_Y lists, respectively.
6. Data Concatenation and Output:
After processing all demos, the code concatenates the data from all demos into single NumPy arrays X (features) and Y (actions).
Error Handling: Checks if any demos were parsed successfully. If not, it raises a RuntimeError.
Prints the shapes of the resulting feature matrix X and action labels Y.
Prints the X array.
In summary, this code provides a robust and efficient way to extract player movement and action data from CS2 demo files using the awpy library, specifically focusing on tick-level data and avoiding potential parsing errors related to grenades or rounds.