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())
+155 -3
View File
@@ -244,6 +244,8 @@ def fetch_json_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
if not proxies.has_proxies:
cooldown.hit()
continue
if exc.code == 404: # permanent: resource does not exist
raise
soft += 1
if soft >= retries:
raise
@@ -280,6 +282,8 @@ def fetch_bytes_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
if not proxies.has_proxies:
cooldown.hit()
continue
if exc.code == 404: # permanent: resource does not exist
raise
soft += 1
if soft >= retries:
raise
@@ -428,7 +432,7 @@ def cmd_trophies(args) -> int:
try:
maindeck, sideboard = fetch_deck(entry["aggregate_id"], entry["deck_index"],
limiter, cooldown, proxies)
valid = len(maindeck) == 40
valid = len(maindeck) >= 40 # limited decks are 40+ cards (41, 42, ... are legal)
if not valid:
with lock:
stats["invalid"] += 1
@@ -477,7 +481,7 @@ def cmd_trophies(args) -> int:
print("\n===== trophy fetch summary =====")
print(f"index entries : {len(entries)}")
print(f"new decks fetched : {stats['fetched']}")
print(f" valid (40 cards) : {stats['valid']}")
print(f" valid (>=40 cards): {stats['valid']}")
print(f" invalid : {stats['invalid']}")
print(f" failed : {stats['failed']}")
print(f"total valid stored : {total_valid} -> {decks_path}")
@@ -485,6 +489,76 @@ def cmd_trophies(args) -> int:
return 0
def cmd_draftdata(args) -> int:
"""Fetch full per-pick draft replays (`/data/draft?draft_id=`) incl. pack contents."""
stamp = datetime.now().strftime("%Y%m%d")
out_dir = Path(args.out) if args.out else (DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "draftdata")
out_dir.mkdir(parents=True, exist_ok=True)
ids: list[str] = []
seen: set[str] = set()
with Path(args.index).open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
did = json.loads(line)["aggregate_id"]
if did not in seen:
seen.add(did)
ids.append(did)
done = {p.stem for p in out_dir.glob("*.json")}
pending = [d for d in ids if d not in done]
if args.max_drafts:
pending = pending[: args.max_drafts]
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
print(f"[draftdata] {len(ids)} ids, {len(done)} done, {len(pending)} pending", file=sys.stderr)
lock = threading.Lock()
stats = {"ok": 0, "failed": 0, "missing": 0}
missing: list[str] = []
t0 = time.time()
def worker(did: str) -> None:
try:
data = fetch_json_rl(f"{BASE}/data/draft?draft_id={did}", limiter, cooldown, proxies)
tmp = out_dir / f"{did}.json.part"
tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
tmp.replace(out_dir / f"{did}.json")
with lock:
stats["ok"] += 1
except HTTPError as exc:
if exc.code == 404: # this draft has no pick replay
with lock:
missing.append(did)
stats["missing"] += 1
return
with lock:
stats["failed"] += 1
print(f" [failed] {did}: {exc}", file=sys.stderr)
except Exception as exc: # noqa: BLE001
with lock:
stats["failed"] += 1
print(f" [failed] {did}: {exc}", file=sys.stderr)
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, d) for d in pending]
for i, fut in enumerate(as_completed(futures), 1):
fut.result()
if not args.quiet and (i % 10 == 0 or i == len(futures)):
el = time.time() - t0
print(f" {i}/{len(futures)} ok={stats['ok']} missing={stats['missing']} "
f"failed={stats['failed']} {i / el if el else 0:.1f}/s", file=sys.stderr)
if missing:
(out_dir / "_missing.txt").write_text("\n".join(sorted(missing)) + "\n", encoding="utf-8")
print(f"\n===== draftdata summary =====\nnew: {stats['ok']} missing(404): {stats['missing']} "
f"failed: {stats['failed']} stored: {len(done) + stats['ok']}\n-> {out_dir}")
return 0
def cmd_replays(args) -> int:
"""Download the turn-by-turn GRE replay (gzip) for every game.
@@ -531,7 +605,14 @@ def cmd_replays(args) -> int:
for g in games:
fh.write(json.dumps(g, ensure_ascii=False) + "\n")
done = {p.name[: -len(".json.gz")] for p in out_dir.rglob("*.json.gz")}
if args.selection_file:
want = [ln.strip() for ln in Path(args.selection_file).read_text(encoding="utf-8").splitlines()
if ln.strip()]
order = {hp: i for i, hp in enumerate(want)}
games = [g for g in games if g["history_path"] in order]
games.sort(key=lambda g: order[g["history_path"]])
done = {p.relative_to(out_dir).as_posix()[: -len(".json.gz")] for p in out_dir.rglob("*.json.gz")}
pending = [g for g in games if g["history_path"] not in done]
if args.max_replays:
pending = pending[: args.max_replays]
@@ -580,6 +661,45 @@ def cmd_replays(args) -> int:
return 0
def cmd_stats(args) -> int:
"""Fetch the aggregate/statistics endpoints (scenarios 1, 2, 6).
* /api/card_data -> card_data.json (per-card)
* /api/card_data?colors=<pair> -> card_data.<pair>.json (archetype context)
* /color_ratings/data -> color_ratings.json (color win rates)
* /api/draft_metagame/ -> draft_metagame.json (pick order over time)
"""
stamp = datetime.now().strftime("%Y%m%d")
out_dir = Path(args.out) if args.out else (DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "stats")
out_dir.mkdir(parents=True, exist_ok=True)
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
exp, fmt = args.set.upper(), args.format
base = f"{BASE}/api/card_data?expansion={exp}&event_type={fmt}&time_period={args.time_period}"
jobs = [("card_data.json", base)]
for color in COLOR_PAIRS:
jobs.append((f"card_data.{color}.json", f"{base}&colors={color}"))
jobs.append(("color_ratings.json",
f"{BASE}/color_ratings/data?expansion={exp}&event_type={fmt}"
f"&time_period={args.time_period}&combine_splash=true"))
jobs.append(("draft_metagame.json",
f"{BASE}/api/draft_metagame/?expansion={exp}&format={fmt}"
f"&time_period={args.time_period}"))
for name, url in jobs:
try:
data = fetch_json_rl(url, limiter, cooldown, proxies)
(out_dir / name).write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
n = len(data.get("data", [])) if isinstance(data, dict) else len(data)
print(f" [ok] {name:26} ({n} items)", file=sys.stderr)
except Exception as exc: # noqa: BLE001
print(f" [failed] {name}: {exc}", file=sys.stderr)
print(f"\nstored -> {out_dir}")
return 0
def read_jsonl_ids(path: Path, key: str) -> set:
ids: set = set()
if not path.exists():
@@ -754,6 +874,8 @@ def build_parser() -> argparse.ArgumentParser:
pr.add_argument("--set", required=True)
pr.add_argument("--format", default="PremierDraft")
pr.add_argument("--events", required=True, help="event_details.jsonl from the drafts command")
pr.add_argument("--selection-file", default=None,
help="only fetch the history_paths listed in this file (one per line)")
pr.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/replays)")
pr.add_argument("-w", "--workers", type=int, default=8)
pr.add_argument("-r", "--rate", type=float, default=10.0)
@@ -765,6 +887,36 @@ def build_parser() -> argparse.ArgumentParser:
pr.add_argument("--max-replays", type=int)
pr.add_argument("-q", "--quiet", action="store_true")
pr.set_defaults(func=cmd_replays)
ps = sub.add_parser("stats", help="fetch aggregate stats: card_data, per-color, color_ratings, draft_metagame")
ps.add_argument("--set", required=True)
ps.add_argument("--format", default="PremierDraft")
ps.add_argument("--time-period", default="ALL_TIME")
ps.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/stats)")
ps.add_argument("-r", "--rate", type=float, default=5.0)
ps.add_argument("--cooldown", type=float, default=2.0)
ps.add_argument("--proxy", action="append", default=[])
ps.add_argument("--proxy-file")
ps.add_argument("--cookie")
ps.add_argument("--cookie-file")
ps.set_defaults(func=cmd_stats)
pdd = sub.add_parser("draftdata", help="fetch full per-pick draft replays incl. pack contents")
pdd.add_argument("--set", required=True)
pdd.add_argument("--format", default="PremierDraft")
pdd.add_argument("--index", required=True, help="trophies_index.jsonl (draft ids)")
pdd.add_argument("--out", default=None,
help="output dir (default: data/17lands/<SET><YYYYMMDD>/draftdata)")
pdd.add_argument("-w", "--workers", type=int, default=48)
pdd.add_argument("-r", "--rate", type=float, default=0.0, help="requests/sec (0 = no limit)")
pdd.add_argument("--cooldown", type=float, default=0.0)
pdd.add_argument("--proxy", action="append", default=[])
pdd.add_argument("--proxy-file")
pdd.add_argument("--cookie")
pdd.add_argument("--cookie-file")
pdd.add_argument("--max-drafts", type=int)
pdd.add_argument("-q", "--quiet", action="store_true")
pdd.set_defaults(func=cmd_draftdata)
return parser