Files
mtga/scripts/build_replay_graph.py
fukunee 58446ec562 Add TRK set preview and refresh draft analysis
Track the TRK preview package and the newest value artifacts for FRA20261007, move the 17lands API notes under data, and ignore downloaded 17lands, card image and live directories.
2026-11-15 11:37:16 +08:00

484 lines
18 KiB
Python

#!/usr/bin/env python
"""Build a multi-tier card-card interaction graph from 17lands GRE replays.
Nodes are cards (mtga grpId / name), weighted by how often they are actually
cast. Edges are drawn at four *tiers* of evidence, from strongest to weakest:
strong -- within one resolution window, casting card A caused an ability /
token / trigger-holder to be created whose source permanent is
another card B on the battlefield (same controller). This is the
"chain / triggered" signal. Plain +1/+1 counters are ignored.
medium -- A and B were cast by the same player in the same turn.
weak -- A and B were cast by the same player in the same game.
veryweak -- A and B are in the same draft pool / deck.
For every tier we also record the *margins* needed to normalise the co-counts
into lift / PMI later (how many games / turns / decks the single card appears
in).
Output (under --out):
card_graph_edges.json {nodes:{name:...}, edges:[{a,b,strong,...}], meta:{...}}
Nothing here depends on third-party packages.
"""
from __future__ import annotations
import argparse
import gzip
import json
from collections import Counter, defaultdict
from pathlib import Path
# zone / object type constants (MTGA GRE)
STACK_ZONE = 27
BATTLEFIELD_ZONE = 28
HAND_ZONE = 31
CARD = "GameObjectType_Card"
ABILITY = "GameObjectType_Ability"
TOKEN = "GameObjectType_Token"
TRIGGER = "GameObjectType_TriggerHolder"
MAKER_TYPES = {ABILITY, TOKEN, TRIGGER}
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
# state-change effects that indicate a permanent chained with the resolving card
EFFECT_ANN = {
"AnnotationType_CounterAdded",
"AnnotationType_CounterRemoved",
"AnnotationType_PowerToughnessModCreated",
"AnnotationType_AttachmentCreated",
"AnnotationType_RevealedCardCreated",
"AnnotationType_GainDesignation",
"AnnotationType_MultistepEffectStarted",
"AnnotationType_DisqualifiedEffect",
"AnnotationType_ReplacementEffectApplied",
}
def load_jsonl(path: Path):
with path.open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if line:
yield json.loads(line)
def build_id2name(snapshot: Path) -> dict[int, str]:
id2name: dict[int, str] = {}
cd = snapshot / "stats/card_data.json"
if cd.exists():
for c in json.loads(cd.read_text(encoding="utf-8"))["data"]:
id2name[int(c["mtga_id"])] = c["name"]
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
for cid, m in (rec.get("cards") or {}).items():
if m.get("name"):
id2name.setdefault(int(cid), m["name"])
return id2name
def primary_pair(colors: str | None) -> str | None:
"""Map a deck_colors string (e.g. "WBg") to its primary two-colour pair."""
if not colors:
return None
order = "WUBRG"
up = [c for c in colors if c in order] # uppercase = main colours
low = [c for c in colors.upper() if c in order]
if len(up) >= 2:
pair = up[:2]
elif len(up) == 1:
pair = [up[0]] + [c for c in low if c != up[0]][:1]
else:
pair = low[:2]
if not pair:
return None
return "".join(sorted(pair, key=order.index))
def build_deck_pairs(snapshot: Path, mode: str = "primary") -> dict[str, str]:
"""draft_id -> primary colour pair.
mode="primary": fold any deck (incl. 3-colour) to its first two main colours.
mode="main2" : only keep decks whose *main* colour count is <= 2 (2-colour
+ splash). Decks with a third main colour are dropped.
"""
pairs: dict[str, str] = {}
path = snapshot / "drafts/event_details.jsonl"
if not path.exists():
return pairs
for rec in load_jsonl(path):
did = rec.get("draft_id")
dc = (rec.get("metadata") or {}).get("deck_colors")
if mode == "main2" and dc:
main = [c for c in dc if c in "WUBRG"]
if len(main) > 2:
continue
pair = primary_pair(dc)
if did and pair:
pairs[did] = pair
return pairs
def build_id2colors(snapshot: Path) -> dict[str, set]:
"""card name -> set of colour-identity letters ('' = colourless)."""
colors: dict[str, set] = {}
cd = snapshot / "stats/card_data.json"
if cd.exists():
for c in json.loads(cd.read_text(encoding="utf-8"))["data"]:
colors[c["name"]] = set(c.get("color") or "")
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
for _cid, m in (rec.get("cards") or {}).items():
if m.get("name"):
colors.setdefault(m["name"], set(m.get("color_identity") or []))
return colors
def build_pools(snapshot: Path, id2name: dict[int, str]) -> dict[str, set[str]]:
"""draft_id -> set of nonland card names in the draft pool."""
pools: dict[str, set[str]] = {}
path = snapshot / "drafts/event_details.jsonl"
if not path.exists():
return pools
for rec in load_jsonl(path):
did = rec.get("draft_id")
if not did:
continue
cards = ((rec.get("details") or {}).get("draft_pool") or {}).get("cards") or []
names = {id2name[c] for c in cards if c in id2name}
if names:
pools[did] = names
return pools
def parse_replay(path: Path, id2name: dict[int, str]):
"""Replay one GRE game and return the raw interaction events.
Returns dict with:
casts : list[(seq, card_name, controller, turn)] nonland casts
makers : list[(seq, src_name, controller, kind)] new ability/token/trigger
game_cards : {controller: set(names)} every nonland card that player owned
turns : {controller: {turn: set(names)}} nonland casts per turn
"""
data = json.loads(gzip.open(path, "rb").read())
events = data.get("events") or []
objs: dict[int, dict] = {}
prev_stack: set[int] = set()
seen_bf: set[int] = set()
casts: list[tuple[int, str, int, int]] = []
makers: list[tuple[int, str, int, str]] = []
game_cards: dict[int, set] = defaultdict(set)
turns: dict[int, dict[int, set]] = defaultdict(lambda: defaultdict(set))
turn = 0
seq = 0
def source_name(o: dict):
"""Resolve the card a maker/effect belongs to.
Prefer the object's own ``objectSourceGrpId`` (the card that created an
ability/token); otherwise walk the ``parentId`` chain. This also
resolves a token's own ability back to the spell that made the token.
"""
seen = set()
cur = o
while cur is not None:
iid = cur.get("instanceId")
if iid in seen:
return None
seen.add(iid)
s = id2name.get(cur.get("objectSourceGrpId"))
if s:
return s
if cur.get("type") in (CARD, TOKEN):
s = id2name.get(cur.get("grpId"))
if s:
return s
pid = cur.get("parentId")
cur = objs.get(pid) if pid is not None else None
return None
for e in events:
gsm = e.get("gameStateMessage") or {}
if not gsm:
continue
seq += 1
turninfo = gsm.get("turnInfo") or {}
if turninfo.get("turnNumber"):
turn = turninfo["turnNumber"]
if gsm.get("type") == "GameStateType_Full":
objs = {}
# Object id remaps (must happen before we look at zone membership)
for a in gsm.get("annotations") or []:
if "AnnotationType_ObjectIdChanged" not in (a.get("type") or []):
continue
oid = nid = None
for det in a.get("details") or []:
if det.get("key") == "orig_id" and det.get("valueInt32"):
oid = det["valueInt32"][0]
if det.get("key") == "new_id" and det.get("valueInt32"):
nid = det["valueInt32"][0]
if oid in objs and nid is not None:
objs[nid] = objs.pop(oid)
for iid in gsm.get("diffDeletedInstanceIds") or []:
objs.pop(iid, None)
# 1. apply all object definitions first, so parent chains resolve
new_objs = []
for o in gsm.get("gameObjects") or []:
o = dict(o)
iid = o["instanceId"]
prev = objs.get(iid)
if prev is None:
objs[iid] = o
new_objs.append(o)
else:
merged = dict(prev)
merged.update(o)
objs[iid] = merged
# 2. maker objects: tokens & trigger-holders are born on the battlefield
for o in new_objs:
if o.get("type") not in (TOKEN, TRIGGER):
continue
nm = source_name(o)
if not nm or nm in BASICS:
continue
kind = "trigger" if o.get("type") == TRIGGER else "token"
makers.append((seq, nm, o.get("controllerSeatId"), kind))
# 2b. effect annotations: a permanent's effect chained with the resolution
for a in gsm.get("annotations") or []:
tys = a.get("type") or []
if not tys or tys[0] not in EFFECT_ANN:
continue
aff = a.get("affectorId")
if aff is None:
continue
ao = objs.get(aff)
nm = source_name(ao) if ao else None
if nm and nm not in BASICS:
makers.append((seq, nm, ao.get("controllerSeatId"), "effect"))
# 3. zone membership changes -> casts, land drops and abilities on stack
zones = {z["zoneId"]: z for z in gsm.get("zones") or []}
st = zones.get(STACK_ZONE)
if st is not None:
now = set(st.get("objectInstanceIds") or [])
for iid in now - prev_stack:
o = objs.get(iid) or {}
otype = o.get("type")
if otype == CARD:
nm = id2name.get(o.get("grpId"))
if not nm or nm in BASICS:
continue
ctrl = o.get("controllerSeatId")
casts.append((seq, nm, ctrl, turn))
game_cards[ctrl].add(nm)
turns[ctrl][turn].add(nm)
elif otype == ABILITY:
src = source_name(o)
if src and src not in BASICS:
makers.append((seq, src, o.get("controllerSeatId"), "ability"))
prev_stack = now
bf = zones.get(BATTLEFIELD_ZONE)
if bf is not None:
for iid in bf.get("objectInstanceIds") or []:
if iid in seen_bf:
continue
seen_bf.add(iid)
o = objs.get(iid) or {}
if o.get("type") != CARD:
continue
# lands are intentionally not part of the interaction graph
return {
"casts": casts,
"makers": makers,
"game_cards": game_cards,
"turns": turns,
"seat": data.get("seat_id"),
}
def strong_pairs(casts, makers):
"""Attribute each maker to the preceding cast by the *same* controller.
The window ends at the controller's next cast (opponent casts do not cut it).
"""
casts = sorted(casts, key=lambda c: c[0])
by_ctrl: dict[int, list[int]] = defaultdict(list)
for i, (_s, _c, ctrl, _t) in enumerate(casts):
by_ctrl[ctrl].append(i)
out = Counter()
effects = Counter()
for ctrl, idxs in by_ctrl.items():
for k, i in enumerate(idxs):
seq, card, _c, _t = casts[i]
end = casts[idxs[k + 1]][0] if k + 1 < len(idxs) else 10 ** 12
for mseq, src, mctrl, kind in makers:
if not (seq < mseq < end):
continue
if mctrl != ctrl or src == card:
continue
a, b = (card, src) if card < src else (src, card)
if kind == "effect":
effects[(a, b)] += 1
else:
# trigger-holder is the most explicit signal -> extra weight
out[(a, b)] += 2 if kind == "trigger" else 1
return out, effects
def pairs_within(items, out, seen_pairs=None):
a = sorted(items)
for i in range(len(a)):
for j in range(i + 1, len(a)):
out[(a[i], a[j])] += 1
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--limit", type=int, default=0, help="debug: only N replays")
ap.add_argument("--deck-colors", choices=["primary", "main2"], default="main2",
help="main2=2-colour+splash only (default); primary=fold 3-colour into pair")
ap.add_argument("--card-colors", choices=["pair", "all"], default="all",
help="all=keep splash cards in pair views (default, report dims them); pair=drop them")
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
snapshot = Path(args.snapshot)
out = Path(args.out)
dest = out / "card_graph_edges.json"
if dest.exists() and not args.force:
print(f"exists, skip: {dest} (use --force)")
return 0
id2name = build_id2name(snapshot)
pools = build_pools(snapshot, id2name)
rows = list(load_jsonl(snapshot / "replays/replay_index.jsonl"))
deck_pair = build_deck_pairs(snapshot, args.deck_colors)
id2colors = build_id2colors(snapshot)
def allowed_in(pair: str):
if args.card_colors == "all":
return None
pset = set(pair)
return lambda nm: id2colors.get(nm, set()) <= pset
def new_bucket():
return {
"cast_count": Counter(), "cast_games": Counter(),
"strong": Counter(), "effect": Counter(),
"medium": Counter(), "weak": Counter(), "veryweak": Counter(),
"tier_turn": Counter(), "pool_card": Counter(),
"unit_games": 0, "unit_turns": 0, "unit_decks": 0,
}
buckets: dict[str, dict] = {"__ALL__": new_bucket()}
def add_game(bucket: dict, g: dict, seat: int, pool, allowed=None) -> None:
keep = (lambda nm: True) if allowed is None else allowed
bucket["unit_games"] += 1
casts = [c for c in g["casts"] if c[2] == seat and keep(c[1])]
seen = set()
for _seq, card, _ctrl, _turn in casts:
bucket["cast_count"][card] += 1
seen.add(card)
for card in seen:
bucket["cast_games"][card] += 1
turns = {t: {nm for nm in names if keep(nm)}
for t, names in g["turns"].get(seat, {}).items()}
turns = {t: ns for t, ns in turns.items() if ns}
for _turn, names in turns.items():
bucket["unit_turns"] += 1
for nm in names:
bucket["tier_turn"][nm] += 1
makers = [m for m in g["makers"] if m[2] == seat and keep(m[1])]
s_pairs, e_pairs = strong_pairs(casts, makers)
for k, n in s_pairs.items():
bucket["strong"][k] += n
for k, n in e_pairs.items():
bucket["effect"][k] += n
for _turn, names in turns.items():
if len(names) >= 2:
pairs_within(names, bucket["medium"])
gnames = {nm for nm in g["game_cards"].get(seat, set()) if keep(nm)}
if len(gnames) >= 2:
pairs_within(gnames, bucket["weak"])
if pool:
pool = {nm for nm in pool if keep(nm)}
bucket["unit_decks"] += 1
for nm in pool:
bucket["pool_card"][nm] += 1
if len(pool) >= 2:
pairs_within(pool, bucket["veryweak"])
done = skipped = 0
for i, r in enumerate(rows, 1):
if args.limit and done >= args.limit:
break
path = snapshot / "replays" / f"{r['history_path']}.json.gz"
if not path.exists():
skipped += 1
continue
try:
g = parse_replay(path, id2name)
except Exception as exc: # noqa: BLE001
print(f" !! {path.name}: {exc}")
skipped += 1
continue
seat = g.get("seat")
if seat is None:
continue
done += 1
pool = pools.get(r["draft_id"])
add_game(buckets["__ALL__"], g, seat, pool)
pair = deck_pair.get(r["draft_id"])
if pair:
buckets.setdefault(pair, new_bucket())
add_game(buckets[pair], g, seat, pool, allowed_in(pair))
if i % 500 == 0:
print(f" {i}/{len(rows)} parsed={done} skipped={skipped}")
out.mkdir(parents=True, exist_ok=True)
views: dict[str, dict] = {}
for key, b in buckets.items():
all_pairs = (set(b["strong"]) | set(b["effect"]) | set(b["medium"])
| set(b["weak"]) | set(b["veryweak"]))
edges = []
for (a, bb) in all_pairs:
edges.append({
"a": a, "b": bb,
"strong": b["strong"].get((a, bb), 0),
"effect": b["effect"].get((a, bb), 0),
"medium": b["medium"].get((a, bb), 0),
"weak": b["weak"].get((a, bb), 0),
"veryweak": b["veryweak"].get((a, bb), 0),
})
edges.sort(key=lambda e: (-(e["strong"]), -(e["effect"]),
-(e["medium"]), -(e["weak"])))
nodes = {}
for nm, n in b["cast_count"].most_common():
nodes[nm] = {
"casts": n,
"cast_games": b["cast_games"].get(nm, 0),
"turn_cells": b["tier_turn"].get(nm, 0),
"deck_games": b["pool_card"].get(nm, 0),
}
views[key] = {
"nodes": nodes, "edges": edges,
"meta": {
"games": b["unit_games"], "turn_cells": b["unit_turns"],
"decks": b["unit_decks"], "replays_available": done,
"replays_skipped": skipped,
},
}
keys = ["__ALL__"] + sorted(k for k in views if k != "__ALL__")
payload = {"views": views, "keys": keys}
dest.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
summary = ", ".join(
f"{k}:{len(views[k]['nodes'])}n/{len(views[k]['edges'])}e" for k in keys)
print(f"wrote {len(views)} views ({done} games) -> {dest}\n {summary}")
return 0
if __name__ == "__main__":
raise SystemExit(main())