Use OpenAlex IDs for EU authors
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
spsaefan
2026-07-17 13:32:59 +02:00
parent dfdc35ad81
commit 410bcdec4b
2 changed files with 440 additions and 76 deletions
+128 -35
View File
@@ -1,5 +1,6 @@
import asyncio
import logging
from collections import defaultdict
from datetime import datetime
from typing import Any, Literal
@@ -26,6 +27,9 @@ from .model import (
TopicWordCloud,
TopicWordCloudWord,
)
from inse.projects.projects_search_client import (
get_eu_organization_contributions,
)
TOP_AUTHOR_LIMIT = 10
TOPIC_HEATMAP_LIMIT = 25
@@ -333,18 +337,27 @@ async def get_top_authors(
normalized_id = _normalize_institution_id(institution_id)
authors = await _safe_institution_authors(normalized_id)
works = _top_work_authors(authors, works_period)
aliases = await _institution_aliases(
normalized_id,
organization_name,
)
eu_projects = await _safe_top_authors(
"eu_projects",
_top_eu_project_publication_authors(),
_top_eu_project_publication_authors(aliases),
)
patents = await _safe_top_authors(
"patents",
_top_patent_authors(normalized_id),
)
news = await _safe_top_authors(
"news",
_top_news_authors(authors),
)
return TopAuthorStatistics(
institution_id=normalized_id,
works=works,
@@ -826,52 +839,132 @@ async def _top_patent_authors(institution_id: str) -> list[TopAuthor]:
]
async def _top_eu_project_publication_authors() -> list[TopAuthor]:
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_FP7_PUBLICATIONS,
async def _top_eu_project_publication_authors(
organization_names: list[str],
) -> list[TopAuthor]:
contributions = await get_eu_organization_contributions(
organization_names=organization_names,
)
project_ids = list(contributions.keys())
if not project_ids:
return []
publication_response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
body={
"size": 0,
"aggs": {
"authors": {
"terms": {
"script": {
"lang": "painless",
"source": _cordis_publication_authors_script(),
},
"size": TOP_AUTHOR_LIMIT,
"order": {"_count": "desc"},
}
"size": 10000,
"_source": ["projectID", "doi", "qaProcessedDoi"],
"query": {
"terms": {
"projectID": project_ids,
}
},
},
cluster=ESCluster.INSE,
)
doi_project_ids = _cordis_publication_doi_project_ids(
publication_response,
set(project_ids),
)
if not doi_project_ids:
return []
works_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_project_ids),
}
},
},
cluster=ESCluster.NES,
)
return _openalex_work_authors_by_eu_projects(works_response, doi_project_ids)
def _cordis_publication_doi_project_ids(
response: dict[str, Any],
allowed_project_ids: set[str],
) -> dict[str, set[str]]:
doi_project_ids: dict[str, set[str]] = defaultdict(set)
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
project_id = str(source.get("projectID") or "").strip()
if not project_id or project_id not in allowed_project_ids:
continue
for field in ("doi", "qaProcessedDoi"):
doi = _normalize_doi(source.get(field))
if doi:
doi_project_ids[doi].add(project_id)
return dict(doi_project_ids)
def _normalize_doi(value: Any) -> str | None:
if not isinstance(value, str) or not value.strip():
return None
doi = value.strip().lower()
if doi.startswith("https://doi.org/"):
return doi
if doi.startswith("http://doi.org/"):
return "https://" + doi.removeprefix("http://")
if doi.startswith("doi.org/"):
return f"https://{doi}"
return f"https://doi.org/{doi}"
def _openalex_work_authors_by_eu_projects(
response: dict[str, Any],
doi_project_ids: dict[str, set[str]],
) -> list[TopAuthor]:
author_project_ids: dict[str, set[str]] = defaultdict(set)
author_names: dict[str, str] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
project_ids = doi_project_ids.get(_normalize_doi(source.get("doi")) or "")
if not project_ids:
continue
for authorship in source.get("authorships") or []:
author = authorship.get("author") or {}
author_id = _normalize_author_id(author.get("id"))
author_name = str(author.get("display_name") or "").strip()
if not author_id or not author_name:
continue
author_project_ids[author_id].update(project_ids)
author_names.setdefault(author_id, author_name)
ranked_authors = sorted(
author_project_ids.items(),
key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
)
return [
TopAuthor(
name=str(bucket["key"]),
count=int(bucket.get("doc_count", 0)),
id=_short_author_id(author_id),
name=author_names[author_id],
count=len(project_ids),
)
for bucket in (
response.get("aggregations", {}).get("authors", {}).get("buckets", [])
)
if str(bucket.get("key", "")).strip()
for author_id, project_ids in ranked_authors[:TOP_AUTHOR_LIMIT]
]
def _cordis_publication_authors_script() -> str:
return (
"def names = new HashSet(); "
"def source = params['_source']; "
"def value = source.containsKey('authors') ? source['authors'] "
" : (source.containsKey('Authors') ? source['Authors'] : null); "
"if (value instanceof String && value.length() > 0) { "
" for (name in value.splitOnToken(';')) { "
" def trimmed = name.trim(); "
" if (trimmed.length() > 0) { names.add(trimmed); } "
" } "
"} "
"return new ArrayList(names);"
)
def _normalize_author_id(value: Any) -> str | None:
if not isinstance(value, str) or not value.strip():
return None
short_id = value.replace("https://openalex.org/", "").strip().upper()
return f"https://openalex.org/{short_id}"
async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]:
+312 -41
View File
@@ -28,14 +28,19 @@ def anyio_backend():
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
async def search(**kwargs):
index = kwargs["index"]
if index == config.settings.openalex_works_search_index:
return {"hits": {"total": {"value": 120}}}
if index == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"total": {"value": 35}}}
if index == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD:
return {"aggregations": {"projects": {"value": 10}}}
if index == ESIndex.PROJECTS_BUND_V1:
return {"hits": {"total": {"value": 5}}}
return {"hits": {"total": {"value": 3}}}
with patch(
@@ -45,7 +50,10 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University", "Example Uni"]),
):
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
result = await get_dashboard_statistics(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
@@ -57,21 +65,38 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
"eu_projects": 10,
"bmbf_projects": 5,
}
calls = mocked_search.await_args_list
assert calls[0].kwargs["index"] == config.settings.openalex_works_search_index
assert calls[0].kwargs["query"]["nested"]["query"]["term"] == {
publication_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == config.settings.openalex_works_search_index
)
assert publication_call.kwargs["query"]["nested"]["query"]["term"] == {
"authorships.institutions.id": ORG_INSTITUTION_ID
}
assert calls[1].kwargs["query"]["nested"]["query"]["term"] == {
"affiliations.institution.id": ORG_INSTITUTION_ID
person_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
)
person_query = person_call.kwargs["query"]
recent_affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
assert recent_affiliation["nested"]["path"] == "affiliations"
assert recent_affiliation["nested"]["query"]["bool"]["filter"][0] == {
"match_phrase": {
"affiliations.institution.id": ORG_INSTITUTION_ID
}
}
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in calls[2:])
assert [call.kwargs["index"] for call in calls[2:]] == [
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
ESIndex.PROJECTS_BUND_V1,
ESIndex.PROJECTS_DFG_ALL,
]
assert calls[2].kwargs["body"]["query"] == {
eu_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
)
assert eu_call.kwargs["cluster"] == ESCluster.INSE
assert eu_call.kwargs["body"]["query"] == {
"terms": {
"name.keyword": [
"EXAMPLE ORG",
@@ -80,15 +105,29 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
]
}
}
assert calls[3].kwargs["query"]["bool"]["minimum_should_match"] == 1
assert calls[3].kwargs["query"]["bool"]["should"][0]["match"] == {
bund_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
)
assert bund_call.kwargs["cluster"] == ESCluster.INSE
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
"Zuwendungsempfänger": {
"query": "Example Org",
"operator": "and",
}
}
assert calls[4].kwargs["query"]["bool"]["minimum_should_match"] == 1
assert calls[4].kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][
dfg_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.PROJECTS_DFG_ALL
)
assert dfg_call.kwargs["cluster"] == ESCluster.INSE
assert dfg_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
assert dfg_call.kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][
"match"
] == {
"Antragstellende Institution": {
@@ -99,7 +138,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
@pytest.mark.anyio
async def test_top_authors_maps_works_patents_and_news_without_project_queries():
async def test_top_authors_maps_works_patents_news_and_eu_projects():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -124,31 +163,95 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
]
}
}
if kwargs["index"] == "aktuell_postproc":
return {
"aggregations": {
"authors": {
"buckets": [{"key": "Ada Example", "doc_count": 6}]
}
}
}
if kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS:
return {
"aggregations": {
"authors": {
"buckets": [
{"key": "Grace Example", "doc_count": 8},
{"key": "Ada Example", "doc_count": 5},
{"key": "Ada Example", "doc_count": 6}
]
}
}
}
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
return {
"hits": {
"hits": [
{
"_source": {
"projectID": "P1",
"doi": "10.1234/p1",
}
},
{
"_source": {
"projectID": "P2",
"qaProcessedDoi": "https://doi.org/10.1234/p2",
}
},
]
}
}
if kwargs["index"] == config.settings.openalex_works_search_index:
return {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1234/p1",
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
}
},
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
}
},
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1234/p2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
}
}
],
}
},
]
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search, patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_contributions",
new=AsyncMock(
return_value={
"P1": object(),
"P2": object(),
}
),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(
return_value=[
@@ -156,7 +259,10 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
]
),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.works[0].model_dump() == {
"id": "A1",
@@ -169,30 +275,180 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
"count": 4,
}
assert [author.model_dump() for author in result.eu_projects] == [
{"id": None, "name": "Grace Example", "count": 8},
{"id": None, "name": "Ada Example", "count": 5},
{"id": "A2", "name": "Grace Example", "count": 2},
{"id": "A1", "name": "Ada Example", "count": 1},
]
assert result.news[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 6,
}
project_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"]
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
in {
ESIndex.PROJECTS_DFG_ALL,
ESIndex.PROJECTS_BUND_V1,
}
]
assert project_calls == []
eu_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS
if call.kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD
]
assert len(eu_calls) == 1
terms = eu_calls[0].kwargs["body"]["aggs"]["authors"]["terms"]
assert terms["size"] == 10
assert "splitOnToken(';')" in terms["script"]["source"]
eu_body = eu_calls[0].kwargs["body"]
assert set(eu_body["query"]["terms"]["projectID"]) == {
"P1",
"P2",
}
assert eu_body["_source"] == ["projectID", "doi", "qaProcessedDoi"]
assert "aggs" not in eu_body
works_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == config.settings.openalex_works_search_index
]
assert len(works_calls) == 1
works_body = works_calls[0].kwargs["body"]
assert works_body["query"]["terms"]["doi"] == [
"https://doi.org/10.1234/p1",
"https://doi.org/10.1234/p2",
]
assert works_body["_source"] == [
"doi",
"authorships.author.id",
"authorships.author.display_name",
]
@pytest.mark.anyio
async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_id():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
assert kwargs["body"]["query"] == {
"terms": {"projectID": ["P1", "P2"]}
}
return {
"hits": {
"hits": [
{"_source": {"projectID": "P1", "doi": "10.1/P1-A"}},
{"_source": {"projectID": "P1", "doi": "10.1/P1-B"}},
{"_source": {"projectID": "P2", "doi": "10.1/P2"}},
{"_source": {"projectID": "OUTSIDE", "doi": "10.1/OUT"}},
]
}
}
if kwargs["index"] == config.settings.openalex_works_search_index:
assert kwargs["body"]["query"]["terms"]["doi"] == [
"https://doi.org/10.1/p1-a",
"https://doi.org/10.1/p1-b",
"https://doi.org/10.1/p2",
]
return {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1/p1-a",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
}
},
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
}
},
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/p1-b",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
}
}
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/p2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
}
}
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/not-requested",
"authorships": [
{
"author": {
"id": "https://openalex.org/A999",
"display_name": "Outside Author",
}
}
],
}
},
]
}
}
return {"aggregations": {"authors": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_contributions",
new=AsyncMock(
return_value={
"P1": object(),
"P2": object(),
}
),
), 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.eu_projects] == [
{"id": "A1", "name": "Ada Example", "count": 2},
{"id": "A2", "name": "Grace Example", "count": 1},
]
@pytest.mark.anyio
@@ -213,16 +469,26 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
]
}
}
raise RuntimeError("projects unavailable")
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_contributions",
new=AsyncMock(return_value={"P1": object()}),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.works[0].name == "Ada Example"
assert result.eu_projects == []
@@ -272,6 +538,9 @@ async def test_top_authors_can_rank_works_by_last_five_years():
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_contributions",
new=AsyncMock(return_value={}),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
@@ -432,13 +701,15 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
== "topics.field.id"
)
assert (
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
["subfields"]["terms"]["field"]
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"]["terms"][
"field"
]
== "topics.subfield.id"
)
assert (
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
["subfields"]["aggs"]["topics"]["terms"]["field"]
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"][
"aggs"
]["topics"]["terms"]["field"]
== "topics.id"
)
subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]