> ## Documentation Index
> Fetch the complete documentation index at: https://docs.granuleux.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Round-model features

> Build a per-tick training table for a round win model from /rounds and /states.

This guide turns one game into a table with one row per state sample of live round time: side-level features at that
moment and the round winner as the label. Run it over many games to get a training set for an in-round win
probability model.

Cost per game: 1 unit for `/rounds` plus 5 per round for `/states` (a 24-round map is about 121 units).

## Fetch

```python theme={null}
import os, requests
import numpy as np
import pandas as pd

API = "https://api.granuleux.com"
H = {"Authorization": f"Bearer {os.environ['CS2API_KEY']}"}

def get(path, **params):
    r = requests.get(f"{API}{path}", headers=H, params=params, timeout=60)
    r.raise_for_status()
    return r.json()["data"]

GAME = "2398724:1"
game = get(f"/v1/games/{GAME}")
assert game["has_state"], "this game has no player state"

rounds = pd.DataFrame(get(f"/v1/games/{GAME}/rounds"))
FIELDS = "t_round,side,alive,x,y,z,hp,armor,helmet,kit,equip,cash,flash,defusing,in_bomb_zone,place"
states = pd.concat(
    [pd.DataFrame(get(f"/v1/games/{GAME}/states", round=int(n), fields=FIELDS)) for n in rounds.round_no],
    ignore_index=True)
```

`steamid` stays a string, so pandas keeps it exact.

## Drop non-players

Coaches can appear in raw state: they sit in a team slot but are never alive. Keep only the game roster.

```python theme={null}
roster = {p["steamid"] for p in game["roster"]}
states = states[states.steamid.isin(roster)]
```

## Bomb site positions

The API has no site coordinates, but every sample has the player's map callout in `place`. The mean position of the
samples standing in `BombsiteA` / `BombsiteB` is a usable site centre for this map.

```python theme={null}
sites = (states[states.place.isin(["BombsiteA", "BombsiteB"])]
         .groupby("place")[["x", "y", "z"]].mean())

def dist_to(site, df):
    if site not in sites.index:
        return pd.Series(np.nan, index=df.index)
    c = sites.loc[site]
    return np.sqrt((df.x - c.x) ** 2 + (df.y - c.y) ** 2 + (df.z - c.z) ** 2)

states["d_a"] = dist_to("BombsiteA", states)
states["d_b"] = dist_to("BombsiteB", states)
states["d_site"] = states[["d_a", "d_b"]].min(axis=1)      # world units to the nearer site
```

## Per-side features at each sample

```python theme={null}
alive = states[states.alive].copy()
alive["flashed"] = alive.flash > 0
alive["armored"] = alive.armor > 0

per_side = alive.groupby(["round_no", "tick", "side"]).agg(
    alive=("steamid", "size"),
    hp=("hp", "sum"),
    armored=("armored", "sum"),
    helmets=("helmet", "sum"),
    kits=("kit", "sum"),
    equip=("equip", "sum"),
    cash=("cash", "sum"),
    flashed=("flashed", "sum"),
    in_bomb_zone=("in_bomb_zone", "sum"),
    min_d_site=("d_site", "min"),
    defusing=("defusing", "any"),
)
wide = per_side.unstack("side")
wide.columns = [f"{side.lower()}_{name}" for name, side in wide.columns]

# every sampled tick, also those where one side has nobody alive
ticks = states.groupby(["round_no", "tick"]).t_round.first().to_frame()
X = ticks.join(wide)
counts = [c for c in X.columns if c.endswith(("_alive", "_hp", "_armored", "_helmets", "_kits", "_equip",
                                               "_cash", "_flashed", "_in_bomb_zone"))]
X[counts] = X[counts].fillna(0)
X = X.drop(columns=["t_kits", "t_defusing"], errors="ignore")   # CT-only signals
X = X.reset_index()
```

## Round context and the label

```python theme={null}
r = rounds.set_index("round_no")
X["score_ct"] = X.round_no.map(r.score_ct_before)
X["score_t"] = X.round_no.map(r.score_t_before)
X["ct_equip_start"] = X.round_no.map(r.ct_equip)        # team equipment value at freeze end
X["t_equip_start"] = X.round_no.map(r.t_equip)

plant = X.round_no.map(r.plant_tick)                     # NaN when the bomb was never planted
X["planted"] = plant.notna() & (X.tick >= plant)
X["t_since_plant"] = np.where(X.planted, (X.tick - plant) / 64, np.nan)
site = X.round_no.map(r.bomb_site)
X["plant_site_b"] = np.where(X.planted, (site == "B").astype(float), np.nan)

X["ct_win"] = (X.round_no.map(r.winner_side) == "CT").astype(int)   # label
X["game_id"] = game["game_id"]
```

`X` now has one row per sample with columns such as `ct_alive`, `t_alive`, `ct_hp`, `t_hp`, `ct_equip`,
`t_min_d_site`, `ct_flashed`, `ct_defusing`, `planted`, `t_since_plant`, `t_round` and the label `ct_win`.

## Things to get right

* **Split by game, not by row.** Samples of the same round are highly correlated; put whole games (better: whole
  matches) in either train or test.
* **No leakage from round results.** `winner_side`, `reason`, `end_tick`, `duration_s` and `n_kills` describe the
  outcome. Use them only for the label, never as features. `plant_tick` and `bomb_site` are safe only through
  `planted` and `t_since_plant` as above, which are known at the sample.
* **The last sample** of each round is the round end tick, where the outcome is already decided. Consider dropping
  samples at `tick == end_tick`.
* **Overtime and missing rounds.** `round_no` continues in overtime; check `game["missing_rounds"]`.
* **Pauses.** `t_round` is not corrected for pauses; see [Time](https://docs.granuleux.com/concepts/time.md).
* **Finer resolution.** For every tick, use the `ticks` parquet ([Files](https://docs.granuleux.com/data/files.md)) with the same logic,
  assigning rounds by the `freeze_end_tick` / `end_tick` windows.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.