#!/usr/bin/env python3 """Per-color-pair archetype templates (README ยง4), using the official FRA limited archetypes as the unit instead of noisy k-means sub-clusters (silhouette was only ~0.02-0.04, i.e. no real separation). Official FRA limited archetypes (Hexhaven colleges / Lorwyn Five): WU Fatehold Surveil Aggro UB Theorix Graveyard Math BR Stingerquill Face Burn RG Konstrari Mana Ramp WG Vigorbloom Life Gain WB Liliana's Attrition UR Chandra's Prowess BG Garruk's Bestiary WR Ajani's Army UG Jace's Mastery Stats are computed over a committed "core" subset (decks running >= half of the archetype's signature cards) so frequency-based targets are meaningful. """ from __future__ import annotations import argparse import json import math import re from collections import Counter, defaultdict from datetime import datetime, timezone from pathlib import Path CURVE = [("1", lambda c: c == 1), ("2", lambda c: c == 2), ("3", lambda c: c == 3), ("4", lambda c: c == 4), ("5+", lambda c: c >= 5)] BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"} ALL_COLORS = "WUBRG" Z = 1.959964 P0 = 0.5626 # global mean GIH WR (recomputed below if possible) OFFICIAL = { "WU": ("Fatehold", "Surveil Aggro"), "UB": ("Theorix", "Graveyard Math"), "BR": ("Stingerquill", "Face Burn"), "RG": ("Konstrari", "Mana Ramp"), "WG": ("Vigorbloom", "Life Gain"), "WB": ("Liliana", "Attrition"), "UR": ("Chandra", "Prowess"), "BG": ("Garruk", "Bestiary"), "WR": ("Ajani", "Army"), "UG": ("Jace", "Mastery"), } CANON = { "Token Swarm": ("create", "token"), "Sacrifice Value": ("sacrifice",), "Spells Matter": ("instant or sorcery", "whenever you cast"), "Prowess": ("prowess",), "Reanimator": ("return target creature card from your graveyard", "return it to the battlefield", "from your graveyard to the battlefield"), "Graveyard Value": ("graveyard", "flashback"), "Counters Growth": ("+1/+1 counter", "counter on", "counters on"), "Equipment Aggro": ("equipment",), "Auras Matter": ("aura",), "Mill Drain": ("mill",), "Landfall Ramp": ("landfall",), "Flash Ambush": ("flash",), "Lifegain Payoff": ("gain life", "lifelink", "you gain"), "Treasure Ramp": ("treasure",), "Artifacts Matter": ("artifact",), "Enchantments Matter": ("enchantment",), "Big Mana Payoff": ("add {", "mana of any"), "Cascade Value": ("cascade",), "Cost Reduction": ("costs less", "cost {", "costs {"), "Power Matters": ("power is", "greatest power", "equal to its power", "power and toughness"), "Evasion Tempo": ("flying", "menace", "can't be blocked", "unblockable"), "Removal Heavy": ("destroy target", "exile target"), } MTGCH: dict = {} 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 up = [c for c in colors if c in ALL_COLORS] low = [c for c in colors.upper() if c in 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] return "".join(sorted(pair, key=ALL_COLORS.index)) if pair else None def slugify(s): return re.sub(r"[^A-Za-z0-9]+", "_", s or "").strip("_") def wilson(wins, n, z=Z): if not n: return None p = wins / n d = 1 + z * z / n c = p + z * z / (2 * n) m = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) return [round((c - m) / d, 3), round((c + m) / d, 3)] def pips(mana_cost): out = Counter() for sym in re.findall(r"\{([^}]+)\}", mana_cost or ""): for ch in sym: if ch in ALL_COLORS: out[ch] += 1 return out def required_colors(mana_cost): req = set() for sym in re.findall(r"\{([^}]+)\}", mana_cost or ""): if "/" in sym: continue for ch in sym: if ch in ALL_COLORS: req.add(ch) return req def load_mtgch(cards_dir: Path, cache: Path) -> dict: if cache.exists(): return json.loads(cache.read_text(encoding="utf-8")) out = {} for p in cards_dir.rglob("*.txt"): nm, orc, kws = None, [], [] try: for line in p.open(encoding="utf-8", errors="ignore"): if line.startswith("Name:"): nm = line[5:].strip() elif line.startswith("Oracle:"): orc.append(line[7:].strip()) elif line.startswith("K:"): kws.append(line[2:].split(":")[0].strip()) except OSError: continue if nm: out[nm] = {"oracle": " ".join(orc).lower(), "keywords": kws} cache.parent.mkdir(parents=True, exist_ok=True) cache.write_text(json.dumps(out, ensure_ascii=False), encoding="utf-8") return out def mech_tags(name): info = MTGCH.get(name) if not info: return [] text = info["oracle"] + " " + " ".join(info["keywords"]).lower() return [t for t, keys in CANON.items() if any(k in text for k in keys)] def role_list(base, tags): types = base.get("types") or [] if any("Land" in t for t in types): return ["land"] r = [] if any("Creature" in t for t in types): r.append("creature") if base.get("rarity") in ("mythic", "rare") and (base.get("ever_drawn_win_rate") or 0) >= 0.58: r.append("bomb") if "Removal Heavy" in tags: r.append("removal") if any("Instant" in t or "Sorcery" in t for t in types) and "Removal Heavy" in tags: r.append("interaction") if base.get("cmc") is not None and base["cmc"] >= 5: r.append("topend") if tags: r.append("payoff") return r or ["filler"] def build(snapshot: Path, out_dir: Path, mtgch_dir: Path, core_frac=0.5) -> None: global MTGCH, P0 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"): if md.get(k) in (None, "", []): md[k] = c.get(k) _tg = sum(c.get("ever_drawn_game_count") or 0 for c in cards.values()) _tw = sum((c.get("ever_drawn_win_rate") or 0) * (c.get("ever_drawn_game_count") or 0) for c in cards.values()) if _tg: P0 = _tw / _tg MTGCH = load_mtgch(mtgch_dir / "cards", out_dir.parent / "_shared/mtgch_index.json") pair_stats = {} for p in OFFICIAL: f = snapshot / f"stats/card_data.{p}.json" if f.exists(): pair_stats[p] = {c["name"]: (c.get("ever_drawn_game_count") or 0, c.get("ever_drawn_win_rate")) for c in json.loads(f.read_text(encoding="utf-8"))["data"]} relations = {} rf = out_dir / "card_relations.json" if rf.exists(): relations = json.loads(rf.read_text(encoding="utf-8")) trophy = defaultdict(lambda: [0, 0]) ev = snapshot / "drafts/event_details.jsonl" draft_card_games = {} for rec in load_jsonl(ev): agg = defaultdict(lambda: [0, 0]) for m in rec.get("details", {}).get("match_results") or []: for g in m.get("game_results") or []: seen = set() for key in ("opening_hand", "drawn_cards", "tutored_cards"): for cid in g.get(key) or []: nm = id2name.get(cid) if nm: seen.add(nm) won = 1 if g.get("won") else 0 for nm in seen: agg[nm][0] += 1 agg[nm][1] += won draft_card_games[rec["draft_id"]] = agg for nm, (gg, ww) in agg.items(): trophy[nm][0] += gg trophy[nm][1] += ww trophy_gih = {nm: (v[1] / v[0] if v[0] >= 20 else None) for nm, v in trophy.items()} def is_land(nm): return any("Land" in t for t in (meta.get(nm, {}).get("types") or [])) by_pair = defaultdict(list) for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"): p = primary_pair(deck.get("colors")) if p: by_pair[p].append(deck) tdir = out_dir / "templates" tdir.mkdir(parents=True, exist_ok=True) index, members_map = {}, {} for arch, decks in sorted(by_pair.items(), key=lambda kv: -len(kv[1])): if arch not in OFFICIAL: # skip mono / malformed color strings continue n = len(decks) cnts, land_tot, basic_list, nbasic, extras_list = [], [], [], [], [] for deck in decks: cnt, lands, bl, nbl = Counter(), 0, Counter(), Counter() for e in deck["maindeck"]: nm = id2name.get(e["mtga_id"]) if nm is None: continue if is_land(nm): lands += e["count"] if nm in BASICS: bl[nm] += e["count"] else: nbl[nm] += e["count"] continue cnt[nm] += e["count"] cnts.append(cnt) land_tot.append(lands) basic_list.append(bl) nbasic.append(nbl) extras_list.append([ch for ch in deck.get("colors", "") if ch.islower()]) # pass 1: signature cards = most-included spells incl0 = Counter() for i in range(n): for nm in cnts[i]: incl0[nm] += 1 top = [nm for nm, _ in incl0.most_common(10)] top_set = set(top) thr_n = max(2, int(len(top_set) * core_frac)) sel = [i for i in range(n) if len(set(cnts[i]) & top_set) >= thr_n] if len(sel) < max(12, int(0.3 * n)): sel = list(range(n)) m = len(sel) mean, cluster_total = Counter(), Counter() for i in sel: for nm, v in cnts[i].items(): mean[nm] += v / m cluster_total.update(cnts[i]) land_mean = Counter() for i in sel: for nm, v in nbasic[i].items(): land_mean[nm] += v / m clust = defaultdict(lambda: [0, 0]) for i in sel: for nm, (gg, ww) in (draft_card_games.get(decks[i].get("aggregate_id")) or {}).items(): clust[nm][0] += gg clust[nm][1] += ww gi = pair_stats.get(arch, {}) cards_out = [] for nm, mc in sorted(mean.items(), key=lambda kv: -kv[1]): base = cards.get(nm, {}) g = base.get("ever_drawn_game_count") or 0 gw = base.get("ever_drawn_win_rate") wins = (gw * g) if (gw is not None and g) else 0 tags = mech_tags(nm) p_shrunk = ((wins + 100.0 * P0) / (g + 100.0)) if (g + 100.0) else P0 pg, pw = gi.get(nm, (0, None)) pair_shrunk = ((pw * pg + 100.0 * p_shrunk) / (pg + 100.0)) if (pw is not None and pg) else p_shrunk defwd = sum(1 for i in sel if nm in cnts[i]) vals = [cnts[i][nm] for i in sel if nm in cnts[i]] cincl = defwd / m cg = clust.get(nm) cluster_gih = (cg[1] / cg[0]) if (cg and cg[0] >= 20) else None tbase = trophy_gih.get(nm) rel = relations.get(nm, {}) cards_out.append({ "mtga_id": base.get("mtga_id"), "name": nm, "rarity": base.get("rarity"), "cmc": meta.get(nm, {}).get("cmc"), "color_pips": dict(pips(meta.get(nm, {}).get("mana_cost", ""))), "roles": role_list(base, tags), "mechanic_tags": tags, "target_copies": round(mc, 2), "copies_when_played": round(cluster_total[nm] / defwd, 2) if defwd else 0, "expected_copies": round(mc, 3), "inclusion": round(cincl, 4), "max_copies": max(vals) if vals else 0, "importance": round(100.0 * mc * (p_shrunk / P0), 2) if P0 else 0, "affinity": round((pair_shrunk - P0) * 100, 2), "pair_gih_wr": (round(pw, 4) if pw is not None else None), "pair_games": pg, "value": round(mc * (p_shrunk - P0) * 100, 2), "gih_wr": gw, "gih_wr_ci": wilson(wins, g), "alsa": base.get("avg_seen"), "iwd": base.get("drawn_improvement_win_rate"), "ata": base.get("avg_pick"), "play_rate": base.get("play_rate"), "context_delta": (round(cluster_gih - tbase, 4) if (cluster_gih is not None and tbase is not None) else None), "cluster_gih_wr": (round(cluster_gih, 4) if cluster_gih is not None else None), "cluster_sample_games": (cg[0] if cg else 0), "trophy_gih_wr": (round(tbase, 4) if tbase is not None else None), "sample_games": g, "synergy": rel.get("synergy", []), "substitutes": rel.get("substitutes", []), "antisynergy": rel.get("antisynergy", []), "pick_priority": 0, "pick_threshold": {"P1": 1 if (base.get("avg_pick") or 9) <= 2.5 else 0, "midpack": bool((base.get("play_rate") or 0) > 0.5)}, }) for nm, mc in sorted(land_mean.items(), key=lambda kv: -kv[1]): if mc < 0.05: continue base = cards.get(nm, meta.get(nm, {})) cards_out.append({ "mtga_id": base.get("mtga_id"), "name": nm, "rarity": base.get("rarity"), "cmc": meta.get(nm, {}).get("cmc"), "color_pips": dict(pips(meta.get(nm, {}).get("mana_cost", ""))), "roles": ["land"], "mechanic_tags": [], "target_copies": round(mc, 2), "copies_when_played": round(mc, 2), "expected_copies": round(mc, 3), "inclusion": None, "max_copies": 1, "importance": 0.0, "affinity": None, "pair_gih_wr": base.get("ever_drawn_win_rate"), "pair_games": 0, "value": None, "gih_wr": base.get("ever_drawn_win_rate"), "gih_wr_ci": None, "alsa": base.get("avg_seen"), "iwd": None, "ata": base.get("avg_pick"), "play_rate": base.get("play_rate"), "context_delta": None, "cluster_gih_wr": None, "cluster_sample_games": 0, "trophy_gih_wr": None, "sample_games": base.get("ever_drawn_game_count") or 0, "synergy": [], "substitutes": [], "antisynergy": [], "pick_priority": 0, "pick_threshold": {"P1": 0, "midpack": False}, }) nonland = [r for r in cards_out if r["roles"] != ["land"]] for i, r in enumerate(sorted(nonland, key=lambda r: -r["importance"]), 1): r["pick_priority"] = i cards_out.sort(key=lambda r: (r["roles"] == ["land"], -(r.get("target_copies") or 0), -(r.get("importance") or 0))) defining_cards = [r["name"] for r in sorted(nonland, key=lambda r: -r["importance"])][:8] allowed = set(arch.upper()) affinity_cards = [r["name"] for r in sorted( (r for r in nonland if set(required_colors(meta.get(r["name"], {}).get("mana_cost", ""))) <= allowed and (r.get("pair_games") or 0) >= 40), key=lambda r: -(r.get("affinity") or -99))][:8] curve, crea, tot_spell, pipsum = Counter(), 0.0, 0.0, Counter() for nm, mc in mean.items(): cmc = meta.get(nm, {}).get("cmc") or 0 tot_spell += mc for b, fn in CURVE: if fn(cmc): curve[b] += mc if any("Creature" in t for t in (meta.get(nm, {}).get("types") or [])): crea += mc for ch, v in pips(meta.get(nm, {}).get("mana_cost", "")).items(): pipsum[ch] += v * mc cl_extra = Counter(len(extras_list[i]) for i in sel) cl_basic = Counter() for i in sel: cl_basic.update(basic_list[i]) landsrc = Counter() for nm, mc in land_mean.items(): for ch in (meta.get(nm, {}).get("color_identity") or []): if ch in ALL_COLORS: landsrc[ch] += mc combined = Counter(pipsum) for k, v in landsrc.items(): combined[k] += v primary = defining_cards[0] if defining_cards else arch theme, mech = OFFICIAL[arch] slug = f"{arch}-{slugify(primary)}-{slugify(mech)}" template = { "expansion": "FRA", "format": "PremierDraft", "archetype": arch, "colors": arch, "archetype_name": f"{arch}-{primary}-{mech}", "archetype_slug": slug, "official_name": f"{theme} {mech}", "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "confidence": round(min(1.0, m / 100), 2), "n_decks": m, "cluster_size": n, "defining_cards": defining_cards, "affinity_cards": affinity_cards, "deck_params": { "land_count": round(sum(land_tot[i] for i in sel) / m, 2), "splash_dist": dict(sorted(cl_extra.items())), "curve_targets": {b: round(curve.get(b, 0), 2) for b, _ in CURVE}, "creature_ratio": round(crea / (tot_spell or 1), 3), "color_weights": {k: round(v / (sum(combined.values()) or 1), 3) for k, v in sorted(combined.items())}, "spell_pips": {k: round(v / (sum(pipsum.values()) or 1), 3) for k, v in sorted(pipsum.items())}, "land_sources": {k: round(v, 2) for k, v in sorted(landsrc.items())}, "basic_lands": {k: round(v / m, 2) for k, v in sorted(cl_basic.items())}, }, "cards": cards_out, } (tdir / f"FRA.PremierDraft.{slug}.json").write_text( json.dumps(template, ensure_ascii=False, indent=1), encoding="utf-8") index[slug] = {"archetype": arch, "n": m, "cluster_size": n, "name": template["archetype_name"], "official": template["official_name"], "defining_cards": defining_cards, "key_cards": defining_cards[:5]} members_map[slug] = sorted({decks[i].get("aggregate_id") for i in sel}) print(f"{slug:44} cluster={n:3} core={m:3} {template['official_name']}") (tdir / "_index.json").write_text(json.dumps(index, ensure_ascii=False, indent=1), encoding="utf-8") (tdir / "_members.json").write_text(json.dumps(members_map, ensure_ascii=False), encoding="utf-8") print(f"\nwrote {len(index)} pair-level templates -> {tdir}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--snapshot", required=True) ap.add_argument("--out", required=True) ap.add_argument("--mtgch", default="data/mtgch") ap.add_argument("--core-frac", type=float, default=0.5) a = ap.parse_args() build(Path(a.snapshot), Path(a.out), Path(a.mtgch), a.core_frac) if __name__ == "__main__": main()