203 lines
8.3 KiB
Python
203 lines
8.3 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.
|
|
|
|
The `industry` role is EGO-RELATIVE: a node is industry in this ego's network
|
|
only if it has a company-typed affiliation on a work SHARED with the ego, and
|
|
those company names are stored on the node as `company_insts`. A global
|
|
"has a company affiliation anywhere in the corpus" flag mislabels people whose
|
|
industry ties have nothing to do with this ego (measured: 2 of 6 industry
|
|
nodes in the first audited network).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Any, Callable
|
|
|
|
from service.scripts.profiling.multipliers.graph import Graph, short_id
|
|
from service.scripts.profiling.multipliers.metrics import is_suspicious_profile
|
|
|
|
|
|
def collect_author_context(
|
|
works: list[dict[str, Any]],
|
|
focal_short_ids: set[str],
|
|
max_authors_per_work: int = 50,
|
|
doi_normalizer: Callable[[str | None], str | None] | None = None,
|
|
) -> tuple[dict[str, set[str]], dict[str, str], dict[str, dict[str, set[str]]]]:
|
|
"""One pass over the work extract -> (dois_by_author, inst_by_author, company_links).
|
|
|
|
dois_by_author focal author -> their work DOIs (CORDIS join); only
|
|
collected when `doi_normalizer` is given.
|
|
inst_by_author author -> their MOST FREQUENT institution display name
|
|
across all their works (ties break lexicographically).
|
|
First-seen selection showed minority affiliations.
|
|
company_links focal ego -> {co-author -> company display names}, from
|
|
company-typed affiliations the co-author holds ON WORKS
|
|
SHARED with that ego. An ego's own company affiliations
|
|
land under their own id. Works above
|
|
`max_authors_per_work` are excluded, mirroring the graph's
|
|
hyperauthorship cap — consortium papers are not
|
|
collaboration evidence.
|
|
"""
|
|
dois_by_author: dict[str, set[str]] = {}
|
|
inst_counts: dict[str, dict[str, int]] = {}
|
|
company_links: dict[str, dict[str, set[str]]] = {}
|
|
|
|
for w in works:
|
|
doi = doi_normalizer(w.get("doi")) if doi_normalizer else None
|
|
seen: set[str] = set()
|
|
focal_on_work: list[str] = []
|
|
company_on_work: list[tuple[str, set[str]]] = []
|
|
for a in w.get("authorships") or []:
|
|
aid = short_id((a.get("author") or {}).get("id"))
|
|
if not aid or aid in seen:
|
|
continue
|
|
seen.add(aid)
|
|
if aid in focal_short_ids:
|
|
focal_on_work.append(aid)
|
|
if doi:
|
|
dois_by_author.setdefault(aid, set()).add(doi)
|
|
companies: set[str] = set()
|
|
for inst in a.get("institutions") or []:
|
|
name = inst.get("display_name")
|
|
if not name:
|
|
continue
|
|
counts = inst_counts.setdefault(aid, {})
|
|
counts[name] = counts.get(name, 0) + 1
|
|
if inst.get("type") == "company":
|
|
companies.add(name)
|
|
if companies:
|
|
company_on_work.append((aid, companies))
|
|
|
|
if company_on_work and 2 <= len(seen) <= max_authors_per_work:
|
|
for ego in focal_on_work:
|
|
links = company_links.setdefault(ego, {})
|
|
for aid, companies in company_on_work:
|
|
links.setdefault(aid, set()).update(companies)
|
|
|
|
inst_by_author = {
|
|
aid: max(counts.items(), key=lambda kv: (kv[1], kv[0]))[0]
|
|
for aid, counts in inst_counts.items()
|
|
}
|
|
return dois_by_author, inst_by_author, company_links
|
|
|
|
|
|
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_links: dict[str, 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.
|
|
`company_links` comes from `collect_author_context`.
|
|
"""
|
|
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)]
|
|
|
|
ego_company = company_links.get(ego_id, {})
|
|
nodes = []
|
|
for nid in selected:
|
|
node = graph.nodes[nid]
|
|
if nid == ego_id:
|
|
role = "ego"
|
|
elif nid in mentees:
|
|
role = "mentee"
|
|
elif nid in ego_company and not node.is_focal:
|
|
role = "industry"
|
|
elif node.is_focal:
|
|
role = "cohort"
|
|
else:
|
|
role = "external"
|
|
node_doc = {
|
|
"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),
|
|
}
|
|
# which companies connect this person to the ego (present on every
|
|
# role — a mentee or cohort member can hold a company link too)
|
|
if nid in ego_company:
|
|
node_doc["company_insts"] = sorted(ego_company[nid])
|
|
nodes.append(node_doc)
|
|
|
|
# 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
|