Files
2026-08-27 13:53:10 +02:00

640 lines
22 KiB
Python

#!/usr/bin/env python3
"""
spike_audit.py — M0 de-risking spike for the multiplicator-detection module.
Extracts the institution's OpenAlex author set (two-group union) and the
FULL-authorship work set for those authors, caches both as gzipped JSONL, and
prints an audit report covering: reproduction (author/work counts), field
coverage (author_position / is_corresponding / institution type), scale
(authors-per-work histogram, pair counts at caps 20/50/100), profile quality,
INSE cluster permissions, and org_patents signal reachability.
Findings and what each one decided: README, "M0 spike results".
Usage:
python service/scripts/multipliers/spike_audit.py --institution-id I62318514
Credentials come from service/src/main/inse/.env. Nothing is written to the real
cluster unless --probe-writes is passed (it creates and deletes a throwaway index).
"""
from __future__ import annotations
import argparse
import collections
import gzip
import json
import math
import os
import statistics
import sys
import time
from pathlib import Path
from typing import Any, Iterable, Iterator
import httpx
import yaml
from dotenv import load_dotenv
SCRIPT_DIR = Path(__file__).resolve().parent
ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env"
load_dotenv(dotenv_path=ENV_PATH)
# --- clusters -------------------------------------------------------------
NES_URL = (os.environ.get("ELASTICSEARCH_URL") or "").rstrip("/")
NES_KEY = os.environ.get("ELASTICSEARCH_API_KEY") or ""
INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/")
INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or ""
# --- extraction knobs (spike-only; the real build reads these from YAML) --
AFFILIATION_YEAR_GTE = 2025
WORK_YEAR_GTE = 1950
AUTHOR_PAGE_SIZE = 1000
AUTHOR_BATCH_SIZE = 250
WORK_PAGE_SIZE = 1000
PAIR_CAPS = (20, 50, 100)
REQUEST_TIMEOUT = 180.0
PROBE_INDEX = "multiplicators_spike_probe"
# ES helpers
def _headers(api_key: str) -> dict[str, str]:
return {
"Authorization": f"ApiKey {api_key}",
"Content-Type": "application/json",
"Accept": "application/json",
}
def es_request(
client: httpx.Client,
method: str,
base_url: str,
api_key: str,
path: str,
body: dict[str, Any] | None = None,
) -> httpx.Response:
url = f"{base_url}/{path.lstrip('/')}"
return client.request(
method, url, headers=_headers(api_key), json=body, timeout=REQUEST_TIMEOUT
)
def es_search(
client: httpx.Client, base_url: str, api_key: str, index: str, body: dict[str, Any]
) -> dict[str, Any]:
response = es_request(client, "POST", base_url, api_key, f"{index}/_search", body)
if not response.is_success:
raise RuntimeError(
f"ES error {response.status_code} for {index}:\n{response.text[:1000]}"
)
return response.json()
# ---------------------------------------------------------------------
# Institution resolution
# ---------------------------------------------------------------------
def resolve_institution(client: httpx.Client, institution_id: str) -> dict[str, Any]:
"""Look up ror + display_name for --institution-id from openalex-institutions."""
raw = institution_id.strip()
short = raw.rsplit("/", 1)[-1]
full = f"https://openalex.org/{short}"
result = es_search(
client,
NES_URL,
NES_KEY,
"openalex-institutions",
{"size": 1, "query": {"term": {"id": full}}},
)
hits = result["hits"]["hits"]
if not hits:
raise SystemExit(f"Institution {full} not found in openalex-institutions.")
source = hits[0]["_source"]
return {
"id": full,
"short_id": short,
"ror": source.get("ror"),
"display_name": source.get("display_name"),
}
# ---------------------------------------------------------------------
# Author queries (two-group union — group 2 recovers empty-last-known authors)
# ---------------------------------------------------------------------
def recent_affiliation_filter(insts: list[dict[str, Any]]) -> dict[str, Any]:
"""Recent affiliation with ANY cohort institution (matched by id, ror as backup)."""
ids = [i["id"] for i in insts]
shoulds: list[dict[str, Any]] = [{"terms": {"affiliations.institution.id": ids}}]
rors = [i["ror"] for i in insts if i.get("ror")]
if rors:
shoulds.append({"terms": {"affiliations.institution.ror": rors}})
return {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{"bool": {"should": shoulds, "minimum_should_match": 1}},
{"range": {"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}}},
]
}
},
}
}
def last_known_filter(insts: list[dict[str, Any]]) -> dict[str, Any]:
"""last_known_institutions membership in the cohort, matched by ID."""
return {
"nested": {
"path": "last_known_institutions",
"query": {
"terms": {"last_known_institutions.id": [i["id"] for i in insts]}
},
}
}
def last_known_exists_filter() -> dict[str, Any]:
return {
"nested": {
"path": "last_known_institutions",
"query": {"exists": {"field": "last_known_institutions.display_name"}},
}
}
AUTHOR_SOURCE = [
"id",
"display_name",
"orcid",
"works_count",
"cited_by_count",
"last_known_institutions",
"affiliations",
]
def author_query(query: dict[str, Any], search_after: Any) -> dict[str, Any]:
body = {
"size": AUTHOR_PAGE_SIZE,
"track_total_hits": True,
"_source": AUTHOR_SOURCE,
"query": query,
"sort": [{"id": {"order": "asc"}}],
}
if search_after:
body["search_after"] = search_after
return body
def collect_authors(
client: httpx.Client, insts: list[dict[str, Any]]
) -> dict[str, dict[str, Any]]:
groups = {
"backend_compatible": {
"bool": {
"filter": [last_known_filter(insts), recent_affiliation_filter(insts)]
}
},
"empty_last_known_recent": {
"bool": {
"filter": [recent_affiliation_filter(insts)],
"must_not": [last_known_exists_filter()],
}
},
}
authors: dict[str, dict[str, Any]] = {}
for group_name, query in groups.items():
search_after = None
total = None
read = 0
while True:
result = es_search(
client, NES_URL, NES_KEY, "openalex-authors",
author_query(query, search_after),
)
hits = result["hits"]["hits"]
if total is None:
total = result["hits"]["total"]["value"]
print(f" [{group_name}] expected {total}")
if not hits:
break
for hit in hits:
src = hit["_source"]
aid = src.get("id")
if not aid:
continue
if aid not in authors:
authors[aid] = {
"id": aid,
"display_name": src.get("display_name"),
"orcid": src.get("orcid"),
"works_count": src.get("works_count"),
"cited_by_count": src.get("cited_by_count"),
"source_sets": [group_name],
}
elif group_name not in authors[aid]["source_sets"]:
authors[aid]["source_sets"].append(group_name)
read += 1
search_after = hits[-1]["sort"]
print(f" [{group_name}] read {read}/{total}")
time.sleep(0.05)
return authors
# ---------------------------------------------------------------------
# Work queries — FULL authorships, no inner_hits
# ---------------------------------------------------------------------
WORK_SOURCE = [
"id",
"doi",
"publication_year",
"type",
"cited_by_count",
"primary_topic.id",
"primary_topic.display_name",
"primary_topic.field.id",
"primary_topic.field.display_name",
"authorships.author.id",
"authorships.author.display_name",
"authorships.author_position",
"authorships.is_corresponding",
"authorships.institutions.id",
"authorships.institutions.display_name",
"authorships.institutions.type",
"authorships.institutions.country_code",
"authorships.institutions.lineage",
]
def works_batch_query(author_ids: list[str], search_after: Any) -> dict[str, Any]:
body = {
"size": WORK_PAGE_SIZE,
"track_total_hits": True,
"_source": WORK_SOURCE,
"query": {
"bool": {
"filter": [
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
{
"nested": {
"path": "authorships",
"query": {"terms": {"authorships.author.id": author_ids}},
}
},
]
}
},
"sort": [{"id": {"order": "asc"}}],
}
if search_after:
body["search_after"] = search_after
return body
def collect_works(
client: httpx.Client, author_ids: list[str]
) -> dict[str, dict[str, Any]]:
works: dict[str, dict[str, Any]] = {}
total_batches = (len(author_ids) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
for i in range(0, len(author_ids), AUTHOR_BATCH_SIZE):
batch = author_ids[i : i + AUTHOR_BATCH_SIZE]
batch_no = i // AUTHOR_BATCH_SIZE + 1
search_after = None
while True:
result = es_search(
client, NES_URL, NES_KEY, "openalex-works*",
works_batch_query(batch, search_after),
)
hits = result["hits"]["hits"]
if not hits:
break
for hit in hits:
src = hit["_source"]
wid = src.get("id")
if wid and wid not in works:
works[wid] = src
search_after = hits[-1]["sort"]
print(f" work batch {batch_no}/{total_batches}: unique works {len(works)}")
time.sleep(0.05)
return works
# ---------------------------------------------------------------------
# Cache IO
# ---------------------------------------------------------------------
def write_jsonl_gz(path: Path, records: Iterable[dict[str, Any]]) -> None:
with gzip.open(path, "wt", encoding="utf-8", newline="\n") as f:
for record in records:
f.write(json.dumps(record, ensure_ascii=True) + "\n")
def read_jsonl_gz(path: Path) -> Iterator[dict[str, Any]]:
with gzip.open(path, "rt", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
yield json.loads(line)
# ---------------------------------------------------------------------
# Audit computations
# ---------------------------------------------------------------------
def _percentile(sorted_vals: list[int], q: float) -> int:
if not sorted_vals:
return 0
idx = min(len(sorted_vals) - 1, int(math.ceil(q * len(sorted_vals)) - 1))
return sorted_vals[max(0, idx)]
def audit_field_coverage(works: list[dict[str, Any]]) -> dict[str, Any]:
n_authorships = 0
with_position = 0
with_corresponding = 0
n_institutions = 0
with_inst_type = 0
company_institutions = 0
for w in works:
for a in w.get("authorships", []) or []:
n_authorships += 1
if a.get("author_position"):
with_position += 1
if a.get("is_corresponding") is not None:
with_corresponding += 1
for inst in a.get("institutions", []) or []:
n_institutions += 1
itype = inst.get("type")
if itype:
with_inst_type += 1
if itype == "company":
company_institutions += 1
def pct(x: int, n: int) -> float:
return round(100.0 * x / n, 2) if n else 0.0
return {
"authorships_total": n_authorships,
"author_position_pct": pct(with_position, n_authorships),
"is_corresponding_pct": pct(with_corresponding, n_authorships),
"institutions_total": n_institutions,
"institution_type_pct": pct(with_inst_type, n_institutions),
"company_institutions": company_institutions,
}
def audit_scale(works: list[dict[str, Any]]) -> dict[str, Any]:
sizes: list[int] = []
pairs_at_cap = {cap: 0 for cap in PAIR_CAPS}
for w in works:
author_ids = {
a["author"]["id"]
for a in (w.get("authorships") or [])
if a.get("author", {}).get("id")
}
n = len(author_ids)
sizes.append(n)
for cap in PAIR_CAPS:
if 2 <= n <= cap:
pairs_at_cap[cap] += n * (n - 1) // 2
sizes_sorted = sorted(sizes)
return {
"works": len(sizes),
"authors_per_work": {
"p50": _percentile(sizes_sorted, 0.50),
"p90": _percentile(sizes_sorted, 0.90),
"p99": _percentile(sizes_sorted, 0.99),
"max": sizes_sorted[-1] if sizes_sorted else 0,
},
"hyperauthorship_works_gt_100": sum(1 for s in sizes if s > 100),
"pair_instances_at_cap": pairs_at_cap,
}
def audit_career(
author_ids: set[str], works: list[dict[str, Any]]
) -> dict[str, Any]:
"""active_years and suspicious-profile flags for in-set authors (exact history)."""
years_by_author: dict[str, set[int]] = collections.defaultdict(set)
for w in works:
year = w.get("publication_year")
if not isinstance(year, int):
continue
for a in w.get("authorships", []) or []:
aid = a.get("author", {}).get("id")
if aid in author_ids:
years_by_author[aid].add(year)
active_years_list: list[int] = []
suspicious = 0
for aid in author_ids:
years = years_by_author.get(aid)
if not years:
continue
active_years_list.append(len(years))
first_year = min(years)
span = max(years) - first_year + 1
if first_year < 1970 or span > 60:
suspicious += 1
ay_sorted = sorted(active_years_list)
return {
"authors_with_works": len(ay_sorted),
"suspicious_profile_count": suspicious,
"suspicious_profile_pct": (
round(100.0 * suspicious / len(ay_sorted), 2) if ay_sorted else 0.0
),
"active_years": {
"p50": _percentile(ay_sorted, 0.50),
"p90": _percentile(ay_sorted, 0.90),
"max": ay_sorted[-1] if ay_sorted else 0,
"mean": round(statistics.fmean(ay_sorted), 2) if ay_sorted else 0.0,
},
}
def audit_signals(client: httpx.Client, inst: dict[str, Any]) -> dict[str, Any]:
"""Probe org_patents (INSE cluster) for matched_authors + match_type breakdown."""
if not INSE_URL or not INSE_KEY:
return {"error": "INSE cluster credentials missing"}
try:
result = es_search(
client, INSE_URL, INSE_KEY, "org_patents",
{
"size": 0,
"track_total_hits": True,
"query": {"term": {"institution_id": inst["short_id"]}},
"aggs": {"by_match_type": {"terms": {"field": "match_type"}}},
},
)
except RuntimeError as exc:
return {"error": str(exc)[:300]}
buckets = (
result.get("aggregations", {}).get("by_match_type", {}).get("buckets", [])
)
return {
"org_patents_for_institution": result["hits"]["total"]["value"],
"match_type_breakdown": {b["key"]: b["doc_count"] for b in buckets},
}
def audit_permissions(client: httpx.Client, probe_writes: bool) -> dict[str, Any]:
"""Test create / bulk / delete-by-query / delete on the INSE cluster."""
if not probe_writes:
return {"skipped": "pass --probe-writes to test index create/bulk/delete"}
if not INSE_URL or not INSE_KEY:
return {"error": "INSE cluster credentials missing"}
out: dict[str, Any] = {}
create = es_request(
client, "PUT", INSE_URL, INSE_KEY, PROBE_INDEX,
{"mappings": {"properties": {"institution_id": {"type": "keyword"}}}},
)
out["create_index"] = create.status_code
if create.is_success:
bulk_body = (
json.dumps({"index": {"_index": PROBE_INDEX, "_id": "probe_1"}})
+ "\n"
+ json.dumps({"institution_id": "PROBE"})
+ "\n"
)
bulk = client.post(
f"{INSE_URL}/_bulk",
headers={**_headers(INSE_KEY), "Content-Type": "application/x-ndjson"},
content=bulk_body,
timeout=REQUEST_TIMEOUT,
)
out["bulk_index"] = bulk.status_code
client.post(f"{INSE_URL}/{PROBE_INDEX}/_refresh", headers=_headers(INSE_KEY))
dbq = es_request(
client, "POST", INSE_URL, INSE_KEY, f"{PROBE_INDEX}/_delete_by_query",
{"query": {"term": {"institution_id": "PROBE"}}},
)
out["delete_by_query"] = dbq.status_code # expect 403 if it mirrors org_patents
drop = es_request(client, "DELETE", INSE_URL, INSE_KEY, PROBE_INDEX)
out["delete_index"] = drop.status_code
return out
# ---------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--institution-id", required=True)
parser.add_argument(
"--config", default=str(SCRIPT_DIR / "multipliers.yaml"),
help="YAML config; its cohorts.<ID>.institution_ids extends the author set "
"beyond the primary institution (e.g. the university hospital).",
)
parser.add_argument(
"--cache-dir", default=str(SCRIPT_DIR / "cache"),
help="Where to read/write the extracted author/work JSONL.gz",
)
parser.add_argument(
"--skip-extract", action="store_true",
help="Reuse cached JSONL.gz instead of hitting ES for author/work extraction.",
)
parser.add_argument(
"--probe-writes", action="store_true",
help="Create+bulk+delete a throwaway index on INSE to test write permissions.",
)
args = parser.parse_args()
if not NES_URL or not NES_KEY:
raise SystemExit(f"Missing NES credentials. Checked {ENV_PATH}")
cache_dir = Path(args.cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
short = args.institution_id.strip().rsplit("/", 1)[-1]
authors_path = cache_dir / f"authors_{short}.jsonl.gz"
works_path = cache_dir / f"works_{short}.jsonl.gz"
cohort_ids = [short]
config_path = Path(args.config)
if config_path.exists():
with open(config_path, "r", encoding="utf-8") as f:
cfg = yaml.safe_load(f) or {}
cohort_cfg = (cfg.get("cohorts") or {}).get(short) or {}
if cohort_cfg.get("institution_ids"):
cohort_ids = [str(i) for i in cohort_cfg["institution_ids"]]
with httpx.Client() as client:
insts = [resolve_institution(client, i) for i in cohort_ids]
inst = insts[0] # primary
print(f"Cohort ({len(insts)} institutions):")
for i in insts:
print(f" {i['short_id']:<14} {i['display_name']}")
if args.skip_extract and authors_path.exists() and works_path.exists():
print("Reusing cached extract.")
authors = {a["id"]: a for a in read_jsonl_gz(authors_path)}
works = list(read_jsonl_gz(works_path))
else:
print("\nExtracting authors...")
authors = collect_authors(client, insts)
write_jsonl_gz(authors_path, authors.values())
print(f"Authors: {len(authors)} -> {authors_path}")
print("\nExtracting works (full authorships)...")
author_ids = sorted(authors.keys())
works_map = collect_works(client, author_ids)
works = list(works_map.values())
write_jsonl_gz(works_path, works)
print(f"Works: {len(works)} -> {works_path}")
author_id_set = set(authors.keys())
print("\nComputing audit...")
report = {
"institution": inst,
"cohort": [
{"id": i["short_id"], "display_name": i["display_name"]} for i in insts
],
"reproduction": {
"author_count": len(authors),
"work_count": len(works),
"group_breakdown": dict(
collections.Counter(
tuple(sorted(a["source_sets"])) and "+".join(sorted(a["source_sets"]))
for a in authors.values()
)
),
},
"field_coverage": audit_field_coverage(works),
"scale": audit_scale(works),
"career_quality": audit_career(author_id_set, works),
"signals": audit_signals(client, inst),
"permissions": audit_permissions(client, args.probe_writes),
}
report_path = cache_dir / f"spike_report_{short}.json"
with open(report_path, "w", encoding="utf-8", newline="\n") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
print("\n=== SPIKE AUDIT REPORT ===")
print(json.dumps(report, ensure_ascii=False, indent=2))
print(f"\nWritten: {report_path}")
if __name__ == "__main__":
main()