This commit is contained in:
2026-10-08 01:17:58 +08:00
parent 7364e0388b
commit 6b65861e1f
128 changed files with 208315 additions and 21339 deletions
+91 -100
View File
@@ -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")