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:
@@ -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'}")
|
||||
Reference in New Issue
Block a user