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

258 lines
9.4 KiB
Python

#!/usr/bin/env python3
"""Turn clusters into concrete statistical decklists.
For each color pair: cluster its trophy decks (TF-IDF on the pair's own colors,
so the split is style, not splash), then synthesize a representative decklist
per cluster:
* 23 spells: take cards by mean copies, count = round(mean), fill to 23
* lands: mean basic lands of the cluster, scaled to the cluster's land count
Outputs (under value/<SNAPSHOT>/):
cluster_decks/<COLORS>-c<k>.json
cluster_decks/_index.json
reports/cluster_decks.md
"""
from __future__ import annotations
import argparse
import json
import math
import random
from collections import Counter, defaultdict
from pathlib import Path
SPELL_TARGET = 23
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 norm(a):
return math.sqrt(sum(v * v for v in a))
def kmeans(X, k, iters=120, seed=7):
rnd = random.Random(seed)
n = len(X)
centers = [list(X[rnd.randrange(n)])]
for _ in range(k - 1):
d2 = [min(sum((xi - ci) ** 2 for xi, ci in zip(x, c)) for c in centers) for x in X]
total = sum(d2) or 1.0
r = rnd.random() * total
acc = 0.0
for i, v in enumerate(d2):
acc += v
if acc >= r:
centers.append(list(X[i]))
break
assign = [0] * n
for _ in range(iters):
changed = False
for i, x in enumerate(X):
best, bc = None, 0
for j, c in enumerate(centers):
d = sum((xi - ci) ** 2 for xi, ci in zip(x, c))
if best is None or d < best:
best, bc = d, j
if assign[i] != bc:
assign[i], changed = bc, True
sums = [[0.0] * len(X[0]) for _ in range(k)]
counts = [0] * k
for i, x in enumerate(X):
counts[assign[i]] += 1
for d, v in enumerate(x):
sums[assign[i]][d] += v
for j in range(k):
if counts[j]:
centers[j] = [v / counts[j] for v in sums[j]]
if not changed:
break
return assign
def silhouette(D, assign, k):
n = len(D)
groups = defaultdict(list)
for i, a in enumerate(assign):
groups[a].append(i)
if k < 2 or any(len(g) < 2 for g in groups.values()):
return -1.0
s = []
for i in range(n):
gi = assign[i]
a = sum(D[i][j] for j in groups[gi] if j != i) / (len(groups[gi]) - 1)
b = min(sum(D[i][j] for j in groups[g]) / len(groups[g]) for g in groups if g != gi)
s.append((b - a) / max(a, b) if max(a, b) else 0.0)
return sum(s) / n
def gram(X):
n = len(X)
ns = [sum(v * v for v in x) for x in X]
D = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
d2 = ns[i] + ns[j] - 2 * sum(a * b for a, b in zip(X[i], X[j]))
D[i][j] = D[j][i] = math.sqrt(d2 if d2 > 0 else 0.0)
return D
def build(snapshot: Path, out_dir: Path, ks=(2, 3), min_decks=40, min_rate=0.05) -> 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", "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 []))
pairs = defaultdict(list)
for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
p = primary_pair(deck.get("colors"))
if p:
pairs[p].append(deck)
out_dir.joinpath("cluster_decks").mkdir(parents=True, exist_ok=True)
index, report = {}, ["# FRA PremierDraft · 簇 → 统计牌表\n",
f"每簇取均值张数合成 {SPELL_TARGET} 咒语 + 地。\n"]
for arch, decks in sorted(pairs.items(), key=lambda kv: -len(kv[1])):
if len(decks) < min_decks:
continue
n = len(decks)
cnts, landinfo = [], []
for deck in decks:
cnt, all_lands, basics, lands = Counter(), Counter(), Counter(), 0
for e in deck["maindeck"]:
nm = id2name.get(e["mtga_id"])
if nm is None:
continue
if is_land(nm):
lands += e["count"]
all_lands[nm] += e["count"]
if nm in {"Plains", "Island", "Swamp", "Mountain", "Forest"}:
basics[nm] += e["count"]
continue
cnt[nm] += e["count"]
cnts.append(cnt)
landinfo.append((lands, basics, all_lands))
df = Counter()
for cnt in cnts:
for nm in cnt:
if set(cards.get(nm, {}).get("color") or "") <= set(arch):
df[nm] += 1
vocab = sorted(nm for nm, d in df.items() if d / n >= min_rate)
idx = {nm: i for i, nm in enumerate(vocab)}
X = []
for cnt in cnts:
v = [0.0] * len(vocab)
for nm, c in cnt.items():
if nm in idx:
v[idx[nm]] = c * math.log(n / df[nm])
ln = norm(v) or 1.0
X.append([x / ln for x in v])
D = gram(X)
best = None
for k in ks:
if k >= n:
continue
a = kmeans(X, k)
s = silhouette(D, a, k)
if best is None or s > best[2]:
best = (k, a, s)
k, assign, sil = best
for c in range(k):
members = [i for i, a in enumerate(assign) if a == c]
if len(members) < 3:
continue
mean = Counter()
for i in members:
for nm, v in cnts[i].items():
mean[nm] += v / len(members)
ranked = sorted(mean.items(), key=lambda kv: -kv[1])
spells = [{"name": nm, "target_copies": round(mc, 3),
"cmc": meta.get(nm, {}).get("cmc"),
"types": meta.get(nm, {}).get("types")}
for nm, mc in ranked if mc > 0]
spell_sum = sum(s["target_copies"] for s in spells)
mean_land = Counter()
for i in members:
for nm, v in landinfo[i][2].items():
mean_land[nm] += v / len(members)
lands = {nm: round(v, 2) for nm, v in mean_land.items() if v >= 0.05}
land_sum = round(sum(lands.values()), 2)
rec = {
"archetype": arch, "cluster": c, "n": len(members),
"silhouette": round(sil, 3),
"target_spells": round(spell_sum, 2), "target_lands": land_sum,
"deck": {"spells": spells, "lands": lands},
}
(out_dir / "cluster_decks" / f"{arch}-c{c}.json").write_text(
json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
txt = [f"# {arch}-c{c} (n={len(members)}) spells={spell_sum:.2f} lands={land_sum}"]
txt += [f"{s['target_copies']:.2f}x {s['name']}" for s in spells]
txt.append("-- lands --")
txt += [f"{v:.1f}x {nm}" for nm, v in sorted(lands.items(), key=lambda kv: -kv[1])]
(out_dir / "cluster_decks" / f"{arch}-c{c}.txt").write_text("\n".join(txt), encoding="utf-8")
index[f"{arch}-c{c}"] = {"n": len(members), "spells": round(spell_sum, 2),
"top": [s["name"] for s in spells[:6]]}
report.append(f"\n## {arch}-c{c} (n={len(members)}, silhouette={sil:.3f})\n")
report.append(f"目标:咒语 {spell_sum:.2f} 张,地 {land_sum} 张;地构成 {lands}\n")
report.append("| 目标张数 | 牌 | CMC |")
report.append("|---|---|---|")
for s in spells[:25]:
report.append(f"| {s['target_copies']:.2f} | {s['name']} | {s['cmc']} |")
(out_dir / "cluster_decks" / "_index.json").write_text(
json.dumps(index, ensure_ascii=False, indent=1), encoding="utf-8")
(out_dir / "reports").mkdir(parents=True, exist_ok=True)
(out_dir / "reports/cluster_decks.md").write_text("\n".join(report), encoding="utf-8")
print(f"wrote {len(index)} cluster decklists")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--min-decks", type=int, default=40)
args = ap.parse_args()
build(Path(args.snapshot), Path(args.out), min_decks=args.min_decks)
return 0
if __name__ == "__main__":
raise SystemExit(main())