Files
arzani bc4193316f
LocationBasedServices/smartguide/pipeline/head This commit looks good
founder potential/mutlipliers backend added
2026-09-17 19:34:30 +02:00

162 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""
networks.py — materialize per-author ego-network documents for visualization.
The scores index answers "what did this person score"; the network index answers
"who are they connected to and how" — the data a frontend needs to draw the
ego-network figures (force layout, role colors, tooltips). The neighbor-neighbor
edges that make graph shape readable (dense mesh = one community, spokes with gaps
= brokered structural holes) come from works that do NOT include the ego, so they
can only be materialized here, while the full graph is in memory — no request-time
query can reconstruct them.
Doc shape (one per focal author, _id = <institution>_<author>):
nodes[] {id, name, role, inst, active_years, suspicious}
role: ego | mentee | cohort | industry | external
edges[] {a, b, w, n_works, cross, first_year, last_year}
w = decayed collaboration strength; cross = mostly cross-institution
ego{} small header duplicate (bucket, tags, sub_scores) so the network
endpoint can render standalone
totals total_coauthors, cohort_coauthors, shown
Node selection: the ego's strongest `max_nodes` co-authors by tie weight, with up
to `max_forced_mentees` mentees force-included first — mentees' ties are decayed
and team-size-divided, so a pure top-by-weight cut hides exactly the people the
mentor score is about (empirically: a 100-mentee professor had zero mentees in his
unforced top 42). Positions are NOT stored — the frontend's force layout
(e.g. echarts `graph` series) lays out at render time.
"""
from __future__ import annotations
from typing import Any
from graph import Graph
from 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_by_author_work: dict[str, dict[str, list[str]]],
company_work_authors: dict[str, 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.
Industry roles are TIE-LEVEL, not lifetime: a neighbour is marked `industry`
only if a company affiliation of theirs appears on a work SHARED with the ego
— matching what `industry_coauthor_share` counts. (The first version flagged
anyone who ever had a company affiliation anywhere in the corpus, which
painted predominantly-academic people orange over one dual affiliation from
years ago, with a university name in the tooltip contradicting the colour.)
The triggering company names ship on the node as `company_insts`, and
`inst_by_author` should be the author's MOST FREQUENT institution so the
default label matches reality.
"""
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]
# company evidence ON WORKS SHARED WITH THE EGO only
shared_companies: set[str] = set()
for wid, names in (company_by_author_work.get(nid) or {}).items():
if ego_id in company_work_authors.get(wid, ()):
shared_companies.update(names)
if nid == ego_id:
role = "ego"
elif nid in mentees:
role = "mentee"
elif shared_companies and not node.is_focal:
role = "industry"
elif node.is_focal:
role = "cohort"
else:
role = "external"
entry = {
"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),
}
if shared_companies:
# the receipts for the industry colour (also kept on cohort/
# mentee nodes so tooltips can show the industry link)
entry["company_insts"] = sorted(shared_companies)
nodes.append(entry)
# all corpus edges among the selected nodes — 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