fix treemap
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit

This commit is contained in:
2026-07-14 13:09:45 +02:00
parent a0ef884ca3
commit dfdc35ad81
12 changed files with 777 additions and 268 deletions
+28 -1
View File
@@ -27,7 +27,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 +38,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 +66,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]
+25
View File
@@ -13,6 +13,7 @@ from .model import (
DashboardStatistics,
TopAuthorStatistics,
TopicHeatmap,
TopicWordCloud,
)
from .service import (
get_dashboard_bmbf_projects,
@@ -24,6 +25,7 @@ from .service import (
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
get_topic_word_cloud,
)
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
@@ -166,3 +168,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,
)
+291 -110
View File
@@ -20,11 +20,18 @@ from .model import (
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__)
@@ -112,14 +119,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,
@@ -266,10 +333,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 +348,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 +429,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 +501,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 +679,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 +783,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 +810,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.PROJECTS_DFG_ALL,
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 +826,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 []
+142 -142
View File
@@ -12,6 +12,7 @@ from inse.dashboard.service import (
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
get_topic_word_cloud,
)
from inse.model import ESCluster, ESIndex
@@ -98,7 +99,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
@pytest.mark.anyio
async def test_top_authors_maps_works_and_dfg_project_aggregations():
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 +132,14 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
}
}
}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
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 +149,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 +163,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",
@@ -183,133 +183,16 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations():
if call.kwargs["index"]
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
]
assert len(project_calls) == 1
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL
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.PROJECTS_DFG_ALL:
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.PROJECTS_DFG_ALL:
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.PROJECTS_DFG_ALL:
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 +218,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 +225,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 +328,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 +406,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 +431,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 +479,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)
@@ -12,7 +12,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>;
}
@@ -32,7 +32,7 @@ export interface TopAuthor {
export interface TopAuthorStatistics {
institution_id: string;
works: TopAuthor[];
projects: TopAuthor[];
eu_projects: TopAuthor[];
patents: TopAuthor[];
news: TopAuthor[];
}
@@ -48,6 +48,22 @@ export interface TopicHeatmapField {
name: string;
total: number;
values: TopicHeatmapValue[];
subfields: TopicHeatmapSubfield[];
}
export interface TopicHeatmapSubfield {
id: string;
name: string;
total: number;
values: TopicHeatmapValue[];
topics: TopicHeatmapTopic[];
}
export interface TopicHeatmapTopic {
id: string;
name: string;
total: number;
values: TopicHeatmapValue[];
}
export interface TopicHeatmap {
@@ -57,6 +73,17 @@ export interface TopicHeatmap {
fields: TopicHeatmapField[];
}
export interface TopicWordCloudWord {
id: string;
name: string;
count: number;
}
export interface TopicWordCloud {
topic_id: string;
words: TopicWordCloudWord[];
}
@Injectable({ providedIn: 'root' })
export class DashboardStatisticsService {
private readonly httpClient = inject(HttpClient);
@@ -122,4 +149,18 @@ export class DashboardStatisticsService {
{ 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 },
);
}
}
@@ -105,6 +105,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',
@@ -1,5 +1,9 @@
@if (heatmap?.fields?.length) {
<div echarts [options]="options" class="topic-treemap-chart"></div>
<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.' }}
@@ -1,8 +1,13 @@
import { Component, Input, OnChanges } from '@angular/core';
import { Component, Input, OnChanges, inject } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { TopicHeatmap } from '../dashboard-statistics.service';
import {
TopicWordCloudDialogComponent,
TopicWordCloudDialogData,
} from '../topic-wordcloud-dialog/topic-wordcloud-dialog.component';
@Component({
selector: 'app-topic-heatmap',
@@ -11,6 +16,7 @@ import { TopicHeatmap } from '../dashboard-statistics.service';
styleUrl: './topic-heatmap.component.scss',
})
export class TopicHeatmapComponent implements OnChanges {
private readonly dialog = inject(MatDialog);
@Input() heatmap?: TopicHeatmap;
@Input() loading = false;
@@ -32,6 +38,26 @@ export class TopicHeatmapComponent implements OnChanges {
this.options = this.buildOptions();
}
onChartClick(event: any): void {
const data = event?.data;
if (!data?.id || !data?.subfieldName || data?.children?.length) return;
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
TopicWordCloudDialogComponent,
{
width: '85vw',
maxWidth: '92vw',
data: {
topicId: data.id,
topicName: data.name,
fieldName: data.fieldName,
subfieldName: data.subfieldName,
fromYear: this.heatmap?.years.at(0),
toYear: this.heatmap?.years.at(-1),
},
},
);
}
private buildOptions(): EChartsOption {
const fields = this.heatmap?.fields ?? [];
const data = fields.map((field) => ({
@@ -47,12 +73,22 @@ export class TopicHeatmapComponent implements OnChanges {
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,
children: (field.subfields ?? [])
.filter((subfield) => subfield.total > 0)
.map((subfield) => ({
id: subfield.id,
name: subfield.name,
value: subfield.total,
fieldName: field.name,
children: (subfield.topics ?? [])
.filter((topic) => topic.total > 0)
.map((topic) => ({
id: topic.id,
name: topic.name,
value: topic.total,
fieldName: field.name,
subfieldName: subfield.name,
})),
})),
}));
@@ -60,11 +96,13 @@ export class TopicHeatmapComponent implements OnChanges {
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}`;
const field = params.data?.fieldName
? `<br />Field: ${params.data.fieldName}`
: '';
const subfield = params.data?.subfieldName
? `<br />Subfield: ${params.data.subfieldName}`
: '';
return `${params.name}${field}${subfield}<br /><strong>${count}</strong> Publikationen`;
},
},
series: [
@@ -0,0 +1,37 @@
<div class="dialog-title" mat-dialog-title>
<div>
<h2>{{ data.topicName }}</h2>
<p>
{{ data.fieldName }}
@if (data.subfieldName) {
<span>· {{ data.subfieldName }}</span>
}
</p>
</div>
<button mat-icon-button type="button" aria-label="Dialog schließen" mat-dialog-close>
<mat-icon>close</mat-icon>
</button>
</div>
<mat-dialog-content>
@if (loading) {
<div class="word-cloud-state">Verwandte Themen werden geladen ...</div>
} @else if (loadFailed) {
<div class="word-cloud-state error">Wordcloud konnte nicht geladen werden.</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.count + ' Publikationen'">
{{ word.name }}
</span>
}
</div>
} @else {
<div class="word-cloud-state">Keine verwandten Themen gefunden.</div>
}
</mat-dialog-content>
@@ -0,0 +1,49 @@
.dialog-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
h2 {
margin: 0;
}
p {
margin: 4px 0 0;
color: #64748b;
font-size: 0.875rem;
}
}
mat-dialog-content {
min-height: 330px;
}
.word-cloud-chart {
min-height: 300px;
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 12px 18px;
padding: 24px;
border-radius: 12px;
background: linear-gradient(145deg, #f8fafc, #ffffff);
}
.word-cloud-word {
line-height: 1.1;
text-align: center;
}
.word-cloud-state {
min-height: 300px;
display: grid;
place-items: center;
color: #64748b;
&.error {
color: #b91c1c;
}
}
@@ -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;
}
}