429 lines
17 KiB
Python
429 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
signals.py — M3 amplifier signal joins: patents, news, EU CORDIS projects.
|
|
|
|
Sources and their link quality (README, "M3 — amplifier signal joins"):
|
|
PATENTS org_patents.matched_authors, real OpenAlex author ids. Only
|
|
{institution, both} match types are scored; name-only is evidence.
|
|
NEWS aktuell_postproc LLM-extracted names, normalized-exact match.
|
|
CORDIS DOI overlap, no name matching.
|
|
|
|
All joins return plain dict[author_short_id, count] and are independent of the
|
|
graph/scoring modules.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import gzip
|
|
import hashlib
|
|
import json
|
|
import time
|
|
import unicodedata
|
|
from collections import defaultdict
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from service.scripts.profiling.multipliers.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, dict[str, Any]], dict[str, int]]:
|
|
"""Per-author patent profiles from org_patents. Returns (scored, name_only).
|
|
|
|
`scored` covers docs whose match_type is in `scored_match_types`:
|
|
{"patents": int, "first_patent_year": int|None,
|
|
"last_patent_year": int|None, "counts_by_year": {year: int}}
|
|
The amplifier uses `patents`; the years feed the founder models off this
|
|
same scan. `name_only` is a bare count — evidence only, never scored.
|
|
"""
|
|
scored: dict[str, dict[str, Any]] = {}
|
|
name_only: dict[str, int] = defaultdict(int)
|
|
search_after = None
|
|
while True:
|
|
body: dict[str, Any] = {
|
|
"size": PAGE_SIZE,
|
|
"_source": [
|
|
"match_type",
|
|
"publication_year",
|
|
"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"]
|
|
is_scored = src.get("match_type") in scored_match_types
|
|
year = src.get("publication_year")
|
|
if not isinstance(year, int):
|
|
try:
|
|
year = int(str(year).strip()[:4])
|
|
except (TypeError, ValueError):
|
|
year = None
|
|
for author in src.get("matched_authors") or []:
|
|
aid = author.get("openalex_author_id")
|
|
if not aid:
|
|
continue
|
|
if not is_scored:
|
|
name_only[aid] += 1
|
|
continue
|
|
profile = scored.setdefault(
|
|
aid, {"patents": 0, "counts_by_year": {}}
|
|
)
|
|
profile["patents"] += 1
|
|
if year is not None:
|
|
profile["counts_by_year"][year] = (
|
|
profile["counts_by_year"].get(year, 0) + 1
|
|
)
|
|
search_after = hits[-1]["sort"]
|
|
|
|
for profile in scored.values():
|
|
years = sorted(profile["counts_by_year"])
|
|
profile["first_patent_year"] = years[0] if years else None
|
|
profile["last_patent_year"] = years[-1] if years else None
|
|
return scored, dict(name_only)
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# Patents, name-matched — higher-recall source for the founder models
|
|
# ---------------------------------------------------------------------
|
|
# Under `founding.patent_source: api` (production) these profiles are merged
|
|
# per-author with the org_patents profiles above. Coverage, cost, the merge
|
|
# rationale and this endpoint's known limitations: README, "Feature sourcing".
|
|
|
|
|
|
def author_patent_profiles(
|
|
author_ids: list[str],
|
|
base_url: str,
|
|
concurrency: int = 16,
|
|
timeout: float = 60.0,
|
|
retries: int = 5,
|
|
progress_every: int = 500,
|
|
max_failed_fraction: float = 0.01,
|
|
) -> tuple[dict[str, dict[str, Any]], list[str]]:
|
|
"""Per-author patent profile from `/api/inse-service/authors/{id}/patents`.
|
|
|
|
Returns (profiles, failed_ids). `profiles` contains only authors with >= 1
|
|
patent — callers treat a missing key as zero. `publication_year` arrives as
|
|
a string and is coerced from its first four characters.
|
|
|
|
Two-stage failure handling: the concurrent pass records failures instead of
|
|
raising, then retries them SEQUENTIALLY — under full load the backend 502s
|
|
on authors that succeed instantly once pressure drops, so per-request
|
|
retries alone are not enough. Raises only if survivors exceed
|
|
`max_failed_fraction`; smaller gaps are printed and returned, never silent.
|
|
"""
|
|
results: dict[str, dict[str, Any]] = {}
|
|
done = 0
|
|
|
|
def fetch(client: httpx.Client, author_id: str) -> bool:
|
|
"""One author; True on success. Retries transient failures in-place."""
|
|
nonlocal done
|
|
for attempt in range(retries):
|
|
try:
|
|
response = client.get(
|
|
f"{base_url.rstrip('/')}/api/inse-service/authors/{author_id}/patents"
|
|
)
|
|
response.raise_for_status()
|
|
break
|
|
except (httpx.HTTPError, httpx.HTTPStatusError):
|
|
if attempt == retries - 1:
|
|
return False
|
|
time.sleep(2**attempt)
|
|
|
|
patents = response.json().get("patents") or []
|
|
done += 1
|
|
if progress_every and done % progress_every == 0:
|
|
print(f" patents: {done}/{len(author_ids)} authors", flush=True)
|
|
if not patents:
|
|
return True
|
|
counts_by_year: dict[int, int] = defaultdict(int)
|
|
for patent in patents:
|
|
try:
|
|
year = int(str(patent.get("publication_year")).strip()[:4])
|
|
except (TypeError, ValueError):
|
|
continue
|
|
counts_by_year[year] += 1
|
|
years = sorted(counts_by_year)
|
|
results[author_id] = {
|
|
"patents": len(patents),
|
|
"first_patent_year": years[0] if years else None,
|
|
"last_patent_year": years[-1] if years else None,
|
|
"counts_by_year": dict(counts_by_year),
|
|
}
|
|
return True
|
|
|
|
limits = httpx.Limits(max_connections=concurrency, max_keepalive_connections=concurrency)
|
|
with httpx.Client(timeout=timeout, limits=limits) as client:
|
|
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
|
outcomes = list(pool.map(lambda aid: fetch(client, aid), author_ids))
|
|
failed = [aid for aid, ok in zip(author_ids, outcomes) if not ok]
|
|
|
|
if failed:
|
|
print(f" patents: retrying {len(failed)} load-failed authors sequentially")
|
|
still_failed = [aid for aid in failed if not fetch(client, aid)]
|
|
else:
|
|
still_failed = []
|
|
|
|
if len(still_failed) > max(1, int(max_failed_fraction * len(author_ids))):
|
|
raise RuntimeError(
|
|
f"Patent join failed for {len(still_failed)}/{len(author_ids)} authors "
|
|
f"even after sequential retry — backend looks unhealthy, not flaky. "
|
|
f"First failures: {still_failed[:5]}"
|
|
)
|
|
if still_failed:
|
|
print(f" WARNING: patent data missing for {len(still_failed)} authors "
|
|
f"(treated as zero patents): {still_failed}")
|
|
return results, still_failed
|
|
|
|
|
|
def cached_author_patent_profiles(
|
|
author_ids: list[str],
|
|
base_url: str,
|
|
cache_path: Path,
|
|
concurrency: int = 16,
|
|
force: bool = False,
|
|
) -> dict[str, dict[str, Any]]:
|
|
"""`author_patent_profiles` with a disk cache keyed on the cohort, so a
|
|
changed author set invalidates it automatically. The join is the slowest
|
|
stage in the pipeline (20-65 min) and the YAML weights it feeds get retuned
|
|
repeatedly."""
|
|
cohort_key = hashlib.sha256(
|
|
json.dumps(sorted(author_ids)).encode()
|
|
).hexdigest()[:12]
|
|
|
|
if not force and cache_path.exists():
|
|
with gzip.open(cache_path, "rt", encoding="utf-8") as f:
|
|
cached = json.load(f)
|
|
if cached.get("cohort_key") == cohort_key:
|
|
failed = cached.get("failed_ids") or []
|
|
print(f"Reusing cached patent join ({len(cached['profiles'])} authors "
|
|
f"with patents"
|
|
+ (f"; {len(failed)} known gaps: {failed}" if failed else "")
|
|
+ f") — delete {cache_path.name} or pass --force-extract to refresh.")
|
|
return {
|
|
aid: {**p, "counts_by_year": {int(y): c for y, c in
|
|
p["counts_by_year"].items()}}
|
|
for aid, p in cached["profiles"].items()
|
|
}
|
|
print("Cached patent join is for a different cohort — refetching.")
|
|
|
|
profiles, failed_ids = author_patent_profiles(
|
|
author_ids, base_url, concurrency=concurrency
|
|
)
|
|
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with gzip.open(cache_path, "wt", encoding="utf-8", newline="\n") as f:
|
|
# persisted so gaps stay visible on cached re-runs
|
|
json.dump({"cohort_key": cohort_key, "profiles": profiles,
|
|
"failed_ids": failed_ids}, f)
|
|
return profiles
|
|
|
|
|
|
def merge_patent_profiles(
|
|
primary: dict[str, dict[str, Any]],
|
|
secondary: dict[str, dict[str, Any]],
|
|
) -> tuple[dict[str, dict[str, Any]], dict[str, int]]:
|
|
"""Best-available patent profile per author from two sources.
|
|
|
|
Neither source dominates (README, "Feature sourcing"), so per author the
|
|
higher `patents` count wins whole (ties -> primary). Counts are never
|
|
summed: the same patent can exist in both corpora with no id-level dedup at
|
|
this aggregation, so summing would double-count.
|
|
|
|
Returns (merged, stats) with stats counting who supplied each profile.
|
|
"""
|
|
merged: dict[str, dict[str, Any]] = {}
|
|
stats = {"primary": 0, "secondary": 0}
|
|
for aid in set(primary) | set(secondary):
|
|
p, s = primary.get(aid), secondary.get(aid)
|
|
if p is not None and (s is None or p["patents"] >= s["patents"]):
|
|
merged[aid] = p
|
|
stats["primary"] += 1
|
|
else:
|
|
merged[aid] = s
|
|
stats["secondary"] += 1
|
|
return merged, stats
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# 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). A normalized name shared by more
|
|
than one cohort author is skipped entirely — miscrediting is worse than
|
|
missing.
|
|
"""
|
|
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.
|
|
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,
|
|
) -> tuple[dict[str, dict[str, int]], dict[str, dict[str, Any]]]:
|
|
"""All signal joins.
|
|
|
|
Returns (metrics, org_patent_profiles). `metrics` are flat per-metric dicts
|
|
merged onto the metric rows and scored; `org_patent_profiles` is the nested
|
|
per-author structure from the same scan, returned separately because it
|
|
must NOT be merged onto a metric row.
|
|
"""
|
|
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)}"
|
|
)
|
|
metrics = {
|
|
"patent_count": {aid: p["patents"] for aid, p in patents_scored.items()},
|
|
"patent_count_name_only": patents_name_only,
|
|
"news_mentions": news,
|
|
"cordis_eu_projects": cordis,
|
|
}
|
|
return metrics, patents_scored
|