diff --git a/service/scripts/multipliers/README.md b/service/scripts/multipliers/README.md index d9d2cbe6..d18829d1 100644 --- a/service/scripts/multipliers/README.md +++ b/service/scripts/multipliers/README.md @@ -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. diff --git a/service/scripts/multipliers/make_report.py b/service/scripts/multipliers/make_report.py new file mode 100644 index 00000000..68138d11 --- /dev/null +++ b/service/scripts/multipliers/make_report.py @@ -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 " {out_path} ({len(html):,} bytes, {len(data)} cases)") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/multipliers/multipliers.yaml b/service/scripts/multipliers/multipliers.yaml index 6d26a316..7fdbe95c 100644 --- a/service/scripts/multipliers/multipliers.yaml +++ b/service/scripts/multipliers/multipliers.yaml @@ -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 diff --git a/service/scripts/multipliers/report_template.html b/service/scripts/multipliers/report_template.html new file mode 100644 index 00000000..99bce523 --- /dev/null +++ b/service/scripts/multipliers/report_template.html @@ -0,0 +1,461 @@ + + +
+ + +Smart-Guide · Multiplier detection
++ Each figure shows one person (ringed) and their strongest co-authors, with every + collaboration the corpus records among 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. +
+