diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 6c2b52f9..4b12260b 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,6 +1,8 @@ import asyncio import logging import re +from types import SimpleNamespace +from collections import defaultdict from datetime import datetime from typing import Any, Literal @@ -38,6 +40,14 @@ from .model import ( TopicWordCloud, TopicWordCloudWord, ) +from inse.projects.eu_cordis_projects_client import ( + get_eu_project_ids_by_organization_filters, +) +from inse.projects.model import ( + EuCordisProjectType, + ProjectType, + ProjectsFilteringProperties, +) TOP_AUTHOR_LIMIT = 10 TOPIC_HEATMAP_LIMIT = 25 @@ -49,6 +59,30 @@ DashboardPeriod = tuple[int | None, int | None] logger = logging.getLogger(__name__) +async def get_eu_organization_project_contributions( + organization_names: list[str], + projects_filtering_properties: ProjectsFilteringProperties, +) -> SimpleNamespace: + project_ids_by_type = await get_eu_project_ids_by_organization_filters( + project_types=list(EuCordisProjectType), + organization_names=organization_names, + ) + project_ids = { + str(project_id) + for ids in project_ids_by_type.values() + for project_id in ids + } + return SimpleNamespace( + elements=[ + SimpleNamespace(project_id=project_id) + for project_id in sorted(project_ids) + ], + total=len(project_ids), + page=projects_filtering_properties.page, + size=projects_filtering_properties.size, + ) + + ACADEMIC_TITLE_RE = re.compile( r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+", re.IGNORECASE, @@ -940,6 +974,7 @@ async def get_top_authors( from_year = datetime.now().year - 4 to_year = datetime.now().year period = _dashboard_period(from_year, to_year) + aliases = await _institution_aliases(normalized_id, organization_name) authors = await _safe_institution_authors(normalized_id) works = _top_work_authors(authors, period) projects = await _safe_top_authors( @@ -953,8 +988,9 @@ async def get_top_authors( ) eu_projects = await _safe_top_authors( "eu_projects", - _top_eu_project_publication_authors(), + _top_eu_project_publication_authors(normalized_id, aliases, authors), ) + patents = await _safe_top_authors( "patents", _top_patent_authors( @@ -963,10 +999,12 @@ async def get_top_authors( to_year=period[1], ), ) + news = await _safe_top_authors( "news", _top_news_authors(authors), ) + return TopAuthorStatistics( institution_id=normalized_id, works=works, @@ -1921,52 +1959,168 @@ async def _top_patent_authors( ] -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( + institution_id: str, + organization_names: list[str], + institution_authors: list[dict[str, Any]], +) -> list[TopAuthor]: + institution_author_ids = { + author_id + for author in institution_authors + if (author_id := _normalize_author_id(author.get("id"))) + } + if not institution_author_ids: + return [] + + project_page = await get_eu_organization_project_contributions( + organization_names=organization_names, + projects_filtering_properties=ProjectsFilteringProperties( + project_type=ProjectType.EU, + page=0, + size=10000, + ), + ) + + project_ids = [project.project_id for project in project_page.elements] + + 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", "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="openalex-works", + body={ + "size": 10000, + "_source": [ + "doi", + "authorships.author.id", + "authorships.author.display_name", + "authorships.institutions.id", + ], + "query": { + "bool": { + "filter": [ + {"terms": {"doi": sorted(doi_project_ids)}}, + _institution_works_query(institution_id), + ] + } + }, + }, + cluster=ESCluster.NES, + ) + + return _openalex_work_authors_by_eu_projects( + works_response, + doi_project_ids, + institution_id, + institution_author_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 + doi = _normalize_doi(source.get("qaProcessedDoi")) + 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]], + institution_id: str, + institution_author_ids: set[str], +) -> list[TopAuthor]: + # Count unique CORDIS projects per author, not publications. Multiple works + # (and therefore multiple DOIs) can belong to the same project ID. + 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 []: + if not any( + institution.get("id") == institution_id + for institution in authorship.get("institutions") or [] + ): + continue + 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 author_id not in institution_author_ids + 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]: diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 82120462..16ddf379 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,6 +1,6 @@ -from types import SimpleNamespace from unittest.mock import AsyncMock, patch from datetime import datetime +from types import SimpleNamespace import pytest from fastapi import HTTPException @@ -8,17 +8,9 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole -from inse.authors.institution_membership_query import ( - build_active_institution_membership_query, -) from inse.dashboard.service import ( - get_dashboard_bmbf_project_statuses, + _openalex_work_authors_by_eu_projects, get_dashboard_organization, - get_dashboard_dfg_project_statuses, - get_dashboard_dfg_topics, - get_dashboard_eu_project_statuses, - get_dashboard_patents, - get_dashboard_publications, get_dashboard_statistics, get_top_authors, get_topic_heatmap, @@ -35,307 +27,23 @@ def anyio_backend(): return "asyncio" -@pytest.mark.anyio -async def test_dashboard_patents_uses_org_patent_total(): - with patch( - "inse.dashboard.service.OrgPatentsSearchClient.search_by_institution", - new=AsyncMock(return_value=([], 42)), - ) as search: - result = await get_dashboard_patents(ORG_INSTITUTION_ID, "Example Org") - - assert result.model_dump() == { - "institution_id": ORG_INSTITUTION_ID, - "organization_name": "Example Org", - "value": 42, - } - search.assert_awaited_once_with( - ORG_INSTITUTION_ID, - page=0, - size=0, - from_year=None, - to_year=None, - ) - - -@pytest.mark.anyio -async def test_dashboard_publications_filters_by_publication_year_period(): - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(return_value={"hits": {"total": {"value": 7}}}), - ) as search: - result = await get_dashboard_publications( - ORG_INSTITUTION_ID, - "Example Org", - from_year=2020, - to_year=2024, - ) - - assert result.value == 7 - query = search.await_args.kwargs["query"] - assert query["bool"]["must"][0]["nested"]["query"]["term"] == { - "authorships.institutions.id": ORG_INSTITUTION_ID - } - assert query["bool"]["filter"] == [ - {"range": {"publication_year": {"gte": 2020, "lte": 2024}}} - ] - - -@pytest.mark.anyio -async def test_dashboard_eu_project_statuses_deduplicates_projects(): - async def scan(**kwargs): - assert kwargs["index"] == str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD) - assert kwargs["source"] == ["projectID"] - yield {"_source": {"projectID": "P2"}} - yield {"_source": {"projectID": "P1"}} - yield {"_source": {"projectID": "P1"}} - - response = { - "aggregations": { - "ongoing": {"projects": {"value": 2}}, - "upcoming": {"projects": {"value": 1}}, - "completed": {"projects": {"value": 7}}, - } - } - with patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch("inse.dashboard.service.elasticsearch.scan", new=scan), patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(return_value=response), - ) as search: - result = await get_dashboard_eu_project_statuses( - ORG_INSTITUTION_ID, - "Example Org", - ) - - assert result.model_dump() == { - "institution_id": ORG_INSTITUTION_ID, - "organization_name": "Example Org", - "ongoing": 2, - "upcoming": 1, - "completed": 7, - } - call = search.await_args - assert call.kwargs["index"] == ESIndex.CORDIS_EU_PROJECTS_WILDCARD - assert call.kwargs["body"]["query"] == { - "terms": {"id": ["P1", "P2"]} - } - today = datetime.now().date().isoformat() - aggregations = call.kwargs["body"]["aggs"] - assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [ - {"range": {"startDate": {"lte": today}}}, - {"range": {"endDate": {"gte": today}}}, - ] - assert aggregations["upcoming"]["filter"] == { - "range": {"startDate": {"gt": today}} - } - assert aggregations["completed"]["filter"] == { - "range": {"endDate": {"lt": today}} - } - assert all( - aggregation["aggs"]["projects"]["cardinality"]["field"] == "id" - for aggregation in aggregations.values() - ) - - -@pytest.mark.anyio -async def test_dashboard_eu_project_statuses_restricts_project_set_by_period(): - async def scan(**kwargs): - yield {"_source": {"projectID": "P2"}} - yield {"_source": {"projectID": "P1"}} - - with patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch("inse.dashboard.service.elasticsearch.scan", new=scan), patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock( - return_value={ - "aggregations": { - "ongoing": {"projects": {"value": 1}}, - "upcoming": {"projects": {"value": 0}}, - "completed": {"projects": {"value": 1}}, - } - } - ), - ) as search: - await get_dashboard_eu_project_statuses( - ORG_INSTITUTION_ID, - "Example Org", - from_year=2020, - to_year=2024, - ) - - assert search.await_args.kwargs["body"]["query"] == { - "bool": { - "filter": [ - {"terms": {"id": ["P1", "P2"]}}, - { - "bool": { - "filter": [ - {"range": {"startDate": {"lte": "2024-12-31"}}}, - {"range": {"endDate": {"gte": "2020-01-01"}}}, - ] - } - }, - ] - } - } - - -@pytest.mark.anyio -async def test_dashboard_bmbf_project_statuses_uses_funding_dates(): - response = { - "aggregations": { - "ongoing": {"doc_count": 4}, - "upcoming": {"doc_count": 2}, - "completed": {"doc_count": 19}, - } - } - with patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(return_value=response), - ) as search: - result = await get_dashboard_bmbf_project_statuses( - ORG_INSTITUTION_ID, - "Example Org", - ) - - assert result.model_dump() == { - "institution_id": ORG_INSTITUTION_ID, - "organization_name": "Example Org", - "ongoing": 4, - "upcoming": 2, - "completed": 19, - } - call = search.await_args - assert call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1 - assert call.kwargs["body"]["query"]["bool"]["minimum_should_match"] == 1 - today = datetime.now().strftime("%d.%m.%Y") - aggregations = call.kwargs["body"]["aggs"] - assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [ - {"range": {"funding_start": {"lte": today}}}, - {"range": {"funding_end": {"gte": today}}}, - ] - assert aggregations["upcoming"]["filter"] == { - "range": {"funding_start": {"gt": today}} - } - assert aggregations["completed"]["filter"] == { - "range": {"funding_end": {"lt": today}} - } - - -@pytest.mark.anyio -async def test_dashboard_dfg_project_statuses_uses_nested_status_de(): - with patch( - "inse.dashboard.service._get_dfg_project_ids_for_institution", - new=AsyncMock(return_value=["123", "456"]), - ) as project_ids, patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock( - return_value={ - "aggregations": { - "projects_nested": { - "selected_projects": { - "ongoing": {"projects": {"value": 1}}, - "completed": {"projects": {"value": 1}}, - } - } - } - } - ), - ) as search: - result = await get_dashboard_dfg_project_statuses( - ORG_INSTITUTION_ID, - "Example Org", - from_year=2020, - to_year=2024, - ) - - project_ids.assert_awaited_once_with( - ORG_INSTITUTION_ID, - ) - assert result.model_dump() == { - "institution_id": ORG_INSTITUTION_ID, - "organization_name": "Example Org", - "ongoing": 1, - "upcoming": 0, - "completed": 1, - } - call = search.await_args - assert call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2 - selected = call.kwargs["body"]["aggs"]["projects_nested"]["aggs"][ - "selected_projects" - ] - assert selected["filter"] == { - "bool": { - "filter": [ - {"terms": {"projects.project_id": [123, 456]}}, - { - "bool": { - "filter": [ - { - "range": { - "projects.funding_start": {"lte": 2024} - } - }, - { - "bool": { - "should": [ - { - "range": { - "projects.funding_end": { - "gte": 2020 - } - } - }, - { - "bool": { - "must_not": { - "exists": { - "field": "projects.funding_end" - } - } - } - }, - ], - "minimum_should_match": 1, - } - }, - ] - } - }, - ] - } - } - assert selected["aggs"]["ongoing"]["filter"] == { - "match_phrase": {"projects.status_de": "laufend"} - } - assert selected["aggs"]["completed"]["filter"] == { - "match_phrase": {"projects.status_de": "abgeschlossen"} - } - assert all( - selected["aggs"][status]["aggs"]["projects"]["cardinality"]["field"] - == "projects.project_id" - for status in ("ongoing", "completed") - ) - - @pytest.mark.anyio 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}}} + if index == ESIndex.DFG_INSTITUTES_V2: if "institute_ids" in kwargs["body"].get("aggs", {}): return { @@ -358,6 +66,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): } } } + return {"hits": {"total": {"value": 3}}} with patch( @@ -376,7 +85,10 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): ) ), ): - 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, @@ -388,32 +100,34 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "eu_projects": 10, "bmbf_projects": 5, } - calls = mocked_search.await_args_list - calls_by_index = { - call.kwargs["index"]: call - for call in calls - if call.kwargs["index"] != ESIndex.DFG_INSTITUTES_V2 - } - works_call = calls_by_index[config.settings.openalex_works_search_index] - authors_call = calls_by_index[ESIndex.OPENALEX_AUTHORS] - eu_call = calls_by_index[ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD] - bmbf_call = calls_by_index[ESIndex.PROJECTS_BUND_V1] - dfg_calls = [ + + publication_call = next( call - for call in calls - if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2 - ] - dfg_institutes_call, dfg_projects_call = dfg_calls - assert works_call.kwargs["query"]["nested"]["query"]["term"] == { + 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 authors_call.kwargs["query"] == build_active_institution_membership_query( - ORG_INSTITUTION_ID + + person_call = next( + call + for call in mocked_search.await_args_list + if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS ) - assert all( - call.kwargs["cluster"] == ESCluster.INSE - for call in [eu_call, bmbf_call, *dfg_calls] + 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] == { + "term": {"affiliations.institution.id": ORG_INSTITUTION_ID} + } + 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": [ @@ -423,141 +137,32 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): ] } } - assert bmbf_call.kwargs["query"]["bool"]["minimum_should_match"] == 1 - assert bmbf_call.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", } } - dfg_query = dfg_institutes_call.kwargs["body"]["query"] - assert dfg_query["bool"]["minimum_should_match"] == 1 - assert dfg_query["bool"]["should"] == [ - { - "terms": { - "institute_name_de.keyword": [ - "Example University", - "Example Universität", - ] - } - }, - { - "terms": { - "institute_name_en.keyword": [ - "Example University", - "Example Universität", - ] - } - }, + + dfg_calls = [ + call + for call in mocked_search.await_args_list + if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2 ] - assert dfg_projects_call.kwargs["body"]["query"] == { - "terms": {"institute_id": [10210]} - } - assert dfg_projects_call.kwargs["body"]["aggs"] == { - "projects_nested": { - "nested": {"path": "projects"}, - "aggs": { - "project_ids": { - "filter": { - "terms": {"projects.institute_ref_id": [10210]} - }, - "aggs": { - "values": { - "terms": { - "field": "projects.project_id", - "size": 10000, - } - } - }, - } - }, - } - } + assert len(dfg_calls) == 2 + assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls) @pytest.mark.anyio -async def test_dashboard_dfg_topics_returns_deduplicated_topics(): - async def scan(**kwargs): - assert kwargs == { - "index": "projects_dfg_openalex_topics", - "query": {"terms": {"project_id": ["101", "102"]}}, - "source": ["project_id", "topic_matches"], - "page_size": 1000, - "cluster": ESCluster.INSE, - } - yield { - "_source": { - "project_id": "101", - "topic_matches": [ - { - "topic_id": "https://openalex.org/T1", - "topic_display_name": "Topic One", - "subfield": "Subfield One", - "field": "Field One", - "domain": "Domain One", - } - ], - } - } - yield { - "_source": { - "project_id": "102", - "topic_matches": [ - { - "topic_id": "https://openalex.org/T1", - "topic_display_name": "Topic One", - "subfield": "Subfield One", - "field": "Field One", - "domain": "Domain One", - }, - { - "topic_id": "https://openalex.org/T2", - "topic_display_name": "Topic Two", - "subfield": "Subfield Two", - "field": "Field Two", - "domain": "Domain Two", - }, - ], - } - } - - with patch( - "inse.dashboard.service._get_dfg_project_ids_for_institution", - new=AsyncMock(return_value=["101", "102"]), - ), patch("inse.dashboard.service.elasticsearch.scan", new=scan): - result = await get_dashboard_dfg_topics( - ORG_INSTITUTION_ID, - "Example Org", - ) - - assert result.model_dump() == { - "institution_id": ORG_INSTITUTION_ID, - "organization_name": "Example Org", - "project_count": 2, - "matched_project_count": 2, - "topics": [ - { - "id": "https://openalex.org/T1", - "name": "Topic One", - "subfield": "Subfield One", - "field": "Field One", - "domain": "Domain One", - "project_count": 2, - }, - { - "id": "https://openalex.org/T2", - "name": "Topic Two", - "subfield": "Subfield Two", - "field": "Field Two", - "domain": "Domain Two", - "project_count": 1, - }, - ], - } - - -@pytest.mark.anyio -async def test_top_authors_maps_works_patents_eu_dfg_and_news(): +async def test_top_authors_maps_works_patents_news_and_eu_projects(): async def search(**kwargs): if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: return { @@ -582,76 +187,120 @@ async def test_top_authors_maps_works_patents_eu_dfg_and_news(): ] } } + 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.DFG_PROJECTS: + if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD: return { "hits": { - "total": {"value": 2}, "hits": [ { "_source": { - "id": "P1", - "persons": [ - {"person_id": 2, "full_name": "Grace Example"}, + "projectID": "P1", + "qaProcessedDoi": "10.1234/p1", + } + }, + { + "_source": { + "projectID": "P2", + "qaProcessedDoi": "https://doi.org/10.1234/p2", + } + }, + ] + } + } + + if kwargs["index"] == ESIndex.DFG_PROJECTS: + return { + "aggregations": { + "people": { + "buckets": [{"key": "Grace Example", "doc_count": 3}] + } + } + } + + if kwargs["index"] == "openalex-works": + return { + "hits": { + "hits": [ + { + "_source": { + "doi": "https://doi.org/10.1234/p1", + "authorships": [ { - "person_id": 99, - "full_name": "Outside Collaborator", + "author": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + }, + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], }, ], } }, { "_source": { - "id": "P2", - "persons": [ - {"person_id": 2, "full_name": "Grace Example"}, - {"person_id": 2, "full_name": "Grace Example"}, + "doi": "https://doi.org/10.1234/p2", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + } ], } }, - ], + ] } } - if kwargs["index"] == ESIndex.DFG_PERSONS: - return {"hits": {"hits": []}} + 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_project_contributions", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[ + SimpleNamespace(project_id="P1"), + SimpleNamespace(project_id="P2"), + SimpleNamespace(project_id="P3"), + ], + ) + ), + ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock( return_value=[ {"id": "A1", "name": "Ada Example", "count": 4}, ] ), - ), 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=[2]), ): - 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", @@ -664,40 +313,295 @@ async def test_top_authors_maps_works_patents_eu_dfg_and_news(): "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.projects[0].model_dump() == { - "id": "A2", - "name": "Grace Example", - "count": 2, - } 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"] == ESIndex.DFG_PROJECTS + if call.kwargs["index"] + in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1} ] - assert len(project_calls) == 1 - assert project_calls[0].kwargs["body"]["query"] == { - "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": [2]}}, - }, - } + 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", + "P3", + } + assert eu_body["_source"] == ["projectID", "qaProcessedDoi"] + assert "aggs" not in eu_body + + works_calls = [ + call + for call in mocked_search.await_args_list + if call.kwargs["index"] == "openalex-works" + ] + assert len(works_calls) == 1 + works_body = works_calls[0].kwargs["body"] + assert works_body["query"]["bool"]["filter"][0]["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", + "authorships.institutions.id", + ] + + +def test_eu_author_count_groups_multiple_publications_by_project_id(): + works_response = { + "hits": { + "hits": [ + { + "_source": { + "doi": "https://doi.org/10.1/marcus-a", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5007170803", + "display_name": "Marcus Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + }, + { + "author": { + "id": "https://openalex.org/A999", + "display_name": "External Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + }, + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.1/marcus-b", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5007170803", + "display_name": "Marcus Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + } + ], + } + }, + ] + } + } + doi_project_ids = { + "https://doi.org/10.1/marcus-a": {"P1"}, + "https://doi.org/10.1/marcus-b": {"P1"}, + } + + result = _openalex_work_authors_by_eu_projects( + works_response, + doi_project_ids, + ORG_INSTITUTION_ID, + {"https://openalex.org/A5007170803"}, + ) + + assert [author.model_dump() for author in result] == [ + {"id": "A5007170803", "name": "Marcus Example", "count": 1} + ] + + +@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": [ + { + "_source": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + "works_count": 3, + "counts_by_year": [], + } + }, + { + "_source": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + "works_count": 1, + "counts_by_year": [], + } + }, + ] + } + } + if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD: + assert kwargs["body"]["query"] == { + "terms": {"projectID": ["P1", "P2"]} + } + return { + "hits": { + "hits": [ + { + "_source": { + "projectID": "P1", + "qaProcessedDoi": "10.1/P1-A", + } + }, + { + "_source": { + "projectID": "P1", + "qaProcessedDoi": "10.1/P1-B", + } + }, + { + "_source": { + "projectID": "P2", + "qaProcessedDoi": "10.1/P2", + } + }, + { + "_source": { + "projectID": "OUTSIDE", + "qaProcessedDoi": "10.1/OUT", + } + }, + ] + } + } + + if kwargs["index"] == "openalex-works": + assert kwargs["body"]["query"]["bool"]["filter"][0]["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", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + }, + { + "author": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + }, + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.1/p1-b", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.1/p2", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + }, + "institutions": [{"id": ORG_INSTITUTION_ID}], + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.1/not-requested", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A999", + "display_name": "Outside Author", + } + } + ], + } + }, + ] + } + } + if kwargs["index"] == ESIndex.DFG_PROJECTS: + return { + "aggregations": { + "people": { + "buckets": [ + {"key": "Ada Example", "doc_count": 2}, + {"key": "ada example", "doc_count": 3}, + {"key": "DFG Person", "doc_count": 4}, + ] + } + } + } + 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_project_contributions", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[ + SimpleNamespace(project_id="P1"), + SimpleNamespace(project_id="P2"), + ], + ) + ), + ), 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 @@ -718,22 +622,34 @@ 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_project_contributions", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[ + SimpleNamespace(project_id="P1"), + ], + ) + ), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), - ), patch( - "inse.dashboard.service.autocomplete_institutions_for_selector", - new=AsyncMock(return_value=SimpleNamespace(elements=[])), ): - 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.projects == [] assert result.eu_projects == [] assert result.patents == [] assert result.news == [] @@ -781,12 +697,12 @@ 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_project_contributions", + new=AsyncMock(return_value=SimpleNamespace(elements=[])), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), - ), patch( - "inse.dashboard.service.autocomplete_institutions_for_selector", - new=AsyncMock(return_value=SimpleNamespace(elements=[])), ): result = await get_top_authors( ORG_INSTITUTION_ID, @@ -944,13 +860,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"] diff --git a/webapp/src/app/api/model/topAuthorStatistics.ts b/webapp/src/app/api/model/topAuthorStatistics.ts index 05af3ed5..cdb809c7 100644 --- a/webapp/src/app/api/model/topAuthorStatistics.ts +++ b/webapp/src/app/api/model/topAuthorStatistics.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech