Files
arzani 577b9f4557
LocationBasedServices/smartguide/pipeline/head This commit looks good
initial version of multipliers in three levels: bridgers, mentors & amplifiers
2026-07-16 01:52:54 +02:00

260 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""
graph.py — co-author graph construction for multiplicator detection (M1, Stage C).
Input: the cached work extract (see spike_audit.py) as plain dicts.
Output: plain-Python structures the metrics module consumes:
- edges: dict[(src, dst)] -> EdgeStats (undirected, src < dst, SHORT author ids)
- nodes: dict[author_id] -> NodeStats (per-author aggregates over their works)
Design constraints (from the M0 spike):
- Works with more than `max_authors_per_work` authors (default 50, chosen from the
measured p90=17 / p99=144 distribution) are excluded from GRAPH construction only —
a 4,839-author consortium paper is not a collaboration signal, but it still counts
toward publication years, which are aggregated here in NodeStats for ALL works.
- Edge weights follow the plan: sum of decay^(ref_year - year) / (n_authors - 1)
per shared work, so recent, small-team collaborations weigh most.
- All author/institution ids are shortened ("https://openalex.org/A5..." -> "A5...")
to keep the adjacency structures small.
Everything here is pure computation over plain data — no I/O, no ES — so it is unit
testable with hand-built fixtures.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Iterable
import polars as pl
OPENALEX_PREFIX = "https://openalex.org/"
def short_id(raw: str | None) -> str | None:
if not raw:
return None
return raw.rsplit("/", 1)[-1] if "/" in raw else raw
@dataclass
class EdgeStats:
weight: float = 0.0 # decay- and team-size-weighted collaboration strength
n_works: int = 0 # raw shared-work count
cross_inst_weight: float = 0.0 # weight portion where the pair shared NO institution
first_joint_year: int | None = None
last_joint_year: int | None = None
@dataclass
class NodeStats:
display_name: str | None = None
is_focal: bool = False # member of the institution author set
publication_years: set[int] = field(default_factory=set) # ALL works (uncapped)
n_works: int = 0 # ALL works (uncapped)
field_counts: dict[str, int] = field(default_factory=dict) # primary_topic.field
n_company_works: int = 0 # works with >=1 co-author institution type=company
n_typed_works: int = 0 # works where >=1 institution has a non-null type
# supervision signature inputs (per work, position-aware; capped works only)
n_last_author_works: int = 0
last_author_junior_first: list[tuple[str, int]] = field(default_factory=list)
# ^ (first_author_id, year) for works where THIS node was last author
@dataclass
class Graph:
edges: dict[tuple[str, str], EdgeStats]
nodes: dict[str, NodeStats]
n_works_used: int # works that entered pair generation
n_works_capped: int # works excluded by max_authors_per_work
ref_year: int # decay reference year
def _work_author_rows(
works: Iterable[dict[str, Any]],
) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]]]:
"""Flatten works into one row per (work, author) plus per-work metadata."""
rows: list[dict[str, Any]] = []
work_meta: dict[str, dict[str, Any]] = {}
for w in works:
wid = short_id(w.get("id"))
year = w.get("publication_year")
if not wid or not isinstance(year, int):
continue
authorships = w.get("authorships") or []
seen: set[str] = set()
work_rows = []
has_company = False
has_typed = False
first_author: str | None = None
last_author: str | None = None
for a in authorships:
aid = short_id((a.get("author") or {}).get("id"))
if not aid or aid in seen:
continue
seen.add(aid)
insts = a.get("institutions") or []
inst_ids = frozenset(
short_id(i.get("id")) for i in insts if i.get("id")
)
for i in insts:
itype = i.get("type")
if itype:
has_typed = True
if itype == "company":
has_company = True
position = a.get("author_position")
if position == "first" and first_author is None:
first_author = aid
if position == "last":
last_author = aid
work_rows.append(
{
"work_id": wid,
"year": year,
"author_id": aid,
"display_name": (a.get("author") or {}).get("display_name"),
"inst_ids": inst_ids,
}
)
n_authors = len(seen)
field_id = short_id(((w.get("primary_topic") or {}).get("field") or {}).get("id"))
work_meta[wid] = {
"year": year,
"n_authors": n_authors,
"field_id": field_id,
"has_company": has_company,
"has_typed": has_typed,
"first_author": first_author,
"last_author": last_author,
}
rows.extend(work_rows)
return rows, work_meta
def build_graph(
works: Iterable[dict[str, Any]],
focal_author_ids: set[str],
max_authors_per_work: int = 50,
decay: float = 0.8,
ref_year: int | None = None,
) -> Graph:
"""Build the weighted co-author graph and per-author aggregates.
`focal_author_ids` may contain full URLs or short ids; both are normalized.
`ref_year` defaults to the max publication year in the corpus so results are
deterministic for a given extract (never wall-clock dependent).
"""
focal = {short_id(a) for a in focal_author_ids}
rows, work_meta = _work_author_rows(works)
if ref_year is None:
ref_year = max((m["year"] for m in work_meta.values()), default=0)
# ---- node aggregates over ALL works (uncapped) ----
nodes: dict[str, NodeStats] = {}
for row in rows:
aid = row["author_id"]
node = nodes.get(aid)
if node is None:
node = nodes[aid] = NodeStats(
display_name=row["display_name"], is_focal=aid in focal
)
meta = work_meta[row["work_id"]]
node.publication_years.add(row["year"])
node.n_works += 1
if meta["field_id"]:
node.field_counts[meta["field_id"]] = (
node.field_counts.get(meta["field_id"], 0) + 1
)
if meta["has_typed"]:
node.n_typed_works += 1
if meta["has_company"]:
node.n_company_works += 1
# supervision signature (uses author_position; only meaningful on capped works —
# "last author" on a 500-author consortium paper is not a supervision signal)
for wid, meta in work_meta.items():
if not (2 <= meta["n_authors"] <= max_authors_per_work):
continue
la, fa = meta["last_author"], meta["first_author"]
if la and la in nodes:
nodes[la].n_last_author_works += 1
if fa and fa != la:
nodes[la].last_author_junior_first.append((fa, meta["year"]))
# ---- pair generation via polars self-join (capped works only) ----
usable_work_ids = {
wid
for wid, meta in work_meta.items()
if 2 <= meta["n_authors"] <= max_authors_per_work
}
n_capped = sum(
1 for meta in work_meta.values() if meta["n_authors"] > max_authors_per_work
)
pair_rows = [r for r in rows if r["work_id"] in usable_work_ids]
edges: dict[tuple[str, str], EdgeStats] = {}
if pair_rows:
df = pl.DataFrame(
{
"work_id": [r["work_id"] for r in pair_rows],
"author_id": [r["author_id"] for r in pair_rows],
}
)
pairs = (
df.join(df, on="work_id", suffix="_b")
.filter(pl.col("author_id") < pl.col("author_id_b"))
.select("work_id", "author_id", "author_id_b")
)
# institution sets are tiny per row; resolve shared-institution in Python
inst_by_work_author: dict[tuple[str, str], frozenset] = {
(r["work_id"], r["author_id"]): r["inst_ids"] for r in pair_rows
}
for wid, a, b in pairs.iter_rows():
meta = work_meta[wid]
year = meta["year"]
w = (decay ** (ref_year - year)) / (meta["n_authors"] - 1)
key = (a, b)
e = edges.get(key)
if e is None:
e = edges[key] = EdgeStats()
e.weight += w
e.n_works += 1
insts_a = inst_by_work_author[(wid, a)]
insts_b = inst_by_work_author[(wid, b)]
if not (insts_a & insts_b):
e.cross_inst_weight += w
if e.first_joint_year is None or year < e.first_joint_year:
e.first_joint_year = year
if e.last_joint_year is None or year > e.last_joint_year:
e.last_joint_year = year
return Graph(
edges=edges,
nodes=nodes,
n_works_used=len(usable_work_ids),
n_works_capped=n_capped,
ref_year=ref_year,
)
def adjacency(graph: Graph) -> dict[str, dict[str, float]]:
"""Symmetric weighted adjacency over ALL nodes (focal + external)."""
adj: dict[str, dict[str, float]] = {}
for (a, b), e in graph.edges.items():
adj.setdefault(a, {})[b] = e.weight
adj.setdefault(b, {})[a] = e.weight
return adj
def focal_subgraph(graph: Graph) -> dict[str, dict[str, float]]:
"""Adjacency restricted to focal (institution-internal) nodes only."""
adj: dict[str, dict[str, float]] = {}
for (a, b), e in graph.edges.items():
na, nb = graph.nodes.get(a), graph.nodes.get(b)
if na and nb and na.is_focal and nb.is_focal:
adj.setdefault(a, {})[b] = e.weight
adj.setdefault(b, {})[a] = e.weight
return adj