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

233 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""
signals.py — M3 amplifier signal joins: patents, news, EU CORDIS projects.
Link quality differs per source and dictates how each is used (plan §4):
PATENTS org_patents.matched_authors carries real OpenAlex author IDs with a
doc-level match_type. Only {institution, both} count toward the score;
name-only matches are kept as a separate evidence count.
NEWS aktuell_postproc holds LLM-extracted person names. Matching is
normalized-exact (casefold + diacritic fold): "René Müller" == "rene
muller". A normalized name shared by MULTIPLE cohort authors is skipped
entirely (precision over recall) — crediting the wrong person is worse
than missing a mention. Low YAML weight by design.
CORDIS DOI-overlap join (no name matching): the author's work DOIs from the
extract intersected with cordis_eu_*_publications DOIs -> distinct
project IDs per author.
All functions return plain dict[author_short_id, count] and are independent of the
graph/scoring modules.
"""
from __future__ import annotations
import unicodedata
from collections import defaultdict
from typing import Any
import httpx
from extract import INSE_KEY, INSE_URL, es_search
PAGE_SIZE = 1000
DOI_BATCH = 500
# ---------------------------------------------------------------------
# Patents — org_patents (already author-ID-linked by index_org_patents.py)
# ---------------------------------------------------------------------
def patent_counts(
client: httpx.Client,
institution_short_id: str,
scored_match_types: tuple[str, ...] = ("institution", "both"),
) -> tuple[dict[str, int], dict[str, int]]:
"""Per-author patent counts from org_patents.
Returns (scored, name_only): scored counts only docs whose match_type is in
`scored_match_types`; name_only is kept as evidence and never enters the score.
"""
scored: dict[str, int] = defaultdict(int)
name_only: dict[str, int] = defaultdict(int)
search_after = None
while True:
body: dict[str, Any] = {
"size": PAGE_SIZE,
"_source": ["match_type", "matched_authors.openalex_author_id"],
"query": {"term": {"institution_id": institution_short_id}},
"sort": [{"patent_id": {"order": "asc"}}],
}
if search_after:
body["search_after"] = search_after
result = es_search(client, INSE_URL, INSE_KEY, "org_patents", body)
hits = result["hits"]["hits"]
if not hits:
break
for hit in hits:
src = hit["_source"]
target = scored if src.get("match_type") in scored_match_types else name_only
for author in src.get("matched_authors") or []:
aid = author.get("openalex_author_id")
if aid:
target[aid] += 1
search_after = hits[-1]["sort"]
return dict(scored), dict(name_only)
# ---------------------------------------------------------------------
# News — aktuell_postproc (LLM-extracted names, normalized-exact match)
# ---------------------------------------------------------------------
def normalize_name(name: str) -> str:
"""casefold + strip diacritics + collapse whitespace ("René Müller" -> "rene muller")."""
decomposed = unicodedata.normalize("NFKD", name)
stripped = "".join(c for c in decomposed if not unicodedata.combining(c))
return " ".join(stripped.casefold().split())
def news_mention_counts(
client: httpx.Client,
display_names: dict[str, str],
require_relevant: bool = True,
) -> tuple[dict[str, int], int]:
"""Per-author news mention counts.
display_names: author_short_id -> display_name for the whole cohort.
Returns (counts, ambiguous_names_skipped). Names that normalize identically for
more than one cohort author are skipped entirely.
"""
by_norm: dict[str, list[str]] = defaultdict(list)
for aid, name in display_names.items():
if name:
by_norm[normalize_name(name)].append(aid)
ambiguous = {norm for norm, aids in by_norm.items() if len(aids) > 1}
counts: dict[str, int] = defaultdict(int)
search_after = None
while True:
body: dict[str, Any] = {
"size": PAGE_SIZE,
"_source": ["authors", "relevant"],
"query": {"exists": {"field": "authors"}},
"sort": [{"news_id.keyword": {"order": "asc"}}],
}
if search_after:
body["search_after"] = search_after
result = es_search(client, INSE_URL, INSE_KEY, "aktuell_postproc", body)
hits = result["hits"]["hits"]
if not hits:
break
for hit in hits:
src = hit["_source"]
if require_relevant and not src.get("relevant"):
continue
for name in src.get("authors") or []:
norm = normalize_name(name)
if norm in ambiguous:
continue
aids = by_norm.get(norm)
if aids:
counts[aids[0]] += 1
search_after = hits[-1]["sort"]
return dict(counts), len(ambiguous)
# ---------------------------------------------------------------------
# EU CORDIS — DOI-overlap join
# ---------------------------------------------------------------------
def normalize_doi(doi: str | None) -> str | None:
if not doi:
return None
doi = doi.strip().casefold()
for prefix in ("https://doi.org/", "http://doi.org/", "doi.org/", "doi:"):
if doi.startswith(prefix):
doi = doi[len(prefix):]
return doi or None
def cordis_project_counts(
client: httpx.Client,
dois_by_author: dict[str, set[str]],
) -> dict[str, int]:
"""Distinct CORDIS project count per author via DOI overlap.
dois_by_author values must already be normalized (normalize_doi).
"""
all_dois = sorted({d for dois in dois_by_author.values() for d in dois})
projects_by_doi: dict[str, set[str]] = defaultdict(set)
for start in range(0, len(all_dois), DOI_BATCH):
batch = all_dois[start : start + DOI_BATCH]
# NOT a terms query: 21% of CORDIS DOIs contain uppercase, and `terms` on a
# keyword field is case-sensitive. Per-term case_insensitive matching instead.
result = es_search(
client, INSE_URL, INSE_KEY, "cordis_eu_*_publications",
{
"size": len(batch) * 4, # a DOI can appear in several frameworks
"_source": ["doi", "projectID"],
"query": {
"bool": {
"should": [
{"term": {"doi": {"value": d, "case_insensitive": True}}}
for d in batch
],
"minimum_should_match": 1,
}
},
},
)
for hit in result["hits"]["hits"]:
src = hit["_source"]
doi = normalize_doi(src.get("doi"))
project = src.get("projectID")
if doi and project is not None:
projects_by_doi[doi].add(str(project))
counts: dict[str, int] = {}
for aid, dois in dois_by_author.items():
projects: set[str] = set()
for doi in dois:
projects |= projects_by_doi.get(doi, set())
if projects:
counts[aid] = len(projects)
return counts
# ---------------------------------------------------------------------
# Orchestration
# ---------------------------------------------------------------------
def collect_signals(
institution_short_id: str,
display_names: dict[str, str],
dois_by_author: dict[str, set[str]],
scored_match_types: tuple[str, ...] = ("institution", "both"),
news_require_relevant: bool = True,
) -> dict[str, dict[str, int]]:
"""All signal joins. Returns per-metric dicts keyed by author_short_id."""
with httpx.Client() as client:
patents_scored, patents_name_only = patent_counts(
client, institution_short_id, scored_match_types
)
news, ambiguous_skipped = news_mention_counts(
client, display_names, require_relevant=news_require_relevant
)
cordis = cordis_project_counts(client, dois_by_author)
print(
f"Signals: patents scored for {len(patents_scored)} authors "
f"(name-only evidence: {len(patents_name_only)}), "
f"news mentions for {len(news)} (ambiguous names skipped: {ambiguous_skipped}), "
f"CORDIS projects for {len(cordis)}"
)
return {
"patent_count": patents_scored,
"patent_count_name_only": patents_name_only,
"news_mentions": news,
"cordis_eu_projects": cordis,
}