#!/usr/bin/env python3 """ metrics.py — bridger / mentor metrics for multiplicator detection (M1, Stage D). Pure computations over the structures produced by graph.py. Field-by-field definitions and the rationale behind them: docs/ROADMAP.md §3. Two invariants the code depends on: - Seniority is `active_years_at`, never first_publication_year — merged OpenAlex profiles give active professors debut years like 1893. - Mentor metrics run over FOCAL pairs only: external co-authors' year-sets are truncated to shared works, so an external senior would look junior. A data-correctness requirement, not a modelling choice. """ from __future__ import annotations import heapq import math from dataclasses import dataclass, field from service.scripts.profiling.multipliers.graph import EdgeStats, Graph, adjacency, focal_subgraph def incident_edges(graph: Graph) -> dict[str, list[tuple[str, EdgeStats]]]: """One pass over the edge dict -> per-author incident edge lists. Every per-author metric must use this instead of scanning graph.edges: a full-edge scan per focal author is O(E * authors) and does not finish.""" incident: dict[str, list[tuple[str, EdgeStats]]] = {} for (a, b), e in graph.edges.items(): incident.setdefault(a, []).append((b, e)) incident.setdefault(b, []).append((a, e)) return incident # --------------------------------------------------------------------- # Career primitives # --------------------------------------------------------------------- def active_years_at(publication_years: set[int], year: int) -> int: """Distinct publication years up to and including `year` (robust seniority).""" return sum(1 for y in publication_years if y <= year) def is_suspicious_profile(publication_years: set[int]) -> bool: """Merged-profile flag, same rule as inse/persons/logic.py.""" if not publication_years: return False first = min(publication_years) span = max(publication_years) - first + 1 return first < 1970 or span > 60 # --------------------------------------------------------------------- # Betweenness — Brandes (2001), weighted variant with Dijkstra. # Weights are collaboration STRENGTHS, shortest paths need DISTANCES, so # distances are 1/weight. # --------------------------------------------------------------------- def betweenness_centrality( adj: dict[str, dict[str, float]], normalized: bool = True ) -> dict[str, float]: nodes = list(adj.keys()) bc = {v: 0.0 for v in nodes} for s in nodes: # per-source state is lazy (touched nodes only) — initialising over all # V nodes per source would be O(V^2) before any work happens dist: dict[str, float] = {s: 0.0} sigma: dict[str, float] = {s: 1.0} preds: dict[str, list[str]] = {} done: set[str] = set() order: list[str] = [] heap: list[tuple[float, str]] = [(0.0, s)] while heap: d, v = heapq.heappop(heap) if v in done: continue done.add(v) order.append(v) sigma_v = sigma[v] for u, w in adj[v].items(): if w <= 0: continue nd = d + 1.0 / w old = dist.get(u) if old is None or nd < old - 1e-12: dist[u] = nd sigma[u] = sigma_v preds[u] = [v] heapq.heappush(heap, (nd, u)) elif abs(nd - old) <= 1e-12 and u not in done: sigma[u] += sigma_v preds.setdefault(u, []).append(v) # accumulation, reverse order of discovery delta: dict[str, float] = {} for v in reversed(order): dv = delta.get(v, 0.0) coeff = (1.0 + dv) / sigma[v] for p in preds.get(v, ()): delta[p] = delta.get(p, 0.0) + sigma[p] * coeff if v != s: bc[v] += dv # undirected: each pair counted twice for v in bc: bc[v] /= 2.0 if normalized and len(nodes) > 2: scale = 1.0 / ((len(nodes) - 1) * (len(nodes) - 2) / 2.0) for v in bc: bc[v] *= scale return bc # --------------------------------------------------------------------- # Burt's constraint — low constraint == structural-hole spanner (bridger). # Computed on the FULL graph, external co-authors included. # --------------------------------------------------------------------- def burt_constraint( adj: dict[str, dict[str, float]], nodes: list[str] | None = None ) -> dict[str, float]: """Constraint c_i = sum_j (p_ij + sum_q p_iq * p_qj)^2 over neighbours j of i. p_ij = w_ij / sum_k w_ik. Isolates get constraint 1.0 (fully constrained). """ # once, not inside the O(d^2) inner loop — that would be O(d^3) and # unusable on hub nodes totals = {v: sum(neigh.values()) for v, neigh in adj.items()} result: dict[str, float] = {} targets = nodes if nodes is not None else list(adj.keys()) for i in targets: neigh = adj.get(i) or {} total = totals.get(i, 0.0) if total <= 0: result[i] = 1.0 continue p_i = {j: w / total for j, w in neigh.items()} c = 0.0 for j, p_ij in p_i.items(): indirect = 0.0 for q, p_iq in p_i.items(): if q == j: continue q_neigh = adj.get(q) if not q_neigh: continue w_qj = q_neigh.get(j) if w_qj: indirect += p_iq * (w_qj / totals[q]) c += (p_ij + indirect) ** 2 result[i] = c return result # --------------------------------------------------------------------- # Simple per-node shares # --------------------------------------------------------------------- def field_entropy(field_counts: dict[str, int]) -> float: """Shannon entropy (bits) over primary_topic.field of an author's works.""" total = sum(field_counts.values()) if total <= 0: return 0.0 ent = 0.0 for c in field_counts.values(): if c > 0: p = c / total ent -= p * math.log2(p) return ent def cross_institution_share( graph: Graph, author_id: str, incident: dict[str, list[tuple[str, EdgeStats]]] | None = None, ) -> float: """Share of an author's edge weight where the pair shared no institution.""" if incident is None: incident = incident_edges(graph) total = 0.0 cross = 0.0 for _, e in incident.get(author_id, ()): total += e.weight cross += e.cross_inst_weight return cross / total if total > 0 else 0.0 # --------------------------------------------------------------------- # Mentor metrics — debut-year-free (see module docstring) # --------------------------------------------------------------------- @dataclass class MentorMetrics: juniors_mentored: int = 0 junior_progression_rate: float | None = None # None if no juniors last_author_with_junior_first: int = 0 mentoring_rate: float = 0.0 junior_ids: list[str] = field(default_factory=list) # evidence def mentor_metrics( graph: Graph, focal_author_id: str, junior_active_years_max: int = 4, senior_active_years_min: int = 10, progressed_active_years_min: int = 5, incident: dict[str, list[tuple[str, EdgeStats]]] | None = None, ) -> MentorMetrics: """Seniority-gap mentorship over focal-internal pairs. A co-author J counts as "mentored" when, at the year Y of the FIRST joint work: active_years_at(J, Y) <= junior_active_years_max (J was Early-career) active_years_at(focal, Y) >= senior_active_years_min (focal was Established+) Progression: J later reached >= progressed_active_years_min active years. """ focal_node = graph.nodes.get(focal_author_id) if focal_node is None: return MentorMetrics() if incident is None: incident = incident_edges(graph) juniors: list[str] = [] progressed = 0 for other, e in incident.get(focal_author_id, ()): if e.first_joint_year is None: continue other_node = graph.nodes.get(other) if other_node is None or not other_node.is_focal or not focal_node.is_focal: continue # internal pairs only — external year-sets are truncated y = e.first_joint_year if ( active_years_at(other_node.publication_years, y) <= junior_active_years_max and active_years_at(focal_node.publication_years, y) >= senior_active_years_min ): juniors.append(other) if len(other_node.publication_years) >= progressed_active_years_min: progressed += 1 # supervision signature: focal last author, junior first author last_author_junior_first = 0 for first_author, year in focal_node.last_author_junior_first: fa_node = graph.nodes.get(first_author) if fa_node is None or not fa_node.is_focal: continue if active_years_at(fa_node.publication_years, year) <= junior_active_years_max: last_author_junior_first += 1 total_active = len(focal_node.publication_years) return MentorMetrics( juniors_mentored=len(juniors), junior_progression_rate=(progressed / len(juniors)) if juniors else None, last_author_with_junior_first=last_author_junior_first, mentoring_rate=(len(juniors) / total_active) if total_active else 0.0, junior_ids=juniors, ) # --------------------------------------------------------------------- # Orchestration: all raw metrics for every focal author # --------------------------------------------------------------------- def compute_all_metrics( graph: Graph, junior_active_years_max: int = 4, senior_active_years_min: int = 10, progressed_active_years_min: int = 5, industry_share_shrinkage_k: int = 5, ) -> dict[str, dict]: """Raw (un-normalized) metric rows keyed by focal author id.""" internal = focal_subgraph(graph) full_adj = adjacency(graph) incident = incident_edges(graph) focal_ids = [aid for aid, n in graph.nodes.items() if n.is_focal] bc = betweenness_centrality(internal) if internal else {} constraint = burt_constraint(full_adj, nodes=[a for a in focal_ids if a in full_adj]) rows: dict[str, dict] = {} for aid in focal_ids: node = graph.nodes[aid] mm = mentor_metrics( graph, aid, junior_active_years_max=junior_active_years_max, senior_active_years_min=senior_active_years_min, progressed_active_years_min=progressed_active_years_min, incident=incident, ) strength = sum(full_adj.get(aid, {}).values()) rows[aid] = { "author_id": aid, "display_name": node.display_name, "active_years": len(node.publication_years), "n_works": node.n_works, "suspicious_profile": is_suspicious_profile(node.publication_years), # bridger "betweenness": bc.get(aid, 0.0), "constraint": constraint.get(aid, 1.0), "brokerage": 1.0 - constraint.get(aid, 1.0), # higher = more bridging "field_entropy": field_entropy(node.field_counts), "cross_institution_share": cross_institution_share(graph, aid, incident), "strength": strength, "n_coauthors": len(full_adj.get(aid, {})), # not scored; the founder classifier's `industry_collab_papers` # input verbatim "industry_collab_papers": node.n_company_works, "industry_coauthor_share": ( node.n_company_works / node.n_typed_works if node.n_typed_works else 0.0 ), # the SCORED variant: +k damps the small-denominator artifact # where 2-of-2 company works outranks 40-of-80 "industry_coauthor_share_shrunk": ( node.n_company_works / (node.n_typed_works + industry_share_shrinkage_k) if node.n_typed_works else 0.0 ), # mentor "juniors_mentored": mm.juniors_mentored, "junior_progression_rate": mm.junior_progression_rate, "last_author_with_junior_first": mm.last_author_with_junior_first, "mentoring_rate": mm.mentoring_rate, "junior_ids": mm.junior_ids, } return rows