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 eae2251a..bbc047db 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -54,6 +54,8 @@ class DfgProjectTopic(BaseModel): field: str | None = None domain: str | None = None project_count: int + field_project_count: int + subfield_project_count: int keywords: list[DfgProjectKeyword] @@ -65,6 +67,22 @@ class DfgProjectTopics(BaseModel): topics: list[DfgProjectTopic] +class EuProjectTopics(BaseModel): + institution_id: str + organization_name: str + project_count: int + matched_project_count: int + topics: list[DfgProjectTopic] + + +class BundProjectTopics(BaseModel): + institution_id: str + organization_name: str + project_count: int + matched_project_count: int + topics: list[DfgProjectTopic] + + class TopAuthor(BaseModel): id: str | None = None name: str @@ -80,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 bd5ad49b..a0d0de82 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -10,32 +10,48 @@ from inse.tags import Tags from .model import ( BmbfProjectStatusStatistics, + BundProjectTopics, DashboardStatistics, DashboardStatisticValue, DfgProjectStatusStatistics, DfgProjectTopics, + EuProjectTopics, EuProjectStatusStatistics, TopAuthorStatistics, + TopAuthorAnalysis, TopicHeatmap, TopicWordCloud, ) from .service import ( - get_dashboard_bmbf_project_statuses, - get_dashboard_bmbf_projects, - get_dashboard_dfg_project_statuses, - get_dashboard_dfg_projects, - get_dashboard_dfg_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]) @@ -256,6 +272,46 @@ async def dashboard_dfg_project_topics( ) +@router.get( + "/projects/eu/topics", + operation_id="getDashboardEuProjectTopics", + response_model=EuProjectTopics, +) +async def dashboard_eu_project_topics( + 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, +) -> EuProjectTopics: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_eu_topics( + organization.openalex_institution_id, + organization.name, + from_year=from_year, + to_year=to_year, + ) + + +@router.get( + "/projects/bund/topics", + operation_id="getDashboardBundProjectTopics", + response_model=BundProjectTopics, +) +async def dashboard_bund_project_topics( + 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, +) -> BundProjectTopics: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_bund_topics( + organization.openalex_institution_id, + organization.name, + from_year=from_year, + to_year=to_year, + ) + + @router.get( "/top-authors", operation_id="getDashboardTopAuthors", @@ -281,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 ec065b45..873c55f0 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,48 +1,29 @@ import asyncio 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, DashboardStatistics, - DfgProjectKeyword, DashboardStatisticValue, - DfgProjectStatusStatistics, - DfgProjectTopic, - DfgProjectTopics, - EuProjectStatusStatistics, - TopAuthor, - TopAuthorStatistics, TopicHeatmap, TopicHeatmapField, TopicHeatmapSubfield, @@ -51,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] = {} @@ -149,46 +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 _date_period(period: DashboardPeriod, date_format: str) -> DashboardPeriod: - from_year, to_year = period - if date_format == "iso": - return ( - f"{from_year}-01-01" if from_year is not None else None, - f"{to_year}-12-31" if to_year is not None else None, - ) - return ( - f"01.01.{from_year}" if from_year is not None else None, - f"31.12.{to_year}" if to_year is not None else None, - ) - - def get_dashboard_organization( session: Session, access_token: AccessToken, @@ -212,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, @@ -241,25 +111,22 @@ async def get_dashboard_publications( ) -> DashboardStatisticValue: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - institution = await institutions_v2_service.get_institution_by_id_or_raise( - raw_oa_institution_id=_raw_institution_id(normalized_id), - source=["id", "works_count", "counts_by_year"], + publication_years: list[int] = [] + if period != (None, None): + first_year = period[0] if period[0] is not None else 1900 + last_year = period[1] if period[1] is not None else 2100 + publication_years = list(range(first_year, last_year + 1)) + + works = await works_v2_service.get_works( + page=0, + size=1, + institution_ids=[normalized_id], + publication_years=publication_years, ) - if period == (None, None): - value = int(institution.works_count or 0) - else: - value = sum( - int(entry.works_count or 0) - for entry in institution.counts_by_year or [] - if ( - (period[0] is None or int(entry.year or 0) >= period[0]) - and (period[1] is None or int(entry.year or 0) <= period[1]) - ) - ) return DashboardStatisticValue( institution_id=normalized_id, organization_name=organization_name, - value=value, + value=works.total, ) @@ -319,914 +186,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=( - [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 - ), - 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_overlap_filter( - "startDate", - "endDate", - _date_period(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=( - [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 - ), - 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_overlap_filter( - "funding_start", - "funding_end", - _date_period(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=( - [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=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_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_overlap_filter( - "projects.funding_start", - "projects.funding_end", - period, - missing_end_is_ongoing=True, - ): - 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) - - topic_list = [ - DfgProjectTopic( - id=topic["id"], - name=topic["name"], - subfield=topic["subfield"], - field=topic["field"], - domain=topic["domain"], - project_count=len(topic["project_ids"]), - 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_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 = _top_work_authors(authors, 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), - ) - - 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, @@ -1445,39 +404,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)) @@ -1505,8 +434,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") } @@ -1582,901 +510,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() - - -def _top_work_authors( - authors: list[dict[str, Any]], - period: DashboardPeriod, -) -> list[TopAuthor]: - if period != (None, None): - ranked_authors = sorted( - ( - { - **author, - "selected_works_count": _works_count_in_period(author, period), - } - for author in authors - ), - key=lambda author: author["selected_works_count"], - reverse=True, - ) - else: - ranked_authors = [ - {**author, "selected_works_count": author["works_count"]} - for author in authors - ] - - return [ - TopAuthor( - id=_short_author_id(author["id"]), - name=author["name"], - count=author["selected_works_count"], - ) - for author in ranked_authors[:TOP_AUTHOR_LIMIT] - if author["selected_works_count"] > 0 - ] - - -def _works_count_in_period(author: dict[str, Any], period: DashboardPeriod) -> int: - from_year, to_year = period - return sum( - int(item.get("works_count", 0) or 0) - for item in author.get("counts_by_year", []) - if ( - (from_year is None or int(item.get("year", 0) or 0) >= from_year) - and (to_year is None or int(item.get("year", 0) or 0) <= to_year) - ) - ) - - -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=( - [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 - ), - 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: - """Uses the same author-only EU project search as the person detail page.""" - 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=( - [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 - ), - 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]]) -> list[TopAuthor]: - if not authors: - return [] - - author_names = [author["name"] for author in authors] - response = await elasticsearch.search( - index="aktuell_postproc", - body={ - "size": 0, - "query": {"terms": {"authors.keyword": author_names}}, - "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 2de2ca6e..4445262a 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,5 +1,6 @@ +import asyncio from datetime import datetime -from types import SimpleNamespace +import hashlib from unittest.mock import AsyncMock, patch import pytest @@ -9,45 +10,177 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( - _openalex_work_authors_by_eu_projects, - _get_dfg_project_ids_from_projects_service, - _reconcile_project_status_counts, - get_dashboard_bmbf_projects, - get_dashboard_dfg_projects, - get_dashboard_eu_projects, 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.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner +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.model import TopAuthor +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 ( + _count_eu_projects_for_candidates, + _openalex_work_authors_by_eu_projects, + _top_news_authors, + get_top_authors, +) +from inse.exceptions import ElasticsearchException +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 from inse.projects.model import ( BundProjectPage, + BundProjectSummary, DfgProjectPage, DfgProjectSummary, EuCordisProjectSearchPage, EuCordisProjectSummary, EuCordisProjectType, ) +from inse.works.v2 import service as works_v2_service +from inse.works.v2.model import WorkPageV2 ORG_INSTITUTION_ID = "https://openalex.org/I123" +@pytest.mark.anyio +async def test_eu_project_counts_are_bounded_retried_and_isolated(): + attempts: dict[str, int] = {} + active_requests = 0 + maximum_active_requests = 0 + + async def count_projects(author_id: str, **kwargs) -> int: + nonlocal active_requests, maximum_active_requests + attempts[author_id] = attempts.get(author_id, 0) + 1 + active_requests += 1 + maximum_active_requests = max(maximum_active_requests, active_requests) + await asyncio.sleep(0.001) + active_requests -= 1 + if author_id == "A0" and attempts[author_id] < 3: + raise ElasticsearchException("temporary") + if author_id == "A1": + raise ElasticsearchException("unavailable") + return int(author_id.removeprefix("A")) + + candidates = [ + TopAuthor(id=f"A{index}", name=f"Author {index}", count=0) for index in range(8) + ] + with ( + patch( + "inse.dashboard.top_authors_service._person_eu_project_count", + new=count_projects, + ), + patch( + "inse.dashboard.top_authors_service.EU_PROJECT_COUNT_RETRY_DELAY_SECONDS", + 0, + ), + ): + result = await _count_eu_projects_for_candidates(candidates) + + assert maximum_active_requests <= 5 + assert attempts["A0"] == 3 + assert attempts["A1"] == 3 + assert [author.id for author in result] == [ + "A0", + "A2", + "A3", + "A4", + "A5", + "A6", + "A7", + ] + + @pytest.fixture def anyio_backend(): return "asyncio" 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(): + assert _project_boundary_year_filter( + "startDate", "endDate", (2022, 2026), "iso" + ) == { + "bool": { + "filter": [ + {"range": {"startDate": {"lte": "2026-12-31"}}}, + {"range": {"endDate": {"gte": "2022-01-01"}}}, + ] + } + } + assert _project_boundary_year_filter( + "projects.funding_start", + "projects.funding_end", + (2022, 2026), + "year", + ) == { + "bool": { + "filter": [ + {"range": {"projects.funding_start": {"lte": 2026}}}, + {"range": {"projects.funding_end": {"gte": 2022}}}, + ] + } + } + + +@pytest.mark.anyio +async def test_top_news_authors_applies_dashboard_period(): + response = { + "aggregations": { + "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}}} + yield {"_id": "N1"} + yield {"_id": "N2"} + + 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"}], + from_year=2020, + to_year=2023, + ) + + assert result[0].count == 3 + assert mocked_search.await_args.kwargs["body"]["query"] == { + "bool": { + "filter": [ + {"terms": {"authors.keyword": ["Ada Example"]}}, + {"terms": {"news_id.keyword": ["N1", "N2"]}}, + ] + } + } @pytest.mark.anyio @@ -68,7 +201,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( @@ -86,13 +219,168 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service(): assert first_call.kwargs["funding_end_years"][0] == "2020" +@pytest.mark.anyio +async def test_eu_topics_scan_all_programme_indices_and_deduplicate_projects(): + scanned_indices: list[str] = [] + + async def scan(**kwargs): + scanned_indices.append(kwargs["index"]) + if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING): + yield { + "_source": { + "project_id": "P1", + "keyword": "AI", + "topic_matches": [ + { + "topic_id": "T1", + "topic_display_name": "Artificial Intelligence", + "field": "Computer Science", + "subfield": "AI", + "domain": "Physical Sciences", + } + ], + } + } + yield { + "_source": { + "project_id": "P1", + "keyword": "Robotics", + "topic_matches": [ + { + "topic_id": "T2", + "topic_display_name": "Robotics", + "field": "Computer Science", + "subfield": "Robotics", + "domain": "Physical Sciences", + } + ], + } + } + if kwargs["index"] == str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS): + yield { + "_source": { + "project_id": "P2", + "keyword": "AI", + "topic_matches": [ + { + "topic_id": "T1", + "topic_display_name": "Artificial Intelligence", + "field": "Computer Science", + "subfield": "AI", + "domain": "Physical Sciences", + } + ], + } + } + + 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", + from_year=2022, + to_year=2026, + ) + + assert scanned_indices == [ + str(ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING), + str(ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS), + str(ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS), + ] + assert result.project_count == 3 + assert result.matched_project_count == 2 + assert result.topics[0].project_count == 2 + assert result.topics[0].keywords[0].project_count == 2 + assert {topic.field_project_count for topic in result.topics} == {2} + assert {topic.name: topic.subfield_project_count for topic in result.topics} == { + "Artificial Intelligence": 2, + "Robotics": 1, + } + + +@pytest.mark.anyio +async def test_bund_topics_use_mapping_index_and_unique_hierarchy_counts(): + project_page = BundProjectPage( + elements=[ + BundProjectSummary(funding_code="B1"), + BundProjectSummary(funding_code="B2"), + ], + total=2, + page=0, + size=1000, + ) + + async def scan(**kwargs): + assert kwargs["index"] == str(ESIndex.PROJECTS_BUND_TOPICS) + mapping_ids = { + funding_code: hashlib.sha256(funding_code.encode("utf-8")).hexdigest() + for funding_code in ("B1", "B2") + } + assert kwargs["query"] == { + "terms": {"project_id": sorted(mapping_ids.values())} + } + for project_id, topic_id, topic_name, subfield in ( + (mapping_ids["B1"], "T1", "Artificial Intelligence", "AI"), + (mapping_ids["B1"], "T2", "Robotics", "Robotics"), + (mapping_ids["B2"], "T1", "Artificial Intelligence", "AI"), + ): + yield { + "_source": { + "project_id": project_id, + "keyword": topic_name, + "topic_matches": [ + { + "topic_id": topic_id, + "topic_display_name": topic_name, + "field": "Computer Science", + "subfield": subfield, + "domain": "Physical Sciences", + } + ], + } + } + + 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, + "Example Org", + from_year=2022, + to_year=2026, + ) + + project_call = mocked_projects.await_args + assert project_call.kwargs["active_from_year"] == 2022 + assert project_call.kwargs["active_to_year"] == 2026 + assert result.project_count == 2 + assert result.matched_project_count == 2 + assert {topic.field_project_count for topic in result.topics} == {2} + assert {topic.name: topic.subfield_project_count for topic in result.topics} == { + "Artificial Intelligence": 2, + "Robotics": 1, + } + + @pytest.mark.anyio async def test_dashboard_statistics_counts_organization_data_and_all_projects(): - async def search(**kwargs): - index = kwargs["index"] + async def search(*args, **kwargs): + index = kwargs.get("index", args[0] if args else None) if index == config.settings.openalex_works_search_index: - return {"hits": {"total": {"value": 120}}} + return {"hits": {"total": {"value": 120}, "hits": []}} if index == ESIndex.OPENALEX_AUTHORS: return {"hits": {"total": {"value": 35}}} @@ -106,9 +394,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": { @@ -128,48 +414,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, @@ -187,22 +484,18 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects(): "bmbf_projects": 5, } -@pytest.mark.anyio -async def test_dashboard_publications_uses_institutions_v2_counts(): - institution = Institution( - id=ORG_INSTITUTION_ID, - works_count=250, - counts_by_year=[ - AuthorCountsByYearInner(year=2021, works_count=10), - AuthorCountsByYearInner(year=2022, works_count=12), - AuthorCountsByYearInner(year=2023, works_count=14), - ], - ) +@pytest.mark.anyio +async def test_dashboard_publications_uses_institution_publications_logic(): with patch( - "inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise", - new=AsyncMock(return_value=institution), - ) as mocked_get_institution: + "inse.dashboard.service.works_v2_service.get_works", + new=AsyncMock( + side_effect=[ + WorkPageV2(elements=[], total=250, page=0, size=1), + WorkPageV2(elements=[], total=22, page=0, size=1), + ] + ), + ) as mocked_get_works: all_time = await get_dashboard_publications( ORG_INSTITUTION_ID, "Example Org", @@ -216,9 +509,17 @@ async def test_dashboard_publications_uses_institutions_v2_counts(): assert all_time.value == 250 assert selected_period.value == 22 - assert mocked_get_institution.await_args_list[0].kwargs == { - "raw_oa_institution_id": "I123", - "source": ["id", "works_count", "counts_by_year"], + assert mocked_get_works.await_args_list[0].kwargs == { + "page": 0, + "size": 1, + "institution_ids": [ORG_INSTITUTION_ID], + "publication_years": [], + } + assert mocked_get_works.await_args_list[1].kwargs == { + "page": 0, + "size": 1, + "institution_ids": [ORG_INSTITUTION_ID], + "publication_years": [2021, 2022], } @@ -254,7 +555,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( @@ -268,8 +569,11 @@ async def test_dashboard_dfg_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"][-1] == "2022" - assert call.kwargs["funding_end_years"][0] == "2020" + assert call.kwargs["funding_start_years"] is None + assert call.kwargs["funding_end_years"] is None + assert call.kwargs["active_from_year"] == 2020 + assert call.kwargs["active_to_year"] == 2022 + assert call.kwargs["skip_enrichment"] is True assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 @@ -279,7 +583,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( @@ -293,20 +597,20 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"][-1] == "2020" - assert call.kwargs["funding_end_years"][0] == "2018" + assert call.kwargs["funding_start_years"] is None + assert call.kwargs["funding_end_years"] is None + assert call.kwargs["active_from_year"] == 2018 + assert call.kwargs["active_to_year"] == 2020 assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 @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( @@ -320,8 +624,10 @@ async def test_dashboard_eu_projects_uses_projects_service_total(): mocked_get_projects.assert_awaited_once() call = mocked_get_projects.await_args assert call.kwargs["raw_oa_institution_id"] == "I123" - assert call.kwargs["funding_start_years"][-1] == "2021" - assert call.kwargs["funding_end_years"][0] == "2019" + assert call.kwargs["funding_start_years"] is None + assert call.kwargs["funding_end_years"] is None + assert call.kwargs["active_from_year"] == 2019 + assert call.kwargs["active_to_year"] == 2021 assert call.kwargs["project_types"] == list(EuCordisProjectType) assert call.kwargs["page"] == 0 assert call.kwargs["size"] == 1 @@ -357,11 +663,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: @@ -387,9 +689,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}]} } } @@ -438,13 +738,58 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): return {"aggregations": {"people": {"buckets": []}}} + scan_calls = [] + + async def scan(**kwargs): + scan_calls.append(kwargs) + yield { + "_id": "W1", + "_source": { + "id": "https://openalex.org/W1", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + }, + }, + { + "author": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + }, + }, + ], + }, + } + yield { + "_id": "W2", + "_source": { + "id": "https://openalex.org/W2", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + }, + } + ], + }, + } + async def eu_projects(**kwargs): 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, @@ -457,21 +802,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.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( @@ -482,7 +836,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): assert result.works[0].model_dump() == { "id": "A1", "name": "Ada Example", - "count": 42, + "count": 2, } assert result.patents[0].model_dump() == { "id": "A1", @@ -502,8 +856,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 == [] @@ -523,18 +876,43 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects(): assert eu_body["_source"] == ["projectID", "qaProcessedDoi"] assert "aggs" not in eu_body - works_calls = [ + assert len(scan_calls) == 1 + assert scan_calls[0]["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD) + assert scan_calls[0]["query"]["bool"]["must"] == [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [ORG_INSTITUTION_ID] + } + }, + } + }, + } + } + ] + assert scan_calls[0]["source"] == [ + "id", + "authorships.author.id", + "authorships.author.display_name", + ] + + eu_work_calls = [ call for call in mocked_search.await_args_list if call.kwargs["index"] == "openalex-works" ] - assert len(works_calls) == 1 - works_body = works_calls[0].kwargs["body"] - assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [ + assert len(eu_work_calls) == 1 + eu_works_body = eu_work_calls[0].kwargs["body"] + assert eu_works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [ "https://doi.org/10.1234/p1", "https://doi.org/10.1234/p2", ] - assert works_body["_source"] == [ + assert eu_works_body["_source"] == [ "doi", "authorships.author.id", "authorships.author.display_name", @@ -628,9 +1006,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": [ @@ -751,44 +1127,60 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i return {"aggregations": {"authors": {"buckets": []}}} async def eu_projects(**kwargs): + assert kwargs["funding_start_years"] is None + assert kwargs["funding_end_years"] is None if kwargs.get("raw_oa_institution_id"): + assert kwargs["active_from_year"] is None + assert kwargs["active_to_year"] is None 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, size=1000, ) + assert kwargs["active_from_year"] == 2020 + assert kwargs["active_to_year"] == 2022 return EuCordisProjectSearchPage( elements=[], - total={"A1": 4, "A2": 1}[kwargs["author_id"]], + total={"A1": 4, "A2": 0}[kwargs["author_id"]], page=0, 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, "Example Org", + from_year=2020, + to_year=2022, ) assert [author.model_dump() for author in result.eu_projects] == [ {"id": "A1", "name": "Ada Example", "count": 4}, - {"id": "A2", "name": "Grace Example", "count": 1}, ] @@ -813,24 +1205,39 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): raise RuntimeError("projects unavailable") - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.get_eu_organization_project_contributions", - new=AsyncMock( - return_value=SimpleNamespace( - elements=[ - SimpleNamespace(project_id="P1"), + async def scan(**kwargs): + yield { + "_id": "W1", + "_source": { + "id": "https://openalex.org/W1", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + } + } ], - ) + }, + } + + 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, @@ -879,18 +1286,56 @@ async def test_top_authors_can_rank_works_by_last_five_years(): } return {"aggregations": {"people": {"buckets": []}}} - with patch( - "inse.dashboard.service.elasticsearch.search", - new=AsyncMock(side_effect=search), - ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), - ), patch( - "inse.dashboard.service.get_eu_organization_project_contributions", - new=AsyncMock(return_value=SimpleNamespace(elements=[])), - ), patch( - "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", - new=AsyncMock(return_value=[]), + scan_calls = [] + + async def scan(**kwargs): + scan_calls.append(kwargs) + for index in range(16): + yield { + "_id": f"W-grace-{index}", + "_source": { + "authorships": [ + { + "author": { + "id": "https://openalex.org/A2", + "display_name": "Grace Example", + } + } + ] + }, + } + for index in range(2): + yield { + "_id": f"W-ada-{index}", + "_source": { + "authorships": [ + { + "author": { + "id": "https://openalex.org/A1", + "display_name": "Ada Example", + } + } + ] + }, + } + + 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, @@ -909,6 +1354,16 @@ async def test_top_authors_can_rank_works_by_last_five_years(): "count": 2, } + work_scan_calls = [ + call + for call in scan_calls + if call["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD) + ] + assert len(work_scan_calls) == 1 + assert work_scan_calls[0]["query"]["bool"]["must"][1] == { + "terms": {"publication_year": list(range(current_year - 4, current_year + 1))} + } + @pytest.mark.anyio async def test_topic_heatmap_maps_field_year_counts_and_shares(): @@ -1000,7 +1455,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( @@ -1054,17 +1509,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 @@ -1080,7 +1532,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( @@ -1116,7 +1568,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..72a8c1e2 --- /dev/null +++ b/service/src/main/inse/dashboard/top_authors_service.py @@ -0,0 +1,1138 @@ +import asyncio +import logging +import re +from collections import defaultdict +from datetime import datetime +from typing import Any, Literal + +from fastapi import HTTPException + +from inse import config +from inse.exceptions import ElasticsearchException, UpstreamAPIException +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 +EU_PROJECT_COUNT_CONCURRENCY = 5 +EU_PROJECT_COUNT_MAX_ATTEMPTS = 3 +EU_PROJECT_COUNT_RETRY_DELAY_SECONDS = 0.5 +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 [] + + # Candidate discovery is deliberately all-time. The selected period is + # applied to each person's authoritative project count below. Otherwise a + # person can disappear merely because their recent projects have no linked + # CORDIS publication/DOI, despite having projects in the selected period. + project_ids = await _get_eu_project_ids_from_projects_service(institution_id) + + 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, + ) + ranked = await _count_eu_projects_for_candidates( + candidates, + from_year=from_year, + to_year=to_year, + ) + ranked = [author for author in ranked if author.count > 0] + ranked.sort(key=lambda author: (-author.count, author.name, author.id or "")) + return ranked[:TOP_AUTHOR_LIMIT] + + +async def _count_eu_projects_for_candidates( + candidates: list[TopAuthor], + from_year: int | None = None, + to_year: int | None = None, +) -> list[TopAuthor]: + semaphore = asyncio.Semaphore(EU_PROJECT_COUNT_CONCURRENCY) + + async def load(candidate: TopAuthor) -> TopAuthor | None: + if not candidate.id: + return None + + for attempt in range(1, EU_PROJECT_COUNT_MAX_ATTEMPTS + 1): + try: + async with semaphore: + count = await _person_eu_project_count( + candidate.id, + from_year=from_year, + to_year=to_year, + ) + return TopAuthor(id=candidate.id, name=candidate.name, count=count) + except (ElasticsearchException, UpstreamAPIException, HTTPException) as exc: + is_retryable = ( + not isinstance(exc, (HTTPException, UpstreamAPIException)) + or exc.status_code >= 500 + ) + if not is_retryable or attempt == EU_PROJECT_COUNT_MAX_ATTEMPTS: + logger.warning( + "Could not load EU project count for author %s after %s attempt(s).", + candidate.id, + attempt, + exc_info=True, + ) + return None + await asyncio.sleep(EU_PROJECT_COUNT_RETRY_DELAY_SECONDS * attempt) + + return None + + results = await asyncio.gather(*(load(candidate) for candidate in candidates)) + return [result for result in results if result is not None] + + +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/projects/eu_cordis_projects_client.py b/service/src/main/inse/projects/eu_cordis_projects_client.py index 731cd699..be4fd23d 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_client.py @@ -741,6 +741,8 @@ async def _build_eu_cordis_search_query( title: str | None = None, funding_start_years: list[str] | None = None, funding_end_years: list[str] | None = None, + active_from_year: int | None = None, + active_to_year: int | None = None, countries: list[str] | None = None, framework_programmes: list[str] | None = None, funding_schemes: list[str] | None = None, @@ -876,6 +878,18 @@ async def _build_eu_cordis_search_query( if funding_end_years: must_clauses.append(_eu_year_filters("endDate", funding_end_years)) + # Period-overlap filter: a project was active in the selected interval when + # it started no later than the interval end and ended no earlier than the + # interval start. This is intentionally separate from exact-year filters. + if active_to_year is not None: + must_clauses.append( + {"range": {"startDate": {"lte": f"{active_to_year}-12-31"}}} + ) + if active_from_year is not None: + must_clauses.append( + {"range": {"endDate": {"gte": f"{active_from_year}-01-01"}}} + ) + # === Project core filters === if framework_programmes: must_clauses.append({"terms": {"frameworkProgramme": framework_programmes}}) @@ -937,6 +951,8 @@ async def search_eu_cordis_projects( title: str | None = None, funding_start_years: list[str] | None = None, funding_end_years: list[str] | None = None, + active_from_year: int | None = None, + active_to_year: int | None = None, countries: list[str] | None = None, framework_programmes: list[str] | None = None, funding_schemes: list[str] | None = None, @@ -965,6 +981,8 @@ async def search_eu_cordis_projects( title=title, funding_start_years=funding_start_years, funding_end_years=funding_end_years, + active_from_year=active_from_year, + active_to_year=active_to_year, countries=countries, framework_programmes=framework_programmes, funding_schemes=funding_schemes, diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 0c8d126d..924e1e41 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -369,6 +369,8 @@ async def search_dfg_projects( sort_direction: str = "asc", fuzzy: bool = False, skip_enrichment: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> DfgProjectPage: """Searches for DFG projects based on the provided filtering and sorting criteria. @@ -489,6 +491,11 @@ async def search_dfg_projects( if funding_end_years: must_clauses.append({"terms": {"funding_end": funding_end_years}}) + if active_to_year is not None: + must_clauses.append({"range": {"funding_start": {"lte": str(active_to_year)}}}) + if active_from_year is not None: + must_clauses.append({"range": {"funding_end": {"gte": str(active_from_year)}}}) + if names: name_must_clauses = [] for full_name in names: @@ -600,7 +607,6 @@ async def search_dfg_projects( body["sort"] = [sort_config] # print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") # === Execute Search === - print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}") response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, body=body, @@ -612,6 +618,9 @@ async def search_dfg_projects( if skip_enrichment: return _complete_response_to_dfg_project_page(response, page, size) + if not hits: + return _complete_response_to_dfg_project_page(response, page, size) + project_ids = [hit["_source"]["id"] for hit in hits] topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids) @@ -858,6 +867,8 @@ async def search_bund_projects_with_filters( sort_direction: str = "asc", fuzzy: bool = False, skip_topic_enrichment: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> BundProjectPage: """ Main search function for BUND projects, analogous to the DFG search. @@ -999,6 +1010,15 @@ async def search_bund_projects_with_filters( if funding_end_years: must_clauses.append(_bund_year_filters("funding_end", funding_end_years)) + if active_to_year is not None: + must_clauses.append( + {"range": {"funding_start": {"lte": f"31.12.{active_to_year}"}}} + ) + if active_from_year is not None: + must_clauses.append( + {"range": {"funding_end": {"gte": f"01.01.{active_from_year}"}}} + ) + body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}} # === Sorting === sort_by = sort_by.strip().lower() diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index f1abccf8..eabd2228 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -188,6 +188,8 @@ async def get_dfg_projects( sort_direction: str = "asc", fuzzy: bool = False, skip_enrichment: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> DfgProjectPage: logger.debug( "Fetching DFG projects for author_id=%s, author_filter_ids=%s, " @@ -284,6 +286,8 @@ async def get_dfg_projects( sort_direction=sort_direction, fuzzy=fuzzy, skip_enrichment=skip_enrichment, + active_from_year=active_from_year, + active_to_year=active_to_year, ) async def get_institution_cordis_eu_projects_funding_over_time( @@ -459,6 +463,8 @@ async def search_bund_projects_with_filters( sort_by: str = "title", sort_direction: str = "asc", fuzzy: bool = False, + active_from_year: int | None = None, + active_to_year: int | None = None, ) -> BundProjectPage: institution_aliases = [] if raw_oa_institution_id: @@ -494,7 +500,9 @@ async def search_bund_projects_with_filters( size=size, sort_by=sort_by, sort_direction=sort_direction, - fuzzy=fuzzy + fuzzy=fuzzy, + active_from_year=active_from_year, + active_to_year=active_to_year, ) def _calculate_funding_over_time( @@ -656,6 +664,8 @@ async def search_eu_cordis_projects( title: str | None = None, funding_start_years: list[str] | None = None, funding_end_years: list[str] | None = None, + active_from_year: int | None = None, + active_to_year: int | None = None, countries: list[str] | None = None, framework_programmes: list[str] | None = None, funding_schemes: list[str] | None = None, @@ -716,6 +726,8 @@ async def search_eu_cordis_projects( title=title, funding_start_years=funding_start_years, funding_end_years=funding_end_years, + active_from_year=active_from_year, + active_to_year=active_to_year, countries=countries, framework_programmes=framework_programmes, funding_schemes=funding_schemes, diff --git a/service/src/main/inse/projects/test_eu_cordis_search_client.py b/service/src/main/inse/projects/test_eu_cordis_search_client.py index 342f383b..f6e7d5c3 100644 --- a/service/src/main/inse/projects/test_eu_cordis_search_client.py +++ b/service/src/main/inse/projects/test_eu_cordis_search_client.py @@ -2,6 +2,21 @@ import pytest from inse.projects import eu_cordis_projects_client as eu_cordis_search_client +@pytest.mark.anyio +async def test_active_period_filter_matches_projects_overlapping_interval(): + query, _, _ = await eu_cordis_search_client._build_eu_cordis_search_query( + active_from_year=2022, + active_to_year=2026, + ) + + assert {"range": {"startDate": {"lte": "2026-12-31"}}} in query["bool"][ + "must" + ] + assert {"range": {"endDate": {"gte": "2022-01-01"}}} in query["bool"][ + "must" + ] + + @pytest.mark.anyio async def test_search_eu_cordis_projects_by_title(): """Test searching EU CORDIS projects by title.""" @@ -362,4 +377,4 @@ async def test_search_eu_cordis_projects_with_fuzzy_topic_search(): # Note: This may return 0 results if the topic ID doesn't exist # The important thing is that it doesn't crash assert isinstance(res.total, int) - assert isinstance(res.elements, list) \ No newline at end of file + assert isinstance(res.elements, list) diff --git a/service/src/main/inse/projects/test_projects_dfg.py b/service/src/main/inse/projects/test_projects_dfg.py index f9eb82b9..bc331c62 100644 --- a/service/src/main/inse/projects/test_projects_dfg.py +++ b/service/src/main/inse/projects/test_projects_dfg.py @@ -1,4 +1,7 @@ +from unittest.mock import AsyncMock, patch + import pytest + from inse.projects import projects_search_client @@ -20,6 +23,33 @@ async def test_search_dfg_projects(): for name in element.names ) + +@pytest.mark.anyio +async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash(): + response = { + "hits": { + "total": {"value": 0}, + "hits": [], + } + } + with patch( + "inse.projects.projects_search_client.elasticsearch.search", + new=AsyncMock(return_value=response), + ) as mocked_search: + result = await projects_search_client.search_dfg_projects( + page=0, + size=1, + funding_start_years=["2022"], + funding_end_years=["2026"], + ) + + assert result.total == 0 + assert result.elements == [] + query = mocked_search.await_args.kwargs["body"]["query"] + assert {"terms": {"funding_start": ["2022"]}} in query["bool"]["must"] + assert {"terms": {"funding_end": ["2026"]}} in query["bool"]["must"] + + @pytest.mark.anyio async def test_get_dfg_project_by_id(): # Get by ID of the project we found or a known one diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 6f406f0b..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'; @@ -59,6 +59,8 @@ export interface DfgProjectTopic { field?: string | null; domain?: string | null; project_count: number; + field_project_count: number; + subfield_project_count: number; keywords: DfgProjectKeyword[]; } @@ -75,6 +77,9 @@ export interface DfgProjectTopics { topics: DfgProjectTopic[]; } +export interface EuProjectTopics extends DfgProjectTopics {} +export interface BundProjectTopics extends DfgProjectTopics {} + export interface TopAuthor { id?: string | null; name: string; @@ -90,6 +95,11 @@ export interface TopAuthorStatistics { news: TopAuthor[]; } +export interface TopAuthorAnalysis { + institution_id: string; + authors: TopAuthor[]; +} + export interface TopicWordCloudWord { id: string; name: string; @@ -202,12 +212,59 @@ export class DashboardStatisticsService { ); } + getEuProjectTopics( + period: DashboardPeriodBounds = {}, + ): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`, + { params: this.periodParams(period) }, + ); + } + + getBundProjectTopics( + period: DashboardPeriodBounds = {}, + ): Observable { + return this.httpClient.get( + `${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`, + { params: this.periodParams(period) }, + ); + } + 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 ?? [], + }; + }), ); } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 7cf8b2bc..75bceafa 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -40,7 +40,9 @@ [attr.aria-disabled]="!institutionRouteId()" [attr.aria-label]=" 'Publikationen von ' + organizationName() + ' anzeigen' - "> + " + matTooltip="Anzahl der Publikationen im ausgewählten Zeitraum" + matTooltipPosition="above">
menu_book
@@ -60,7 +62,9 @@ class="statistics-card" routerLink="/persons" [queryParams]="personListQueryParams()" - [attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'"> + [attr.aria-label]="'Personen von ' + organizationName() + ' anzeigen'" + matTooltip="Anzahl der Personen im ausgewählten Zeitraum" + matTooltipPosition="above">
groups
@@ -81,9 +85,11 @@ [routerLink]="['/institution', institutionRouteId(), 'patents']" [class.disabled]="!institutionRouteId()" [attr.aria-disabled]="!institutionRouteId()" - [attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'"> + [attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'" + matTooltip="Anzahl der Patente im ausgewählten Zeitraum" + matTooltipPosition="above">
- description + {{ patentIcon }}
Patente @@ -101,7 +107,9 @@ class="statistics-card" routerLink="/projects" [queryParams]="{ selected_project_types: 'eu' }" - aria-label="EU-Projekte anzeigen"> + aria-label="EU-Projekte anzeigen" + matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden EU-Projekte im ausgewählten Zeitraum" + matTooltipPosition="above">
public
@@ -121,7 +129,9 @@ class="statistics-card" routerLink="/projects" [queryParams]="{ selected_project_types: 'bund' }" - aria-label="Bund-Projekte anzeigen"> + aria-label="Bund-Projekte anzeigen" + matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden Bund-Projekte im ausgewählten Zeitraum" + matTooltipPosition="above">
account_balance
@@ -141,7 +151,9 @@ class="statistics-card" routerLink="/projects" [queryParams]="{ selected_project_types: 'dfg' }" - aria-label="DFG-Projekte anzeigen"> + aria-label="DFG-Projekte anzeigen" + matTooltip="Anzahl der laufenden, abgeschlossenen und kommenden DFG-Projekte im ausgewählten Zeitraum" + matTooltipPosition="above">
science
@@ -317,6 +329,92 @@ } + @if (euTopicsLoading || euTopicsError || euProjectTopics) { +
+
+
+

EU-Projekt-Topics

+

+ Gematchte EU-Projekte nach Field, Subfield und Topic. Ein Klick + auf ein Topic zeigt die zugehörigen Keywords. +

+
+ @if (euProjectTopics) { +

+ {{ euProjectTopics.matched_project_count | number }} von + {{ euProjectTopics.project_count | number }} Projekten gematcht +

+ } +
+ + @if (euTopicsLoading) { +
+ +
+ } @else if (euTopicsError) { +

+ Die EU-Topic-Treemap konnte nicht geladen werden. +

+ } @else { + + + } +
+ } + + @if (bundTopicsLoading || bundTopicsError || bundProjectTopics) { +
+
+
+

BUND-Projekt-Topics

+

+ Gematchte BUND-Projekte nach Field, Subfield und Topic. Ein Klick + auf ein Topic zeigt die zugehörigen Keywords. +

+
+ @if (bundProjectTopics) { +

+ {{ bundProjectTopics.matched_project_count | number }} von + {{ bundProjectTopics.project_count | number }} Projekten gematcht +

+ } +
+ + @if (bundTopicsLoading) { +
+ +
+ } @else if (bundTopicsError) { +

+ Die BUND-Topic-Treemap konnte nicht geladen werden. +

+ } @else { + + + } +
+ } + @if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
@@ -355,6 +453,8 @@ class="author-name author-link" [routerLink]="authorLink(dataset, entry)" [queryParams]="authorQueryParams(dataset, entry)" + [appComponentTooltip]="AuthorTooltipComponent" + [tooltipInputs]="{ authorId: entry.id }" [title]="authorDisplayName(dataset, entry)"> {{ authorDisplayName(dataset, entry) }} diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 034a1e76..68839065 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -39,7 +39,16 @@ } .dashboard-period-slider { - width: min(100%, 34rem); + width: 280px; + max-width: 100%; + margin-left: auto; + } + + @media (max-width: 720px) { + .dashboard-period-slider { + width: 100%; + margin-left: 0; + } } .statistics-grid { diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index cb9982c5..14fadca4 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -1,9 +1,13 @@ import { Component, OnInit } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { MatIconModule } from '@angular/material/icon'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { Observable, finalize } from 'rxjs'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatDialog } from '@angular/material/dialog'; +import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive'; +import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component'; +import { PATENT_ICON } from '../../shared/ui/icons'; import { EuProjectStatusChartComponent } from './eu-project-status-chart/eu-project-status-chart.component'; import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; @@ -18,6 +22,7 @@ import { } from './topic-wordcloud-dialog/topic-wordcloud-dialog.component'; import { BmbfProjectStatusStatistics, + BundProjectTopics, DashboardPeriodBounds, DashboardStatisticValue, DashboardStatistics, @@ -26,6 +31,7 @@ import { DfgProjectTopic, DfgProjectTopics, EuProjectStatusStatistics, + EuProjectTopics, TopAuthor, TopAuthorStatistics, } from './dashboard-statistics.service'; @@ -56,6 +62,8 @@ type DashboardPeriodMode = imports: [ DecimalPipe, MatIconModule, + MatTooltipModule, + ComponentTooltipDirective, RouterLink, LoadingComponent, EuProjectStatusChartComponent, @@ -66,6 +74,8 @@ type DashboardPeriodMode = styleUrl: './dashboard.component.scss', }) export class DashboardComponent implements OnInit { + readonly AuthorTooltipComponent = AppAuthorTooltipComponent; + readonly patentIcon = PATENT_ICON; statistics?: Partial; statisticsLoading = false; statisticsError = false; @@ -96,6 +106,14 @@ export class DashboardComponent implements OnInit { dfgTopicTreemap?: TopicTreemapData; dfgTopicsLoading = false; dfgTopicsError = false; + euProjectTopics?: EuProjectTopics; + euTopicTreemap?: TopicTreemapData; + euTopicsLoading = false; + euTopicsError = false; + bundProjectTopics?: BundProjectTopics; + bundTopicTreemap?: TopicTreemapData; + bundTopicsLoading = false; + bundTopicsError = false; euProjectStatuses?: EuProjectStatusStatistics; euProjectStatusesLoading = false; euProjectStatusesError = false; @@ -108,10 +126,12 @@ export class DashboardComponent implements OnInit { readonly topicTreemapMinYear = 1900; readonly topicTreemapMaxYear = new Date().getFullYear(); dashboardPeriodMode: DashboardPeriodMode = 'all_time'; - dashboardFromYear = this.topicTreemapMaxYear - 4; + dashboardFromYear = this.topicTreemapMinYear; dashboardToYear = this.topicTreemapMaxYear; selectedTopicTreemapNode?: string; selectedDfgTopicTreemapNode?: string; + selectedEuTopicTreemapNode?: string; + selectedBundTopicTreemapNode?: string; private topicTreemapReloadQueued = false; private topicTreemapRequestId = 0; @@ -128,6 +148,8 @@ export class DashboardComponent implements OnInit { this.loadTopAuthors(); this.loadTopicTreemap(); this.loadDfgProjectTopics(); + this.loadEuProjectTopics(); + this.loadBundProjectTopics(); this.loadEuProjectStatuses(); this.loadBmbfProjectStatuses(); this.loadDfgProjectStatuses(); @@ -245,10 +267,12 @@ export class DashboardComponent implements OnInit { ([subfieldName, group]) => ({ id: `${fieldName}::${subfieldName}`, name: subfieldName, - total: group.topics.reduce( - (sum, topic) => sum + topic.project_count, - 0, - ), + total: + group.topics[0]?.subfield_project_count ?? + group.topics.reduce( + (sum, topic) => sum + topic.project_count, + 0, + ), values: [], topics: group.topics.map((topic) => ({ id: topic.id, @@ -261,10 +285,12 @@ export class DashboardComponent implements OnInit { return { id: fieldName, name: fieldName, - total: mappedSubfields.reduce( - (sum, subfield) => sum + subfield.total, - 0, - ), + total: + [...subfields.values()][0]?.topics[0]?.field_project_count ?? + mappedSubfields.reduce( + (sum, subfield) => sum + subfield.total, + 0, + ), values: [], subfields: mappedSubfields, }; @@ -352,6 +378,7 @@ export class DashboardComponent implements OnInit { onDfgTopicTreemapNodeChange(nodeId: string | undefined): void { this.selectedDfgTopicTreemapNode = nodeId; + this.updateDashboardPeriodUrl(); } onDfgTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { @@ -378,6 +405,64 @@ export class DashboardComponent implements OnInit { ); } + onEuTopicTreemapNodeChange(nodeId: string | undefined): void { + this.selectedEuTopicTreemapNode = nodeId; + this.updateDashboardPeriodUrl(); + } + + onEuTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { + const euTopic = this.euProjectTopics?.topics.find( + (entry) => entry.id === topic.topicId, + ); + if (!euTopic) return; + + this.dialog.open( + TopicWordCloudDialogComponent, + { + width: '85vw', + maxWidth: '92vw', + data: { + ...topic, + source: 'eu', + words: euTopic.keywords.map((keyword) => ({ + id: keyword.name, + name: keyword.name, + count: keyword.project_count, + })), + }, + }, + ); + } + + onBundTopicTreemapNodeChange(nodeId: string | undefined): void { + this.selectedBundTopicTreemapNode = nodeId; + this.updateDashboardPeriodUrl(); + } + + onBundTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { + const bundTopic = this.bundProjectTopics?.topics.find( + (entry) => entry.id === topic.topicId, + ); + if (!bundTopic) return; + + this.dialog.open( + TopicWordCloudDialogComponent, + { + width: '85vw', + maxWidth: '92vw', + data: { + ...topic, + source: 'bund', + words: bundTopic.keywords.map((keyword) => ({ + id: keyword.name, + name: keyword.name, + count: keyword.project_count, + })), + }, + }, + ); + } + onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void { const period = this.selectedPeriodBounds(); this.dialog.open( @@ -406,23 +491,34 @@ export class DashboardComponent implements OnInit { this.dashboardPeriodMode = mode; } this.applyPresetPeriod(); - this.dashboardFromYear = this.parseDashboardYear( - params.get('fromYear'), - this.dashboardFromYear, - ); - this.dashboardToYear = this.parseDashboardYear( - params.get('toYear'), - this.dashboardToYear, - ); + if (this.dashboardPeriodMode !== 'all_time') { + this.dashboardFromYear = this.parseDashboardYear( + params.get('fromYear'), + this.dashboardFromYear, + ); + this.dashboardToYear = this.parseDashboardYear( + params.get('toYear'), + this.dashboardToYear, + ); + } if (this.dashboardFromYear > this.dashboardToYear) { this.dashboardFromYear = this.dashboardToYear; } this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined; + this.selectedDfgTopicTreemapNode = + params.get('dfgTreemapNode') ?? undefined; + this.selectedEuTopicTreemapNode = + params.get('euTreemapNode') ?? undefined; + this.selectedBundTopicTreemapNode = + params.get('bundTreemapNode') ?? undefined; } private applyPresetPeriod(): void { const currentYear = this.topicTreemapMaxYear; - if (this.dashboardPeriodMode === 'last_10_years') { + if (this.dashboardPeriodMode === 'all_time') { + this.dashboardFromYear = this.topicTreemapMinYear; + this.dashboardToYear = currentYear; + } else if (this.dashboardPeriodMode === 'last_10_years') { this.dashboardFromYear = currentYear - 9; this.dashboardToYear = currentYear; } else if (this.dashboardPeriodMode === 'last_5_years') { @@ -440,6 +536,9 @@ export class DashboardComponent implements OnInit { fromYear: period.fromYear ?? null, toYear: period.toYear ?? null, treemapNode: this.selectedTopicTreemapNode ?? null, + dfgTreemapNode: this.selectedDfgTopicTreemapNode ?? null, + euTreemapNode: this.selectedEuTopicTreemapNode ?? null, + bundTreemapNode: this.selectedBundTopicTreemapNode ?? null, }, queryParamsHandling: 'merge', replaceUrl: true, @@ -469,6 +568,8 @@ export class DashboardComponent implements OnInit { this.loadTopAuthors(); this.loadTopicTreemap(); this.loadDfgProjectTopics(); + this.loadEuProjectTopics(); + this.loadBundProjectTopics(); this.loadEuProjectStatuses(); this.loadBmbfProjectStatuses(); this.loadDfgProjectStatuses(); @@ -552,6 +653,40 @@ export class DashboardComponent implements OnInit { }); } + private loadEuProjectTopics(): void { + this.euTopicsLoading = true; + this.euTopicsError = false; + this.statisticsService + .getEuProjectTopics(this.selectedPeriodBounds()) + .pipe(finalize(() => (this.euTopicsLoading = false))) + .subscribe({ + next: (topics) => { + this.euProjectTopics = topics; + this.euTopicTreemap = this.buildDfgTopicTreemapData(topics); + }, + error: () => { + this.euTopicsError = true; + }, + }); + } + + private loadBundProjectTopics(): void { + this.bundTopicsLoading = true; + this.bundTopicsError = false; + this.statisticsService + .getBundProjectTopics(this.selectedPeriodBounds()) + .pipe(finalize(() => (this.bundTopicsLoading = false))) + .subscribe({ + next: (topics) => { + this.bundProjectTopics = topics; + this.bundTopicTreemap = this.buildDfgTopicTreemapData(topics); + }, + error: () => { + this.bundTopicsError = true; + }, + }); + } + private loadEuProjectStatuses(): void { this.euProjectStatusesLoading = true; this.euProjectStatusesError = false; diff --git a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts index 6639bbf4..a8b75dc0 100644 --- a/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts +++ b/webapp/src/app/modules/dashboard/topic-wordcloud-dialog/topic-wordcloud-dialog.component.ts @@ -23,7 +23,7 @@ export interface TopicWordCloudDialogData { fromYear?: number; toYear?: number; words?: TopicWordCloudWord[]; - source?: 'publications' | 'dfg'; + source?: 'publications' | 'dfg' | 'eu' | 'bund'; } interface DisplayWord extends TopicWordCloudWord {