"""Tests for metrics: betweenness vs networkx oracle, constraint on a star, active_years_at robustness (the planted-1893-outlier regression guard), mentor logic.""" from __future__ import annotations import pytest from graph import build_graph from metrics import ( active_years_at, betweenness_centrality, burt_constraint, compute_all_metrics, field_entropy, is_suspicious_profile, mentor_metrics, ) from test_graph import UDE, make_work networkx = pytest.importorskip("networkx") # --------------------------------------------------------------------- # active_years_at — THE regression guard for the whole design premise # --------------------------------------------------------------------- def test_active_years_at_unmoved_by_planted_1893_outlier(): """A single misattributed 1893 work must shift active_years_at by exactly 1, unlike first_pub_year-based career age, which it would shift by ~120 years.""" clean = set(range(2010, 2026)) # 16 active years poisoned = clean | {1893} # merged-profile artifact assert active_years_at(clean, 2025) == 16 assert active_years_at(poisoned, 2025) == 17 # +1, not +120 # seniority classification at the time of an early collaboration is unaffected assert active_years_at(clean, 2013) == 4 # still "Early" in 2013 assert active_years_at(poisoned, 2013) == 5 # off by exactly one year # the poisoned profile IS flagged for evidence confidence assert not is_suspicious_profile(clean) assert is_suspicious_profile(poisoned) # --------------------------------------------------------------------- # betweenness — barbell fixture + networkx oracle # --------------------------------------------------------------------- def _nx_graph(adj): g = networkx.Graph() for a, neigh in adj.items(): g.add_node(a) for b, w in neigh.items(): g.add_edge(a, b, weight=w, distance=1.0 / w) return g def test_betweenness_barbell_bridge_dominates(): """Two triangles joined by one bridge node: the bridge has max betweenness.""" adj = {} def add(a, b, w=1.0): adj.setdefault(a, {})[b] = w adj.setdefault(b, {})[a] = w for x, y in [("A", "B"), ("B", "C"), ("A", "C")]: add(x, y) for x, y in [("D", "E"), ("E", "F"), ("D", "F")]: add(x, y) add("C", "M") add("M", "D") bc = betweenness_centrality(adj) assert bc["M"] == max(bc.values()) assert bc["A"] == pytest.approx(0.0) oracle = networkx.betweenness_centrality( _nx_graph(adj), weight="distance", normalized=True ) for node, value in bc.items(): assert value == pytest.approx(oracle[node], abs=1e-9), node def test_betweenness_weighted_paths_vs_oracle(): """Weighted graph where the shortest path is NOT the fewest-hops path.""" adj = {} def add(a, b, w): adj.setdefault(a, {})[b] = w adj.setdefault(b, {})[a] = w # strong two-hop route A-X-B (distance 0.2+0.2) beats direct weak A-B (distance 2) add("A", "B", 0.5) add("A", "X", 5.0) add("X", "B", 5.0) add("B", "C", 1.0) bc = betweenness_centrality(adj) oracle = networkx.betweenness_centrality( _nx_graph(adj), weight="distance", normalized=True ) for node, value in bc.items(): assert value == pytest.approx(oracle[node], abs=1e-9), node assert bc["X"] > 0.0 # X sits on the A->B shortest path def test_betweenness_random_graph_vs_oracle(): """Randomized (but seeded) graph, full oracle comparison.""" rng = networkx.gnm_random_graph(24, 60, seed=7) adj = {} for a, b in rng.edges(): w = ((a * 31 + b * 17) % 9 + 1) / 3.0 # deterministic pseudo-weights adj.setdefault(str(a), {})[str(b)] = w adj.setdefault(str(b), {})[str(a)] = w for n in rng.nodes(): adj.setdefault(str(n), {}) bc = betweenness_centrality(adj) oracle = networkx.betweenness_centrality( _nx_graph(adj), weight="distance", normalized=True ) for node, value in bc.items(): assert value == pytest.approx(oracle[node], abs=1e-7), node # --------------------------------------------------------------------- # Burt constraint — star fixture # --------------------------------------------------------------------- def test_constraint_star_center_is_unconstrained(): """Star: the hub bridges structural holes (low constraint); each spoke is fully dependent on the hub (constraint 1.0). Clique members sit in between.""" star = {} for spoke in ["S1", "S2", "S3", "S4"]: star.setdefault("HUB", {})[spoke] = 1.0 star[spoke] = {"HUB": 1.0} c = burt_constraint(star) assert c["HUB"] == pytest.approx(0.25) # sum of (1/4)^2 * 4 for spoke in ["S1", "S2", "S3", "S4"]: assert c[spoke] == pytest.approx(1.0) triangle = { "A": {"B": 1.0, "C": 1.0}, "B": {"A": 1.0, "C": 1.0}, "C": {"A": 1.0, "B": 1.0}, } c3 = burt_constraint(triangle) # closed triad: everyone highly constrained, more than the star hub assert c3["A"] > c["HUB"] oracle = networkx.constraint(_nx_graph(triangle), weight="weight") assert c3["A"] == pytest.approx(oracle["A"], abs=1e-9) def test_field_entropy(): assert field_entropy({}) == 0.0 assert field_entropy({"F1": 10}) == 0.0 assert field_entropy({"F1": 5, "F2": 5}) == pytest.approx(1.0) assert field_entropy({"F1": 1, "F2": 1, "F3": 1, "F4": 1}) == pytest.approx(2.0) # --------------------------------------------------------------------- # Mentor metrics # --------------------------------------------------------------------- def _career(aid, years, wid_prefix): """Solo-ish works giving `aid` a publication history (paired with a throwaway co-author so the works survive the n_authors >= 2 filter).""" return [ make_work(f"{wid_prefix}{y}", y, [(aid, UDE, "first"), (f"X_{aid}_{y}", [], "last")]) for y in years ] def test_mentor_seniority_gap_and_progression(): works = [] # PROF: established since 2000 (>=10 active years by 2015) works += _career("PROF", range(2000, 2026), "P") # JUNIOR: first-ever activity 2015 (active_years_at(2015)=1), then progresses works += [ make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")]), ] works += _career("JUNIOR", range(2016, 2022), "J") # 6 more years -> progressed # PEER: senior colleague, first joint work 2020 when both are senior works += _career("PEER", range(2000, 2026), "Q") works += [make_work("JP", 2020, [("PEER", UDE, "first"), ("PROF", UDE, "last")])] g = build_graph(works, {"PROF", "JUNIOR", "PEER"}) mm = mentor_metrics(g, "PROF") assert mm.juniors_mentored == 1 assert mm.junior_ids == ["JUNIOR"] assert mm.junior_progression_rate == pytest.approx(1.0) # PROF was last author on J1 with a junior first author assert mm.last_author_with_junior_first == 1 # the senior PEER never counts assert "PEER" not in mm.junior_ids def test_mentor_excludes_external_coauthors(): """External co-authors have truncated year-sets and must never count as juniors.""" works = _career("PROF", range(2000, 2026), "P") works += [make_work("E1", 2020, [("EXT", [], "first"), ("PROF", UDE, "last")])] g = build_graph(works, {"PROF"}) # EXT not focal mm = mentor_metrics(g, "PROF") assert mm.juniors_mentored == 0 assert mm.last_author_with_junior_first == 0 def test_mentor_requires_focal_seniority_at_first_joint_year(): """Two juniors co-publishing: neither mentors the other.""" works = [ make_work("W1", 2020, [("J1", UDE, "first"), ("J2", UDE, "last")]), make_work("W2", 2021, [("J1", UDE, "first"), ("J2", UDE, "last")]), ] g = build_graph(works, {"J1", "J2"}) assert mentor_metrics(g, "J2").juniors_mentored == 0 def test_compute_all_metrics_shapes(): works = _career("PROF", range(2000, 2026), "P") works += [make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")])] g = build_graph(works, {"PROF", "JUNIOR"}) rows = compute_all_metrics(g) assert set(rows) == {"PROF", "JUNIOR"} prof = rows["PROF"] assert prof["juniors_mentored"] == 1 assert prof["active_years"] == 26 assert 0.0 <= prof["industry_coauthor_share"] <= 1.0 assert prof["suspicious_profile"] is False