check-dashboard #275

Merged
farajollahi merged 18 commits from check-dashboard into dev 2026-08-11 13:50:26 +02:00
22 changed files with 3595 additions and 2224 deletions
@@ -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,
)
+92
View File
@@ -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}},
}
}
@@ -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,
)
@@ -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,
)
+23
View File
@@ -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
@@ -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)
@@ -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,
)
@@ -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,
}
}
+152 -8
View File
@@ -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",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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,
@@ -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()
+13 -1
View File
@@ -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,
@@ -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)
assert isinstance(res.elements, list)
@@ -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
@@ -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<EuProjectTopics> {
return this.httpClient.get<EuProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/topics`,
{ params: this.periodParams(period) },
);
}
getBundProjectTopics(
period: DashboardPeriodBounds = {},
): Observable<BundProjectTopics> {
return this.httpClient.get<BundProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bund/topics`,
{ params: this.periodParams(period) },
);
}
getTopAuthors(
period: DashboardPeriodBounds = {},
): Observable<TopAuthorStatistics> {
return this.httpClient.get<TopAuthorStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`,
{ params: this.periodParams(period) },
const analysis = (source: string) =>
this.httpClient
.get<TopAuthorAnalysis>(
`${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 ?? [],
};
}),
);
}
@@ -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">
<div class="statistics-icon statistics-icon--publications">
<mat-icon>menu_book</mat-icon>
</div>
@@ -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">
<div class="statistics-icon statistics-icon--persons">
<mat-icon>groups</mat-icon>
</div>
@@ -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">
<div class="statistics-icon statistics-icon--patents">
<mat-icon>description</mat-icon>
<mat-icon>{{ patentIcon }}</mat-icon>
</div>
<div>
<span>Patente</span>
@@ -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">
<div class="statistics-icon statistics-icon--eu-projects">
<mat-icon>public</mat-icon>
</div>
@@ -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">
<div class="statistics-icon statistics-icon--bund-projects">
<mat-icon>account_balance</mat-icon>
</div>
@@ -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">
<div class="statistics-icon statistics-icon--dfg-projects">
<mat-icon>science</mat-icon>
</div>
@@ -317,6 +329,92 @@
</section>
}
@if (euTopicsLoading || euTopicsError || euProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>EU-Projekt-Topics</h2>
<p>
Gematchte EU-Projekte nach Field, Subfield und Topic. Ein Klick
auf ein Topic zeigt die zugehörigen Keywords.
</p>
</div>
@if (euProjectTopics) {
<p class="dfg-topic-summary">
{{ euProjectTopics.matched_project_count | number }} von
{{ euProjectTopics.project_count | number }} Projekten gematcht
</p>
}
</header>
@if (euTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="EU-Topics werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (euTopicsError) {
<p class="statistics-error">
Die EU-Topic-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="euTopicTreemap"
[selectedNodeId]="selectedEuTopicTreemapNode"
countLabel="EU-Projekte"
[showCountInTooltip]="false"
(selectedNodeIdChange)="onEuTopicTreemapNodeChange($event)"
(topicSelect)="onEuTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (bundTopicsLoading || bundTopicsError || bundProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>BUND-Projekt-Topics</h2>
<p>
Gematchte BUND-Projekte nach Field, Subfield und Topic. Ein Klick
auf ein Topic zeigt die zugehörigen Keywords.
</p>
</div>
@if (bundProjectTopics) {
<p class="dfg-topic-summary">
{{ bundProjectTopics.matched_project_count | number }} von
{{ bundProjectTopics.project_count | number }} Projekten gematcht
</p>
}
</header>
@if (bundTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="BUND-Topics werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (bundTopicsError) {
<p class="statistics-error">
Die BUND-Topic-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-treemap
[data]="bundTopicTreemap"
[selectedNodeId]="selectedBundTopicTreemapNode"
countLabel="BUND-Projekte"
[showCountInTooltip]="false"
(selectedNodeIdChange)="onBundTopicTreemapNodeChange($event)"
(topicSelect)="onBundTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (topAuthorsLoading || topAuthorsError || hasTopAuthorData()) {
<section class="top-authors-section">
<header class="top-authors-header">
@@ -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) }}
</a>
@@ -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 {
@@ -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<DashboardStatistics>;
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, TopicWordCloudDialogData>(
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, TopicWordCloudDialogData>(
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<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
@@ -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;
@@ -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 {