Track the TRK preview package and the newest value artifacts for FRA20261007, move the 17lands API notes under data, and ignore downloaded 17lands, card image and live directories.
230 lines
9.1 KiB
Python
230 lines
9.1 KiB
Python
#!/usr/bin/env python3
|
|
"""M2: build per-archetype template decks (v1) from the trophy decklists.
|
|
|
|
For each two-color archetype, aggregate the winning decklists into the template
|
|
parameters defined in README §4:
|
|
deck_params: land_count, curve targets, creature_ratio, color pips, basics
|
|
cards[]: target_copies (avg copies), inclusion, copy distribution,
|
|
per-archetype importance / pick order
|
|
|
|
Outputs (under value/<SNAPSHOT>/):
|
|
templates/<SET>.<FORMAT>.<COLORS>.json
|
|
templates/_index.json
|
|
reports/templates_overview.md
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
import statistics
|
|
from collections import Counter, defaultdict
|
|
from pathlib import Path
|
|
|
|
CURVE_BUCKETS = ["0", "1", "2", "3", "4", "5", "6", "7+"]
|
|
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
|
|
PIP_RE = re.compile(r"\{([^}]+)\}")
|
|
|
|
|
|
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 curve_bucket(cmc):
|
|
if cmc is None:
|
|
return None
|
|
c = int(cmc)
|
|
return "7+" if c >= 7 else str(c)
|
|
|
|
|
|
def pips(mana_cost: str, color_identity) -> Counter:
|
|
out = Counter()
|
|
for sym in PIP_RE.findall(mana_cost or ""):
|
|
for ch in sym:
|
|
if ch in "WUBRG":
|
|
out[ch] += 1
|
|
return out
|
|
|
|
|
|
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", "mana_cost", "types", "color_identity"):
|
|
if md.get(k) in (None, "", []):
|
|
md[k] = c.get(k)
|
|
md.setdefault("rarity", c.get("rarity"))
|
|
|
|
def is_land(nm):
|
|
return any("Land" in t for t in (meta.get(nm, {}).get("types") or []))
|
|
|
|
def is_basic(nm):
|
|
return nm in BASICS
|
|
|
|
groups = defaultdict(list)
|
|
for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
|
|
arch = primary_pair(deck.get("colors"))
|
|
if arch and len(arch) == 2:
|
|
groups[arch].append(deck)
|
|
|
|
index = {}
|
|
report = ["# FRA PremierDraft · Archetype 模板 v1\n"]
|
|
for arch, decks in sorted(groups.items(), key=lambda kv: -len(kv[1])):
|
|
if len(decks) < min_decks:
|
|
continue
|
|
n = len(decks)
|
|
spell_counts = Counter()
|
|
decks_with = Counter()
|
|
copy_dist = defaultdict(Counter)
|
|
land_totals, basic_totals, pip_totals = [], Counter(), Counter()
|
|
curves = Counter()
|
|
creatures = 0
|
|
spells = 0
|
|
|
|
for deck in decks:
|
|
lands = 0
|
|
deck_cards = Counter()
|
|
for entry in deck["maindeck"]:
|
|
nm = id2name.get(entry["mtga_id"])
|
|
cnt = entry["count"]
|
|
if nm is None:
|
|
continue
|
|
if is_land(nm):
|
|
lands += cnt
|
|
if is_basic(nm):
|
|
basic_totals[nm] += cnt
|
|
continue
|
|
deck_cards[nm] += cnt
|
|
land_totals.append(lands)
|
|
for nm, cnt in deck_cards.items():
|
|
spell_counts[nm] += cnt
|
|
decks_with[nm] += 1
|
|
copy_dist[nm][min(cnt, 3)] += 1
|
|
b = curve_bucket(meta.get(nm, {}).get("cmc"))
|
|
if b:
|
|
curves[b] += cnt
|
|
if any("Creature" in t for t in (meta.get(nm, {}).get("types") or [])):
|
|
creatures += cnt
|
|
else:
|
|
spells += cnt
|
|
for ch, val in pips(meta.get(nm, {}).get("mana_cost", ""), None).items():
|
|
pip_totals[ch] += val * cnt
|
|
|
|
# importance within archetype: shrunk WR + inclusion
|
|
inc = {nm: decks_with[nm] / n for nm in decks_with}
|
|
wr = {nm: (cards.get(nm, {}).get("gih_shrunk")) for nm in decks_with}
|
|
wr_vals = [v for v in wr.values() if v is not None]
|
|
mu = statistics.mean(wr_vals) if wr_vals else 0.0
|
|
sd = statistics.pstdev(wr_vals) if len(wr_vals) > 1 else 1.0
|
|
inc_vals = list(inc.values())
|
|
imu = statistics.mean(inc_vals) if inc_vals else 0.0
|
|
isd = statistics.pstdev(inc_vals) if len(inc_vals) > 1 else 1.0
|
|
rows = []
|
|
for nm, total in spell_counts.items():
|
|
wrz = ((wr[nm] - mu) / sd) if (wr.get(nm) is not None and sd) else 0.0
|
|
inz = ((inc[nm] - imu) / isd) if isd else 0.0
|
|
rows.append({
|
|
"name": nm,
|
|
"mtga_id": cards.get(nm, meta.get(nm, {})).get("mtga_id"),
|
|
"rarity": cards.get(nm, meta.get(nm, {})).get("rarity"),
|
|
"cmc": meta.get(nm, {}).get("cmc"),
|
|
"mana_cost": meta.get(nm, {}).get("mana_cost", ""),
|
|
"types": meta.get(nm, {}).get("types"),
|
|
"target_copies": round(total / n, 3), # avg copies across decks
|
|
"avg_copies_played": round(total / decks_with[nm], 3) if decks_with[nm] else 0,
|
|
"inclusion": round(inc[nm], 4),
|
|
"c1": copy_dist[nm].get(1, 0),
|
|
"c2": copy_dist[nm].get(2, 0),
|
|
"c3plus": copy_dist[nm].get(3, 0),
|
|
"gih_wr": cards.get(nm, {}).get("ever_drawn_win_rate"),
|
|
"gih_shrunk": wr.get(nm),
|
|
"importance": round(0.6 * wrz + 0.4 * inz, 4),
|
|
})
|
|
rows.sort(key=lambda r: -r["importance"])
|
|
for i, r in enumerate(rows, 1):
|
|
r["pick_priority"] = i
|
|
|
|
primary = max(rows, key=lambda r: (r["target_copies"], r["inclusion"]))["name"] if rows else None
|
|
total_curve = sum(curves.values()) or 1
|
|
template = {
|
|
"expansion": "FRA",
|
|
"format": "PremierDraft",
|
|
"archetype": arch,
|
|
"archetype_name": f"{arch}-{primary}" if primary else arch,
|
|
"n_decks": n,
|
|
"deck_params": {
|
|
"land_count": round(statistics.mean(land_totals), 2),
|
|
"basic_lands": {k: round(v / n, 2) for k, v in sorted(basic_totals.items())},
|
|
"color_pips": {k: round(v / n, 2) for k, v in sorted(pip_totals.items())},
|
|
"curve": {b: round(curves.get(b, 0) / n, 2) for b in CURVE_BUCKETS},
|
|
"creature_ratio": round(creatures / (creatures + spells), 3) if (creatures + spells) else None,
|
|
"spells_per_deck": round(sum(spell_counts.values()) / n, 2),
|
|
},
|
|
"cards": rows,
|
|
}
|
|
(out_dir / "templates").mkdir(parents=True, exist_ok=True)
|
|
path = out_dir / "templates" / f"FRA.PremierDraft.{arch}.json"
|
|
path.write_text(json.dumps(template, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
index[arch] = {"archetype_name": template["archetype_name"], "n_decks": n,
|
|
"land_count": template["deck_params"]["land_count"],
|
|
"creature_ratio": template["deck_params"]["creature_ratio"],
|
|
"key_cards": [r["name"] for r in rows[:5]]}
|
|
|
|
dp = template["deck_params"]
|
|
report.append(f"\n## {template['archetype_name']} (n={n})\n")
|
|
report.append(f"- 地:**{dp['land_count']}**;生物比:**{dp['creature_ratio']}**;基础地:{dp['basic_lands']}")
|
|
report.append(f"- 曲线:{dp['curve']}")
|
|
report.append(f"- 关键牌:{' · '.join(r['name'] for r in rows[:8])}")
|
|
|
|
ex = out_dir / "decks"
|
|
ex.mkdir(parents=True, exist_ok=True)
|
|
ex.joinpath(f"{arch}.txt").write_text(
|
|
"\n".join(f"{r['target_copies']:.1f}x {r['name']}" for r in rows[:23]), encoding="utf-8")
|
|
|
|
(out_dir / "templates" / "_index.json").write_text(
|
|
json.dumps(index, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
(out_dir / "reports").mkdir(parents=True, exist_ok=True)
|
|
(out_dir / "reports/templates_overview.md").write_text("\n".join(report), encoding="utf-8")
|
|
print(f"wrote {len(index)} archetype templates -> {out_dir}/templates/")
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser(description="Build archetype templates (M2).")
|
|
ap.add_argument("--snapshot", required=True)
|
|
ap.add_argument("--out", required=True)
|
|
ap.add_argument("--min-decks", type=int, default=25)
|
|
args = ap.parse_args()
|
|
build(Path(args.snapshot), Path(args.out), args.min_decks)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|