Files
mtga/scripts/build_stability.py
T
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

233 lines
8.2 KiB
Python

#!/usr/bin/env python
"""Bootstrap stability of the two-pass sub-archetype clustering.
For each color pair:
* reference clustering (the same two-pass method as build_templates_contract.py)
-> per cluster, the top-12 "defining cards" by excess inclusion P(c|cluster) - P(c|pair)
* B bootstrap resamples (with replacement): recluster, match each reference cluster to
the resample cluster with the largest deck overlap, Jaccard of the defining-card sets
* report mean Jaccard per cluster, plus how often each defining card shows up
Output: .tmp/stability.json
"""
from __future__ import annotations
import argparse
import json
import math
import random
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import build_templates_contract as B # noqa: E402
SNAP = ROOT / "data/17lands/FRA20261007"
OUT = ROOT / "value/FRA20261007/stability.json"
B_BOOT = 20
TOPN = 12
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
WEIGHT: dict = {}
RARITY: dict = {}
def load_cards():
data = json.loads((SNAP / "stats/card_data.json").read_text(encoding="utf-8"))["data"]
id2name = {c["mtga_id"]: c["name"] for c in data}
for c in data:
WEIGHT[c["name"]] = 1.0 + math.log(max(1, c.get("game_count") or 1))
RARITY[c["name"]] = (c.get("rarity") or "").lower()
for line in (SNAP / "drafts/draft_picks.jsonl").read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
r = json.loads(line)
for cid, m in (r.get("cards") or {}).items():
if m.get("name"):
id2name.setdefault(int(cid), m["name"])
return id2name
def feats(cnts, vocab):
idx = {nm: i for i, nm in enumerate(vocab)}
n = len(cnts)
df = Counter()
for c in cnts:
for nm in c:
if nm in idx:
df[nm] += 1
disc = {nm: 4.0 * (df[nm] / n) * (1 - df[nm] / n) for nm in vocab}
def X(weights):
out = []
for c in cnts:
v = [0.0] * len(vocab)
for nm, cc in c.items():
if nm in idx:
v[idx[nm]] = cc * WEIGHT.get(nm, 1.0) * weights.get(nm, 0.0)
L = math.sqrt(sum(x * x for x in v)) or 1.0
out.append([x / L for x in v])
return out
def pick(XX):
D = B.gram(XX)
b = None
for k in (2,):
if k >= n:
continue
a = B.kmeans(XX, k)
if min(Counter(a).values()) < 3:
continue
s = B.silhouette(D, a, k)
if b is None or s > b[2]:
b = (k, a, s)
return b
def outlier(X, assign, kk):
# (其他) = outlier relative to the deck's OWN cluster (mean + 2*sd of that cluster)
dim = len(vocab)
gg = defaultdict(list)
for i, a in enumerate(assign):
gg[a].append(i)
cent = {g: [sum(X[i][j] for i in gg[g]) / len(gg[g]) for j in range(dim)] for g in gg}
d2c = [math.sqrt(sum((X[i][j] - cent[assign[i]][j]) ** 2 for j in range(dim))) for i in range(n)]
flag = [False] * n
for g in gg:
ds = [d2c[i] for i in gg[g]]
m = sum(ds) / len(ds)
sd = (sum((x - m) ** 2 for x in ds) / len(ds)) ** 0.5 or 1.0
for i in gg[g]:
if d2c[i] > m + 2.0 * sd:
flag[i] = True
return [kk if flag[i] else assign[i] for i in range(n)]
X1v = X(disc)
b1 = pick(X1v)
if b1 is None:
return None
a1 = outlier(X1v, b1[1], b1[0]) # (其他) joins the weighting
g1 = defaultdict(list)
for i, aa in enumerate(a1):
g1[aa].append(i)
inc = {nm: {g: 0 for g in g1} for nm in vocab}
for g, mem in g1.items():
for i in mem:
for nm in cnts[i]:
if nm in inc:
inc[nm][g] += 1
spec = {}
for nm in vocab:
pbar = df[nm] / n
spec[nm] = sum((len(g1[g]) / n) * ((inc[nm][g] / len(g1[g])) - pbar) ** 2 for g in g1)
mx = max(spec.values()) or 1.0
spec = {nm: v / mx for nm, v in spec.items()}
X2 = X(spec)
b2 = pick(X2)
if b2 is not None:
k, assign, Xf = b2[0], b2[1], X2
else:
k, assign, Xf = b1[0], b1[1], X1v
return k + 1, outlier(Xf, assign, k)
def defining(cnts, assign, k, vocab, n):
pbar = {nm: sum(1 for c in cnts if nm in c) / n for nm in vocab}
out = {}
for g in range(k + 1):
mem = [i for i in range(len(cnts)) if assign[i] == g]
if not mem:
continue
ex = {nm: sum(1 for i in mem if nm in cnts[i]) / len(mem) - pbar[nm] for nm in vocab}
out[g] = [nm for nm, _ in sorted(ex.items(), key=lambda x: -x[1])[:TOPN]]
return out
def main() -> int:
id2name = load_cards()
by_pair = defaultdict(list)
for line in (SNAP / "trophies/trophies_decks.jsonl").read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
d = json.loads(line)
pair = re.sub(r"[^A-Z]", "", d.get("colors") or "")
if len(pair) != 2:
continue
c = Counter()
for e in d["maindeck"]:
nm = id2name.get(e["mtga_id"])
if nm and nm not in BASICS and RARITY.get(nm) not in ("rare", "mythic"):
c[nm] += e["count"]
by_pair[pair].append(c)
res = {}
for pair, cnts in sorted(by_pair.items()):
n = len(cnts)
df = Counter()
for c in cnts:
for nm in c:
df[nm] += 1
vocab = sorted(nm for nm, cc in df.items() if cc / n >= 0.05)
base = feats(cnts, vocab)
if base is None:
continue
k, assign = base
ref = defining(cnts, assign, k, vocab, n)
boot = defaultdict(lambda: defaultdict(int)) # ref_cluster -> card -> times in top-N
jacs = defaultdict(list)
for b in range(B_BOOT):
sample = [random.randrange(n) for _ in range(n)]
sub = [cnts[i] for i in sample]
got = feats(sub, vocab)
if got is None:
continue
k2, a2 = got
def2 = defining(sub, a2, k2, vocab, n)
# map each reference cluster to the resample cluster with max deck overlap
for gc, cards_ref in ref.items():
sref = {i for i in range(n) if assign[i] == gc}
best_c2, best_ov = None, -1
for gc2 in def2:
sb = set(sample[j] for j in range(n) if a2[j] == gc2)
ov = len(sref & sb)
if ov > best_ov:
best_ov, best_c2 = ov, gc2
if best_c2 is None or not def2[best_c2]:
continue
cards_b = def2[best_c2]
jac = len(set(cards_ref) & set(cards_b)) / len(set(cards_ref) | set(cards_b))
jacs[gc].append(jac)
for nm in cards_b:
boot[gc][nm] += 1
clusters = []
for gc in sorted(ref):
js = jacs.get(gc) or [0.0]
clusters.append({
"c": gc, "n": sum(1 for i in range(n) if assign[i] == gc),
"jac": round(sum(js) / len(js), 3),
"cards": [{"name": nm, "freq": round(boot[gc].get(nm, 0) / B_BOOT, 2)} for nm in ref[gc]],
})
mean = round(sum(c["jac"] for c in clusters) / len(clusters), 3)
cmap = {}
for gc in ref:
for nm in ref[gc]:
cmap[nm] = max(cmap.get(nm, 0.0), boot[gc].get(nm, 0) / B_BOOT)
res[pair] = {"mean": mean, "clusters": clusters, "cards": cmap}
print(f"{pair}: 稳定性 {mean:.2f} " + " ".join(f"簇{c['c']}={c['jac']:.2f}" for c in clusters))
OUT.write_text(json.dumps(res, ensure_ascii=False), encoding="utf-8")
overall = sum(v["mean"] for v in res.values()) / len(res)
print(f"\n整体平均稳定性 {overall:.3f} -> {OUT}")
return 0
if __name__ == "__main__":
_ap = argparse.ArgumentParser()
_ap.add_argument("--snapshot", required=True)
_ap.add_argument("--out", required=True)
_a = _ap.parse_args()
SNAP = Path(_a.snapshot)
OUT = Path(_a.out) / "stability.json"
raise SystemExit(main())