gem
v0.15.0

Who Stacked Each Camp, Who Cleared It, and What Did the Stacks Give?

Question. Which camps were stacked, and by whom? Who killed the stacked creeps: a teammate, the stacker, or the enemy? And how much gold did stacked camps give each player?

Each stack at its time, as tall as its creeps, split by who killed them

Radiant stacked

6 stacks → Timbersaw 12, Sniper 7, Ember Spirit 7, Tiny 4

5 stacks → Tiny 26

2 stacks → Sniper 4

8 stacks → Timbersaw 35, Sniper 3

1 stack → Tiny 2

Dire stacked

4 stacks → Shadow Fiend 14, Timbersaw 1, Sniper 1

2 stacks → Pangolier 9

2 stacks → Shadow Fiend 5, Rubick 5

The stacked camps

37122211321131

ancientCamp 3, stacked 7 times

  1. Lion support

    6 creeps in 2 waves; killed by Timbersaw 6

    300 gold to the killers

  2. Timbersaw core, matched by position

    3 creeps in 3 waves; killed by Timbersaw 3

    126 gold to the killers

  3. Timbersaw core

    6 creeps in 2 waves; killed by Timbersaw 6

    280 gold to the killers

  4. Timbersaw core

    6 creeps in 2 waves; killed by Sniper 3, Timbersaw 2

    277 gold to the killers

  5. Timbersaw core

    6 creeps in 2 waves; killed by Timbersaw 5

    218 gold to the killers

  6. Timbersaw core, matched by position

    6 creeps in 2 waves; killed by Timbersaw 6

    300 gold to the killers

  7. Pangolier core

    4 creeps in 2 waves; killed by Pangolier 4

    238 gold to the killers

Each player

HeroRoleStacks (exact)Creeps killedGoldShare
core1 (0)328246%
core2 (1)155925%
core8 (6)481,89614%
support6 (5)000%
support5 (4)000%
core4 (3)196683%
core072013%
core2 (1)94012%
support2 (1)51314%
support0000%

Figure 1. The 30 stacks of match 8856501050. First, each stack at its time, on the row of the player the game credited with it: a bar is as tall as its stacked creeps and split by who killed them. Rows by killer show who farmed the stacks. Then the stacked camps, sized by how often each was stacked and ringed by the side that stacked it, and each player's numbers: stacked creeps killed, their gold, and its share of the player's neutral gold. Pick a stack, a camp or a player to see its stacks in every part.

  • Killed by the stacker
  • by a teammate
  • by the enemy
  • pulled by lane creeps
  • by no player
  • small
  • medium
  • large
  • ancient
  • Radiant
  • Dire

The facts

  • match.camp_stacks: every stack the game counted. A camp spawned a wave while creeps from an earlier wave were still alive, and the game credited a player with it (m_iCampsStacked, OpenDota's camps_stacked). Each has its camp, tier, waves alive and player; player_exact says whether the credit left no choice of camp, or the camp was matched to the player by position.
  • match.neutral_creeps: every creep a camp spawned, with its camp, when it spawned and died, and who killed it.
  • match.combat_log: GOLD entries for killing a neutral (reason 14), and neutral DEATH entries.
  • player.lh_t_min: last hits at 10:00, for supports and cores.

What counts

  • A stacked creep is one of the camp's creeps alive at a stack: the earlier waves and the new one. A camp stacked again while those creeps live adds only its new wave; the rest stay with the first stack.
  • The gold a stacked creep gave is its killer's neutral-kill gold on the tick it died, split evenly over the neutrals that player's units killed on that tick. A summon's or an illusion's kill counts for its hero.
  • A pull is a stacked creep a lane creep killed. It counts for no player.
  • Supports and cores: the SUPPORTS_PER_TEAM (2) players of each side with the fewest last hits at 10:00 are supports. That is this recipe's choice; change it to use another.

The core farm recipe looks at the cores' whole income from 10 to 20 minutes; this one follows the stacks through the whole game.

The recipe

examples/cookbook/stacks.py
"""Who stacked each camp, who cleared it, and what did the stacks give?

A stack is a camp that spawned a wave while creeps from an earlier wave were
still alive, and that the game counted (``match.camp_stacks``: the player it
credited, and whether that credit left no choice or the camp was matched by
position). Its stacked creeps are the camp's creeps alive at the stack: the
earlier waves and the new one (``match.neutral_creeps``). A creep in two stacks
of the same camp belongs to the first.

For each stacked creep: who killed it, and the gold the killer got for it, the
killer's creep-kill gold (``GOLD`` reason ``NEUTRAL_GOLD``) on the tick it died,
split evenly over the neutrals the killer's units killed on that tick. A summon's
or an illusion's kill counts for its hero. A stacked creep killed by a lane creep
was pulled; it counts for no player.

A player is a support or a core by last hits: the ``SUPPORTS_PER_TEAM`` players
of each side with the fewest at ``ROLE_READING_S`` are supports. That is this
recipe's choice; change it to use another.

    python examples/cookbook/stacks.py replay.dem [more.dem ...]
"""

from __future__ import annotations

import sys
from collections import Counter, defaultdict

import pandas as pd

import gem

SUPPORTS_PER_TEAM = 2  # this many players per side with the fewest last hits are supports
ROLE_READING_S = 600  # the last hits that decide supports and cores: at 10:00
NEUTRAL_GOLD = 14  # the GOLD reason for killing a neutral creep
NEUTRAL_PREFIX = "npc_dota_neutral_"
LANE_CREEP_PREFIX = "npc_dota_creep_"
TEAMS = {2: "radiant", 3: "dire"}
STACK_COLUMNS = [
    "match_id", "time_s", "camp", "camp_type", "hero", "side", "role", "exact", "waves", "creeps",
]  # fmt: skip
CREEP_COLUMNS = [
    "match_id", "stack_s", "camp", "stacker", "stacker_side", "died_s", "killer", "killer_side",
    "pulled", "gold",
]  # fmt: skip
FLOW_COLUMNS = [
    "match_id", "stacker", "stacker_side", "killer", "killer_side", "enemy", "creeps", "gold",
]  # fmt: skip
PLAYER_COLUMNS = [
    "match_id", "hero", "side", "role", "stacks", "exact", "killed", "gold", "neutral_gold",
]  # fmt: skip


def roles(match: gem.ParsedMatch) -> dict[str, str]:
    """Return each hero's role: ``support`` or ``core``, by last hits at ``ROLE_READING_S``.

    Args:
        match: A parsed match.

    Returns:
        Hero name -> ``support`` or ``core``.
    """
    out = {}
    for team in TEAMS:
        side = [p for p in match.players if p.team == team]
        side.sort(key=lambda p: _last_hits_at(p, ROLE_READING_S))
        for i, player in enumerate(side):
            out[player.hero_name] = "support" if i < SUPPORTS_PER_TEAM else "core"
    return out


def _last_hits_at(player: gem.ParsedPlayer, time_s: int) -> int:
    if time_s in player.game_times_min:
        return player.lh_t_min[player.game_times_min.index(time_s)]
    return player.lh_t_min[-1] if player.lh_t_min else 0


def _seconds(match: gem.ParsedMatch, tick: int) -> int | None:
    return match.game_clock.game_seconds_at(tick) if match.game_clock is not None else None


def stack_table(match: gem.ParsedMatch, role: dict[str, str] | None = None) -> pd.DataFrame:
    """Return every stack: when, which camp, who stacked it and how many creeps it held.

    Args:
        match: A parsed match.
        role: ``roles(match)``, if already built.

    Returns:
        One row per stack, in time order, with ``STACK_COLUMNS``. ``exact`` is
        ``True`` when the game's credit left no choice of camp; ``creeps`` counts
        the stacked creeps (the earlier waves alive and the new one), none for a
        stack whose camp is unknown.
    """
    role = roles(match) if role is None else role
    heroes = {p.player_id: p for p in match.players}
    held = Counter(id(stack) for stack, _ in _stacked(match))
    rows = []
    for stack in match.camp_stacks:
        player = heroes.get(stack.player_id) if stack.player_id is not None else None
        hero = player.hero_name if player else None
        rows.append(
            {
                "match_id": match.match_id,
                "time_s": _seconds(match, stack.tick),
                "camp": stack.camp_id,
                "camp_type": stack.camp_type,
                "hero": hero,
                "side": TEAMS.get(player.team) if player else None,
                "role": role.get(hero) if hero else None,
                "exact": stack.player_exact,
                "waves": stack.waves_alive,
                "creeps": held[id(stack)],
            }
        )
    frame = pd.DataFrame(rows, columns=STACK_COLUMNS)
    frame["camp"] = frame["camp"].astype("Int64")  # a camp off the catalog is <NA>
    return frame


def _stacked(match: gem.ParsedMatch) -> list[tuple[gem.CampStack, gem.NeutralCreep]]:
    """Each stacked creep with the first stack of its camp it was alive at.

    A stack whose camp is unknown (its spawner matches no catalogued camp) gets
    no creeps: they can't be told apart from another unknown camp's.
    """
    by_camp: dict[int | None, list[gem.NeutralCreep]] = defaultdict(list)
    for creep in match.neutral_creeps:
        by_camp[creep.camp_id].append(creep)
    first: dict[int, tuple[gem.CampStack, gem.NeutralCreep]] = {}
    for stack in sorted(match.camp_stacks, key=lambda s: s.tick):
        if stack.camp_id is None:
            continue
        for creep in by_camp[stack.camp_id]:
            alive = creep.spawned_tick <= stack.tick and (
                creep.died_tick is None or creep.died_tick > stack.tick
            )
            if alive:
                first.setdefault(id(creep), (stack, creep))
    return list(first.values())


def _kill_gold(match: gem.ParsedMatch) -> dict[tuple[int, str], float]:
    """Each hero's creep-kill gold on a tick, per neutral its units killed on that tick."""
    gold: Counter[tuple[int, str]] = Counter()
    kills: Counter[tuple[int, str]] = Counter()
    for entry in match.combat_log:
        if entry.log_type == "GOLD" and entry.gold_reason == NEUTRAL_GOLD:
            gold[(entry.tick, entry.target_name)] += entry.value
        elif entry.log_type == "DEATH" and entry.target_name.startswith(NEUTRAL_PREFIX):
            kills[(entry.tick, entry.damage_source_name or entry.attacker_name)] += 1
    return {key: value / max(kills[key], 1) for key, value in gold.items()}


def stacked_creeps(match: gem.ParsedMatch) -> pd.DataFrame:
    """Return every stacked creep: its stack, who killed it and the gold it gave.

    Args:
        match: A parsed match.

    Returns:
        One row per stacked creep, with ``CREEP_COLUMNS``. ``killer`` is the
        killing player's hero, or the unit that killed it when no player did
        (a lane creep for a pulled creep), or ``None`` if unknown or alive.
        ``gold`` is the creep's share of its killer's gold, unrounded.
    """
    heroes = {p.player_id: p for p in match.players}
    gold = _kill_gold(match)
    rows = []
    for stack, creep in _stacked(match):
        stacker = heroes.get(stack.player_id) if stack.player_id is not None else None
        killer = heroes.get(creep.killer_player_id) if creep.killer_player_id is not None else None
        pulled = (creep.killer_name or "").startswith(LANE_CREEP_PREFIX)
        died = creep.died_tick
        rows.append(
            {
                "match_id": match.match_id,
                "stack_s": _seconds(match, stack.tick),
                "camp": stack.camp_id,
                "stacker": stacker.hero_name if stacker else None,
                "stacker_side": TEAMS.get(stacker.team) if stacker else None,
                "died_s": _seconds(match, died) if died is not None else None,
                "killer": killer.hero_name if killer else creep.killer_name,
                "killer_side": TEAMS.get(killer.team) if killer else None,
                "pulled": pulled,
                "gold": gold.get((died, killer.hero_name), 0.0) if killer and died else 0.0,
            }
        )
    frame = pd.DataFrame(rows, columns=CREEP_COLUMNS)
    frame["died_s"] = frame["died_s"].astype("Int64")
    return frame


def flows(creeps: pd.DataFrame) -> pd.DataFrame:
    """Return who cleared each player's stacks: stacked creeps and gold, stacker -> killer.

    Only creeps a player stacked and a player killed count. ``enemy`` marks a
    side's stacked creeps the other side killed.

    Args:
        creeps: ``stacked_creeps(...)`` for one match or many.

    Returns:
        One row per match, stacker and killer, most creeps first, with ``FLOW_COLUMNS``.
    """
    played = creeps.dropna(subset=["stacker", "killer_side"])
    grouped = played.groupby(
        ["match_id", "stacker", "stacker_side", "killer", "killer_side"], as_index=False
    ).agg(creeps=("gold", "size"), gold=("gold", "sum"))
    grouped["enemy"] = grouped["stacker_side"] != grouped["killer_side"]
    grouped["gold"] = grouped["gold"].astype(float).round().astype(int)
    return grouped[FLOW_COLUMNS].sort_values(
        ["match_id", "creeps"], ascending=[True, False], kind="stable", ignore_index=True
    )


def player_table(
    match: gem.ParsedMatch,
    stacks: pd.DataFrame | None = None,
    creeps: pd.DataFrame | None = None,
    role: dict[str, str] | None = None,
) -> pd.DataFrame:
    """Return each player's stacks, and the stacked creeps they killed and their gold.

    ``neutral_gold`` is all the player's creep-kill gold from neutrals, stacked
    or not, to set the stacks' gold against.

    Args:
        match: A parsed match.
        stacks: ``stack_table(match)``, if already built.
        creeps: ``stacked_creeps(match)``, if already built.
        role: ``roles(match)``, if already built.

    Returns:
        One row per player, Radiant first, with ``PLAYER_COLUMNS``.
    """
    role = roles(match) if role is None else role
    stacks = stack_table(match, role) if stacks is None else stacks
    creeps = stacked_creeps(match) if creeps is None else creeps
    neutral: Counter[str] = Counter()
    for entry in match.combat_log:
        if entry.log_type == "GOLD" and entry.gold_reason == NEUTRAL_GOLD:
            neutral[entry.target_name] += entry.value
    killed = creeps.dropna(subset=["killer_side"])
    rows = []
    for player in sorted(match.players, key=lambda p: (p.team, p.player_id)):
        hero = player.hero_name
        mine = stacks[stacks["hero"] == hero]
        kills = killed[killed["killer"] == hero]
        rows.append(
            {
                "match_id": match.match_id,
                "hero": hero,
                "side": TEAMS.get(player.team),
                "role": role.get(hero),
                "stacks": len(mine),
                "exact": int(mine["exact"].sum()),
                "killed": len(kills),
                "gold": round(kills["gold"].sum()),
                "neutral_gold": neutral[hero],
            }
        )
    return pd.DataFrame(rows, columns=PLAYER_COLUMNS)


def main(paths: list[str]) -> None:
    """Print each replay's stacks, who cleared them and each player's numbers, then the totals."""
    if len(paths) == 1:
        matches = [gem.parse(paths[0])]
    else:
        matches = [result.match for result in gem.parse_many(paths) if result.match is not None]
    players = []
    for match in matches:
        role = roles(match)
        stacks = stack_table(match, role)
        creeps = stacked_creeps(match)
        table = player_table(match, stacks, creeps, role)
        players.append(table)
        by_side = stacks["side"].value_counts()
        print(
            f"\n{match.match_id}: {len(stacks)} stacks (radiant {by_side.get('radiant', 0)}, "
            f"dire {by_side.get('dire', 0)}), {(stacks['role'] == 'support').sum()} by supports; "
            f"stacked creeps pulled: {int(creeps['pulled'].sum())}"
        )
        print(stacks.drop(columns=["match_id"]).to_string(index=False))
        print("Stacked by -> cleared by:")
        print(flows(creeps).drop(columns=["match_id"]).to_string(index=False))
        print(table.drop(columns=["match_id"]).to_string(index=False))
    every = pd.concat(players, ignore_index=True)
    cores = every[every["role"] == "core"]
    print(
        f"\nSupports made {every.loc[every['role'] == 'support', 'stacks'].sum()} of "
        f"{every['stacks'].sum()} stacks. Cores killed {cores['killed'].sum()} of "
        f"{every['killed'].sum()} stacked creeps a player killed, and took "
        f"{cores['gold'].sum():,} of their {cores['neutral_gold'].sum():,} neutral gold from them."
    )


if __name__ == "__main__":  # parse_many's worker processes re-import this file
    main(sys.argv[1:])

On one match

python examples/cookbook/stacks.py 8856501050.dem, with the stacks' first and last rows and the largest flows:

8856501050: 30 stacks (radiant 22, dire 8), 13 by supports; stacked creeps pulled: 1
 time_s  camp camp_type                             hero    side    role  exact  waves  creeps
    240     3   ancient               npc_dota_hero_lion radiant support   True      2       6
    240     6    medium               npc_dota_hero_lion radiant support   True      2       4
    300     1     large               npc_dota_hero_lion radiant support   True      2       6
    360     4     large          npc_dota_hero_nevermore    dire    core   True      2       3
    420    21     small npc_dota_hero_ancient_apparition radiant support   True      2       6
...
   4440     3   ancient          npc_dota_hero_pangolier    dire    core   True      2       4
   5460    16   ancient             npc_dota_hero_sniper radiant    core   True      2       6
Stacked by -> cleared by:
                         stacker stacker_side                     killer killer_side  enemy  creeps  gold
          npc_dota_hero_shredder      radiant     npc_dota_hero_shredder     radiant  False      35  1393
npc_dota_hero_ancient_apparition      radiant         npc_dota_hero_tiny     radiant  False      26   535
         npc_dota_hero_nevermore         dire    npc_dota_hero_nevermore        dire  False      14   449
              npc_dota_hero_lion      radiant     npc_dota_hero_shredder     radiant  False      12   475
         npc_dota_hero_pangolier         dire    npc_dota_hero_pangolier        dire  False       9   401
              npc_dota_hero_lion      radiant npc_dota_hero_ember_spirit        dire   True       7   201
              npc_dota_hero_lion      radiant       npc_dota_hero_sniper     radiant  False       7   276
            npc_dota_hero_rubick         dire    npc_dota_hero_nevermore        dire  False       5   219
...
                            hero    side    role  stacks  exact  killed  gold  neutral_gold
              npc_dota_hero_tiny radiant    core       1      0      32   824         14539
            npc_dota_hero_sniper radiant    core       2      1      15   592         12917
          npc_dota_hero_shredder radiant    core       8      6      48  1896         13956
              npc_dota_hero_lion radiant support       6      5       0     0           256
npc_dota_hero_ancient_apparition radiant support       5      4       0     0           469
         npc_dota_hero_nevermore    dire    core       4      3      19   668         23049
      npc_dota_hero_ember_spirit    dire    core       0      0       7   201          7966
         npc_dota_hero_pangolier    dire    core       2      1       9   401         20561
            npc_dota_hero_rubick    dire support       2      1       5   131          3298
            npc_dota_hero_treant    dire support       0      0       0     0          1571

Radiant made 22 of the 30 stacks, 19 of them by 20:00. Timbersaw stacked 8 camps and killed 48 stacked creeps, 35 of them his own, for 1,896 gold: 14% of his neutral gold. Ancient Apparition's 5 stacks went to Tiny (26 creeps), and Lion's 6 were split between Timbersaw, Sniper, Tiny and Ember Spirit, on the other side, who took 7 of them. On Dire, Shadow Fiend and Pangolier mostly stacked for themselves.

Across the fixtures

The 9 fixture replays have 229 stacks:

MatchStacks (Radiant / Dire)By supportsStacked creeps killed by coresKilled by the enemyCores' neutral gold from stacks
882252040613 (3 / 10)558 of 611216%
882259393218 (11 / 7)890 of 961111%
885518813922 (8 / 14)1295 of 111611%
885524270450 (25 / 25)27204 of 2361111%
885650105030 (22 / 8)13130 of 13595%
886018733530 (11 / 19)25129 of 1391010%
886825999313 (6 / 7)456 of 581425%
897405301121 (6 / 15)698 of 99813%
903961907632 (16 / 16)29141 of 145615%
All 9229 (108 / 121)1291,001 of 1,0808710%
  • Who stacks: supports made 129 of the 229 stacks (56%), from 29 of 32 on 9039619076 to 6 of 21 on 8974053011. The game's credit fixed the camp for 89 stacks; the other 140 were matched to their player by position.
  • Who clears: cores killed 93% of the stacked creeps a player killed, and supports 79. 445 of the 1,080 (41%) were killed by the player who stacked them: Alchemist on 8855242704 stacked 13 camps and killed 96 stacked creeps for 3,297 gold, a quarter of his neutral gold.
  • The enemy killed 87 stacked creeps (8%), and lane creeps 14 (pulls).
  • What stacks gave: 33,477 of the cores' 333,671 neutral gold (10%) came from stacked creeps, from 5% on 8856501050 to 25% on 8868259993.

What this does not say

  • Whether a stack was worth it. The gold is what the stacked creeps gave, not what the stacker or the farmer would have earned doing something else.
  • Who pulled the camp. The game credits one player with a stack; a teammate who helped, or a stack made from range, is not in the credit.
  • Which hero a creep's gold went to when two players killed neutrals on one tick. A creep's killer is the combat log's attacker on its death tick, and a creep that died on a tick another neutral died to someone else has no killer.

Variations

  • Change SUPPORTS_PER_TEAM or ROLE_READING_S, or replace roles with OpenDota's player.lane_role.
  • Filter stacked_creeps to pulled to see which camps fed the lanes, and when.
  • Group stack_table by camp and camp_type to ask which camps each side stacks, or by time_s // 600 to see when.