From 616b83e5461be4f55fba88a924ace498a52ed55d Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 19 Jul 2026 19:15:26 +0200 Subject: [PATCH] Added default institution from token. Added button links depending on current tab. Changed top 10 to top 20 and added custom projects top 20 query for projects --- .../inse/university_ranking/trend_logic.py | 175 +++++++++++++++++- .../uni-trend-parent.component.html | 13 +- .../uni-trend-parent.component.scss | 6 +- .../uni-trend-parent.component.ts | 59 +++++- .../author-selector.component.html | 9 + .../author-selector.component.ts | 13 ++ .../institution-selector.component.html | 18 +- .../institution-selector.component.ts | 22 +++ 8 files changed, 292 insertions(+), 23 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index b27588f8..692a33e5 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -745,6 +745,11 @@ async def get_trend_data( return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) +# Default fallback institution: University of Duisburg-Essen +DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" +DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" +DEFAULT_TOP_TOPICS_SIZE = 20 + async def get_top_topics_for_entity( entity_id: str, entity_type: str, @@ -773,12 +778,12 @@ async def get_top_topics_for_entity( pass sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True) - top_10 = sorted_topics[:10] - items = [{"name": name, "count": count} for name, count in top_10] + top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE] + items = [{"name": name, "count": count} for name, count in top_slice] - sum_top_10 = sum(count for name, count in top_10) + sum_top = sum(count for name, count in top_slice) total_topics = sum(topic_counts.values()) - other_count = max(0, total_topics - sum_top_10) + other_count = max(0, total_topics - sum_top) if other_count > 0: items.append({"name": "Andere Themen", "count": other_count}) @@ -787,6 +792,161 @@ async def get_top_topics_for_entity( logger.error("Failed to query top patent topics for institution: %s", e) return {"items": []} + if search_type == "projects": + try: + from inse.patents.search_client import PatentSearchClient + patent_client = PatentSearchClient() + short_id = entity_id.split("/")[-1] + + aliases = [short_id, entity_id] + if entity_type == "institution": + try: + res_alias = await elasticsearch.search( + index="institutions_alias", + query={"term": {"id.keyword": entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id}"}}, + size=1, + cluster="nes" + ) + hits_alias = res_alias.get("hits", {}).get("hits", []) + if hits_alias: + aliases = hits_alias[0]["_source"].get("aliases", [short_id]) + except Exception: + pass + + include_german = True + if entity_type == "country" and entity_id.strip().upper() != "DE": + include_german = False + elif entity_type == "region" and "DE" not in entity_id.strip().upper(): + include_german = False + + project_ids_by_index = {} + + # 1. BUND + if include_german: + bund_filters = [] + if entity_type == "institution": + bund_filters.append({ + "bool": { + "should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases], + "minimum_should_match": 1 + } + }) + try: + bund_res = await patent_client._search( + index=ESIndex.PROJECTS_BUND_V1.value, + payload={ + "query": {"bool": {"filter": bund_filters}}, + "size": 10000, + "_source": ["_id"] + } + ) + p_ids = [h["_id"] for h in bund_res.get("hits", {}).get("hits", []) if "_id" in h] + if p_ids: + project_ids_by_index[ESIndex.PROJECTS_BUND_TOPICS.value] = p_ids + except Exception as e: + logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e) + + # 2. DFG + if include_german: + try: + dfg_pids = [] + if entity_type == "institution": + should_clauses = [{"match": {"root_name_en": {"query": alias, "operator": "and"}}} for alias in aliases] + dfg_inst_res = await patent_client._search( + index=ESIndex.DFG_INSTITUTES.value, + payload={"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}}, "size": 1000} + ) + for hit in dfg_inst_res.get("hits", {}).get("hits", []): + for p in hit.get("_source", {}).get("projects", []): + if p.get("project_id"): + dfg_pids.append(str(p["project_id"])) + if dfg_pids or entity_type != "institution": + dfg_filters = [] + if dfg_pids: + dfg_filters.append({"ids": {"values": dfg_pids}}) + dfg_res = await patent_client._search( + index=ESIndex.DFG_PROJECTS.value, + payload={"query": {"bool": {"filter": dfg_filters}}, "size": 10000, "_source": ["id"]} + ) + p_ids = [str(h["_source"]["id"]) for h in dfg_res.get("hits", {}).get("hits", []) if h.get("_source", {}).get("id")] + if p_ids: + project_ids_by_index[ESIndex.PROJECTS_DFG_TOPICS.value] = p_ids + except Exception as e: + logger.warning("Failed to fetch DFG project IDs in get_top_topics_for_entity: %s", e) + + # 3. EU CORDIS + eu_indices = [ + (ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value), + (ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value), + (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value) + ] + for org_idx, proj_idx, topic_idx in eu_indices: + try: + filter_clauses = [] + if entity_type == "institution": + filter_clauses.append({"terms": {"name.keyword": [alias.upper() for alias in aliases]}}) + elif entity_type == "country": + filter_clauses.append({"term": {"country": entity_id.strip().upper()}}) + + eu_org_res = await patent_client._search( + index=org_idx.value, + payload={ + "query": {"bool": {"filter": filter_clauses}}, + "size": 0, + "aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}} + } + ) + eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])] + if eu_pids: + project_ids_by_index[topic_idx] = eu_pids + except Exception as e: + logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e) + + topic_counts = {} + for topic_idx, p_ids in project_ids_by_index.items(): + if not p_ids: + continue + for i in range(0, len(p_ids), 1000): + chunk = p_ids[i:i+1000] + payload = { + "query": {"terms": {"project_id": chunk}}, + "size": 0, + "aggs": { + "topic_matches": { + "nested": {"path": "topic_matches"}, + "aggs": { + "topics": { + "terms": {"field": "topic_matches.topic_display_name", "size": 100} + } + } + } + } + } + try: + res = await patent_client._search(index=topic_idx, payload=payload) + buckets = res.get("aggregations", {}).get("topic_matches", {}).get("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 topics from %s: %s", topic_idx, 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 project topics for entity: %s", e) + return {"items": []} + # 1. Normalize ID and prepare filter clause if entity_type == "institution": entity_url = entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id}" @@ -862,7 +1022,7 @@ async def get_top_topics_for_entity( "top_topics": { "terms": { "field": "primary_topic.id", - "size": 10 + "size": DEFAULT_TOP_TOPICS_SIZE }, "aggs": { "top_topic_hits": { @@ -896,8 +1056,8 @@ async def get_top_topics_for_entity( # Calculate "Other" total_hits = res.get("hits", {}).get("total", {}).get("value", 0) - sum_top_10 = sum(b["count"] for b in items) - other_count = max(0, total_hits - sum_top_10) + sum_top_slice = sum(b["count"] for b in items) + other_count = max(0, total_hits - sum_top_slice) if other_count > 0: items.append({"name": "Andere Themen", "count": other_count}) @@ -905,4 +1065,3 @@ async def get_top_topics_for_entity( except Exception as e: logger.error("Failed to query top topics for entity in ES: %s", e) return {"items": []} - diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 74ac9c3c..2061e003 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -23,6 +23,12 @@ campaign News @@ -159,7 +165,10 @@ @if (activeConfig().showInstitutionSelector) { @if (activeConfig().showAuthorSelector) { (20); + // Input containing extracted/selected keywords from parent readonly keywordsInput = input([], { alias: 'keywords' }); @@ -156,10 +166,15 @@ export class UniTrendParentComponent implements OnInit { 'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all' >('publications'); readonly selectedTrendTopics = signal([]); - readonly primaryInstitution = signal(null); + readonly primaryInstitution = signal('I62318514'); readonly primaryInstitutionName = signal( 'Universität Duisburg-Essen', ); + + readonly isUde = computed(() => { + const p = this.primaryInstitution() || 'I62318514'; + return p.includes('I62318514') || p === 'I62318514'; + }); readonly comparisonInstitutions = signal([]); readonly comparisonCountries = signal([ { id: 'DE', name: 'Deutschland' }, @@ -746,13 +761,44 @@ export class UniTrendParentComponent implements OnInit { } ngOnInit() { + if (this.credentialService) { + const profile = this.credentialService.accountProfile(); + if (profile?.organization_name) { + this.primaryInstitutionName.set(profile.organization_name); + } + const orgId = this.credentialService.effectiveOrganizationId(); + if (orgId && this.organizationService) { + this.organizationService.getOrganisations().subscribe({ + next: (res) => { + const matchingOrg = res.items?.find((o) => o.id === orgId); + const openAlexId = + matchingOrg?.other_inst_id || + (matchingOrg as any)?.openalex_institution_id; + if (matchingOrg && openAlexId) { + this.primaryInstitution.set(openAlexId); + if (matchingOrg.name) { + this.primaryInstitutionName.set(matchingOrg.name); + } + } + }, + error: () => {}, + }); + } + } this.initializeDefaultInstitutions(); } // Dynamically load top institutions to initialize comparisons using the top-institutions service initializeDefaultInstitutions() { + const primaryId = this.primaryInstitution() || 'I62318514'; + const primaryName = + this.primaryInstitutionName() || 'Universität Duisburg-Essen'; + const kws = this.keywords(); - if (kws.length === 0) return; + if (kws.length === 0) { + this.comparisonInstitutions.set([{ id: primaryId, name: primaryName }]); + return; + } // Use mapped topic names if softSearch is false const topics = this.state?.topicsList() ?? kws; @@ -782,6 +828,7 @@ export class UniTrendParentComponent implements OnInit { overallInsts: Array; }) => { const uniqueInsts = new Map(); + uniqueInsts.set(primaryId, primaryName); deInsts.forEach((inst: TopInstitutionItem) => { if (inst.id) @@ -1066,6 +1113,9 @@ export class UniTrendParentComponent implements OnInit { setSearchType( type: 'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all', ) { + if (type === 'news' && !this.isUde()) { + return; + } this.selectedSearchType.set(type); // Auto-initialize default lists if empty for the target type @@ -1089,10 +1139,7 @@ export class UniTrendParentComponent implements OnInit { // Add comparison institution addInstitution(id: string, name: string) { const current = this.comparisonInstitutions(); - if ( - !current.some((i: CompareItem) => i.id === id) && - id !== this.primaryInstitution() - ) { + if (!current.some((i: CompareItem) => i.id === id)) { this.comparisonInstitutions.set([...current, { id, name }]); } this.searchQuery.set(''); diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.html b/webapp/src/app/shared/ui/author-selector/author-selector.component.html index cd347469..237a6c23 100644 --- a/webapp/src/app/shared/ui/author-selector/author-selector.component.html +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.html @@ -56,6 +56,15 @@ {{ auth.name }} + + open_in_new + ('publications'); readonly comparisonAuthors = input([]); readonly topSuggestions = input([]); readonly isSuggestionsLoading = input(false); @@ -31,6 +32,18 @@ export class AuthorSelectorComponent { readonly toggleVisibility = output(); readonly selectPie = output<{ id: string; name: string; type: 'author' }>(); + getRedirectUrl(id: string): string { + const cleanId = id.includes('/') ? id.split('/').pop() || id : id; + const tab = this.activeTab(); + if (tab === 'projects') { + return `/person/${cleanId}/projects?page=0&size=10&sort_by=title&sort_direction=asc&search=`; + } + if (tab === 'patents') { + return `/person/${cleanId}/patents`; + } + return `/person/${cleanId}/publications`; + } + onSelectPie(id: string, name: string): void { this.selectPie.emit({ id, name, type: 'author' }); } diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.html b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.html index d62b2c85..5c42a819 100644 --- a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.html +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.html @@ -7,13 +7,8 @@ + (click)="onSelectPrimaryBadge()" + [title]="'Klicken, um die Einrichtung zur Vergleichsliste hinzuzufügen'"> Zugewiesen: {{ @@ -77,6 +72,15 @@ {{ inst.name }} + + open_in_new + ('publications'); readonly comparisonInstitutions = input([]); readonly primaryInstitution = input(null); readonly primaryInstitutionName = input(null); @@ -37,6 +38,27 @@ export class InstitutionSelectorComponent { type: 'institution'; }>(); + onSelectPrimaryBadge(): void { + const id = this.primaryInstitution(); + const name = this.primaryInstitutionName(); + if (id && name) { + this.addInstitution.emit({ id, name }); + this.onSelectPie(id, name); + } + } + + getRedirectUrl(id: string): string { + const cleanId = id.includes('/') ? id.split('/').pop() || id : id; + const tab = this.activeTab(); + if (tab === 'projects') { + return `/institution/${cleanId}/projects?project_tab=bund&page=0&size=10&search=&sort_by=title&sort_direction=asc`; + } + if (tab === 'patents') { + return `/institution/${cleanId}/patents?filter=all&sortBy=date&matchType=all&page=1`; + } + return `/institution/${cleanId}/publications`; + } + onSelectPie(id: string, name: string): void { this.selectPie.emit({ id, name, type: 'institution' }); }