diff --git a/service/src/main/inse/dashboard/institute_helper.py b/service/src/main/inse/dashboard/institute_helper.py
new file mode 100644
index 00000000..87c63d3d
--- /dev/null
+++ b/service/src/main/inse/dashboard/institute_helper.py
@@ -0,0 +1,29 @@
+from inse.exceptions import NotFoundException
+from inse.integrations import elasticsearch
+from inse.model import ESIndex
+from inse.models.openalex.institution import Institution
+
+
+async def get_openalex_institution(institution_id: str) -> Institution:
+ """Load an institution from OpenAlex using the user's institution ID."""
+ raw_institution_id = institution_id.strip().removeprefix(
+ "https://openalex.org/"
+ )
+ normalized_id = f"https://openalex.org/{raw_institution_id.upper()}"
+ response = await elasticsearch.search(
+ index=ESIndex.OPENALEX_INSTITUTIONS,
+ query={"term": {"id": normalized_id}},
+ size=1,
+ )
+ hits = response.get("hits", {}).get("hits", [])
+ if not hits:
+ raise NotFoundException(
+ f"Institution with ID '{raw_institution_id}' not found."
+ )
+
+ institution = Institution.from_dict(hits[0].get("_source", {}))
+ if institution is None:
+ raise NotFoundException(
+ f"Institution with ID '{raw_institution_id}' could not be parsed."
+ )
+ return institution
diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py
index c59f8028..74cbff0c 100644
--- a/service/src/main/inse/dashboard/model.py
+++ b/service/src/main/inse/dashboard/model.py
@@ -18,6 +18,39 @@ class DashboardStatisticValue(BaseModel):
value: int
+class EuProjectStatusStatistics(BaseModel):
+ institution_id: str
+ organization_name: str
+ ongoing: int
+ upcoming: int
+ completed: int
+
+
+class BmbfProjectStatusStatistics(BaseModel):
+ institution_id: str
+ organization_name: str
+ ongoing: int
+ upcoming: int
+ completed: int
+
+
+class DfgProjectTopic(BaseModel):
+ id: str
+ name: str
+ subfield: str | None = None
+ field: str | None = None
+ domain: str | None = None
+ project_count: int
+
+
+class DfgProjectTopics(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
@@ -27,7 +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]
@@ -38,11 +71,27 @@ class TopicHeatmapValue(BaseModel):
share: float
+class TopicHeatmapTopic(BaseModel):
+ id: str
+ name: str
+ total: int
+ values: list[TopicHeatmapValue]
+
+
+class TopicHeatmapSubfield(BaseModel):
+ id: str
+ name: str
+ total: int
+ values: list[TopicHeatmapValue]
+ topics: list[TopicHeatmapTopic]
+
+
class TopicHeatmapField(BaseModel):
id: str
name: str
total: int
values: list[TopicHeatmapValue]
+ subfields: list[TopicHeatmapSubfield]
class TopicHeatmap(BaseModel):
@@ -50,3 +99,14 @@ class TopicHeatmap(BaseModel):
organization_name: str
years: list[int]
fields: list[TopicHeatmapField]
+
+
+class TopicWordCloudWord(BaseModel):
+ id: str
+ name: str
+ count: int
+
+
+class TopicWordCloud(BaseModel):
+ topic_id: str
+ words: list[TopicWordCloudWord]
diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py
index 0012bff3..403bcb9d 100644
--- a/service/src/main/inse/dashboard/router.py
+++ b/service/src/main/inse/dashboard/router.py
@@ -9,21 +9,30 @@ from inse.database import get_session
from inse.tags import Tags
from .model import (
+ BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
+ DfgProjectTopics,
+ EuProjectStatusStatistics,
TopAuthorStatistics,
TopicHeatmap,
+ TopicWordCloud,
)
from .service import (
+ get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
+ get_dashboard_dfg_topics,
get_dashboard_eu_projects,
+ get_dashboard_eu_project_statuses,
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,
)
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
@@ -77,6 +86,22 @@ async def dashboard_persons(
)
+@router.get(
+ "/statistics/patents",
+ operation_id="getDashboardPatents",
+ response_model=DashboardStatisticValue,
+)
+async def dashboard_patents(
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> DashboardStatisticValue:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_patents(
+ organization.openalex_institution_id,
+ organization.name,
+ )
+
+
@router.get(
"/statistics/projects/eu",
operation_id="getDashboardEuProjects",
@@ -93,6 +118,22 @@ async def dashboard_eu_projects(
)
+@router.get(
+ "/projects/eu/status",
+ operation_id="getDashboardEuProjectStatuses",
+ response_model=EuProjectStatusStatistics,
+)
+async def dashboard_eu_project_statuses(
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> EuProjectStatusStatistics:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_eu_project_statuses(
+ organization.openalex_institution_id,
+ organization.name,
+ )
+
+
@router.get(
"/statistics/projects/bmbf",
operation_id="getDashboardBmbfProjects",
@@ -109,6 +150,22 @@ async def dashboard_bmbf_projects(
)
+@router.get(
+ "/projects/bmbf/status",
+ operation_id="getDashboardBmbfProjectStatuses",
+ response_model=BmbfProjectStatusStatistics,
+)
+async def dashboard_bmbf_project_statuses(
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> BmbfProjectStatusStatistics:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_bmbf_project_statuses(
+ organization.openalex_institution_id,
+ organization.name,
+ )
+
+
@router.get(
"/statistics/projects/dfg",
operation_id="getDashboardDfgProjects",
@@ -125,6 +182,22 @@ async def dashboard_dfg_projects(
)
+@router.get(
+ "/projects/dfg/topics",
+ operation_id="getDashboardDfgProjectTopics",
+ response_model=DfgProjectTopics,
+)
+async def dashboard_dfg_project_topics(
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> DfgProjectTopics:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_dashboard_dfg_topics(
+ organization.openalex_institution_id,
+ organization.name,
+ )
+
+
@router.get(
"/top-authors",
operation_id="getDashboardTopAuthors",
@@ -166,3 +239,26 @@ async def dashboard_topic_heatmap(
to_year=to_year,
limit=limit,
)
+
+
+@router.get(
+ "/topic-wordcloud",
+ operation_id="getDashboardTopicWordCloud",
+ response_model=TopicWordCloud,
+)
+async def dashboard_topic_word_cloud(
+ topic_id: str = Query(alias="topicId", min_length=1),
+ from_year: int | None = Query(default=None, ge=1900, le=2100),
+ to_year: int | None = Query(default=None, ge=1900, le=2100),
+ limit: int = Query(default=30, ge=1, le=100),
+ session: Session = Depends(get_session),
+ access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+) -> TopicWordCloud:
+ organization = get_dashboard_organization(session, access_token)
+ return await get_topic_word_cloud(
+ institution_id=organization.openalex_institution_id,
+ topic_id=topic_id,
+ from_year=from_year,
+ to_year=to_year,
+ limit=limit,
+ )
diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py
index ce9a9b2b..04788962 100644
--- a/service/src/main/inse/dashboard/service.py
+++ b/service/src/main/inse/dashboard/service.py
@@ -13,34 +13,34 @@ from inse.institutions.institutions_search_client import InstitutionsSearchClien
from inse.model import ESCluster, ESIndex
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
+from .institute_helper import get_openalex_institution
from .model import (
+ BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
+ DfgProjectTopic,
+ DfgProjectTopics,
+ EuProjectStatusStatistics,
TopAuthor,
TopAuthorStatistics,
TopicHeatmap,
TopicHeatmapField,
+ TopicHeatmapSubfield,
+ TopicHeatmapTopic,
TopicHeatmapValue,
+ TopicWordCloud,
+ TopicWordCloudWord,
)
TOP_AUTHOR_LIMIT = 10
TOPIC_HEATMAP_LIMIT = 25
+TOPIC_HEATMAP_SUBFIELD_LIMIT = 100
+TOPIC_HEATMAP_TOPIC_LIMIT = 100
+TOPIC_WORD_CLOUD_LIMIT = 30
TOPIC_HEATMAP_YEARS = 5
WorksPeriod = Literal["all_time", "last_5_years"]
logger = logging.getLogger(__name__)
-DFG_INSTITUTION_FIELDS = [
- "Antragstellende Institution",
- "Mitantragstellende Institution",
- "Beteiligte Einrichtung",
- "Beteiligte Hochschule",
- "Beteiligte Institution",
- "IGK-Partnerinstitution",
- "Partnerorganisation",
- "Unternehmen",
-]
-
-
def _total(response: dict[str, Any]) -> int:
total = response.get("hits", {}).get("total", 0)
if isinstance(total, dict):
@@ -112,14 +112,74 @@ async def get_dashboard_persons(
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
+
+ target_year = datetime.now().year - 1
+
+ recent_affiliation_query = {
+ "nested": {
+ "path": "affiliations",
+ "query": {
+ "bool": {
+ "filter": [
+ {
+ "match_phrase": {
+ "affiliations.institution.id": normalized_id
+ }
+ },
+ {"range": {"affiliations.years": {"gte": target_year}}},
+ ]
+ }
+ },
+ }
+ }
+ matching_last_known_institution_query = {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {
+ "match_phrase": {
+ "last_known_institutions.id": normalized_id
+ }
+ },
+ }
+ }
+ missing_last_known_institutions_query = {
+ "bool": {
+ "must_not": [
+ {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {"exists": {"field": "last_known_institutions.id"}},
+ }
+ }
+ ]
+ }
+ }
+ search_query = {
+ "bool": {
+ "should": [
+ {
+ "bool": {
+ "filter": [
+ matching_last_known_institution_query,
+ recent_affiliation_query,
+ ]
+ }
+ },
+ {
+ "bool": {
+ "filter": [
+ missing_last_known_institutions_query,
+ recent_affiliation_query,
+ ]
+ }
+ },
+ ],
+ "minimum_should_match": 1,
+ }
+ }
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
- query={
- "nested": {
- "path": "affiliations",
- "query": {"term": {"affiliations.institution.id": normalized_id}},
- }
- },
+ query=search_query,
size=0,
track_total_hits=True,
cluster=ESCluster.NES,
@@ -127,6 +187,23 @@ async def get_dashboard_persons(
return _dashboard_statistic_value(normalized_id, organization_name, response)
+async def get_dashboard_patents(
+ institution_id: str,
+ organization_name: str,
+) -> DashboardStatisticValue:
+ normalized_id = _normalize_institution_id(institution_id)
+ _, total = await OrgPatentsSearchClient().search_by_institution(
+ normalized_id,
+ page=0,
+ size=0,
+ )
+ return DashboardStatisticValue(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ value=total,
+ )
+
+
async def get_dashboard_eu_projects(
institution_id: str,
organization_name: str,
@@ -159,6 +236,86 @@ async def get_dashboard_eu_projects(
)
+async def get_dashboard_eu_project_statuses(
+ institution_id: str,
+ organization_name: str,
+) -> EuProjectStatusStatistics:
+ normalized_id = _normalize_institution_id(institution_id)
+ aliases = await _institution_aliases(normalized_id, organization_name)
+ 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))
+
+ if not project_ids:
+ return EuProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=0,
+ upcoming=0,
+ completed=0,
+ )
+
+ today = datetime.now().date().isoformat()
+ response = await elasticsearch.search(
+ index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
+ body={
+ "size": 0,
+ "query": {"terms": {"id": sorted(project_ids)}},
+ "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", {})
+ return EuProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=_project_status_count(aggregations, "ongoing"),
+ upcoming=_project_status_count(aggregations, "upcoming"),
+ completed=_project_status_count(aggregations, "completed"),
+ )
+
+
+def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int:
+ return int(
+ aggregations.get(status_name, {}).get("projects", {}).get("value", 0)
+ )
+
+
async def get_dashboard_bmbf_projects(
institution_id: str,
organization_name: str,
@@ -175,20 +332,200 @@ async def get_dashboard_bmbf_projects(
return _dashboard_statistic_value(normalized_id, organization_name, response)
+async def get_dashboard_bmbf_project_statuses(
+ institution_id: str,
+ organization_name: str,
+) -> BmbfProjectStatusStatistics:
+ normalized_id = _normalize_institution_id(institution_id)
+ aliases = await _institution_aliases(normalized_id, organization_name)
+ today = datetime.now().strftime("%d.%m.%Y")
+ response = await elasticsearch.search(
+ index=ESIndex.PROJECTS_BUND_V1,
+ body={
+ "size": 0,
+ "query": _alias_match_query("Zuwendungsempfänger", aliases),
+ "aggs": _project_status_filter_aggregations(
+ start_field="funding_start",
+ end_field="funding_end",
+ today=today,
+ ),
+ },
+ cluster=ESCluster.INSE,
+ )
+ aggregations = response.get("aggregations", {})
+ return BmbfProjectStatusStatistics(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ ongoing=int(aggregations.get("ongoing", {}).get("doc_count", 0)),
+ upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)),
+ completed=int(aggregations.get("completed", {}).get("doc_count", 0)),
+ )
+
+
+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,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
- aliases = await _institution_aliases(normalized_id, organization_name)
- response = await elasticsearch.search(
- index=ESIndex.DFG_PROJECTS,
- query=_dfg_institution_query(aliases),
- size=0,
- track_total_hits=True,
+ project_ids = await _get_dfg_project_ids_for_institution(normalized_id)
+ return DashboardStatisticValue(
+ institution_id=normalized_id,
+ organization_name=organization_name,
+ value=len(project_ids),
+ )
+
+
+async def get_dashboard_dfg_topics(
+ institution_id: str,
+ organization_name: str,
+) -> DfgProjectTopics:
+ normalized_id = _normalize_institution_id(institution_id)
+ project_ids = await _get_dfg_project_ids_for_institution(normalized_id)
+ 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", "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
+ 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(),
+ },
+ )
+ topic["project_ids"].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"]),
+ )
+ 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_for_institution(
+ institution_id: str,
+) -> list[str]:
+ 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,
)
- return _dashboard_statistic_value(normalized_id, organization_name, response)
+ 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,
+ )
+ return [
+ 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
+ ]
def _dashboard_statistic_value(
@@ -246,12 +583,34 @@ def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]:
}
-def _dfg_institution_query(aliases: list[str]) -> dict[str, Any]:
+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": [
- _alias_match_query(field, aliases)
- for field in DFG_INSTITUTION_FIELDS
+ {
+ "terms": {
+ "institute_name_de.keyword": institution_names,
+ }
+ },
+ {
+ "terms": {
+ "institute_name_en.keyword": institution_names,
+ }
+ },
],
"minimum_should_match": 1,
}
@@ -266,10 +625,9 @@ 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)
- aliases = await _safe_institution_aliases(normalized_id, organization_name)
- projects = await _safe_top_authors(
- "projects",
- _top_project_authors(authors, aliases),
+ eu_projects = await _safe_top_authors(
+ "eu_projects",
+ _top_eu_project_publication_authors(),
)
patents = await _safe_top_authors(
"patents",
@@ -282,7 +640,7 @@ async def get_top_authors(
return TopAuthorStatistics(
institution_id=normalized_id,
works=works,
- projects=projects,
+ eu_projects=eu_projects,
patents=patents,
news=news,
)
@@ -363,7 +721,49 @@ async def get_topic_heatmap(
}
}
},
- }
+ },
+ "subfields": {
+ "terms": {
+ "field": "topics.subfield.id",
+ "size": TOPIC_HEATMAP_SUBFIELD_LIMIT,
+ "order": [
+ {"works": "desc"},
+ {"_key": "asc"},
+ ],
+ },
+ "aggs": {
+ "subfield_name": {
+ "terms": {
+ "field": "topics.subfield.display_name.keyword",
+ "size": 1,
+ }
+ },
+ "works": {
+ "reverse_nested": {},
+ },
+ "topics": {
+ "terms": {
+ "field": "topics.id",
+ "size": TOPIC_HEATMAP_TOPIC_LIMIT,
+ "order": [
+ {"works": "desc"},
+ {"_key": "asc"},
+ ],
+ },
+ "aggs": {
+ "topic_name": {
+ "terms": {
+ "field": "topics.display_name.keyword",
+ "size": 1,
+ }
+ },
+ "works": {
+ "reverse_nested": {},
+ },
+ },
+ },
+ },
+ },
},
}
},
@@ -393,6 +793,88 @@ async def get_topic_heatmap(
)
+async def get_topic_word_cloud(
+ institution_id: str,
+ topic_id: str,
+ from_year: int | None = None,
+ to_year: int | None = None,
+ limit: int = TOPIC_WORD_CLOUD_LIMIT,
+) -> TopicWordCloud:
+ normalized_institution_id = _normalize_institution_id(institution_id)
+ filters: list[dict[str, Any]] = []
+ if from_year is not None or to_year is not None:
+ year_range: dict[str, int] = {}
+ if from_year is not None:
+ year_range["gte"] = from_year
+ if to_year is not None:
+ year_range["lte"] = to_year
+ filters.append({"range": {"publication_year": year_range}})
+
+ response = await elasticsearch.search(
+ index=config.settings.openalex_works_search_index,
+ body={
+ "size": 0,
+ "query": {
+ "bool": {
+ "must": [
+ _institution_works_query(normalized_institution_id),
+ {
+ "nested": {
+ "path": "topics",
+ "query": {"term": {"topics.id": topic_id}},
+ }
+ },
+ ],
+ "filter": filters,
+ }
+ },
+ "aggs": {
+ "topics_nested": {
+ "nested": {"path": "topics"},
+ "aggs": {
+ "topics": {
+ "terms": {
+ "field": "topics.id",
+ "size": limit + 1,
+ "order": [
+ {"works": "desc"},
+ {"_key": "asc"},
+ ],
+ },
+ "aggs": {
+ "topic_name": {
+ "terms": {
+ "field": "topics.display_name.keyword",
+ "size": 1,
+ }
+ },
+ "works": {"reverse_nested": {}},
+ },
+ }
+ },
+ }
+ },
+ },
+ cluster=ESCluster.NES,
+ )
+ buckets = (
+ response.get("aggregations", {})
+ .get("topics_nested", {})
+ .get("topics", {})
+ .get("buckets", [])
+ )
+ words = [
+ TopicWordCloudWord(
+ id=str(bucket["key"]),
+ name=_aggregation_name(bucket, "topic_name", str(bucket["key"])),
+ count=int(bucket.get("works", {}).get("doc_count", 0)),
+ )
+ for bucket in buckets
+ if bucket.get("key") and str(bucket["key"]) != topic_id
+ ][:limit]
+ return TopicWordCloud(topic_id=topic_id, words=words)
+
+
async def _safe_top_authors(
source: str, operation: Any
) -> list[TopAuthor]:
@@ -489,11 +971,51 @@ def _topic_heatmap_field(
name=_field_name(bucket, field_names.get(field_id, field_id)),
total=int(bucket.get("works", {}).get("doc_count", 0)),
values=values,
+ subfields=[
+ _topic_heatmap_subfield(subfield)
+ for subfield in bucket.get("subfields", {}).get("buckets", [])
+ if subfield.get("key")
+ ],
+ )
+
+
+def _topic_heatmap_subfield(
+ bucket: dict[str, Any],
+) -> TopicHeatmapSubfield:
+ subfield_id = str(bucket["key"])
+ return TopicHeatmapSubfield(
+ id=subfield_id,
+ name=_aggregation_name(bucket, "subfield_name", subfield_id),
+ total=int(bucket.get("works", {}).get("doc_count", 0)),
+ values=[],
+ topics=[
+ _topic_heatmap_topic(topic)
+ for topic in bucket.get("topics", {}).get("buckets", [])
+ if topic.get("key")
+ ],
+ )
+
+
+def _topic_heatmap_topic(
+ bucket: dict[str, Any],
+) -> TopicHeatmapTopic:
+ topic_id = str(bucket["key"])
+ return TopicHeatmapTopic(
+ id=topic_id,
+ name=_aggregation_name(bucket, "topic_name", topic_id),
+ total=int(bucket.get("works", {}).get("doc_count", 0)),
+ values=[],
)
def _field_name(bucket: dict[str, Any], fallback: str) -> str:
- name_buckets = bucket.get("field_name", {}).get("buckets", [])
+ return _aggregation_name(bucket, "field_name", fallback)
+
+
+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
@@ -553,17 +1075,6 @@ async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]
return []
-async def _safe_institution_aliases(
- institution_id: str,
- organization_name: str,
-) -> list[str]:
- try:
- return await _institution_aliases(institution_id, organization_name)
- except Exception:
- logger.exception("Could not load aliases for institution %s.", institution_id)
- return [organization_name]
-
-
async def _institution_authors(institution_id: str) -> list[dict[str, Any]]:
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
@@ -591,92 +1102,6 @@ async def _institution_authors(institution_id: str) -> list[dict[str, Any]]:
]
-async def _top_project_authors(
- authors: list[dict[str, Any]],
- aliases: list[str],
-) -> list[TopAuthor]:
- if not aliases:
- return []
- counts: dict[str, int] = {}
- names: dict[str, str] = {}
- for bucket in await _top_dfg_project_author_buckets(aliases):
- key = str(bucket.get("key", "")).strip()
- if key:
- normalized_key = key.casefold()
- names[normalized_key] = key
- counts[normalized_key] = counts.get(normalized_key, 0) + int(
- bucket.get("doc_count", 0)
- )
-
- institution_authors = {author["name"].casefold(): author for author in authors}
- ranked = sorted(
- (
- (name, count)
- for name, count in counts.items()
- if count > 0
- ),
- key=lambda item: (-item[1], names[item[0]].casefold()),
- )
- return [
- TopAuthor(
- id=(
- _short_author_id(institution_authors[name]["id"])
- if name in institution_authors
- else None
- ),
- name=(
- institution_authors[name]["name"]
- if name in institution_authors
- else names[name]
- ),
- count=count,
- )
- for name, count in ranked[:TOP_AUTHOR_LIMIT]
- ]
-
-
-async def _top_dfg_project_author_buckets(
- aliases: list[str],
-) -> list[dict[str, Any]]:
- response = await elasticsearch.search(
- index=ESIndex.DFG_PROJECTS,
- body={
- "size": 0,
- "query": _dfg_institution_query(aliases),
- "aggs": {
- "people": {
- "terms": {
- "script": {
- "lang": "painless",
- "source": _dfg_involved_persons_script(),
- },
- "size": 10000,
- }
- }
- },
- },
- cluster=ESCluster.INSE,
- )
- return (
- response.get("aggregations", {}).get("people", {}).get("buckets", [])
- )
-
-
-def _dfg_involved_persons_script() -> str:
- return (
- "def names = new HashSet(); "
- "def value = params['_source'].containsKey('Beteiligte Personen') "
- " ? params['_source']['Beteiligte Personen'] : null; "
- "if (value instanceof String && value.length() > 0) { "
- " for (name in value.splitOnToken(';')) { "
- " def trimmed = name.trim(); "
- " if (trimmed.length() > 0) { names.add(trimmed); } "
- " } "
- "} "
- "return new ArrayList(names);"
- )
-
-
async def _top_patent_authors(institution_id: str) -> list[TopAuthor]:
client = OrgPatentsSearchClient()
authors = await client.top_authors_by_institution(
@@ -693,6 +1118,54 @@ async def _top_patent_authors(institution_id: str) -> list[TopAuthor]:
]
+async def _top_eu_project_publication_authors() -> list[TopAuthor]:
+ response = await elasticsearch.search(
+ index=ESIndex.CORDIS_EU_FP7_PUBLICATIONS,
+ body={
+ "size": 0,
+ "aggs": {
+ "authors": {
+ "terms": {
+ "script": {
+ "lang": "painless",
+ "source": _cordis_publication_authors_script(),
+ },
+ "size": TOP_AUTHOR_LIMIT,
+ "order": {"_count": "desc"},
+ }
+ }
+ },
+ },
+ cluster=ESCluster.INSE,
+ )
+ return [
+ TopAuthor(
+ name=str(bucket["key"]),
+ count=int(bucket.get("doc_count", 0)),
+ )
+ for bucket in (
+ response.get("aggregations", {}).get("authors", {}).get("buckets", [])
+ )
+ if str(bucket.get("key", "")).strip()
+ ]
+
+
+def _cordis_publication_authors_script() -> str:
+ return (
+ "def names = new HashSet(); "
+ "def source = params['_source']; "
+ "def value = source.containsKey('authors') ? source['authors'] "
+ " : (source.containsKey('Authors') ? source['Authors'] : null); "
+ "if (value instanceof String && value.length() > 0) { "
+ " for (name in value.splitOnToken(';')) { "
+ " def trimmed = name.trim(); "
+ " if (trimmed.length() > 0) { names.add(trimmed); } "
+ " } "
+ "} "
+ "return new ArrayList(names);"
+ )
+
+
async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]:
if not authors:
return []
diff --git a/service/src/main/inse/dashboard/test_institute_helper.py b/service/src/main/inse/dashboard/test_institute_helper.py
new file mode 100644
index 00000000..24fb4fea
--- /dev/null
+++ b/service/src/main/inse/dashboard/test_institute_helper.py
@@ -0,0 +1,40 @@
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from inse.dashboard.institute_helper import get_openalex_institution
+from inse.models.openalex.institution import Institution
+
+
+@pytest.fixture
+def anyio_backend():
+ return "asyncio"
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "institution_id",
+ ["I62318514", "https://openalex.org/I62318514"],
+)
+async def test_get_openalex_institution_accepts_short_and_full_id(
+ institution_id: str,
+):
+ institution = Institution(
+ id="https://openalex.org/I62318514",
+ display_name="University of Duisburg-Essen",
+ display_name_alternatives=["Universität Duisburg-Essen"],
+ )
+ with patch(
+ "inse.dashboard.institute_helper.elasticsearch.search",
+ new=AsyncMock(
+ return_value={"hits": {"hits": [{"_source": institution.to_dict()}]}}
+ ),
+ ) as search:
+ result = await get_openalex_institution(institution_id)
+
+ assert result == institution
+ search.assert_awaited_once_with(
+ index="openalex-institutions",
+ query={"term": {"id": "https://openalex.org/I62318514"}},
+ size=1,
+ )
diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py
index 0d2914c0..03615c1d 100644
--- a/service/src/main/inse/dashboard/test_service.py
+++ b/service/src/main/inse/dashboard/test_service.py
@@ -8,12 +8,18 @@ from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.dashboard.service import (
+ get_dashboard_bmbf_project_statuses,
get_dashboard_organization,
+ get_dashboard_dfg_topics,
+ get_dashboard_eu_project_statuses,
+ get_dashboard_patents,
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
+ get_topic_word_cloud,
)
from inse.model import ESCluster, ESIndex
+from inse.models.openalex.institution import Institution
ORG_INSTITUTION_ID = "https://openalex.org/I123"
@@ -23,6 +29,125 @@ def anyio_backend():
return "asyncio"
+@pytest.mark.anyio
+async def test_dashboard_patents_uses_org_patent_total():
+ with patch(
+ "inse.dashboard.service.OrgPatentsSearchClient.search_by_institution",
+ new=AsyncMock(return_value=([], 42)),
+ ) as search:
+ result = await get_dashboard_patents(ORG_INSTITUTION_ID, "Example Org")
+
+ assert result.model_dump() == {
+ "institution_id": ORG_INSTITUTION_ID,
+ "organization_name": "Example Org",
+ "value": 42,
+ }
+ search.assert_awaited_once_with(ORG_INSTITUTION_ID, page=0, size=0)
+
+
+@pytest.mark.anyio
+async def test_dashboard_eu_project_statuses_deduplicates_projects():
+ async def scan(**kwargs):
+ assert kwargs["index"] == str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD)
+ assert kwargs["source"] == ["projectID"]
+ yield {"_source": {"projectID": "P2"}}
+ yield {"_source": {"projectID": "P1"}}
+ yield {"_source": {"projectID": "P1"}}
+
+ response = {
+ "aggregations": {
+ "ongoing": {"projects": {"value": 2}},
+ "upcoming": {"projects": {"value": 1}},
+ "completed": {"projects": {"value": 7}},
+ }
+ }
+ with patch(
+ "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
+ new=AsyncMock(return_value=["Example University"]),
+ ), patch("inse.dashboard.service.elasticsearch.scan", new=scan), patch(
+ "inse.dashboard.service.elasticsearch.search",
+ new=AsyncMock(return_value=response),
+ ) as search:
+ result = await get_dashboard_eu_project_statuses(
+ ORG_INSTITUTION_ID,
+ "Example Org",
+ )
+
+ assert result.model_dump() == {
+ "institution_id": ORG_INSTITUTION_ID,
+ "organization_name": "Example Org",
+ "ongoing": 2,
+ "upcoming": 1,
+ "completed": 7,
+ }
+ call = search.await_args
+ assert call.kwargs["index"] == ESIndex.CORDIS_EU_PROJECTS_WILDCARD
+ assert call.kwargs["body"]["query"] == {
+ "terms": {"id": ["P1", "P2"]}
+ }
+ today = datetime.now().date().isoformat()
+ aggregations = call.kwargs["body"]["aggs"]
+ assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [
+ {"range": {"startDate": {"lte": today}}},
+ {"range": {"endDate": {"gte": today}}},
+ ]
+ assert aggregations["upcoming"]["filter"] == {
+ "range": {"startDate": {"gt": today}}
+ }
+ assert aggregations["completed"]["filter"] == {
+ "range": {"endDate": {"lt": today}}
+ }
+ assert all(
+ aggregation["aggs"]["projects"]["cardinality"]["field"] == "id"
+ for aggregation in aggregations.values()
+ )
+
+
+@pytest.mark.anyio
+async def test_dashboard_bmbf_project_statuses_uses_funding_dates():
+ response = {
+ "aggregations": {
+ "ongoing": {"doc_count": 4},
+ "upcoming": {"doc_count": 2},
+ "completed": {"doc_count": 19},
+ }
+ }
+ with patch(
+ "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
+ new=AsyncMock(return_value=["Example University"]),
+ ), patch(
+ "inse.dashboard.service.elasticsearch.search",
+ new=AsyncMock(return_value=response),
+ ) as search:
+ result = await get_dashboard_bmbf_project_statuses(
+ ORG_INSTITUTION_ID,
+ "Example Org",
+ )
+
+ assert result.model_dump() == {
+ "institution_id": ORG_INSTITUTION_ID,
+ "organization_name": "Example Org",
+ "ongoing": 4,
+ "upcoming": 2,
+ "completed": 19,
+ }
+ call = search.await_args
+ assert call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
+ assert call.kwargs["body"]["query"]["bool"]["minimum_should_match"] == 1
+ today = datetime.now().strftime("%d.%m.%Y")
+ aggregations = call.kwargs["body"]["aggs"]
+ assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [
+ {"range": {"funding_start": {"lte": today}}},
+ {"range": {"funding_end": {"gte": today}}},
+ ]
+ assert aggregations["upcoming"]["filter"] == {
+ "range": {"funding_start": {"gt": today}}
+ }
+ assert aggregations["completed"]["filter"] == {
+ "range": {"funding_end": {"lt": today}}
+ }
+
+
@pytest.mark.anyio
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
async def search(**kwargs):
@@ -35,6 +160,28 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
return {"aggregations": {"projects": {"value": 10}}}
if index == ESIndex.PROJECTS_BUND_V1:
return {"hits": {"total": {"value": 5}}}
+ if index == ESIndex.DFG_INSTITUTES_V2:
+ if "institute_ids" in kwargs["body"].get("aggs", {}):
+ return {
+ "aggregations": {
+ "institute_ids": {"buckets": [{"key": 10210}]}
+ }
+ }
+ return {
+ "aggregations": {
+ "projects_nested": {
+ "project_ids": {
+ "values": {
+ "buckets": [
+ {"key": 101},
+ {"key": 102},
+ {"key": 103},
+ ]
+ }
+ }
+ }
+ }
+ }
return {"hits": {"total": {"value": 3}}}
with patch(
@@ -43,6 +190,15 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
) 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"],
+ )
+ ),
):
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
@@ -57,20 +213,34 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
"bmbf_projects": 5,
}
calls = mocked_search.await_args_list
- assert calls[0].kwargs["index"] == config.settings.openalex_works_search_index
- assert calls[0].kwargs["query"]["nested"]["query"]["term"] == {
+ calls_by_index = {
+ call.kwargs["index"]: call
+ for call in calls
+ if call.kwargs["index"] != ESIndex.DFG_INSTITUTES_V2
+ }
+ works_call = calls_by_index[config.settings.openalex_works_search_index]
+ authors_call = calls_by_index[ESIndex.OPENALEX_AUTHORS]
+ eu_call = calls_by_index[ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD]
+ bmbf_call = calls_by_index[ESIndex.PROJECTS_BUND_V1]
+ dfg_calls = [
+ call
+ for call in calls
+ if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
+ ]
+ dfg_institutes_call, dfg_projects_call = dfg_calls
+ assert works_call.kwargs["query"]["nested"]["query"]["term"] == {
"authorships.institutions.id": ORG_INSTITUTION_ID
}
- assert calls[1].kwargs["query"]["nested"]["query"]["term"] == {
- "affiliations.institution.id": ORG_INSTITUTION_ID
+ assert authors_call.kwargs["query"]["bool"]["should"][0]["bool"]["filter"][
+ 0
+ ]["nested"]["query"]["match_phrase"] == {
+ "last_known_institutions.id": ORG_INSTITUTION_ID
}
- assert all(call.kwargs["cluster"] == ESCluster.INSE for call in calls[2:])
- assert [call.kwargs["index"] for call in calls[2:]] == [
- ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
- ESIndex.PROJECTS_BUND_V1,
- ESIndex.DFG_PROJECTS,
- ]
- assert calls[2].kwargs["body"]["query"] == {
+ assert all(
+ call.kwargs["cluster"] == ESCluster.INSE
+ for call in [eu_call, bmbf_call, *dfg_calls]
+ )
+ assert eu_call.kwargs["body"]["query"] == {
"terms": {
"name.keyword": [
"EXAMPLE ORG",
@@ -79,26 +249,141 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
]
}
}
- assert calls[3].kwargs["query"]["bool"]["minimum_should_match"] == 1
- assert calls[3].kwargs["query"]["bool"]["should"][0]["match"] == {
+ assert bmbf_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
+ assert bmbf_call.kwargs["query"]["bool"]["should"][0]["match"] == {
"Zuwendungsempfänger": {
"query": "Example Org",
"operator": "and",
}
}
- assert calls[4].kwargs["query"]["bool"]["minimum_should_match"] == 1
- assert calls[4].kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][
- "match"
- ] == {
- "Antragstellende Institution": {
- "query": "Example Org",
- "operator": "and",
+ dfg_query = dfg_institutes_call.kwargs["body"]["query"]
+ assert dfg_query["bool"]["minimum_should_match"] == 1
+ assert dfg_query["bool"]["should"] == [
+ {
+ "terms": {
+ "institute_name_de.keyword": [
+ "Example University",
+ "Example Universität",
+ ]
+ }
+ },
+ {
+ "terms": {
+ "institute_name_en.keyword": [
+ "Example University",
+ "Example Universität",
+ ]
+ }
+ },
+ ]
+ assert dfg_projects_call.kwargs["body"]["query"] == {
+ "terms": {"institute_id": [10210]}
+ }
+ assert dfg_projects_call.kwargs["body"]["aggs"] == {
+ "projects_nested": {
+ "nested": {"path": "projects"},
+ "aggs": {
+ "project_ids": {
+ "filter": {
+ "terms": {"projects.institute_ref_id": [10210]}
+ },
+ "aggs": {
+ "values": {
+ "terms": {
+ "field": "projects.project_id",
+ "size": 10000,
+ }
+ }
+ },
+ }
+ },
}
}
@pytest.mark.anyio
-async def test_top_authors_maps_works_and_dfg_project_aggregations():
+async def test_dashboard_dfg_topics_returns_deduplicated_topics():
+ async def scan(**kwargs):
+ assert kwargs == {
+ "index": "projects_dfg_openalex_topics",
+ "query": {"terms": {"project_id": ["101", "102"]}},
+ "source": ["project_id", "topic_matches"],
+ "page_size": 1000,
+ "cluster": ESCluster.INSE,
+ }
+ yield {
+ "_source": {
+ "project_id": "101",
+ "topic_matches": [
+ {
+ "topic_id": "https://openalex.org/T1",
+ "topic_display_name": "Topic One",
+ "subfield": "Subfield One",
+ "field": "Field One",
+ "domain": "Domain One",
+ }
+ ],
+ }
+ }
+ yield {
+ "_source": {
+ "project_id": "102",
+ "topic_matches": [
+ {
+ "topic_id": "https://openalex.org/T1",
+ "topic_display_name": "Topic One",
+ "subfield": "Subfield One",
+ "field": "Field One",
+ "domain": "Domain One",
+ },
+ {
+ "topic_id": "https://openalex.org/T2",
+ "topic_display_name": "Topic Two",
+ "subfield": "Subfield Two",
+ "field": "Field Two",
+ "domain": "Domain Two",
+ },
+ ],
+ }
+ }
+
+ with patch(
+ "inse.dashboard.service._get_dfg_project_ids_for_institution",
+ new=AsyncMock(return_value=["101", "102"]),
+ ), patch("inse.dashboard.service.elasticsearch.scan", new=scan):
+ result = await get_dashboard_dfg_topics(
+ ORG_INSTITUTION_ID,
+ "Example Org",
+ )
+
+ assert result.model_dump() == {
+ "institution_id": ORG_INSTITUTION_ID,
+ "organization_name": "Example Org",
+ "project_count": 2,
+ "matched_project_count": 2,
+ "topics": [
+ {
+ "id": "https://openalex.org/T1",
+ "name": "Topic One",
+ "subfield": "Subfield One",
+ "field": "Field One",
+ "domain": "Domain One",
+ "project_count": 2,
+ },
+ {
+ "id": "https://openalex.org/T2",
+ "name": "Topic Two",
+ "subfield": "Subfield Two",
+ "field": "Field Two",
+ "domain": "Domain Two",
+ "project_count": 1,
+ },
+ ],
+ }
+
+
+@pytest.mark.anyio
+async def test_top_authors_maps_works_patents_and_news_without_project_queries():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -131,11 +416,14 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
}
}
}
- if kwargs["index"] == ESIndex.DFG_PROJECTS:
+ if kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS:
return {
"aggregations": {
- "people": {
- "buckets": [{"key": "Grace Example", "doc_count": 3}]
+ "authors": {
+ "buckets": [
+ {"key": "Grace Example", "doc_count": 8},
+ {"key": "Ada Example", "doc_count": 5},
+ ]
}
}
}
@@ -145,9 +433,6 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
"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.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(
return_value=[
@@ -162,16 +447,15 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
"name": "Ada Example",
"count": 42,
}
- assert result.projects[0].model_dump() == {
- "id": "A2",
- "name": "Grace Example",
- "count": 3,
- }
assert result.patents[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 4,
}
+ assert [author.model_dump() for author in result.eu_projects] == [
+ {"id": None, "name": "Grace Example", "count": 8},
+ {"id": None, "name": "Ada Example", "count": 5},
+ ]
assert result.news[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
@@ -181,135 +465,18 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
call
for call in mocked_search.await_args_list
if call.kwargs["index"]
- in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
+ in {ESIndex.DFG_PROJECTS_V2, ESIndex.PROJECTS_BUND_V1}
]
- assert len(project_calls) == 1
- assert project_calls[0].kwargs["index"] == ESIndex.DFG_PROJECTS
- assert project_calls[0].kwargs["body"]["query"]["bool"][
- "minimum_should_match"
- ] == 1
- assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][
- "people"
- ]["terms"]["script"]["source"]
-
-
-@pytest.mark.anyio
-async def test_top_authors_keeps_dfg_project_authors_without_openalex_match():
- async def search(**kwargs):
- if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
- return {"hits": {"hits": []}}
- if kwargs["index"] == ESIndex.DFG_PROJECTS:
- return {
- "aggregations": {
- "people": {
- "buckets": [{"key": "Project Person", "doc_count": 9}]
- }
- }
- }
- 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.OrgPatentsSearchClient.top_authors_by_institution",
- new=AsyncMock(return_value=[]),
- ):
- result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
-
- assert result.projects[0].model_dump() == {
- "id": None,
- "name": "Project Person",
- "count": 9,
- }
-
-
-@pytest.mark.anyio
-async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count():
- async def search(**kwargs):
- if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
- return {"hits": {"hits": []}}
- if kwargs["index"] == ESIndex.DFG_PROJECTS:
- return {
- "aggregations": {
- "people": {
- "buckets": [
- {"key": f"Project Person {count}", "doc_count": count}
- for count in range(1, 12)
- ]
- }
- }
- }
- 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.OrgPatentsSearchClient.top_authors_by_institution",
- new=AsyncMock(return_value=[]),
- ):
- result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
-
- assert [author.count for author in result.projects] == list(range(11, 1, -1))
- assert result.projects[0].name == "Project Person 11"
- assert len(result.projects) == 10
-
-
-@pytest.mark.anyio
-async def test_top_authors_combines_dfg_involved_people_case_insensitively():
- async def search(**kwargs):
- if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
- return {
- "hits": {
- "hits": [
- {
- "_source": {
- "id": "https://openalex.org/A1",
- "display_name": "Ada Example",
- "works_count": 1,
- "counts_by_year": [],
- }
- }
- ]
- }
- }
- if kwargs["index"] == ESIndex.DFG_PROJECTS:
- return {
- "aggregations": {
- "people": {
- "buckets": [
- {"key": "Ada Example", "doc_count": 2},
- {"key": "ada example", "doc_count": 3},
- {"key": "DFG Person", "doc_count": 4},
- ]
- }
- }
- }
- return {"aggregations": {"authors": {"buckets": []}}}
-
- with patch(
- "inse.dashboard.service.elasticsearch.search",
- new=AsyncMock(side_effect=search),
- ), patch(
- "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
- new=AsyncMock(return_value=["Example University"]),
- ), patch(
- "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
- new=AsyncMock(return_value=[]),
- ):
- result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
-
- assert [author.model_dump() for author in result.projects] == [
- {"id": "A1", "name": "Ada Example", "count": 5},
- {"id": None, "name": "DFG Person", "count": 4},
+ assert project_calls == []
+ eu_calls = [
+ call
+ for call in mocked_search.await_args_list
+ if call.kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS
]
+ assert len(eu_calls) == 1
+ terms = eu_calls[0].kwargs["body"]["aggs"]["authors"]["terms"]
+ assert terms["size"] == 10
+ assert "splitOnToken(';')" in terms["script"]["source"]
@pytest.mark.anyio
@@ -335,9 +502,6 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
- ), patch(
- "inse.dashboard.service.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=[]),
@@ -345,7 +509,7 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
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 == []
@@ -448,6 +612,42 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
]
},
},
+ "subfields": {
+ "buckets": [
+ {
+ "key": "https://openalex.org/subfields/1702",
+ "subfield_name": {
+ "buckets": [
+ {
+ "key": "Artificial Intelligence",
+ "doc_count": 7,
+ }
+ ]
+ },
+ "works": {
+ "doc_count": 7,
+ },
+ "topics": {
+ "buckets": [
+ {
+ "key": "https://openalex.org/T100",
+ "topic_name": {
+ "buckets": [
+ {
+ "key": "Machine learning",
+ "doc_count": 6,
+ }
+ ]
+ },
+ "works": {
+ "doc_count": 6,
+ },
+ }
+ ]
+ },
+ }
+ ]
+ },
}
]
}
@@ -490,6 +690,22 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
{"year": 2023, "count": 4, "share": 0.4},
{"year": 2024, "count": 8, "share": 0.4},
],
+ "subfields": [
+ {
+ "id": "https://openalex.org/subfields/1702",
+ "name": "Artificial Intelligence",
+ "total": 7,
+ "values": [],
+ "topics": [
+ {
+ "id": "https://openalex.org/T100",
+ "name": "Machine learning",
+ "total": 6,
+ "values": [],
+ }
+ ],
+ }
+ ],
}
body = mocked_search.await_args_list[0].kwargs["body"]
assert body["query"]["bool"]["must"][0]["nested"]["query"]["term"] == {
@@ -499,6 +715,22 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
body["aggs"]["topics_nested"]["aggs"]["fields"]["terms"]["field"]
== "topics.field.id"
)
+ assert (
+ body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
+ ["subfields"]["terms"]["field"]
+ == "topics.subfield.id"
+ )
+ assert (
+ body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
+ ["subfields"]["aggs"]["topics"]["terms"]["field"]
+ == "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"]
+ )
@pytest.mark.anyio
@@ -531,6 +763,58 @@ async def test_topic_heatmap_defaults_to_last_five_years():
}
+@pytest.mark.anyio
+async def test_topic_word_cloud_maps_related_topics_and_excludes_selected_topic():
+ response = {
+ "aggregations": {
+ "topics_nested": {
+ "topics": {
+ "buckets": [
+ {
+ "key": "https://openalex.org/T100",
+ "topic_name": {"buckets": [{"key": "Selected topic"}]},
+ "works": {"doc_count": 9},
+ },
+ {
+ "key": "https://openalex.org/T200",
+ "topic_name": {"buckets": [{"key": "Related topic"}]},
+ "works": {"doc_count": 6},
+ },
+ ]
+ }
+ }
+ }
+ }
+ with patch(
+ "inse.dashboard.service.elasticsearch.search",
+ new=AsyncMock(return_value=response),
+ ) as mocked_search:
+ result = await get_topic_word_cloud(
+ institution_id=ORG_INSTITUTION_ID,
+ topic_id="https://openalex.org/T100",
+ from_year=2023,
+ to_year=2024,
+ )
+
+ assert result.model_dump() == {
+ "topic_id": "https://openalex.org/T100",
+ "words": [
+ {
+ "id": "https://openalex.org/T200",
+ "name": "Related topic",
+ "count": 6,
+ }
+ ],
+ }
+ body = mocked_search.await_args.kwargs["body"]
+ assert body["query"]["bool"]["must"][1]["nested"]["query"]["term"] == {
+ "topics.id": "https://openalex.org/T100"
+ }
+ assert body["query"]["bool"]["filter"] == [
+ {"range": {"publication_year": {"gte": 2023, "lte": 2024}}}
+ ]
+
+
def test_get_dashboard_organization_uses_effective_organization():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py
index 1e34ea34..afc08614 100644
--- a/service/src/main/inse/integrations/elasticsearch.py
+++ b/service/src/main/inse/integrations/elasticsearch.py
@@ -101,6 +101,9 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
ESIndex.PROJECTS_BUND_V1,
ESIndex.DFG_PROJECTS,
+ ESIndex.DFG_PROJECTS_V2,
+ ESIndex.DFG_INSTITUTES_V2,
+ ESIndex.PROJECTS_DFG_OPENALEX_TOPICS,
}:
return ESCluster.INSE
else:
diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py
index 970ec14f..1e904b5f 100644
--- a/service/src/main/inse/model.py
+++ b/service/src/main/inse/model.py
@@ -62,6 +62,9 @@ class ESIndex(StrEnum):
ORG_PATENTS = "org_patents"
PROJECTS_BUND_V1 = "projects_bund_v1"
+ DFG_PROJECTS_V2 = "dfg_projects_2.0"
+ DFG_INSTITUTES_V2 = "dfg_institutes_2.0"
+ PROJECTS_DFG_OPENALEX_TOPICS = "projects_dfg_openalex_topics"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
diff --git a/webapp/src/app/api/model/topAuthorStatistics.ts b/webapp/src/app/api/model/topAuthorStatistics.ts
index 6ea5990a..745d0b24 100644
--- a/webapp/src/app/api/model/topAuthorStatistics.ts
+++ b/webapp/src/app/api/model/topAuthorStatistics.ts
@@ -13,7 +13,7 @@ import { TopAuthor } from './topAuthor';
export interface TopAuthorStatistics {
institution_id: string;
works: Array
+ Laufende, kommende und abgeschlossene EU- und Bund-Projekte Ihrer Organisation. +
++ Der Status der EU- und Bund-Projekte konnte nicht geladen werden. +
+ } @else if (euProjectStatuses && bmbfProjectStatuses) { +Publikationen Ihrer Organisation nach Field.
Die Field-Treemap konnte nicht geladen werden.
} @else { -+ Verteilung der gematchten Topics aus den DFG-Projekten Ihrer Organisation. +
++ {{ dfgProjectTopics.matched_project_count | number }} von + {{ dfgProjectTopics.project_count | number }} Projekten gematcht +
+ } ++ Das DFG-Topic-Diagramm konnte nicht geladen werden. +
+ } @else { +Keine gematchten DFG-Topics vorhanden.
+} diff --git a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.scss b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.scss similarity index 62% rename from webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.scss rename to webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.scss index 773d1c4e..73da71f3 100644 --- a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.scss +++ b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.scss @@ -1,9 +1,9 @@ -.topic-treemap-chart { +.dfg-topic-donut-chart { width: 100%; - height: 560px; + height: 440px; } -.topic-treemap-empty { +.dfg-topic-donut-empty { display: grid; min-height: 260px; margin: 0; diff --git a/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.ts b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.ts new file mode 100644 index 00000000..09e88311 --- /dev/null +++ b/webapp/src/app/modules/dashboard/dfg-topic-donut/dfg-topic-donut.component.ts @@ -0,0 +1,113 @@ +import { Component, Input, OnChanges } from '@angular/core'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; + +import { DfgProjectTopic } from '../dashboard-statistics.service'; + +@Component({ + selector: 'app-dfg-topic-donut', + imports: [NgxEchartsDirective], + templateUrl: './dfg-topic-donut.component.html', + styleUrl: './dfg-topic-donut.component.scss', +}) +export class DfgTopicDonutComponent implements OnChanges { + @Input() topics: DfgProjectTopic[] = []; + + options: EChartsOption = {}; + + ngOnChanges(): void { + this.options = { + color: [ + '#7255d9', + '#2563eb', + '#0891b2', + '#059669', + '#65a30d', + '#ca8a04', + '#ea580c', + '#dc2626', + '#db2777', + '#9333ea', + ], + tooltip: { + trigger: 'item', + confine: true, + formatter: (params: any) => + `${this.escapeHtml(String(params.name ?? ''))}- {{ loading ? 'Wird geladen ...' : 'Keine Field-Daten vorhanden.' }} -
-} diff --git a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts b/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts deleted file mode 100644 index d124c1d4..00000000 --- a/webapp/src/app/modules/dashboard/topic-heatmap/topic-heatmap.component.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { Component, Input, OnChanges } from '@angular/core'; -import { EChartsOption } from 'echarts'; -import { NgxEchartsDirective } from 'ngx-echarts'; - -import { TopicHeatmap } from '../dashboard-statistics.service'; - -@Component({ - selector: 'app-topic-heatmap', - imports: [NgxEchartsDirective], - templateUrl: './topic-heatmap.component.html', - styleUrl: './topic-heatmap.component.scss', -}) -export class TopicHeatmapComponent implements OnChanges { - @Input() heatmap?: TopicHeatmap; - @Input() loading = false; - - options: EChartsOption = {}; - private readonly colors = [ - '#2563eb', - '#059669', - '#d97706', - '#dc2626', - '#7c3aed', - '#0284c7', - '#ea580c', - '#4f46e5', - '#0f766e', - '#be123c', - ]; - - ngOnChanges(): void { - this.options = this.buildOptions(); - } - - private buildOptions(): EChartsOption { - const fields = this.heatmap?.fields ?? []; - const data = fields.map((field) => ({ - id: field.id, - name: field.name, - value: field.total || this.totalCount(field.values), - label: { - show: true, - formatter: (params: any) => - `${params.name}\n${this.formatCount(params.value)}`, - color: '#ffffff', - fontWeight: 700, - lineHeight: 18, - overflow: 'truncate' as const, - }, - children: field.values - .filter((value) => value.count > 0) - .map((value) => ({ - name: String(value.year), - value: value.count, - share: value.share, - })), - })); - - return { - tooltip: { - formatter: (params: any) => { - const count = Number(params.value ?? 0); - const share = - typeof params.data?.share === 'number' - ? `Die wichtigsten Begriffe zum ausgewählten Forschungsthema
+Die Schriftgröße entspricht der Anzahl der Publikationen.
++ {{ loading ? 'Wird geladen ...' : 'Keine Field-Daten vorhanden.' }} +
+} diff --git a/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.scss b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.scss new file mode 100644 index 00000000..2d97dea6 --- /dev/null +++ b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.scss @@ -0,0 +1,36 @@ +.topic-treemap-chart { + width: 100%; + height: 560px; +} + +.topic-treemap-breadcrumbs { + display: flex; + align-items: center; + gap: 0.4rem; + min-height: 2rem; + margin-bottom: 0.5rem; + color: #64748b; + + button { + padding: 0; + border: 0; + background: transparent; + color: #2563eb; + font: inherit; + cursor: pointer; + + &:disabled { + color: #334155; + font-weight: 700; + cursor: default; + } + } +} + +.topic-treemap-empty { + display: grid; + min-height: 260px; + margin: 0; + place-items: center; + color: #64748b; +} diff --git a/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.ts b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.ts new file mode 100644 index 00000000..9b31a0b5 --- /dev/null +++ b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.ts @@ -0,0 +1,434 @@ +import { + Component, + EventEmitter, + Input, + OnChanges, + Output, + SimpleChanges, +} from '@angular/core'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; + +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; +import { + TopicTreemapData, + TopicTreemapTopicSelect, +} from './topic-treemap.models'; + +export { + TopicTreemapData, + TopicTreemapField, + TopicTreemapSubfield, + TopicTreemapTopic, + TopicTreemapTopicSelect, + TopicTreemapValue, +} from './topic-treemap.models'; + +interface TreemapBreadcrumb { + label: string; + nodeId?: string; +} + +@Component({ + selector: 'app-topic-treemap', + imports: [NgxEchartsDirective], + templateUrl: './topic-treemap.component.html', + styleUrl: './topic-treemap.component.scss', +}) +export class TopicTreemapComponent implements OnChanges { + private readonly fieldColorOpacity = 0.78; + @Input() data?: TopicTreemapData; + @Input() loading = false; + @Input() selectedNodeId?: string; + @Output() selectedNodeIdChange = new EventEmitter