From ebb986b22502c867230ab2576f296303a8cec213 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 19 Jul 2026 19:12:23 +0200 Subject: [PATCH 1/4] added additional comparison fields in dfg projects --- .../university_ranking/trend_strategies.py | 106 +++++++++++------- 1 file changed, 66 insertions(+), 40 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index e8474b02..eee0014d 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -1136,7 +1136,28 @@ class ProjectsTrendStrategy(TrendStrategy): {"match": {"abstract_de": keyword}}, {"match": {"abstract_en": keyword}}, {"match": {"final_report_abstract_de": keyword}}, - {"match": {"final_report_abstract_en": keyword}} + {"match": {"final_report_abstract_en": keyword}}, + { + "nested": { + "path": "publications", + "query": {"match": {"publications.title": keyword}} + } + }, + { + "nested": { + "path": "subject_classification", + "query": { + "bool": { + "should": [ + {"match": {"subject_classification.fach": keyword}}, + {"match": {"subject_classification.fachkollegium": keyword}}, + {"match": {"subject_classification.wissenschaftsbereich": keyword}} + ], + "minimum_should_match": 1 + } + } + } + } ], "minimum_should_match": 1 } @@ -1432,61 +1453,46 @@ class AllTrendStrategy(TrendStrategy): regions: Optional[List[str]] = None, authors: Optional[List[str]] = None, ) -> TrendResponse: - # Runs Publications, Patents, Projects, and News strategies concurrently - # overlays their curves to display a Topic Lifecycle dashboard for UDE + target_inst = institutions[0] if institutions and len(institutions) > 0 else DEFAULT_INSTITUTION_ID + short_id = target_inst.split("/")[-1].upper() + is_ude = (short_id == "I62318514") + pub_strat = PublicationsTrendStrategy() pat_strat = PatentsTrendStrategy() proj_strat = ProjectsTrendStrategy() - news_strat = NewsTrendStrategy() - # Query UDE publications data only - pub_task = pub_strat.get_trend(topics, keywords, fuzzy, institutions=[DEFAULT_INSTITUTION_ID]) - pat_task = pat_strat.get_trend(topics, keywords, fuzzy) - proj_task = proj_strat.get_trend(topics, keywords, fuzzy) - news_task = news_strat.get_trend(topics, keywords, fuzzy) + tasks = [ + pub_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]), + pat_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]), + proj_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]) + ] - pub_res, pat_res, proj_res, news_res = await asyncio.gather(pub_task, pat_task, proj_task, news_task) + if is_ude: + news_strat = NewsTrendStrategy() + tasks.append(news_strat.get_trend(topics, keywords, fuzzy)) + + results = await asyncio.gather(*tasks) + pub_res = results[0] + pat_res = results[1] + proj_res = results[2] + news_res = results[3] if is_ude else None start_year = 2000 end_year = datetime.datetime.now().year - 1 years_range = list(range(start_year, end_year + 1)) - # Extract UDE publications series - pub_series = next((s for s in pub_res.series if s.entity_id == DEFAULT_INSTITUTION_ID), None) + pub_series = pub_res.series[0] if pub_res.series else None pat_series = pat_res.series[0] if pat_res.series else None proj_series = proj_res.series[0] if proj_res.series else None - # Reconstruct a single news series containing the correct data for each topic - merged_news_topic_data = {} - for topic in topics: - term_key = f"news_topic_{topic}" - matching_series = next((s for s in news_res.series if s.entity_id == term_key), None) - if matching_series and topic in matching_series.topic_data: - merged_news_topic_data[topic] = matching_series.topic_data[topic] - else: - merged_news_topic_data[topic] = [ - TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) - for yr in years_range - ] - - news_series = TrendSeries( - entity_id="news", - entity_name="UDE Campus Aktuell Beiträge", - entity_type="institution", - topic_data=merged_news_topic_data - ) - - # Build composite TrendSeries composite_series = [] - - # Helper to construct TrendSeries + def add_composite(series_obj: Optional[TrendSeries], c_id: str, c_name: str): topic_data_map = {} for topic in topics: if series_obj and topic in series_obj.topic_data: topic_data_map[topic] = series_obj.topic_data[topic] else: - # Fallback empty list topic_data_map[topic] = [ TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) for yr in years_range @@ -1498,9 +1504,29 @@ class AllTrendStrategy(TrendStrategy): topic_data=topic_data_map )) - add_composite(pub_series, "publications", "Akademische Publikationen (UDE)") - add_composite(pat_series, "patents", "Patentanmeldungen (UDE)") - add_composite(proj_series, "projects", "Drittmittelförderung (UDE)") - add_composite(news_series, "news", "UDE Campus Aktuell Beiträge") + add_composite(pub_series, "publications", "Akademische Publikationen") + add_composite(pat_series, "patents", "Patentanmeldungen") + add_composite(proj_series, "projects", "Drittmittelförderung") + + if is_ude and news_res: + merged_news_topic_data = {} + for topic in topics: + term_key = f"news_topic_{topic}" + matching_series = next((s for s in news_res.series if s.entity_id == term_key), None) + if matching_series and topic in matching_series.topic_data: + merged_news_topic_data[topic] = matching_series.topic_data[topic] + else: + merged_news_topic_data[topic] = [ + TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) + for yr in years_range + ] + + news_series = TrendSeries( + entity_id="news", + entity_name="UDE Campus Aktuell Beiträge", + entity_type="institution", + topic_data=merged_news_topic_data + ) + add_composite(news_series, "news", "UDE Campus Aktuell Beiträge") return TrendResponse(series=composite_series, years=years_range) 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 2/4] 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 @@ @@ -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 +
} - @for (key of [entityId() || titleText() || 'overall']; track key) { -
- } +
diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 309069db..0557dc8f 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -367,16 +367,25 @@ export class UniTrendParentComponent implements OnInit { } // Default: publications, patents, projects + // Resilient ID normalization helper + const cleanId = (id: string | null | undefined): string => { + if (!id) return ''; + const lower = id.toLowerCase().trim(); + return lower.includes('/') ? lower.split('/').pop()! : lower; + }; + const currentInstIds = new Set( - this.comparisonInstitutions().map((i: CompareItem) => i.id.toLowerCase()), + this.comparisonInstitutions().map((i: CompareItem) => cleanId(i.id)), ); const currentCountryIds = new Set( - this.comparisonCountries().map((c: CompareItem) => c.id.toLowerCase()), + this.comparisonCountries().map((c: CompareItem) => cleanId(c.id)), ); const currentRegionIds = new Set( - this.comparisonRegions().map((r: CompareItem) => r.id.toLowerCase()), + this.comparisonRegions().map((r: CompareItem) => cleanId(r.id)), + ); + const primaryInstCleanId = cleanId( + this.primaryInstitution() || 'I62318514', ); - const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase(); const primaryInstSeries: TrendSeries[] = []; const compInstSeries: TrendSeries[] = []; @@ -384,19 +393,20 @@ export class UniTrendParentComponent implements OnInit { const regionSeries: TrendSeries[] = []; raw.series.forEach((s: TrendSeries) => { - const id = s.entity_id.toLowerCase(); + const cId = cleanId(s.entity_id); if (s.entity_type === 'institution') { - if (id === defaultInstId) { + if (cId === primaryInstCleanId) { primaryInstSeries.push(s); - } else if (currentInstIds.has(id)) { + } + if (currentInstIds.has(cId)) { compInstSeries.push(s); } } else if (s.entity_type === 'country') { - if (currentCountryIds.has(id)) { + if (currentCountryIds.has(cId)) { countrySeries.push(s); } } else if (s.entity_type === 'region') { - if (currentRegionIds.has(id)) { + if (currentRegionIds.has(cId)) { regionSeries.push(s); } } @@ -554,18 +564,23 @@ export class UniTrendParentComponent implements OnInit { // Handle initialization and synchronization of URL state this.route.queryParams.subscribe((params) => { + let hasInstsFromUrl = false; if (params['search_type']) { this.selectedSearchType.set(params['search_type'] as any); } // Parse institutions serialized as id|name if (params['institutions']) { + hasInstsFromUrl = true; const insts = Array.isArray(params['institutions']) ? params['institutions'] : [params['institutions']]; const parsed = insts.map((i: string) => { const parts = i.split('|'); - return { id: parts[0], name: parts[1] || parts[0] }; + const cleanId = parts[0].includes('/') + ? parts[0].split('/').pop() || parts[0] + : parts[0]; + return { id: cleanId, name: parts[1] || parts[0] }; }); const currentIds = this.comparisonInstitutions() @@ -579,10 +594,11 @@ export class UniTrendParentComponent implements OnInit { if (currentIds !== parsedIds) { this.comparisonInstitutions.set(parsed); } - } else { - if (this.comparisonInstitutions().length > 0) { - this.comparisonInstitutions.set([]); - } + } + + // If URL didn't specify institutions and list is currently empty, initialize defaults + if (!hasInstsFromUrl && this.comparisonInstitutions().length === 0) { + this.initializeDefaultInstitutions(); } // Parse countries @@ -1138,9 +1154,17 @@ export class UniTrendParentComponent implements OnInit { // Add comparison institution addInstitution(id: string, name: string) { + const cleanId = id.includes('/') ? id.split('/').pop() || id : id; const current = this.comparisonInstitutions(); - if (!current.some((i: CompareItem) => i.id === id)) { - this.comparisonInstitutions.set([...current, { id, name }]); + const exists = current.some((i: CompareItem) => { + const itemClean = i.id.includes('/') + ? i.id.split('/').pop() || i.id + : i.id; + return itemClean.toLowerCase() === cleanId.toLowerCase(); + }); + if (!exists) { + this.comparisonInstitutions.set([...current, { id: cleanId, name }]); + this.updateUrlParams(); } this.searchQuery.set(''); this.searchResults.set([]); @@ -1151,6 +1175,7 @@ export class UniTrendParentComponent implements OnInit { this.comparisonInstitutions.set( current.filter((i: CompareItem) => i.id !== id), ); + this.updateUrlParams(); } // Add country or region @@ -1175,6 +1200,7 @@ export class UniTrendParentComponent implements OnInit { this.locationQuery.set(''); this.locationSearchResults.set([]); this.loadTrendSuggestions(); + this.updateUrlParams(); } removeLocation(id: string, type: 'country' | 'continent') { @@ -1190,6 +1216,7 @@ export class UniTrendParentComponent implements OnInit { ); } this.loadTrendSuggestions(); + this.updateUrlParams(); } // Add Top 3 Authors for a selected institution from institutions autocomplete @@ -1230,6 +1257,7 @@ export class UniTrendParentComponent implements OnInit { }); this.comparisonAuthors.set(updated); this.isSuggestionsLoading.set(false); + this.updateUrlParams(); }, error: (err) => { console.error('Failed to load top authors for institution:', err); @@ -1246,12 +1274,14 @@ export class UniTrendParentComponent implements OnInit { const current = this.comparisonAuthors(); if (!current.some((a) => a.id === shortId)) { this.comparisonAuthors.set([...current, { id: shortId, name }]); + this.updateUrlParams(); } } removeAuthor(id: string) { const current = this.comparisonAuthors(); this.comparisonAuthors.set(current.filter((a: CompareItem) => a.id !== id)); + this.updateUrlParams(); } // Scaling mode toggle (data reuses instantly) diff --git a/webapp/src/app/shared/ui/author-selector/author-selector.component.ts b/webapp/src/app/shared/ui/author-selector/author-selector.component.ts index 5874ff19..a54068b7 100644 --- a/webapp/src/app/shared/ui/author-selector/author-selector.component.ts +++ b/webapp/src/app/shared/ui/author-selector/author-selector.component.ts @@ -36,12 +36,12 @@ export class AuthorSelectorComponent { 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=`; + return `/inse-webapp/person/${cleanId}/projects?page=0&size=10&sort_by=title&sort_direction=asc&search=`; } if (tab === 'patents') { - return `/person/${cleanId}/patents`; + return `/inse-webapp/person/${cleanId}/patents`; } - return `/person/${cleanId}/publications`; + return `/inse-webapp/person/${cleanId}/publications`; } onSelectPie(id: string, name: string): void { diff --git a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts index e8ebd9d2..e2d0160a 100644 --- a/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts +++ b/webapp/src/app/shared/ui/institution-selector/institution-selector.component.ts @@ -51,12 +51,12 @@ export class InstitutionSelectorComponent { 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`; + return `/inse-webapp/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 `/inse-webapp/institution/${cleanId}/patents?filter=all&sortBy=date&matchType=all&page=1`; } - return `/institution/${cleanId}/publications`; + return `/inse-webapp/institution/${cleanId}/publications`; } onSelectPie(id: string, name: string): void { @@ -92,8 +92,20 @@ export class InstitutionSelectorComponent { isAlreadyAdded(id: string | undefined): boolean { if (!id) return false; - const isPrimary = this.primaryInstitution() === id; - const isComp = this.comparisonInstitutions().some((i) => i.id === id); + const cleanTarget = id.includes('/') ? id.split('/').pop() || id : id; + const primaryId = this.primaryInstitution(); + const cleanPrimary = primaryId + ? primaryId.includes('/') + ? primaryId.split('/').pop() || primaryId + : primaryId + : null; + const isPrimary = cleanPrimary?.toLowerCase() === cleanTarget.toLowerCase(); + const isComp = this.comparisonInstitutions().some((i) => { + const cleanItem = i.id.includes('/') + ? i.id.split('/').pop() || i.id + : i.id; + return cleanItem.toLowerCase() === cleanTarget.toLowerCase(); + }); return isPrimary || isComp; } } From 2aea08ab315722dcdc7ec206141cf9a8dcf569a2 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sun, 19 Jul 2026 20:26:14 +0200 Subject: [PATCH 4/4] fixed project pie chart for sure now --- .../university_ranking/trend_strategies.py | 62 +++++++++++++------ .../uni-trend-parent.component.ts | 3 +- 2 files changed, 43 insertions(+), 22 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 6aca6404..954c1e21 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -746,22 +746,37 @@ class ProjectsTrendStrategy(TrendStrategy): primary_inst_id = DEFAULT_INSTITUTION_ID primary_inst_name = DEFAULT_INSTITUTION_NAME - query_institutions = [] - if institutions: - query_institutions = [i.strip() for i in institutions] - if primary_inst_id not in query_institutions: - query_institutions.insert(0, primary_inst_id) + def clean_inst_id(id_str: str) -> str: + return id_str.split("/")[-1] if id_str and "/" in id_str else id_str + + primary_inst_short = clean_inst_id(DEFAULT_INSTITUTION_ID) + primary_inst_full = f"https://openalex.org/{primary_inst_short}" + + raw_insts = institutions or [] + query_insts_short = [clean_inst_id(i) for i in raw_insts if i] + if primary_inst_short not in query_insts_short: + query_insts_short.insert(0, primary_inst_short) + + # Preserve order while deduplicating + seen_insts = set() + dedup_inst_shorts = [] + for s_id in query_insts_short: + if s_id not in seen_insts: + seen_insts.add(s_id) + dedup_inst_shorts.append(s_id) + + query_institutions = dedup_inst_shorts + ids_to_resolve = [f"https://openalex.org/{i}" for i in query_institutions] query_countries = countries or [] query_regions = regions or [] clean_countries = [c.strip().upper() for c in query_countries] clean_regions = [r.strip() for r in query_regions] - ids_to_resolve = list(set(query_institutions)) # 1. Resolve institution names & aliases, country names, and regions async def fetch_institutions(): - names = {primary_inst_id: primary_inst_name} + names = {primary_inst_full: DEFAULT_INSTITUTION_NAME, primary_inst_short: DEFAULT_INSTITUTION_NAME} codes = {} aliases_map = {} if not ids_to_resolve: @@ -778,20 +793,27 @@ class ProjectsTrendStrategy(TrendStrategy): ) for hit in res.get("hits", {}).get("hits", []): source = hit["_source"] - inst_id = source["id"] - names[inst_id] = source.get("display_name", inst_id) - codes[inst_id] = source.get("country_code", "") - - async def get_aliases(inst_id): - try: - return inst_id, await client.get_institution_aliases_by_oa_institution_id(inst_id) - except Exception as e: - logger.warning("Failed to get aliases for %s: %s", inst_id, e) - return inst_id, [names.get(inst_id, inst_id)] + full_id = source["id"] + short_id = clean_inst_id(full_id) + d_name = source.get("display_name", full_id) + c_code = source.get("country_code", "") + names[full_id] = d_name + names[short_id] = d_name + codes[full_id] = c_code + codes[short_id] = c_code - alias_results = await asyncio.gather(*(get_aliases(inst_id) for inst_id in ids_to_resolve)) - for inst_id, aliases in alias_results: - aliases_map[inst_id] = aliases + async def get_aliases(inst_short_id): + try: + resolved = await client.get_institution_aliases_by_oa_institution_id(inst_short_id) + return inst_short_id, resolved or [names.get(inst_short_id, inst_short_id)] + except Exception as e: + logger.warning("Failed to get aliases for %s: %s", inst_short_id, e) + return inst_short_id, [names.get(inst_short_id, inst_short_id)] + + alias_results = await asyncio.gather(*(get_aliases(i) for i in query_institutions)) + for inst_short_id, aliases in alias_results: + aliases_map[inst_short_id] = aliases + aliases_map[f"https://openalex.org/{inst_short_id}"] = aliases except Exception as e: logger.warning("Failed to resolve institution details from ES: %s", e) return names, codes, aliases_map diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 0557dc8f..5ab09e62 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -397,8 +397,7 @@ export class UniTrendParentComponent implements OnInit { if (s.entity_type === 'institution') { if (cId === primaryInstCleanId) { primaryInstSeries.push(s); - } - if (currentInstIds.has(cId)) { + } else if (currentInstIds.has(cId)) { compInstSeries.push(s); } } else if (s.entity_type === 'country') {