From 3d092b02f3b0fe64df5ad1e53ee9e6d159d4ff88 Mon Sep 17 00:00:00 2001 From: Farajollahi Date: Tue, 11 Aug 2026 10:16:25 +0200 Subject: [PATCH] refactor(dashboard): split dashboard logic into dedicated services - add separate services for top authors, project statuses and topic treemaps - extract shared project ID and statistics logic - move common period and institution helpers into common module - add individual top-author API routes - load top-author analyses independently in the frontend - remove unused dashboard code and helper functions - reduce the main dashboard service to general statistics and topic visualizations --- .../inse/dashboard/bund_topics_service.py | 142 + service/src/main/inse/dashboard/common.py | 92 + .../main/inse/dashboard/dfg_topics_service.py | 103 + .../main/inse/dashboard/eu_topics_service.py | 109 + service/src/main/inse/dashboard/model.py | 5 + .../inse/dashboard/project_ids_service.py | 102 + .../dashboard/project_statistics_service.py | 122 + .../inse/dashboard/project_status_service.py | 513 ++++ service/src/main/inse/dashboard/router.py | 120 +- service/src/main/inse/dashboard/service.py | 2312 +---------------- .../src/main/inse/dashboard/test_service.py | 403 +-- .../inse/dashboard/top_authors_service.py | 1100 ++++++++ .../dashboard/dashboard-statistics.service.ts | 42 +- 13 files changed, 2681 insertions(+), 2484 deletions(-) create mode 100644 service/src/main/inse/dashboard/bund_topics_service.py create mode 100644 service/src/main/inse/dashboard/common.py create mode 100644 service/src/main/inse/dashboard/dfg_topics_service.py create mode 100644 service/src/main/inse/dashboard/eu_topics_service.py create mode 100644 service/src/main/inse/dashboard/project_ids_service.py create mode 100644 service/src/main/inse/dashboard/project_statistics_service.py create mode 100644 service/src/main/inse/dashboard/project_status_service.py create mode 100644 service/src/main/inse/dashboard/top_authors_service.py diff --git a/service/src/main/inse/dashboard/bund_topics_service.py b/service/src/main/inse/dashboard/bund_topics_service.py new file mode 100644 index 00000000..5a241c49 --- /dev/null +++ b/service/src/main/inse/dashboard/bund_topics_service.py @@ -0,0 +1,142 @@ +import hashlib +from collections import defaultdict +from typing import Any + +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.projects import service as projects_service + +from .model import BundProjectTopics, DfgProjectKeyword, DfgProjectTopic +from .common import ( + dashboard_period as _dashboard_period, + normalize_institution_id as _normalize_institution_id, + raw_institution_id as _raw_institution_id, +) + + +async def get_dashboard_bund_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> BundProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.search_bund_projects_with_filters( + institutions_search_client=InstitutionsSearchClient(), + executing_agency=None, + raw_oa_institution_id=_raw_institution_id(normalized_id), + title=None, + keywords=None, + funding_arts=None, + topic_ids=None, + filter_topic_ids=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + project_ids.update( + project.funding_code + for project in projects.elements + if project.funding_code + ) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + if project_ids: + mapping_project_ids = sorted( + hashlib.sha256(project_id.encode("utf-8")).hexdigest() + for project_id in project_ids + ) + async for hit in elasticsearch.scan( + index=str(ESIndex.PROJECTS_BUND_TOPICS), + query={"terms": {"project_id": mapping_project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return BundProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) diff --git a/service/src/main/inse/dashboard/common.py b/service/src/main/inse/dashboard/common.py new file mode 100644 index 00000000..e670b2f7 --- /dev/null +++ b/service/src/main/inse/dashboard/common.py @@ -0,0 +1,92 @@ +from typing import Any, Literal + +from fastapi import HTTPException, status + +DashboardPeriod = tuple[int | None, int | None] + + +def dashboard_period( + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardPeriod: + if from_year is not None and to_year is not None and from_year > to_year: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="from_year must be less than or equal to to_year.", + ) + return from_year, to_year + + +def project_overlap_filter( + start_field: str, + end_field: str, + period: DashboardPeriod, + *, + missing_end_is_ongoing: bool = False, +) -> dict[str, Any] | None: + from_year, to_year = period + filters: list[dict[str, Any]] = [] + if to_year is not None: + filters.append({"range": {start_field: {"lte": to_year}}}) + if from_year is not None: + end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}} + if missing_end_is_ongoing: + end_filter = { + "bool": { + "should": [ + end_filter, + {"bool": {"must_not": {"exists": {"field": end_field}}}}, + ], + "minimum_should_match": 1, + } + } + filters.append(end_filter) + return {"bool": {"filter": filters}} if filters else None + + +def project_boundary_year_filter( + start_field: str, + end_field: str, + period: DashboardPeriod, + date_format: Literal["iso", "de", "year"], +) -> dict[str, Any] | None: + from_year, to_year = period + filters: list[dict[str, Any]] = [] + if to_year is not None: + if date_format == "year": + filters.append({"range": {start_field: {"lte": to_year}}}) + else: + last_day = ( + f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" + ) + filters.append({"range": {start_field: {"lte": last_day}}}) + if from_year is not None: + if date_format == "year": + filters.append({"range": {end_field: {"gte": from_year}}}) + else: + first_day = ( + f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}" + ) + filters.append({"range": {end_field: {"gte": first_day}}}) + return {"bool": {"filter": filters}} if filters else None + + +def normalize_institution_id(value: str) -> str: + return ( + value + if value.startswith("https://openalex.org/") + else f"https://openalex.org/{value}" + ) + + +def raw_institution_id(value: str) -> str: + return normalize_institution_id(value).removeprefix("https://openalex.org/") + + +def institution_works_query(institution_id: str) -> dict[str, Any]: + return { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.id": institution_id}}, + } + } diff --git a/service/src/main/inse/dashboard/dfg_topics_service.py b/service/src/main/inse/dashboard/dfg_topics_service.py new file mode 100644 index 00000000..2332c809 --- /dev/null +++ b/service/src/main/inse/dashboard/dfg_topics_service.py @@ -0,0 +1,103 @@ +from collections import defaultdict +from typing import Any + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex + +from .model import DfgProjectKeyword, DfgProjectTopic, DfgProjectTopics +from .common import normalize_institution_id as _normalize_institution_id +from .project_ids_service import _get_dfg_project_ids_from_projects_service + + +async def get_dashboard_dfg_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DfgProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + project_ids = await _get_dfg_project_ids_from_projects_service( + normalized_id, + from_year=from_year, + to_year=to_year, + ) + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + + if project_ids: + async for hit in elasticsearch.scan( + index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS), + query={"terms": {"project_id": project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return DfgProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) diff --git a/service/src/main/inse/dashboard/eu_topics_service.py b/service/src/main/inse/dashboard/eu_topics_service.py new file mode 100644 index 00000000..a4cbeaee --- /dev/null +++ b/service/src/main/inse/dashboard/eu_topics_service.py @@ -0,0 +1,109 @@ +from collections import defaultdict +from typing import Any + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex + +from .model import DfgProjectKeyword, DfgProjectTopic, EuProjectTopics +from .common import normalize_institution_id as _normalize_institution_id +from .project_ids_service import _get_eu_project_ids_from_projects_service + + +async def get_dashboard_eu_topics( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> EuProjectTopics: + normalized_id = _normalize_institution_id(institution_id) + project_ids = await _get_eu_project_ids_from_projects_service( + normalized_id, + from_year=from_year, + to_year=to_year, + ) + topics: dict[str, dict[str, Any]] = {} + matched_project_ids: set[str] = set() + + if project_ids: + mapping_indices = ( + ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, + ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, + ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, + ) + for mapping_index in mapping_indices: + async for hit in elasticsearch.scan( + index=str(mapping_index), + query={"terms": {"project_id": project_ids}}, + source=["project_id", "keyword", "topic_matches"], + page_size=1000, + cluster=ESCluster.INSE, + ): + source = hit.get("_source", {}) + project_id = str(source.get("project_id") or "") + if not project_id: + continue + keyword = str(source.get("keyword") or "").strip() + matched_project_ids.add(project_id) + for match in source.get("topic_matches", []): + topic_id = str(match.get("topic_id") or "") + if not topic_id: + continue + topic = topics.setdefault( + topic_id, + { + "id": topic_id, + "name": str(match.get("topic_display_name") or topic_id), + "subfield": match.get("subfield"), + "field": match.get("field"), + "domain": match.get("domain"), + "project_ids": set(), + "keywords": {}, + }, + ) + topic["project_ids"].add(project_id) + if keyword: + topic["keywords"].setdefault(keyword, set()).add(project_id) + + field_project_ids: dict[str, set[str]] = defaultdict(set) + subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) + for topic in topics.values(): + field_name = str(topic["field"] or "") + subfield_name = str(topic["subfield"] or "") + field_project_ids[field_name].update(topic["project_ids"]) + subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) + + topic_list = [ + DfgProjectTopic( + id=topic["id"], + name=topic["name"], + subfield=topic["subfield"], + field=topic["field"], + domain=topic["domain"], + project_count=len(topic["project_ids"]), + field_project_count=len(field_project_ids[str(topic["field"] or "")]), + subfield_project_count=len( + subfield_project_ids[ + (str(topic["field"] or ""), str(topic["subfield"] or "")) + ] + ), + keywords=sorted( + [ + DfgProjectKeyword( + name=keyword, + project_count=len(keyword_project_ids), + ) + for keyword, keyword_project_ids in topic["keywords"].items() + ], + key=lambda entry: (-entry.project_count, entry.name), + ), + ) + for topic in topics.values() + ] + topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) + return EuProjectTopics( + institution_id=normalized_id, + organization_name=organization_name, + project_count=len(project_ids), + matched_project_count=len(matched_project_ids), + topics=topic_list, + ) diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index ada6c020..bbc047db 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -98,6 +98,11 @@ class TopAuthorStatistics(BaseModel): news: list[TopAuthor] +class TopAuthorAnalysis(BaseModel): + institution_id: str + authors: list[TopAuthor] + + class TopicHeatmapValue(BaseModel): year: int count: int diff --git a/service/src/main/inse/dashboard/project_ids_service.py b/service/src/main/inse/dashboard/project_ids_service.py new file mode 100644 index 00000000..e5bbb37d --- /dev/null +++ b/service/src/main/inse/dashboard/project_ids_service.py @@ -0,0 +1,102 @@ +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.projects import service as projects_service +from inse.projects.model import EuCordisProjectType + +from .common import ( + dashboard_period as _dashboard_period, + raw_institution_id as _raw_institution_id, +) + + +async def _get_dfg_project_ids_from_projects_service( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + """Returns every matching DFG project ID through the canonical project service.""" + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.get_dfg_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(institution_id), + author_id=None, + author_filter_ids=None, + institution_ids=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=( + [str(year) for year in range(1900, period[1] + 1)] + if period[1] is not None + else None + ), + funding_end_years=( + [str(year) for year in range(period[0], 2101)] + if period[0] is not None + else None + ), + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + project_ids.update(project.id for project in projects.elements if project.id) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + return sorted(project_ids) + + +async def _get_eu_project_ids_from_projects_service( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + """Loads all organization EU project IDs from the canonical project service.""" + period = _dashboard_period(from_year, to_year) + page_size = 1000 + page_number = 0 + project_ids: set[str] = set() + + while True: + projects = await projects_service.search_eu_cordis_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(institution_id), + author_id=None, + author_ids=None, + organization_ids=None, + organization_names=None, + project_types=list(EuCordisProjectType), + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + page=page_number, + size=page_size, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + project_ids.update(project.id for project in projects.elements if project.id) + if len(project_ids) >= projects.total or not projects.elements: + break + page_number += 1 + + return sorted(project_ids) diff --git a/service/src/main/inse/dashboard/project_statistics_service.py b/service/src/main/inse/dashboard/project_statistics_service.py new file mode 100644 index 00000000..10f68bde --- /dev/null +++ b/service/src/main/inse/dashboard/project_statistics_service.py @@ -0,0 +1,122 @@ +from inse.institutions.institutions_search_client import InstitutionsSearchClient +from inse.projects import service as projects_service +from inse.projects.model import EuCordisProjectType + +from .common import ( + dashboard_period as _dashboard_period, + normalize_institution_id as _normalize_institution_id, + raw_institution_id as _raw_institution_id, +) +from .model import DashboardStatisticValue + + +async def get_dashboard_eu_projects( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardStatisticValue: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + projects = await projects_service.search_eu_cordis_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(normalized_id), + author_id=None, + author_ids=None, + organization_ids=None, + organization_names=None, + project_types=list(EuCordisProjectType), + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=projects.total, + ) + + +async def get_dashboard_bmbf_projects( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardStatisticValue: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + projects = await projects_service.search_bund_projects_with_filters( + institutions_search_client=InstitutionsSearchClient(), + executing_agency=None, + raw_oa_institution_id=_raw_institution_id(normalized_id), + title=None, + keywords=None, + funding_arts=None, + topic_ids=None, + filter_topic_ids=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=projects.total, + ) + + +async def get_dashboard_dfg_projects( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardStatisticValue: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + projects = await projects_service.get_dfg_projects( + institutions_search_client=InstitutionsSearchClient(), + raw_oa_institution_id=_raw_institution_id(normalized_id), + author_id=None, + author_filter_ids=None, + institution_ids=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + page=0, + size=1, + sort_by="id", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + return DashboardStatisticValue( + institution_id=normalized_id, + organization_name=organization_name, + value=projects.total, + ) diff --git a/service/src/main/inse/dashboard/project_status_service.py b/service/src/main/inse/dashboard/project_status_service.py new file mode 100644 index 00000000..4c32b94b --- /dev/null +++ b/service/src/main/inse/dashboard/project_status_service.py @@ -0,0 +1,513 @@ +from datetime import datetime +from typing import Any + +from inse.institutions.institutions_search_client import InstitutionsSearchClient + +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex + +from .common import ( + DashboardPeriod, + dashboard_period as _dashboard_period, + normalize_institution_id as _normalize_institution_id, + project_boundary_year_filter as _project_boundary_year_filter, + project_overlap_filter as _project_overlap_filter, + raw_institution_id as _raw_institution_id, +) +from .institute_helper import get_openalex_institution +from .model import ( + BmbfProjectStatusStatistics, + DfgProjectStatusStatistics, + EuProjectStatusStatistics, +) +from .project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) + + +def _status_count(aggregations: dict[str, Any], status_name: str) -> int: + return int(aggregations.get(status_name, {}).get("projects", {}).get("value", 0)) + + +def reconcile_status_counts( + total: int, ongoing: int, upcoming: int, completed: int +) -> tuple[int, int, int]: + """Make status buckets add up to the authoritative project-service total.""" + counts = [max(0, ongoing), max(0, upcoming), max(0, completed)] + difference = total - sum(counts) + if difference >= 0: + counts[0] += difference + return counts[0], counts[1], counts[2] + + excess = -difference + for index in (0, 1, 2): + reduction = min(counts[index], excess) + counts[index] -= reduction + excess -= reduction + if excess == 0: + break + return counts[0], counts[1], counts[2] + + +def _status_filter_aggregations( + start_field: str, end_field: str, today: str +) -> dict[str, Any]: + return { + "ongoing": { + "filter": { + "bool": { + "filter": [ + {"range": {start_field: {"lte": today}}}, + {"range": {end_field: {"gte": today}}}, + ] + } + } + }, + "upcoming": {"filter": {"range": {start_field: {"gt": today}}}}, + "completed": {"filter": {"range": {end_field: {"lt": today}}}}, + } + + +async def get_dashboard_eu_project_statuses( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> EuProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + aliases = await _institution_aliases(normalized_id, organization_name) + project_ids = await _eu_project_ids_for_aliases(aliases) + total = ( + await get_dashboard_eu_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + if not project_ids: + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=total, + upcoming=0, + completed=0, + ) + + today = datetime.now().date().isoformat() + period = _dashboard_period(from_year, to_year) + filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}] + if period_filter := _project_boundary_year_filter( + "startDate", "endDate", period, "iso" + ): + filters.append(period_filter) + response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, + body={ + "size": 0, + "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, + "aggs": { + "ongoing": { + "filter": { + "bool": { + "filter": [ + {"range": {"startDate": {"lte": today}}}, + {"range": {"endDate": {"gte": today}}}, + ] + } + }, + "aggs": {"projects": {"cardinality": {"field": "id"}}}, + }, + "upcoming": { + "filter": {"range": {"startDate": {"gt": today}}}, + "aggs": {"projects": {"cardinality": {"field": "id"}}}, + }, + "completed": { + "filter": {"range": {"endDate": {"lt": today}}}, + "aggs": {"projects": {"cardinality": {"field": "id"}}}, + }, + }, + }, + cluster=ESCluster.INSE, + ) + aggregations = response.get("aggregations", {}) + ongoing, upcoming, completed = reconcile_status_counts( + total, + _status_count(aggregations, "ongoing"), + _status_count(aggregations, "upcoming"), + _status_count(aggregations, "completed"), + ) + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=ongoing, + upcoming=upcoming, + completed=completed, + ) + + +async def get_dashboard_bmbf_project_statuses( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> BmbfProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + aliases = await _institution_aliases(normalized_id, organization_name) + period = _dashboard_period(from_year, to_year) + filters = [_alias_match_query("Zuwendungsempfänger", aliases)] + if period_filter := _project_boundary_year_filter( + "funding_start", "funding_end", period, "de" + ): + filters.append(period_filter) + response = await elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + body={ + "size": 0, + "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, + "aggs": _status_filter_aggregations( + "funding_start", "funding_end", datetime.now().strftime("%d.%m.%Y") + ), + }, + cluster=ESCluster.INSE, + ) + aggregations = response.get("aggregations", {}) + total = ( + await get_dashboard_bmbf_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + ongoing, upcoming, completed = reconcile_status_counts( + total, + int(aggregations.get("ongoing", {}).get("doc_count", 0)), + int(aggregations.get("upcoming", {}).get("doc_count", 0)), + int(aggregations.get("completed", {}).get("doc_count", 0)), + ) + return BmbfProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=ongoing, + upcoming=upcoming, + completed=completed, + ) + + +async def get_dashboard_dfg_project_statuses( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> DfgProjectStatusStatistics: + normalized_id = _normalize_institution_id(institution_id) + period = _dashboard_period(from_year, to_year) + project_ids = await _get_dfg_project_ids_for_institution(normalized_id) + total = ( + await get_dashboard_dfg_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + if not project_ids: + return DfgProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=total, + upcoming=0, + completed=0, + ) + + filters: list[dict[str, Any]] = [ + { + "terms": { + "projects.project_id": [int(project_id) for project_id in project_ids] + } + } + ] + if period_filter := _project_boundary_year_filter( + "projects.funding_start", "projects.funding_end", period, "year" + ): + filters.append(period_filter) + response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "aggs": { + "projects_nested": { + "nested": {"path": "projects"}, + "aggs": { + "selected_projects": { + "filter": filters[0] + if len(filters) == 1 + else {"bool": {"filter": filters}}, + "aggs": { + "ongoing": { + "filter": { + "match_phrase": { + "projects.status_de": "laufend" + } + }, + "aggs": { + "projects": { + "cardinality": { + "field": "projects.project_id" + } + } + }, + }, + "completed": { + "filter": { + "match_phrase": { + "projects.status_de": "abgeschlossen" + } + }, + "aggs": { + "projects": { + "cardinality": { + "field": "projects.project_id" + } + } + }, + }, + }, + } + }, + } + }, + }, + cluster=ESCluster.INSE, + ) + aggregations = ( + response.get("aggregations", {}) + .get("projects_nested", {}) + .get("selected_projects", {}) + ) + ongoing, upcoming, completed = reconcile_status_counts( + total, + _status_count(aggregations, "ongoing"), + 0, + _status_count(aggregations, "completed"), + ) + return DfgProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=ongoing, + upcoming=upcoming, + completed=completed, + ) + + +async def _get_dfg_project_ids_for_institution( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[str]: + period = _dashboard_period(from_year, to_year) + institution = await get_openalex_institution(institution_id) + institution_names = _openalex_institution_names(institution) + + institutes_response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "query": _dfg_institute_name_query(institution_names), + "aggs": { + "institute_ids": {"terms": {"field": "institute_id", "size": 1000}} + }, + }, + cluster=ESCluster.INSE, + ) + institute_ids = [ + bucket["key"] + for bucket in ( + institutes_response.get("aggregations", {}) + .get("institute_ids", {}) + .get("buckets", []) + ) + if bucket.get("key") is not None + ] + if not institute_ids: + return [] + + projects_response = await elasticsearch.search( + index=ESIndex.DFG_INSTITUTES_V2, + body={ + "size": 0, + "query": {"terms": {"institute_id": institute_ids}}, + "aggs": { + "projects_nested": { + "nested": {"path": "projects"}, + "aggs": { + "project_ids": { + "filter": { + "terms": {"projects.institute_ref_id": institute_ids} + }, + "aggs": { + "values": { + "terms": { + "field": "projects.project_id", + "size": 10000, + } + } + }, + } + }, + } + }, + }, + cluster=ESCluster.INSE, + ) + project_ids = [ + str(bucket["key"]) + for bucket in ( + projects_response.get("aggregations", {}) + .get("projects_nested", {}) + .get("project_ids", {}) + .get("values", {}) + .get("buckets", []) + ) + if bucket.get("key") is not None + ] + return await _filter_dfg_project_ids_by_period(project_ids, period) + + +async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]: + project_ids: set[str] = set() + async for hit in elasticsearch.scan( + index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD), + query=_eu_organization_query(aliases), + source=["projectID"], + page_size=1000, + cluster=ESCluster.INSE, + ): + project_id = hit.get("_source", {}).get("projectID") + if project_id is not None: + project_ids.add(str(project_id)) + return project_ids + + +async def _filter_dfg_project_ids_by_period( + project_ids: list[str], + period: DashboardPeriod, +) -> list[str]: + period_filter = _project_overlap_filter( + "funding_start", + "funding_end", + period, + missing_end_is_ongoing=True, + ) + if not project_ids or not period_filter: + return project_ids + + numeric_project_ids = [ + int(project_id) for project_id in project_ids if str(project_id).isdigit() + ] + if not numeric_project_ids: + return [] + + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": 0, + "query": { + "bool": { + "filter": [ + {"terms": {"id": numeric_project_ids}}, + period_filter, + ] + } + }, + "aggs": { + "project_ids": { + "terms": { + "field": "id", + "size": len(numeric_project_ids), + } + } + }, + }, + cluster=ESCluster.INSE, + ) + return [ + str(bucket["key"]) + for bucket in ( + response.get("aggregations", {}).get("project_ids", {}).get("buckets", []) + ) + if bucket.get("key") is not None + ] + + +async def _institution_aliases( + institution_id: str, + organization_name: str, +) -> list[str]: + aliases = ( + await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id( + _raw_institution_id(institution_id) + ) + ) + return sorted( + { + alias.strip() + for alias in [organization_name, *aliases] + if alias and alias.strip() + } + ) + + +def _eu_organization_query(aliases: list[str]) -> dict[str, Any]: + return { + "terms": { + "name.keyword": [alias.upper() for alias in aliases], + } + } + + +def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]: + return { + "bool": { + "should": [ + { + "match": { + field: { + "query": alias, + "operator": "and", + } + } + } + for alias in aliases + ], + "minimum_should_match": 1, + } + } + + +def _openalex_institution_names(institution: Any) -> list[str]: + return sorted( + { + name.strip() + for name in [ + institution.display_name, + *(institution.display_name_alternatives or []), + *(institution.display_name_acronyms or []), + ] + if name and name.strip() + } + ) + + +def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]: + return { + "bool": { + "should": [ + { + "terms": { + "institute_name_de.keyword": institution_names, + } + }, + { + "terms": { + "institute_name_en.keyword": institution_names, + } + }, + ], + "minimum_should_match": 1, + } + } diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index fb01a93a..a0d0de82 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -18,28 +18,40 @@ from .model import ( EuProjectTopics, EuProjectStatusStatistics, TopAuthorStatistics, + TopAuthorAnalysis, TopicHeatmap, TopicWordCloud, ) from .service import ( - get_dashboard_bmbf_project_statuses, - get_dashboard_bmbf_projects, - get_dashboard_bund_topics, - get_dashboard_dfg_project_statuses, - get_dashboard_dfg_projects, - get_dashboard_dfg_topics, - get_dashboard_eu_topics, - get_dashboard_eu_project_statuses, - get_dashboard_eu_projects, get_dashboard_organization, get_dashboard_patents, get_dashboard_persons, get_dashboard_publications, get_dashboard_statistics, - get_top_authors, get_topic_heatmap, get_topic_word_cloud, ) +from .project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) +from .bund_topics_service import get_dashboard_bund_topics +from .dfg_topics_service import get_dashboard_dfg_topics +from .eu_topics_service import get_dashboard_eu_topics +from .project_status_service import ( + get_dashboard_bmbf_project_statuses, + get_dashboard_dfg_project_statuses, + get_dashboard_eu_project_statuses, +) +from .top_authors_service import ( + get_top_authors, + get_top_eu_project_authors, + get_top_news_authors, + get_top_patent_authors, + get_top_project_authors, + get_top_work_authors, +) router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD]) @@ -325,6 +337,94 @@ async def dashboard_top_authors( ) +@router.get( + "/top-authors/works", + operation_id="getDashboardTopWorkAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_work_authors( + works_period: Literal["all_time", "last_5_years"] = Query( + default="all_time", pattern="^(all_time|last_5_years)$" + ), + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_work_authors( + organization.openalex_institution_id, works_period, from_year, to_year + ) + + +@router.get( + "/top-authors/projects", + operation_id="getDashboardTopProjectAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_project_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_project_authors( + organization.openalex_institution_id, organization.name, from_year, to_year + ) + + +@router.get( + "/top-authors/eu-projects", + operation_id="getDashboardTopEuProjectAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_eu_project_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_eu_project_authors( + organization.openalex_institution_id, from_year, to_year + ) + + +@router.get( + "/top-authors/patents", + operation_id="getDashboardTopPatentAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_patent_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_patent_authors( + organization.openalex_institution_id, from_year, to_year + ) + + +@router.get( + "/top-authors/news", + operation_id="getDashboardTopNewsAuthors", + response_model=TopAuthorAnalysis, +) +async def dashboard_top_news_authors( + from_year: int | None = Query(default=None, ge=1900, le=2100), + to_year: int | None = Query(default=None, ge=1900, le=2100), + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> TopAuthorAnalysis: + organization = get_dashboard_organization(session, access_token) + return await get_top_news_authors( + organization.openalex_institution_id, from_year, to_year + ) + + @router.get( "/topic-heatmap", operation_id="getDashboardTopicHeatmap", diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index c2a5fad2..a162da74 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,52 +1,29 @@ import asyncio -import hashlib import logging -import re -from collections import defaultdict -from datetime import datetime -from types import SimpleNamespace -from typing import Any, Literal +from typing import Any from fastapi import HTTPException, status from sqlmodel import Session from inse import config from inse.auth.model import AccessToken, Organization -from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.institutions.v2 import service as institutions_v2_service from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient from inse.persons import service as persons_service -from inse.projects import service as projects_service -from inse.projects.dfg_institutions.service import ( - autocomplete_institutions_for_selector, -) -from inse.projects.eu_cordis_projects_client import ( - get_eu_project_ids_by_organization_filters, -) -from inse.projects.logic import get_person_ids_by_institution_ids -from inse.projects.model import ( - EuCordisProjectType, - ProjectsFilteringProperties, - ProjectType, -) from inse.works.v2 import service as works_v2_service -from .institute_helper import get_openalex_institution +from .common import ( + DashboardPeriod, + dashboard_period as _dashboard_period, + institution_works_query as _institution_works_query, + normalize_institution_id as _normalize_institution_id, + raw_institution_id as _raw_institution_id, +) from .model import ( - BmbfProjectStatusStatistics, - BundProjectTopics, DashboardStatistics, - DfgProjectKeyword, DashboardStatisticValue, - DfgProjectStatusStatistics, - DfgProjectTopic, - DfgProjectTopics, - EuProjectTopics, - EuProjectStatusStatistics, - TopAuthor, - TopAuthorStatistics, TopicHeatmap, TopicHeatmapField, TopicHeatmapSubfield, @@ -55,94 +32,19 @@ from .model import ( TopicWordCloud, TopicWordCloudWord, ) +from .project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) -TOP_AUTHOR_LIMIT = 10 TOPIC_HEATMAP_LIMIT = 25 TOPIC_HEATMAP_SUBFIELD_LIMIT = 100 TOPIC_HEATMAP_TOPIC_LIMIT = 100 TOPIC_WORD_CLOUD_LIMIT = 30 -WorksPeriod = Literal["all_time", "last_5_years"] -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, -) - - -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 _total(response: dict[str, Any]) -> int: - total = response.get("hits", {}).get("total", 0) - if isinstance(total, dict): - return int(total.get("value", 0)) - return int(total or 0) - - -def _dashboard_period( - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardPeriod: - if from_year is not None and to_year is not None and from_year > to_year: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="from_year must be less than or equal to to_year.", - ) - return from_year, to_year - - def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None: from_year, to_year = period year_range: dict[str, int] = {} @@ -153,67 +55,6 @@ def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None: return {"range": {"publication_year": year_range}} if year_range else None -def _project_overlap_filter( - start_field: str, - end_field: str, - period: DashboardPeriod, - *, - missing_end_is_ongoing: bool = False, -) -> dict[str, Any] | None: - from_year, to_year = period - filters: list[dict[str, Any]] = [] - if to_year is not None: - filters.append({"range": {start_field: {"lte": to_year}}}) - if from_year is not None: - end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}} - if missing_end_is_ongoing: - end_filter = { - "bool": { - "should": [ - end_filter, - {"bool": {"must_not": {"exists": {"field": end_field}}}}, - ], - "minimum_should_match": 1, - } - } - filters.append(end_filter) - return {"bool": {"filter": filters}} if filters else None - - -def _project_boundary_year_filter( - start_field: str, - end_field: str, - period: DashboardPeriod, - date_format: Literal["iso", "de", "year"], -) -> dict[str, Any] | None: - from_year, to_year = period - filters: list[dict[str, Any]] = [] - - # A project overlaps the selected interval if it begins no later than the - # interval end and finishes no earlier than the interval start. - if to_year is not None: - if date_format == "year": - filters.append({"range": {start_field: {"lte": to_year}}}) - else: - last_day = ( - f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}" - ) - filters.append({"range": {start_field: {"lte": last_day}}}) - - if from_year is not None: - if date_format == "year": - filters.append({"range": {end_field: {"gte": from_year}}}) - else: - first_day = ( - f"{from_year}-01-01" - if date_format == "iso" - else f"01.01.{from_year}" - ) - filters.append({"range": {end_field: {"gte": first_day}}}) - - return {"bool": {"filter": filters}} if filters else None - - def get_dashboard_organization( session: Session, access_token: AccessToken, @@ -237,14 +78,18 @@ async def get_dashboard_statistics( organization_name: str, ) -> DashboardStatistics: normalized_id = _normalize_institution_id(institution_id) - publications, persons, eu_projects, bmbf_projects, dfg_projects = ( - await asyncio.gather( - get_dashboard_publications(institution_id, organization_name), - get_dashboard_persons(institution_id, organization_name), - get_dashboard_eu_projects(institution_id, organization_name), - get_dashboard_bmbf_projects(institution_id, organization_name), - get_dashboard_dfg_projects(institution_id, organization_name), - ) + ( + publications, + persons, + eu_projects, + bmbf_projects, + dfg_projects, + ) = await asyncio.gather( + get_dashboard_publications(institution_id, organization_name), + get_dashboard_persons(institution_id, organization_name), + get_dashboard_eu_projects(institution_id, organization_name), + get_dashboard_bmbf_projects(institution_id, organization_name), + get_dashboard_dfg_projects(institution_id, organization_name), ) return DashboardStatistics( institution_id=normalized_id, @@ -299,13 +144,6 @@ async def get_dashboard_publications( ) -def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None: - from_year, to_year = period - if from_year is None and to_year is None: - return None - return list(range(from_year or 1900, (to_year or 2100) + 1)) - - async def get_dashboard_persons( institution_id: str, organization_name: str, @@ -362,1147 +200,6 @@ async def get_dashboard_patents( ) -async def get_dashboard_eu_projects( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - projects = await projects_service.search_eu_cordis_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), - author_id=None, - author_ids=None, - organization_ids=None, - organization_names=None, - project_types=list(EuCordisProjectType), - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - framework_programmes=None, - funding_schemes=None, - statuses=None, - page=0, - size=1, - sort_by="id", - sort_direction="asc", - fuzzy=False, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=projects.total, - ) - - -async def get_dashboard_eu_project_statuses( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> EuProjectStatusStatistics: - normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) - project_ids = await _eu_project_ids_for_aliases(aliases) - - if not project_ids: - total = ( - await get_dashboard_eu_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - return EuProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=total, - upcoming=0, - completed=0, - ) - - today = datetime.now().date().isoformat() - period = _dashboard_period(from_year, to_year) - filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}] - if period_filter := _project_boundary_year_filter( - "startDate", - "endDate", - period, - "iso", - ): - filters.append(period_filter) - query = ( - {"terms": {"id": sorted(project_ids)}} - if len(filters) == 1 - else {"bool": {"filter": filters}} - ) - response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - body={ - "size": 0, - "query": query, - "aggs": { - "ongoing": { - "filter": { - "bool": { - "filter": [ - {"range": {"startDate": {"lte": today}}}, - {"range": {"endDate": {"gte": today}}}, - ] - } - }, - "aggs": { - "projects": {"cardinality": {"field": "id"}} - }, - }, - "upcoming": { - "filter": {"range": {"startDate": {"gt": today}}}, - "aggs": { - "projects": {"cardinality": {"field": "id"}} - }, - }, - "completed": { - "filter": {"range": {"endDate": {"lt": today}}}, - "aggs": { - "projects": {"cardinality": {"field": "id"}} - }, - }, - }, - }, - cluster=ESCluster.INSE, - ) - aggregations = response.get("aggregations", {}) - total = ( - await get_dashboard_eu_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - ongoing, upcoming, completed = _reconcile_project_status_counts( - total, - _project_status_count(aggregations, "ongoing"), - _project_status_count(aggregations, "upcoming"), - _project_status_count(aggregations, "completed"), - ) - return EuProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=ongoing, - upcoming=upcoming, - completed=completed, - ) - - -def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int: - return int( - aggregations.get(status_name, {}).get("projects", {}).get("value", 0) - ) - - -def _reconcile_project_status_counts( - total: int, - ongoing: int, - upcoming: int, - completed: int, -) -> tuple[int, int, int]: - """Makes status buckets add up to the authoritative project-service total.""" - counts = [max(0, ongoing), max(0, upcoming), max(0, completed)] - difference = total - sum(counts) - if difference >= 0: - counts[0] += difference - return counts[0], counts[1], counts[2] - - # Defensive fallback for stale/duplicated status documents: reduce buckets - # without ever returning negative values, preferring the inferred ongoing - # bucket before changing explicit upcoming/completed classifications. - excess = -difference - for index in (0, 1, 2): - reduction = min(counts[index], excess) - counts[index] -= reduction - excess -= reduction - if excess == 0: - break - return counts[0], counts[1], counts[2] - - -async def get_dashboard_bmbf_projects( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - projects = await projects_service.search_bund_projects_with_filters( - institutions_search_client=InstitutionsSearchClient(), - executing_agency=None, - raw_oa_institution_id=_raw_institution_id(normalized_id), - title=None, - keywords=None, - funding_arts=None, - topic_ids=None, - filter_topic_ids=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - page=0, - size=1, - sort_by="id", - sort_direction="asc", - fuzzy=False, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=projects.total, - ) - - -async def get_dashboard_bmbf_project_statuses( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> BmbfProjectStatusStatistics: - normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) - period = _dashboard_period(from_year, to_year) - filters = [_alias_match_query("Zuwendungsempfänger", aliases)] - if period_filter := _project_boundary_year_filter( - "funding_start", - "funding_end", - period, - "de", - ): - filters.append(period_filter) - today = datetime.now().strftime("%d.%m.%Y") - response = await elasticsearch.search( - index=ESIndex.PROJECTS_BUND_V1, - body={ - "size": 0, - "query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}}, - "aggs": _project_status_filter_aggregations( - start_field="funding_start", - end_field="funding_end", - today=today, - ), - }, - cluster=ESCluster.INSE, - ) - aggregations = response.get("aggregations", {}) - total = ( - await get_dashboard_bmbf_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - ongoing, upcoming, completed = _reconcile_project_status_counts( - total, - int(aggregations.get("ongoing", {}).get("doc_count", 0)), - int(aggregations.get("upcoming", {}).get("doc_count", 0)), - int(aggregations.get("completed", {}).get("doc_count", 0)), - ) - return BmbfProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=ongoing, - upcoming=upcoming, - completed=completed, - ) - - -def _project_status_filter_aggregations( - start_field: str, - end_field: str, - today: str, -) -> dict[str, Any]: - return { - "ongoing": { - "filter": { - "bool": { - "filter": [ - {"range": {start_field: {"lte": today}}}, - {"range": {end_field: {"gte": today}}}, - ] - } - } - }, - "upcoming": {"filter": {"range": {start_field: {"gt": today}}}}, - "completed": {"filter": {"range": {end_field: {"lt": today}}}}, - } - - -async def get_dashboard_dfg_projects( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - projects = await projects_service.get_dfg_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), - author_id=None, - author_filter_ids=None, - institution_ids=None, - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - page=0, - size=1, - sort_by="id", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - return DashboardStatisticValue( - institution_id=normalized_id, - organization_name=organization_name, - value=projects.total, - ) - - -async def get_dashboard_dfg_project_statuses( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DfgProjectStatusStatistics: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - project_ids = await _get_dfg_project_ids_for_institution( - normalized_id, - ) - if not project_ids: - total = ( - await get_dashboard_dfg_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - return DfgProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=total, - upcoming=0, - completed=0, - ) - - selected_project_filters: list[dict[str, Any]] = [ - { - "terms": { - "projects.project_id": [ - int(project_id) for project_id in project_ids - ] - } - } - ] - if period_filter := _project_boundary_year_filter( - "projects.funding_start", - "projects.funding_end", - period, - "year", - ): - selected_project_filters.append(period_filter) - - response = await elasticsearch.search( - index=ESIndex.DFG_INSTITUTES_V2, - body={ - "size": 0, - "aggs": { - "projects_nested": { - "nested": {"path": "projects"}, - "aggs": { - "selected_projects": { - "filter": ( - selected_project_filters[0] - if len(selected_project_filters) == 1 - else {"bool": {"filter": selected_project_filters}} - ), - "aggs": { - "ongoing": { - "filter": { - "match_phrase": { - "projects.status_de": "laufend" - } - }, - "aggs": { - "projects": { - "cardinality": { - "field": "projects.project_id" - } - } - }, - }, - "completed": { - "filter": { - "match_phrase": { - "projects.status_de": "abgeschlossen" - } - }, - "aggs": { - "projects": { - "cardinality": { - "field": "projects.project_id" - } - } - }, - }, - }, - } - }, - } - }, - }, - cluster=ESCluster.INSE, - ) - aggregations = ( - response.get("aggregations", {}) - .get("projects_nested", {}) - .get("selected_projects", {}) - ) - total = ( - await get_dashboard_dfg_projects( - normalized_id, - organization_name, - from_year=from_year, - to_year=to_year, - ) - ).value - ongoing, upcoming, completed = _reconcile_project_status_counts( - total, - _project_status_count(aggregations, "ongoing"), - 0, - _project_status_count(aggregations, "completed"), - ) - return DfgProjectStatusStatistics( - institution_id=normalized_id, - organization_name=organization_name, - ongoing=ongoing, - upcoming=upcoming, - completed=completed, - ) - - -async def get_dashboard_dfg_topics( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> DfgProjectTopics: - normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_dfg_project_ids_from_projects_service( - normalized_id, - from_year=from_year, - to_year=to_year, - ) - topics: dict[str, dict[str, Any]] = {} - matched_project_ids: set[str] = set() - - if project_ids: - async for hit in elasticsearch.scan( - index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS), - query={"terms": {"project_id": project_ids}}, - source=["project_id", "keyword", "topic_matches"], - page_size=1000, - cluster=ESCluster.INSE, - ): - source = hit.get("_source", {}) - project_id = str(source.get("project_id") or "") - if not project_id: - continue - keyword = str(source.get("keyword") or "").strip() - matched_project_ids.add(project_id) - for match in source.get("topic_matches", []): - topic_id = str(match.get("topic_id") or "") - if not topic_id: - continue - topic = topics.setdefault( - topic_id, - { - "id": topic_id, - "name": str(match.get("topic_display_name") or topic_id), - "subfield": match.get("subfield"), - "field": match.get("field"), - "domain": match.get("domain"), - "project_ids": set(), - "keywords": {}, - }, - ) - topic["project_ids"].add(project_id) - if keyword: - topic["keywords"].setdefault(keyword, set()).add(project_id) - - field_project_ids: dict[str, set[str]] = defaultdict(set) - subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) - for topic in topics.values(): - field_name = str(topic["field"] or "") - subfield_name = str(topic["subfield"] or "") - field_project_ids[field_name].update(topic["project_ids"]) - subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) - - topic_list = [ - DfgProjectTopic( - id=topic["id"], - name=topic["name"], - subfield=topic["subfield"], - field=topic["field"], - domain=topic["domain"], - project_count=len(topic["project_ids"]), - field_project_count=len(field_project_ids[str(topic["field"] or "")]), - subfield_project_count=len( - subfield_project_ids[ - (str(topic["field"] or ""), str(topic["subfield"] or "")) - ] - ), - keywords=sorted( - [ - DfgProjectKeyword( - name=keyword, - project_count=len(keyword_project_ids), - ) - for keyword, keyword_project_ids in topic["keywords"].items() - ], - key=lambda entry: (-entry.project_count, entry.name), - ), - ) - for topic in topics.values() - ] - topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) - return DfgProjectTopics( - institution_id=normalized_id, - organization_name=organization_name, - project_count=len(project_ids), - matched_project_count=len(matched_project_ids), - topics=topic_list, - ) - - -async def get_dashboard_eu_topics( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> EuProjectTopics: - normalized_id = _normalize_institution_id(institution_id) - project_ids = await _get_eu_project_ids_from_projects_service( - normalized_id, - from_year=from_year, - to_year=to_year, - ) - topics: dict[str, dict[str, Any]] = {} - matched_project_ids: set[str] = set() - - if project_ids: - mapping_indices = ( - ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING, - ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS, - ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS, - ) - for mapping_index in mapping_indices: - async for hit in elasticsearch.scan( - index=str(mapping_index), - query={"terms": {"project_id": project_ids}}, - source=["project_id", "keyword", "topic_matches"], - page_size=1000, - cluster=ESCluster.INSE, - ): - source = hit.get("_source", {}) - project_id = str(source.get("project_id") or "") - if not project_id: - continue - keyword = str(source.get("keyword") or "").strip() - matched_project_ids.add(project_id) - for match in source.get("topic_matches", []): - topic_id = str(match.get("topic_id") or "") - if not topic_id: - continue - topic = topics.setdefault( - topic_id, - { - "id": topic_id, - "name": str(match.get("topic_display_name") or topic_id), - "subfield": match.get("subfield"), - "field": match.get("field"), - "domain": match.get("domain"), - "project_ids": set(), - "keywords": {}, - }, - ) - topic["project_ids"].add(project_id) - if keyword: - topic["keywords"].setdefault(keyword, set()).add(project_id) - - field_project_ids: dict[str, set[str]] = defaultdict(set) - subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) - for topic in topics.values(): - field_name = str(topic["field"] or "") - subfield_name = str(topic["subfield"] or "") - field_project_ids[field_name].update(topic["project_ids"]) - subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) - - topic_list = [ - DfgProjectTopic( - id=topic["id"], - name=topic["name"], - subfield=topic["subfield"], - field=topic["field"], - domain=topic["domain"], - project_count=len(topic["project_ids"]), - field_project_count=len(field_project_ids[str(topic["field"] or "")]), - subfield_project_count=len( - subfield_project_ids[ - (str(topic["field"] or ""), str(topic["subfield"] or "")) - ] - ), - keywords=sorted( - [ - DfgProjectKeyword( - name=keyword, - project_count=len(keyword_project_ids), - ) - for keyword, keyword_project_ids in topic["keywords"].items() - ], - key=lambda entry: (-entry.project_count, entry.name), - ), - ) - for topic in topics.values() - ] - topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) - return EuProjectTopics( - institution_id=normalized_id, - organization_name=organization_name, - project_count=len(project_ids), - matched_project_count=len(matched_project_ids), - topics=topic_list, - ) - - -async def get_dashboard_bund_topics( - institution_id: str, - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> BundProjectTopics: - normalized_id = _normalize_institution_id(institution_id) - period = _dashboard_period(from_year, to_year) - page_size = 1000 - page_number = 0 - project_ids: set[str] = set() - - while True: - projects = await projects_service.search_bund_projects_with_filters( - institutions_search_client=InstitutionsSearchClient(), - executing_agency=None, - raw_oa_institution_id=_raw_institution_id(normalized_id), - title=None, - keywords=None, - funding_arts=None, - topic_ids=None, - filter_topic_ids=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - page=page_number, - size=page_size, - sort_by="id", - sort_direction="asc", - fuzzy=False, - ) - project_ids.update( - project.funding_code - for project in projects.elements - if project.funding_code - ) - if len(project_ids) >= projects.total or not projects.elements: - break - page_number += 1 - - topics: dict[str, dict[str, Any]] = {} - matched_project_ids: set[str] = set() - if project_ids: - mapping_project_ids = sorted( - hashlib.sha256(project_id.encode("utf-8")).hexdigest() - for project_id in project_ids - ) - async for hit in elasticsearch.scan( - index=str(ESIndex.PROJECTS_BUND_TOPICS), - query={"terms": {"project_id": mapping_project_ids}}, - source=["project_id", "keyword", "topic_matches"], - page_size=1000, - cluster=ESCluster.INSE, - ): - source = hit.get("_source", {}) - project_id = str(source.get("project_id") or "") - if not project_id: - continue - keyword = str(source.get("keyword") or "").strip() - matched_project_ids.add(project_id) - for match in source.get("topic_matches", []): - topic_id = str(match.get("topic_id") or "") - if not topic_id: - continue - topic = topics.setdefault( - topic_id, - { - "id": topic_id, - "name": str(match.get("topic_display_name") or topic_id), - "subfield": match.get("subfield"), - "field": match.get("field"), - "domain": match.get("domain"), - "project_ids": set(), - "keywords": {}, - }, - ) - topic["project_ids"].add(project_id) - if keyword: - topic["keywords"].setdefault(keyword, set()).add(project_id) - - field_project_ids: dict[str, set[str]] = defaultdict(set) - subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set) - for topic in topics.values(): - field_name = str(topic["field"] or "") - subfield_name = str(topic["subfield"] or "") - field_project_ids[field_name].update(topic["project_ids"]) - subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"]) - - topic_list = [ - DfgProjectTopic( - id=topic["id"], - name=topic["name"], - subfield=topic["subfield"], - field=topic["field"], - domain=topic["domain"], - project_count=len(topic["project_ids"]), - field_project_count=len(field_project_ids[str(topic["field"] or "")]), - subfield_project_count=len( - subfield_project_ids[ - (str(topic["field"] or ""), str(topic["subfield"] or "")) - ] - ), - keywords=sorted( - [ - DfgProjectKeyword( - name=keyword, - project_count=len(keyword_project_ids), - ) - for keyword, keyword_project_ids in topic["keywords"].items() - ], - key=lambda entry: (-entry.project_count, entry.name), - ), - ) - for topic in topics.values() - ] - topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id)) - return BundProjectTopics( - institution_id=normalized_id, - organization_name=organization_name, - project_count=len(project_ids), - matched_project_count=len(matched_project_ids), - topics=topic_list, - ) - - -async def _get_dfg_project_ids_from_projects_service( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[str]: - """Returns every matching DFG project ID through the canonical project service.""" - period = _dashboard_period(from_year, to_year) - page_size = 1000 - page_number = 0 - project_ids: set[str] = set() - - while True: - projects = await projects_service.get_dfg_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(institution_id), - author_id=None, - author_filter_ids=None, - institution_ids=None, - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=( - [str(year) for year in range(1900, period[1] + 1)] - if period[1] is not None - else None - ), - funding_end_years=( - [str(year) for year in range(period[0], 2101)] - if period[0] is not None - else None - ), - page=page_number, - size=page_size, - sort_by="id", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - project_ids.update(project.id for project in projects.elements if project.id) - if len(project_ids) >= projects.total or not projects.elements: - break - page_number += 1 - - return sorted(project_ids) - - -async def _get_dfg_project_ids_for_institution( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[str]: - period = _dashboard_period(from_year, to_year) - institution = await get_openalex_institution(institution_id) - institution_names = _openalex_institution_names(institution) - - institutes_response = await elasticsearch.search( - index=ESIndex.DFG_INSTITUTES_V2, - body={ - "size": 0, - "query": _dfg_institute_name_query(institution_names), - "aggs": { - "institute_ids": { - "terms": {"field": "institute_id", "size": 1000} - } - }, - }, - cluster=ESCluster.INSE, - ) - institute_ids = [ - bucket["key"] - for bucket in ( - institutes_response.get("aggregations", {}) - .get("institute_ids", {}) - .get("buckets", []) - ) - if bucket.get("key") is not None - ] - if not institute_ids: - return [] - - projects_response = await elasticsearch.search( - index=ESIndex.DFG_INSTITUTES_V2, - body={ - "size": 0, - "query": {"terms": {"institute_id": institute_ids}}, - "aggs": { - "projects_nested": { - "nested": {"path": "projects"}, - "aggs": { - "project_ids": { - "filter": { - "terms": {"projects.institute_ref_id": institute_ids} - }, - "aggs": { - "values": { - "terms": { - "field": "projects.project_id", - "size": 10000, - } - } - }, - } - }, - } - }, - }, - cluster=ESCluster.INSE, - ) - project_ids = [ - str(bucket["key"]) - for bucket in ( - projects_response.get("aggregations", {}) - .get("projects_nested", {}) - .get("project_ids", {}) - .get("values", {}) - .get("buckets", []) - ) - if bucket.get("key") is not None - ] - return await _filter_dfg_project_ids_by_period(project_ids, period) - - -async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]: - project_ids: set[str] = set() - async for hit in elasticsearch.scan( - index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD), - query=_eu_organization_query(aliases), - source=["projectID"], - page_size=1000, - cluster=ESCluster.INSE, - ): - project_id = hit.get("_source", {}).get("projectID") - if project_id is not None: - project_ids.add(str(project_id)) - return project_ids - - -async def _count_eu_projects_in_period( - project_ids: set[str], - period_filter: dict[str, Any], -) -> int: - if not project_ids: - return 0 - response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, - body={ - "size": 0, - "query": { - "bool": { - "filter": [ - {"terms": {"id": sorted(project_ids)}}, - period_filter, - ] - } - }, - "aggs": {"projects": {"cardinality": {"field": "id"}}}, - }, - cluster=ESCluster.INSE, - ) - return int( - response.get("aggregations", {}) - .get("projects", {}) - .get("value", 0) - ) - - -async def _filter_dfg_project_ids_by_period( - project_ids: list[str], - period: DashboardPeriod, -) -> list[str]: - period_filter = _project_overlap_filter( - "funding_start", - "funding_end", - period, - missing_end_is_ongoing=True, - ) - if not project_ids or not period_filter: - return project_ids - - numeric_project_ids = [ - int(project_id) - for project_id in project_ids - if str(project_id).isdigit() - ] - if not numeric_project_ids: - return [] - - response = await elasticsearch.search( - index=ESIndex.DFG_PROJECTS, - body={ - "size": 0, - "query": { - "bool": { - "filter": [ - {"terms": {"id": numeric_project_ids}}, - period_filter, - ] - } - }, - "aggs": { - "project_ids": { - "terms": { - "field": "id", - "size": len(numeric_project_ids), - } - } - }, - }, - cluster=ESCluster.INSE, - ) - return [ - str(bucket["key"]) - for bucket in ( - response.get("aggregations", {}) - .get("project_ids", {}) - .get("buckets", []) - ) - if bucket.get("key") is not None - ] - - -def _dashboard_statistic_value( - institution_id: str, - organization_name: str, - response: dict[str, Any], -) -> DashboardStatisticValue: - return DashboardStatisticValue( - institution_id=institution_id, - organization_name=organization_name, - value=_total(response), - ) - - -async def _institution_aliases( - institution_id: str, - organization_name: str, -) -> list[str]: - aliases = await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id( - _raw_institution_id(institution_id) - ) - return sorted( - { - alias.strip() - for alias in [organization_name, *aliases] - if alias and alias.strip() - } - ) - - -def _eu_organization_query(aliases: list[str]) -> dict[str, Any]: - return { - "terms": { - "name.keyword": [alias.upper() for alias in aliases], - } - } - - -def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]: - return { - "bool": { - "should": [ - { - "match": { - field: { - "query": alias, - "operator": "and", - } - } - } - for alias in aliases - ], - "minimum_should_match": 1, - } - } - - -def _openalex_institution_names(institution: Any) -> list[str]: - return sorted( - { - name.strip() - for name in [ - institution.display_name, - *(institution.display_name_alternatives or []), - *(institution.display_name_acronyms or []), - ] - if name and name.strip() - } - ) - - -def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]: - return { - "bool": { - "should": [ - { - "terms": { - "institute_name_de.keyword": institution_names, - } - }, - { - "terms": { - "institute_name_en.keyword": institution_names, - } - }, - ], - "minimum_should_match": 1, - } - } - - -async def get_top_authors( - institution_id: str, - organization_name: str, - works_period: WorksPeriod = "all_time", - from_year: int | None = None, - to_year: int | None = None, -) -> TopAuthorStatistics: - normalized_id = _normalize_institution_id(institution_id) - if from_year is None and to_year is None and works_period == "last_5_years": - from_year = datetime.now().year - 4 - to_year = datetime.now().year - period = _dashboard_period(from_year, to_year) - authors = await _safe_institution_authors(normalized_id) - works = await _safe_top_authors( - "works", - _top_work_authors(normalized_id, period), - ) - projects = await _safe_top_authors( - "projects", - _top_project_authors( - authors=authors, - organization_name=organization_name, - from_year=period[0], - to_year=period[1], - ), - ) - eu_projects = await _safe_top_authors( - "eu_projects", - _top_eu_project_publication_authors( - normalized_id, - authors, - from_year=period[0], - to_year=period[1], - ), - ) - - patents = await _safe_top_authors( - "patents", - _top_patent_authors( - normalized_id, - from_year=period[0], - to_year=period[1], - ), - ) - - news = await _safe_top_authors( - "news", - _top_news_authors( - authors, - from_year=period[0], - to_year=period[1], - ), - ) - - return TopAuthorStatistics( - institution_id=normalized_id, - works=works, - projects=projects, - eu_projects=eu_projects, - patents=patents, - news=news, - ) - - async def get_topic_heatmap( institution_id: str, organization_name: str, @@ -1721,39 +418,9 @@ async def get_topic_word_cloud( return TopicWordCloud(topic_id=topic_id, words=words) -async def _safe_top_authors( - source: str, operation: Any -) -> list[TopAuthor]: - try: - return await operation - except Exception: - logger.exception("Dashboard top-author aggregation failed for %s.", source) - return [] - - -def _normalize_institution_id(value: str) -> str: - short_id = value.replace("https://openalex.org/", "").strip().upper() - return f"https://openalex.org/{short_id}" - - -def _raw_institution_id(value: str) -> str: - return value.replace("https://openalex.org/", "").strip().upper() - - -def _institution_works_query(institution_id: str) -> dict[str, Any]: - return { - "nested": { - "path": "authorships.institutions", - "query": {"term": {"authorships.institutions.id": institution_id}}, - } - } - - def _year_totals(response: dict[str, Any]) -> dict[int, int]: buckets = ( - response.get("aggregations", {}) - .get("publication_years", {}) - .get("buckets", []) + response.get("aggregations", {}).get("publication_years", {}).get("buckets", []) ) return { int(bucket["key"]): int(bucket.get("doc_count", 0)) @@ -1781,8 +448,7 @@ async def _field_names(field_ids: list[str | None]) -> dict[str, str]: return { source["id"]: source["display_name"] for hit in response.get("hits", {}).get("hits", []) - if (source := hit.get("_source", {})).get("id") - and source.get("display_name") + if (source := hit.get("_source", {})).get("id") and source.get("display_name") } @@ -1858,930 +524,8 @@ def _field_name(bucket: dict[str, Any], fallback: str) -> str: return _aggregation_name(bucket, "field_name", fallback) -def _aggregation_name( - bucket: dict[str, Any], aggregation: str, fallback: str -) -> str: +def _aggregation_name(bucket: dict[str, Any], aggregation: str, fallback: str) -> str: name_buckets = bucket.get(aggregation, {}).get("buckets", []) if name_buckets and name_buckets[0].get("key"): return str(name_buckets[0]["key"]) return fallback - - -def _short_author_id(value: str) -> str: - return value.replace("https://openalex.org/", "").strip().upper() - - -async def _top_work_authors( - institution_id: str, - period: DashboardPeriod, -) -> list[TopAuthor]: - must = [works_v2_service._institutions_nested_query([institution_id])] - if publication_years := _dashboard_publication_years(period): - must.append({"terms": {"publication_year": publication_years}}) - - author_counts: dict[str, int] = defaultdict(int) - author_names: dict[str, str] = {} - async for hit in elasticsearch.scan( - index=str(ESIndex.OPENALEX_WORKS_WILDCARD), - query={"bool": {"must": must}}, - source=["id", "authorships.author.id", "authorships.author.display_name"], - page_size=1000, - cluster=ESCluster.NES, - ): - hit_author_ids: set[str] = set() - for authorship in hit.get("_source", {}).get("authorships", []): - author = authorship.get("author") or {} - author_id = author.get("id") - if not author_id: - continue - author_id = str(author_id) - hit_author_ids.add(author_id) - if author.get("display_name"): - author_names.setdefault(author_id, str(author["display_name"])) - for author_id in hit_author_ids: - author_counts[author_id] += 1 - - ranked_authors = sorted( - ( - { - "id": author_id, - "name": author_names.get(author_id, author_id), - "count": count, - } - for author_id, count in author_counts.items() - ), - key=lambda author: author["count"], - reverse=True, - ) - return [ - TopAuthor( - id=_short_author_id(author["id"]), - name=author["name"], - count=author["count"], - ) - for author in ranked_authors[:TOP_AUTHOR_LIMIT] - if author["count"] > 0 - ] - - -async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]: - try: - return await _institution_authors(institution_id) - except Exception: - logger.exception("Could not load authors for institution %s.", institution_id) - return [] - - -async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: - response = await elasticsearch.search( - index=ESIndex.OPENALEX_AUTHORS, - query={ - "nested": { - "path": "last_known_institutions", - "query": {"term": {"last_known_institutions.id": institution_id}}, - } - }, - source=["id", "display_name", "works_count", "counts_by_year"], - size=10000, - sort=[{"works_count": {"order": "desc", "missing": "_last"}}], - cluster=ESCluster.NES, - ) - return [ - { - "id": str(source["id"]), - "name": str(source["display_name"]), - "works_count": int(source.get("works_count", 0)), - "counts_by_year": source.get("counts_by_year", []) or [], - } - for hit in response.get("hits", {}).get("hits", []) - if (source := hit.get("_source", {})).get("id") - and source.get("display_name") - ] - - -async def _top_project_authors( - authors: list[dict[str, Any]], - organization_name: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[TopAuthor]: - period = _dashboard_period(from_year, to_year) - institution_ids = await _dfg_institution_ids_for_organization( - organization_name=organization_name, - ) - - logger.info( - "DFG institution IDs for %s: %s", - organization_name, - institution_ids, - ) - - if not institution_ids: - logger.warning( - "No DFG institution IDs found for organization %s.", - organization_name, - ) - return [] - - selected_person_ids = set( - await get_person_ids_by_institution_ids(institution_ids=institution_ids) - ) - - logger.info( - "Found %s DFG persons for organization %s.", - len(selected_person_ids), - organization_name, - ) - - if not selected_person_ids: - return [] - - project_ids_by_person: dict[int, set[str]] = {} - names: dict[int, str] = {} - - page = 0 - size = 10000 - processed = 0 - - while True: - project_hits, total = await _dfg_project_author_hits( - page=page, - size=size, - person_ids=selected_person_ids, - period=period, - ) - - if not project_hits: - break - - for project in project_hits: - project_id = _dfg_project_id(project) - if not project_id: - continue - - persons = project.get("persons", []) - if not isinstance(persons, list): - continue - - for person in persons: - if not isinstance(person, dict): - continue - - person_id = person.get("person_id") - full_name = person.get("full_name") - if person_id is None or not full_name: - continue - - try: - normalized_person_id = int(person_id) - except (TypeError, ValueError): - continue - - if normalized_person_id not in selected_person_ids: - continue - - project_ids_by_person.setdefault(normalized_person_id, set()).add( - project_id - ) - names[normalized_person_id] = str(full_name).strip() - - processed += len(project_hits) - if processed >= total: - break - - page += 1 - - 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( - ( - (person_id, project_ids) - for person_id, project_ids in project_ids_by_person.items() - if project_ids and names.get(person_id) - ), - key=lambda item: ( - -len(item[1]), - names[item[0]].casefold(), - ), - ) - - 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 = _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=( - _short_author_id(matched_author["id"]) - if matched_author - else None - ), - name=matched_author["name"] if matched_author else dfg_name, - count=len(project_ids), - ) - ) - - logger.info( - "DFG top authors for %s: %s", - organization_name, - [ - { - "name": author.name, - "count": author.count, - "id": author.id, - } - for author in result - ], - ) - - 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, - page=0, - size=10000, - ) - return [institution.id for institution in page.elements if institution.id is not None] - - -async def _dfg_project_author_hits( - page: int, - size: int, - person_ids: set[int], - period: DashboardPeriod = (None, None), -) -> tuple[list[dict[str, Any]], int]: - person_query = { - "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": sorted(person_ids)}}, - }, - } - period_filter = _project_overlap_filter( - "funding_start", - "funding_end", - period, - missing_end_is_ongoing=True, - ) - query = ( - {"bool": {"filter": [person_query, period_filter]}} - if period_filter - else person_query - ) - response = await elasticsearch.search( - index=ESIndex.DFG_PROJECTS, - body={ - "size": size, - "from": page * size, - "_source": [ - "id", - "project_id", - "persons", - ], - "query": query, - "sort": [ - { - "id": { - "order": "asc", - "missing": "_last", - } - } - ], - }, - cluster=ESCluster.INSE, - track_total_hits=True, - ) - - hits_block = response.get("hits", {}) - total_value = hits_block.get("total", 0) - - if isinstance(total_value, dict): - total = int(total_value.get("value", 0)) - else: - total = int(total_value or 0) - - hits = [ - hit.get("_source", {}) - for hit in hits_block.get("hits", []) - if isinstance(hit.get("_source"), dict) - ] - - logger.info( - "Loaded %s of %s matching DFG projects on page %s.", - len(hits), - total, - page, - ) - - return hits, total - - -def _dfg_project_id(project: dict[str, Any]) -> str | None: - project_id = project.get("id") - if project_id is None: - project_id = project.get("project_id") - return str(project_id) if project_id is not None else None - - -async def _top_patent_authors( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[TopAuthor]: - client = OrgPatentsSearchClient() - authors = await client.top_authors_by_institution( - institution_id=institution_id, - size=TOP_AUTHOR_LIMIT, - from_year=from_year, - to_year=to_year, - ) - return [ - TopAuthor( - id=_short_author_id(author["id"]), - name=author["name"], - count=author["count"], - ) - for author in authors - ] - - -async def _top_eu_project_publication_authors( - institution_id: str, - institution_authors: list[dict[str, Any]], - from_year: int | None = None, - to_year: int | None = None, -) -> 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_ids = await _get_eu_project_ids_from_projects_service( - institution_id, - from_year=from_year, - to_year=to_year, - ) - - if not project_ids: - return [] - - publication_response = await elasticsearch.search( - index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, - body={ - "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, - ) - - candidates = _openalex_work_authors_by_eu_projects( - works_response, - doi_project_ids, - institution_id, - institution_author_ids, - limit=None, - ) - counts = await asyncio.gather( - *( - _person_eu_project_count( - candidate.id, - from_year=from_year, - to_year=to_year, - ) - for candidate in candidates - if candidate.id - ) - ) - ranked = [ - TopAuthor(id=candidate.id, name=candidate.name, count=count) - for candidate, count in zip(candidates, counts, strict=True) - ] - ranked.sort(key=lambda author: (-author.count, author.name, author.id or "")) - return ranked[:TOP_AUTHOR_LIMIT] - - -async def _get_eu_project_ids_from_projects_service( - institution_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> list[str]: - """Loads all organization EU project IDs from the canonical project service.""" - period = _dashboard_period(from_year, to_year) - page_size = 1000 - page_number = 0 - project_ids: set[str] = set() - - while True: - projects = await projects_service.search_eu_cordis_projects( - institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(institution_id), - author_id=None, - author_ids=None, - organization_ids=None, - organization_names=None, - project_types=list(EuCordisProjectType), - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - framework_programmes=None, - funding_schemes=None, - statuses=None, - page=page_number, - size=page_size, - sort_by="id", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - project_ids.update(project.id for project in projects.elements if project.id) - if len(project_ids) >= projects.total or not projects.elements: - break - page_number += 1 - - return sorted(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 - 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], - limit: int | None = TOP_AUTHOR_LIMIT, -) -> 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]), - ) - - authors = [ - TopAuthor( - id=_short_author_id(author_id), - name=author_names[author_id], - count=len(project_ids), - ) - for author_id, project_ids in ranked_authors - ] - return authors[:limit] if limit is not None else authors - - -async def _person_eu_project_count( - author_id: str, - from_year: int | None = None, - to_year: int | None = None, -) -> int: - """Returns the same filtered EU project total as the person projects tab.""" - period = _dashboard_period(from_year, to_year) - projects = await projects_service.search_eu_cordis_projects( - page=0, - size=1, - project_types=None, - raw_oa_institution_id=None, - institutions_search_client=None, - author_id=_short_author_id(author_id), - author_ids=None, - organization_ids=None, - organization_names=None, - keywords=None, - topic_ids=None, - filter_topic_ids=None, - title=None, - funding_start_years=None, - funding_end_years=None, - active_from_year=period[0], - active_to_year=period[1], - countries=None, - framework_programmes=None, - funding_schemes=None, - statuses=None, - sort_by="title", - sort_direction="asc", - fuzzy=False, - skip_enrichment=True, - ) - return projects.total - - -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]], - from_year: int | None = None, - to_year: int | None = None, -) -> list[TopAuthor]: - if not authors: - return [] - - period = _dashboard_period(from_year, to_year) - author_names = [author["name"] for author in authors] - filters: list[dict[str, Any]] = [ - {"terms": {"authors.keyword": author_names}} - ] - if period != (None, None): - date_range: dict[str, int] = {} - if period[0] is not None: - date_range["gte"] = period[0] - if period[1] is not None: - date_range["lte"] = period[1] - news_ids = [ - str(hit["_id"]) - async for hit in elasticsearch.scan( - index=str(ESIndex.AKTUELLES), - query={"range": {"date_year": date_range}}, - source=False, - page_size=1000, - cluster=ESCluster.INSE, - ) - if hit.get("_id") - ] - if not news_ids: - return [] - filters.append({"terms": {"news_id.keyword": news_ids}}) - - response = await elasticsearch.search( - index="aktuell_postproc", - body={ - "size": 0, - "query": ( - filters[0] - if len(filters) == 1 - else {"bool": {"filter": filters}} - ), - "aggs": { - "authors": { - "terms": { - "field": "authors.keyword", - "size": 10000, - "order": [ - {"_count": "desc"}, - {"_key": "asc"}, - ], - } - } - }, - }, - cluster=ESCluster.INSE, - ) - buckets = response.get("aggregations", {}).get("authors", {}).get("buckets", []) - institution_authors = {author["name"].casefold(): author for author in authors} - - return [ - TopAuthor( - id=_short_author_id(institution_authors[str(bucket["key"]).casefold()]["id"]), - name=institution_authors[str(bucket["key"]).casefold()]["name"], - count=int(bucket.get("doc_count", 0)), - ) - for bucket in buckets - if str(bucket.get("key", "")).casefold() in institution_authors - ][:TOP_AUTHOR_LIMIT] diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 648097f6..2e8cc6c0 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,6 +1,5 @@ from datetime import datetime import hashlib -from types import SimpleNamespace from unittest.mock import AsyncMock, patch import pytest @@ -10,25 +9,33 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( - _get_dfg_project_ids_from_projects_service, - _openalex_work_authors_by_eu_projects, - _project_boundary_year_filter, - _reconcile_project_status_counts, - _top_news_authors, - get_dashboard_bmbf_projects, - get_dashboard_bund_topics, - get_dashboard_dfg_projects, - get_dashboard_eu_projects, - get_dashboard_eu_topics, get_dashboard_organization, get_dashboard_persons, get_dashboard_publications, get_dashboard_statistics, - get_top_authors, get_topic_heatmap, get_topic_word_cloud, ) -from inse.model import ESCluster, ESIndex +from inse.dashboard.common import ( + project_boundary_year_filter as _project_boundary_year_filter, +) +from inse.dashboard.bund_topics_service import get_dashboard_bund_topics +from inse.dashboard.eu_topics_service import get_dashboard_eu_topics +from inse.dashboard.project_status_service import reconcile_status_counts +from inse.dashboard.project_ids_service import ( + _get_dfg_project_ids_from_projects_service, +) +from inse.dashboard.project_statistics_service import ( + get_dashboard_bmbf_projects, + get_dashboard_dfg_projects, + get_dashboard_eu_projects, +) +from inse.dashboard.top_authors_service import ( + _openalex_work_authors_by_eu_projects, + _top_news_authors, + get_top_authors, +) +from inse.model import ESIndex from inse.models.openalex.institution import Institution from inse.models.openalex.meta import Meta from inse.persons.model import CustomAuthorsListResponse @@ -52,8 +59,8 @@ def anyio_backend(): def test_project_status_counts_match_authoritative_total(): - assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5) - assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3) + assert reconcile_status_counts(12, 4, 1, 5) == (6, 1, 5) + assert reconcile_status_counts(7, 4, 2, 3) == (2, 2, 3) def test_project_status_period_uses_interval_overlap(): @@ -86,25 +93,25 @@ def test_project_status_period_uses_interval_overlap(): async def test_top_news_authors_applies_dashboard_period(): response = { "aggregations": { - "authors": { - "buckets": [{"key": "Ada Example", "doc_count": 3}] - } + "authors": {"buckets": [{"key": "Ada Example", "doc_count": 3}]} } } + async def scan(**kwargs): assert kwargs["index"] == str(ESIndex.AKTUELLES) - assert kwargs["query"] == { - "range": {"date_year": {"gte": 2020, "lte": 2023}} - } + assert kwargs["query"] == {"range": {"date_year": {"gte": 2020, "lte": 2023}}} yield {"_id": "N1"} yield {"_id": "N2"} - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(return_value=response), - ) as mocked_search, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as mocked_search, + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), ): result = await _top_news_authors( [{"id": "https://openalex.org/A1", "name": "Ada Example"}], @@ -141,7 +148,7 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service(): ] with patch( - "inse.dashboard.service.projects_service.get_dfg_projects", + "inse.projects.service.get_dfg_projects", new=AsyncMock(side_effect=pages), ) as mocked_get_projects: project_ids = await _get_dfg_project_ids_from_projects_service( @@ -213,10 +220,13 @@ async def test_eu_topics_scan_all_programme_indices_and_deduplicate_projects(): } } - with patch( - "inse.dashboard.service._get_eu_project_ids_from_projects_service", - new=AsyncMock(return_value=["P1", "P2", "P3"]), - ), patch("inse.dashboard.service.elasticsearch.scan", new=scan): + with ( + patch( + "inse.dashboard.eu_topics_service._get_eu_project_ids_from_projects_service", + new=AsyncMock(return_value=["P1", "P2", "P3"]), + ), + patch("inse.integrations.elasticsearch.scan", new=scan), + ): result = await get_dashboard_eu_topics( ORG_INSTITUTION_ID, "Example Org", @@ -282,12 +292,15 @@ async def test_bund_topics_use_mapping_index_and_unique_hierarchy_counts(): } } - with patch( - "inse.dashboard.service.projects_service.search_bund_projects_with_filters", - new=AsyncMock(return_value=project_page), - ) as mocked_projects, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, + with ( + patch( + "inse.projects.service.search_bund_projects_with_filters", + new=AsyncMock(return_value=project_page), + ) as mocked_projects, + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), ): result = await get_dashboard_bund_topics( ORG_INSTITUTION_ID, @@ -328,9 +341,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): if index == ESIndex.DFG_INSTITUTES_V2: if "institute_ids" in kwargs["body"].get("aggs", {}): return { - "aggregations": { - "institute_ids": {"buckets": [{"key": 10210}]} - } + "aggregations": {"institute_ids": {"buckets": [{"key": 10210}]}} } return { "aggregations": { @@ -350,48 +361,59 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): return {"hits": {"total": {"value": 3}}} - 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", "Example Uni"]), - ), patch( - "inse.dashboard.service.get_openalex_institution", - new=AsyncMock( - return_value=Institution( - id=ORG_INSTITUTION_ID, - display_name="Example University", - display_name_alternatives=["Example Universität"], - ) + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), ), - ), patch( - "inse.dashboard.service.projects_service.get_dfg_projects", - new=AsyncMock( - return_value=DfgProjectPage(elements=[], total=3, page=0, size=1) + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University", "Example Uni"]), ), - ), patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", - new=AsyncMock( - return_value=EuCordisProjectSearchPage( - elements=[], total=10, page=0, size=1 - ) + patch( + "inse.dashboard.project_status_service.get_openalex_institution", + new=AsyncMock( + return_value=Institution( + id=ORG_INSTITUTION_ID, + display_name="Example University", + display_name_alternatives=["Example Universität"], + ) + ), ), - ), patch( - "inse.dashboard.service.projects_service.search_bund_projects_with_filters", - new=AsyncMock( - return_value=BundProjectPage(elements=[], total=5, page=0, size=1) + patch( + "inse.projects.service.get_dfg_projects", + new=AsyncMock( + return_value=DfgProjectPage(elements=[], total=3, page=0, size=1) + ), ), - ), patch( - "inse.dashboard.service.persons_service.search_persons_list", - new=AsyncMock( - return_value=CustomAuthorsListResponse( - results=[], meta=Meta(count=35, page=1, per_page=1) - ) + patch( + "inse.projects.service.search_eu_cordis_projects", + new=AsyncMock( + return_value=EuCordisProjectSearchPage( + elements=[], total=10, page=0, size=1 + ) + ), + ), + patch( + "inse.projects.service.search_bund_projects_with_filters", + new=AsyncMock( + return_value=BundProjectPage(elements=[], total=5, page=0, size=1) + ), + ), + patch( + "inse.dashboard.service.persons_service.search_persons_list", + new=AsyncMock( + return_value=CustomAuthorsListResponse( + results=[], meta=Meta(count=35, page=1, per_page=1) + ) + ), + ), + patch( + "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", + new=AsyncMock( + return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120) + ), ), - ), patch( - "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", - new=AsyncMock(return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)), ): result = await get_dashboard_statistics( ORG_INSTITUTION_ID, @@ -409,17 +431,21 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } + @pytest.mark.anyio async def test_dashboard_publications_uses_exact_es_count_for_period(): - with patch( - "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", - new=AsyncMock( - return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) - ), - ) as mocked_get_institution, patch( - "inse.dashboard.service.elasticsearch.count", - new=AsyncMock(return_value=22), - ) as mocked_count: + with ( + patch( + "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", + new=AsyncMock( + return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250) + ), + ) as mocked_get_institution, + patch( + "inse.integrations.elasticsearch.count", + new=AsyncMock(return_value=22), + ) as mocked_count, + ): all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -478,7 +504,7 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): project_page = DfgProjectPage(elements=[], total=42, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.get_dfg_projects", + "inse.projects.service.get_dfg_projects", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_dfg_projects( @@ -506,7 +532,7 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total(): project_page = BundProjectPage(elements=[], total=29, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.search_bund_projects_with_filters", + "inse.projects.service.search_bund_projects_with_filters", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_bmbf_projects( @@ -530,12 +556,10 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total(): @pytest.mark.anyio async def test_dashboard_eu_projects_uses_projects_service_total(): - project_page = EuCordisProjectSearchPage( - elements=[], total=37, page=0, size=1 - ) + project_page = EuCordisProjectSearchPage(elements=[], total=37, page=0, size=1) with patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", + "inse.projects.service.search_eu_cordis_projects", new=AsyncMock(return_value=project_page), ) as mocked_get_projects: result = await get_dashboard_eu_projects( @@ -588,11 +612,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): if kwargs["index"] == "aktuell_postproc": return { "aggregations": { - "authors": { - "buckets": [ - {"key": "Ada Example", "doc_count": 6} - ] - } + "authors": {"buckets": [{"key": "Ada Example", "doc_count": 6}]} } } if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD: @@ -618,9 +638,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): if kwargs["index"] == ESIndex.DFG_PROJECTS: return { "aggregations": { - "people": { - "buckets": [{"key": "Grace Example", "doc_count": 3}] - } + "people": {"buckets": [{"key": "Grace Example", "doc_count": 3}]} } } @@ -712,9 +730,15 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): if kwargs.get("raw_oa_institution_id"): return EuCordisProjectSearchPage( elements=[ - EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), - EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), - EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU), + EuCordisProjectSummary( + id="P1", project_type=EuCordisProjectType.FP7 + ), + EuCordisProjectSummary( + id="P2", project_type=EuCordisProjectType.H2020 + ), + EuCordisProjectSummary( + id="P3", project_type=EuCordisProjectType.HEU + ), ], total=3, page=0, @@ -727,24 +751,30 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): size=1, ) - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ) as mocked_search, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.projects_service.search_eu_cordis_projects", - new=AsyncMock(side_effect=eu_projects), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock( - return_value=[ - {"id": "A1", "name": "Ada Example", "count": 4}, - ] + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ) as mocked_search, + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.projects.service.search_eu_cordis_projects", + new=AsyncMock(side_effect=eu_projects), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock( + return_value=[ + {"id": "A1", "name": "Ada Example", "count": 4}, + ] + ), ), ): result = await get_top_authors( @@ -775,8 +805,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): project_calls = [ call for call in mocked_search.await_args_list - if call.kwargs["index"] - in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1} + if call.kwargs["index"] in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1} ] assert project_calls == [] @@ -926,9 +955,7 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i } } if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD: - assert kwargs["body"]["query"] == { - "terms": {"projectID": ["P1", "P2"]} - } + assert kwargs["body"]["query"] == {"terms": {"projectID": ["P1", "P2"]}} return { "hits": { "hits": [ @@ -1056,8 +1083,12 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i if kwargs.get("raw_oa_institution_id"): return EuCordisProjectSearchPage( elements=[ - EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7), - EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020), + EuCordisProjectSummary( + id="P1", project_type=EuCordisProjectType.FP7 + ), + EuCordisProjectSummary( + id="P2", project_type=EuCordisProjectType.H2020 + ), ], total=2, page=0, @@ -1070,18 +1101,23 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i size=1, ) - 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.projects_service.search_eu_cordis_projects", - new=AsyncMock(side_effect=eu_projects), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.projects.service.search_eu_cordis_projects", + new=AsyncMock(side_effect=eu_projects), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ), ): result = await get_top_authors( ORG_INSTITUTION_ID, @@ -1133,27 +1169,23 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): }, } - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, - ), 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"), - ], - ) + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), ), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), ): result = await get_top_authors( ORG_INSTITUTION_ID, @@ -1235,21 +1267,23 @@ async def test_top_authors_can_rank_works_by_last_five_years(): }, } - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ) as mocked_search, patch( - "inse.dashboard.service.elasticsearch.scan", - new=scan, - ), 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=[]), + with ( + patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), + patch( + "inse.integrations.elasticsearch.scan", + new=scan, + ), + patch( + "inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", + new=AsyncMock(return_value=["Example University"]), + ), + patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ), ): result = await get_top_authors( ORG_INSTITUTION_ID, @@ -1369,7 +1403,7 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): } with patch( - "inse.dashboard.service.elasticsearch.search", + "inse.integrations.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search: result = await get_topic_heatmap( @@ -1423,17 +1457,14 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares(): == "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"] assert "aggs" not in subfield_aggs["subfields"]["aggs"]["works"] - assert ( - "aggs" - not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"] - ) + assert "aggs" not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"] @pytest.mark.anyio @@ -1449,7 +1480,7 @@ async def test_topic_heatmap_defaults_to_all_time(): return {"hits": {"hits": []}} with patch( - "inse.dashboard.service.elasticsearch.search", + "inse.integrations.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search: result = await get_topic_heatmap( @@ -1485,7 +1516,7 @@ async def test_topic_word_cloud_maps_related_topics_and_excludes_selected_topic( } } with patch( - "inse.dashboard.service.elasticsearch.search", + "inse.integrations.elasticsearch.search", new=AsyncMock(return_value=response), ) as mocked_search: result = await get_topic_word_cloud( diff --git a/service/src/main/inse/dashboard/top_authors_service.py b/service/src/main/inse/dashboard/top_authors_service.py new file mode 100644 index 00000000..a8e62560 --- /dev/null +++ b/service/src/main/inse/dashboard/top_authors_service.py @@ -0,0 +1,1100 @@ +import asyncio +import logging +import re +from collections import defaultdict +from datetime import datetime +from typing import Any, Literal + +from inse import config +from inse.integrations import elasticsearch +from inse.model import ESCluster, ESIndex +from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.projects import service as projects_service +from inse.projects.dfg_institutions.service import ( + autocomplete_institutions_for_selector, +) +from inse.projects.logic import get_person_ids_by_institution_ids +from inse.works.v2 import service as works_v2_service + +from .common import ( + DashboardPeriod, + dashboard_period as _dashboard_period, + institution_works_query as _institution_works_query, + normalize_institution_id as _normalize_institution_id, + project_overlap_filter as _project_overlap_filter, +) +from .model import TopAuthor, TopAuthorAnalysis, TopAuthorStatistics +from .project_ids_service import _get_eu_project_ids_from_projects_service + +TOP_AUTHOR_LIMIT = 10 +logger = logging.getLogger(__name__) +ACADEMIC_TITLE_RE = re.compile( + r"^(?:(?:professor(?:in)?|prof|dr)(?:\\.-[a-z]+)?\\.?|rer\\.|nat\\.|med\\.|ing\\.)\\s+", + re.IGNORECASE, +) + + +WorksPeriod = Literal["all_time", "last_5_years"] + + +def _period( + works_period: WorksPeriod = "all_time", + from_year: int | None = None, + to_year: int | None = None, +) -> DashboardPeriod: + if from_year is None and to_year is None and works_period == "last_5_years": + from_year = datetime.now().year - 4 + to_year = datetime.now().year + return _dashboard_period(from_year, to_year) + + +async def get_top_authors( + institution_id: str, + organization_name: str, + works_period: WorksPeriod = "all_time", + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorStatistics: + normalized_id = _normalize_institution_id(institution_id) + period = _period(works_period, from_year, to_year) + authors = await _safe_institution_authors(normalized_id) + + works = await _safe_top_authors("works", _top_work_authors(normalized_id, period)) + projects = await _safe_top_authors( + "projects", + _top_project_authors( + authors=authors, + organization_name=organization_name, + from_year=period[0], + to_year=period[1], + ), + ) + eu_projects = await _safe_top_authors( + "eu_projects", + _top_eu_project_publication_authors( + normalized_id, + authors, + from_year=period[0], + to_year=period[1], + ), + ) + patents = await _safe_top_authors( + "patents", + _top_patent_authors( + normalized_id, + from_year=period[0], + to_year=period[1], + ), + ) + news = await _safe_top_authors( + "news", + _top_news_authors( + authors, + from_year=period[0], + to_year=period[1], + ), + ) + + return TopAuthorStatistics( + institution_id=normalized_id, + works=works, + projects=projects, + eu_projects=eu_projects, + patents=patents, + news=news, + ) + + +async def get_top_work_authors( + institution_id: str, + works_period: WorksPeriod = "all_time", + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_work_authors( + normalized_id, _period(works_period, from_year, to_year) + ), + ) + + +async def get_top_project_authors( + institution_id: str, + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_project_authors( + authors=await _safe_institution_authors(normalized_id), + organization_name=organization_name, + from_year=period[0], + to_year=period[1], + ), + ) + + +async def get_top_eu_project_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + authors = await _safe_institution_authors(normalized_id) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_eu_project_publication_authors( + normalized_id, + authors, + from_year=period[0], + to_year=period[1], + ), + ) + + +async def get_top_patent_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_patent_authors( + normalized_id, + from_year=period[0], + to_year=period[1], + ), + ) + + +async def get_top_news_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> TopAuthorAnalysis: + normalized_id = _normalize_institution_id(institution_id) + period = _period(from_year=from_year, to_year=to_year) + return TopAuthorAnalysis( + institution_id=normalized_id, + authors=await _top_news_authors( + await _safe_institution_authors(normalized_id), + from_year=period[0], + to_year=period[1], + ), + ) + + +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 _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None: + from_year, to_year = period + if from_year is None and to_year is None: + return None + return list(range(from_year or 1900, (to_year or 2100) + 1)) + + +async def _safe_top_authors(source: str, operation: Any) -> list[TopAuthor]: + try: + return await operation + except Exception: + logger.exception("Dashboard top-author aggregation failed for %s.", source) + return [] + + +def _short_author_id(value: str) -> str: + return value.replace("https://openalex.org/", "").strip().upper() + + +async def _top_work_authors( + institution_id: str, + period: DashboardPeriod, +) -> list[TopAuthor]: + must = [works_v2_service._institutions_nested_query([institution_id])] + if publication_years := _dashboard_publication_years(period): + must.append({"terms": {"publication_year": publication_years}}) + + author_counts: dict[str, int] = defaultdict(int) + author_names: dict[str, str] = {} + async for hit in elasticsearch.scan( + index=str(ESIndex.OPENALEX_WORKS_WILDCARD), + query={"bool": {"must": must}}, + source=["id", "authorships.author.id", "authorships.author.display_name"], + page_size=1000, + cluster=ESCluster.NES, + ): + hit_author_ids: set[str] = set() + for authorship in hit.get("_source", {}).get("authorships", []): + author = authorship.get("author") or {} + author_id = author.get("id") + if not author_id: + continue + author_id = str(author_id) + hit_author_ids.add(author_id) + if author.get("display_name"): + author_names.setdefault(author_id, str(author["display_name"])) + for author_id in hit_author_ids: + author_counts[author_id] += 1 + + ranked_authors = sorted( + ( + { + "id": author_id, + "name": author_names.get(author_id, author_id), + "count": count, + } + for author_id, count in author_counts.items() + ), + key=lambda author: author["count"], + reverse=True, + ) + return [ + TopAuthor( + id=_short_author_id(author["id"]), + name=author["name"], + count=author["count"], + ) + for author in ranked_authors[:TOP_AUTHOR_LIMIT] + if author["count"] > 0 + ] + + +async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]: + try: + return await _institution_authors(institution_id) + except Exception: + logger.exception("Could not load authors for institution %s.", institution_id) + return [] + + +async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: + response = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + query={ + "nested": { + "path": "last_known_institutions", + "query": {"term": {"last_known_institutions.id": institution_id}}, + } + }, + source=["id", "display_name", "works_count", "counts_by_year"], + size=10000, + sort=[{"works_count": {"order": "desc", "missing": "_last"}}], + cluster=ESCluster.NES, + ) + return [ + { + "id": str(source["id"]), + "name": str(source["display_name"]), + "works_count": int(source.get("works_count", 0)), + "counts_by_year": source.get("counts_by_year", []) or [], + } + for hit in response.get("hits", {}).get("hits", []) + if (source := hit.get("_source", {})).get("id") and source.get("display_name") + ] + + +async def _top_project_authors( + authors: list[dict[str, Any]], + organization_name: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + period = _dashboard_period(from_year, to_year) + institution_ids = await _dfg_institution_ids_for_organization( + organization_name=organization_name, + ) + + logger.info( + "DFG institution IDs for %s: %s", + organization_name, + institution_ids, + ) + + if not institution_ids: + logger.warning( + "No DFG institution IDs found for organization %s.", + organization_name, + ) + return [] + + selected_person_ids = set( + await get_person_ids_by_institution_ids(institution_ids=institution_ids) + ) + + logger.info( + "Found %s DFG persons for organization %s.", + len(selected_person_ids), + organization_name, + ) + + if not selected_person_ids: + return [] + + project_ids_by_person: dict[int, set[str]] = {} + names: dict[int, str] = {} + + page = 0 + size = 10000 + processed = 0 + + while True: + project_hits, total = await _dfg_project_author_hits( + page=page, + size=size, + person_ids=selected_person_ids, + period=period, + ) + + if not project_hits: + break + + for project in project_hits: + project_id = _dfg_project_id(project) + if not project_id: + continue + + persons = project.get("persons", []) + if not isinstance(persons, list): + continue + + for person in persons: + if not isinstance(person, dict): + continue + + person_id = person.get("person_id") + full_name = person.get("full_name") + if person_id is None or not full_name: + continue + + try: + normalized_person_id = int(person_id) + except (TypeError, ValueError): + continue + + if normalized_person_id not in selected_person_ids: + continue + + project_ids_by_person.setdefault(normalized_person_id, set()).add( + project_id + ) + names[normalized_person_id] = str(full_name).strip() + + processed += len(project_hits) + if processed >= total: + break + + page += 1 + + 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( + ( + (person_id, project_ids) + for person_id, project_ids in project_ids_by_person.items() + if project_ids and names.get(person_id) + ), + key=lambda item: ( + -len(item[1]), + names[item[0]].casefold(), + ), + ) + + 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 = _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=(_short_author_id(matched_author["id"]) if matched_author else None), + name=matched_author["name"] if matched_author else dfg_name, + count=len(project_ids), + ) + ) + + logger.info( + "DFG top authors for %s: %s", + organization_name, + [ + { + "name": author.name, + "count": author.count, + "id": author.id, + } + for author in result + ], + ) + + 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, + page=0, + size=10000, + ) + return [ + institution.id for institution in page.elements if institution.id is not None + ] + + +async def _dfg_project_author_hits( + page: int, + size: int, + person_ids: set[int], + period: DashboardPeriod = (None, None), +) -> tuple[list[dict[str, Any]], int]: + person_query = { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": sorted(person_ids)}}, + }, + } + period_filter = _project_overlap_filter( + "funding_start", + "funding_end", + period, + missing_end_is_ongoing=True, + ) + query = ( + {"bool": {"filter": [person_query, period_filter]}} + if period_filter + else person_query + ) + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": size, + "from": page * size, + "_source": [ + "id", + "project_id", + "persons", + ], + "query": query, + "sort": [ + { + "id": { + "order": "asc", + "missing": "_last", + } + } + ], + }, + cluster=ESCluster.INSE, + track_total_hits=True, + ) + + hits_block = response.get("hits", {}) + total_value = hits_block.get("total", 0) + + if isinstance(total_value, dict): + total = int(total_value.get("value", 0)) + else: + total = int(total_value or 0) + + hits = [ + hit.get("_source", {}) + for hit in hits_block.get("hits", []) + if isinstance(hit.get("_source"), dict) + ] + + logger.info( + "Loaded %s of %s matching DFG projects on page %s.", + len(hits), + total, + page, + ) + + return hits, total + + +def _dfg_project_id(project: dict[str, Any]) -> str | None: + project_id = project.get("id") + if project_id is None: + project_id = project.get("project_id") + return str(project_id) if project_id is not None else None + + +async def _top_patent_authors( + institution_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + client = OrgPatentsSearchClient() + authors = await client.top_authors_by_institution( + institution_id=institution_id, + size=TOP_AUTHOR_LIMIT, + from_year=from_year, + to_year=to_year, + ) + return [ + TopAuthor( + id=_short_author_id(author["id"]), + name=author["name"], + count=author["count"], + ) + for author in authors + ] + + +async def _top_eu_project_publication_authors( + institution_id: str, + institution_authors: list[dict[str, Any]], + from_year: int | None = None, + to_year: int | None = None, +) -> 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_ids = await _get_eu_project_ids_from_projects_service( + institution_id, + from_year=from_year, + to_year=to_year, + ) + + if not project_ids: + return [] + + publication_response = await elasticsearch.search( + index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, + body={ + "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, + ) + + candidates = _openalex_work_authors_by_eu_projects( + works_response, + doi_project_ids, + institution_id, + institution_author_ids, + limit=None, + ) + counts = await asyncio.gather( + *( + _person_eu_project_count( + candidate.id, + from_year=from_year, + to_year=to_year, + ) + for candidate in candidates + if candidate.id + ) + ) + ranked = [ + TopAuthor(id=candidate.id, name=candidate.name, count=count) + for candidate, count in zip(candidates, counts, strict=True) + ] + ranked.sort(key=lambda author: (-author.count, author.name, author.id or "")) + return ranked[:TOP_AUTHOR_LIMIT] + + +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], + limit: int | None = TOP_AUTHOR_LIMIT, +) -> 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]), + ) + + authors = [ + TopAuthor( + id=_short_author_id(author_id), + name=author_names[author_id], + count=len(project_ids), + ) + for author_id, project_ids in ranked_authors + ] + return authors[:limit] if limit is not None else authors + + +async def _person_eu_project_count( + author_id: str, + from_year: int | None = None, + to_year: int | None = None, +) -> int: + """Returns the same filtered EU project total as the person projects tab.""" + period = _dashboard_period(from_year, to_year) + projects = await projects_service.search_eu_cordis_projects( + page=0, + size=1, + project_types=None, + raw_oa_institution_id=None, + institutions_search_client=None, + author_id=_short_author_id(author_id), + author_ids=None, + organization_ids=None, + organization_names=None, + keywords=None, + topic_ids=None, + filter_topic_ids=None, + title=None, + funding_start_years=None, + funding_end_years=None, + active_from_year=period[0], + active_to_year=period[1], + countries=None, + framework_programmes=None, + funding_schemes=None, + statuses=None, + sort_by="title", + sort_direction="asc", + fuzzy=False, + skip_enrichment=True, + ) + return projects.total + + +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]], + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + if not authors: + return [] + + period = _dashboard_period(from_year, to_year) + author_names = [author["name"] for author in authors] + filters: list[dict[str, Any]] = [{"terms": {"authors.keyword": author_names}}] + if period != (None, None): + date_range: dict[str, int] = {} + if period[0] is not None: + date_range["gte"] = period[0] + if period[1] is not None: + date_range["lte"] = period[1] + news_ids = [ + str(hit["_id"]) + async for hit in elasticsearch.scan( + index=str(ESIndex.AKTUELLES), + query={"range": {"date_year": date_range}}, + source=False, + page_size=1000, + cluster=ESCluster.INSE, + ) + if hit.get("_id") + ] + if not news_ids: + return [] + filters.append({"terms": {"news_id.keyword": news_ids}}) + + response = await elasticsearch.search( + index="aktuell_postproc", + body={ + "size": 0, + "query": ( + filters[0] if len(filters) == 1 else {"bool": {"filter": filters}} + ), + "aggs": { + "authors": { + "terms": { + "field": "authors.keyword", + "size": 10000, + "order": [ + {"_count": "desc"}, + {"_key": "asc"}, + ], + } + } + }, + }, + cluster=ESCluster.INSE, + ) + buckets = response.get("aggregations", {}).get("authors", {}).get("buckets", []) + institution_authors = {author["name"].casefold(): author for author in authors} + + return [ + TopAuthor( + id=_short_author_id( + institution_authors[str(bucket["key"]).casefold()]["id"] + ), + name=institution_authors[str(bucket["key"]).casefold()]["name"], + count=int(bucket.get("doc_count", 0)), + ) + for bucket in buckets + if str(bucket.get("key", "")).casefold() in institution_authors + ][:TOP_AUTHOR_LIMIT] diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 894da8a3..629cb31d 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -1,6 +1,6 @@ import { HttpClient } from '@angular/common/http'; import { Injectable, inject } from '@angular/core'; -import { Observable } from 'rxjs'; +import { Observable, catchError, forkJoin, map, of } from 'rxjs'; import { Configuration } from '../../api'; import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models'; @@ -95,6 +95,11 @@ export interface TopAuthorStatistics { news: TopAuthor[]; } +export interface TopAuthorAnalysis { + institution_id: string; + authors: TopAuthor[]; +} + export interface TopicWordCloudWord { id: string; name: string; @@ -228,9 +233,38 @@ export class DashboardStatisticsService { getTopAuthors( period: DashboardPeriodBounds = {}, ): Observable { - return this.httpClient.get( - `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`, - { params: this.periodParams(period) }, + const analysis = (source: string) => + this.httpClient + .get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors/${source}`, + { params: this.periodParams(period) }, + ) + .pipe(catchError(() => of(null))); + + return forkJoin({ + works: analysis('works'), + projects: analysis('projects'), + euProjects: analysis('eu-projects'), + patents: analysis('patents'), + news: analysis('news'), + }).pipe( + map((responses) => { + const successfulResponse = Object.values(responses).find( + (response) => response !== null, + ); + if (!successfulResponse) { + throw new Error('All top-author analyses failed.'); + } + + return { + institution_id: successfulResponse.institution_id, + works: responses.works?.authors ?? [], + projects: responses.projects?.authors ?? [], + eu_projects: responses.euProjects?.authors ?? [], + patents: responses.patents?.authors ?? [], + news: responses.news?.authors ?? [], + }; + }), ); }