Files
smartguide/service/scripts/profiling/multipliers/networks.py
T
2026-08-27 13:53:10 +02:00

128 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""
networks.py — per-author ego-network documents for visualization.
The scores index answers "what did this person score"; this one answers "who
are they connected to and how". Neighbour-neighbour edges come from works that
do not include the ego, so they can only be materialized here, while the full
graph is in memory. Doc shape and node-selection rules: README, "Network
visualization index".
Node selection forces up to `max_forced_mentees` mentees in before the
top-by-weight cut: mentee ties are decayed and team-size-divided, so a pure
top-N hides exactly the people the mentor score is about.
"""
from __future__ import annotations
from typing import Any
from service.scripts.profiling.multipliers.graph import Graph
from service.scripts.profiling.multipliers.metrics import is_suspicious_profile
def build_network_docs(
graph: Graph,
metric_rows: dict[str, dict[str, Any]],
scored_rows: list[dict[str, Any]],
incident: dict[str, list],
inst_by_author: dict[str, str],
company_authors: set[str],
max_nodes: int = 42,
max_forced_mentees: int = 14,
) -> list[dict[str, Any]]:
"""One visualization doc per focal author.
metric_rows must still carry the FULL `junior_ids` (pre-scoring; the scored
rows' evidence list is capped). scored_rows supply the ego header fields.
"""
scored_by_id = {r["author_id"]: r for r in scored_rows}
docs: list[dict[str, Any]] = []
for ego_id, mrow in metric_rows.items():
srow = scored_by_id.get(ego_id)
if srow is None:
continue
mentees = set(mrow.get("junior_ids") or [])
ranked = sorted(
incident.get(ego_id, []), key=lambda kv: kv[1].weight, reverse=True
)
mentee_picks = [n for n, _ in ranked if n in mentees][:max_forced_mentees]
forced = set(mentee_picks)
others = [n for n, _ in ranked if n not in forced]
selected = [ego_id] + mentee_picks + others[: max_nodes - len(mentee_picks)]
idset = set(selected)
nodes = []
for nid in selected:
node = graph.nodes[nid]
if nid == ego_id:
role = "ego"
elif nid in mentees:
role = "mentee"
elif nid in company_authors and not node.is_focal:
role = "industry"
elif node.is_focal:
role = "cohort"
else:
role = "external"
nodes.append(
{
"id": nid,
"name": node.display_name,
"role": role,
"inst": inst_by_author.get(nid, ""),
"active_years": len(node.publication_years),
"suspicious": is_suspicious_profile(node.publication_years),
}
)
# pair lookups against the edge dict (~900 per ego), NOT a scan of
# the 5.8M-edge dict per ego
edges = []
for i, a in enumerate(selected):
for b in selected[i + 1:]:
e = graph.edges.get((a, b) if a < b else (b, a))
if e is None:
continue
edges.append(
{
"a": a,
"b": b,
"w": round(e.weight, 3),
"n_works": e.n_works,
"cross": bool(
e.weight > 0 and e.cross_inst_weight / e.weight > 0.5
),
"first_year": e.first_joint_year,
"last_year": e.last_joint_year,
}
)
cohort_coauthors = sum(
1 for n, _ in ranked if graph.nodes[n].is_focal
)
docs.append(
{
"author_id": ego_id,
"display_name": srow.get("display_name"),
"ego": {
"career_bucket": srow.get("career_bucket"),
"active_years": srow.get("active_years"),
"n_works": srow.get("n_works"),
"suspicious_profile": srow.get("suspicious_profile"),
"tags": srow.get("tags", []),
"sub_scores": srow.get("sub_scores", {}),
"max_sub_score": srow.get("max_sub_score"),
},
"total_coauthors": len(ranked),
"cohort_coauthors": cohort_coauthors,
"mentee_count": len(mentees),
"shown": len(selected) - 1,
"shown_mentees": len(mentee_picks),
"nodes": nodes,
"edges": edges,
}
)
return docs