implement dfg topics donutchart
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -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
|
||||
@@ -18,6 +18,23 @@ class DashboardStatisticValue(BaseModel):
|
||||
value: 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
|
||||
|
||||
@@ -11,6 +11,7 @@ from inse.tags import Tags
|
||||
from .model import (
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DfgProjectTopics,
|
||||
TopAuthorStatistics,
|
||||
TopicHeatmap,
|
||||
TopicWordCloud,
|
||||
@@ -18,8 +19,10 @@ from .model import (
|
||||
from .service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_patents,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
@@ -79,6 +82,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",
|
||||
@@ -127,6 +146,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",
|
||||
|
||||
@@ -13,9 +13,12 @@ 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 (
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DfgProjectTopic,
|
||||
DfgProjectTopics,
|
||||
TopAuthor,
|
||||
TopAuthorStatistics,
|
||||
TopicHeatmap,
|
||||
@@ -182,6 +185,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,
|
||||
@@ -235,15 +255,144 @@ async def get_dashboard_dfg_projects(
|
||||
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_V2,
|
||||
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(
|
||||
@@ -301,44 +450,32 @@ 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": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "institutions",
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
_alias_match_query(
|
||||
"institutions.institute_name_de", aliases
|
||||
),
|
||||
_alias_match_query(
|
||||
"institutions.institute_name_en", aliases
|
||||
),
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
"terms": {
|
||||
"institute_name_de.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "persons",
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
_alias_match_query(
|
||||
"persons.affiliation_de", aliases
|
||||
),
|
||||
_alias_match_query(
|
||||
"persons.affiliation_en", aliases
|
||||
),
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
"terms": {
|
||||
"institute_name_en.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
],
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
@@ -9,12 +9,15 @@ from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
get_dashboard_organization,
|
||||
get_dashboard_dfg_topics,
|
||||
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"
|
||||
|
||||
@@ -24,6 +27,22 @@ 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_statistics_counts_organization_data_and_all_projects():
|
||||
async def search(**kwargs):
|
||||
@@ -36,6 +55,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(
|
||||
@@ -44,6 +85,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")
|
||||
|
||||
@@ -58,12 +108,21 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
"bmbf_projects": 5,
|
||||
}
|
||||
calls = mocked_search.await_args_list
|
||||
calls_by_index = {call.kwargs["index"]: call for call in calls}
|
||||
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_call = calls_by_index[ESIndex.DFG_PROJECTS_V2]
|
||||
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
|
||||
}
|
||||
@@ -74,7 +133,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
}
|
||||
assert all(
|
||||
call.kwargs["cluster"] == ESCluster.INSE
|
||||
for call in [eu_call, bmbf_call, dfg_call]
|
||||
for call in [eu_call, bmbf_call, *dfg_calls]
|
||||
)
|
||||
assert eu_call.kwargs["body"]["query"] == {
|
||||
"terms": {
|
||||
@@ -92,18 +151,130 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
dfg_query = dfg_call.kwargs["query"]
|
||||
dfg_query = dfg_institutes_call.kwargs["body"]["query"]
|
||||
assert dfg_query["bool"]["minimum_should_match"] == 1
|
||||
assert dfg_query["bool"]["should"][0]["nested"]["path"] == "institutions"
|
||||
assert dfg_query["bool"]["should"][0]["nested"]["query"]["bool"]["should"][
|
||||
0
|
||||
]["bool"]["should"][0]["match"] == {
|
||||
"institutions.institute_name_de": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
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,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
assert dfg_query["bool"]["should"][1]["nested"]["path"] == "persons"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
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
|
||||
|
||||
@@ -102,6 +102,8 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
ESIndex.PROJECTS_BUND_V1,
|
||||
ESIndex.PROJECTS_DFG_ALL,
|
||||
ESIndex.DFG_PROJECTS_V2,
|
||||
ESIndex.DFG_INSTITUTES_V2,
|
||||
ESIndex.PROJECTS_DFG_OPENALEX_TOPICS,
|
||||
}:
|
||||
return ESCluster.INSE
|
||||
else:
|
||||
|
||||
@@ -62,6 +62,8 @@ class ESIndex(StrEnum):
|
||||
PROJECTS_BUND_V1 = "projects_bund_v1"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
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"
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface DashboardStatistics {
|
||||
organization_name: string;
|
||||
publications: number;
|
||||
persons: number;
|
||||
patents: number;
|
||||
projects: number;
|
||||
dfg_projects: number;
|
||||
eu_projects: number;
|
||||
@@ -23,6 +24,23 @@ export interface DashboardStatisticValue {
|
||||
value: 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;
|
||||
@@ -107,6 +125,12 @@ 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`,
|
||||
@@ -125,6 +149,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> {
|
||||
|
||||
@@ -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"
|
||||
@@ -127,14 +148,60 @@
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@if (topicHeatmapError) {
|
||||
@if (topicHeatmapLoading) {
|
||||
<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 (topicHeatmapError) {
|
||||
<p class="statistics-error">
|
||||
Die Field-Treemap konnte nicht geladen werden.
|
||||
</p>
|
||||
} @else {
|
||||
<app-topic-heatmap
|
||||
[heatmap]="topicHeatmap"
|
||||
[loading]="topicHeatmapLoading"></app-topic-heatmap>
|
||||
[selectedNodeId]="selectedTopicTreemapNode"
|
||||
(selectedNodeIdChange)="onTopicTreemapNodeChange($event)">
|
||||
</app-topic-heatmap>
|
||||
}
|
||||
</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;
|
||||
@@ -133,6 +138,18 @@
|
||||
width: min(100%, 34rem);
|
||||
}
|
||||
|
||||
.topic-heatmap-loading {
|
||||
min-height: 25rem;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.dfg-topic-summary {
|
||||
flex: 0 0 auto;
|
||||
color: #475569;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.top-authors-header {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
|
||||
@@ -2,13 +2,16 @@ 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 { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { TopicHeatmapComponent } from './topic-heatmap/topic-heatmap.component';
|
||||
import { DfgTopicDonutComponent } from './dfg-topic-donut/dfg-topic-donut.component';
|
||||
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
|
||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||
import {
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DashboardStatisticsService,
|
||||
DfgProjectTopics,
|
||||
TopAuthor,
|
||||
TopAuthorStatistics,
|
||||
TopAuthorsWorksPeriod,
|
||||
@@ -17,6 +20,7 @@ import {
|
||||
type DashboardStatisticKey =
|
||||
| 'publications'
|
||||
| 'persons'
|
||||
| 'patents'
|
||||
| 'eu_projects'
|
||||
| 'bmbf_projects'
|
||||
| 'dfg_projects';
|
||||
@@ -26,6 +30,8 @@ type DashboardStatisticKey =
|
||||
DecimalPipe,
|
||||
MatIconModule,
|
||||
RouterLink,
|
||||
LoadingComponent,
|
||||
DfgTopicDonutComponent,
|
||||
TopicHeatmapComponent,
|
||||
YearRangeSliderComponent,
|
||||
],
|
||||
@@ -39,6 +45,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,
|
||||
@@ -46,6 +53,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,18 +66,29 @@ export class DashboardComponent implements OnInit {
|
||||
topicHeatmap?: TopicHeatmap;
|
||||
topicHeatmapLoading = false;
|
||||
topicHeatmapError = false;
|
||||
dfgProjectTopics?: DfgProjectTopics;
|
||||
dfgTopicsLoading = false;
|
||||
dfgTopicsError = false;
|
||||
readonly topicTreemapMinYear = 1900;
|
||||
readonly topicTreemapMaxYear = new Date().getFullYear();
|
||||
topicTreemapFromYear = this.topicTreemapMaxYear - 4;
|
||||
topicTreemapToYear = this.topicTreemapMaxYear;
|
||||
selectedTopicTreemapNode?: string;
|
||||
private topicTreemapReloadQueued = false;
|
||||
private topicHeatmapRequestId = 0;
|
||||
|
||||
constructor(private statisticsService: DashboardStatisticsService) {}
|
||||
constructor(
|
||||
private statisticsService: DashboardStatisticsService,
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.restoreTopicTreemapState();
|
||||
this.loadStatistics();
|
||||
this.loadTopAuthors();
|
||||
this.loadTopicHeatmap();
|
||||
this.loadDfgProjectTopics();
|
||||
}
|
||||
|
||||
private loadStatistics(): void {
|
||||
@@ -79,6 +98,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(),
|
||||
@@ -146,6 +166,10 @@ export class DashboardComponent implements OnInit {
|
||||
);
|
||||
}
|
||||
|
||||
hasDfgTopicData(): boolean {
|
||||
return (this.dfgProjectTopics?.topics.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
setTopAuthorsWorksPeriod(period: TopAuthorsWorksPeriod): void {
|
||||
if (period === this.topAuthorsWorksPeriod) return;
|
||||
this.topAuthorsWorksPeriod = period;
|
||||
@@ -170,14 +194,61 @@ export class DashboardComponent implements OnInit {
|
||||
}
|
||||
|
||||
onTopicTreemapRangeChange(): void {
|
||||
this.topicHeatmapLoading = true;
|
||||
this.topicHeatmapError = false;
|
||||
this.topicHeatmapRequestId += 1;
|
||||
this.updateTopicTreemapUrl();
|
||||
if (this.topicTreemapReloadQueued) return;
|
||||
this.topicTreemapReloadQueued = true;
|
||||
queueMicrotask(() => {
|
||||
setTimeout(() => {
|
||||
this.topicTreemapReloadQueued = false;
|
||||
this.loadTopicHeatmap();
|
||||
});
|
||||
}
|
||||
|
||||
onTopicTreemapNodeChange(nodeId: string | undefined): void {
|
||||
this.selectedTopicTreemapNode = nodeId;
|
||||
this.updateTopicTreemapUrl();
|
||||
}
|
||||
|
||||
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.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(
|
||||
key: DashboardStatisticKey,
|
||||
request: Observable<DashboardStatisticValue>,
|
||||
@@ -239,23 +310,51 @@ export class DashboardComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
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 loadTopicHeatmap(): void {
|
||||
if (this.topicTreemapFromYear > this.topicTreemapToYear) {
|
||||
this.topicHeatmapLoading = false;
|
||||
this.topicHeatmapError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = ++this.topicHeatmapRequestId;
|
||||
this.topicHeatmapLoading = true;
|
||||
this.topicHeatmapError = false;
|
||||
this.statisticsService
|
||||
.getTopicHeatmap(this.topicTreemapFromYear, this.topicTreemapToYear)
|
||||
.pipe(finalize(() => (this.topicHeatmapLoading = false)))
|
||||
.pipe(
|
||||
finalize(() => {
|
||||
if (requestId === this.topicHeatmapRequestId) {
|
||||
this.topicHeatmapLoading = false;
|
||||
}
|
||||
}),
|
||||
)
|
||||
.subscribe({
|
||||
next: (heatmap) => {
|
||||
this.topicHeatmap = heatmap;
|
||||
if (requestId === this.topicHeatmapRequestId) {
|
||||
this.topicHeatmap = heatmap;
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.topicHeatmapError = true;
|
||||
if (requestId === this.topicHeatmapRequestId) {
|
||||
this.topicHeatmapError = 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>
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.dfg-topic-donut-chart {
|
||||
width: 100%;
|
||||
height: 440px;
|
||||
}
|
||||
|
||||
.dfg-topic-donut-empty {
|
||||
display: grid;
|
||||
min-height: 260px;
|
||||
margin: 0;
|
||||
place-items: center;
|
||||
color: #64748b;
|
||||
}
|
||||
@@ -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) =>
|
||||
({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
"'": ''',
|
||||
'"': '"',
|
||||
})[character] ?? character,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,19 @@
|
||||
@if (heatmap?.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"
|
||||
|
||||
@@ -3,6 +3,30 @@
|
||||
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;
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { Component, Input, OnChanges, inject } from '@angular/core';
|
||||
import {
|
||||
Component,
|
||||
EventEmitter,
|
||||
Input,
|
||||
OnChanges,
|
||||
Output,
|
||||
SimpleChanges,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { EChartsOption } from 'echarts';
|
||||
import { NgxEchartsDirective } from 'ngx-echarts';
|
||||
@@ -10,6 +18,11 @@ import {
|
||||
TopicWordCloudDialogData,
|
||||
} from '../topic-wordcloud-dialog/topic-wordcloud-dialog.component';
|
||||
|
||||
interface TreemapBreadcrumb {
|
||||
label: string;
|
||||
nodeId?: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-topic-heatmap',
|
||||
imports: [NgxEchartsDirective],
|
||||
@@ -21,15 +34,22 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
private readonly fieldColorOpacity = 0.78;
|
||||
@Input() heatmap?: TopicHeatmap;
|
||||
@Input() loading = false;
|
||||
@Input() selectedNodeId?: string;
|
||||
@Output() selectedNodeIdChange = new EventEmitter<string | undefined>();
|
||||
|
||||
options: EChartsOption = {};
|
||||
|
||||
ngOnChanges(): void {
|
||||
this.options = this.buildOptions();
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['heatmap'] || 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.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
|
||||
TopicWordCloudDialogComponent,
|
||||
@@ -37,7 +57,7 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
width: '85vw',
|
||||
maxWidth: '92vw',
|
||||
data: {
|
||||
topicId: data.id,
|
||||
topicId: data.entityId,
|
||||
topicName: data.name,
|
||||
fieldName: data.fieldName,
|
||||
subfieldName: data.subfieldName,
|
||||
@@ -48,16 +68,51 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
);
|
||||
}
|
||||
|
||||
breadcrumbs(): TreemapBreadcrumb[] {
|
||||
const result: TreemapBreadcrumb[] = [{ label: 'Fields' }];
|
||||
if (!this.selectedNodeId || !this.heatmap) return result;
|
||||
|
||||
for (const field of this.heatmap.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.heatmap?.fields ?? [];
|
||||
const data = fields.map((field) => {
|
||||
const hierarchyData = fields.map((field) => {
|
||||
const fieldColor = topicHierarchyColor({
|
||||
field_id: field.id,
|
||||
field_name: field.name,
|
||||
});
|
||||
|
||||
return {
|
||||
id: field.id,
|
||||
id: `field:${field.id}`,
|
||||
entityId: field.id,
|
||||
nodeId: `field:${field.id}`,
|
||||
name: field.name,
|
||||
value: field.total || this.totalCount(field.values),
|
||||
itemStyle: {
|
||||
@@ -82,7 +137,9 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
children: (field.subfields ?? [])
|
||||
.filter((subfield) => subfield.total > 0)
|
||||
.map((subfield) => ({
|
||||
id: subfield.id,
|
||||
id: `subfield:${subfield.id}`,
|
||||
entityId: subfield.id,
|
||||
nodeId: `subfield:${subfield.id}`,
|
||||
name: subfield.name,
|
||||
value: subfield.total,
|
||||
fieldName: field.name,
|
||||
@@ -99,7 +156,9 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
children: (subfield.topics ?? [])
|
||||
.filter((topic) => topic.total > 0)
|
||||
.map((topic) => ({
|
||||
id: topic.id,
|
||||
id: `topic:${topic.id}`,
|
||||
entityId: topic.id,
|
||||
nodeId: `topic:${topic.id}`,
|
||||
name: topic.name,
|
||||
value: topic.total,
|
||||
fieldName: field.name,
|
||||
@@ -118,6 +177,7 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
})),
|
||||
};
|
||||
});
|
||||
const data = this.visibleData(hierarchyData);
|
||||
|
||||
return {
|
||||
tooltip: {
|
||||
@@ -170,11 +230,11 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
type: 'treemap',
|
||||
data,
|
||||
roam: false,
|
||||
nodeClick: 'zoomToNode',
|
||||
nodeClick: false,
|
||||
sort: 'desc',
|
||||
drillDownIcon: '',
|
||||
breadcrumb: {
|
||||
show: true,
|
||||
show: false,
|
||||
bottom: 0,
|
||||
height: 24,
|
||||
left: 8,
|
||||
@@ -303,6 +363,54 @@ export class TopicHeatmapComponent implements OnChanges {
|
||||
};
|
||||
}
|
||||
|
||||
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.heatmap) return undefined;
|
||||
const topicId = topicNodeId.slice('topic:'.length);
|
||||
for (const field of this.heatmap.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.heatmap) return undefined;
|
||||
|
||||
const field = this.heatmap.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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user