#!/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//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" up = [c for c in colors if c in order] # uppercase = main colors low = [c for c in colors.upper() if c in order] # all colors if len(up) >= 2: pair = up[:2] elif len(up) == 1: pair = [up[0]] + [c for c in low if c != up[0]][:1] else: pair = low[:2] if not pair: return None return "".join(sorted(pair, key=order.index)) 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())