Improve DFG top author OpenAlex matching
This commit is contained in:
@@ -20,6 +20,7 @@ class DashboardStatisticValue(BaseModel):
|
||||
|
||||
class TopAuthor(BaseModel):
|
||||
id: str | None = None
|
||||
dfg_person_id: int | None = None
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
@@ -30,6 +31,10 @@ TOPIC_HEATMAP_LIMIT = 25
|
||||
TOPIC_HEATMAP_YEARS = 5
|
||||
WorksPeriod = Literal["all_time", "last_5_years"]
|
||||
logger = logging.getLogger(__name__)
|
||||
ACADEMIC_TITLE_RE = re.compile(
|
||||
r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
DFG_INSTITUTION_FIELDS = [
|
||||
"Antragstellende Institution",
|
||||
@@ -50,6 +55,34 @@ def _total(response: dict[str, Any]) -> int:
|
||||
return int(total or 0)
|
||||
|
||||
|
||||
def _normalize_person_name(name: str) -> str:
|
||||
normalized = " ".join(name.strip().casefold().split())
|
||||
while True:
|
||||
without_title = ACADEMIC_TITLE_RE.sub("", normalized).strip()
|
||||
if without_title == normalized:
|
||||
return without_title
|
||||
normalized = without_title
|
||||
|
||||
|
||||
def _is_initial_surname_match(full_name: str, initial_name: str) -> bool:
|
||||
full_parts = _normalize_person_name(full_name).split()
|
||||
initial_parts = _normalize_person_name(initial_name).replace(".", "").split()
|
||||
if len(full_parts) < 2 or len(initial_parts) < 2:
|
||||
return False
|
||||
return (
|
||||
len(initial_parts[0]) == 1
|
||||
and full_parts[0].startswith(initial_parts[0])
|
||||
and full_parts[-1] == initial_parts[-1]
|
||||
)
|
||||
|
||||
|
||||
def _is_supported_name_variant(full_name: str, candidate_name: str) -> bool:
|
||||
return (
|
||||
_normalize_person_name(full_name) == _normalize_person_name(candidate_name)
|
||||
or _is_initial_surname_match(full_name, candidate_name)
|
||||
)
|
||||
|
||||
|
||||
def get_dashboard_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
@@ -709,11 +742,13 @@ async def _top_project_authors(
|
||||
|
||||
page += 1
|
||||
|
||||
institution_authors = {
|
||||
author["name"].strip().casefold(): author
|
||||
for author in authors
|
||||
if author.get("name")
|
||||
}
|
||||
institution_authors: dict[str, list[dict[str, Any]]] = {}
|
||||
for author in authors:
|
||||
if author.get("name"):
|
||||
institution_authors.setdefault(
|
||||
_normalize_person_name(author["name"]),
|
||||
[],
|
||||
).append(author)
|
||||
|
||||
ranked = sorted(
|
||||
(
|
||||
@@ -727,14 +762,33 @@ async def _top_project_authors(
|
||||
),
|
||||
)
|
||||
|
||||
ranked_person_ids = [person_id for person_id, _ in ranked[:TOP_AUTHOR_LIMIT]]
|
||||
dfg_orcids = await _dfg_person_orcids(ranked_person_ids)
|
||||
|
||||
result: list[TopAuthor] = []
|
||||
|
||||
for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]:
|
||||
dfg_name = names[person_id]
|
||||
matched_author = institution_authors.get(
|
||||
dfg_name.casefold()
|
||||
matched_author = _single_author_match(
|
||||
institution_authors.get(_normalize_person_name(dfg_name), [])
|
||||
)
|
||||
|
||||
if matched_author is None and (orcid := dfg_orcids.get(person_id)):
|
||||
matched_author = await _openalex_author_by_orcid(orcid)
|
||||
|
||||
if matched_author is None:
|
||||
matched_author = await _openalex_author_by_dfg_publication_evidence(
|
||||
dfg_name=dfg_name,
|
||||
project_ids=project_ids,
|
||||
)
|
||||
|
||||
if matched_author is None:
|
||||
logger.info(
|
||||
"No exact OpenAlex match for DFG author '%s' (person_id=%s).",
|
||||
dfg_name,
|
||||
person_id,
|
||||
)
|
||||
|
||||
result.append(
|
||||
TopAuthor(
|
||||
id=(
|
||||
@@ -742,6 +796,7 @@ async def _top_project_authors(
|
||||
if matched_author
|
||||
else None
|
||||
),
|
||||
dfg_person_id=person_id,
|
||||
name=(
|
||||
matched_author["name"]
|
||||
if matched_author
|
||||
@@ -767,6 +822,230 @@ async def _top_project_authors(
|
||||
return result
|
||||
|
||||
|
||||
def _single_author_match(authors: list[dict[str, Any]]) -> dict[str, Any] | None:
|
||||
return authors[0] if len(authors) == 1 else None
|
||||
|
||||
|
||||
async def _dfg_person_orcids(person_ids: list[int]) -> dict[int, str]:
|
||||
if not person_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_PERSONS,
|
||||
body={
|
||||
"size": len(person_ids),
|
||||
"_source": ["person_id", "orcid_id"],
|
||||
"query": {"terms": {"person_id": person_ids}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Could not load DFG ORCIDs for top project authors.")
|
||||
return {}
|
||||
|
||||
result: dict[int, str] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
person_id = source.get("person_id")
|
||||
orcid = source.get("orcid_id")
|
||||
if person_id is None or not orcid:
|
||||
continue
|
||||
try:
|
||||
result[int(person_id)] = str(orcid)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return result
|
||||
|
||||
|
||||
async def _openalex_author_by_orcid(orcid: str) -> dict[str, Any] | None:
|
||||
normalized_orcid = orcid.replace("https://orcid.org/", "").strip()
|
||||
if not normalized_orcid:
|
||||
return None
|
||||
|
||||
prefixed_orcid = f"https://orcid.org/{normalized_orcid}"
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
body={
|
||||
"size": 2,
|
||||
"_source": ["id", "display_name"],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"orcid.keyword": normalized_orcid}},
|
||||
{"term": {"orcid.keyword": prefixed_orcid}},
|
||||
{"term": {"ids.orcid.keyword": normalized_orcid}},
|
||||
{"term": {"ids.orcid.keyword": prefixed_orcid}},
|
||||
{"term": {"orcid": normalized_orcid}},
|
||||
{"term": {"orcid": prefixed_orcid}},
|
||||
{"term": {"ids.orcid": normalized_orcid}},
|
||||
{"term": {"ids.orcid": prefixed_orcid}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.NES,
|
||||
track_total_hits=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Could not resolve OpenAlex author by ORCID %s.", orcid)
|
||||
return None
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if len(hits) != 1:
|
||||
logger.info(
|
||||
"OpenAlex ORCID lookup for %s returned %s hits.",
|
||||
orcid,
|
||||
len(hits),
|
||||
)
|
||||
return None
|
||||
|
||||
source = hits[0].get("_source", {})
|
||||
if not source.get("id") or not source.get("display_name"):
|
||||
return None
|
||||
return {
|
||||
"id": str(source["id"]),
|
||||
"name": str(source["display_name"]),
|
||||
}
|
||||
|
||||
|
||||
async def _openalex_author_by_dfg_publication_evidence(
|
||||
dfg_name: str,
|
||||
project_ids: set[str],
|
||||
) -> dict[str, Any] | None:
|
||||
dois = await _dfg_project_publication_dois(project_ids)
|
||||
if not dois:
|
||||
return None
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body={
|
||||
"size": 10000,
|
||||
"_source": [
|
||||
"doi",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
],
|
||||
"query": {
|
||||
"terms": {
|
||||
"doi": sorted(_doi_variants(dois)),
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Could not resolve OpenAlex author from DFG publication DOIs for %s.",
|
||||
dfg_name,
|
||||
)
|
||||
return None
|
||||
|
||||
candidates: dict[str, dict[str, Any]] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
doi = source.get("doi")
|
||||
if not doi:
|
||||
continue
|
||||
for authorship in source.get("authorships", []) or []:
|
||||
author = authorship.get("author", {}) if isinstance(authorship, dict) else {}
|
||||
author_id = author.get("id")
|
||||
display_name = author.get("display_name")
|
||||
if not author_id or not display_name:
|
||||
continue
|
||||
if not _is_supported_name_variant(dfg_name, str(display_name)):
|
||||
continue
|
||||
candidate = candidates.setdefault(
|
||||
str(author_id),
|
||||
{
|
||||
"id": str(author_id),
|
||||
"name": str(display_name),
|
||||
"dois": set(),
|
||||
},
|
||||
)
|
||||
candidate["dois"].add(str(doi))
|
||||
|
||||
supported_candidates = [
|
||||
candidate
|
||||
for candidate in candidates.values()
|
||||
if len(candidate["dois"]) >= 2
|
||||
]
|
||||
if len(supported_candidates) != 1:
|
||||
if supported_candidates:
|
||||
logger.info(
|
||||
"DFG publication DOI lookup for %s returned %s candidates.",
|
||||
dfg_name,
|
||||
len(supported_candidates),
|
||||
)
|
||||
return None
|
||||
|
||||
candidate = supported_candidates[0]
|
||||
return {
|
||||
"id": candidate["id"],
|
||||
"name": candidate["name"],
|
||||
}
|
||||
|
||||
|
||||
async def _dfg_project_publication_dois(project_ids: set[str]) -> set[str]:
|
||||
if not project_ids:
|
||||
return set()
|
||||
|
||||
numeric_project_ids = [
|
||||
int(project_id)
|
||||
for project_id in project_ids
|
||||
if str(project_id).isdigit()
|
||||
]
|
||||
if not numeric_project_ids:
|
||||
return set()
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
body={
|
||||
"size": len(numeric_project_ids),
|
||||
"_source": ["publications.doi"],
|
||||
"query": {"terms": {"id": numeric_project_ids}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Could not load DFG publication DOIs.")
|
||||
return set()
|
||||
|
||||
dois: set[str] = set()
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
for publication in hit.get("_source", {}).get("publications", []) or []:
|
||||
doi = publication.get("doi") if isinstance(publication, dict) else None
|
||||
if doi:
|
||||
dois.add(str(doi).strip())
|
||||
return {doi for doi in dois if doi}
|
||||
|
||||
|
||||
def _doi_variants(dois: set[str]) -> set[str]:
|
||||
variants: set[str] = set()
|
||||
for doi in dois:
|
||||
normalized = doi.strip()
|
||||
if not normalized:
|
||||
continue
|
||||
raw = normalized
|
||||
for prefix in ("https://doi.org/", "http://dx.doi.org/"):
|
||||
if raw.casefold().startswith(prefix):
|
||||
raw = raw[len(prefix):]
|
||||
break
|
||||
variants.update(
|
||||
{
|
||||
normalized,
|
||||
normalized.lower(),
|
||||
f"https://doi.org/{raw}",
|
||||
f"https://doi.org/{raw.lower()}",
|
||||
}
|
||||
)
|
||||
return variants
|
||||
|
||||
|
||||
async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]:
|
||||
page = await autocomplete_institutions_for_selector(
|
||||
query=organization_name,
|
||||
@@ -797,7 +1076,7 @@ async def _dfg_project_author_hits(
|
||||
"query": {
|
||||
"terms": {"persons.person_id": sorted(person_ids)}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
"sort": [
|
||||
{
|
||||
|
||||
@@ -202,21 +202,25 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
|
||||
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"dfg_person_id": None,
|
||||
"name": "Ada Example",
|
||||
"count": 42,
|
||||
}
|
||||
assert result.projects[0].model_dump() == {
|
||||
"id": "A2",
|
||||
"dfg_person_id": 2,
|
||||
"name": "Grace Example",
|
||||
"count": 2,
|
||||
}
|
||||
assert result.patents[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"dfg_person_id": None,
|
||||
"name": "Ada Example",
|
||||
"count": 4,
|
||||
}
|
||||
assert result.news[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"dfg_person_id": None,
|
||||
"name": "Ada Example",
|
||||
"count": 6,
|
||||
}
|
||||
@@ -294,6 +298,7 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match():
|
||||
|
||||
assert result.projects[0].model_dump() == {
|
||||
"id": None,
|
||||
"dfg_person_id": 9,
|
||||
"name": "Project Person",
|
||||
"count": 9,
|
||||
}
|
||||
@@ -363,6 +368,7 @@ async def test_top_authors_processes_all_dfg_project_pages():
|
||||
|
||||
assert result.projects[0].model_dump() == {
|
||||
"id": None,
|
||||
"dfg_person_id": 9,
|
||||
"name": "Project Person",
|
||||
"count": 10001,
|
||||
}
|
||||
@@ -488,8 +494,255 @@ async def test_top_authors_matches_dfg_project_people_to_openalex_case_insensiti
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert [author.model_dump() for author in result.projects] == [
|
||||
{"id": "A1", "name": "Ada Example", "count": 1},
|
||||
{"id": None, "name": "DFG Person", "count": 1},
|
||||
{"id": "A1", "dfg_person_id": 1, "name": "Ada Example", "count": 1},
|
||||
{"id": None, "dfg_person_id": 2, "name": "DFG Person", "count": 1},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_links_dfg_project_people_by_title_stripped_name_or_orcid():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == config.settings.openalex_works_search_index:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1/example",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5056038758",
|
||||
"display_name": "G. Bacher",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.2/example",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5056038758",
|
||||
"display_name": "G. Bacher",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.3/example",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5025875670",
|
||||
"display_name": "Stephan Barcikowski",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.4/example",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5025875670",
|
||||
"display_name": "Stephan Barcikowski",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
if kwargs.get("query") is not None:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A3",
|
||||
"display_name": "Stephan Schulz",
|
||||
"works_count": 1,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A5068103398",
|
||||
"display_name": "U. Bovensiepen",
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.DFG_PERSONS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"person_id": 1,
|
||||
"orcid_id": "0000-0002-1506-4491",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"person_id": 3,
|
||||
"orcid_id": "0000-0003-2896-4488",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.DFG_PROJECTS:
|
||||
if kwargs["body"].get("_source") == ["publications.doi"]:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"publications": [
|
||||
{"doi": "https://doi.org/10.1/example"}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"publications": [
|
||||
{"doi": "https://doi.org/10.2/example"}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"publications": [
|
||||
{"doi": "https://doi.org/10.3/example"},
|
||||
{"doi": "https://doi.org/10.4/example"},
|
||||
]
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
return {
|
||||
"hits": {
|
||||
"total": {"value": 3},
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": 1,
|
||||
"project_id": None,
|
||||
"persons": [
|
||||
{
|
||||
"person_id": 1,
|
||||
"full_name": "Professor Dr. Uwe Bovensiepen",
|
||||
},
|
||||
{
|
||||
"person_id": 2,
|
||||
"full_name": "Professor Dr. Gerd Bacher",
|
||||
},
|
||||
{
|
||||
"person_id": 3,
|
||||
"full_name": "Professor Dr. Stephan Schulz",
|
||||
},
|
||||
{
|
||||
"person_id": 4,
|
||||
"full_name": "Professor Dr.-Ing. Stephan Barcikowski",
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"id": 2,
|
||||
"project_id": None,
|
||||
"persons": [
|
||||
{
|
||||
"person_id": 1,
|
||||
"full_name": "Professor Dr. Uwe Bovensiepen",
|
||||
},
|
||||
{
|
||||
"person_id": 2,
|
||||
"full_name": "Professor Dr. Gerd Bacher",
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"id": 3,
|
||||
"project_id": None,
|
||||
"persons": [
|
||||
{
|
||||
"person_id": 1,
|
||||
"full_name": "Professor Dr. Uwe Bovensiepen",
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"authors": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.autocomplete_institutions_for_selector",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[SimpleNamespace(id=101)]
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_person_ids_by_institution_ids",
|
||||
new=AsyncMock(return_value=[1, 2, 3, 4]),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert [author.model_dump() for author in result.projects] == [
|
||||
{
|
||||
"id": "A5068103398",
|
||||
"dfg_person_id": 1,
|
||||
"name": "U. Bovensiepen",
|
||||
"count": 3,
|
||||
},
|
||||
{
|
||||
"id": "A5056038758",
|
||||
"dfg_person_id": 2,
|
||||
"name": "G. Bacher",
|
||||
"count": 2,
|
||||
},
|
||||
{
|
||||
"id": "A3",
|
||||
"dfg_person_id": 3,
|
||||
"name": "Stephan Schulz",
|
||||
"count": 1,
|
||||
},
|
||||
{
|
||||
"id": "A5025875670",
|
||||
"dfg_person_id": 4,
|
||||
"name": "Stephan Barcikowski",
|
||||
"count": 1,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -585,11 +838,13 @@ async def test_top_authors_can_rank_works_by_last_five_years():
|
||||
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A2",
|
||||
"dfg_person_id": None,
|
||||
"name": "Grace Example",
|
||||
"count": 16,
|
||||
}
|
||||
assert result.works[1].model_dump() == {
|
||||
"id": "A1",
|
||||
"dfg_person_id": None,
|
||||
"name": "Ada Example",
|
||||
"count": 2,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user