diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index 74cbff0c..82759df4 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -60,6 +60,7 @@ class TopAuthor(BaseModel): class TopAuthorStatistics(BaseModel): institution_id: str works: list[TopAuthor] + projects: list[TopAuthor] eu_projects: list[TopAuthor] patents: list[TopAuthor] news: list[TopAuthor] diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 04788962..3eecda54 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,5 +1,6 @@ import asyncio import logging +import re from datetime import datetime from typing import Any, Literal @@ -12,6 +13,8 @@ from inse.integrations import elasticsearch from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.projects.dfg_institutions.service import autocomplete_institutions_for_selector +from inse.projects.logic import get_person_ids_by_institution_ids from .institute_helper import get_openalex_institution from .model import ( @@ -41,6 +44,41 @@ TOPIC_HEATMAP_YEARS = 5 WorksPeriod = Literal["all_time", "last_5_years"] logger = logging.getLogger(__name__) + +ACADEMIC_TITLE_RE = re.compile( + r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+", + re.IGNORECASE, +) + + +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): @@ -625,6 +663,13 @@ async def get_top_authors( normalized_id = _normalize_institution_id(institution_id) authors = await _safe_institution_authors(normalized_id) works = _top_work_authors(authors, works_period) + projects = await _safe_top_authors( + "projects", + _top_project_authors( + authors=authors, + organization_name=organization_name, + ), + ) eu_projects = await _safe_top_authors( "eu_projects", _top_eu_project_publication_authors(), @@ -640,6 +685,7 @@ async def get_top_authors( return TopAuthorStatistics( institution_id=normalized_id, works=works, + projects=projects, eu_projects=eu_projects, patents=patents, news=news, @@ -1102,6 +1148,463 @@ async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: ] +async def _top_project_authors( + authors: list[dict[str, Any]], + organization_name: str, +) -> list[TopAuthor]: + 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, + ) + + 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], +) -> tuple[list[dict[str, Any]], int]: + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": size, + "from": page * size, + "_source": [ + "id", + "project_id", + "persons", + ], + "query": { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": sorted(person_ids)}}, + }, + }, + "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) -> list[TopAuthor]: client = OrgPatentsSearchClient() authors = await client.top_authors_by_institution( diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 03615c1d..250f2e09 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,3 +1,4 @@ +from types import SimpleNamespace from unittest.mock import AsyncMock, patch from datetime import datetime @@ -383,7 +384,7 @@ async def test_dashboard_dfg_topics_returns_deduplicated_topics(): @pytest.mark.anyio -async def test_top_authors_maps_works_patents_and_news_without_project_queries(): +async def test_top_authors_maps_works_patents_eu_dfg_and_news(): async def search(**kwargs): if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: return { @@ -427,6 +428,37 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries() } } } + if kwargs["index"] == ESIndex.DFG_PROJECTS: + return { + "hits": { + "total": {"value": 2}, + "hits": [ + { + "_source": { + "id": "P1", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + { + "person_id": 99, + "full_name": "Outside Collaborator", + }, + ], + } + }, + { + "_source": { + "id": "P2", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + {"person_id": 2, "full_name": "Grace Example"}, + ], + } + }, + ], + } + } + if kwargs["index"] == ESIndex.DFG_PERSONS: + return {"hits": {"hits": []}} return {"aggregations": {"people": {"buckets": []}}} with patch( @@ -439,6 +471,12 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries() {"id": "A1", "name": "Ada Example", "count": 4}, ] ), + ), patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock(return_value=SimpleNamespace(elements=[SimpleNamespace(id=101)])), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[2]), ): result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") @@ -456,6 +494,11 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries() {"id": None, "name": "Grace Example", "count": 8}, {"id": None, "name": "Ada Example", "count": 5}, ] + assert result.projects[0].model_dump() == { + "id": "A2", + "name": "Grace Example", + "count": 2, + } assert result.news[0].model_dump() == { "id": "A1", "name": "Ada Example", @@ -464,10 +507,15 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries() project_calls = [ call for call in mocked_search.await_args_list - if call.kwargs["index"] - in {ESIndex.DFG_PROJECTS_V2, ESIndex.PROJECTS_BUND_V1} + if call.kwargs["index"] == ESIndex.DFG_PROJECTS ] - assert project_calls == [] + assert len(project_calls) == 1 + assert project_calls[0].kwargs["body"]["query"] == { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": [2]}}, + }, + } eu_calls = [ call for call in mocked_search.await_args_list @@ -505,10 +553,14 @@ async def test_top_authors_returns_partial_response_when_one_source_fails(): ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), + ), patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock(return_value=SimpleNamespace(elements=[])), ): result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") assert result.works[0].name == "Ada Example" + assert result.projects == [] assert result.eu_projects == [] assert result.patents == [] assert result.news == [] @@ -559,6 +611,9 @@ async def test_top_authors_can_rank_works_by_last_five_years(): ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), + ), patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock(return_value=SimpleNamespace(elements=[])), ): result = await get_top_authors( ORG_INSTITUTION_ID, diff --git a/webapp/src/app/api/model/topAuthorStatistics.ts b/webapp/src/app/api/model/topAuthorStatistics.ts index 3d06243b..69949f0c 100644 --- a/webapp/src/app/api/model/topAuthorStatistics.ts +++ b/webapp/src/app/api/model/topAuthorStatistics.ts @@ -12,6 +12,7 @@ import { TopAuthor } from './topAuthor'; export interface TopAuthorStatistics { institution_id: string; works: Array; + projects: Array; eu_projects: Array; patents: Array; news: Array; diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 7a38b2a9..a216fa2b 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -67,6 +67,7 @@ export interface TopAuthor { export interface TopAuthorStatistics { institution_id: string; works: TopAuthor[]; + projects: TopAuthor[]; eu_projects: TopAuthor[]; patents: TopAuthor[]; news: TopAuthor[]; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 36b1069d..28b1365f 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -271,7 +271,7 @@

Top 10 Personen aller Zeiten

-

Nach Anzahl der Works, Patente und News Ihrer Organisation.

+

Nach Anzahl der Works, DFG-Projekte, Patente und News Ihrer Organisation.

diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 45b1b471..124f8053 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -281,8 +281,10 @@ margin-bottom: 0.25rem; font-size: 0.85rem; - span { + .author-name { overflow: hidden; + color: #1d4ed8; + font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } @@ -290,8 +292,6 @@ .author-link { overflow: hidden; - color: #1d4ed8; - font-weight: 600; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 9a16019f..5d8ae1d2 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -39,6 +39,12 @@ type DashboardStatisticKey = | 'eu_projects' | 'bmbf_projects' | 'dfg_projects'; +type TopAuthorDataset = { + title: string; + icon: string; + entries: TopAuthor[]; + stripAuthorTitle?: boolean; +}; @Component({ selector: 'dashboard', imports: [ @@ -142,11 +148,7 @@ export class DashboardComponent implements OnInit { return this.statisticLoading[key]; } - topAuthorDatasets(): Array<{ - title: string; - icon: string; - entries: TopAuthor[]; - }> { + topAuthorDatasets(): TopAuthorDataset[] { return [ { title: 'Publikationen', @@ -163,15 +165,17 @@ export class DashboardComponent implements OnInit { icon: 'description', entries: this.topAuthors?.patents ?? [], }, + { + title: 'DFG Projekte', + icon: 'account_tree', + entries: this.topAuthors?.projects ?? [], + stripAuthorTitle: true, + }, { title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] }, ]; } - visibleTopAuthorDatasets(): Array<{ - title: string; - icon: string; - entries: TopAuthor[]; - }> { + visibleTopAuthorDatasets(): TopAuthorDataset[] { const datasets = this.topAuthorDatasets(); return this.topAuthorsLoading ? datasets @@ -206,6 +210,30 @@ export class DashboardComponent implements OnInit { return (count / maximum) * 100; } + authorDisplayName(dataset: TopAuthorDataset, entry: TopAuthor): string { + if (!dataset.stripAuthorTitle) return entry.name; + + return ( + entry.name + .replace( + /^(?:(?:(?:apl\.\s*)?prof(?:essor)?\.?|priv\.-doz\.?|pd|dr\.?)\s+)+/i, + '', + ) + .trim() || entry.name + ); + } + + authorLink(_dataset: TopAuthorDataset, entry: TopAuthor): string[] { + return ['/person', entry.id!, 'overview']; + } + + authorQueryParams( + _dataset: TopAuthorDataset, + _entry: TopAuthor, + ): Record | null { + return null; + } + organizationName(): string { return this.statistics?.organization_name ?? 'Ihre Organisation'; }