File size: 7,388 Bytes
9542666 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | #!/usr/bin/env python3
"""Generate a self-contained interactive co-authorship graph (D3 force layout).
Nodes are authors (size + color by number of papers in the vault); edges are
co-authorships (width by number of papers shared). Filtered to authors with at
least --min-papers papers, and edges only between kept authors. One HTML file,
D3 from CDN; drag, scroll-zoom, hover a node for the name (the biggest hubs are
labelled always).
python3 _scripts/make_author_graph.py # >=3 papers -> reports/author-graph.html
python3 _scripts/make_author_graph.py --min-papers 5 --out reports/authors5.html
python3 _scripts/make_author_graph.py --embed --out graph.html # header stripped, for <iframe>
Companion to make_graph.py (the idea/paper stance graph); publishing recipe and
the HF-Space upload gotcha are in skills/visualize-graph/SKILL.md.
"""
import argparse
import glob
import json
import os
import re
from collections import Counter
from itertools import combinations
VAULT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def build(min_papers):
paper_authors = []
for f in glob.glob(os.path.join(VAULT, "papers", "*.md")):
m = re.search(r"^authors:\s*\[(.*)\]", open(f, encoding="utf-8").read(), re.M)
if m:
paper_authors.append(re.findall(r"\[\[(.+?)\]\]", m.group(1)))
cnt = Counter(a for auth in paper_authors for a in auth)
keep = {a for a, c in cnt.items() if c >= min_papers}
ew = Counter()
for auth in paper_authors:
kept = sorted(a for a in auth if a in keep)
for x, y in combinations(kept, 2):
ew[(x, y)] += 1
nodes = [{"id": a, "label": a, "n": cnt[a]} for a in sorted(keep, key=lambda a: -cnt[a])]
links = [{"source": x, "target": y, "w": w} for (x, y), w in ew.items()]
return {"nodes": nodes, "links": links, "maxn": max(cnt[a] for a in keep) if keep else 1}
HEADER = '''<div id="hd"><h1>{title}</h1>
<p>Authors with at least {min} papers in the corpus; links are co-authorships (thicker = more papers together). Node size and shade track paper count. Drag, scroll to zoom, hover for a name.</p></div>
'''
TEMPLATE = '''<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>{title}</title>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<style>
:root{{--bg:#fbfaf8;--ink:#1a1a1f;--muted:#6b6b78;--line:#e7e4de;}}
*{{box-sizing:border-box}} html,body{{margin:0;height:100%}}
body{{background:var(--bg);color:var(--ink);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;overflow:hidden}}
#hd{{position:fixed;top:0;left:0;right:0;padding:14px 20px;z-index:5;pointer-events:none}}
#hd h1{{font:600 19px/1.2 Georgia,serif;margin:0}}
#hd p{{margin:3px 0 0;color:var(--muted);font-size:13px;max-width:660px}}
#legend{{position:fixed;bottom:16px;left:16px;background:#fffdfaee;border:1px solid var(--line);border-radius:10px;padding:11px 13px;font-size:12.5px;z-index:5;box-shadow:0 2px 10px #0000000d}}
#legend b{{display:block;margin:0 0 6px;font-size:11px;letter-spacing:.05em;text-transform:uppercase;color:var(--muted)}}
#legend .row{{display:flex;align-items:center;gap:8px;margin:4px 0}}
#net{{width:100vw;height:100vh;cursor:grab}}
.link{{stroke:#b9b3a6;stroke-opacity:.5}}
.node circle{{stroke:#fff;stroke-width:1.2}}
.lbl{{font-size:11px;fill:var(--ink);pointer-events:none;paint-order:stroke;stroke:#fbfaf8;stroke-width:3px;stroke-linejoin:round}}
</style></head><body>
{header}<div id="legend">
<b>Node</b>
<div class="row"><svg width="46" height="16"><circle cx="8" cy="8" r="4" fill="#7fcdbb"/><circle cx="30" cy="8" r="8" fill="#0f5c58"/></svg>papers (size + shade)</div>
<b style="margin-top:8px">Link</b>
<div class="row"><svg width="46" height="10"><line x1="2" y1="5" x2="44" y2="5" stroke="#b9b3a6" stroke-width="1"/></svg>1 paper together</div>
<div class="row"><svg width="46" height="10"><line x1="2" y1="5" x2="44" y2="5" stroke="#b9b3a6" stroke-width="4"/></svg>many together</div>
</div>
<svg id="net"></svg>
<script>
const data={data};
const color=d3.scaleSequential(d3.interpolateYlGnBu).domain([{minp}, data.maxn]);
const R=n=>4+1.15*n, LBL_MIN=5;
const svg=d3.select("#net"),W=innerWidth,H=innerHeight,g=svg.append("g");
const zoom=d3.zoom().scaleExtent([0.15,4]).on("zoom",e=>g.attr("transform",e.transform));svg.call(zoom);
const link=g.append("g").selectAll("line").data(data.links).join("line")
.attr("class","link").attr("stroke-width",d=>0.6+d.w*0.55);
const node=g.append("g").selectAll("g").data(data.nodes).join("g").attr("class","node");
node.append("circle").attr("r",d=>R(d.n)).attr("fill",d=>color(d.n));
node.append("title").text(d=>d.label+" · "+d.n+" papers");
node.append("text").attr("class","lbl").attr("x",d=>R(d.n)+3).attr("y",4)
.style("opacity",d=>d.n>=LBL_MIN?1:0).text(d=>d.label);
node.on("mouseover",function(e,d){{d3.select(this).select("text").style("opacity",1)}})
.on("mouseout",function(e,d){{d3.select(this).select("text").style("opacity",d.n>=LBL_MIN?1:0)}});
node.call(d3.drag()
.on("start",(e,d)=>{{if(!e.active)sim.alphaTarget(.3).restart();d.fx=d.x;d.fy=d.y}})
.on("drag",(e,d)=>{{d.fx=e.x;d.fy=e.y}})
.on("end",(e,d)=>{{if(!e.active)sim.alphaTarget(0);d.fx=null;d.fy=null}}));
function ticked(){{
link.attr("x1",d=>d.source.x).attr("y1",d=>d.source.y).attr("x2",d=>d.target.x).attr("y2",d=>d.target.y);
node.attr("transform",d=>`translate(${{d.x}},${{d.y}})`);
}}
const sim=d3.forceSimulation(data.nodes)
.force("link",d3.forceLink(data.links).id(d=>d.id).distance(d=>82-Math.min(d.w,6)*5).strength(d=>0.14+d.w*0.05))
.force("charge",d3.forceManyBody().strength(-320).distanceMax(600))
.force("x",d3.forceX(W/2).strength(.05)).force("y",d3.forceY(H/2).strength(.05))
.force("collide",d3.forceCollide(d=>R(d.n)+7).strength(.9))
.stop();
sim.tick(400); // pre-settle synchronously (no animation race)
ticked();
fit();
sim.on("tick",ticked); // redraw when drag re-heats the sim
function fit(){{
const xs=data.nodes.map(d=>d.x),ys=data.nodes.map(d=>d.y);
const x0=Math.min(...xs),x1=Math.max(...xs),y0=Math.min(...ys),y1=Math.max(...ys);
const w=(x1-x0)||1,h=(y1-y0)||1,k=Math.min(3,0.9/Math.max(w/W,h/H));
svg.call(zoom.transform,d3.zoomIdentity.translate(W/2-k*(x0+x1)/2,H/2-k*(y0+y1)/2).scale(k));
}}
</script></body></html>'''
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--min-papers", type=int, default=3)
ap.add_argument("--embed", action="store_true")
ap.add_argument("--title", default=None)
ap.add_argument("--out", default="reports/author-graph.html")
a = ap.parse_args()
title = a.title or f"Co-authorship — authors with ≥{a.min_papers} papers"
data = build(a.min_papers)
header = "" if a.embed else HEADER.format(title=title, min=a.min_papers)
html = TEMPLATE.format(title=title, header=header, data=json.dumps(data), minp=a.min_papers)
out = a.out if os.path.isabs(a.out) else os.path.join(VAULT, a.out)
os.makedirs(os.path.dirname(out), exist_ok=True)
with open(out, "w", encoding="utf-8") as f:
f.write(html)
print(f"wrote {out}: {len(data['nodes'])} authors, {len(data['links'])} co-authorship edges")
if __name__ == "__main__":
main()
|