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.
188 lines
7.0 KiB
Python
188 lines
7.0 KiB
Python
#!/usr/bin/env python3
|
||
"""Detect card packages / synergy from trophy deck co-occurrence.
|
||
|
||
Confound control: co-occurrence is measured **within each color pair** and then
|
||
pooled, so two cards "co-occur" only if they show up together more than expected
|
||
given that both live in the same colors.
|
||
|
||
For a card pair (a,b):
|
||
exp = sum_arch n_a(arch)*n_b(arch)/n(arch)
|
||
lift = observed / exp
|
||
Edges with high lift + decent support form synergy packages.
|
||
|
||
Outputs (under value/<SNAPSHOT>/):
|
||
reports/packages.md
|
||
packages.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 components(nodes, edges):
|
||
parent = {n: n for n in nodes}
|
||
|
||
def find(x):
|
||
while parent[x] != x:
|
||
parent[x] = parent[parent[x]]
|
||
x = parent[x]
|
||
return x
|
||
|
||
for a, b in edges:
|
||
ra, rb = find(a), find(b)
|
||
if ra != rb:
|
||
parent[ra] = rb
|
||
groups = defaultdict(list)
|
||
for n in nodes:
|
||
groups[find(n)].append(n)
|
||
return list(groups.values())
|
||
|
||
|
||
def build(snapshot: Path, out_dir: Path, min_cooc: int, lift_thr: float,
|
||
comp_lift: float, min_df: int) -> 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", "mana_cost", "types", "color"):
|
||
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 []))
|
||
|
||
arch_decks = defaultdict(list)
|
||
for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
|
||
arch = primary_pair(deck.get("colors"))
|
||
if not arch:
|
||
continue
|
||
names = {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[arch].append(names)
|
||
|
||
pair_obs = Counter()
|
||
pair_exp = defaultdict(float)
|
||
for arch, decks in arch_decks.items():
|
||
n = len(decks)
|
||
cardcnt = Counter()
|
||
for s in decks:
|
||
for c in s:
|
||
cardcnt[c] += 1
|
||
keep = [c for c, k in cardcnt.items() if k >= min_df]
|
||
for i in range(len(keep)):
|
||
for j in range(i + 1, len(keep)):
|
||
a, b = sorted((keep[i], keep[j]))
|
||
pair_exp[(a, b)] += cardcnt[a] * cardcnt[b] / n
|
||
for s in decks:
|
||
lst = sorted(x for x in s if x in set(keep))
|
||
for i in range(len(lst)):
|
||
for j in range(i + 1, len(lst)):
|
||
pair_obs[(lst[i], lst[j])] += 1
|
||
|
||
pairs = []
|
||
for (a, b), obs in pair_obs.items():
|
||
if obs < min_cooc:
|
||
continue
|
||
exp = pair_exp[(a, b)] or 1e-9
|
||
lift = obs / exp
|
||
if lift >= lift_thr:
|
||
pairs.append({"a": a, "b": b, "cooc": obs, "exp": round(exp, 1),
|
||
"lift": round(lift, 3),
|
||
"colors": f"{cards.get(a, {}).get('color', '')}/{cards.get(b, {}).get('color', '')}"})
|
||
pairs.sort(key=lambda p: -p["lift"])
|
||
|
||
# packages = connected components of strong edges
|
||
strong = [(p["a"], p["b"]) for p in pairs if p["lift"] >= comp_lift]
|
||
nodes = {n for e in strong for n in e}
|
||
comps = sorted((c for c in components(nodes, strong)),
|
||
key=lambda c: (-len(c), c))
|
||
packages = []
|
||
for c in comps:
|
||
if len(c) < 2:
|
||
continue
|
||
cset = set(c)
|
||
internal = [p for p in pairs if p["a"] in cset and p["b"] in cset]
|
||
best = max(internal, key=lambda p: p["lift"]) if internal else None
|
||
avg_lift = sum(p["lift"] for p in internal) / len(internal) if internal else 0
|
||
packages.append({
|
||
"size": len(c),
|
||
"cards": sorted(c, key=lambda n: -sum(p["cooc"] for p in pairs
|
||
if n in (p["a"], p["b"]))),
|
||
"core": f"{best['a']} + {best['b']}" if best else None,
|
||
"avg_lift": round(avg_lift, 2),
|
||
})
|
||
packages.sort(key=lambda p: -p["size"])
|
||
|
||
(out_dir / "packages.json").write_text(
|
||
json.dumps({"n_decks": sum(len(v) for v in arch_decks.values()),
|
||
"top_pairs": pairs[:200], "packages": packages},
|
||
ensure_ascii=False, indent=1), encoding="utf-8")
|
||
|
||
rep = ["# FRA PremierDraft · 卡牌包 / 协同检测\n",
|
||
f"同色对内共现 lift(obs≥{min_cooc},lift≥{lift_thr});包 = lift≥{comp_lift} 边的连通分量。\n",
|
||
f"统计基于 {sum(len(v) for v in arch_decks.values())} 副奖杯牌表。\n",
|
||
"## 高 lift 牌对 Top 40\n",
|
||
"| # | 牌 A | 牌 B | 颜色 | 同现 | 期望 | lift |",
|
||
"|---|---|---|---|---|---|---|"]
|
||
for i, p in enumerate(pairs[:40], 1):
|
||
rep.append(f"| {i} | {p['a']} | {p['b']} | {p['colors']} | {p['cooc']} | {p['exp']} | **{p['lift']}** |")
|
||
rep.append("\n## 卡牌包(连通分量)\n")
|
||
for pk in packages[:25]:
|
||
rep.append(f"### {pk['core']} (size={pk['size']}, avg lift {pk['avg_lift']})")
|
||
rep.append("- " + " · ".join(pk["cards"][:14]) + "\n")
|
||
(out_dir / "reports").mkdir(parents=True, exist_ok=True)
|
||
(out_dir / "reports/packages.md").write_text("\n".join(rep), encoding="utf-8")
|
||
print(f"pairs>=thr: {len(pairs)}; packages: {len(packages)}")
|
||
print("top pairs:", [(p['a'], p['b'], p['lift']) for p in pairs[:6]])
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--snapshot", required=True)
|
||
ap.add_argument("--out", required=True)
|
||
ap.add_argument("--min-cooc", type=int, default=15)
|
||
ap.add_argument("--lift-thr", type=float, default=1.35)
|
||
ap.add_argument("--comp-lift", type=float, default=1.8)
|
||
ap.add_argument("--min-df", type=int, default=25)
|
||
args = ap.parse_args()
|
||
build(Path(args.snapshot), Path(args.out), args.min_cooc, args.lift_thr,
|
||
args.comp_lift, args.min_df)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|