draw
This commit is contained in:
+91
-100
@@ -1,22 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
"""M1: build the per-card value table for a set from 17Lands data.
|
||||
|
||||
Keyed by **card name** (not mtga_id): basic lands are dropped and reprints
|
||||
merged, so the table has exactly the set's playable cards (for FRA: 290, which
|
||||
matches stats/card_data.json).
|
||||
|
||||
Inputs (all under data/17lands/<SNAPSHOT>/):
|
||||
stats/card_data.json per-card GIH WR / ALSA / ATA / play_rate / IWD
|
||||
drafts/draft_picks.jsonl card metadata (name, cmc, mana_cost, types)
|
||||
trophies/trophies_decks.jsonl 1113 trophy decklists -> inclusion / target copies
|
||||
trophies/trophies_decks.jsonl trophy decklists -> inclusion / target copies
|
||||
|
||||
Outputs (under value/<SNAPSHOT>/):
|
||||
cards.csv / cards.json the per-card table
|
||||
reports/cards_overview.md a human-readable summary
|
||||
|
||||
Method notes
|
||||
* "GIH WR" = ever_drawn_win_rate; sample = ever_drawn_game_count.
|
||||
* shrunk WR = empirical-Bayes shrinkage toward the field mean:
|
||||
(wins + k*p0) / (games + k), wins = wr*games, k = PRIOR_GAMES
|
||||
* wilson_low = 95% Wilson lower bound on the GIH WR.
|
||||
* inclusion / target copies come only from the 1113 trophy decks (winning
|
||||
population), which is exactly what we want for template building.
|
||||
cards.csv / cards.json
|
||||
archetype_membership.json
|
||||
reports/cards_overview.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,12 +26,10 @@ import statistics
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
PRIOR_GAMES = 100.0 # shrinkage strength
|
||||
PRIOR_GAMES = 100.0 # empirical-Bayes shrinkage strength
|
||||
Z = 1.959964 # 95%
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def load_jsonl(path: Path):
|
||||
with path.open(encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
@@ -51,6 +46,14 @@ def primary_pair(colors: str | None) -> str | None:
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else (cs[0] if cs else None)
|
||||
|
||||
|
||||
def is_basic(types) -> bool:
|
||||
return any("Basic Land" in t for t in (types or []))
|
||||
|
||||
|
||||
def is_land(types) -> bool:
|
||||
return any("Land" in t for t in (types or []))
|
||||
|
||||
|
||||
def wilson_low(wins: float, n: float, z: float = Z) -> float | None:
|
||||
if not n:
|
||||
return None
|
||||
@@ -63,75 +66,78 @@ def wilson_low(wins: float, n: float, z: float = Z) -> float | None:
|
||||
|
||||
def zscores(values: dict) -> dict:
|
||||
xs = [v for v in values.values() if v is not None]
|
||||
if len(xs) < 2:
|
||||
return {k: 0.0 for k in values}
|
||||
mu = statistics.mean(xs)
|
||||
sd = statistics.pstdev(xs) or 1.0
|
||||
mu = statistics.mean(xs) if xs else 0.0
|
||||
sd = statistics.pstdev(xs) if len(xs) > 1 else 1.0
|
||||
sd = sd or 1.0
|
||||
return {k: ((v - mu) / sd if v is not None else -2.0) for k, v in values.items()}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def build(snapshot: Path, out_dir: Path) -> None:
|
||||
data = json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]
|
||||
card = {c["mtga_id"]: dict(c) for c in data}
|
||||
cards = {c["name"]: dict(c) for c in data} # 290, name-keyed
|
||||
|
||||
# card metadata from draft_picks (name, cmc, mana_cost, types)
|
||||
# metadata (cmc / mana_cost / types) + id -> name from draft_picks
|
||||
id2name: dict[int, str] = {c["mtga_id"]: c["name"] for c in data}
|
||||
name_meta: dict[str, dict] = {}
|
||||
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
|
||||
for cid, m in (rec.get("cards") or {}).items():
|
||||
cid = int(cid)
|
||||
entry = card.setdefault(cid, {"mtga_id": cid, "name": m.get("name")})
|
||||
entry.setdefault("cmc", m.get("cmc"))
|
||||
entry.setdefault("mana_cost", m.get("mana_cost"))
|
||||
entry.setdefault("types", m.get("types"))
|
||||
entry.setdefault("color", "".join(m.get("color_identity") or []))
|
||||
nm = m.get("name")
|
||||
id2name[cid] = nm
|
||||
name_meta.setdefault(nm, dict(m))
|
||||
for c in data: # fill gaps from card_data
|
||||
md = name_meta.setdefault(c["name"], {})
|
||||
for k in ("cmc", "mana_cost", "types"):
|
||||
if md.get(k) in (None, "", []):
|
||||
md[k] = c.get(k)
|
||||
|
||||
decks = list(load_jsonl(snapshot / "trophies/trophies_decks.jsonl"))
|
||||
n_decks = len(decks)
|
||||
|
||||
# inclusion / copy distribution, overall and per archetype
|
||||
# aggregate decklists by NAME, dropping basic lands
|
||||
decks_with = Counter()
|
||||
total_copies = Counter()
|
||||
copy_dist = defaultdict(Counter) # cid -> {1: n, 2: n, 3+: n}
|
||||
arch_decks = Counter() # archetype -> number of decks
|
||||
arch_decks_with = Counter() # (arch, cid) -> decks with card
|
||||
copy_dist = defaultdict(Counter)
|
||||
arch_decks = Counter()
|
||||
arch_decks_with = Counter()
|
||||
for d in decks:
|
||||
arch = primary_pair(d.get("colors"))
|
||||
arch_decks[arch] += 1
|
||||
counts = Counter()
|
||||
for c in d["maindeck"]:
|
||||
counts[c["mtga_id"]] += c["count"]
|
||||
for cid, n in counts.items():
|
||||
decks_with[cid] += 1
|
||||
total_copies[cid] += n
|
||||
copy_dist[cid][min(n, 3)] += 1
|
||||
arch_decks_with[(arch, cid)] += 1
|
||||
for entry in d["maindeck"]:
|
||||
nm = id2name.get(entry["mtga_id"])
|
||||
if nm is None or nm not in cards: # basic land / unknown
|
||||
continue
|
||||
counts[nm] += entry["count"]
|
||||
for nm, n in counts.items():
|
||||
decks_with[nm] += 1
|
||||
total_copies[nm] += n
|
||||
copy_dist[nm][min(n, 3)] += 1
|
||||
arch_decks_with[(arch, nm)] += 1
|
||||
|
||||
# field mean for shrinkage
|
||||
tot_g = sum(c.get("ever_drawn_game_count") or 0 for c in card.values())
|
||||
tot_g = sum(c.get("ever_drawn_game_count") or 0 for c in cards.values())
|
||||
tot_w = sum((c.get("ever_drawn_win_rate") or 0) * (c.get("ever_drawn_game_count") or 0)
|
||||
for c in card.values())
|
||||
for c in cards.values())
|
||||
p0 = (tot_w / tot_g) if tot_g else 0.5
|
||||
|
||||
rows = []
|
||||
for cid, c in card.items():
|
||||
types = c.get("types") or []
|
||||
is_basic = any("Basic Land" in t for t in types)
|
||||
is_land = any("Land" in t for t in types)
|
||||
for nm, c in cards.items():
|
||||
meta = name_meta.get(nm, {})
|
||||
types = c.get("types") or meta.get("types") or []
|
||||
g = c.get("ever_drawn_game_count") or 0
|
||||
wr = c.get("ever_drawn_win_rate")
|
||||
wins = (wr * g) if (wr is not None and g) else 0.0
|
||||
shrunk = (wins + PRIOR_GAMES * p0) / (g + PRIOR_GAMES) if (g or PRIOR_GAMES) else None
|
||||
dw = decks_with.get(cid, 0)
|
||||
dw = decks_with.get(nm, 0)
|
||||
rows.append({
|
||||
"mtga_id": cid,
|
||||
"name": c.get("name") or str(cid),
|
||||
"name": nm,
|
||||
"mtga_id": c["mtga_id"],
|
||||
"color": c.get("color") or "",
|
||||
"rarity": c.get("rarity") or "",
|
||||
"cmc": c.get("cmc"),
|
||||
"mana_cost": c.get("mana_cost") or "",
|
||||
"cmc": c.get("cmc", meta.get("cmc")),
|
||||
"mana_cost": c.get("mana_cost") or meta.get("mana_cost") or "",
|
||||
"types": "|".join(types),
|
||||
"is_land": is_land,
|
||||
"is_basic": is_basic,
|
||||
"is_land": is_land(types),
|
||||
"gih_games": g,
|
||||
"gih_wr": wr,
|
||||
"gih_wilson_low": wilson_low(wins, g) if g else None,
|
||||
@@ -142,39 +148,33 @@ def build(snapshot: Path, out_dir: Path) -> None:
|
||||
"ata": c.get("avg_pick"),
|
||||
"trophy_decks": dw,
|
||||
"inclusion": dw / n_decks if n_decks else None,
|
||||
"avg_copies_all": total_copies.get(cid, 0) / n_decks if n_decks else None,
|
||||
"avg_copies_played": total_copies.get(cid, 0) / dw if dw else None,
|
||||
"c1": copy_dist[cid].get(1, 0),
|
||||
"c2": copy_dist[cid].get(2, 0),
|
||||
"c3plus": copy_dist[cid].get(3, 0),
|
||||
"avg_copies_all": total_copies.get(nm, 0) / n_decks if n_decks else None,
|
||||
"avg_copies_played": total_copies.get(nm, 0) / dw if dw else None,
|
||||
"c1": copy_dist[nm].get(1, 0),
|
||||
"c2": copy_dist[nm].get(2, 0),
|
||||
"c3plus": copy_dist[nm].get(3, 0),
|
||||
})
|
||||
|
||||
# composite importance (spells only): shrunk WR + inclusion + play_rate
|
||||
spells = [r for r in rows if not r["is_land"]]
|
||||
wr_z = zscores({r["mtga_id"]: r["gih_shrunk"] for r in spells})
|
||||
inc_z = zscores({r["mtga_id"]: r["inclusion"] for r in spells})
|
||||
iwd_z = zscores({r["mtga_id"]: r["iwd"] for r in spells})
|
||||
wr_z = zscores({r["name"]: r["gih_shrunk"] for r in spells})
|
||||
inc_z = zscores({r["name"]: r["inclusion"] for r in spells})
|
||||
iwd_z = zscores({r["name"]: r["iwd"] for r in spells})
|
||||
for r in rows:
|
||||
if r["is_land"]:
|
||||
r["importance"] = None
|
||||
else:
|
||||
r["importance"] = round(0.5 * wr_z[r["mtga_id"]] + 0.35 * inc_z[r["mtga_id"]] +
|
||||
0.15 * iwd_z[r["mtga_id"]], 4)
|
||||
r["importance"] = (None if r["is_land"] else
|
||||
round(0.5 * wr_z[r["name"]] + 0.35 * inc_z[r["name"]] +
|
||||
0.15 * iwd_z[r["name"]], 4))
|
||||
|
||||
# archetype membership (for per-color templates)
|
||||
arch_members = defaultdict(list)
|
||||
for (arch, cid), n in arch_decks_with.items():
|
||||
if arch and len(arch) == 2: # only the 10 two-color archetypes
|
||||
arch_members[arch].append((cid, n / arch_decks[arch]))
|
||||
for (arch, nm), n in arch_decks_with.items():
|
||||
if arch and len(arch) == 2:
|
||||
arch_members[arch].append((nm, n / arch_decks[arch]))
|
||||
|
||||
# ---- write ----
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "cards.json").write_text(
|
||||
json.dumps({"field_mean_gih_wr": p0, "n_decks": n_decks, "cards": rows},
|
||||
ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
fields = list(rows[0].keys())
|
||||
with (out_dir / "cards.csv").open("w", encoding="utf-8", newline="") as fh:
|
||||
w = csv.DictWriter(fh, fieldnames=fields)
|
||||
w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
|
||||
w.writeheader()
|
||||
for r in sorted(rows, key=lambda r: (r["importance"] is None, -(r["importance"] or 0))):
|
||||
w.writerow(r)
|
||||
@@ -183,51 +183,42 @@ def build(snapshot: Path, out_dir: Path) -> None:
|
||||
ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
|
||||
write_report(out_dir, rows, spells, arch_members, n_decks, p0)
|
||||
print(f"field mean GIH WR = {p0:.4f}; decks = {n_decks}; unique cards = {len(rows)}")
|
||||
print(f"field mean GIH WR = {p0:.4f}; decks = {n_decks}; unique cards (no basics) = {len(rows)}")
|
||||
print(f"wrote {out_dir}/cards.csv, cards.json, archetype_membership.json, reports/cards_overview.md")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def write_report(out_dir: Path, rows, spells, arch_members, n_decks, p0) -> None:
|
||||
by_id = {r["mtga_id"]: r for r in rows}
|
||||
by_name = {r["name"]: r for r in rows}
|
||||
reports = out_dir / "reports"
|
||||
reports.mkdir(parents=True, exist_ok=True)
|
||||
L = []
|
||||
L.append("# FRA PremierDraft · 单卡价值与模板概览 v0\n")
|
||||
L.append(f"- 奖杯牌表:**{n_decks}** 副;全场 GIH WR 均值:**{p0:.3f}**")
|
||||
L.append("- 收缩先验:k=100;`importance = 0.5·z(shrunk GIH WR) + 0.35·z(采纳率) + 0.15·z(IWD)`(仅非地)\n")
|
||||
L = ["# FRA PremierDraft · 单卡价值与模板概览 v0\n",
|
||||
f"- 奖杯牌表:**{n_decks}** 副;单卡(去基本地、按名去重):**{len(rows)}**;全场 GIH WR 均值:**{p0:.3f}**",
|
||||
"- 收缩先验 k=100;`importance = 0.5·z(收缩WR) + 0.35·z(采纳率) + 0.15·z(IWD)`(仅非地)\n"]
|
||||
|
||||
def table(title, items, key):
|
||||
def table(title, items):
|
||||
L.append(f"## {title}\n")
|
||||
L.append("| # | 牌 | 色 | 稀有 | CMC | GIH WR | 收缩WR | 采纳率 | 平均张数 | importance |")
|
||||
L.append("|---|---|---|---|---|---|---|---|---|---|")
|
||||
for i, r in enumerate(items, 1):
|
||||
L.append(f"| {i} | {r['name']} | {r['color'] or '-'} | {r['rarity'][:2]} | "
|
||||
f"{r['cmc'] if r['cmc'] is not None else '-'} | "
|
||||
f"{fmt(r['gih_wr'])} | {fmt(r['gih_shrunk'])} | "
|
||||
f"{pct(r['inclusion'])} | {fmt(r['avg_copies_all'],2)} | {fmt(r['importance'],2)} |")
|
||||
f"{r['cmc'] if r['cmc'] is not None else '-'} | {fmt(r['gih_wr'])} | "
|
||||
f"{fmt(r['gih_shrunk'])} | {pct(r['inclusion'])} | "
|
||||
f"{fmt(r['avg_copies_all'],2)} | {fmt(r['importance'],2)} |")
|
||||
L.append("")
|
||||
|
||||
top = sorted([r for r in spells if r["gih_games"] >= 200],
|
||||
key=lambda r: -(r["importance"] or -9))
|
||||
table("综合重要性 Top 30(GIH 样本 ≥200)", top[:30], "importance")
|
||||
inc = sorted(spells, key=lambda r: -(r["inclusion"] or 0))[:30]
|
||||
table("采纳率 Top 30(奖杯牌表最常见的牌)", inc, "inclusion")
|
||||
wr = sorted([r for r in spells if r["gih_games"] >= 200],
|
||||
key=lambda r: -(r["gih_shrunk"] or 0))[:20]
|
||||
table("收缩 GIH WR Top 20", wr, "gih_shrunk")
|
||||
table("综合重要性 Top 30(GIH 样本 ≥200)",
|
||||
sorted([r for r in spells if r["gih_games"] >= 200], key=lambda r: -(r["importance"] or -9))[:30])
|
||||
table("采纳率 Top 30(奖杯牌表最常见的牌)",
|
||||
sorted(spells, key=lambda r: -(r["inclusion"] or 0))[:30])
|
||||
table("收缩 GIH WR Top 20(样本 ≥200)",
|
||||
sorted([r for r in spells if r["gih_games"] >= 200], key=lambda r: -(r["gih_shrunk"] or 0))[:20])
|
||||
|
||||
L.append("## 各 archetype 关键牌(按采纳率)\n")
|
||||
for arch in sorted(arch_members, key=lambda a: (a is None, a)):
|
||||
top5 = ""
|
||||
members = [(cid, rate) for cid, rate in arch_members[arch]
|
||||
if by_id.get(cid) and not by_id[cid]["is_land"]]
|
||||
for arch in sorted(arch_members):
|
||||
members = [(nm, rate) for nm, rate in arch_members[arch]
|
||||
if by_name.get(nm) and not by_name[nm]["is_land"]]
|
||||
members.sort(key=lambda x: -x[1])
|
||||
names = []
|
||||
for cid, rate in members[:5]:
|
||||
r = by_id[cid]
|
||||
names.append(f"{r['name']} {rate*100:.0f}%")
|
||||
L.append(f"- **{arch}**: " + " · ".join(names))
|
||||
L.append(f"- **{arch}**: " + " · ".join(f"{nm} {rate*100:.0f}%" for nm, rate in members[:5]))
|
||||
L.append("")
|
||||
(reports / "cards_overview.md").write_text("\n".join(L), encoding="utf-8")
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Careful sub-style analysis of the trophy decks, per color pair.
|
||||
|
||||
Two axes:
|
||||
A. splash composition (which 3rd/4th colors are added)
|
||||
B. play style (curve / creature ratio) and how it relates to record
|
||||
|
||||
Outputs: value/<SNAPSHOT>/reports/styles.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
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"
|
||||
cs = [c for c in order if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
def corr(xs, ys):
|
||||
n = len(xs)
|
||||
if n < 3:
|
||||
return 0.0
|
||||
mx, my = statistics.mean(xs), statistics.mean(ys)
|
||||
cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
|
||||
sx = statistics.pstdev(xs) or 1e-9
|
||||
sy = statistics.pstdev(ys) or 1e-9
|
||||
return cov / (n * sx * sy)
|
||||
|
||||
|
||||
def build(snapshot: Path, out_dir: Path, min_decks: 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", "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 []))
|
||||
|
||||
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)
|
||||
|
||||
rep = ["# FRA PremierDraft · 同色组子流派(仔细版)\n",
|
||||
"A. 第三色/第四色构成;B. 风格(曲线、生物比)与战绩关系。\n",
|
||||
"> 战绩 `record = wins/(wins+losses)`;全部是 7 胜牌,故区间约 0.78–1.00。\n"]
|
||||
|
||||
for arch, decks in sorted(pairs.items(), key=lambda kv: -len(kv[1])):
|
||||
if len(decks) < min_decks:
|
||||
continue
|
||||
splash = defaultdict(list)
|
||||
style = []
|
||||
for d in decks:
|
||||
extra = "".join(c for c in "WUBRG"
|
||||
if c in d.get("colors", "").upper() and c not in arch)
|
||||
rec = d["wins"] / (d["wins"] + d["losses"]) if (d["wins"] + d["losses"]) else None
|
||||
cnt = Counter()
|
||||
lands = 0
|
||||
for e in d["maindeck"]:
|
||||
nm = id2name.get(e["mtga_id"])
|
||||
if nm is None:
|
||||
continue
|
||||
if is_land(nm):
|
||||
lands += e["count"]
|
||||
else:
|
||||
cnt[nm] += e["count"]
|
||||
cmcs = [meta.get(nm, {}).get("cmc") or 0 for nm, k in cnt.items() for _ in range(k)]
|
||||
crea = sum(k for nm, k in cnt.items()
|
||||
if any("Creature" in t for t in (meta.get(nm, {}).get("types") or [])))
|
||||
spells = sum(cnt.values()) or 1
|
||||
feats = {
|
||||
"avg_cmc": sum(cmcs) / len(cmcs) if cmcs else 0,
|
||||
"creature_ratio": crea / spells,
|
||||
"cheap": sum(k for nm, k in cnt.items() if (meta.get(nm, {}).get("cmc") or 0) <= 2) / spells,
|
||||
"topend": sum(k for nm, k in cnt.items() if (meta.get(nm, {}).get("cmc") or 0) >= 5) / spells,
|
||||
"lands": lands, "record": rec, "extra": extra,
|
||||
}
|
||||
style.append(feats)
|
||||
splash[extra or "pure"].append(feats)
|
||||
|
||||
n = len(decks)
|
||||
rep.append(f"\n## {arch} (n={n})\n")
|
||||
# A. splash
|
||||
rep.append("**A. 第三色构成**\n")
|
||||
rep.append("| 变体 | n | 占比 | 平均记录 | 均费 | 生物比 |")
|
||||
rep.append("|---|---|---|---|---|---|")
|
||||
for extra, rows in sorted(splash.items(), key=lambda kv: -len(kv[1])):
|
||||
recs = [r["record"] for r in rows if r["record"] is not None]
|
||||
rep.append(f"| {arch}{('+' + extra) if extra != 'pure' else ' (纯)'} | {len(rows)} | "
|
||||
f"{len(rows)/n*100:.0f}% | {statistics.mean(recs):.3f} | "
|
||||
f"{statistics.mean(r['avg_cmc'] for r in rows):.2f} | "
|
||||
f"{statistics.mean(r['creature_ratio'] for r in rows):.3f} |")
|
||||
rep.append("")
|
||||
# B. style vs record
|
||||
recs = [r["record"] for r in style if r["record"] is not None]
|
||||
rep.append("**B. 风格与战绩**\n")
|
||||
rep.append(f"- 相关系数:均费↔记录 = **{corr([r['avg_cmc'] for r in style], [r['record'] or 0 for r in style]):+.3f}**,"
|
||||
f"生物比↔记录 = **{corr([r['creature_ratio'] for r in style], [r['record'] or 0 for r in style]):+.3f}**,"
|
||||
f"2费密度↔记录 = **{corr([r['cheap'] for r in style], [r['record'] or 0 for r in style]):+.3f}**")
|
||||
# tertiles by avg_cmc
|
||||
srt = sorted(style, key=lambda r: r["avg_cmc"])
|
||||
t = len(srt) // 3
|
||||
for label, seg in (("低费", srt[:t]), ("中费", srt[t:2*t]), ("高费", srt[2*t:])):
|
||||
if seg:
|
||||
rr = [r["record"] for r in seg if r["record"] is not None]
|
||||
rep.append(f"- {label}(均费 {statistics.mean(r['avg_cmc'] for r in seg):.2f}):"
|
||||
f"记录 {statistics.mean(rr):.3f},生物比 {statistics.mean(r['creature_ratio'] for r in seg):.3f},n={len(seg)}")
|
||||
rep.append("")
|
||||
|
||||
(out_dir / "reports").mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "reports/styles.md").write_text("\n".join(rep), encoding="utf-8")
|
||||
print("wrote reports/styles.md")
|
||||
|
||||
|
||||
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), args.min_decks)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/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"
|
||||
cs = [c for c in order if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
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())
|
||||
@@ -0,0 +1,250 @@
|
||||
#!/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"
|
||||
cs = [c for c in order if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
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())
|
||||
@@ -0,0 +1,222 @@
|
||||
#!/usr/bin/env python3
|
||||
"""M2: build per-archetype template decks (v1) from the trophy decklists.
|
||||
|
||||
For each two-color archetype, aggregate the winning decklists into the template
|
||||
parameters defined in README §4:
|
||||
deck_params: land_count, curve targets, creature_ratio, color pips, basics
|
||||
cards[]: target_copies (avg copies), inclusion, copy distribution,
|
||||
per-archetype importance / pick order
|
||||
|
||||
Outputs (under value/<SNAPSHOT>/):
|
||||
templates/<SET>.<FORMAT>.<COLORS>.json
|
||||
templates/_index.json
|
||||
reports/templates_overview.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
CURVE_BUCKETS = ["0", "1", "2", "3", "4", "5", "6", "7+"]
|
||||
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
|
||||
PIP_RE = re.compile(r"\{([^}]+)\}")
|
||||
|
||||
|
||||
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"
|
||||
cs = [c for c in order if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else (cs[0] if cs else None)
|
||||
|
||||
|
||||
def curve_bucket(cmc):
|
||||
if cmc is None:
|
||||
return None
|
||||
c = int(cmc)
|
||||
return "7+" if c >= 7 else str(c)
|
||||
|
||||
|
||||
def pips(mana_cost: str, color_identity) -> Counter:
|
||||
out = Counter()
|
||||
for sym in PIP_RE.findall(mana_cost or ""):
|
||||
for ch in sym:
|
||||
if ch in "WUBRG":
|
||||
out[ch] += 1
|
||||
return out
|
||||
|
||||
|
||||
def build(snapshot: Path, out_dir: Path, min_decks: 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_identity"):
|
||||
if md.get(k) in (None, "", []):
|
||||
md[k] = c.get(k)
|
||||
md.setdefault("rarity", c.get("rarity"))
|
||||
|
||||
def is_land(nm):
|
||||
return any("Land" in t for t in (meta.get(nm, {}).get("types") or []))
|
||||
|
||||
def is_basic(nm):
|
||||
return nm in BASICS
|
||||
|
||||
groups = defaultdict(list)
|
||||
for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
|
||||
arch = primary_pair(deck.get("colors"))
|
||||
if arch and len(arch) == 2:
|
||||
groups[arch].append(deck)
|
||||
|
||||
index = {}
|
||||
report = ["# FRA PremierDraft · Archetype 模板 v1\n"]
|
||||
for arch, decks in sorted(groups.items(), key=lambda kv: -len(kv[1])):
|
||||
if len(decks) < min_decks:
|
||||
continue
|
||||
n = len(decks)
|
||||
spell_counts = Counter()
|
||||
decks_with = Counter()
|
||||
copy_dist = defaultdict(Counter)
|
||||
land_totals, basic_totals, pip_totals = [], Counter(), Counter()
|
||||
curves = Counter()
|
||||
creatures = 0
|
||||
spells = 0
|
||||
|
||||
for deck in decks:
|
||||
lands = 0
|
||||
deck_cards = Counter()
|
||||
for entry in deck["maindeck"]:
|
||||
nm = id2name.get(entry["mtga_id"])
|
||||
cnt = entry["count"]
|
||||
if nm is None:
|
||||
continue
|
||||
if is_land(nm):
|
||||
lands += cnt
|
||||
if is_basic(nm):
|
||||
basic_totals[nm] += cnt
|
||||
continue
|
||||
deck_cards[nm] += cnt
|
||||
land_totals.append(lands)
|
||||
for nm, cnt in deck_cards.items():
|
||||
spell_counts[nm] += cnt
|
||||
decks_with[nm] += 1
|
||||
copy_dist[nm][min(cnt, 3)] += 1
|
||||
b = curve_bucket(meta.get(nm, {}).get("cmc"))
|
||||
if b:
|
||||
curves[b] += cnt
|
||||
if any("Creature" in t for t in (meta.get(nm, {}).get("types") or [])):
|
||||
creatures += cnt
|
||||
else:
|
||||
spells += cnt
|
||||
for ch, val in pips(meta.get(nm, {}).get("mana_cost", ""), None).items():
|
||||
pip_totals[ch] += val * cnt
|
||||
|
||||
# importance within archetype: shrunk WR + inclusion
|
||||
inc = {nm: decks_with[nm] / n for nm in decks_with}
|
||||
wr = {nm: (cards.get(nm, {}).get("gih_shrunk")) for nm in decks_with}
|
||||
wr_vals = [v for v in wr.values() if v is not None]
|
||||
mu = statistics.mean(wr_vals) if wr_vals else 0.0
|
||||
sd = statistics.pstdev(wr_vals) if len(wr_vals) > 1 else 1.0
|
||||
inc_vals = list(inc.values())
|
||||
imu = statistics.mean(inc_vals) if inc_vals else 0.0
|
||||
isd = statistics.pstdev(inc_vals) if len(inc_vals) > 1 else 1.0
|
||||
rows = []
|
||||
for nm, total in spell_counts.items():
|
||||
wrz = ((wr[nm] - mu) / sd) if (wr.get(nm) is not None and sd) else 0.0
|
||||
inz = ((inc[nm] - imu) / isd) if isd else 0.0
|
||||
rows.append({
|
||||
"name": nm,
|
||||
"mtga_id": cards.get(nm, meta.get(nm, {})).get("mtga_id"),
|
||||
"rarity": cards.get(nm, meta.get(nm, {})).get("rarity"),
|
||||
"cmc": meta.get(nm, {}).get("cmc"),
|
||||
"mana_cost": meta.get(nm, {}).get("mana_cost", ""),
|
||||
"types": meta.get(nm, {}).get("types"),
|
||||
"target_copies": round(total / n, 3), # avg copies across decks
|
||||
"avg_copies_played": round(total / decks_with[nm], 3) if decks_with[nm] else 0,
|
||||
"inclusion": round(inc[nm], 4),
|
||||
"c1": copy_dist[nm].get(1, 0),
|
||||
"c2": copy_dist[nm].get(2, 0),
|
||||
"c3plus": copy_dist[nm].get(3, 0),
|
||||
"gih_wr": cards.get(nm, {}).get("ever_drawn_win_rate"),
|
||||
"gih_shrunk": wr.get(nm),
|
||||
"importance": round(0.6 * wrz + 0.4 * inz, 4),
|
||||
})
|
||||
rows.sort(key=lambda r: -r["importance"])
|
||||
for i, r in enumerate(rows, 1):
|
||||
r["pick_priority"] = i
|
||||
|
||||
primary = max(rows, key=lambda r: (r["target_copies"], r["inclusion"]))["name"] if rows else None
|
||||
total_curve = sum(curves.values()) or 1
|
||||
template = {
|
||||
"expansion": "FRA",
|
||||
"format": "PremierDraft",
|
||||
"archetype": arch,
|
||||
"archetype_name": f"{arch}-{primary}" if primary else arch,
|
||||
"n_decks": n,
|
||||
"deck_params": {
|
||||
"land_count": round(statistics.mean(land_totals), 2),
|
||||
"basic_lands": {k: round(v / n, 2) for k, v in sorted(basic_totals.items())},
|
||||
"color_pips": {k: round(v / n, 2) for k, v in sorted(pip_totals.items())},
|
||||
"curve": {b: round(curves.get(b, 0) / n, 2) for b in CURVE_BUCKETS},
|
||||
"creature_ratio": round(creatures / (creatures + spells), 3) if (creatures + spells) else None,
|
||||
"spells_per_deck": round(sum(spell_counts.values()) / n, 2),
|
||||
},
|
||||
"cards": rows,
|
||||
}
|
||||
(out_dir / "templates").mkdir(parents=True, exist_ok=True)
|
||||
path = out_dir / "templates" / f"FRA.PremierDraft.{arch}.json"
|
||||
path.write_text(json.dumps(template, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
index[arch] = {"archetype_name": template["archetype_name"], "n_decks": n,
|
||||
"land_count": template["deck_params"]["land_count"],
|
||||
"creature_ratio": template["deck_params"]["creature_ratio"],
|
||||
"key_cards": [r["name"] for r in rows[:5]]}
|
||||
|
||||
dp = template["deck_params"]
|
||||
report.append(f"\n## {template['archetype_name']} (n={n})\n")
|
||||
report.append(f"- 地:**{dp['land_count']}**;生物比:**{dp['creature_ratio']}**;基础地:{dp['basic_lands']}")
|
||||
report.append(f"- 曲线:{dp['curve']}")
|
||||
report.append(f"- 关键牌:{' · '.join(r['name'] for r in rows[:8])}")
|
||||
|
||||
ex = out_dir / "decks"
|
||||
ex.mkdir(parents=True, exist_ok=True)
|
||||
ex.joinpath(f"{arch}.txt").write_text(
|
||||
"\n".join(f"{r['target_copies']:.1f}x {r['name']}" for r in rows[:23]), encoding="utf-8")
|
||||
|
||||
(out_dir / "templates" / "_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/templates_overview.md").write_text("\n".join(report), encoding="utf-8")
|
||||
print(f"wrote {len(index)} archetype templates -> {out_dir}/templates/")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Build archetype templates (M2).")
|
||||
ap.add_argument("--snapshot", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--min-decks", type=int, default=25)
|
||||
args = ap.parse_args()
|
||||
build(Path(args.snapshot), Path(args.out), args.min_decks)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,539 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Emit sub-archetype templates strictly following README §4.
|
||||
|
||||
Reads the trophy decks + card_data + per-pair card_data + card_relations +
|
||||
mtgch Oracle text, and writes one contract JSON per cluster:
|
||||
value/<SNAPSHOT>/templates/FRA.PremierDraft.<archetype_slug>.json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import re
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
CURVE = [("1", lambda c: c == 1), ("2", lambda c: c == 2), ("3", lambda c: c == 3),
|
||||
("4", lambda c: c == 4), ("5+", lambda c: c >= 5)]
|
||||
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
|
||||
ALL_COLORS = "WUBRG"
|
||||
Z = 1.959964
|
||||
|
||||
# §3.4 controlled vocabulary -> matching phrases in Oracle text / keywords
|
||||
CANON = {
|
||||
"Token Swarm": ("create", "token"),
|
||||
"Sacrifice Value": ("sacrifice",),
|
||||
"Spells Matter": ("instant or sorcery", "whenever you cast"),
|
||||
"Prowess": ("prowess",),
|
||||
"Reanimator": ("return target creature card from your graveyard",
|
||||
"return it to the battlefield", "from your graveyard to the battlefield"),
|
||||
"Graveyard Value": ("graveyard", "flashback"),
|
||||
"Counters Growth": ("+1/+1 counter", "counter on", "counters on"),
|
||||
"Equipment Aggro": ("equipment",),
|
||||
"Auras Matter": ("aura",),
|
||||
"Mill Drain": ("mill",),
|
||||
"Landfall Ramp": ("landfall",),
|
||||
"Flash Ambush": ("flash",),
|
||||
"Lifegain Payoff": ("gain life", "lifelink", "you gain"),
|
||||
"Treasure Ramp": ("treasure",),
|
||||
"Artifacts Matter": ("artifact",),
|
||||
"Enchantments Matter": ("enchantment",),
|
||||
"Big Mana Payoff": ("add {", "mana of any"),
|
||||
"Cascade Value": ("cascade",),
|
||||
"Cost Reduction": ("costs less", "cost {", "costs {"),
|
||||
"Power Matters": ("power is", "greatest power", "equal to its power", "power and toughness"),
|
||||
"Evasion Tempo": ("flying", "menace", "can't be blocked", "unblockable"),
|
||||
"Removal Heavy": ("destroy target", "exile target"),
|
||||
}
|
||||
MTGCH: dict = {}
|
||||
|
||||
|
||||
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
|
||||
cs = [c for c in ALL_COLORS if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
def slugify(s):
|
||||
return re.sub(r"[^A-Za-z0-9]+", "_", s or "").strip("_")
|
||||
|
||||
|
||||
def wilson(wins, n, z=Z):
|
||||
if not n:
|
||||
return None
|
||||
p = wins / n
|
||||
d = 1 + z * z / n
|
||||
c = p + z * z / (2 * n)
|
||||
m = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
|
||||
return [round((c - m) / d, 3), round((c + m) / d, 3)]
|
||||
|
||||
|
||||
def pips(mana_cost):
|
||||
out = Counter()
|
||||
for sym in re.findall(r"\{([^}]+)\}", mana_cost or ""):
|
||||
for ch in sym:
|
||||
if ch in ALL_COLORS:
|
||||
out[ch] += 1
|
||||
return out
|
||||
|
||||
|
||||
def load_mtgch(cards_dir: Path, names: set, cache: Path) -> dict:
|
||||
if cache.exists():
|
||||
d = json.loads(cache.read_text(encoding="utf-8"))
|
||||
if names.issubset(d):
|
||||
return d
|
||||
out = {}
|
||||
for p in cards_dir.rglob("*.txt"):
|
||||
nm, orc, kws = None, [], []
|
||||
try:
|
||||
for line in p.open(encoding="utf-8", errors="ignore"):
|
||||
if line.startswith("Name:"):
|
||||
nm = line[5:].strip()
|
||||
elif line.startswith("Oracle:"):
|
||||
orc.append(line[7:].strip())
|
||||
elif line.startswith("K:"):
|
||||
kws.append(line[2:].split(":")[0].strip())
|
||||
except OSError:
|
||||
continue
|
||||
if nm:
|
||||
out[nm] = {"oracle": " ".join(orc).lower(), "keywords": kws}
|
||||
cache.parent.mkdir(parents=True, exist_ok=True)
|
||||
cache.write_text(json.dumps(out, ensure_ascii=False), encoding="utf-8")
|
||||
return out
|
||||
|
||||
|
||||
def mech_tags(name) -> list:
|
||||
info = MTGCH.get(name)
|
||||
if not info:
|
||||
return []
|
||||
text = info["oracle"] + " " + " ".join(info["keywords"]).lower()
|
||||
return [tag for tag, keys in CANON.items() if any(k in text for k in keys)]
|
||||
|
||||
|
||||
def role_list(base, tags):
|
||||
r, types = [], base.get("types") or []
|
||||
if any("Land" in t for t in types):
|
||||
return ["land"]
|
||||
if any("Creature" in t for t in types):
|
||||
r.append("creature")
|
||||
if base.get("rarity") in ("mythic", "rare") and (base.get("ever_drawn_win_rate") or 0) >= 0.58:
|
||||
r.append("bomb")
|
||||
if "Removal Heavy" in tags:
|
||||
r.append("removal")
|
||||
if any("Instant" in t or "Sorcery" in t for t in types) and ("Removal Heavy" in tags):
|
||||
r.append("interaction")
|
||||
if base.get("cmc") is not None and base["cmc"] >= 5:
|
||||
r.append("topend")
|
||||
if tags:
|
||||
r.append("payoff")
|
||||
return r or ["filler"]
|
||||
|
||||
|
||||
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]
|
||||
r = rnd.random() * (sum(d2) or 1.0)
|
||||
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 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 silhouette(D, assign, k):
|
||||
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(len(D)):
|
||||
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) / len(s)
|
||||
|
||||
|
||||
def build(snapshot: Path, out_dir: Path, mtgch_dir: Path, ks=(2, 3), min_decks=40,
|
||||
min_rate=0.05) -> None:
|
||||
global MTGCH
|
||||
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", "color_identity"):
|
||||
if md.get(k) in (None, "", []):
|
||||
md[k] = c.get(k)
|
||||
|
||||
MTGCH = load_mtgch(mtgch_dir / "cards", set(cards),
|
||||
out_dir.parent / "_shared/mtgch_index.json")
|
||||
relations = {}
|
||||
rf = out_dir / "card_relations.json"
|
||||
if rf.exists():
|
||||
relations = json.loads(rf.read_text(encoding="utf-8"))
|
||||
|
||||
pair_gih = {}
|
||||
for p in ("WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"):
|
||||
f = snapshot / f"stats/card_data.{p}.json"
|
||||
if f.exists():
|
||||
pair_gih[p] = {c["name"]: c.get("ever_drawn_win_rate")
|
||||
for c in json.loads(f.read_text(encoding="utf-8"))["data"]}
|
||||
|
||||
# per-draft card -> [seen_games, wins], for cluster-level context_delta
|
||||
draft_card_games: dict = {}
|
||||
ev = snapshot / "drafts/event_details.jsonl"
|
||||
if ev.exists():
|
||||
for rec in load_jsonl(ev):
|
||||
agg = defaultdict(lambda: [0, 0])
|
||||
for m in rec.get("details", {}).get("match_results") or []:
|
||||
for g in m.get("game_results") or []:
|
||||
seen = set()
|
||||
for key in ("opening_hand", "drawn_cards", "tutored_cards"):
|
||||
for cid in g.get(key) or []:
|
||||
nm = id2name.get(cid)
|
||||
if nm:
|
||||
seen.add(nm)
|
||||
won = 1 if g.get("won") else 0
|
||||
for nm in seen:
|
||||
agg[nm][0] += 1
|
||||
agg[nm][1] += won
|
||||
draft_card_games[rec["draft_id"]] = agg
|
||||
|
||||
# trophy-wide baseline per card (same population as the clusters)
|
||||
trophy = defaultdict(lambda: [0, 0])
|
||||
for agg in draft_card_games.values():
|
||||
for nm, (gg, ww) in agg.items():
|
||||
trophy[nm][0] += gg
|
||||
trophy[nm][1] += ww
|
||||
trophy_gih = {nm: (v[1] / v[0] if v[0] >= 20 else None) for nm, v in trophy.items()}
|
||||
|
||||
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)
|
||||
|
||||
tdir = out_dir / "templates"
|
||||
tdir.mkdir(parents=True, exist_ok=True)
|
||||
index = {}
|
||||
members_map = {}
|
||||
for arch, decks in sorted(pairs.items(), key=lambda kv: -len(kv[1])):
|
||||
if len(decks) < min_decks:
|
||||
continue
|
||||
n = len(decks)
|
||||
cnts, land_tot, basic_tot, nbasic, extra_dist = [], [], Counter(), [], Counter()
|
||||
for deck in decks:
|
||||
cnt, lands, bl, nbl = Counter(), 0, Counter(), Counter()
|
||||
for e in deck["maindeck"]:
|
||||
nm = id2name.get(e["mtga_id"])
|
||||
if nm is None:
|
||||
continue
|
||||
if is_land(nm):
|
||||
lands += e["count"]
|
||||
if nm in BASICS:
|
||||
bl[nm] += e["count"]
|
||||
else:
|
||||
nbl[nm] += e["count"]
|
||||
continue
|
||||
cnt[nm] += e["count"]
|
||||
cnts.append(cnt)
|
||||
land_tot.append(lands)
|
||||
basic_tot.update(bl)
|
||||
nbasic.append(nbl)
|
||||
extra_dist[len(set(deck.get("colors", "").upper()) - set(arch))] += 1
|
||||
|
||||
df = Counter()
|
||||
for cnt in cnts:
|
||||
for nm in cnt:
|
||||
if set(cards.get(nm, {}).get("color") or "") <= set(arch):
|
||||
df[nm] += 1
|
||||
pair_total = Counter()
|
||||
for cnt in cnts:
|
||||
pair_total.update(cnt)
|
||||
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)
|
||||
if min(Counter(a).values()) < 3:
|
||||
continue
|
||||
s = silhouette(D, a, k)
|
||||
if best is None or s > best[2]:
|
||||
best = (k, a, s)
|
||||
if best is None:
|
||||
continue
|
||||
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)
|
||||
cluster_total = Counter()
|
||||
for i in members:
|
||||
cluster_total.update(cnts[i])
|
||||
n_rest = max(1, n - len(members))
|
||||
land_mean = Counter()
|
||||
for i in members:
|
||||
for nm, v in nbasic[i].items():
|
||||
land_mean[nm] += v / len(members)
|
||||
gi = pair_gih.get(arch, {})
|
||||
clust = defaultdict(lambda: [0, 0])
|
||||
for i in members:
|
||||
for nm, (gg, ww) in (draft_card_games.get(decks[i].get("aggregate_id")) or {}).items():
|
||||
clust[nm][0] += gg
|
||||
clust[nm][1] += ww
|
||||
max_mc = max(mean.values()) or 1.0
|
||||
gv = [gi.get(nm) for nm in mean if gi.get(nm) is not None] or [0.5]
|
||||
lo, hi = min(gv), max(gv)
|
||||
cards_out = []
|
||||
for nm, mc in sorted(mean.items(), key=lambda kv: -kv[1]):
|
||||
base = cards.get(nm, {})
|
||||
g = base.get("ever_drawn_game_count") or 0
|
||||
gw = base.get("ever_drawn_win_rate")
|
||||
wins = (gw * g) if (gw is not None and g) else 0
|
||||
gic = gi.get(nm)
|
||||
tags = mech_tags(nm)
|
||||
imp = 0.7 * (mc / max_mc) + 0.3 * (((gic - lo) / (hi - lo)) if (gic and hi > lo) else 0.5)
|
||||
defining = mc - (pair_total[nm] - cluster_total[nm]) / n_rest
|
||||
rel = relations.get(nm, {})
|
||||
defwd = sum(1 for i in members if nm in cnts[i])
|
||||
incl = defwd / len(members)
|
||||
tc = (cluster_total[nm] / defwd) if defwd else 0.0 # actual copies when played
|
||||
cg = clust.get(nm)
|
||||
cluster_gih = (cg[1] / cg[0]) if (cg and cg[0] >= 20) else None
|
||||
tbase = trophy_gih.get(nm)
|
||||
ctx_delta = (round(cluster_gih - tbase, 4)
|
||||
if (cluster_gih is not None and tbase is not None) else None)
|
||||
cards_out.append({
|
||||
"mtga_id": base.get("mtga_id"),
|
||||
"name": nm,
|
||||
"rarity": base.get("rarity"),
|
||||
"cmc": meta.get(nm, {}).get("cmc"),
|
||||
"color_pips": dict(pips(meta.get(nm, {}).get("mana_cost", ""))),
|
||||
"roles": role_list(base, tags),
|
||||
"mechanic_tags": tags,
|
||||
"target_copies": round(tc, 2),
|
||||
"expected_copies": round(mc, 3),
|
||||
"inclusion": round(incl, 4),
|
||||
"min_copies": 1 if incl >= 0.5 else 0,
|
||||
"max_copies": max(1, min(4, math.ceil(tc) + (1 if tc >= 1 else 0))),
|
||||
"importance": round(imp, 3),
|
||||
"defining_score": round(defining, 3),
|
||||
"pick_priority": 0,
|
||||
"pick_threshold": {"P1": 1 if (base.get("avg_pick") or 9) <= 2.5 else 0,
|
||||
"midpack": bool((base.get("play_rate") or 0) > 0.5)},
|
||||
"gih_wr": gw,
|
||||
"gih_wr_ci": wilson(wins, g),
|
||||
"alsa": base.get("avg_seen"),
|
||||
"ata": base.get("avg_pick"),
|
||||
"play_rate": base.get("play_rate"),
|
||||
"context_delta": ctx_delta,
|
||||
"cluster_gih_wr": (round(cluster_gih, 4) if cluster_gih is not None else None),
|
||||
"cluster_sample_games": (cg[0] if cg else 0),
|
||||
"trophy_gih_wr": (round(tbase, 4) if tbase is not None else None),
|
||||
"sample_games": g,
|
||||
"synergy": rel.get("synergy", []),
|
||||
"substitutes": rel.get("substitutes", []),
|
||||
"antisynergy": rel.get("antisynergy", []),
|
||||
})
|
||||
# nonbasic lands
|
||||
for nm, mc in sorted(land_mean.items(), key=lambda kv: -kv[1]):
|
||||
if mc < 0.05:
|
||||
continue
|
||||
base = cards.get(nm, meta.get(nm, {}))
|
||||
cards_out.append({
|
||||
"mtga_id": base.get("mtga_id"), "name": nm,
|
||||
"rarity": base.get("rarity"),
|
||||
"cmc": meta.get(nm, {}).get("cmc"),
|
||||
"color_pips": dict(pips(meta.get(nm, {}).get("mana_cost", ""))),
|
||||
"roles": ["land"], "mechanic_tags": [],
|
||||
"target_copies": round(mc, 3), "min_copies": 1 if mc >= 0.5 else 0,
|
||||
"max_copies": max(1, math.ceil(mc)), "importance": 0.5,
|
||||
"pick_priority": 0, "pick_threshold": {"P1": 0, "midpack": False},
|
||||
"gih_wr": base.get("ever_drawn_win_rate"), "gih_wr_ci": None,
|
||||
"alsa": base.get("avg_seen"), "ata": base.get("avg_pick"),
|
||||
"play_rate": base.get("play_rate"), "context_delta": None,
|
||||
"sample_games": base.get("ever_drawn_game_count") or 0,
|
||||
"synergy": [], "substitutes": [], "antisynergy": [],
|
||||
})
|
||||
# pick_priority: importance order (pick semantics)
|
||||
for i, r in enumerate(sorted((r for r in cards_out if r["roles"] != ["land"]),
|
||||
key=lambda r: -r["importance"]), 1):
|
||||
r["pick_priority"] = i
|
||||
# display order: CMC asc, then importance; lands last
|
||||
cards_out.sort(key=lambda r: (r["roles"] == ["land"],
|
||||
-(r.get("target_copies") or 0),
|
||||
r.get("cmc") if r.get("cmc") is not None else 99))
|
||||
|
||||
curve, crea, tot_spell, pipsum = Counter(), 0.0, 0.0, Counter()
|
||||
for nm, mc in mean.items():
|
||||
cmc = meta.get(nm, {}).get("cmc") or 0
|
||||
tot_spell += mc
|
||||
for b, fn in CURVE:
|
||||
if fn(cmc):
|
||||
curve[b] += mc
|
||||
if any("Creature" in t for t in (meta.get(nm, {}).get("types") or [])):
|
||||
crea += mc
|
||||
for ch, v in pips(meta.get(nm, {}).get("mana_cost", "")).items():
|
||||
pipsum[ch] += v * mc
|
||||
primary = max(mean.items(), key=lambda kv: kv[1])[0]
|
||||
defining_cards = [r["name"] for r in
|
||||
sorted((r for r in cards_out if r["roles"] != ["land"]),
|
||||
key=lambda r: -r["defining_score"])][:8]
|
||||
tagw = Counter()
|
||||
_byname = {r["name"]: r for r in cards_out}
|
||||
for _nm in defining_cards[:8]:
|
||||
for t in _byname[_nm]["mechanic_tags"]:
|
||||
tagw[t] += _byname[_nm]["target_copies"]
|
||||
mech = (tagw.most_common(1)[0][0] if tagw else
|
||||
("Midrange" if crea / (tot_spell or 1) < 0.55 else "Creatures"))
|
||||
base_slug = f"{arch}-{slugify(primary)}-{slugify(mech)}"
|
||||
slug, suffix = base_slug, 2
|
||||
while slug in index:
|
||||
slug = f"{base_slug}-{suffix}"
|
||||
suffix += 1
|
||||
landsrc = Counter()
|
||||
for nm, mc in land_mean.items():
|
||||
for ch in (meta.get(nm, {}).get("color_identity") or []):
|
||||
if ch in ALL_COLORS:
|
||||
landsrc[ch] += mc
|
||||
combined = Counter(pipsum)
|
||||
for k, v in landsrc.items():
|
||||
combined[k] += v
|
||||
color_weights = {kk: round(v / (sum(combined.values()) or 1), 3)
|
||||
for kk, v in sorted(combined.items())}
|
||||
spell_pips = {kk: round(v / (sum(pipsum.values()) or 1), 3)
|
||||
for kk, v in sorted(pipsum.items())}
|
||||
extra_avg = sum(a * b for a, b in extra_dist.items()) / n
|
||||
template = {
|
||||
"expansion": "FRA", "format": "PremierDraft",
|
||||
"archetype": arch, "cluster": c,
|
||||
"archetype_name": f"{arch}-{primary}-{mech}",
|
||||
"archetype_slug": slug,
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"confidence": round(min(1.0, len(members) / 150), 2),
|
||||
"n_decks": len(members), "silhouette": round(sil, 3),
|
||||
"defining_cards": defining_cards,
|
||||
"deck_params": {
|
||||
"land_count": round(sum(land_tot[i] for i in members) / len(members), 2),
|
||||
"splash_max": int(round(extra_avg)),
|
||||
"splash_dist": dict(sorted(extra_dist.items())),
|
||||
"curve_targets": {b: round(curve.get(b, 0), 2) for b, _ in CURVE},
|
||||
"creature_ratio": round(crea / (tot_spell or 1), 3),
|
||||
"color_weights": color_weights,
|
||||
"spell_pips": spell_pips,
|
||||
"land_sources": {kk: round(v, 2) for kk, v in sorted(landsrc.items())},
|
||||
"basic_lands": {kk: round(v / len(members), 2)
|
||||
for kk, v in sorted(basic_tot.items())},
|
||||
},
|
||||
"cards": cards_out,
|
||||
}
|
||||
(tdir / f"FRA.PremierDraft.{slug}.json").write_text(
|
||||
json.dumps(template, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
index[slug] = {"archetype": arch, "cluster": c, "n": len(members),
|
||||
"name": template["archetype_name"],
|
||||
"defining_cards": defining_cards,
|
||||
"key_cards": [r["name"] for r in cards_out if r["roles"] != ["land"]][:5]}
|
||||
members_map[slug] = sorted({decks[i].get("aggregate_id") for i in members})
|
||||
print(f"{slug} n={len(members)} mech={mech}")
|
||||
|
||||
(tdir / "_index.json").write_text(json.dumps(index, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
(tdir / "_members.json").write_text(json.dumps(members_map, ensure_ascii=False),
|
||||
encoding="utf-8")
|
||||
print(f"\nwrote {len(index)} templates -> {tdir}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--snapshot", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--mtgch", default="data/mtgch")
|
||||
ap.add_argument("--min-decks", type=int, default=40)
|
||||
args = ap.parse_args()
|
||||
build(Path(args.snapshot), Path(args.out), Path(args.mtgch), min_decks=args.min_decks)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/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"
|
||||
cs = [c for c in order if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
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())
|
||||
@@ -0,0 +1,281 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Find distinct sub-archetypes ("流派") inside each color pair.
|
||||
|
||||
Pure standard library (no numpy). For each two-color pair:
|
||||
* build a deck x card matrix (TF-IDF weighted, nonland cards only)
|
||||
* k-means for k=2..4, pick the best by silhouette
|
||||
* describe each cluster by its most over-represented cards + deck stats
|
||||
|
||||
Outputs (under value/<SNAPSHOT>/):
|
||||
subarchetypes/<COLORS>.json
|
||||
reports/subarchetypes.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
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"
|
||||
cs = [c for c in order if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
def norm(a):
|
||||
return math.sqrt(sum(v * v for v in a))
|
||||
|
||||
|
||||
def dot(a, b):
|
||||
return sum(x * y for x, y in zip(a, b))
|
||||
|
||||
|
||||
def kmeans(X, k, iters=120, seed=7):
|
||||
rnd = random.Random(seed)
|
||||
n = len(X)
|
||||
# k-means++ init
|
||||
centers = [list(X[rnd.randrange(n)])]
|
||||
for _ in range(k - 1):
|
||||
d2 = []
|
||||
for x in X:
|
||||
best = min(sum((xi - ci) ** 2 for xi, ci in zip(x, c)) for c in centers)
|
||||
d2.append(best)
|
||||
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
|
||||
else:
|
||||
centers.append(list(X[rnd.randrange(n)]))
|
||||
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] = bc
|
||||
changed = 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)
|
||||
if k < 2 or n <= k:
|
||||
return -1.0
|
||||
groups = defaultdict(list)
|
||||
for i, a in enumerate(assign):
|
||||
groups[a].append(i)
|
||||
if 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_matrix(X):
|
||||
n = len(X)
|
||||
norms = [sum(v * v for v in x) for x in X]
|
||||
# squared distances via dot products; store sqrt
|
||||
D = [[0.0] * n for _ in range(n)]
|
||||
for i in range(n):
|
||||
xi = X[i]
|
||||
for j in range(i + 1, n):
|
||||
d2 = norms[i] + norms[j] - 2 * dot(xi, X[j])
|
||||
d = math.sqrt(d2 if d2 > 0 else 0.0)
|
||||
D[i][j] = D[j][i] = d
|
||||
return D
|
||||
|
||||
|
||||
def build(snapshot: Path, out_dir: Path, min_decks: int,
|
||||
ks=(2, 3, 4), min_card_rate=0.05, color_restrict=True) -> 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"):
|
||||
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 / "subarchetypes").mkdir(parents=True, exist_ok=True)
|
||||
report = ["# FRA PremierDraft · 同色组子流派分析\n",
|
||||
"方法:仅用非地牌,TF-IDF 加权 → KMeans(k=2..4) → 取 silhouette 最高;",
|
||||
"下面列出每个簇的**差异化卡牌**(簇内平均张数 − 组内其余)与套牌统计。\n"]
|
||||
|
||||
for arch, decks in sorted(pairs.items(), key=lambda kv: -len(kv[1])):
|
||||
if len(decks) < min_decks:
|
||||
continue
|
||||
n = len(decks)
|
||||
raw, stats = [], []
|
||||
for deck in decks:
|
||||
cnt = Counter()
|
||||
lands = 0
|
||||
colors = set()
|
||||
for e in deck["maindeck"]:
|
||||
nm = id2name.get(e["mtga_id"])
|
||||
if nm is None:
|
||||
continue
|
||||
if is_land(nm):
|
||||
lands += e["count"]
|
||||
continue
|
||||
cnt[nm] += e["count"]
|
||||
for c in deck.get("colors", ""):
|
||||
colors.add(c.upper())
|
||||
cmcs = [meta.get(nm, {}).get("cmc") or 0 for nm, k in cnt.items() for _ in range(k)]
|
||||
crea = sum(k for nm, k in cnt.items()
|
||||
if any("Creature" in t for t in (meta.get(nm, {}).get("types") or [])))
|
||||
spells = sum(cnt.values()) or 1
|
||||
raw.append(cnt)
|
||||
stats.append({
|
||||
"lands": lands, "spells": spells,
|
||||
"avg_cmc": sum(cmcs) / len(cmcs) if cmcs else 0,
|
||||
"creature_ratio": crea / spells,
|
||||
"colors": "".join(c for c in "WUBRG" if c in colors),
|
||||
})
|
||||
# vocabulary: cards in >= min_card_rate of decks; optionally only the
|
||||
# archetype's own colors (filters out splash cards so style can surface)
|
||||
df = Counter()
|
||||
for cnt in raw:
|
||||
for nm in cnt:
|
||||
if color_restrict and not set(cards.get(nm, {}).get("color") or "") <= set(arch):
|
||||
continue
|
||||
df[nm] += 1
|
||||
vocab = sorted(nm for nm, d in df.items() if d / n >= min_card_rate)
|
||||
idx = {nm: i for i, nm in enumerate(vocab)}
|
||||
X = []
|
||||
for cnt in raw:
|
||||
vec = [0.0] * len(vocab)
|
||||
for nm, c in cnt.items():
|
||||
if nm in idx:
|
||||
vec[idx[nm]] = c * math.log(n / df[nm])
|
||||
ln = norm(vec) or 1.0
|
||||
X.append([v / ln for v in vec])
|
||||
D = gram_matrix(X)
|
||||
|
||||
best = None
|
||||
for k in ks:
|
||||
if k >= n:
|
||||
continue
|
||||
assign = kmeans(X, k)
|
||||
sil = silhouette(D, assign, k)
|
||||
if best is None or sil > best[2]:
|
||||
best = (k, assign, sil)
|
||||
k, assign, sil = best
|
||||
|
||||
clusters = []
|
||||
for j in range(k):
|
||||
members = [i for i, a in enumerate(assign) if a == j]
|
||||
if not members:
|
||||
continue
|
||||
# differential cards: mean copies within - mean within rest
|
||||
mean_in = Counter()
|
||||
for i in members:
|
||||
for nm, c in raw[i].items():
|
||||
mean_in[nm] += c
|
||||
for nm in mean_in:
|
||||
mean_in[nm] /= len(members)
|
||||
rest = [i for i in range(n) if assign[i] != j]
|
||||
mean_out = Counter()
|
||||
for i in rest:
|
||||
for nm, c in raw[i].items():
|
||||
mean_out[nm] += c
|
||||
for nm in mean_out:
|
||||
mean_out[nm] /= max(1, len(rest))
|
||||
diffs = sorted(((nm, mean_in[nm] - mean_out.get(nm, 0.0)) for nm in list(mean_in)),
|
||||
key=lambda x: -x[1])
|
||||
diffs = [d for d in diffs if d[1] > 0.08][:8]
|
||||
clusters.append({
|
||||
"size": len(members),
|
||||
"avg_lands": round(sum(stats[i]["lands"] for i in members) / len(members), 2),
|
||||
"avg_cmc": round(sum(stats[i]["avg_cmc"] for i in members) / len(members), 2),
|
||||
"creature_ratio": round(sum(stats[i]["creature_ratio"] for i in members) / len(members), 3),
|
||||
"splash_3color_rate": round(sum(1 for i in members if len(stats[i]["colors"]) >= 3) / len(members), 3),
|
||||
"defining_cards": [{"name": nm, "in": round(mean_in[nm], 2),
|
||||
"out": round(mean_out.get(nm, 0.0), 2),
|
||||
"diff": round(d, 2)} for nm, d in diffs],
|
||||
})
|
||||
(out_dir / "subarchetypes" / f"{arch}.json").write_text(
|
||||
json.dumps({"archetype": arch, "n_decks": n, "k": k,
|
||||
"silhouette": round(sil, 3), "clusters": clusters},
|
||||
ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
|
||||
report.append(f"\n## {arch} (n={n}) — k={k}, silhouette={sil:.3f}\n")
|
||||
for ci, cl in enumerate(clusters, 1):
|
||||
cards_str = " · ".join(f"{c['name']} (+{c['diff']})" for c in cl["defining_cards"][:6])
|
||||
report.append(f"**簇 {ci}** n={cl['size']} | 地 {cl['avg_lands']} | 均费 {cl['avg_cmc']} | "
|
||||
f"生物比 {cl['creature_ratio']} | 三色率 {cl['splash_3color_rate']}")
|
||||
report.append(f"- 定义牌:{cards_str}\n")
|
||||
print(f"{arch}: n={n} best k={k} silhouette={sil:.3f} sizes={[c['size'] for c in clusters]}")
|
||||
|
||||
(out_dir / "reports").mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "reports/subarchetypes.md").write_text("\n".join(report), encoding="utf-8")
|
||||
print(f"\nwrote {out_dir}/reports/subarchetypes.md and subarchetypes/*.json")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Find sub-archetypes per color pair.")
|
||||
ap.add_argument("--snapshot", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--min-decks", type=int, default=40)
|
||||
ap.add_argument("--all-colors", action="store_true",
|
||||
help="do not restrict to the pair's own colors (keep splash cards)")
|
||||
args = ap.parse_args()
|
||||
build(Path(args.snapshot), Path(args.out), args.min_decks,
|
||||
color_restrict=not args.all_colors)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,380 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render the archetype templates as an HTML view.
|
||||
|
||||
Combines:
|
||||
value/<SNAPSHOT>/templates/*.json (parameters + evidence)
|
||||
value/<SNAPSHOT>/templates/_members.json (cluster -> draft ids)
|
||||
data/17lands/<SNAPSHOT>/drafts/event_details.jsonl (game results)
|
||||
data/mtgch/image-en|image-cn/*.webp (card art, EN/CN)
|
||||
|
||||
Output: value/<SNAPSHOT>/reports/templates/index.html + <slug>.html
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
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 slugify(s):
|
||||
return re.sub(r"[^A-Za-z0-9]+", "_", s or "").strip("_")
|
||||
|
||||
|
||||
def primary_pair(colors):
|
||||
if not colors:
|
||||
return None
|
||||
cs = [c for c in "WUBRG" if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
def esc(s):
|
||||
return html.escape(str(s)) if s is not None else ""
|
||||
|
||||
|
||||
COLOR_HEX = {"W": "#f8e7b9", "U": "#bcd9ea", "B": "#cac5c0", "R": "#f0a58f", "G": "#a3c9a0"}
|
||||
|
||||
|
||||
def load_cn_names(mtgch: Path) -> dict:
|
||||
f = mtgch / "cardnames-zh-CN.txt"
|
||||
out = {}
|
||||
if f.exists():
|
||||
for line in f.open(encoding="utf-8"):
|
||||
parts = line.rstrip("\n").split("|")
|
||||
if len(parts) >= 2 and parts[0] and parts[1] and parts[1] != parts[0]:
|
||||
out[parts[0]] = parts[1]
|
||||
return out
|
||||
|
||||
|
||||
def build(snapshot: Path, out_dir: Path, mtgch: Path, report_dir: Path) -> None:
|
||||
tdir = out_dir / "templates"
|
||||
rel = os.path.relpath(mtgch, report_dir).replace("\\", "/")
|
||||
rel_img_en = f"{rel}/image-en"
|
||||
rel_img_cn = f"{rel}/image-cn"
|
||||
|
||||
# id -> name
|
||||
cards = json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]
|
||||
id2name = {c["mtga_id"]: c["name"] for c in cards}
|
||||
card_url = {c["name"]: c.get("url") for c in cards}
|
||||
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
|
||||
for cid, m in (rec.get("cards") or {}).items():
|
||||
id2name.setdefault(int(cid), m.get("name"))
|
||||
card_url.setdefault(m.get("name"), m.get("image_url"))
|
||||
|
||||
def img(name, lang):
|
||||
sl = slugify(name).lower()
|
||||
if sl:
|
||||
p = mtgch / f"image-{lang}" / sl[0] / f"{sl}.full.webp"
|
||||
if p.exists():
|
||||
return f"{rel_img_en if lang == 'en' else rel_img_cn}/{sl[0]}/{sl}.full.webp"
|
||||
if lang == "cn":
|
||||
pe = mtgch / "image-en" / sl[0] / f"{sl}.full.webp"
|
||||
if pe.exists():
|
||||
return f"{rel_img_en}/{sl[0]}/{sl}.full.webp"
|
||||
return card_url.get(name) # Scryfall fallback (EN)
|
||||
|
||||
cn_names = load_cn_names(mtgch)
|
||||
|
||||
# game results per draft_id
|
||||
games_by_draft: dict[str, list] = defaultdict(list)
|
||||
ev = snapshot / "drafts/event_details.jsonl"
|
||||
if ev.exists():
|
||||
for rec in load_jsonl(ev):
|
||||
for m in rec.get("details", {}).get("match_results") or []:
|
||||
for g in m.get("game_results") or []:
|
||||
games_by_draft[rec["draft_id"]].append({
|
||||
"won": bool(g.get("won")), "on_play": g.get("on_play"),
|
||||
"turns": g.get("total_turns"), "opp": primary_pair(g.get("opponent_colors")),
|
||||
"mull": g.get("mulligans") or 0,
|
||||
})
|
||||
|
||||
members = json.loads((tdir / "_members.json").read_text(encoding="utf-8"))
|
||||
draft_rec = {}
|
||||
for d in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
|
||||
draft_rec[d["aggregate_id"]] = (d["wins"], d["losses"])
|
||||
templates = []
|
||||
for f in tdir.glob("FRA.PremierDraft.*.json"):
|
||||
templates.append(json.loads(f.read_text(encoding="utf-8")))
|
||||
templates.sort(key=lambda t: (t["archetype"], -t["n_decks"]))
|
||||
|
||||
report_dir.mkdir(parents=True, exist_ok=True)
|
||||
for t in templates:
|
||||
slug = t["archetype_slug"]
|
||||
gl = []
|
||||
for did in members.get(slug, []):
|
||||
gl.extend(games_by_draft.get(did, []))
|
||||
wins = sum(1 for g in gl if g["won"])
|
||||
n = len(gl) or 1
|
||||
rec = wins / n
|
||||
onp = [g for g in gl if g["on_play"] is True]
|
||||
dfp = [g for g in gl if g["on_play"] is False]
|
||||
op_wr = (sum(1 for g in onp if g["won"]) / len(onp)) if onp else 0
|
||||
df_wr = (sum(1 for g in dfp if g["won"]) / len(dfp)) if dfp else 0
|
||||
turns = [g["turns"] for g in gl if g["turns"]]
|
||||
avg_turns = sum(turns) / len(turns) if turns else 0
|
||||
mull = sum(g["mull"] for g in gl) / n
|
||||
drafts = [draft_rec[d] for d in members.get(slug, []) if d in draft_rec]
|
||||
dn = len(drafts) or 1
|
||||
dr_avg = sum(w / (w + l) for w, l in drafts) / dn if drafts else 0
|
||||
dr_70 = sum(1 for w, l in drafts if l == 0) / dn if drafts else 0
|
||||
opp = defaultdict(lambda: [0, 0])
|
||||
for g in gl:
|
||||
o = g["opp"] or "?"
|
||||
opp[o][0] += 1
|
||||
opp[o][1] += 1 if g["won"] else 0
|
||||
|
||||
t["_game"] = {"n": len(gl), "wr": rec, "op_wr": op_wr, "df_wr": df_wr,
|
||||
"avg_turns": avg_turns, "mull": mull, "drafts": dn,
|
||||
"draft_record": dr_avg, "seven0": dr_70,
|
||||
"matchups": sorted(((k, v[0], v[1] / v[0]) for k, v in opp.items()),
|
||||
key=lambda x: -x[1])}
|
||||
write_detail(t, slug, img, id2name, report_dir, rel, cn_names)
|
||||
write_index(templates, report_dir)
|
||||
print(f"rendered {len(templates)} template pages -> {report_dir}")
|
||||
|
||||
|
||||
def card_tile(c, img, id2name, cn_names):
|
||||
en = img(c["name"], "en")
|
||||
cn = img(c["name"], "cn")
|
||||
tc = c["target_copies"]
|
||||
cd = c.get("context_delta")
|
||||
cd_s = "-" if cd is None else f"{cd:+.3f}"
|
||||
cd_cls = "" if cd is None else ("ctx-pos" if cd > 0 else "ctx-neg")
|
||||
tags = " ".join(f"<span class=tg>{esc(t)}</span>" for t in (c.get("mechanic_tags") or []))
|
||||
roles = " ".join(esc(r) for r in (c.get("roles") or []))
|
||||
syn = ", ".join(esc(id2name.get(s["mtga_id"], s["mtga_id"])) for s in (c.get("synergy") or [])[:3])
|
||||
imgs = ""
|
||||
if en:
|
||||
imgs += f'<img class="ci en" loading="lazy" src="{en}" alt="{esc(c["name"])}">'
|
||||
if cn:
|
||||
imgs += f'<img class="ci cn" loading="lazy" src="{cn}" alt="{esc(c["name"])}">'
|
||||
if not en and not cn:
|
||||
imgs = '<div class="ci placeholder">no image</div>'
|
||||
cid = c.get("mtga_id")
|
||||
cn = cn_names.get(c["name"])
|
||||
return f"""<div class="card">
|
||||
<div class="imgwrap">{imgs}</div>
|
||||
<div class="cbody">
|
||||
<div class="cname">{esc(c["name"])}</div>
|
||||
{f'<div class="cnname">{esc(cn)}</div>' if cn else ''}
|
||||
<div class="crow"><span class="tc">{tc:.2f}</span><span class="rl">{roles}</span>
|
||||
<span class="imp">imp {c.get("importance")}</span></div>
|
||||
<div class="stats">GIH {fmt(c.get("gih_wr"))} · Δ <span class="{cd_cls}">{cd_s}</span> · inc {pct(c.get("inclusion"))} · prio {c.get("pick_priority")} · n={c.get("cluster_sample_games")}</div>
|
||||
<div class="tags">{tags}</div>
|
||||
{f'<div class="syn">syn: {syn}</div>' if syn else ''}
|
||||
</div></div>"""
|
||||
|
||||
|
||||
def key_tile(c, img, id2name, cn_names, rank):
|
||||
en = img(c["name"], "en")
|
||||
cn = img(c["name"], "cn")
|
||||
imgs = ""
|
||||
if en:
|
||||
imgs += f'<img class="ci en" loading="lazy" src="{en}" alt="{esc(c["name"])}">'
|
||||
if cn:
|
||||
imgs += f'<img class="ci cn" loading="lazy" src="{cn}" alt="{esc(c["name"])}">'
|
||||
if not en and not cn:
|
||||
imgs = '<div class="ci placeholder">no image</div>'
|
||||
cnname = cn_names.get(c["name"])
|
||||
cd = c.get("context_delta")
|
||||
cd_s = "-" if cd is None else f"{cd:+.3f}"
|
||||
cd_cls = "" if cd is None else ("ctx-pos" if cd > 0 else "ctx-neg")
|
||||
tags = " ".join(f"<span class=tg>{esc(t)}</span>" for t in (c.get("mechanic_tags") or []))
|
||||
syn = ", ".join(esc(id2name.get(s["mtga_id"], s["mtga_id"])) for s in (c.get("synergy") or [])[:3])
|
||||
return f"""<div class="keycard">
|
||||
<div class="keyrank">#{rank}</div>
|
||||
<div class="imgwrap">{imgs}</div>
|
||||
<div class="cbody">
|
||||
<div class="cname">{esc(c["name"])}</div>
|
||||
{f'<div class="cnname">{esc(cnname)}</div>' if cnname else ''}
|
||||
<div class="krow"><span class="tc big">{c["target_copies"]:.2f}</span>
|
||||
<span class="imp">imp {c.get("importance")}</span></div>
|
||||
<div class="stats">GIH {fmt(c.get("gih_wr"))} · inc {pct(c.get("inclusion"))} · Δ <span class="{cd_cls}">{cd_s}</span> ·
|
||||
{' '.join(esc(r) for r in (c.get('roles') or []))}</div>
|
||||
<div class="tags">{tags}</div>
|
||||
{f'<div class="syn">syn: {syn}</div>' if syn else ''}
|
||||
</div></div>"""
|
||||
|
||||
|
||||
def pct(v):
|
||||
return "-" if v is None else f"{v*100:.0f}%"
|
||||
|
||||
|
||||
def fmt(v, nd=3):
|
||||
return "-" if v is None else (f"{v:.{nd}f}" if isinstance(v, float) else str(v))
|
||||
|
||||
|
||||
def write_detail(t, slug, img, id2name, report_dir, rel, cn_names):
|
||||
dp = t["deck_params"]
|
||||
nonland = [c for c in t["cards"] if c.get("roles") != ["land"]]
|
||||
lands = [c for c in t["cards"] if c.get("roles") == ["land"]]
|
||||
g = t["_game"]
|
||||
curve = dp["curve_targets"]
|
||||
cmax = max(curve.values()) or 1
|
||||
curve_html = "".join(
|
||||
f'<div class="bar"><div class="barfill" style="height:{v/cmax*100:.0f}%"></div>'
|
||||
f'<div class="barlab">{k}</div><div class="barval">{v:.1f}</div></div>'
|
||||
for k, v in curve.items())
|
||||
cw = dp["color_weights"]
|
||||
cw_html = "".join(
|
||||
f'<span class="cw" style="background:{COLOR_HEX.get(k, "#ddd")}">{k} {v*100:.0f}%</span>'
|
||||
for k, v in cw.items())
|
||||
mu_rows = "".join(
|
||||
f"<tr><td>{esc(k)}</td><td>{v[0]}</td><td>{v[1]*100:.0f}%</td>"
|
||||
f"<td><div class='mbar'><div style='width:{v[1]*100:.0f}%'></div></div></td></tr>"
|
||||
for k, v in sorted(((k, (cnt, wr)) for k, cnt, wr in g["matchups"]), key=lambda x: -x[1][0]))
|
||||
defmap = {c["name"]: c for c in nonland}
|
||||
defining = [defmap[nm] for nm in t.get("defining_cards", []) if nm in defmap][:6]
|
||||
if not defining:
|
||||
defining = nonland[:6]
|
||||
tiles = "".join(card_tile(c, img, id2name, cn_names) for c in nonland)
|
||||
key_html = "".join(key_tile(c, img, id2name, cn_names, i)
|
||||
for i, c in enumerate(defining, 1))
|
||||
land_tiles = "".join(
|
||||
f'<span class="lt">{esc(c["name"])} {c["target_copies"]:.2f}</span>' for c in lands)
|
||||
|
||||
doc = f"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>{esc(t['archetype_name'])} · FRA</title>
|
||||
<style>{CSS}</style></head><body class="show-en">
|
||||
<div class="topbar"><a href="index.html">← 所有 archetype</a>
|
||||
<label class="toggle"><input type="checkbox" id="lang"> 中文卡图</label></div>
|
||||
<h1>{esc(t['archetype_name'])}</h1>
|
||||
<div class="meta">archetype <b>{esc(t['archetype'])}</b> · slug <code>{esc(slug)}</code> ·
|
||||
n_decks <b>{t['n_decks']}</b> · confidence {t['confidence']} · silhouette {t['silhouette']}</div>
|
||||
<div class="panel">
|
||||
<div class="kv"><span>地</span><b>{dp['land_count']}</b></div>
|
||||
<div class="kv"><span>生物比</span><b>{dp['creature_ratio']}</b></div>
|
||||
<div class="kv"><span>splash_max</span><b>{dp['splash_max']}</b></div>
|
||||
<div class="curve">{curve_html}</div>
|
||||
<div class="cws">{cw_html}</div>
|
||||
</div>
|
||||
<h2>定义牌(区分本流派)</h2>
|
||||
<div class="keygrid">{key_html}</div>
|
||||
<h2>对局数据(本簇 {g['n']} 局 / {g['drafts']} 副牌)</h2>
|
||||
<div class="panel game">
|
||||
<div class="kv"><span>牌表均战绩</span><b>{g['draft_record']*100:.1f}%</b></div>
|
||||
<div class="kv"><span>7-0 率</span><b>{g['seven0']*100:.1f}%</b></div>
|
||||
<div class="kv"><span>单局胜率</span><b>{g['wr']*100:.1f}%</b></div>
|
||||
<div class="kv"><span>先手胜率</span><b>{g['op_wr']*100:.1f}%</b></div>
|
||||
<div class="kv"><span>后手胜率</span><b>{g['df_wr']*100:.1f}%</b></div>
|
||||
<div class="kv"><span>平均回合</span><b>{g['avg_turns']:.1f}</b></div>
|
||||
<div class="kv"><span>平均调度</span><b>{g['mull']:.2f}</b></div>
|
||||
</div>
|
||||
<h3>对位(我方胜率 vs 对手双色)</h3>
|
||||
<table class="mu"><tr><th>对手</th><th>n</th><th>我方胜率</th><th></th></tr>{mu_rows}</table>
|
||||
<h2>曲线</h2><div class="curve big">{curve_html}</div>
|
||||
<h2>咒语({len(nonland)} 张,数字=target_copies)</h2>
|
||||
<div class="grid">{tiles}</div>
|
||||
<h2>非基本地 / 基本地</h2>
|
||||
<div class="lands">{land_tiles}</div>
|
||||
<div class="basics">基本地:{esc(dp.get('basic_lands'))}</div>
|
||||
<script>
|
||||
const c=document.getElementById('lang');
|
||||
c.addEventListener('change',()=>document.body.classList.toggle('show-cn',c.checked));
|
||||
</script>
|
||||
</body></html>"""
|
||||
(report_dir / f"{slug}.html").write_text(doc, encoding="utf-8")
|
||||
|
||||
|
||||
def write_index(templates, report_dir):
|
||||
rows = ""
|
||||
for t in templates:
|
||||
dp = t["deck_params"]
|
||||
g = t["_game"]
|
||||
key = " · ".join(esc(c["name"]) for c in t["cards"] if c.get("roles") != ["land"])[:80]
|
||||
rows += (f'<tr><td><a href="{esc(t["archetype_slug"])}.html">{esc(t["archetype_name"])}</a></td>'
|
||||
f'<td>{esc(t["archetype"])}</td><td>{t["n_decks"]}</td>'
|
||||
f'<td>{dp["land_count"]}</td><td>{dp["creature_ratio"]}</td>'
|
||||
f'<td>{g["wr"]*100:.1f}%</td><td>{g["avg_turns"]:.1f}</td>'
|
||||
f'<td class="kc">{key}…</td></tr>')
|
||||
doc = f"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
|
||||
<title>FRA 模板视图</title><style>{CSS}</style></head><body>
|
||||
<h1>FRA PremierDraft · 子流派模板视图</h1>
|
||||
<p>{len(templates)} 个子流派(按色对聚类)。点名字看牌表 + 对局数据 + 卡图。</p>
|
||||
<table class="idx"><tr><th>archetype</th><th>色</th><th>n</th><th>地</th><th>生物比</th>
|
||||
<th>胜率</th><th>回合</th><th>关键牌</th></tr>{rows}</table>
|
||||
</body></html>"""
|
||||
(report_dir / "index.html").write_text(doc, encoding="utf-8")
|
||||
|
||||
|
||||
CSS = """
|
||||
*{box-sizing:border-box} body{font-family:system-ui,'Segoe UI',sans-serif;margin:0;padding:20px;
|
||||
background:#12141a;color:#e8e8ea}
|
||||
a{color:#7cc4ff;text-decoration:none} h1{margin:.2em 0} h2{margin-top:1.4em;border-bottom:1px solid #2a2e3a;padding-bottom:.2em}
|
||||
.topbar{display:flex;justify-content:space-between;align-items:center;font-size:14px}
|
||||
.meta,.basics{color:#9aa2b1;font-size:13px;margin:.4em 0}
|
||||
.panel{display:flex;gap:18px;flex-wrap:wrap;align-items:flex-end;background:#1b1e27;border:1px solid #2a2e3a;
|
||||
border-radius:10px;padding:12px 16px;margin:10px 0}
|
||||
.kv{display:flex;flex-direction:column;font-size:12px;color:#9aa2b1}.kv b{font-size:18px;color:#fff}
|
||||
.curve{display:flex;gap:6px;align-items:flex-end;height:80px}
|
||||
.curve.big{height:130px}
|
||||
.bar{display:flex;flex-direction:column;align-items:center;justify-content:flex-end;width:44px;height:100%}
|
||||
.barfill{width:100%;background:linear-gradient(#4a90d9,#2f5f96);border-radius:4px 4px 0 0;min-height:2px}
|
||||
.barlab{font-size:11px;color:#9aa2b1}.barval{font-size:10px;color:#c9d1e0}
|
||||
.cws{display:flex;gap:6px;align-items:center}
|
||||
.cw{color:#111;font-weight:600;font-size:12px;padding:3px 8px;border-radius:6px}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-top:10px}
|
||||
.card{background:#1b1e27;border:1px solid #2a2e3a;border-radius:10px;overflow:hidden;display:flex;flex-direction:column}
|
||||
.imgwrap{aspect-ratio:488/680;background:#0c0e13}
|
||||
.ci{width:100%;height:100%;object-fit:cover;display:block}
|
||||
body.show-en .cn{display:none} body.show-cn .en{display:none}
|
||||
.placeholder{display:flex;align-items:center;justify-content:center;color:#555;font-size:12px}
|
||||
.cbody{padding:8px 10px}
|
||||
.cname{font-weight:600;font-size:13px;line-height:1.2;min-height:2.4em}
|
||||
.cnname{font-size:12px;color:#c9a34a;margin-top:-2px}
|
||||
.crow{display:flex;align-items:center;gap:6px;margin:4px 0}
|
||||
.tc{background:#2f5f96;color:#fff;font-weight:700;border-radius:6px;padding:1px 7px;font-size:13px}
|
||||
.rl{font-size:11px;color:#9aa2b1}.imp{font-size:11px;color:#c9a34a;margin-left:auto}
|
||||
.stats{font-size:11px;color:#9aa2b1}
|
||||
.tags{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px}
|
||||
.tg{background:#262b38;color:#a9d0ff;font-size:10px;padding:1px 6px;border-radius:10px}
|
||||
.syn{font-size:10px;color:#7f8aa0;margin-top:3px}
|
||||
.ctx-pos{color:#4ad07a}.ctx-neg{color:#e06a6a}
|
||||
table{border-collapse:collapse;width:100%;font-size:13px}
|
||||
th,td{text-align:left;padding:6px 8px;border-bottom:1px solid #2a2e3a}
|
||||
.mu td:first-child{font-weight:600}
|
||||
.mbar{background:#262b38;border-radius:4px;height:10px;overflow:hidden}
|
||||
.mbar>div{height:100%;background:#4a90d9}
|
||||
.lands{display:flex;flex-wrap:wrap;gap:8px}
|
||||
.keygrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:14px;margin:12px 0}
|
||||
.keycard{background:linear-gradient(#241d0c,#1b1e27);border:1px solid #c9a34a;border-radius:12px;overflow:hidden;position:relative;box-shadow:0 0 0 1px #00000055,0 6px 18px #00000055}
|
||||
.keyrank{position:absolute;top:8px;left:8px;background:#c9a34a;color:#111;font-weight:800;border-radius:8px;padding:2px 9px;z-index:3;font-size:13px}
|
||||
.keycard .imgwrap{aspect-ratio:488/680;background:#0c0e13}
|
||||
.keycard .cname{font-size:14px}
|
||||
.krow{display:flex;align-items:center;gap:8px;margin:6px 0}
|
||||
.tc.big{font-size:16px;padding:2px 10px}
|
||||
.lt{background:#1b1e27;border:1px solid #2a2e3a;border-radius:6px;padding:4px 8px;font-size:12px}
|
||||
.idx .kc{color:#9aa2b1;font-size:12px}
|
||||
.cloud{font-size:12px}
|
||||
"""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--snapshot", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--mtgch", default="data/mtgch")
|
||||
ap.add_argument("--report-dir", default=None)
|
||||
args = ap.parse_args()
|
||||
out = Path(args.out)
|
||||
snapshot = Path(args.snapshot)
|
||||
report_dir = Path(args.report_dir) if args.report_dir else out / "reports/templates"
|
||||
build(snapshot, out, Path(args.mtgch), report_dir)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate whether running a package correlates with a better record.
|
||||
|
||||
All decks are 7-win trophies, so record in [0.78, 1.0]. We compare, per
|
||||
package, the mean record and 7-0 rate across "dose" buckets (how many of the
|
||||
package's cards the deck runs).
|
||||
|
||||
Outputs: value/<SNAPSHOT>/reports/package_impact.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
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"
|
||||
cs = [c for c in order if c in colors.upper()]
|
||||
return "".join(cs[:2]) if len(cs) >= 2 else None
|
||||
|
||||
|
||||
def build(snapshot: Path, out_dir: Path) -> 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))
|
||||
|
||||
def is_land(nm):
|
||||
return any("Land" in t for t in (meta.get(nm, {}).get("types") or []))
|
||||
|
||||
decks = []
|
||||
for d in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
|
||||
names = set()
|
||||
for e in d["maindeck"]:
|
||||
nm = id2name.get(e["mtga_id"])
|
||||
if nm in cards and not is_land(nm):
|
||||
names.add(nm)
|
||||
wins, losses = d["wins"], d["losses"]
|
||||
decks.append({"names": names, "wins": wins, "losses": losses,
|
||||
"record": wins / (wins + losses) if wins + losses else None,
|
||||
"seven0": losses == 0, "arch": primary_pair(d.get("colors"))})
|
||||
|
||||
pkg = json.loads((out_dir / "packages.json").read_text(encoding="utf-8"))["packages"]
|
||||
baseline = statistics.mean(d["record"] for d in decks)
|
||||
base70 = sum(1 for d in decks if d["seven0"]) / len(decks)
|
||||
|
||||
rep = ["# FRA PremierDraft · 卡牌包战绩贡献\n",
|
||||
f"基线(全部 {len(decks)} 副奖杯):平均记录 **{baseline:.3f}**,7-0 率 **{base70*100:.1f}%**。\n",
|
||||
"> 「剂量」= 该副牌运行了包里几张牌。记录越高、7-0 率越高越好。\n"]
|
||||
|
||||
for p in pkg:
|
||||
pc = set(p["cards"])
|
||||
buckets = defaultdict(list)
|
||||
for d in decks:
|
||||
k = len(d["names"] & pc)
|
||||
buckets[k].append(d)
|
||||
# only show buckets with >=8 decks, merge tail into "n+"
|
||||
rows = sorted(buckets.items())
|
||||
rep.append(f"\n## 包:{p['core']} (size={p['size']}, avg lift {p['avg_lift']})\n")
|
||||
rep.append("| 运行张数 | n | 平均记录 | 7-0 率 | 平均 losses |")
|
||||
rep.append("|---|---|---|---|---|")
|
||||
for k, ds in rows:
|
||||
if len(ds) < 5:
|
||||
continue
|
||||
rec = statistics.mean(d["record"] for d in ds if d["record"] is not None)
|
||||
s70 = sum(1 for d in ds if d["seven0"]) / len(ds)
|
||||
ml = statistics.mean(d["losses"] for d in ds)
|
||||
rep.append(f"| {k} | {len(ds)} | {rec:.3f} | {s70*100:.1f}% | {ml:.2f} |")
|
||||
rep.append("")
|
||||
|
||||
# control: blue staples (high inclusion, low lift) as a contrast
|
||||
blue_staples = ["Surveillance Phantasm", "Mindseeker Oculus", "Icy Reception", "Unsummon"]
|
||||
buckets = defaultdict(list)
|
||||
for d in decks:
|
||||
buckets[len(d["names"] & set(blue_staples))].append(d)
|
||||
rep.append("\n## 对照:蓝色通用件(高采纳、低 lift)\n")
|
||||
rep.append("| 运行张数 | n | 平均记录 | 7-0 率 |")
|
||||
rep.append("|---|---|---|---|")
|
||||
for k, ds in sorted(buckets.items()):
|
||||
if len(ds) < 5:
|
||||
continue
|
||||
rep.append(f"| {k} | {len(ds)} | "
|
||||
f"{statistics.mean(d['record'] for d in ds if d['record'] is not None):.3f} | "
|
||||
f"{sum(1 for d in ds if d['seven0'])/len(ds)*100:.1f}% |")
|
||||
|
||||
(out_dir / "reports").mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "reports/package_impact.md").write_text("\n".join(rep), encoding="utf-8")
|
||||
print("wrote reports/package_impact.md")
|
||||
print(f"baseline record={baseline:.3f} 7-0={base70*100:.1f}%")
|
||||
|
||||
|
||||
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())
|
||||
Reference in New Issue
Block a user