Merge branch 'dev' into chips-and-tooltips
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Mats Paul Tončik
2026-07-26 15:03:47 +02:00
26 changed files with 1224 additions and 152698 deletions
+5
View File
@@ -12,6 +12,11 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
# Debugging: Log every outgoing Elasticsearch query (index + payload)
PRINT_ES_QUERIES=false
# Debugging: Log the duration of every Elasticsearch request
PRINT_ES_TIMINGS=true
# Sentence Transformers Configuration
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2
View File
@@ -69,6 +69,8 @@ class Settings(BaseSettings):
elasticsearch_api_key: Optional[str] = None
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
print_es_queries: bool = False
print_es_timings: bool = False
model_config = SettingsConfigDict(env_file=str(ENV_FILE))
+1
View File
@@ -60,6 +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]
+503
View File
@@ -1,5 +1,6 @@
import asyncio
import logging
import re
from datetime import datetime
from typing import Any, Literal
@@ -12,6 +13,8 @@ from inse.integrations import elasticsearch
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.model import ESCluster, ESIndex
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
from inse.projects.dfg_institutions.service import autocomplete_institutions_for_selector
from inse.projects.logic import get_person_ids_by_institution_ids
from .institute_helper import get_openalex_institution
from .model import (
@@ -41,6 +44,41 @@ TOPIC_HEATMAP_YEARS = 5
WorksPeriod = Literal["all_time", "last_5_years"]
logger = logging.getLogger(__name__)
ACADEMIC_TITLE_RE = re.compile(
r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+",
re.IGNORECASE,
)
def _normalize_person_name(name: str) -> str:
normalized = " ".join(name.strip().casefold().split())
while True:
without_title = ACADEMIC_TITLE_RE.sub("", normalized).strip()
if without_title == normalized:
return without_title
normalized = without_title
def _is_initial_surname_match(full_name: str, initial_name: str) -> bool:
full_parts = _normalize_person_name(full_name).split()
initial_parts = _normalize_person_name(initial_name).replace(".", "").split()
if len(full_parts) < 2 or len(initial_parts) < 2:
return False
return (
len(initial_parts[0]) == 1
and full_parts[0].startswith(initial_parts[0])
and full_parts[-1] == initial_parts[-1]
)
def _is_supported_name_variant(full_name: str, candidate_name: str) -> bool:
return (
_normalize_person_name(full_name) == _normalize_person_name(candidate_name)
or _is_initial_surname_match(full_name, candidate_name)
)
def _total(response: dict[str, Any]) -> int:
total = response.get("hits", {}).get("total", 0)
if isinstance(total, dict):
@@ -625,6 +663,13 @@ 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)
projects = await _safe_top_authors(
"projects",
_top_project_authors(
authors=authors,
organization_name=organization_name,
),
)
eu_projects = await _safe_top_authors(
"eu_projects",
_top_eu_project_publication_authors(),
@@ -640,6 +685,7 @@ async def get_top_authors(
return TopAuthorStatistics(
institution_id=normalized_id,
works=works,
projects=projects,
eu_projects=eu_projects,
patents=patents,
news=news,
@@ -1102,6 +1148,463 @@ async def _institution_authors(institution_id: str) -> list[dict[str, Any]]:
]
async def _top_project_authors(
authors: list[dict[str, Any]],
organization_name: str,
) -> list[TopAuthor]:
institution_ids = await _dfg_institution_ids_for_organization(
organization_name=organization_name,
)
logger.info(
"DFG institution IDs for %s: %s",
organization_name,
institution_ids,
)
if not institution_ids:
logger.warning(
"No DFG institution IDs found for organization %s.",
organization_name,
)
return []
selected_person_ids = set(
await get_person_ids_by_institution_ids(institution_ids=institution_ids)
)
logger.info(
"Found %s DFG persons for organization %s.",
len(selected_person_ids),
organization_name,
)
if not selected_person_ids:
return []
project_ids_by_person: dict[int, set[str]] = {}
names: dict[int, str] = {}
page = 0
size = 10000
processed = 0
while True:
project_hits, total = await _dfg_project_author_hits(
page=page,
size=size,
person_ids=selected_person_ids,
)
if not project_hits:
break
for project in project_hits:
project_id = _dfg_project_id(project)
if not project_id:
continue
persons = project.get("persons", [])
if not isinstance(persons, list):
continue
for person in persons:
if not isinstance(person, dict):
continue
person_id = person.get("person_id")
full_name = person.get("full_name")
if person_id is None or not full_name:
continue
try:
normalized_person_id = int(person_id)
except (TypeError, ValueError):
continue
if normalized_person_id not in selected_person_ids:
continue
project_ids_by_person.setdefault(normalized_person_id, set()).add(
project_id
)
names[normalized_person_id] = str(full_name).strip()
processed += len(project_hits)
if processed >= total:
break
page += 1
institution_authors: dict[str, list[dict[str, Any]]] = {}
for author in authors:
if author.get("name"):
institution_authors.setdefault(
_normalize_person_name(author["name"]),
[],
).append(author)
ranked = sorted(
(
(person_id, project_ids)
for person_id, project_ids in project_ids_by_person.items()
if project_ids and names.get(person_id)
),
key=lambda item: (
-len(item[1]),
names[item[0]].casefold(),
),
)
ranked_person_ids = [person_id for person_id, _ in ranked[:TOP_AUTHOR_LIMIT]]
dfg_orcids = await _dfg_person_orcids(ranked_person_ids)
result: list[TopAuthor] = []
for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]:
dfg_name = names[person_id]
matched_author = _single_author_match(
institution_authors.get(_normalize_person_name(dfg_name), [])
)
if matched_author is None and (orcid := dfg_orcids.get(person_id)):
matched_author = await _openalex_author_by_orcid(orcid)
if matched_author is None:
matched_author = await _openalex_author_by_dfg_publication_evidence(
dfg_name=dfg_name,
project_ids=project_ids,
)
if matched_author is None:
logger.info(
"No exact OpenAlex match for DFG author '%s' (person_id=%s).",
dfg_name,
person_id,
)
result.append(
TopAuthor(
id=(
_short_author_id(matched_author["id"])
if matched_author
else None
),
name=matched_author["name"] if matched_author else dfg_name,
count=len(project_ids),
)
)
logger.info(
"DFG top authors for %s: %s",
organization_name,
[
{
"name": author.name,
"count": author.count,
"id": author.id,
}
for author in result
],
)
return result
def _single_author_match(authors: list[dict[str, Any]]) -> dict[str, Any] | None:
return authors[0] if len(authors) == 1 else None
async def _dfg_person_orcids(person_ids: list[int]) -> dict[int, str]:
if not person_ids:
return {}
try:
response = await elasticsearch.search(
index=ESIndex.DFG_PERSONS,
body={
"size": len(person_ids),
"_source": ["person_id", "orcid_id"],
"query": {"terms": {"person_id": person_ids}},
},
cluster=ESCluster.INSE,
)
except Exception:
logger.exception("Could not load DFG ORCIDs for top project authors.")
return {}
result: dict[int, str] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
person_id = source.get("person_id")
orcid = source.get("orcid_id")
if person_id is None or not orcid:
continue
try:
result[int(person_id)] = str(orcid)
except (TypeError, ValueError):
continue
return result
async def _openalex_author_by_orcid(orcid: str) -> dict[str, Any] | None:
normalized_orcid = orcid.replace("https://orcid.org/", "").strip()
if not normalized_orcid:
return None
prefixed_orcid = f"https://orcid.org/{normalized_orcid}"
try:
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
body={
"size": 2,
"_source": ["id", "display_name"],
"query": {
"bool": {
"should": [
{"term": {"orcid.keyword": normalized_orcid}},
{"term": {"orcid.keyword": prefixed_orcid}},
{"term": {"ids.orcid.keyword": normalized_orcid}},
{"term": {"ids.orcid.keyword": prefixed_orcid}},
{"term": {"orcid": normalized_orcid}},
{"term": {"orcid": prefixed_orcid}},
{"term": {"ids.orcid": normalized_orcid}},
{"term": {"ids.orcid": prefixed_orcid}},
],
"minimum_should_match": 1,
}
},
},
cluster=ESCluster.NES,
track_total_hits=True,
)
except Exception:
logger.exception("Could not resolve OpenAlex author by ORCID %s.", orcid)
return None
hits = response.get("hits", {}).get("hits", [])
if len(hits) != 1:
logger.info(
"OpenAlex ORCID lookup for %s returned %s hits.",
orcid,
len(hits),
)
return None
source = hits[0].get("_source", {})
if not source.get("id") or not source.get("display_name"):
return None
return {
"id": str(source["id"]),
"name": str(source["display_name"]),
}
async def _openalex_author_by_dfg_publication_evidence(
dfg_name: str,
project_ids: set[str],
) -> dict[str, Any] | None:
dois = await _dfg_project_publication_dois(project_ids)
if not dois:
return None
try:
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body={
"size": 10000,
"_source": [
"doi",
"authorships.author.id",
"authorships.author.display_name",
],
"query": {"terms": {"doi": sorted(_doi_variants(dois))}},
},
cluster=ESCluster.NES,
)
except Exception:
logger.exception(
"Could not resolve OpenAlex author from DFG publication DOIs for %s.",
dfg_name,
)
return None
candidates: dict[str, dict[str, Any]] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
doi = source.get("doi")
if not doi:
continue
for authorship in source.get("authorships", []) or []:
author = authorship.get("author", {}) if isinstance(authorship, dict) else {}
author_id = author.get("id")
display_name = author.get("display_name")
if not author_id or not display_name:
continue
if not _is_supported_name_variant(dfg_name, str(display_name)):
continue
candidate = candidates.setdefault(
str(author_id),
{
"id": str(author_id),
"name": str(display_name),
"dois": set(),
},
)
candidate["dois"].add(str(doi))
supported_candidates = [
candidate
for candidate in candidates.values()
if len(candidate["dois"]) >= 2
]
if len(supported_candidates) != 1:
if supported_candidates:
logger.info(
"DFG publication DOI lookup for %s returned %s candidates.",
dfg_name,
len(supported_candidates),
)
return None
candidate = supported_candidates[0]
return {
"id": candidate["id"],
"name": candidate["name"],
}
async def _dfg_project_publication_dois(project_ids: set[str]) -> set[str]:
if not project_ids:
return set()
numeric_project_ids = [
int(project_id)
for project_id in project_ids
if str(project_id).isdigit()
]
if not numeric_project_ids:
return set()
try:
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
body={
"size": len(numeric_project_ids),
"_source": ["publications.doi"],
"query": {"terms": {"id": numeric_project_ids}},
},
cluster=ESCluster.INSE,
)
except Exception:
logger.exception("Could not load DFG publication DOIs.")
return set()
dois: set[str] = set()
for hit in response.get("hits", {}).get("hits", []):
for publication in hit.get("_source", {}).get("publications", []) or []:
doi = publication.get("doi") if isinstance(publication, dict) else None
if doi:
dois.add(str(doi).strip())
return {doi for doi in dois if doi}
def _doi_variants(dois: set[str]) -> set[str]:
variants: set[str] = set()
for doi in dois:
normalized = doi.strip()
if not normalized:
continue
raw = normalized
for prefix in ("https://doi.org/", "http://dx.doi.org/"):
if raw.casefold().startswith(prefix):
raw = raw[len(prefix):]
break
variants.update(
{
normalized,
normalized.lower(),
f"https://doi.org/{raw}",
f"https://doi.org/{raw.lower()}",
}
)
return variants
async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]:
page = await autocomplete_institutions_for_selector(
query=organization_name,
page=0,
size=10000,
)
return [institution.id for institution in page.elements if institution.id is not None]
async def _dfg_project_author_hits(
page: int,
size: int,
person_ids: set[int],
) -> tuple[list[dict[str, Any]], int]:
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
body={
"size": size,
"from": page * size,
"_source": [
"id",
"project_id",
"persons",
],
"query": {
"nested": {
"path": "persons",
"query": {"terms": {"persons.person_id": sorted(person_ids)}},
},
},
"sort": [
{
"id": {
"order": "asc",
"missing": "_last",
}
}
],
},
cluster=ESCluster.INSE,
track_total_hits=True,
)
hits_block = response.get("hits", {})
total_value = hits_block.get("total", 0)
if isinstance(total_value, dict):
total = int(total_value.get("value", 0))
else:
total = int(total_value or 0)
hits = [
hit.get("_source", {})
for hit in hits_block.get("hits", [])
if isinstance(hit.get("_source"), dict)
]
logger.info(
"Loaded %s of %s matching DFG projects on page %s.",
len(hits),
total,
page,
)
return hits, total
def _dfg_project_id(project: dict[str, Any]) -> str | None:
project_id = project.get("id")
if project_id is None:
project_id = project.get("project_id")
return str(project_id) if project_id is not None else None
async def _top_patent_authors(institution_id: str) -> list[TopAuthor]:
client = OrgPatentsSearchClient()
authors = await client.top_authors_by_institution(
@@ -1,3 +1,4 @@
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from datetime import datetime
@@ -383,7 +384,7 @@ async def test_dashboard_dfg_topics_returns_deduplicated_topics():
@pytest.mark.anyio
async def test_top_authors_maps_works_patents_and_news_without_project_queries():
async def test_top_authors_maps_works_patents_eu_dfg_and_news():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -427,6 +428,37 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
}
}
}
if kwargs["index"] == ESIndex.DFG_PROJECTS:
return {
"hits": {
"total": {"value": 2},
"hits": [
{
"_source": {
"id": "P1",
"persons": [
{"person_id": 2, "full_name": "Grace Example"},
{
"person_id": 99,
"full_name": "Outside Collaborator",
},
],
}
},
{
"_source": {
"id": "P2",
"persons": [
{"person_id": 2, "full_name": "Grace Example"},
{"person_id": 2, "full_name": "Grace Example"},
],
}
},
],
}
}
if kwargs["index"] == ESIndex.DFG_PERSONS:
return {"hits": {"hits": []}}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
@@ -439,6 +471,12 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
{"id": "A1", "name": "Ada Example", "count": 4},
]
),
), patch(
"inse.dashboard.service.autocomplete_institutions_for_selector",
new=AsyncMock(return_value=SimpleNamespace(elements=[SimpleNamespace(id=101)])),
), patch(
"inse.dashboard.service.get_person_ids_by_institution_ids",
new=AsyncMock(return_value=[2]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
@@ -456,6 +494,11 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
{"id": None, "name": "Grace Example", "count": 8},
{"id": None, "name": "Ada Example", "count": 5},
]
assert result.projects[0].model_dump() == {
"id": "A2",
"name": "Grace Example",
"count": 2,
}
assert result.news[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
@@ -464,10 +507,15 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
project_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"]
in {ESIndex.DFG_PROJECTS_V2, ESIndex.PROJECTS_BUND_V1}
if call.kwargs["index"] == ESIndex.DFG_PROJECTS
]
assert project_calls == []
assert len(project_calls) == 1
assert project_calls[0].kwargs["body"]["query"] == {
"nested": {
"path": "persons",
"query": {"terms": {"persons.person_id": [2]}},
},
}
eu_calls = [
call
for call in mocked_search.await_args_list
@@ -505,10 +553,14 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
), patch(
"inse.dashboard.service.autocomplete_institutions_for_selector",
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
):
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 == []
@@ -559,6 +611,9 @@ async def test_top_authors_can_rank_works_by_last_five_years():
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
), patch(
"inse.dashboard.service.autocomplete_institutions_for_selector",
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
):
result = await get_top_authors(
ORG_INSTITUTION_ID,
@@ -1,5 +1,6 @@
import json
import logging
import time
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
import httpx
@@ -110,6 +111,10 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
return None
def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]:
return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
def _wrap_exception(e: Exception) -> Exception:
logger.exception(f"Elasticsearch raised an exception: {e}")
if isinstance(e, httpx.HTTPStatusError):
@@ -125,6 +130,63 @@ def _wrap_exception(e: Exception) -> Exception:
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
async def _request(
method: str,
cluster: ESCluster,
path: str,
*,
json_body: Optional[Any] = None,
params: Optional[Dict[str, Any]] = None,
content: Optional[bytes] = None,
content_type: str = "application/json",
) -> httpx.Response:
"""Sends an authenticated request to cluster and returns the raw response.
Args:
method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE").
cluster: The Elasticsearch cluster to send the request to.
path: The path appended to the cluster URL (without leading slash).
json_body: Optional JSON-serialisable request body.
params: Optional query parameters.
content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body.
content_type: The Content-Type header value.
Returns:
httpx.Response: The successful response (status already checked).
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
client = get_client()
start = time.perf_counter()
try:
response = await client.request(
method,
f"{elasticsearch_url}/{path}",
json=json_body,
params=params,
content=content,
headers=_headers(api_key, content_type=content_type),
)
response.raise_for_status()
if config.settings.print_es_timings:
elapsed_ms = (time.perf_counter() - start) * 1000
logger.debug(
f"Elasticsearch request {method} {path} on cluster '{cluster}' took {elapsed_ms:.1f} ms"
)
return response
except Exception as exc:
if config.settings.print_es_timings:
elapsed_ms = (time.perf_counter() - start) * 1000
logger.debug(
f"Elasticsearch request {method} {path} on cluster '{cluster}' failed after {elapsed_ms:.1f} ms"
)
raise _wrap_exception(exc) from exc
async def search(
index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict] = None,
@@ -175,10 +237,6 @@ async def search(
elif len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
payload: Dict[str, Any] = {}
if body is not None:
@@ -210,61 +268,34 @@ async def search(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
)
client = get_client()
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
)
if config.settings.print_es_queries:
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}"
)
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload)
return response.json()
async def open_point_in_time(
index: str, keep_alive: str = "1m", cluster: str = "nes"
) -> str:
"""Opens a point-in-time on the given index and returns its id."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive})
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_pit",
params={"keep_alive": keep_alive},
headers=headers,
)
response.raise_for_status()
return response.json()["id"]
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()["id"]
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
"""Closes a previously opened point-in-time."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
client = get_client()
try:
response = await client.request(
"DELETE",
f"{elasticsearch_url}/_pit",
json={"id": pit_id},
headers=headers,
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
await _request("DELETE", cluster, "_pit", json_body={"id": pit_id})
async def scan(
@@ -280,13 +311,9 @@ async def scan(
Unlike ``from``/``size`` pagination, this is not bounded by
``index.max_result_window``, so it can stream result sets larger than 10k.
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
search_after: Optional[List] = None
try:
client = get_client()
while True:
payload: Dict[str, Any] = {
"size": page_size,
@@ -299,14 +326,7 @@ async def scan(
if search_after is not None:
payload["search_after"] = search_after
try:
response = await client.post(
f"{elasticsearch_url}/_search", json=payload, headers=headers
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, "_search", json_body=payload)
result = response.json()
hits = result.get("hits", {}).get("hits", [])
@@ -338,23 +358,13 @@ async def get(
if isinstance(index, ESIndex):
cluster = _index_to_cluster(index) or cluster
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
params = {}
if source is not None:
params["_source_includes"] = ",".join(source)
client = get_client()
try:
response = await client.get(
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params)
return response.json()
async def update(
@@ -363,20 +373,11 @@ async def update(
doc: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request(
"POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc}
)
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_update/{doc_id}",
json={"doc": doc},
headers=headers,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def index_doc(
@@ -385,20 +386,11 @@ async def index_doc(
document: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request(
"PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document
)
client = get_client()
try:
response = await client.put(
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
json=document,
headers=headers,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def count(
@@ -431,24 +423,15 @@ async def count(
if len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
payload = {"query": query} if query else {}
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=headers
)
response.raise_for_status()
return response.json().get("count", 0)
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload)
return response.json().get("count", 0)
async def msearch(
@@ -473,9 +456,6 @@ async def msearch(
if c is not None:
cluster = c
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"}
lines = []
for idx, body in searches:
if isinstance(idx, list):
@@ -488,16 +468,13 @@ async def msearch(
ndjson_payload = "\n".join(lines) + "\n"
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/_msearch",
content=ndjson_payload.encode("utf-8"),
headers=headers,
)
response.raise_for_status()
res_json = response.json()
return res_json.get("responses", [])
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request(
"POST",
cluster,
"_msearch",
content=ndjson_payload.encode("utf-8"),
content_type="application/x-ndjson",
)
return response.json().get("responses", [])
+1
View File
@@ -68,6 +68,7 @@ class ESIndex(StrEnum):
AKTUELLES = "aktuell"
AKTUELLES_POSTPROC = "aktuell_postproc"
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
@@ -170,6 +170,19 @@ async def test_get_top_topics_for_entity_projects():
assert "items" in res
@pytest.mark.anyio
async def test_get_top_topics_for_entity_news():
res = await get_top_topics_for_entity(
entity_id="UDE",
entity_type="institution",
start_year=2018,
end_year=2024,
search_type="news",
)
assert isinstance(res, dict)
assert "items" in res
@pytest.mark.anyio
async def test_get_trend_data_delegation():
res = await get_trend_data(
@@ -456,31 +456,99 @@ async def get_top_topics_for_entity(
if search_type == "news":
try:
res = await elasticsearch.search(
index=ESIndex.AKTUELLES_POSTPROC.value,
body={
"query": {"match_all": {}},
"size": 0,
"_source": False,
"aggs": {
"top_topics": {
"terms": {
"field": "topics.display_name.keyword",
"size": DEFAULT_TOP_TOPICS_SIZE,
date_filter = TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year)
news_ids = []
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES.value,
query={"bool": {"filter": [date_filter]}},
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
if nid:
news_ids.append(str(nid))
except Exception as e:
logger.warning("Failed scanning aktuell for news IDs in date range: %s", e)
topic_counts: Dict[str, int] = {}
if news_ids:
msearch_queries = []
for i in range(0, len(news_ids), 2000):
chunk = news_ids[i : i + 2000]
payload = {
"query": {
"bool": {
"should": [
{"ids": {"values": chunk}},
{"terms": {"news_id.keyword": chunk}},
{"terms": {"news_id": chunk}},
],
"minimum_should_match": 1,
}
}
},
},
cluster=ESCluster.INSE,
)
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets]
total_hits = res.get("hits", {}).get("total", {})
total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0)
sum_top = sum(b["count"] for b in items)
other_count = max(0, total_val - sum_top)
},
"size": 0,
"_source": False,
"aggs": {
"top_topics": {
"terms": {
"field": "topic_matches.topic_display_name.keyword",
"size": 100,
}
}
},
}
msearch_queries.append((ESIndex.AKTUELLES_OPENALEX_TOPICS.value, payload))
if msearch_queries:
try:
responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE)
for res in responses:
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
for b in buckets:
t_name = b["key"]
cnt = b["doc_count"]
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
except Exception as e:
logger.warning("Failed to aggregate news top topics via msearch: %s", e)
else:
# If no year filter bounds active or scan returned no IDs, aggregate all topics directly from openalex_topics
try:
res = await elasticsearch.search(
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
body={
"query": {"match_all": {}},
"size": 0,
"_source": False,
"aggs": {
"top_topics": {
"terms": {
"field": "topic_matches.topic_display_name.keyword",
"size": 100,
}
}
},
},
cluster=ESCluster.INSE,
)
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
for b in buckets:
t_name = b["key"]
cnt = b["doc_count"]
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
except Exception as e:
logger.warning("Failed to fallback query news top topics: %s", e)
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE]
items = [{"name": name, "count": count} for name, count in top_slice]
sum_top = sum(count for name, count in top_slice)
total_topics = sum(topic_counts.values())
other_count = max(0, total_topics - sum_top)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
return {"items": items}
except Exception as e:
logger.error("Failed to query top news topics for entity: %s", e)
@@ -1066,11 +1066,24 @@ class NewsTrendStrategy(TrendStrategy):
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
# Scan UDE news postprocessed index to get matching news IDs without size limit cutoffs
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]:
news_ids: Set[str] = set()
if fuzzy:
term = t_name
es_query = {"match": {"topics.display_name": term}}
es_query = {"term": {"topic_matches.topic_display_name.keyword": term}}
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
query=es_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_source", {}).get("news_id") or hit.get("_id")
if nid:
news_ids.add(str(nid))
except Exception as e:
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
else:
if keywords and idx < len(keywords) and keywords[idx]:
raw_kw = keywords[idx]
@@ -1079,43 +1092,28 @@ class NewsTrendStrategy(TrendStrategy):
term = t_name
else:
term = t_name
es_query = {"match": {"keywords": term}}
news_ids: Set[str] = set()
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES_POSTPROC.value,
query=es_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(nid)
except Exception as e:
logger.warning("Failed to scan UDE news postproc: %s", e)
# If non-fuzzy keyword search, also search article content fields in 'aktuell' index
if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
try:
content_query = {
"query_string": {
"query": term,
"fields": AKTUELLES_SEARCH_FIELDS,
"default_operator": "AND",
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
try:
content_query = {
"query_string": {
"query": term,
"fields": AKTUELLES_SEARCH_FIELDS,
"default_operator": "AND",
}
}
}
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES.value,
query=content_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(nid)
except Exception as e:
logger.warning("Failed to scan UDE news content in aktuell: %s", e)
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES.value,
query=content_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(str(nid))
except Exception as e:
logger.warning("Failed to scan UDE news content in aktuell: %s", e)
return list(news_ids)
@@ -1134,7 +1132,16 @@ class NewsTrendStrategy(TrendStrategy):
"query": {
"bool": {
"filter": [
{"ids": {"values": chunk}},
{
"bool": {
"should": [
{"ids": {"values": chunk}},
{"terms": {"news_id.keyword": chunk}},
{"terms": {"news_id": chunk}},
],
"minimum_should_match": 1,
}
},
TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year),
]
}
@@ -13,6 +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>;
@@ -67,6 +67,7 @@ export interface TopAuthor {
export interface TopAuthorStatistics {
institution_id: string;
works: TopAuthor[];
projects: TopAuthor[];
eu_projects: TopAuthor[];
patents: TopAuthor[];
news: TopAuthor[];
@@ -271,7 +271,7 @@
<header class="top-authors-header">
<div>
<h2>Top 10 Personen aller Zeiten</h2>
<p>Nach Anzahl der Works, Patente und News Ihrer Organisation.</p>
<p>Nach Anzahl der Works, DFG-Projekte, Patente und News Ihrer Organisation.</p>
</div>
<div class="top-authors-period-toggle" aria-label="Works-Zeitraum">
<button
@@ -312,13 +312,18 @@
<div class="author-bar-label">
@if (entry.id) {
<a
class="author-link"
[routerLink]="['/person', entry.id, 'overview']"
[title]="entry.name">
{{ entry.name }}
class="author-name author-link"
[routerLink]="authorLink(dataset, entry)"
[queryParams]="authorQueryParams(dataset, entry)"
[title]="authorDisplayName(dataset, entry)">
{{ authorDisplayName(dataset, entry) }}
</a>
} @else {
<span [title]="entry.name">{{ entry.name }}</span>
<span
class="author-name"
[title]="authorDisplayName(dataset, entry)">
{{ authorDisplayName(dataset, entry) }}
</span>
}
<strong>{{ entry.count | number }}</strong>
</div>
@@ -281,8 +281,10 @@
margin-bottom: 0.25rem;
font-size: 0.85rem;
span {
.author-name {
overflow: hidden;
color: #1d4ed8;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -290,8 +292,6 @@
.author-link {
overflow: hidden;
color: #1d4ed8;
font-weight: 600;
text-decoration: none;
text-overflow: ellipsis;
white-space: nowrap;
@@ -39,6 +39,12 @@ type DashboardStatisticKey =
| 'eu_projects'
| 'bmbf_projects'
| 'dfg_projects';
type TopAuthorDataset = {
title: string;
icon: string;
entries: TopAuthor[];
stripAuthorTitle?: boolean;
};
@Component({
selector: 'dashboard',
imports: [
@@ -142,11 +148,7 @@ export class DashboardComponent implements OnInit {
return this.statisticLoading[key];
}
topAuthorDatasets(): Array<{
title: string;
icon: string;
entries: TopAuthor[];
}> {
topAuthorDatasets(): TopAuthorDataset[] {
return [
{
title: 'Publikationen',
@@ -163,15 +165,17 @@ export class DashboardComponent implements OnInit {
icon: 'description',
entries: this.topAuthors?.patents ?? [],
},
{
title: 'DFG Projekte',
icon: 'account_tree',
entries: this.topAuthors?.projects ?? [],
stripAuthorTitle: true,
},
{ title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] },
];
}
visibleTopAuthorDatasets(): Array<{
title: string;
icon: string;
entries: TopAuthor[];
}> {
visibleTopAuthorDatasets(): TopAuthorDataset[] {
const datasets = this.topAuthorDatasets();
return this.topAuthorsLoading
? datasets
@@ -206,6 +210,30 @@ export class DashboardComponent implements OnInit {
return (count / maximum) * 100;
}
authorDisplayName(dataset: TopAuthorDataset, entry: TopAuthor): string {
if (!dataset.stripAuthorTitle) return entry.name;
return (
entry.name
.replace(
/^(?:(?:(?:apl\.\s*)?prof(?:essor)?\.?|priv\.-doz\.?|pd|dr\.?)\s+)+/i,
'',
)
.trim() || entry.name
);
}
authorLink(_dataset: TopAuthorDataset, entry: TopAuthor): string[] {
return ['/person', entry.id!, 'overview'];
}
authorQueryParams(
_dataset: TopAuthorDataset,
_entry: TopAuthor,
): Record<string, string | number> | null {
return null;
}
organizationName(): string {
return this.statistics?.organization_name ?? 'Ihre Organisation';
}
@@ -132,14 +132,24 @@ export class SearchResultsStateService {
// without a resolvable keyword are skipped when building the lookup map
// so they can never collide on an `undefined` key and shadow a real one.
readonly topicsList = computed(() => {
const list = this.keywords().map((kw) => {
const entry = this.selectedKeywordEntries().find(
(e) =>
e.llm_keyword?.keyword?.trim().toLowerCase() ===
kw.trim().toLowerCase(),
);
return entry?.topic_mapping?.topic?.display_name ?? kw;
});
const list = this.keywords()
.map((kw) => {
const normalized = kw.trim().toLowerCase();
const entry = this.selectedKeywordEntries().find(
(e) =>
e.llm_keyword?.keyword?.trim().toLowerCase() === normalized ||
e.topic_mapping?.topic?.id?.trim().toLowerCase() === normalized,
);
const displayName = entry?.topic_mapping?.topic?.display_name;
if (displayName && !displayName.startsWith('http')) {
return displayName;
}
if (kw.startsWith('http') || kw.includes('openalex.org/topics')) {
return '';
}
return kw;
})
.filter((t) => t.length > 0);
return Array.from(new Set(list));
});
@@ -8,7 +8,10 @@ import { CommonModule } from '@angular/common';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { TrendResponse } from '../../../api';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import {
topicHierarchyColor,
TopicColorVariant,
} from '../../../resolvers/utils/topic-colors';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
@@ -25,7 +28,8 @@ export class UniPieChartComponent {
readonly entityName = input<string | null>(null);
readonly startYear = input<number>(2010);
readonly endYear = input<number>(2025);
readonly getTopicColor = input<(topic: string) => string>();
readonly getTopicColor =
input<(topic: string, variant?: TopicColorVariant) => string>();
// Inputs for direct rendering (useful for overall top 10 topics chart)
readonly titleText = input<string | null>(null);
@@ -33,15 +37,18 @@ export class UniPieChartComponent {
readonly loading = input<boolean>(false);
readonly error = input<boolean>(false);
private resolveTopicColor(topic: string): string {
private resolveTopicColorTokens(topic: string) {
if (topic === 'Andere Themen') {
return '#9ca3af'; // gray for "Other" topics
return { color: 'hsl(214, 20%, 93%)', border: 'hsl(214, 20%, 80%)' };
}
const customResolver = this.getTopicColor();
if (customResolver) {
return customResolver(topic);
}
return topicHierarchyColor({ name: topic });
const bgColor = customResolver
? customResolver(topic, 'bg')
: topicHierarchyColor({ name: topic }, 'bg');
const border = customResolver
? customResolver(topic, 'border')
: topicHierarchyColor({ name: topic }, 'border');
return { color: bgColor, border };
}
readonly chartOptions = computed<EChartsOption>(() => {
@@ -79,13 +86,19 @@ export class UniPieChartComponent {
// 3. If direct pieData input is provided, use it
const directData = this.pieData();
if (directData !== null) {
pieDataList = directData.map((item) => ({
value: item.value,
name: item.name,
itemStyle: {
color: this.resolveTopicColor(item.name),
},
}));
pieDataList = directData.map((item) => {
const tokens = this.resolveTopicColorTokens(item.name);
return {
value: item.value,
name: item.name,
itemStyle: {
color: tokens.color,
opacity: 0.95,
borderColor: tokens.border,
borderWidth: 1.5,
},
};
});
title = this.titleText() ?? 'Themenverteilung';
} else {
// Otherwise, filter and extract from TrendResponse
@@ -125,11 +138,15 @@ export class UniPieChartComponent {
const totalRaw = filtered.reduce((sum, item) => sum + item.raw, 0);
if (totalRaw > 0) {
const tokens = this.resolveTopicColorTokens(topicName);
pieDataList.push({
value: totalRaw,
name: topicName,
itemStyle: {
color: this.resolveTopicColor(topicName),
color: tokens.color,
opacity: 0.95,
borderColor: tokens.border,
borderWidth: 1.5,
},
});
}
@@ -199,11 +216,17 @@ export class UniPieChartComponent {
smooth: true,
},
emphasis: {
scale: true,
scaleSize: 6,
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.2)',
},
label: {
show: true,
fontSize: 10,
fontWeight: 'bold',
formatter: '{b}\n{c} ({d}%)',
},
},
data: pieDataList,
@@ -79,9 +79,13 @@ export class UniTrendChartComponent {
// Build series: Line in top grid, growth volume bars and S-Curve in bottom grid
trendData.series.forEach((entity, entityIdx) => {
const color = getFn
const rawColor = getFn
? getFn(entity.entity_id)
: entityColors[entityIdx % entityColors.length];
const color = rawColor.replace(
/hsl\(\s*([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)%\s+([+-]?\d+(?:\.\d+)?)%\s*\)/gi,
'hsl($1, $2%, $3%)',
);
if ((entity as any).visible === false) {
return;
}
@@ -97,16 +101,13 @@ export class UniTrendChartComponent {
return currentMode === 'normalized' ? yrData.normalized : yrData.raw;
});
const isStacked = currentMode === 'total' || currentMode === 'cumulative';
series.push({
name: `${entity.entity_name}`,
type: 'line',
xAxisIndex: 0,
yAxisIndex: 0,
stack: isStacked ? 'Total' : undefined,
areaStyle: {
opacity: isStacked ? 0.3 : 0.12,
opacity: 0.12,
},
data: lineData,
smooth: true,
@@ -142,7 +143,7 @@ export class UniTrendChartComponent {
yAxisIndex: 1,
data: bars,
itemStyle: {
color: color, // Takes the color of the institution!
color: color,
},
markLine:
entityIdx === 0
@@ -202,9 +203,13 @@ export class UniTrendChartComponent {
res += `<div style="max-height: 280px; overflow-y: auto; padding-right: 6px;">`;
trendData.series.forEach((entity: TrendSeries, entityIdx: number) => {
const color = getFn
const rawColor = getFn
? getFn(entity.entity_id)
: entityColors[entityIdx % entityColors.length];
const color = rawColor.replace(
/hsl\(\s*([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)%\s+([+-]?\d+(?:\.\d+)?)%\s*\)/gi,
'hsl($1, $2%, $3%)',
);
if ((entity as any).visible === false) {
return;
}
@@ -175,15 +175,15 @@
<!-- Main Full-Width Content Area -->
<main class="trend-main-fullwidth">
@if (isPageResolving() || (isTrendLoading() && !rawTrendResponse())) {
<app-loading
text="Trenddaten werden geladen..."
icon="trending_up"
[size]="200"
[diameter]="200"></app-loading>
} @else if (rawTrendResponse()) {
@if (rawTrendResponse()) {
<!-- Chart Holder Card (100% Full Width) -->
<div class="chart-holder-card">
@if (isTrendLoading() || isPageResolving()) {
<div class="loader-overlay">
<mat-spinner diameter="40"></mat-spinner>
<p>Daten werden geladen...</p>
</div>
}
@if (selectedTrendTopics().length > 0) {
<div class="chart-topic-tabs">
@for (topic of selectedTrendTopics(); track topic) {
@@ -18,9 +18,6 @@ import {
ResolveEnd,
} from '@angular/router';
import { forkJoin } from 'rxjs';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import {
@@ -29,7 +26,6 @@ import {
} from '@angular/material/button-toggle';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatTooltipModule } from '@angular/material/tooltip';
import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component';
import { UniPieChartComponent } from '../uni-pie-chart/uni-pie-chart.component';
@@ -48,14 +44,16 @@ import {
} from '../../../api';
import { CredentialService } from '../../../shared/services/credential.service';
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import {
topicHierarchyColor,
TopicColorVariant,
} from '../../../resolvers/utils/topic-colors';
import { YearRangeSliderComponent } from '../../../shared/ui/year-range-slider/year-range-slider.component';
import { LocationSelectorComponent } from '../../../shared/ui/location-selector/location-selector.component';
import { InstitutionSelectorComponent } from '../../../shared/ui/institution-selector/institution-selector.component';
import { AuthorSelectorComponent } from '../../../shared/ui/author-selector/author-selector.component';
import { AuthorInstitutionSelectorComponent } from '../../../shared/ui/author-institution-selector/author-institution-selector.component';
import { SearchResultsStateService } from '../../keywords-search/search-results/search-results-state.service';
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
import { TopicTreemapComponent } from '../../../shared/ui/topic-treemap/topic-treemap.component';
import {
TopicTreemapData,
@@ -145,7 +143,6 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
InstitutionSelectorComponent,
AuthorSelectorComponent,
AuthorInstitutionSelectorComponent,
LoadingComponent,
TopicTreemapComponent,
],
templateUrl: './uni-trend-parent.component.html',
@@ -260,36 +257,61 @@ export class UniTrendParentComponent implements OnInit {
return topicOrKeyword;
}
getTopicColor(topic: string): string {
getTopicColor(topic: string, variant: TopicColorVariant = 'base'): string {
const mapped = this.getMappedTopic(topic);
const entries = this.state?.selectedKeywordEntries() ?? [];
const ext = this.state?.extractedKeywords() ?? [];
const man = this.state?.manualKeywords() ?? [];
const topicsList = this.state?.topics() ?? [];
const all = [...entries, ...ext, ...man];
const targetLower = topic.toLowerCase().trim();
const mappedLower = mapped.toLowerCase().trim();
const topicObj = topicsList.find(
(t) =>
t.display_name?.toLowerCase().trim() === mappedLower ||
t.display_name?.toLowerCase().trim() === targetLower ||
t.id?.toLowerCase().trim() === targetLower,
);
if (topicObj) {
return topicHierarchyColor(
{
name: topicObj.display_name,
field_name: topicObj.field?.display_name,
domain_name: topicObj.domain?.display_name,
field_id: topicObj.field?.id,
domain_id: topicObj.domain?.id,
id: topicObj.id,
},
variant,
);
}
const match = all.find(
(e) =>
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
mappedLower ||
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
targetLower ||
e.llm_keyword?.keyword?.toLowerCase().trim() === targetLower,
e.llm_keyword?.keyword?.toLowerCase().trim() === targetLower ||
e.llm_keyword?.keyword?.toLowerCase().trim() === mappedLower,
);
if (match && match.topic_mapping?.topic) {
return topicHierarchyColor({
name: match.topic_mapping.topic.display_name,
field_name: match.topic_mapping.topic.field?.display_name,
domain_name: match.topic_mapping.topic.domain?.display_name,
field_id: match.topic_mapping.topic.field?.id,
domain_id: match.topic_mapping.topic.domain?.id,
id: match.topic_mapping.topic.id,
});
return topicHierarchyColor(
{
name: match.topic_mapping.topic.display_name,
field_name: match.topic_mapping.topic.field?.display_name,
domain_name: match.topic_mapping.topic.domain?.display_name,
field_id: match.topic_mapping.topic.field?.id,
domain_id: match.topic_mapping.topic.domain?.id,
id: match.topic_mapping.topic.id,
},
variant,
);
}
return topicHierarchyColor({ name: mapped });
return topicHierarchyColor({ name: mapped }, variant);
}
readonly boundGetTopicColor = this.getTopicColor.bind(this);
@@ -530,14 +552,23 @@ export class UniTrendParentComponent implements OnInit {
if (!res || !res.series || res.series.length === 0) return false;
const startYr = this.startYear();
const endYr = this.endYear();
const mapped = this.getMappedTopic(topic).toLowerCase().trim();
const topicLower = topic.toLowerCase().trim();
const mappedLower = this.getMappedTopic(topic).toLowerCase().trim();
return !res.series.some((s) => {
const yearlyList =
s.topic_data?.[topic] ||
s.topic_data?.[mapped] ||
Object.values(s.topic_data || {})[0];
if (!yearlyList) return false;
if (!s.topic_data) return false;
const matchingKey = Object.keys(s.topic_data).find((key) => {
const kLower = key.toLowerCase().trim();
return (
kLower === topicLower ||
kLower === mappedLower ||
(kLower.startsWith('news_topic_') &&
kLower.slice('news_topic_'.length) === topicLower)
);
});
if (!matchingKey) return false;
const yearlyList = s.topic_data[matchingKey];
if (!yearlyList || !Array.isArray(yearlyList)) return false;
const total = yearlyList
.filter((y) => y.year >= startYr && y.year <= endYr)
.reduce((sum, item) => sum + (item.raw || 0), 0);
@@ -545,6 +576,12 @@ export class UniTrendParentComponent implements OnInit {
});
}
findFirstNonEmptyTopic(topics: string[]): string {
if (!topics || topics.length === 0) return '';
const nonEmpties = topics.filter((t) => !this.isTopicEmpty(t));
return nonEmpties.length > 0 ? nonEmpties[0] : topics[0] || '';
}
isVisible(id: string): boolean {
return this.entityVisibilityMap().get(id) !== false;
}
@@ -666,6 +703,25 @@ export class UniTrendParentComponent implements OnInit {
);
const resolveEntityName = (s: TrendSeries): string => {
let rawName = s.entity_name || '';
if (rawName.startsWith('news_topic_')) {
rawName = rawName.slice('news_topic_'.length);
}
if (
rawName.startsWith('http://') ||
rawName.startsWith('https://') ||
rawName.includes('openalex.org/topics/')
) {
const mapped = this.getMappedTopic(rawName);
if (mapped && !mapped.startsWith('http')) {
return mapped;
}
const match = this.state?.topics()?.find((t) => t.id === rawName);
if (match?.display_name) {
return match.display_name;
}
}
const cId = cleanId(s.entity_id);
if (s.entity_type === 'institution') {
@@ -754,8 +810,16 @@ export class UniTrendParentComponent implements OnInit {
}
});
// Preserve existing keys as well
Object.assign(newTopicData, s.topic_data);
// Preserve extra keys only if they are not raw URIs
Object.entries(s.topic_data).forEach(([rk, val]) => {
if (
!rk.startsWith('http://') &&
!rk.startsWith('https://') &&
!newTopicData[rk]
) {
newTopicData[rk] = val;
}
});
return {
...s,
@@ -873,10 +937,10 @@ export class UniTrendParentComponent implements OnInit {
if (resolved.topics && resolved.topics.length > 0) {
this.selectedTrendTopics.set(resolved.topics);
this.fetchedTopics.set([...resolved.topics]);
const firstNonEmpty = resolved.topics.find(
(t: string) => !this.isTopicEmpty(t),
);
const targetTopic = firstNonEmpty || resolved.topics[0];
const targetTopic =
resolved.initialActiveTopic ||
resolved.topics.find((t: string) => !this.isTopicEmpty(t)) ||
resolved.topics[0];
this.activeChartTopic.set(targetTopic);
} else {
this.fetchedTopics.set([...this.selectedTrendTopics()]);
@@ -910,6 +974,14 @@ export class UniTrendParentComponent implements OnInit {
this.fetchedAuthors.set([...this.comparisonAuthors()]);
}
if (resolved.topSuggestions) {
this.topSuggestions.set(resolved.topSuggestions);
}
if (resolved.recommendedAuthors) {
this.recommendedAuthors.set(resolved.recommendedAuthors);
}
if (resolved.treemapData) {
this.topicTreemap.set(resolved.treemapData);
}
@@ -953,11 +1025,20 @@ export class UniTrendParentComponent implements OnInit {
this.selectedTrendTopics.set(topics);
}
// Initialize active chart topic to the first selected topic if empty or invalid
// Initialize active chart topic to a valid non-empty topic
const active = currentActive;
const updatedSelections = untracked(() => this.selectedTrendTopics());
if (!active || !updatedSelections.includes(active)) {
this.activeChartTopic.set(updatedSelections[0] || '');
const mappedActive = this.getMappedTopic(active);
if (
mappedActive &&
updatedSelections.includes(mappedActive) &&
!this.isTopicEmpty(mappedActive)
) {
this.activeChartTopic.set(mappedActive);
} else {
this.activeChartTopic.set(
this.findFirstNonEmptyTopic(updatedSelections),
);
}
// If comparison list is empty, initialize default institutions/authors dynamically
@@ -1029,7 +1110,11 @@ export class UniTrendParentComponent implements OnInit {
: a.id.toLowerCase();
return rawSeriesCleanIds.has(cleanA);
});
} else if (searchType === 'news' || searchType === 'all') {
} else if (
searchType === 'news' ||
searchType === 'all' ||
searchType === 'patents'
) {
allEntitiesFetched = true;
} else {
// publications, patents, projects
@@ -1380,7 +1465,11 @@ export class UniTrendParentComponent implements OnInit {
if (kws.length === 0) return;
const topics = this.state?.topicsList() ?? kws;
const topic = topics[0] || kws[0] || 'Artificial Intelligence';
const topic =
this.findFirstNonEmptyTopic(topics) ||
topics[0] ||
kws[0] ||
'Artificial Intelligence';
this.personsApiService
.searchPersonsList(
@@ -1576,7 +1665,6 @@ export class UniTrendParentComponent implements OnInit {
});
}
this.isTrendLoading.set(false);
this.updateUrlParams();
},
error: () => {
this.isTrendLoading.set(false);
@@ -1676,8 +1764,8 @@ export class UniTrendParentComponent implements OnInit {
this.selectedTrendTopics.set(updated);
const active = this.activeChartTopic();
if (!updated.includes(active)) {
this.activeChartTopic.set(updated[0] || '');
if (!updated.includes(active) || this.isTopicEmpty(active)) {
this.activeChartTopic.set(this.findFirstNonEmptyTopic(updated));
}
}
@@ -1852,13 +1940,12 @@ export class UniTrendParentComponent implements OnInit {
}
}
// Topic tab toggle (data reuses instantly)
// Topic tab toggle (data reuses instantly, no router navigation to prevent chart flickering)
updateActiveChartTopic(topic: string) {
if (this.isTopicEmpty(topic)) {
return;
}
this.activeChartTopic.set(topic);
this.updateUrlParams();
}
// Autocomplete query changes for institutions
+129 -10
View File
@@ -1,8 +1,13 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { catchError, of, Observable, map } from 'rxjs';
import { TrendResponse, UniversityRankingsService } from '../api';
import { catchError, of, Observable, map, forkJoin } from 'rxjs';
import {
TrendResponse,
UniversityRankingsService,
PersonsService,
} from '../api';
import { SearchResultsStateService } from '../modules/keywords-search/search-results/search-results-state.service';
import { CredentialService } from '../shared/services/credential.service';
export interface CompareItem {
id: string;
@@ -19,6 +24,9 @@ export interface UniTrendResolvedData {
countries: CompareItem[];
regions: CompareItem[];
authors: CompareItem[];
initialActiveTopic?: string;
topSuggestions?: any[];
recommendedAuthors?: any[];
treemapNode?: string | null;
}
@@ -28,11 +36,18 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
): Observable<UniTrendResolvedData> => {
const params = route.queryParamMap;
const searchState = inject(SearchResultsStateService, { optional: true });
const credentialService = inject(CredentialService, { optional: true });
const searchType = params.get('search_type') || 'publications';
const fuzzy = params.get('fuzzy') !== 'false';
const treemapNode = params.get('treemapNode');
// Primary institution from user token / credential service
const primaryInstId =
credentialService?.effectiveInstitutionId() || 'I62318514';
const primaryInstName =
credentialService?.organizationName() || 'Universität Duisburg-Essen';
// Extract keywords & topics
let keywords = params.getAll('keyword');
if (keywords.length === 0) {
@@ -79,9 +94,17 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const cleanId = parts[0].includes('/')
? parts[0].split('/').pop() || parts[0]
: parts[0];
return { id: cleanId, name: parts[1] || cleanId };
const isPrimary =
cleanId.toLowerCase() === primaryInstId.toLowerCase() ||
primaryInstId.toLowerCase().includes(cleanId.toLowerCase());
const name = parts[1] || (isPrimary ? primaryInstName : parts[0]);
return { id: cleanId, name };
});
if (parsedInstitutions.length === 0 && searchType !== 'authors') {
parsedInstitutions.push({ id: primaryInstId, name: primaryInstName });
}
const countryParams = params.getAll('countries');
const parsedCountries: CompareItem[] = countryParams.map((c) => {
const parts = c.split('|');
@@ -103,15 +126,22 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const instIds =
parsedInstitutions.length > 0
? parsedInstitutions.map((i) => i.id)
: ['I62318514'];
: [primaryInstId];
const countryIds =
parsedCountries.length > 0 ? parsedCountries.map((c) => c.id) : ['DE'];
const regionIds = parsedRegions.map((r) => r.id);
const authorIds = parsedAuthors.map((a) => a.id);
const apiService = inject(UniversityRankingsService);
const personsService = inject(PersonsService, { optional: true });
return apiService
const primaryTopic = topics[0] || 'Artificial Intelligence';
const countryFilter =
parsedCountries.length > 0 ? parsedCountries[0].id : undefined;
const regionFilter =
parsedRegions.length > 0 ? parsedRegions[0].id : undefined;
const trendObs$ = apiService
.getTrendApiInseServiceUniversityRankingsTrendGet(
topics,
keywords,
@@ -122,9 +152,94 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
authorIds,
searchType as any,
)
.pipe(
catchError(() => of(null)),
map((trendResponse) => ({
.pipe(catchError(() => of(null)));
const topInstObs$ =
searchType !== 'authors'
? apiService
.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
primaryTopic,
regionFilter,
countryFilter,
6,
)
.pipe(catchError(() => of([])))
: of([]);
const recAuthorsObs$ =
searchType === 'authors' && personsService
? personsService
.searchPersonsList(
undefined,
primaryInstId,
'cited_by_count',
'desc',
[primaryTopic],
1,
6,
undefined,
)
.pipe(
map((res: any) => res.results || []),
catchError(() => of([])),
)
: of([]);
return forkJoin({
trendResponse: trendObs$,
topSuggestions: topInstObs$,
recommendedAuthors: recAuthorsObs$,
}).pipe(
map(({ trendResponse, topSuggestions, recommendedAuthors }) => {
// Find the first topic with non-zero publication data
let initialActiveTopic = primaryTopic;
if (
trendResponse?.series &&
trendResponse.series.length > 0 &&
topics.length > 0
) {
const nonEmptyTopic = topics.find((t) =>
trendResponse.series.some((s) => {
if (!s.topic_data) return false;
const tLower = t.toLowerCase().trim();
const matchingKey = Object.keys(s.topic_data).find((key) => {
const kLower = key.toLowerCase().trim();
return (
kLower === tLower ||
(kLower.startsWith('news_topic_') &&
kLower.slice('news_topic_'.length) === tLower)
);
});
if (!matchingKey) return false;
const yearlyList = s.topic_data[matchingKey];
if (!yearlyList || !Array.isArray(yearlyList)) return false;
const total = yearlyList.reduce(
(sum, item) => sum + (item.raw || 0),
0,
);
return total > 0;
}),
);
if (nonEmptyTopic) {
initialActiveTopic = nonEmptyTopic;
}
}
// If in author mode and no explicit authors were passed in URL, populate default top authors
if (
searchType === 'authors' &&
parsedAuthors.length === 0 &&
recommendedAuthors?.length
) {
recommendedAuthors.slice(0, 3).forEach((author: any) => {
parsedAuthors.push({
id: author.id,
name: author.display_name || 'Unbekannt',
});
});
}
return {
trendResponse,
searchType,
topics,
@@ -134,7 +249,11 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
countries: parsedCountries,
regions: parsedRegions,
authors: parsedAuthors,
initialActiveTopic,
topSuggestions: topSuggestions as any[],
recommendedAuthors: recommendedAuthors as any[],
treemapNode,
})),
);
};
}),
);
};
+13 -1
View File
@@ -78,10 +78,15 @@ export function classificationSectionColor(
return `hsl(${normalizeHue(hue)} ${FIELD_COLOR_SATURATION}% ${FIELD_COLOR_LIGHTNESS}%)`;
}
export type TopicColorVariant = 'base' | 'bg' | 'border';
export function topicHierarchyColor(
topic: TopicHierarchyColorInput | undefined | null,
variant: TopicColorVariant = 'base',
): string {
if (!topic) {
if (variant === 'bg') return 'hsl(214, 80%, 95%)';
if (variant === 'border') return 'hsl(214, 60%, 85%)';
return 'hsl(214 82% 42%)';
}
@@ -102,7 +107,14 @@ export function topicHierarchyColor(
stableHue(fallbackIdentity);
const hue = normalizeHue(baseHue);
return `hsl(${hue} ${FIELD_COLOR_SATURATION}% ${FIELD_COLOR_LIGHTNESS}%)`;
if (variant === 'bg') {
return `hsl(${hue}, 75%, 80%)`;
}
if (variant === 'border') {
return `hsl(${hue}, 60%, 65%)`;
}
return `hsl(${hue}, ${FIELD_COLOR_SATURATION}%, ${FIELD_COLOR_LIGHTNESS}%)`;
}
function normalizeColorKey(
@@ -36,7 +36,7 @@ interface TreemapBreadcrumb {
styleUrl: './topic-treemap.component.scss',
})
export class TopicTreemapComponent implements OnChanges {
private readonly fieldColorOpacity = 0.78;
private readonly fieldColorOpacity = 0.95;
@Input() data?: TopicTreemapData;
@Input() loading = false;
@Input() selectedNodeId?: string;
@@ -103,10 +103,13 @@ export class TopicTreemapComponent implements OnChanges {
private buildOptions(): EChartsOption {
const fields = this.data?.fields ?? [];
const hierarchyData = fields.map((field) => {
const fieldColor = topicHierarchyColor({
field_id: field.id,
field_name: field.name,
});
const fieldColor = topicHierarchyColor(
{
field_id: field.id,
field_name: field.name,
},
'bg',
);
return {
id: `field:${field.id}`,