diff --git a/service/scripts/multipliers/.gitignore b/service/scripts/multipliers/.gitignore new file mode 100644 index 00000000..cf7c1dee --- /dev/null +++ b/service/scripts/multipliers/.gitignore @@ -0,0 +1,5 @@ +# extracted person-level data + generated artifacts — never commit +cache/ +reports/ +*.log +__pycache__/ diff --git a/service/scripts/multipliers/README.md b/service/scripts/multipliers/README.md new file mode 100644 index 00000000..d9d2cbe6 --- /dev/null +++ b/service/scripts/multipliers/README.md @@ -0,0 +1,490 @@ +# Multiplicator detection — offline pipeline + +Detects **multiplicators** among an institution's researchers — *bridgers* (connect +disconnected research communities), *mentors* (bring up junior/debutant co-authors), and +*amplifiers* (patents, industry co-authorship, news visibility) — from OpenAlex plus the +patent/project/news sources, and writes per-author scores + tags + evidence to a derived +Elasticsearch index. + +Follows the repo's offline pattern (`scripts/patents/index_org_patents.py`): all analysis +and joining happen **offline**, the result lands in a **separate, institution-parameterised +ES index**, and a thin read-only backend router is added only once the UI needs it. + +**New here? Read [ROADMAP.md](docs/ROADMAP.md) first** — a ground-up explanation of the +concept, every index field, the related work behind the metrics, and what's next. + +## Status + +**M0 — spike: done. M1 — metrics core: done** (exit check PASS). **M2 — pipeline + +`multiplicators_v1` index: done** (idempotency verified). **M3 — amplifier signal +joins: wired and indexed** (patents / news / CORDIS; results below) — remaining: +the coach calibration session. **M4 — read router:** pending, once the UI needs it. +All results per milestone are documented in the sections below. + +## Setup + +```bash +cd service/scripts/multipliers +python -m venv .venv && source .venv/bin/activate +pip install -r requirements.txt +``` + +Credentials are read from `service/src/main/inse/.env`: +- `ELASTICSEARCH_URL` / `ELASTICSEARCH_API_KEY` — NES cluster (OpenAlex). +- `ELASTICSEARCH_INSE_URL` / `ELASTICSEARCH_INSE_API_KEY` — INSE cluster (patents, news). + +## Run the spike + +```bash +# Extract + audit for University of Duisburg-Essen (writes cache/ + report json) +python spike_audit.py --institution-id I62318514 + +# Re-audit from the cache without re-hitting ES +python spike_audit.py --institution-id I62318514 --skip-extract + +# Also test write/delete permissions on the INSE cluster (throwaway index) +python spike_audit.py --institution-id I62318514 --probe-writes +``` + +Outputs land in `cache/`: +- `authors_.jsonl.gz` — the two-group author union. +- `works_.jsonl.gz` — full-authorship works (external co-authors + institutions). +- `spike_report_.json` — the audit report. + +The report answers: reproduction (author/work counts), field coverage +(`author_position` / `is_corresponding` / institution `type`), scale (authors-per-work +histogram, pair counts at caps 20/50/100), career quality (suspicious-profile %, +`active_years` distribution), signal reachability (`org_patents` match-type breakdown), +and write permissions. + +`cache/` is disposable and should not be committed (it can be hundreds of MB and contains +extracted person data). + +--- + +## M0 spike results (I62318514, run 2026-07-15) + +The spike existed to answer six questions the whole design was betting on. Full raw +numbers in `cache/spike_report_I62318514.json`; this section explains each stat, why it +was measured, and which downstream metric it feeds. + +### 1. Reproduction — is the extraction correct? + +| Stat | Value | Meaning | +|---|---|---| +| Author count | **4,921** | Exactly reproduces the audited seed extraction (`llm_evaluations/basic_applied_experimental/ude_audit_report.json`). Our port of the query is faithful. | +| — `backend_compatible` group | 4,740 | Authors with `last_known_institutions == UDE` **and** a recent UDE affiliation. | +| — `empty_last_known_recent` group | 181 | Authors with a recent UDE affiliation but **no** `last_known_institutions` at all. Without this second query group, 3.7% of the cohort would silently vanish — this is why the author set is a *union of two queries*, not one. | +| Work count | **183,661** | All works by those 4,921 authors, globally, unrestricted by institution or year. Matches the seed audit. | + +**Contributes to:** everything. This is the corpus. The "all works globally" property is +load-bearing for the career metrics: it means `active_years` is *exact* for in-set +authors (we see their complete history), while for external co-authors we only see works +shared with UDE — which is why mentor metrics are restricted to UDE-internal pairs. + +### 2. Field coverage — are the fields the metrics need actually populated? + +The OpenAlex Pydantic models declare these fields, but that says nothing about whether +the ES index actually populates them. Two sub-scores would have died silently. + +| Stat | Value | Feeds | Verdict | +|---|---|---|---| +| Authorships total | 3,805,507 | — | denominator | +| `author_position` populated | **100%** | `last_author_with_junior_first` (mentor): the classic supervision signature — PI last, junior first. | ✅ computable | +| `is_corresponding` populated | **100%** | reserved for later refinement (corresponding-author weighting). | ✅ available | +| `institutions.type` populated | **99.91%** | `cross_sector_share` / `industry_coauthor_share` (bridger + amplifier): share of works with a co-author at `type == "company"`. | ✅ computable | +| Company-institution occurrences | **67,131** | same | dense enough to rank on — this is the strongest *ID-linked* industry signal we have, stronger than any name-matched source. | + +**Contributes to:** confirms the metric set needs no fallbacks. Had `institutions.type` +been empty, the amplifier would have collapsed onto 123 high-confidence patents (see §6). + +### 3. Scale — where does the pair explosion land, and what cap do we need? + +Co-author pair generation is quadratic per work: a work with *n* authors yields +*n·(n−1)/2* pairs. The distribution of authors-per-work decides whether the self-join is +feasible locally and where to cap it. + +| Stat | Value | +|---|---| +| Authors per work p50 / p90 / p99 / max | **5 / 17 / 144 / 4,839** | +| Works with > 100 authors | **2,459** (1.3%) | +| Pair instances at cap 20 / 50 / 100 | **3.9M / 8.0M / 13.9M** | + +**Why `max_authors_per_work` matters** (the cap): the max-4,839-author work alone would +generate ~11.7M pairs — more than the *entire rest of the corpus* at cap 50 — and a +hyperauthored consortium paper (CERN/medical mega-trials) carries no real collaboration +signal: being 1 of 4,839 names says nothing about who actually works with whom, but it +*would* create a giant artificial clique that inflates betweenness and strength for +everyone on it, poisoning the bridger score. The cap drops works above the threshold +from **graph construction only** — they still count for publication years / `active_years`. + +**Chosen: `max_authors_per_work = 50`.** Rationale: p90 = 17, so a cap of 50 keeps ≥ 99% +of works (cap sits well above p90, below p99 = 144) while excluding only true +hyperauthorship; the resulting 8.0M pair instances collapse to ~1–2M distinct edges, +comfortably in-memory for polars. It's a config value (`extraction.max_authors_per_work`), +not code — tunable per institution. + +**Contributes to:** graph construction (Stage C); confirms the "pure local compute, no +DuckDB/warehouse" bet. + +### 4. Career quality — can we bucket careers, and how bad is profile merging? + +Background: `analysis/career_stage/` established that `first_publication_year` is +unreliable at UDE (merged OpenAlex profiles → debut years of 1893/1906 for active +professors) and that `active_years` (distinct years with ≥ 1 publication) is robust. +The pipeline therefore buckets by `active_years` and uses prefix-counted +`active_years_at(A, Y)` instead of debut years for the mentor metrics. + +| Stat | Value | Meaning / use | +|---|---|---| +| Suspicious profiles | **225 (4.6%)** | `first_year < 1970 or career_span > 60` (same flag as `persons/logic.py`). These are likely *merged identities*. They are **not dropped** — their `active_years` is still fine — but their evidence is marked `low_confidence`. Especially important for the **bridger** score: a merged profile is one node standing in for two people and *systematically* fakes bridging. | +| `active_years` p50 / p90 / max / mean | **4 / 25 / 60 / 8.9** | p50 = 4 means **half the cohort is career-stage "Early" (≤ 4)**. This is why percentile normalization happens *within career buckets* (Early/Emerging/Established/Senior via `_classify_career_stage`): institution-wide percentiles would just rank seniority, and no early-career person could ever surface as a multiplicator. | + +**Contributes to:** career bucketing (scoring), mentor junior/senior thresholds, +confidence flags on evidence. + +### 5. Permissions — can we ship the result anywhere? + +Initial spike: `PUT` to create an index on the INSE cluster → **403** (key can read, not +create). Resolved 2026-07-15: **`multiplicators_v1` was created by the cluster admin**, +and the standard INSE key can now write to it (verified: doc create + delete both +succeed). The build step must therefore *never* try to create/re-create the index — only +delete-by-institution + bulk-index into the existing one (same constraint as +`org_patents`, whose key also rejects `_delete_by_query`; use the search + bulk-delete +loop from `patents/org/elastic_search_client.py`). + +**Contributes to:** M2 index/build design. + +### 6. Signal reachability — which amplifier sources are real? + +| Stat | Value | Meaning | +|---|---|---| +| `org_patents` docs for UDE | **436** | The patent→OpenAlex-author link index exists and is populated. | +| — `match_type: name` | 313 | Name-only match. **Evidence only, weight 0** — name matching is the weakest link type. | +| — `match_type: both` | 65 | Institution assignee **and** name match — highest confidence. **Scores.** | +| — `match_type: institution` | 58 | Institution-assignee match. **Scores.** | + +**Contributes to:** amplifier sub-score. Only 123 patents are high-confidence, so patents +are a *secondary* amplifier signal; the primary is `industry_coauthor_share` (67k +ID-linked company co-authorships, §2). News (`aktuell_postproc`, exact-string person +match) enters at low weight; DFG (token containment) and Bund (no person link) are +excluded entirely. + +### Spike exit criteria — all met (see below for M1) + +- ✅ Extraction reproduces the audited counts exactly. +- ✅ Every planned metric is confirmed computable — no fallbacks needed. +- ✅ `max_authors_per_work = 50` chosen from measured data. +- ✅ Write path to `multiplicators_v1` verified end-to-end. +- ✅ Amplifier signal priorities re-ordered based on measured density + (industry co-authorship primary, patents secondary). + +--- + +## M1 results (metrics core, run 2026-07-15) + +Modules: `graph.py` (co-author graph via polars self-join, decay weights, hyperauthorship +cap), `metrics.py` (Brandes betweenness with inverted weights, Burt constraint on the +full graph incl. externals, field entropy, industry co-author share, debut-year-free +mentor metrics on `active_years_at`), `scoring.py` + `multipliers.yaml` +(within-career-bucket percentiles → weighted sub-scores → tags). 26 unit tests +(`pytest`), including exact agreement with networkx oracles for betweenness/constraint +and the planted-1893-outlier regression guard for `active_years_at`. + +Run with: + +```bash +python build.py --institution-id I62318514 # scores + summary from the cache +python validate_sample.py --institution-id I62318514 # 60-person exit check +``` + +### Full-corpus run (I62318514) + +| Stat | Value | +|---|---| +| Runtime end-to-end | **2.6 min** (load 15s, graph 31s, metrics 112s) — exit criterion was < 15 min | +| Graph | 639,544 nodes (4,921 focal + externals), 4,143,499 edges | +| Works used / capped | 160,396 / 4,823 (`max_authors_per_work = 50`) | +| Tags at threshold 0.85 | bridger 66, mentor 91, amplifier 609 | + +The amplifier tag count is inflated for now: only `industry_coauthor_share` exists at M1 +(patents/news/CORDIS join in M3), so weight redistribution makes it a single-metric +sub-score. Ignore amplifier tags until M3. + +### M1 exit check — PASS + +Against the 60 hand-labeled researchers in `analysis/career_stage/career_stage_sample.csv` +(31 Professor / 29 Researcher), mentor scores must concentrate on professors: + +| known status | n | median mentor score | +|---|---|---| +| Professor | 25 | **0.715** | +| Researcher | 18 | 0.493 | + +Top of the list is face-valid: senior professors with 30–50 mentored juniors and strong +last-author-with-junior-first signatures (Bacher, Sures, Hering, Gunzer, …). The two +high-scoring "Researchers" are informative, not embarrassing: e.g. a core-facility +scientist with 37 juniors but **zero** last-author works — the independent supervision +signature correctly separates "publishes with many juniors" from "supervises them". + +### ⚠ Cohort-coverage finding (must be decided in M2) + +17 of the 60 sample people are missing from the 4,921-author cohort. Diagnosed causes: + +1. **University-hospital clinicians are systematically excluded.** Prominent UDE + medicine professors (e.g. Witzke, Bingel) have + `last_known_institutions = Essen University Hospital (I4210119759)`, and the + hospital is **not** in UDE's OpenAlex lineage — OpenAlex models it as a *related* + institution, not a child. **2,437 active (2025+) authors** sit behind this gap — + roughly half a cohort. Fix: make the cohort definition accept a list of + institution IDs (`I62318514` + `I4210119759` + …) per deployment, sourced from + `associated_institutions` and confirmed by a human. +2. **Stale affiliation years exclude current staff.** E.g. Saccà has + `last_known = UDE` but no `affiliations.years >= 2025` entry, so the recency + filter drops her. Fix candidates: widen the window (>= 2023), or accept + `last_known = UDE` alone with a works-recency check. + +Both are extraction-time cohort decisions with precision/recall tradeoffs — they belong +to the coaches/product owner, not to code defaults. + +--- + +## M1 validation in detail (what was checked, against what ground truth) + +### The ground truth + +`analysis/career_stage/career_stage_sample.csv` — 60 UDE researchers with manually +researched **role labels** (`known_status`: 31 Professor / 29 Researcher incl. doctoral), +across five discipline groups (Biology, CS, Engineering, Medicine, Sociology), each with +an OpenAlex author ID (so the join to our scores is exact — no name matching involved). +The sample was originally built for the career-stage analysis; it does **not** label +anyone as a "multiplicator" — no such ground truth exists yet (that is the M3 golden set +the innovation coaches will provide). + +### What exactly was evaluated + +One directional sanity check on the riskiest sub-score: *supervision is part of the +professor role, so if the mentor sub-score measures anything like real mentorship, +professors must score systematically higher than researchers.* Defined check: +professors' **median mentor sub-score > researchers'**. + +The check is stronger than it looks because scores are percentiles **within career +buckets**: a Senior researcher is compared against Senior professors, not against PhD +students, so a trivial "older people score higher" effect is largely normalized away — +the gap has to come from mentor behaviour (juniors mentored, last-author-with-junior- +first works), not raw seniority. + +### Results (UDE-only cohort, 2026-07-15; archived as `cache/*_I62318514.udeonly.json`) + +43 of 60 matched (17 missing — see the cohort-coverage finding above). Medians: + +| sub-score | Professor (n=25) | Researcher (n=18) | check | +|---|---|---|---| +| **mentor** | **0.715** | **0.493** | **PASS** | +| bridger | 0.603 | 0.508 | (informational) | +| amplifier | 0.655 | 0.413 | (single-metric until M3 — ignore) | + +Ranking detail, more convincing than the medians: + +- Top = senior professors with strong dual signals: Gerd Bacher (37 juniors, 16 + last-author-junior-first works), Bernd Sures (52, 24), Daniel Hering (35, 25), + Matthias Gunzer (54 juniors). +- Bottom = early-career researchers with 0 juniors. +- The two high-scoring "Researchers" are the system working, not failing: + Birte Möhlendick (0.924, 12 juniors) — plausibly a group leader whose formal title + lags her role; Farnusch Kaschani (0.714, **37 juniors but 0 last-author works**) — + the classic core-facility-scientist profile: on many students' papers without + supervising them. The two mentor signals disagreeing on exactly this person is why + `last_author_with_junior_first` exists as an independent cross-check. + +### What this does NOT show + +It validates the *direction* of the mentor proxy, not that top-ranked people are good +mentors or multiplicators: professor-vs-researcher is a coarse label, n=43 is small, +bridger has no ground truth in this sample, and amplifier is a single-metric score until +M3. The real validation is the coach golden set (M3). This check is kept as a +regression: re-run `validate_sample.py` after every weight change or dump refresh. + +--- + +## Cohort fix + re-run (2026-07-15, config version 2) + +The hospital gap above is fixed by a **configurable cohort list**: `cohorts.. +institution_ids` in `multipliers.yaml`. **How the list was discovered — and how to +build one for another university — is documented in +[ASSOCIATED_INSTITUTIONS.md](docs/ASSOCIATED_INSTITUTIONS.md).** For UDE it holds 9 institutions — UDE, Essen +University Hospital, the West German Heart Center, the Erwin L. Hahn Institute, and the +five OpenAlex lineage children (RISP, DTNW, KWI, ZBT, IUTA) — with the deliberate +exclusions (Kliniken Essen-Mitte, the independent An-Institute) documented inline for +the coaches to revisit. Candidates were sourced from `associated_institutions` in +`openalex-institutions`; the extractor now matches `last_known_institutions` / +`affiliations` by **institution ID terms** over the whole list. + +### Before / after (UDE-only → 9-institution cohort) + +| | UDE-only | cohort | note | +|---|---|---|---| +| Authors | 4,921 | **6,583** | +1,662, mostly hospital clinicians | +| Works | 183,661 | **221,603** | | +| Graph | 640k nodes / 4.14M edges | 764k / 5.26M | | +| Pipeline runtime | 2.6 min | **4.5 min** | still far under the 15-min criterion | +| Sample matched | 43/60 | **45/60** | Witzke + Bingel recovered | +| Mentor exit check | 0.715 vs 0.493 PASS | **0.699 vs 0.493 PASS** | stable | +| Tags (bridger/mentor/amplifier) | 66/91/609 | 96/131/763 | scales with cohort | + +Face validity of the fix: both recovered professors immediately tag as mentors with +strong evidence — Witzke (Senior, 73 juniors mentored), Bingel (Senior, 34 juniors, +21 last-author-with-junior-first works). + +### The remaining 15 missing, fully diagnosed + +- **9 × correctly excluded** — they left UDE (`last_known` now Halle, Würzburg, + Greifswald, OU Netherlands, ISG, or none). The sample is older than the corpus; + these are not gaps. +- **6 × stale-affiliation cases** — `last_known` IS in the cohort but their most + recent cohort affiliation year is 2021–2024, so the `affiliation_years_gte: 2025` + recency filter drops them. At least one (Saccà, last seen 2024) is a current + professor — publication lag alone can push someone out of a 1-year window. + **Recommendation for M2:** set `extraction.affiliation_years_gte: 2023` (already + config) — captures normal publication lag while still excluding long-departed + authors. Decide with the coaches; it trades a little precision for recall. + +--- + +## M2 — pipeline + ES index (done 2026-07-15) + +New modules: `extract.py` (canonical cohort-aware extraction, config-driven), +`index.py` (`MultiplicatorsIndexClient` for `multiplicators_v1` on the INSE cluster), +`build.py` (single entry point: extract → graph → metrics → scoring → index). +`spike_audit.py` remains self-contained for auditing any institution. + +```bash +python build.py --institution-id I62318514 # full run (reuses cache) +python build.py --institution-id I62318514 --force-extract # refresh from ES +python build.py --institution-id I62318514 --no-index # local artifacts only +``` + +### Index contract (`multiplicators_v1`, INSE cluster) + +- Doc `_id` = `_` (e.g. `I62318514_A5087456839`); + one doc per author per institution. +- Every doc: raw metrics, per-bucket percentiles, sub-scores, tags, career bucket, + `suspicious_profile`, evidence (junior ids), `config_hash`, `computed_at`, + `cohort_institution_ids`. Explicit mapping is PUT on every run (additive). +- Idempotent re-runs: collect the institution's doc ids → bulk-delete → bulk-index → + poll `_count` until the expected count is visible. **Verified: delete 9,474 → + index 9,474 → count 9,474.** + +### Key-permission gotchas (learned the hard way, encoded in `index.py`) + +The admin-created index + standard INSE key allows: read, `_bulk` index/delete, +`_mapping` updates, `_count`. It does **not** allow: index create/delete, +`_delete_by_query` (same as org_patents), and — new finding — **`_refresh` +(`indices:admin/refresh` → 403)**. A first client version silently relied on refresh +and saw phantom docs during delete (stale visibility inflated the delete count) and a +too-early post-index count. The client now never calls `_refresh`: it collects all doc +ids BEFORE deleting, and verifies by polling `_count` (auto-refresh ≈ 1s) instead. + +### Run with `affiliation_years_gte: 2023` (config v2 → v3) + +| | 2025 cutoff | 2023 cutoff | +|---|---|---| +| Authors / works | 6,583 / 221,603 | **9,475 / 267,467** | +| Graph | 764k nodes / 5.26M edges | 865k / 5.82M | +| Full runtime (incl. extract + index) | — | **~14.5 min** | +| Sample matched | 45/60 | **51/60** | +| Mentor exit check | 0.699 vs 0.493 PASS | **0.740 vs 0.494 PASS** (wider gap) | + +The 9 still-missing sample people are exactly the 9 confirmed leavers (last_known now +Halle, Würzburg, Greifswald, …) — correct exclusions, zero unexplained gaps. All six +stale-affiliation cases were recovered (some via 2023+ affiliations with the hospital / +institute cohort members rather than UDE itself). + +Career-bucket distribution in the index: Early 5,361 / Emerging 1,591 / +Established 777 / Senior 1,745. Tags: bridger 133, mentor 161, amplifier 1,107 +(amplifier still single-metric until M3 — ignore). + +### Next (M3) + +Wire the signal joins into the amplifier score (`org_patents` match_type +institution/both, news with name normalization at low weight, CORDIS DOI-join), +then calibrate the YAML weights with the innovation coaches against their golden set. +M4 (read router in `inse/`) once the UI needs it. + +--- + +## M3 — amplifier signal joins (done 2026-07-15) + +Before wiring, a live-index audit showed the amplifier was degenerate: its only input +(`industry_coauthor_share`) was 0 for 61.5% of the cohort, and the "top amplifiers" +were small-denominator ratio artifacts (share = 1.0 with 2 typed works). Two fixes: + +1. **Shrinkage**: scoring now uses `industry_coauthor_share_shrunk = company/(typed+k)` + (k=5, config `signals.industry_share_shrinkage_k`); the raw share stays in the doc. +2. **Three independent signal joins** (`signals.py`), weights in YAML + (shrunk share 0.50 / patents 0.25 / CORDIS 0.15 / news 0.10): + +| signal | join mechanism | UDE yield (9,474 authors) | +|---|---|---| +| `patent_count` | `org_patents.matched_authors` author IDs, `match_type ∈ {institution, both}`; name-only kept as `patent_count_name_only` evidence, never scored | 55 authors (17 more name-only) | +| `news_mentions` | `aktuell_postproc` LLM-extracted names, normalized-exact match (casefold + diacritic fold); a normalized name shared by >1 cohort authors credits NO ONE | 1,369 authors; **839 ambiguous names skipped** (precision over recall) | +| `cordis_eu_projects` | DOI overlap with `cordis_eu_*_publications` → distinct projectIDs. **Case-insensitive term matching** — 21% of CORDIS DOIs contain uppercase and a plain `terms` query silently misses them | 1,342 authors | + +Signal join runtime ≈ 9 min (the case-insensitive CORDIS batches dominate); total +pipeline ≈ 20 min. Mentor/bridger untouched: validation unchanged (51/60, mentor +check PASS 0.740 vs 0.494). + +### Effect on the amplifier tag + +Tags went **1,107 → 10**. With four independent inputs, a ≥0.85 *weighted mean* of +within-bucket percentiles requires being near the top on most channels — the tag now +means something. The new top-10 is face-valid (Wiltfang, Erbel, Kaiser, Schierning — +patent-holding, industry-connected, media-visible seniors). Two open calibration +questions for the coaches: + +- **Threshold per tag?** 0.85 yields 133 bridgers / 161 mentors / 10 amplifiers. + If more amplifier candidates are wanted, either lower a per-tag threshold + (currently one global `tags.threshold`) or re-weight. +- **Split-profile artifact**: an Early-bucket author with 1 active year made top-10 + amplifier — almost certainly a split OpenAlex profile of a senior professor + (patents/news land on the fragment). Bucket-relative ranking amplifies fragments; + the `suspicious_profile` flag does not catch splits (only merges). Known + limitation — ORCID-based resolution is the deferred fix. + +### M3 remaining + +The **coach calibration session**: golden set of 10–20 known multiplicators, tune the +YAML (weights, per-tag thresholds), re-run `validate_sample.py` as regression. + +--- + +## Network visualization index (`multiplicator_networks_v1`, added 2026-07-16) + +The scores index answers *what did this person score*; this companion index answers +*who are they connected to and how* — everything a frontend needs to draw the +ego-network figures (force layout, role colors, tooltips) without recomputing +anything. Materialized by `build.py` (`networks.py`) while the full graph is in +memory, because the **neighbor-neighbor edges** that make graph shape readable +(dense mesh = one community; spokes with gaps = brokered structural holes) come from +works that do NOT include the ego — no request-time query can reconstruct them. + +One doc per focal author, `_id = _` (same scheme as scores): + +| field | content | +|---|---| +| `nodes[]` | `{id, name, role, inst, active_years, suspicious}`; role ∈ ego / mentee / cohort / industry / external | +| `edges[]` | `{a, b, w, n_works, cross, first_year, last_year}` — `w` = decayed tie strength, `cross` = mostly cross-institution | +| `ego{}` | header duplicate (bucket, tags, sub_scores, max_sub_score) so a network endpoint renders standalone | +| totals | `total_coauthors`, `cohort_coauthors`, `mentee_count`, `shown`, `shown_mentees` | +| provenance | `config_hash`, `computed_at`, `cohort_institution_ids` | + +Selection: strongest `network.max_nodes` (42) co-authors by tie weight with up to +`network.max_forced_mentees` (14) mentees force-included first — mentees' ties are +decayed and team-size-divided, so a pure top-by-weight cut hides exactly the people +the mentor score is about. Positions are NOT stored: the webapp's echarts `graph` +series (force layout) lays out at render time; map role → color, active_years → +symbol size, `cross` → dashed line. + +`nodes`/`edges` are mapped `"enabled": false` (stored, never indexed) — the index +stays small and fast for the queryable header fields (`institution_id`, `author_id`, +`ego.tags`, `computed_at`, …). Skip building with `--no-network`. diff --git a/service/scripts/multipliers/build.py b/service/scripts/multipliers/build.py new file mode 100644 index 00000000..ae7a971f --- /dev/null +++ b/service/scripts/multipliers/build.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +""" +build.py — single entry point for the multiplicator pipeline (M2). + +extract (cached) -> graph -> metrics -> scoring -> local artifacts -> ES index. + + python build.py --institution-id I62318514 # full run + python build.py --institution-id I62318514 --force-extract # refresh the ES extract + python build.py --institution-id I62318514 --no-index # skip the ES write + +Artifacts in --cache-dir: + authors_.jsonl.gz / works_.jsonl.gz the extract (reused unless --force-extract) + scores_.jsonl.gz one scored row per focal author + build_summary_.json stage timings + tag counts + top lists + +The ES write targets `multiplicators_v1` on the INSE cluster (admin-created; the API +key cannot create indices). Doc _id = _; every run deletes the +institution's docs first, so re-runs are idempotent. +""" +from __future__ import annotations + +import argparse +import gzip +import json +import time +from pathlib import Path + +from extract import extract_to_cache, read_jsonl_gz +from graph import build_graph, short_id +from index import NETWORK_MAPPING, NETWORKS_INDEX, MultiplicatorsIndexClient +from metrics import compute_all_metrics, incident_edges +from networks import build_network_docs +from scoring import load_config, score_rows +from signals import collect_signals, normalize_doi + +SCRIPT_DIR = Path(__file__).resolve().parent + + +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")) + parser.add_argument("--cache-dir", default=str(SCRIPT_DIR / "cache")) + parser.add_argument( + "--force-extract", action="store_true", + help="Re-extract from ES even if a cache exists.", + ) + parser.add_argument( + "--no-index", action="store_true", + help="Compute and write local artifacts but skip the ES indexing step.", + ) + parser.add_argument( + "--no-signals", action="store_true", + help="Skip the patents/news/CORDIS signal joins (amplifier falls back to " + "industry co-authorship alone).", + ) + parser.add_argument( + "--no-network", action="store_true", + help="Skip materializing the per-author ego-network visualization docs.", + ) + args = parser.parse_args() + + short = args.institution_id.strip().rsplit("/", 1)[-1] + cache_dir = Path(args.cache_dir) + config = load_config(args.config) + timings: dict[str, float] = {} + + # ---- extract (cache-aware) ---- + t0 = time.time() + authors_path, works_path, insts = extract_to_cache( + args.institution_id, config, cache_dir, force=args.force_extract + ) + cohort_short_ids = [i["short_id"] for i in insts] + timings["extract_s"] = round(time.time() - t0, 1) + + # ---- load ---- + t0 = time.time() + focal_ids = {a["id"] for a in read_jsonl_gz(authors_path)} + works = list(read_jsonl_gz(works_path)) + timings["load_cache_s"] = round(time.time() - t0, 1) + print(f"Loaded {len(works)} works, {len(focal_ids)} focal authors " + f"({timings['load_cache_s']}s)") + + # ---- single pass over works before they are freed: DOIs per focal author + # (CORDIS join) + per-author institution label and company flag (network docs) + focal_short_ids = {short_id(a) for a in focal_ids} + dois_by_author: dict[str, set[str]] = {} + inst_by_author: dict[str, str] = {} + company_authors: set[str] = set() + for w in works: + doi = normalize_doi(w.get("doi")) + for a in w.get("authorships") or []: + aid = short_id((a.get("author") or {}).get("id")) + if not aid: + continue + if doi and aid in focal_short_ids: + dois_by_author.setdefault(aid, set()).add(doi) + for inst in a.get("institutions") or []: + if aid not in inst_by_author and inst.get("display_name"): + inst_by_author[aid] = inst["display_name"] + if inst.get("type") == "company": + company_authors.add(aid) + + # ---- graph ---- + t0 = time.time() + graph = build_graph( + works, + focal_ids, + max_authors_per_work=config["extraction"]["max_authors_per_work"], + decay=config["graph"]["decay"], + ) + del works + timings["build_graph_s"] = round(time.time() - t0, 1) + print(f"Graph: {len(graph.nodes)} nodes, {len(graph.edges)} edges, " + f"{graph.n_works_used} works used, {graph.n_works_capped} capped, " + f"ref_year={graph.ref_year} ({timings['build_graph_s']}s)") + + # ---- metrics ---- + t0 = time.time() + metric_rows = compute_all_metrics( + graph, + junior_active_years_max=config["mentor"]["junior_active_years_max"], + senior_active_years_min=config["mentor"]["senior_active_years_min"], + progressed_active_years_min=config["mentor"]["progressed_active_years_min"], + industry_share_shrinkage_k=config.get("signals", {}).get( + "industry_share_shrinkage_k", 5 + ), + ) + timings["metrics_s"] = round(time.time() - t0, 1) + print(f"Metrics for {len(metric_rows)} focal authors ({timings['metrics_s']}s)") + + # ---- signal joins (patents / news / CORDIS) ---- + if args.no_signals: + print("Skipping signal joins (--no-signals).") + timings["signals_s"] = 0.0 + else: + t0 = time.time() + signals_cfg = config.get("signals") or {} + display_names = { + aid: row.get("display_name") or "" for aid, row in metric_rows.items() + } + signal_counts = collect_signals( + short, + display_names, + {a: d for a, d in dois_by_author.items() if a in metric_rows}, + scored_match_types=tuple( + signals_cfg.get("patent_match_types", ["institution", "both"]) + ), + news_require_relevant=signals_cfg.get("news_require_relevant", True), + ) + for metric, counts in signal_counts.items(): + for aid, row in metric_rows.items(): + row[metric] = counts.get(aid, 0) + timings["signals_s"] = round(time.time() - t0, 1) + print(f"Signal joins done ({timings['signals_s']}s)") + + # ---- scoring ---- + t0 = time.time() + scored = score_rows(metric_rows, config) + timings["scoring_s"] = round(time.time() - t0, 1) + + scores_path = cache_dir / f"scores_{short}.jsonl.gz" + with gzip.open(scores_path, "wt", encoding="utf-8", newline="\n") as f: + for row in scored: + f.write(json.dumps(row, ensure_ascii=True) + "\n") + print(f"Scores -> {scores_path} ({timings['scoring_s']}s)") + + # ---- index into ES ---- + docs_written = 0 + if args.no_index: + print("Skipping ES indexing (--no-index).") + else: + t0 = time.time() + es = MultiplicatorsIndexClient() + es.ensure_mapping() + docs_written = es.index_rows(short, cohort_short_ids, scored) + count = es.count_for_institution(short) + timings["index_s"] = round(time.time() - t0, 1) + print(f"Indexed {docs_written} docs into {es.index} " + f"(count for {short}: {count}) ({timings['index_s']}s)") + if count != len(scored): + raise RuntimeError( + f"Post-index count mismatch: expected {len(scored)}, index has {count}" + ) + + # ---- ego-network visualization docs ---- + network_docs_written = 0 + if args.no_index or args.no_network: + print("Skipping network materialization.") + else: + t0 = time.time() + network_cfg = config.get("network") or {} + network_docs = build_network_docs( + graph, + metric_rows, + scored, + incident_edges(graph), + inst_by_author, + company_authors, + max_nodes=int(network_cfg.get("max_nodes", 42)), + max_forced_mentees=int(network_cfg.get("max_forced_mentees", 14)), + ) + net_es = MultiplicatorsIndexClient(index=NETWORKS_INDEX) + net_es.ensure_mapping(NETWORK_MAPPING) + network_docs_written = net_es.index_rows(short, cohort_short_ids, network_docs) + timings["network_s"] = round(time.time() - t0, 1) + print(f"Indexed {network_docs_written} network docs into {net_es.index} " + f"({timings['network_s']}s)") + + # ---- summary ---- + tag_counts: dict[str, int] = {} + for row in scored: + for tag in row["tags"]: + tag_counts[tag] = tag_counts.get(tag, 0) + 1 + + def top(sub: str, k: int = 10): + rows = sorted(scored, key=lambda r: r["sub_scores"].get(sub, 0), reverse=True) + return [ + { + "author_id": r["author_id"], + "name": r["display_name"], + "score": r["sub_scores"][sub], + "bucket": r["career_bucket"], + "active_years": r["active_years"], + "suspicious": r["suspicious_profile"], + } + for r in rows[:k] + ] + + summary = { + "institution": short, + "cohort": cohort_short_ids, + "config_hash": config["_config_hash"], + "counts": { + "focal_authors_scored": len(scored), + "nodes": len(graph.nodes), + "edges": len(graph.edges), + "works_used": graph.n_works_used, + "works_capped": graph.n_works_capped, + "tags": tag_counts, + "suspicious_profiles": sum(1 for r in scored if r["suspicious_profile"]), + "es_docs_written": docs_written, + "es_network_docs_written": network_docs_written, + }, + "timings": timings, + "top_bridgers": top("bridger"), + "top_mentors": top("mentor"), + "top_amplifiers": top("amplifier"), + } + summary_path = cache_dir / f"build_summary_{short}.json" + with open(summary_path, "w", encoding="utf-8", newline="\n") as f: + json.dump(summary, f, ensure_ascii=False, indent=2) + print(json.dumps(summary["counts"], ensure_ascii=False, indent=2)) + print(f"Summary -> {summary_path}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/multipliers/conftest.py b/service/scripts/multipliers/conftest.py new file mode 100644 index 00000000..88b7f134 --- /dev/null +++ b/service/scripts/multipliers/conftest.py @@ -0,0 +1,5 @@ +"""Make the module root importable from tests/ (pytest inserts this dir via conftest).""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) diff --git a/service/scripts/multipliers/docs/ASSOCIATED_INSTITUTIONS.md b/service/scripts/multipliers/docs/ASSOCIATED_INSTITUTIONS.md new file mode 100644 index 00000000..c4eb893e --- /dev/null +++ b/service/scripts/multipliers/docs/ASSOCIATED_INSTITUTIONS.md @@ -0,0 +1,116 @@ +# Cohort discovery: finding a university's associated institutions in OpenAlex + +How the `cohorts..institution_ids` list in `multipliers.yaml` was built for the +University of Duisburg-Essen (I62318514), and how to repeat the process for another +university. Context: the multiplicator pipeline's author set is only as good as this +list — matching UDE alone silently excluded ~2,400 active clinicians, including +prominent medicine professors (found via the M1 validation, where 17/60 hand-labeled +people were missing). + +## Why this is necessary: `lineage` vs `associated_institutions` + +Every institution document in OpenAlex (index `openalex-institutions`) carries two +relationship fields: + +- **`lineage`** — the strict parent hierarchy: a list of institution IDs including the + institution itself and its parents. This is what ID-based filters normally use + (e.g. `company_connections/logic.py` checks `UDE_OPENALEX_ID in lineage`). +- **`associated_institutions`** — a looser list of linked institutions, each with a + `relationship` label: `child`, `parent`, or `related`. + +The trap: **OpenAlex models German university hospitals as `related`, not as lineage +children.** Essen University Hospital's own `lineage` contains only itself. Any filter +built on UDE's ID or lineage therefore can never match hospital-affiliated authors — +the entire clinical medical faculty — no matter how the query is written. + +## The discovery method (3 steps) + +### Step 1 — read the university's `associated_institutions` + +Query the `openalex-institutions` document for the primary ID and list its +`associated_institutions`. For UDE (I62318514): + +| ID | relationship | name | authors (all-time last_known) | +|---|---|---|---| +| I4210090139 | child | Rhein-Ruhr Institut für Sozialforschung | 11 | +| I4210092428 | child | Deutsches Textilforschungszentrum Nord-West | 170 | +| I4210110714 | child | Institute for Advanced Study in the Humanities (KWI) | 81 | +| I4210146441 | child | Hydrogen and Fuel Cell Center (ZBT) | 98 | +| I4210154243 | child | Institut für Energie- und Umwelttechnik (IUTA) | 233 | +| **I4210119759** | **related** | **Essen University Hospital** | **7,484** | +| I4210146447 | related | Kliniken Essen-Mitte | 788 | +| I2799342142 | related | Salomon Ludwig Steinheim-Institut | — | +| I4210124583 | related | IWW Water Centre | — | + +(For comparison: UDE itself has 14,388 all-time last_known authors.) + +### Step 2 — follow one hop into any `related` hospital + +The hospital's own `associated_institutions` revealed a member invisible from UDE's +record: the **West German Heart and Vascular Center Essen (I4210161917)** is a `child` +of the hospital (1,021 authors) — two hops from UDE. + +### Step 3 — validate against real people (this catches what no query can) + +The **Erwin L. Hahn Institute for MRI (I127668822)** was NOT found by any metadata +walk: in OpenAlex it is completely isolated — `lineage` contains only itself, +`associated_institutions` is empty. It surfaced only when diagnosing why a specific +hand-labeled professor (Ulrike Bingel) was missing from the cohort: it appeared in her +affiliation list. Lesson: after building the list from metadata, always check a set of +known current researchers against the extracted cohort — the misses point to +institutions the graph walk cannot reach. + +## Inclusion decisions for UDE (documented in `multipliers.yaml`) + +**Included (9):** + +- `I62318514` UDE (primary) +- `I4210119759` Essen University Hospital — it *is* the university medical centre; + its `related` label is an OpenAlex modelling choice, not an organisational fact +- `I4210161917` West German Heart and Vascular Center (child of the hospital) +- `I127668822` Erwin L. Hahn Institute (joint UDE institute; isolated in OpenAlex) +- The five lineage children: RISP, DTNW, KWI, ZBT, IUTA — small but unambiguous + +**Excluded by default (revisit with the coaches):** + +- `I4210146447` Kliniken Essen-Mitte — an independent hospital group; `related` + reflects collaboration, not membership; its staff are not UDE researchers +- `I2799342142` Salomon Ludwig Steinheim-Institut and `I4210124583` IWW Water + Centre — *An-Institute*: legally independent institutes **at** UDE, not **of** it + +The borderline cases are exactly the German-institutional-law ones (An-Institute, +municipal hospital groups). These are human judgment calls, which is why the list +lives in config with the reasoning inline, not in code. + +## Effect on the cohort (measured) + +| | UDE ID only | 9-institution cohort | +|---|---|---| +| Authors (affiliation ≥ 2023) | ~7,100¹ | 9,475 | +| Hand-labeled sample matched | 43/60² | 51/60 | +| Unexplained misses | 17 | **0** (the 9 remaining all verifiably left UDE) | + +¹ approximate — the single-ID number was measured at the 2025 cutoff (4,921); scaled here for context. +² at the 2025 cutoff; the cohort fix and the 2023 affiliation window each contributed. + +Recovered by the fix, as a face-validity check: Oliver Witzke (Senior, 73 juniors +mentored → tagged mentor) and Ulrike Bingel (Senior, 34 juniors, 21 +last-author-with-junior-first works → tagged mentor). + +## Repeating this for another university + +1. Fetch `associated_institutions` from `openalex-institutions` for the primary ID; + collect all `child` entries and every `related` entry. +2. For any `related` hospital / medical centre, fetch ITS `associated_institutions` + and collect its children. +3. For each candidate, count authors + (`last_known_institutions.id == ` on `openalex-authors`) — size tells + you what an inclusion decision is worth. +4. Decide inclusions with a human: university hospitals in; independent hospital + groups and An-Institute out unless the institution says otherwise. +5. Write the `cohorts.` block in `multipliers.yaml` with the reasoning + as inline comments. +6. Run the extraction, then validate against a list of known current researchers + (professors from several faculties, especially medicine). Every unexplained miss + is either a missing cohort member (like the Hahn Institute) or a stale-affiliation + case (tune `extraction.affiliation_years_gte`). diff --git a/service/scripts/multipliers/docs/ROADMAP.md b/service/scripts/multipliers/docs/ROADMAP.md new file mode 100644 index 00000000..e806975d --- /dev/null +++ b/service/scripts/multipliers/docs/ROADMAP.md @@ -0,0 +1,239 @@ +# Multiplicator Detection — Concept, Technical Walkthrough & Roadmap + +A ground-up explanation of what this module does, how every field in the +`multiplicators_v1` index is computed and what it means, where the ideas come from, +and where the project stands. Written for a reader with no prior context. + +Companion docs: [README.md](../README.md) (per-milestone results and stats), +[ASSOCIATED_INSTITUTIONS.md](ASSOCIATED_INSTITUTIONS.md) (cohort discovery method). + +--- + +## 1. What problem this solves + +The university's innovation coaches want to find **multiplicators**: people whose value +isn't only their own research output, but their effect on the system around them — they +connect groups that otherwise wouldn't talk, they grow junior researchers into +independent scientists, they carry research out of academia into industry and the +public. These people are invisible in classic rankings (citations, h-index), which +measure individual output, not systemic effect. + +The core bet of the whole project: **these behaviors leave measurable traces in +publication metadata.** Who you publish with, when, in what role, and across which +institutional boundaries is recorded in OpenAlex for every paper. So instead of asking +"who is influential?" we ask three narrower, checkable questions, each an archetype: + +- **Bridger** — do your collaborations span otherwise-disconnected communities, + fields, institutions, sectors? +- **Mentor** — do junior people repeatedly start their careers publishing with you, + in the role configuration typical of supervision? +- **Amplifier** — does your work escape academia: patents, industry co-authorship, + EU projects, press coverage? + +Everything else is machinery for answering those three questions honestly at the +scale of ~9,500 people. + +## 2. The pipeline, step by step + +**Step 1 — Define who "the university" is (cohort).** OpenAlex models Essen University +Hospital as merely *related* to UDE, not part of it, so filtering by UDE's ID alone +silently loses the entire clinical faculty (~2,400 active people). The cohort is +therefore an explicit list of 9 institution IDs (UDE + hospital + heart center + +affiliated institutes) — the `cohort_institution_ids` array on every document. An +author belongs if their last-known institution is in that list **and** they have an +affiliation year ≥ 2023 (publication lag makes a 1-year window drop current staff). +Details: [ASSOCIATED_INSTITUTIONS.md](ASSOCIATED_INSTITUTIONS.md). + +**Step 2 — Extract.** For those ~9,475 authors we pull **all their works globally** — +not just university-affiliated ones — with the *complete* author list of every paper, +including external co-authors and each co-author's institution (with its type: +education, company, healthcare…). Result: ~267k works, ~3.8M authorship records. +The "all works globally" property matters: it makes career histories *exact* for +cohort members, while external co-authors' histories are truncated to shared works — +a fact the mentor metrics must respect (see §3). + +**Step 3 — Build the co-authorship graph.** Every paper connects each pair of its +authors with an edge. Three refinements: + +- **Team-size weighting**: a pair on a 3-author paper gets weight 1/(n−1) = 0.5; on a + 40-author paper, 1/39. Being 2 of 3 authors is strong evidence you actually work + together; being 2 of 40 is weak evidence. +- **Time decay**: each paper's contribution is multiplied by 0.8^(years ago). A 2025 + collaboration counts full; a 2010 one counts ~3%. We're looking for *current* + multiplicators. +- **Hyperauthorship cap**: papers with >50 authors (CERN-style consortia; the corpus + max is 4,839 authors on one paper) are excluded from the graph entirely — that one + paper alone would create ~11.7M fake "collaboration" edges and a giant artificial + clique. Those papers still count for career metrics. + +Result: ~865k nodes (cohort + all their external co-authors), ~5.8M weighted edges. + +**Step 4 — Compute metrics on that graph** (§3, field by field). + +**Step 5 — Normalize fairly and score.** Raw metrics aren't comparable between a PhD +student and a 30-year professor, so every metric becomes a **percentile within the +person's career stage**, then three weighted sub-scores, then tags above a threshold +(§4). + +**Step 6 — Join external signals** (patents, news, EU projects) and **write everything +to `multiplicators_v1`** — one document per person, containing raw values, percentiles, +scores, tags, and evidence, so a coach can always see *why* someone scored what they +scored. + +## 3. A real document, field by field + +Example: Tabea M. G. Pakull, `_id = I62318514_A5043360678` (institution + author — +the same person at another university would be a separate doc). An ES `_version: 8` +just means the doc was overwritten 8 times by re-runs; the `fields` block ES returns +alongside `_source` is its internal columnar echo — ignore it. + +### Career context + +| field | example value | meaning | +|---|---|---| +| `active_years` | 3 | Distinct calendar years with ≥1 publication — our seniority measure. We deliberately do **not** use "years since first publication": the repo's career-stage analysis found merged OpenAlex profiles give active professors debut years like 1893. One wrong old paper distorts career span by decades but moves `active_years` by exactly +1. | +| `career_bucket` | "Early" | Early ≤4, Emerging ≤9, Established ≤14, Senior >14 active years — thresholds taken unchanged from the backend's `_classify_career_stage`, empirically validated against 60 known professors/researchers. **All percentiles are computed against the same bucket only.** | +| `n_works` | 12 | Works in the extract. | +| `suspicious_profile` | false | Merged-identity flag (first year <1970 or span >60). True ⇒ treat evidence as low-confidence; ~18% of Seniors carry it. | + +### Bridger metrics (network structure) + +| field | example | what it measures | +|---|---|---| +| `betweenness` | 0 | **Betweenness centrality** on the cohort-internal graph: how often the strongest connection paths between other cohort members run *through you*. High = the network's traffic must pass you = you connect groups. Edge weights are "closeness", so paths use inverted weights as distances. A 0 is normal early-career; the percentile can still be ~0.44 because most of the bucket is also 0 and ties share their average rank. | +| `constraint` → `brokerage` | 0.085 → 0.915 | **Burt's constraint** looks only at your *ego network* (you + your co-authors): do your contacts also know each other? High constraint = you sit inside one dense clique. Low = your contacts live in separate worlds and *you* are the only link — you span "structural holes". Stored as `brokerage = 1 − constraint` so higher = more bridging. Computed on the **full graph including external co-authors**, so it sees outward bridging that internal betweenness can't. In the example: 82 co-authors who barely know each other — 90th percentile of the Early bucket. | +| `field_entropy` | 0.98 | Shannon entropy over the scientific fields of the person's papers. 0 = monodisciplinary; 1.0 bit ≈ two fields evenly; 2.0 ≈ four. Topical breadth as a proxy for interdisciplinary bridging (OpenAlex has no faculty structure, so this is the honest substitute — it must never be presented as "bridges faculties"). | +| `cross_institution_share` | 0.85 | Share of collaboration weight with co-authors sharing *no* institution with the person — external orientation. | +| `strength`, `n_coauthors` | 8.25, 82 | Total decayed edge weight and distinct co-author count — "reach", context only, not scored directly. | + +### Mentor metrics + +OpenAlex has no supervision records and debut years are unreliable, so the mentor +signals are built on **`active_years_at(person, year)`** — how many active years +someone had accumulated *as of a given year* — which inherits the robustness of +`active_years` (a spurious 1893 paper shifts it by exactly 1, not 120). + +| field | definition | +|---|---| +| `juniors_mentored` | Count of cohort co-authors who, in the year of their *first* joint paper, had ≤4 active years (Early) **while the focal person had ≥10** (Established+). A seniority-*gap* criterion — two PhD students co-publishing never counts. | +| `junior_progression_rate` | Of those juniors, the fraction who later reached ≥5 active years — separates "grew them up" from "co-signed once". `null` = no juniors = not applicable (excluded from scoring, not counted against the person). | +| `last_author_with_junior_first` | Papers where the person is **last author** with an Early-career **first author** — the classic supervision signature (student first, PI last). Deliberately independent of the gap logic: when the two disagree (37 "juniors" but zero last-author papers) that's the core-facility-scientist pattern, not a mentor. | +| `mentoring_rate` | juniors ÷ own active years. Without a rate, prolific seniors win on volume alone (professor median 224 papers vs 11 for researchers). | + +Mentor metrics are computed **only between cohort members**: external co-authors' +histories are truncated to shared works, so an external senior would masquerade as a +junior. This scope restriction is a data-correctness requirement, not a choice. + +### Amplifier metrics + +| field | source & link quality | +|---|---| +| `industry_coauthor_share` | Share of typed works with ≥1 company-affiliated co-author. The strongest industry signal available because it's **institution-ID-linked** — no name matching. Kept raw for transparency. | +| `industry_coauthor_share_shrunk` | The **scored** variant: company ÷ (typed + 5). Why: with raw shares, someone with 2-of-2 company papers gets share 1.0 and beats someone with 40-of-80 — before this fix, the index's entire top-10 "amplifiers" were such small-denominator artifacts. The +5 makes small samples humble. | +| `patent_count` | From `org_patents`, which links patents to OpenAlex author IDs. Only high-confidence matches (`match_type` = institution/both) are scored. | +| `patent_count_name_only` | Name-only patent matches — **evidence only, never scored**. | +| `news_mentions` | University press corpus, LLM-extracted names, matched after normalizing case and diacritics (René = rene). If a normalized name belongs to *two* cohort people, **nobody** gets credit (839 names skipped at UDE) — miscrediting is worse than missing. Hence the low weight. | +| `cordis_eu_projects` | Distinct EU projects joined by **DOI overlap** (the person's paper DOIs ∩ DOIs attached to CORDIS project publications) — no name matching. Matching is case-insensitive because 21% of CORDIS DOIs contain uppercase. | + +### Scoring plumbing + +| field | meaning | +|---|---| +| `percentiles.*` | Each raw metric's mean-rank percentile *within the career bucket*. Ties share their average rank — that's why a metric at 0 in a mostly-zero bucket shows ~0.44–0.50, not 1.0: a mass of zeros must not be rewarded. `null` metrics are excluded, and their weight is redistributed. | +| `sub_scores.{bridger,mentor,amplifier}` | Weighted means of the percentiles. Weights live in `multipliers.yaml`, never in code — coaches retune them. Current amplifier weights: shrunk share 0.50, patents 0.25, CORDIS 0.15, news 0.10. | +| `tags` | Sub-score ≥ `tags.threshold` (0.85) ⇒ tag; a person can hold 0–3. Current yield at UDE: 133 bridgers, 161 mentors, 10 amplifiers. | +| `max_sub_score` | Best sub-score — the default ranking key. | +| `evidence.junior_ids` | Receipts (which people count as mentees) — a coach never sees a bare number. | +| `config_hash`, `computed_at` | Which YAML weighting produced the score, and when. Scores are cohort-relative and weight-dependent; without this they'd be unfalsifiable after the next retune. | +| `institution_id`, `cohort_institution_ids` | Which university this doc belongs to and which 9 institutions defined its cohort. | + +Worked example (the Pakull doc): amplifier = 0.50·0.99 (shrunk share) + 0.25·0.50 +(patents, tie-mass) + 0.15·0.98 (one EU project — 98th percentile *for an +Early-career person*) + 0.10·0.47 (news) = **0.8131** — high, but under 0.85 ⇒ no +tag. Mentor 0.494 ≈ bucket median: all-zero mentor metrics in a bucket where nearly +everyone is zero lands exactly mid-pack. + +## 4. related work + +- **Co-authorship graphs as collaboration networks** — Mark Newman's early-2000s + studies of scientific collaboration networks, which also introduced the 1/(n−1) + team-size weighting. The warning that huge author lists break co-authorship + semantics is Blaise Cronin's "hyperauthorship" critique — the basis for the + 50-author cap. +- **Bridger, theory** — Granovetter's "strength of weak ties" (1973): novel + information flows across bridges between groups, not within dense cliques. +- **Bridger, operationalization** — *betweenness centrality* (Linton Freeman, 1977), + computed with Ulrik Brandes' 2001 algorithm (implemented in `metrics.py`, tested + against networkx); *structural holes and constraint* (Ronald Burt, 1992; his 2004 + "Structural holes and good ideas" showed brokers produce more good ideas). The + weights-are-distances inversion for betweenness is a standard weighted-network + practice. Shannon entropy as a diversity/interdisciplinarity indicator follows + standard scientometrics usage (Stirling-style diversity). +- **Mentor** — reading mentorship from publication genealogies is established in + scientometrics (e.g. Malmgren, Ottino & Amaral's Nature study of mentor–protégé + networks). The first-author-student / last-author-PI convention is a documented + authorship norm in the life sciences — credible at a medicine-heavy university. + Shipped caveat: co-authorship ≠ supervision; it's a proxy, validated directionally + against 60 hand-labeled people (professors' median mentor score 0.740 vs + researchers' 0.494). +- **Amplifier** — the university "third mission" / knowledge-transfer literature + (Etzkowitz & Leydesdorff's Triple Helix line): patents, industry co-publication, + joint projects as measurable transfer channels. Industry co-authorship as primary + indicator is pragmatic: it's the only channel linked by institution IDs rather + than names. +- **Fair comparison** — percentile indicators within reference groups are the modern + bibliometrics standard (compare like with like). Our reference group is the career + bucket; the buckets come from this repo's own `analysis/career_stage/` work, which + is also the empirical source for the most important design decision: rejecting + `first_publication_year` in favor of `active_years`. `active_years_at(A, Y)` is our + small extension of that finding. +- **Data-quality corrections** (all found by measuring, not assumed): the hospital + cohort gap (OpenAlex `related` vs lineage), ratio shrinkage, tie-sharing + percentiles, the news ambiguity rule, merged/split-profile flags — responses to + the well-known author-disambiguation weaknesses of bibliographic databases. + +## 5. What was achieved (status) + +Three falsifiable behavioral definitions instead of a vague label; a decay- and +team-size-weighted collaboration graph over the complete global publication history +of a correctly-defined 9-institution cohort; established network-science and +bibliometric measures, made robust against the two dominant data pathologies (merged +profiles, hyperauthorship); within-career-stage normalization; three independent +external evidence channels joined at their honest link quality; and a queryable index +where every person carries raw values, percentiles, scores, tags, and receipts — +validated against hand-labeled ground truth, every tunable in config, every score +stamped with the config that produced it. + +| Milestone | Status | +|---|---| +| M0 — de-risking spike against the real cluster | ✅ done | +| M1 — graph + metrics + scoring core, 60-person validation | ✅ done (PASS) | +| M2 — cohort fix, extraction module, idempotent `multiplicators_v1` indexing | ✅ done | +| M3 — amplifier signal joins (patents / news / CORDIS) + shrinkage fix | ✅ wired & indexed | + +## 6. Roadmap — what's next + +1. **M3 calibration session (human, next).** Coaches provide a golden set of 10–20 + known multiplicators, ideally labeled by type. Tune `multipliers.yaml` + (sub-score weights, per-tag thresholds — 0.85 currently yields 133/161/10 + bridger/mentor/amplifier tags; if more amplifier candidates are wanted, introduce + per-tag thresholds). Re-run `validate_sample.py` after every change as regression. +2. **M4 — read-only serving layer**, once the UI needs it: thin FastAPI router in + `inse/multiplicators/` over BOTH indices — `multiplicators_v1` for list views + (by tag/bucket/score + per-person evidence) and `multiplicator_networks_v1` for + the ego-network visualization (one doc per author: nodes with roles, edges with + tie strength/cross-institution flags, ego header — render with echarts force + layout; see README "Network visualization index"). Then + `./gradlew :service:exportOpenApiSpec` to regenerate the Angular client. +3. **Scheduling** — re-run `build.py` per dump refresh (Airflow, like the other + crawlers); scores are batch-computed, serving is read-only. +4. **Deferred improvements**, in value order: + - **ORCID / `ude_persons_1.0` bridge** — the single highest-value follow-up: fixes + news linking, catches *split* profiles (the `suspicious_profile` flag only + catches merges; one split-profile artifact sits in the current amplifier + top-10), and would enable faculty-level bridging via the staff directory. + - Per-field percentile cohorts (biologist baselines ≠ sociologist baselines) — + decide with coaches. + - Project layer as graph edges (consortium co-membership), DFG/Bund signals if a + real person-link ever exists. + - Committing the module (currently untracked on `feature/find-multipliers`). diff --git a/service/scripts/multipliers/extract.py b/service/scripts/multipliers/extract.py new file mode 100644 index 00000000..c08f806f --- /dev/null +++ b/service/scripts/multipliers/extract.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python3 +""" +extract.py — cohort-aware extraction of the author + work sets from Elasticsearch. + +Canonical home of the extraction logic (spike_audit.py and build.py both use it). + +The author set is a UNION OF TWO QUERIES (a correctness requirement found during the +seed audit — group 2 recovers ~4% of authors that group 1 silently drops): + + 1. backend_compatible last_known_institutions in the cohort AND a recent + cohort affiliation (years >= extraction.affiliation_years_gte) + 2. empty_last_known_recent recent cohort affiliation but NO last_known_institutions + +The cohort is the list of OpenAlex institution IDs from `cohorts..institution_ids` +in multiplicators.yaml (falling back to the primary ID alone). This exists because +OpenAlex does NOT model university hospitals as lineage children — matching only the +primary institution excluded ~2,400 active UDE clinicians. + +The work set is ALL works by those authors, globally (full authorship lists incl. +external co-authors — required for the bridging signals), paginated with +search_after over an id sort, batched ~250 author IDs per terms query. +""" +from __future__ import annotations + +import gzip +import json +import os +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) + +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 "" + +AUTHOR_PAGE_SIZE = 1000 +AUTHOR_BATCH_SIZE = 250 +WORK_PAGE_SIZE = 1000 +REQUEST_TIMEOUT = 180.0 + + +# --------------------------------------------------------------------- +# 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() + + +# --------------------------------------------------------------------- +# Config / cohort +# --------------------------------------------------------------------- + + +def load_config(path: str | Path) -> dict[str, Any]: + with open(path, "r", encoding="utf-8") as f: + return yaml.safe_load(f) or {} + + +def cohort_ids_for(config: dict[str, Any], primary_short_id: str) -> list[str]: + cohort = (config.get("cohorts") or {}).get(primary_short_id) or {} + ids = cohort.get("institution_ids") + return [str(i) for i in ids] if ids else [primary_short_id] + + +def resolve_institution(client: httpx.Client, institution_id: str) -> dict[str, Any]: + """Look up ror + display_name from openalex-institutions.""" + short = institution_id.strip().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 +# --------------------------------------------------------------------- + + +def recent_affiliation_filter( + insts: list[dict[str, Any]], year_gte: int +) -> 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": year_gte}}}, + ] + } + }, + } + } + + +def last_known_filter(insts: list[dict[str, Any]]) -> dict[str, Any]: + 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 collect_authors( + client: httpx.Client, + insts: list[dict[str, Any]], + affiliation_year_gte: int, +) -> dict[str, dict[str, Any]]: + groups = { + "backend_compatible": { + "bool": { + "filter": [ + last_known_filter(insts), + recent_affiliation_filter(insts, affiliation_year_gte), + ] + } + }, + "empty_last_known_recent": { + "bool": { + "filter": [recent_affiliation_filter(insts, affiliation_year_gte)], + "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: + body: dict[str, Any] = { + "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 + result = es_search(client, NES_URL, NES_KEY, "openalex-authors", body) + 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 collect_works( + client: httpx.Client, author_ids: list[str], work_year_gte: int +) -> 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: + body: dict[str, Any] = { + "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": batch} + }, + } + }, + ] + } + }, + "sort": [{"id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + result = es_search(client, NES_URL, NES_KEY, "openalex-works*", body) + 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) + + +# --------------------------------------------------------------------- +# Top-level: extract to cache +# --------------------------------------------------------------------- + + +def extract_to_cache( + institution_id: str, + config: dict[str, Any], + cache_dir: Path, + force: bool = False, +) -> tuple[Path, Path, list[dict[str, Any]]]: + """Extract authors + works for the cohort to jsonl.gz caches. + + Returns (authors_path, works_path, resolved cohort institutions). Reuses an + existing cache unless force=True. + """ + if not NES_URL or not NES_KEY: + raise SystemExit(f"Missing NES credentials. Checked {ENV_PATH}") + + short = institution_id.strip().rsplit("/", 1)[-1] + cache_dir.mkdir(parents=True, exist_ok=True) + authors_path = cache_dir / f"authors_{short}.jsonl.gz" + works_path = cache_dir / f"works_{short}.jsonl.gz" + + extraction_cfg = config.get("extraction") or {} + affiliation_year_gte = int(extraction_cfg.get("affiliation_years_gte", 2023)) + work_year_gte = int(extraction_cfg.get("work_year_gte", 1950)) + + with httpx.Client() as client: + insts = [ + resolve_institution(client, i) for i in cohort_ids_for(config, short) + ] + print(f"Cohort ({len(insts)} institutions, affiliation years >= {affiliation_year_gte}):") + for inst in insts: + print(f" {inst['short_id']:<14} {inst['display_name']}") + + if not force and authors_path.exists() and works_path.exists(): + print("Reusing cached extract (use --force-extract to refresh).") + return authors_path, works_path, insts + + print("\nExtracting authors...") + authors = collect_authors(client, insts, affiliation_year_gte) + write_jsonl_gz(authors_path, authors.values()) + print(f"Authors: {len(authors)} -> {authors_path}") + + print("\nExtracting works (full authorships)...") + works_map = collect_works(client, sorted(authors.keys()), work_year_gte) + write_jsonl_gz(works_path, works_map.values()) + print(f"Works: {len(works_map)} -> {works_path}") + + return authors_path, works_path, insts diff --git a/service/scripts/multipliers/graph.py b/service/scripts/multipliers/graph.py new file mode 100644 index 00000000..6d0dff54 --- /dev/null +++ b/service/scripts/multipliers/graph.py @@ -0,0 +1,259 @@ +#!/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 diff --git a/service/scripts/multipliers/index.py b/service/scripts/multipliers/index.py new file mode 100644 index 00000000..22cdd2dd --- /dev/null +++ b/service/scripts/multipliers/index.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +""" +index.py — idempotent indexing of scored multiplicator rows into Elasticsearch. + +Target: the `multiplicators_v1` index on the INSE cluster. The index was created by +the cluster admin — the standard API key can read/write/update-mapping but NOT +create or delete indices, so this module must never attempt index creation. + +Idempotency: doc _id = "_", and every run first +deletes the institution's existing docs via a search + bulk-delete-by-id loop. +That loop (not _delete_by_query) is deliberate: the same cluster rejects +_delete_by_query with 403 for the org_patents key — see +inse/patents/org/elastic_search_client.py for the precedent. +""" +from __future__ import annotations + +import json +import time +from datetime import datetime, timezone +from typing import Any + +import httpx + +from extract import INSE_KEY, INSE_URL, _headers + +MULTIPLICATORS_INDEX = "multiplicators_v1" +NETWORKS_INDEX = "multiplicator_networks_v1" +REQUEST_TIMEOUT = 120.0 +BULK_CHUNK = 500 + +MAPPING = { + "properties": { + "institution_id": {"type": "keyword"}, + "cohort_institution_ids": {"type": "keyword"}, + "author_id": {"type": "keyword"}, + "display_name": { + "type": "text", + "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, + }, + "career_bucket": {"type": "keyword"}, + "active_years": {"type": "integer"}, + "n_works": {"type": "integer"}, + "suspicious_profile": {"type": "boolean"}, + "tags": {"type": "keyword"}, + "max_sub_score": {"type": "float"}, + "sub_scores": { + "properties": { + "bridger": {"type": "float"}, + "mentor": {"type": "float"}, + "amplifier": {"type": "float"}, + } + }, + # M3 signal counts + "patent_count": {"type": "integer"}, + "patent_count_name_only": {"type": "integer"}, # evidence only, never scored + "news_mentions": {"type": "integer"}, + "cordis_eu_projects": {"type": "integer"}, + "industry_coauthor_share_shrunk": {"type": "float"}, + # raw metrics + percentiles kept as dynamic float objects (calibration needs them) + "percentiles": {"type": "object", "dynamic": True}, + "evidence": { + "properties": {"junior_ids": {"type": "keyword"}}, + }, + "config_hash": {"type": "keyword"}, + "computed_at": {"type": "date"}, + } +} + +# Visualization docs: nodes/edges live in _source only ("enabled": false — never +# indexed/queried per-field, the frontend GETs whole docs by _id or author filter), +# which keeps the index small despite ~900 edge objects per doc. +NETWORK_MAPPING = { + "properties": { + "institution_id": {"type": "keyword"}, + "cohort_institution_ids": {"type": "keyword"}, + "author_id": {"type": "keyword"}, + "display_name": { + "type": "text", + "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, + }, + "ego": { + "properties": { + "career_bucket": {"type": "keyword"}, + "active_years": {"type": "integer"}, + "n_works": {"type": "integer"}, + "suspicious_profile": {"type": "boolean"}, + "tags": {"type": "keyword"}, + "max_sub_score": {"type": "float"}, + "sub_scores": { + "properties": { + "bridger": {"type": "float"}, + "mentor": {"type": "float"}, + "amplifier": {"type": "float"}, + } + }, + } + }, + "total_coauthors": {"type": "integer"}, + "cohort_coauthors": {"type": "integer"}, + "mentee_count": {"type": "integer"}, + "shown": {"type": "integer"}, + "shown_mentees": {"type": "integer"}, + "nodes": {"type": "object", "enabled": False}, + "edges": {"type": "object", "enabled": False}, + "config_hash": {"type": "keyword"}, + "computed_at": {"type": "date"}, + } +} + + +class MultiplicatorsIndexClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + index: str = MULTIPLICATORS_INDEX, + transport: httpx.BaseTransport | None = None, + ): + self.base_url = (base_url or INSE_URL).rstrip("/") + self.api_key = api_key if api_key is not None else INSE_KEY + self.index = index + self.client = httpx.Client(transport=transport, timeout=REQUEST_TIMEOUT) + if not self.base_url or not self.api_key: + raise SystemExit("Missing INSE cluster credentials (ELASTICSEARCH_INSE_*).") + + def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response: + return self.client.request( + method, + f"{self.base_url}/{path.lstrip('/')}", + headers=_headers(self.api_key), + **kwargs, + ) + + def ensure_mapping(self, mapping: dict[str, Any] | None = None) -> None: + """PUT the explicit mapping (additive; safe on every run). Never creates the index.""" + response = self._request( + "PUT", f"{self.index}/_mapping", json=mapping or MAPPING + ) + if not response.is_success: + raise RuntimeError( + f"Mapping update failed ({response.status_code}): {response.text[:500]}" + ) + + def count_for_institution(self, institution_short_id: str) -> int: + response = self._request( + "POST", + f"{self.index}/_count", + json={"query": {"term": {"institution_id": institution_short_id}}}, + ) + response.raise_for_status() + return response.json()["count"] + + def _wait_for_count(self, institution_short_id: str, expected: int, + timeout_s: float = 30.0) -> int: + """Poll _count until it reaches `expected` or timeout. + + The API key is NOT allowed to call _refresh (indices:admin/refresh -> 403), + so visibility of deletes/writes depends on the index's auto-refresh + (default 1s). Polling is the only verification available to this key.""" + deadline = time.time() + timeout_s + count = -1 + while time.time() < deadline: + count = self.count_for_institution(institution_short_id) + if count == expected: + return count + time.sleep(1.0) + return count + + def _collect_ids_for_institution(self, institution_short_id: str) -> list[str]: + """All doc _ids for the institution, paginated with search_after (collected + BEFORE any deletes, so stale-visibility cannot inflate or loop the delete).""" + ids: list[str] = [] + search_after = None + while True: + body: dict[str, Any] = { + "size": 1000, + "_source": False, + "query": {"term": {"institution_id": institution_short_id}}, + "sort": [{"author_id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + response = self._request("POST", f"{self.index}/_search", json=body) + response.raise_for_status() + hits = response.json()["hits"]["hits"] + if not hits: + break + ids.extend(h["_id"] for h in hits) + search_after = hits[-1]["sort"] + return ids + + def delete_for_institution(self, institution_short_id: str) -> int: + """Collect ids, then bulk-delete-by-id (the key rejects _delete_by_query + with 403). Returns the number of docs actually deleted.""" + ids = self._collect_ids_for_institution(institution_short_id) + deleted = 0 + for start in range(0, len(ids), BULK_CHUNK): + chunk = ids[start : start + BULK_CHUNK] + lines = "".join( + json.dumps({"delete": {"_index": self.index, "_id": doc_id}}) + "\n" + for doc_id in chunk + ) + bulk = self.client.post( + f"{self.base_url}/_bulk", + headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"}, + content=lines, + ) + bulk.raise_for_status() + for item in bulk.json()["items"]: + result = item.get("delete", {}) + if result.get("result") == "deleted": + deleted += 1 + elif result.get("error"): + raise RuntimeError(f"Bulk delete error: {result['error']}") + if ids: + remaining = self._wait_for_count(institution_short_id, 0) + if remaining != 0: + raise RuntimeError( + f"{remaining} docs for {institution_short_id} still visible " + f"after delete (expected 0)" + ) + return deleted + + def index_rows( + self, + institution_short_id: str, + cohort_short_ids: list[str], + scored_rows: list[dict[str, Any]], + ) -> int: + """Delete-then-bulk-index all rows for the institution. Returns docs written.""" + computed_at = datetime.now(timezone.utc).isoformat() + deleted = self.delete_for_institution(institution_short_id) + print(f"Deleted {deleted} existing docs for {institution_short_id}") + + written = 0 + for start in range(0, len(scored_rows), BULK_CHUNK): + chunk = scored_rows[start : start + BULK_CHUNK] + lines = [] + for row in chunk: + doc = { + **row, + "institution_id": institution_short_id, + "cohort_institution_ids": cohort_short_ids, + "computed_at": computed_at, + } + doc_id = f"{institution_short_id}_{row['author_id']}" + lines.append( + json.dumps({"index": {"_index": self.index, "_id": doc_id}}) + ) + lines.append(json.dumps(doc, ensure_ascii=True)) + bulk = self.client.post( + f"{self.base_url}/_bulk", + headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"}, + content="\n".join(lines) + "\n", + ) + bulk.raise_for_status() + result = bulk.json() + if result.get("errors"): + first_error = next( + (i["index"].get("error") for i in result["items"] + if i.get("index", {}).get("error")), + None, + ) + raise RuntimeError(f"Bulk indexing reported errors, first: {first_error}") + written += len(chunk) + visible = self._wait_for_count(institution_short_id, written) + if visible != written: + raise RuntimeError( + f"Post-index count mismatch for {institution_short_id}: " + f"wrote {written}, index shows {visible} after 30s" + ) + return written diff --git a/service/scripts/multipliers/metrics.py b/service/scripts/multipliers/metrics.py new file mode 100644 index 00000000..ac3ce51a --- /dev/null +++ b/service/scripts/multipliers/metrics.py @@ -0,0 +1,341 @@ +#!/usr/bin/env python3 +""" +metrics.py — bridger / mentor metrics for multiplicator detection (M1, Stage D). + +All functions are pure computations over the structures produced by graph.py. + +Career-age foundation (see analysis/career_stage/README.md): first_publication_year is +UNRELIABLE at UDE (merged OpenAlex profiles -> debut years like 1893), so nothing here +uses it. The robust primitive is the prefix-counted active-year count + + active_years_at(A, Y) = |{ y in distinct_publication_years(A) : y <= Y }| + +which a single misattributed old work moves by exactly 1. It inherits the empirically +validated career-stage thresholds from inse/persons/logic.py unchanged. + +Mentor metrics are computed over FOCAL (institution-internal) pairs only: the extract +contains the complete global history of focal authors, so their year-sets are exact, +while external co-authors' year-sets are truncated to shared works (an external senior +would look junior). This scope restriction is a data-correctness requirement, not a +modelling choice. +""" +from __future__ import annotations + +import heapq +import math +from dataclasses import dataclass, field + +from graph import EdgeStats, Graph, adjacency, focal_subgraph + + +def incident_edges(graph: Graph) -> dict[str, list[tuple[str, EdgeStats]]]: + """One pass over the edge dict -> per-author incident edge lists. + + Every per-author metric must use this instead of scanning graph.edges — + a full-edge scan per focal author is O(E * authors) and does not finish.""" + incident: dict[str, list[tuple[str, EdgeStats]]] = {} + for (a, b), e in graph.edges.items(): + incident.setdefault(a, []).append((b, e)) + incident.setdefault(b, []).append((a, e)) + return incident + + +# --------------------------------------------------------------------- +# Career primitives +# --------------------------------------------------------------------- + + +def active_years_at(publication_years: set[int], year: int) -> int: + """Distinct publication years up to and including `year` (robust seniority).""" + return sum(1 for y in publication_years if y <= year) + + +def is_suspicious_profile(publication_years: set[int]) -> bool: + """Merged-profile flag, same rule as inse/persons/logic.py.""" + if not publication_years: + return False + first = min(publication_years) + span = max(publication_years) - first + 1 + return first < 1970 or span > 60 + + +# --------------------------------------------------------------------- +# Betweenness — Brandes (2001), weighted variant with Dijkstra. +# Weights are collaboration STRENGTHS; shortest paths need DISTANCES, so we +# pass 1/weight (strong ties = short distances). Pure stdlib. +# --------------------------------------------------------------------- + + +def betweenness_centrality( + adj: dict[str, dict[str, float]], normalized: bool = True +) -> dict[str, float]: + nodes = list(adj.keys()) + bc = {v: 0.0 for v in nodes} + + for s in nodes: + # single-source shortest paths (Dijkstra on 1/weight distances). + # All per-source state is lazy (touched nodes only) — a per-source init + # over all V nodes would make the whole thing O(V^2) before any work. + dist: dict[str, float] = {s: 0.0} + sigma: dict[str, float] = {s: 1.0} + preds: dict[str, list[str]] = {} + done: set[str] = set() + order: list[str] = [] + heap: list[tuple[float, str]] = [(0.0, s)] + while heap: + d, v = heapq.heappop(heap) + if v in done: + continue + done.add(v) + order.append(v) + sigma_v = sigma[v] + for u, w in adj[v].items(): + if w <= 0: + continue + nd = d + 1.0 / w + old = dist.get(u) + if old is None or nd < old - 1e-12: + dist[u] = nd + sigma[u] = sigma_v + preds[u] = [v] + heapq.heappush(heap, (nd, u)) + elif abs(nd - old) <= 1e-12 and u not in done: + sigma[u] += sigma_v + preds.setdefault(u, []).append(v) + # accumulation, reverse order of discovery + delta: dict[str, float] = {} + for v in reversed(order): + dv = delta.get(v, 0.0) + coeff = (1.0 + dv) / sigma[v] + for p in preds.get(v, ()): + delta[p] = delta.get(p, 0.0) + sigma[p] * coeff + if v != s: + bc[v] += dv + + # undirected: each pair counted twice + for v in bc: + bc[v] /= 2.0 + if normalized and len(nodes) > 2: + scale = 1.0 / ((len(nodes) - 1) * (len(nodes) - 2) / 2.0) + for v in bc: + bc[v] *= scale + return bc + + +# --------------------------------------------------------------------- +# Burt's constraint — low constraint == structural-hole spanner (bridger). +# Computed on the FULL graph (external co-authors included): someone whose +# UDE-internal network is dense but who alone connects to industry/abroad +# is a bridger that internal betweenness cannot see. +# --------------------------------------------------------------------- + + +def burt_constraint( + adj: dict[str, dict[str, float]], nodes: list[str] | None = None +) -> dict[str, float]: + """Constraint c_i = sum_j (p_ij + sum_q p_iq * p_qj)^2 over neighbours j of i. + + p_ij = w_ij / sum_k w_ik. Isolates get constraint 1.0 (fully constrained). + """ + # strength totals once — recomputing sum(neigh.values()) inside the O(d^2) + # inner loop makes this O(d^3) and unusable on hub nodes + totals = {v: sum(neigh.values()) for v, neigh in adj.items()} + + result: dict[str, float] = {} + targets = nodes if nodes is not None else list(adj.keys()) + for i in targets: + neigh = adj.get(i) or {} + total = totals.get(i, 0.0) + if total <= 0: + result[i] = 1.0 + continue + p_i = {j: w / total for j, w in neigh.items()} + c = 0.0 + for j, p_ij in p_i.items(): + indirect = 0.0 + for q, p_iq in p_i.items(): + if q == j: + continue + q_neigh = adj.get(q) + if not q_neigh: + continue + w_qj = q_neigh.get(j) + if w_qj: + indirect += p_iq * (w_qj / totals[q]) + c += (p_ij + indirect) ** 2 + result[i] = c + return result + + +# --------------------------------------------------------------------- +# Simple per-node shares +# --------------------------------------------------------------------- + + +def field_entropy(field_counts: dict[str, int]) -> float: + """Shannon entropy (bits) over primary_topic.field of an author's works.""" + total = sum(field_counts.values()) + if total <= 0: + return 0.0 + ent = 0.0 + for c in field_counts.values(): + if c > 0: + p = c / total + ent -= p * math.log2(p) + return ent + + +def cross_institution_share( + graph: Graph, + author_id: str, + incident: dict[str, list[tuple[str, EdgeStats]]] | None = None, +) -> float: + """Share of an author's edge weight where the pair shared no institution.""" + if incident is None: + incident = incident_edges(graph) + total = 0.0 + cross = 0.0 + for _, e in incident.get(author_id, ()): + total += e.weight + cross += e.cross_inst_weight + return cross / total if total > 0 else 0.0 + + +# --------------------------------------------------------------------- +# Mentor metrics — debut-year-free (see module docstring) +# --------------------------------------------------------------------- + + +@dataclass +class MentorMetrics: + juniors_mentored: int = 0 + junior_progression_rate: float | None = None # None if no juniors + last_author_with_junior_first: int = 0 + mentoring_rate: float = 0.0 + junior_ids: list[str] = field(default_factory=list) # evidence + + +def mentor_metrics( + graph: Graph, + focal_author_id: str, + junior_active_years_max: int = 4, + senior_active_years_min: int = 10, + progressed_active_years_min: int = 5, + incident: dict[str, list[tuple[str, EdgeStats]]] | None = None, +) -> MentorMetrics: + """Seniority-gap mentorship over focal-internal pairs. + + A co-author J counts as "mentored" when, at the year Y of the FIRST joint work: + active_years_at(J, Y) <= junior_active_years_max (J was Early-career) + active_years_at(focal, Y) >= senior_active_years_min (focal was Established+) + Progression: J later reached >= progressed_active_years_min total active years. + """ + focal_node = graph.nodes.get(focal_author_id) + if focal_node is None: + return MentorMetrics() + if incident is None: + incident = incident_edges(graph) + + juniors: list[str] = [] + progressed = 0 + for other, e in incident.get(focal_author_id, ()): + if e.first_joint_year is None: + continue + other_node = graph.nodes.get(other) + if other_node is None or not other_node.is_focal or not focal_node.is_focal: + continue # internal pairs only — external year-sets are truncated + y = e.first_joint_year + if ( + active_years_at(other_node.publication_years, y) <= junior_active_years_max + and active_years_at(focal_node.publication_years, y) >= senior_active_years_min + ): + juniors.append(other) + if len(other_node.publication_years) >= progressed_active_years_min: + progressed += 1 + + # supervision signature: focal last author, junior (at that work's year) first author + last_author_junior_first = 0 + for first_author, year in focal_node.last_author_junior_first: + fa_node = graph.nodes.get(first_author) + if fa_node is None or not fa_node.is_focal: + continue + if active_years_at(fa_node.publication_years, year) <= junior_active_years_max: + last_author_junior_first += 1 + + total_active = len(focal_node.publication_years) + return MentorMetrics( + juniors_mentored=len(juniors), + junior_progression_rate=(progressed / len(juniors)) if juniors else None, + last_author_with_junior_first=last_author_junior_first, + mentoring_rate=(len(juniors) / total_active) if total_active else 0.0, + junior_ids=juniors, + ) + + +# --------------------------------------------------------------------- +# Orchestration: all raw metrics for every focal author +# --------------------------------------------------------------------- + + +def compute_all_metrics( + graph: Graph, + junior_active_years_max: int = 4, + senior_active_years_min: int = 10, + progressed_active_years_min: int = 5, + industry_share_shrinkage_k: int = 5, +) -> dict[str, dict]: + """Raw (un-normalized) metric rows keyed by focal author id.""" + internal = focal_subgraph(graph) + full_adj = adjacency(graph) + incident = incident_edges(graph) + focal_ids = [aid for aid, n in graph.nodes.items() if n.is_focal] + + bc = betweenness_centrality(internal) if internal else {} + constraint = burt_constraint(full_adj, nodes=[a for a in focal_ids if a in full_adj]) + + rows: dict[str, dict] = {} + for aid in focal_ids: + node = graph.nodes[aid] + mm = mentor_metrics( + graph, + aid, + junior_active_years_max=junior_active_years_max, + senior_active_years_min=senior_active_years_min, + progressed_active_years_min=progressed_active_years_min, + incident=incident, + ) + strength = sum(full_adj.get(aid, {}).values()) + rows[aid] = { + "author_id": aid, + "display_name": node.display_name, + "active_years": len(node.publication_years), + "n_works": node.n_works, + "suspicious_profile": is_suspicious_profile(node.publication_years), + # bridger + "betweenness": bc.get(aid, 0.0), + "constraint": constraint.get(aid, 1.0), + "brokerage": 1.0 - constraint.get(aid, 1.0), # higher = more bridging + "field_entropy": field_entropy(node.field_counts), + "cross_institution_share": cross_institution_share(graph, aid, incident), + "strength": strength, + "n_coauthors": len(full_adj.get(aid, {})), + # amplifier inputs available from OpenAlex alone + "industry_coauthor_share": ( + node.n_company_works / node.n_typed_works if node.n_typed_works else 0.0 + ), + # shrunk variant for SCORING: n_company/(n_typed+k) damps the small- + # denominator artifact where 2-of-2 company works outranks 40-of-80 — + # the live index's top "amplifiers" were exactly such ratio artifacts + "industry_coauthor_share_shrunk": ( + node.n_company_works / (node.n_typed_works + industry_share_shrinkage_k) + if node.n_typed_works + else 0.0 + ), + # mentor + "juniors_mentored": mm.juniors_mentored, + "junior_progression_rate": mm.junior_progression_rate, + "last_author_with_junior_first": mm.last_author_with_junior_first, + "mentoring_rate": mm.mentoring_rate, + "junior_ids": mm.junior_ids, + } + return rows diff --git a/service/scripts/multipliers/multipliers.yaml b/service/scripts/multipliers/multipliers.yaml new file mode 100644 index 00000000..6d26a316 --- /dev/null +++ b/service/scripts/multipliers/multipliers.yaml @@ -0,0 +1,110 @@ +# Multiplicator detection — all tunables live here. +# Coaches will retune weights/thresholds; every output doc carries a config_hash +# of this file so scores stay attributable to the weighting that produced them. + +version: 2 + +# --------------------------------------------------------------------------- +# Cohorts — which OpenAlex institutions constitute "the university". +# +# Keyed by the primary institution ID passed as --institution-id. If a cohort +# entry exists, the author set is extracted over ALL listed IDs; otherwise the +# primary ID alone is used. Needed because OpenAlex does NOT model university +# hospitals as lineage children: Essen University Hospital is only "related" +# to UDE, which silently excluded ~2,437 active clinicians (incl. prominent +# medicine professors) from the cohort — found via the M1 validation, where +# 17/60 hand-labeled people were missing. +# +# Source of candidates: openalex-institutions `associated_institutions` of the +# primary ID (children + related), one hop deep. Every inclusion/exclusion is +# a human judgment call — document the reason next to each entry. +# --------------------------------------------------------------------------- +cohorts: + I62318514: + name: University of Duisburg-Essen + institution_ids: + - I62318514 # UDE itself (primary) + - I4210119759 # Essen University Hospital — the university medical centre; + # "related" in OpenAlex, NOT lineage, hence the coverage gap + - I4210161917 # West German Heart and Vascular Center Essen — child of the hospital + - I127668822 # Erwin L. Hahn Institute for MRI — joint UDE institute, + # isolated in OpenAlex (no lineage/associated links at all) + - I4210090139 # Rhein-Ruhr Institut für Sozialforschung (child of UDE) + - I4210092428 # Deutsches Textilforschungszentrum Nord-West (child of UDE) + - I4210110714 # Institute for Advanced Study in the Humanities Essen / KWI (child) + - I4210146441 # The Hydrogen and Fuel Cell Center / ZBT (child of UDE) + - I4210154243 # Institut für Energie- und Umwelttechnik / IUTA (child of UDE) + # Deliberately EXCLUDED (decide with the coaches before enabling): + # - I4210146447 Kliniken Essen-Mitte — independent hospital group, only + # "related"; staff are not UDE researchers (~788 authors) + # - I2799342142 Salomon Ludwig Steinheim-Institut — independent An-Institut + # - I4210124583 IWW Water Centre — independent An-Institut + +extraction: + # "Recent affiliation" cutoff for the author set. 2023 (not the current year): + # publication lag pushes current staff out of a 1-year window — the M1 validation + # found 6 current-ish people (incl. an active professor) with newest affiliation + # year 2021-2024. 2023 captures normal lag while still excluding long-departed. + affiliation_years_gte: 2023 + work_year_gte: 1950 + # Chosen from the M0 spike (authors/work p50=5, p90=17, p99=144, max=4839): + # cap 50 keeps >=99% of works and excludes only true hyperauthorship, which + # carries no collaboration signal but would create giant artificial cliques. + max_authors_per_work: 50 + +graph: + decay: 0.8 # per-year edge weight decay (ref = newest corpus year) + +career: + # active_years bucket thresholds — mirror inse/persons/logic.py _classify_career_stage. + # Buckets: Early <= 4, Emerging <= 9, Established <= 14, Senior > 14. + buckets: [4, 9, 14] + bucket_names: [Early, Emerging, Established, Senior] + +mentor: + junior_active_years_max: 4 # junior == Early-career at first joint work + senior_active_years_min: 10 # focal must be Established+ at first joint work + progressed_active_years_min: 5 + +signals: + # org_patents match_types that count toward the score; "name"-only matches are + # carried as evidence (patent_count_name_only) but never scored. + patent_match_types: [institution, both] + news_require_relevant: true # only aktuell_postproc docs the LLM marked relevant + # Shrinkage constant for industry_coauthor_share_shrunk = company/(typed+k): + # damps small denominators (2-of-2 works with a company co-author is not a + # stronger industry signal than 40-of-80). Found via the live-index audit, + # where all top-10 "amplifiers" were such ratio artifacts. + industry_share_shrinkage_k: 5 + +network: + # Per-author ego-network docs for the visualization frontend + # (index multiplicator_networks_v1). Nodes shown = strongest co-authors by tie + # weight, with mentees force-included first — their decayed, team-size-divided + # ties otherwise never make the cut (a 100-mentee professor had ZERO mentees + # in his unforced top 42). + max_nodes: 42 + max_forced_mentees: 14 + +# Sub-score weights over WITHIN-BUCKET percentiles of the raw metrics. +# Weights within each sub-score should sum to 1. +weights: + bridger: + betweenness: 0.35 + brokerage: 0.25 # 1 - Burt constraint, full graph incl. externals + field_entropy: 0.20 + cross_institution_share: 0.20 + mentor: + juniors_mentored: 0.35 + mentoring_rate: 0.25 + last_author_with_junior_first: 0.25 + junior_progression_rate: 0.15 + amplifier: + industry_coauthor_share_shrunk: 0.50 # primary: ID-linked company co-authorship, shrunk + patent_count: 0.25 # high-confidence org_patents (institution/both) + cordis_eu_projects: 0.15 # DOI-join, no name matching + news_mentions: 0.10 # normalized-exact name match — lossy; keep low + +tags: + threshold: 0.85 # tag fires when sub-score >= threshold (multiple allowed) + min_active_years: 2 # never tag someone with <2 active years (no history) diff --git a/service/scripts/multipliers/networks.py b/service/scripts/multipliers/networks.py new file mode 100644 index 00000000..582f1f09 --- /dev/null +++ b/service/scripts/multipliers/networks.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +""" +networks.py — materialize per-author ego-network documents for visualization. + +The scores index answers "what did this person score"; the network index answers +"who are they connected to and how" — the data a frontend needs to draw the +ego-network figures (force layout, role colors, tooltips). The neighbor-neighbor +edges that make graph shape readable (dense mesh = one community, spokes with gaps += brokered structural holes) come from works that do NOT include the ego, so they +can only be materialized here, while the full graph is in memory — no request-time +query can reconstruct them. + +Doc shape (one per focal author, _id = _): + + nodes[] {id, name, role, inst, active_years, suspicious} + role: ego | mentee | cohort | industry | external + edges[] {a, b, w, n_works, cross, first_year, last_year} + w = decayed collaboration strength; cross = mostly cross-institution + ego{} small header duplicate (bucket, tags, sub_scores) so the network + endpoint can render standalone + totals total_coauthors, cohort_coauthors, shown + +Node selection: the ego's strongest `max_nodes` co-authors by tie weight, with up +to `max_forced_mentees` mentees force-included first — mentees' ties are decayed +and team-size-divided, so a pure top-by-weight cut hides exactly the people the +mentor score is about (empirically: a 100-mentee professor had zero mentees in his +unforced top 42). Positions are NOT stored — the frontend's force layout +(e.g. echarts `graph` series) lays out at render time. +""" +from __future__ import annotations + +from typing import Any + +from graph import Graph +from metrics import is_suspicious_profile + + +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_authors: 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. + """ + 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)] + idset = set(selected) + + nodes = [] + for nid in selected: + node = graph.nodes[nid] + if nid == ego_id: + role = "ego" + elif nid in mentees: + role = "mentee" + elif nid in company_authors and not node.is_focal: + role = "industry" + elif node.is_focal: + role = "cohort" + else: + role = "external" + nodes.append( + { + "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), + } + ) + + # all corpus edges among the selected nodes — 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 diff --git a/service/scripts/multipliers/requirements.txt b/service/scripts/multipliers/requirements.txt new file mode 100644 index 00000000..65ebba8a --- /dev/null +++ b/service/scripts/multipliers/requirements.txt @@ -0,0 +1,7 @@ +httpx>=0.27 +python-dotenv>=1.0 +polars>=1.0 +pyyaml>=6.0 + +# test-only (never in the service image): +# pip install pytest networkx diff --git a/service/scripts/multipliers/scoring.py b/service/scripts/multipliers/scoring.py new file mode 100644 index 00000000..aa50af22 --- /dev/null +++ b/service/scripts/multipliers/scoring.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +""" +scoring.py — normalization, sub-scores and tags (M1, Stage F). + +Procedure (per plan §3/§6): + 1. Bucket every focal author by career stage from `active_years` + (Early/Emerging/Established/Senior — thresholds mirror inse/persons/logic.py). + 2. Percentile-rank every raw metric WITHIN its bucket, so early-career people + compete against early-career people. The M0 spike found median active_years = 4: + half the cohort is "Early", and institution-wide percentiles would simply rank + seniority. + 3. Sub-scores = weighted mean of the percentiles (weights from multiplicators.yaml). + 4. Tag anyone >= tags.threshold on a sub-score (multiple tags allowed). + +Raw values, percentiles, and sub-scores are ALL persisted — coaches and calibration +both need the intermediates. None/NaN raw values are excluded from percentile ranking +and contribute 0 to the weighted mean (weight is redistributed over present metrics). +""" +from __future__ import annotations + +import hashlib +import json +from typing import Any + +import yaml + + +def load_config(path: str) -> dict[str, Any]: + with open(path, "r", encoding="utf-8") as f: + config = yaml.safe_load(f) + config["_config_hash"] = hashlib.sha256( + json.dumps(config, sort_keys=True, default=str).encode() + ).hexdigest()[:12] + return config + + +def career_bucket(active_years: int, thresholds: list[int], names: list[str]) -> str: + """Bucket by active_years. thresholds=[4,9,14] -> Early/Emerging/Established/Senior.""" + for threshold, name in zip(thresholds, names): + if active_years <= threshold: + return name + return names[len(thresholds)] + + +def percentile_ranks(values: dict[str, float | None]) -> dict[str, float]: + """Mean-rank percentiles in (0, 1] over the non-None values. + + Ties share their mean rank, so a metric where most values are 0 (e.g. + juniors_mentored for Early authors) does not hand everyone a high percentile. + """ + present = [(aid, v) for aid, v in values.items() if v is not None] + if not present: + return {} + present.sort(key=lambda kv: kv[1]) + n = len(present) + ranks: dict[str, float] = {} + i = 0 + while i < n: + j = i + while j + 1 < n and present[j + 1][1] == present[i][1]: + j += 1 + mean_rank = (i + j) / 2 + 1 # 1-based mean rank of the tie group + for k in range(i, j + 1): + ranks[present[k][0]] = mean_rank / n + i = j + 1 + return ranks + + +def score_rows( + metric_rows: dict[str, dict[str, Any]], config: dict[str, Any] +) -> list[dict[str, Any]]: + """Turn raw metric rows into scored, tagged, bucket-normalized output rows.""" + career_cfg = config["career"] + weights: dict[str, dict[str, float]] = config["weights"] + tag_threshold: float = config["tags"]["threshold"] + min_active_years: int = config["tags"].get("min_active_years", 0) + + # 1. bucket assignment + buckets: dict[str, list[str]] = {} + for aid, row in metric_rows.items(): + bucket = career_bucket( + row["active_years"], career_cfg["buckets"], career_cfg["bucket_names"] + ) + row["career_bucket"] = bucket + buckets.setdefault(bucket, []).append(aid) + + # 2. within-bucket percentiles for every metric used by any sub-score + metric_names = sorted({m for w in weights.values() for m in w}) + percentiles: dict[str, dict[str, float]] = {aid: {} for aid in metric_rows} + for bucket_members in buckets.values(): + for metric in metric_names: + values = { + aid: metric_rows[aid].get(metric) + for aid in bucket_members + if isinstance(metric_rows[aid].get(metric), (int, float)) + } + for aid, pctl in percentile_ranks(values).items(): + percentiles[aid][metric] = pctl + + # 3+4. weighted sub-scores and tags + out: list[dict[str, Any]] = [] + for aid, row in metric_rows.items(): + sub_scores: dict[str, float] = {} + for sub, metric_weights in weights.items(): + total_weight = 0.0 + acc = 0.0 + for metric, weight in metric_weights.items(): + pctl = percentiles[aid].get(metric) + if pctl is not None: + acc += weight * pctl + total_weight += weight + sub_scores[sub] = round(acc / total_weight, 4) if total_weight > 0 else 0.0 + + tags = ( + [s for s, v in sub_scores.items() if v >= tag_threshold] + if row["active_years"] >= min_active_years + else [] + ) + + out.append( + { + **{k: v for k, v in row.items() if k != "junior_ids"}, + "percentiles": { + m: round(p, 4) for m, p in percentiles[aid].items() + }, + "sub_scores": sub_scores, + "tags": tags, + "max_sub_score": max(sub_scores.values()) if sub_scores else 0.0, + "evidence": {"junior_ids": row.get("junior_ids", [])[:25]}, + "config_hash": config["_config_hash"], + } + ) + + out.sort(key=lambda r: r["max_sub_score"], reverse=True) + return out diff --git a/service/scripts/multipliers/signals.py b/service/scripts/multipliers/signals.py new file mode 100644 index 00000000..278042de --- /dev/null +++ b/service/scripts/multipliers/signals.py @@ -0,0 +1,232 @@ +#!/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, + } diff --git a/service/scripts/multipliers/spike_audit.py b/service/scripts/multipliers/spike_audit.py new file mode 100644 index 00000000..93a58f4a --- /dev/null +++ b/service/scripts/multipliers/spike_audit.py @@ -0,0 +1,656 @@ +#!/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 that +answers the six questions the rest of the pipeline is betting on: + + 1. Reproduction — author / work counts vs the known 4,921 / 183,661 for UDE. + 2. Field coverage — % of authorships with author_position / is_corresponding, and + % of institutions with a non-null `type`. Decides whether the + mentorship (last-author) and cross-sector signals are computable. + 3. Scale — authors-per-work histogram and distinct co-author pair counts at + caps of 20 / 50 / 100. Picks max_authors_per_work; confirms the + "pure Python / polars, no DuckDB" sizing bet. + 4. Quality — % of authors flagged has_suspicious_publication_years (merged + profiles) and the active_years distribution. + 5. Permissions — can we create / bulk-write / delete on the INSE cluster, and does + _delete_by_query 403 there as it does for org_patents? + 6. Signals — does org_patents carry matched_authors for this institution, and + what is the match_type breakdown? + +Unlike the seed (llm_evaluations/.../build_ude_author_work_set.py) this drops inner_hits +and pulls every authorship (external co-authors + their institutions) — without that +there is no bridging signal. + +Usage: + python service/scripts/multipliers/spike_audit.py --institution-id I62318514 + +Credentials are read from service/src/main/inse/.env (ELASTICSEARCH_* for the NES/OpenAlex +cluster, ELASTICSEARCH_INSE_* for patents/news). 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 (parameterised — no hardcoded UDE) +# --------------------------------------------------------------------- + + +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. + + (The seed script matched the display_name string; ID terms are equivalent for a + single institution and the only sane option for a multi-institution cohort.)""" + 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..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() diff --git a/service/scripts/multipliers/tests/test_graph.py b/service/scripts/multipliers/tests/test_graph.py new file mode 100644 index 00000000..e8468677 --- /dev/null +++ b/service/scripts/multipliers/tests/test_graph.py @@ -0,0 +1,130 @@ +"""Tests for graph construction (pair generation, weights, caps, node aggregates).""" +from __future__ import annotations + +import pytest + +from graph import build_graph, focal_subgraph, short_id + + +def make_work(wid, year, authors, field_id=None): + """authors: list of (author_id, institutions[(id,type)], position).""" + return { + "id": f"https://openalex.org/{wid}", + "publication_year": year, + "primary_topic": ( + {"field": {"id": f"https://openalex.org/fields/{field_id}"}} + if field_id + else None + ), + "authorships": [ + { + "author": {"id": f"https://openalex.org/{aid}", "display_name": aid}, + "author_position": pos, + "institutions": [ + {"id": f"https://openalex.org/{iid}", "type": itype} + for iid, itype in insts + ], + } + for aid, insts, pos in authors + ], + } + + +UDE = [("I1", "education")] +COMPANY = [("I9", "company")] + + +def test_short_id(): + assert short_id("https://openalex.org/A5023888391") == "A5023888391" + assert short_id("A5023888391") == "A5023888391" + assert short_id(None) is None + + +def test_edge_weight_decay_and_team_size(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("A2", UDE, "last")]), + make_work("W2", 2025, [("A1", UDE, "first"), ("A2", UDE, "last")]), + ] + g = build_graph(works, {"A1", "A2"}, decay=0.8) + assert g.ref_year == 2026 + e = g.edges[("A1", "A2")] + # W1: 0.8^0 / 1 = 1.0 ; W2: 0.8^1 / 1 = 0.8 + assert e.weight == pytest.approx(1.8) + assert e.n_works == 2 + assert e.first_joint_year == 2025 + assert e.last_joint_year == 2026 + + +def test_team_size_divides_weight(): + works = [ + make_work( + "W1", 2026, + [("A1", UDE, "first"), ("A2", UDE, "middle"), ("A3", UDE, "last")], + ) + ] + g = build_graph(works, {"A1", "A2", "A3"}) + # n_authors=3 -> each pair gets 1/(3-1) = 0.5 + assert g.edges[("A1", "A2")].weight == pytest.approx(0.5) + assert len(g.edges) == 3 + + +def test_hyperauthorship_cap_excludes_pairs_but_keeps_years(): + big = make_work( + "W1", 2020, [(f"A{i}", UDE, "middle") for i in range(1, 61)] + ) + small = make_work("W2", 2021, [("A1", UDE, "first"), ("A2", UDE, "last")]) + g = build_graph([big, small], {"A1", "A2"}, max_authors_per_work=50) + assert g.n_works_capped == 1 + assert g.n_works_used == 1 + assert set(g.edges) == {("A1", "A2")} + # capped work still contributes publication years + assert 2020 in g.nodes["A1"].publication_years + assert 2021 in g.nodes["A1"].publication_years + + +def test_cross_institution_weight(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("A2", COMPANY, "last")]), + make_work("W2", 2026, [("A1", UDE, "first"), ("A3", UDE, "last")]), + ] + g = build_graph(works, {"A1", "A2", "A3"}) + assert g.edges[("A1", "A2")].cross_inst_weight == pytest.approx(1.0) + assert g.edges[("A1", "A3")].cross_inst_weight == pytest.approx(0.0) + + +def test_company_share_and_fields(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("A2", COMPANY, "last")], "F11"), + make_work("W2", 2026, [("A1", UDE, "first"), ("A3", UDE, "last")], "F22"), + ] + g = build_graph(works, {"A1"}) + n = g.nodes["A1"] + assert n.n_company_works == 1 and n.n_typed_works == 2 + assert n.field_counts == {"F11": 1, "F22": 1} + + +def test_focal_subgraph_excludes_externals(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("EXT", COMPANY, "last")]), + make_work("W2", 2026, [("A1", UDE, "first"), ("A2", UDE, "last")]), + ] + g = build_graph(works, {"A1", "A2"}) + internal = focal_subgraph(g) + assert "EXT" not in internal + assert set(internal["A1"].keys()) == {"A2"} + + +def test_last_author_junior_first_recorded(): + works = [ + make_work("W1", 2026, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")]), + ] + g = build_graph(works, {"JUNIOR", "PROF"}) + assert g.nodes["PROF"].last_author_junior_first == [("JUNIOR", 2026)] + assert g.nodes["JUNIOR"].last_author_junior_first == [] + + +def test_duplicate_authorships_deduped(): + w = make_work("W1", 2026, [("A1", UDE, "first"), ("A1", UDE, "last"), ("A2", UDE, "middle")]) + g = build_graph([w], {"A1", "A2"}) + # A1 duplicated -> counts once; n_authors=2 -> weight divisor 1 + assert g.edges[("A1", "A2")].weight == pytest.approx(1.0) diff --git a/service/scripts/multipliers/tests/test_metrics.py b/service/scripts/multipliers/tests/test_metrics.py new file mode 100644 index 00000000..6d13ea63 --- /dev/null +++ b/service/scripts/multipliers/tests/test_metrics.py @@ -0,0 +1,231 @@ +"""Tests for metrics: betweenness vs networkx oracle, constraint on a star, +active_years_at robustness (the planted-1893-outlier regression guard), mentor logic.""" +from __future__ import annotations + +import pytest + +from graph import build_graph +from metrics import ( + active_years_at, + betweenness_centrality, + burt_constraint, + compute_all_metrics, + field_entropy, + is_suspicious_profile, + mentor_metrics, +) +from test_graph import UDE, make_work + +networkx = pytest.importorskip("networkx") + + +# --------------------------------------------------------------------- +# active_years_at — THE regression guard for the whole design premise +# --------------------------------------------------------------------- + + +def test_active_years_at_unmoved_by_planted_1893_outlier(): + """A single misattributed 1893 work must shift active_years_at by exactly 1, + unlike first_pub_year-based career age, which it would shift by ~120 years.""" + clean = set(range(2010, 2026)) # 16 active years + poisoned = clean | {1893} # merged-profile artifact + + assert active_years_at(clean, 2025) == 16 + assert active_years_at(poisoned, 2025) == 17 # +1, not +120 + # seniority classification at the time of an early collaboration is unaffected + assert active_years_at(clean, 2013) == 4 # still "Early" in 2013 + assert active_years_at(poisoned, 2013) == 5 # off by exactly one year + + # the poisoned profile IS flagged for evidence confidence + assert not is_suspicious_profile(clean) + assert is_suspicious_profile(poisoned) + + +# --------------------------------------------------------------------- +# betweenness — barbell fixture + networkx oracle +# --------------------------------------------------------------------- + + +def _nx_graph(adj): + g = networkx.Graph() + for a, neigh in adj.items(): + g.add_node(a) + for b, w in neigh.items(): + g.add_edge(a, b, weight=w, distance=1.0 / w) + return g + + +def test_betweenness_barbell_bridge_dominates(): + """Two triangles joined by one bridge node: the bridge has max betweenness.""" + adj = {} + + def add(a, b, w=1.0): + adj.setdefault(a, {})[b] = w + adj.setdefault(b, {})[a] = w + + for x, y in [("A", "B"), ("B", "C"), ("A", "C")]: + add(x, y) + for x, y in [("D", "E"), ("E", "F"), ("D", "F")]: + add(x, y) + add("C", "M") + add("M", "D") + + bc = betweenness_centrality(adj) + assert bc["M"] == max(bc.values()) + assert bc["A"] == pytest.approx(0.0) + + oracle = networkx.betweenness_centrality( + _nx_graph(adj), weight="distance", normalized=True + ) + for node, value in bc.items(): + assert value == pytest.approx(oracle[node], abs=1e-9), node + + +def test_betweenness_weighted_paths_vs_oracle(): + """Weighted graph where the shortest path is NOT the fewest-hops path.""" + adj = {} + + def add(a, b, w): + adj.setdefault(a, {})[b] = w + adj.setdefault(b, {})[a] = w + + # strong two-hop route A-X-B (distance 0.2+0.2) beats direct weak A-B (distance 2) + add("A", "B", 0.5) + add("A", "X", 5.0) + add("X", "B", 5.0) + add("B", "C", 1.0) + + bc = betweenness_centrality(adj) + oracle = networkx.betweenness_centrality( + _nx_graph(adj), weight="distance", normalized=True + ) + for node, value in bc.items(): + assert value == pytest.approx(oracle[node], abs=1e-9), node + assert bc["X"] > 0.0 # X sits on the A->B shortest path + + +def test_betweenness_random_graph_vs_oracle(): + """Randomized (but seeded) graph, full oracle comparison.""" + rng = networkx.gnm_random_graph(24, 60, seed=7) + adj = {} + for a, b in rng.edges(): + w = ((a * 31 + b * 17) % 9 + 1) / 3.0 # deterministic pseudo-weights + adj.setdefault(str(a), {})[str(b)] = w + adj.setdefault(str(b), {})[str(a)] = w + for n in rng.nodes(): + adj.setdefault(str(n), {}) + + bc = betweenness_centrality(adj) + oracle = networkx.betweenness_centrality( + _nx_graph(adj), weight="distance", normalized=True + ) + for node, value in bc.items(): + assert value == pytest.approx(oracle[node], abs=1e-7), node + + +# --------------------------------------------------------------------- +# Burt constraint — star fixture +# --------------------------------------------------------------------- + + +def test_constraint_star_center_is_unconstrained(): + """Star: the hub bridges structural holes (low constraint); each spoke is + fully dependent on the hub (constraint 1.0). Clique members sit in between.""" + star = {} + for spoke in ["S1", "S2", "S3", "S4"]: + star.setdefault("HUB", {})[spoke] = 1.0 + star[spoke] = {"HUB": 1.0} + c = burt_constraint(star) + assert c["HUB"] == pytest.approx(0.25) # sum of (1/4)^2 * 4 + for spoke in ["S1", "S2", "S3", "S4"]: + assert c[spoke] == pytest.approx(1.0) + + triangle = { + "A": {"B": 1.0, "C": 1.0}, + "B": {"A": 1.0, "C": 1.0}, + "C": {"A": 1.0, "B": 1.0}, + } + c3 = burt_constraint(triangle) + # closed triad: everyone highly constrained, more than the star hub + assert c3["A"] > c["HUB"] + oracle = networkx.constraint(_nx_graph(triangle), weight="weight") + assert c3["A"] == pytest.approx(oracle["A"], abs=1e-9) + + +def test_field_entropy(): + assert field_entropy({}) == 0.0 + assert field_entropy({"F1": 10}) == 0.0 + assert field_entropy({"F1": 5, "F2": 5}) == pytest.approx(1.0) + assert field_entropy({"F1": 1, "F2": 1, "F3": 1, "F4": 1}) == pytest.approx(2.0) + + +# --------------------------------------------------------------------- +# Mentor metrics +# --------------------------------------------------------------------- + + +def _career(aid, years, wid_prefix): + """Solo-ish works giving `aid` a publication history (paired with a throwaway + co-author so the works survive the n_authors >= 2 filter).""" + return [ + make_work(f"{wid_prefix}{y}", y, [(aid, UDE, "first"), (f"X_{aid}_{y}", [], "last")]) + for y in years + ] + + +def test_mentor_seniority_gap_and_progression(): + works = [] + # PROF: established since 2000 (>=10 active years by 2015) + works += _career("PROF", range(2000, 2026), "P") + # JUNIOR: first-ever activity 2015 (active_years_at(2015)=1), then progresses + works += [ + make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")]), + ] + works += _career("JUNIOR", range(2016, 2022), "J") # 6 more years -> progressed + # PEER: senior colleague, first joint work 2020 when both are senior + works += _career("PEER", range(2000, 2026), "Q") + works += [make_work("JP", 2020, [("PEER", UDE, "first"), ("PROF", UDE, "last")])] + + g = build_graph(works, {"PROF", "JUNIOR", "PEER"}) + mm = mentor_metrics(g, "PROF") + + assert mm.juniors_mentored == 1 + assert mm.junior_ids == ["JUNIOR"] + assert mm.junior_progression_rate == pytest.approx(1.0) + # PROF was last author on J1 with a junior first author + assert mm.last_author_with_junior_first == 1 + # the senior PEER never counts + assert "PEER" not in mm.junior_ids + + +def test_mentor_excludes_external_coauthors(): + """External co-authors have truncated year-sets and must never count as juniors.""" + works = _career("PROF", range(2000, 2026), "P") + works += [make_work("E1", 2020, [("EXT", [], "first"), ("PROF", UDE, "last")])] + g = build_graph(works, {"PROF"}) # EXT not focal + mm = mentor_metrics(g, "PROF") + assert mm.juniors_mentored == 0 + assert mm.last_author_with_junior_first == 0 + + +def test_mentor_requires_focal_seniority_at_first_joint_year(): + """Two juniors co-publishing: neither mentors the other.""" + works = [ + make_work("W1", 2020, [("J1", UDE, "first"), ("J2", UDE, "last")]), + make_work("W2", 2021, [("J1", UDE, "first"), ("J2", UDE, "last")]), + ] + g = build_graph(works, {"J1", "J2"}) + assert mentor_metrics(g, "J2").juniors_mentored == 0 + + +def test_compute_all_metrics_shapes(): + works = _career("PROF", range(2000, 2026), "P") + works += [make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")])] + g = build_graph(works, {"PROF", "JUNIOR"}) + rows = compute_all_metrics(g) + assert set(rows) == {"PROF", "JUNIOR"} + prof = rows["PROF"] + assert prof["juniors_mentored"] == 1 + assert prof["active_years"] == 26 + assert 0.0 <= prof["industry_coauthor_share"] <= 1.0 + assert prof["suspicious_profile"] is False diff --git a/service/scripts/multipliers/tests/test_scoring.py b/service/scripts/multipliers/tests/test_scoring.py new file mode 100644 index 00000000..2c1d0594 --- /dev/null +++ b/service/scripts/multipliers/tests/test_scoring.py @@ -0,0 +1,120 @@ +"""Property-style tests for scoring: percentile bounds, tie handling, bucket isolation, +weight redistribution for missing metrics, tagging rules.""" +from __future__ import annotations + +import pytest + +from scoring import career_bucket, percentile_ranks, score_rows + +CONFIG = { + "_config_hash": "testhash", + "career": {"buckets": [4, 9, 14], "bucket_names": ["Early", "Emerging", "Established", "Senior"]}, + "weights": { + "bridger": {"betweenness": 0.5, "field_entropy": 0.5}, + "mentor": {"juniors_mentored": 1.0}, + }, + "tags": {"threshold": 0.85, "min_active_years": 2}, +} + + +def row(aid, active_years, betweenness=0.0, entropy=0.0, juniors=0): + return { + "author_id": aid, + "active_years": active_years, + "betweenness": betweenness, + "field_entropy": entropy, + "juniors_mentored": juniors, + "junior_ids": [], + } + + +def test_career_bucket_thresholds_match_backend(): + names = ["Early", "Emerging", "Established", "Senior"] + assert career_bucket(1, [4, 9, 14], names) == "Early" + assert career_bucket(4, [4, 9, 14], names) == "Early" + assert career_bucket(5, [4, 9, 14], names) == "Emerging" + assert career_bucket(9, [4, 9, 14], names) == "Emerging" + assert career_bucket(10, [4, 9, 14], names) == "Established" + assert career_bucket(14, [4, 9, 14], names) == "Established" + assert career_bucket(15, [4, 9, 14], names) == "Senior" + + +def test_percentiles_in_zero_one_and_ties_share_mean_rank(): + p = percentile_ranks({"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0}) + assert all(0.0 < v <= 1.0 for v in p.values()) + assert p["d"] == pytest.approx(1.0) + assert p["a"] == pytest.approx(0.25) + + # a metric that is 0 for most people must not hand out high percentiles + p = percentile_ranks({"a": 0, "b": 0, "c": 0, "d": 5}) + assert p["a"] == pytest.approx(0.5) # mean rank of the 3-way tie: (1+2+3)/3 / 4 + assert p["d"] == pytest.approx(1.0) + # None values are excluded entirely + p = percentile_ranks({"a": None, "b": 1.0}) + assert "a" not in p and p["b"] == pytest.approx(1.0) + + +def test_percentiles_computed_within_buckets_not_across(): + rows = { + # Early bucket: modest raw values + "e1": row("e1", 2, betweenness=0.1, entropy=0.5), + "e2": row("e2", 3, betweenness=0.0, entropy=0.0), + # Senior bucket: huge raw values + "s1": row("s1", 20, betweenness=0.9, entropy=3.0), + "s2": row("s2", 25, betweenness=0.8, entropy=2.0), + } + scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)} + # e1 tops the EARLY bucket despite raw values far below the seniors + assert scored["e1"]["percentiles"]["betweenness"] == pytest.approx(1.0) + assert scored["s1"]["percentiles"]["betweenness"] == pytest.approx(1.0) + assert scored["e1"]["career_bucket"] == "Early" + assert scored["s1"]["career_bucket"] == "Senior" + + +def test_monotonicity_more_bridging_never_lowers_score(): + base = { + "a": row("a", 3, betweenness=0.1, entropy=1.0), + "b": row("b", 3, betweenness=0.2, entropy=1.0), + "c": row("c", 3, betweenness=0.3, entropy=1.0), + } + improved = { + "a": row("a", 3, betweenness=0.25, entropy=1.0), # a gains betweenness + "b": row("b", 3, betweenness=0.2, entropy=1.0), + "c": row("c", 3, betweenness=0.3, entropy=1.0), + } + s_base = {r["author_id"]: r for r in score_rows(base, CONFIG)} + s_improved = {r["author_id"]: r for r in score_rows(improved, CONFIG)} + assert ( + s_improved["a"]["sub_scores"]["bridger"] + >= s_base["a"]["sub_scores"]["bridger"] + ) + + +def test_missing_metric_weight_redistributed(): + rows = { + "a": {**row("a", 3, entropy=2.0), "betweenness": None}, + "b": {**row("b", 3, entropy=1.0), "betweenness": None}, + } + scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)} + # bridger falls back to entropy alone; the top entropy holder gets 1.0 + assert scored["a"]["sub_scores"]["bridger"] == pytest.approx(1.0) + + +def test_tags_fire_above_threshold_and_respect_min_active_years(): + rows = { + # 8-person Early bucket: m ranks 7/8 = 0.875 >= 0.85 threshold + **{f"x{i}": row(f"x{i}", 3, juniors=0) for i in range(6)}, + "m": row("m", 3, juniors=7), + "newbie": {**row("newbie", 1, juniors=9), "active_years": 1}, + } + scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)} + assert "mentor" in scored["m"]["tags"] + assert scored["newbie"]["tags"] == [] # min_active_years=2 gate + + +def test_output_carries_raw_percentile_subscore_and_hash(): + scored = score_rows({"a": row("a", 3, betweenness=0.5)}, CONFIG)[0] + assert scored["betweenness"] == 0.5 # raw + assert "betweenness" in scored["percentiles"] # percentile + assert "bridger" in scored["sub_scores"] # sub-score + assert scored["config_hash"] == "testhash" diff --git a/service/scripts/multipliers/tests/test_signals.py b/service/scripts/multipliers/tests/test_signals.py new file mode 100644 index 00000000..38a97fd5 --- /dev/null +++ b/service/scripts/multipliers/tests/test_signals.py @@ -0,0 +1,35 @@ +"""Tests for the pure parts of the signal joins: name/DOI normalization and +the ambiguity rule for news matching.""" +from __future__ import annotations + +from signals import normalize_doi, normalize_name + + +def test_normalize_name_diacritics_case_whitespace(): + assert normalize_name("René Müller") == "rene muller" + assert normalize_name("CHRISTOPH GILLE") == "christoph gille" # news is often ALL-CAPS + assert normalize_name(" Anna-Lena Giesecke ") == "anna-lena giesecke" + assert normalize_name("Barbara Saccà") == normalize_name("Barbara Sacca") + assert normalize_name("Bülent Eken") == "bulent eken" + + +def test_normalize_doi_prefixes_and_case(): + assert normalize_doi("https://doi.org/10.1371/journal.pone.0018216") == \ + "10.1371/journal.pone.0018216" + assert normalize_doi("DOI:10.1016/J.CELL.2020.01.001") == "10.1016/j.cell.2020.01.001" + assert normalize_doi("doi.org/10.1/x") == "10.1/x" + assert normalize_doi("10.1/x") == "10.1/x" + assert normalize_doi("") is None + assert normalize_doi(None) is None + + +def test_ambiguous_name_rule(): + """Two cohort authors normalizing to the same name -> both excluded from news.""" + from collections import defaultdict + names = {"A1": "Wei Zhang", "A2": "Wei ZHANG", "A3": "Unique Person"} + by_norm = defaultdict(list) + for aid, n in names.items(): + by_norm[normalize_name(n)].append(aid) + ambiguous = {k for k, v in by_norm.items() if len(v) > 1} + assert normalize_name("Wei Zhang") in ambiguous + assert normalize_name("Unique Person") not in ambiguous diff --git a/service/scripts/multipliers/validate_sample.py b/service/scripts/multipliers/validate_sample.py new file mode 100644 index 00000000..3f98ff14 --- /dev/null +++ b/service/scripts/multipliers/validate_sample.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +""" +validate_sample.py — M1 exit check against the 60-person hand-labeled sample. + +analysis/career_stage/career_stage_sample.csv holds 60 UDE researchers with +manually verified status (31 Professor / 29 Researcher incl. doctoral). The +mentor sub-score is a proxy for supervision with no ground truth in OpenAlex, +so the cheapest sanity check is: mentor scores must concentrate on the +professors. If they don't, the proxy is wrong and M2 waits (plan §5, M1 exit). + +Usage: + python validate_sample.py --institution-id I62318514 +""" +from __future__ import annotations + +import argparse +import csv +import gzip +import json +import statistics +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPT_DIR.parent.parent.parent +SAMPLE_CSV = REPO_ROOT / "analysis" / "career_stage" / "career_stage_sample.csv" + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--institution-id", required=True) + parser.add_argument("--cache-dir", default=str(SCRIPT_DIR / "cache")) + args = parser.parse_args() + + short = args.institution_id.strip().rsplit("/", 1)[-1] + scores_path = Path(args.cache_dir) / f"scores_{short}.jsonl.gz" + if not scores_path.exists(): + raise SystemExit(f"Run build.py first — missing {scores_path}") + + scores: dict[str, dict] = {} + with gzip.open(scores_path, "rt", encoding="utf-8") as f: + for line in f: + row = json.loads(line) + scores[row["author_id"]] = row + + sample: list[dict] = [] + with open(SAMPLE_CSV, newline="", encoding="utf-8-sig") as f: + for rec in csv.DictReader(f): + sample.append(rec) + + by_status: dict[str, list[dict]] = {} + missing: list[str] = [] + for rec in sample: + aid = rec["openalex_author_id"].strip() + row = scores.get(aid) + if row is None: + missing.append(f"{rec['name']} ({aid})") + continue + by_status.setdefault(rec["known_status"], []).append( + {"name": rec["name"], "discipline": rec["discipline_group"], **row} + ) + + print(f"Sample: {len(sample)} people, matched in scores: " + f"{sum(len(v) for v in by_status.values())}, missing: {len(missing)}") + for m in missing: + print(f" MISSING: {m}") + + report: dict = {"missing": missing, "by_status": {}} + for sub in ("mentor", "bridger", "amplifier"): + print(f"\n=== {sub} sub-score by known status ===") + for status, rows in sorted(by_status.items()): + vals = [r["sub_scores"][sub] for r in rows] + entry = { + "n": len(vals), + "median": round(statistics.median(vals), 3), + "mean": round(statistics.fmean(vals), 3), + "min": round(min(vals), 3), + "max": round(max(vals), 3), + } + report["by_status"].setdefault(status, {})[sub] = entry + print(f" {status:<12} n={entry['n']:>2} median={entry['median']:.3f} " + f"mean={entry['mean']:.3f} range=[{entry['min']:.3f}, {entry['max']:.3f}]") + + # headline check: professors' median mentor score > researchers' + prof = report["by_status"].get("Professor", {}).get("mentor", {}) + res = report["by_status"].get("Researcher", {}).get("mentor", {}) + if prof and res: + ok = prof["median"] > res["median"] + print(f"\nM1 exit check — professors' median mentor score " + f"({prof['median']}) > researchers' ({res['median']}): " + f"{'PASS' if ok else 'FAIL'}") + report["m1_exit_mentor_check"] = "PASS" if ok else "FAIL" + + # per-person detail for eyeballing + print("\n=== per-person (sorted by mentor score) ===") + everyone = [r for rows in by_status.values() for r in rows] + for r in sorted(everyone, key=lambda x: x["sub_scores"]["mentor"], reverse=True): + status = next(s for s, rows in by_status.items() if r in rows) + print(f" {r['sub_scores']['mentor']:.3f} {status:<11} {r['career_bucket']:<12}" + f" juniors={r['juniors_mentored']:>3} laj={r['last_author_with_junior_first']:>3}" + f" {r['name']} ({r['discipline']})") + + out = Path(args.cache_dir) / f"validation_{short}.json" + with open(out, "w", encoding="utf-8", newline="\n") as f: + json.dump(report, f, ensure_ascii=False, indent=2) + print(f"\nReport -> {out}") + + +if __name__ == "__main__": + main()