refactor/trend_visual #255

Merged
kuzko merged 8 commits from refactor/trend_visual into dev 2026-08-01 13:05:16 +02:00
22 changed files with 3278 additions and 2249 deletions
+10 -1
View File
@@ -6,5 +6,14 @@ RUN mkdir /test && \
pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \
pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1"
ARG MODEL_NAME=intfloat/multilingual-e5-base
ENV MODEL_NAME=${MODEL_NAME}
ENV SENTENCE_TRANSFORMERS_HOME=/models
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-base')"
ENV HF_HOME=/models
RUN python -c "import os, sentence_transformers; sentence_transformers.SentenceTransformer(os.environ['MODEL_NAME'])"
ENV HF_HUB_OFFLINE=1
ENV TRANSFORMERS_OFFLINE=1
ENV HF_DATASETS_OFFLINE=1
+22 -3
View File
@@ -6,9 +6,28 @@ so it is available for local runs or testing.
Usage (run once from project root):
python service/sentence_transformer/download_model.py
"""
import os
import sys
from pathlib import Path
# Ensure service/src/main is in sys.path
current_dir = Path(__file__).parent.resolve()
src_main_dir = current_dir.parent / "src" / "main"
if str(src_main_dir) not in sys.path:
sys.path.insert(0, str(src_main_dir))
from inse.config import settings
from sentence_transformers import SentenceTransformer
MODEL_NAME = "intfloat/multilingual-e5-base"
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
MODEL_NAME = settings.sentence_transformers_model_name
print(f"Downloading '{MODEL_NAME}' to cache directory...")
model = SentenceTransformer(MODEL_NAME)
print("Done.")
print(f"Verifying offline model loading for '{MODEL_NAME}'...")
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"
os.environ["HF_DATASETS_OFFLINE"] = "1"
offline_model = SentenceTransformer(MODEL_NAME, local_files_only=True)
print("Done. Model downloaded and verified for 100% offline usage.")
+2 -1
View File
@@ -169,8 +169,9 @@ def main():
print("No topics found. Exiting.")
return
from inse.util import get_model
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
model = SentenceTransformer(MODEL_NAME)
model = get_model()
# 1. Gather all texts to embed
keywords_by_topic = []
@@ -3,6 +3,7 @@ from typing import List, Optional
from fastapi import APIRouter, Query, Depends
from inse.tags import Tags
from inse.exceptions import BadRequestException
from . import logic, trend_logic
from .model import (
RankingResponse,
@@ -43,7 +44,7 @@ def get_trend_strategy(search_type: TrendSearchType = Query(TrendSearchType.PUBL
return NewsTrendStrategy()
elif search_type == TrendSearchType.ALL:
return AllTrendStrategy()
raise ValueError(f"Unknown search type: {search_type}")
raise BadRequestException(f"Unknown search type: {search_type}")
@router.get(
"",
@@ -74,6 +75,8 @@ async def get_trend(
authors: Optional[List[str]] = Query(None, description="List of OpenAlex Author IDs"),
strategy: TrendStrategy = Depends(get_trend_strategy)
):
if not topics or len(topics) == 0:
raise BadRequestException("Topics list cannot be empty")
return await strategy.get_trend(
topics=topics,
keywords=keywords,
@@ -128,12 +128,23 @@ async def get_top_institutions_by_region(
meta_top = await TrendMetadataResolver.resolve_all(topics=[topic])
topic_id = meta_top.get("resolved_topic_ids", {}).get(topic)
topic_display_name = meta_top.get("resolved_topic_names", {}).get(topic, topic)
topic_filter = (
{"term": {"topics.id.keyword": topic_id}}
if topic_id
else {"match_phrase": {"topics.display_name": topic}}
)
if not topic_id and (topic.startswith("https://openalex.org/") or (topic.startswith("T") and topic[1:].isdigit())):
topic_id = topic if topic.startswith("https://openalex.org/") else f"https://openalex.org/{topic}"
if topic_id:
topic_filter = {
"bool": {
"should": [
{"term": {"topics.id.keyword": topic_id}},
{"term": {"topics.id": topic_id}},
],
"minimum_should_match": 1,
}
}
else:
topic_filter = {"match_phrase": {"topics.display_name": topic_display_name}}
must_clauses: List[Dict[str, Any]] = [
{"term": {"type": "education"}},
@@ -12,15 +12,18 @@ DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
def clean_inst_id(id_str: str) -> str:
"""Extracts short OpenAlex ID from full URL or returns as-is."""
"""Extracts short OpenAlex ID from full URL or returns as-is, ensuring uppercase prefix."""
if not id_str:
return ""
s = id_str.strip()
return s.split("/")[-1] if "/" in s else s
raw_id = s.split("/")[-1] if "/" in s else s
if len(raw_id) > 1 and raw_id[0].isalpha():
return raw_id[0].upper() + raw_id[1:]
return raw_id.upper()
def to_full_inst_url(id_str: str) -> str:
"""Ensures institution ID is formatted as a full OpenAlex URL."""
"""Ensures institution ID is formatted as a full OpenAlex URL with proper capitalization."""
cleaned = clean_inst_id(id_str)
return f"https://openalex.org/{cleaned}" if cleaned else id_str
@@ -85,8 +88,9 @@ class TrendMetadataResolver:
alias_results = await asyncio.gather(*(get_alias(i) for i in inst_full_ids))
for short_id, alias_list in alias_results:
aliases_map[short_id] = alias_list
aliases_map[f"https://openalex.org/{short_id}"] = alias_list
s_upper = clean_inst_id(short_id)
aliases_map[s_upper] = alias_list
aliases_map[f"https://openalex.org/{s_upper}"] = alias_list
except Exception as e:
logger.warning("Failed to resolve institutions from ES: %s", e)
@@ -142,31 +146,65 @@ class TrendMetadataResolver:
async def fetch_topics():
topic_ids: Dict[str, str] = {}
topic_display_names: Dict[str, str] = {}
if not topic_names:
return topic_ids
return topic_ids, topic_display_names
should_clauses = []
for t in topic_names:
if not t:
continue
clean_id = clean_inst_id(t)
canonical_id = f"https://openalex.org/{clean_id}" if clean_id.startswith("T") else t
if t.startswith("https://openalex.org/") or (clean_id.startswith("T") and clean_id[1:].isdigit()):
should_clauses.extend([
{"term": {"id": canonical_id}},
{"term": {"id.keyword": canonical_id}},
{"term": {"id": clean_id}},
{"term": {"id.keyword": clean_id}},
])
else:
should_clauses.append({"match_phrase": {"display_name": t}})
try:
res = await elasticsearch.search(
index=ESIndex.OPENALEX_TOPICS.value,
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}},
size=len(topic_names) * 2,
query={"bool": {"should": should_clauses, "minimum_should_match": 1}},
size=max(10, len(topic_names) * 3),
source=["id", "display_name"],
cluster="nes",
)
for hit in res.get("hits", {}).get("hits", []):
src = hit["_source"]
full_id = src.get("id", "")
short_id = clean_inst_id(full_id)
canonical_id = f"https://openalex.org/{short_id}" if short_id.startswith("T") else full_id
d_name = src.get("display_name", "")
for t in topic_names:
if t.lower() in d_name.lower():
topic_ids[t] = src["id"]
t_clean = clean_inst_id(t)
t_canonical = f"https://openalex.org/{t_clean}" if t_clean.startswith("T") else t
if (
t == full_id
or t == short_id
or t == canonical_id
or t_canonical == canonical_id
or t_clean == short_id
or t.lower() in d_name.lower()
or d_name.lower() in t.lower()
):
topic_ids[t] = canonical_id
topic_display_names[t] = d_name
topic_display_names[canonical_id] = d_name
topic_display_names[short_id] = d_name
topic_display_names[full_id] = d_name
except Exception as e:
logger.warning("Failed to resolve topic IDs from ES: %s", e)
return topic_ids
return topic_ids, topic_display_names
(
(inst_names, inst_country_codes, inst_aliases),
country_names,
(continent_names, continent_country_codes),
resolved_topic_ids,
(resolved_topic_ids, resolved_topic_names),
) = await asyncio.gather(
fetch_institutions(),
fetch_countries(),
@@ -182,6 +220,7 @@ class TrendMetadataResolver:
"continent_names": continent_names,
"continent_country_codes": continent_country_codes,
"resolved_topic_ids": resolved_topic_ids,
"resolved_topic_names": resolved_topic_names,
}
@@ -196,6 +235,12 @@ class TrendQueryBuilder:
fuzzy: bool = True,
) -> Dict[str, Any]:
"""Builds a topic or keyword matching clause."""
target_id = resolved_topic_id
if not target_id and topic_display_name:
c_id = clean_inst_id(topic_display_name)
if c_id.startswith("T") and c_id[1:].isdigit():
target_id = f"https://openalex.org/{c_id}"
if not fuzzy and keyword:
return {
"bool": {
@@ -208,12 +253,15 @@ class TrendQueryBuilder:
"minimum_should_match": 1,
}
}
elif resolved_topic_id:
elif target_id:
c_id = clean_inst_id(target_id)
canonical_id = f"https://openalex.org/{c_id}" if c_id.startswith("T") else target_id
target_ids = list(dict.fromkeys([canonical_id, target_id, c_id]))
return {
"bool": {
"should": [
{"nested": {"path": "topics", "query": {"term": {"topics.id": resolved_topic_id}}}},
{"term": {"primary_topic.id": resolved_topic_id}},
{"nested": {"path": "topics", "query": {"terms": {"topics.id": target_ids}}}},
{"terms": {"primary_topic.id": target_ids}},
],
"minimum_should_match": 1,
}
@@ -316,7 +316,7 @@ class AuthorsTrendStrategy(TrendStrategy):
if not query_authors:
return TrendResponse(series=[], years=years_range)
query_authors_clean = [clean_inst_id(a).upper() for a in query_authors if a]
query_authors_clean = [clean_inst_id(a) for a in query_authors if a]
# Resolve author display names
resolved_names: Dict[str, str] = {}
@@ -329,7 +329,7 @@ class AuthorsTrendStrategy(TrendStrategy):
cluster=ESCluster.NES,
)
for hit in res.get("hits", {}).get("hits", []):
short_id = hit["_id"]
short_id = clean_inst_id(hit["_id"])
full_id = f"https://openalex.org/{short_id}"
display_name = hit["_source"].get("display_name", short_id)
resolved_names[short_id] = display_name
@@ -340,14 +340,12 @@ class AuthorsTrendStrategy(TrendStrategy):
meta = await TrendMetadataResolver.resolve_all(topics=topics)
resolved_topic_ids = meta["resolved_topic_ids"]
query_authors_full = [
a if a.startswith("https://openalex.org/") else f"https://openalex.org/{clean_inst_id(a).upper()}"
for a in query_authors
]
query_authors_full = [to_full_inst_url(a) for a in query_authors if a]
filters_map: Dict[str, Dict[str, Any]] = {}
for auth_id, auth_url in zip(query_authors, query_authors_full):
filters_map[f"author_{auth_id}"] = {
clean_id = clean_inst_id(auth_id)
filters_map[f"author_{clean_id}"] = {
"nested": {
"path": "authorships",
"query": {"term": {"authorships.author.id": auth_url}},
@@ -508,16 +506,17 @@ class PatentsTrendStrategy(TrendStrategy):
def matches_patent(patent, topic: str, keyword: Optional[str], is_fuzzy: bool) -> bool:
if matches_topic(patent, topic):
return True
if not is_fuzzy and keyword:
t_lower = topic.lower()
if patent.title and t_lower in patent.title.lower():
return True
if patent.abstract and t_lower in patent.abstract.lower():
return True
if keyword:
kw_lower = keyword.lower()
if patent.title and kw_lower in patent.title.lower():
return True
if patent.abstract and kw_lower in patent.abstract.lower():
return True
if patent.openalex_topics:
for ot in patent.openalex_topics:
if ot.topic_display_name and kw_lower in ot.topic_display_name.lower():
return True
return False
accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = {
+72 -60
View File
@@ -1,60 +1,72 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains utility functions
for the service implementation.
"""
from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise NotFoundException("Not found.")
else:
return value
def get_persons_data(hit:dict):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
return author
from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model
_model: SentenceTransformer | None = None
def get_model():
global _model
if _model is None:
import os
# If SENTENCE_TRANSFORMERS_HOME is not set, check if container-baked /models folder is available
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
if os.path.exists("/models"):
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
os.environ["HF_HUB_OFFLINE"] = "1"
else:
# If it is set to /models, enforce offline mode as it is baked into the image
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
os.environ["HF_HUB_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name
_model = SentenceTransformer(model_name)
return _model
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains utility functions
for the service implementation.
"""
from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise NotFoundException("Not found.")
else:
return value
def get_persons_data(hit:dict):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
return author
from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model
_model: SentenceTransformer | None = None
def get_model():
global _model
if _model is None:
import os
# Determine offline mode
is_offline = os.environ.get("HF_HUB_OFFLINE") == "1"
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
if os.path.exists("/models"):
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
os.environ["HF_HOME"] = "/models"
is_offline = True
elif os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
is_offline = True
if is_offline:
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"
os.environ["HF_DATASETS_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name
try:
if is_offline:
_model = SentenceTransformer(model_name, local_files_only=True)
else:
_model = SentenceTransformer(model_name)
except Exception:
# Fallback if local_files_only fails in unexpected local dev environments
_model = SentenceTransformer(model_name)
return _model␍
File diff suppressed because it is too large Load Diff
@@ -1,19 +1,17 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface DfgProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
export interface DfgProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
+4 -1
View File
@@ -285,6 +285,7 @@ export const routes: Routes = [
'search_type',
'topic',
'topics',
'trend_topics',
'keyword',
'keywords',
'institutions',
@@ -294,7 +295,9 @@ export const routes: Routes = [
'fuzzy',
];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
(key) =>
from.queryParamMap.getAll(key).join(',') !==
to.queryParamMap.getAll(key).join(','),
);
},
},
@@ -51,9 +51,7 @@
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="
'Durchschnittliche jährliche Förderung durch die Europäische Union'
"
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
[value]="
(euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
@@ -150,7 +150,9 @@ export class SearchResultsStateService {
return kw;
})
.filter((t) => t.length > 0);
return Array.from(new Set(list));
const uniqueTopics = Array.from(new Set(list));
return uniqueTopics;
});
setPayload(payload: SearchResultsPayload): void {
@@ -0,0 +1,61 @@
import { TrendSeries } from '../../../api';
export interface CompareItem {
id: string;
name: string;
}
export interface TrendStrategyConfig {
showInstitutionSelector: boolean;
showLocationSelector: boolean;
showAuthorSelector: boolean;
yAxisLabel: string;
chartTitle: string;
}
export type TrendSeriesWithVisibility = TrendSeries & { visible?: boolean };
export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
publications: {
showInstitutionSelector: true,
showLocationSelector: true,
showAuthorSelector: false,
yAxisLabel: 'Publikationen',
chartTitle: 'Publikationstrends',
},
authors: {
showInstitutionSelector: false,
showLocationSelector: false,
showAuthorSelector: true,
yAxisLabel: 'Publikationen von Autoren',
chartTitle: 'Autorentrends',
},
patents: {
showInstitutionSelector: false,
showLocationSelector: false,
showAuthorSelector: false,
yAxisLabel: 'Patentanmeldungen',
chartTitle: 'Patentrecherche-Trends',
},
projects: {
showInstitutionSelector: true,
showLocationSelector: true,
showAuthorSelector: false,
yAxisLabel: 'Projektförderung (Anz)',
chartTitle: 'Drittmittelförderung-Trends',
},
news: {
showInstitutionSelector: false,
showLocationSelector: false,
showAuthorSelector: false,
yAxisLabel: 'Pressemitteilungen',
chartTitle: 'Nachrichtentrends',
},
all: {
showInstitutionSelector: false,
showLocationSelector: false,
showAuthorSelector: false,
yAxisLabel: 'Aktivitäts-Index',
chartTitle: 'Cross-Domain-Themenlebenszyklus (UDE)',
},
};
@@ -0,0 +1,213 @@
import { Injectable, inject, signal } from '@angular/core';
import {
UniversityRankingsService,
PersonsService,
TrendResponse,
TopInstitutionItem,
Author,
} from '../../../api';
import { cleanEntityId } from '../utils/trend.utils';
export interface TrendRequestParams {
topics: string[];
keywords?: string[];
fuzzy: boolean;
institutions?: string[];
countries?: string[];
regions?: string[];
authors?: string[];
searchType: string;
}
@Injectable({
providedIn: 'root',
})
export class TrendDataService {
private readonly apiService = inject(UniversityRankingsService);
private readonly personsApiService = inject(PersonsService);
// Cache signals
readonly cachedResponse = signal<TrendResponse | null>(null);
readonly cachedParams = signal<TrendRequestParams | null>(null);
// Secondary data signals
readonly topSuggestions = signal<TopInstitutionItem[]>([]);
readonly recommendedAuthors = signal<Author[]>([]);
readonly topTopicsData = signal<{ value: number; name: string }[]>([]);
// Loading signals
readonly isSuggestionsLoading = signal<boolean>(false);
readonly isTopTopicsLoading = signal<boolean>(false);
readonly topTopicsError = signal<boolean>(false);
private readonly cacheMap = new Map<string, TrendResponse>();
private getCacheKey(params: TrendRequestParams): string {
return JSON.stringify({
searchType: params.searchType,
fuzzy: params.fuzzy,
topics: [...params.topics].sort(),
keywords: params.keywords ? [...params.keywords].sort() : [],
insts: (params.institutions || []).map(cleanEntityId).sort(),
authors: (params.authors || []).map(cleanEntityId).sort(),
countries: (params.countries || []).sort(),
regions: (params.regions || []).sort(),
});
}
/**
* Updates cache map with response and params from resolver or component.
*/
updateCache(response: TrendResponse, params: TrendRequestParams): void {
const key = this.getCacheKey(params);
this.cacheMap.set(key, response);
this.cachedResponse.set(response);
this.cachedParams.set(params);
}
/**
* Checks if exact requested params can be satisfied by cached response.
*/
canReuseCache(newParams: TrendRequestParams): boolean {
const key = this.getCacheKey(newParams);
return this.cacheMap.has(key);
}
/**
* Retrieves exact cached response for requested params.
*/
getCachedResponse(newParams: TrendRequestParams): TrendResponse | null {
const key = this.getCacheKey(newParams);
return this.cacheMap.get(key) ?? null;
}
/**
* Loads top 10 research topics for a selected pie entity.
*/
loadTopTopicsForEntity(
entityId: string,
entityType: string,
startYear: number,
endYear: number,
searchType: string,
): void {
if (!entityId || searchType === 'all') {
this.topTopicsData.set([]);
return;
}
this.isTopTopicsLoading.set(true);
this.topTopicsError.set(false);
const cleanId = cleanEntityId(entityId);
this.apiService
.getTopTopicsApiInseServiceUniversityRankingsTopTopicsGet(
cleanId,
entityType,
startYear,
endYear,
searchType,
)
.subscribe({
next: (res) => {
const mapped = (res.items || []).map((item) => ({
value: item.count,
name: item.name,
}));
this.topTopicsData.set(mapped);
this.isTopTopicsLoading.set(false);
},
error: (err) => {
console.error('Failed to load top topics:', err);
this.topTopicsError.set(true);
this.isTopTopicsLoading.set(false);
this.topTopicsData.set([]);
},
});
}
/**
* Loads top institution suggestions based on topic/country/region.
*/
loadInstitutionSuggestions(
topic: string,
countryFilter?: string,
regionFilter?: string,
): void {
this.isSuggestionsLoading.set(true);
this.apiService
.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
topic,
regionFilter,
countryFilter,
6,
)
.subscribe({
next: (res: any) => {
this.topSuggestions.set(res || []);
this.isSuggestionsLoading.set(false);
},
error: () => {
this.topSuggestions.set([]);
this.isSuggestionsLoading.set(false);
},
});
}
/**
* Loads recommended authors for selected topic and institution.
*/
loadRecommendedAuthors(topic: string, primaryInstId: string): void {
this.isSuggestionsLoading.set(true);
const cleanInst = cleanEntityId(primaryInstId) || 'I62318514';
this.personsApiService
.searchPersonsList(
undefined,
cleanInst,
'cited_by_count',
'desc',
[topic],
1,
6,
undefined,
)
.subscribe({
next: (res) => {
if (res.results && res.results.length > 0) {
this.recommendedAuthors.set(res.results);
this.isSuggestionsLoading.set(false);
} else {
// Global fallback search across all institutions
this.personsApiService
.searchPersonsList(
undefined,
undefined,
'cited_by_count',
'desc',
[topic],
1,
6,
undefined,
)
.subscribe({
next: (globalRes) => {
this.recommendedAuthors.set(globalRes.results || []);
this.isSuggestionsLoading.set(false);
},
error: () => {
this.recommendedAuthors.set([]);
this.isSuggestionsLoading.set(false);
},
});
}
},
error: () => {
this.recommendedAuthors.set([]);
this.isSuggestionsLoading.set(false);
},
});
}
}
@@ -143,7 +143,24 @@ export class UniPieChartComponent {
};
}
Object.entries(series.topic_data).forEach(([topicName, yearlyItems]) => {
const seenTopics = new Set<string>();
const entries = Object.entries(series.topic_data);
const hasDisplayNameKeys = entries.some(
([name]) => !name.startsWith('http') && !/^T\d+$/i.test(name),
);
entries.forEach(([topicName, yearlyItems]) => {
const isRawId =
topicName.startsWith('http') || /^T\d+$/i.test(topicName);
if (hasDisplayNameKeys && isRawId) {
return;
}
const normKey = topicName.toLowerCase().trim();
if (seenTopics.has(normKey)) {
return;
}
seenTopics.add(normKey);
const filtered = (yearlyItems || []).filter(
(y) => y.year >= startYr && y.year <= endYr,
);
@@ -38,19 +38,30 @@ export class UniTrendChartComponent {
const years = trendData.years.filter((y) => y >= startYr && y <= endYr);
const xAxisData = years.map(String);
// Resolve the active topic to compare one at a time to prevent line overlaps
const availableKeys = Object.keys(trendData.series[0].topic_data || {});
const displayNameKeys = availableKeys.filter(
(k) => !/^T\d+$/i.test(k) && !k.startsWith('http'),
);
const topics = displayNameKeys.length > 0 ? displayNameKeys : availableKeys;
const active = this.activeTopic();
const selectedTopic =
active && (availableKeys.includes(active) || topics.includes(active))
? active
: topics.length > 0
? topics[0]
: null;
let selectedTopic: string | null = null;
if (active) {
if (availableKeys.includes(active)) {
selectedTopic = active;
} else {
const foundKey = availableKeys.find(
(k) => k.toLowerCase().trim() === active.toLowerCase().trim(),
);
if (foundKey) {
selectedTopic = foundKey;
}
}
}
if (!selectedTopic) {
selectedTopic = topics.length > 0 ? topics[0] : availableKeys[0] || null;
}
if (!selectedTopic) {
return {};
@@ -136,7 +136,7 @@
[primaryInstitutionName]="primaryInstitutionName()"
[topSuggestions]="topSuggestions()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[activeChartTopic]="mappedActiveChartTopic()"
[searchQuery]="searchQuery()"
[searchResults]="searchResults()"
[getEntityColor]="boundGetEntityColor"
@@ -158,7 +158,7 @@
[comparisonAuthors]="comparisonAuthors()"
[topSuggestions]="recommendedAuthors()"
[isSuggestionsLoading]="isSuggestionsLoading()"
[activeChartTopic]="activeChartTopic()"
[activeChartTopic]="mappedActiveChartTopic()"
[searchQuery]="authorSearchQuery()"
[searchResults]="authorSearchResults()"
[getEntityColor]="boundGetEntityColor"
@@ -186,23 +186,23 @@
}
@if (selectedTrendTopics().length > 0) {
<div class="chart-topic-tabs">
@for (topic of selectedTrendTopics(); track topic) {
@for (topic of selectedTrendTopics(); track $index) {
@if (selectedSearchType() === 'news') {
<app-topic-chip
[label]="topic"
[label]="getMappedTopic(topic)"
[active]="isVisible('news_topic_' + topic)"
[color]="getTopicColor(topic)"
[disabled]="false"
[matTooltip]="topic"
[matTooltip]="getMappedTopic(topic)"
(chipClick)="toggleVisibility('news_topic_' + topic)">
</app-topic-chip>
} @else if (selectedTrendTopics().length > 1) {
} @else {
<app-topic-chip
[label]="topic"
[label]="getMappedTopic(topic)"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
[matTooltip]="topic"
[matTooltip]="getMappedTopic(topic)"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
}
@@ -212,7 +212,7 @@
<app-uni-trend-chart
[data]="trendResponse()"
[mode]="chartMode()"
[activeTopic]="activeChartTopic()"
[activeTopic]="mappedActiveChartTopic()"
[startYear]="startYear()"
[endYear]="endYear()"
[getEntityColor]="boundGetEntityColor"></app-uni-trend-chart>
@@ -0,0 +1,117 @@
import { TrendSeries, TopicYearlyData } from '../../../api';
import { CompareItem } from '../models/trend.models';
/**
* Extracts short OpenAlex ID from full URL or string, ensuring uppercase ID prefix (e.g. I62318514, A50012345).
*/
export function cleanEntityId(id: string | null | undefined): string {
if (!id) return '';
const trimmed = id.trim();
const raw = trimmed.includes('/') ? trimmed.split('/').pop()! : trimmed;
if (raw.length > 1 && /^[a-zA-Z]/.test(raw)) {
return raw[0].toUpperCase() + raw.substring(1);
}
return raw.toUpperCase();
}
/**
* Checks if a given topic contains zero publication/patent counts across all series within year range.
*/
export function isTopicEmptyForSeries(
topicName: string,
seriesList: TrendSeries[],
startYr: number,
endYr: number,
): boolean {
if (!seriesList || seriesList.length === 0) return true;
for (const s of seriesList) {
const topicItems = s.topic_data?.[topicName] || [];
const filtered = topicItems.filter(
(y) => y.year >= startYr && y.year <= endYr,
);
const sumRaw = filtered.reduce((acc, curr) => acc + (curr.raw || 0), 0);
if (sumRaw > 0) return false;
}
return true;
}
/**
* Finds the first non-empty topic in the list.
*/
export function findFirstNonEmptyTopic(
topics: string[],
seriesList: TrendSeries[],
startYr: number,
endYr: number,
): string {
if (!topics || topics.length === 0) return '';
for (const t of topics) {
if (!isTopicEmptyForSeries(t, seriesList, startYr, endYr)) {
return t;
}
}
return topics[0];
}
/**
* Builds deterministic entity color lookup map based on entity order and ID.
*/
export function buildEntityColorIndex(
primaryId: string | null,
institutions: CompareItem[],
countries: CompareItem[],
regions: CompareItem[],
authors: CompareItem[],
): (id: string) => string {
const entityColors = [
'#ec4899', // Pink (Primary UDE)
'#3b82f6', // Blue
'#10b981', // Emerald Green
'#f59e0b', // Amber/Yellow
'#8b5cf6', // Purple
'#06b6d4', // Cyan
'#6366f1', // Indigo
'#ef4444', // Red
'#14b8a6', // Teal
'#f97316', // Orange
'#d946ef', // Fuchsia
'#84cc16', // Lime
'#22c55e', // Green
'#a855f7', // Purple/Fuchsia
'#eab308', // Yellow
'#f43f5e', // Rose
];
const colorMap = new Map<string, string>();
let nextIdx = 0;
const cleanPrimary = cleanEntityId(primaryId || 'I62318514');
if (cleanPrimary) {
colorMap.set(cleanPrimary, entityColors[0]);
nextIdx = 1;
}
const allItems = [...institutions, ...countries, ...regions, ...authors];
allItems.forEach((item) => {
const cId = cleanEntityId(item.id);
if (cId && !colorMap.has(cId)) {
const color = entityColors[nextIdx % entityColors.length];
colorMap.set(cId, color);
nextIdx++;
}
});
return (id: string): string => {
const cId = cleanEntityId(id);
if (cId === 'WORLD') {
return '#3b82f6';
}
if (colorMap.has(cId)) {
return colorMap.get(cId)!;
}
const charCodeSum = cId
.split('')
.reduce((sum, char) => sum + char.charCodeAt(0), 0);
return entityColors[(nextIdx + charCodeSum) % entityColors.length];
};
}
+87 -40
View File
@@ -8,11 +8,13 @@ import {
} 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;
name: string;
}
import { CompareItem } from '../modules/university-ranking/models/trend.models';
import { cleanEntityId } from '../modules/university-ranking/utils/trend.utils';
import { ErrorService } from '../shared/services/error.service';
import {
TrendDataService,
TrendRequestParams,
} from '../modules/university-ranking/services/trend-data.service';
export interface UniTrendResolvedData {
trendResponse: TrendResponse | null;
@@ -37,14 +39,16 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const params = route.queryParamMap;
const searchState = inject(SearchResultsStateService, { optional: true });
const credentialService = inject(CredentialService, { optional: true });
const trendDataService = inject(TrendDataService);
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 =
const rawPrimaryInstId =
credentialService?.effectiveInstitutionId() || 'I62318514';
const primaryInstId = cleanEntityId(rawPrimaryInstId);
const primaryInstName =
credentialService?.organizationName() || 'Universität Duisburg-Essen';
@@ -63,18 +67,36 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
keywords = searchState.keywords();
}
let topics = params.getAll('topic');
let topics = fuzzy
? [...params.getAll('trend_topics'), ...params.getAll('trend_topic')]
: [];
if (topics.length === 0) {
const rawTopics = params.get('topics');
if (rawTopics) {
topics = rawTopics
.split(',')
const rawTopicsList = [
...params.getAll('topic'),
...params.getAll('topics'),
];
if (rawTopicsList.length > 0) {
topics = rawTopicsList
.flatMap((t) => t.split(','))
.map((t) => t.trim())
.filter((t) => t.length > 0);
}
}
if (topics.length === 0 && searchState) {
topics = fuzzy ? searchState.topicsList() : searchState.keywords();
if (searchState) {
const stateTopics = fuzzy
? searchState.topicsList()
: searchState.keywords();
if (
!fuzzy ||
topics.length === 0 ||
(fuzzy &&
stateTopics.length > 0 &&
topics.some((t) => t.startsWith('http') || /^T\d+$/i.test(t)))
) {
topics = stateTopics;
}
}
// Fallback defaults if no topics/keywords present yet
@@ -87,16 +109,12 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
keywords = topics;
}
// Parse comparison items
// Parse comparison items ensuring clean uppercase OpenAlex IDs
const instParams = params.getAll('institutions');
const parsedInstitutions: CompareItem[] = instParams.map((i) => {
const parts = i.split('|');
const cleanId = parts[0].includes('/')
? parts[0].split('/').pop() || parts[0]
: parts[0];
const isPrimary =
cleanId.toLowerCase() === primaryInstId.toLowerCase() ||
primaryInstId.toLowerCase().includes(cleanId.toLowerCase());
const cleanId = cleanEntityId(parts[0]);
const isPrimary = cleanId === primaryInstId;
const name = parts[1] || (isPrimary ? primaryInstName : parts[0]);
return { id: cleanId, name };
});
@@ -108,7 +126,7 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const countryParams = params.getAll('countries');
const parsedCountries: CompareItem[] = countryParams.map((c) => {
const parts = c.split('|');
return { id: parts[0], name: parts[1] || parts[0] };
return { id: parts[0].toUpperCase(), name: parts[1] || parts[0] };
});
const regionParams = params.getAll('regions');
@@ -120,19 +138,19 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const authorParams = params.getAll('authors');
const parsedAuthors: CompareItem[] = authorParams.map((a) => {
const parts = a.split('|');
return { id: parts[0], name: parts[1] || parts[0] };
const cleanId = cleanEntityId(parts[0]);
return { id: cleanId, name: parts[1] || parts[0] };
});
const instIds =
parsedInstitutions.length > 0
? parsedInstitutions.map((i) => i.id)
: [primaryInstId];
const countryIds =
parsedCountries.length > 0 ? parsedCountries.map((c) => c.id) : ['DE'];
const countryIds = parsedCountries.map((c) => c.id);
const regionIds = parsedRegions.map((r) => r.id);
const authorIds = parsedAuthors.map((a) => a.id);
const apiService = inject(UniversityRankingsService);
const errorService = inject(ErrorService);
const personsService = inject(PersonsService, { optional: true });
const primaryTopic = topics[0] || 'Artificial Intelligence';
@@ -141,18 +159,49 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const regionFilter =
parsedRegions.length > 0 ? parsedRegions[0].id : undefined;
const trendObs$ = apiService
.getTrendApiInseServiceUniversityRankingsTrendGet(
topics,
keywords,
fuzzy,
instIds,
countryIds,
regionIds,
authorIds,
searchType as any,
)
.pipe(catchError(() => of(null)));
const currentParams: TrendRequestParams = {
topics,
keywords,
fuzzy,
institutions: instIds,
countries: countryIds,
regions: regionIds,
authors: authorIds,
searchType,
};
// Check exact parameter keyed cache
let trendObs$: Observable<TrendResponse | null>;
if (trendDataService.canReuseCache(currentParams)) {
trendObs$ = of(trendDataService.getCachedResponse(currentParams));
} else {
trendObs$ = apiService
.getTrendApiInseServiceUniversityRankingsTrendGet(
topics,
keywords,
fuzzy,
instIds,
countryIds,
regionIds,
authorIds,
searchType as any,
)
.pipe(
map((res) => {
trendDataService.updateCache(res, currentParams);
return res;
}),
catchError((err) => {
errorService.setError({
statusCode: err?.status || 500,
title: 'Visualisierungs-Fehler',
message: 'Trenddaten konnten nicht geladen werden.',
errorDetails: err?.message || String(err),
});
return of(null);
}),
);
}
const topInstObs$ =
searchType !== 'authors'
@@ -191,7 +240,6 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
recommendedAuthors: recAuthorsObs$,
}).pipe(
map(({ trendResponse, topSuggestions, recommendedAuthors }) => {
// Find the first topic with non-zero publication data
let initialActiveTopic = primaryTopic;
if (
trendResponse?.series &&
@@ -225,7 +273,6 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
}
}
// If in author mode and no explicit authors were passed in URL, populate default top authors
if (
searchType === 'authors' &&
parsedAuthors.length === 0 &&
@@ -233,7 +280,7 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
) {
recommendedAuthors.slice(0, 3).forEach((author: any) => {
parsedAuthors.push({
id: author.id,
id: cleanEntityId(author.id),
name: author.display_name || 'Unbekannt',
});
});
+11
View File
@@ -317,3 +317,14 @@ h3 {
color: var(--sg-text-muted);
font-size: 13px;
}
/* Scalable Relative Inline Icon Utility */
.pie-icon-indicator {
font-size: 1.1em !important;
width: 1.1em !important;
height: 1.1em !important;
line-height: 1.1em !important;
vertical-align: middle;
flex-shrink: 0;
transition: transform 0.3s ease;
}