fix-analyses-dashboard #241

Merged
farajollahi merged 8 commits from fix-analyses-dashboard into dev 2026-07-24 21:07:05 +02:00
29 changed files with 3036 additions and 696 deletions
@@ -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
+61 -1
View File
@@ -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]
+96
View File
@@ -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,
)
+605 -132
View File
@@ -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 []
@@ -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,
)
+447 -163
View File
@@ -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)
@@ -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:
+3
View File
@@ -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"
@@ -13,7 +13,7 @@ import { TopAuthor } from './topAuthor';
export interface TopAuthorStatistics {
institution_id: string;
works: Array<TopAuthor>;
projects: Array<TopAuthor>;
eu_projects: Array<TopAuthor>;
patents: Array<TopAuthor>;
news: Array<TopAuthor>;
}
@@ -3,6 +3,7 @@ import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Configuration } from '../../api';
import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models';
export type TopAuthorsWorksPeriod = 'all_time' | 'last_5_years';
@@ -11,6 +12,7 @@ export interface DashboardStatistics {
organization_name: string;
publications: number;
persons: number;
patents: number;
projects: number;
dfg_projects: number;
eu_projects: number;
@@ -23,6 +25,39 @@ export interface DashboardStatisticValue {
value: number;
}
export interface EuProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
export interface BmbfProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
export interface DfgProjectTopic {
id: string;
name: string;
subfield?: string | null;
field?: string | null;
domain?: string | null;
project_count: number;
}
export interface DfgProjectTopics {
institution_id: string;
organization_name: string;
project_count: number;
matched_project_count: number;
topics: DfgProjectTopic[];
}
export interface TopAuthor {
id?: string | null;
name: string;
@@ -32,29 +67,20 @@ export interface TopAuthor {
export interface TopAuthorStatistics {
institution_id: string;
works: TopAuthor[];
projects: TopAuthor[];
eu_projects: TopAuthor[];
patents: TopAuthor[];
news: TopAuthor[];
}
export interface TopicHeatmapValue {
year: number;
count: number;
share: number;
}
export interface TopicHeatmapField {
export interface TopicWordCloudWord {
id: string;
name: string;
total: number;
values: TopicHeatmapValue[];
count: number;
}
export interface TopicHeatmap {
institution_id: string;
organization_name: string;
years: number[];
fields: TopicHeatmapField[];
export interface TopicWordCloud {
topic_id: string;
words: TopicWordCloudWord[];
}
@Injectable({ providedIn: 'root' })
@@ -80,12 +106,30 @@ export class DashboardStatisticsService {
);
}
getPatentCount(): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/patents`,
);
}
getEuProjectCount(): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/eu`,
);
}
getEuProjectStatuses(): Observable<EuProjectStatusStatistics> {
return this.httpClient.get<EuProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/eu/status`,
);
}
getBmbfProjectStatuses(): Observable<BmbfProjectStatusStatistics> {
return this.httpClient.get<BmbfProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/bmbf/status`,
);
}
getBmbfProjectCount(): Observable<DashboardStatisticValue> {
return this.httpClient.get<DashboardStatisticValue>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/statistics/projects/bmbf`,
@@ -98,6 +142,12 @@ export class DashboardStatisticsService {
);
}
getDfgProjectTopics(): Observable<DfgProjectTopics> {
return this.httpClient.get<DfgProjectTopics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/topics`,
);
}
getTopAuthors(
worksPeriod: TopAuthorsWorksPeriod = 'all_time',
): Observable<TopAuthorStatistics> {
@@ -109,17 +159,31 @@ export class DashboardStatisticsService {
);
}
getTopicHeatmap(
getTopicTreemap(
fromYear?: number,
toYear?: number,
): Observable<TopicHeatmap> {
): Observable<TopicTreemapData> {
const params: Record<string, number> = {};
if (fromYear !== undefined) params['from_year'] = fromYear;
if (toYear !== undefined) params['to_year'] = toYear;
return this.httpClient.get<TopicHeatmap>(
return this.httpClient.get<TopicTreemapData>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/topic-heatmap`,
{ params },
);
}
getTopicWordCloud(
topicId: string,
fromYear?: number,
toYear?: number,
): Observable<TopicWordCloud> {
const params: Record<string, string | number> = { topicId };
if (fromYear !== undefined) params['from_year'] = fromYear;
if (toYear !== undefined) params['to_year'] = toYear;
return this.httpClient.get<TopicWordCloud>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/topic-wordcloud`,
{ params },
);
}
}
@@ -23,6 +23,27 @@
</div>
</a>
<a
class="statistics-card"
[routerLink]="['/institution', institutionRouteId(), 'patents']"
[class.disabled]="!institutionRouteId()"
[attr.aria-disabled]="!institutionRouteId()"
[attr.aria-label]="'Patente von ' + organizationName() + ' anzeigen'">
<div class="statistics-icon statistics-icon--patents">
<mat-icon>description</mat-icon>
</div>
<div>
<span>Patente</span>
<strong>
{{
isStatisticLoading('patents')
? '…'
: ((statistics?.patents | number) ?? '–')
}}
</strong>
</div>
</a>
<a
class="statistics-card"
routerLink="/persons"
@@ -108,67 +129,137 @@
<p class="statistics-error">Die Kennzahlen konnten nicht geladen werden.</p>
}
@if (topicHeatmapLoading || topicHeatmapError || hasTopicHeatmapData()) {
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
euProjectStatusesError ||
bmbfProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses)
) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Projektstatus nach Fördergeber</h2>
<p>
Laufende, kommende und abgeschlossene EU- und Bund-Projekte Ihrer Organisation.
</p>
</div>
@if (euProjectStatuses && bmbfProjectStatuses) {
<div class="project-status-summary">
<span>
EU:
{{
euProjectStatuses.ongoing +
euProjectStatuses.upcoming +
euProjectStatuses.completed | number
}}
</span>
<span>
Bund:
{{
bmbfProjectStatuses.ongoing +
bmbfProjectStatuses.upcoming +
bmbfProjectStatuses.completed | number
}}
</span>
</div>
}
</header>
@if (euProjectStatusesLoading || bmbfProjectStatusesLoading) {
<div class="project-status-loading" role="status" aria-live="polite">
<app-loading
text="Projektstatus wird geladen …"
icon="stacked_bar_chart"
size="64"
diameter="64"></app-loading>
</div>
} @else if (euProjectStatusesError || bmbfProjectStatusesError) {
<p class="statistics-error">
Der Status der EU- und Bund-Projekte konnte nicht geladen werden.
</p>
} @else if (euProjectStatuses && bmbfProjectStatuses) {
<app-eu-project-status-chart
[statuses]="euProjectStatuses"
[bmbfStatuses]="bmbfProjectStatuses"></app-eu-project-status-chart>
}
</section>
}
@if (topicTreemapLoading || topicTreemapError || hasTopicTreemapData()) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Field Treemap</h2>
<p>Publikationen Ihrer Organisation nach Field.</p>
</div>
<div class="topic-treemap-period-controls" aria-label="Zeitraum">
<div class="topic-treemap-period-toggle">
<button
type="button"
[class.active]="topicTreemapPeriod === 'last_5_years'"
(click)="setTopicTreemapPeriod('last_5_years')">
5 Jahre
</button>
<button
type="button"
[class.active]="topicTreemapPeriod === 'last_10_years'"
(click)="setTopicTreemapPeriod('last_10_years')">
10 Jahre
</button>
<button
type="button"
[class.active]="topicTreemapPeriod === 'all_time'"
(click)="setTopicTreemapPeriod('all_time')">
Alle
</button>
</div>
<label>
Von
<input
type="number"
min="1900"
max="2100"
[value]="topicTreemapFromYear"
(change)="
onTopicTreemapYearChange('from', $any($event.target).value)
" />
</label>
<label>
Bis
<input
type="number"
min="1900"
max="2100"
[value]="topicTreemapToYear"
(change)="
onTopicTreemapYearChange('to', $any($event.target).value)
" />
</label>
<div class="topic-treemap-year-slider">
<app-year-range-slider
[minYear]="topicTreemapMinYear"
[maxYear]="topicTreemapMaxYear"
[(startYear)]="topicTreemapFromYear"
[(endYear)]="topicTreemapToYear"
(startYearChange)="onTopicTreemapRangeChange()"
(endYearChange)="onTopicTreemapRangeChange()">
</app-year-range-slider>
</div>
</header>
@if (topicHeatmapError) {
@if (topicTreemapLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="Treemap-Daten für den gewählten Zeitraum werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (topicTreemapError) {
<p class="statistics-error">
Die Field-Treemap konnte nicht geladen werden.
</p>
} @else {
<app-topic-heatmap
[heatmap]="topicHeatmap"
[loading]="topicHeatmapLoading"></app-topic-heatmap>
<app-topic-treemap
[data]="topicTreemap"
[selectedNodeId]="selectedTopicTreemapNode"
(selectedNodeIdChange)="onTopicTreemapNodeChange($event)"
(topicSelect)="onTopicTreemapTopicSelect($event)">
</app-topic-treemap>
}
</section>
}
@if (dfgTopicsLoading || dfgTopicsError || dfgProjectTopics) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>DFG-Projekt-Topics</h2>
<p>
Verteilung der gematchten Topics aus den DFG-Projekten Ihrer Organisation.
</p>
</div>
@if (dfgProjectTopics) {
<p class="dfg-topic-summary">
{{ dfgProjectTopics.matched_project_count | number }} von
{{ dfgProjectTopics.project_count | number }} Projekten gematcht
</p>
}
</header>
@if (dfgTopicsLoading) {
<div class="topic-heatmap-loading" role="status" aria-live="polite">
<app-loading
text="DFG-Topics werden geladen …"
icon="account_tree"
size="72"
diameter="72"></app-loading>
</div>
} @else if (dfgTopicsError) {
<p class="statistics-error">
Das DFG-Topic-Diagramm konnte nicht geladen werden.
</p>
} @else {
<app-dfg-topic-donut
[topics]="dfgProjectTopics?.topics ?? []"></app-dfg-topic-donut>
}
</section>
}
@@ -73,6 +73,11 @@
color: #15803d;
}
&--patents {
background: #fee2e2;
color: #b91c1c;
}
&--eu-projects {
background: #e0f2fe;
color: #0369a1;
@@ -129,68 +134,41 @@
}
}
.topic-treemap-period-controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.65rem;
.topic-treemap-year-slider {
width: min(100%, 34rem);
}
label {
display: inline-flex;
align-items: center;
gap: 0.35rem;
.topic-heatmap-loading {
min-height: 25rem;
display: grid;
place-items: center;
}
.project-status-loading {
min-height: 15rem;
display: grid;
place-items: center;
}
.project-status-summary {
display: flex;
flex: 0 0 auto;
gap: 0.5rem;
span {
padding: 0.35rem 0.65rem;
border-radius: 999px;
background: #f1f5f9;
color: #475569;
font-size: 0.9rem;
font-weight: 600;
}
input {
width: 5.5rem;
padding: 0.45rem 0.55rem;
border: 1px solid #cbd5e1;
border-radius: 6px;
color: #0f172a;
font: inherit;
&:focus {
border-color: #93c5fd;
outline: 3px solid #bfdbfe;
outline-offset: 0;
}
}
}
.topic-treemap-period-toggle {
display: inline-flex;
overflow: hidden;
border: 1px solid #cbd5e1;
border-radius: 6px;
background: #fff;
button {
padding: 0.5rem 0.7rem;
border: 0;
border-right: 1px solid #cbd5e1;
background: transparent;
color: #334155;
cursor: pointer;
font: inherit;
font-weight: 600;
&:last-child {
border-right: 0;
}
&.active {
background: #1d4ed8;
color: #fff;
}
&:focus-visible {
outline: 3px solid #93c5fd;
outline-offset: -3px;
}
}
.dfg-topic-summary {
flex: 0 0 auto;
color: #475569;
font-weight: 600;
}
.top-authors-header {
@@ -2,16 +2,33 @@ import { Component, OnInit } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { Observable, finalize } from 'rxjs';
import { RouterLink } from '@angular/router';
import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { DfgTopicDonutComponent } from './dfg-topic-donut/dfg-topic-donut.component';
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';
import {
TopicTreemapComponent,
} from '../../shared/ui/topic-treemap/topic-treemap.component';
import {
TopicTreemapData,
TopicTreemapTopicSelect,
} from '../../shared/ui/topic-treemap/topic-treemap.models';
import {
TopicWordCloudDialogComponent,
TopicWordCloudDialogData,
} from './topic-wordcloud-dialog/topic-wordcloud-dialog.component';
import {
BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
DashboardStatisticsService,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthor,
TopAuthorStatistics,
TopAuthorsWorksPeriod,
TopicHeatmap,
} from './dashboard-statistics.service';
import {
activeInstitutionPersonListQueryParams,
@@ -20,18 +37,22 @@ import {
type DashboardStatisticKey =
| 'publications'
| 'persons'
| 'patents'
| 'eu_projects'
| 'bmbf_projects'
| 'dfg_projects';
type TopicTreemapPeriod =
| 'last_5_years'
| 'last_10_years'
| 'all_time'
| 'custom';
@Component({
selector: 'dashboard',
imports: [DecimalPipe, MatIconModule, RouterLink, TopicHeatmapComponent],
imports: [
DecimalPipe,
MatIconModule,
RouterLink,
LoadingComponent,
DfgTopicDonutComponent,
EuProjectStatusChartComponent,
TopicTreemapComponent,
YearRangeSliderComponent,
],
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.scss',
})
@@ -42,6 +63,7 @@ export class DashboardComponent implements OnInit {
statisticLoading: Record<DashboardStatisticKey, boolean> = {
publications: false,
persons: false,
patents: false,
eu_projects: false,
bmbf_projects: false,
dfg_projects: false,
@@ -49,6 +71,7 @@ export class DashboardComponent implements OnInit {
statisticErrors: Record<DashboardStatisticKey, boolean> = {
publications: false,
persons: false,
patents: false,
eu_projects: false,
bmbf_projects: false,
dfg_projects: false,
@@ -58,19 +81,41 @@ export class DashboardComponent implements OnInit {
topAuthorsLoading = false;
topAuthorsError = false;
topAuthorsWorksPeriod: TopAuthorsWorksPeriod = 'all_time';
topicHeatmap?: TopicHeatmap;
topicHeatmapLoading = false;
topicHeatmapError = false;
topicTreemapPeriod: TopicTreemapPeriod = 'last_5_years';
topicTreemapFromYear = new Date().getFullYear() - 4;
topicTreemapToYear = new Date().getFullYear();
topicTreemap?: TopicTreemapData;
topicTreemapLoading = false;
topicTreemapError = false;
dfgProjectTopics?: DfgProjectTopics;
dfgTopicsLoading = false;
dfgTopicsError = false;
euProjectStatuses?: EuProjectStatusStatistics;
euProjectStatusesLoading = false;
euProjectStatusesError = false;
bmbfProjectStatuses?: BmbfProjectStatusStatistics;
bmbfProjectStatusesLoading = false;
bmbfProjectStatusesError = false;
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
topicTreemapFromYear = this.topicTreemapMaxYear - 4;
topicTreemapToYear = this.topicTreemapMaxYear;
selectedTopicTreemapNode?: string;
private topicTreemapReloadQueued = false;
private topicTreemapRequestId = 0;
constructor(private statisticsService: DashboardStatisticsService) {}
constructor(
private statisticsService: DashboardStatisticsService,
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
) {}
ngOnInit() {
this.restoreTopicTreemapState();
this.loadStatistics();
this.loadTopAuthors();
this.loadTopicHeatmap();
this.loadTopicTreemap();
this.loadDfgProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
}
private loadStatistics(): void {
@@ -80,6 +125,7 @@ export class DashboardComponent implements OnInit {
this.statisticsService.getPublicationCount(),
);
this.loadStatistic('persons', this.statisticsService.getPersonCount());
this.loadStatistic('patents', this.statisticsService.getPatentCount());
this.loadStatistic(
'eu_projects',
this.statisticsService.getEuProjectCount(),
@@ -109,6 +155,11 @@ export class DashboardComponent implements OnInit {
icon: 'menu_book',
entries: this.topAuthors?.works ?? [],
},
{
title: 'EU-Projekte',
icon: 'public',
entries: this.topAuthors?.eu_projects ?? [],
},
{
title: 'Patente',
icon: 'description',
@@ -135,13 +186,17 @@ export class DashboardComponent implements OnInit {
);
}
hasTopicHeatmapData(): boolean {
return (this.topicHeatmap?.fields ?? []).some(
hasTopicTreemapData(): boolean {
return (this.topicTreemap?.fields ?? []).some(
(field) =>
field.total > 0 || field.values.some((value) => value.count > 0),
);
}
hasDfgTopicData(): boolean {
return (this.dfgProjectTopics?.topics.length ?? 0) > 0;
}
setTopAuthorsWorksPeriod(period: TopAuthorsWorksPeriod): void {
if (period === this.topAuthorsWorksPeriod) return;
this.topAuthorsWorksPeriod = period;
@@ -172,35 +227,71 @@ export class DashboardComponent implements OnInit {
);
}
setTopicTreemapPeriod(period: TopicTreemapPeriod): void {
if (period === this.topicTreemapPeriod && period !== 'custom') return;
const currentYear = new Date().getFullYear();
this.topicTreemapPeriod = period;
if (period === 'last_5_years') {
this.topicTreemapFromYear = currentYear - 4;
this.topicTreemapToYear = currentYear;
} else if (period === 'last_10_years') {
this.topicTreemapFromYear = currentYear - 9;
this.topicTreemapToYear = currentYear;
} else if (period === 'all_time') {
this.topicTreemapFromYear = 1900;
this.topicTreemapToYear = currentYear;
}
this.loadTopicHeatmap();
onTopicTreemapRangeChange(): void {
this.topicTreemapLoading = true;
this.topicTreemapError = false;
this.topicTreemapRequestId += 1;
this.updateTopicTreemapUrl();
if (this.topicTreemapReloadQueued) return;
this.topicTreemapReloadQueued = true;
setTimeout(() => {
this.topicTreemapReloadQueued = false;
this.loadTopicTreemap();
});
}
onTopicTreemapYearChange(field: 'from' | 'to', value: string): void {
const year = Number(value);
if (!Number.isInteger(year)) return;
onTopicTreemapNodeChange(nodeId: string | undefined): void {
this.selectedTopicTreemapNode = nodeId;
this.updateTopicTreemapUrl();
}
if (field === 'from') {
this.topicTreemapFromYear = year;
} else {
this.topicTreemapToYear = year;
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
TopicWordCloudDialogComponent,
{
width: '85vw',
maxWidth: '92vw',
data: topic,
},
);
}
private restoreTopicTreemapState(): void {
const params = this.route.snapshot.queryParamMap;
this.topicTreemapFromYear = this.parseTreemapYear(
params.get('treemapFrom'),
this.topicTreemapFromYear,
);
this.topicTreemapToYear = this.parseTreemapYear(
params.get('treemapTo'),
this.topicTreemapToYear,
);
if (this.topicTreemapFromYear > this.topicTreemapToYear) {
this.topicTreemapFromYear = this.topicTreemapToYear;
}
this.topicTreemapPeriod = 'custom';
this.loadTopicHeatmap();
this.selectedTopicTreemapNode = params.get('treemapNode') ?? undefined;
}
private updateTopicTreemapUrl(): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: {
treemapFrom: this.topicTreemapFromYear,
treemapTo: this.topicTreemapToYear,
treemapNode: this.selectedTopicTreemapNode ?? null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
private parseTreemapYear(value: string | null, fallback: number): number {
const year = Number(value);
return Number.isInteger(year) &&
year >= this.topicTreemapMinYear &&
year <= this.topicTreemapMaxYear
? year
: fallback;
}
private loadStatistic(
@@ -264,23 +355,83 @@ export class DashboardComponent implements OnInit {
});
}
private loadTopicHeatmap(): void {
private loadDfgProjectTopics(): void {
this.dfgTopicsLoading = true;
this.dfgTopicsError = false;
this.statisticsService
.getDfgProjectTopics()
.pipe(finalize(() => (this.dfgTopicsLoading = false)))
.subscribe({
next: (topics) => {
this.dfgProjectTopics = topics;
},
error: () => {
this.dfgTopicsError = true;
},
});
}
private loadEuProjectStatuses(): void {
this.euProjectStatusesLoading = true;
this.euProjectStatusesError = false;
this.statisticsService
.getEuProjectStatuses()
.pipe(finalize(() => (this.euProjectStatusesLoading = false)))
.subscribe({
next: (statuses) => {
this.euProjectStatuses = statuses;
},
error: () => {
this.euProjectStatusesError = true;
},
});
}
private loadBmbfProjectStatuses(): void {
this.bmbfProjectStatusesLoading = true;
this.bmbfProjectStatusesError = false;
this.statisticsService
.getBmbfProjectStatuses()
.pipe(finalize(() => (this.bmbfProjectStatusesLoading = false)))
.subscribe({
next: (statuses) => {
this.bmbfProjectStatuses = statuses;
},
error: () => {
this.bmbfProjectStatusesError = true;
},
});
}
private loadTopicTreemap(): void {
if (this.topicTreemapFromYear > this.topicTreemapToYear) {
this.topicHeatmapError = true;
this.topicTreemapLoading = false;
this.topicTreemapError = true;
return;
}
this.topicHeatmapLoading = true;
this.topicHeatmapError = false;
const requestId = ++this.topicTreemapRequestId;
this.topicTreemapLoading = true;
this.topicTreemapError = false;
this.statisticsService
.getTopicHeatmap(this.topicTreemapFromYear, this.topicTreemapToYear)
.pipe(finalize(() => (this.topicHeatmapLoading = false)))
.getTopicTreemap(this.topicTreemapFromYear, this.topicTreemapToYear)
.pipe(
finalize(() => {
if (requestId === this.topicTreemapRequestId) {
this.topicTreemapLoading = false;
}
}),
)
.subscribe({
next: (heatmap) => {
this.topicHeatmap = heatmap;
next: (treemap) => {
if (requestId === this.topicTreemapRequestId) {
this.topicTreemap = treemap;
}
},
error: () => {
this.topicHeatmapError = true;
if (requestId === this.topicTreemapRequestId) {
this.topicTreemapError = true;
}
},
});
}
@@ -0,0 +1,5 @@
@if (topics.length) {
<div echarts [options]="options" class="dfg-topic-donut-chart"></div>
} @else {
<p class="dfg-topic-donut-empty">Keine gematchten DFG-Topics vorhanden.</p>
}
@@ -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;
@@ -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) =>
`<strong>${this.escapeHtml(String(params.name ?? ''))}</strong><br>${Number(params.value ?? 0).toLocaleString('de-DE')} DFG-Projekte`,
},
legend: {
type: 'scroll',
orient: 'vertical',
top: 'middle',
right: 12,
width: '38%',
textStyle: { color: '#334155' },
formatter: (name: string) => this.truncate(name, 42),
},
graphic: [
{
type: 'text',
left: '30%',
top: '46%',
style: {
text: `${this.topics.length}\nTopics`,
align: 'center',
fill: '#0f172a',
fontSize: 18,
fontWeight: 700,
lineHeight: 25,
},
},
],
series: [
{
name: 'DFG-Topics',
type: 'pie',
radius: ['42%', '72%'],
center: ['32%', '50%'],
avoidLabelOverlap: true,
minAngle: 3,
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
borderRadius: 5,
},
label: { show: false },
emphasis: {
scaleSize: 8,
label: {
show: true,
formatter: '{b}\n{c} Projekte',
fontWeight: 700,
},
},
data: this.topics.map((topic) => ({
id: topic.id,
name: topic.name,
value: topic.project_count,
})),
},
],
};
}
private truncate(value: string, maximum: number): string {
return value.length > maximum
? `${value.slice(0, maximum - 1)}…`
: value;
}
private escapeHtml(value: string): string {
return value.replace(
/[&<>'"]/g,
(character) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
})[character] ?? character,
);
}
}
@@ -0,0 +1,6 @@
<div
echarts
[options]="options"
class="eu-project-status-chart"
role="img"
aria-label="Gestapeltes Balkendiagramm zum Status der EU- und Bund-Projekte"></div>
@@ -0,0 +1,4 @@
.eu-project-status-chart {
width: 100%;
height: 300px;
}
@@ -0,0 +1,108 @@
import { Component, Input, OnChanges } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import {
BmbfProjectStatusStatistics,
EuProjectStatusStatistics,
} from '../dashboard-statistics.service';
@Component({
selector: 'app-eu-project-status-chart',
imports: [NgxEchartsDirective],
templateUrl: './eu-project-status-chart.component.html',
styleUrl: './eu-project-status-chart.component.scss',
})
export class EuProjectStatusChartComponent implements OnChanges {
@Input({ required: true }) statuses!: EuProjectStatusStatistics;
@Input({ required: true }) bmbfStatuses!: BmbfProjectStatusStatistics;
options: EChartsOption = {};
ngOnChanges(): void {
const values = [
{
name: 'Laufend',
data: [
this.statuses?.ongoing ?? 0,
this.bmbfStatuses?.ongoing ?? 0,
],
color: '#2563eb',
},
{
name: 'Kommend',
data: [
this.statuses?.upcoming ?? 0,
this.bmbfStatuses?.upcoming ?? 0,
],
color: '#f59e0b',
},
{
name: 'Abgeschlossen',
data: [
this.statuses?.completed ?? 0,
this.bmbfStatuses?.completed ?? 0,
],
color: '#64748b',
},
];
this.options = {
color: values.map((item) => item.color),
animationDuration: 500,
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
confine: true,
valueFormatter: (value) =>
`${Number(value ?? 0).toLocaleString('de-DE')} Projekte`,
},
legend: {
top: 0,
left: 'center',
data: values.map((item) => item.name),
textStyle: { color: '#334155' },
},
grid: { top: 56, right: 24, bottom: 30, left: 24, containLabel: true },
xAxis: {
type: 'value',
minInterval: 1,
name: 'Anzahl Projekte',
nameLocation: 'middle',
nameGap: 28,
axisLabel: { color: '#64748b' },
splitLine: { lineStyle: { color: '#e2e8f0' } },
},
yAxis: {
type: 'category',
data: ['EU-Projekte', 'Bund-Projekte'],
axisTick: { show: false },
axisLine: { show: false },
axisLabel: { color: '#334155', fontWeight: 600 },
},
series: values.map((item, index) => ({
name: item.name,
type: 'bar',
stack: 'status',
barWidth: 54,
data: item.data,
label: {
show: true,
position: 'inside',
formatter: (params) =>
Number(params.value ?? 0) > 0 ? String(params.value) : '',
color: '#ffffff',
fontWeight: 700,
},
itemStyle: {
borderRadius:
index === 0
? [6, 0, 0, 6]
: index === values.length - 1
? [0, 6, 6, 0]
: 0,
},
})),
};
}
}
@@ -1,7 +0,0 @@
@if (heatmap?.fields?.length) {
<div echarts [options]="options" class="topic-treemap-chart"></div>
} @else {
<p class="topic-treemap-empty">
{{ loading ? 'Wird geladen ...' : 'Keine Field-Daten vorhanden.' }}
</p>
}
@@ -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'
? `<br />Anteil im Jahr: <strong>${(params.data.share * 100).toFixed(1)}%</strong>`
: '';
return `${params.name}<br /><strong>${count}</strong> Publikationen${share}`;
},
},
series: [
{
name: 'Fields',
type: 'treemap',
data,
roam: false,
nodeClick: 'zoomToNode',
sort: 'desc',
drillDownIcon: '',
breadcrumb: {
show: true,
bottom: 0,
height: 24,
left: 8,
right: 8,
emptyItemWidth: 80,
itemStyle: {
color: '#f8fafc',
borderColor: '#cbd5e1',
borderWidth: 1,
textStyle: {
color: '#334155',
fontWeight: 600,
},
},
emphasis: {
itemStyle: {
color: '#e0f2fe',
borderColor: '#93c5fd',
textStyle: {
color: '#0f172a',
fontWeight: 700,
},
},
},
},
color: this.colors,
colorMappingBy: 'id',
label: {
show: true,
formatter: (params: any) =>
`${params.name}\n${this.formatCount(params.value)}`,
color: '#ffffff',
fontWeight: 600,
lineHeight: 18,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
overflow: 'truncate',
},
upperLabel: {
show: true,
formatter: (params: any) =>
`${params.name} · ${this.formatCount(params.value)}`,
height: 30,
color: '#ffffff',
fontWeight: 700,
overflow: 'truncate',
},
levels: [
{
color: this.colors,
label: {
show: true,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
{
color: this.colors,
label: {
show: true,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
{
colorSaturation: [0.45, 0.78],
label: {
show: true,
formatter: (params: any) =>
`${params.name}\n${this.formatCount(params.value)}`,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
color: '#ffffff',
fontWeight: 700,
lineHeight: 18,
overflow: 'truncate',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 2,
gapWidth: 2,
},
},
],
leafDepth: 1,
top: 8,
right: 8,
bottom: 32,
left: 8,
animationDurationUpdate: 450,
emphasis: {
focus: 'self',
label: {
color: '#ffffff',
},
},
itemStyle: {
borderRadius: 4,
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
],
};
}
private totalCount(values: Array<{ count: number }>): number {
return values.reduce((sum, value) => sum + value.count, 0);
}
private formatCount(value: unknown): string {
return Number(value ?? 0).toLocaleString('de-DE');
}
}
@@ -0,0 +1,98 @@
<div class="dialog-title" mat-dialog-title>
<div class="dialog-heading">
<div>
<span class="dialog-eyebrow">Topic Insights</span>
<h2>Keyword Wordcloud</h2>
<p>Die wichtigsten Begriffe zum ausgewählten Forschungsthema</p>
</div>
</div>
<button
class="dialog-close"
mat-icon-button
type="button"
aria-label="Dialog schließen"
mat-dialog-close>
<mat-icon>close</mat-icon>
</button>
</div>
<mat-dialog-content>
<div class="topic-context-card" aria-label="Ausgewählte Themenhierarchie">
<div class="topic-context-item">
<span class="topic-context-icon topic-context-icon--field" aria-hidden="true">
<mat-icon>category</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Field</span>
<strong [title]="data.fieldName || ''">{{ data.fieldName || '–' }}</strong>
</span>
</div>
<mat-icon class="topic-context-arrow" aria-hidden="true">chevron_right</mat-icon>
<div class="topic-context-item">
<span class="topic-context-icon topic-context-icon--subfield" aria-hidden="true">
<mat-icon>account_tree</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Subfield</span>
<strong [title]="data.subfieldName || ''">{{ data.subfieldName || '–' }}</strong>
</span>
</div>
<mat-icon class="topic-context-arrow" aria-hidden="true">chevron_right</mat-icon>
<div class="topic-context-item topic-context-item--topic">
<span class="topic-context-icon topic-context-icon--topic" aria-hidden="true">
<mat-icon>label</mat-icon>
</span>
<span class="topic-context-copy">
<span class="topic-context-label">Topic</span>
<strong [title]="data.topicName">{{ data.topicName }}</strong>
</span>
</div>
</div>
<section class="word-cloud-panel" aria-labelledby="word-cloud-heading">
<div class="word-cloud-panel-header">
<div>
<h3 id="word-cloud-heading">Top Keywords</h3>
<p>Die Schriftgröße entspricht der Anzahl der Publikationen.</p>
</div>
@if (!loading && !loadFailed && words.length) {
<span class="word-count">{{ words.length }} Begriffe</span>
}
</div>
@if (loading) {
<div class="word-cloud-state">
<span class="state-icon state-icon--loading" aria-hidden="true">
<mat-icon>hourglass_top</mat-icon>
</span>
<strong>Wordcloud wird erstellt</strong>
<span>Die wichtigsten Keywords werden geladen …</span>
</div>
} @else if (loadFailed) {
<div class="word-cloud-state word-cloud-state--error">
<span class="state-icon" aria-hidden="true"><mat-icon>cloud_off</mat-icon></span>
<strong>Wordcloud nicht verfügbar</strong>
<span>Die Keywords konnten nicht geladen werden.</span>
</div>
} @else if (words.length) {
<div class="word-cloud-chart" aria-label="Wordcloud verwandter Themen">
@for (word of words; track word.id) {
<span
class="word-cloud-word"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[title]="word.name + ': ' + word.count + ' Publikationen'">
{{ word.name }}
</span>
}
</div>
} @else {
<div class="word-cloud-state">
<span class="state-icon" aria-hidden="true"><mat-icon>search_off</mat-icon></span>
<strong>Keine Keywords gefunden</strong>
<span>Für dieses Topic sind im gewählten Zeitraum keine Daten vorhanden.</span>
</div>
}
</section>
</mat-dialog-content>
@@ -0,0 +1,308 @@
.dialog-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
padding: 24px 28px 20px;
border-bottom: 1px solid var(--sg-border, #dde5f2);
background: linear-gradient(135deg, #ffffff 52%, #f6f0ff 100%);
h2 {
margin: 1px 0 3px;
color: var(--sg-text, #101a3d);
font-family: 'Montserrat', sans-serif;
font-size: 1.375rem;
font-weight: 700;
line-height: 1.25;
}
p {
margin: 0;
color: var(--sg-text-muted, #64708f);
font-size: 0.8125rem;
font-weight: 400;
}
}
.dialog-heading {
display: flex;
align-items: center;
}
.dialog-eyebrow {
display: block;
color: #7255d9;
font-size: 0.6875rem;
font-weight: 700;
letter-spacing: 0.08em;
line-height: 1.2;
text-transform: uppercase;
}
.dialog-close {
flex: 0 0 auto;
color: var(--sg-text-muted, #64708f);
&:hover {
background: #f1f3f7;
color: var(--sg-text, #101a3d);
}
}
mat-dialog-content {
min-height: 410px;
padding: 20px 28px 28px !important;
background: #ffffff;
}
.topic-context-card {
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto minmax(0, 1fr);
align-items: center;
gap: 12px;
margin-bottom: 18px;
padding: 12px;
border: 1px solid var(--sg-border, #dde5f2);
border-radius: 12px;
background: var(--sg-surface-muted, #f7f9ff);
}
.topic-context-item {
display: flex;
min-width: 0;
align-items: center;
gap: 10px;
padding: 5px 6px;
}
.topic-context-icon {
display: grid;
width: 34px;
height: 34px;
flex: 0 0 34px;
place-items: center;
border-radius: 9px;
mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
}
.topic-context-icon--field {
border: 1px solid #bdd4ff;
background: #f0f6ff;
color: #0b63ce;
}
.topic-context-icon--subfield {
border: 1px solid #bdebcf;
background: #effaf3;
color: #24834f;
}
.topic-context-icon--topic {
border: 1px solid #d8cafe;
background: #f6f0ff;
color: #7255d9;
}
.topic-context-copy {
display: flex;
min-width: 0;
flex-direction: column;
gap: 2px;
strong {
overflow: hidden;
color: #334155;
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.35;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.topic-context-item--topic strong {
color: #7255d9;
}
.topic-context-label {
color: var(--sg-text-soft, #8a95b3);
font-size: 0.625rem;
font-weight: 700;
letter-spacing: 0.07em;
line-height: 1.2;
text-transform: uppercase;
}
.topic-context-arrow {
width: 18px;
height: 18px;
color: #a8b2c8;
font-size: 18px;
}
.word-cloud-panel {
overflow: hidden;
border: 1px solid var(--sg-border, #dde5f2);
border-radius: 16px;
background: #ffffff;
box-shadow: var(--sg-shadow-sm);
}
.word-cloud-panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 18px;
border-bottom: 1px solid #e8edf5;
h3 {
margin: 0 0 2px;
color: var(--sg-text, #101a3d);
font-family: 'Montserrat', sans-serif;
font-size: 0.9375rem;
font-weight: 700;
}
p {
margin: 0;
color: var(--sg-text-muted, #64708f);
font-size: 0.75rem;
}
}
.word-count {
flex: 0 0 auto;
padding: 5px 9px;
border: 1px solid #d8cafe;
border-radius: 999px;
background: #f6f0ff;
color: #7255d9;
font-size: 0.6875rem;
font-weight: 700;
}
.word-cloud-chart {
display: flex;
min-height: 280px;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 14px 20px;
padding: 30px 34px;
background:
radial-gradient(circle at 15% 20%, rgba(114, 85, 217, 0.06), transparent 28%),
radial-gradient(circle at 85% 75%, rgba(11, 99, 206, 0.05), transparent 30%),
#ffffff;
}
.word-cloud-word {
padding: 3px 5px;
border-radius: 6px;
cursor: help;
line-height: 1.1;
text-align: center;
transition:
transform 150ms ease,
background-color 150ms ease;
&:hover {
background: rgba(241, 243, 247, 0.9);
transform: translateY(-2px);
}
}
.word-cloud-state {
display: flex;
min-height: 280px;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 6px;
padding: 24px;
color: var(--sg-text-muted, #64708f);
text-align: center;
strong {
margin-top: 4px;
color: var(--sg-text, #101a3d);
font-size: 0.9375rem;
}
> span:last-child {
font-size: 0.8125rem;
}
}
.state-icon {
display: grid;
width: 46px;
height: 46px;
place-items: center;
border-radius: 50%;
background: #f1f3f7;
color: #64708f;
}
.state-icon--loading {
background: #f6f0ff;
color: #7255d9;
animation: state-pulse 1.4s ease-in-out infinite;
}
.word-cloud-state--error .state-icon {
background: #fff1f5;
color: #d12f61;
}
@keyframes state-pulse {
50% {
box-shadow: 0 0 0 8px rgba(114, 85, 217, 0.08);
transform: scale(1.04);
}
}
@media (max-width: 700px) {
.dialog-title {
padding: 20px;
}
mat-dialog-content {
padding: 16px 20px 20px !important;
}
.topic-context-card {
grid-template-columns: 1fr;
gap: 4px;
}
.topic-context-arrow {
display: none;
}
.topic-context-copy strong {
white-space: normal;
}
.word-cloud-chart {
min-height: 240px;
gap: 10px 14px;
padding: 24px 18px;
}
}
@media (prefers-reduced-motion: reduce) {
.state-icon--loading {
animation: none;
}
.word-cloud-word {
transition: none;
}
}
@@ -0,0 +1,102 @@
import { CommonModule } from '@angular/common';
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
MAT_DIALOG_DATA,
MatDialogModule,
} from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import {
DashboardStatisticsService,
TopicWordCloudWord,
} from '../dashboard-statistics.service';
export interface TopicWordCloudDialogData {
topicId: string;
topicName: string;
fieldName?: string;
subfieldName?: string;
fromYear?: number;
toYear?: number;
}
interface DisplayWord extends TopicWordCloudWord {
color: string;
fontSize: number;
fontWeight: number;
}
@Component({
selector: 'app-topic-wordcloud-dialog',
standalone: true,
imports: [CommonModule, MatButtonModule, MatDialogModule, MatIconModule],
templateUrl: './topic-wordcloud-dialog.component.html',
styleUrl: './topic-wordcloud-dialog.component.scss',
})
export class TopicWordCloudDialogComponent {
readonly data = inject<TopicWordCloudDialogData>(MAT_DIALOG_DATA);
private readonly statisticsService = inject(DashboardStatisticsService);
private readonly destroyRef = inject(DestroyRef);
words: DisplayWord[] = [];
loading = true;
loadFailed = false;
private readonly colors = [
'#2563eb',
'#059669',
'#d97706',
'#dc2626',
'#7c3aed',
'#0284c7',
'#ea580c',
'#4f46e5',
'#0f766e',
'#be123c',
];
constructor() {
this.statisticsService
.getTopicWordCloud(
this.data.topicId,
this.data.fromYear,
this.data.toYear,
)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (response) => {
this.words = this.buildWords(response.words);
this.loading = false;
},
error: () => {
this.loading = false;
this.loadFailed = true;
},
});
}
private buildWords(words: TopicWordCloudWord[]): DisplayWord[] {
if (!words.length) return [];
const values = words.map((word) => word.count);
const minimum = Math.min(...values);
const maximum = Math.max(...values);
const scaled = words.map((word, index) => {
const intensity =
maximum === minimum ? 1 : (word.count - minimum) / (maximum - minimum);
return {
...word,
color: this.colors[index % this.colors.length],
fontSize: Math.round(14 + intensity * 24),
fontWeight: intensity > 0.66 ? 800 : intensity > 0.33 ? 600 : 400,
};
});
const centred: DisplayWord[] = [];
scaled.forEach((word, index) => {
if (index % 2 === 0) centred.push(word);
else centred.unshift(word);
});
return centred;
}
}
@@ -22,14 +22,17 @@ export type TopicChipColor = TopicChipPaletteColor | string;
export type TopicChipSize = 'normal' | 'mini';
export type TopicChipTooltipTarget = 'label' | 'button';
interface TopicChipColorTokens {
export interface TopicChipColorTokens {
border: string;
background: string;
activeBackground: string;
color: string;
}
const TOPIC_CHIP_COLORS: Record<TopicChipPaletteColor, TopicChipColorTokens> = {
export const TOPIC_CHIP_COLORS: Record<
TopicChipPaletteColor,
TopicChipColorTokens
> = {
purple: {
border: '#d8cafe',
background: '#f6f0ff',
@@ -0,0 +1,26 @@
@if (data?.fields?.length) {
@if (selectedNodeId) {
<nav class="topic-treemap-breadcrumbs" aria-label="Treemap-Navigation">
@for (item of breadcrumbs(); track item.nodeId ?? 'root'; let last = $last) {
<button
type="button"
[disabled]="last"
(click)="selectBreadcrumb(item.nodeId)">
{{ item.label }}
</button>
@if (!last) {
<span aria-hidden="true">›</span>
}
}
</nav>
}
<div
echarts
[options]="options"
class="topic-treemap-chart"
(chartClick)="onChartClick($event)"></div>
} @else {
<p class="topic-treemap-empty">
{{ loading ? 'Wird geladen ...' : 'Keine Field-Daten vorhanden.' }}
</p>
}
@@ -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;
}
@@ -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<string | undefined>();
@Output() topicSelect = new EventEmitter<TopicTreemapTopicSelect>();
options: EChartsOption = {};
ngOnChanges(changes: SimpleChanges): void {
if (changes['data'] || changes['selectedNodeId']) {
this.options = this.buildOptions();
}
}
onChartClick(event: any): void {
const data = event?.data;
const selectedNodeId = data?.nodeId ?? this.nodeIdFromTreePath(event);
this.selectedNodeIdChange.emit(selectedNodeId);
if (!data?.id || !data?.subfieldName || data?.children?.length) return;
this.topicSelect.emit({
topicId: data.entityId,
topicName: data.name,
fieldName: data.fieldName,
subfieldName: data.subfieldName,
fromYear: this.data?.years.at(0),
toYear: this.data?.years.at(-1),
});
}
breadcrumbs(): TreemapBreadcrumb[] {
const result: TreemapBreadcrumb[] = [{ label: 'Fields' }];
if (!this.selectedNodeId || !this.data) return result;
for (const field of this.data.fields) {
const fieldNodeId = `field:${field.id}`;
if (this.selectedNodeId === fieldNodeId) {
return [...result, { label: field.name, nodeId: fieldNodeId }];
}
for (const subfield of field.subfields) {
const subfieldNodeId = `subfield:${subfield.id}`;
const topic = subfield.topics.find(
(entry) => `topic:${entry.id}` === this.selectedNodeId,
);
if (this.selectedNodeId === subfieldNodeId || topic) {
return [
...result,
{ label: field.name, nodeId: fieldNodeId },
{ label: subfield.name, nodeId: subfieldNodeId },
...(topic
? [{ label: topic.name, nodeId: `topic:${topic.id}` }]
: []),
];
}
}
}
return result;
}
selectBreadcrumb(nodeId?: string): void {
this.selectedNodeIdChange.emit(nodeId);
}
private buildOptions(): EChartsOption {
const fields = this.data?.fields ?? [];
const hierarchyData = fields.map((field) => {
const fieldColor = topicHierarchyColor({
field_id: field.id,
field_name: field.name,
});
return {
id: `field:${field.id}`,
entityId: field.id,
nodeId: `field:${field.id}`,
name: field.name,
value: field.total || this.totalCount(field.values),
itemStyle: {
color: fieldColor,
opacity: this.fieldColorOpacity,
},
emphasis: {
itemStyle: {
color: fieldColor,
opacity: this.fieldColorOpacity,
},
},
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.subfields ?? [])
.filter((subfield) => subfield.total > 0)
.map((subfield) => ({
id: `subfield:${subfield.id}`,
entityId: subfield.id,
nodeId: `subfield:${subfield.id}`,
name: subfield.name,
value: subfield.total,
fieldName: field.name,
itemStyle: {
color: fieldColor,
opacity: this.fieldColorOpacity,
},
emphasis: {
itemStyle: {
color: fieldColor,
opacity: this.fieldColorOpacity,
},
},
children: (subfield.topics ?? [])
.filter((topic) => topic.total > 0)
.map((topic) => ({
id: `topic:${topic.id}`,
entityId: topic.id,
nodeId: `topic:${topic.id}`,
name: topic.name,
value: topic.total,
fieldName: field.name,
subfieldName: subfield.name,
itemStyle: {
color: fieldColor,
opacity: this.fieldColorOpacity,
},
emphasis: {
itemStyle: {
color: fieldColor,
opacity: this.fieldColorOpacity,
},
},
})),
})),
};
});
const data = this.visibleData(hierarchyData);
return {
tooltip: {
trigger: 'item',
confine: true,
backgroundColor: '#ffffff',
borderColor: '#d8cafe',
borderWidth: 1,
padding: 0,
extraCssText:
'max-width: 360px; border-radius: 12px; box-shadow: 0 14px 36px rgba(16, 26, 61, 0.18);',
formatter: (params: any) => {
const count = Number(params.value ?? 0);
const name = this.escapeHtml(String(params.name ?? ''));
const fieldName = params.data?.fieldName
? this.escapeHtml(String(params.data.fieldName))
: '';
const subfieldName = params.data?.subfieldName
? this.escapeHtml(String(params.data.subfieldName))
: '';
const hierarchy = [fieldName, subfieldName]
.filter(Boolean)
.map(
(item) =>
`<span style="display:inline-flex;align-items:center;gap:4px;">${item}</span>`,
)
.join('<span style="color:#a8b2c8;padding:0 3px;">›</span>');
return `
<div style="min-width:220px;padding:14px 16px;white-space:normal;">
${
hierarchy
? `<div style="margin-bottom:7px;color:#64708f;font-size:11px;line-height:1.4;">${hierarchy}</div>`
: ''
}
<div style="color:#101a3d;font-size:15px;font-weight:700;line-height:1.4;overflow-wrap:anywhere;">${name}</div>
<div style="display:flex;align-items:baseline;gap:5px;margin-top:10px;color:#64708f;font-size:12px;">
<strong style="color:#7255d9;font-size:16px;">${this.formatCount(count)}</strong>
Publikationen
</div>
<div style="margin-top:9px;padding-top:9px;border-top:1px solid #edf0f6;color:#8a95b3;font-size:11px;">
Klicken, um diesen Bereich zu vergrößern
</div>
</div>`;
},
},
series: [
{
name: 'Fields',
type: 'treemap',
data,
roam: false,
nodeClick: false,
sort: 'desc',
drillDownIcon: '',
breadcrumb: {
show: false,
bottom: 0,
height: 24,
left: 8,
right: 8,
emptyItemWidth: 80,
itemStyle: {
color: '#f8fafc',
borderColor: '#cbd5e1',
borderWidth: 1,
textStyle: {
color: '#334155',
fontWeight: 600,
},
},
emphasis: {
itemStyle: {
color: '#e0f2fe',
borderColor: '#93c5fd',
textStyle: {
color: '#0f172a',
fontWeight: 700,
},
},
},
},
label: {
show: true,
formatter: (params: any) =>
`${params.name}\n${this.formatCount(params.value)}`,
color: '#ffffff',
fontWeight: 600,
lineHeight: 18,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
overflow: 'truncate',
},
upperLabel: {
show: true,
formatter: (params: any) =>
`${params.name} · ${this.formatCount(params.value)}`,
height: 30,
color: '#ffffff',
fontWeight: 700,
overflow: 'truncate',
},
levels: [
{
label: {
show: true,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
{
label: {
show: true,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
{
label: {
show: true,
formatter: (params: any) =>
`${params.name}\n${this.formatCount(params.value)}`,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
color: '#ffffff',
fontWeight: 700,
lineHeight: 18,
overflow: 'truncate',
},
upperLabel: { show: false },
itemStyle: {
borderColor: '#ffffff',
borderWidth: 2,
gapWidth: 2,
},
},
],
leafDepth: 1,
top: 8,
right: 8,
bottom: 32,
left: 8,
animationDurationUpdate: 450,
emphasis: {
label: {
color: '#ffffff',
fontSize: 15,
fontWeight: 800,
textShadowBlur: 4,
textShadowColor: 'rgba(15, 23, 42, 0.45)',
},
itemStyle: {
borderColor: '#ffffff',
borderWidth: 5,
shadowBlur: 18,
shadowColor: 'rgba(15, 23, 42, 0.35)',
},
},
itemStyle: {
borderRadius: 4,
borderColor: '#ffffff',
borderWidth: 3,
gapWidth: 3,
},
},
],
};
}
private visibleData(hierarchyData: any[]): any[] {
if (!this.selectedNodeId) return hierarchyData;
if (this.selectedNodeId.startsWith('field:')) {
const field = hierarchyData.find(
(entry) => entry.nodeId === this.selectedNodeId,
);
return field?.children ?? hierarchyData;
}
const subfieldNodeId = this.selectedNodeId.startsWith('subfield:')
? this.selectedNodeId
: this.subfieldNodeIdForTopic(this.selectedNodeId);
for (const field of hierarchyData) {
const subfield = field.children?.find(
(entry: any) => entry.nodeId === subfieldNodeId,
);
if (subfield) return subfield.children ?? [];
}
return hierarchyData;
}
private subfieldNodeIdForTopic(topicNodeId: string): string | undefined {
if (!topicNodeId.startsWith('topic:') || !this.data) return undefined;
const topicId = topicNodeId.slice('topic:'.length);
for (const field of this.data.fields) {
const subfield = field.subfields.find((entry) =>
entry.topics.some((topic) => topic.id === topicId),
);
if (subfield) return `subfield:${subfield.id}`;
}
return undefined;
}
private nodeIdFromTreePath(event: any): string | undefined {
const path = (event?.treePathInfo ?? [])
.map((entry: { name?: string }) => entry.name)
.filter(Boolean);
if (path.length <= 1 || !this.data) return undefined;
const field = this.data.fields.find((entry) => entry.name === path[1]);
if (!field) return undefined;
const subfield = field.subfields.find((entry) => entry.name === path[2]);
if (!subfield) return `field:${field.id}`;
const topic = subfield.topics.find((entry) => entry.name === path[3]);
return topic ? `topic:${topic.id}` : `subfield:${subfield.id}`;
}
private totalCount(values: Array<{ count: number }>): number {
return values.reduce((sum, value) => sum + value.count, 0);
}
private formatCount(value: unknown): string {
return Number(value ?? 0).toLocaleString('de-DE');
}
private escapeHtml(value: string): string {
return value.replace(
/[&<>'"]/g,
(character) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
})[character] ?? character,
);
}
}
@@ -0,0 +1,44 @@
export interface TopicTreemapValue {
year: number;
count: number;
share: number;
}
export interface TopicTreemapTopic {
id: string;
name: string;
total: number;
values: TopicTreemapValue[];
}
export interface TopicTreemapSubfield {
id: string;
name: string;
total: number;
values: TopicTreemapValue[];
topics: TopicTreemapTopic[];
}
export interface TopicTreemapField {
id: string;
name: string;
total: number;
values: TopicTreemapValue[];
subfields: TopicTreemapSubfield[];
}
export interface TopicTreemapData {
institution_id: string;
organization_name: string;
years: number[];
fields: TopicTreemapField[];
}
export interface TopicTreemapTopicSelect {
topicId: string;
topicName: string;
fieldName: string;
subfieldName: string;
fromYear?: number;
toYear?: number;
}