added report generation script for the multiplier presentation with GUIDE
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-07-29 12:18:33 +02:00
parent 577b9f4557
commit 74587f5c6d
4 changed files with 764 additions and 0 deletions
+28
View File
@@ -488,3 +488,31 @@ symbol size, `cross` → dashed line.
`nodes`/`edges` are mapped `"enabled": false` (stored, never indexed) — the index
stays small and fast for the queryable header fields (`institution_id`, `author_id`,
`ego.tags`, `computed_at`, …). Skip building with `--no-network`.
### Regenerating the HTML report
`make_report.py` renders a self-contained HTML report of four contrasting cases
straight from the two live ES indices — no local cache required, so it works on any
machine with cluster access after a build has run:
```bash
python make_report.py --institution-id I62318514
# -> reports/multiplier_networks.html (open in any browser; light/dark toggle)
python make_report.py --institution-id I62318514 \
--author-ids A5113304257,A5043495754,A5007801159,A5123934012 # explicit cast
```
The cast is pinned in `report.featured_author_ids` (config) so the report is
reproducible across weight tunes and dump refreshes; `--author-ids` overrides it and
`--auto` falls back to selecting the current top bridger / mentor / amplifier plus the
highest-scoring person who carries **no** tag — the last one exposes where the
thresholds bite (and, when that person's best sub-score is *above* 0.85, the
`tags.min_active_years` guard that withholds tags from one-year profiles, which are
usually **split** OpenAlex identities — the case `suspicious_profile` cannot catch,
since that flag detects merges).
The page layout lives in `report_template.html` (tracked); `reports/` and `cache/` are
gitignored, so a `git clean -fdx` or fresh checkout wipes generated reports and
extracts — re-run the command above to rebuild the report, and `build.py` only if the
indices themselves need refreshing.
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""
make_report.py — render the ego-network HTML report from the LIVE ES indices.
Reads `multiplicators_v1` (scores) + `multiplicator_networks_v1` (nodes/edges) —
the same two documents a frontend service would fetch — and writes a single
self-contained HTML file to reports/. No local cache needed: the report can be
regenerated any time after a build, on any machine with cluster access.
python make_report.py --institution-id I62318514
python make_report.py --institution-id I62318514 \
--author-ids A5113304257,A5043495754 # explicit cast instead of auto-pick
By default it picks one showcase per tag (highest bridger / mentor / amplifier)
plus the highest-scoring person who just misses the tag threshold — the four
contrasting cases that make the metrics legible.
The force-directed layout is computed here and baked into the file so the report
stays dependency-free; a real frontend should instead let echarts' `graph` series
lay out the same nodes/edges live.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import sys
from pathlib import Path
import httpx
import yaml
from dotenv import load_dotenv
SCRIPT_DIR = Path(__file__).resolve().parent
ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env"
load_dotenv(dotenv_path=ENV_PATH)
INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/")
INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or ""
SCORES_INDEX = "multiplicators_v1"
NETWORKS_INDEX = "multiplicator_networks_v1"
SCORE_FIELDS = (
"author_id", "display_name", "career_bucket", "active_years", "n_works",
"suspicious_profile", "tags", "sub_scores", "percentiles", "betweenness",
"brokerage", "constraint", "field_entropy", "cross_institution_share",
"strength", "n_coauthors", "industry_coauthor_share",
"industry_coauthor_share_shrunk", "juniors_mentored",
"junior_progression_rate", "mentoring_rate", "last_author_with_junior_first",
"patent_count", "news_mentions", "cordis_eu_projects",
)
# ---------------------------------------------------------------------
# ES access
# ---------------------------------------------------------------------
def _headers() -> dict[str, str]:
return {"Authorization": f"ApiKey {INSE_KEY}", "Content-Type": "application/json"}
def es_get(client: httpx.Client, index: str, doc_id: str) -> dict | None:
r = client.get(f"{INSE_URL}/{index}/_doc/{doc_id}", headers=_headers(), timeout=30)
if r.status_code == 404:
return None
r.raise_for_status()
return r.json()["_source"]
def es_search(client: httpx.Client, index: str, body: dict) -> dict:
r = client.post(f"{INSE_URL}/{index}/_search", headers=_headers(), json=body, timeout=60)
r.raise_for_status()
return r.json()
def pick_showcase(client: httpx.Client, institution: str) -> list[tuple[str, str]]:
"""(author_id, kind) for the top bridger / mentor / amplifier + top near-miss."""
picks: list[tuple[str, str]] = []
seen: set[str] = set()
for tag in ("bridger", "mentor", "amplifier"):
res = es_search(client, SCORES_INDEX, {
"size": 5,
"_source": ["author_id"],
"query": {"bool": {"filter": [
{"term": {"institution_id": institution}},
{"term": {"tags": tag}},
]}},
"sort": [{f"sub_scores.{tag}": {"order": "desc"}}],
})
for hit in res["hits"]["hits"]:
aid = hit["_source"]["author_id"]
if aid not in seen:
picks.append((aid, tag))
seen.add(aid)
break
# highest scorer that carries no tag — shows where the threshold bites
res = es_search(client, SCORES_INDEX, {
"size": 5,
"_source": ["author_id"],
"query": {"bool": {
"filter": [{"term": {"institution_id": institution}}],
"must_not": [{"exists": {"field": "tags"}}],
}},
"sort": [{"max_sub_score": {"order": "desc"}}],
})
for hit in res["hits"]["hits"]:
aid = hit["_source"]["author_id"]
if aid not in seen:
picks.append((aid, "example"))
seen.add(aid)
break
return picks
# ---------------------------------------------------------------------
# Layout
# ---------------------------------------------------------------------
def fr_layout(node_ids, edge_list, w=760, h=560, iters=350, seed=7):
"""Fruchterman-Reingold with the ego pinned to the centre (deterministic seed)."""
rng = random.Random(seed)
pos = {n: [rng.uniform(0, w), rng.uniform(0, h)] for n in node_ids}
ego = node_ids[0]
pos[ego] = [w / 2, h / 2]
k = math.sqrt(w * h / max(len(node_ids), 1)) * 0.9
t = w / 8
wmax = max((e[2] for e in edge_list), default=1.0)
for _ in range(iters):
disp = {n: [0.0, 0.0] for n in node_ids}
for i, a in enumerate(node_ids):
for b in node_ids[i + 1:]:
dx = pos[a][0] - pos[b][0]
dy = pos[a][1] - pos[b][1]
d = max(math.hypot(dx, dy), 0.01)
f = k * k / d
disp[a][0] += dx / d * f; disp[a][1] += dy / d * f
disp[b][0] -= dx / d * f; disp[b][1] -= dy / d * f
for a, b, wt in edge_list:
dx = pos[a][0] - pos[b][0]
dy = pos[a][1] - pos[b][1]
d = max(math.hypot(dx, dy), 0.01)
f = d * d / k * (0.3 + 0.7 * wt / wmax)
disp[a][0] -= dx / d * f; disp[a][1] -= dy / d * f
disp[b][0] += dx / d * f; disp[b][1] += dy / d * f
for n in node_ids:
if n == ego:
continue
dx, dy = disp[n]
d = max(math.hypot(dx, dy), 0.01)
pos[n][0] = min(w - 20, max(20, pos[n][0] + dx / d * min(d, t)))
pos[n][1] = min(h - 20, max(20, pos[n][1] + dy / d * min(d, t)))
t *= 0.97
return pos
def compose(client: httpx.Client, institution: str, picks: list[tuple[str, str]]) -> dict:
out: dict[str, dict] = {}
for author_id, kind in picks:
doc_id = f"{institution}_{author_id}"
net = es_get(client, NETWORKS_INDEX, doc_id)
score = es_get(client, SCORES_INDEX, doc_id)
if not net or not score:
print(f" skip {author_id}: missing doc", file=sys.stderr)
continue
node_ids = [n["id"] for n in net["nodes"]]
pos = fr_layout(node_ids, [(e["a"], e["b"], e["w"]) for e in net["edges"]])
nodes = []
for n in net["nodes"]:
entry = {
"id": n["id"], "name": n["name"], "role": n["role"],
"inst": n.get("inst", ""), "active_years": n["active_years"],
"x": round(pos[n["id"]][0], 1), "y": round(pos[n["id"]][1], 1),
}
if n.get("company_insts"):
entry["company_insts"] = n["company_insts"]
nodes.append(entry)
out[author_id] = {
"kind": kind,
"score_row": {k: score[k] for k in SCORE_FIELDS if k in score},
"total_coauthors": net["total_coauthors"],
"shown": net["shown"],
"nodes": nodes,
"edges": [
{"a": e["a"], "b": e["b"], "w": e["w"], "n": e["n_works"],
"cross": e["cross"], "y0": e["first_year"]}
for e in net["edges"]
],
"config_hash": score.get("config_hash", ""),
"computed_at": (score.get("computed_at") or "")[:10],
}
roles: dict[str, int] = {}
for n in nodes:
roles[n["role"]] = roles.get(n["role"], 0) + 1
print(f" {kind:<10} {score.get('display_name')}: {roles}", file=sys.stderr)
return out
TEMPLATE_PATH = SCRIPT_DIR / "report_template.html"
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--institution-id", required=True)
parser.add_argument(
"--author-ids", default="",
help="Comma-separated author IDs to feature. Overrides report.featured_author_ids "
"in the config; pass --auto to force automatic selection instead.",
)
parser.add_argument(
"--auto", action="store_true",
help="Ignore the pinned cast and auto-select the current top scorer per tag.",
)
parser.add_argument("--config", default=str(SCRIPT_DIR / "multipliers.yaml"))
parser.add_argument("--out", default=str(SCRIPT_DIR / "reports" / "multiplier_networks.html"))
args = parser.parse_args()
if not INSE_URL or not INSE_KEY:
raise SystemExit(f"Missing INSE credentials. Checked {ENV_PATH}")
institution = args.institution_id.strip().rsplit("/", 1)[-1]
# cast precedence: --author-ids > --auto > config pin > automatic
pinned: list[str] = []
if not args.auto and not args.author_ids:
config_path = Path(args.config)
if config_path.exists():
config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
pinned = [
str(a) for a in ((config.get("report") or {}).get("featured_author_ids") or [])
]
with httpx.Client() as client:
ids = [a.strip() for a in args.author_ids.split(",") if a.strip()] or pinned
if ids:
kinds = ["bridger", "mentor", "amplifier", "example"]
picks = [(a, kinds[i] if i < len(kinds) else "example")
for i, a in enumerate(ids)]
source = "config-pinned" if pinned and not args.author_ids else "explicit"
print(f"Cast ({source}): {[p[0] for p in picks]}", file=sys.stderr)
else:
picks = pick_showcase(client, institution)
print(f"Auto-selected showcase: {[p[0] for p in picks]}", file=sys.stderr)
data = compose(client, institution, picks)
if not data:
raise SystemExit("No documents found — has build.py run for this institution?")
template = TEMPLATE_PATH.read_text(encoding="utf-8")
payload = json.dumps(data, ensure_ascii=True)
assert "</script" not in payload, "data would break out of the script tag"
html = template.replace("__DATA__", payload)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(html, encoding="utf-8")
print(f"Report -> {out_path} ({len(html):,} bytes, {len(data)} cases)")
if __name__ == "__main__":
main()
@@ -108,3 +108,14 @@ weights:
tags:
threshold: 0.85 # tag fires when sub-score >= threshold (multiple allowed)
min_active_years: 2 # never tag someone with <2 active years (no history)
report:
# Cast for make_report.py, in order: bridger, mentor, amplifier, near-miss.
# Pinned so the report is reproducible — without this the script auto-picks the
# current top scorer per tag, which changes with every weight tune or dump refresh.
# Remove/empty the list to fall back to automatic selection.
featured_author_ids:
- A5113304257 # Jan Egger — top bridger
- A5043495754 # Cornelius Deuschl — top mentor
- A5007801159 # Jens Wiltfang — top amplifier
- A5043360678 # Tabea M. G. Pakull — strong profile just below the tag line
@@ -0,0 +1,461 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Multipliers, drawn as networks</title>
<style>
:root {
--surface: #fcfcfb;
--surface-2: #f4f3f0;
--ink: #0b0b0b;
--ink-2: #52514e;
--ink-3: #8a8983;
--line: #e4e2dc;
--ego: #e87ba4;
--cohort: #2a78d6;
--mentee: #1baf7a;
--industry: #eb6834;
--external: #b5b4ac;
--bar: #2a78d6;
--node-stroke: rgba(11,11,11,.35);
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--surface: #1a1a19;
--surface-2: #232322;
--ink: #ffffff;
--ink-2: #c3c2b7;
--ink-3: #8a8983;
--line: #3a3936;
--ego: #d55181;
--cohort: #3987e5;
--mentee: #199e70;
--industry: #d95926;
--external: #55544f;
--bar: #3987e5;
--node-stroke: rgba(255,255,255,.35);
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--surface: #1a1a19;
--surface-2: #232322;
--ink: #ffffff;
--ink-2: #c3c2b7;
--ink-3: #8a8983;
--line: #3a3936;
--ego: #d55181;
--cohort: #3987e5;
--mentee: #199e70;
--industry: #d95926;
--external: #55544f;
--bar: #3987e5;
--node-stroke: rgba(255,255,255,.35);
color-scheme: dark;
}
:root[data-theme="light"] {
--surface: #fcfcfb;
--surface-2: #f4f3f0;
--ink: #0b0b0b;
--ink-2: #52514e;
--ink-3: #8a8983;
--line: #e4e2dc;
--ego: #e87ba4;
--cohort: #2a78d6;
--mentee: #1baf7a;
--industry: #eb6834;
--external: #b5b4ac;
--bar: #2a78d6;
--node-stroke: rgba(11,11,11,.35);
color-scheme: light;
}
body {
background: var(--surface);
color: var(--ink);
font-family: Charter, Georgia, 'Times New Roman', serif;
line-height: 1.55;
margin: 0;
}
.wrap { max-width: 1160px; margin: 0 auto; padding: 40px 24px 80px; }
header.page { max-width: 70ch; margin-bottom: 12px; }
.eyebrow {
font-family: -apple-system, 'Segoe UI', sans-serif;
font-size: 11px; letter-spacing: .14em; text-transform: uppercase;
color: var(--ink-3); margin: 0 0 10px;
}
h1 { font-size: 34px; line-height: 1.15; margin: 0 0 12px; text-wrap: balance; font-weight: 700; }
.lede { color: var(--ink-2); font-size: 16.5px; margin: 0; }
.legend {
position: sticky; top: 0; z-index: 5;
background: var(--surface);
border-block: 1px solid var(--line);
margin: 28px 0 0;
padding: 10px 2px;
display: flex; flex-wrap: wrap; gap: 14px 22px; align-items: center;
font-family: -apple-system, 'Segoe UI', sans-serif; font-size: 12.5px; color: var(--ink-2);
}
.legend .li { display: inline-flex; align-items: center; gap: 7px; }
.dot { width: 11px; height: 11px; border-radius: 50%; border: 1px solid var(--node-stroke); flex: none; }
.dot.ego { outline: 2px solid var(--ink); outline-offset: 1.5px; }
.edge-sample { width: 26px; height: 0; border-top: 2px solid var(--ink-3); flex: none; }
.edge-sample.dashed { border-top-style: dashed; }
section.case { margin-top: 52px; }
.case-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px 14px; margin-bottom: 4px; }
.case-eyebrow { font-family: -apple-system,'Segoe UI',sans-serif; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; margin: 0; }
h2 { font-size: 26px; margin: 0; font-weight: 700; }
.pill {
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 11.5px; font-weight: 600;
padding: 2.5px 10px; border-radius: 999px; letter-spacing: .04em;
border: 1px solid var(--line); color: var(--ink-2); background: var(--surface-2);
}
.pill.tag { color: var(--surface); border: none; }
.meta-line { font-family: -apple-system,'Segoe UI',sans-serif; font-size: 13px; color: var(--ink-3); margin: 2px 0 18px; }
.case-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(280px, 1fr); gap: 26px; align-items: start; }
@media (max-width: 900px) { .case-grid { grid-template-columns: 1fr; } }
.netbox { border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); overflow: hidden; }
.netbox svg { display: block; width: 100%; height: auto; }
.netfoot { font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12px; color: var(--ink-3); padding: 8px 12px; border-top: 1px solid var(--line); }
.panel { display: flex; flex-direction: column; gap: 18px; }
.panel h3 {
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 11px; letter-spacing: .12em;
text-transform: uppercase; color: var(--ink-3); margin: 0 0 8px; font-weight: 600;
}
.scorebar { display: grid; grid-template-columns: 74px 1fr 44px; align-items: center; gap: 10px; margin-bottom: 7px;
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12.5px; }
.scorebar .nm { color: var(--ink-2); }
.scorebar .val { font-variant-numeric: tabular-nums; text-align: right; color: var(--ink); }
.track { position: relative; height: 10px; background: var(--surface-2); border-radius: 4px; border: 1px solid var(--line); }
.fill { position: absolute; inset: 0 auto 0 0; border-radius: 4px 3px 3px 4px; background: var(--bar); opacity: .55; }
.fill.lead { opacity: 1; }
.thresh { position: absolute; top: -3px; bottom: -3px; left: 85%; width: 0; border-left: 2px dashed var(--ink-3); }
table.mx { border-collapse: collapse; width: 100%; font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12.5px; }
table.mx th { text-align: left; font-weight: 600; color: var(--ink-3); font-size: 11px; letter-spacing: .06em; text-transform: uppercase; padding: 8px 0 4px; }
table.mx td { padding: 3.5px 0; border-top: 1px solid var(--line); color: var(--ink-2); }
table.mx td.num { font-variant-numeric: tabular-nums; text-align: right; color: var(--ink); white-space: nowrap; }
table.mx td.num.hot { font-weight: 700; }
.reading { max-width: 72ch; margin-top: 18px; font-size: 15.5px; color: var(--ink-2); }
.reading strong { color: var(--ink); }
.tooltip {
position: fixed; pointer-events: none; z-index: 20; display: none;
background: var(--ink); color: var(--surface);
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12px; line-height: 1.45;
padding: 8px 11px; border-radius: 7px; max-width: 260px; box-shadow: 0 4px 14px rgba(0,0,0,.25);
}
.tooltip .t-name { font-weight: 700; }
.tooltip .t-dim { opacity: .75; }
footer.page { margin-top: 60px; border-top: 1px solid var(--line); padding-top: 16px;
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12.5px; color: var(--ink-3); max-width: 78ch; }
svg .node { cursor: pointer; }
#themeToggle {
position: fixed; top: 14px; right: 14px; z-index: 30;
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12px; padding: 6px 12px;
border-radius: 999px; border: 1px solid var(--line); background: var(--surface-2);
color: var(--ink-2); cursor: pointer;
}
#themeToggle:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
</style>
</head>
<body>
<div class="wrap">
<header class="page">
<p class="eyebrow" id="topline">Smart-Guide · Multiplier detection</p>
<h1>Four researchers, drawn as the networks that scored them</h1>
<p class="lede">
Each figure shows one person (ringed) and their strongest co-authors, with every
collaboration the corpus records <em>among</em> those co-authors. The shape is the
metric: spokes that don't touch are brokered structural holes; a dense mesh is a
tight community; green marks the juniors a mentor brought up; orange marks a
company link on the works shared with that person. Hover any node for its details.
</p>
</header>
<div class="legend" id="legend">
<span class="li"><span class="dot ego" style="background:var(--ego)"></span>the person (ego)</span>
<span class="li"><span class="dot" style="background:var(--cohort)"></span>cohort co-author</span>
<span class="li"><span class="dot" style="background:var(--mentee)"></span>their mentee (junior at first joint paper)</span>
<span class="li"><span class="dot" style="background:var(--industry)"></span>company link on works shared with the ego</span>
<span class="li"><span class="dot" style="background:var(--external)"></span>external academic</span>
<span class="li"><span class="edge-sample"></span>collaboration (width = decayed strength)</span>
<span class="li"><span class="edge-sample dashed"></span>mostly cross-institution</span>
<span class="li">node size = active years</span>
</div>
<div id="cases"></div>
<footer class="page">
Data: OpenAlex works of the institution cohort (works ≤ 50 authors enter the graph;
edge strength decays 0.8/year), read from the <code>multiplicators_v1</code> and
<code>multiplicator_networks_v1</code> indices. Networks show each ego's strongest
co-authors — totals are given per figure. Scores are percentile-normalized within
career buckets; tag threshold 0.85. Config <span id="cfg"></span>, computed
<span id="ts"></span>. Mentee marking uses the seniority-gap rule and is restricted
to cohort members; external co-authors' histories are truncated to shared works, so
their node size is a lower bound. An orange node means a company affiliation appeared
on a work shared with the ego — the company is named in the tooltip.
</footer>
</div>
<div class="tooltip" id="tip"></div>
<button id="themeToggle" aria-label="Toggle color theme">theme</button>
<script>
const DATA = __DATA__;
const ROLE = { ego:'--ego', cohort:'--cohort', mentee:'--mentee', industry:'--industry', external:'--external' };
const ORDER = ['bridger','mentor','amplifier','example'];
const EYEBROW = {
bridger: ['Case 1 — the bridger archetype', '--cohort'],
mentor: ['Case 2 — the mentor archetype', '--mentee'],
amplifier:['Case 3 — the amplifier archetype', '--industry'],
example: ['Case 4 — a strong profile below the tag line', '--ego'],
};
const ROLE_LABEL = {
ego: 'This case’s subject',
cohort: 'Cohort co-author',
mentee: 'Mentee — junior at first joint paper',
industry: 'Company link on shared works',
external: 'External academic',
};
const fmt = (v, d=2) => v == null ? '—' : (+v).toFixed(d);
const pct = v => v == null ? '—' : Math.round(v*100) + '%';
function readingFor(kind, r, d) {
const p = r.percentiles || {};
if (kind === 'bridger') return `
<strong>${r.display_name}</strong> holds the cohort's highest bridger score
(<strong>${fmt(r.sub_scores.bridger,3)}</strong>). The picture explains it: the
${d.total_coauthors} co-authors split into groups that barely touch except through
the ego — brokerage ${fmt(r.brokerage,2)} (${pct(p.brokerage)} of the career
bucket), ${pct(r.cross_institution_share)} of collaboration weight crosses
institutions (dashed edges), and betweenness sits at the ${pct(p.betweenness)}
percentile. Where the mentor's figure below is one dense mesh, this one is spokes
and gaps — the gaps <em>are</em> the structural holes.`;
if (kind === 'mentor') return `
<strong>${r.display_name}</strong> tops the mentor ranking
(<strong>${fmt(r.sub_scores.mentor,3)}</strong>) with ${r.juniors_mentored} cohort
co-authors who were Early-career at their first joint paper while the ego was
already Established — the green nodes — plus ${r.last_author_with_junior_first}
papers in the classic supervision configuration (ego last author, a junior first).
The mesh is dense: this is one connected group, the opposite structure of the
bridger above. Only the ${d.shown} strongest ties of ${d.total_coauthors} are drawn.`;
if (kind === 'amplifier') return `
<strong>${r.display_name}</strong> tops the amplifier ranking
(<strong>${fmt(r.sub_scores.amplifier,3)}</strong>) on converging independent
channels: ${r.patent_count} high-confidence patent${r.patent_count===1?'':'s'},
${r.cordis_eu_projects} EU project${r.cordis_eu_projects===1?'':'s'} via DOI
overlap, ${r.news_mentions} press mention${r.news_mentions===1?'':'s'}, and a
shrunk industry co-authorship share of ${fmt(r.industry_coauthor_share_shrunk,2)}
(${pct(p.industry_coauthor_share_shrunk)} of the bucket). With
${d.total_coauthors.toLocaleString('en')} total co-authors only the strongest
${d.shown} are drawn — orange nodes carry a company affiliation on the shared work.`;
const best = Math.max(...Object.values(r.sub_scores));
const bestName = Object.entries(r.sub_scores).sort((a,b)=>b[1]-a[1])[0][0];
const gated = best >= 0.85;
return `
<strong>${r.display_name}</strong> is the system's honest edge case: the
highest-scoring person who still carries <strong>no tag</strong>. The ${bestName}
sub-score reaches ${fmt(best,3)} ${gated
? `— <em>above</em> the 0.85 line. The tag is withheld by the
<code>min_active_years</code> guard: ${r.active_years} active
year${r.active_years===1?'':'s'} is too thin a history to rank on, and a
high score on one year is the signature of a <em>split</em> OpenAlex profile
— a fragment of someone's record carrying a share of their patents, press or
industry ties. The guard catches what <code>suspicious_profile</code> cannot:
that flag detects merged identities, not split ones.`
: `— just under the 0.85 line, on ${r.active_years} active
year${r.active_years===1?'':'s'}. Thresholds are meant to surface the top of
each bucket, and this profile sits one weight-tune away from either side.`}
Either way it is the case coaches should see: ${d.total_coauthors} co-authors,
brokerage ${fmt(r.brokerage,2)} (${pct(p.brokerage)} of the bucket),
${pct(r.cross_institution_share)} cross-institution weight — a real profile that
the ranking deliberately holds back.`;
}
function svgNet(d) {
const W = 760, H = 560, ns = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(ns, 'svg');
svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
svg.setAttribute('role', 'img');
svg.setAttribute('aria-label', `Co-author network of ${d.score_row.display_name}`);
const byId = {};
d.nodes.forEach(n => byId[n.id] = n);
const ego = d.nodes[0];
const wmax = Math.max(...d.edges.map(e => e.w), 0.01);
const eg = document.createElementNS(ns, 'g');
d.edges.forEach(e => {
const a = byId[e.a], b = byId[e.b];
if (!a || !b) return;
const ln = document.createElementNS(ns, 'line');
ln.setAttribute('x1', a.x); ln.setAttribute('y1', a.y);
ln.setAttribute('x2', b.x); ln.setAttribute('y2', b.y);
const touchesEgo = (e.a === ego.id || e.b === ego.id);
ln.setAttribute('stroke', 'currentColor');
ln.setAttribute('stroke-opacity', touchesEgo ? 0.42 : 0.16);
ln.setAttribute('stroke-width', Math.max(0.6, Math.min(4.5, 2.8*Math.sqrt(e.w/wmax))));
if (e.cross) ln.setAttribute('stroke-dasharray', '4 3');
eg.appendChild(ln);
});
eg.setAttribute('color', 'var(--ink-3)');
svg.appendChild(eg);
const edgeToEgo = {};
d.edges.forEach(e => {
if (e.a === ego.id) edgeToEgo[e.b] = e;
if (e.b === ego.id) edgeToEgo[e.a] = e;
});
const ng = document.createElementNS(ns, 'g');
d.nodes.forEach(n => {
const c = document.createElementNS(ns, 'circle');
const isEgo = n.role === 'ego';
const r = isEgo ? 13 : Math.max(4, Math.min(9, 3 + 1.1*Math.sqrt(n.active_years)));
c.setAttribute('class', 'node');
c.setAttribute('cx', n.x); c.setAttribute('cy', n.y); c.setAttribute('r', r);
c.setAttribute('fill', `var(${ROLE[n.role]})`);
c.setAttribute('stroke', isEgo ? 'var(--ink)' : 'var(--node-stroke)');
c.setAttribute('stroke-width', isEgo ? 2.5 : 1);
c.addEventListener('pointerenter', ev => {
const e = edgeToEgo[n.id];
showTip(ev, `
<div class="t-name">${n.name || n.id}</div>
<div>${ROLE_LABEL[n.role] || n.role}</div>
${n.inst ? `<div class="t-dim">${n.inst}</div>` : ''}
${n.company_insts ? `<div>Industry link: ${n.company_insts.join(', ')}</div>` : ''}
<div class="t-dim">${n.active_years} active year${n.active_years===1?'':'s'}${
e ? ` · tie strength ${e.w.toFixed(2)} · ${e.n} joint work${e.n===1?'':'s'} · since ${e.y0}` : ''}</div>`);
});
c.addEventListener('pointermove', moveTip);
c.addEventListener('pointerleave', hideTip);
ng.appendChild(c);
});
svg.appendChild(ng);
const label = document.createElementNS(ns, 'text');
label.setAttribute('x', ego.x); label.setAttribute('y', ego.y + 30);
label.setAttribute('text-anchor', 'middle');
label.setAttribute('style', 'font-family:-apple-system,Segoe UI,sans-serif;font-size:12.5px;font-weight:700;fill:var(--ink);paint-order:stroke;stroke:var(--surface);stroke-width:3px;');
label.textContent = ego.name;
svg.appendChild(label);
return svg;
}
const tip = document.getElementById('tip');
function showTip(ev, html) { tip.innerHTML = html; tip.style.display = 'block'; moveTip(ev); }
function moveTip(ev) {
const pad = 14;
let x = ev.clientX + pad, y = ev.clientY + pad;
const r = tip.getBoundingClientRect();
if (x + r.width > innerWidth - 8) x = ev.clientX - r.width - pad;
if (y + r.height > innerHeight - 8) y = ev.clientY - r.height - pad;
tip.style.left = x + 'px'; tip.style.top = y + 'px';
}
function hideTip() { tip.style.display = 'none'; }
function metricRows(r) {
const p = r.percentiles || {};
const groups = [
['Bridging', [
['Betweenness', fmt(r.betweenness, r.betweenness && r.betweenness < 0.01 ? 4 : 3), p.betweenness],
['Brokerage (1−constraint)', fmt(r.brokerage), p.brokerage],
['Field entropy', fmt(r.field_entropy), p.field_entropy],
['Cross-institution share', fmt(r.cross_institution_share), p.cross_institution_share],
]],
['Mentoring', [
['Juniors mentored', r.juniors_mentored, p.juniors_mentored],
['Last-author + junior first', r.last_author_with_junior_first, p.last_author_with_junior_first],
['Mentoring rate', fmt(r.mentoring_rate), p.mentoring_rate],
]],
['Amplification', [
['Industry share (shrunk)', fmt(r.industry_coauthor_share_shrunk), p.industry_coauthor_share_shrunk],
['Patents (high-confidence)', r.patent_count, p.patent_count],
['EU projects (DOI join)', r.cordis_eu_projects, p.cordis_eu_projects],
['News mentions', r.news_mentions, p.news_mentions],
]],
];
let html = '<table class="mx"><tr><th>Metric</th><th style="text-align:right">Raw</th><th style="text-align:right">Bucket&nbsp;pctl</th></tr>';
for (const [g, rows] of groups) {
html += `<tr><td colspan="3" style="border-top:none;padding-top:10px;font-weight:600;color:var(--ink-3);font-size:11px;letter-spacing:.06em;text-transform:uppercase">${g}</td></tr>`;
for (const [nm, raw, pc] of rows) {
const hot = pc != null && pc >= 0.9;
html += `<tr><td>${nm}</td><td class="num">${raw == null ? '—' : raw}</td><td class="num${hot?' hot':''}">${pc==null?'—':pct(pc)}</td></tr>`;
}
}
return html + '</table>';
}
const container = document.getElementById('cases');
let firstCase = null;
for (const kind of ORDER) {
const key = Object.keys(DATA).find(k => DATA[k].kind === kind);
if (!key) continue;
const d = DATA[key], r = d.score_row;
if (!firstCase) firstCase = d;
const [eyebrow, hue] = EYEBROW[kind];
const lead = Object.entries(r.sub_scores).sort((a,b)=>b[1]-a[1])[0][0];
const sec = document.createElement('section');
sec.className = 'case';
sec.innerHTML = `
<p class="case-eyebrow" style="color:var(${hue})">${eyebrow}</p>
<div class="case-head">
<h2>${r.display_name}</h2>
${(r.tags||[]).map(t => `<span class="pill tag" style="background:var(${hue})">${t}</span>`).join('')}
${(r.tags||[]).length === 0 ? '<span class="pill">no tag</span>' : ''}
<span class="pill">${r.career_bucket} · ${r.active_years} active years</span>
${r.suspicious_profile ? '<span class="pill">low-confidence profile</span>' : ''}
</div>
<p class="meta-line">${r.n_works} works · ${d.total_coauthors.toLocaleString('en')} co-authors
(strongest ${d.shown} drawn) · author ${r.author_id}</p>
<div class="case-grid">
<div class="netbox">
<div class="svg-slot"></div>
<div class="netfoot">Edges among the drawn co-authors are the corpus's actual
collaborations — their density (or absence) is what constraint/brokerage measures.</div>
</div>
<div class="panel">
<div>
<h3>Sub-scores <span style="letter-spacing:0;text-transform:none">(dashed line = 0.85 tag threshold)</span></h3>
${['bridger','mentor','amplifier'].map(s => `
<div class="scorebar">
<span class="nm">${s}</span>
<span class="track"><span class="fill${s===lead?' lead':''}" style="width:${(r.sub_scores[s]*100).toFixed(1)}%"></span><span class="thresh"></span></span>
<span class="val">${fmt(r.sub_scores[s],3)}</span>
</div>`).join('')}
</div>
<div>${metricRows(r)}</div>
</div>
</div>
<p class="reading">${readingFor(kind, r, d)}</p>`;
sec.querySelector('.svg-slot').appendChild(svgNet(d));
container.appendChild(sec);
}
if (firstCase) {
document.getElementById('cfg').textContent = firstCase.config_hash || '—';
document.getElementById('ts').textContent = firstCase.computed_at || '—';
}
document.getElementById('themeToggle').addEventListener('click', () => {
const root = document.documentElement;
const dark = root.getAttribute('data-theme') === 'dark' ||
(!root.getAttribute('data-theme') && matchMedia('(prefers-color-scheme: dark)').matches);
root.setAttribute('data-theme', dark ? 'light' : 'dark');
});
</script>
</body>
</html>