This commit is contained in:
2026-10-08 00:17:17 +08:00
parent 31812ec75d
commit 7364e0388b
9 changed files with 33175 additions and 23 deletions
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""M1: build the per-card value table for a set from 17Lands data.
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
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.
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import statistics
from collections import Counter, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
PRIOR_GAMES = 100.0 # shrinkage strength
Z = 1.959964 # 95%
# --------------------------------------------------------------------------- #
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: str | None) -> str | None:
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 wilson_low(wins: float, n: float, z: float = Z) -> float | None:
if not n:
return None
p = wins / n
d = 1 + z * z / n
centre = p + z * z / (2 * n)
margin = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return (centre - margin) / d
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
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}
# card metadata from draft_picks (name, cmc, mana_cost, types)
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 []))
decks = list(load_jsonl(snapshot / "trophies/trophies_decks.jsonl"))
n_decks = len(decks)
# inclusion / copy distribution, overall and per archetype
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
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
# field mean for shrinkage
tot_g = sum(c.get("ever_drawn_game_count") or 0 for c in card.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())
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)
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)
rows.append({
"mtga_id": cid,
"name": c.get("name") or str(cid),
"color": c.get("color") or "",
"rarity": c.get("rarity") or "",
"cmc": c.get("cmc"),
"mana_cost": c.get("mana_cost") or "",
"types": "|".join(types),
"is_land": is_land,
"is_basic": is_basic,
"gih_games": g,
"gih_wr": wr,
"gih_wilson_low": wilson_low(wins, g) if g else None,
"gih_shrunk": shrunk,
"iwd": c.get("drawn_improvement_win_rate"),
"play_rate": c.get("play_rate"),
"alsa": c.get("avg_seen"),
"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),
})
# 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})
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)
# 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]))
# ---- 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.writeheader()
for r in sorted(rows, key=lambda r: (r["importance"] is None, -(r["importance"] or 0))):
w.writerow(r)
(out_dir / "archetype_membership.json").write_text(
json.dumps({k: sorted(v, key=lambda x: -x[1]) for k, v in arch_members.items()},
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"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}
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")
def table(title, items, key):
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)} |")
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")
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"]]
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("")
(reports / "cards_overview.md").write_text("\n".join(L), encoding="utf-8")
def fmt(v, nd=3):
return "-" if v is None else (f"{v:.{nd}f}" if isinstance(v, float) else str(v))
def pct(v):
return "-" if v is None else f"{v*100:.0f}%"
def main() -> int:
ap = argparse.ArgumentParser(description="Build the per-card value table (M1).")
ap.add_argument("--snapshot", required=True, help="e.g. data/17lands/FRA20261007")
ap.add_argument("--out", required=True, help="e.g. value/FRA20261007")
args = ap.parse_args()
build(Path(args.snapshot), Path(args.out))
return 0
if __name__ == "__main__":
raise SystemExit(main())