Files
mtga/scripts/build_card_relations.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

157 lines
5.4 KiB
Python

#!/usr/bin/env python3
"""Per-card relations from trophy co-occurrence (within color pair).
For every card, produce:
synergy : partners with lift >= 1.4 (played together) -> {mtga_id, lift}
substitutes : same-role cards you swap -> {mtga_id, penalty} (lift < 1)
antisynergy : partners with lift <= 0.7 -> {mtga_id, lift}
Output: value/<SNAPSHOT>/card_relations.json
"""
from __future__ import annotations
import argparse
import json
from collections import Counter, defaultdict
from pathlib import Path
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 primary_pair(colors):
if not colors:
return None
order = "WUBRG"
up = [c for c in colors if c in order] # uppercase = main colors
low = [c for c in colors.upper() if c in order] # all colors
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 cmc_bucket(cmc):
if cmc is None:
return -1
c = int(cmc)
return c if c < 5 else 5
def build(snapshot: Path, out_dir: Path, min_df: int = 20) -> None:
cards = {c["name"]: c for c in
json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]}
id2name, meta = {}, {}
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
for cid, m in (rec.get("cards") or {}).items():
cid = int(cid)
id2name[cid] = m.get("name")
meta.setdefault(m.get("name"), dict(m))
for nm, c in cards.items():
md = meta.setdefault(nm, {})
for k in ("cmc", "types"):
if md.get(k) in (None, ""):
md[k] = c.get(k)
def is_land(nm):
return any("Land" in t for t in (meta.get(nm, {}).get("types") or []))
def is_creature(nm):
return any("Creature" in t for t in (meta.get(nm, {}).get("types") or []))
arch_decks = defaultdict(list)
for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
p = primary_pair(deck.get("colors"))
if not p:
continue
s = {id2name[e["mtga_id"]] for e in deck["maindeck"]
if id2name.get(e["mtga_id"]) in cards and not is_land(id2name[e["mtga_id"]])}
arch_decks[p].append(s)
obs = Counter()
exp = defaultdict(float)
df = Counter()
for arch, decks in arch_decks.items():
n = len(decks)
cc = Counter()
for s in decks:
for c in s:
cc[c] += 1
keep = {c for c, k in cc.items() if k >= min_df}
for c in keep:
df[c] += 1
a = sorted(keep)
for i in range(len(a)):
for j in range(i + 1, len(a)):
exp[(a[i], a[j])] += cc[a[i]] * cc[a[j]] / n
for s in decks:
lst = sorted(x for x in s if x in keep)
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
obs[(lst[i], lst[j])] += 1
lift = {}
for (a, b), o in obs.items():
e = exp[(a, b)] or 1e-9
lift[(a, b)] = o / e
lift[(b, a)] = o / e
relations = {}
for nm in cards:
syn, anti, subs = [], [], []
for other in cards:
if other == nm:
continue
key = (nm, other) if (nm, other) in lift else (other, nm)
l = lift.get(key)
o = obs.get(key, 0)
if l is None:
continue
if l >= 1.4 and o >= 10:
syn.append((other, l))
if l <= 0.7 and o >= 4 and exp.get(key, 0) >= 12:
anti.append((other, l))
# substitutes: same slot (cmc bucket + creature-ness), mutually exclusive
same_slot = (cmc_bucket(meta.get(nm, {}).get("cmc")) ==
cmc_bucket(meta.get(other, {}).get("cmc")) and
is_creature(nm) == is_creature(other) and
set(cards.get(nm, {}).get("color") or "") ==
set(cards.get(other, {}).get("color") or ""))
if same_slot and l < 1.0 and o >= 8:
subs.append((other, 1.0 - l))
syn.sort(key=lambda x: -x[1])
anti.sort(key=lambda x: x[1])
subs.sort(key=lambda x: -x[1])
relations[nm] = {
"mtga_id": cards[nm]["mtga_id"],
"synergy": [{"mtga_id": cards[o]["mtga_id"], "lift": round(l, 3)} for o, l in syn[:5]],
"antisynergy": [{"mtga_id": cards[o]["mtga_id"], "lift": round(l, 3)} for o, l in anti[:5]],
"substitutes": [{"mtga_id": cards[o]["mtga_id"], "penalty": round(p, 4)} for o, p in subs[:5]],
}
(out_dir / "card_relations.json").write_text(
json.dumps(relations, ensure_ascii=False, indent=1), encoding="utf-8")
have = sum(1 for v in relations.values() if v["synergy"] or v["antisynergy"] or v["substitutes"])
print(f"pairs with lift: {len(lift)//2}; cards with >=1 relation: {have}/{len(relations)}")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
args = ap.parse_args()
build(Path(args.snapshot), Path(args.out))
return 0
if __name__ == "__main__":
raise SystemExit(main())