#!/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())