Add TRK set preview and refresh draft analysis

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.
This commit is contained in:
2026-11-15 11:37:16 +08:00
parent 4984b1f756
commit 58446ec562
1131 changed files with 1430660 additions and 189314 deletions
+76
View File
@@ -0,0 +1,76 @@
"""Shared top/bottom banner + centred page wrapper for the standalone report pages.
All these pages live in ``value/<SNAP>/reports/`` so the links below are relative to
that directory (``matchups.html``, ``card_graph.html``, ``cluster_viz.html`` and
``templates/index.html``).
"""
from __future__ import annotations
import re
import shutil
from pathlib import Path
ASSETS_SRC = Path(__file__).resolve().parent / "assets"
ASSETS = ("d3.v7.min.js",) # 随报告一起发布的前端资源
def ensure_assets(reports_dir) -> int:
"""把 scripts/assets/ 下的前端资源拷到 <reports>/assets/(首页图、d3 等),返回拷贝数。
这些文件不在 value/ 里(否则每次重建都被清掉),而在 render 时随报告部署。
"""
dst = Path(reports_dir) / "assets"
dst.mkdir(parents=True, exist_ok=True)
n = 0
for name in ASSETS:
src = ASSETS_SRC / name
if src.exists() and not (dst / name).exists():
shutil.copy2(src, dst / name)
n += 1
return n
NAV = [
("templates/index.html", "首页"),
("daily.html", "每日走势"),
("matchups.html", "克制矩阵"),
("card_graph.html", "牌间关系图"),
("cluster_viz.html", "聚类可视化"),
]
CSS = """*{box-sizing:border-box} body{font-family:system-ui,'Segoe UI',sans-serif;margin:0;padding:0;
background:#12141a;color:#e8e8ea}
.wrap{max-width:1460px;margin:0 auto;padding:20px 20px 8px}
.banner{background:#0f1218;border-bottom:1px solid #232b38}
.banner.bot{border-bottom:0;border-top:1px solid #232b38;margin-top:26px}
.bwrap{max-width:1460px;margin:0 auto;padding:10px 20px;display:flex;align-items:center;gap:18px;
font-size:13px;flex-wrap:wrap}
.brand{font-weight:700;color:#fff;text-decoration:none}
.banner .nav{display:flex;gap:14px;margin-left:auto;flex-wrap:wrap}
.banner .nav a{color:#9fb0c7;text-decoration:none}
.banner .nav a:hover{color:#fff}
.banner .nav a.on{color:#fff;font-weight:600}
.footwrap{max-width:1460px;margin:0 auto;padding:10px 20px;font-size:12px;color:#8a94a6;line-height:1.8}
"""
def set_of(path) -> str:
"""从 `value/TRK20261114` / `data/17lands/TRK20261114` 这类目录名取系列码。"""
m = re.match(r"([A-Za-z]+)", Path(path).name)
return (m.group(1) if m else "FRA").upper()
SET = "FRA" # 由各 renderer 从 out_dir / snapshot 名推导后覆盖(如 TRK)
def banner(current: str = "", extra: str = "") -> str:
links = "".join(
f'<a href="{h}"{" class=\"on\"" if h == current else ""}>{t}</a>' for h, t in NAV)
return ('<header class="banner"><div class="bwrap">'
f'<a class="brand" href="templates/index.html">{SET} PremierDraft · 子流派模板</a>'
f'<nav class="nav">{links}</nav>{extra}</div></header>')
def footbanner(legend: str = "") -> str:
"""Legend-only footer (no nav / attribution)."""
return f'<footer class="banner bot"><div class="footwrap">{legend}</div></footer>' if legend else ""
+408
View File
@@ -0,0 +1,408 @@
#!/usr/bin/env python
"""Turn the raw replay edge counts into a normalised card-association graph.
Pipeline
--------
1. NPMI per tier. Raw co-counts favour popular cards, so each of the four
evidence tiers (strong / medium / weak / veryweak) is turned into a
normalised pointwise mutual information, using that tier's own margins.
2. Iterative diffusion. A *two-step* association is folded back into the edge
weights a few times:
S <- (1-a) * S0 + a * (N^T S0 N) N = row-normalised adjacency
This is the "迭代计算" step: directly observed links are reinforced by the
links their neighbourhoods share, so weak-but-consistent synergies surface.
3. Sparsify. Keep, per card, its top-K strongest partners (default 20) so the
later clustering is not dominated by ubiquitous glue cards.
4. Louvain communities. Pure-python modularity optimisation gives the "聚落"
(card clusters) and, alongside, the bridges between them.
Outputs (under --out):
card_graph.json nodes + edges + per-tier npmi + cluster ids
card_clusters.json cluster -> ranked cards
reports/card_graph.md human readable summary
No third-party packages required.
"""
from __future__ import annotations
import argparse
import json
import math
from collections import Counter, defaultdict
from pathlib import Path
TIERS = ("strong", "effect", "medium", "weak", "veryweak")
# how much each tier contributes to the combined association score
TIER_WEIGHT = {"strong": 3.0, "effect": 1.2, "medium": 1.5,
"weak": 0.6, "veryweak": 0.25}
def npmi(p_ab: float, p_a: float, p_b: float) -> float:
if p_ab <= 0 or p_a <= 0 or p_b <= 0:
return 0.0
p_ab = min(p_ab, 1.0)
val = math.log(p_ab / (p_a * p_b))
denom = -math.log(p_ab)
if denom <= 1e-12:
return 0.0
return val / denom
def compute_npmi(payload, weights=None):
weights = weights or TIER_WEIGHT
nodes = payload["nodes"]
edges = payload["edges"]
meta = payload["meta"]
units = {
"strong": sum(e["strong"] for e in edges) or 1,
"effect": sum(e.get("effect", 0) for e in edges) or 1,
"medium": meta["turn_cells"] or 1,
"weak": meta["games"] or 1,
"veryweak": meta["decks"] or 1,
}
# margins per tier
margin = {t: Counter() for t in TIERS}
for e in edges:
for t in TIERS:
if e[t]:
margin[t][e["a"]] += e[t]
margin[t][e["b"]] += e[t]
for t in TIERS:
if units[t] <= 1:
units[t] = 1
# per-tier rate of a card (denominator uses that tier's own unit count)
for e in edges:
score = 0.0
for t in TIERS:
c = e[t]
if not c:
continue
p_ab = c / units[t]
p_a = margin[t][e["a"]] / units[t]
p_b = margin[t][e["b"]] / units[t]
v = npmi(p_ab, p_a, p_b)
e["npmi_" + t] = round(v, 4)
if v > 0:
score += weights.get(t, 0.0) * v
e["score"] = round(score, 5)
return payload
def sparsify(edges, top_k):
"""Keep each node's top-K partners by combined score."""
adj = defaultdict(dict)
for e in edges:
s = e["score"]
if s <= 0:
continue
adj[e["a"]][e["b"]] = s
adj[e["b"]][e["a"]] = s
keep = set()
for a, nbrs in adj.items():
for b, _ in sorted(nbrs.items(), key=lambda kv: -kv[1])[:top_k]:
keep.add((a, b) if a < b else (b, a))
out = [e for e in edges if (e["a"], e["b"]) in keep]
return out, adj
def diffuse(edges, iters=3, alpha=0.5):
"""Fold two-step associations back into the edge weights (iteratively)."""
if not edges:
return edges
# sparse adjacency over the *current* scores
W = defaultdict(dict)
for e in edges:
s = e["score"]
if s <= 0:
continue
W[e["a"]][e["b"]] = s
W[e["b"]][e["a"]] = s
for _ in range(iters):
# row normalise
N = {}
for a, nbrs in W.items():
tot = sum(nbrs.values()) or 1.0
N[a] = {b: v / tot for b, v in nbrs.items()}
new = defaultdict(float)
for e in edges:
a, b, s0 = e["a"], e["b"], e["score"]
if s0 <= 0:
continue
two = sum(N[a].get(k, 0.0) * N[b].get(k, 0.0) for k in set(N[a]) | set(N[b]))
new[(a, b)] = (1 - alpha) * s0 + alpha * two
if not new:
break
for e in edges:
e["score"] = round(new.get((e["a"], e["b"]), e["score"]), 5)
W = defaultdict(dict)
for e in edges:
if e["score"] > 0:
W[e["a"]][e["b"]] = e["score"]
W[e["b"]][e["a"]] = e["score"]
return edges
def louvain(edges, resolution=1.0, max_passes=40, max_levels=10):
"""Multi-level weighted Louvain modularity optimisation (pure python)."""
nodes = sorted({e["a"] for e in edges} | {e["b"] for e in edges})
adj = {i: {} for i in range(len(nodes))}
for e in edges:
s = e["score"]
if s <= 0 or e["a"] == e["b"]:
continue
i, j = nodes.index(e["a"]), nodes.index(e["b"])
adj[i][j] = adj[i].get(j, 0.0) + s
adj[j][i] = adj[j].get(i, 0.0) + s
# membership of every original node, composed across levels
original = {i: i for i in adj}
cur_adj = adj
for _level in range(max_levels):
deg = {i: sum(cur_adj[i].values()) for i in cur_adj}
m = sum(deg.values()) / 2 or 1.0
comm = _local_moving(cur_adj, deg, m, max_passes, resolution)
ncomm = len(set(comm.values()))
if ncomm == len(cur_adj):
break
# compose membership
for i in original:
original[i] = comm[original[i]]
# aggregate graph: new_adj[C][D] = sum of weights from C into D
new_adj = defaultdict(dict)
for i, nbrs in cur_adj.items():
ci = comm[i]
for j, w in nbrs.items():
cj = comm[j]
new_adj[ci][cj] = new_adj[ci].get(cj, 0.0) + w
cur_adj = {c: dict(nbrs) for c, nbrs in new_adj.items()}
# relabel compactly
labels = {c: k for k, c in enumerate(sorted(cur_adj))}
cur_adj = {labels[c]: {labels[d]: w for d, w in nbrs.items()}
for c, nbrs in cur_adj.items()}
for i in original:
original[i] = labels[original[i]]
# compact final labels
remap = {}
for i in original:
remap.setdefault(original[i], len(remap))
return {nodes[i]: remap[original[i]] for i in original}
def _local_moving(adj, deg, m, max_passes, resolution=1.0):
comm = {i: i for i in adj}
comm_deg = {i: deg[i] for i in adj}
m2 = 2 * m
order = sorted(adj, key=lambda i: -deg[i])
for _ in range(max_passes):
improved = False
for i in order:
ci = comm[i]
links = defaultdict(float)
for j, w in adj[i].items():
links[comm[j]] += w
comm_deg[ci] -= deg[i]
best, best_gain = ci, links.get(ci, 0.0) - comm_deg[ci] * deg[i] / m2
for c, w in links.items():
g = w - resolution * comm_deg[c] * deg[i] / m2
if g > best_gain + 1e-12:
best, best_gain = c, g
comm_deg[best] += deg[i]
if best != ci:
comm[i] = best
improved = True
if not improved:
break
return comm
def modularity(edges, members):
deg = defaultdict(float)
wsum = defaultdict(float)
m = 0.0
for e in edges:
s = e["score"]
if s <= 0:
continue
m += s
deg[e["a"]] += s
deg[e["b"]] += s
if members.get(e["a"]) == members.get(e["b"]):
wsum[members.get(e["a"])] += 2 * s
if m == 0:
return 0.0
q = 0.0
for c in set(members.values()):
d = sum(deg[n] for n in members if members[n] == c)
q += wsum[c] / (2 * m) - (d / (2 * m)) ** 2
return q
def merge_small(edges, members, min_size):
"""Absorb clusters smaller than min_size into their strongest neighbour."""
if min_size <= 1:
return members
stuck = set()
while True:
size = Counter(members.values())
small = [c for c, n in size.items() if n < min_size and c not in stuck]
if not small:
break
c = min(small, key=lambda x: size[x]) # smallest first
cw: dict = defaultdict(float)
for e in edges:
s = e.get("score", 0)
if s <= 0:
continue
ca, cb = members.get(e["a"]), members.get(e["b"])
if ca is None or cb is None or ca == cb:
continue
if ca == c:
cw[cb] += s
elif cb == c:
cw[ca] += s
if not cw:
stuck.add(c) # isolated small cluster
continue
tgt = max(cw, key=cw.get)
for node, cl in members.items():
if cl == c:
members[node] = tgt
# compact + order labels by descending size
order = {}
for cid, _n in Counter(members.values()).most_common():
order[cid] = len(order)
return {n: order[c] for n, c in members.items()}
def analyze_view(view, weights, top_k, diffuse_iters, resolution, colors,
min_cluster=6):
"""NPMI + diffusion + sparsify + Louvain for one (colour-group) view."""
payload = compute_npmi(view, weights)
sparse, _ = sparsify(payload["edges"], top_k)
sparse = diffuse(sparse, iters=diffuse_iters)
sparse, _ = sparsify(sparse, top_k)
members = louvain(sparse, resolution=resolution)
members = merge_small(sparse, members, min_cluster)
q = modularity(sparse, members)
clusters = defaultdict(list)
for name, info in payload["nodes"].items():
info["cluster"] = members.get(name, -1)
clusters[info["cluster"]].append(name)
cluster_rows = []
for cid, names in clusters.items():
ranked = sorted(names, key=lambda n: -payload["nodes"][n]["casts"])
color_hist = Counter()
for n in names:
color_hist[colors.get(n, "") or "C"] += 1
cluster_rows.append({
"cluster": cid,
"size": len(names),
"casts": sum(payload["nodes"][n]["casts"] for n in names),
"colors": color_hist.most_common(),
"cards": ranked,
})
cluster_rows.sort(key=lambda r: (-r["casts"], -r["size"]))
payload["edges"] = sparse
payload["clusters"] = cluster_rows
payload.setdefault("meta", {})["modularity"] = round(q, 4)
return payload
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--edges", default=None, help="path to card_graph_edges.json")
ap.add_argument("--top-k", type=int, default=20)
ap.add_argument("--diffuse-iters", type=int, default=3)
ap.add_argument("--resolution", type=float, default=0.8)
ap.add_argument("--min-cluster", type=int, default=6,
help="merge clusters smaller than this into a neighbour")
ap.add_argument("--tiers", default="strong,effect,medium,weak,veryweak",
help="comma list of tiers that feed the combined score")
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
edges_path = Path(args.edges) if args.edges else out / "card_graph_edges.json"
dest = out / "card_graph.json"
if dest.exists() and not args.force:
print(f"exists, skip: {dest} (use --force)")
return 0
raw = json.loads(edges_path.read_text(encoding="utf-8"))
views = raw["views"] if "views" in raw else {"__ALL__": raw}
keys = raw.get("keys") or list(views)
active = {t.strip() for t in args.tiers.split(",") if t.strip()}
weights = {t: (TIER_WEIGHT[t] if t in active else 0.0) for t in TIERS}
colors = {}
cards_path = out / "cards.json"
if cards_path.exists():
for c in json.loads(cards_path.read_text(encoding="utf-8")).get("cards", []):
colors[c["name"]] = c.get("color", "")
processed = {}
for key in keys:
if key not in views:
continue
processed[key] = analyze_view(views[key], weights, args.top_k,
args.diffuse_iters, args.resolution,
colors, args.min_cluster)
out_payload = {"views": processed, "keys": keys}
dest.write_text(json.dumps(out_payload, ensure_ascii=False), encoding="utf-8")
(out / "card_clusters.json").write_text(
json.dumps({k: processed[k]["clusters"] for k in keys if k in processed},
ensure_ascii=False, indent=1), encoding="utf-8")
_write_report(out, processed, keys, args.top_k)
for k in keys:
v = processed.get(k)
if v:
print(f" {k}: {len(v['nodes'])} nodes, {len(v['edges'])} edges, "
f"{len(v['clusters'])} clusters, Q={v['meta']['modularity']}")
print(f"wrote {len(processed)} graphs -> {dest}")
return 0
def _write_report(out: Path, processed, keys, top_k):
reports = out / "reports"
reports.mkdir(parents=True, exist_ok=True)
lines = ["# Card interaction graph", ""]
for key in keys:
v = processed.get(key)
if not v:
continue
meta = v["meta"]
lines += [
f"## {key}",
f"- games: **{meta['games']}** · cards: **{len(v['nodes'])}** · "
f"edges: **{len(v['edges'])}** · clusters: **{len(v['clusters'])}** "
f"(Q={meta['modularity']})",
"",
]
for row in v["clusters"][:12]:
head = ", ".join(row["cards"][:8])
col = " ".join(f"{c}:{n}" for c, n in row["colors"][:3])
lines.append(f"- **C{row['cluster']}** (n={row['size']}, {col}): {head}")
spec = sorted((e for e in v["edges"] if e.get("strong", 0) > 0),
key=lambda e: -e.get("npmi_strong", 0))[:8]
if spec:
lines.append("")
for e in spec:
lines.append(f" - {e['a']} ↔ {e['b']} "
f"npmi={e.get('npmi_strong')} strong={e['strong']}")
lines.append("")
(reports / "card_graph.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
if __name__ == "__main__":
raise SystemExit(main())
+11 -2
View File
@@ -42,8 +42,17 @@ 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)
up = [c for c in colors if c in order]
low = [c for c in colors.upper() if c in order]
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 is_basic(types) -> bool:
+11 -4
View File
@@ -29,10 +29,17 @@ def primary_pair(colors):
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 None
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:
Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

+2
View File
File diff suppressed because one or more lines are too long
+11 -4
View File
@@ -29,10 +29,17 @@ def primary_pair(colors):
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 None
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 cmc_bucket(cmc):
if cmc is None:
return -1
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env python
"""Parse 17lands GRE replays into real "cast / played" counts per card.
For each replay we replay the GameStateMessages and detect:
* cast - a GameObjectType_Card entering the Stack zone (zoneId 27), controlled by
our seat (activated abilities, which are GameObjectType_Ability, excluded)
* play - a land card entering the Battlefield zone (zoneId 28)
Counts are aggregated per card name together with the number of replay-games in which
the card was in that draft's 40-card maindeck, giving:
cast_rate = casts / games-in-deck (spells, casts per game)
cast_game_pct = games-with-cast / games-in-deck
play_rate = land plays / games-in-deck
Output: value/<snapshot>/cast_stats.json
"""
from __future__ import annotations
import argparse
import gzip
import json
from collections import Counter, defaultdict
from pathlib import Path
STACK_ZONE = 27
BATTLEFIELD_ZONE = 28
def load_jsonl(p: Path):
with p.open(encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
yield json.loads(line)
def build_id2name(snapshot: Path) -> dict[int, str]:
id2name: dict[int, str] = {}
for c in json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]:
id2name[c["mtga_id"]] = c["name"]
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
for cid, m in (rec.get("cards") or {}).items():
id2name.setdefault(int(cid), m.get("name"))
return id2name
def build_decks(snapshot: Path, id2name: dict[int, str]) -> dict[str, tuple[set, set]]:
"""draft_id -> (nonland names in maindeck, land names in maindeck)."""
land_names = set(_BASICS)
for c in json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]:
if any("Land" in t for t in (c.get("types") or [])):
land_names.add(c["name"])
decks: dict[str, tuple[set, set]] = {}
for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
aid = deck.get("aggregate_id")
if not aid:
continue
nl, ld = set(), set()
for e in deck.get("maindeck") or []:
nm = id2name.get(e.get("mtga_id"))
if not nm:
continue
(ld if nm in land_names else nl).add(nm)
decks[aid] = (nl, ld)
return decks
_BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
def parse_replay(path: Path, me: int, id2name: dict[int, str]):
"""Return (casts Counter[name], land_plays Counter[name])."""
data = json.loads(gzip.open(path, "rb").read())
events = data.get("events") or []
me = data.get("seat_id") or me
casts: Counter = Counter()
land_plays: Counter = Counter()
objs: dict[int, dict] = {}
prev_stack: set[int] = set()
seen_bf: set[int] = set()
for e in events:
gsm = e.get("gameStateMessage") or {}
for o in gsm.get("gameObjects") or []:
objs[o["instanceId"]] = o
zones = {z["zoneId"]: z for z in gsm.get("zones") or []}
st = zones.get(STACK_ZONE)
if st is not None:
now = set(st.get("objectInstanceIds") or [])
for iid in now - prev_stack:
o = objs.get(iid) or {}
if o.get("controllerSeatId") != me or o.get("type") != "GameObjectType_Card":
continue
nm = id2name.get(o.get("grpId"))
if nm:
casts[nm] += 1
prev_stack = now
bf = zones.get(BATTLEFIELD_ZONE)
if bf is not None:
for iid in bf.get("objectInstanceIds") or []:
if iid in seen_bf:
continue
seen_bf.add(iid)
o = objs.get(iid) or {}
if o.get("controllerSeatId") == me and "CardType_Land" in (o.get("cardTypes") or []):
nm = id2name.get(o.get("grpId"))
if nm:
land_plays[nm] += 1
return casts, land_plays
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
snapshot = Path(args.snapshot)
out = Path(args.out)
dest = out / "cast_stats.json"
if dest.exists() and not args.force:
print(f"exists, skip: {dest} (use --force)")
return 0
id2name = build_id2name(snapshot)
decks = build_decks(snapshot, id2name)
print(f"id2name={len(id2name)} decks={len(decks)}")
rows = list(load_jsonl(snapshot / "replays/replay_index.jsonl"))
stat = defaultdict(lambda: {"cast": 0, "cast_games": 0, "play": 0, "play_games": 0, "games": 0})
by_draft = defaultdict(lambda: {"games": 0, "cast": defaultdict(int), "cg": defaultdict(int),
"play": defaultdict(int), "pg": defaultdict(int)})
done = skipped = 0
for i, r in enumerate(rows, 1):
draft_id = r["draft_id"]
deck = decks.get(draft_id)
if not deck:
skipped += 1
continue
path = snapshot / "replays" / f"{r['history_path']}.json.gz"
if not path.exists():
skipped += 1
continue
try:
casts, plays = parse_replay(path, 0, id2name)
except Exception as e: # noqa: BLE001
print(f" !! {path.name}: {e}")
skipped += 1
continue
nl, ld = deck
bd = by_draft[draft_id]
bd["games"] += 1
for nm, n in casts.items():
bd["cast"][nm] += n
bd["cg"][nm] += 1
for nm, n in plays.items():
bd["play"][nm] += n
bd["pg"][nm] += 1
for nm in nl | ld:
stat[nm]["games"] += 1
for nm, n in casts.items():
stat[nm]["cast"] += n
stat[nm]["cast_games"] += 1
for nm, n in plays.items():
stat[nm]["play"] += n
stat[nm]["play_games"] += 1
done += 1
if i % 200 == 0:
print(f" {i}/{len(rows)} (parsed {done}, skipped {skipped})")
out.mkdir(parents=True, exist_ok=True)
dest.write_text(json.dumps(stat, ensure_ascii=False), encoding="utf-8")
bd_dest = out / "cast_by_draft.json"
bd_dest.write_text(json.dumps(
{k: {"games": v["games"], "cast": dict(v["cast"]), "cg": dict(v["cg"]),
"play": dict(v["play"]), "pg": dict(v["pg"])} for k, v in by_draft.items()},
ensure_ascii=False), encoding="utf-8")
print(f"wrote {bd_dest} ({len(by_draft)} drafts)")
print(f"wrote {len(stat)} cards from {done} replays (skipped {skipped}) -> {dest}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+11 -4
View File
@@ -37,10 +37,17 @@ def primary_pair(colors):
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 None
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 norm(a):
return math.sqrt(sum(v * v for v in a))
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Compute archetype matchup matrices from game results.
Our side = the template (cluster) the draft belongs to (via templates/_members.json);
opponent side = opponent_colors collapsed to main pair.
NOTE: every deck here is a 7-win trophy deck, so these win rates are *conditional
on our deck being a trophy deck* — read them as relative matchup strength.
Outputs:
value/<SNAPSHOT>/matchups/FRA.PremierDraft.matrix.json
value/<SNAPSHOT>/reports/matchups.md
"""
from __future__ import annotations
import argparse
import json
import math
import re
from collections import Counter, defaultdict
from pathlib import Path
PAIRS = ["WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"]
Z = 1.959964
RANK_ORDER = {"Bronze": 0, "Silver": 1, "Gold": 2, "Platinum": 3, "Diamond": 4, "Mythic": 5}
RANK_MIN = 2 # Gold
def rank_ok(s):
return RANK_ORDER.get((s or "").split("-")[0], 99) >= RANK_MIN
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 wilson(w, n, z=Z):
if not n:
return [None, None]
p = w / 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 main_pair(colors):
if not colors:
return "?"
up = [c for c in colors if c in "WUBRG"]
if len(up) >= 2:
return "".join(sorted(up[:2], key="WUBRG".index))
if len(up) == 1:
return up[0]
return "?"
def build(snapshot: Path, out_dir: Path) -> None:
_sm = re.match(r"([A-Za-z]+)", out_dir.name)
SET = (_sm.group(1) if _sm else "FRA").upper()
members = json.loads((out_dir / "templates/_members.json").read_text(encoding="utf-8"))
index = json.loads((out_dir / "templates/_index.json").read_text(encoding="utf-8"))
draft_to_slug = {did: slug for slug, ids in members.items() for did in ids}
cell = defaultdict(lambda: [0, 0]) # (slug, opp_pair) -> [n, wins]
paircell = defaultdict(lambda: [0, 0]) # (our_pair, opp_pair) -> [n, wins]
games = 0
for rec in load_jsonl(snapshot / "drafts/event_details.jsonl"):
slug = draft_to_slug.get(rec["draft_id"])
our_pair = index.get(slug, {}).get("archetype")
for m in rec.get("details", {}).get("match_results") or []:
for g in m.get("game_results") or []:
if not rank_ok(g.get("start_rank")):
continue
opp = main_pair(g.get("opponent_colors"))
won = 1 if g.get("won") else 0
games += 1
if slug:
c = cell[(slug, opp)]
c[0] += 1
c[1] += won
if our_pair:
c = paircell[(our_pair, opp)]
c[0] += 1
c[1] += won
def matrix(keys, cells, key_fn):
out = {}
for k in keys:
row = {}
for opp in PAIRS + ["?"]:
c = cells.get(key_fn(k, opp))
if c and c[0] >= 10:
row[opp] = {"winrate": round(c[1] / c[0], 3), "ci": wilson(c[1], c[0]), "n": c[0]}
out[k] = row
return out
slug_keys = [s for s in index]
m_full = matrix(slug_keys, cell, lambda s, o: (s, o))
m_pair = matrix(PAIRS, paircell, lambda s, o: (s, o))
(out_dir / "matchups").mkdir(parents=True, exist_ok=True)
(out_dir / f"matchups/{SET}.PremierDraft.matrix.json").write_text(json.dumps({
"expansion": SET, "format": "PremierDraft",
"note": "trophy-conditional: our side is always a 7-win deck; read as relative strength",
"games": games,
"archetypes": slug_keys,
"matrix": m_full,
"color_pair_matrix": m_pair,
}, ensure_ascii=False, indent=1), encoding="utf-8")
# report
rep = [f"# {SET} PremierDraft · 克制矩阵(相对强度)\n",
f"{games} 局;我方均为 7 胜牌表 → 绝对胜率偏高,**看相对差异**。\n",
"## 双色对 × 双色对(我方胜率 / n)\n",
"| 我方 | " + " | ".join(PAIRS) + " |",
"|---|" + "---|" * len(PAIRS)]
for me in PAIRS:
row = [me]
for opp in PAIRS:
c = paircell.get((me, opp))
row.append(f"{c[1]/c[0]*100:.0f}% ({c[0]})" if c and c[0] >= 10 else "-")
rep.append("| " + " | ".join(row) + " |")
(out_dir / "reports").mkdir(parents=True, exist_ok=True)
(out_dir / "reports/matchups.md").write_text("\n".join(rep), encoding="utf-8")
filled = sum(1 for r in m_full.values() for _ in r)
print(f"games={games}; template cells(>=10)={filled}; wrote matchups/{SET}.PremierDraft.matrix.json + reports/matchups.md")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
build(Path(a.snapshot), Path(a.out))
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python
"""Build a per-draft "cards that were offered" index from 17lands draftdata.
For each replay in <snapshot>/draftdata/<draft_id>.json we union every entry of
``picks[].available[]`` (the pack contents the seat actually saw) into a set of
card names, then cache ``{draft_id: [names...]}`` to value/<snapshot>/offer_index.json.
This lets the template builder compute a rarity-fair inclusion:
P(card is played | card was offered to this seat)
which removes the bias that rare/mythic cards are simply never passed to you.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True, help="e.g. data/17lands/FRA20261007")
ap.add_argument("--out", required=True, help="e.g. value/FRA20261007")
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
snapshot = Path(args.snapshot)
out = Path(args.out)
dest = out / "offer_index.json"
if dest.exists() and not args.force:
print(f"exists, skip: {dest} (use --force to rebuild)")
return 0
ddir = snapshot / "draftdata"
files = sorted(ddir.glob("*.json"))
index: dict[str, list[str]] = {}
for i, f in enumerate(files, 1):
try:
d = json.loads(f.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
print(f" !! {f.name}: {e}")
continue
seen: set[str] = set()
for pk in d.get("picks") or []:
for c in pk.get("available") or []:
nm = c.get("name")
if nm:
seen.add(nm)
if seen:
index[f.stem] = sorted(seen)
if i % 100 == 0:
print(f" {i}/{len(files)}")
out.mkdir(parents=True, exist_ok=True)
dest.write_text(json.dumps(index, ensure_ascii=False), encoding="utf-8")
avg = (sum(len(v) for v in index.values()) / len(index)) if index else 0
print(f"wrote {len(index)} drafts (avg {avg:.1f} cards offered) -> {dest}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""Build one maximally-strong "typical" deck per sub-archetype.
Rarity budget (from trophy data: ~0.6 mythic / ~1.9 rare / ~8.8 uncommon per
deck): at most 1 mythic + 1 rare + 9 uncommons, rest commons -> 23 spells + lands.
Cards are chosen by quality-in-archetype (affinity); creature/spell split follows
the archetype's creature ratio; basic lands only in colours the deck uses.
Outputs: value/<SNAPSHOT>/reference_decks/<slug>.json + .txt
"""
from __future__ import annotations
import argparse
import json
import re
from collections import Counter, defaultdict
from pathlib import Path
ALL_COLORS = "WUBRG"
BASIC_COLOR = {"Plains": "W", "Island": "U", "Swamp": "B", "Mountain": "R", "Forest": "G"}
RARITY_CAP = {"mythic": 1, "rare": 1, "uncommon": 9, "common": 99}
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 score(c):
return c["affinity"] if c.get("affinity") is not None else (c.get("importance") or 0)
def build_deck(t, cap):
allowed = set((t.get("colors") or t["archetype"]).upper())
spells = [c for c in t["cards"] if c["roles"] != ["land"]]
cand = [c for c in spells if set(required_colors(c.get("mana_cost", ""))) <= allowed]
cre = sorted((c for c in cand if "creature" in (c.get("roles") or [])),
key=score, reverse=True)
non = sorted((c for c in cand if "creature" not in (c.get("roles") or [])),
key=score, reverse=True)
cr = t["deck_params"].get("creature_ratio") or 0.55
n_cre = min(17, max(10, round(23 * cr)))
used = defaultdict(int)
counts = Counter()
total = 0
def add(c):
nonlocal total
rar = (c.get("rarity") or "common").lower()
if rar not in cap:
rar = "common"
cop = min(3, max(1, round(c.get("copies_when_played") or 1)))
for _ in range(cop):
if total >= 23 or used[rar] >= cap[rar]:
break
used[rar] += 1
counts[c["name"]] += 1
total += 1
for c in cre:
if total >= n_cre:
break
add(c)
for c in non:
if total >= 23:
break
add(c)
for c in cre + non: # fill if creature pass capped early
if total >= 23:
break
add(c)
info = {c["name"]: c for c in cand}
deck = [{"name": n, "count": k, "rarity": info[n].get("rarity"), "cmc": info[n].get("cmc"),
"roles": info[n].get("roles"), "mechanic_tags": info[n].get("mechanic_tags")}
for n, k in sorted(counts.items(),
key=lambda kv: (0 if "creature" in (info[kv[0]].get("roles") or []) else 1,
info[kv[0]].get("cmc") or 0))]
n_creatures = sum(d["count"] for d in deck if "creature" in (d["roles"] or []))
dp = t["deck_params"]
nl = round(dp["land_count"])
bases = {k: v for k, v in dp["basic_lands"].items()
if v > 0.3 and BASIC_COLOR.get(k, "?") in allowed}
if not bases:
bases = {k: 1.0 for k in BASIC_COLOR if BASIC_COLOR[k] in allowed} or {"Plains": 1.0}
s = sum(bases.values()) or 1
lands = {k: max(1, round(v / s * nl)) for k, v in bases.items()}
while sum(lands.values()) > nl:
lands[max(lands, key=lands.get)] -= 1
while sum(lands.values()) < nl:
lands[max(bases, key=bases.get)] += 1
return deck, lands, used, n_creatures
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--uncommon", type=int, default=9)
a = ap.parse_args()
out = Path(a.out)
cap = dict(RARITY_CAP)
cap["uncommon"] = a.uncommon
tdir = out / "templates"
ddir = out / "reference_decks"
ddir.mkdir(parents=True, exist_ok=True)
for f in sorted(tdir.glob("*.PremierDraft.*.json")):
t = json.loads(f.read_text(encoding="utf-8"))
if t.get("reference_deck"):
# actual medoid deck of the cluster (the real 40 cards closest to all others)
rd = t["reference_deck"]
deck, lands = rd["spells"], rd["lands"]
used = Counter()
for d in deck:
used[d.get("rarity") or "common"] += d["count"]
n_creatures = sum(d["count"] for d in deck if "creature" in (d.get("roles") or []))
src = rd.get("source", "actual medoid deck")
src += f" · 战绩 {rd['record']}" if rd.get("record") else ""
else:
deck, lands, used, n_creatures = build_deck(t, cap)
src = "constructed (max-quality under rarity budget)"
rec = {"archetype": t["archetype"], "archetype_slug": t["archetype_slug"],
"archetype_name": t["archetype_name"], "colors": t.get("colors"),
"source": src,
"rarity_budget": cap, "rarity_used": dict(used),
"n_creatures": n_creatures,
"spells": deck, "lands": lands,
"total_spells": sum(d["count"] for d in deck),
"total_lands": sum(lands.values())}
(ddir / f"{t['archetype_slug']}.json").write_text(
json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
txt = [f"# {t['archetype_name']} ({t.get('colors')}) {src}",
f"# used={dict(used)} creatures={n_creatures}"]
txt += [f"{d['count']}x {d['name']} [{d['rarity']}]" for d in deck]
txt.append("-- lands --")
txt += [f"{v}x {k}" for k, v in sorted(lands.items(), key=lambda kv: -kv[1])]
(ddir / f"{t['archetype_slug']}.txt").write_text("\n".join(txt), encoding="utf-8")
# MTGA-importable decklist
mtga = ["Deck"]
mtga += [f"{d['count']} {d['name']}" for d in deck]
mtga += [f"{v} {k}" for k, v in sorted(lands.items(), key=lambda kv: -kv[1])]
(ddir / f"{t['archetype_slug']}.mtga.txt").write_text("\n".join(mtga) + "\n", encoding="utf-8")
print(f"{t['archetype_name']:44} spells={rec['total_spells']} lands={rec['total_lands']} "
f"creatures={n_creatures} {dict(used)}")
print(f"\nwrote {len(list(ddir.glob('*.json')))} reference decks -> {ddir}")
if __name__ == "__main__":
main()
+483
View File
@@ -0,0 +1,483 @@
#!/usr/bin/env python
"""Build a multi-tier card-card interaction graph from 17lands GRE replays.
Nodes are cards (mtga grpId / name), weighted by how often they are actually
cast. Edges are drawn at four *tiers* of evidence, from strongest to weakest:
strong -- within one resolution window, casting card A caused an ability /
token / trigger-holder to be created whose source permanent is
another card B on the battlefield (same controller). This is the
"chain / triggered" signal. Plain +1/+1 counters are ignored.
medium -- A and B were cast by the same player in the same turn.
weak -- A and B were cast by the same player in the same game.
veryweak -- A and B are in the same draft pool / deck.
For every tier we also record the *margins* needed to normalise the co-counts
into lift / PMI later (how many games / turns / decks the single card appears
in).
Output (under --out):
card_graph_edges.json {nodes:{name:...}, edges:[{a,b,strong,...}], meta:{...}}
Nothing here depends on third-party packages.
"""
from __future__ import annotations
import argparse
import gzip
import json
from collections import Counter, defaultdict
from pathlib import Path
# zone / object type constants (MTGA GRE)
STACK_ZONE = 27
BATTLEFIELD_ZONE = 28
HAND_ZONE = 31
CARD = "GameObjectType_Card"
ABILITY = "GameObjectType_Ability"
TOKEN = "GameObjectType_Token"
TRIGGER = "GameObjectType_TriggerHolder"
MAKER_TYPES = {ABILITY, TOKEN, TRIGGER}
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
# state-change effects that indicate a permanent chained with the resolving card
EFFECT_ANN = {
"AnnotationType_CounterAdded",
"AnnotationType_CounterRemoved",
"AnnotationType_PowerToughnessModCreated",
"AnnotationType_AttachmentCreated",
"AnnotationType_RevealedCardCreated",
"AnnotationType_GainDesignation",
"AnnotationType_MultistepEffectStarted",
"AnnotationType_DisqualifiedEffect",
"AnnotationType_ReplacementEffectApplied",
}
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 build_id2name(snapshot: Path) -> dict[int, str]:
id2name: dict[int, str] = {}
cd = snapshot / "stats/card_data.json"
if cd.exists():
for c in json.loads(cd.read_text(encoding="utf-8"))["data"]:
id2name[int(c["mtga_id"])] = c["name"]
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
for cid, m in (rec.get("cards") or {}).items():
if m.get("name"):
id2name.setdefault(int(cid), m["name"])
return id2name
def primary_pair(colors: str | None) -> str | None:
"""Map a deck_colors string (e.g. "WBg") to its primary two-colour pair."""
if not colors:
return None
order = "WUBRG"
up = [c for c in colors if c in order] # uppercase = main colours
low = [c for c in colors.upper() if c in order]
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 build_deck_pairs(snapshot: Path, mode: str = "primary") -> dict[str, str]:
"""draft_id -> primary colour pair.
mode="primary": fold any deck (incl. 3-colour) to its first two main colours.
mode="main2" : only keep decks whose *main* colour count is <= 2 (2-colour
+ splash). Decks with a third main colour are dropped.
"""
pairs: dict[str, str] = {}
path = snapshot / "drafts/event_details.jsonl"
if not path.exists():
return pairs
for rec in load_jsonl(path):
did = rec.get("draft_id")
dc = (rec.get("metadata") or {}).get("deck_colors")
if mode == "main2" and dc:
main = [c for c in dc if c in "WUBRG"]
if len(main) > 2:
continue
pair = primary_pair(dc)
if did and pair:
pairs[did] = pair
return pairs
def build_id2colors(snapshot: Path) -> dict[str, set]:
"""card name -> set of colour-identity letters ('' = colourless)."""
colors: dict[str, set] = {}
cd = snapshot / "stats/card_data.json"
if cd.exists():
for c in json.loads(cd.read_text(encoding="utf-8"))["data"]:
colors[c["name"]] = set(c.get("color") or "")
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
for _cid, m in (rec.get("cards") or {}).items():
if m.get("name"):
colors.setdefault(m["name"], set(m.get("color_identity") or []))
return colors
def build_pools(snapshot: Path, id2name: dict[int, str]) -> dict[str, set[str]]:
"""draft_id -> set of nonland card names in the draft pool."""
pools: dict[str, set[str]] = {}
path = snapshot / "drafts/event_details.jsonl"
if not path.exists():
return pools
for rec in load_jsonl(path):
did = rec.get("draft_id")
if not did:
continue
cards = ((rec.get("details") or {}).get("draft_pool") or {}).get("cards") or []
names = {id2name[c] for c in cards if c in id2name}
if names:
pools[did] = names
return pools
def parse_replay(path: Path, id2name: dict[int, str]):
"""Replay one GRE game and return the raw interaction events.
Returns dict with:
casts : list[(seq, card_name, controller, turn)] nonland casts
makers : list[(seq, src_name, controller, kind)] new ability/token/trigger
game_cards : {controller: set(names)} every nonland card that player owned
turns : {controller: {turn: set(names)}} nonland casts per turn
"""
data = json.loads(gzip.open(path, "rb").read())
events = data.get("events") or []
objs: dict[int, dict] = {}
prev_stack: set[int] = set()
seen_bf: set[int] = set()
casts: list[tuple[int, str, int, int]] = []
makers: list[tuple[int, str, int, str]] = []
game_cards: dict[int, set] = defaultdict(set)
turns: dict[int, dict[int, set]] = defaultdict(lambda: defaultdict(set))
turn = 0
seq = 0
def source_name(o: dict):
"""Resolve the card a maker/effect belongs to.
Prefer the object's own ``objectSourceGrpId`` (the card that created an
ability/token); otherwise walk the ``parentId`` chain. This also
resolves a token's own ability back to the spell that made the token.
"""
seen = set()
cur = o
while cur is not None:
iid = cur.get("instanceId")
if iid in seen:
return None
seen.add(iid)
s = id2name.get(cur.get("objectSourceGrpId"))
if s:
return s
if cur.get("type") in (CARD, TOKEN):
s = id2name.get(cur.get("grpId"))
if s:
return s
pid = cur.get("parentId")
cur = objs.get(pid) if pid is not None else None
return None
for e in events:
gsm = e.get("gameStateMessage") or {}
if not gsm:
continue
seq += 1
turninfo = gsm.get("turnInfo") or {}
if turninfo.get("turnNumber"):
turn = turninfo["turnNumber"]
if gsm.get("type") == "GameStateType_Full":
objs = {}
# Object id remaps (must happen before we look at zone membership)
for a in gsm.get("annotations") or []:
if "AnnotationType_ObjectIdChanged" not in (a.get("type") or []):
continue
oid = nid = None
for det in a.get("details") or []:
if det.get("key") == "orig_id" and det.get("valueInt32"):
oid = det["valueInt32"][0]
if det.get("key") == "new_id" and det.get("valueInt32"):
nid = det["valueInt32"][0]
if oid in objs and nid is not None:
objs[nid] = objs.pop(oid)
for iid in gsm.get("diffDeletedInstanceIds") or []:
objs.pop(iid, None)
# 1. apply all object definitions first, so parent chains resolve
new_objs = []
for o in gsm.get("gameObjects") or []:
o = dict(o)
iid = o["instanceId"]
prev = objs.get(iid)
if prev is None:
objs[iid] = o
new_objs.append(o)
else:
merged = dict(prev)
merged.update(o)
objs[iid] = merged
# 2. maker objects: tokens & trigger-holders are born on the battlefield
for o in new_objs:
if o.get("type") not in (TOKEN, TRIGGER):
continue
nm = source_name(o)
if not nm or nm in BASICS:
continue
kind = "trigger" if o.get("type") == TRIGGER else "token"
makers.append((seq, nm, o.get("controllerSeatId"), kind))
# 2b. effect annotations: a permanent's effect chained with the resolution
for a in gsm.get("annotations") or []:
tys = a.get("type") or []
if not tys or tys[0] not in EFFECT_ANN:
continue
aff = a.get("affectorId")
if aff is None:
continue
ao = objs.get(aff)
nm = source_name(ao) if ao else None
if nm and nm not in BASICS:
makers.append((seq, nm, ao.get("controllerSeatId"), "effect"))
# 3. zone membership changes -> casts, land drops and abilities on stack
zones = {z["zoneId"]: z for z in gsm.get("zones") or []}
st = zones.get(STACK_ZONE)
if st is not None:
now = set(st.get("objectInstanceIds") or [])
for iid in now - prev_stack:
o = objs.get(iid) or {}
otype = o.get("type")
if otype == CARD:
nm = id2name.get(o.get("grpId"))
if not nm or nm in BASICS:
continue
ctrl = o.get("controllerSeatId")
casts.append((seq, nm, ctrl, turn))
game_cards[ctrl].add(nm)
turns[ctrl][turn].add(nm)
elif otype == ABILITY:
src = source_name(o)
if src and src not in BASICS:
makers.append((seq, src, o.get("controllerSeatId"), "ability"))
prev_stack = now
bf = zones.get(BATTLEFIELD_ZONE)
if bf is not None:
for iid in bf.get("objectInstanceIds") or []:
if iid in seen_bf:
continue
seen_bf.add(iid)
o = objs.get(iid) or {}
if o.get("type") != CARD:
continue
# lands are intentionally not part of the interaction graph
return {
"casts": casts,
"makers": makers,
"game_cards": game_cards,
"turns": turns,
"seat": data.get("seat_id"),
}
def strong_pairs(casts, makers):
"""Attribute each maker to the preceding cast by the *same* controller.
The window ends at the controller's next cast (opponent casts do not cut it).
"""
casts = sorted(casts, key=lambda c: c[0])
by_ctrl: dict[int, list[int]] = defaultdict(list)
for i, (_s, _c, ctrl, _t) in enumerate(casts):
by_ctrl[ctrl].append(i)
out = Counter()
effects = Counter()
for ctrl, idxs in by_ctrl.items():
for k, i in enumerate(idxs):
seq, card, _c, _t = casts[i]
end = casts[idxs[k + 1]][0] if k + 1 < len(idxs) else 10 ** 12
for mseq, src, mctrl, kind in makers:
if not (seq < mseq < end):
continue
if mctrl != ctrl or src == card:
continue
a, b = (card, src) if card < src else (src, card)
if kind == "effect":
effects[(a, b)] += 1
else:
# trigger-holder is the most explicit signal -> extra weight
out[(a, b)] += 2 if kind == "trigger" else 1
return out, effects
def pairs_within(items, out, seen_pairs=None):
a = sorted(items)
for i in range(len(a)):
for j in range(i + 1, len(a)):
out[(a[i], a[j])] += 1
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--limit", type=int, default=0, help="debug: only N replays")
ap.add_argument("--deck-colors", choices=["primary", "main2"], default="main2",
help="main2=2-colour+splash only (default); primary=fold 3-colour into pair")
ap.add_argument("--card-colors", choices=["pair", "all"], default="all",
help="all=keep splash cards in pair views (default, report dims them); pair=drop them")
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
snapshot = Path(args.snapshot)
out = Path(args.out)
dest = out / "card_graph_edges.json"
if dest.exists() and not args.force:
print(f"exists, skip: {dest} (use --force)")
return 0
id2name = build_id2name(snapshot)
pools = build_pools(snapshot, id2name)
rows = list(load_jsonl(snapshot / "replays/replay_index.jsonl"))
deck_pair = build_deck_pairs(snapshot, args.deck_colors)
id2colors = build_id2colors(snapshot)
def allowed_in(pair: str):
if args.card_colors == "all":
return None
pset = set(pair)
return lambda nm: id2colors.get(nm, set()) <= pset
def new_bucket():
return {
"cast_count": Counter(), "cast_games": Counter(),
"strong": Counter(), "effect": Counter(),
"medium": Counter(), "weak": Counter(), "veryweak": Counter(),
"tier_turn": Counter(), "pool_card": Counter(),
"unit_games": 0, "unit_turns": 0, "unit_decks": 0,
}
buckets: dict[str, dict] = {"__ALL__": new_bucket()}
def add_game(bucket: dict, g: dict, seat: int, pool, allowed=None) -> None:
keep = (lambda nm: True) if allowed is None else allowed
bucket["unit_games"] += 1
casts = [c for c in g["casts"] if c[2] == seat and keep(c[1])]
seen = set()
for _seq, card, _ctrl, _turn in casts:
bucket["cast_count"][card] += 1
seen.add(card)
for card in seen:
bucket["cast_games"][card] += 1
turns = {t: {nm for nm in names if keep(nm)}
for t, names in g["turns"].get(seat, {}).items()}
turns = {t: ns for t, ns in turns.items() if ns}
for _turn, names in turns.items():
bucket["unit_turns"] += 1
for nm in names:
bucket["tier_turn"][nm] += 1
makers = [m for m in g["makers"] if m[2] == seat and keep(m[1])]
s_pairs, e_pairs = strong_pairs(casts, makers)
for k, n in s_pairs.items():
bucket["strong"][k] += n
for k, n in e_pairs.items():
bucket["effect"][k] += n
for _turn, names in turns.items():
if len(names) >= 2:
pairs_within(names, bucket["medium"])
gnames = {nm for nm in g["game_cards"].get(seat, set()) if keep(nm)}
if len(gnames) >= 2:
pairs_within(gnames, bucket["weak"])
if pool:
pool = {nm for nm in pool if keep(nm)}
bucket["unit_decks"] += 1
for nm in pool:
bucket["pool_card"][nm] += 1
if len(pool) >= 2:
pairs_within(pool, bucket["veryweak"])
done = skipped = 0
for i, r in enumerate(rows, 1):
if args.limit and done >= args.limit:
break
path = snapshot / "replays" / f"{r['history_path']}.json.gz"
if not path.exists():
skipped += 1
continue
try:
g = parse_replay(path, id2name)
except Exception as exc: # noqa: BLE001
print(f" !! {path.name}: {exc}")
skipped += 1
continue
seat = g.get("seat")
if seat is None:
continue
done += 1
pool = pools.get(r["draft_id"])
add_game(buckets["__ALL__"], g, seat, pool)
pair = deck_pair.get(r["draft_id"])
if pair:
buckets.setdefault(pair, new_bucket())
add_game(buckets[pair], g, seat, pool, allowed_in(pair))
if i % 500 == 0:
print(f" {i}/{len(rows)} parsed={done} skipped={skipped}")
out.mkdir(parents=True, exist_ok=True)
views: dict[str, dict] = {}
for key, b in buckets.items():
all_pairs = (set(b["strong"]) | set(b["effect"]) | set(b["medium"])
| set(b["weak"]) | set(b["veryweak"]))
edges = []
for (a, bb) in all_pairs:
edges.append({
"a": a, "b": bb,
"strong": b["strong"].get((a, bb), 0),
"effect": b["effect"].get((a, bb), 0),
"medium": b["medium"].get((a, bb), 0),
"weak": b["weak"].get((a, bb), 0),
"veryweak": b["veryweak"].get((a, bb), 0),
})
edges.sort(key=lambda e: (-(e["strong"]), -(e["effect"]),
-(e["medium"]), -(e["weak"])))
nodes = {}
for nm, n in b["cast_count"].most_common():
nodes[nm] = {
"casts": n,
"cast_games": b["cast_games"].get(nm, 0),
"turn_cells": b["tier_turn"].get(nm, 0),
"deck_games": b["pool_card"].get(nm, 0),
}
views[key] = {
"nodes": nodes, "edges": edges,
"meta": {
"games": b["unit_games"], "turn_cells": b["unit_turns"],
"decks": b["unit_decks"], "replays_available": done,
"replays_skipped": skipped,
},
}
keys = ["__ALL__"] + sorted(k for k in views if k != "__ALL__")
payload = {"views": views, "keys": keys}
dest.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
summary = ", ".join(
f"{k}:{len(views[k]['nodes'])}n/{len(views[k]['edges'])}e" for k in keys)
print(f"wrote {len(views)} views ({done} games) -> {dest}\n {summary}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python
"""Bootstrap stability of the two-pass sub-archetype clustering.
For each color pair:
* reference clustering (the same two-pass method as build_templates_contract.py)
-> per cluster, the top-12 "defining cards" by excess inclusion P(c|cluster) - P(c|pair)
* B bootstrap resamples (with replacement): recluster, match each reference cluster to
the resample cluster with the largest deck overlap, Jaccard of the defining-card sets
* report mean Jaccard per cluster, plus how often each defining card shows up
Output: .tmp/stability.json
"""
from __future__ import annotations
import argparse
import json
import math
import random
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import build_templates_contract as B # noqa: E402
SNAP = ROOT / "data/17lands/FRA20261007"
OUT = ROOT / "value/FRA20261007/stability.json"
B_BOOT = 20
TOPN = 12
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
WEIGHT: dict = {}
RARITY: dict = {}
def load_cards():
data = json.loads((SNAP / "stats/card_data.json").read_text(encoding="utf-8"))["data"]
id2name = {c["mtga_id"]: c["name"] for c in data}
for c in data:
WEIGHT[c["name"]] = 1.0 + math.log(max(1, c.get("game_count") or 1))
RARITY[c["name"]] = (c.get("rarity") or "").lower()
for line in (SNAP / "drafts/draft_picks.jsonl").read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
r = json.loads(line)
for cid, m in (r.get("cards") or {}).items():
if m.get("name"):
id2name.setdefault(int(cid), m["name"])
return id2name
def feats(cnts, vocab):
idx = {nm: i for i, nm in enumerate(vocab)}
n = len(cnts)
df = Counter()
for c in cnts:
for nm in c:
if nm in idx:
df[nm] += 1
disc = {nm: 4.0 * (df[nm] / n) * (1 - df[nm] / n) for nm in vocab}
def X(weights):
out = []
for c in cnts:
v = [0.0] * len(vocab)
for nm, cc in c.items():
if nm in idx:
v[idx[nm]] = cc * WEIGHT.get(nm, 1.0) * weights.get(nm, 0.0)
L = math.sqrt(sum(x * x for x in v)) or 1.0
out.append([x / L for x in v])
return out
def pick(XX):
D = B.gram(XX)
b = None
for k in (2,):
if k >= n:
continue
a = B.kmeans(XX, k)
if min(Counter(a).values()) < 3:
continue
s = B.silhouette(D, a, k)
if b is None or s > b[2]:
b = (k, a, s)
return b
def outlier(X, assign, kk):
# (其他) = outlier relative to the deck's OWN cluster (mean + 2*sd of that cluster)
dim = len(vocab)
gg = defaultdict(list)
for i, a in enumerate(assign):
gg[a].append(i)
cent = {g: [sum(X[i][j] for i in gg[g]) / len(gg[g]) for j in range(dim)] for g in gg}
d2c = [math.sqrt(sum((X[i][j] - cent[assign[i]][j]) ** 2 for j in range(dim))) for i in range(n)]
flag = [False] * n
for g in gg:
ds = [d2c[i] for i in gg[g]]
m = sum(ds) / len(ds)
sd = (sum((x - m) ** 2 for x in ds) / len(ds)) ** 0.5 or 1.0
for i in gg[g]:
if d2c[i] > m + 2.0 * sd:
flag[i] = True
return [kk if flag[i] else assign[i] for i in range(n)]
X1v = X(disc)
b1 = pick(X1v)
if b1 is None:
return None
a1 = outlier(X1v, b1[1], b1[0]) # (其他) joins the weighting
g1 = defaultdict(list)
for i, aa in enumerate(a1):
g1[aa].append(i)
inc = {nm: {g: 0 for g in g1} for nm in vocab}
for g, mem in g1.items():
for i in mem:
for nm in cnts[i]:
if nm in inc:
inc[nm][g] += 1
spec = {}
for nm in vocab:
pbar = df[nm] / n
spec[nm] = sum((len(g1[g]) / n) * ((inc[nm][g] / len(g1[g])) - pbar) ** 2 for g in g1)
mx = max(spec.values()) or 1.0
spec = {nm: v / mx for nm, v in spec.items()}
X2 = X(spec)
b2 = pick(X2)
if b2 is not None:
k, assign, Xf = b2[0], b2[1], X2
else:
k, assign, Xf = b1[0], b1[1], X1v
return k + 1, outlier(Xf, assign, k)
def defining(cnts, assign, k, vocab, n):
pbar = {nm: sum(1 for c in cnts if nm in c) / n for nm in vocab}
out = {}
for g in range(k + 1):
mem = [i for i in range(len(cnts)) if assign[i] == g]
if not mem:
continue
ex = {nm: sum(1 for i in mem if nm in cnts[i]) / len(mem) - pbar[nm] for nm in vocab}
out[g] = [nm for nm, _ in sorted(ex.items(), key=lambda x: -x[1])[:TOPN]]
return out
def main() -> int:
id2name = load_cards()
by_pair = defaultdict(list)
for line in (SNAP / "trophies/trophies_decks.jsonl").read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
d = json.loads(line)
pair = re.sub(r"[^A-Z]", "", d.get("colors") or "")
if len(pair) != 2:
continue
c = Counter()
for e in d["maindeck"]:
nm = id2name.get(e["mtga_id"])
if nm and nm not in BASICS and RARITY.get(nm) not in ("rare", "mythic"):
c[nm] += e["count"]
by_pair[pair].append(c)
res = {}
for pair, cnts in sorted(by_pair.items()):
n = len(cnts)
df = Counter()
for c in cnts:
for nm in c:
df[nm] += 1
vocab = sorted(nm for nm, cc in df.items() if cc / n >= 0.05)
base = feats(cnts, vocab)
if base is None:
continue
k, assign = base
ref = defining(cnts, assign, k, vocab, n)
boot = defaultdict(lambda: defaultdict(int)) # ref_cluster -> card -> times in top-N
jacs = defaultdict(list)
for b in range(B_BOOT):
sample = [random.randrange(n) for _ in range(n)]
sub = [cnts[i] for i in sample]
got = feats(sub, vocab)
if got is None:
continue
k2, a2 = got
def2 = defining(sub, a2, k2, vocab, n)
# map each reference cluster to the resample cluster with max deck overlap
for gc, cards_ref in ref.items():
sref = {i for i in range(n) if assign[i] == gc}
best_c2, best_ov = None, -1
for gc2 in def2:
sb = set(sample[j] for j in range(n) if a2[j] == gc2)
ov = len(sref & sb)
if ov > best_ov:
best_ov, best_c2 = ov, gc2
if best_c2 is None or not def2[best_c2]:
continue
cards_b = def2[best_c2]
jac = len(set(cards_ref) & set(cards_b)) / len(set(cards_ref) | set(cards_b))
jacs[gc].append(jac)
for nm in cards_b:
boot[gc][nm] += 1
clusters = []
for gc in sorted(ref):
js = jacs.get(gc) or [0.0]
clusters.append({
"c": gc, "n": sum(1 for i in range(n) if assign[i] == gc),
"jac": round(sum(js) / len(js), 3),
"cards": [{"name": nm, "freq": round(boot[gc].get(nm, 0) / B_BOOT, 2)} for nm in ref[gc]],
})
mean = round(sum(c["jac"] for c in clusters) / len(clusters), 3)
cmap = {}
for gc in ref:
for nm in ref[gc]:
cmap[nm] = max(cmap.get(nm, 0.0), boot[gc].get(nm, 0) / B_BOOT)
res[pair] = {"mean": mean, "clusters": clusters, "cards": cmap}
print(f"{pair}: 稳定性 {mean:.2f} " + " ".join(f"簇{c['c']}={c['jac']:.2f}" for c in clusters))
OUT.write_text(json.dumps(res, ensure_ascii=False), encoding="utf-8")
overall = sum(v["mean"] for v in res.values()) / len(res)
print(f"\n整体平均稳定性 {overall:.3f} -> {OUT}")
return 0
if __name__ == "__main__":
_ap = argparse.ArgumentParser()
_ap.add_argument("--snapshot", required=True)
_ap.add_argument("--out", required=True)
_a = _ap.parse_args()
SNAP = Path(_a.snapshot)
OUT = Path(_a.out) / "stability.json"
raise SystemExit(main())
+11 -4
View File
@@ -39,10 +39,17 @@ def primary_pair(colors):
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)
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
File diff suppressed because it is too large Load Diff
+457
View File
@@ -0,0 +1,457 @@
#!/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()
+1 -1
View File
@@ -647,7 +647,7 @@ def cmd_replays(args) -> int:
futures = [pool.submit(worker, g) for g in pending]
for i, fut in enumerate(as_completed(futures), 1):
fut.result()
if not args.quiet and (i % 25 == 0 or i == len(futures)):
if not args.quiet and (i % 200 == 0 or i == len(futures)):
el = time.time() - t0
print(f" {i}/{len(futures)} ok={stats['ok']} failed={stats['failed']} "
f"{i / el if el else 0:.1f}/s", file=sys.stderr)
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Download a set's card images to data/card_images/<SET>/ for LOCAL reports.
New sets (e.g. TRK) have no images in `data/mtgch`, so the template pages fall
back to remote 17lands CDN URLs. This script caches them locally so the report
works offline and loads instantly.
Image source: `data/scryfall/<SET>.json` (see fetch_scryfall.py) `image_url`,
with a fallback to the 17lands `draft_picks.jsonl` image_url.
Filename: `<slugify(name)>.jpg|webp` — MUST match `render_templates_html.slugify`
(the renderer looks up `data/card_images/<SET>/<slug>.<ext>`).
Usage:
python scripts/fetch_card_images.py --set TRK
python scripts/fetch_card_images.py --set TRK --snapshot data/17lands/TRK20261114 -w 8
"""
from __future__ import annotations
import argparse
import http.client
import json
import sys
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from render_templates_html import slugify # noqa: E402
UA = {"User-Agent": "MtgaAnalysis/1.0"}
def _download(url: str, dest: Path, tries: int = 4) -> bool:
if dest.exists() and dest.stat().st_size > 1000:
return False
tmp = dest.with_suffix(dest.suffix + ".part")
last = None
for i in range(tries):
try:
req = urllib.request.Request(url, headers=UA)
with urllib.request.urlopen(req, timeout=60) as r:
data = r.read()
if len(data) < 500:
raise ValueError(f"too small ({len(data)} bytes)")
tmp.write_bytes(data)
tmp.replace(dest)
return True
except (urllib.error.HTTPError, http.client.IncompleteRead,
ConnectionError, TimeoutError, OSError, ValueError) as e:
last = e
time.sleep(1.5 * (i + 1))
print(f" [failed] {dest.name}: {last}", file=sys.stderr)
return False
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--set", required=True, help="17lands set code, e.g. TRK")
ap.add_argument("--snapshot", default=None,
help="可选:data/17lands/<snap>,用它补 draft_picks 的 image_url")
ap.add_argument("--out", default="data/card_images")
ap.add_argument("-w", "--workers", type=int, default=8)
a = ap.parse_args()
setcode = a.set.upper()
urls: dict[str, str] = {}
sf = ROOT / "data" / "scryfall" / f"{setcode}.json"
if sf.exists():
for name, rec in json.loads(sf.read_text(encoding="utf-8")).items():
u = (rec or {}).get("image_url")
if u:
urls.setdefault(name, u)
snap = Path(a.snapshot) if a.snapshot else None
dp = (snap / "drafts/draft_picks.jsonl") if snap else None
if dp and dp.exists():
for line in dp.open(encoding="utf-8"):
line = line.strip()
if not line:
continue
for m in (json.loads(line).get("cards") or {}).values():
nm, u = m.get("name"), m.get("image_url")
if nm and u:
urls.setdefault(nm, u)
if not urls:
raise SystemExit("no image urls: run scripts/fetch_scryfall.py first")
out_dir = ROOT / a.out / setcode
out_dir.mkdir(parents=True, exist_ok=True)
jobs = []
for name, u in urls.items():
sl = slugify(name).lower()
if not sl:
continue
ext = Path(u.split("?")[0]).suffix.lower() or ".jpg"
if ext not in (".jpg", ".jpeg", ".webp", ".png"):
ext = ".jpg"
jobs.append((u, out_dir / f"{sl}{ext}"))
print(f"[{setcode}] {len(urls)} cards -> {out_dir} (workers={a.workers})")
ok = 0
t0 = time.time()
with ThreadPoolExecutor(max_workers=a.workers) as pool:
futs = [pool.submit(_download, u, d) for u, d in jobs]
for i, f in enumerate(as_completed(futs), 1):
ok += 1 if f.result() else 0
if i % 50 == 0 or i == len(futs):
print(f" {i}/{len(futs)} new={ok} {i/(time.time()-t0):.1f}/s", flush=True)
print(f"done: {ok} new, {len(list(out_dir.iterdir()))} files in {out_dir}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Fetch a set's card data from Scryfall into data/scryfall/<SET>.json.
The local `data/mtgch` card library is often incomplete for a brand-new set
(e.g. TRK: 117/336 cards), which starves `mech_tags` / `types` in
`build_templates_contract.py`. Scryfall has every card's Oracle text, so we
cache it here and let the build merge it in for names mtgch doesn't cover.
Output: {"<SET>": {"<card name>": {oracle, keywords, mana_cost, cmc,
types, color_identity, rarity, image_url, layout}}}
Usage:
python scripts/fetch_scryfall.py --set TRK # scryfall set code = trk
python scripts/fetch_scryfall.py --set TRK --scryfall-set trk
"""
from __future__ import annotations
import argparse
import http.client
import json
import re
import time
import urllib.error
import urllib.request
from pathlib import Path
API = "https://api.scryfall.com/cards/search"
UA = {"User-Agent": "MtgaAnalysis/1.0", "Accept": "application/json"}
def _get(url: str, tries: int = 6) -> dict:
last = None
for i in range(tries):
try:
req = urllib.request.Request(url, headers=UA)
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
if e.code == 404:
raise SystemExit(f"not found: {url}")
last = e
time.sleep(2 * (i + 1))
except (http.client.IncompleteRead, ConnectionError, TimeoutError, OSError) as e:
last = e
time.sleep(2 * (i + 1))
raise SystemExit(f"gave up after {tries}: {url} ({last})")
def _types(type_line: str) -> list[str]:
left = (type_line or "").split("—")[0]
return [w for w in re.split(r"[\s/]+", left) if w]
def _record(c: dict) -> dict:
faces = c.get("card_faces") or []
oracle = c.get("oracle_text") or " ".join(f.get("oracle_text", "") for f in faces)
mc = c.get("mana_cost") or (faces[0].get("mana_cost") if faces else "") or ""
img = (c.get("image_uris") or {}).get("normal")
if not img and faces:
img = (faces[0].get("image_uris") or {}).get("normal")
return {
"oracle": oracle,
"keywords": c.get("keywords") or [],
"mana_cost": mc,
"cmc": c.get("cmc"),
"types": _types(c.get("type_line", "")),
"color_identity": c.get("color_identity") or [],
"rarity": c.get("rarity"),
"image_url": img,
"layout": c.get("layout"),
}
def fetch(set_code: str, scryfall_set: str) -> dict:
out: dict = {}
url = f"{API}?q=set:{scryfall_set}&unique=cards&order=set"
n_pages = 0
while url:
d = _get(url)
for c in d.get("data") or []:
rec = _record(c)
out[c["name"]] = rec
# also index each face name so "A" resolves to "A // B"
for f in c.get("card_faces") or []:
if f.get("name"):
out.setdefault(f["name"], rec)
n_pages += 1
url = d.get("next_page")
print(f" page {n_pages}: +{len(d.get('data') or [])} (total {len(out)})", flush=True)
if url:
time.sleep(0.1) # be polite (<10 req/s)
return out
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--set", required=True, help="17lands set code, e.g. TRK")
ap.add_argument("--scryfall-set", default=None,
help="scryfall set code (default: --set lowercased)")
ap.add_argument("--out", default="data/scryfall")
ap.add_argument("--merge", action="store_true",
help="merge into existing <SET>.json instead of overwriting")
a = ap.parse_args()
setcode = a.set.upper()
sf = (a.scryfall_set or setcode).lower()
data = fetch(setcode, sf)
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
p = out / f"{setcode}.json"
if a.merge and p.exists():
old = json.loads(p.read_text(encoding="utf-8"))
old.update(data)
data = old
p.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"\nwrote {len(data)} cards -> {p} (scryfall set '{sf}')")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+11 -4
View File
@@ -35,10 +35,17 @@ def primary_pair(colors):
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 None
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 components(nodes, edges):
parent = {n: n for n in nodes}
+11 -4
View File
@@ -33,10 +33,17 @@ def primary_pair(colors):
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 None
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 norm(a):
return math.sqrt(sum(v * v for v in a))
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""把多个 17lands 快照目录合并成一份(按主键去重)。
用途:17Lands 的奖杯窗口是滚动的,单次抓取只覆盖约 1~2 天;定期抓取后把各批
` data/17lands/<SET><DATE>/ ` 合并,得到更大的样本再重建 `value/`。
用法(可复现):
python scripts/merge_snapshots.py --out data/17lands/FRA20261011 \
data/17lands/FRA20261007 data/17lands/FRA20261011
规则:
* jsonl(index/decks/drafts):按各自主键去重,追加写出;已去重的输入会被跳过。
* draftdata/ :文件名 = draft_id,直接并集拷贝。
* replays/ :以 `replay_index.jsonl` 的 history_path 为准并集拷贝 *.json.gz。
* stats/ :默认保留第一个存在的(聚合数据不合并;可用 --stats-from 指定)。
* 不删除任何源文件;--out 与某个输入相同则原地合并(先写 .orig 备份)。
"""
from __future__ import annotations
import argparse
import json
import shutil
from pathlib import Path
# 每个 jsonl 的主键
KEYS = {
"trophies/trophies_index.jsonl": lambda r: r.get("aggregate_id"),
"trophies/trophies_decks.jsonl": lambda r: (r.get("aggregate_id"), r.get("deck_index")),
"drafts/draft_picks.jsonl": lambda r: r.get("draft_id"),
"drafts/event_details.jsonl": lambda r: r.get("draft_id"),
}
def load_jsonl(p: Path):
if not p.exists():
return []
out = []
for ln in p.read_text(encoding="utf-8").splitlines():
if ln.strip():
try:
out.append(json.loads(ln))
except json.JSONDecodeError:
pass
return out
def merge_jsonl(out_root: Path, sources: list[Path], rel: str, keyfn) -> tuple[int, int]:
seen, rows = set(), []
for s in sources:
for r in load_jsonl(s / rel):
k = keyfn(r)
if k is None or k in seen:
continue
seen.add(k)
rows.append(json.dumps(r, ensure_ascii=False))
if not rows:
return 0, 0
dest = out_root / rel
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists() and dest not in [None]:
shutil.copy2(dest, dest.with_suffix(dest.suffix + ".orig")) if not dest.with_suffix(
dest.suffix + ".orig").exists() else None
dest.write_text("\n".join(rows) + "\n", encoding="utf-8")
return len(seen), len(rows)
def merge_dir(out_root: Path, sources: list[Path], rel: str, suffix: str) -> int:
dest = out_root / rel
dest.mkdir(parents=True, exist_ok=True)
have = {p.name for p in dest.glob("*" + suffix)}
added = 0
for s in sources:
d = s / rel
if not d.exists():
continue
for f in d.glob("*" + suffix):
if f.name not in have:
shutil.copy2(f, dest / f.name)
have.add(f.name)
added += 1
return added
def merge_replays(out_root: Path, sources: list[Path]) -> tuple[int, int]:
"""以 replay_index.jsonl 的 history_path 并集拷贝 gz。"""
paths, seen = [], set()
for s in sources:
for r in load_jsonl(s / "replays/replay_index.jsonl"):
hp = r.get("history_path")
if hp and hp not in seen:
seen.add(hp)
paths.append(r)
# 源里可能只有 gz 没有 index:也扫一遍
for gz in (s / "replays").rglob("*.json.gz"):
hp = gz.relative_to(s / "replays").as_posix()[:-len(".json.gz")]
if hp not in seen:
seen.add(hp)
paths.append({"history_path": hp})
dest = out_root / "replays"
dest.mkdir(parents=True, exist_ok=True)
(dest / "replay_index.jsonl").write_text(
"\n".join(json.dumps(r, ensure_ascii=False) for r in paths) + "\n", encoding="utf-8")
have = {p.relative_to(dest).as_posix()[:-len(".json.gz")] for p in dest.rglob("*.json.gz")}
missing = [r["history_path"] for r in paths if r["history_path"] not in have]
added = 0
for hp in missing:
for s in sources:
src = s / "replays" / (hp + ".json.gz")
if src.exists():
d = dest / (hp + ".json.gz")
d.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, d)
added += 1
break
return len(paths), added
def main() -> int:
ap = argparse.ArgumentParser(description="合并多个 17lands 快照(去重)")
ap.add_argument("sources", nargs="+", help="源快照目录,按优先级从左到右")
ap.add_argument("--out", required=True, help="输出/原地合并目录")
ap.add_argument("--stats-from", default=None, help="stats/ 从哪个源取(默认第一个有 stats 的)")
ap.add_argument("--skip-replays", action="store_true")
a = ap.parse_args()
sources = [Path(s) for s in a.sources]
out_root = Path(a.out)
out_root.mkdir(parents=True, exist_ok=True)
for rel, keyfn in KEYS.items():
u, n = merge_jsonl(out_root, sources, rel, keyfn)
print(f" {rel:32s} -> {u} unique")
n = merge_dir(out_root, sources, "draftdata", ".json")
print(f" draftdata/ +{n} files -> "
f"{len(list((out_root / 'draftdata').glob('*.json')))}")
if not a.skip_replays:
total, added = merge_replays(out_root, sources)
print(f" replays/ index={total} +{added} gz -> "
f"{len(list((out_root / 'replays').rglob('*.json.gz')))}")
# stats:取一个源(聚合数据不合并)
if not (out_root / "stats/card_data.json").exists():
src = Path(a.stats_from) if a.stats_from else next(
(s for s in sources if (s / "stats/card_data.json").exists()), None)
if src:
shutil.copytree(src / "stats", out_root / "stats", dirs_exist_ok=True)
print(f" stats/ copied from {src}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""把 bin/advisor/v2.0/advisor pick 的结果 + 每张牌的 IIH / ALSA 排成人看的表。
用法(state JSON 与 advisor 完全一致):
python scripts/pick_view.py --state state.json
echo '{"pack":[...],"pool":[...]}' | python scripts/pick_view.py
字段说明:
GIH = ever_drawn_win_rate(见过就赢的胜率)
IIH = GIH − GNS(never_drawn_win_rate),即“置入手中带来的胜率提升”
ALSA = avg_seen(平均最后被看到的位置,越小越早被抢)
score = advisor 跨 20 个思路加权后的分(决定建议抓哪张)
value = 这张牌在自己最合思路里的分
"""
import argparse
import importlib.machinery
import importlib.util
import json
import sys
from collections import Counter
from pathlib import Path
m_P0 = 0.5626 # advisor 的 P0,用于缺 GIH 时的粗估
ROOT = Path(__file__).resolve().parent.parent
def load_advisor():
_c = sorted((ROOT / "bin" / "advisor").glob("v*/advisor"))
_p = _c[-1] if _c else (ROOT / "bin" / "advisor" / "v2.0" / "advisor")
loader = importlib.machinery.SourceFileLoader("advisor", str(_p))
spec = importlib.util.spec_from_loader("advisor", loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
def iih(d, name):
"""IIH = GIH − GNS(百分点)。缺字段就退回 drawn_improvement_win_rate。"""
c = d.cdata.get(name) or {}
gih = c.get("ever_drawn_win_rate")
gns = c.get("never_drawn_win_rate")
if gih is not None and gns is not None:
return (gih - gns) * 100
imp = c.get("drawn_improvement_win_rate")
if imp is not None:
return imp * 100
if gih is None and c.get("win_rate") is not None:
return (d.gjwr(name) - m_P0) * 100 # 只能给个粗略下界,带 * 标记
return None
def fmt(v, width=6, digits=1, plus=True):
if v is None:
return " " * (width - 1) + "—"
return ("%+*.*f" if plus else "%*.*f") % (width, digits, v)
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", default="FRA20261011")
ap.add_argument("--state", default="-")
a = ap.parse_args()
adv = load_advisor()
d = adv.Data(a.snapshot)
st = json.load(open(a.state, encoding="utf-8")) if a.state != "-" else json.load(sys.stdin)
pack = [d.name_of(c) for c in st.get("pack") or []]
bad = d.unknown(pack + [d.name_of(c) for c in (st.get("pool") or [])])
if bad:
print("无法识别的牌:", bad)
return 2
scored, fits, weights = adv.score_cards(d, pack, adv.pool_counts(st.get("pool")), st.get("colors"))
best_slug = max(fits, key=lambda s: fits[s]) if fits else None
def minmax(slug, nm):
"""该牌在指定思路里的 min/max_copies(实测的同名张数区间)。"""
if slug not in d.templates:
return 0, 0
c = d.templates[slug]["_cardmap"].get(nm)
return int((c or {}).get("min_copies") or 0), int((c or {}).get("max_copies") or 0)
print("## 包内 %d 张(按 score 降序)\n" % len(pack))
print("| # | 牌 | 费用 | GIH | **IIH** | **ALSA** | **score** | value | min/max | 该牌最合的思路 |")
print("|---|---|---|---|---|---|---|---|---|---|")
for i, r in enumerate(scored, 1):
nm = r["name"]
c = d.cdata.get(nm) or {}
gih = c.get("ever_drawn_win_rate")
tag = ""
if gih is None and c.get("win_rate") is not None:
gih = d.gjwr(nm) # 17lands 没给 ever_drawn,用回归外推
tag = "*"
slug = r.get("archetype")
arch = d.templates[slug]["archetype_name"] if slug in d.templates else "—"
sel = " ← **建议**" if i == 1 else ""
mn, mx = minmax(slug, nm)
mm = "%d/%d" % (mn, mx) if mx else "—"
print("| %d | %s%s | `%s` | %s | %s | %s | **%.3f** | %.3f | %s | %s |" % (
i, nm, sel, d.mana_cost(nm) or "—",
(fmt(gih * 100, 5, 1, False) + tag) if gih is not None else fmt(None, 5, 1, False),
fmt(iih(d, nm), 5), fmt(c.get("avg_seen"), 5, 2, False),
r.get("score", 0), r.get("value", 0), mm, arch))
pool = adv.pool_counts(st.get("pool"))
pips = Counter()
for nm, n in pool.items():
if nm in adv.BASICS or adv.is_land(d, nm):
continue
for ch in d.req_colors(nm):
pips[ch] += n
print("\n## 牌池 %d 张 · 色符 %s\n" % (
sum(pool.values()), " · ".join("%s %d" % (k, v) for k, v in pips.most_common()) or "(空)"))
main = [s for s in d.index if not s.endswith("-Other")]
print("## 20 个思路的 fit(对同一副牌池)\n")
print("| 思路 | 色组 | fit | 权重 | 条形 |")
print("|---|---|---|---|---|")
top = max(fits.values()) if fits else 1
for s in sorted(main, key=lambda x: -fits.get(x, 0)):
t = d.templates[s]
bar = "█" * max(0, int(round(fits.get(s, 0) / top * 20))) if top > 0 else ""
print("| %s%s | %s | **%.3f** | %.3f | `%s` |" % (
t["archetype_name"], " ←" if s == max(fits, key=lambda k: fits[k]) else "",
(t.get("colors") or t["archetype"]).upper(), fits.get(s, 0), weights.get(s, 0), bar))
return 0
if __name__ == "__main__":
sys.exit(main())
+604
View File
@@ -0,0 +1,604 @@
#!/usr/bin/env python
"""Render <out>/card_graph.json into a standalone HTML report (reports/card_graph.html).
Views = __ALL__ plus one per deck colour pair (WU, UB, ...). Each view is
computed independently (own NPMI, own Louvain clusters, own layout).
"""
import argparse
import sys
import json
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _layout # noqa: E402
_ap = argparse.ArgumentParser()
_ap.add_argument("--out", required=True, help="e.g. value/FRA20261007")
_ap.add_argument("--snapshot", required=True, help="e.g. data/17lands/FRA20261007")
_ap.add_argument("--d3", default=None)
_args = _ap.parse_args()
OUT = Path(_args.out) / "reports" / "card_graph.html"
_layout.SET = _layout.set_of(_args.out)
_layout.ensure_assets(OUT.parent)
GRAPH = Path(_args.out) / "card_graph.json"
CARDS = Path(_args.out) / "cards.json"
raw = json.loads(GRAPH.read_text(encoding="utf-8"))
views_raw = raw["views"]
keys = raw.get("keys") or list(views_raw)
color_map = {}
if CARDS.exists():
for c in json.loads(CARDS.read_text(encoding="utf-8")).get("cards", []):
color_map[c["name"]] = c.get("color", "")
# 17lands "games played" per card (used for node size)
plays_map = {}
CD = Path(_args.snapshot) / "stats/card_data.json"
if CD.exists():
for c in json.loads(CD.read_text(encoding="utf-8"))["data"]:
plays_map[c["name"]] = c.get("game_count") or 0
PALETTE = ["#5a9fd4", "#d46a5a", "#5aa86b", "#d4b25a", "#a07fd4",
"#4fd0c0", "#d47fb0", "#8fbf4a", "#c0c0c0", "#e08a3c",
"#7f8fe0", "#d0d0d0"]
def build_view(key: str, v: dict) -> dict:
pairset = set(key) if key != "__ALL__" else None
nodes = []
for name, info in v["nodes"].items():
col = color_map.get(name, "")
splash = bool(pairset and (set(col) - pairset))
nodes.append({
"id": name,
"casts": info["casts"],
"games": info.get("cast_games", 0),
"plays": plays_map.get(name, info["casts"]),
"cl": info.get("cluster", -1),
"col": col,
"splash": splash,
})
edges = []
for e in v["edges"]:
if e.get("score", 0) <= 0:
continue
edges.append({
"s": e["a"], "t": e["b"],
"w": round(e["score"], 4),
"sr": e.get("npmi_strong", 0),
"st": e["strong"], "ef": e.get("effect", 0), "md": e["medium"],
})
cluster_rows = []
for row in v["clusters"]:
cluster_rows.append({
"id": row["cluster"], "size": row["size"], "casts": row["casts"],
"cards": row["cards"][:16], "colors": row.get("colors", []),
})
cl_of = {n["id"]: n["cl"] for n in nodes}
cadj = {}
for e in edges:
a, b = cl_of.get(e["s"], -1), cl_of.get(e["t"], -1)
if a < 0 or b < 0 or a == b:
continue
key = tuple(sorted((a, b)))
cadj[key] = cadj.get(key, 0.0) + e["w"]
best = {}
nmap = {n["id"]: n for n in nodes}
for e in edges:
if e["st"] <= 0:
continue
for a, b in ((e["s"], e["t"]), (e["t"], e["s"])):
cur = best.get(a)
if cur is None or e["st"] > cur[1]:
best[a] = (b, e["st"])
strong_npmi = sorted((e for e in edges if e["st"] > 0),
key=lambda e: -e["sr"])[:25]
meta = dict(v["meta"])
return {
"nodes": nodes, "edges": edges, "clusters": cluster_rows,
"cadj": [[list(k), round(val, 3)] for k, val in cadj.items()],
"bestPartner": best, "strongNpmi": strong_npmi, "meta": meta,
}
views = {k: build_view(k, views_raw[k]) for k in keys if k in views_raw}
keys = ["__ALL__"] + sorted((k for k in keys if k != "__ALL__"),
key=lambda k: -views[k]["meta"]["games"])
payload = {"keys": keys, "views": views, "palette": PALETTE}
html = r"""<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>__SET__ 牌间关系图 · 统计实验报告</title>
<style>
:root{--bg:#0e1116;--panel:#161b22;--panel2:#1c2230;--line:#2a3240;
--txt:#e6edf3;--dim:#8b98a8;--accent:#5a9fd4;}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--txt);
font:14px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Noto Sans SC",sans-serif}
a{color:var(--accent)}
header{padding:30px 40px 18px;border-bottom:1px solid var(--line);
background:linear-gradient(180deg,#182130,#0e1116)}
h1{margin:0 0 6px;font-size:25px}
.sub{color:var(--dim);font-size:13px}
.wrap{max-width:1280px;margin:0 auto;padding:22px 40px 80px}
section{margin:30px 0}
h2{font-size:18px;margin:0 0 13px;padding-left:10px;border-left:3px solid var(--accent)}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-top:16px}
.stat{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:12px 14px}
.stat .v{font-size:22px;font-weight:600;color:#fff}
.stat .l{color:var(--dim);font-size:12px;margin-top:2px}
.grid2{display:grid;grid-template-columns:1fr;gap:18px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:16px}
table{width:100%;border-collapse:collapse;font-size:13px}
th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line)}
th{color:var(--dim);font-weight:500;position:sticky;top:0;background:var(--panel)}
tr:hover td{background:var(--panel2)}
.num{text-align:right;font-variant-numeric:tabular-nums}
.tier .tag{font-weight:600}
.groups{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px}
.groups button{background:#1b2029;color:#cfd8e6;border:1px solid var(--line);
border-radius:8px;padding:4px 12px;cursor:pointer;font-size:13px}
.groups button.on{background:#2f5f96;border-color:#4a86c9;color:#fff}
.cl-card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:13px;margin-bottom:11px}
.cl-head{display:flex;align-items:center;gap:9px;margin-bottom:7px}
.dot{width:12px;height:12px;border-radius:50%;flex:0 0 auto}
.cl-title{font-weight:600}
.cl-meta{color:var(--dim);font-size:12px}
.bar{display:flex;height:8px;border-radius:5px;overflow:hidden;margin:7px 0 9px;background:#0a0d12}
.bar span{display:block;height:100%}
.chips{display:flex;flex-wrap:wrap;gap:6px}
.chip{background:var(--panel2);border:1px solid var(--line);border-radius:20px;padding:2px 10px;font-size:12px}
.controls{display:flex;flex-wrap:wrap;gap:16px;align-items:center;margin-bottom:12px}
.controls label{color:var(--dim);font-size:12px;display:flex;gap:7px;align-items:center}
input[type=range]{width:130px}
canvas{display:block;width:100%;height:640px;background:radial-gradient(circle at 50% 45%,#141b26,#0b0e13);
border:1px solid var(--line);border-radius:12px;cursor:grab}
.legend{display:flex;flex-wrap:wrap;gap:13px;margin-top:10px;font-size:12px;color:var(--dim)}
.legend span{display:flex;gap:6px;align-items:center}
.heat{display:grid;gap:3px;font-size:11px}
.heat div{aspect-ratio:1;border-radius:4px;display:flex;align-items:center;justify-content:center;color:#cdd6e0}
.note{color:var(--dim);font-size:12.5px}
.note li{margin:4px 0}
code{background:#0a0d12;border:1px solid var(--line);border-radius:5px;padding:1px 5px;font-size:12px}
#tip{position:fixed;pointer-events:none;background:#0a0d12ee;border:1px solid var(--line);
border-radius:8px;padding:8px 10px;font-size:12px;opacity:0;transition:opacity .1s;z-index:9;max-width:260px}
#toast{position:fixed;left:50%;bottom:28px;transform:translateX(-50%);background:#2f5f96;color:#fff;
padding:9px 18px;border-radius:9px;font-size:13px;opacity:0;transition:opacity .2s;pointer-events:none;z-index:20}
.kbd{color:var(--dim)}
.empty{color:var(--dim);padding:20px;text-align:center}
__LAYOUT_CSS__
</style>
</head>
<body>
__BANNER__
<main class="wrap">
<header>
<h1>__SET__ 牌间关系图 · 统计实验报告</h1>
<div class="sub">数据源:17Lands GRE 逐回合回放 · 分层关系(强/效果/中/弱/微弱)→ NPMI → 迭代扩散 → Louvain 聚落 · <b>按套牌色组分别计算</b></div>
<div class="stats" id="stats"></div>
</header>
<div class="wrap">
<section>
<h2>1 · 图模型:分层关系</h2>
<div class="card">
<table class="tier">
<thead><tr><th>层</th><th>含义</th><th>从回放提取的信号</th></tr></thead>
<tbody>
<tr><td><span class="tag" style="color:#5a9fd4">strong</span></td>
<td>打出 A 时,场上的 B 触发/连锁</td>
<td><code>Ability / Token / TriggerHolder</code> 的 <code>parentId</code> 回溯源卡;同控制者且 B≠A</td></tr>
<tr><td><span class="tag" style="color:#4fd0c0">effect</span></td>
<td>打出 A 时,场上的 B 产生效果</td>
<td>counter / 贴附 / 复制 / 指定等 annotation 的 <code>affectorId</code> 回溯源卡 B</td></tr>
<tr><td><span class="tag" style="color:#5aa86b">medium</span></td>
<td>同回合、同玩家出牌</td><td><code>(game, turn, controller)</code> 两两配对</td></tr>
<tr><td><span class="tag" style="color:#d4b25a">weak</span></td>
<td>同局、同玩家出牌</td><td><code>(game, controller)</code> 两两配对</td></tr>
<tr><td><span class="tag" style="color:#a07fd4">veryweak</span></td>
<td>同一牌池</td><td><code>event_details.draft_pool</code> 两两配对</td></tr>
</tbody>
</table>
<p class="note" style="margin:12px 0 0">
只用<b>当前色组</b>的套牌(按 <code>event_details.deck_colors</code> 主色对分组)重新计算 NPMI → 两步扩散
<code>S←(1-α)S+α·N·S·N</code> → 每卡 top-20 边 → Louvain。节点权重 = 施放次数。
</p>
</div>
</section>
<section>
<h2>2 · 交互式牌图 <span class="kbd" id="viewMeta"></span></h2>
<div class="groups" id="groups"></div>
<div class="groups" id="colorGroups">
<span class="kbd" style="align-self:center;margin-right:4px">着色</span>
<button data-v="cluster" class="on">按聚落</button>
<button data-v="color">按颜色</button>
<button data-v="casts">按出场次数</button>
</div>
<div class="controls">
<label>边阈值 <input type="range" id="edgeThresh" min="0" max="1" step="0.005">
<span id="threshVal" class="kbd"></span></label>
<label><input type="checkbox" id="strongOnly"> 只看强关系边</label>
<label><input type="checkbox" id="hideIsolated" checked> 隐藏无边的牌</label>
<label><input type="checkbox" id="labels"> 显示标签</label>
<label>吸引力 <input type="range" id="attract" min="0.5" max="4" step="0.1" value="1.8">
<span id="attractVal" class="kbd">1.8</span></label>
<label>排斥力 <input type="range" id="repel" min="0.5" max="6" step="0.1" value="2.8">
<span id="repelVal" class="kbd">2.8</span></label>
<label>分槽 <input type="range" id="clgrav" min="0" max="0.6" step="0.01" value="0.12">
<span id="clgravVal" class="kbd">0.12</span></label>
<span class="kbd" id="edgeCount"></span>
</div>
<canvas id="cv"></canvas>
<div class="legend" id="legend"></div>
<p class="note" style="margin-top:8px">节点大小∝17Lands 出场次数;拖动阈值会自动隐藏没有可见边的牌。拖拽节点微调布局,滚轮缩放。</p>
</section>
<section>
<h2>3 · 聚落(Louvain 社区)</h2>
<div id="clusterGrid"></div>
</section>
<section>
<h2>4 · 聚落间联系强度</h2>
<div class="card"><div class="note" style="margin-bottom:10px">行/列为聚落,色深 = 两簇之间所有边的分数之和(归一化)。</div>
<div id="heat"></div></div>
</section>
<section>
<h2>5 · 强协同(按 NPMI 排序)</h2>
<div class="card"><table id="synTable">
<thead><tr><th>组合</th><th class="num">NPMI</th><th class="num">强次数</th><th class="num">效果</th></tr></thead>
<tbody></tbody></table></div>
</section>
<section>
<h2>6 · 已知偏差与后续</h2>
<div class="card"><ul class="note">
<li>触发按“上次施放 → 同一控制者下次施放”归因;中间夹激活异能可能误挂。</li>
<li>静态/领主效应(“你操控的生物 +1/+1”等)不产生逐事件信号,事件法无法捕捉。</li>
<li>通用 pump(由正在结算的咒语自身产生)按设计排除。</li>
<li>仅使用 17Lands 登录账号本人的对局(seat),且只落地 2819/9041 局,存在奖杯对局偏差。</li>
</ul></div>
</section>
</div>
<div id="tip"></div>
<div id="toast"></div>
<script>__D3__</script>
<script>
const DATA = __PAYLOAD__;
const m0 = DATA.views['__ALL__'].meta;
const MTG = {W:'#e9dcae',U:'#4f9fd8',B:'#8a7f9c',R:'#d95d4e',G:'#57a86b'};
function hex2rgb(h){h=h.replace('#','');return [parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)];}
/* ---------- mutable view state ---------- */
let curView='__ALL__', V=null;
let N=[], L=[], nameIdx={}, MAXW=1, CL_COLORS={}, bestPartner={}, CLUSTERS=[], CADJ=[];
let colorMode='cluster', thresh=0.1, strongOnly=false, showLabels=false, hideIsolated=true;
let GAMMA=1.8, SPRING=0.5, REPMUL=2.8, REP_BASE=700, CLGRAV=0.12, ANCHOR={}, MAXPLAYS=1;
let drag=null, panning=null, last=null, scale=1, ox=0, oy=0, downNode=null, downPt=null;
const W=1000,H=640;
function colorOf(n, mode){
if(mode==='cluster') return CL_COLORS[n.cl]||'#888';
if(mode==='color'){
const c=(n.col||'').split('').filter(x=>MTG[x]);
if(!c.length) return '#9aa4b0';
let r=0,g=0,b=0; c.forEach(x=>{const t=hex2rgb(MTG[x]);r+=t[0];g+=t[1];b+=t[2];});
return `rgb(${r/c.length|0},${g/c.length|0},${b/c.length|0})`;
}
const t=Math.min(1,(n.plays||0)/MAXPLAYS);
const v=Math.round(60+t*195);
return `rgb(${v/2|0},${80+t*120|0},${180+t*60|0})`;
}
function initPositions(){
N.forEach((n,i)=>{
const a=i*2.399963, r=Math.sqrt(i/N.length)*360;
n.x=W/2+Math.cos(a)*r; n.y=H/2+Math.sin(a)*r; n.vx=0; n.vy=0;
n.r=3+16*Math.sqrt((n.plays||0)/MAXPLAYS); // 17lands play count -> radius
});
}
/* ---------- d3-force layout ----------
link force: strong edge -> short distance + high strength (atomic bond)
charge : global repulsion
repel : extra Coulomb repulsion between un-connected pairs
collide : keep circles apart, center: gravity to canvas middle */
let sim=null;
function buildLayout(){
if(sim){ sim.on("tick",null); sim.stop(); }
initPositions();
const EK=new Map();
for(const l of L){ const k=l.s*1000000+l.t; EK.set(k, Math.max(EK.get(k)||0, l.w)); }
const links=L.map(l=>({source:l.s, target:l.t, w:l.w, st:l.st}));
// cluster anchors on a ring -> each 聚落 gravitates to its own direction
ANCHOR={};
const K=Math.max(1, CLUSTERS.length);
CLUSTERS.forEach((c,i)=>{
const th=-Math.PI/2 + 2*Math.PI*i/K;
ANCHOR[c.id]={x:W/2+320*Math.cos(th), y:H/2+195*Math.sin(th)};
});
function forceRepel(){
let nodes=[];
function force(){
for(let i=0;i<nodes.length;i++){
const a=nodes[i];
for(let j=i+1;j<nodes.length;j++){
const b=nodes[j];
let dx=b.x-a.x, dy=b.y-a.y, d2=dx*dx+dy*dy+0.01;
if(d2>260000) continue;
if(EK.get(i*1000000+j)) continue; // connected -> link/charge handle it
const f=REP_BASE*REPMUL/d2, d=Math.sqrt(d2);
const fx=f*dx/d, fy=f*dy/d;
a.vx-=fx; a.vy-=fy; b.vx+=fx; b.vy+=fy;
}
}
}
force.initialize=n=>{nodes=n;};
return force;
}
sim=d3.forceSimulation(N)
.force("link", d3.forceLink(links).id((d,i)=>i)
.distance(l=>30+185*(1-Math.min(1,l.w/MAXW)))
.strength(l=>SPRING*Math.pow(Math.min(1,l.w/MAXW),GAMMA)*0.8+0.02))
.force("charge", d3.forceManyBody().strength(-90).distanceMax(420))
.force("repel", forceRepel())
.force("cx", d3.forceX(d=>(ANCHOR[d.cl]||{x:W/2}).x).strength(CLGRAV))
.force("cy", d3.forceY(d=>(ANCHOR[d.cl]||{y:H/2}).y).strength(CLGRAV))
.force("center", d3.forceCenter(W/2,H/2).strength(0.03))
.force("collide", d3.forceCollide(d=>d.r+2).iterations(1))
.alpha(1).alphaDecay(0.028)
.on("tick", draw);
}
/* ---------- render ---------- */
const cv=document.getElementById('cv'), ctx=cv.getContext('2d');
function resize(){
const dpr=window.devicePixelRatio||1;
cv.width=cv.clientWidth*dpr; cv.height=640*dpr;
ctx.setTransform(dpr,0,0,dpr,0,0);
draw();
}
window.addEventListener('resize',resize);
function draw(){
ctx.clearRect(0,0,cv.width,cv.height);
ctx.save(); ctx.translate(ox,oy); ctx.scale(scale,scale);
const vis=L.filter(l=> l.w>=thresh && (!strongOnly || l.st>0));
const active=new Set();
for(const l of vis){ active.add(l.s); active.add(l.t); }
for(const l of vis){
const a=N[l.s], b=N[l.t];
const t=Math.min(1,l.w/1.6);
ctx.strokeStyle = l.st>0 ? `rgba(90,159,212,${0.12+t*0.5})`
: `rgba(150,160,175,${0.05+t*0.22})`;
ctx.lineWidth = l.st>0 ? 0.6+t*1.6 : 0.4+t*0.9;
ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y); ctx.stroke();
}
for(let i=0;i<N.length;i++){
if(hideIsolated && !active.has(i)) continue;
const n=N[i];
const rr = n.splash ? n.r*0.55 : n.r; // splash cards drawn small + faint
ctx.beginPath(); ctx.arc(n.x,n.y,rr,0,6.2832);
ctx.fillStyle=colorOf(n,colorMode);
ctx.globalAlpha=(n===drag)?1:(n.splash?0.30:0.92); ctx.fill(); ctx.globalAlpha=1;
if(n.splash){ ctx.strokeStyle='#8b98a8'; ctx.lineWidth=0.6; ctx.stroke(); }
if(showLabels || n.casts>=650){
ctx.globalAlpha=n.splash?0.45:1;
ctx.fillStyle='#dfe7ef'; ctx.font='11px sans-serif'; ctx.textAlign='center';
ctx.fillText(n.id, n.x, n.y-rr-3);
ctx.globalAlpha=1;
}
}
if(CLGRAV>0.02){ // draw cluster anchor slots
for(const c of CLUSTERS){
const a=ANCHOR[c.id]; if(!a) continue;
ctx.beginPath(); ctx.arc(a.x,a.y,4,0,6.2832);
ctx.fillStyle=((CL_COLORS[c.id]||'#888')+'55'); ctx.fill();
ctx.fillStyle='#8b98a8'; ctx.font='10px sans-serif'; ctx.textAlign='center';
ctx.fillText('C'+c.id, a.x, a.y-8);
}
}
ctx.restore();
document.getElementById('edgeCount').textContent = vis.length+' 条可见边 / '+active.size+' 张牌';
}
function pos(ev){
const rect=cv.getBoundingClientRect();
return {x:(ev.clientX-rect.left-ox)/scale, y:(ev.clientY-rect.top-oy)/scale};
}
cv.addEventListener('mousedown',e=>{
const p=pos(e); let hit=null;
for(const n of N){ if((n.x-p.x)**2+(n.y-p.y)**2<(n.r+6)**2){hit=n;break;} }
downNode=hit; downPt={x:e.clientX,y:e.clientY};
if(hit){ drag=hit; drag.fx=drag.x; drag.fy=drag.y; if(sim) sim.alphaTarget(0.3).restart(); }
else {panning=true; last={x:e.clientX,y:e.clientY};}
cv.style.cursor='grabbing';
});
window.addEventListener('mousemove',e=>{
const tip=document.getElementById('tip');
if(drag){ const p=pos(e); drag.fx=p.x; drag.fy=p.y; drag.x=p.x; drag.y=p.y; draw(); return; }
if(panning && last){ ox+=e.clientX-last.x; oy+=e.clientY-last.y; last={x:e.clientX,y:e.clientY}; draw(); return; }
const p=pos(e); let hit=null;
for(const n of N){ if((n.x-p.x)**2+(n.y-p.y)**2<(n.r+6)**2){hit=n;break;} }
if(hit){
const bp=bestPartner[hit.id];
tip.innerHTML=`<b>${hit.id}</b>${hit.splash?' <span class="kbd">(splash)</span>':''}<br>`+
`聚落 C${hit.cl} · 17lands 出场 ${hit.plays||0} · 本次施放 ${hit.casts}`+
(bp?`<br>最强伙伴:${bp[0]} (${bp[1]})`:'')+(hit.col?`<br>颜色:${hit.col}`:'')+
`<br><span style="color:#8b98a8">点击复制卡名</span>`;
tip.style.left=(e.clientX+14)+'px'; tip.style.top=(e.clientY+14)+'px'; tip.style.opacity=1;
} else tip.style.opacity=0;
});
window.addEventListener('mouseup',e=>{
if(downNode && downPt){ // click (not drag) -> copy card name
const dx=e.clientX-downPt.x, dy=e.clientY-downPt.y;
if(dx*dx+dy*dy < 25) copyText(downNode.id);
}
downNode=null; downPt=null;
if(drag){ drag.fx=null; drag.fy=null; }
if(sim) sim.alphaTarget(0);
drag=null; panning=false; cv.style.cursor='grab';
});
function copyText(t){
let ok=false;
try{
const ta=document.createElement('textarea');
ta.value=t; ta.style.position='fixed'; ta.style.opacity='0'; ta.style.left='-9999px';
document.body.appendChild(ta); ta.focus(); ta.select();
ok=document.execCommand('copy'); ta.remove();
}catch(err){ ok=false; }
if(!ok && navigator.clipboard) navigator.clipboard.writeText(t).catch(()=>{});
const el=document.getElementById('toast');
el.textContent='已复制:'+t; el.style.opacity=1;
clearTimeout(el._t); el._t=setTimeout(()=>{el.style.opacity=0;},1200);
}
cv.addEventListener('wheel',e=>{e.preventDefault(); const f=e.deltaY<0?1.1:0.9; scale=Math.max(0.3,Math.min(4,scale*f)); draw();},{passive:false});
/* ---------- per-view UI ---------- */
function buildStats(){
const m=V.meta;
document.getElementById('stats').innerHTML = [
[m.games,'对局(本色组)'], [N.length,'卡牌节点'], [V.edges.length,'加权边'],
[V.clusters.length,'聚落'], [(m.modularity!=null?m.modularity:0).toFixed(3),'模块度 Q'],
[V.edges.reduce((a,e)=>a+e.st,0),'强关系事件'],
].map(([v,l])=>`<div class="stat"><div class="v">${v}</div><div class="l">${l}</div></div>`).join('');
}
function buildLegend(){
const el=document.getElementById('legend'); el.innerHTML='';
if(colorMode==='cluster'){
CLUSTERS.forEach(c=>{const d=document.createElement('span');
d.innerHTML=`<i class="dot" style="background:${CL_COLORS[c.id]}"></i> C${c.id} (${c.size})`;
el.appendChild(d);});
} else if(colorMode==='color'){
Object.entries({W:'白',U:'蓝',B:'黑',R:'红',G:'绿'}).forEach(([k,v])=>{
const d=document.createElement('span'); d.innerHTML=`<i class="dot" style="background:${MTG[k]}"></i> ${v}`; el.appendChild(d);});
} else el.innerHTML='<span>颜色越亮 = 17Lands 出场次数越多</span>';
}
function buildClusters(){
const cg=document.getElementById('clusterGrid'); cg.innerHTML='';
CLUSTERS.forEach(c=>{
const total=c.colors.reduce((s,x)=>s+x[1],0)||1;
const bar=c.colors.slice(0,5).map(([col,n])=>{
const cc=col.split('').filter(x=>MTG[x]).map(x=>MTG[x]);
const fill=cc.length?`rgb(${cc.map(x=>hex2rgb(x)).reduce((a,b)=>[a[0]+b[0],a[1]+b[1],a[2]+b[2]]).map(v=>v/cc.length|0).join(',')})`:'#7a8493';
return `<span style="width:${n/total*100}%;background:${fill}" title="${col||'colorless'}:${n}"></span>`;
}).join('');
const div=document.createElement('div'); div.className='cl-card';
div.innerHTML=`<div class="cl-head"><i class="dot" style="background:${CL_COLORS[c.id]}"></i>
<span class="cl-title">聚落 C${c.id}</span>
<span class="cl-meta">${c.size} 张 · 共施放 ${c.casts}</span></div>
<div class="bar">${bar}</div>
<div class="chips">${c.cards.map(x=>`<span class="chip">${x}</span>`).join('')}</div>`;
cg.appendChild(div);
});
}
function buildHeat(){
const ids=CLUSTERS.map(c=>c.id), maxv=Math.max(...CADJ.map(x=>x[1]),1);
const cell=(a,b)=>{
if(a===b) return `<div style="background:#2a3240">—</div>`;
const key=[Math.min(a,b),Math.max(a,b)];
const hit=CADJ.find(x=>x[0][0]===key[0]&&x[0][1]===key[1]);
const v=hit?hit[1]:0, t=v/maxv;
return `<div style="background:rgba(90,159,212,${(t*0.9+0.03).toFixed(2)})" title="C${a}–C${b}: ${v.toFixed(1)}">${t>0.55?v.toFixed(0):''}</div>`;
};
let h=`<div class="heat" style="grid-template-columns:34px repeat(${ids.length},1fr)">`;
h+='<div></div>'+ids.map(i=>`<div style="color:#8b98a8">C${i}</div>`).join('');
for(const a of ids){ h+=`<div style="color:#8b98a8;display:flex;align-items:center">C${a}</div>`;
for(const b of ids) h+=cell(a,b); }
h+='</div>';
document.getElementById('heat').innerHTML=h;
}
function buildSynTable(){
const tb=document.querySelector('#synTable tbody'); tb.innerHTML='';
V.strongNpmi.forEach(e=>{
const tr=document.createElement('tr');
tr.innerHTML=`<td>${e.s} <span class="kbd">↔</span> ${e.t}</td>
<td class="num">${e.sr.toFixed(3)}</td><td class="num">${e.st}</td><td class="num">${e.ef}</td>`;
tb.appendChild(tr);
});
}
function setupGroups(){
const bar=document.getElementById('groups'); bar.innerHTML='';
DATA.keys.forEach(k=>{
const b=document.createElement('button');
b.textContent=(k==='__ALL__'?'全部色对':k);
b.className=(k===curView?'on':'');
b.onclick=()=>setView(k);
bar.appendChild(b);
});
}
function setView(key){
curView=key; V=DATA.views[key];
N=V.nodes.map(n=>({...n}));
nameIdx={}; N.forEach((n,i)=>nameIdx[n.id]=i);
L=V.edges.filter(e=>e.w>0 && e.s in nameIdx && e.t in nameIdx)
.map(e=>({s:nameIdx[e.s],t:nameIdx[e.t],w:e.w,sr:e.sr,st:e.st}));
MAXW=Math.max(...L.map(l=>l.w),1e-6);
MAXPLAYS=Math.max(...N.map(n=>n.plays||0),1);
CLUSTERS=V.clusters; CADJ=V.cadj; bestPartner=V.bestPartner;
CL_COLORS={}; CLUSTERS.forEach((c,i)=>CL_COLORS[c.id]=DATA.palette[i%DATA.palette.length]);
// reset canvas transform
scale=1; ox=0; oy=0;
// threshold default
const ws=L.map(l=>l.w).sort((a,b)=>b-a);
thresh = ws[Math.min(700,ws.length-1)] || MAXW*0.3;
const el=document.getElementById('edgeThresh');
el.max=MAXW.toFixed(3); el.step=(MAXW/200).toFixed(4); el.value=thresh;
document.getElementById('threshVal').textContent=thresh.toFixed(3);
document.getElementById('viewMeta').textContent =
`(${key==='__ALL__'?'全部色对':key} · ${V.meta.games} 局 · Q=${(V.meta.modularity||0).toFixed(3)})`;
setupGroups(); buildStats(); buildLegend(); buildClusters(); buildHeat(); buildSynTable();
buildLayout(); resize();
}
/* ---------- controls ---------- */
document.querySelectorAll('#colorGroups button').forEach(b=>{
b.onclick=()=>{ colorMode=b.dataset.v; buildLegend(); draw();
document.querySelectorAll('#colorGroups button').forEach(x=>x.classList.toggle('on', x===b)); };
});
document.getElementById('edgeThresh').oninput=e=>{thresh=+e.target.value;
document.getElementById('threshVal').textContent=thresh.toFixed(3); draw();};
document.getElementById('strongOnly').onchange=e=>{strongOnly=e.target.checked; draw();};
document.getElementById('hideIsolated').onchange=e=>{hideIsolated=e.target.checked; draw();};
document.getElementById('labels').onchange=e=>{showLabels=e.target.checked; draw();};
let attrTimer=null;
document.getElementById('attract').oninput=e=>{
GAMMA=+e.target.value; document.getElementById('attractVal').textContent=GAMMA.toFixed(1);
clearTimeout(attrTimer); attrTimer=setTimeout(()=>{ if(sim) sim.alpha(1).restart(); },120);
};
document.getElementById('repel').oninput=e=>{
REPMUL=+e.target.value; document.getElementById('repelVal').textContent=REPMUL.toFixed(1);
clearTimeout(attrTimer); attrTimer=setTimeout(()=>{ if(sim) sim.alpha(1).restart(); },120);
};
document.getElementById('clgrav').oninput=e=>{
CLGRAV=+e.target.value; document.getElementById('clgravVal').textContent=CLGRAV.toFixed(2);
if(sim){ sim.force("cx").strength(CLGRAV); sim.force("cy").strength(CLGRAV); }
clearTimeout(attrTimer); attrTimer=setTimeout(()=>{ if(sim) sim.alpha(1).restart(); },120);
};
setView('__ALL__');
</script>
</main>
__FOOTBANNER__
</body>
</html>
"""
d3_path = Path(_args.d3) if _args.d3 else (Path(__file__).parent / "assets" / "d3.v7.min.js")
d3_src = d3_path.read_text(encoding="utf-8") if d3_path.exists() else ""
html = (html.replace("__SET__", _layout.SET)
.replace("__LAYOUT_CSS__", _layout.CSS)
.replace("__BANNER__", _layout.banner("card_graph.html"))
.replace("__FOOTBANNER__", _layout.footbanner("节点大小 = 17lands 出场数;连线 = 同现强度(NPMI),颜色 = Louvain 社区。各色组独立计算,可切换视图对比。")))
html = html.replace("__D3__", d3_src)
html = html.replace("__PAYLOAD__", json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
OUT.write_text(html, encoding="utf-8")
print(f"wrote {OUT} ({OUT.stat().st_size/1024:.0f} KB), views={len(views)}, d3={'yes' if d3_src else 'NO'}")
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python
"""Append a per-card REAL cast/play rate table to the report's data_review.md.
Reads value/<out>/cast_stats.json (produced by build_cast_stats.py) and writes a
"## 单卡施放率" section into value/<out>/reports/data_review.md, replacing any previous
one (idempotent, delimited by markers).
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
MARK_BEGIN = "<!-- CAST_STATS:BEGIN -->"
MARK_END = "<!-- CAST_STATS:END -->"
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
args = ap.parse_args()
snapshot = Path(args.snapshot)
out = Path(args.out)
stats = json.loads((out / "cast_stats.json").read_text(encoding="utf-8"))
cards = {c["name"]: c for c in
json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]}
rows = []
for nm, s in stats.items():
c = cards.get(nm) or {}
is_land = any("Land" in t for t in (c.get("types") or []))
use = s.get("play", 0) if is_land else s.get("cast", 0)
g = s.get("games", 0)
if not g:
continue
games_with = s.get("play_games", 0) if is_land else s.get("cast_games", 0)
rows.append((nm, c.get("rarity") or "", "地" if is_land else "咒语",
use, g, use / g, games_with / g))
rows.sort(key=lambda r: -r[5])
lines = [MARK_BEGIN, "", "## 5. 单卡施放率(REPLAY 实测)", "",
"由 `scripts/build_cast_stats.py` 解析 17lands GRE replays 得到:",
"**施放** = `GameObjectType_Card` 进入 Stack(zoneId 27,我方);",
"**地** = 地牌进入 Battlefield(zoneId 28)。",
"",
"公式:`次/局 = 使用次数 / 该牌被带进比赛的局数`(REPLAY 实测,共 "
f"{len(rows)} 张牌)。",
"「出现局%」= 至少有 1 次施放/落场的对局占比。",
"",
"| # | 牌 | 稀有度 | 类型 | 使用次数 | 带进局数 | 次/局 | 出现局% |",
"|---:|---|---|---|---:|---:|---:|---:|"]
for i, (nm, rar, kind, use, g, rate, pct) in enumerate(rows, 1):
lines.append(f"| {i} | {nm} | {rar} | {kind} | {use} | {g} | {rate:.2f} | {pct*100:.0f}% |")
lines += ["", MARK_END, ""]
section = "\n".join(lines)
rp = out / "reports" / "data_review.md"
text = rp.read_text(encoding="utf-8") if rp.exists() else "# 数据体检\n"
if MARK_BEGIN in text and MARK_END in text:
head = text[:text.index(MARK_BEGIN)]
tail = text[text.index(MARK_END) + len(MARK_END):]
text = head + section + tail
else:
text = text.rstrip() + "\n\n" + section + "\n"
rp.parent.mkdir(parents=True, exist_ok=True)
rp.write_text(text, encoding="utf-8")
print(f"wrote {len(rows)} rows -> {rp}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+622
View File
@@ -0,0 +1,622 @@
#!/usr/bin/env python
"""2D visualization of the deck-clustering pipeline (one-off, .tmp/).
Feature space (same as the rebuilt build_templates_contract.py):
v[card] = copies * (1 + ln(game_count)) * 4p(1-p) # playability x discriminating power
rare/mythic excluded, basic lands excluded, printings merged by NAME.
Views: __ALL__ (10 color pairs together) + one per color pair.
Each view draws:
① MDS 2D projection (coordinates kept in REAL distance units + a scale bar,
so different tabs can be compared quantitatively)
② a vs b scatter (intra-cluster distance vs nearest other cluster),
with a FIXED axis range across all views.
Output: .tmp/cluster_viz.html
"""
from __future__ import annotations
import argparse
import json
import math
import random
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import build_templates_contract as B # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _layout # noqa: E402
SNAP = ROOT / "data/17lands/FRA20261007"
OUT = ROOT / "value/FRA20261007/reports/cluster_viz.html"
STAB = ROOT / "value/FRA20261007/stability.json"
MERGE_L1 = 270 # weighted complete-linkage merge threshold
MERGE_MAX = 6
BAR_UNITS = 0.5 # scale-bar length (in distance units)
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
WEIGHT: dict = {}
RARITY: dict = {}
def load_card_names():
data = json.loads((SNAP / "stats/card_data.json").read_text(encoding="utf-8"))["data"]
id2name = {c["mtga_id"]: c["name"] for c in data}
for c in data:
WEIGHT[c["name"]] = 1.0 + math.log(max(1, c.get("game_count") or 1))
RARITY[c["name"]] = (c.get("rarity") or "").lower()
for line in (SNAP / "drafts/draft_picks.jsonl").read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
r = json.loads(line)
for cid, m in (r.get("cards") or {}).items():
if m.get("name"):
id2name.setdefault(int(cid), m["name"])
return id2name
def l1(a, b):
return sum(WEIGHT.get(k, 1.0) * abs(a.get(k, 0) - b.get(k, 0)) for k in set(a) | set(b))
def merge_groups(cnts):
n = len(cnts)
parent = list(range(n))
members = {i: [i] for i in range(n)}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
pairs = []
for i in range(n):
for j in range(i + 1, n):
d = l1(cnts[i], cnts[j])
if d <= MERGE_L1:
pairs.append((d, i, j))
pairs.sort()
for _, i, j in pairs:
ri, rj = find(i), find(j)
if ri == rj:
continue
mi, mj = members[ri], members[rj]
if len(mi) + len(mj) > MERGE_MAX:
continue
if all(l1(cnts[a], cnts[b]) <= MERGE_L1 for a in mi for b in mj):
parent[rj] = ri
members[ri] = mi + mj
members.pop(rj, None)
return [sorted(v) for v in members.values()]
def mds2(D, n):
D2 = [[D[i][j] ** 2 for j in range(n)] for i in range(n)]
rmean = [sum(D2[i]) / n for i in range(n)]
total = sum(rmean) / n
Bm = [[-0.5 * (D2[i][j] - rmean[i] - rmean[j] + total) for j in range(n)] for i in range(n)]
def mv(M, v):
return [sum(row[j] * v[j] for j in range(n)) for row in M]
def unit(v):
s = math.sqrt(sum(x * x for x in v)) or 1.0
return [x / s for x in v]
def power(M):
random.seed(7)
v = [random.random() - 0.5 for _ in range(n)]
for _ in range(300):
v = unit(mv(M, v))
w = mv(M, v)
return sum(v[i] * w[i] for i in range(n)), v
l1v, e1 = power(Bm)
B2 = [[Bm[i][j] - l1v * e1[i] * e1[j] for j in range(n)] for i in range(n)]
l2v, e2 = power(B2)
return [(e1[i] * math.sqrt(max(l1v, 0)), e2[i] * math.sqrt(max(l2v, 0))) for i in range(n)]
def mds2_sparse(rows, n, d, iters=160):
colsum = [0.0] * d
for r in rows:
for c, v in r.items():
colsum[c] += v
mean = [s / n for s in colsum]
def Xv(v):
return [sum(val * v[c] for c, val in r.items()) for r in rows]
def Xtv(u):
out = [0.0] * d
for i, r in enumerate(rows):
ui = u[i]
if ui:
for c, val in r.items():
out[c] += val * ui
return out
def Gc(u):
s = sum(u)
w = [Xtv(u)[c] - mean[c] * s for c in range(d)]
mw = sum(mean[c] * w[c] for c in range(d))
return [a - mw for a in Xv(w)]
def unit(v):
s = math.sqrt(sum(x * x for x in v)) or 1.0
return [x / s for x in v]
def power(op, seed):
random.seed(seed)
u = unit([random.random() - 0.5 for _ in range(n)])
for _ in range(iters):
u = unit(op(u))
w = op(u)
return sum(u[i] * w[i] for i in range(n)), u
l1v, u1 = power(Gc, 11)
def Gc2(v):
w = Gc(v)
p = sum(u1[i] * v[i] for i in range(n))
return [w[i] - l1v * p * u1[i] for i in range(n)]
l2v, u2 = power(Gc2, 12)
return [(u1[i] * math.sqrt(max(l1v, 0)), u2[i] * math.sqrt(max(l2v, 0))) for i in range(n)]
def ab_for(D, labels, n):
"""for each point: a = mean dist to same-label peers, b = mean dist to nearest other label."""
groups = defaultdict(list)
for i, g in enumerate(labels):
groups[g].append(i)
A, Bv = [], []
for i in range(n):
gi = labels[i]
peers = groups[gi]
a = sum(D[i][j] for j in peers if j != i) / (len(peers) - 1) if len(peers) > 1 else 0.0
b = min((sum(D[i][j] for j in groups[g]) / len(groups[g]) for g in groups if g != gi), default=0.0)
A.append(a)
Bv.append(b)
return A, Bv
def ab_sparse(rows, labels, n):
"""same as ab_for but with sparse rows (L2-normalized) -> computes distances on the fly."""
groups = defaultdict(list)
for i, g in enumerate(labels):
groups[g].append(i)
sums = [defaultdict(float) for _ in range(n)]
cnts = [Counter() for _ in range(n)]
for i in range(n):
ri = rows[i]
for j in range(i + 1, n):
rj = rows[j]
if len(ri) > len(rj):
a_, b_ = ri, rj
else:
a_, b_ = rj, ri
dot = sum(v * b_.get(k, 0.0) for k, v in a_.items())
d2 = 2.0 - 2.0 * dot
d = math.sqrt(d2) if d2 > 0 else 0.0
gj = labels[j]
sums[i][gj] += d
cnts[i][gj] += 1
sums[j][labels[i]] += d
cnts[j][labels[i]] += 1
A, Bv = [], []
for i in range(n):
gi = labels[i]
a = sums[i][gi] / cnts[i][gi] if cnts[i][gi] else 0.0
b = min((sums[i][g] / cnts[i][g] for g in sums[i] if g != gi and cnts[i][g]), default=0.0)
A.append(a)
Bv.append(b)
tot = sum(sum(d.values()) for d in sums)
cnt = sum(sum(c.values()) for c in cnts)
return A, Bv, (tot / cnt if cnt else 0.0)
def make_points(coords, groups, decks, A=None, Bv=None, extra=None):
out = []
for gi in groups:
x = sum(coords[i][0] for i in gi) / len(gi)
y = sum(coords[i][1] for i in gi) / len(gi)
recs = Counter(f"{decks[i]['wins']}-{decks[i]['losses']}" for i in gi)
top = ", ".join(nm for nm, _ in decks[gi[0]]["cnt"].most_common(6))
p = {"x": x, "y": y, "n": len(gi),
"rec": "/".join(f"{k}×{v}" if v > 1 else k for k, v in recs.most_common()),
"splash": decks[gi[0]]["splash"], "top": top}
if A is not None:
p["a"] = sum(A[i] for i in gi) / len(gi)
p["b"] = sum(Bv[i] for i in gi) / len(gi)
if extra:
p.update(extra(gi))
out.append(p)
return out
def rescale_mean(coords, mean_orig):
"""scale MDS coords so the mean pairwise 2D distance == mean original distance."""
n = len(coords)
if n < 2 or not mean_orig:
return coords, 1.0
m2 = sum(math.dist(coords[i], coords[j]) for i in range(n) for j in range(i + 1, n)) / (n * (n - 1) / 2)
k = mean_orig / m2 if m2 else 1.0
return [(x * k, y * k) for x, y in coords], k
def fit_scale(pts, half=270.0):
ext = max((max(abs(p["x"]), abs(p["y"])) for p in pts), default=1.0) or 1.0
return half / ext
def build_view(decks, weights_disc, pair_labels=None, k=None):
n = len(decks)
df = Counter()
for d in decks:
for nm in d["cnt"]:
df[nm] += 1
vocab = sorted(nm for nm, c in df.items() if c / n >= 0.05)
idx = {nm: i for i, nm in enumerate(vocab)}
disc = {nm: 4.0 * (df[nm] / n) * (1 - df[nm] / n) for nm in vocab}
X = []
for d in decks:
v = [0.0] * len(vocab)
for nm, c in d["cnt"].items():
if nm in idx:
v[idx[nm]] = c * WEIGHT.get(nm, 1.0) * disc[nm]
L = math.sqrt(sum(x * x for x in v)) or 1.0
X.append([x / L for x in v])
return X, D_from_X(X)
def D_from_X(X):
n = len(X)
ns = [sum(v * v for v in x) for x in X]
D = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
d2 = ns[i] + ns[j] - 2 * sum(a * b for a, b in zip(X[i], X[j]))
D[i][j] = D[j][i] = math.sqrt(d2 if d2 > 0 else 0.0)
return D
def main() -> int:
id2name = load_card_names()
stab = {}
_sp = STAB
if _sp.exists():
stab = json.loads(_sp.read_text(encoding="utf-8"))
by_pair = defaultdict(list)
for line in (SNAP / "trophies/trophies_decks.jsonl").read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
d = json.loads(line)
colors = d.get("colors") or ""
pair = re.sub(r"[^A-Z]", "", colors)
if len(pair) != 2:
continue
cnt = Counter()
for e in d["maindeck"]:
nm = id2name.get(e["mtga_id"])
if nm and nm not in BASICS and RARITY.get(nm) not in ("rare", "mythic"):
cnt[nm] += e["count"]
by_pair[pair].append({"cnt": cnt, "wins": d.get("wins"), "losses": d.get("losses"),
"splash": "".join(ch for ch in colors if ch.islower())})
data = {}
pair_coords = {}
abmax = 0.0
for pair, decks in sorted(by_pair.items()):
n = len(decks)
if n < 6:
continue
df = Counter()
for d in decks:
for nm in d["cnt"]:
df[nm] += 1
vocab = sorted(nm for nm, c in df.items() if c / n >= 0.05)
idx = {nm: i for i, nm in enumerate(vocab)}
def _X(weights):
X = []
for d in decks:
v = [0.0] * len(vocab)
for nm, c in d["cnt"].items():
if nm in idx:
v[idx[nm]] = c * WEIGHT.get(nm, 1.0) * weights.get(nm, 0.0)
L = math.sqrt(sum(x * x for x in v)) or 1.0
X.append([x / L for x in v])
return X
def _pick(X):
D = D_from_X(X)
b = None
for kk in (2,):
if kk >= n:
continue
aa = B.kmeans(X, kk)
if min(Counter(aa).values()) < 3:
continue
s = B.silhouette(D, aa, kk)
if b is None or s > b[2]:
b = (kk, aa, s)
return b, D
def _outlier(X, assign, kk):
# (其他) = outlier relative to the deck's OWN cluster (mean + 2*sd of that cluster)
dim = len(vocab)
gg = defaultdict(list)
for i, a in enumerate(assign):
gg[a].append(i)
cent = {g: [sum(X[i][j] for i in gg[g]) / len(gg[g]) for j in range(dim)] for g in gg}
d2c = [math.sqrt(sum((X[i][j] - cent[assign[i]][j]) ** 2 for j in range(dim))) for i in range(n)]
flag = [False] * n
for g in gg:
ds = [d2c[i] for i in gg[g]]
m = sum(ds) / len(ds)
sd = (sum((x - m) ** 2 for x in ds) / len(ds)) ** 0.5 or 1.0
for i in gg[g]:
if d2c[i] > m + 2.0 * sd:
flag[i] = True
return [kk if flag[i] else assign[i] for i in range(n)]
disc1 = {nm: 4.0 * (df[nm] / n) * (1 - df[nm] / n) for nm in vocab}
X1v = _X(disc1)
b1, D1 = _pick(X1v)
if b1 is None:
continue
sil1 = b1[2]
a1 = _outlier(X1v, b1[1], b1[0]) # (其他) joins the weighting
g1 = defaultdict(list)
for i, aa in enumerate(a1):
g1[aa].append(i)
inc = {nm: {g: 0 for g in g1} for nm in vocab}
for g, mem in g1.items():
for i in mem:
for nm in decks[i]["cnt"]:
if nm in inc:
inc[nm][g] += 1
spec = {}
for nm in vocab:
pbar = df[nm] / n
spec[nm] = sum((len(g1[g]) / n) * ((inc[nm][g] / len(g1[g])) - pbar) ** 2 for g in g1)
mx = max(spec.values()) or 1.0
spec = {nm: v / mx for nm, v in spec.items()}
X2v = _X(spec)
b2, D2 = _pick(X2v)
if b2 is not None:
kb, assign, sil, cl_pass, D, Xf = b2[0], b2[1], b2[2], 2, D2, X2v
else:
kb, assign, sil, cl_pass, D, Xf = b1[0], b1[1], b1[2], 1, D1, X1v
assign = _outlier(Xf, assign, kb)
other_c = kb
k = kb + 1
A, Bv = ab_for(D, assign, n)
mean_orig = sum(D[i][j] for i in range(n) for j in range(i + 1, n)) / (n * (n - 1) / 2)
cds, _ = rescale_mean(mds2(D, n), mean_orig)
pair_coords[pair] = cds
mg = merge_groups([d["cnt"] for d in decks])
pts = make_points(cds, mg, decks, A, Bv,
extra=lambda gi: {"c": Counter(assign[i] for i in gi).most_common(1)[0][0]})
scale = fit_scale(pts)
clusters = []
for cc in range(k):
idxs = [i for i in range(n) if assign[i] == cc]
if not idxs:
continue
clusters.append({"a": sum(A[i] for i in idxs) / len(idxs),
"b": sum(Bv[i] for i in idxs) / len(idxs), "n": len(idxs), "c": cc})
pbar = {nm: df[nm] / n for nm in vocab}
defcards = {}
for cc in range(k):
mem = [i for i in range(n) if assign[i] == cc]
if not mem:
continue
ex = {nm: sum(1 for i in mem if nm in decks[i]["cnt"]) / len(mem) - pbar[nm] for nm in vocab}
defcards[cc] = [nm for nm, _ in sorted(ex.items(), key=lambda x: -x[1])[:10]]
data[pair] = {"k": k, "sil": round(sil, 4), "sil1": round(sil1, 4), "pass": cl_pass,
"defcards": defcards, "other_c": other_c,
"n": n, "vocab": len(vocab),
"merged": sum(1 for g in mg if len(g) > 1), "scale": round(scale, 2),
"pts": pts, "clusters": clusters}
for p in pts:
abmax = max(abmax, p["a"], p["b"])
# ---- ALL ----
all_decks, pair_local = [], []
for p, ds in sorted(by_pair.items()):
for j, d in enumerate(ds):
all_decks.append((p, d))
pair_local.append(j)
an = len(all_decks)
adf = Counter()
for _, d in all_decks:
for nm in d["cnt"]:
adf[nm] += 1
avocab = sorted(nm for nm, c in adf.items() if c / an >= 0.03)
aidx = {nm: i for i, nm in enumerate(avocab)}
adisc = {nm: 4.0 * (adf[nm] / an) * (1 - adf[nm] / an) for nm in avocab}
arows = []
for _, d in all_decks:
r = {}
for nm, kk in d["cnt"].items():
if nm in aidx:
r[aidx[nm]] = kk * WEIGHT.get(nm, 1.0) * adisc[nm]
L = math.sqrt(sum(v * v for v in r.values())) or 1.0
arows.append({c: v / L for c, v in r.items()})
pairs_sorted = sorted(by_pair)
pair_of = [pairs_sorted.index(p) for p, _ in all_decks]
Aa, Ba, amean = ab_sparse(arows, pair_of, an)
acds, _ = rescale_mean(mds2_sparse(arows, an, len(avocab)), amean)
adecks = [d for _, d in all_decks]
amg = merge_groups([d["cnt"] for d in adecks])
apts = make_points(acds, amg, adecks, Aa, Ba,
extra=lambda gi: {"pair": Counter(pair_of[i] for i in gi).most_common(1)[0][0]})
aclusters = []
for pc in range(len(pairs_sorted)):
idxs = [i for i in range(an) if pair_of[i] == pc]
if not idxs:
continue
aclusters.append({"a": sum(Aa[i] for i in idxs) / len(idxs),
"b": sum(Ba[i] for i in idxs) / len(idxs), "n": len(idxs), "pair": pc})
data["__ALL__"] = {"all": True, "n": an, "vocab": len(avocab),
"merged": sum(1 for g in amg if len(g) > 1),
"scale": round(fit_scale(apts), 2), "pairs": pairs_sorted, "pts": apts,
"clusters": aclusters}
for p in apts:
abmax = max(abmax, p["a"], p["b"])
data["_meta"] = {"abmax": round(abmax, 3), "bar": BAR_UNITS}
data["_stab"] = stab
_html = (HTML_TMPL.replace("__DATA__", json.dumps(data, ensure_ascii=False))
.replace("__LAYOUT_CSS__", _layout.CSS)
.replace("__BANNER__", _layout.banner("cluster_viz.html"))
.replace("__FOOTBANNER__", _layout.footbanner("① MDS 投影为每页独立计算,看相对远近;② 的 a–b 各页共用同一坐标范围,可直接比较。距离单位见各图左下比例尺。")))
OUT.write_text(_html, encoding="utf-8")
print(f"wrote {OUT} ({len(data) - 2} pairs + ALL, {an} decks)")
return 0
HTML_TMPL = r"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
<title>聚类 2D 可视化</title><style>
body{background:#0e1116;color:#dfe6f0;font:14px/1.5 system-ui,"Segoe UI",sans-serif;margin:0;padding:20px}
h1{font-size:20px;margin:0 0 4px}p.sub{color:#8b96a8;margin:0 0 14px;max-width:980px}
.bar{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px}
.bar button{background:#1b2029;color:#cfd8e6;border:1px solid #2a3240;border-radius:8px;padding:5px 12px;cursor:pointer;font-size:13px}
.bar button.on{background:#2f5f96;border-color:#4a86c9;color:#fff}
.wrap{display:flex;gap:18px;align-items:flex-start;flex-wrap:wrap}
.col{display:flex;flex-direction:column;gap:6px}
.cap{font-size:12px;color:#9fb0c7;max-width:600px}
svg{background:#12161d;border:1px solid #232b38;border-radius:12px;display:block}
.meta{background:#151a22;border:1px solid #232b38;border-radius:12px;padding:12px 16px;min-width:250px}
.meta b{color:#fff}.meta .k{color:#8b96a8}
.legend{display:flex;gap:12px;flex-wrap:wrap;margin-top:8px}
.legend i{width:11px;height:11px;border-radius:50%;display:inline-block;margin-right:5px;vertical-align:middle}
#tip{position:fixed;pointer-events:none;background:#0b0e13f2;border:1px solid #3a475c;border-radius:8px;padding:8px 10px;font-size:12px;max-width:360px;display:none;z-index:9;box-shadow:0 6px 20px #000a}
small{color:#8b96a8}.dotp{cursor:pointer}
#stab{margin-top:14px;max-width:1100px}
#stab h3{font-size:14px;color:#cfd8e6;margin:0 0 6px}
.dcr{font-size:12px;margin:3px 0;line-height:1.7}
.dcr .dcc{width:10px;height:10px;border-radius:50%;display:inline-block;margin-right:6px}
#stab small{color:#8b96a8}
__LAYOUT_CSS__</style></head><body>
__BANNER__
<main class="wrap">
<h1>牌表聚类 2D 可视化</h1>
<p class="sub">聚类用<b>两遍法</b>:pass1 用 <code>4p(1−p)</code> 粗聚类,再按 <code>specificity=ΣₖP(k)[P(c|k)−P(c|pair)]²</code> 重加权,pass2 重聚类。特征 = 张数 × (1+ln(game_count)) × 权重;剔基本地与稀有/密稀;同名不同印刷合并。
距离均以<b>真实距离单位</b>绘制,每张图都有<b>比例尺</b>,a–b 图各页共用同一坐标范围 → 可跨图对比。
距离极近的牌表已合并成更大的圆(每多 1 副面积 ×1.5)。</p>
<div class="bar" id="bar"></div>
<div class="wrap">
<div class="col">
<div class="cap">① MDS 2D 投影(每页独立 MDS;左下角标尺 = 0.5 距离单位,<b>各页比例不同</b>)</div>
<svg id="svg" width="600" height="600" viewBox="0 0 600 600"></svg>
</div>
<div class="col">
<div class="cap" id="cap2">② a(簇内距离,→) vs b(最近他簇距离,↑),各页同尺度</div>
<svg id="svg2" width="380" height="380" viewBox="0 0 380 380"></svg>
</div>
<div class="meta" id="meta"></div>
</div>
<div id="stab"></div>
<div id="tip"></div>
<script>
const DATA = __DATA__;
const META = DATA._meta;
const COL = ['#4a90d9','#e0673a','#4ad07a','#c9a34a','#a06ad0'];
const PAL = ['#4a90d9','#e0673a','#4ad07a','#c9a34a','#a06ad0','#e05a8a','#3cc9c9','#f0a020','#8b8bff','#7ab648'];
const KEYS = ['__ALL__', ...Object.keys(DATA).filter(k=>k[0]!=='_'&&k!=='__ALL__')];
let cur = '__ALL__';
const bar = document.getElementById('bar');
KEYS.forEach(k=>{const b=document.createElement('button');b.dataset.k=k;b.textContent=(k==='__ALL__'?'全部色对':k);b.onclick=()=>{cur=k;render();};bar.appendChild(b);});
const tip = document.getElementById('tip');
function pcol(d,pt){return d.all ? PAL[pt.pair%10] : ((d.other_c!=null&&pt.c==d.other_c) ? "#7f8aa0" : COL[pt.c%5]);}
function rOf(n){return 6*Math.pow(1.5,(n-1)/2);}
function render(){
[...bar.children].forEach(b=>b.classList.toggle('on', b.dataset.k===cur));
const d = DATA[cur], isAll = !!d.all, sc = d.scale, cx=300, cy=300;
let h = `<g stroke="#3a475c" stroke-width="2"><line x1="24" y1="560" x2="${(24+META.bar*sc).toFixed(0)}" y2="560"/>
<line x1="24" y1="554" x2="24" y2="566"/><line x1="${(24+META.bar*sc).toFixed(0)}" y1="554" x2="${(24+META.bar*sc).toFixed(0)}" y2="566"/></g>
<text x="24" y="578" fill="#9fb0c7" font-size="11">比例尺 = ${META.bar} 距离单位</text>`;
d.pts.forEach((pt,i)=>{
const px = cx + pt.x*sc, py = cy - pt.y*sc, r = rOf(pt.n);
h += `<circle class="dotp" cx="${px.toFixed(1)}" cy="${py.toFixed(1)}" r="${r.toFixed(1)}"
fill="${pcol(d,pt)}" fill-opacity="${pt.n>1?0.95:(pt.splash?0.45:0.8)}"
onmouseenter="show(${i})" onmousemove="move(event)" onmouseleave="hide()"></circle>`;
});
document.getElementById('svg').innerHTML = h;
// ② a-b, fixed scale
const R=320, X0=40, Y0=340, amax=META.abmax||1;
const ax = v=>X0+v/amax*R, ay = v=>Y0-v/amax*R;
let h2 = `<rect x="${X0}" y="${Y0-R}" width="${R}" height="${R}" fill="none" stroke="#2a3240"/>`;
[0.25,0.5,0.75,1].forEach(t=>{
h2 += `<line x1="${X0}" y1="${ay(amax*t)}" x2="${X0+R}" y2="${ay(amax*t)}" stroke="#232b38"/>`
+ `<line x1="${ax(amax*t)}" y1="${Y0}" x2="${ax(amax*t)}" y2="${Y0-R}" stroke="#232b38"/>`;
});
h2 += `<line x1="${ax(0)}" y1="${ay(0)}" x2="${ax(amax)}" y2="${ay(amax)}" stroke="#5a6478" stroke-dasharray="4 4"/>`;
h2 += `<text x="${X0+R}" y="${Y0+16}" fill="#8b96a8" font-size="11" text-anchor="end">a(簇内距离)→ ${amax}</text>`
+ `<text x="14" y="${Y0-R}" fill="#8b96a8" font-size="11">↑ b(最近他簇)${amax}</text>`;
d.clusters.forEach(cl=>{
const px=ax(cl.a), py=ay(cl.b), r=4.5;
const lab = isAll ? d.pairs[cl.pair] : ((d.other_c!=null&&cl.c==d.other_c) ? '(其他)' : '簇'+cl.c);
const col = isAll ? PAL[cl.pair%10] : ((d.other_c!=null&&cl.c==d.other_c) ? '#7f8aa0' : COL[cl.c%5]);
h2 += `<circle cx="${px.toFixed(1)}" cy="${py.toFixed(1)}" r="${r.toFixed(1)}" fill="${col}" fill-opacity="0.9"></circle>`
+ `<text x="${px.toFixed(1)}" y="${(py-r-4).toFixed(1)}" fill="#cfd8e6" font-size="11" text-anchor="middle">${lab} (${cl.n})</text>`
+ `<title>${lab}: a=${cl.a.toFixed(3)} b=${cl.b.toFixed(3)} n=${cl.n}</title>`;
});
document.getElementById('svg2').innerHTML = h2;
const leg = isAll
? d.pairs.map((p,i)=>`<span><i style="background:${PAL[i%10]}"></i>${p}</span>`).join('')
: [...new Set(d.pts.map(p=>p.c))].sort().map(c=>`<span><i style="background:${COL[c%5]}"></i>簇 ${c}</span>`).join('');
const st = (DATA._stab||{})[cur];
const dc = d.defcards || {};
let hs = '';
Object.keys(dc).forEach(cc=>{
const dfc = dc[cc].map(nm=>{
const f = st ? (st.cards[nm]||0) : 0;
const col = f>=0.8?'#4ad07a':(f>=0.5?'#e0c34a':'#7f8aa0');
return `<span style="color:${col}">${nm} <small>${Math.round(f*100)}%</small></span>`;
}).join(' · ');
const isOther = (d.other_c!=null&&Number(cc)==d.other_c);
hs += `<div class="dcr"><span class="dcc" style="background:${isOther?'#7f8aa0':COL[cc%5]}"></span><b>${isOther?'(其他)':'簇'+cc}</b>(${d.pts.filter(p=>p.c==cc).length} 点)定义牌:${dfc}</div>`;
});
document.getElementById('stab').innerHTML = isAll ? ''
: `<h3>定义牌 & 稳定性 <small>(bootstrap ${st?st.n_boot||20:20} 次,定义牌重现率;绿≥80% 黄≥50% 灰<50%)</small>${st?` · 簇平均 Jaccard <b>${st.mean}</b>`:''}</h3>`+hs;
document.getElementById('meta').innerHTML =
`<div><b>${isAll?'全部色对':cur}</b> · ${d.n} 副 · ${d.pts.length} 点(合并 ${d.merged} 组)· 维度 ${d.vocab}</div>`
+ (isAll ? `<div><span class="k">a/b 按"色对"分组</span></div>`
: `<div><span class="k">silhouette</span> <b>${d.sil1} → ${d.sil}</b> <small>(pass ${d.pass})</small></div>`)
+ `<div class="legend">${leg}</div>`
+ `<p><small>① 每页独立 MDS,标尺长度即该页的 px/距离;② 的坐标系各页完全相同,可直接比较。</small></p>`;
}
function show(i){const d=DATA[cur],pt=d.pts[i],t=document.getElementById('tip');
const extra = d.all ? d.pairs[pt.pair] : '簇 '+pt.c;
t.innerHTML = `<b>${extra}</b>${pt.n>1?' · <span style="color:#ffd479">'+pt.n+' 副接近</span>':''} · 战绩 ${pt.rec}${pt.splash?' · splash '+pt.splash:''}<br>`
+ `<span style="color:#9fb0c7">${pt.top}</span><br><small>a=${pt.a.toFixed(3)} b=${pt.b.toFixed(3)}</small>`;
t.style.display='block';}
function move(e){const t=document.getElementById('tip');t.style.left=(e.clientX+14)+'px';t.style.top=(e.clientY+14)+'px';}
function hide(){document.getElementById('tip').style.display='none';}
render();
</script>
</main>
__FOOTBANNER__
</body></html>
"""
if __name__ == "__main__":
_ap = argparse.ArgumentParser()
_ap.add_argument("--snapshot", required=True)
_ap.add_argument("--out", required=True)
_a = _ap.parse_args()
SNAP = Path(_a.snapshot)
OUT = Path(_a.out) / "reports" / "cluster_viz.html"
_layout.SET = _layout.set_of(_a.out)
_layout.ensure_assets(OUT.parent)
STAB = Path(_a.out) / "stability.json"
raise SystemExit(main())
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python
"""按「双色色组 × 日期」统计每日胜率,渲染成折线图(只画胜率)。
数据:data/17lands/<snap>/drafts/event_details.jsonl(每局 completion_time + won)
+ trophies/trophies_index.jsonl(draft_id -> 我方色组)
色组:用 primary_pair 归到 10 个双色(单色/无归类丢弃)。
输出:value/<snap>/reports/daily.html
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import _layout # noqa: E402
from render_templates_html import primary_pair # noqa: E402
PAIRS = ["WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"]
COLOR = {"WU": "#e8d76a", "UB": "#7cc4ff", "BR": "#e06a6a", "RG": "#e0956a",
"WG": "#8fe08f", "WB": "#c9c9cf", "BG": "#6ad0a0", "UR": "#b48cff",
"UG": "#5fd6cf", "WR": "#ff9f6a"}
def load_jsonl(p: Path):
if not p.exists():
return []
return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()]
def build(snapshot: Path) -> dict:
colors = {r["aggregate_id"]: r.get("colors")
for r in load_jsonl(snapshot / "trophies/trophies_index.jsonl")}
# day -> pair -> [games, wins]
day = defaultdict(lambda: defaultdict(lambda: [0, 0]))
for rec in load_jsonl(snapshot / "drafts/event_details.jsonl"):
pair = primary_pair(colors.get(rec.get("draft_id")))
if pair not in PAIRS:
continue
for m in rec.get("details", {}).get("match_results") or []:
for g in m.get("game_results") or []:
ct = g.get("completion_time")
if not ct:
continue
d = datetime.fromtimestamp(int(ct), tz=timezone.utc).strftime("%Y-%m-%d")
day[d][pair][0] += 1
day[d][pair][1] += 1 if g.get("won") else 0
days = sorted(day)
series = []
for p in PAIRS:
pts = []
for d in days:
gg, ww = day[d].get(p, [0, 0])
if gg:
pts.append({"d": d, "g": gg, "w": ww, "wr": round(ww / gg, 4)})
if pts:
series.append({"pair": p, "points": pts})
# 全场每日
allp = []
for d in days:
gg = sum(v[0] for v in day[d].values())
ww = sum(v[1] for v in day[d].values())
allp.append({"d": d, "g": gg, "w": ww, "wr": round(ww / gg, 4)})
return {"days": days, "series": series, "all": allp,
"color": COLOR, "pairs": PAIRS}
HTML = r"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>__SET__ · 色组每日走势</title><style>__LAYOUT_CSS__
.dash{max-width:1460px;margin:0 auto;padding:16px 20px}
.ctl{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:10px 0 4px}
.ctl button{background:#232b38;color:#cfd8e6;border:1px solid #33405a;border-radius:8px;padding:4px 12px;cursor:pointer}
.ctl button.on{background:#2f5f96;color:#fff;border-color:#2f5f96}
.leg{display:flex;gap:12px;flex-wrap:wrap;margin:8px 0}
.leg span{display:inline-flex;align-items:center;gap:5px;font-size:12px;cursor:pointer;padding:1px 4px;border-radius:5px}
.leg span.off{opacity:.3}
.leg i{width:12px;height:12px;border-radius:3px;display:inline-block}
svg text{fill:#c7d0de}
.tip{position:fixed;pointer-events:none;background:#0f1218;border:1px solid #33405a;border-radius:6px;
padding:6px 9px;font-size:12px;color:#e8e8ea;display:none;z-index:99}
.note{color:#8a94a6;font-size:12px}
</style></head><body>
__BANNER__
<div class="dash">
<h1>__SET__ · 双色色组每日走势</h1>
<p class="note">按 <code>completion_time</code>(UTC)分天,统计每个双色色组当天的<b>胜率</b>。样本均为 7 胜奖杯牌表,绝对胜率偏高(≈80%+),请看<b>相对变化</b>。</p>
<div class="ctl">
<span>显示:</span>
<button id="allbtn" data-all="1">全场</button>
</div>
<div class="leg" id="leg"></div>
<svg id="chart" width="1140" height="460"></svg>
</div>
<div class="tip" id="tip"></div>
__FOOTBANNER__
<script src="assets/d3.v7.min.js"></script>
<script>
const DATA=__DATA__;
let showAll=false;
const hidden=new Set();
const legend=document.getElementById("leg");
DATA.pairs.forEach(p=>{
const s=document.createElement("span"); s.dataset.p=p;
s.innerHTML='<i style="background:'+DATA.color[p]+'"></i>'+p;
s.onclick=()=>{ if(hidden.has(p))hidden.delete(p); else hidden.add(p); s.classList.toggle("off"); draw(); };
legend.appendChild(s);
});
document.getElementById("allbtn").onclick=e=>{showAll=!showAll;e.target.classList.toggle("on",showAll);draw();};
const W=1140,H=460,M={l:56,r:16,t:16,b:34};
const svg=d3.select("#chart"); const tip=document.getElementById("tip");
function draw(){
svg.selectAll("*").remove();
const xs=DATA.days.map(d=>new Date(d+"T00:00:00Z"));
const x=d3.scaleTime().domain(d3.extent(xs)).range([M.l,W-M.r]);
let allv=[]; DATA.series.forEach(s=>s.points.forEach(p=>allv.push(p.wr)));
if(showAll) DATA.all.forEach(p=>allv.push(p.wr));
let ymax=Math.min(1,d3.max(allv)*1.05);
let ymin=Math.max(0,d3.min(allv)*0.95);
const y=d3.scaleLinear().domain([ymin,ymax||1]).nice().range([H-M.b,M.t]);
const gx=svg.append("g").attr("transform","translate(0,"+(H-M.b)+")")
.call(d3.axisBottom(x).ticks(Math.min(DATA.days.length,10)).tickFormat(d3.timeFormat("%m-%d")));
const gy=svg.append("g").attr("transform","translate("+M.l+",0)")
.call(d3.axisLeft(y).tickFormat(v=>(v*100).toFixed(0)+"%"));
gx.selectAll("text").attr("fill","#c7d0de"); gy.selectAll("text").attr("fill","#c7d0de");
gx.selectAll("line").attr("stroke","#2a2e3a"); gy.selectAll("line").attr("stroke","#2a2e3a");
gy.selectAll(".domain").attr("stroke","#33405a"); gx.selectAll(".domain").attr("stroke","#33405a");
const line=d3.line().x(p=>x(new Date(p.d+"T00:00:00Z"))).y(p=>y(p.wr));
if(showAll){
svg.append("path").datum(DATA.all).attr("fill","none").attr("stroke","#fff")
.attr("stroke-width",2.4).attr("stroke-dasharray","5 3").attr("d",line);
}
DATA.series.forEach(s=>{
if(hidden.has(s.pair))return;
svg.append("path").datum(s.points).attr("fill","none").attr("stroke",DATA.color[s.pair])
.attr("stroke-width",2).attr("d",line);
svg.selectAll(".pt-"+s.pair).data(s.points).enter().append("circle")
.attr("cx",p=>x(new Date(p.d+"T00:00:00Z"))).attr("cy",p=>y(p.wr)).attr("r",3)
.attr("fill",DATA.color[s.pair])
.on("mousemove",(e,p)=>{tip.style.display="block";
tip.style.left=(e.clientX+12)+"px"; tip.style.top=(e.clientY+12)+"px";
tip.innerHTML=s.pair+" · "+p.d+"<br>局数 "+p.g+" · 胜 "+p.w+"<br>胜率 "+(p.wr*100).toFixed(1)+"%";})
.on("mouseleave",()=>tip.style.display="none");
});
}
draw();
</script>
</body></html>
"""
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
data = build(Path(a.snapshot))
out = Path(a.out) / "reports" / "daily.html"
_layout.SET = _layout.set_of(a.out)
out.parent.mkdir(parents=True, exist_ok=True)
_layout.ensure_assets(out.parent)
html = (HTML.replace("__DATA__", json.dumps(data, ensure_ascii=False))
.replace("__SET__", _layout.SET)
.replace("__LAYOUT_CSS__", _layout.CSS)
.replace("__BANNER__", _layout.banner("daily.html"))
.replace("__FOOTBANNER__", _layout.footbanner(
"按天统计(UTC);游标悬停看当天局数/胜场/胜率。样本 = 7 胜奖杯牌表,绝对胜率偏高。")))
out.write_text(html, encoding="utf-8")
print(f"wrote {out} ({len(data['days'])} 天, {len(data['series'])} 个色组)")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""Render the matchup matrix as an interactive HTML heatmap.
Output: value/<SNAPSHOT>/reports/matchups.html
* color-pair 10x10
* the 21 template clusters vs opponent pairs (click a column header to sort)
"""
from __future__ import annotations
import argparse
import sys
import html
import json
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _layout # noqa: E402
PAIRS = ["WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"]
AVG = 0.84
def esc(s):
return html.escape(str(s))
def color(wr, lo=0.70, hi=0.95):
if wr is None:
return "#1b1e27"
t = max(0.0, min(1.0, (wr - lo) / (hi - lo)))
hue = 8 + t * 130 # red -> green
return f"hsl({hue:.0f},58%,{28 + t * 16:.0f}%)"
def build(out_dir: Path, report_dir: Path) -> None:
_layout.SET = _layout.set_of(out_dir)
_mx = sorted((out_dir / "matchups").glob("*.PremierDraft.matrix.json"))
if not _mx:
raise SystemExit(f"no matchups/*.PremierDraft.matrix.json under {out_dir}")
m = json.loads(_mx[0].read_text(encoding="utf-8"))
index = json.loads((out_dir / "templates/_index.json").read_text(encoding="utf-8"))
def cell_table(title, keys, row_label, matrix, cols):
head = "".join(f'<th class="sortcol" data-i="{i}">{c}</th>' for i, c in enumerate(cols))
rows = ""
for k in keys:
row = matrix.get(k, {})
tds = ""
for i, opp in enumerate(cols):
c = row.get(opp)
if c and c.get("n"):
wr = c["winrate"]
tds += (f'<td class="cell" data-i="{i}" data-v="{wr}" '
f'style="background:{color(wr)}" title="n={c["n"]} CI={c.get("ci")}">'
f'{wr*100:.0f}%<span class="n">{c["n"]}</span></td>')
else:
tds += f'<td class="cell empty" data-i="{i}" data-v=""></td>'
rows += f'<tr><td class="name">{row_label(k)}</td>{tds}</tr>'
return f"""<h2>{title}</h2>
<table class="mx"><thead><tr><th>我方 \\ 对手</th>{head}</tr></thead><tbody>{rows}</tbody></table>"""
pair_tbl = cell_table("双色对 × 双色对", PAIRS, lambda k: k, m["color_pair_matrix"], PAIRS)
tpl_tbl = cell_table("子流派模板 × 对手双色(点列头排序)",
[s for s in index if not s.endswith("-Other")],
lambda s: f'<a href="templates/{esc(s)}.html">{esc(index[s]["name"])}</a>',
m["matrix"], PAIRS)
doc = f"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{_layout.SET} 克制矩阵</title><style>{CSS}{_layout.CSS}</style></head><body>
{_layout.banner("matchups.html")}
<main class="wrap">
<h1>{_layout.SET} PremierDraft · 克制矩阵</h1>
<p class="note">数字 = 我方胜率(格子右下小字为样本 n,鼠标悬停看置信区间)。我方均为 7 胜奖杯牌表,
绝对胜率偏高,请看<b>相对差异</b>;绿=占优,红=吃亏。点表头/列头可排序。</p>
{pair_tbl}
{tpl_tbl}
<p class="note">来源:<code>matchups/{_layout.SET}.PremierDraft.matrix.json</code>,由 {m['games']} 局(data/17lands 的 event_details)统计。</p>
</main>
{_layout.footbanner("数字 = 我方胜率;格子右下小字为样本 n。我方均为 7 胜奖杯牌表,绝对胜率偏高,请看相对差异;绿 = 占优,红 = 吃亏。")}
<script>{JS}</script>
</body></html>"""
report_dir.mkdir(parents=True, exist_ok=True)
_layout.ensure_assets(report_dir)
(report_dir / "matchups.html").write_text(doc, encoding="utf-8")
print(f"wrote {report_dir / 'matchups.html'}")
CSS = """
*{box-sizing:border-box} body{font-family:system-ui,'Segoe UI',sans-serif;margin:0;padding:20px;background:#12141a;color:#e8e8ea}
a{color:#7cc4ff;text-decoration:none} h1{margin:.3em 0} h2{margin-top:1.2em}
.topbar{font-size:14px}.note{color:#9aa2b1;font-size:13px;max-width:1000px}
table.mx{border-collapse:separate;border-spacing:3px;font-size:12px;margin-top:8px}
table.mx th{background:#1b1e27;color:#c7cfdd;padding:5px 7px;border-radius:6px;font-weight:600;cursor:pointer;user-select:none}
table.mx th.sortcol::after{content:' ⇅';opacity:.35}
table.mx th.sortcol[data-dir=asc]::after{content:' ▲';opacity:1}
table.mx th.sortcol[data-dir=desc]::after{content:' ▼';opacity:1}
table.mx td{text-align:center;border-radius:6px;padding:5px 7px;min-width:52px;color:#fff}
table.mx td.name{background:#1b1e27;text-align:left;font-weight:600;white-space:nowrap;min-width:230px}
table.mx td.empty{background:#15181f}
td.cell .n{display:block;font-size:9px;opacity:.7}
"""
JS = """
document.querySelectorAll('table.mx th.sortcol').forEach(th => {
th.addEventListener('click', () => {
const tbl = th.closest('table');
const tb = tbl.tBodies[0];
const i = +th.dataset.i;
const dir = th.dataset.dir === 'asc' ? 'desc' : 'asc';
th.dataset.dir = dir;
tbl.querySelectorAll('th.sortcol').forEach(o => { if (o !== th) o.removeAttribute('data-dir'); });
const rows = [...tb.rows];
rows.sort((a, b) => {
const an = a.cells[i + 1].dataset.v, bn = b.cells[i + 1].dataset.v;
if (an === '' && bn === '') return 0;
if (an === '') return 1;
if (bn === '') return -1;
return dir === 'asc' ? parseFloat(an) - parseFloat(bn) : parseFloat(bn) - parseFloat(an);
});
rows.forEach(r => tb.appendChild(r));
});
});
"""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--report-dir", default=None)
a = ap.parse_args()
out = Path(a.out)
rd = Path(a.report_dir) if a.report_dir else out / "reports"
build(out, rd)
if __name__ == "__main__":
main()
File diff suppressed because it is too large Load Diff
+683
View File
@@ -0,0 +1,683 @@
#!/usr/bin/env python3
"""用 17lands 的真实轮抓数据验证 bin/advisor/v2.0/advisor(M7)。
两种模式:
--replay 在同一串真实卡包里,把 advisor 的推荐和人类实际抓的牌对拍,
给出「首选吻合率 / 人类选择落在 advisor 前三的比例」,以及两个基线
(随机、无脑抓全场 GIH 最高)作为参照。
--full 让 advisor 自己抓完一包(不再参考人类选牌),抓完直接 build,
检查能不能配出合法的 40 张(23 咒语 + 17 地)。
--md 额外生成一份可评估的 Markdown 报告:每局的 advisor 牌表、人类实际牌表、
费用分布 / 生物比例对比、对同一牌池的 20 个子流派拟合度。
数据来源:data/17lands/<snapshot>/draftdata/*.json(每手都带该座位看到的
完整 `available` 包)与 trophies/trophies_decks.jsonl(人类最终牌表)。
注意:包流用的是人类座位看到的包。真实轮抓里自己的选牌会改变回传到你手上的
包(包在转),所以 --full 是近似模拟——这是我们手头唯一真实的包流。
用法:
python scripts/sim_draft.py --replay -n 50
python scripts/sim_draft.py --full -n 50 --verbose
python scripts/sim_draft.py -n 50 --draft-colors BR --md bin/sim.md
"""
import argparse
import importlib.machinery
import importlib.util
import json
import random
import statistics
import sys
from collections import Counter
from datetime import date
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BASIC_BY_COLOR = {"W": "Plains", "U": "Island", "B": "Swamp", "R": "Mountain", "G": "Forest"}
CN_BASIC = {"W": "平原", "U": "海岛", "B": "沼泽", "R": "山脉", "G": "森林"}
# 曲线桶 → 代表 CMC(算「目标平均 CMC」用)
BUCKET_CMC = {"1": 1.0, "2": 2.0, "3": 3.0, "4": 4.0, "5": 5.0, "6+": 6.0}
FULL_DRAFT_PICKS = 42 # 一局完整轮抓 = 14×3 = 42 手;不足的一律不当测试用例
def load_advisor():
"""bin/advisor/<version>/advisor 没有 .py 后缀,必须显式给 SourceFileLoader。"""
_c = sorted((ROOT / "bin" / "advisor").glob("v*/advisor"))
path = _c[-1] if _c else (ROOT / "bin" / "advisor" / "v2.0" / "advisor")
loader = importlib.machinery.SourceFileLoader("advisor", str(path))
spec = importlib.util.spec_from_loader("advisor", loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
def human_arch_label(adv, d, rec):
"""人类牌表最合的 archetype slug(对 20 个 main 取 archetype_fit 最大)—— 用作分层标签。"""
if not rec:
return None
have = {}
for c in rec.get("maindeck") or []:
nm = str(c.get("name") or "")
if nm.isdigit() or adv.is_land(d, nm):
continue
have[nm] = have.get(nm, 0) + (c.get("count") or 1)
if not have:
return None
fits = {s: adv.archetype_fit(d, s, have) for s in d.main}
return max(fits, key=lambda s: fits[s]) if fits else None
# ---------------------------------------------------------------- 数据读取
def read_drafts(snap_dir: Path, n: int, seed: int, decks=None, colors=None,
require_full: int = FULL_DRAFT_PICKS, adv=None, data=None, per_arch=None):
"""按 draftdata 读包流,并做**分层抽样**(避免抽出来挤在一种类型里)。
* **日志不完整(不足 `require_full` 手)的局直接剔除**,不当测试用例;
* 传了 `colors`(如 "BR" / "UR")→ 只保留人类牌表是该色对的局,再随机抽 n;
* 否则按**人类牌表色对分层**,按比例随机抽 n(各色组都进来一点);
* n=0 或 ≥ 可用局数 → 全要。
返回 `(chosen, stats)`,其中 `chosen=[(stem, seq), ...]`,
`stats={"total": 文件数, "full": 完整局数, "dropped": 剔除数}`。
"""
random.seed(seed)
parsed, dropped = [], 0
for f in sorted((snap_dir / "draftdata").glob("*.json")):
try:
dd = json.loads(f.read_text(encoding="utf-8"))
except Exception:
dropped += 1
continue
seq = []
for pk in dd.get("picks") or []:
pack = [c["name"] for c in (pk.get("available") or []) if c.get("name")]
human = (pk.get("pick") or {}).get("name")
if pack and human:
seq.append((pack, human))
if require_full and len(seq) < require_full:
dropped += 1
continue
parsed.append((f.stem, seq))
stats = {"total": len(parsed) + dropped, "full": len(parsed), "dropped": dropped}
if colors:
want = str(colors).upper()
parsed = [(s, q) for s, q in parsed
if str(((decks or {}).get(s) or {}).get("colors") or "").upper().startswith(want)]
if per_arch and adv is not None and data is not None:
# 按“人类牌最合的 arch”分层,每档最多 per_arch 局(覆盖 20 个 main arch)
groups = {}
for s, q in parsed:
L = human_arch_label(adv, data, (decks or {}).get(s))
if L:
groups.setdefault(L, []).append((s, q))
chosen = []
for g in groups.values():
random.shuffle(g)
chosen += g[:per_arch]
random.shuffle(chosen)
stats["per_arch"] = per_arch
stats["covered"] = len(groups)
return chosen, stats
if not n or n >= len(parsed):
chosen = list(parsed)
elif decks:
groups = {}
for s, q in parsed:
key = str(((decks.get(s) or {}).get("colors") or "?")).upper()
groups.setdefault(key, []).append((s, q))
for g in groups.values():
random.shuffle(g)
total = len(parsed)
alloc = {k: int(n * len(g) / total) for k, g in groups.items()}
rem = n - sum(alloc.values())
for _, k in reversed(sorted((n * len(g) / total - alloc[k], k) for k, g in groups.items())):
if rem <= 0:
break
alloc[k] += 1
rem -= 1
chosen = []
for k, g in groups.items():
chosen += g[:alloc[k]]
if len(chosen) < n: # 某些层样本不够,从剩余里补
picked = {s for s, _ in chosen}
rest = [(s, q) for s, q in parsed if s not in picked]
random.shuffle(rest)
chosen += rest[:n - len(chosen)]
chosen = chosen[:n]
random.shuffle(chosen)
else:
chosen = random.sample(parsed, n) if n < len(parsed) else list(parsed)
return chosen, stats
def read_decks(snap_dir: Path):
decks = {}
p = snap_dir / "trophies" / "trophies_decks.jsonl"
if p.exists():
for line in p.read_text(encoding="utf-8").splitlines():
if line.strip():
r = json.loads(line)
decks[r["aggregate_id"]] = r
return decks
def basic_ids(deck_rows):
"""基本地在 17lands 里 name 存的是数字 mtga_id,名字只能靠牌表反推。
判据:单副里出现过 ≥5 张(非基本地不会放 5 张)。颜色取「所有含该 id 的牌表
颜色集合的交集」——一定是该基本地颜色集的子集。交集只剩一种颜色就能确定,
否则给出候选(宁可写「基本地(森林/山脉)」也不能猜错)。
"""
inter, mx = {}, {}
for r in deck_rows:
cols = set((r.get("colors") or "").upper()) & set("WUBRG")
for c in r.get("maindeck") or []:
nm = str(c.get("name") or "")
if not nm.isdigit():
continue
mid, k = c["mtga_id"], c.get("count") or 1
inter[mid] = (inter[mid] & cols) if mid in inter else set(cols)
mx[mid] = max(mx.get(mid, 0), k)
out = {}
for mid, cs in inter.items():
if mx.get(mid, 0) < 5:
continue
if len(cs) == 1:
out[mid] = BASIC_BY_COLOR[next(iter(cs))]
elif cs:
out[mid] = "基本地(%s)" % "/".join(CN_BASIC[c] for c in sorted(cs, key="WUBRG".index))
else:
out[mid] = "基本地"
return out
def human_pairs(rec, id2name):
"""人类牌表的 [(名字, 张数), ...];数字 id 的地翻成 Plains/Island/…"""
out = []
for c in rec.get("maindeck") or []:
nm = str(c.get("name") or "")
if nm.isdigit():
nm = id2name.get(c["mtga_id"], "land#%s" % c["mtga_id"])
out.append((nm, c.get("count") or 1))
return out
# ---------------------------------------------------------------- 牌表分析
def curve_profile(d, adv, pairs):
"""费用分布 / 平均 CMC。只统计非地牌;cmc 拿不到的单独计。"""
buckets = Counter()
tot = n = 0
for nm, k in pairs:
cmc = d.cmc(nm)
if cmc is None:
continue
buckets[adv.curve_bucket(cmc)] += k
tot += cmc * k
n += k
avg = (tot / n) if n else None
return {"buckets": buckets, "avg": avg, "n": n}
def is_land_like(d, adv, nm):
"""基本地不在 d.cdata 里,adv.is_land 认不出来,得另外判一下。"""
return (nm in adv.BASICS or nm.startswith("land#") or nm.startswith("基本地")
or adv.is_land(d, nm))
def is_creature(d, nm):
return "creature" in " ".join((d.cdata.get(nm) or {}).get("types") or []).lower()
def deck_strength(d, pairs):
vals = []
for nm, k in pairs:
wr = (d.cdata.get(nm) or {}).get("ever_drawn_win_rate")
if wr is not None:
vals += [wr] * k
return statistics.mean(vals) if vals else None
def fmt_curve(prof, order):
return " ".join("%s:%d" % (b, prof["buckets"].get(b, 0)) for b in order)
# ---------------------------------------------------------------- 模拟一局
def simulate(d, adv, seq, rec, id2name):
pool, locked = [], None
for i, (pack, _human) in enumerate(seq):
if locked is None and adv.LOCK_FROM_PICK > 0 and i + 1 >= adv.LOCK_FROM_PICK:
locked = adv.commit_arch(d, adv.pool_counts(pool), None)
scored, _, _ = adv.score_cards(d, pack, adv.pool_counts(pool), None,
{"pick_index": i + 1, "locked": locked})
pool.append(scored[0]["name"])
have = adv.pool_counts(pool)
built = adv.build_deck(d, have, None)
deck = built["deck"]
slug = built["archetype"]["slug"]
t = d.templates[slug]
spell_pairs = [(s["name"], s["count"]) for s in deck["spells"]]
land_pairs = [(nm, k) for nm, k in deck["lands"].items()]
over = {s["name"]: (s["count"], have.get(s["name"], 0))
for s in deck["spells"] if s["count"] > have.get(s["name"], 0)}
problems = [] # build 自己的错(总数不对 / 超池)
warns = [] # 牌池本身的限制(这位玩家的日志只留下 27 手之类)
total = deck["total_spells"] + deck["total_lands"]
if total != 40:
problems.append("总数 %d≠40" % total)
if deck["total_spells"] < 23:
warns.append("牌池只有 %d 张可打咒语" % deck["total_spells"])
if over:
problems.append("超出牌池 %s" % list(over)[:2])
hpairs = human_pairs(rec, id2name) if rec else []
h_spells = [(nm, k) for nm, k in hpairs if not is_land_like(d, adv, nm)]
h_lands = [(nm, k) for nm, k in hpairs if is_land_like(d, adv, nm)]
dp = t.get("deck_params") or {}
cre_target = float(dp.get("creature_ratio") or 0.55)
land_target = float(dp.get("land_count") or 17)
n_cre = sum(k for nm, k in spell_pairs if is_creature(d, nm))
cre_ok = abs(n_cre - cre_target * 23.0) <= cre_target * 23.0 * adv.CRE_TOL
q_ad = deck_strength(d, spell_pairs)
q_hu = deck_strength(d, h_spells) if h_spells else None
shared = set(nm for nm, _ in spell_pairs) & set(nm for nm, _ in h_spells)
main = [s for s in d.index if not s.endswith("-Other")]
fits = {s: adv.archetype_fit(d, s, have) for s in main}
# advisor / 人类 各自**最终牌表**在同一 advisor 思路下的拟合度
# (只算咒语、均不含地,apples-to-apples)
adv_have = {nm: k for nm, k in spell_pairs}
hu_have = {nm: k for nm, k in h_spells}
fit_adv = adv.archetype_fit(d, slug, adv_have)
fit_hu = adv.archetype_fit(d, slug, hu_have) if hu_have else None
hu_fits = {s: adv.archetype_fit(d, s, hu_have) for s in main} if hu_have else {}
hu_best = max(hu_fits, key=lambda s: hu_fits[s]) if hu_fits else None
# 曲线贴合度:实际分布 vs 该 stream 的目标曲线(L1,归一到 23 张便于对比)
ctarget = adv.target_curve(d, t)
tgt_cmc = (sum(BUCKET_CMC.get(b, 6) * v for b, v in ctarget.items())
/ (sum(ctarget.values()) or 1.0))
ad_curve = curve_profile(d, adv, spell_pairs)["buckets"]
dev_ad = sum(abs(ad_curve.get(b, 0) - ctarget.get(b, 0)) for b in ctarget)
dev_ad = dev_ad * 23.0 / max(1, sum(ad_curve.values()))
dev_hu = None
if h_spells:
hb = curve_profile(d, adv, h_spells)["buckets"]
dev_hu = sum(abs(hb.get(b, 0) - ctarget.get(b, 0)) for b in ctarget)
dev_hu = dev_hu * 23.0 / max(1, sum(hb.values()))
return {
"picks": sum(have.values()),
"hand": len(seq),
"slug": slug, "arch": t["archetype_name"],
"colors": (t.get("colors") or t["archetype"]).upper(),
"fit": fits[slug],
"spells": spell_pairs, "lands": land_pairs,
"spell_n": sum(k for _, k in spell_pairs),
"land_n": sum(k for _, k in land_pairs),
"creatures": sum(k for nm, k in spell_pairs if is_creature(d, nm)),
"cre_target": cre_target, "cre_ok": cre_ok,
"tgt_cmc": tgt_cmc, "land_target": land_target,
"fit_adv": fit_adv, "fit_hu": fit_hu, "hu_fits": hu_fits,
"hu_best": hu_best, "hu_best_fit": (hu_fits.get(hu_best) if hu_best else None),
"curve": curve_profile(d, adv, spell_pairs),
"q_advisor": q_ad, "q_human": q_hu,
"curve_dev": dev_ad, "curve_dev_human": dev_hu,
"problems": problems, "warns": warns, "mtga": deck["mtga"], "fits": fits,
"human_arch": (rec or {}).get("colors") or "?",
"human_record": ("%d-%d" % (rec["wins"], rec["losses"])) if rec else "?",
"human_spells": h_spells, "human_lands": h_lands,
"human_curve": curve_profile(d, adv, h_spells) if h_spells else None,
"shared": len(shared),
"best_fit": max(fits, key=lambda s: fits[s]) if fits else None,
}
# ---------------------------------------------------------------- 对拍模式
def mode_replay(d, adv, drafts, verbose):
tot = a1 = a3 = rnd1 = b1 = 0
per = []
for stem, seq in drafts:
pool, ok, locked = [], 0, None
for i, (pack, human) in enumerate(seq):
if locked is None and adv.LOCK_FROM_PICK > 0 and i + 1 >= adv.LOCK_FROM_PICK:
locked = adv.commit_arch(d, adv.pool_counts(pool), None)
scored, _, _ = adv.score_cards(d, pack, adv.pool_counts(pool), None,
{"pick_index": i + 1, "locked": locked})
top = [x["name"] for x in scored]
tot += 1
a1 += top[0] == human
a3 += human in top[:3]
b1 += max(pack, key=lambda nm: ((d.cdata.get(nm) or {}).get("ever_drawn_win_rate") or 0)) == human
rnd1 += random.choice(pack) == human
ok += top[0] == human
pool.append({"name": human, "count": 1})
per.append((stem[:8], len(seq), ok))
print("回放 %d 局 / %d 手(在同一串包流里对拍)" % (len(drafts), tot))
print(" 随机抓一张 = 人类 : %5.1f%%" % (rnd1 / tot * 100))
print(" 无脑抓全场GIH最高 = 人类 : %5.1f%%" % (b1 / tot * 100))
print(" advisor 首选 = 人类 : %5.1f%%" % (a1 / tot * 100))
print(" 人类选择 ∈ 前三 : %5.1f%%" % (a3 / tot * 100))
if verbose:
print("\n 每局:draft / 手数 / 首选吻合")
for stem, n, ok in per:
print(" %s %3d 手 %2d/%d" % (stem, n, ok, n))
return {"picks": tot, "top1": a1 / tot, "top3": a3 / tot,
"baseline_gih": b1 / tot, "baseline_random": rnd1 / tot}
# ---------------------------------------------------------------- 完整模拟
def mode_full(d, adv, drafts, decks, id2name, verbose):
rows = []
for stem, seq in drafts:
r = simulate(d, adv, seq, decks.get(stem), id2name)
r["draft"] = stem[:8]
r["stem"] = stem
rows.append(r)
if verbose:
print("=" * 74)
print("%s 抓了 %d 手 → %s" % (r["draft"], r["picks"], r["arch"]))
print(r["mtga"])
print()
print("%-9s %4s %-34s %-4s %4s %3s %4s %s" % (
"draft", "手数", "advisor→思路", "色组", "咒语", "地", "生物", "问题"))
for r in rows:
mark = " ".join(r["problems"])
if r.get("warns"):
mark = (mark + " " + "/".join(r["warns"])).strip()
print("%-9s %4d %-34s %-4s %4d %3d %4d %s" % (
r["draft"], r["picks"], r["arch"][:34], r["colors"],
r["spell_n"], r["land_n"], r["creatures"], mark))
bad = [r for r in rows if r["problems"]]
print()
print("合法 40 张: %d/%d" % (len(rows) - len(bad), len(rows)))
nwarn = [r for r in rows if r.get("warns")]
if nwarn:
print("(另有 %d 局牌池本身就凑不够 23 咒语:%s)"
% (len(nwarn), "、".join("%s %s" % (r["draft"], ";".join(r["warns"])) for r in nwarn)))
qs = [(r["q_advisor"], r["q_human"]) for r in rows if r["q_advisor"] and r["q_human"]]
if qs:
ma = statistics.mean(q[0] for q in qs)
mh = statistics.mean(q[1] for q in qs)
print("配出牌组强度(非地牌全场 GIH 均值): advisor %.4f vs 人类实际 %.4f (%+.4f)"
% (ma, mh, ma - mh))
fs = [(r["fit_adv"], r["fit_hu"]) for r in rows if r.get("fit_hu") is not None]
if fs:
print("拟合度 fit(同一 advisor 思路,牌表 23 张,只算咒语): advisor %.1f vs 人类 %.1f (%+.1f)"
% (statistics.mean(f[0] for f in fs), statistics.mean(f[1] for f in fs),
statistics.mean(f[0] - f[1] for f in fs)))
print("人类牌自己最合的思路 = advisor 思路: %d/%d"
% (sum(1 for r in rows if r.get("hu_best") == r["slug"]), len(rows)))
print("目标均值: CMC %.2f · 生物 %.1f · 地 %.1f" % (
statistics.mean(r["tgt_cmc"] for r in rows),
statistics.mean(r["cre_target"] * 23.0 for r in rows),
statistics.mean(r["land_target"] for r in rows)))
print("思路分布:", dict(Counter(r["colors"] for r in rows).most_common()))
return rows
# ---------------------------------------------------------------- Markdown 报告
def _code_deck(d, adv, pairs, lands=None):
lines = ["Deck"]
for nm, k in pairs:
lines.append("%d %s" % (k, nm))
if lands:
for nm, k in sorted(lands, key=lambda x: -x[1]):
lines.append("%d %s" % (k, nm))
return "```\n" + "\n".join(lines) + "\n```"
def render_markdown(d, adv, rows, meta, replay):
order = [b for b, _ in adv.CURVE]
L = []
A = L.append
A("# FRA Premier Draft — advisor 模拟报告")
A("")
A("> 快照 `%s` · 抽样 %d 局(seed %d)· 生成于 %s" % (
meta["snapshot"], len(rows), meta["seed"], date.today()))
A("> 数据:`data/17lands/%s/draftdata/*.json`(真实包流)+ `trophies/trophies_decks.jsonl`(人类牌表)" % meta["snapshot"])
A("> 程序:`bin/advisor/v2.0/advisor`(M7)· 复现:`python scripts/sim_draft.py -n %d --md bin/sim.md`" % len(rows))
A("")
A("**怎么读这份报告**:advisor 在同一串真实卡包里**自己重抓一遍**(不看人类选牌),")
A("抓完调 `build` 配 40 张。「人类」列是同一位玩家实际打出来的牌表(数据源是奖杯牌表,")
A("所以战绩都是 7-x,不是全部对局的样本)。17lands 对基本地只存数字 id,")
A("报告中按「含它的所有牌表颜色交集」标成 `基本地(森林/山脉)` 这样的候选形式,不瞎猜。")
A("")
A("---")
A("")
# ---- 摘要
bad = [r for r in rows if r["problems"]]
warns = [r for r in rows if r.get("warns")]
# 牌池残缺(日志不完整)的局会把均值带偏,统计口径只算“牌池完整”的局
M = [r for r in rows if not r.get("warns")] or rows
qs = [(r["q_advisor"], r["q_human"]) for r in M if r["q_advisor"] and r["q_human"]]
A("## 摘要")
A("")
A("| 指标 | 结果 |")
A("|---|---|")
A("| 配出合法 40 张 | **%d / %d** |" % (len(rows) - len(bad), len(rows)))
if meta.get("per_arch"):
A("| 抽样口径 | 按 arch(人类牌最合)分层,每 arch %d 局 |" % meta["per_arch"])
if warns:
A("| 其中牌池本身凑不够 23 咒语 | %d 局(%s;日志残缺,非 build 问题) |"
% (len(warns), "、".join("`%s`" % r["draft"] for r in warns)))
if len(M) != len(rows):
A("| 下方均值口径 | 只计入牌池完整的 **%d / %d** 局 |" % (len(M), len(rows)))
if qs:
ma = statistics.mean(q[0] for q in qs)
mh = statistics.mean(q[1] for q in qs)
A("| 牌组强度(非地牌全场 GIH 均值) | advisor **%.4f** vs 人类 %.4f(%+.4f) |" % (ma, mh, ma - mh))
fs = [(r["fit_adv"], r["fit_hu"]) for r in M if r.get("fit_hu") is not None]
fo = [(r["fit_adv"], r["hu_best_fit"]) for r in M if r.get("hu_best_fit") is not None]
if fs:
A("| 拟合度 fit(人类牌套 advisor 思路,牌表 23 张) | advisor **%.1f** vs 人类 %.1f(%+.1f) |" % (
statistics.mean(f[0] for f in fs), statistics.mean(f[1] for f in fs),
statistics.mean(f[0] - f[1] for f in fs)))
if fo:
A("| 拟合度 fit(各自最合思路,牌表 23 张) | advisor **%.1f** vs 人类 %.1f(%+.1f) |" % (
statistics.mean(f[0] for f in fo), statistics.mean(f[1] for f in fo),
statistics.mean(f[0] - f[1] for f in fo)))
A("| **arch 一致性**(advisor 思路 = 人类牌最合思路) | **%d / %d(%.0f%%)** |" % (
sum(1 for r in M if r.get("hu_best") == r["slug"]), len(M),
100.0 * sum(1 for r in M if r.get("hu_best") == r["slug"]) / max(1, len(M))))
A("| 平均咒语 / 地 | %.1f / %.1f |" % (
statistics.mean(r["spell_n"] for r in M), statistics.mean(r["land_n"] for r in M)))
A("| 平均生物比例 | %.1f%% |" % (100 * statistics.mean(
(r["creatures"] / r["spell_n"]) for r in M if r["spell_n"])))
A("| 生物比例达标(±10%% 相对 archetype) | **%d / %d** |"
% (len([r for r in M if r["cre_ok"]]), len(M)))
A("| 平均 CMC | %.2f |" % statistics.mean(
r["curve"]["avg"] for r in M if r["curve"]["avg"] is not None))
A("| 目标 CMC / 生物 / 地(各思路均值) | %.2f / %.1f / %.1f |" % (
statistics.mean(r["tgt_cmc"] for r in M),
statistics.mean(r["cre_target"] * 23.0 for r in M),
statistics.mean(r["land_target"] for r in M)))
dvs = [r for r in M if r.get("curve_dev") is not None]
if dvs:
line = "| 曲线贴合度(实际 vs 目标,L1,归一到 23) | advisor **%.2f**" % statistics.mean(
r["curve_dev"] for r in dvs)
dhu = [r for r in dvs if r.get("curve_dev_human") is not None]
if dhu:
line += " vs 人类 %.2f |" % statistics.mean(r["curve_dev_human"] for r in dhu)
else:
line += " |"
A(line)
if replay:
A("| 对拍:首选吻合 / 前三 | %.1f%% / %.1f%%(随机 %.1f%%,无脑抓最高 GIH %.1f%%) |" % (
100 * replay["top1"], 100 * replay["top3"],
100 * replay["baseline_random"], 100 * replay["baseline_gih"]))
A("| 平均抓牌手数(42=日志完整) | %.1f(完整 %d / %d) |" % (
statistics.mean(r["picks"] for r in rows),
sum(1 for r in rows if r["picks"] >= 42), len(rows)))
A("| 平均与人类牌表重合 | %.1f 张 |" % statistics.mean(r["shared"] for r in M))
A("")
dist = Counter(r["colors"] for r in rows)
A("**思路分布**:" + " · ".join("%s ×%d" % (k, v) for k, v in dist.most_common()))
A("")
if bad:
A("**有问题的局**:" + ";".join("%s(%s)" % (r["draft"], "、".join(r["problems"])) for r in bad))
A("")
# ---- 逐局
A("## 逐局详情")
A("")
for i, r in enumerate(rows, 1):
A("### %d. `%s`" % (i, r["draft"]))
A("")
A("- 包流 **%d 手**(advisor 共抓 %d 张)" % (r["hand"], r["picks"]))
A("- advisor 思路:**%s**(色组 %s,fit %.1f)" % (r["arch"], r["colors"], r["fit"]))
A("- 牌表:**%d 咒语 + %d 地**,生物 %d 张(%.0f%%;archetype 目标 %.0f%% ±10%%)%s"
% (r["spell_n"], r["land_n"], r["creatures"],
100 * r["creatures"] / r["spell_n"] if r["spell_n"] else 0,
100 * r["cre_target"], "" if r["cre_ok"] else " ⚠️ 超出容差"))
A("- 费用分布:`%s`" % fmt_curve(r["curve"], order))
A("- 曲线贴合度(vs 目标,L1):advisor **%.2f**%s" % (
r["curve_dev"],
(" / 人类 %.2f" % r["curve_dev_human"]) if r.get("curve_dev_human") is not None else ""))
A("- 强度(非地牌全场 GIH 均值):advisor **%s**%s"
% (("%.4f" % r["q_advisor"]) if r["q_advisor"] else "—",
(" / 人类 %s(%s,%s)" % (("%.4f" % r["q_human"]) if r["q_human"] else "—",
r["human_arch"], r["human_record"])) if r["q_human"] else ""))
A("- 与人类牌表重合 **%d 张**" % r["shared"])
A("- 拟合度 fit(advisor 思路 **%s**,只算咒语):advisor **%.1f**/人类 %s%s" % (
r["arch"], r["fit_adv"],
("%.1f" % r["fit_hu"]) if r.get("fit_hu") is not None else "—",
("(人类牌自己最合:%s %.1f)" % (
d.templates[r["hu_best"]]["archetype_name"], r["hu_best_fit"]))
if r.get("hu_best") else ""))
if r["problems"]:
A("- ❌ **构建错误**:%s" % ";".join(r["problems"]))
if r.get("warns"):
A("- ⚠️ 牌池限制:%s(这局日志只留下 %d 手,非 build 问题)"
% (";".join(r["warns"]), r["picks"]))
A("")
A("**advisor 的牌表**")
A("")
A(_code_deck(d, adv, r["spells"], r["lands"]))
A("")
if r["human_spells"]:
A("**费用分布 / 指标对比**(目标 = 完美基线 2/7/6/4/3/1 打底 + 本 stream 实测浮动)")
A("")
tgt_name = d.templates[r["slug"]]["archetype_name"]
hu_name = (d.templates[r["hu_best"]]["archetype_name"]
if r.get("hu_best") in d.templates else "—")
A("| | arch | " + " | ".join(order) + " | 合计 | 平均 CMC | 生物 | 地 | 曲线贴合度 | 强度 | fit |")
A("|---|" + "---|" * (len(order) + 8))
tc = adv.target_curve(d, d.templates[r["slug"]])
A("| **目标** | %s | " % tgt_name + " | ".join("%.1f" % tc.get(b, 0) for b in order)
+ " | %.1f | %.2f | %.1f (%.0f%%) | %.1f | — | — | — |" % (
sum(tc.values()), r["tgt_cmc"], r["cre_target"] * 23.0,
100 * r["cre_target"], r["land_target"]))
A("| advisor | %s | " % tgt_name
+ " | ".join(str(r["curve"]["buckets"].get(b, 0)) for b in order)
+ " | %d | %s | %d (%.0f%%) | %d | %s | %s | %s |" % (
r["spell_n"],
("%.2f" % r["curve"]["avg"]) if r["curve"]["avg"] is not None else "—",
r["creatures"], 100 * r["creatures"] / r["spell_n"] if r["spell_n"] else 0, r["land_n"],
("%.2f" % r["curve_dev"]) if r.get("curve_dev") is not None else "—",
("%.4f" % r["q_advisor"]) if r["q_advisor"] else "—",
("%.1f" % r["fit_adv"]) if r.get("fit_adv") is not None else "—"))
hc = r["human_curve"]
h_cre = sum(k for nm, k in r["human_spells"] if is_creature(d, nm))
hu_tag = r["human_arch"] + (("(最合 %s)" % hu_name) if hu_name != "—" else "")
A("| 人类 | %s | " % hu_tag
+ " | ".join(str(hc["buckets"].get(b, 0)) for b in order)
+ " | %d | %s | %d (%.0f%%) | %d | %s | %s | %s |" % (
sum(hc["buckets"].values()),
("%.2f" % hc["avg"]) if hc["avg"] is not None else "—",
h_cre, 100 * h_cre / max(1, hc["n"]),
sum(k for _, k in r["human_lands"]),
("%.2f" % r["curve_dev_human"]) if r.get("curve_dev_human") is not None else "—",
("%.4f" % r["q_human"]) if r["q_human"] else "—",
("%.1f" % r["hu_best_fit"]) if r.get("hu_best_fit") is not None else "—"))
A("")
A("**人类实际牌表**(%s,%s)" % (r["human_arch"], r["human_record"]))
A("")
A(_code_deck(d, adv, r["human_spells"], r["human_lands"]))
A("")
A("---")
A("")
A("*报告由 `scripts/sim_draft.py` 生成;advisor 为确定性程序,同一 seed 必得同一结果。*")
return "\n".join(L)
# ---------------------------------------------------------------- main
def main() -> int:
ap = argparse.ArgumentParser(description="用 17lands 真实包流验证 bin/advisor/v2.0/advisor")
ap.add_argument("--snapshot", default="FRA20261011")
ap.add_argument("-n", type=int, default=50, help="抽样局数(0=全部);默认 50")
ap.add_argument("--seed", type=int, default=7)
ap.add_argument("--draft-colors", default=None,
help="只测某个色对的局(如 BR / UR);默认按色对分层随机抽,避免全是一种类型")
ap.add_argument("--per-arch", type=int, default=5,
help="按 arch 分层,每个 arch 抽 N 局(默认 5;0 = 关闭,改用 -n)")
ap.add_argument("--replay", action="store_true", help="只跑对拍")
ap.add_argument("--full", action="store_true", help="只跑完整模拟")
ap.add_argument("--verbose", action="store_true", help="打印每局细节/牌表")
ap.add_argument("--md", nargs="?", const="bin/sim.md", default=None,
help="生成 Markdown 报告(默认 bin/sim.md)")
ap.add_argument("--json", action="store_true", help="额外输出 JSON 摘要")
a = ap.parse_args()
if not a.replay and not a.full:
a.replay = a.full = True
adv = load_advisor()
d = adv.Data(a.snapshot)
snap = ROOT / "data" / "17lands" / a.snapshot
decks = read_decks(snap)
drafts, rd = read_drafts(snap, a.n, a.seed, decks, a.draft_colors,
adv=adv, data=d, per_arch=a.per_arch)
deck_rows = list(decks.values())
id2name = {c["mtga_id"]: nm for nm, c in d.cdata.items() if c.get("mtga_id")}
id2name.update({mid: nm for mid, nm in basic_ids(deck_rows).items() if mid not in id2name})
comp = Counter(str((decks.get(stem) or {}).get("colors") or "?") for stem, _ in drafts)
tag = ("· 每 arch %d 局(覆盖 %d arch)" % (rd["per_arch"], rd.get("covered", 0))
if rd.get("per_arch") else "")
print("### 抽样 %d 局(候选 %d,剔除不完整 %d)%s · 人类色对:%s\n" % (
len(drafts), rd["full"], rd["dropped"], tag,
" · ".join("%s×%d" % (k, v) for k, v in comp.most_common())))
summary = {"snapshot": a.snapshot, "drafts": len(drafts)}
replay = None
if a.replay:
print("### 对拍模式\n")
replay = mode_replay(d, adv, drafts, a.verbose)
summary["replay"] = replay
print()
if a.full or a.md:
print("### 完整模拟模式(advisor 自己抓 + build)\n")
rows = mode_full(d, adv, drafts, decks, id2name, a.verbose)
summary["full"] = {
"n": len(rows), "legal": len([r for r in rows if not r["problems"]]),
"q_advisor": statistics.mean([r["q_advisor"] for r in rows if r["q_advisor"]] or [0]),
"q_human": statistics.mean([r["q_human"] for r in rows if r["q_human"]] or [0]),
"fit_advisor": statistics.mean([r["fit_adv"] for r in rows if r.get("fit_adv") is not None] or [0]),
"fit_human": statistics.mean([r["fit_hu"] for r in rows if r.get("fit_hu") is not None] or [0]),
"target_cmc": statistics.mean([r["tgt_cmc"] for r in rows] or [0]),
"target_creatures": statistics.mean([r["cre_target"] * 23.0 for r in rows] or [0]),
"target_lands": statistics.mean([r["land_target"] for r in rows] or [0]),
"colors": dict(Counter(r["colors"] for r in rows)),
}
if a.md:
md = render_markdown(d, adv, rows,
{"snapshot": a.snapshot, "seed": a.seed, "per_arch": a.per_arch},
replay)
out = Path(a.md)
if not out.is_absolute():
out = ROOT / out
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(md, encoding="utf-8")
print("\nMarkdown 报告 → %s(%.1f KB)" % (out, len(md.encode("utf-8")) / 1024))
if a.json:
print()
print(json.dumps(summary, ensure_ascii=False, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main())
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Ablate the advisor's affinity / affinity_cluster weights on real draft data.
`card_value = W_GIH·gih + W_AFF·affinity + W_AFF_CLUSTER·affinity_cluster`
`affinity` = 该牌在**本颜色对**里的 GIH 相对 P0(组内质量,已按色对去均值)
`affinity_cluster` = 该牌在**本簇**里相对同色对的提升(簇内特异)
这两个都是「子集信号」(pair ⊂ 全局,cluster ⊂ pair),叠在全局 GIH 上会重复计分。
本脚本遍历一组权重,跑 sim_draft 的对拍 + 完整模拟,看 top1/top3 / 牌组强度 /
曲线贴合 / 生物达标 怎么变。
用法:
python scripts/tune_weights.py --snapshot FRA20261011 --per-arch 5
"""
from __future__ import annotations
import argparse
import io
import json
import statistics
import sys
from collections import Counter
from contextlib import redirect_stdout
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import sim_draft as S # noqa: E402
CONFIGS = [
("base .85/.80/.45", 0.85, 0.80, 0.45),
("aff .85/.60/.45", 0.85, 0.60, 0.45),
("aff .85/.40/.45", 0.85, 0.40, 0.45),
("aff .85/.20/.45", 0.85, 0.20, 0.45),
("clu .85/.80/.30", 0.85, 0.80, 0.30),
("clu .85/.80/.15", 0.85, 0.80, 0.15),
("both .85/.50/.25", 0.85, 0.50, 0.25),
("both .85/.35/.15", 0.85, 0.35, 0.15),
("nogih .85/.40/.00", 0.85, 0.40, 0.00),
("gih↑ 1.20/.40/.20", 1.20, 0.40, 0.20),
("aff .80 clu 0", 0.85, 0.80, 0.00),
("aff .60 clu .15", 0.85, 0.60, 0.15),
("gih1.0 .60/.15", 1.00, 0.60, 0.15),
]
def evaluate(adv, d, drafts, decks, id2name):
with redirect_stdout(io.StringIO()):
rp = S.mode_replay(d, adv, drafts, False)
rows = []
for stem, seq in drafts:
rows.append(S.simulate(d, adv, seq, decks.get(stem), id2name))
legal = sum(1 for r in rows if not r["problems"])
qa = [r["q_advisor"] for r in rows if r["q_advisor"]]
qh = [r["q_human"] for r in rows if r["q_human"]]
fa = [r["fit_adv"] for r in rows if r.get("fit_adv") is not None]
fh = [r["fit_hu"] for r in rows if r.get("fit_hu") is not None]
cd = [r["curve_dev"] for r in rows if r.get("curve_dev") is not None]
cre = sum(1 for r in rows if r["cre_ok"])
return {
"top1": rp["top1"], "top3": rp["top3"], "gih_base": rp["baseline_gih"],
"legal": legal, "n": len(rows),
"q_adv": statistics.mean(qa) if qa else 0.0,
"q_human": statistics.mean(qh) if qh else 0.0,
"fit_adv": statistics.mean(fa) if fa else 0.0,
"fit_hu": statistics.mean(fh) if fh else 0.0,
"curve": statistics.mean(cd) if cd else 0.0,
"cre": cre,
"colors": Counter(r["colors"] for r in rows).most_common(4),
}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", default="FRA20261011")
ap.add_argument("--per-arch", type=int, default=5)
ap.add_argument("--seed", type=int, default=7)
ap.add_argument("--pick", default=None, help="只跑指定下标的配置,如 0,1,4")
ap.add_argument("--json", default=None, help="把结果写成 json")
a = ap.parse_args()
adv = S.load_advisor()
d = adv.Data(a.snapshot)
snap = ROOT / "data" / "17lands" / a.snapshot
decks = S.read_decks(snap)
drafts, rd = S.read_drafts(snap, 0, a.seed, decks, None, adv=adv, data=d,
per_arch=a.per_arch)
id2name = {c["mtga_id"]: nm for nm, c in d.cdata.items() if c.get("mtga_id")}
id2name.update({mid: nm for mid, nm in S.basic_ids(list(decks.values())).items()
if mid not in id2name})
print("抽样 %d 局(%d 个 arch)· snapshot %s\n" % (len(drafts), rd.get("covered", 0), a.snapshot))
base = None
out = []
print("%-18s %6s %6s %8s %8s %7s %5s %5s" % (
"config", "top1", "top3", "q_adv", "fit_adv", "curve", "cre", "legal"))
cfgs = CONFIGS
if a.pick:
idx = [int(x) for x in a.pick.split(",") if x.strip() != ""]
cfgs = [CONFIGS[i] for i in idx]
for tag, wg, wa, wc in cfgs:
adv.W_GIH, adv.W_AFF, adv.W_AFF_CLUSTER = wg, wa, wc
m = evaluate(adv, d, drafts, decks, id2name)
out.append({"tag": tag, "W_GIH": wg, "W_AFF": wa, "W_AFF_CLUSTER": wc, **m})
if base is None:
base = m
print("%-18s %5.1f%% %5.1f%% %8.4f %8.1f %7.2f %3d/%-2d %3d/%d" % (
tag, m["top1"] * 100, m["top3"] * 100, m["q_adv"], m["fit_adv"],
m["curve"], m["cre"], m["n"], m["legal"], m["n"]))
print("\n(top1/top3 = 与人类选牌吻合;q_adv = 配出牌组强度(GIH 均值,偏高是循环指标);"
"fit_adv = 自身思路拟合度(同样循环);curve = 曲线 L1 越低越好;cre = 生物达标)")
if a.json:
Path(a.json).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
print("wrote", a.json)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+11 -4
View File
@@ -29,10 +29,17 @@ def primary_pair(colors):
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 None
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 build(snapshot: Path, out_dir: Path) -> None:
cards = {c["name"]: c for c in
json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]}