Merge remote-tracking branch 'origin/dev' into feature/preprocessing
LocationBasedServices/smartguide/pipeline/head This commit looks good
@@ -0,0 +1,59 @@
|
||||
# Career-Stage-Analyse
|
||||
|
||||
Diese Analyse untersucht, wie sich der Karrierestatus von Forschenden (Professor vs.
|
||||
Researcher) aus deren Publikationshistorie in OpenAlex ableiten lässt. Das Ergebnis ist die
|
||||
Grundlage für die Career-Stage-Klassifikation im SmartGuide-Backend.
|
||||
|
||||
## Vorgehen
|
||||
|
||||
- **Stichprobe:** 60 Forschende der UDE mit manuell recherchiertem, bekanntem Status
|
||||
(31 Professor, 29 Researcher inkl. Doctoral Researcher) aus fünf Disziplingruppen:
|
||||
Biology, Computer Science, Engineering, Medicine, Sociology
|
||||
([career_stage_sample.csv](career_stage_sample.csv)).
|
||||
- **Datenerhebung:** Für jede Person wurden alle Werke über die OpenAlex-API geladen
|
||||
([openalex_client.py](openalex_client.py)) und daraus pro Person Metriken berechnet
|
||||
([career_stage_analysis.py](career_stage_analysis.py) →
|
||||
[career_stage_results.csv](career_stage_results.csv)):
|
||||
- `career_span`: Jahre vom ersten bis zum letzten Publikationsjahr (inklusiv)
|
||||
- `active_years`: Anzahl **unterschiedlicher** Jahre mit mindestens einer Publikation
|
||||
- `publication_count`, `publications_per_active_year`, `publications_per_career_year`,
|
||||
`years_since_last_publication`
|
||||
- **Auswertung:** Vergleich der Metriken zwischen den bekannten Status-Gruppen, auch je
|
||||
Disziplingruppe ([career_stage_visualization.py](career_stage_visualization.py) →
|
||||
[plots/](plots/), [summaries/](summaries/)).
|
||||
|
||||
## Ergebnisse
|
||||
|
||||
Die Gruppen trennen sich deutlich (Median Professor vs. Researcher):
|
||||
|
||||
| Metrik | Professor | Researcher |
|
||||
| ----------------------------- | --------- | ---------- |
|
||||
| Aktive Publikationsjahre | 28 | 5 |
|
||||
| Career Span (Jahre) | 31 | 7 |
|
||||
| Publikationen | 224 | 11 |
|
||||
| Publikationen je aktivem Jahr | 7,6 | 1,8 |
|
||||
|
||||
Wichtigste Erkenntnis: **`career_span` ist unzuverlässig.** Fehlerhafte Autorenzuordnungen in
|
||||
OpenAlex führen zu unplausibel frühen Erstpublikationen (z. B. 1893/1906 bei aktiven
|
||||
Professor:innen) und blähen die Spannweite massiv auf (Mittelwert 45 Jahre bei Median 31).
|
||||
**`active_years` ist dagegen robust:** Ein einzelnes falsch zugeordnetes altes Werk erhöht die
|
||||
Spannweite um Jahrzehnte, die aktiven Jahre aber nur um 1. Die Trennung zwischen den Gruppen
|
||||
ist bei `active_years` zudem über alle Disziplingruppen hinweg konsistent.
|
||||
|
||||
## Fazit: finale Entscheidungskriterien im Projekt
|
||||
|
||||
Die Career Stage wird im Backend ausschließlich über die **aktiven Publikationsjahre**
|
||||
(`active_years`) bestimmt (siehe `_classify_career_stage` in
|
||||
`service/src/main/inse/persons/logic.py`):
|
||||
|
||||
| Aktive Jahre | Career Stage |
|
||||
| ------------ | ------------ |
|
||||
| 0 | unknown |
|
||||
| 1–4 | Early |
|
||||
| 5–9 | Emerging |
|
||||
| 10–14 | Established |
|
||||
| ≥ 15 | Senior |
|
||||
|
||||
Zusätzlich wird `has_suspicious_publication_years` gesetzt (Erstpublikation vor 1970 oder
|
||||
Career Span > 60 Jahre), um Personen mit vermutlich fehlerhafter OpenAlex-Zuordnung zu
|
||||
kennzeichnen.
|
||||
@@ -0,0 +1,195 @@
|
||||
import csv
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openalex_client import get_all_author_works
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
|
||||
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
|
||||
|
||||
def extract_publication_years(works: list[dict[str, Any]]) -> list[int]:
|
||||
"""
|
||||
Extracts all valid publication years from the OpenAlex works response.
|
||||
|
||||
One entry in the returned list represents one publication.
|
||||
Therefore, duplicate years are intentionally kept.
|
||||
Example:
|
||||
[2020, 2020, 2021] means 3 publications in 2 active years.
|
||||
"""
|
||||
years: list[int] = []
|
||||
|
||||
for work in works:
|
||||
year = work.get("publication_year")
|
||||
|
||||
if isinstance(year, int):
|
||||
years.append(year)
|
||||
elif isinstance(year, str) and year.isdigit():
|
||||
years.append(int(year))
|
||||
|
||||
return years
|
||||
|
||||
|
||||
def normalize_known_status(known_status: str) -> str:
|
||||
"""
|
||||
Normalizes manually assigned status labels.
|
||||
|
||||
The analysis compares Professor vs Researcher. Doctoral Researcher is therefore
|
||||
mapped to Researcher to keep the groups consistent.
|
||||
"""
|
||||
cleaned_status = known_status.strip()
|
||||
|
||||
if cleaned_status == "Doctoral Researcher":
|
||||
return "Researcher"
|
||||
|
||||
return cleaned_status
|
||||
|
||||
|
||||
def compute_metrics(publication_years: list[int]) -> dict[str, int | float | None]:
|
||||
"""
|
||||
Computes publication-history-based career metrics.
|
||||
|
||||
Important distinction:
|
||||
- publication_count counts all publications
|
||||
- active_years counts distinct years with at least one publication
|
||||
- career_span counts the full inclusive span from first to last publication year
|
||||
"""
|
||||
current_year = datetime.now().year
|
||||
|
||||
if not publication_years:
|
||||
return {
|
||||
"first_publication_year": None,
|
||||
"last_publication_year": None,
|
||||
"career_age": None,
|
||||
"career_span": None,
|
||||
"active_years": 0,
|
||||
"publication_count": 0,
|
||||
"publications_per_active_year": None,
|
||||
"publications_per_career_year": None,
|
||||
"years_since_last_publication": None,
|
||||
}
|
||||
|
||||
sorted_years = sorted(publication_years)
|
||||
unique_years = sorted(set(publication_years))
|
||||
|
||||
first_year = sorted_years[0]
|
||||
last_year = sorted_years[-1]
|
||||
|
||||
publication_count = len(sorted_years)
|
||||
active_years = len(unique_years)
|
||||
|
||||
career_age = last_year - first_year
|
||||
career_span = last_year - first_year + 1
|
||||
|
||||
publications_per_active_year = (
|
||||
publication_count / active_years if active_years > 0 else None
|
||||
)
|
||||
|
||||
publications_per_career_year = (
|
||||
publication_count / career_span if career_span > 0 else None
|
||||
)
|
||||
|
||||
years_since_last_publication = current_year - last_year
|
||||
|
||||
return {
|
||||
"first_publication_year": first_year,
|
||||
"last_publication_year": last_year,
|
||||
"career_age": career_age,
|
||||
"career_span": career_span,
|
||||
"active_years": active_years,
|
||||
"publication_count": publication_count,
|
||||
"publications_per_active_year": publications_per_active_year,
|
||||
"publications_per_career_year": publications_per_career_year,
|
||||
"years_since_last_publication": years_since_last_publication,
|
||||
}
|
||||
|
||||
|
||||
def create_empty_metrics() -> dict[str, int | float | None]:
|
||||
return {
|
||||
"first_publication_year": None,
|
||||
"last_publication_year": None,
|
||||
"career_age": None,
|
||||
"career_span": None,
|
||||
"active_years": 0,
|
||||
"publication_count": 0,
|
||||
"publications_per_active_year": None,
|
||||
"publications_per_career_year": None,
|
||||
"years_since_last_publication": None,
|
||||
}
|
||||
|
||||
|
||||
def analyze_sample() -> None:
|
||||
if not INPUT_FILE.exists():
|
||||
raise FileNotFoundError(f"Input file not found: {INPUT_FILE}")
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
with INPUT_FILE.open(mode="r", encoding="utf-8", newline="") as input_file:
|
||||
reader = csv.DictReader(input_file)
|
||||
|
||||
for row in reader:
|
||||
name = row.get("name", "").strip()
|
||||
discipline = row.get("discipline", "").strip()
|
||||
discipline_group = row.get("discipline_group", "").strip()
|
||||
known_status = normalize_known_status(row.get("known_status", ""))
|
||||
openalex_author_id = row.get("openalex_author_id", "").strip()
|
||||
|
||||
if not discipline_group:
|
||||
discipline_group = discipline
|
||||
|
||||
if not openalex_author_id:
|
||||
print(f"Skipping {name}: missing OpenAlex author ID")
|
||||
continue
|
||||
|
||||
print(f"Fetching works for {name} ({openalex_author_id})...")
|
||||
|
||||
try:
|
||||
works = get_all_author_works(openalex_author_id)
|
||||
publication_years = extract_publication_years(works)
|
||||
metrics = compute_metrics(publication_years)
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error while processing {name}: {error}")
|
||||
metrics = create_empty_metrics()
|
||||
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"discipline": discipline,
|
||||
"discipline_group": discipline_group,
|
||||
"known_status": known_status,
|
||||
"openalex_author_id": openalex_author_id,
|
||||
**metrics,
|
||||
}
|
||||
)
|
||||
|
||||
fieldnames = [
|
||||
"name",
|
||||
"discipline",
|
||||
"discipline_group",
|
||||
"known_status",
|
||||
"openalex_author_id",
|
||||
"first_publication_year",
|
||||
"last_publication_year",
|
||||
"career_age",
|
||||
"career_span",
|
||||
"active_years",
|
||||
"publication_count",
|
||||
"publications_per_active_year",
|
||||
"publications_per_career_year",
|
||||
"years_since_last_publication",
|
||||
]
|
||||
|
||||
with OUTPUT_FILE.open(mode="w", encoding="utf-8", newline="") as output_file:
|
||||
writer = csv.DictWriter(output_file, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
writer.writerows(results)
|
||||
|
||||
print(f"Analysis finished. Results written to {OUTPUT_FILE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
analyze_sample()
|
||||
@@ -0,0 +1,61 @@
|
||||
name,discipline,discipline_group,known_status,openalex_author_id,first_publication_year,last_publication_year,career_age,career_span,active_years,publication_count,publications_per_active_year,publications_per_career_year,years_since_last_publication
|
||||
Barbara Saccà,Biology,Biology,Professor,A5075803366,1997,2024,27,28,26,91,3.5,3.25,2
|
||||
Bernd Sures,Biology,Biology,Professor,A5088631999,1994,2026,32,33,32,410,12.8125,12.424242424242424,0
|
||||
Daniel Hering,Biology,Biology,Professor,A5031147249,1893,2026,133,134,37,326,8.81081081081081,2.4328358208955225,0
|
||||
Daniel Hoffmann,Biology,Biology,Professor,A5074555350,1966,2026,60,61,35,332,9.485714285714286,5.442622950819672,0
|
||||
Peter Bayer,Biology,Biology,Professor,A5060566345,1969,2026,57,58,37,358,9.675675675675675,6.172413793103448,0
|
||||
Bianca Kamba,Biology,Biology,Researcher,A5036363877,2017,2025,8,9,4,9,2.25,1.0,1
|
||||
Daniel Grabner,Biology,Biology,Researcher,A5063959731,1980,2026,46,47,19,95,5.0,2.021276595744681,0
|
||||
Farnusch Kaschani,Biology,Biology,Researcher,A5078099512,2005,2026,21,22,21,182,8.666666666666666,8.272727272727273,0
|
||||
Kathrin Januschke,Biology,Biology,Researcher,A5064225981,2011,2026,15,16,15,36,2.4,2.25,0
|
||||
Richard Kosinski,Biology,Biology,Researcher,A5014403509,1986,2022,36,37,4,6,1.5,0.16216216216216217,4
|
||||
Jens Krüger,Computer Graphics and Visualization,Computer Science,Professor,A5087449583,1964,2025,61,62,20,67,3.35,1.0806451612903225,1
|
||||
Torben Weis,Distributed Systems,Computer Science,Professor,A5016729057,1980,2026,46,47,43,197,4.5813953488372094,4.191489361702128,0
|
||||
Stefan Schneegaß,Human Computer Interaction,Computer Science,Professor,A5024328962,2008,2026,18,19,17,224,13.176470588235293,11.789473684210526,0
|
||||
Gregor Schiele,Intelligent Embedded Systems,Computer Science,Professor,A5028943371,1999,2026,27,28,22,155,7.045454545454546,5.535714285714286,0
|
||||
Pedro José Marrón,Networked Embedded Systems,Computer Science,Professor,A5047117780,1996,2026,30,31,28,285,10.178571428571429,9.193548387096774,0
|
||||
Lucas Davi,Secure Software Systems,Computer Science,Professor,A5089242868,2009,2026,17,18,18,137,7.611111111111111,7.611111111111111,0
|
||||
Volker Gruhn,Software Engineering,Computer Science,Professor,A5049739067,1989,2025,36,37,36,410,11.38888888888889,11.08108108108108,1
|
||||
Andreas Metzger,Software Systems Engineering,Computer Science,Professor,A5082025709,1992,2026,34,35,28,202,7.214285714285714,5.771428571428571,0
|
||||
Andreas Vogelsang,Software Systems Engineering,Computer Science,Professor,A5022998651,2005,2026,21,22,20,225,11.25,10.227272727272727,0
|
||||
Barbara König,Theoretical Computer Science,Computer Science,Professor,A5103103785,1906,2026,120,121,36,230,6.388888888888889,1.9008264462809918,0
|
||||
Alexandra Dmitrienko,Vertrauenswürdige Systeme,Computer Science,Professor,A5042835341,2010,2026,16,17,17,110,6.470588235294118,6.470588235294118,0
|
||||
Carina Liebers,Human Computer Interaction,Computer Science,Researcher,A5004350173,2022,2026,4,5,5,11,2.2,2.2,0
|
||||
Jonas Keppel,Human Computer Interaction,Computer Science,Researcher,A5015767175,2022,2026,4,5,5,11,2.2,2.2,0
|
||||
Carlos Medina Sánchez,Networked Embedded Systems,Computer Science,Researcher,A5093479876,2023,2025,2,3,2,2,1.0,0.6666666666666666,1
|
||||
Marcus Handte,Networked Embedded Systems,Computer Science,Researcher,A5007170803,2004,2026,22,23,23,107,4.6521739130434785,4.6521739130434785,0
|
||||
Simon Janzon,Networked Embedded Systems,Computer Science,Researcher,A5044472300,2020,2025,5,6,5,6,1.2,1.0,1
|
||||
Christian Niesler,Secure Software Systems,Computer Science,Researcher,A5069184110,2021,2026,5,6,5,9,1.8,1.5,0
|
||||
Christian Scholz,Secure Software Systems,Computer Science,Researcher,A5120610207,2025,2026,1,2,2,2,1.0,1.0,0
|
||||
Pascal Winkler,Secure Software Systems,Computer Science,Researcher,A5081189339,2009,2026,17,18,6,22,3.6666666666666665,1.2222222222222223,0
|
||||
Stefan Hanenberg,Software Engineering,Computer Science,Researcher,A5027034338,2000,2025,25,26,25,105,4.2,4.038461538461538,1
|
||||
Wilhelm Koop,Software Engineering,Computer Science,Researcher,A5019228221,2016,2022,6,7,6,14,2.3333333333333335,2.0,4
|
||||
Venkata Marella,Vertrauenswürdige Systeme,Computer Science,Researcher,A5082156768,2017,2026,9,10,8,11,1.375,1.1,0
|
||||
Burak Atakan,Engineering,Engineering,Professor,A5041521847,1989,2026,37,38,35,202,5.771428571428571,5.315789473684211,0
|
||||
Corina Andronescu,Engineering,Engineering,Professor,A5082583063,2008,2026,18,19,19,137,7.2105263157894735,7.2105263157894735,0
|
||||
Gerd Bacher,Engineering,Engineering,Professor,A5056038758,1985,2026,41,42,38,385,10.131578947368421,9.166666666666666,0
|
||||
Miriam Böhm,Engineering,Engineering,Researcher,A5037448457,2011,2021,10,11,8,12,1.5,1.0909090909090908,5
|
||||
Soheil Salighe,Steuerung Regelung und Systemdynamik,Engineering,Researcher,A5041884757,2017,2024,7,8,5,7,1.4,0.875,2
|
||||
Tobias Mikolas,Engineering,Engineering,Researcher,A5002909977,2021,2023,2,3,2,2,1.0,0.6666666666666666,3
|
||||
Boris Hadaschik,Medicine,Medicine,Professor,A5077243123,2001,2026,25,26,24,791,32.958333333333336,30.423076923076923,0
|
||||
Hartmut Schmidt,Medicine,Medicine,Professor,A5015932441,1910,2026,116,117,63,1024,16.253968253968253,8.752136752136753,0
|
||||
Matthias Gunzer,Medicine,Medicine,Professor,A5020520632,1997,2026,29,30,29,343,11.827586206896552,11.433333333333334,0
|
||||
Oliver Witzke,Medicine,Medicine,Professor,A5087456839,1954,2026,72,73,34,615,18.08823529411765,8.424657534246576,0
|
||||
Stephan Lang,Medicine,Medicine,Professor,A5030649192,1929,2026,97,98,44,859,19.522727272727273,8.76530612244898,0
|
||||
Tienush Rassaf,Medicine,Medicine,Professor,A5048609556,2002,2025,23,24,19,62,3.263157894736842,2.5833333333333335,1
|
||||
Ulrike Bingel,Medicine,Medicine,Professor,A5002281474,1998,2026,28,29,27,315,11.666666666666666,10.862068965517242,0
|
||||
Birte Möhlendick,Medicine,Medicine,Researcher,A5030635588,2010,2025,15,16,14,48,3.4285714285714284,3.0,1
|
||||
Julia Schwichtenberg,Medicine,Medicine,Researcher,A5119372151,2025,2026,1,2,2,3,1.5,1.5,0
|
||||
Katrin Schuldt,Medicine,Medicine,Researcher,A5002003996,2000,2026,26,27,7,12,1.7142857142857142,0.4444444444444444,0
|
||||
Sabrina Guckenbiehl,Medicine,Medicine,Researcher,A5008120333,2021,2026,5,6,6,31,5.166666666666667,5.166666666666667,0
|
||||
Zülal Cibir,Medicine,Medicine,Researcher,A5035081158,2019,2025,6,7,7,21,3.0,3.0,1
|
||||
Frank Kleemann,Sociology,Sociology,Professor,A5041694590,1999,2025,26,27,22,106,4.818181818181818,3.925925925925926,1
|
||||
Gregor Bongaerts,Sociology,Sociology,Professor,A5012265262,2000,2025,25,26,18,55,3.0555555555555554,2.1153846153846154,1
|
||||
Helen Baykara-Krumme,Sociology,Sociology,Professor,A5010111732,2007,2026,19,20,19,71,3.736842105263158,3.55,0
|
||||
Marcel Erlinghagen,Sociology,Sociology,Professor,A5021715937,1970,2026,56,57,29,131,4.517241379310345,2.2982456140350878,0
|
||||
Ute Klammer,Sociology,Sociology,Professor,A5055077517,1997,2026,29,30,25,146,5.84,4.866666666666666,0
|
||||
Andreas Jansen,Sociology,Sociology,Researcher,A5030957194,1991,2026,35,36,12,15,1.25,0.4166666666666667,0
|
||||
Antonia Görtz,Sociology,Sociology,Researcher,A5066776558,2022,2025,3,4,2,2,1.0,0.5,1
|
||||
Friedrich Scheller,Sociology,Sociology,Researcher,A5072565080,2014,2020,6,7,2,2,1.0,0.2857142857142857,6
|
||||
Lara Altenstädter,Sociology,Sociology,Researcher,A5070117981,2019,2023,4,5,5,15,3.0,3.0,3
|
||||
Lisa Mansfeld,Sociology,Sociology,Researcher,A5018318930,2021,2026,5,6,5,9,1.8,1.5,0
|
||||
|
@@ -0,0 +1,61 @@
|
||||
name,discipline,discipline_group,known_status,openalex_author_id
|
||||
Barbara Saccà,Biology,Biology,Professor,A5075803366
|
||||
Bernd Sures,Biology,Biology,Professor,A5088631999
|
||||
Daniel Hering,Biology,Biology,Professor,A5031147249
|
||||
Daniel Hoffmann,Biology,Biology,Professor,A5074555350
|
||||
Peter Bayer,Biology,Biology,Professor,A5060566345
|
||||
Bianca Kamba,Biology,Biology,Researcher,A5036363877
|
||||
Daniel Grabner,Biology,Biology,Researcher,A5063959731
|
||||
Farnusch Kaschani,Biology,Biology,Researcher,A5078099512
|
||||
Kathrin Januschke,Biology,Biology,Researcher,A5064225981
|
||||
Richard Kosinski,Biology,Biology,Researcher,A5014403509
|
||||
Jens Krüger,Computer Graphics and Visualization,Computer Science,Professor,A5087449583
|
||||
Torben Weis,Distributed Systems,Computer Science,Professor,A5016729057
|
||||
Stefan Schneegaß,Human Computer Interaction,Computer Science,Professor,A5024328962
|
||||
Gregor Schiele,Intelligent Embedded Systems,Computer Science,Professor,A5028943371
|
||||
Pedro José Marrón,Networked Embedded Systems,Computer Science,Professor,A5047117780
|
||||
Lucas Davi,Secure Software Systems,Computer Science,Professor,A5089242868
|
||||
Volker Gruhn,Software Engineering,Computer Science,Professor,A5049739067
|
||||
Andreas Metzger,Software Systems Engineering,Computer Science,Professor,A5082025709
|
||||
Andreas Vogelsang,Software Systems Engineering,Computer Science,Professor,A5022998651
|
||||
Barbara König,Theoretical Computer Science,Computer Science,Professor,A5103103785
|
||||
Alexandra Dmitrienko,Vertrauenswürdige Systeme,Computer Science,Professor,A5042835341
|
||||
Carina Liebers,Human Computer Interaction,Computer Science,Researcher,A5004350173
|
||||
Jonas Keppel,Human Computer Interaction,Computer Science,Researcher,A5015767175
|
||||
Carlos Medina Sánchez,Networked Embedded Systems,Computer Science,Researcher,A5093479876
|
||||
Marcus Handte,Networked Embedded Systems,Computer Science,Researcher,A5007170803
|
||||
Simon Janzon,Networked Embedded Systems,Computer Science,Researcher,A5044472300
|
||||
Christian Niesler,Secure Software Systems,Computer Science,Researcher,A5069184110
|
||||
Christian Scholz,Secure Software Systems,Computer Science,Researcher,A5120610207
|
||||
Pascal Winkler,Secure Software Systems,Computer Science,Researcher,A5081189339
|
||||
Stefan Hanenberg,Software Engineering,Computer Science,Researcher,A5027034338
|
||||
Wilhelm Koop,Software Engineering,Computer Science,Researcher,A5019228221
|
||||
Venkata Marella,Vertrauenswürdige Systeme,Computer Science,Researcher,A5082156768
|
||||
Burak Atakan,Engineering,Engineering,Professor,A5041521847
|
||||
Corina Andronescu,Engineering,Engineering,Professor,A5082583063
|
||||
Gerd Bacher,Engineering,Engineering,Professor,A5056038758
|
||||
Miriam Böhm,Engineering,Engineering,Researcher,A5037448457
|
||||
Soheil Salighe,Steuerung Regelung und Systemdynamik,Engineering,Researcher,A5041884757
|
||||
Tobias Mikolas,Engineering,Engineering,Researcher,A5002909977
|
||||
Boris Hadaschik,Medicine,Medicine,Professor,A5077243123
|
||||
Hartmut Schmidt,Medicine,Medicine,Professor,A5015932441
|
||||
Matthias Gunzer,Medicine,Medicine,Professor,A5020520632
|
||||
Oliver Witzke,Medicine,Medicine,Professor,A5087456839
|
||||
Stephan Lang,Medicine,Medicine,Professor,A5030649192
|
||||
Tienush Rassaf,Medicine,Medicine,Professor,A5048609556
|
||||
Ulrike Bingel,Medicine,Medicine,Professor,A5002281474
|
||||
Birte Möhlendick,Medicine,Medicine,Researcher,A5030635588
|
||||
Julia Schwichtenberg,Medicine,Medicine,Researcher,A5119372151
|
||||
Katrin Schuldt,Medicine,Medicine,Researcher,A5002003996
|
||||
Sabrina Guckenbiehl,Medicine,Medicine,Researcher,A5008120333
|
||||
Zülal Cibir,Medicine,Medicine,Researcher,A5035081158
|
||||
Frank Kleemann,Sociology,Sociology,Professor,A5041694590
|
||||
Gregor Bongaerts,Sociology,Sociology,Professor,A5012265262
|
||||
Helen Baykara-Krumme,Sociology,Sociology,Professor,A5010111732
|
||||
Marcel Erlinghagen,Sociology,Sociology,Professor,A5021715937
|
||||
Ute Klammer,Sociology,Sociology,Professor,A5055077517
|
||||
Andreas Jansen,Sociology,Sociology,Researcher,A5030957194
|
||||
Antonia Görtz,Sociology,Sociology,Researcher,A5066776558
|
||||
Friedrich Scheller,Sociology,Sociology,Researcher,A5072565080
|
||||
Lara Altenstädter,Sociology,Sociology,Researcher,A5070117981
|
||||
Lisa Mansfeld,Sociology,Sociology,Researcher,A5018318930
|
||||
|
@@ -0,0 +1,633 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable, Literal
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
PLOTS_DIR = BASE_DIR / "plots"
|
||||
SUMMARY_DIR = BASE_DIR / "summaries"
|
||||
|
||||
STATUS_ORDER = ["Professor", "Researcher"]
|
||||
METRICS = [
|
||||
"career_span",
|
||||
"active_years",
|
||||
"publication_count",
|
||||
"publications_per_active_year",
|
||||
"publications_per_career_year",
|
||||
"years_since_last_publication",
|
||||
]
|
||||
|
||||
NUMERIC_COLUMNS = [
|
||||
"first_publication_year",
|
||||
"last_publication_year",
|
||||
"career_age",
|
||||
*METRICS,
|
||||
]
|
||||
|
||||
METRIC_LABELS = {
|
||||
"career_span": "Career Span in Years",
|
||||
"active_years": "Active Publication Years",
|
||||
"publication_count": "Number of Publications",
|
||||
"publications_per_active_year": "Publications per Active Year",
|
||||
"publications_per_career_year": "Publications per Career Year",
|
||||
"years_since_last_publication": "Years Since Last Publication",
|
||||
}
|
||||
|
||||
METRIC_TITLES = {
|
||||
"career_span": "Career Span",
|
||||
"active_years": "Active Publication Years",
|
||||
"publication_count": "Publication Count",
|
||||
"publications_per_active_year": "Publications per Active Year",
|
||||
"publications_per_career_year": "Publications per Career Year",
|
||||
"years_since_last_publication": "Years Since Last Publication",
|
||||
}
|
||||
|
||||
|
||||
StatisticFunction = Callable[[pd.Series], float]
|
||||
ScatterLabelMode = Literal["none", "outliers", "all"]
|
||||
|
||||
|
||||
def prepare_data() -> pd.DataFrame:
|
||||
if not INPUT_FILE.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Input file not found: {INPUT_FILE}. "
|
||||
"Run career_stage_analysis.py first."
|
||||
)
|
||||
|
||||
df = pd.read_csv(INPUT_FILE)
|
||||
|
||||
if "discipline_group" not in df.columns:
|
||||
df["discipline_group"] = df.get("discipline", "Unknown")
|
||||
|
||||
df["discipline_group"] = df["discipline_group"].fillna("Unknown")
|
||||
df["known_status"] = df["known_status"].fillna("Unknown")
|
||||
|
||||
for column in NUMERIC_COLUMNS:
|
||||
if column in df.columns:
|
||||
df[column] = pd.to_numeric(df[column], errors="coerce")
|
||||
|
||||
return df
|
||||
|
||||
|
||||
def ordered_statuses(df: pd.DataFrame) -> list[str]:
|
||||
statuses = [status for status in STATUS_ORDER if status in df["known_status"].unique()]
|
||||
additional_statuses = sorted(
|
||||
status
|
||||
for status in df["known_status"].dropna().unique()
|
||||
if status not in STATUS_ORDER
|
||||
)
|
||||
return statuses + additional_statuses
|
||||
|
||||
|
||||
def ordered_discipline_groups(df: pd.DataFrame) -> list[str]:
|
||||
return sorted(df["discipline_group"].dropna().unique())
|
||||
|
||||
|
||||
def mean_value(series: pd.Series) -> float:
|
||||
return series.mean()
|
||||
|
||||
|
||||
def median_value(series: pd.Series) -> float:
|
||||
return series.median()
|
||||
|
||||
|
||||
def build_summary(df: pd.DataFrame, group_columns: list[str]) -> pd.DataFrame:
|
||||
rows: list[dict[str, object]] = []
|
||||
|
||||
for group_values, group in df.groupby(group_columns, dropna=False):
|
||||
if not isinstance(group_values, tuple):
|
||||
group_values = (group_values,)
|
||||
|
||||
row: dict[str, object] = {
|
||||
column: value for column, value in zip(group_columns, group_values)
|
||||
}
|
||||
row["sample_size"] = len(group)
|
||||
|
||||
for metric in METRICS:
|
||||
if metric not in group.columns:
|
||||
continue
|
||||
|
||||
values = group[metric].dropna()
|
||||
row[f"mean_{metric}"] = values.mean() if not values.empty else None
|
||||
row[f"median_{metric}"] = values.median() if not values.empty else None
|
||||
|
||||
rows.append(row)
|
||||
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def save_summary_tables(df: pd.DataFrame) -> None:
|
||||
SUMMARY_DIR.mkdir(exist_ok=True)
|
||||
|
||||
summary_by_status = build_summary(df, ["known_status"])
|
||||
summary_by_status.to_csv(
|
||||
SUMMARY_DIR / "summary_by_status.csv",
|
||||
index=False,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
summary_by_discipline_group = build_summary(df, ["discipline_group"])
|
||||
summary_by_discipline_group.to_csv(
|
||||
SUMMARY_DIR / "summary_by_discipline_group.csv",
|
||||
index=False,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
summary_by_discipline_group_and_status = build_summary(
|
||||
df,
|
||||
["discipline_group", "known_status"],
|
||||
)
|
||||
summary_by_discipline_group_and_status.to_csv(
|
||||
SUMMARY_DIR / "summary_by_discipline_group_and_status.csv",
|
||||
index=False,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def save_bar_plot_by_status(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
statistic_name: str,
|
||||
statistic_function: StatisticFunction,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
grouped = df.groupby("known_status")[metric].apply(statistic_function)
|
||||
grouped = grouped.reindex(ordered_statuses(df)).dropna()
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
grouped.plot(kind="bar")
|
||||
plt.title(title)
|
||||
plt.xlabel("Known Status")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=30, ha="right")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
print(f"Saved {statistic_name} plot: {filename}")
|
||||
|
||||
|
||||
def save_grouped_bar_plot_by_discipline_group(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
statistic_name: str,
|
||||
statistic_function: StatisticFunction,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
grouped = (
|
||||
df.groupby(["discipline_group", "known_status"])[metric]
|
||||
.apply(statistic_function)
|
||||
.unstack("known_status")
|
||||
)
|
||||
|
||||
grouped = grouped.reindex(ordered_discipline_groups(df))
|
||||
grouped = grouped.reindex(columns=ordered_statuses(df))
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
grouped.plot(kind="bar")
|
||||
plt.title(title)
|
||||
plt.xlabel("Discipline Group")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=30, ha="right")
|
||||
plt.legend(title="Known Status")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
print(f"Saved {statistic_name} discipline group plot: {filename}")
|
||||
|
||||
|
||||
def save_box_plot_by_status(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
statuses = ordered_statuses(df)
|
||||
data = [df.loc[df["known_status"] == status, metric].dropna() for status in statuses]
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
plt.boxplot(data, labels=statuses)
|
||||
plt.title(title)
|
||||
plt.xlabel("Known Status")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=30, ha="right")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def save_box_plot_by_discipline_group_and_status(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
labels: list[str] = []
|
||||
data: list[pd.Series] = []
|
||||
|
||||
for discipline_group in ordered_discipline_groups(df):
|
||||
discipline_group_data = df[df["discipline_group"] == discipline_group]
|
||||
|
||||
for status in ordered_statuses(discipline_group_data):
|
||||
values = discipline_group_data.loc[
|
||||
discipline_group_data["known_status"] == status,
|
||||
metric,
|
||||
].dropna()
|
||||
|
||||
if values.empty:
|
||||
continue
|
||||
|
||||
labels.append(f"{discipline_group}\n{status}")
|
||||
data.append(values)
|
||||
|
||||
if not data:
|
||||
return
|
||||
|
||||
plt.figure(figsize=(14, 6))
|
||||
plt.boxplot(data, labels=labels)
|
||||
plt.title(title)
|
||||
plt.xlabel("Discipline Group and Known Status")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=45, ha="right")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def save_histogram(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
title: str,
|
||||
xlabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
plt.figure(figsize=(10, 6))
|
||||
df[metric].dropna().plot(kind="hist", bins=10)
|
||||
plt.title(title)
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel("Number of Researchers")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def is_outlier(row: pd.Series, df: pd.DataFrame, x_metric: str, y_metric: str) -> bool:
|
||||
x_values = df[x_metric].dropna()
|
||||
y_values = df[y_metric].dropna()
|
||||
|
||||
if x_values.empty or y_values.empty:
|
||||
return False
|
||||
|
||||
x_threshold = x_values.quantile(0.75) + 1.5 * (
|
||||
x_values.quantile(0.75) - x_values.quantile(0.25)
|
||||
)
|
||||
y_threshold = y_values.quantile(0.75) + 1.5 * (
|
||||
y_values.quantile(0.75) - y_values.quantile(0.25)
|
||||
)
|
||||
|
||||
x_value = row.get(x_metric)
|
||||
y_value = row.get(y_metric)
|
||||
|
||||
if pd.isna(x_value) or pd.isna(y_value):
|
||||
return False
|
||||
|
||||
is_statistical_outlier = x_value > x_threshold or y_value > y_threshold
|
||||
is_researcher_with_long_history = (
|
||||
row.get("known_status") == "Researcher"
|
||||
and (x_value > 20 or row.get("publication_count", 0) > 100)
|
||||
)
|
||||
is_suspiciously_old_first_publication = row.get("first_publication_year", 9999) < 1970
|
||||
|
||||
return bool(
|
||||
is_statistical_outlier
|
||||
or is_researcher_with_long_history
|
||||
or is_suspiciously_old_first_publication
|
||||
)
|
||||
|
||||
|
||||
def should_label_point(
|
||||
row: pd.Series,
|
||||
df: pd.DataFrame,
|
||||
x_metric: str,
|
||||
y_metric: str,
|
||||
label_mode: ScatterLabelMode,
|
||||
) -> bool:
|
||||
if label_mode == "none":
|
||||
return False
|
||||
|
||||
if label_mode == "all":
|
||||
return True
|
||||
|
||||
return is_outlier(row, df, x_metric, y_metric)
|
||||
|
||||
|
||||
def save_scatter_plot(
|
||||
df: pd.DataFrame,
|
||||
x_metric: str,
|
||||
y_metric: str,
|
||||
group_column: str,
|
||||
title: str,
|
||||
xlabel: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
label_mode: ScatterLabelMode = "none",
|
||||
) -> None:
|
||||
figure_width = 15 if label_mode == "all" else 11
|
||||
figure_height = 9 if label_mode == "all" else 7
|
||||
label_fontsize = 6 if label_mode == "all" else 8
|
||||
|
||||
plt.figure(figsize=(figure_width, figure_height))
|
||||
|
||||
for group_name, group in df.groupby(group_column):
|
||||
plt.scatter(group[x_metric], group[y_metric], label=group_name, alpha=0.8)
|
||||
|
||||
for _, row in group.iterrows():
|
||||
x_value = row.get(x_metric)
|
||||
y_value = row.get(y_metric)
|
||||
name = row.get("name")
|
||||
|
||||
if (
|
||||
pd.notna(name)
|
||||
and pd.notna(x_value)
|
||||
and pd.notna(y_value)
|
||||
and should_label_point(row, df, x_metric, y_metric, label_mode)
|
||||
):
|
||||
plt.annotate(
|
||||
str(name),
|
||||
(x_value, y_value),
|
||||
fontsize=label_fontsize,
|
||||
xytext=(5, 5),
|
||||
textcoords="offset points",
|
||||
)
|
||||
|
||||
plt.title(title)
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
plt.legend(title=group_column)
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def create_status_plots(df: pd.DataFrame) -> None:
|
||||
for metric in ["career_span", "publication_count", "active_years"]:
|
||||
metric_title = METRIC_TITLES[metric]
|
||||
metric_label = METRIC_LABELS[metric]
|
||||
|
||||
save_bar_plot_by_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="average",
|
||||
statistic_function=mean_value,
|
||||
title=f"Average {metric_title} by Known Status",
|
||||
ylabel=f"Average {metric_label}",
|
||||
filename=f"average_{metric}_by_status.png",
|
||||
)
|
||||
|
||||
save_bar_plot_by_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="median",
|
||||
statistic_function=median_value,
|
||||
title=f"Median {metric_title} by Known Status",
|
||||
ylabel=f"Median {metric_label}",
|
||||
filename=f"median_{metric}_by_status.png",
|
||||
)
|
||||
|
||||
for metric in [
|
||||
"publications_per_active_year",
|
||||
"publications_per_career_year",
|
||||
"years_since_last_publication",
|
||||
]:
|
||||
metric_title = METRIC_TITLES[metric]
|
||||
metric_label = METRIC_LABELS[metric]
|
||||
|
||||
save_bar_plot_by_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="average",
|
||||
statistic_function=mean_value,
|
||||
title=f"Average {metric_title} by Known Status",
|
||||
ylabel=f"Average {metric_label}",
|
||||
filename=f"average_{metric}_by_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_status(
|
||||
df=df,
|
||||
metric="career_span",
|
||||
title="Distribution of Career Span by Known Status",
|
||||
ylabel="Career Span in Years",
|
||||
filename="boxplot_career_span_by_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_status(
|
||||
df=df,
|
||||
metric="publication_count",
|
||||
title="Distribution of Publication Count by Known Status",
|
||||
ylabel="Number of Publications",
|
||||
filename="boxplot_publication_count_by_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_status(
|
||||
df=df,
|
||||
metric="active_years",
|
||||
title="Distribution of Active Publication Years by Known Status",
|
||||
ylabel="Active Publication Years",
|
||||
filename="boxplot_active_years_by_status.png",
|
||||
)
|
||||
|
||||
|
||||
def create_discipline_group_plots(df: pd.DataFrame) -> None:
|
||||
for metric in ["career_span", "publication_count", "active_years"]:
|
||||
metric_title = METRIC_TITLES[metric]
|
||||
metric_label = METRIC_LABELS[metric]
|
||||
|
||||
save_grouped_bar_plot_by_discipline_group(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="average",
|
||||
statistic_function=mean_value,
|
||||
title=f"Average {metric_title} by Discipline Group and Status",
|
||||
ylabel=f"Average {metric_label}",
|
||||
filename=f"average_{metric}_by_discipline_group_and_status.png",
|
||||
)
|
||||
|
||||
save_grouped_bar_plot_by_discipline_group(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="median",
|
||||
statistic_function=median_value,
|
||||
title=f"Median {metric_title} by Discipline Group and Status",
|
||||
ylabel=f"Median {metric_label}",
|
||||
filename=f"median_{metric}_by_discipline_group_and_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_discipline_group_and_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
title=f"Distribution of {metric_title} by Discipline Group and Status",
|
||||
ylabel=metric_label,
|
||||
filename=f"boxplot_{metric}_by_discipline_group_and_status.png",
|
||||
)
|
||||
|
||||
|
||||
def create_distribution_plots(df: pd.DataFrame) -> None:
|
||||
save_histogram(
|
||||
df=df,
|
||||
metric="career_span",
|
||||
title="Career Span Distribution",
|
||||
xlabel="Career Span in Years",
|
||||
filename="histogram_career_span.png",
|
||||
)
|
||||
|
||||
save_histogram(
|
||||
df=df,
|
||||
metric="publication_count",
|
||||
title="Publication Count Distribution",
|
||||
xlabel="Number of Publications",
|
||||
filename="histogram_publication_count.png",
|
||||
)
|
||||
|
||||
|
||||
def create_scatter_plots(df: pd.DataFrame) -> None:
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publication Count by Status",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_status.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publication Count by Status with Outlier Labels",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_status_outliers.png",
|
||||
label_mode="outliers",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publication Count by Status with All Names",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_status_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="discipline_group",
|
||||
title="Career Span vs Publication Count by Discipline Group",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_discipline_group.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="discipline_group",
|
||||
title="Career Span vs Publication Count by Discipline Group with All Names",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_discipline_group_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="active_years",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Active Publication Years vs Publication Count by Status",
|
||||
xlabel="Active Publication Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_active_years_vs_publication_count_by_status.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="active_years",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Active Publication Years vs Publication Count by Status with All Names",
|
||||
xlabel="Active Publication Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_active_years_vs_publication_count_by_status_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publications_per_active_year",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publications per Active Year by Status",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Publications per Active Year",
|
||||
filename="scatter_career_span_vs_publications_per_active_year_by_status.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publications_per_active_year",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publications per Active Year by Status with All Names",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Publications per Active Year",
|
||||
filename="scatter_career_span_vs_publications_per_active_year_by_status_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
|
||||
def create_visualizations() -> None:
|
||||
PLOTS_DIR.mkdir(exist_ok=True)
|
||||
SUMMARY_DIR.mkdir(exist_ok=True)
|
||||
|
||||
df = prepare_data()
|
||||
|
||||
if df.empty:
|
||||
print("No data available for visualization.")
|
||||
return
|
||||
|
||||
save_summary_tables(df)
|
||||
create_status_plots(df)
|
||||
create_discipline_group_plots(df)
|
||||
create_distribution_plots(df)
|
||||
create_scatter_plots(df)
|
||||
|
||||
print(f"Visualizations saved to {PLOTS_DIR}")
|
||||
print(f"Summary tables saved to {SUMMARY_DIR}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_visualizations()
|
||||
@@ -0,0 +1,96 @@
|
||||
import json
|
||||
from typing import Any
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
|
||||
REQUEST_TIMEOUT_SECONDS = 30
|
||||
PER_PAGE = 200
|
||||
|
||||
|
||||
def normalize_author_id(author_id: str) -> str:
|
||||
"""
|
||||
Normalizes OpenAlex author IDs.
|
||||
|
||||
Supported inputs:
|
||||
- A123456789
|
||||
- https://openalex.org/A123456789
|
||||
- https://api.openalex.org/authors/A123456789
|
||||
"""
|
||||
cleaned_author_id = author_id.strip()
|
||||
|
||||
if cleaned_author_id.startswith("https://api.openalex.org/authors/"):
|
||||
return cleaned_author_id.replace(
|
||||
"https://api.openalex.org/authors/",
|
||||
"https://openalex.org/",
|
||||
)
|
||||
|
||||
if cleaned_author_id.startswith("https://openalex.org/"):
|
||||
return cleaned_author_id
|
||||
|
||||
if cleaned_author_id.startswith("A"):
|
||||
return f"https://openalex.org/{cleaned_author_id}"
|
||||
|
||||
return cleaned_author_id
|
||||
|
||||
|
||||
def fetch_openalex_page(author_id: str, cursor: str) -> dict[str, Any]:
|
||||
normalized_author_id = normalize_author_id(author_id)
|
||||
|
||||
query_params = urlencode(
|
||||
{
|
||||
"filter": f"authorships.author.id:{normalized_author_id}",
|
||||
"per-page": PER_PAGE,
|
||||
"cursor": cursor,
|
||||
"sort": "publication_year:asc",
|
||||
}
|
||||
)
|
||||
|
||||
url = f"{OPENALEX_WORKS_URL}?{query_params}"
|
||||
|
||||
request = Request(
|
||||
url,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "AIIS career stage analysis",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
|
||||
response_body = response.read().decode("utf-8")
|
||||
return json.loads(response_body)
|
||||
|
||||
except HTTPError as error:
|
||||
raise RuntimeError(
|
||||
f"OpenAlex request failed with HTTP status {error.code}: {url}"
|
||||
) from error
|
||||
|
||||
except URLError as error:
|
||||
raise RuntimeError(f"OpenAlex request failed: {error}") from error
|
||||
|
||||
|
||||
def get_all_author_works(author_id: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Fetches all works for an OpenAlex author by using cursor pagination.
|
||||
"""
|
||||
works: list[dict[str, Any]] = []
|
||||
cursor = "*"
|
||||
|
||||
while cursor:
|
||||
data = fetch_openalex_page(author_id, cursor)
|
||||
|
||||
page_results = data.get("results", [])
|
||||
works.extend(page_results)
|
||||
|
||||
meta = data.get("meta", {})
|
||||
next_cursor = meta.get("next_cursor")
|
||||
|
||||
if not next_cursor or next_cursor == cursor:
|
||||
break
|
||||
|
||||
cursor = next_cursor
|
||||
|
||||
return works
|
||||
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 81 KiB |
@@ -0,0 +1,6 @@
|
||||
discipline_group,sample_size,mean_career_span,median_career_span,mean_active_years,median_active_years,mean_publication_count,median_publication_count,mean_publications_per_active_year,median_publications_per_active_year,mean_publications_per_career_year,median_publications_per_career_year,mean_years_since_last_publication,median_years_since_last_publication
|
||||
Biology,10,44.5,35.0,23.0,23.5,184.5,138.5,6.410136743886744,6.833333333333333,4.342828101969518,2.8414179104477615,0.7,0.0
|
||||
Computer Science,22,24.90909090909091,18.5,17.136363636363637,17.5,115.54545454545455,106.0,5.194674030118668,4.390697674418605,4.383304699676206,3.1192307692307693,0.4090909090909091,0.0
|
||||
Engineering,6,20.166666666666668,15.0,17.833333333333332,13.5,124.16666666666667,74.5,4.5022556390977435,3.6357142857142857,4.054259702286018,3.2033492822966507,1.6666666666666667,1.0
|
||||
Medicine,12,37.916666666666664,26.5,23.0,21.5,343.6666666666667,188.5,10.699183227664198,8.416666666666666,7.862918672933688,6.795662100456621,0.25,0.0
|
||||
Sociology,10,21.8,23.0,13.9,15.0,55.2,35.0,3.0017820858310875,3.0277777777777777,2.245860377439325,2.206815114709852,1.2,0.5
|
||||
|
@@ -0,0 +1,11 @@
|
||||
discipline_group,known_status,sample_size,mean_career_span,median_career_span,mean_active_years,median_active_years,mean_publication_count,median_publication_count,mean_publications_per_active_year,median_publications_per_active_year,mean_publications_per_career_year,median_publications_per_career_year,mean_years_since_last_publication,median_years_since_last_publication
|
||||
Biology,Professor,5,62.8,58.0,33.4,35.0,303.4,332.0,8.856940154440155,9.485714285714286,5.944422997812213,5.442622950819672,0.4,0.0
|
||||
Biology,Researcher,5,26.2,22.0,12.6,15.0,65.6,36.0,3.9633333333333334,2.4,2.741233206126823,2.021276595744681,1.0,0.0
|
||||
Computer Science,Professor,11,39.72727272727273,31.0,25.90909090909091,22.0,203.8181818181818,202.0,8.05960497723338,7.214285714285714,6.804834459316603,6.470588235294118,0.18181818181818182,0.0
|
||||
Computer Science,Researcher,11,10.090909090909092,6.0,8.363636363636363,5.0,27.272727272727273,11.0,2.3297430830039527,2.2,1.96177494003581,1.5,0.6363636363636364,0.0
|
||||
Engineering,Professor,3,33.0,38.0,30.666666666666668,35.0,241.33333333333334,202.0,7.704511278195487,7.2105263157894735,7.230994152046783,7.2105263157894735,0.0,0.0
|
||||
Engineering,Researcher,3,7.333333333333333,8.0,5.0,5.0,7.0,7.0,1.3,1.4,0.8775252525252525,0.875,3.3333333333333335,3.0
|
||||
Medicine,Professor,7,56.714285714285715,30.0,34.285714285714285,29.0,572.7142857142857,615.0,16.225810703206655,16.253968253968253,11.606273280584732,8.76530612244898,0.14285714285714285,0.0
|
||||
Medicine,Researcher,5,11.6,7.0,7.2,7.0,23.0,21.0,2.961904761904762,3.0,2.6222222222222222,3.0,0.4,0.0
|
||||
Sociology,Professor,5,32.0,27.0,22.6,22.0,101.8,106.0,4.393564171662176,4.517241379310345,3.3512445644024593,3.55,0.4,0.0
|
||||
Sociology,Researcher,5,11.6,6.0,5.2,5.0,8.6,9.0,1.61,1.25,1.1404761904761904,0.5,2.0,1.0
|
||||
|
@@ -0,0 +1,3 @@
|
||||
known_status,sample_size,mean_career_span,median_career_span,mean_active_years,median_active_years,mean_publication_count,median_publication_count,mean_publications_per_active_year,median_publications_per_active_year,mean_publications_per_career_year,median_publications_per_career_year,mean_years_since_last_publication,median_years_since_last_publication
|
||||
Professor,31,45.38709677419355,31.0,28.93548387096774,28.0,290.35483870967744,224.0,9.40652855281006,7.611111111111111,7.234464912380307,6.172413793103448,0.22580645161290322,0.0
|
||||
Researcher,29,13.10344827586207,7.0,8.0,5.0,27.82758620689655,11.0,2.4897711858356537,1.8,1.9562675238653737,1.5,1.1724137931034482,0.0
|
||||
|
@@ -0,0 +1,188 @@
|
||||
{
|
||||
"summary": {
|
||||
"created_at": "2026-07-17T07:28:53.584386Z",
|
||||
"index": "work-classifications",
|
||||
"read_only": true,
|
||||
"expected_count": null,
|
||||
"documents": 16003,
|
||||
"initial_count": 16003,
|
||||
"final_count": 16003,
|
||||
"count_consistent": true,
|
||||
"expected_count_matches": true,
|
||||
"index_integrity_valid": true
|
||||
},
|
||||
"mapping": {
|
||||
"valid": true,
|
||||
"error_count": 0,
|
||||
"errors": []
|
||||
},
|
||||
"documents": {
|
||||
"schema_valid": 16003,
|
||||
"schema_invalid": 0,
|
||||
"field_order_valid": 16003,
|
||||
"field_order_invalid": 0,
|
||||
"unique_work_ids": 16003,
|
||||
"duplicate_work_id_count": 0,
|
||||
"duplicate_work_ids": {},
|
||||
"schema_error_counts": {},
|
||||
"field_order_error_counts": {}
|
||||
},
|
||||
"classification": {
|
||||
"categories": {
|
||||
"basic_research": {
|
||||
"count": 7620,
|
||||
"percentage": 47.62
|
||||
},
|
||||
"applied_research": {
|
||||
"count": 6407,
|
||||
"percentage": 40.04
|
||||
},
|
||||
"experimental_development": {
|
||||
"count": 1122,
|
||||
"percentage": 7.01
|
||||
},
|
||||
"non_research": {
|
||||
"count": 854,
|
||||
"percentage": 5.34
|
||||
}
|
||||
},
|
||||
"quadrants": {
|
||||
"pure_applied": {
|
||||
"count": 7510,
|
||||
"percentage": 46.93
|
||||
},
|
||||
"use_inspired_basic": {
|
||||
"count": 4964,
|
||||
"percentage": 31.02
|
||||
},
|
||||
"pure_basic": {
|
||||
"count": 2667,
|
||||
"percentage": 16.67
|
||||
},
|
||||
"not_applicable": {
|
||||
"count": 862,
|
||||
"percentage": 5.39
|
||||
}
|
||||
},
|
||||
"confidence": {
|
||||
"high": {
|
||||
"count": 10426,
|
||||
"percentage": 65.15
|
||||
},
|
||||
"medium": {
|
||||
"count": 5525,
|
||||
"percentage": 34.52
|
||||
},
|
||||
"low": {
|
||||
"count": 52,
|
||||
"percentage": 0.32
|
||||
}
|
||||
},
|
||||
"insufficient_context": {
|
||||
"false": {
|
||||
"count": 15004,
|
||||
"percentage": 93.76
|
||||
},
|
||||
"true": {
|
||||
"count": 999,
|
||||
"percentage": 6.24
|
||||
}
|
||||
},
|
||||
"signals_used": {
|
||||
"title": 15807,
|
||||
"topics": 15804,
|
||||
"work_type": 14791,
|
||||
"venue": 13160,
|
||||
"abstract": 10017,
|
||||
"funders": 3812,
|
||||
"language": 666,
|
||||
"year": 22
|
||||
},
|
||||
"applied_orientation_score": {
|
||||
"overall": {
|
||||
"count": 15149,
|
||||
"min": 10.0,
|
||||
"max": 92.0,
|
||||
"mean": 48.01,
|
||||
"median": 40.0
|
||||
},
|
||||
"by_category": {
|
||||
"applied_research": {
|
||||
"count": 6407,
|
||||
"min": 35.0,
|
||||
"max": 90.0,
|
||||
"mean": 67.39,
|
||||
"median": 70.0
|
||||
},
|
||||
"basic_research": {
|
||||
"count": 7620,
|
||||
"min": 10.0,
|
||||
"max": 55.0,
|
||||
"mean": 26.71,
|
||||
"median": 30.0
|
||||
},
|
||||
"experimental_development": {
|
||||
"count": 1122,
|
||||
"min": 60.0,
|
||||
"max": 92.0,
|
||||
"mean": 81.97,
|
||||
"median": 80.0
|
||||
},
|
||||
"non_research": {
|
||||
"count": 0,
|
||||
"min": null,
|
||||
"max": null,
|
||||
"mean": null,
|
||||
"median": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"current_rule_consistency": {
|
||||
"consistent": 16003,
|
||||
"inconsistent": 0,
|
||||
"consistent_percentage": 100.0,
|
||||
"error_counts": {}
|
||||
},
|
||||
"stored_validation": {
|
||||
"states": {
|
||||
"valid": 14726,
|
||||
"invalid": 1277
|
||||
},
|
||||
"valid_state_consistent_with_error_list": 16003,
|
||||
"valid_state_inconsistent_with_error_list": 0,
|
||||
"error_occurrences": 1278,
|
||||
"error_counts": {
|
||||
"applied_research_score_outside_expected_range": 1155,
|
||||
"basic_research_quadrant_score_mismatch": 102,
|
||||
"applied_research_quadrant_mismatch": 13,
|
||||
"experimental_development_quadrant_mismatch": 6,
|
||||
"basic_research_quadrant_mismatch": 1,
|
||||
"experimental_development_score_outside_expected_range": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"missing_title": 10,
|
||||
"missing_doi": 1501,
|
||||
"missing_publication_year": 0,
|
||||
"empty_authors": 0,
|
||||
"empty_institutions": 3017,
|
||||
"empty_topics": 50,
|
||||
"publication_year": {
|
||||
"min": 1950,
|
||||
"max": 2026
|
||||
},
|
||||
"classified_at": {
|
||||
"min": "2026-07-10T18:42:03Z",
|
||||
"max": "2026-07-17T06:38:43Z"
|
||||
}
|
||||
},
|
||||
"provenance": {
|
||||
"models": {
|
||||
"gemma4-e4b": 16003
|
||||
},
|
||||
"prompt_versions": {
|
||||
"frascati_v1": 16003
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic"
|
||||
ES_API_KEY = "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
|
||||
TARGET_INDEX = "work-classifications"
|
||||
WORKS_INDEX = "openalex-works*"
|
||||
WORK_YEAR_GTE = 1950
|
||||
|
||||
DEFAULT_AUTHORS_FILE = ROOT / "ude_authors_set.jsonl"
|
||||
DEFAULT_OUTPUT_DIR = ROOT / "evaluation"
|
||||
|
||||
REQUEST_TIMEOUT = 120.0
|
||||
SEARCH_PAGE_SIZE = 1000
|
||||
SCROLL_KEEP_ALIVE = "5m"
|
||||
SAMPLE_SIZE = 100
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
return (
|
||||
datetime.now(timezone.utc)
|
||||
.isoformat()
|
||||
.replace(
|
||||
"+00:00",
|
||||
"Z",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def timestamp() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
|
||||
|
||||
def auth_header() -> str:
|
||||
value = ES_API_KEY.strip()
|
||||
|
||||
if not value:
|
||||
raise RuntimeError("ES_API_KEY is empty.")
|
||||
|
||||
if value.startswith("ApiKey "):
|
||||
return value
|
||||
|
||||
return f"ApiKey {value}"
|
||||
|
||||
|
||||
def normalize_openalex_id(
|
||||
value: Any,
|
||||
prefix: str,
|
||||
) -> str | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
|
||||
candidate = value.strip().rstrip("/")
|
||||
if not candidate:
|
||||
return None
|
||||
|
||||
short_id = candidate.rsplit("/", 1)[-1].upper()
|
||||
|
||||
if not short_id.startswith(prefix):
|
||||
return None
|
||||
|
||||
suffix = short_id[len(prefix) :]
|
||||
if not suffix.isdigit():
|
||||
return None
|
||||
|
||||
return f"https://openalex.org/{short_id}"
|
||||
|
||||
|
||||
def normalize_author_id(
|
||||
value: Any,
|
||||
) -> str | None:
|
||||
return normalize_openalex_id(
|
||||
value,
|
||||
"A",
|
||||
)
|
||||
|
||||
|
||||
def normalize_work_id(
|
||||
value: Any,
|
||||
) -> str | None:
|
||||
return normalize_openalex_id(
|
||||
value,
|
||||
"W",
|
||||
)
|
||||
|
||||
|
||||
def unwrap(
|
||||
record: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
for key in (
|
||||
"_source",
|
||||
"source",
|
||||
):
|
||||
nested = record.get(key)
|
||||
if isinstance(nested, dict):
|
||||
return nested
|
||||
|
||||
return record
|
||||
|
||||
|
||||
def iter_jsonl(
|
||||
path: Path,
|
||||
) -> Iterable[tuple[int, dict[str, Any]]]:
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"File not found: {path}")
|
||||
|
||||
with path.open(
|
||||
"r",
|
||||
encoding="utf-8-sig",
|
||||
) as handle:
|
||||
for line_number, raw_line in enumerate(
|
||||
handle,
|
||||
start=1,
|
||||
):
|
||||
line = raw_line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
value = json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(
|
||||
f"Invalid JSON at {path}:{line_number}: {exc}"
|
||||
) from exc
|
||||
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f"Expected a JSON object at {path}:{line_number}.")
|
||||
|
||||
yield line_number, value
|
||||
|
||||
|
||||
def extract_author(
|
||||
record: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
source = unwrap(record)
|
||||
|
||||
ids = source.get("ids") if isinstance(source.get("ids"), dict) else {}
|
||||
|
||||
author_id = (
|
||||
normalize_author_id(source.get("id"))
|
||||
or normalize_author_id(ids.get("openalex"))
|
||||
or normalize_author_id(record.get("_id"))
|
||||
)
|
||||
|
||||
if author_id is None:
|
||||
raise ValueError("Author record has no valid OpenAlex ID.")
|
||||
|
||||
display_name = source.get("display_name")
|
||||
if not isinstance(display_name, str):
|
||||
display_name = None
|
||||
|
||||
return {
|
||||
"author_id": author_id,
|
||||
"display_name": display_name,
|
||||
}
|
||||
|
||||
|
||||
def load_authors(
|
||||
path: Path,
|
||||
) -> tuple[dict[str, dict[str, Any]], int]:
|
||||
authors: dict[str, dict[str, Any]] = {}
|
||||
duplicate_records = 0
|
||||
|
||||
for line_number, record in iter_jsonl(path):
|
||||
try:
|
||||
author = extract_author(record)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{path}:{line_number}: {exc}") from exc
|
||||
|
||||
author_id = author["author_id"]
|
||||
|
||||
if author_id in authors:
|
||||
duplicate_records += 1
|
||||
|
||||
if (
|
||||
authors[author_id].get("display_name") is None
|
||||
and author.get("display_name") is not None
|
||||
):
|
||||
authors[author_id]["display_name"] = author["display_name"]
|
||||
continue
|
||||
|
||||
authors[author_id] = author
|
||||
|
||||
if not authors:
|
||||
raise RuntimeError(f"No authors were loaded from {path}.")
|
||||
|
||||
return authors, duplicate_records
|
||||
|
||||
|
||||
def extract_authorship_author_ids(
|
||||
source: dict[str, Any],
|
||||
) -> set[str]:
|
||||
result: set[str] = set()
|
||||
authorships = source.get("authorships")
|
||||
|
||||
if not isinstance(authorships, list):
|
||||
return result
|
||||
|
||||
for authorship in authorships:
|
||||
if not isinstance(authorship, dict):
|
||||
continue
|
||||
|
||||
author = authorship.get("author")
|
||||
if not isinstance(author, dict):
|
||||
continue
|
||||
|
||||
author_id = normalize_author_id(author.get("id"))
|
||||
if author_id is not None:
|
||||
result.add(author_id)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class ElasticsearchClient:
|
||||
def __init__(self) -> None:
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update(
|
||||
{
|
||||
"Authorization": auth_header(),
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
)
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
body: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
response = self.session.request(
|
||||
method,
|
||||
(f"{ES_BASE_URL.rstrip('/')}/{path.lstrip('/')}"),
|
||||
json=body,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(
|
||||
f"Elasticsearch {response.status_code} "
|
||||
f"{method} {path}\n"
|
||||
f"{response.text[:4000]}"
|
||||
)
|
||||
|
||||
payload = response.json()
|
||||
if not isinstance(payload, dict):
|
||||
raise RuntimeError("Elasticsearch returned invalid JSON.")
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
def index_count(
|
||||
client: ElasticsearchClient,
|
||||
index: str,
|
||||
) -> int:
|
||||
payload = client.request(
|
||||
"GET",
|
||||
f"{index}/_count",
|
||||
)
|
||||
count = payload.get("count")
|
||||
|
||||
if not isinstance(count, int):
|
||||
raise RuntimeError(f"Could not read count for index {index}.")
|
||||
|
||||
return count
|
||||
|
||||
|
||||
def total_hits_value(
|
||||
value: Any,
|
||||
) -> int:
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
|
||||
if isinstance(value, dict):
|
||||
nested = value.get("value")
|
||||
if isinstance(nested, int):
|
||||
return nested
|
||||
|
||||
raise RuntimeError("Could not read Elasticsearch total hits.")
|
||||
|
||||
|
||||
def scan_scroll(
|
||||
client: ElasticsearchClient,
|
||||
index: str,
|
||||
body: dict[str, Any],
|
||||
label: str,
|
||||
handle_hit: Callable[[dict[str, Any]], None],
|
||||
) -> dict[str, int]:
|
||||
scroll_id: str | None = None
|
||||
fetched = 0
|
||||
reported_total: int | None = None
|
||||
|
||||
request_body = dict(body)
|
||||
request_body["size"] = SEARCH_PAGE_SIZE
|
||||
request_body["track_total_hits"] = True
|
||||
request_body["sort"] = ["_doc"]
|
||||
|
||||
try:
|
||||
response = client.request(
|
||||
"POST",
|
||||
(f"{index}/_search?scroll={SCROLL_KEEP_ALIVE}"),
|
||||
request_body,
|
||||
)
|
||||
|
||||
while True:
|
||||
current_scroll_id = response.get("_scroll_id")
|
||||
if isinstance(current_scroll_id, str) and current_scroll_id:
|
||||
scroll_id = current_scroll_id
|
||||
|
||||
hits_block = response.get("hits")
|
||||
if not isinstance(hits_block, dict):
|
||||
raise RuntimeError("Search response has no hits object.")
|
||||
|
||||
if reported_total is None:
|
||||
reported_total = total_hits_value(hits_block.get("total"))
|
||||
|
||||
hits = hits_block.get("hits")
|
||||
if not isinstance(hits, list):
|
||||
raise RuntimeError("Search response has no hits list.")
|
||||
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
if not isinstance(hit, dict):
|
||||
raise RuntimeError("Search returned an invalid hit.")
|
||||
|
||||
handle_hit(hit)
|
||||
|
||||
fetched += len(hits)
|
||||
|
||||
print(f"{label}: {fetched}/{reported_total}")
|
||||
|
||||
if scroll_id is None:
|
||||
raise RuntimeError("Elasticsearch did not return a scroll ID.")
|
||||
|
||||
response = client.request(
|
||||
"POST",
|
||||
"_search/scroll",
|
||||
{
|
||||
"scroll": SCROLL_KEEP_ALIVE,
|
||||
"scroll_id": scroll_id,
|
||||
},
|
||||
)
|
||||
|
||||
finally:
|
||||
if scroll_id is not None:
|
||||
try:
|
||||
client.request(
|
||||
"DELETE",
|
||||
"_search/scroll",
|
||||
{"scroll_id": [scroll_id]},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f"Warning: could not clear Elasticsearch scroll context: {exc}")
|
||||
|
||||
if reported_total is None:
|
||||
raise RuntimeError(f"{label}: no total hit count was returned.")
|
||||
|
||||
if fetched != reported_total:
|
||||
raise RuntimeError(
|
||||
f"{label}: fetched {fetched} hits, "
|
||||
f"but Elasticsearch reported "
|
||||
f"{reported_total}."
|
||||
)
|
||||
|
||||
return {
|
||||
"reported_total": reported_total,
|
||||
"fetched": fetched,
|
||||
}
|
||||
|
||||
|
||||
def fetch_classified_work_ids(
|
||||
client: ElasticsearchClient,
|
||||
) -> tuple[
|
||||
int,
|
||||
int,
|
||||
set[str],
|
||||
int,
|
||||
]:
|
||||
initial_count = index_count(
|
||||
client,
|
||||
TARGET_INDEX,
|
||||
)
|
||||
|
||||
classified_work_ids: set[str] = set()
|
||||
|
||||
def handle_hit(
|
||||
hit: dict[str, Any],
|
||||
) -> None:
|
||||
source = hit.get("_source")
|
||||
es_id = hit.get("_id")
|
||||
|
||||
work_id = (
|
||||
normalize_work_id(source.get("work_id"))
|
||||
if isinstance(source, dict)
|
||||
else None
|
||||
) or normalize_work_id(es_id)
|
||||
|
||||
if work_id is None:
|
||||
raise RuntimeError(f"Invalid work ID in target index: {es_id}")
|
||||
|
||||
classified_work_ids.add(work_id)
|
||||
|
||||
stats = scan_scroll(
|
||||
client=client,
|
||||
index=TARGET_INDEX,
|
||||
body={
|
||||
"_source": ["work_id"],
|
||||
"query": {"match_all": {}},
|
||||
},
|
||||
label="Target index",
|
||||
handle_hit=handle_hit,
|
||||
)
|
||||
|
||||
final_count = index_count(
|
||||
client,
|
||||
TARGET_INDEX,
|
||||
)
|
||||
|
||||
if stats["reported_total"] != initial_count:
|
||||
raise RuntimeError(
|
||||
f"The target index changed before the scroll "
|
||||
f"snapshot was opened: count={initial_count}, "
|
||||
f"snapshot={stats['reported_total']}."
|
||||
)
|
||||
|
||||
if len(classified_work_ids) != stats["fetched"]:
|
||||
raise RuntimeError(
|
||||
f"The target index contains "
|
||||
f"{stats['fetched']} documents but only "
|
||||
f"{len(classified_work_ids)} unique work IDs."
|
||||
)
|
||||
|
||||
return (
|
||||
initial_count,
|
||||
final_count,
|
||||
classified_work_ids,
|
||||
stats["fetched"],
|
||||
)
|
||||
|
||||
|
||||
def source_work_query(
|
||||
author_ids: list[str],
|
||||
work_year_gte: int,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"_source": [
|
||||
"id",
|
||||
"updated_date",
|
||||
"authorships.author.id",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": work_year_gte}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": (author_ids)}},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def candidate_is_better(
|
||||
current: dict[str, Any],
|
||||
candidate: dict[str, Any],
|
||||
) -> bool:
|
||||
current_index = current.get("index")
|
||||
candidate_index = candidate.get("index")
|
||||
|
||||
if candidate_index == "openalex-works" and current_index != "openalex-works":
|
||||
return True
|
||||
|
||||
if current_index == "openalex-works" and candidate_index != "openalex-works":
|
||||
return False
|
||||
|
||||
current_updated = current.get("updated_date")
|
||||
candidate_updated = candidate.get("updated_date")
|
||||
|
||||
return isinstance(candidate_updated, str) and (
|
||||
not isinstance(current_updated, str) or candidate_updated > current_updated
|
||||
)
|
||||
|
||||
|
||||
def fetch_source_works(
|
||||
client: ElasticsearchClient,
|
||||
author_ids: set[str],
|
||||
work_year_gte: int,
|
||||
) -> tuple[
|
||||
dict[str, dict[str, Any]],
|
||||
dict[str, Any],
|
||||
]:
|
||||
selected_works: dict[str, dict[str, Any]] = {}
|
||||
|
||||
invalid_work_id_count = 0
|
||||
invalid_work_id_samples: list[str] = []
|
||||
no_listed_author_count = 0
|
||||
no_listed_author_samples: list[str] = []
|
||||
|
||||
def handle_hit(
|
||||
hit: dict[str, Any],
|
||||
) -> None:
|
||||
nonlocal invalid_work_id_count
|
||||
nonlocal no_listed_author_count
|
||||
|
||||
source = hit.get("_source")
|
||||
if not isinstance(source, dict):
|
||||
raise RuntimeError("A source work hit has no valid _source.")
|
||||
|
||||
work_id = normalize_work_id(source.get("id")) or normalize_work_id(
|
||||
hit.get("_id")
|
||||
)
|
||||
|
||||
if work_id is None:
|
||||
invalid_work_id_count += 1
|
||||
if len(invalid_work_id_samples) < SAMPLE_SIZE:
|
||||
invalid_work_id_samples.append(str(hit.get("_id")))
|
||||
return
|
||||
|
||||
work_author_ids = extract_authorship_author_ids(source)
|
||||
relevant_author_ids = work_author_ids & author_ids
|
||||
|
||||
if not relevant_author_ids:
|
||||
no_listed_author_count += 1
|
||||
if len(no_listed_author_samples) < SAMPLE_SIZE:
|
||||
no_listed_author_samples.append(work_id)
|
||||
return
|
||||
|
||||
candidate = {
|
||||
"index": hit.get("_index"),
|
||||
"updated_date": source.get("updated_date"),
|
||||
"author_ids": relevant_author_ids,
|
||||
}
|
||||
|
||||
current = selected_works.get(work_id)
|
||||
|
||||
if current is None or candidate_is_better(
|
||||
current,
|
||||
candidate,
|
||||
):
|
||||
selected_works[work_id] = candidate
|
||||
|
||||
stats = scan_scroll(
|
||||
client=client,
|
||||
index=WORKS_INDEX,
|
||||
body=source_work_query(
|
||||
sorted(author_ids),
|
||||
work_year_gte,
|
||||
),
|
||||
label="OpenAlex works",
|
||||
handle_hit=handle_hit,
|
||||
)
|
||||
|
||||
data_quality = {
|
||||
"source_raw_hits": stats["fetched"],
|
||||
"source_unique_works": len(selected_works),
|
||||
"source_duplicate_documents": (
|
||||
stats["fetched"]
|
||||
- len(selected_works)
|
||||
- invalid_work_id_count
|
||||
- no_listed_author_count
|
||||
),
|
||||
"source_invalid_work_ids": (invalid_work_id_count),
|
||||
"source_invalid_work_id_samples": (invalid_work_id_samples),
|
||||
"source_hits_without_listed_ude_author": (no_listed_author_count),
|
||||
"source_hits_without_listed_ude_author_samples": (no_listed_author_samples),
|
||||
}
|
||||
|
||||
return selected_works, data_quality
|
||||
|
||||
|
||||
def coverage_status(
|
||||
total: int,
|
||||
classified: int,
|
||||
) -> str:
|
||||
if total == 0:
|
||||
return "no_works"
|
||||
|
||||
if classified == 0:
|
||||
return "not_started"
|
||||
|
||||
if classified == total:
|
||||
return "complete"
|
||||
|
||||
return "partial"
|
||||
|
||||
|
||||
def author_sort_key(
|
||||
item: dict[str, Any],
|
||||
) -> tuple[Any, ...]:
|
||||
total = item["total_works"]
|
||||
classified = item["classified_works"]
|
||||
|
||||
coverage = classified / total if total > 0 else None
|
||||
|
||||
return (
|
||||
coverage is None,
|
||||
-coverage if coverage is not None else 0.0,
|
||||
-total,
|
||||
-classified,
|
||||
(
|
||||
item["display_name"].casefold()
|
||||
if isinstance(
|
||||
item["display_name"],
|
||||
str,
|
||||
)
|
||||
else ""
|
||||
),
|
||||
item["author_id"],
|
||||
)
|
||||
|
||||
|
||||
def build_report(
|
||||
*,
|
||||
authors_path: Path,
|
||||
authors: dict[str, dict[str, Any]],
|
||||
duplicate_author_records: int,
|
||||
initial_target_count: int,
|
||||
final_target_count: int,
|
||||
classified_work_ids: set[str],
|
||||
target_documents_scanned: int,
|
||||
selected_works: dict[str, dict[str, Any]],
|
||||
source_quality: dict[str, Any],
|
||||
work_year_gte: int,
|
||||
) -> dict[str, Any]:
|
||||
total_counts: Counter[str] = Counter()
|
||||
classified_counts: Counter[str] = Counter()
|
||||
|
||||
classified_source_work_ids: set[str] = set()
|
||||
|
||||
for work_id, work in selected_works.items():
|
||||
work_author_ids = work["author_ids"]
|
||||
is_classified = work_id in classified_work_ids
|
||||
|
||||
for author_id in work_author_ids:
|
||||
total_counts[author_id] += 1
|
||||
|
||||
if is_classified:
|
||||
classified_counts[author_id] += 1
|
||||
|
||||
if is_classified:
|
||||
classified_source_work_ids.add(work_id)
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
status_counts: Counter[str] = Counter()
|
||||
|
||||
author_work_assignments_total = 0
|
||||
author_work_assignments_classified = 0
|
||||
|
||||
for author_id, author in authors.items():
|
||||
total = total_counts.get(
|
||||
author_id,
|
||||
0,
|
||||
)
|
||||
classified = classified_counts.get(
|
||||
author_id,
|
||||
0,
|
||||
)
|
||||
unclassified = total - classified
|
||||
|
||||
coverage = classified / total if total > 0 else None
|
||||
|
||||
status = coverage_status(
|
||||
total,
|
||||
classified,
|
||||
)
|
||||
status_counts[status] += 1
|
||||
|
||||
author_work_assignments_total += total
|
||||
author_work_assignments_classified += classified
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"author_id": author_id,
|
||||
"display_name": author["display_name"],
|
||||
"total_works": total,
|
||||
"classified_works": classified,
|
||||
"unclassified_works": (unclassified),
|
||||
"coverage_percent": (
|
||||
round(
|
||||
coverage * 100.0,
|
||||
2,
|
||||
)
|
||||
if coverage is not None
|
||||
else None
|
||||
),
|
||||
"coverage_status": status,
|
||||
}
|
||||
)
|
||||
|
||||
rows.sort(key=author_sort_key)
|
||||
|
||||
unique_work_coverage = (
|
||||
len(classified_source_work_ids) / len(selected_works)
|
||||
if selected_works
|
||||
else None
|
||||
)
|
||||
|
||||
assignment_coverage = (
|
||||
author_work_assignments_classified / author_work_assignments_total
|
||||
if author_work_assignments_total
|
||||
else None
|
||||
)
|
||||
|
||||
target_outside_source = classified_work_ids - set(selected_works)
|
||||
|
||||
return {
|
||||
"summary": {
|
||||
"created_at": utc_now(),
|
||||
"target_index": TARGET_INDEX,
|
||||
"works_index": WORKS_INDEX,
|
||||
"work_year_gte": work_year_gte,
|
||||
"authors_file": str(authors_path.resolve()),
|
||||
"authors_total": len(authors),
|
||||
"source_unique_works": len(selected_works),
|
||||
"target_index_documents": len(classified_work_ids),
|
||||
"target_index_initial_count": (initial_target_count),
|
||||
"target_index_final_count": (final_target_count),
|
||||
"target_index_count_consistent": (
|
||||
initial_target_count
|
||||
== final_target_count
|
||||
== target_documents_scanned
|
||||
== len(classified_work_ids)
|
||||
),
|
||||
"classified_source_works": len(classified_source_work_ids),
|
||||
"unclassified_source_works": (
|
||||
len(selected_works) - len(classified_source_work_ids)
|
||||
),
|
||||
"unique_work_coverage_percent": (
|
||||
round(
|
||||
unique_work_coverage * 100.0,
|
||||
2,
|
||||
)
|
||||
if unique_work_coverage is not None
|
||||
else None
|
||||
),
|
||||
"author_work_assignments_total": (author_work_assignments_total),
|
||||
"author_work_assignments_classified": (author_work_assignments_classified),
|
||||
"author_work_assignment_coverage_percent": (
|
||||
round(
|
||||
assignment_coverage * 100.0,
|
||||
2,
|
||||
)
|
||||
if assignment_coverage is not None
|
||||
else None
|
||||
),
|
||||
"authors_by_status": {
|
||||
"complete": status_counts["complete"],
|
||||
"partial": status_counts["partial"],
|
||||
"not_started": status_counts["not_started"],
|
||||
"no_works": status_counts["no_works"],
|
||||
},
|
||||
},
|
||||
"data_quality": {
|
||||
"duplicate_author_records": (duplicate_author_records),
|
||||
**source_quality,
|
||||
"target_documents_outside_source_work_set": (len(target_outside_source)),
|
||||
"target_documents_outside_source_work_set_samples": (
|
||||
sorted(target_outside_source)[:SAMPLE_SIZE]
|
||||
),
|
||||
},
|
||||
"sorting": {
|
||||
"primary": ("coverage percentage descending"),
|
||||
"secondary": ("total_works descending"),
|
||||
"tertiary": (
|
||||
"classified_works descending, "
|
||||
"display_name ascending, "
|
||||
"author_id ascending"
|
||||
),
|
||||
"authors_with_no_works": "last",
|
||||
},
|
||||
"notes": [
|
||||
(
|
||||
"total_works is calculated directly from "
|
||||
"openalex-works* for the listed UDE authors."
|
||||
),
|
||||
(
|
||||
f"Only works with publication_year >= "
|
||||
f"{work_year_gte} are included, matching the "
|
||||
"classification pipeline."
|
||||
),
|
||||
(
|
||||
"Duplicate work documents across matching "
|
||||
"OpenAlex indices are reduced to one work ID. "
|
||||
"The openalex-works document is preferred; "
|
||||
"otherwise the newest updated_date is used."
|
||||
),
|
||||
(
|
||||
"A coauthored work is counted once for every "
|
||||
"listed UDE author on that work."
|
||||
),
|
||||
(
|
||||
"The script is read-only and does not modify "
|
||||
"Elasticsearch or the author JSONL file."
|
||||
),
|
||||
],
|
||||
"authors": rows,
|
||||
}
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Report classification coverage for every author "
|
||||
"in a UDE author JSONL list using OpenAlex works "
|
||||
"stored in Elasticsearch."
|
||||
)
|
||||
)
|
||||
parser.add_argument(
|
||||
"--authors",
|
||||
type=Path,
|
||||
default=DEFAULT_AUTHORS_FILE,
|
||||
help=("Path to ude_authors_set.jsonl."),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--work-year-gte",
|
||||
type=int,
|
||||
default=WORK_YEAR_GTE,
|
||||
help=("Minimum publication year included in total_works."),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
type=Path,
|
||||
default=None,
|
||||
help=("Optional output JSON path."),
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
|
||||
authors_path = args.authors.resolve()
|
||||
output_path = (
|
||||
args.output.resolve()
|
||||
if args.output is not None
|
||||
else (
|
||||
DEFAULT_OUTPUT_DIR
|
||||
/ (f"ude_author_classification_coverage_{timestamp()}.json")
|
||||
).resolve()
|
||||
)
|
||||
|
||||
authors, duplicate_author_records = load_authors(authors_path)
|
||||
author_ids = set(authors)
|
||||
|
||||
print(f"UDE authors loaded: {len(authors)}")
|
||||
|
||||
client = ElasticsearchClient()
|
||||
|
||||
(
|
||||
initial_target_count,
|
||||
final_target_count,
|
||||
classified_work_ids,
|
||||
target_documents_scanned,
|
||||
) = fetch_classified_work_ids(client)
|
||||
|
||||
print(f"Unique classified work IDs: {len(classified_work_ids)}")
|
||||
|
||||
selected_works, source_quality = fetch_source_works(
|
||||
client=client,
|
||||
author_ids=author_ids,
|
||||
work_year_gte=args.work_year_gte,
|
||||
)
|
||||
|
||||
print(f"Unique source works: {len(selected_works)}")
|
||||
|
||||
report = build_report(
|
||||
authors_path=authors_path,
|
||||
authors=authors,
|
||||
duplicate_author_records=(duplicate_author_records),
|
||||
initial_target_count=(initial_target_count),
|
||||
final_target_count=(final_target_count),
|
||||
classified_work_ids=(classified_work_ids),
|
||||
target_documents_scanned=(target_documents_scanned),
|
||||
selected_works=selected_works,
|
||||
source_quality=source_quality,
|
||||
work_year_gte=args.work_year_gte,
|
||||
)
|
||||
|
||||
output_path.parent.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True,
|
||||
)
|
||||
output_path.write_text(
|
||||
json.dumps(
|
||||
report,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
summary = report["summary"]
|
||||
statuses = summary["authors_by_status"]
|
||||
|
||||
print(f"Classified source works: {summary['classified_source_works']}")
|
||||
print(f"Unique work coverage: {summary['unique_work_coverage_percent']}%")
|
||||
print(
|
||||
"Authors complete/partial/not started/no works: "
|
||||
f"{statuses['complete']}/"
|
||||
f"{statuses['partial']}/"
|
||||
f"{statuses['not_started']}/"
|
||||
f"{statuses['no_works']}"
|
||||
)
|
||||
print(f"Output: {output_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"run_id": "20260717_005426_057540",
|
||||
"started_at": "2026-07-17T00:54:26Z",
|
||||
"finished_at": "2026-07-17T00:54:57Z",
|
||||
"duration_seconds": 31.063,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 2,
|
||||
"workers": 1,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 2,
|
||||
"valid": 2,
|
||||
"invalid": 0,
|
||||
"categories": {
|
||||
"basic_research": 2
|
||||
},
|
||||
"validation_errors": {}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 2,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 6351,
|
||||
"cached_prompt_tokens": 5824,
|
||||
"uncached_prompt_tokens": 527,
|
||||
"completion_tokens": 1707,
|
||||
"real_total_usage": 2234
|
||||
},
|
||||
"throughput_indexed_per_hour": 231.79,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 391,
|
||||
"pending": 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"run_id": "20260717_005603_805495",
|
||||
"started_at": "2026-07-17T00:56:03Z",
|
||||
"finished_at": "2026-07-17T01:12:01Z",
|
||||
"duration_seconds": 958.094,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 20,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 927,
|
||||
"invalid": 73,
|
||||
"categories": {
|
||||
"basic_research": 562,
|
||||
"applied_research": 340,
|
||||
"experimental_development": 67,
|
||||
"non_research": 31
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 60,
|
||||
"basic_research_quadrant_score_mismatch": 12,
|
||||
"applied_research_quadrant_mismatch": 1
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3240183,
|
||||
"cached_prompt_tokens": 2912992,
|
||||
"uncached_prompt_tokens": 327191,
|
||||
"completion_tokens": 839984,
|
||||
"real_total_usage": 1167175
|
||||
},
|
||||
"throughput_indexed_per_hour": 3757.46,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 1392,
|
||||
"pending": 191
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"run_id": "20260717_011548_698699",
|
||||
"started_at": "2026-07-17T01:15:48Z",
|
||||
"finished_at": "2026-07-17T01:28:58Z",
|
||||
"duration_seconds": 790.125,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 25,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 940,
|
||||
"invalid": 60,
|
||||
"categories": {
|
||||
"basic_research": 575,
|
||||
"non_research": 16,
|
||||
"applied_research": 338,
|
||||
"experimental_development": 71
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 54,
|
||||
"basic_research_quadrant_score_mismatch": 6
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3231350,
|
||||
"cached_prompt_tokens": 2913504,
|
||||
"uncached_prompt_tokens": 317846,
|
||||
"completion_tokens": 835555,
|
||||
"real_total_usage": 1153401
|
||||
},
|
||||
"throughput_indexed_per_hour": 4556.24,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 2392,
|
||||
"pending": 169
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"run_id": "20260717_013708_966462",
|
||||
"started_at": "2026-07-17T01:37:08Z",
|
||||
"finished_at": "2026-07-17T01:49:01Z",
|
||||
"duration_seconds": 712.64,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 30,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 948,
|
||||
"invalid": 52,
|
||||
"categories": {
|
||||
"applied_research": 360,
|
||||
"basic_research": 557,
|
||||
"experimental_development": 68,
|
||||
"non_research": 15
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 49,
|
||||
"basic_research_quadrant_score_mismatch": 3
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3224853,
|
||||
"cached_prompt_tokens": 2927360,
|
||||
"uncached_prompt_tokens": 297493,
|
||||
"completion_tokens": 827150,
|
||||
"real_total_usage": 1124643
|
||||
},
|
||||
"throughput_indexed_per_hour": 5051.64,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 3393,
|
||||
"pending": 150
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"run_id": "20260717_020319_001747",
|
||||
"started_at": "2026-07-17T02:03:19Z",
|
||||
"finished_at": "2026-07-17T02:14:00Z",
|
||||
"duration_seconds": 641.141,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 35,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 935,
|
||||
"invalid": 65,
|
||||
"categories": {
|
||||
"basic_research": 559,
|
||||
"non_research": 22,
|
||||
"applied_research": 342,
|
||||
"experimental_development": 77
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 58,
|
||||
"basic_research_quadrant_score_mismatch": 7
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3234874,
|
||||
"cached_prompt_tokens": 2913440,
|
||||
"uncached_prompt_tokens": 321434,
|
||||
"completion_tokens": 831117,
|
||||
"real_total_usage": 1152551
|
||||
},
|
||||
"throughput_indexed_per_hour": 5614.99,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 4393,
|
||||
"pending": 134
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"run_id": "20260717_022730_111266",
|
||||
"started_at": "2026-07-17T02:27:30Z",
|
||||
"finished_at": "2026-07-17T02:37:39Z",
|
||||
"duration_seconds": 609.859,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 1000,
|
||||
"workers": 40,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 1000,
|
||||
"valid": 915,
|
||||
"invalid": 85,
|
||||
"categories": {
|
||||
"applied_research": 382,
|
||||
"non_research": 29,
|
||||
"basic_research": 526,
|
||||
"experimental_development": 63
|
||||
},
|
||||
"validation_errors": {
|
||||
"applied_research_score_outside_expected_range": 74,
|
||||
"basic_research_quadrant_score_mismatch": 9,
|
||||
"basic_research_quadrant_mismatch": 1,
|
||||
"applied_research_quadrant_mismatch": 1
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 1000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 3247991,
|
||||
"cached_prompt_tokens": 2913120,
|
||||
"uncached_prompt_tokens": 334871,
|
||||
"completion_tokens": 835172,
|
||||
"real_total_usage": 1170043
|
||||
},
|
||||
"throughput_indexed_per_hour": 5903.0,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 5393,
|
||||
"pending": 122
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"run_id": "20260717_030100_386210",
|
||||
"started_at": "2026-07-17T03:01:00Z",
|
||||
"finished_at": "2026-07-17T06:38:43Z",
|
||||
"duration_seconds": 13062.969,
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"parameters": {
|
||||
"limit": 10000,
|
||||
"workers": 30,
|
||||
"model": "gemma4-e4b",
|
||||
"prompt_version": "frascati_v1",
|
||||
"sqlite_file": "C:\\Users\\Roman\\Desktop\\smartguide\\llm_evaluations\\basic_applied_experimental\\classification_pipeline_v2.sqlite3",
|
||||
"target_index": "work-classifications",
|
||||
"preflight_only": false
|
||||
},
|
||||
"classification": {
|
||||
"llm_completed": 10000,
|
||||
"valid": 9089,
|
||||
"invalid": 911,
|
||||
"categories": {
|
||||
"non_research": 708,
|
||||
"basic_research": 4382,
|
||||
"applied_research": 4275,
|
||||
"experimental_development": 635
|
||||
},
|
||||
"validation_errors": {
|
||||
"basic_research_quadrant_score_mismatch": 55,
|
||||
"applied_research_score_outside_expected_range": 844,
|
||||
"applied_research_quadrant_mismatch": 10,
|
||||
"experimental_development_quadrant_mismatch": 2,
|
||||
"experimental_development_score_outside_expected_range": 1
|
||||
}
|
||||
},
|
||||
"indexing": {
|
||||
"newly_indexed": 10000,
|
||||
"recovered_from_ready": 0
|
||||
},
|
||||
"token_usage": {
|
||||
"prompt_tokens": 32719632,
|
||||
"cached_prompt_tokens": 29184896,
|
||||
"uncached_prompt_tokens": 3534736,
|
||||
"completion_tokens": 8554523,
|
||||
"real_total_usage": 12089259
|
||||
},
|
||||
"throughput_indexed_per_hour": 2755.88,
|
||||
"sqlite_counts_after_run": {
|
||||
"indexed": 15402,
|
||||
"pending": 185
|
||||
}
|
||||
}
|
||||
@@ -23,18 +23,24 @@ Run tests: `./gradlew :service:test`
|
||||
Builds the `org_patents` Elasticsearch index for a given institution: fetches its
|
||||
OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee
|
||||
and/or inventor name, and reindexes. Each patent is tagged with a `match_type`
|
||||
(`institution`, `name`, or `both`, the latter being highest confidence). For common
|
||||
inventor names, a name match is only kept if the assignee is the institution itself or
|
||||
the person, to avoid pulling in unrelated patents via a shared name.
|
||||
(`institution`, `name`, or `both`, the latter being highest confidence). Every
|
||||
inventor-name match counts outright only if the assignee is the institution itself;
|
||||
everything else matched on name alone — a personal-assignee match or a third-party
|
||||
assignee (e.g. an industry partner on a co-invented patent) — only counts if the
|
||||
patent's primary IPC/CPC classification also maps to OpenAlex research topics that
|
||||
appear on the author's own profile. This applies regardless of how common the name
|
||||
looks in our local OpenAlex data — a name can appear unique there while still being
|
||||
common globally in EPO/USPTO, so a bare name match alone is never a strong enough
|
||||
signal on its own.
|
||||
|
||||
```bash
|
||||
python scripts/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
python scripts/patents/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
```
|
||||
|
||||
**Example — University of Duisburg-Essen:**
|
||||
|
||||
```bash
|
||||
python scripts/index_org_patents.py --institution-id I62318514
|
||||
python scripts/patents/index_org_patents.py --institution-id I62318514
|
||||
```
|
||||
|
||||
The OpenAlex institution ID appears in the app URL, e.g. `/institution/I62318514/overview`.
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
{
|
||||
"institution": "I62318514",
|
||||
"cohort": [
|
||||
"I62318514",
|
||||
"I4210119759",
|
||||
"I4210161917",
|
||||
"I127668822",
|
||||
"I4210090139",
|
||||
"I4210092428",
|
||||
"I4210110714",
|
||||
"I4210146441",
|
||||
"I4210154243"
|
||||
],
|
||||
"config_hash": "fd4877f30747",
|
||||
"counts": {
|
||||
"focal_authors_scored": 9474,
|
||||
"nodes": 864646,
|
||||
"edges": 5822006,
|
||||
"works_used": 228103,
|
||||
"works_capped": 9238,
|
||||
"tags": {
|
||||
"mentor": 161,
|
||||
"bridger": 133,
|
||||
"amplifier": 10
|
||||
},
|
||||
"suspicious_profiles": 400,
|
||||
"es_docs_written": 9474,
|
||||
"es_network_docs_written": 9474
|
||||
},
|
||||
"timings": {
|
||||
"extract_s": 0.6,
|
||||
"load_cache_s": 18.8,
|
||||
"build_graph_s": 45.0,
|
||||
"metrics_s": 319.0,
|
||||
"signals_s": 389.7,
|
||||
"scoring_s": 0.1,
|
||||
"index_s": 11.4,
|
||||
"network_s": 92.7
|
||||
},
|
||||
"top_bridgers": [
|
||||
{
|
||||
"author_id": "A5113304257",
|
||||
"name": "Jan Egger",
|
||||
"score": 0.9533,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5051904885",
|
||||
"name": "Feyza Cansiz",
|
||||
"score": 0.9436,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5015256836",
|
||||
"name": "Giebel Bernd",
|
||||
"score": 0.9403,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5029568311",
|
||||
"name": "S. Ugurel-Becker",
|
||||
"score": 0.9395,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5039473892",
|
||||
"name": "D. Schadendorf",
|
||||
"score": 0.9329,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5098748894",
|
||||
"name": "Bahadır Eryılmaz",
|
||||
"score": 0.927,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5120610796",
|
||||
"name": "Ulrich Sure",
|
||||
"score": 0.9263,
|
||||
"bucket": "Early",
|
||||
"active_years": 2,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5007940140",
|
||||
"name": "Amin Dada",
|
||||
"score": 0.9262,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5101839832",
|
||||
"name": "Mohammed-Ali Sheikh",
|
||||
"score": 0.9243,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5074268016",
|
||||
"name": "Anika Grüneboom",
|
||||
"score": 0.922,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 9,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_mentors": [
|
||||
{
|
||||
"author_id": "A5043495754",
|
||||
"name": "Cornelius Deuschl",
|
||||
"score": 0.9613,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5030635588",
|
||||
"name": "Birte Möhlendick",
|
||||
"score": 0.9582,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5029722705",
|
||||
"name": "Freya Droege",
|
||||
"score": 0.95,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5062907808",
|
||||
"name": "Wolfgang P. Fendler",
|
||||
"score": 0.9437,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5048453026",
|
||||
"name": "Alpaslan Tasdogan",
|
||||
"score": 0.9436,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5063064952",
|
||||
"name": "Nora Bruns",
|
||||
"score": 0.9408,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5036496827",
|
||||
"name": "Ramazan Jabbarli",
|
||||
"score": 0.9336,
|
||||
"bucket": "Established",
|
||||
"active_years": 13,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5041276010",
|
||||
"name": "Heiko Wende",
|
||||
"score": 0.9291,
|
||||
"bucket": "Senior",
|
||||
"active_years": 31,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5110823011",
|
||||
"name": "Dagmar Führer",
|
||||
"score": 0.9285,
|
||||
"bucket": "Senior",
|
||||
"active_years": 32,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5047137012",
|
||||
"name": "David Kersting",
|
||||
"score": 0.9284,
|
||||
"bucket": "Established",
|
||||
"active_years": 12,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_amplifiers": [
|
||||
{
|
||||
"author_id": "A5007801159",
|
||||
"name": "Jens Wiltfang",
|
||||
"score": 0.9282,
|
||||
"bucket": "Senior",
|
||||
"active_years": 35,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5049577078",
|
||||
"name": "Stefan Kleine",
|
||||
"score": 0.9121,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5055188384",
|
||||
"name": "Benjamin Zingsem",
|
||||
"score": 0.8991,
|
||||
"bucket": "Established",
|
||||
"active_years": 10,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5036507802",
|
||||
"name": "Martin Schüler",
|
||||
"score": 0.8934,
|
||||
"bucket": "Senior",
|
||||
"active_years": 47,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5123934012",
|
||||
"name": "Karl Sebastian Lang",
|
||||
"score": 0.8883,
|
||||
"bucket": "Early",
|
||||
"active_years": 1,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5016532166",
|
||||
"name": "Adalbert Krawczyk",
|
||||
"score": 0.8779,
|
||||
"bucket": "Senior",
|
||||
"active_years": 16,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5052587248",
|
||||
"name": "Gabi Schierning",
|
||||
"score": 0.8751,
|
||||
"bucket": "Senior",
|
||||
"active_years": 23,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5024191146",
|
||||
"name": "Markus Kaiser",
|
||||
"score": 0.868,
|
||||
"bucket": "Senior",
|
||||
"active_years": 30,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5044921528",
|
||||
"name": "Annette Paschen",
|
||||
"score": 0.862,
|
||||
"bucket": "Senior",
|
||||
"active_years": 29,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5107541231",
|
||||
"name": "Raimund Erbel",
|
||||
"score": 0.8519,
|
||||
"bucket": "Senior",
|
||||
"active_years": 52,
|
||||
"suspicious": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
{
|
||||
"institution": "I62318514",
|
||||
"config_hash": "a49ddd388990",
|
||||
"counts": {
|
||||
"focal_authors_scored": 4921,
|
||||
"nodes": 639544,
|
||||
"edges": 4143499,
|
||||
"works_used": 160396,
|
||||
"works_capped": 4823,
|
||||
"tags": {
|
||||
"amplifier": 609,
|
||||
"mentor": 91,
|
||||
"bridger": 66
|
||||
},
|
||||
"suspicious_profiles": 225
|
||||
},
|
||||
"timings": {
|
||||
"load_cache_s": 15.2,
|
||||
"build_graph_s": 31.3,
|
||||
"metrics_s": 112.2,
|
||||
"scoring_s": 0.0
|
||||
},
|
||||
"top_bridgers": [
|
||||
{
|
||||
"author_id": "A5113304257",
|
||||
"name": "Jan Egger",
|
||||
"score": 0.9488,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5015256836",
|
||||
"name": "Giebel Bernd",
|
||||
"score": 0.9379,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5074268016",
|
||||
"name": "Anika Grüneboom",
|
||||
"score": 0.9277,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 9,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5101839832",
|
||||
"name": "Mohammed-Ali Sheikh",
|
||||
"score": 0.9227,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5093725590",
|
||||
"name": "Ahammed Suhail Odungat",
|
||||
"score": 0.9178,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5123321088",
|
||||
"name": "Heiko Wende",
|
||||
"score": 0.9166,
|
||||
"bucket": "Early",
|
||||
"active_years": 2,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5093128319",
|
||||
"name": "Pascal Raszke",
|
||||
"score": 0.9115,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5009410023",
|
||||
"name": "Yossarian Liebsch",
|
||||
"score": 0.9098,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5038988072",
|
||||
"name": "Ulrike Schara‐Schmidt",
|
||||
"score": 0.9095,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5092634227",
|
||||
"name": "Abdelrahman Elwy",
|
||||
"score": 0.9089,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_mentors": [
|
||||
{
|
||||
"author_id": "A5043495754",
|
||||
"name": "Cornelius Deuschl",
|
||||
"score": 0.9533,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5063064952",
|
||||
"name": "Nora Bruns",
|
||||
"score": 0.9508,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5062907808",
|
||||
"name": "Wolfgang P. Fendler",
|
||||
"score": 0.9477,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5016126468",
|
||||
"name": "Jassin Rashidi‐Alavijeh",
|
||||
"score": 0.9338,
|
||||
"bucket": "Established",
|
||||
"active_years": 13,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5041276010",
|
||||
"name": "Heiko Wende",
|
||||
"score": 0.9314,
|
||||
"bucket": "Senior",
|
||||
"active_years": 31,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5036496827",
|
||||
"name": "Ramazan Jabbarli",
|
||||
"score": 0.9271,
|
||||
"bucket": "Established",
|
||||
"active_years": 13,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5090806187",
|
||||
"name": "Ivana Kraiselburd",
|
||||
"score": 0.9262,
|
||||
"bucket": "Established",
|
||||
"active_years": 12,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5030635588",
|
||||
"name": "Birte Möhlendick",
|
||||
"score": 0.9244,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5052523213",
|
||||
"name": "Ulrich Sure",
|
||||
"score": 0.9229,
|
||||
"bucket": "Senior",
|
||||
"active_years": 32,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5016243200",
|
||||
"name": "Ulf Dittmer",
|
||||
"score": 0.9209,
|
||||
"bucket": "Senior",
|
||||
"active_years": 34,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_amplifiers": [
|
||||
{
|
||||
"author_id": "A5001941348",
|
||||
"name": "Matthias Rinke",
|
||||
"score": 1.0,
|
||||
"bucket": "Senior",
|
||||
"active_years": 25,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5026928109",
|
||||
"name": "Nicole Stracke",
|
||||
"score": 1.0,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5072469617",
|
||||
"name": "Stefan Esser",
|
||||
"score": 1.0,
|
||||
"bucket": "Established",
|
||||
"active_years": 10,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5045156629",
|
||||
"name": "Mirrasoul J. Mousavi",
|
||||
"score": 0.9991,
|
||||
"bucket": "Senior",
|
||||
"active_years": 20,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5102956234",
|
||||
"name": "Tanja Trarbach",
|
||||
"score": 0.9988,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5108819622",
|
||||
"name": "Andreas Roos",
|
||||
"score": 0.9982,
|
||||
"bucket": "Senior",
|
||||
"active_years": 15,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5060245622",
|
||||
"name": "Heidi Wiehler",
|
||||
"score": 0.9978,
|
||||
"bucket": "Established",
|
||||
"active_years": 12,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5005113935",
|
||||
"name": "C. L. Munch",
|
||||
"score": 0.9977,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 7,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5014449031",
|
||||
"name": "Boris S. Kerner",
|
||||
"score": 0.9973,
|
||||
"bucket": "Senior",
|
||||
"active_years": 51,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5034381567",
|
||||
"name": "Yannick Beckmann",
|
||||
"score": 0.9965,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 9,
|
||||
"suspicious": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
Cohort (9 institutions, affiliation years >= 2023):
|
||||
I62318514 University of Duisburg-Essen
|
||||
I4210119759 Essen University Hospital
|
||||
I4210161917 West German Heart and Vascular Center Essen
|
||||
I127668822 Erwin L. Hahn Institute for Magnetic Resonance Imaging
|
||||
I4210090139 Rhein-Ruhr Institut für Sozialforschung und Politikberatung
|
||||
I4210092428 Deutsches Textilforschungszentrum Nord-West
|
||||
I4210110714 Institute for Advanced Study in the Humanities Essen
|
||||
I4210146441 The Hydrogen and Fuel Cell Center
|
||||
I4210154243 Institut für Energie- und Umwelttechnik
|
||||
Reusing cached extract (use --force-extract to refresh).
|
||||
Loaded 267467 works, 9475 focal authors (19.0s)
|
||||
Graph: 864646 nodes, 5822006 edges, 228103 works used, 9238 capped, ref_year=2026 (46.6s)
|
||||
Metrics for 9474 focal authors (326.0s)
|
||||
Signals: patents scored for 55 authors (name-only evidence: 17), news mentions for 1369 (ambiguous names skipped: 839), CORDIS projects for 1342
|
||||
Signal joins done (522.1s)
|
||||
Scores -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/scores_I62318514.jsonl.gz (0.1s)
|
||||
Deleted 9474 existing docs for I62318514
|
||||
Indexed 9474 docs into multiplicators_v1 (count for I62318514: 9474) (46.8s)
|
||||
{
|
||||
"focal_authors_scored": 9474,
|
||||
"nodes": 864646,
|
||||
"edges": 5822006,
|
||||
"works_used": 228103,
|
||||
"works_capped": 9238,
|
||||
"tags": {
|
||||
"mentor": 161,
|
||||
"bridger": 133,
|
||||
"amplifier": 10
|
||||
},
|
||||
"suspicious_profiles": 400,
|
||||
"es_docs_written": 9474
|
||||
}
|
||||
Summary -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/build_summary_I62318514.json
|
||||
@@ -0,0 +1,37 @@
|
||||
Cohort (9 institutions, affiliation years >= 2023):
|
||||
I62318514 University of Duisburg-Essen
|
||||
I4210119759 Essen University Hospital
|
||||
I4210161917 West German Heart and Vascular Center Essen
|
||||
I127668822 Erwin L. Hahn Institute for Magnetic Resonance Imaging
|
||||
I4210090139 Rhein-Ruhr Institut für Sozialforschung und Politikberatung
|
||||
I4210092428 Deutsches Textilforschungszentrum Nord-West
|
||||
I4210110714 Institute for Advanced Study in the Humanities Essen
|
||||
I4210146441 The Hydrogen and Fuel Cell Center
|
||||
I4210154243 Institut für Energie- und Umwelttechnik
|
||||
Reusing cached extract (use --force-extract to refresh).
|
||||
Loaded 267467 works, 9475 focal authors (18.8s)
|
||||
Graph: 864646 nodes, 5822006 edges, 228103 works used, 9238 capped, ref_year=2026 (45.0s)
|
||||
Metrics for 9474 focal authors (319.0s)
|
||||
Signals: patents scored for 55 authors (name-only evidence: 17), news mentions for 1369 (ambiguous names skipped: 839), CORDIS projects for 1342
|
||||
Signal joins done (389.7s)
|
||||
Scores -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/scores_I62318514.jsonl.gz (0.1s)
|
||||
Deleted 9474 existing docs for I62318514
|
||||
Indexed 9474 docs into multiplicators_v1 (count for I62318514: 9474) (11.4s)
|
||||
Deleted 0 existing docs for I62318514
|
||||
Indexed 9474 network docs into multiplicator_networks_v1 (92.7s)
|
||||
{
|
||||
"focal_authors_scored": 9474,
|
||||
"nodes": 864646,
|
||||
"edges": 5822006,
|
||||
"works_used": 228103,
|
||||
"works_capped": 9238,
|
||||
"tags": {
|
||||
"mentor": 161,
|
||||
"bridger": 133,
|
||||
"amplifier": 10
|
||||
},
|
||||
"suspicious_profiles": 400,
|
||||
"es_docs_written": 9474,
|
||||
"es_network_docs_written": 9474
|
||||
}
|
||||
Summary -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/build_summary_I62318514.json
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"institution": {
|
||||
"id": "https://openalex.org/I62318514",
|
||||
"short_id": "I62318514",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
"cohort": [
|
||||
{
|
||||
"id": "I62318514",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
{
|
||||
"id": "I4210119759",
|
||||
"display_name": "Essen University Hospital"
|
||||
},
|
||||
{
|
||||
"id": "I4210161917",
|
||||
"display_name": "West German Heart and Vascular Center Essen"
|
||||
},
|
||||
{
|
||||
"id": "I127668822",
|
||||
"display_name": "Erwin L. Hahn Institute for Magnetic Resonance Imaging"
|
||||
},
|
||||
{
|
||||
"id": "I4210090139",
|
||||
"display_name": "Rhein-Ruhr Institut für Sozialforschung und Politikberatung"
|
||||
},
|
||||
{
|
||||
"id": "I4210092428",
|
||||
"display_name": "Deutsches Textilforschungszentrum Nord-West"
|
||||
},
|
||||
{
|
||||
"id": "I4210110714",
|
||||
"display_name": "Institute for Advanced Study in the Humanities Essen"
|
||||
},
|
||||
{
|
||||
"id": "I4210146441",
|
||||
"display_name": "The Hydrogen and Fuel Cell Center"
|
||||
},
|
||||
{
|
||||
"id": "I4210154243",
|
||||
"display_name": "Institut für Energie- und Umwelttechnik"
|
||||
}
|
||||
],
|
||||
"reproduction": {
|
||||
"author_count": 6583,
|
||||
"work_count": 221603,
|
||||
"group_breakdown": {
|
||||
"backend_compatible": 6360,
|
||||
"empty_last_known_recent": 223
|
||||
}
|
||||
},
|
||||
"field_coverage": {
|
||||
"authorships_total": 4365638,
|
||||
"author_position_pct": 100.0,
|
||||
"is_corresponding_pct": 100.0,
|
||||
"institutions_total": 3934359,
|
||||
"institution_type_pct": 99.9,
|
||||
"company_institutions": 82976
|
||||
},
|
||||
"scale": {
|
||||
"works": 221603,
|
||||
"authors_per_work": {
|
||||
"p50": 5,
|
||||
"p90": 18,
|
||||
"p99": 174,
|
||||
"max": 4839
|
||||
},
|
||||
"hyperauthorship_works_gt_100": 3179,
|
||||
"pair_instances_at_cap": {
|
||||
"20": 4921446,
|
||||
"50": 10209552,
|
||||
"100": 17642513
|
||||
}
|
||||
},
|
||||
"career_quality": {
|
||||
"authors_with_works": 6583,
|
||||
"suspicious_profile_count": 302,
|
||||
"suspicious_profile_pct": 4.59,
|
||||
"active_years": {
|
||||
"p50": 4,
|
||||
"p90": 24,
|
||||
"max": 63,
|
||||
"mean": 8.61
|
||||
}
|
||||
},
|
||||
"signals": {
|
||||
"org_patents_for_institution": 462,
|
||||
"match_type_breakdown": {
|
||||
"name": 339,
|
||||
"both": 65,
|
||||
"institution": 58
|
||||
}
|
||||
},
|
||||
"permissions": {
|
||||
"skipped": "pass --probe-writes to test index create/bulk/delete"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"institution": {
|
||||
"id": "https://openalex.org/I62318514",
|
||||
"short_id": "I62318514",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
"reproduction": {
|
||||
"author_count": 4921,
|
||||
"work_count": 183661,
|
||||
"group_breakdown": {
|
||||
"backend_compatible": 4740,
|
||||
"empty_last_known_recent": 181
|
||||
}
|
||||
},
|
||||
"field_coverage": {
|
||||
"authorships_total": 3805507,
|
||||
"author_position_pct": 100.0,
|
||||
"is_corresponding_pct": 100.0,
|
||||
"institutions_total": 3482939,
|
||||
"institution_type_pct": 99.91,
|
||||
"company_institutions": 67131
|
||||
},
|
||||
"scale": {
|
||||
"works": 183661,
|
||||
"authors_per_work": {
|
||||
"p50": 5,
|
||||
"p90": 17,
|
||||
"p99": 144,
|
||||
"max": 4839
|
||||
},
|
||||
"hyperauthorship_works_gt_100": 2459,
|
||||
"pair_instances_at_cap": {
|
||||
"20": 3912695,
|
||||
"50": 7962611,
|
||||
"100": 13897380
|
||||
}
|
||||
},
|
||||
"career_quality": {
|
||||
"authors_with_works": 4921,
|
||||
"suspicious_profile_count": 225,
|
||||
"suspicious_profile_pct": 4.57,
|
||||
"active_years": {
|
||||
"p50": 4,
|
||||
"p90": 25,
|
||||
"max": 60,
|
||||
"mean": 8.94
|
||||
}
|
||||
},
|
||||
"signals": {
|
||||
"org_patents_for_institution": 436,
|
||||
"match_type_breakdown": {
|
||||
"name": 313,
|
||||
"both": 65,
|
||||
"institution": 58
|
||||
}
|
||||
},
|
||||
"permissions": {
|
||||
"create_index": 403
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
Sample: 60 people, matched in scores: 51, missing: 9
|
||||
MISSING: Peter Bayer (A5060566345)
|
||||
MISSING: Richard Kosinski (A5014403509)
|
||||
MISSING: Alexandra Dmitrienko (A5042835341)
|
||||
MISSING: Wilhelm Koop (A5019228221)
|
||||
MISSING: Venkata Marella (A5082156768)
|
||||
MISSING: Miriam Böhm (A5037448457)
|
||||
MISSING: Katrin Schuldt (A5002003996)
|
||||
MISSING: Friedrich Scheller (A5072565080)
|
||||
MISSING: Lara Altenstädter (A5070117981)
|
||||
|
||||
=== mentor sub-score by known status ===
|
||||
Professor n=29 median=0.740 mean=0.691 range=[0.153, 0.921]
|
||||
Researcher n=22 median=0.494 mean=0.514 range=[0.242, 0.958]
|
||||
|
||||
=== bridger sub-score by known status ===
|
||||
Professor n=29 median=0.629 mean=0.618 range=[0.291, 0.856]
|
||||
Researcher n=22 median=0.469 mean=0.509 range=[0.224, 0.796]
|
||||
|
||||
=== amplifier sub-score by known status ===
|
||||
Professor n=29 median=0.612 mean=0.584 range=[0.357, 0.840]
|
||||
Researcher n=22 median=0.450 mean=0.529 range=[0.363, 0.772]
|
||||
|
||||
M1 exit check — professors' median mentor score (0.74) > researchers' (0.494): PASS
|
||||
|
||||
=== per-person (sorted by mentor score) ===
|
||||
0.958 Researcher Established juniors= 30 laj= 6 Birte Möhlendick (Medicine)
|
||||
0.921 Professor Senior juniors=110 laj= 11 Oliver Witzke (Medicine)
|
||||
0.908 Professor Senior juniors= 56 laj= 12 Daniel Hoffmann (Biology)
|
||||
0.903 Professor Senior juniors= 92 laj= 7 Matthias Gunzer (Medicine)
|
||||
0.898 Professor Senior juniors= 41 laj= 16 Gerd Bacher (Engineering)
|
||||
0.891 Professor Senior juniors= 48 laj= 23 Ulrike Bingel (Medicine)
|
||||
0.888 Professor Senior juniors= 70 laj= 27 Bernd Sures (Biology)
|
||||
0.879 Professor Senior juniors=116 laj= 6 Boris Hadaschik (Medicine)
|
||||
0.862 Professor Senior juniors=128 laj= 2 Stephan Lang (Medicine)
|
||||
0.848 Professor Senior juniors= 40 laj= 25 Daniel Hering (Biology)
|
||||
0.833 Professor Senior juniors= 28 laj= 31 Stefan Schneegaß (Computer Science)
|
||||
0.786 Professor Senior juniors= 19 laj= 27 Torben Weis (Computer Science)
|
||||
0.781 Professor Senior juniors= 18 laj= 23 Pedro José Marrón (Computer Science)
|
||||
0.777 Professor Senior juniors= 29 laj= 4 Corina Andronescu (Engineering)
|
||||
0.762 Professor Senior juniors= 14 laj= 7 Barbara Saccà (Biology)
|
||||
0.740 Professor Senior juniors= 8 laj= 15 Lucas Davi (Computer Science)
|
||||
0.735 Professor Senior juniors= 13 laj= 24 Burak Atakan (Engineering)
|
||||
0.723 Researcher Senior juniors= 67 laj= 0 Farnusch Kaschani (Biology)
|
||||
0.722 Professor Senior juniors= 12 laj= 11 Barbara König (Computer Science)
|
||||
0.712 Professor Senior juniors= 12 laj= 21 Gregor Schiele (Computer Science)
|
||||
0.707 Professor Senior juniors= 10 laj= 11 Volker Gruhn (Computer Science)
|
||||
0.679 Researcher Senior juniors= 16 laj= 1 Marcus Handte (Computer Science)
|
||||
0.659 Professor Senior juniors= 45 laj= 0 Hartmut Schmidt (Medicine)
|
||||
0.654 Researcher Senior juniors= 22 laj= 0 Daniel Grabner (Biology)
|
||||
0.612 Professor Senior juniors= 13 laj= 0 Tienush Rassaf (Medicine)
|
||||
0.605 Professor Senior juniors= 6 laj= 8 Jens Krüger (Computer Science)
|
||||
0.601 Professor Senior juniors= 9 laj= 3 Andreas Metzger (Computer Science)
|
||||
0.513 Professor Senior juniors= 4 laj= 5 Andreas Vogelsang (Computer Science)
|
||||
0.500 Professor Senior juniors= 3 laj= 2 Frank Kleemann (Sociology)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Bianca Kamba (Biology)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Carina Liebers (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Jonas Keppel (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Carlos Medina Sánchez (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Christian Scholz (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Tobias Mikolas (Engineering)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Julia Schwichtenberg (Medicine)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Antonia Görtz (Sociology)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Lisa Mansfeld (Sociology)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Simon Janzon (Computer Science)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Christian Niesler (Computer Science)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Pascal Winkler (Computer Science)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Soheil Salighe (Engineering)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Sabrina Guckenbiehl (Medicine)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Zülal Cibir (Medicine)
|
||||
0.418 Researcher Senior juniors= 6 laj= 0 Stefan Hanenberg (Computer Science)
|
||||
0.377 Professor Senior juniors= 2 laj= 0 Ute Klammer (Sociology)
|
||||
0.251 Researcher Senior juniors= 1 laj= 0 Kathrin Januschke (Biology)
|
||||
0.242 Researcher Established juniors= 0 laj= 0 Andreas Jansen (Sociology)
|
||||
0.240 Professor Senior juniors= 1 laj= 0 Helen Baykara-Krumme (Sociology)
|
||||
0.227 Professor Senior juniors= 1 laj= 0 Marcel Erlinghagen (Sociology)
|
||||
0.153 Professor Senior juniors= 0 laj= 0 Gregor Bongaerts (Sociology)
|
||||
|
||||
Report -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/validation_I62318514.json
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"missing": [
|
||||
"Peter Bayer (A5060566345)",
|
||||
"Richard Kosinski (A5014403509)",
|
||||
"Alexandra Dmitrienko (A5042835341)",
|
||||
"Wilhelm Koop (A5019228221)",
|
||||
"Venkata Marella (A5082156768)",
|
||||
"Miriam Böhm (A5037448457)",
|
||||
"Katrin Schuldt (A5002003996)",
|
||||
"Friedrich Scheller (A5072565080)",
|
||||
"Lara Altenstädter (A5070117981)"
|
||||
],
|
||||
"by_status": {
|
||||
"Professor": {
|
||||
"mentor": {
|
||||
"n": 29,
|
||||
"median": 0.74,
|
||||
"mean": 0.691,
|
||||
"min": 0.153,
|
||||
"max": 0.921
|
||||
},
|
||||
"bridger": {
|
||||
"n": 29,
|
||||
"median": 0.629,
|
||||
"mean": 0.618,
|
||||
"min": 0.291,
|
||||
"max": 0.856
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 29,
|
||||
"median": 0.612,
|
||||
"mean": 0.584,
|
||||
"min": 0.357,
|
||||
"max": 0.84
|
||||
}
|
||||
},
|
||||
"Researcher": {
|
||||
"mentor": {
|
||||
"n": 22,
|
||||
"median": 0.494,
|
||||
"mean": 0.514,
|
||||
"min": 0.242,
|
||||
"max": 0.958
|
||||
},
|
||||
"bridger": {
|
||||
"n": 22,
|
||||
"median": 0.469,
|
||||
"mean": 0.509,
|
||||
"min": 0.224,
|
||||
"max": 0.796
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 22,
|
||||
"median": 0.45,
|
||||
"mean": 0.529,
|
||||
"min": 0.363,
|
||||
"max": 0.772
|
||||
}
|
||||
}
|
||||
},
|
||||
"m1_exit_mentor_check": "PASS"
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"missing": [
|
||||
"Barbara Saccà (A5075803366)",
|
||||
"Peter Bayer (A5060566345)",
|
||||
"Richard Kosinski (A5014403509)",
|
||||
"Alexandra Dmitrienko (A5042835341)",
|
||||
"Christian Niesler (A5069184110)",
|
||||
"Pascal Winkler (A5081189339)",
|
||||
"Wilhelm Koop (A5019228221)",
|
||||
"Venkata Marella (A5082156768)",
|
||||
"Miriam Böhm (A5037448457)",
|
||||
"Soheil Salighe (A5041884757)",
|
||||
"Tobias Mikolas (A5002909977)",
|
||||
"Oliver Witzke (A5087456839)",
|
||||
"Ulrike Bingel (A5002281474)",
|
||||
"Katrin Schuldt (A5002003996)",
|
||||
"Helen Baykara-Krumme (A5010111732)",
|
||||
"Friedrich Scheller (A5072565080)",
|
||||
"Lara Altenstädter (A5070117981)"
|
||||
],
|
||||
"by_status": {
|
||||
"Professor": {
|
||||
"mentor": {
|
||||
"n": 25,
|
||||
"median": 0.715,
|
||||
"mean": 0.663,
|
||||
"min": 0.153,
|
||||
"max": 0.921
|
||||
},
|
||||
"bridger": {
|
||||
"n": 25,
|
||||
"median": 0.603,
|
||||
"mean": 0.598,
|
||||
"min": 0.229,
|
||||
"max": 0.849
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 25,
|
||||
"median": 0.655,
|
||||
"mean": 0.604,
|
||||
"min": 0.173,
|
||||
"max": 0.957
|
||||
}
|
||||
},
|
||||
"Researcher": {
|
||||
"mentor": {
|
||||
"n": 18,
|
||||
"median": 0.493,
|
||||
"mean": 0.503,
|
||||
"min": 0.153,
|
||||
"max": 0.924
|
||||
},
|
||||
"bridger": {
|
||||
"n": 18,
|
||||
"median": 0.508,
|
||||
"mean": 0.521,
|
||||
"min": 0.181,
|
||||
"max": 0.804
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 18,
|
||||
"median": 0.413,
|
||||
"mean": 0.543,
|
||||
"min": 0.161,
|
||||
"max": 0.971
|
||||
}
|
||||
}
|
||||
},
|
||||
"m1_exit_mentor_check": "PASS"
|
||||
}
|
||||
@@ -5,12 +5,18 @@ index_org_patents.py — Build the org_patents Elasticsearch index for one insti
|
||||
Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for
|
||||
patents matched via institution assignee and/or author name (match_type: "institution",
|
||||
"name", or "both"), deletes existing documents for the institution, and reindexes.
|
||||
Every inventor-name match counts outright only if the assignee is the institution
|
||||
itself; everything else (a personal-assignee match or a third-party assignee) only
|
||||
counts if the patent's primary IPC/CPC classification also maps to OpenAlex research
|
||||
topics that appear on the author's own profile — applied regardless of how common the
|
||||
name looks in our local OpenAlex data, since a name can appear unique there while
|
||||
still being common globally in EPO/USPTO.
|
||||
|
||||
Usage:
|
||||
python scripts/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
python scripts/patents/index_org_patents.py --institution-id <OpenAlex-ID>
|
||||
|
||||
Example (University of Duisburg-Essen):
|
||||
python scripts/index_org_patents.py --institution-id I62318514
|
||||
python scripts/patents/index_org_patents.py --institution-id I62318514
|
||||
|
||||
Requires src/main/inse/.env with PATENT_ELASTICSEARCH_URL/API_KEY (and OpenAlex ES
|
||||
credentials for author lookup). Runtime scales with author count (~30-40 min for UDE's
|
||||
@@ -27,11 +33,12 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
service_dir = current_dir.parent.parent
|
||||
sys.path.insert(0, str(service_dir / "src" / "main"))
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env")
|
||||
load_dotenv(dotenv_path=service_dir / "src" / "main" / "inse" / ".env")
|
||||
|
||||
from inse.patents.org.logic import index_org_patents_for_institution
|
||||
|
||||
@@ -43,7 +50,7 @@ async def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Build the org_patents index for one institution.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="Example: python scripts/index_org_patents.py --institution-id I62318514",
|
||||
epilog="Example: python scripts/patents/index_org_patents.py --institution-id I62318514",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--institution-id",
|
||||
|
||||
@@ -12,8 +12,15 @@ mapping from `mapping.py`:
|
||||
"source_index": "...",
|
||||
"source_field": "...",
|
||||
"topic_matches": [
|
||||
{"rank": 1, "topic_id": "...", "topic_display_name": "...",
|
||||
"subfield": "...", "field": "...", "domain": "...", "match_score": null}
|
||||
{
|
||||
"rank": 1,
|
||||
"topic_id": "...",
|
||||
"topic_display_name": "...",
|
||||
"subfield": "...",
|
||||
"field": "...",
|
||||
"domain": "...",
|
||||
"match_score": null
|
||||
}
|
||||
],
|
||||
"match_method": "sentence_transformer",
|
||||
"model_name": "...",
|
||||
@@ -62,11 +69,29 @@ for idx in cordis_eu_fp7_euroscivoc cordis_eu_horizon_2020_euroscivoc cordis_eu_
|
||||
done
|
||||
```
|
||||
|
||||
DFG (keyword is the `fach` subject classification, potentially several per
|
||||
project, project id in the `project_id` field). `--text-field` takes a dotted
|
||||
path into the `subject_classifications` array of objects:
|
||||
|
||||
```bash
|
||||
python map_project_topics.py \
|
||||
--source-index dfg_projects_2.0 \
|
||||
--text-field subject_classifications.fach \
|
||||
--project-id-field project_id \
|
||||
--output-index projects_dfg_openalex_topics
|
||||
```
|
||||
|
||||
## Behaviour
|
||||
|
||||
- **Resumable**: source documents whose id already exists in the output index
|
||||
are skipped; the coverage is logged at startup (`Coverage: X/Y already in
|
||||
index, Z still to be processed`). Just rerun after an interruption.
|
||||
index, Z still to be processed`). Just rerun after an interruption.
|
||||
- **Multi-valued text fields**: a dotted `--text-field` (e.g.
|
||||
`subject_classifications.fach`) descends into arrays of objects and produces
|
||||
one output document per distinct value. Documents with a single value keep
|
||||
the source `_id` as output id; documents with several values get
|
||||
`<source_id>::<sha1(value)[:12]>` per value, so resumability works per
|
||||
(project, keyword) pair.
|
||||
- **Incremental**: each unique keyword is searched once, results are
|
||||
bulk-indexed chunk by chunk with progress logs.
|
||||
- **Fail-fast**: exits immediately with a clear message if the backend or the
|
||||
@@ -74,5 +99,5 @@ done
|
||||
- Keywords whose search failed are not persisted (and are retried on the next
|
||||
run); a warning at the end tells how many documents remain.
|
||||
- `--dry-run` matches without creating/writing the output index, `--output
|
||||
file.json` writes a local JSON backup, `--max-docs N` limits the scan for
|
||||
file.json` writes a local JSON backup, `--max-docs N` limits the scan for
|
||||
test runs, `--top-k` sets matches per keyword (default 3).
|
||||
|
||||
@@ -5,7 +5,9 @@ map_project_topics.py — Map project keywords to OpenAlex topics.
|
||||
Streams all documents from a source index, reads a configurable text field
|
||||
(the "project-specific keyword"), matches every unique keyword against
|
||||
OpenAlex topics, and persists one document per (project, keyword) pair into
|
||||
the output index using mapping.PROJECT_TOPICS_MAPPING:
|
||||
the output index using mapping.PROJECT_TOPICS_MAPPING. The text field may be
|
||||
a dotted path into arrays of objects (e.g. subject_classifications.fach);
|
||||
every distinct value then yields its own output document:
|
||||
|
||||
{project_id, keyword, source_index, source_field, topic_matches[],
|
||||
match_method, model_name, built_at}
|
||||
@@ -28,6 +30,14 @@ Usage (EU EuroSciVoc, project id in the projectID source field):
|
||||
--project-id-field projectID \
|
||||
--output-index projects_eu_openalex_topics
|
||||
|
||||
Usage (DFG, keyword is the fach subject classification, several per project,
|
||||
project id in the project_id source field):
|
||||
python map_project_topics.py \
|
||||
--source-index dfg_projects_2.0 \
|
||||
--text-field subject_classifications.fach \
|
||||
--project-id-field project_id \
|
||||
--output-index projects_dfg_openalex_topics
|
||||
|
||||
Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY (and for
|
||||
--*-cluster nes: ELASTICSEARCH_URL/ELASTICSEARCH_API_KEY) in the environment
|
||||
or in the service .env, plus a running backend serving
|
||||
@@ -37,6 +47,7 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -49,12 +60,12 @@ import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from service.scripts.projects.topic_mapper.mapping import PROJECT_TOPICS_MAPPING
|
||||
from mapping import PROJECT_TOPICS_MAPPING
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_ENV_FILE = Path(__file__).resolve().parents[2] / "src" / "main" / "inse" / ".env"
|
||||
DEFAULT_ENV_FILE = Path(__file__).resolve().parents[3] / "src" / "main" / "inse" / ".env"
|
||||
DEFAULT_API_BASE_URL = "http://localhost:8000" #backend TODO replace with env variable
|
||||
VECTOR_SEARCH_PATH = "/api/topics/vector-search"
|
||||
MATCH_METHOD = "sentence_transformer"
|
||||
@@ -198,12 +209,47 @@ async def ensure_index(index: str, cluster: str) -> None:
|
||||
logger.info("Created output index '%s' with explicit mapping.", index)
|
||||
|
||||
|
||||
def extract_text_values(source: dict, field_path: str) -> list[str]:
|
||||
"""Collects every non-empty value at a dotted field path as strings.
|
||||
|
||||
Descends into arrays of objects at any level (e.g.
|
||||
subject_classifications.fach) and deduplicates while preserving order.
|
||||
A flat scalar field yields at most one value, as before.
|
||||
"""
|
||||
values: list[Any] = [source]
|
||||
for part in field_path.split("."):
|
||||
next_values: list[Any] = []
|
||||
for value in values:
|
||||
for item in value if isinstance(value, list) else [value]:
|
||||
if isinstance(item, dict) and part in item:
|
||||
next_values.append(item[part])
|
||||
values = next_values
|
||||
|
||||
texts: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for value in values:
|
||||
for item in value if isinstance(value, list) else [value]:
|
||||
text = "" if item is None else str(item).strip()
|
||||
if text and text not in seen:
|
||||
seen.add(text)
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
async def fetch_source_entries(
|
||||
index: str, cluster: str, text_field: str, id_field: str | None, max_docs: int | None
|
||||
) -> dict[str, tuple[str, str]]:
|
||||
"""Returns doc_id -> (project_id, keyword) for every source document."""
|
||||
"""Returns output_doc_id -> (project_id, keyword) for every source document.
|
||||
|
||||
Documents with a single text value keep their source _id as output id
|
||||
(backwards compatible with existing output indices); documents with
|
||||
several values (e.g. multiple subject classifications) get one entry per
|
||||
value with the id "<source_id>::<sha1(keyword)[:12]>", so resumability
|
||||
keeps working per (project, keyword) pair.
|
||||
"""
|
||||
entries: dict[str, tuple[str, str]] = {}
|
||||
total = 0
|
||||
docs_with_text = 0
|
||||
if id_field == "_id":
|
||||
id_field = None
|
||||
source_fields = [text_field] + ([id_field] if id_field else [])
|
||||
@@ -216,10 +262,21 @@ async def fetch_source_entries(
|
||||
):
|
||||
total += 1
|
||||
doc_source = hit.get("_source", {})
|
||||
text = str(doc_source.get(text_field) or "").strip()
|
||||
project_id = str(doc_source.get(id_field) or "").strip() if id_field else hit["_id"]
|
||||
if text and project_id:
|
||||
entries[hit["_id"]] = (project_id, text)
|
||||
keywords = extract_text_values(doc_source, text_field)
|
||||
if id_field:
|
||||
id_values = extract_text_values(doc_source, id_field)
|
||||
project_id = id_values[0] if id_values else ""
|
||||
else:
|
||||
project_id = hit["_id"]
|
||||
if keywords and project_id:
|
||||
docs_with_text += 1
|
||||
for keyword in keywords:
|
||||
if len(keywords) == 1:
|
||||
out_id = hit["_id"]
|
||||
else:
|
||||
digest = hashlib.sha1(keyword.encode("utf-8")).hexdigest()[:12]
|
||||
out_id = f"{hit['_id']}::{digest}"
|
||||
entries[out_id] = (project_id, keyword)
|
||||
if total % 50000 == 0:
|
||||
logger.info("Scanned %d source documents...", total)
|
||||
if max_docs and total >= max_docs:
|
||||
@@ -227,11 +284,12 @@ async def fetch_source_entries(
|
||||
break
|
||||
|
||||
logger.info(
|
||||
"Scanned %d documents from '%s', %d with a non-empty '%s'.",
|
||||
"Scanned %d documents from '%s', %d with a non-empty '%s' (%d project/keyword pairs).",
|
||||
total,
|
||||
index,
|
||||
len(entries),
|
||||
docs_with_text,
|
||||
text_field,
|
||||
len(entries),
|
||||
)
|
||||
return entries
|
||||
|
||||
@@ -463,14 +521,21 @@ def main() -> None:
|
||||
" python map_project_topics.py --source-index projects_bund_v1 "
|
||||
"--text-field Leistungsplansystematik_fullname --output-index projects_bund_openalex_topics\n"
|
||||
" python map_project_topics.py --source-index cordis_eu_fp7_euroscivoc "
|
||||
"--text-field title --project-id-field projectID --output-index projects_eu_openalex_topics"
|
||||
"--text-field title --project-id-field projectID --output-index projects_eu_openalex_topics\n"
|
||||
" python map_project_topics.py --source-index dfg_projects_2.0 "
|
||||
"--text-field subject_classifications.fach --project-id-field project_id "
|
||||
"--output-index projects_dfg_openalex_topics"
|
||||
),
|
||||
)
|
||||
parser.add_argument("--source-index", required=True, help="Index to read projects from")
|
||||
parser.add_argument(
|
||||
"--text-field",
|
||||
required=True,
|
||||
help="Source field holding the project-specific keyword to match",
|
||||
help=(
|
||||
"Source field holding the project-specific keyword to match; dotted "
|
||||
"paths descend into arrays of objects and map every distinct value "
|
||||
"(e.g. subject_classifications.fach for dfg_projects_2.0)"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-index", required=True, help="Index to persist the topic mappings into"
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
One document per (project, keyword) pair. For sources where the keyword field
|
||||
is unique per project (e.g. projects_bund_v1 Leistungsplansystematik_fullname)
|
||||
this means one document per project.
|
||||
this means one document per project; for multi-valued sources (e.g.
|
||||
dfg_projects_2.0 subject_classifications.fach) several documents per project.
|
||||
"""
|
||||
|
||||
PROJECT_TOPICS_MAPPING = {
|
||||
|
||||
@@ -57,7 +57,6 @@ from inse.patents.service import (
|
||||
router as patents_service_router,
|
||||
)
|
||||
|
||||
from inse.works.purpose_router import router as works_purpose_router
|
||||
from inse.works.v2.router import router as works_v2_router
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -101,7 +100,6 @@ app.include_router(institution_patents_router)
|
||||
app.include_router(org_patents_router)
|
||||
app.include_router(institutions_router)
|
||||
app.include_router(topics_service_router)
|
||||
app.include_router(works_purpose_router)
|
||||
app.include_router(works_service_router)
|
||||
app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
|
||||
@@ -32,17 +32,19 @@ def is_ambiguous_name(
|
||||
openalex_full_name_count: int | None = None,
|
||||
openalex_last_name_count: int | None = None,
|
||||
) -> bool:
|
||||
"""Decide whether a name is ambiguous using only internal project data.
|
||||
"""Decide whether a name is strictly ambiguous using internal project data.
|
||||
|
||||
A name is treated as ambiguous (and therefore handled strictly) when:
|
||||
A name is treated as strictly ambiguous when:
|
||||
- it is a mononym / cannot be parsed into given + family name, or
|
||||
- several authors in the local OpenAlex index share the exact name, or
|
||||
- many authors in the local OpenAlex index share the family name, or
|
||||
- the patent name search returns a very large number of hits.
|
||||
- several authors in the local OpenAlex index share the exact full name.
|
||||
|
||||
Ambiguous names need a strong identity signal (institution/assignee or a
|
||||
full given-name match with a matching research field) before a patent is
|
||||
attributed to the person.
|
||||
A frequent last name alone does **not** make a uniquely named author
|
||||
strictly ambiguous (``openalex_full_name_count == 1``). In that case
|
||||
personal-assignee identity can count when inventor and assignee both
|
||||
match the full OpenAlex name.
|
||||
|
||||
When the full-name count is unknown, last-name frequency and patent-hit
|
||||
volume remain as safety fallbacks.
|
||||
"""
|
||||
parsed = parse_person_name(display_name)
|
||||
if parsed is None or parsed.is_single_token:
|
||||
@@ -54,6 +56,9 @@ def is_ambiguous_name(
|
||||
):
|
||||
return True
|
||||
|
||||
if openalex_full_name_count == 1:
|
||||
return False
|
||||
|
||||
if (
|
||||
openalex_last_name_count is not None
|
||||
and openalex_last_name_count >= OPENALEX_LAST_NAME_COUNT_THRESHOLD
|
||||
@@ -105,6 +110,29 @@ def patent_institution_match(
|
||||
return False
|
||||
|
||||
|
||||
def patent_personal_assignee_full_match(
|
||||
patent: model.PatentEntry,
|
||||
display_name: str,
|
||||
) -> bool:
|
||||
"""True when a personal assignee matches the author's full given name."""
|
||||
if not display_name or not display_name.strip():
|
||||
return False
|
||||
for assignee in patent.assignees:
|
||||
if assignee and first_name_match_kind_for_person(assignee, display_name) == "full":
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def patent_full_personal_identity_match(
|
||||
patent: model.PatentEntry,
|
||||
display_name: str,
|
||||
) -> bool:
|
||||
"""Strong personal identity: full inventor name and full personal assignee."""
|
||||
if best_name_match_kind(patent, display_name) != "full":
|
||||
return False
|
||||
return patent_personal_assignee_full_match(patent, display_name)
|
||||
|
||||
|
||||
def patent_personal_assignee_match(
|
||||
patent: model.PatentEntry,
|
||||
display_name: str,
|
||||
|
||||
@@ -271,29 +271,31 @@ def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) ->
|
||||
if not inventor.given_names:
|
||||
return False
|
||||
|
||||
# Accept immediately when at least one inventor given-name token matches
|
||||
# one of the author's given names as a full token (not only initial),
|
||||
# e.g. "Maria Schmidt" vs "Anna Maria Schmidt". This only counts if at
|
||||
# least one side is a spelled-out name, not a bare initial — two
|
||||
# coincidentally identical single-letter tokens (e.g. both just "K.")
|
||||
# are far too weak a signal on their own and would otherwise match
|
||||
# anyone sharing that one middle initial regardless of their actual
|
||||
# first name (e.g. "Mahendra K. Sharma" incorrectly matching inventor
|
||||
# "Vivek K." or "Virender K." on an unrelated patent).
|
||||
if any(
|
||||
any(
|
||||
tokens_equal(author_given, inventor_given, allow_initial=False)
|
||||
and not (_initial_letter(author_given) and _initial_letter(inventor_given))
|
||||
for author_given in author.given_names
|
||||
)
|
||||
for inventor_given in inventor.given_names
|
||||
):
|
||||
return True
|
||||
author_full = [g for g in author.given_names if _initial_letter(g) is None]
|
||||
inventor_full = [g for g in inventor.given_names if _initial_letter(g) is None]
|
||||
|
||||
inventor_tokens_full = [
|
||||
token for token in inventor.given_names
|
||||
if _initial_letter(token) is None
|
||||
]
|
||||
# Accept when one side's full (spelled-out) given names are entirely
|
||||
# covered by the other's — e.g. "Maria Schmidt" vs "Anna Maria Schmidt"
|
||||
# (shortened form). A single shared given-name token is not enough by
|
||||
# itself when both sides also carry other, non-matching full given
|
||||
# names: that pattern matches different people who happen to share one
|
||||
# common given-name component rather than the same person (e.g. "Kim,
|
||||
# Young Gil" vs "Moon Young Kim" both contain "Young", but "Gil" and
|
||||
# "Moon" don't match — these are two different people, not the same
|
||||
# person under a shortened name).
|
||||
if author_full and inventor_full:
|
||||
smaller, larger = (
|
||||
(author_full, inventor_full)
|
||||
if len(author_full) <= len(inventor_full)
|
||||
else (inventor_full, author_full)
|
||||
)
|
||||
if all(
|
||||
any(tokens_equal(token, other, allow_initial=False) for other in larger)
|
||||
for token in smaller
|
||||
):
|
||||
return True
|
||||
|
||||
inventor_tokens_full = inventor_full
|
||||
|
||||
# Prevent false positives like "Karem C Weber" for "Christian Weber":
|
||||
# if inventor has full given-name tokens but none matches the author,
|
||||
|
||||
@@ -30,7 +30,7 @@ def test_full_name_collision_makes_name_ambiguous() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_last_name_collision_makes_name_ambiguous() -> None:
|
||||
def test_last_name_collision_makes_name_ambiguous_without_full_name_count() -> None:
|
||||
assert (
|
||||
is_ambiguous_name(
|
||||
"Christian Weber",
|
||||
@@ -43,7 +43,27 @@ def test_last_name_collision_makes_name_ambiguous() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_many_patent_hits_make_name_ambiguous() -> None:
|
||||
def test_last_name_collision_not_ambiguous_when_full_name_unique() -> None:
|
||||
assert (
|
||||
is_ambiguous_name(
|
||||
"Pedro José Marrón",
|
||||
openalex_full_name_count=1,
|
||||
openalex_last_name_count=OPENALEX_LAST_NAME_COUNT_THRESHOLD,
|
||||
patent_hit_count=PATENT_HIT_COUNT_THRESHOLD,
|
||||
)
|
||||
is False
|
||||
)
|
||||
|
||||
|
||||
def test_many_patent_hits_not_ambiguous_when_full_name_unique() -> None:
|
||||
assert (
|
||||
is_ambiguous_name(
|
||||
"Pedro José Marrón",
|
||||
openalex_full_name_count=1,
|
||||
patent_hit_count=PATENT_HIT_COUNT_THRESHOLD,
|
||||
)
|
||||
is False
|
||||
)
|
||||
assert (
|
||||
is_ambiguous_name("Christian Weber", patent_hit_count=PATENT_HIT_COUNT_THRESHOLD)
|
||||
is True
|
||||
|
||||
@@ -11,8 +11,13 @@ from inse.patents.authors.ipc_openalex_mapping import (
|
||||
patent_topics_match_author,
|
||||
resolve_mapped_topics_for_code,
|
||||
)
|
||||
from inse.patents.authors.identity import (
|
||||
patent_full_personal_identity_match,
|
||||
patent_personal_assignee_full_match,
|
||||
)
|
||||
from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
|
||||
from inse.patents.common import model
|
||||
from inse.patents.common.parsing import patent_map_key
|
||||
|
||||
|
||||
def _author_with_topic(
|
||||
@@ -172,19 +177,12 @@ def test_filter_rejects_ambiguous_name_on_fuzzy_label_only_match() -> None:
|
||||
[tire_patent],
|
||||
author,
|
||||
is_ambiguous=True,
|
||||
patent_topic_map={"USPTO:US12508845": [spurious_cardiac]},
|
||||
patent_topic_map={patent_map_key(tire_patent): [spurious_cardiac]},
|
||||
)
|
||||
assert filtered == []
|
||||
|
||||
|
||||
def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None:
|
||||
custom = _custom_mapping()
|
||||
custom["subclass"]["C07K"] = mapping_module.MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T10158",
|
||||
topic_display_name="Cancer Immunotherapy and Biomarkers",
|
||||
ipc_level="subclass",
|
||||
ipc_symbol="C07K",
|
||||
)
|
||||
def test_filter_keeps_ambiguous_name_on_keywords_index_topic_match() -> None:
|
||||
author = _author_with_topic(
|
||||
"https://openalex.org/T10158",
|
||||
"Cancer Immunotherapy and Biomarkers",
|
||||
@@ -199,21 +197,124 @@ def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None:
|
||||
ipc=["C07K 14/705"],
|
||||
inventors=["Schadendorf, Dirk"],
|
||||
)
|
||||
spurious = mapping_module.MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T99999",
|
||||
topic_display_name="Antimicrobial Peptides and Activities",
|
||||
index_mapped = mapping_module.MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T10158",
|
||||
topic_display_name="Cancer Immunotherapy and Biomarkers",
|
||||
subfield_id="https://openalex.org/subfields/2705",
|
||||
field_id="https://openalex.org/fields/27",
|
||||
field_name="Medicine",
|
||||
)
|
||||
filtered = filter_patents_by_ipc_topic_mapping(
|
||||
[patent],
|
||||
author,
|
||||
is_ambiguous=True,
|
||||
mapping=custom,
|
||||
patent_topic_map={"EPO:EP1555271": [spurious]},
|
||||
patent_topic_map={patent_map_key(patent): [index_mapped]},
|
||||
)
|
||||
assert len(filtered) == 1
|
||||
|
||||
|
||||
def test_filter_rejects_ambiguous_personal_assignee_without_keywords_match() -> None:
|
||||
author = _author_with_topic(
|
||||
"https://openalex.org/T12345",
|
||||
"Millimeter-Wave Propagation and Modeling",
|
||||
subfield_id="https://openalex.org/subfields/2208",
|
||||
field_id="https://openalex.org/fields/22",
|
||||
domain_id="https://openalex.org/domains/3",
|
||||
)
|
||||
grill_patent = model.PatentEntry(
|
||||
patent_id="EP999",
|
||||
source="EPO",
|
||||
title="FIRE BASIN",
|
||||
ipc=["A47J 37/07"],
|
||||
assignees=["Kaiser, Thomas"],
|
||||
inventors=["Kaiser, Thomas"],
|
||||
)
|
||||
unrelated = mapping_module.MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T88888",
|
||||
topic_display_name="Food Science and Culinary Arts",
|
||||
subfield_id="https://openalex.org/subfields/1106",
|
||||
field_id="https://openalex.org/fields/11",
|
||||
field_name="Agricultural and Biological Sciences",
|
||||
)
|
||||
filtered = filter_patents_by_ipc_topic_mapping(
|
||||
[grill_patent],
|
||||
author,
|
||||
is_ambiguous=True,
|
||||
patent_topic_map={patent_map_key(grill_patent): [unrelated]},
|
||||
)
|
||||
assert filtered == []
|
||||
|
||||
|
||||
def test_filter_keeps_unique_name_on_full_personal_identity_without_topic_match() -> None:
|
||||
author = _author_with_topic(
|
||||
"https://openalex.org/T12345",
|
||||
"Energy Efficient Wireless Sensor Networks",
|
||||
subfield_id="https://openalex.org/subfields/1706",
|
||||
field_id="https://openalex.org/fields/17",
|
||||
domain_id="https://openalex.org/domains/3",
|
||||
)
|
||||
author.display_name = "Pedro José Marrón"
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1542159",
|
||||
source="EPO",
|
||||
title="Card and reader/writer apparatus for cards",
|
||||
ipc=["G06K 19/077"],
|
||||
assignees=["Marron, Pedro José, Dr."],
|
||||
inventors=["Marron, Pedro José"],
|
||||
)
|
||||
unrelated = mapping_module.MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T88888",
|
||||
topic_display_name="Advanced Image Processing Techniques",
|
||||
subfield_id="https://openalex.org/subfields/1704",
|
||||
field_id="https://openalex.org/fields/17",
|
||||
field_name="Computer Science",
|
||||
)
|
||||
assert patent_full_personal_identity_match(patent, author.display_name) is True
|
||||
filtered = filter_patents_by_ipc_topic_mapping(
|
||||
[patent],
|
||||
author,
|
||||
is_ambiguous=False,
|
||||
patent_topic_map={patent_map_key(patent): [unrelated]},
|
||||
)
|
||||
assert len(filtered) == 1
|
||||
assert filtered[0].personal_assignee_match is True
|
||||
|
||||
|
||||
def test_filter_rejects_initial_only_personal_assignee_without_topic_match() -> None:
|
||||
author = _author_with_topic(
|
||||
"https://openalex.org/T12345",
|
||||
"Energy Efficient Wireless Sensor Networks",
|
||||
subfield_id="https://openalex.org/subfields/1706",
|
||||
field_id="https://openalex.org/fields/17",
|
||||
domain_id="https://openalex.org/domains/3",
|
||||
)
|
||||
author.display_name = "Pedro José Marrón"
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP999",
|
||||
source="EPO",
|
||||
title="Card reader",
|
||||
ipc=["G06K 19/077"],
|
||||
assignees=["Marron, P. J."],
|
||||
inventors=["Marron, P. J."],
|
||||
)
|
||||
unrelated = mapping_module.MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T88888",
|
||||
topic_display_name="Advanced Image Processing Techniques",
|
||||
subfield_id="https://openalex.org/subfields/1704",
|
||||
field_id="https://openalex.org/fields/17",
|
||||
field_name="Computer Science",
|
||||
)
|
||||
assert patent_personal_assignee_full_match(patent, author.display_name) is False
|
||||
assert patent_full_personal_identity_match(patent, author.display_name) is False
|
||||
filtered = filter_patents_by_ipc_topic_mapping(
|
||||
[patent],
|
||||
author,
|
||||
is_ambiguous=False,
|
||||
patent_topic_map={patent_map_key(patent): [unrelated]},
|
||||
)
|
||||
assert filtered == []
|
||||
|
||||
|
||||
def test_custom_mapping_table() -> None:
|
||||
custom = _custom_mapping()
|
||||
author = Author(
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""Filter name-matched patents using precomputed IPC/CPC → OpenAlex topic mappings."""
|
||||
"""Filter name-matched patents using IPC/CPC → OpenAlex topic mappings."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.patents.authors.identity import (
|
||||
patent_full_personal_identity_match,
|
||||
patent_institution_match,
|
||||
patent_personal_assignee_match,
|
||||
)
|
||||
@@ -14,6 +15,7 @@ from inse.patents.authors.ipc_openalex_mapping import (
|
||||
load_ipc_openalex_mapping,
|
||||
mapped_topics_match_author,
|
||||
mapped_topics_match_author_for_ambiguous,
|
||||
mapped_topics_match_author_strict,
|
||||
patent_topics_match_author,
|
||||
resolve_mapped_topics_for_patent,
|
||||
)
|
||||
@@ -70,7 +72,15 @@ def filter_patents_by_ipc_topic_mapping(
|
||||
mapping=None,
|
||||
patent_topic_map: dict[str, list[MappedOpenAlexTopic]] | None = None,
|
||||
) -> list[TopicFilterResult]:
|
||||
"""Filter patents by comparing IPC/CPC codes with the author's OpenAlex topics.
|
||||
|
||||
When ``patent_topic_map`` is provided (from the ``patents_openalex_keywords``
|
||||
index via :class:`PatentOpenAlexMappingResolver`), that mapping is the primary
|
||||
signal: patents must share a topic or subfield with the author, unless the
|
||||
assignee matches one of the author's institutions.
|
||||
"""
|
||||
table = mapping if mapping is not None else load_ipc_openalex_mapping()
|
||||
using_keywords_index = patent_topic_map is not None
|
||||
institution_names = [
|
||||
name
|
||||
for institution in author.last_known_institutions or []
|
||||
@@ -87,17 +97,31 @@ def filter_patents_by_ipc_topic_mapping(
|
||||
for patent in patents:
|
||||
institution_match = patent_institution_match(patent, institution_names)
|
||||
personal_assignee_match = patent_personal_assignee_match(patent, display_name)
|
||||
strong_identity = institution_match or personal_assignee_match
|
||||
if using_keywords_index:
|
||||
if is_ambiguous:
|
||||
strong_identity = institution_match
|
||||
else:
|
||||
strong_identity = institution_match or patent_full_personal_identity_match(
|
||||
patent,
|
||||
display_name,
|
||||
)
|
||||
else:
|
||||
strong_identity = institution_match or personal_assignee_match
|
||||
|
||||
mapped_topics = _resolve_patent_topics(patent, table, patent_topic_map)
|
||||
if is_ambiguous:
|
||||
|
||||
if using_keywords_index:
|
||||
matched_via_mapping = mapped_topics_match_author_strict(
|
||||
mapped_topics,
|
||||
author,
|
||||
)
|
||||
elif is_ambiguous:
|
||||
matched_via_mapping = mapped_topics_match_author_for_ambiguous(
|
||||
patent,
|
||||
author,
|
||||
mapped_topics,
|
||||
table,
|
||||
)
|
||||
elif patent_topic_map is not None:
|
||||
matched_via_mapping = mapped_topics_match_author(mapped_topics, author)
|
||||
else:
|
||||
matched_via_mapping = patent_topics_match_author(patent, author, table)
|
||||
|
||||
@@ -113,17 +137,22 @@ def filter_patents_by_ipc_topic_mapping(
|
||||
)
|
||||
continue
|
||||
|
||||
if is_ambiguous:
|
||||
if matched_via_mapping:
|
||||
filtered.append(
|
||||
TopicFilterResult(
|
||||
patent=patent,
|
||||
decision="keep",
|
||||
matched_via_mapping=True,
|
||||
institution_match=False,
|
||||
personal_assignee_match=False,
|
||||
)
|
||||
if matched_via_mapping:
|
||||
filtered.append(
|
||||
TopicFilterResult(
|
||||
patent=patent,
|
||||
decision="keep",
|
||||
matched_via_mapping=True,
|
||||
institution_match=False,
|
||||
personal_assignee_match=False,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
if using_keywords_index:
|
||||
continue
|
||||
|
||||
if is_ambiguous:
|
||||
continue
|
||||
|
||||
if _topic_conflict(mapped_topics, author):
|
||||
|
||||
@@ -50,6 +50,7 @@ _MAX_SEARCH_KEYWORDS = 10
|
||||
_MIN_KEYWORD_RELEVANCE = 0.0
|
||||
_MIN_IPC_MATCH_SCORE = 0.65
|
||||
_MIN_PATENT_MATCH_SCORE = 0.50
|
||||
_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15}
|
||||
_SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"})
|
||||
# Soft field overlap for natural-science / engineering patent domains.
|
||||
_SOFT_MATCH_FIELD_NAMES = frozenset(
|
||||
@@ -492,15 +493,32 @@ def _patent_passes_relevance_gate(
|
||||
return has_topic_match or text_score > 0.0
|
||||
|
||||
|
||||
def _normalize_score_weights(
|
||||
weights: dict[str, float] | None = None,
|
||||
) -> dict[str, float]:
|
||||
raw = {
|
||||
"ipc": float((weights or {}).get("ipc", _DEFAULT_SCORE_WEIGHTS["ipc"])),
|
||||
"topic": float((weights or {}).get("topic", _DEFAULT_SCORE_WEIGHTS["topic"])),
|
||||
"text": float((weights or {}).get("text", _DEFAULT_SCORE_WEIGHTS["text"])),
|
||||
}
|
||||
total = sum(raw.values())
|
||||
if total <= 0:
|
||||
return dict(_DEFAULT_SCORE_WEIGHTS)
|
||||
return {key: value / total for key, value in raw.items()}
|
||||
|
||||
|
||||
def _compute_final_score(
|
||||
ipc_score: float,
|
||||
topic_score: float,
|
||||
text_score: float,
|
||||
*,
|
||||
weights: dict[str, float] | None = None,
|
||||
) -> float:
|
||||
normalized = _normalize_score_weights(weights)
|
||||
return round(
|
||||
0.60 * ipc_score
|
||||
+ 0.25 * topic_score
|
||||
+ 0.15 * text_score,
|
||||
normalized["ipc"] * ipc_score
|
||||
+ normalized["topic"] * topic_score
|
||||
+ normalized["text"] * text_score,
|
||||
4,
|
||||
)
|
||||
|
||||
@@ -753,6 +771,9 @@ async def get_patents_by_keywords(
|
||||
KeywordPatentMatch(
|
||||
patent=patent,
|
||||
match_score=score,
|
||||
ipc_score=ipc_score,
|
||||
topic_score=topic_score,
|
||||
text_score=text_score,
|
||||
matched_keywords=matched_keywords,
|
||||
matched_ipc_symbols=matched_symbols,
|
||||
)
|
||||
|
||||
@@ -45,6 +45,9 @@ class PatentsByKeywordsRequest(BaseModel):
|
||||
class KeywordPatentMatch(BaseModel):
|
||||
patent: PatentEntry
|
||||
match_score: float = Field(description="Combined match quality score.")
|
||||
ipc_score: float = Field(description="IPC/CPC classification match score.")
|
||||
topic_score: float = Field(description="OpenAlex topic overlap score (0 or 1).")
|
||||
text_score: float = Field(description="Title/abstract keyword overlap score.")
|
||||
matched_keywords: list[str] = Field(default_factory=list)
|
||||
matched_ipc_symbols: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@@ -417,6 +417,12 @@ def test_compute_final_score_weights_ipc_topic_and_text() -> None:
|
||||
4,
|
||||
)
|
||||
assert _compute_final_score(0.6742, 0.0, 0.0) == round(0.60 * 0.6742, 4)
|
||||
assert _compute_final_score(
|
||||
0.8,
|
||||
1.0,
|
||||
0.5,
|
||||
weights={"ipc": 0.2, "topic": 0.2, "text": 0.6},
|
||||
) == round(0.2 * 0.8 + 0.2 * 1.0 + 0.6 * 0.5, 4)
|
||||
|
||||
|
||||
def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None:
|
||||
|
||||
@@ -13,10 +13,9 @@ from inse.institutions.institutions_search_client import InstitutionsSearchClien
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.patents.authors.identity import (
|
||||
author_institution_names,
|
||||
is_ambiguous_name,
|
||||
patent_institution_match,
|
||||
patent_personal_assignee_match,
|
||||
)
|
||||
from inse.patents.authors.ipc_openalex_mapping import normalize_openalex_id
|
||||
from inse.patents.authors.name_matching import filter_patents_by_author_name
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.common.model import PatentEntry
|
||||
@@ -27,10 +26,12 @@ from inse.patents.common.parsing import (
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
patent_dedup_key,
|
||||
patent_map_key,
|
||||
)
|
||||
from inse.patents.institutions.logic import get_patents_by_institution_id
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver
|
||||
from inse.patents.org.elastic_search_client import (
|
||||
OrgPatentsSearchClient,
|
||||
fetch_authors_by_institution_name,
|
||||
@@ -218,11 +219,72 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
|
||||
}
|
||||
|
||||
|
||||
MIN_CORROBORATING_TOPIC_OVERLAP = 2
|
||||
|
||||
|
||||
def primary_classification_codes(patent: PatentEntry) -> list[str]:
|
||||
"""Returns only the patent's primary IPC/CPC code(s) (marked "AFI" in the
|
||||
raw EPO/USPTO string), falling back to all codes if none are marked.
|
||||
|
||||
Patents can carry dozens of secondary/incidental classification codes
|
||||
(marked "ALI") alongside their real subject. Resolving OpenAlex topics
|
||||
from *all* of them gives some patents a huge, unfocused topic cloud —
|
||||
confirmed against a real org_patents rebuild, where a 20-code patent
|
||||
picked up 70+ unrelated topics, making a coincidental two-topic overlap
|
||||
with an unrelated same-named author far more likely than intended.
|
||||
"""
|
||||
all_codes = [*patent.ipc, *patent.cpc]
|
||||
primary = [code for code in all_codes if "AFI" in code]
|
||||
return primary or all_codes
|
||||
|
||||
|
||||
def topic_corroborated_patents(
|
||||
patents: list[PatentEntry],
|
||||
author: Author,
|
||||
patent_topic_map: dict[str, list],
|
||||
) -> list[PatentEntry]:
|
||||
"""Keeps only patents whose IPC/CPC-derived OpenAlex topics share at
|
||||
least MIN_CORROBORATING_TOPIC_OVERLAP exact topic IDs with the author's
|
||||
own research topics — used to disambiguate common inventor names where
|
||||
institution/self-assignee matching alone isn't enough.
|
||||
|
||||
Requiring a single shared topic ID was still too loose: broad,
|
||||
genuinely common topics (e.g. "Image Processing Techniques") show up on
|
||||
many unrelated patents *and* on many unrelated researchers' profiles, so
|
||||
one coincidental overlap doesn't mean much (confirmed against a real
|
||||
org_patents rebuild: match_type=name patents still ballooned to ~2000).
|
||||
Two independent topic overlaps happening by chance is far less likely,
|
||||
while a patent genuinely invented by the author would typically share
|
||||
more than one topic with their own body of work. If the author has no
|
||||
topic profile at all, there is nothing to corroborate against.
|
||||
"""
|
||||
author_topic_ids = {
|
||||
normalize_openalex_id(topic.id)
|
||||
for topic in (author.topics or [])
|
||||
if topic.id
|
||||
}
|
||||
author_topic_ids.discard(None)
|
||||
if not author_topic_ids:
|
||||
return []
|
||||
|
||||
kept: list[PatentEntry] = []
|
||||
for patent in patents:
|
||||
mapped_topics = patent_topic_map.get(patent_map_key(patent), [])
|
||||
patent_topic_ids = {
|
||||
normalize_openalex_id(topic.topic_id)
|
||||
for topic in mapped_topics
|
||||
if topic.topic_id
|
||||
}
|
||||
patent_topic_ids.discard(None)
|
||||
if len(patent_topic_ids & author_topic_ids) >= MIN_CORROBORATING_TOPIC_OVERLAP:
|
||||
kept.append(patent)
|
||||
return kept
|
||||
|
||||
|
||||
async def _search_patents_by_author(
|
||||
author: Author,
|
||||
institution_name: str | None,
|
||||
search_client: PatentSearchClient,
|
||||
ipc_client: IpcSearchClient,
|
||||
) -> list[PatentEntry]:
|
||||
author_name = author.display_name
|
||||
if not author_name:
|
||||
@@ -248,40 +310,53 @@ async def _search_patents_by_author(
|
||||
|
||||
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||
patents = deduplicate_patents(patents)
|
||||
patent_hit_count = len(patents)
|
||||
name_matched = filter_patents_by_author_name(patents, author_name)
|
||||
if not name_matched:
|
||||
return []
|
||||
|
||||
from inse.persons import logic as person_logic
|
||||
from inse.patents.authors.name_variants import parse_person_name
|
||||
# Applied to every name-based hit, not gated behind an ambiguity check:
|
||||
# the institution itself being the assignee is the only unambiguous
|
||||
# case — accepted outright. Everything else matched on name alone,
|
||||
# including a personal-assignee match (several different same-named
|
||||
# people could each be listed as their own patent's assignee) or a
|
||||
# third-party assignee (e.g. an industry partner on a co-invented
|
||||
# patent — the normal case for academic patents, not a red flag by
|
||||
# itself), only counts if the patent's IPC/CPC-derived OpenAlex topics
|
||||
# also overlap with the author's own research topics. This
|
||||
# intentionally does not rely on is_ambiguous_name: a name can look
|
||||
# unique in our local OpenAlex slice while still being common globally
|
||||
# in EPO/USPTO, so a bare name-on-inventor match alone is never a
|
||||
# strong enough signal on its own.
|
||||
inst_names = [institution_name] if institution_name else []
|
||||
strong_identity_matched = [
|
||||
p for p in name_matched
|
||||
if patent_institution_match(p, inst_names)
|
||||
]
|
||||
matched_keys = {patent_dedup_key(p) for p in strong_identity_matched}
|
||||
remaining = [p for p in name_matched if patent_dedup_key(p) not in matched_keys]
|
||||
if not remaining:
|
||||
return strong_identity_matched
|
||||
|
||||
full_name_count = await person_logic.count_authors_by_display_name(author_name)
|
||||
parsed_for_last = parse_person_name(author_name)
|
||||
last_name_count: int | None = None
|
||||
if parsed_for_last and not parsed_for_last.is_single_token:
|
||||
last_name_count = await person_logic.count_authors_by_last_name(
|
||||
parsed_for_last.last_name
|
||||
)
|
||||
is_ambiguous = is_ambiguous_name(
|
||||
author_name,
|
||||
patent_hit_count=patent_hit_count,
|
||||
openalex_full_name_count=full_name_count,
|
||||
openalex_last_name_count=last_name_count,
|
||||
)
|
||||
|
||||
if is_ambiguous:
|
||||
# Common names (Zhang, Li, Wang): only keep if the assignee matches the
|
||||
# institution we're building this index for (not any institution from
|
||||
# the author's whole affiliation history) or the person themselves.
|
||||
inst_names = [institution_name] if institution_name else []
|
||||
return [
|
||||
p for p in name_matched
|
||||
if patent_institution_match(p, inst_names)
|
||||
or patent_personal_assignee_match(p, author_name)
|
||||
topic_matched: list[PatentEntry] = []
|
||||
try:
|
||||
resolver = PatentOpenAlexMappingResolver()
|
||||
primary_only = [
|
||||
patent.model_copy(update={
|
||||
"ipc": primary_classification_codes(patent),
|
||||
"cpc": [],
|
||||
})
|
||||
for patent in remaining
|
||||
]
|
||||
else:
|
||||
return name_matched
|
||||
patent_topic_map = await resolver.resolve_topics_for_patents(primary_only)
|
||||
topic_matched = topic_corroborated_patents(remaining, author, patent_topic_map)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"OpenAlex topic corroboration failed for author %s",
|
||||
author_name,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
return strong_identity_matched + topic_matched
|
||||
|
||||
|
||||
async def build_org_patents_for_institution(
|
||||
@@ -320,7 +395,7 @@ async def build_org_patents_for_institution(
|
||||
async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]:
|
||||
async with semaphore:
|
||||
patents = await _search_patents_by_author(
|
||||
author, institution_name, patent_client, ipc_search_client
|
||||
author, institution_name, patent_client
|
||||
)
|
||||
return author, patents
|
||||
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
|
||||
from inse.patents.common.model import PatentEntry
|
||||
from inse.patents.common.parsing import patent_map_key
|
||||
from inse.patents.org.logic import (
|
||||
merge_org_patents,
|
||||
org_patent_document_id,
|
||||
primary_classification_codes,
|
||||
resolve_match_type,
|
||||
topic_corroborated_patents,
|
||||
)
|
||||
from inse.patents.org.model import MatchedAuthor
|
||||
from inse.models.openalex.author import Author
|
||||
|
||||
|
||||
def _patent(
|
||||
@@ -102,3 +107,108 @@ def test_org_patent_document_id_is_stable() -> None:
|
||||
doc_id = org_patent_document_id("I62318514", patent)
|
||||
|
||||
assert doc_id == "I62318514_EPO_EP1234567_20240101_A1"
|
||||
|
||||
|
||||
def _author_with_topics(author_id: str, name: str, topic_ids: list[str]) -> Author:
|
||||
return Author(
|
||||
id=f"https://openalex.org/{author_id}",
|
||||
display_name=name,
|
||||
topics=[WorkTopic(id=tid, display_name=f"Topic {tid}") for tid in topic_ids],
|
||||
)
|
||||
|
||||
|
||||
def _mapped_topics(*topic_ids: str) -> list[MappedOpenAlexTopic]:
|
||||
return [
|
||||
MappedOpenAlexTopic(topic_id=tid, topic_display_name=f"Topic {tid}")
|
||||
for tid in topic_ids
|
||||
]
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_keeps_two_overlapping_topics() -> None:
|
||||
author = _author_with_topics(
|
||||
"A123", "Wei Zhang",
|
||||
["https://openalex.org/T1", "https://openalex.org/T2"],
|
||||
)
|
||||
patent = _patent("EP1")
|
||||
patent_topic_map = {
|
||||
patent_map_key(patent): _mapped_topics(
|
||||
"https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3"
|
||||
),
|
||||
}
|
||||
|
||||
result = topic_corroborated_patents([patent], author, patent_topic_map)
|
||||
|
||||
assert result == [patent]
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_drops_single_coincidental_overlap() -> None:
|
||||
"""A single shared topic isn't enough — broad, common topics show up on
|
||||
many unrelated patents and profiles by coincidence."""
|
||||
author = _author_with_topics(
|
||||
"A123", "Xin Wang",
|
||||
["https://openalex.org/T1", "https://openalex.org/T9"],
|
||||
)
|
||||
patent = _patent("EP2")
|
||||
patent_topic_map = {
|
||||
patent_map_key(patent): _mapped_topics(
|
||||
"https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3"
|
||||
),
|
||||
}
|
||||
|
||||
result = topic_corroborated_patents([patent], author, patent_topic_map)
|
||||
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_drops_patent_without_mapped_topics() -> None:
|
||||
author = _author_with_topics("A123", "Wei Zhang", ["https://openalex.org/T1"])
|
||||
patent = _patent("EP3")
|
||||
|
||||
result = topic_corroborated_patents([patent], author, {})
|
||||
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_topic_corroborated_patents_rejects_everything_without_author_topic_profile() -> None:
|
||||
author = Author(id="https://openalex.org/A999", display_name="Wei Zhang")
|
||||
patent = _patent("EP4")
|
||||
patent_topic_map = {
|
||||
patent_map_key(patent): _mapped_topics(
|
||||
"https://openalex.org/T1", "https://openalex.org/T2"
|
||||
),
|
||||
}
|
||||
|
||||
result = topic_corroborated_patents([patent], author, patent_topic_map)
|
||||
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_primary_classification_codes_keeps_only_afi_marked_codes() -> None:
|
||||
"""A patent with many secondary ("ALI") codes alongside its one primary
|
||||
("AFI") code must only contribute the primary one — otherwise a large
|
||||
secondary-code topic cloud makes coincidental multi-topic overlaps with
|
||||
an unrelated same-named author far too easy (confirmed against a real
|
||||
org_patents rebuild: a 20-code patent picked up 70+ topics)."""
|
||||
patent = _patent("EP1")
|
||||
patent.ipc = [
|
||||
"G06V 10/776 20220101AFI20250422BHUS",
|
||||
"G01N 33/569 20060101ALI20250422BHUS",
|
||||
"G06T 5/20 20060101ALI20250422BHUS",
|
||||
]
|
||||
patent.cpc = ["G16H 30/40 20180101ALI20250422BHUS"]
|
||||
|
||||
result = primary_classification_codes(patent)
|
||||
|
||||
assert result == ["G06V 10/776 20220101AFI20250422BHUS"]
|
||||
|
||||
|
||||
def test_primary_classification_codes_falls_back_to_all_codes_without_afi_marker() -> None:
|
||||
patent = _patent("EP2")
|
||||
patent.ipc = ["G06V 10/776 20220101ALI20250422BHUS"]
|
||||
patent.cpc = ["G01N 33/569 20060101ALI20250422BHUS"]
|
||||
|
||||
result = primary_classification_codes(patent)
|
||||
|
||||
assert result == patent.ipc + patent.cpc
|
||||
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from inse.patents.patents_openalex_keywords.mapping import (
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_LEVEL_LOOKUP_ORDER = ("subgroup", "group", "subclass", "class", "section")
|
||||
_MAX_SEARCH_WINDOW = 10_000 # Elasticsearch's default index.max_result_window
|
||||
|
||||
|
||||
def candidate_doc_ids(symbol: str) -> list[str]:
|
||||
@@ -179,26 +180,35 @@ class PatentsOpenAlexKeywordsClient:
|
||||
return hits[0].get("_source") if hits else None
|
||||
|
||||
async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict[str, Any]]:
|
||||
"""Resolves multiple doc ids in a single _search request (id -> _source)."""
|
||||
"""Resolves multiple doc ids in as few _search requests as possible
|
||||
(id -> _source). Chunked to stay under Elasticsearch's
|
||||
index.max_result_window (10000) — a single query with more ids than
|
||||
that fails with a 400 "Result window is too large" error, which hit
|
||||
real org_patents rebuilds resolving topics for many patents at once.
|
||||
"""
|
||||
unique_ids = list(dict.fromkeys(doc_ids))
|
||||
if not unique_ids:
|
||||
return {}
|
||||
|
||||
results: dict[str, dict[str, Any]] = {}
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json={"size": len(unique_ids), "query": {"ids": {"values": unique_ids}}},
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return {}
|
||||
response.raise_for_status()
|
||||
hits = response.json().get("hits", {}).get("hits", [])
|
||||
return {hit["_id"]: hit.get("_source", {}) for hit in hits}
|
||||
for start in range(0, len(unique_ids), _MAX_SEARCH_WINDOW):
|
||||
chunk = unique_ids[start : start + _MAX_SEARCH_WINDOW]
|
||||
response = await client.post(
|
||||
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json={"size": len(chunk), "query": {"ids": {"values": chunk}}},
|
||||
)
|
||||
if response.status_code == 404:
|
||||
continue
|
||||
response.raise_for_status()
|
||||
hits = response.json().get("hits", {}).get("hits", [])
|
||||
results.update({hit["_id"]: hit.get("_source", {}) for hit in hits})
|
||||
return results
|
||||
|
||||
async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None:
|
||||
ordered_ids = candidate_doc_ids(symbol)
|
||||
|
||||
@@ -15,7 +15,10 @@ from inse.patents.authors.ipc_openalex_mapping import (
|
||||
)
|
||||
from inse.patents.common import model
|
||||
from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.patents_openalex_keywords.client import (
|
||||
PatentsOpenAlexKeywordsClient,
|
||||
candidate_doc_ids,
|
||||
)
|
||||
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -213,8 +216,24 @@ class PatentOpenAlexMappingResolver:
|
||||
self,
|
||||
patents: list[model.PatentEntry],
|
||||
) -> dict[str, list[MappedOpenAlexTopic]]:
|
||||
"""Resolves topics for many patents at once via a single batched
|
||||
Elasticsearch request, instead of the sequential per-patent /
|
||||
per-code lookups in resolve_mapped_topics_for_patent(). This matters
|
||||
a lot when called for many patents at once (e.g. building
|
||||
org_patents across thousands of authors) — one request per code,
|
||||
repeated per patent, previously added minutes of latency."""
|
||||
from inse.patents.common.parsing import patent_map_key
|
||||
|
||||
if not patents:
|
||||
return {}
|
||||
|
||||
candidate_symbols: list[str] = []
|
||||
for patent in patents:
|
||||
for raw_code in (*patent.ipc, *patent.cpc):
|
||||
candidate_symbols.extend(_lookup_candidates(raw_code))
|
||||
|
||||
await self._preload_documents(candidate_symbols)
|
||||
|
||||
result: dict[str, list[MappedOpenAlexTopic]] = {}
|
||||
for patent in patents:
|
||||
result[patent_map_key(patent)] = await self.resolve_mapped_topics_for_patent(
|
||||
@@ -222,6 +241,55 @@ class PatentOpenAlexMappingResolver:
|
||||
)
|
||||
return result
|
||||
|
||||
async def _preload_documents(self, symbols: list[str]) -> None:
|
||||
"""Resolve all IPC/CPC candidate symbols in one or few ES _search requests."""
|
||||
pending = list(
|
||||
dict.fromkeys(
|
||||
normalized
|
||||
for symbol in symbols
|
||||
if (normalized := normalize_symbol(symbol))
|
||||
and normalized not in self._doc_cache
|
||||
)
|
||||
)
|
||||
if not pending:
|
||||
return
|
||||
|
||||
all_doc_ids = list(
|
||||
dict.fromkeys(
|
||||
doc_id
|
||||
for symbol in pending
|
||||
for doc_id in candidate_doc_ids(symbol)
|
||||
)
|
||||
)
|
||||
|
||||
docs_by_id: dict[str, dict] = {}
|
||||
if all_doc_ids and await self._elasticsearch_enabled_for_request():
|
||||
try:
|
||||
batch_size = 500
|
||||
for start in range(0, len(all_doc_ids), batch_size):
|
||||
batch = all_doc_ids[start : start + batch_size]
|
||||
docs_by_id.update(await self.client.lookup_ids(batch))
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"patents_openalex_keywords batch preload failed: %s",
|
||||
exc,
|
||||
)
|
||||
self._elasticsearch_enabled = False
|
||||
|
||||
json_table = load_patents_openalex_keywords_json()
|
||||
for symbol in pending:
|
||||
doc = next(
|
||||
(
|
||||
docs_by_id[doc_id]
|
||||
for doc_id in candidate_doc_ids(symbol)
|
||||
if doc_id in docs_by_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if doc is None:
|
||||
doc = _json_lookup_symbol(symbol, json_table)
|
||||
self._doc_cache[symbol] = doc
|
||||
|
||||
async def _elasticsearch_enabled_for_request(self) -> bool:
|
||||
if not self.use_elasticsearch:
|
||||
return False
|
||||
|
||||
@@ -3,7 +3,10 @@ import json
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.patents_openalex_keywords.client import (
|
||||
_MAX_SEARCH_WINDOW,
|
||||
PatentsOpenAlexKeywordsClient,
|
||||
)
|
||||
from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX
|
||||
|
||||
|
||||
@@ -97,6 +100,34 @@ async def test_lookup_symbol_resolves_via_a_single_batched_request():
|
||||
assert doc == {"ipc_label": "match"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_lookup_ids_chunks_requests_over_max_search_window():
|
||||
"""A single _search with more than index.max_result_window (10000) ids
|
||||
fails with a 400 "Result window is too large" error — confirmed against
|
||||
the real cluster. lookup_ids() must split large id lists into chunks
|
||||
that each stay within that limit."""
|
||||
captured_sizes: list[int] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
values = body["query"]["ids"]["values"]
|
||||
captured_sizes.append(len(values))
|
||||
hits = [{"_id": doc_id, "_source": {"ipc_label": doc_id}} for doc_id in values[:1]]
|
||||
return httpx.Response(200, json={"hits": {"hits": hits}})
|
||||
|
||||
client = PatentsOpenAlexKeywordsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
doc_ids = [f"subgroup:X{i}" for i in range(_MAX_SEARCH_WINDOW + 500)]
|
||||
|
||||
result = await client.lookup_ids(doc_ids)
|
||||
|
||||
assert captured_sizes == [_MAX_SEARCH_WINDOW, 500]
|
||||
assert all(size <= _MAX_SEARCH_WINDOW for size in captured_sizes)
|
||||
assert len(result) == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_lookup_symbol_prefers_more_specific_level_when_multiple_match():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
|
||||
@@ -45,13 +45,26 @@ def test_mapped_topics_from_index_doc_includes_topics_and_keywords() -> None:
|
||||
class _FakeKeywordsClient:
|
||||
def __init__(self, docs: dict[str, dict]):
|
||||
self.docs = docs
|
||||
self.lookup_ids_calls = 0
|
||||
self.lookup_symbol_calls = 0
|
||||
|
||||
async def index_exists(self) -> bool:
|
||||
return True
|
||||
|
||||
async def lookup_symbol(self, symbol: str):
|
||||
self.lookup_symbol_calls += 1
|
||||
return self.docs.get(symbol)
|
||||
|
||||
async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict]:
|
||||
self.lookup_ids_calls += 1
|
||||
result: dict[str, dict] = {}
|
||||
for doc_id in doc_ids:
|
||||
_level, symbol = doc_id.split(":", 1)
|
||||
doc = self.docs.get(symbol)
|
||||
if doc is not None:
|
||||
result[doc_id] = doc
|
||||
return result
|
||||
|
||||
|
||||
def test_resolver_uses_index_doc_before_legacy_fallback() -> None:
|
||||
resolver = PatentOpenAlexMappingResolver(
|
||||
@@ -100,3 +113,45 @@ def test_filter_uses_patent_topic_map_from_resolver() -> None:
|
||||
patent_topic_map=topic_map,
|
||||
)
|
||||
assert len(filtered) == 1
|
||||
|
||||
|
||||
def test_resolve_topics_for_patents_preloads_documents_in_one_batch() -> None:
|
||||
client = _FakeKeywordsClient(
|
||||
{
|
||||
"H01L": {
|
||||
"ipc_level": "subclass",
|
||||
"ipc_symbol": "H01L",
|
||||
"topic_matches": [
|
||||
{
|
||||
"topic_id": "https://openalex.org/T99999",
|
||||
"topic_display_name": "Semiconductor materials and devices",
|
||||
}
|
||||
],
|
||||
"keyword_matches": [],
|
||||
},
|
||||
"C07C": {
|
||||
"ipc_level": "subclass",
|
||||
"ipc_symbol": "C07C",
|
||||
"topic_matches": [
|
||||
{
|
||||
"topic_id": "https://openalex.org/T11111",
|
||||
"topic_display_name": "Organic chemistry",
|
||||
}
|
||||
],
|
||||
"keyword_matches": [],
|
||||
},
|
||||
}
|
||||
)
|
||||
resolver = PatentOpenAlexMappingResolver(client=client, use_elasticsearch=True)
|
||||
patents = [
|
||||
model.PatentEntry(patent_id="EP1", source="EPO", ipc=["H01L 21/02"]),
|
||||
model.PatentEntry(patent_id="EP2", source="EPO", ipc=["C07C 31/20"]),
|
||||
model.PatentEntry(patent_id="US1", source="USPTO", ipc=["H01L 27/04"]),
|
||||
]
|
||||
|
||||
topic_map = asyncio.run(resolver.resolve_topics_for_patents(patents))
|
||||
|
||||
assert client.lookup_ids_calls == 1
|
||||
assert client.lookup_symbol_calls == 0
|
||||
assert len(topic_map) == 3
|
||||
assert all(topics for topics in topic_map.values())
|
||||
|
||||
@@ -136,6 +136,8 @@ def test_first_name_match_kind() -> None:
|
||||
("Schmitz, Oliver", "Oliver J. Schmitz", False),
|
||||
("Schmitz, Oliver J.", "Oliver J. Schmitz", True),
|
||||
("Schmitz, O. J.", "Oliver J. Schmitz", True),
|
||||
("Kim, Young Gil", "Moon Young Kim", False),
|
||||
("Kim, Young Hwan", "Moon Young Kim", False),
|
||||
],
|
||||
)
|
||||
def test_name_matches_person_multi_part(
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
Pydantic models for publication works.
|
||||
"""
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
|
||||
@@ -42,37 +41,3 @@ class WorkPage(BaseModel):
|
||||
class WorkList(BaseModel):
|
||||
elements: List[Work] = Field(default_factory=list, description="All works.")
|
||||
total: int = Field(default=0, description="The total number of works.")
|
||||
|
||||
|
||||
class WorkPurpose(StrEnum):
|
||||
"""Represents the purpose of a work."""
|
||||
|
||||
BASIC_RESEARCH = "Basic Research"
|
||||
APPLIED_RESEARCH = "Applied Research"
|
||||
NON_RESEARCH = "Non-Research"
|
||||
EXPERIMENTAL_DEVELOPMENT = "Experimental Development"
|
||||
|
||||
|
||||
class SpecificWorkPurpose(BaseModel):
|
||||
"""Represents the purpose of a specific work, including its ID, purpose, and optional reasoning."""
|
||||
|
||||
raw_oa_work_id: str = Field(description="The raw OpenAlex work id.")
|
||||
publication_year: Optional[int] = Field(
|
||||
default=None, description="The publication year of the work."
|
||||
)
|
||||
purpose: WorkPurpose = Field(description="The purpose of the work.")
|
||||
reasoning: Optional[str] = Field(
|
||||
default=None, description="The reasoning behind the purpose determination."
|
||||
)
|
||||
|
||||
|
||||
class AuthorWorkPurposes(BaseModel):
|
||||
"""Represents the purposes of an author, including their ID and a list of specific work purposes."""
|
||||
|
||||
raw_oa_author_id: str = Field(description="The raw OpenAlex author id.")
|
||||
total: int = Field(
|
||||
default=0, description="The total number of works for the author."
|
||||
)
|
||||
purposes: List[SpecificWorkPurpose] = Field(
|
||||
default_factory=list, description="The list of specific work purposes."
|
||||
)
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Path
|
||||
|
||||
from inse.tags import Tags
|
||||
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose
|
||||
|
||||
from inse.works import purpose_service
|
||||
|
||||
WORKS_PREFIX = "/api/purpose"
|
||||
|
||||
router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{raw_oa_work_id}/purpose",
|
||||
operation_id="getWorkPurpose",
|
||||
summary="Returns the purpose of a work based on its ID.",
|
||||
)
|
||||
async def get_work_purpose(
|
||||
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
|
||||
) -> SpecificWorkPurpose:
|
||||
return await purpose_service.get_work_purpose(raw_oa_work_id=raw_oa_work_id)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{raw_oa_author_id}/purposes",
|
||||
operation_id="getAuthorWorkPurposes",
|
||||
summary="Returns the purposes of an author based on their ID.",
|
||||
)
|
||||
async def get_author_work_purposes(
|
||||
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
|
||||
) -> AuthorWorkPurposes:
|
||||
return await purpose_service.get_author_work_purposes(
|
||||
raw_oa_author_id=raw_oa_author_id
|
||||
)
|
||||
@@ -1,153 +0,0 @@
|
||||
import logging
|
||||
from typing import Dict, List
|
||||
|
||||
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
|
||||
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
|
||||
raw_oa_work_id = raw_oa_work_id.strip().upper()
|
||||
|
||||
response = await elasticsearch.get(
|
||||
index=ESIndex.OPENALEX_WORKS_WILDCARD,
|
||||
doc_id=raw_oa_work_id,
|
||||
source=["title", "abstract"],
|
||||
)
|
||||
|
||||
logger.debug(f"Elasticsearch response for work id {raw_oa_work_id}: {response}")
|
||||
|
||||
source = response.get("_source", {})
|
||||
if not source:
|
||||
raise NotFoundException(f"Work with id {raw_oa_work_id} not found.")
|
||||
|
||||
logger.debug(f"Found work source for id {raw_oa_work_id}: {source}")
|
||||
|
||||
return SpecificWorkPurpose(
|
||||
raw_oa_work_id=raw_oa_work_id,
|
||||
publication_year=source.get("publication_year"),
|
||||
purpose=WorkPurpose.NON_RESEARCH, # TODO: Replace with actual purpose determination logic
|
||||
reasoning="This is a placeholder reasoning for the purpose determination.",
|
||||
)
|
||||
|
||||
|
||||
async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
|
||||
raw_oa_author_id = raw_oa_author_id.strip().upper()
|
||||
logger.debug(f"Retrieving work purposes for author {raw_oa_author_id}")
|
||||
relevant_work_information = await get_relevant_work_information(raw_oa_author_id)
|
||||
logger.debug(
|
||||
f"Retrieved work ids for author {raw_oa_author_id}: {list(relevant_work_information.keys())}"
|
||||
)
|
||||
raw_work_ids = list(map(_extract_raw_work_id, relevant_work_information.keys()))
|
||||
logger.debug(
|
||||
f"Extracted raw work ids for author {raw_oa_author_id}: {raw_work_ids}"
|
||||
)
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.WORK_CLASSIFICATIONS,
|
||||
source=["work_id", "classification"],
|
||||
query={"terms": {"work_id": raw_work_ids}},
|
||||
size=10000,
|
||||
)
|
||||
logger.debug(f"Elasticsearch response for work classifications v2FOO: {response}")
|
||||
|
||||
purposes: List[SpecificWorkPurpose] = []
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
total_hits = hits_block.get("total", {}).get("value", 0)
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
work_id = source.get("work_id")
|
||||
classification = source.get("classification")
|
||||
if work_id:
|
||||
work_purpose = _primary_classification_category_to_work_purpose(
|
||||
classification.get("primary_category", "")
|
||||
)
|
||||
purposes.append(
|
||||
SpecificWorkPurpose(
|
||||
raw_oa_work_id=work_id,
|
||||
publication_year=relevant_work_information.get(
|
||||
f"https://openalex.org/{work_id}"
|
||||
),
|
||||
purpose=work_purpose,
|
||||
reasoning=classification.get("classification_reason"),
|
||||
)
|
||||
)
|
||||
else:
|
||||
logger.warning(f"Work hit without id for author {raw_oa_author_id}: {hit}")
|
||||
|
||||
return AuthorWorkPurposes(
|
||||
raw_oa_author_id=raw_oa_author_id, total=total_hits, purposes=purposes
|
||||
)
|
||||
|
||||
|
||||
async def get_relevant_work_information(raw_oa_author_id: str) -> Dict[str, int]:
|
||||
raw_oa_author_id = raw_oa_author_id.strip().upper()
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_WORKS_WILDCARD,
|
||||
source=["id", "publication_year"],
|
||||
query={
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"term": {
|
||||
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
size=10000,
|
||||
)
|
||||
|
||||
logger.debug(f"Elasticsearch response for author id {raw_oa_author_id}: {response}")
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
d: Dict[str, int] = {}
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
work_id = source.get("id")
|
||||
publication_year = source.get("publication_year")
|
||||
if work_id:
|
||||
d[work_id] = int(publication_year) if publication_year is not None else 0
|
||||
else:
|
||||
logger.warning(f"Work hit without id for author {raw_oa_author_id}: {hit}")
|
||||
|
||||
return d
|
||||
|
||||
|
||||
def _extract_raw_work_id(work_id: str) -> str:
|
||||
"""
|
||||
Extracts the raw work ID from a full OpenAlex work ID.
|
||||
For example, given "https://openalex.org/W1234567890", it returns "W1234567890".
|
||||
"""
|
||||
if not work_id:
|
||||
return ""
|
||||
return work_id.split("/")[-1]
|
||||
|
||||
|
||||
def _primary_classification_category_to_work_purpose(
|
||||
primary_category: str,
|
||||
) -> WorkPurpose:
|
||||
mapping = {
|
||||
"basic_research": WorkPurpose.BASIC_RESEARCH,
|
||||
"applied_research": WorkPurpose.APPLIED_RESEARCH,
|
||||
"non_research": WorkPurpose.NON_RESEARCH,
|
||||
"experimental_development": WorkPurpose.EXPERIMENTAL_DEVELOPMENT,
|
||||
}
|
||||
return mapping.get(
|
||||
primary_category, WorkPurpose.NON_RESEARCH
|
||||
) # Default to NON_RESEARCH if not found
|
||||
@@ -1,10 +1,12 @@
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
from typing import Optional, List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
from inse.model import Page
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.models.openalex.work import Work
|
||||
|
||||
|
||||
class WorkSortBy(StrEnum):
|
||||
@@ -15,34 +17,163 @@ class WorkSortBy(StrEnum):
|
||||
CITED_BY_COUNT = "cited_by_count"
|
||||
|
||||
|
||||
class AuthorWorkInstitution(BaseModel):
|
||||
institution_id: str = Field(
|
||||
description="The ID of the institution associated with the work"
|
||||
class WorkPage(Page[Work]):
|
||||
pass
|
||||
|
||||
|
||||
class WorkPrimaryCategory(StrEnum):
|
||||
"""Represents the primary category of a work."""
|
||||
|
||||
BASIC_RESEARCH = "basic_research"
|
||||
APPLIED_RESEARCH = "applied_research"
|
||||
NON_RESEARCH = "non_research"
|
||||
EXPERIMENTAL_DEVELOPMENT = "experimental_development"
|
||||
NOT_CLASSIFIED = "not_classified"
|
||||
|
||||
|
||||
class WorkClassificationAuthor(BaseModel):
|
||||
"""An author entry within a work classification document."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The OpenAlex author id.")
|
||||
display_name: Optional[str] = Field(
|
||||
default=None, description="The author's display name."
|
||||
)
|
||||
orcid: Optional[str] = Field(default=None, description="The author's ORCID id.")
|
||||
|
||||
|
||||
class WorkClassificationInstitution(BaseModel):
|
||||
"""An institution entry within a work classification document."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The OpenAlex institution id.")
|
||||
display_name: Optional[str] = Field(
|
||||
default=None, description="The institution's display name."
|
||||
)
|
||||
ror: Optional[str] = Field(default=None, description="The institution's ROR id.")
|
||||
|
||||
|
||||
class WorkClassificationTopicGroup(BaseModel):
|
||||
"""A domain/field/subfield group referenced within a classification topic."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The id of the group.")
|
||||
display_name: Optional[str] = Field(
|
||||
default=None, description="The display name of the group."
|
||||
)
|
||||
|
||||
|
||||
class WorkClassificationTopic(BaseModel):
|
||||
"""A topic entry within a work classification document."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The OpenAlex topic id.")
|
||||
display_name: Optional[str] = Field(
|
||||
default=None, description="The topic's display name."
|
||||
)
|
||||
score: Optional[float] = Field(
|
||||
default=None, description="The relevance score of the topic."
|
||||
)
|
||||
domain: Optional[WorkClassificationTopicGroup] = Field(
|
||||
default=None, description="The topic's domain."
|
||||
)
|
||||
field: Optional[WorkClassificationTopicGroup] = Field(
|
||||
default=None, description="The topic's field."
|
||||
)
|
||||
subfield: Optional[WorkClassificationTopicGroup] = Field(
|
||||
default=None, description="The topic's subfield."
|
||||
)
|
||||
|
||||
|
||||
class WorkClassificationDetails(BaseModel):
|
||||
"""The core classification result for a work."""
|
||||
|
||||
primary_category: Optional[WorkPrimaryCategory] = Field(
|
||||
default=None,
|
||||
description="The primary classification category assigned to the work.",
|
||||
)
|
||||
confidence: Optional[str] = Field(
|
||||
default=None, description="The confidence level of the classification."
|
||||
)
|
||||
pasteur_quadrant: Optional[str] = Field(
|
||||
default=None, description="The Pasteur quadrant classification, if applicable."
|
||||
)
|
||||
applied_orientation_score: Optional[int] = Field(
|
||||
default=None,
|
||||
description="The applied orientation score for the classification.",
|
||||
)
|
||||
insufficient_context: Optional[bool] = Field(
|
||||
default=None,
|
||||
description="Whether there was insufficient context to classify confidently.",
|
||||
)
|
||||
signals_used: Optional[List[str]] = Field(
|
||||
default=None, description="The signals used to arrive at the classification."
|
||||
)
|
||||
classification_reason: Optional[str] = Field(
|
||||
default=None, description="The reasoning behind the classification."
|
||||
)
|
||||
|
||||
|
||||
class WorkClassificationMeta(BaseModel):
|
||||
"""Metadata about how and when a classification was produced."""
|
||||
|
||||
model: Optional[str] = Field(
|
||||
default=None, description="The model used to produce the classification."
|
||||
)
|
||||
institution_name: str = Field(
|
||||
description="The name of the institution associated with the work"
|
||||
prompt_version: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The version of the prompt used to produce the classification.",
|
||||
)
|
||||
institution_country_code: str = Field(
|
||||
description="The country code of the institution associated with the work"
|
||||
classified_at: Optional[datetime] = Field(
|
||||
default=None,
|
||||
description="The timestamp at which the classification was produced.",
|
||||
)
|
||||
|
||||
|
||||
class AuthorWork(BaseModel):
|
||||
id: str = Field(description="The ID of the work")
|
||||
title: str = Field(description="The title of the work")
|
||||
type: str = Field(description="The type of the work")
|
||||
publication_year: int = Field(description="The year the work was published")
|
||||
language_code: str = Field(description="The language code of the work")
|
||||
institutions: List[AuthorWorkInstitution] = Field(
|
||||
description="A list of institutions associated with the work"
|
||||
class WorkClassificationValidation(BaseModel):
|
||||
"""Validation results for a classification."""
|
||||
|
||||
valid: Optional[bool] = Field(
|
||||
default=None, description="Whether the classification passed validation."
|
||||
)
|
||||
errors: Optional[List[str]] = Field(
|
||||
default=None, description="Validation errors, if any."
|
||||
)
|
||||
corrections: Optional[List[str]] = Field(
|
||||
default=None, description="Corrections applied, if any."
|
||||
)
|
||||
|
||||
|
||||
class WorkClassification(BaseModel):
|
||||
"""Represents a full work-classification document."""
|
||||
|
||||
work_id: str = Field(description="The full OpenAlex work id/URL.")
|
||||
doi: Optional[str] = Field(default=None, description="The DOI of the work.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the work.")
|
||||
publication_year: Optional[int] = Field(
|
||||
default=None, description="The publication year of the work."
|
||||
)
|
||||
authors: List[WorkClassificationAuthor] = Field(
|
||||
default_factory=list, description="The authors of the work."
|
||||
)
|
||||
institutions: List[WorkClassificationInstitution] = Field(
|
||||
default_factory=list, description="The institutions associated with the work."
|
||||
)
|
||||
topics: List[WorkTopic] = Field(
|
||||
description="A list of topics associated with the work"
|
||||
topics: List[WorkClassificationTopic] = Field(
|
||||
default_factory=list, description="The topics associated with the work."
|
||||
)
|
||||
cited_by_count: int = Field(
|
||||
description="The number of citations the work has received"
|
||||
classification: Optional[WorkClassificationDetails] = Field(
|
||||
default=None, description="The classification result for the work."
|
||||
)
|
||||
classification_meta: Optional[WorkClassificationMeta] = Field(
|
||||
default=None, description="Metadata about the classification."
|
||||
)
|
||||
validation: Optional[WorkClassificationValidation] = Field(
|
||||
default=None, description="Validation results for the classification."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, source: dict) -> Optional["WorkClassification"]:
|
||||
if not source or "work_id" not in source:
|
||||
return None
|
||||
return cls.model_validate(source)
|
||||
|
||||
|
||||
class AuthorWorkPage(Page[AuthorWork]):
|
||||
class WorkClassificationPage(Page[WorkClassification]):
|
||||
pass
|
||||
|
||||
@@ -1,19 +1,31 @@
|
||||
from typing import Annotated, List
|
||||
import logging
|
||||
from typing import Annotated, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Path, Query
|
||||
|
||||
from inse.tags import Tags
|
||||
from inse.model import SortDirection
|
||||
from inse.works.v2.model import AuthorWorkPage, WorkSortBy
|
||||
from inse.works.v2.model import (
|
||||
WorkClassification,
|
||||
WorkClassificationPage,
|
||||
WorkPage,
|
||||
WorkSortBy,
|
||||
)
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
WORKS_v2_PREFIX = "/api/v2/works"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v2/works", tags=[Tags.WORKS_V2])
|
||||
router = APIRouter(prefix=WORKS_v2_PREFIX, tags=[Tags.WORKS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{raw_oa_author_id}",
|
||||
"/author/{raw_oa_author_id}",
|
||||
operation_id="getAuthorWorkPage",
|
||||
summary="Returns a paginated list of works for a given author based on their ID.",
|
||||
)
|
||||
@@ -26,6 +38,9 @@ async def get_author_works(
|
||||
int,
|
||||
Query(description="The number of works to retrieve per page.", ge=1, le=100),
|
||||
] = 10,
|
||||
title: Annotated[
|
||||
str, Query(description="A title to filter by (partial matches allowed).")
|
||||
] = "",
|
||||
publication_years: Annotated[
|
||||
list[int],
|
||||
Query(description="A list of publication years to filter by."),
|
||||
@@ -52,13 +67,14 @@ async def get_author_works(
|
||||
sort_order: Annotated[
|
||||
SortDirection, Query(description="The order to sort by.")
|
||||
] = SortDirection.DESCENDING,
|
||||
) -> AuthorWorkPage:
|
||||
) -> WorkPage:
|
||||
from inse.works.v2.service import get_author_works
|
||||
|
||||
return await get_author_works(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
page=page,
|
||||
size=size,
|
||||
title=title,
|
||||
publication_years=publication_years or [],
|
||||
publication_types=publication_types or [],
|
||||
institution_ids=institution_ids or [],
|
||||
@@ -69,6 +85,69 @@ async def get_author_works(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/{raw_oa_institution_id}",
|
||||
operation_id="getInstitutionWorkPage",
|
||||
summary="Returns a paginated list of works for a given institution based on their ID.",
|
||||
)
|
||||
async def get_institution_works(
|
||||
raw_oa_institution_id: Annotated[
|
||||
str, Path(description="The raw OpenAlex institution id.")
|
||||
],
|
||||
page: Annotated[
|
||||
int, Query(description="The page number to retrieve. (0-based)", ge=0)
|
||||
] = 0,
|
||||
title: Annotated[
|
||||
str, Query(description="A title to filter by (partial matches allowed).")
|
||||
] = "",
|
||||
size: Annotated[
|
||||
int,
|
||||
Query(description="The number of works to retrieve per page.", ge=1, le=100),
|
||||
] = 10,
|
||||
publication_years: Annotated[
|
||||
list[int],
|
||||
Query(description="A list of publication years to filter by."),
|
||||
] = [],
|
||||
publication_types: Annotated[
|
||||
list[str],
|
||||
Query(description="A list of publication types to filter by."),
|
||||
] = [],
|
||||
author_ids: Annotated[
|
||||
list[str],
|
||||
Query(description="A list of author IDs to filter by."),
|
||||
] = [],
|
||||
topic_ids: Annotated[
|
||||
list[str],
|
||||
Query(description="A list of topic IDs to filter by."),
|
||||
] = [],
|
||||
language_codes: Annotated[
|
||||
list[str],
|
||||
Query(description="A list of language codes to filter by."),
|
||||
] = [],
|
||||
sort_by: Annotated[
|
||||
WorkSortBy, Query(description="The field to sort by.")
|
||||
] = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: Annotated[
|
||||
SortDirection, Query(description="The order to sort by.")
|
||||
] = SortDirection.DESCENDING,
|
||||
) -> WorkPage:
|
||||
from inse.works.v2.service import get_institution_works
|
||||
|
||||
return await get_institution_works(
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
page=page,
|
||||
size=size,
|
||||
title=title,
|
||||
publication_years=publication_years or [],
|
||||
publication_types=publication_types or [],
|
||||
author_ids=author_ids or [],
|
||||
topic_ids=topic_ids or [],
|
||||
language_codes=language_codes or [],
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topics/search",
|
||||
operation_id="getWorkTopicsByIds",
|
||||
@@ -99,3 +178,138 @@ async def get_institutions_by_ids(
|
||||
from inse.works.v2.service import get_work_institutions_by_ids
|
||||
|
||||
return await get_work_institutions_by_ids(institution_ids=institution_ids or [])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/authors/search",
|
||||
operation_id="getAuthorsByIds",
|
||||
summary="Returns a list of authors based on their IDs.",
|
||||
)
|
||||
async def get_authors_by_ids(
|
||||
author_ids: Annotated[
|
||||
list[str],
|
||||
Query(description="A list of author IDs to retrieve."),
|
||||
] = [],
|
||||
) -> List[Author]:
|
||||
from inse.works.v2.service import get_work_authors_by_ids
|
||||
|
||||
return await get_work_authors_by_ids(author_ids=author_ids or [])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topics/autocomplete",
|
||||
operation_id="getTopicAutocomplete",
|
||||
summary="Returns a list of work topics based on a search term for autocomplete functionality.",
|
||||
)
|
||||
async def get_topic_autocomplete(
|
||||
query: Annotated[
|
||||
str,
|
||||
Query(
|
||||
description="A search term to filter topics by (partial matches allowed)."
|
||||
),
|
||||
] = "",
|
||||
) -> List[Topic]:
|
||||
from inse.works.v2.service import search_topics
|
||||
|
||||
return await search_topics(query=query)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institutions/autocomplete",
|
||||
operation_id="getInstitutionAutocomplete",
|
||||
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
|
||||
)
|
||||
async def get_institution_autocomplete(
|
||||
query: Annotated[
|
||||
str,
|
||||
Query(
|
||||
description="A search term to filter institutions by (partial matches allowed)."
|
||||
),
|
||||
] = "",
|
||||
) -> List[Institution]:
|
||||
from inse.works.v2.service import search_institutions
|
||||
|
||||
return await search_institutions(query=query)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/authors/autocomplete",
|
||||
operation_id="getAuthorAutocomplete",
|
||||
summary="Returns a list of authors based on a search term for autocomplete functionality.",
|
||||
)
|
||||
async def get_author_autocomplete(
|
||||
query: Annotated[
|
||||
str,
|
||||
Query(
|
||||
description="A search term to filter authors by (partial matches allowed)."
|
||||
),
|
||||
] = "",
|
||||
) -> List[Author]:
|
||||
from inse.works.v2.service import search_authors
|
||||
|
||||
return await search_authors(query=query)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/classification/author/{raw_oa_author_id}",
|
||||
operation_id="getAuthorWorkClassifications",
|
||||
summary="Returns the classifications of an author's works based on their ID.",
|
||||
)
|
||||
async def get_author_work_classifications(
|
||||
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
|
||||
) -> WorkClassificationPage:
|
||||
from inse.works.v2.service import get_work_classifications_by_author_id
|
||||
|
||||
return await get_work_classifications_by_author_id(
|
||||
raw_oa_author_id=raw_oa_author_id
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/classification/work/{work_id}",
|
||||
operation_id="getWorkClassificationByWorkId",
|
||||
summary="Returns the classifications of a work based on its ID.",
|
||||
)
|
||||
async def get_work_classification_by_work_id(
|
||||
work_id: Annotated[str, Path(description="The OpenAlex work id.")],
|
||||
) -> Optional[WorkClassification]:
|
||||
from inse.works.v2.service import get_work_classification_by_work_id
|
||||
|
||||
return await get_work_classification_by_work_id(work_id=work_id)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/classification/works/search",
|
||||
operation_id="getWorkClassificationsByWorkIds",
|
||||
summary="Returns the classifications of works based on their IDs.",
|
||||
)
|
||||
async def get_work_classifications_by_work_ids(
|
||||
work_ids: Annotated[
|
||||
list[str],
|
||||
Query(
|
||||
description="A list of OpenAlex work IDs to retrieve classifications for."
|
||||
),
|
||||
] = [],
|
||||
page: Annotated[
|
||||
int, Query(description="The page number to retrieve. (0-based)", ge=0)
|
||||
] = 0,
|
||||
size: Annotated[
|
||||
int,
|
||||
Query(
|
||||
description="The number of classifications to retrieve per page.",
|
||||
ge=1,
|
||||
le=100,
|
||||
),
|
||||
] = 10,
|
||||
) -> WorkClassificationPage:
|
||||
from inse.works.v2.service import get_work_classifications_by_work_ids
|
||||
|
||||
logger.debug(
|
||||
f"Fetching work classifications for work IDs: {work_ids}, page: {page}, size: {size}"
|
||||
)
|
||||
|
||||
return await get_work_classifications_by_work_ids(
|
||||
work_ids=work_ids or [],
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
|
||||
@@ -1,80 +1,94 @@
|
||||
import logging
|
||||
from typing import List, Optional, Dict
|
||||
from typing import List, Optional
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex, SortDirection
|
||||
from inse.works.v2.model import (
|
||||
AuthorWork,
|
||||
AuthorWorkInstitution,
|
||||
AuthorWorkPage,
|
||||
WorkClassification,
|
||||
WorkClassificationPage,
|
||||
WorkPage,
|
||||
WorkSortBy,
|
||||
)
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.work import Work
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
async def get_author_works(
|
||||
raw_oa_author_id: str,
|
||||
page: int,
|
||||
size: int,
|
||||
publication_years: Optional[List[int]] = None,
|
||||
publication_types: Optional[List[str]] = None,
|
||||
institution_ids: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
language_codes: Optional[List[str]] = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> AuthorWorkPage:
|
||||
|
||||
must = [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
|
||||
}
|
||||
},
|
||||
}
|
||||
def _authors_nested_query(author_ids: List[str]) -> dict:
|
||||
prefixed = [_prefix_id(aid) for aid in author_ids]
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": prefixed}},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _institutions_nested_query(institution_ids: List[str]) -> dict:
|
||||
prefixed = [_prefix_id(iid) for iid in institution_ids]
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"terms": {"authorships.institutions.id": prefixed}},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _title_query(title: str) -> dict:
|
||||
return {
|
||||
"multi_match": {
|
||||
"query": title,
|
||||
"type": "bool_prefix",
|
||||
"fields": [
|
||||
"title.search_as_you_type",
|
||||
"title.search_as_you_type._2gram",
|
||||
"title.search_as_you_type._3gram",
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _apply_common_filters(
|
||||
must: list,
|
||||
publication_years: Optional[List[int]],
|
||||
publication_types: Optional[List[str]],
|
||||
language_codes: Optional[List[str]],
|
||||
topic_ids: Optional[List[str]],
|
||||
title: Optional[str] = None,
|
||||
) -> None:
|
||||
if publication_years:
|
||||
must.append({"terms": {"publication_year": publication_years}})
|
||||
if publication_types:
|
||||
must.append({"terms": {"type": publication_types}})
|
||||
if language_codes:
|
||||
must.append({"terms": {"language": language_codes}})
|
||||
if institution_ids:
|
||||
must.append(
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": institution_ids
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
if topic_ids:
|
||||
must.append(
|
||||
{"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}}
|
||||
)
|
||||
if title and len(title.strip()) > 0:
|
||||
must.append(_title_query(title))
|
||||
|
||||
|
||||
def _build_sort(sort_by: WorkSortBy, sort_order: SortDirection) -> list:
|
||||
if sort_by == WorkSortBy.TITLE:
|
||||
sort = [{"title.keyword": sort_order.value}]
|
||||
else:
|
||||
sort = [{sort_by.value: sort_order.value}]
|
||||
return [{"title.keyword": sort_order.value}]
|
||||
return [{sort_by.value: sort_order.value}]
|
||||
|
||||
|
||||
async def _execute_works_search(
|
||||
must: list, page: int, size: int, sort_by: WorkSortBy, sort_order: SortDirection
|
||||
) -> WorkPage:
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.OPENALEX_WORKS_WILDCARD,
|
||||
source=[
|
||||
@@ -84,6 +98,7 @@ async def get_author_works(
|
||||
"publication_year",
|
||||
"language",
|
||||
"cited_by_count",
|
||||
"authorships.author",
|
||||
"authorships.institutions.id",
|
||||
"authorships.institutions.display_name",
|
||||
"authorships.institutions.country_code",
|
||||
@@ -92,47 +107,112 @@ async def get_author_works(
|
||||
query={"bool": {"must": must}},
|
||||
size=size,
|
||||
offset=page * size,
|
||||
sort=sort,
|
||||
sort=_build_sort(sort_by, sort_order),
|
||||
)
|
||||
|
||||
logger.debug(f"Elasticsearch response for author {raw_oa_author_id} v2: {response}")
|
||||
hits_block = response.get("hits", {})
|
||||
total = hits_block.get("total", {}).get("value", 0)
|
||||
hits = hits_block.get("hits", [])
|
||||
elements: List[AuthorWork] = []
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
logger.debug(f"Hit source for author {raw_oa_author_id} v2: {source}")
|
||||
institutions: Dict[str, AuthorWorkInstitution] = {}
|
||||
for authorship in source.get("authorships", []):
|
||||
for institution in authorship.get("institutions", []):
|
||||
institution_id = institution.get("id", "")
|
||||
if institution_id not in institutions:
|
||||
institutions[institution_id] = AuthorWorkInstitution(
|
||||
institution_id=institution.get("id", ""),
|
||||
institution_name=institution.get("display_name", ""),
|
||||
institution_country_code=institution.get("country_code") or "",
|
||||
)
|
||||
topics: List[WorkTopic] = [
|
||||
WorkTopic.from_dict(topic) for topic in source.get("topics", [])
|
||||
] # type: ignore
|
||||
elements.append(
|
||||
AuthorWork(
|
||||
id=source.get("id", ""),
|
||||
title=source.get("title", ""),
|
||||
type=source.get("type", ""),
|
||||
publication_year=source.get("publication_year", 0),
|
||||
language_code=source.get("language") or "",
|
||||
institutions=list(institutions.values()),
|
||||
topics=topics,
|
||||
cited_by_count=source.get("cited_by_count", 0),
|
||||
)
|
||||
elements: List[Work] = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
work = Work.from_dict(hit.get("_source", {})) # type: ignore
|
||||
if work is not None:
|
||||
elements.append(work)
|
||||
|
||||
return WorkPage(elements=elements, total=total, page=page, size=size)
|
||||
|
||||
|
||||
async def get_works(
|
||||
page: int,
|
||||
size: int,
|
||||
raw_oa_author_id: Optional[str] = None,
|
||||
raw_oa_institution_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
author_ids: Optional[List[str]] = None,
|
||||
institution_ids: Optional[List[str]] = None,
|
||||
publication_years: Optional[List[int]] = None,
|
||||
publication_types: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
language_codes: Optional[List[str]] = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPage:
|
||||
if not raw_oa_author_id and not raw_oa_institution_id:
|
||||
raise ValueError(
|
||||
"get_works requires at least one of raw_oa_author_id or raw_oa_institution_id"
|
||||
)
|
||||
return AuthorWorkPage(
|
||||
elements=elements,
|
||||
total=total,
|
||||
|
||||
must: List = []
|
||||
|
||||
if raw_oa_author_id:
|
||||
must.append(_authors_nested_query([raw_oa_author_id]))
|
||||
elif author_ids:
|
||||
must.append(_authors_nested_query(author_ids))
|
||||
|
||||
if raw_oa_institution_id:
|
||||
must.append(_institutions_nested_query([raw_oa_institution_id]))
|
||||
elif institution_ids:
|
||||
must.append(_institutions_nested_query(institution_ids))
|
||||
|
||||
_apply_common_filters(
|
||||
must, publication_years, publication_types, language_codes, topic_ids, title
|
||||
)
|
||||
|
||||
return await _execute_works_search(must, page, size, sort_by, sort_order)
|
||||
|
||||
|
||||
async def get_author_works(
|
||||
raw_oa_author_id: str,
|
||||
page: int,
|
||||
size: int,
|
||||
title: str = "",
|
||||
publication_years: Optional[List[int]] = None,
|
||||
publication_types: Optional[List[str]] = None,
|
||||
institution_ids: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
language_codes: Optional[List[str]] = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPage:
|
||||
return await get_works(
|
||||
page=page,
|
||||
size=size,
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
title=title,
|
||||
institution_ids=institution_ids,
|
||||
publication_years=publication_years,
|
||||
publication_types=publication_types,
|
||||
topic_ids=topic_ids,
|
||||
language_codes=language_codes,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
|
||||
|
||||
async def get_institution_works(
|
||||
raw_oa_institution_id: str,
|
||||
page: int,
|
||||
size: int,
|
||||
title: str = "",
|
||||
publication_years: Optional[List[int]] = None,
|
||||
publication_types: Optional[List[str]] = None,
|
||||
author_ids: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
language_codes: Optional[List[str]] = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPage:
|
||||
return await get_works(
|
||||
page=page,
|
||||
size=size,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
author_ids=author_ids,
|
||||
title=title,
|
||||
publication_years=publication_years,
|
||||
publication_types=publication_types,
|
||||
topic_ids=topic_ids,
|
||||
language_codes=language_codes,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
|
||||
|
||||
@@ -170,7 +250,14 @@ async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Insti
|
||||
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.OPENALEX_INSTITUTIONS,
|
||||
source=["id", "display_name", "country_code"],
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"display_name_alternatives",
|
||||
"country_code",
|
||||
"type",
|
||||
"ror",
|
||||
],
|
||||
query={"bool": {"must": must}},
|
||||
size=len(institution_ids),
|
||||
)
|
||||
@@ -186,3 +273,247 @@ async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Insti
|
||||
logger.debug(f"Hit source for institution {source.get('id', '')}: {source}")
|
||||
institutions.append(Institution.from_dict(source)) # type: ignore
|
||||
return institutions
|
||||
|
||||
|
||||
async def get_work_authors_by_ids(author_ids: List[str]) -> List[Author]:
|
||||
logger.debug(f"Fetching authors for IDs: {author_ids}")
|
||||
if not author_ids:
|
||||
return []
|
||||
|
||||
must = [{"terms": {"id": author_ids}}]
|
||||
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.OPENALEX_AUTHORS,
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"orcid",
|
||||
"last_known_institutions",
|
||||
"works_count",
|
||||
],
|
||||
query={"bool": {"must": must}},
|
||||
size=len(author_ids),
|
||||
)
|
||||
|
||||
logger.debug(f"Elasticsearch response for authors {author_ids}: {response}")
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
authors: List[Author] = []
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
logger.debug(f"Hit source for author {source.get('id', '')}: {source}")
|
||||
authors.append(Author.from_dict(source)) # type: ignore
|
||||
return authors
|
||||
|
||||
|
||||
async def search_topics(
|
||||
query: str,
|
||||
size: int = 10,
|
||||
) -> List[Topic]:
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.OPENALEX_TOPICS,
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"subfield",
|
||||
"field",
|
||||
"domain",
|
||||
],
|
||||
query={"match_bool_prefix": {"display_name": query}},
|
||||
size=min(size, 10),
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
elements: List[Topic] = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
topic = Topic.from_dict(hit.get("_source", {})) # type: ignore
|
||||
if topic is not None:
|
||||
elements.append(topic)
|
||||
|
||||
return elements
|
||||
|
||||
|
||||
async def search_institutions(
|
||||
query: str,
|
||||
size: int = 10,
|
||||
) -> List[Institution]:
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.OPENALEX_INSTITUTIONS,
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"display_name_alternatives",
|
||||
"country_code",
|
||||
"type",
|
||||
"ror",
|
||||
],
|
||||
query={
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_bool_prefix": {"display_name": query}},
|
||||
{"match_bool_prefix": {"display_name_alternatives": query}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
size=min(size, 10),
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
elements: List[Institution] = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
institution = Institution.from_dict(hit.get("_source", {})) # type: ignore
|
||||
if institution is not None:
|
||||
elements.append(institution)
|
||||
|
||||
return elements
|
||||
|
||||
|
||||
async def search_authors(
|
||||
query: str,
|
||||
size: int = 10,
|
||||
) -> List[Author]:
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.OPENALEX_AUTHORS,
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"orcid",
|
||||
"last_known_institutions",
|
||||
"works_count",
|
||||
],
|
||||
query={"match_phrase_prefix": {"display_name": query}},
|
||||
size=min(size, 10),
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
elements: List[Author] = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
author = Author.from_dict(hit.get("_source", {})) # type: ignore
|
||||
if author is not None:
|
||||
elements.append(author)
|
||||
|
||||
return elements
|
||||
|
||||
|
||||
async def get_work_classifications_by_author_id(
|
||||
raw_oa_author_id: str,
|
||||
page: int = 0,
|
||||
size: int = 10000,
|
||||
) -> WorkClassificationPage:
|
||||
must = [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authors",
|
||||
"query": {"term": {"authors.id": f"{_prefix_id(raw_oa_author_id)}"}},
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.WORK_CLASSIFICATIONS,
|
||||
source=[
|
||||
"work_id",
|
||||
"doi",
|
||||
"title",
|
||||
"publication_year",
|
||||
"authors",
|
||||
"institutions",
|
||||
"topics",
|
||||
"classification",
|
||||
],
|
||||
query={"bool": {"must": must}},
|
||||
size=size,
|
||||
offset=page * size,
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
total = hits_block.get("total", {}).get("value", 0)
|
||||
elements = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
classification = WorkClassification.from_dict(hit.get("_source", {})) # type: ignore
|
||||
if classification is not None:
|
||||
elements.append(classification)
|
||||
|
||||
return WorkClassificationPage(
|
||||
elements=elements,
|
||||
total=total,
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
|
||||
|
||||
async def get_work_classification_by_work_id(
|
||||
work_id: str,
|
||||
) -> Optional[WorkClassification]:
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.WORK_CLASSIFICATIONS,
|
||||
source=[
|
||||
"work_id",
|
||||
"doi",
|
||||
"title",
|
||||
"publication_year",
|
||||
"authors",
|
||||
"institutions",
|
||||
"topics",
|
||||
"classification",
|
||||
"classification_meta",
|
||||
"validation",
|
||||
],
|
||||
query={"term": {"work_id": f"{_prefix_id(work_id)}"}},
|
||||
size=1,
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None
|
||||
|
||||
return WorkClassification.from_dict(hits[0].get("_source", {}))
|
||||
|
||||
|
||||
async def get_work_classifications_by_work_ids(
|
||||
work_ids: List[str],
|
||||
page: int = 0,
|
||||
size: int = 10000,
|
||||
) -> WorkClassificationPage:
|
||||
prefixed = [_prefix_id(wid) for wid in work_ids]
|
||||
|
||||
logger.debug(f"Fetching work classifications for work IDs: {prefixed}")
|
||||
|
||||
response = await elasticsearch.search(
|
||||
ESIndex.WORK_CLASSIFICATIONS,
|
||||
source=[
|
||||
"work_id",
|
||||
"doi",
|
||||
"title",
|
||||
"publication_year",
|
||||
"authors",
|
||||
"institutions",
|
||||
"topics",
|
||||
"classification",
|
||||
"classification_meta",
|
||||
"validation",
|
||||
],
|
||||
query={"terms": {"work_id": prefixed}},
|
||||
size=size,
|
||||
offset=page * size,
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
total = hits_block.get("total", {}).get("value", 0)
|
||||
elements: List[WorkClassification] = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
classification = WorkClassification.from_dict(hit.get("_source", {}))
|
||||
if classification is not None:
|
||||
elements.append(classification)
|
||||
|
||||
p = WorkClassificationPage(elements=elements, total=total, page=page, size=size)
|
||||
logger.debug(f"Returning WorkClassificationPage: {p}")
|
||||
|
||||
return p
|
||||
|
||||
|
||||
def _prefix_id(raw_id: str) -> str:
|
||||
if not raw_id.startswith("https://openalex.org/"):
|
||||
return f"https://openalex.org/{raw_id}"
|
||||
return raw_id
|
||||
|
||||
@@ -1141,6 +1141,12 @@ Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/work-classifications/_mapping
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/work-classifications/_search
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
@@ -1165,16 +1171,29 @@ Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-authors/_mapping
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-topics/_mapping
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-topics/_search
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-topics/_mapping
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-institutions/_search
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-authors/_mapping
|
||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||
Content-Type: application/json
|
||||
|
||||
|
||||
###
|
||||
|
||||
GET https://project.nes.uni-due.de/elastic/openalex-authors/_search
|
||||
|
||||
@@ -40,10 +40,6 @@ model/authorNetworkNode.ts
|
||||
model/authorParsedLongestName.ts
|
||||
model/authorPositionCount.ts
|
||||
model/authorSummaryStats.ts
|
||||
model/authorWork.ts
|
||||
model/authorWorkInstitution.ts
|
||||
model/authorWorkPage.ts
|
||||
model/authorWorkPurposes.ts
|
||||
model/authorsFilterProperties.ts
|
||||
model/authorsListResponse.ts
|
||||
model/authorship.ts
|
||||
@@ -133,7 +129,9 @@ model/hEUWebLink.ts
|
||||
model/hTTPValidationError.ts
|
||||
model/idTokenMetadata.ts
|
||||
model/inseAccountManagementModelOrganizationProfile.ts
|
||||
model/inseModelsOpenalexWorkPageWorkPage.ts
|
||||
model/inseOrganizationManagementModelOrganizationProfile.ts
|
||||
model/inseWorksV2ModelWorkPage.ts
|
||||
model/institution.ts
|
||||
model/institutionFunderSummary.ts
|
||||
model/institutionGeo.ts
|
||||
@@ -195,7 +193,6 @@ model/rankingResponse.ts
|
||||
model/rebuildResponse.ts
|
||||
model/score.ts
|
||||
model/sortDirection.ts
|
||||
model/specificWorkPurpose.ts
|
||||
model/tokenType.ts
|
||||
model/topAuthor.ts
|
||||
model/topAuthorStatistics.ts
|
||||
@@ -231,14 +228,22 @@ model/work.ts
|
||||
model/workBiblio.ts
|
||||
model/workCitationNormalizedPercentile.ts
|
||||
model/workCitedByPercentileYear.ts
|
||||
model/workClassification.ts
|
||||
model/workClassificationAuthor.ts
|
||||
model/workClassificationDetails.ts
|
||||
model/workClassificationInstitution.ts
|
||||
model/workClassificationMeta.ts
|
||||
model/workClassificationPage.ts
|
||||
model/workClassificationTopic.ts
|
||||
model/workClassificationTopicGroup.ts
|
||||
model/workClassificationValidation.ts
|
||||
model/workCountsByYearInner.ts
|
||||
model/workHasContent.ts
|
||||
model/workIds.ts
|
||||
model/workKeyword.ts
|
||||
model/workMeshInner.ts
|
||||
model/workNetworkNode.ts
|
||||
model/workPage.ts
|
||||
model/workPurpose.ts
|
||||
model/workPrimaryCategory.ts
|
||||
model/workSortBy.ts
|
||||
model/workSustainableDevelopmentGoalsInner.ts
|
||||
model/workTopic.ts
|
||||
|
||||
@@ -22,12 +22,10 @@ import {
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AuthorWorkPurposes } from '../model/authorWorkPurposes';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { SpecificWorkPurpose } from '../model/specificWorkPurpose';
|
||||
import { InseModelsOpenalexWorkPageWorkPage } from '../model/inseModelsOpenalexWorkPageWorkPage';
|
||||
// @ts-ignore
|
||||
import { TopicCount } from '../model/topicCount';
|
||||
// @ts-ignore
|
||||
@@ -35,8 +33,6 @@ import { TopicsByTime } from '../model/topicsByTime';
|
||||
// @ts-ignore
|
||||
import { Work } from '../model/work';
|
||||
// @ts-ignore
|
||||
import { WorkPage } from '../model/workPage';
|
||||
// @ts-ignore
|
||||
import { WorksListResponse } from '../model/worksListResponse';
|
||||
|
||||
// @ts-ignore
|
||||
@@ -158,108 +154,6 @@ export class WorksService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the purposes of an author based on their ID.
|
||||
* @endpoint get /api/purpose/{raw_oa_author_id}/purposes
|
||||
* @param rawOaAuthorId The raw OpenAlex author id.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAuthorWorkPurposes(
|
||||
rawOaAuthorId: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<AuthorWorkPurposes>;
|
||||
public getAuthorWorkPurposes(
|
||||
rawOaAuthorId: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<AuthorWorkPurposes>>;
|
||||
public getAuthorWorkPurposes(
|
||||
rawOaAuthorId: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<AuthorWorkPurposes>>;
|
||||
public getAuthorWorkPurposes(
|
||||
rawOaAuthorId: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter rawOaAuthorId was null or undefined when calling getAuthorWorkPurposes.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/purpose/${this.configuration.encodeParam({ name: 'rawOaAuthorId', value: rawOaAuthorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/purposes`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AuthorWorkPurposes>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a page of works for an author.
|
||||
* @endpoint get /api/works/{author_id}
|
||||
@@ -292,7 +186,7 @@ export class WorksService extends BaseService {
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<WorkPage>;
|
||||
): Observable<InseModelsOpenalexWorkPageWorkPage>;
|
||||
public getAuthorWorks(
|
||||
authorId: string,
|
||||
page?: number,
|
||||
@@ -310,7 +204,7 @@ export class WorksService extends BaseService {
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<WorkPage>>;
|
||||
): Observable<HttpResponse<InseModelsOpenalexWorkPageWorkPage>>;
|
||||
public getAuthorWorks(
|
||||
authorId: string,
|
||||
page?: number,
|
||||
@@ -328,7 +222,7 @@ export class WorksService extends BaseService {
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<WorkPage>>;
|
||||
): Observable<HttpEvent<InseModelsOpenalexWorkPageWorkPage>>;
|
||||
public getAuthorWorks(
|
||||
authorId: string,
|
||||
page?: number,
|
||||
@@ -447,7 +341,7 @@ export class WorksService extends BaseService {
|
||||
|
||||
let localVarPath = `/api/works/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<WorkPage>(
|
||||
return this.httpClient.request<InseModelsOpenalexWorkPageWorkPage>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
@@ -812,106 +706,4 @@ export class WorksService extends BaseService {
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the purpose of a work based on its ID.
|
||||
* @endpoint get /api/purpose/{raw_oa_work_id}/purpose
|
||||
* @param rawOaWorkId The raw OpenAlex work id.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getWorkPurpose(
|
||||
rawOaWorkId: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<SpecificWorkPurpose>;
|
||||
public getWorkPurpose(
|
||||
rawOaWorkId: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<SpecificWorkPurpose>>;
|
||||
public getWorkPurpose(
|
||||
rawOaWorkId: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<SpecificWorkPurpose>>;
|
||||
public getWorkPurpose(
|
||||
rawOaWorkId: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (rawOaWorkId === null || rawOaWorkId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter rawOaWorkId was null or undefined when calling getWorkPurpose.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/purpose/${this.configuration.encodeParam({ name: 'rawOaWorkId', value: rawOaWorkId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/purpose`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<SpecificWorkPurpose>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { AuthorWorkInstitution } from './authorWorkInstitution';
|
||||
import { WorkTopic } from './workTopic';
|
||||
|
||||
export interface AuthorWork {
|
||||
/**
|
||||
* The ID of the work
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* The title of the work
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* The type of the work
|
||||
*/
|
||||
type: string;
|
||||
/**
|
||||
* The year the work was published
|
||||
*/
|
||||
publication_year: number;
|
||||
/**
|
||||
* The language code of the work
|
||||
*/
|
||||
language_code: string;
|
||||
/**
|
||||
* A list of institutions associated with the work
|
||||
*/
|
||||
institutions: Array<AuthorWorkInstitution>;
|
||||
/**
|
||||
* A list of topics associated with the work
|
||||
*/
|
||||
topics: Array<WorkTopic>;
|
||||
/**
|
||||
* The number of citations the work has received
|
||||
*/
|
||||
cited_by_count: number;
|
||||
}
|
||||