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