245 lines
9.8 KiB
Python
245 lines
9.8 KiB
Python
#!/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 trophy decklists -> inclusion / target copies
|
||
|
||
Outputs (under value/<SNAPSHOT>/):
|
||
cards.csv / cards.json
|
||
archetype_membership.json
|
||
reports/cards_overview.md
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import json
|
||
import math
|
||
import statistics
|
||
from collections import Counter, defaultdict
|
||
from pathlib import Path
|
||
|
||
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:
|
||
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 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
|
||
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]
|
||
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"]
|
||
cards = {c["name"]: dict(c) for c in data} # 290, name-keyed
|
||
|
||
# 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)
|
||
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)
|
||
|
||
# aggregate decklists by NAME, dropping basic lands
|
||
decks_with = Counter()
|
||
total_copies = Counter()
|
||
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 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
|
||
|
||
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 cards.values())
|
||
p0 = (tot_w / tot_g) if tot_g else 0.5
|
||
|
||
rows = []
|
||
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(nm, 0)
|
||
rows.append({
|
||
"name": nm,
|
||
"mtga_id": c["mtga_id"],
|
||
"color": c.get("color") or "",
|
||
"rarity": c.get("rarity") 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(types),
|
||
"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(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),
|
||
})
|
||
|
||
spells = [r for r in rows if not r["is_land"]]
|
||
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:
|
||
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))
|
||
|
||
arch_members = defaultdict(list)
|
||
for (arch, nm), n in arch_decks_with.items():
|
||
if arch and len(arch) == 2:
|
||
arch_members[arch].append((nm, n / arch_decks[arch]))
|
||
|
||
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")
|
||
with (out_dir / "cards.csv").open("w", encoding="utf-8", newline="") as fh:
|
||
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)
|
||
(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 (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_name = {r["name"]: r for r in rows}
|
||
reports = out_dir / "reports"
|
||
reports.mkdir(parents=True, exist_ok=True)
|
||
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):
|
||
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 '-'} | {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("")
|
||
|
||
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):
|
||
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])
|
||
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")
|
||
|
||
|
||
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())
|