From 3c910fa0e42c9371cb7d0eef3249bb5394296aa6 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 3 Jul 2026 19:50:28 +0200 Subject: [PATCH 01/13] Backend for institution trend analysis (implemented into university ranking) --- service/src/main/inse/model.py | 2 + .../src/main/inse/university_ranking/model.py | 37 +- .../main/inse/university_ranking/router.py | 69 ++- .../inse/university_ranking/trend_logic.py | 510 ++++++++++++++++++ 4 files changed, 612 insertions(+), 6 deletions(-) create mode 100644 service/src/main/inse/university_ranking/trend_logic.py diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index db452b2e..4194412e 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -34,6 +34,8 @@ class ESIndex(StrEnum): OPENALEX_AUTHORS = "openalex-authors" OPENALEX_INSTITUTIONS = "openalex-institutions" OPENALEX_PUBLICATIONS = "openalex-publications" + OPENALEX_COUNTRIES = "openalex-countries" + OPENALEX_CONTINENTS = "openalex-continents" EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_3.0" diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py index 1b4b8605..7a4791d7 100644 --- a/service/src/main/inse/university_ranking/model.py +++ b/service/src/main/inse/university_ranking/model.py @@ -1,5 +1,5 @@ from pydantic import BaseModel -from typing import List, Literal +from typing import List, Literal, Dict, Optional ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology'] DashboardMetric = Literal['publications', 'citations'] @@ -27,4 +27,37 @@ class RankingResponse(BaseModel): # Raw timeseries data for the ECharts line race timeseries: List[UniversityTopicData] # Computed metrics for the ranking table - rankings: List[UniversityRanking] \ No newline at end of file + rankings: List[UniversityRanking] + +# Trend Analysis Models +class TopicYearlyData(BaseModel): + year: int + raw: int + normalized: float + institutions_count: int + +class TrendSeries(BaseModel): + entity_id: str + entity_name: str + entity_type: Literal['institution', 'country', 'region'] + country_code: Optional[str] = None + # Map topic display name to its yearly data + topic_data: Dict[str, List[TopicYearlyData]] + +class TrendResponse(BaseModel): + series: List[TrendSeries] + years: List[int] + location_mappings: Optional[Dict[str, List[str]]] = None + +from inse.models.openalex.dehydrated_institution import DehydratedInstitution + +class TopInstitutionItem(DehydratedInstitution): + works_count: Optional[int] = None + image_thumbnail_url: Optional[str] = None + exact_topic_count: Optional[int] = None + +class AutocompleteLocationItem(BaseModel): + id: str + display_name: str + code: str + type: Literal['country', 'continent'] \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/router.py b/service/src/main/inse/university_ranking/router.py index 60c52c9d..22e24b1c 100644 --- a/service/src/main/inse/university_ranking/router.py +++ b/service/src/main/inse/university_ranking/router.py @@ -1,7 +1,22 @@ -from fastapi import APIRouter, Query -from . import service -from .model import RankingResponse, ResearchTopic, DashboardMetric +import logging +from typing import List, Optional +from fastapi import APIRouter, Query, Depends, Request + from inse.tags import Tags +from inse.database import get_session +from inse.auth import service as auth_service +from inse.auth.model import AccessToken, UserRole +from . import service, trend_logic +from .model import ( + RankingResponse, + ResearchTopic, + DashboardMetric, + TrendResponse, + TopInstitutionItem, + AutocompleteLocationItem +) + +logger = logging.getLogger(__name__) router = APIRouter( prefix="/api/inse-service/university-rankings", @@ -20,4 +35,50 @@ async def get_rankings( ), metric: DashboardMetric = Query("publications", description="Metric to rank by") ): - return await service.get_university_dashboard_data(topic, metric) \ No newline at end of file + return await service.get_university_dashboard_data(topic, metric) + +@router.get( + "/trend", + response_model=TrendResponse, + summary="Returns timeseries publication data for compared institutions, countries and regions." +) +async def get_trend( + topics: List[ResearchTopic] = Query(..., description="List of topics to analyze"), + institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"), + countries: Optional[List[str]] = Query(None, description="List of country codes"), + regions: Optional[List[str]] = Query(None, description="List of region identifiers") +): + return await trend_logic.get_trend_data( + topics=topics, + institutions=institutions, + countries=countries, + regions=regions + ) + +@router.get( + "/top-institutions", + response_model=List[TopInstitutionItem], + summary="Returns top institutions filtered by country/region and sorted by topic-level publications count." +) +async def get_top_institutions( + topic: str = Query(..., description="Research topic"), + region: Optional[str] = Query(None, description="Region identifier (e.g. EU)"), + country: Optional[str] = Query(None, description="Country code (e.g. DE)"), + limit: int = Query(10, description="Max suggestions to return") +): + return await trend_logic.get_top_institutions_by_region( + topic=topic, + region=region, + country=country, + limit=limit + ) + +@router.get( + "/autocomplete-locations", + response_model=List[AutocompleteLocationItem], + summary="Returns country and continent options for autocomplete inputs." +) +async def get_autocomplete_locations( + query: str = Query(..., description="Query text to search for countries/continents") +): + return await trend_logic.autocomplete_locations(query) \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py new file mode 100644 index 00000000..c025bc74 --- /dev/null +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -0,0 +1,510 @@ +import logging +import uuid +import datetime +from typing import List, Dict, Any, Optional + +from sqlmodel import Session +from inse.integrations import elasticsearch +from inse.model import ESIndex +from inse.auth.model import AccessToken, Organization +from .model import ( + TrendResponse, + TrendSeries, + TopicYearlyData, + TopInstitutionItem, + ResearchTopic, + AutocompleteLocationItem +) + +logger = logging.getLogger(__name__) + +# Default fallback institution: University of Duisburg-Essen +DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" +DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" + +async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: + stripped = query.strip() + if not stripped: + return [] + + import asyncio + + # Query countries index + country_query = { + "bool": { + "should": [ + { + "wildcard": { + "display_name.keyword": { + "value": f"*{stripped}*", + "case_insensitive": True + } + } + }, + { + "match": { + "country_code": { + "query": stripped.upper(), + "boost": 5 + } + } + } + ], + "minimum_should_match": 1 + } + } + + # Query continents index + continent_query = { + "wildcard": { + "display_name.keyword": { + "value": f"*{stripped}*", + "case_insensitive": True + } + } + } + + try: + countries_res, continents_res = await asyncio.gather( + elasticsearch.search(index=str(ESIndex.OPENALEX_COUNTRIES), query=country_query, size=10, cluster="nes"), + elasticsearch.search(index=str(ESIndex.OPENALEX_CONTINENTS), query=continent_query, size=5, cluster="nes") + ) + except Exception as e: + logger.error("Failed to autocomplete locations in ES: %s", e) + return [] + + results = [] + + # Process continents + for hit in continents_res.get("hits", {}).get("hits", []): + source = hit["_source"] + results.append(AutocompleteLocationItem( + id=source["id"], + display_name=source["display_name"], + code=source.get("wikidata_id") or source["id"].split("/")[-1], + type="continent" + )) + + # Process countries + for hit in countries_res.get("hits", {}).get("hits", []): + source = hit["_source"] + results.append(AutocompleteLocationItem( + id=source["id"], + display_name=source["display_name"], + code=source["country_code"], + type="country" + )) + + return results + + +def clean_institution_id(inst_id: str) -> str: + inst_id = inst_id.strip() + if not inst_id.startswith("http"): + return f"https://openalex.org/{inst_id}" + return inst_id + +def min_max_normalize(values: List[int]) -> List[float]: + if not values: + return [] + min_val = min(values) + max_val = max(values) + if max_val == min_val: + return [0.0] * len(values) + return [float(v - min_val) / (max_val - min_val) for v in values] + +async def get_top_institutions_by_region( + topic: str, + region: Optional[str] = None, + country: Optional[str] = None, + limit: int = 10 +) -> List[TopInstitutionItem]: + """ + Search top educational institutions by region or country based on publication counts + for the specific topic, using a two-step Python-based sorting approach. + """ + country_codes = [] + if country: + country_codes = [country] + elif region: + country_codes = REGION_MAPPINGS.get(region, []) + + # Query openalex-institutions for educational entities matching country and topic + must_clauses: List[Dict[str, Any]] = [ + {"term": {"type": "education"}}, + {"match_phrase": {"topics.display_name": topic}} + ] + + if country_codes: + must_clauses.append({"terms": {"geo.country_code": country_codes}}) + + query = {"bool": {"must": must_clauses}} + + # Fetch top 50 by overall works count to cover a good pool of institutions + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query=query, + size=50, + sort=[{"works_count": "desc"}], + cluster="nes" + ) + + hits = res.get("hits", {}).get("hits", []) + candidates = [] + + for hit in hits: + source = hit["_source"] + inst_id = source.get("id") + display_name = source.get("display_name", "Unknown") + country_code = source.get("country_code") + works_count = source.get("works_count") + image_thumbnail_url = source.get("image_thumbnail_url") + + # Extract exact count for the selected topic + exact_topic_count = 0 + for t in source.get("topics", []): + if t.get("display_name", "").lower() == topic.lower(): + exact_topic_count = t.get("count", 0) + break + + candidates.append(TopInstitutionItem( + id=inst_id, + display_name=display_name, + country_code=country_code, + works_count=works_count, + image_thumbnail_url=image_thumbnail_url, + exact_topic_count=exact_topic_count + )) + + # Sort candidates by exact_topic_count descending + candidates.sort(key=lambda x: x.exact_topic_count or 0, reverse=True) + + return candidates[:limit] + +async def get_trend_data( + topics: List[ResearchTopic], + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None +) -> TrendResponse: + """ + Traverses the openalex-works index to retrieve yearly contributions of selected/top + institutions, countries, and regions across multiple topics. + """ + if not topics: + return TrendResponse(series=[], years=[]) + + start_year = 2000 + end_year = datetime.datetime.now().year -1 + years_range = list(range(start_year, end_year + 1)) + + # Resolve primary institution (default University of Duisburg-Essen for everyone) + primary_inst_id = DEFAULT_INSTITUTION_ID + primary_inst_name = DEFAULT_INSTITUTION_NAME + + # Initialize institutions list and ensure primary is included + query_institutions = [] + if institutions: + query_institutions = [clean_institution_id(i) for i in institutions] + if primary_inst_id not in query_institutions: + query_institutions.insert(0, primary_inst_id) + + # Resolve institution names and country codes from openalex-institutions + resolved_names: Dict[str, str] = {primary_inst_id: primary_inst_name} + resolved_country_codes: Dict[str, str] = {} + ids_to_resolve = list(set(query_institutions)) + + if ids_to_resolve: + try: + name_res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query={"terms": {"id": ids_to_resolve}}, + size=len(ids_to_resolve), + cluster="nes" + ) + for hit in name_res.get("hits", {}).get("hits", []): + source = hit["_source"] + resolved_names[source["id"]] = source.get("display_name", source["id"]) + resolved_country_codes[source["id"]] = source.get("country_code", "") + except Exception as e: + logger.warning("Failed to resolve institution details from ES: %s", e) + + # Prepare lists of countries and regions dynamically + query_countries = countries or [] + query_regions = regions or [] + + resolved_country_names: Dict[str, str] = {} + clean_countries: List[str] = [] + if query_countries: + clean_countries = [c.split("/")[-1].upper() for c in query_countries] + try: + c_res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_COUNTRIES), + query={"terms": {"country_code": clean_countries}}, + size=len(clean_countries), + cluster="nes" + ) + for hit in c_res.get("hits", {}).get("hits", []): + source = hit["_source"] + resolved_country_names[source["country_code"]] = source["display_name"] + except Exception as e: + logger.warning("Failed to resolve country names from ES: %s", e) + + resolved_continent_names: Dict[str, str] = {} + continent_country_codes: Dict[str, List[str]] = {} + location_mappings: Dict[str, List[str]] = {} + if query_regions: + clean_regions = [r.split("/")[-1] for r in query_regions] + try: + r_res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_CONTINENTS), + query={ + "bool": { + "should": [ + {"terms": {"wikidata_id": clean_regions}}, + {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}} + ] + } + }, + size=len(clean_regions), + cluster="nes" + ) + for hit in r_res.get("hits", {}).get("hits", []): + source = hit["_source"] + c_code = source.get("wikidata_id") or source["id"].split("/")[-1] + resolved_continent_names[c_code] = source["display_name"] + member_ccs = [ + c["id"].split("/")[-1].upper() for c in source.get("countries", []) + ] + continent_country_codes[c_code] = member_ccs + location_mappings[c_code] = member_ccs + except Exception as e: + logger.warning("Failed to resolve continent names from ES: %s", e) + + # Map of filters inside our Elasticsearch aggregation + filters_map: Dict[str, Dict[str, Any]] = {} + + # Resolve the topic IDs from the openalex-topics index to enable fast term queries + resolved_topic_ids: Dict[str, str] = {} + try: + topic_res = await elasticsearch.search( + index="openalex-topics", + query={ + "bool": { + "should": [ + {"match_phrase": {"display_name": t}} for t in topics + ] + } + }, + size=len(topics) * 2, + cluster="nes" + ) + for hit in topic_res.get("hits", {}).get("hits", []): + source = hit["_source"] + resolved_topic_ids[source["display_name"]] = source["id"] + except Exception as e: + logger.warning("Failed to resolve topic IDs from ES: %s", e) + + # 1. Institution Filters + for inst_id in query_institutions: + filters_map[f"inst_{inst_id}"] = { + "nested": { + "path": "authorships.institutions", + "query": { + "term": { + "authorships.institutions.id": inst_id + } + } + } + } + + # 2. Country Filters + for cc in clean_countries: + filters_map[f"country_{cc}"] = { + "nested": { + "path": "authorships.institutions", + "query": { + "term": { + "authorships.institutions.country_code": cc + } + } + } + } + + # 3. Continent/Region Filters + for r_code, member_ccs in continent_country_codes.items(): + if member_ccs: + filters_map[f"region_{r_code}"] = { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.country_code": member_ccs + } + } + } + } + + # If no entities specified, return empty + if not filters_map: + return TrendResponse(series=[], years=years_range, location_mappings=location_mappings) + + # We will accumulate results in a nested structure: entity_key -> topic -> year -> (count, inst_count) + accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = { + key: {t: {yr: (0, 1) for yr in years_range} for t in topics} + for key in filters_map + } + + # Build topic matching clauses and filters + topic_clauses = [] + topic_filters = {} + for t in topics: + tid = resolved_topic_ids.get(t) + if tid: + clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}}, + {"term": {"primary_topic.id": tid}} + ], + "minimum_should_match": 1 + } + } + else: + clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}}, + {"match_phrase": {"primary_topic.display_name": t}} + ], + "minimum_should_match": 1 + } + } + topic_clauses.append(clause) + topic_filters[t] = clause + + # Construct the single-pass Elasticsearch query + query = { + "bool": { + "must": [ + { + "range": { + "publication_year": { + "gte": start_year, + "lte": end_year + } + } + }, + { + "bool": { + "should": topic_clauses, + "minimum_should_match": 1 + } + } + ] + } + } + + # Build two-layer nested aggregations (topics -> entities -> publication_year) + aggregations = { + "topics_agg": { + "filters": { + "filters": topic_filters + }, + "aggs": { + "entities_agg": { + "filters": { + "filters": filters_map + }, + "aggs": { + "by_year": { + "terms": { + "field": "publication_year", + "size": len(years_range) * 2 + } + } + } + } + } + } + } + + try: + res = await elasticsearch.search( + index=f"{str(ESIndex.OPENALEX_WORKS)}*", + query=query, + body={"aggs": aggregations}, + size=0, + cluster="nes" + ) + + topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) + for t_name, t_bucket in topics_buckets.items(): + entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) + for entity_key, e_bucket in entities_buckets.items(): + year_buckets = e_bucket.get("by_year", {}).get("buckets", []) + for yr_bucket in year_buckets: + yr = int(yr_bucket.get("key")) + count = int(yr_bucket.get("doc_count", 0)) + inst_count = 1 + if yr in years_range: + accumulated_data[entity_key][t_name][yr] = (count, inst_count) + + except Exception as e: + logger.error("Error executing single-pass Elasticsearch query: %s", e) + + # Process and build TrendSeries list + series_list: List[TrendSeries] = [] + + for entity_key, topic_dict in accumulated_data.items(): + # Resolve details for this entity + if entity_key.startswith("inst_"): + entity_id = entity_key[len("inst_"):] + entity_name = resolved_names.get(entity_id, entity_id) + entity_type = "institution" + elif entity_key.startswith("country_"): + entity_id = entity_key[len("country_"):] + entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") + entity_type = "country" + elif entity_key.startswith("region_"): + entity_id = entity_key[len("region_"):] + entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") + entity_type = "region" + else: + continue + + topic_data_map: Dict[str, List[TopicYearlyData]] = {} + + for topic, year_dict in topic_dict.items(): + yearly_data_items: List[TopicYearlyData] = [] + + # Extract raw counts and institution counts in sorted year order + raw_counts = [] + inst_counts = [] + for yr in years_range: + count, inst_count = year_dict[yr] + raw_counts.append(count) + inst_counts.append(inst_count) + + # MinMaxScaler normalization + normalized_counts = min_max_normalize(raw_counts) + + for idx, yr in enumerate(years_range): + yearly_data_items.append(TopicYearlyData( + year=yr, + raw=raw_counts[idx], + normalized=normalized_counts[idx], + institutions_count=inst_counts[idx] + )) + + topic_data_map[topic] = yearly_data_items + + series_list.append(TrendSeries( + entity_id=entity_id, + entity_name=entity_name, + entity_type=entity_type, + country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None, + topic_data=topic_data_map + )) + + return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) -- 2.56.1 From 15fc57da51863854da2c70aecaba6fb138af1287 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 3 Jul 2026 20:04:35 +0200 Subject: [PATCH 02/13] First demo implementation of trend analysis frontend --- .../services/uni-ranking-service.ts | 66 ++- .../uni-trend-chart.component.html | 14 + .../uni-trend-chart.component.scss | 62 +++ .../uni-trend-chart.component.spec.ts | 22 + .../uni-trend-chart.component.ts | 451 ++++++++++++++++++ 5 files changed, 614 insertions(+), 1 deletion(-) create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.scss create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.spec.ts create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts diff --git a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts b/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts index ece71b78..d3e362bf 100644 --- a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts +++ b/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts @@ -1,7 +1,15 @@ // src/app/modules/university-ranking/services/university-data.service.ts import { inject, Injectable } from '@angular/core'; import { Observable } from 'rxjs'; -import { InstitutionsService, RankingResponse } from '../../../api'; +import { + InstitutionsService, + RankingResponse, + TrendResponse, + TopInstitutionItem, + AutocompleteResponse, + AutocompleteLocationItem, +} from '../../../api'; + export type ResearchTopic = | 'Artificial Intelligence' | 'Quantum Computing' @@ -26,4 +34,60 @@ export class UniversityRankingService { metric, ); } + + //trend analysis part + /** + * Fetches the comparative trend analysis data. + */ + getTrend( + topics: string[], + institutions?: string[], + countries?: string[], + regions?: string[], + ): Observable { + return this.apiService.getTrendApiInseServiceUniversityRankingsTrendGet( + topics as any, + institutions, + countries, + regions, + ); + } + + /** + * Fetches recommendations/suggestions of top institutions based on a specific topic. + */ + getTopInstitutions( + topic: string, + region?: string, + country?: string, + limit?: number, + ): Observable { + return this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic, + region, + country, + limit, + ); + } + + /** + * Autocompletes institutions based on query text. + */ + autocomplete(query: string): Observable { + return this.apiService.autocompleteInstitutions( + query, + undefined, + 'education', + 10, + ); + } + + /** + * Autocompletes countries and continents. + */ + autocompleteLocations(query: string): Observable { + return this.apiService.getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query, + ); + } } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html new file mode 100644 index 00000000..d76650ac --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html @@ -0,0 +1,14 @@ +
+ @if (data() && data()!.series && data()!.series.length > 0) { +
+ } @else { +
+
📊
+

No Trend Data Available

+

+ Please select at least one topic and choose institutions or regions to + compare in the control panel. +

+
+ } +
diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.scss new file mode 100644 index 00000000..97762b4a --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.scss @@ -0,0 +1,62 @@ +.chart-wrapper { + position: relative; + width: 100%; + height: 100%; + min-height: 450px; + background: rgba(255, 255, 255, 0.6); + backdrop-filter: blur(10px); + border-radius: 12px; + padding: 16px; + box-sizing: border-box; + + .trend-chart-render { + width: 100%; + height: 480px; + } + + .no-data-msg { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 380px; + text-align: center; + color: #4b5563; + padding: 24px; + border: 2px dashed #e5e7eb; + border-radius: 12px; + background: rgba(249, 250, 251, 0.5); + + .icon { + font-size: 48px; + margin-bottom: 16px; + animation: pulse 2s infinite ease-in-out; + } + + h3 { + font-size: 18px; + font-weight: 600; + color: #111827; + margin-bottom: 8px; + } + + p { + font-size: 14px; + color: #6b7280; + max-width: 320px; + line-height: 1.5; + } + } +} + +@keyframes pulse { + 0%, + 100% { + transform: scale(1); + opacity: 0.8; + } + 50% { + transform: scale(1.08); + opacity: 1; + } +} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.spec.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.spec.ts new file mode 100644 index 00000000..8beb0a2e --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.spec.ts @@ -0,0 +1,22 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { UniTrendChartComponent } from './uni-trend-chart.component'; + +describe('UniTrendChartComponent', () => { + let component: UniTrendChartComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [UniTrendChartComponent], + }).compileComponents(); + + fixture = TestBed.createComponent(UniTrendChartComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts new file mode 100644 index 00000000..f8ba7f61 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -0,0 +1,451 @@ +import { + Component, + ChangeDetectionStrategy, + input, + computed, +} from '@angular/core'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; +import { TrendResponse } from '../../../api'; + +@Component({ + selector: 'app-uni-trend-chart', + templateUrl: './uni-trend-chart.component.html', + styleUrl: './uni-trend-chart.component.scss', + imports: [NgxEchartsDirective], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class UniTrendChartComponent { + // Input signals following Angular v21 standards + readonly data = input(null); + readonly mode = input<'normalized' | 'total'>('total'); + readonly activeTopic = input(null); + readonly startYear = input(2015); + readonly endYear = input(2026); + + // Computed signal to automatically rebuild ECharts options when data or mode changes + readonly chartOptions = computed(() => { + const trendData = this.data(); + if (!trendData || !trendData.series || trendData.series.length === 0) { + return {}; + } + + const currentMode = this.mode(); + const startYr = this.startYear(); + const endYr = this.endYear(); + 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 topics = Object.keys(trendData.series[0].topic_data || {}); + const active = this.activeTopic(); + const selectedTopic = + active && topics.includes(active) + ? active + : topics.length > 0 + ? topics[0] + : null; + + if (!selectedTopic) { + return {}; + } + + const series: any[] = []; + const entityColors = [ + '#ec4899', // Pink + '#3b82f6', // Blue + '#10b981', // Emerald Green + '#f59e0b', // Amber/Yellow + '#8b5cf6', // Purple + '#06b6d4', // Cyan + '#6366f1', // Indigo + ]; + + // Build series: Line in top grid, growth volume bars and S-Curve in bottom grid + trendData.series.forEach((entity, entityIdx) => { + const color = entityColors[entityIdx % entityColors.length]; + + // 1. Add line series for the currently selected topic (placed in Grid 0) + const yrTopicData = entity.topic_data[selectedTopic]; + const lineData = years.map((year) => { + const yrData = yrTopicData?.find((y) => y.year === year); + if (!yrData) return 0; + return currentMode === 'normalized' ? yrData.normalized : yrData.raw; + }); + + series.push({ + name: `${entity.entity_name}`, + type: 'line', + xAxisIndex: 0, + yAxisIndex: 0, + data: lineData, + smooth: true, + lineStyle: { + width: 2.5, + color: color, + }, + itemStyle: { + color: color, + }, + emphasis: { + lineStyle: { width: 3.5 }, + }, + }); + + // 2. Add YoY growth volume bars for the selected topic (placed in Grid 1) + const volumeData = years.map((year) => { + const yrData = yrTopicData?.find((y) => y.year === year); + return yrData ? yrData.raw : 0; + }); + + const bars = years.map((year, idx) => { + const val = volumeData[idx]; + const prevVal = idx > 0 ? volumeData[idx - 1] : val; + const trendSign = val >= prevVal ? 1 : -1; + return [idx, val, trendSign]; + }); + + series.push({ + name: `${entity.entity_name} (YoY Growth)`, + type: 'bar', + xAxisIndex: 1, + yAxisIndex: 1, + data: bars, + itemStyle: { + color: (params: any) => { + const trendSign = params.value[2]; + return trendSign >= 0 ? '#10b981' : '#ef4444'; // Green vs Red + }, + }, + }); + + // 3. Add S-Curve cumulative publications trend overlay (placed in Grid 1) + let cumulativeSum = 0; + const cumulativeData = volumeData.map((val) => { + cumulativeSum += val; + return cumulativeSum; + }); + + series.push({ + name: `${entity.entity_name} (S-Curve)`, + type: 'line', + xAxisIndex: 1, + yAxisIndex: 2, + data: cumulativeData, + smooth: true, + symbol: 'none', + lineStyle: { + width: 2, + color: color, + type: 'dashed', + }, + itemStyle: { + color: color, + }, + }); + }); + + const yAxisName = + currentMode === 'normalized' + ? 'Normalized Scale (0 - 1)' + : 'Publications Volume'; + + return { + title: { + text: `Publication Trends: ${selectedTopic}`, + left: 'left', + textStyle: { + fontSize: 16, + fontWeight: 600, + color: '#1f2937', + }, + }, + tooltip: { + trigger: 'axis', + axisPointer: { type: 'cross' }, + backgroundColor: 'rgba(255, 255, 255, 0.95)', + borderColor: '#e5e7eb', + borderWidth: 1, + textStyle: { + color: '#374151', + fontSize: 12, + }, + formatter: (params: any) => { + if (!params || params.length === 0) return ''; + const yearNum = parseInt(params[0].name, 10); + + let res = `
`; + res += `Year: ${yearNum}
`; + res += `
`; + + trendData.series.forEach((entity, entityIdx) => { + const color = entityColors[entityIdx % entityColors.length]; + res += `
`; + res += ``; + res += `${entity.entity_name}:
`; + + const yrData = entity.topic_data[selectedTopic]?.find( + (y) => y.year === yearNum, + ); + if (yrData) { + const val = + currentMode === 'normalized' ? yrData.normalized : yrData.raw; + const displayVal = + currentMode === 'normalized' + ? val.toFixed(2) + : val.toLocaleString(); + + let contributionStr = ''; + if (currentMode === 'total') { + if (entity.entity_type === 'institution') { + const instCountryCode = entity.country_code?.toUpperCase(); + + const parentCountry = trendData.series.find( + (s) => + s.entity_type === 'country' && + s.entity_id.toUpperCase() === instCountryCode, + ); + + const parentContinent = trendData.series.find((s) => { + if (s.entity_type !== 'region') return false; + const memberCountries = + trendData.location_mappings?.[s.entity_id] || []; + return memberCountries.some( + (c) => c.toUpperCase() === instCountryCode, + ); + }); + + if (parentCountry) { + const parentYr = parentCountry.topic_data[ + selectedTopic + ]?.find((y) => y.year === yearNum); + if (parentYr && parentYr.raw > 0) { + const pct = (yrData.raw / parentYr.raw) * 100; + contributionStr = ` (${pct.toFixed(1)}% of ${parentCountry.entity_name})`; + } + } else if (parentContinent) { + const parentYr = parentContinent.topic_data[ + selectedTopic + ]?.find((y) => y.year === yearNum); + if (parentYr && parentYr.raw > 0) { + const pct = (yrData.raw / parentYr.raw) * 100; + contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`; + } + } else { + const sumInsts = trendData.series + .filter((s) => s.entity_type === 'institution') + .reduce((sum, s) => { + const y = s.topic_data[selectedTopic]?.find( + (yd) => yd.year === yearNum, + ); + return sum + (y ? y.raw : 0); + }, 0); + if (sumInsts > 0) { + const pct = (yrData.raw / sumInsts) * 100; + contributionStr = ` (${pct.toFixed(1)}% of compared institutions)`; + } + } + } else if (entity.entity_type === 'country') { + const countryCode = entity.entity_id.toUpperCase(); + + const parentContinent = trendData.series.find((s) => { + if (s.entity_type !== 'region') return false; + const memberCountries = + trendData.location_mappings?.[s.entity_id] || []; + return memberCountries.some( + (c) => c.toUpperCase() === countryCode, + ); + }); + + const childInstsSum = trendData.series + .filter( + (s) => + s.entity_type === 'institution' && + s.country_code?.toUpperCase() === countryCode, + ) + .reduce((sum, s) => { + const y = s.topic_data[selectedTopic]?.find( + (yd) => yd.year === yearNum, + ); + return sum + (y ? y.raw : 0); + }, 0); + + const remainingVal = Math.max(0, yrData.raw - childInstsSum); + const remainingPct = (remainingVal / yrData.raw) * 100; + + if (parentContinent) { + const parentYr = parentContinent.topic_data[ + selectedTopic + ]?.find((y) => y.year === yearNum); + if (parentYr && parentYr.raw > 0) { + const pct = (yrData.raw / parentYr.raw) * 100; + contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`; + } + } + + if (childInstsSum > 0) { + contributionStr += `
(excl. compared institutions: ${remainingVal.toLocaleString()} / ${remainingPct.toFixed(1)}%)`; + } + } else if (entity.entity_type === 'region') { + const continentId = entity.entity_id; + const memberCountries = + trendData.location_mappings?.[continentId] || []; + + const childSum = trendData.series + .filter((s) => { + if (s.entity_type === 'country') { + return memberCountries.some( + (c) => c.toUpperCase() === s.entity_id.toUpperCase(), + ); + } + if (s.entity_type === 'institution') { + return memberCountries.some( + (c) => + c.toUpperCase() === s.country_code?.toUpperCase(), + ); + } + return false; + }) + .reduce((sum, s) => { + const y = s.topic_data[selectedTopic]?.find( + (yd) => yd.year === yearNum, + ); + return sum + (y ? y.raw : 0); + }, 0); + + const remainingVal = Math.max(0, yrData.raw - childSum); + const remainingPct = (remainingVal / yrData.raw) * 100; + + if (childSum > 0) { + contributionStr = `
(excl. compared elements: ${remainingVal.toLocaleString()} / ${remainingPct.toFixed(1)}%)`; + } + } + } + + res += `• ${selectedTopic}: ${displayVal}${contributionStr}
`; + } + res += `
`; + }); + + res += `
`; + return res; + }, + }, + legend: { + bottom: 5, + left: 'center', + type: 'scroll', + textStyle: { color: '#4b5563' }, + }, + axisPointer: { + link: [{ xAxisIndex: 'all' }], + label: { backgroundColor: '#777' }, + }, + grid: [ + { + left: '6%', + right: '8%', + top: '12%', + height: '52%', + }, + { + left: '6%', + right: '8%', + top: '73%', + height: '14%', + }, + ], + xAxis: [ + { + type: 'category', + data: xAxisData, + boundaryGap: false, + axisLine: { onZero: false, lineStyle: { color: '#e5e7eb' } }, + axisLabel: { color: '#4b5563' }, + splitLine: { show: false }, + min: 'dataMin', + max: 'dataMax', + axisPointer: { z: 100 }, + }, + { + type: 'category', + gridIndex: 1, + data: xAxisData, + boundaryGap: false, + axisLine: { onZero: false, lineStyle: { color: '#e5e7eb' } }, + axisTick: { show: false }, + splitLine: { show: false }, + axisLabel: { show: false }, + min: 'dataMin', + max: 'dataMax', + }, + ], + yAxis: [ + { + scale: true, + name: yAxisName, + nameTextStyle: { color: '#4b5563', padding: [0, 0, 8, 0] }, + axisLabel: { color: '#4b5563' }, + axisLine: { lineStyle: { color: '#e5e7eb' } }, + splitLine: { lineStyle: { color: '#f3f4f6' } }, + }, + { + scale: true, + gridIndex: 1, + splitNumber: 2, + axisLabel: { show: false }, + axisLine: { show: false }, + axisTick: { show: false }, + splitLine: { show: false }, + }, + { + scale: true, + gridIndex: 1, + position: 'right', + axisLabel: { color: '#9ca3af', show: true }, + axisLine: { lineStyle: { color: '#e5e7eb' } }, + splitLine: { show: false }, + }, + ], + brush: { + toolbox: ['rect', 'lineX', 'clear'], + xAxisIndex: 'all', + brushLink: 'all', + outOfBrush: { colorAlpha: 0.15 }, + }, + toolbox: { + left: 'right', + top: 'top', + feature: { + brush: { type: ['rect', 'lineX', 'clear'] }, + saveAsImage: { title: 'Save' }, + }, + }, + dataZoom: [ + { + type: 'inside', + xAxisIndex: [0, 1], + }, + { + type: 'slider', + show: true, + xAxisIndex: [0, 1], + bottom: 30, + height: 15, + borderColor: '#e5e7eb', + fillerColor: 'rgba(236, 72, 153, 0.1)', + handleIcon: + 'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z', + handleSize: '120%', + handleStyle: { + color: '#ec4899', + shadowBlur: 3, + shadowColor: 'rgba(0, 0, 0, 0.2)', + }, + textStyle: { color: '#4b5563' }, + }, + ], + series: series, + }; + }); +} -- 2.56.1 From 47fb41105ad8e9bbbeccc12de2ee8c0fc54aa0dc Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 3 Jul 2026 22:20:56 +0200 Subject: [PATCH 03/13] Parent componentn to diplay different trend diagrams --- .../uni-trend-parent.component.html | 249 ++++++++++ .../uni-trend-parent.component.scss | 449 +++++++++++++++++ .../uni-trend-parent.component.spec.ts | 22 + .../uni-trend-parent.component.ts | 470 ++++++++++++++++++ 4 files changed, 1190 insertions(+) create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.spec.ts create mode 100644 webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts 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 new file mode 100644 index 00000000..a6110133 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -0,0 +1,249 @@ +
+ + + + +
+
+ Visualization Scale: +
+ + +
+
+ +
+ @if (isTrendLoading()) { +
+
+

Retrieving trend data from works index...

+
+ } + @if (selectedTrendTopics().length > 1) { +
+ @for (topic of selectedTrendTopics(); track topic) { + + } +
+ } + +
+
+
diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss new file mode 100644 index 00000000..7e2eda37 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -0,0 +1,449 @@ +.trend-layout { + display: grid; + grid-template-columns: 300px 1fr; + gap: 1.5rem; + margin-top: 1.5rem; + font-family: 'Inter', sans-serif; + + @media (max-width: 1024px) { + grid-template-columns: 1fr; + } +} + +.trend-sidebar { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.control-card { + background: white; + border-radius: 10px; + padding: 1.25rem; + border: 1px solid #e5e7eb; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); + + h3 { + font-size: 0.8rem; + font-weight: 600; + text-transform: uppercase; + color: #6b7280; + margin: 0 0 0.75rem 0; + letter-spacing: 0.05em; + } + + &.suggestions-card { + background: #fafafa; + } +} + +.checkbox-group { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.checkbox-label { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.875rem; + color: #374151; + cursor: pointer; + + input[type='checkbox'] { + accent-color: #3b82f6; + width: 15px; + height: 15px; + cursor: pointer; + } +} + +.comparison-list { + display: flex; + flex-direction: column; + gap: 0.4rem; + max-height: 140px; + overflow-y: auto; + margin-bottom: 0.75rem; + + .empty-list-info { + font-size: 0.75rem; + color: #9ca3af; + text-align: center; + padding: 8px 0; + border: 1px dashed #e5e7eb; + border-radius: 5px; + } +} + +.comparison-item { + display: flex; + justify-content: space-between; + align-items: center; + background: #f3f4f6; + border: 1px solid #e5e7eb; + border-radius: 5px; + padding: 0.3rem 0.5rem; + + .item-name { + font-size: 0.75rem; + color: #374151; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 210px; + } + + .remove-btn { + background: none; + border: none; + color: #9ca3af; + cursor: pointer; + font-size: 0.7rem; + padding: 1px 4px; + border-radius: 3px; + &:hover { + color: #ef4444; + background: #fee2e2; + } + } + + &.location-item { + &.font-country { + background: #f0fdf4 !important; + border-color: #bbf7d0 !important; + .item-name { + color: #166534 !important; + } + } + &.font-region { + background: #eff6ff !important; + border-color: #bfdbfe !important; + .item-name { + color: #1e40af !important; + } + } + } +} + +.autocomplete-search { + position: relative; + width: 100%; + + input { + width: 100%; + padding: 0.5rem; + border-radius: 5px; + border: 1px solid #d1d5db; + font-size: 0.8125rem; + outline: none; + box-sizing: border-box; + &:focus { + border-color: #3b82f6; + } + } +} + +.autocomplete-results { + position: absolute; + top: 100%; + left: 0; + right: 0; + z-index: 50; + background: white; + border: 1px solid #e5e7eb; + border-radius: 5px; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + margin-top: 3px; + padding: 0; + list-style: none; + max-height: 180px; + overflow-y: auto; + + li button { + width: 100%; + text-align: left; + background: none; + border: none; + padding: 0.5rem 0.75rem; + cursor: pointer; + display: flex; + flex-direction: column; + &:hover { + background: #f3f4f6; + } + + .name { + font-size: 0.75rem; + font-weight: 500; + color: #1f2937; + } + .hint { + font-size: 0.65rem; + color: #9ca3af; + margin-top: 1px; + } + } +} + +.suggestions-list { + display: flex; + flex-direction: column; + gap: 0.4rem; + + .suggestions-loader { + font-size: 0.75rem; + color: #9ca3af; + text-align: center; + padding: 8px 0; + } +} + +.suggestion-item { + display: flex; + justify-content: space-between; + align-items: center; + background: white; + border: 1px solid #e5e7eb; + border-radius: 6px; + padding: 0.4rem 0.6rem; + text-align: left; + cursor: pointer; + + &:hover:not([disabled]) { + border-color: #3b82f6; + background: #f0f9ff; + transform: translateY(-1px); + } + + &[disabled] { + opacity: 0.5; + cursor: not-allowed; + background: #f3f4f6; + } + + .info { + display: flex; + flex-direction: column; + max-width: 210px; + + .name { + font-size: 0.75rem; + color: #374151; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .meta { + font-size: 0.65rem; + color: #9ca3af; + margin-top: 1px; + } + } + .add-icon { + font-size: 1rem; + color: #3b82f6; + font-weight: 600; + } +} + +.trend-main { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.trend-toggles-bar { + display: flex; + justify-content: space-between; + align-items: center; + background: white; + border-radius: 10px; + padding: 0.6rem 1rem; + border: 1px solid #e5e7eb; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + + .toggle-label { + font-size: 0.8125rem; + font-weight: 500; + color: #4b5563; + } +} + +.toggle-buttons { + display: flex; + background: #f3f4f6; + border-radius: 6px; + padding: 2px; + + button { + padding: 0.4rem 0.8rem; + border: none; + background: none; + font-size: 0.75rem; + font-weight: 500; + color: #4b5563; + border-radius: 5px; + cursor: pointer; + + &:hover:not(.active) { + color: #111827; + background: rgba(255, 255, 255, 0.5); + } + &.active { + background: white; + color: #3b82f6; + font-weight: 600; + } + } +} + +.chart-holder-card { + position: relative; + background: white; + border-radius: 10px; + border: 1px solid #e5e7eb; + overflow: hidden; + min-height: 400px; +} + +.chart-topic-tabs { + display: flex; + gap: 0.4rem; + padding: 0.6rem 1rem; + background: #f9fafb; + border-bottom: 1px solid #e5e7eb; + + button { + padding: 0.3rem 0.6rem; + border: 1px solid #e5e7eb; + background: white; + color: #4b5563; + border-radius: 5px; + font-size: 0.75rem; + font-weight: 500; + cursor: pointer; + transition: all 0.15s ease; + + &:hover { + border-color: #3b82f6; + color: #3b82f6; + background: #f0f9ff; + } + + &.active { + background: #3b82f6; + border-color: #3b82f6; + color: white; + font-weight: 600; + } + } +} + +.loader-overlay { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(255, 255, 255, 0.8); + z-index: 10; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + + .spinner { + width: 32px; + height: 32px; + border: 3px solid rgba(59, 130, 246, 0.1); + border-radius: 50%; + border-top-color: #3b82f6; + animation: spin 0.8s linear infinite; + margin-bottom: 8px; + } + + p { + font-size: 0.8125rem; + color: #4b5563; + margin: 0; + } +} + +.search-trend-btn-container { + display: flex; + justify-content: flex-end; + padding: 0.5rem 0; +} + +.search-trend-btn { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.6rem 1.2rem; + border-radius: 6px; + font-size: 0.875rem; + font-weight: 600; + cursor: pointer; + border: 1px solid #3b82f6; + background-color: #3b82f6; + color: white; + transition: all 0.2s ease; + + &:hover:not([disabled]) { + background-color: #2563eb; + border-color: #2563eb; + box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.2); + } + + &[disabled] { + opacity: 0.6; + cursor: not-allowed; + background-color: #9ca3af; + border-color: #9ca3af; + } + + &.dirty { + animation: pulse-border 2s infinite; + background-color: #2563eb; + border-color: #1d4ed8; + } +} + +.year-selectors { + display: flex; + gap: 0.5rem; + align-items: center; + + select { + flex: 1; + padding: 0.4rem; + border-radius: 5px; + border: 1px solid #d1d5db; + font-size: 0.8125rem; + background: white; + outline: none; + &:focus { + border-color: #3b82f6; + } + } +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +@keyframes pulse-border { + 0% { + box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7); + } + 70% { + box-shadow: 0 0 0 6px rgba(59, 130, 246, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); + } +} diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.spec.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.spec.ts new file mode 100644 index 00000000..b8b1b660 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.spec.ts @@ -0,0 +1,22 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { UniTrendParentComponent } from './uni-trend-parent.component'; + +describe('UniTrendParentComponent', () => { + let component: UniTrendParentComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [UniTrendParentComponent], + }).compileComponents(); + + fixture = TestBed.createComponent(UniTrendParentComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); 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 new file mode 100644 index 00000000..94ac41df --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -0,0 +1,470 @@ +import { + Component, + ChangeDetectionStrategy, + input, + computed, + signal, + effect, + inject, + OnInit, +} from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { FormsModule } from '@angular/forms'; +import { ActivatedRoute, Router } from '@angular/router'; +import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component'; +import { UniversityRankingsService } from '../../../api/api/university-rankings.service'; +import { InstitutionsService } from '../../../api/api/institutions.service'; +import { + TrendResponse, + TopInstitutionItem, + AutocompleteLocationItem, + AutocompleteResponse, +} from '../../../api'; + +@Component({ + selector: 'app-uni-trend-parent', + standalone: true, + imports: [CommonModule, FormsModule, UniTrendChartComponent], + templateUrl: './uni-trend-parent.component.html', + styleUrl: './uni-trend-parent.component.scss', + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class UniTrendParentComponent implements OnInit { + private readonly apiService = inject(UniversityRankingsService); + private readonly institutionsApiService = inject(InstitutionsService); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + + // Input containing extracted/selected keywords from parent + readonly keywords = input([]); + + // Trend settings signals + readonly selectedTrendTopics = signal([]); + readonly primaryInstitution = signal(null); + readonly primaryInstitutionName = signal( + 'University of Duisburg-Essen', + ); + readonly comparisonInstitutions = signal<{ id: string; name: string }[]>([]); + readonly comparisonCountries = signal<{ id: string; name: string }[]>([]); + readonly comparisonRegions = signal<{ id: string; name: string }[]>([]); + readonly startYear = signal(2015); + readonly endYear = signal(new Date().getFullYear() - 1); + readonly chartMode = signal<'normalized' | 'total'>('total'); + readonly activeChartTopic = signal(''); + + // Cached parameters of the last active search request to track "isDirty" + readonly fetchedTopics = signal([]); + readonly fetchedInstitutions = signal<{ id: string; name: string }[]>([]); + readonly fetchedCountries = signal<{ id: string; name: string }[]>([]); + readonly fetchedRegions = signal<{ id: string; name: string }[]>([]); + + // Results & Loading signals + readonly rawTrendResponse = signal(null); + readonly isTrendLoading = signal(false); + readonly topSuggestions = signal([]); + readonly isSuggestionsLoading = signal(false); + + // Autocomplete UI state + readonly searchQuery = signal(''); + readonly searchResults = signal([]); + readonly locationQuery = signal(''); + readonly locationSearchResults = signal([]); + + // Years array for selects + readonly availableYears: number[] = []; + + // Computed: filters out items locally if they were removed from list + readonly trendResponse = computed(() => { + const raw = this.rawTrendResponse(); + if (!raw) return null; + + const currentInstIds = new Set( + this.comparisonInstitutions().map((i) => i.id.toLowerCase()), + ); + const currentCountryIds = new Set( + this.comparisonCountries().map((c) => c.id.toLowerCase()), + ); + const currentRegionIds = new Set( + this.comparisonRegions().map((r) => r.id.toLowerCase()), + ); + const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase(); + + const filteredSeries = raw.series.filter((s: any) => { + const id = s.entity_id.toLowerCase(); + if (s.entity_type === 'institution') { + return id === defaultInstId || currentInstIds.has(id); + } else if (s.entity_type === 'country') { + return currentCountryIds.has(id); + } else if (s.entity_type === 'region') { + return currentRegionIds.has(id); + } + return false; + }); + + return { + ...raw, + series: filteredSeries, + }; + }); + + // Computed dirty state to enable "Search" button + readonly isDirty = computed(() => { + const fetchedInsts = this.fetchedInstitutions() + .map((i) => i.id) + .sort() + .join(','); + const currentInsts = this.comparisonInstitutions() + .map((i) => i.id) + .sort() + .join(','); + if (fetchedInsts !== currentInsts) return true; + + const fetchedC = this.fetchedCountries() + .map((c) => c.id) + .sort() + .join(','); + const currentC = this.comparisonCountries() + .map((c) => c.id) + .sort() + .join(','); + if (fetchedC !== currentC) return true; + + const fetchedR = this.fetchedRegions() + .map((r) => r.id) + .sort() + .join(','); + const currentR = this.comparisonRegions() + .map((r) => r.id) + .sort() + .join(','); + if (fetchedR !== currentR) return true; + + const fetchedT = this.fetchedTopics().sort().join(','); + const currentT = this.selectedTrendTopics().sort().join(','); + if (fetchedT !== currentT) return true; + + return false; + }); + + constructor() { + // Generate year range from 2000 to current year + const currentYear = new Date().getFullYear(); + for (let y = 2000; y <= currentYear; y++) { + this.availableYears.push(y); + } + + // Effect: automatically sync checkboxes list whenever input keywords change + effect( + () => { + const kws = this.keywords(); + if (kws.length > 0) { + // Find existing selections that are still in keywords, or default to all + const validSelections = this.selectedTrendTopics().filter((t) => + kws.includes(t), + ); + if (validSelections.length > 0) { + this.selectedTrendTopics.set(validSelections); + } else { + this.selectedTrendTopics.set(kws); + } + + // Initialize active chart topic to the first selected topic if empty or invalid + const active = this.activeChartTopic(); + if (!active || !this.selectedTrendTopics().includes(active)) { + this.activeChartTopic.set(this.selectedTrendTopics()[0] || ''); + } + } else { + this.selectedTrendTopics.set([]); + } + }, + { allowSignalWrites: true }, + ); + + // Handle initialization and synchronization of URL state + this.route.queryParams.subscribe((params) => { + // Parse institutions serialized as id|name + if (params['institutions']) { + const insts = Array.isArray(params['institutions']) + ? params['institutions'] + : [params['institutions']]; + const parsed = insts.map((i) => { + const parts = i.split('|'); + return { id: parts[0], name: parts[1] || parts[0] }; + }); + this.comparisonInstitutions.set(parsed); + } + // Parse countries + if (params['countries']) { + const ccs = Array.isArray(params['countries']) + ? params['countries'] + : [params['countries']]; + const parsed = ccs.map((c) => { + const parts = c.split('|'); + return { id: parts[0], name: parts[1] || parts[0] }; + }); + this.comparisonCountries.set(parsed); + } + // Parse regions + if (params['regions']) { + const regs = Array.isArray(params['regions']) + ? params['regions'] + : [params['regions']]; + const parsed = regs.map((r) => { + const parts = r.split('|'); + return { id: parts[0], name: parts[1] || parts[0] }; + }); + this.comparisonRegions.set(parsed); + } + + if (params['start_year']) { + this.startYear.set(Number(params['start_year'])); + } + if (params['end_year']) { + this.endYear.set(Number(params['end_year'])); + } + if (params['chart_mode']) { + this.chartMode.set(params['chart_mode'] as any); + } + if (params['active_chart_topic']) { + this.activeChartTopic.set(params['active_chart_topic']); + } + + // Auto-trigger load once on initial page render if keywords are present + if (this.rawTrendResponse() === null && this.keywords().length > 0) { + this.fetchTrendData(); + } + }); + } + + ngOnInit() { + this.loadTrendSuggestions(); + } + + // Fetch recommended institutions for comparison based on current topics + loadTrendSuggestions() { + this.isSuggestionsLoading.set(true); + const topics = this.selectedTrendTopics(); + const topic = + topics.length > 0 + ? topics[0] + : this.keywords().length > 0 + ? this.keywords()[0] + : 'Artificial Intelligence'; + + const countryFilter = + this.comparisonCountries().length > 0 + ? this.comparisonCountries()[0].id.split('/').pop() + : undefined; + const regionFilter = + this.comparisonRegions().length > 0 + ? this.comparisonRegions()[0].name + : undefined; + + this.apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic, + regionFilter, + countryFilter, + 6, + ) + .subscribe({ + next: (res) => { + this.topSuggestions.set(res || []); + this.isSuggestionsLoading.set(false); + }, + error: () => { + this.isSuggestionsLoading.set(false); + }, + }); + } + + // Trigger search trend data (only when "Search" is clicked) + fetchTrendData() { + const topics = this.selectedTrendTopics(); + if (topics.length === 0) return; + + this.isTrendLoading.set(true); + + // Save parameters of this request to check dirty state later + this.fetchedTopics.set([...topics]); + this.fetchedInstitutions.set([...this.comparisonInstitutions()]); + this.fetchedCountries.set([...this.comparisonCountries()]); + this.fetchedRegions.set([...this.comparisonRegions()]); + + this.apiService + .getTrendApiInseServiceUniversityRankingsTrendGet( + topics, + this.comparisonInstitutions().map((i) => i.id), + this.comparisonCountries().map((c) => c.id), + this.comparisonRegions().map((r) => r.id), + ) + .subscribe({ + next: (response) => { + this.rawTrendResponse.set(response); + this.isTrendLoading.set(false); + this.updateUrlParams(); + }, + error: () => { + this.isTrendLoading.set(false); + }, + }); + } + + // Update query params to synchronize state + updateUrlParams() { + const queryParams: any = { + trend_topics: this.selectedTrendTopics(), + institutions: + this.comparisonInstitutions().length > 0 + ? this.comparisonInstitutions().map((i) => `${i.id}|${i.name}`) + : null, + countries: + this.comparisonCountries().length > 0 + ? this.comparisonCountries().map((c) => `${c.id}|${c.name}`) + : null, + regions: + this.comparisonRegions().length > 0 + ? this.comparisonRegions().map((r) => `${r.id}|${r.name}`) + : null, + start_year: this.startYear(), + end_year: this.endYear(), + chart_mode: this.chartMode(), + active_chart_topic: this.activeChartTopic(), + }; + + this.router.navigate([], { + relativeTo: this.route, + queryParams, + queryParamsHandling: 'merge', + }); + } + + // Checkbox topic toggling + onTrendTopicToggle(topic: string, event: Event) { + const isChecked = (event.target as HTMLInputElement).checked; + const current = this.selectedTrendTopics(); + let updated: string[]; + + if (isChecked) { + updated = current.includes(topic) ? current : [...current, topic]; + } else { + updated = + current.length > 1 ? current.filter((t) => t !== topic) : current; + if (current.length === 1) { + (event.target as HTMLInputElement).checked = true; + } + } + + this.selectedTrendTopics.set(updated); + + // Auto-update active tab selection if previous was removed + const active = this.activeChartTopic(); + if (!updated.includes(active)) { + this.activeChartTopic.set(updated[0] || ''); + } + } + + // Add comparison institution + addInstitution(id: string, name: string) { + const current = this.comparisonInstitutions(); + if (!current.some((i) => i.id === id) && id !== this.primaryInstitution()) { + this.comparisonInstitutions.set([...current, { id, name }]); + } + this.searchQuery.set(''); + this.searchResults.set([]); + } + + // Remove comparison institution (data reuses instantly via computed) + removeInstitution(id: string) { + const current = this.comparisonInstitutions(); + this.comparisonInstitutions.set(current.filter((i) => i.id !== id)); + } + + // Add country or region + addLocation(loc: AutocompleteLocationItem) { + if (loc.type === 'country') { + const current = this.comparisonCountries(); + if (!current.some((c) => c.id === loc.id)) { + this.comparisonCountries.set([ + ...current, + { id: loc.id, name: loc.display_name }, + ]); + } + } else if (loc.type === 'continent') { + const current = this.comparisonRegions(); + if (!current.some((r) => r.id === loc.id)) { + this.comparisonRegions.set([ + ...current, + { id: loc.id, name: loc.display_name }, + ]); + } + } + this.locationQuery.set(''); + this.locationSearchResults.set([]); + this.loadTrendSuggestions(); + } + + // Remove country or region + removeLocation(id: string, type: 'country' | 'continent') { + if (type === 'country') { + const current = this.comparisonCountries(); + this.comparisonCountries.set(current.filter((c) => c.id !== id)); + } else if (type === 'continent') { + const current = this.comparisonRegions(); + this.comparisonRegions.set(current.filter((r) => r.id !== id)); + } + this.loadTrendSuggestions(); + } + + // Scaling mode toggle (data reuses instantly) + setChartMode(mode: 'normalized' | 'total') { + this.chartMode.set(mode); + this.updateUrlParams(); + } + + // Topic tab toggle (data reuses instantly) + updateActiveChartTopic(topic: string) { + this.activeChartTopic.set(topic); + this.updateUrlParams(); + } + + // Autocomplete query changes for institutions + onSearchChange(query: string) { + this.searchQuery.set(query); + if (query.trim().length >= 3) { + this.institutionsApiService + .autocompleteInstitutions(query, undefined, 'education', 10) + .subscribe({ + next: (res) => { + this.searchResults.set(res.results || []); + }, + error: () => { + this.searchResults.set([]); + }, + }); + } else { + this.searchResults.set([]); + } + } + + // Autocomplete query changes for locations + onLocationSearchChange(query: string) { + this.locationQuery.set(query); + if (query.trim().length >= 2) { + this.apiService + .getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query, + ) + .subscribe({ + next: (res) => { + this.locationSearchResults.set(res || []); + }, + error: () => { + this.locationSearchResults.set([]); + }, + }); + } else { + this.locationSearchResults.set([]); + } + } +} -- 2.56.1 From 1ddc5c42c56147f4fc0e2f60fa77d5f0769478d4 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 3 Jul 2026 22:33:32 +0200 Subject: [PATCH 04/13] generated frontend services and models --- service/src/main/inse/tags.py | 1 + .../main/inse/university_ranking/router.py | 2 +- webapp/src/app/api/api/api.ts | 3 + .../api/api/university-rankings.service.ts | 344 ++++++++++++++++++ .../app/api/model/autocompleteLocationItem.ts | 6 + webapp/src/app/api/model/models.ts | 3 + .../src/app/api/model/topInstitutionItem.ts | 7 + webapp/src/app/api/model/trendResponse.ts | 20 + .../keywords-search.component.html | 8 + .../keywords-search.component.ts | 2 + .../services/uni-ranking-service.ts | 10 +- .../uni-trend-chart.component.ts | 79 ++-- .../uni-trend-parent.component.ts | 4 +- 13 files changed, 447 insertions(+), 42 deletions(-) create mode 100644 webapp/src/app/api/api/university-rankings.service.ts create mode 100644 webapp/src/app/api/model/autocompleteLocationItem.ts create mode 100644 webapp/src/app/api/model/topInstitutionItem.ts create mode 100644 webapp/src/app/api/model/trendResponse.ts diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 08fc4bd0..1b25c312 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -12,3 +12,4 @@ class Tags(StrEnum): AUTH = "Auth" ACCOUNT = "Account" ORGANIZATION = "Organization" + UNIVERSITY_RANKINGS = "University Rankings" diff --git a/service/src/main/inse/university_ranking/router.py b/service/src/main/inse/university_ranking/router.py index 22e24b1c..67c12957 100644 --- a/service/src/main/inse/university_ranking/router.py +++ b/service/src/main/inse/university_ranking/router.py @@ -20,7 +20,7 @@ logger = logging.getLogger(__name__) router = APIRouter( prefix="/api/inse-service/university-rankings", - tags=[Tags.INSTITUTIONS] + tags=[Tags.UNIVERSITY_RANKINGS] ) @router.get( diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 8ea55e0b..6a70a903 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -26,6 +26,8 @@ export * from './topics.service'; import { TopicsService } from './topics.service'; export * from './works.service'; import { WorksService } from './works.service'; +export * from './university-rankings.service'; +import { UniversityRankingsService } from './university-rankings.service'; export const APIS = [ AuthService, CompanyConnectionsService, @@ -41,4 +43,5 @@ export const APIS = [ ProjectsService, TopicsService, WorksService, + UniversityRankingsService, ]; diff --git a/webapp/src/app/api/api/university-rankings.service.ts b/webapp/src/app/api/api/university-rankings.service.ts new file mode 100644 index 00000000..f88965d8 --- /dev/null +++ b/webapp/src/app/api/api/university-rankings.service.ts @@ -0,0 +1,344 @@ +/** + * Innovation Search Engine API + * + * NOTE: This class is manually implemented to act as if it were auto-generated by OpenAPI Generator. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { RankingResponse } from '../model/rankingResponse'; +// @ts-ignore +import { TrendResponse } from '../model/trendResponse'; +// @ts-ignore +import { TopInstitutionItem } from '../model/topInstitutionItem'; +// @ts-ignore +import { AutocompleteLocationItem } from '../model/autocompleteLocationItem'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + +@Injectable({ + providedIn: 'root', +}) +export class UniversityRankingsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } + + public getRankingsApiInseServiceUniversityRankingsGet( + topic: + | 'Artificial Intelligence' + | 'Quantum Computing' + | 'Renewable Energy' + | 'Biotechnology', + metric?: 'publications' | 'citations', + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (topic === null || topic === undefined) { + throw new Error( + 'Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + topic, + 'topic', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + metric, + 'metric', + ); + + let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + + let localVarPath = `/api/inse-service/university-rankings`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + public getTrendApiInseServiceUniversityRankingsTrendGet( + topics: string[], + institutions?: string[], + countries?: string[], + regions?: string[], + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (topics === null || topics === undefined) { + throw new Error( + 'Required parameter topics was null or undefined when calling getTrendApiInseServiceUniversityRankingsTrendGet.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + if (topics) { + topics.forEach((val) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + val, + 'topics', + ); + }); + } + if (institutions) { + institutions.forEach((val) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + val, + 'institutions', + ); + }); + } + if (countries) { + countries.forEach((val) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + val, + 'countries', + ); + }); + } + if (regions) { + regions.forEach((val) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + val, + 'regions', + ); + }); + } + + let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + + let localVarPath = `/api/inse-service/university-rankings/trend`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic: string, + region?: string, + country?: string, + limit?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (topic === null || topic === undefined) { + throw new Error( + 'Required parameter topic was null or undefined when calling getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + topic, + 'topic', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + region, + 'region', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + country, + 'country', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); + + let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + + let localVarPath = `/api/inse-service/university-rankings/top-institutions`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + + let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + + let localVarPath = `/api/inse-service/university-rankings/autocomplete-locations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } +} diff --git a/webapp/src/app/api/model/autocompleteLocationItem.ts b/webapp/src/app/api/model/autocompleteLocationItem.ts new file mode 100644 index 00000000..c3fe1cdd --- /dev/null +++ b/webapp/src/app/api/model/autocompleteLocationItem.ts @@ -0,0 +1,6 @@ +export interface AutocompleteLocationItem { + id: string; + display_name: string; + code: string; + type: 'country' | 'continent'; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 8e381ef2..edd20e54 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -177,3 +177,6 @@ export * from './workTopicSubfield'; export * from './worksFilterProperties'; export * from './worksListResponse'; export * from './yearlyData'; +export * from './trendResponse'; +export * from './topInstitutionItem'; +export * from './autocompleteLocationItem'; diff --git a/webapp/src/app/api/model/topInstitutionItem.ts b/webapp/src/app/api/model/topInstitutionItem.ts new file mode 100644 index 00000000..8f1c6489 --- /dev/null +++ b/webapp/src/app/api/model/topInstitutionItem.ts @@ -0,0 +1,7 @@ +import { DehydratedInstitution } from './dehydratedInstitution'; + +export interface TopInstitutionItem extends DehydratedInstitution { + works_count?: number | null; + image_thumbnail_url?: string | null; + exact_topic_count?: number | null; +} diff --git a/webapp/src/app/api/model/trendResponse.ts b/webapp/src/app/api/model/trendResponse.ts new file mode 100644 index 00000000..7f5589f9 --- /dev/null +++ b/webapp/src/app/api/model/trendResponse.ts @@ -0,0 +1,20 @@ +export interface TopicYearlyData { + year: number; + raw: number; + normalized: number; + institutions_count: number; +} + +export interface TrendSeries { + entity_id: string; + entity_name: string; + entity_type: 'institution' | 'country' | 'region'; + country_code?: string | null; + topic_data: { [key: string]: Array }; +} + +export interface TrendResponse { + series: Array; + years: Array; + location_mappings?: { [key: string]: Array } | null; +} diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index 8eb10128..d30dc5f6 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -229,5 +229,13 @@ Suchen + + + @if (selectedKeywords().length > 0) { +
+ +
+ } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 03a02061..52312b88 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -28,6 +28,7 @@ import { TopicsService } from '../../api/api/topics.service'; import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest'; import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component'; +import { UniTrendParentComponent } from '../university-ranking/uni-trend-parent/uni-trend-parent.component'; type InputMode = 'url' | 'text'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; @@ -47,6 +48,7 @@ type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; MatExpansionModule, MatProgressBarModule, TopicAutocompleteComponent, + UniTrendParentComponent, ], templateUrl: './keywords-search.component.html', styleUrl: './keywords-search.component.scss', diff --git a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts b/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts index d3e362bf..311fc10f 100644 --- a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts +++ b/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts @@ -3,6 +3,7 @@ import { inject, Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { InstitutionsService, + UniversityRankingsService, RankingResponse, TrendResponse, TopInstitutionItem, @@ -20,6 +21,7 @@ export type DashboardMetric = 'publications' | 'citations'; @Injectable({ providedIn: 'root' }) export class UniversityRankingService { private apiService = inject(InstitutionsService); + private rankingsApiService = inject(UniversityRankingsService); /** * Fetches ranking and timeseries data directly from the backend. @@ -29,7 +31,7 @@ export class UniversityRankingService { topic: ResearchTopic, metric: DashboardMetric, ): Observable { - return this.apiService.getRankingsApiInseServiceUniversityRankingsGet( + return this.rankingsApiService.getRankingsApiInseServiceUniversityRankingsGet( topic, metric, ); @@ -45,7 +47,7 @@ export class UniversityRankingService { countries?: string[], regions?: string[], ): Observable { - return this.apiService.getTrendApiInseServiceUniversityRankingsTrendGet( + return this.rankingsApiService.getTrendApiInseServiceUniversityRankingsTrendGet( topics as any, institutions, countries, @@ -62,7 +64,7 @@ export class UniversityRankingService { country?: string, limit?: number, ): Observable { - return this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + return this.rankingsApiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( topic, region, country, @@ -86,7 +88,7 @@ export class UniversityRankingService { * Autocompletes countries and continents. */ autocompleteLocations(query: string): Observable { - return this.apiService.getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + return this.rankingsApiService.getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( query, ); } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index f8ba7f61..f549b878 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -6,7 +6,7 @@ import { } from '@angular/core'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; -import { TrendResponse } from '../../../api'; +import { TrendResponse, TrendSeries, TopicYearlyData } from '../../../api'; @Component({ selector: 'app-uni-trend-chart', @@ -162,10 +162,10 @@ export class UniTrendChartComponent { }, tooltip: { trigger: 'axis', - axisPointer: { type: 'cross' }, - backgroundColor: 'rgba(255, 255, 255, 0.95)', + backgroundColor: 'rgba(255, 255, 255, 0.96)', borderColor: '#e5e7eb', borderWidth: 1, + padding: 0, textStyle: { color: '#374151', fontSize: 12, @@ -178,14 +178,14 @@ export class UniTrendChartComponent { res += `Year: ${yearNum}
`; res += `
`; - trendData.series.forEach((entity, entityIdx) => { + trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { const color = entityColors[entityIdx % entityColors.length]; res += `
`; res += ``; res += `${entity.entity_name}:
`; const yrData = entity.topic_data[selectedTopic]?.find( - (y) => y.year === yearNum, + (y: TopicYearlyData) => y.year === yearNum, ); if (yrData) { const val = @@ -201,24 +201,26 @@ export class UniTrendChartComponent { const instCountryCode = entity.country_code?.toUpperCase(); const parentCountry = trendData.series.find( - (s) => + (s: TrendSeries) => s.entity_type === 'country' && s.entity_id.toUpperCase() === instCountryCode, ); - const parentContinent = trendData.series.find((s) => { - if (s.entity_type !== 'region') return false; - const memberCountries = - trendData.location_mappings?.[s.entity_id] || []; - return memberCountries.some( - (c) => c.toUpperCase() === instCountryCode, - ); - }); + const parentContinent = trendData.series.find( + (s: TrendSeries) => { + if (s.entity_type !== 'region') return false; + const memberCountries = + trendData.location_mappings?.[s.entity_id] || []; + return memberCountries.some( + (c: string) => c.toUpperCase() === instCountryCode, + ); + }, + ); if (parentCountry) { const parentYr = parentCountry.topic_data[ selectedTopic - ]?.find((y) => y.year === yearNum); + ]?.find((y: TopicYearlyData) => y.year === yearNum); if (parentYr && parentYr.raw > 0) { const pct = (yrData.raw / parentYr.raw) * 100; contributionStr = ` (${pct.toFixed(1)}% of ${parentCountry.entity_name})`; @@ -226,17 +228,19 @@ export class UniTrendChartComponent { } else if (parentContinent) { const parentYr = parentContinent.topic_data[ selectedTopic - ]?.find((y) => y.year === yearNum); + ]?.find((y: TopicYearlyData) => y.year === yearNum); if (parentYr && parentYr.raw > 0) { const pct = (yrData.raw / parentYr.raw) * 100; contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`; } } else { const sumInsts = trendData.series - .filter((s) => s.entity_type === 'institution') - .reduce((sum, s) => { + .filter( + (s: TrendSeries) => s.entity_type === 'institution', + ) + .reduce((sum: number, s: TrendSeries) => { const y = s.topic_data[selectedTopic]?.find( - (yd) => yd.year === yearNum, + (yd: TopicYearlyData) => yd.year === yearNum, ); return sum + (y ? y.raw : 0); }, 0); @@ -248,24 +252,26 @@ export class UniTrendChartComponent { } else if (entity.entity_type === 'country') { const countryCode = entity.entity_id.toUpperCase(); - const parentContinent = trendData.series.find((s) => { - if (s.entity_type !== 'region') return false; - const memberCountries = - trendData.location_mappings?.[s.entity_id] || []; - return memberCountries.some( - (c) => c.toUpperCase() === countryCode, - ); - }); + const parentContinent = trendData.series.find( + (s: TrendSeries) => { + if (s.entity_type !== 'region') return false; + const memberCountries = + trendData.location_mappings?.[s.entity_id] || []; + return memberCountries.some( + (c: string) => c.toUpperCase() === countryCode, + ); + }, + ); const childInstsSum = trendData.series .filter( - (s) => + (s: TrendSeries) => s.entity_type === 'institution' && s.country_code?.toUpperCase() === countryCode, ) - .reduce((sum, s) => { + .reduce((sum: number, s: TrendSeries) => { const y = s.topic_data[selectedTopic]?.find( - (yd) => yd.year === yearNum, + (yd: TopicYearlyData) => yd.year === yearNum, ); return sum + (y ? y.raw : 0); }, 0); @@ -276,7 +282,7 @@ export class UniTrendChartComponent { if (parentContinent) { const parentYr = parentContinent.topic_data[ selectedTopic - ]?.find((y) => y.year === yearNum); + ]?.find((y: TopicYearlyData) => y.year === yearNum); if (parentYr && parentYr.raw > 0) { const pct = (yrData.raw / parentYr.raw) * 100; contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`; @@ -292,23 +298,24 @@ export class UniTrendChartComponent { trendData.location_mappings?.[continentId] || []; const childSum = trendData.series - .filter((s) => { + .filter((s: TrendSeries) => { if (s.entity_type === 'country') { return memberCountries.some( - (c) => c.toUpperCase() === s.entity_id.toUpperCase(), + (c: string) => + c.toUpperCase() === s.entity_id.toUpperCase(), ); } if (s.entity_type === 'institution') { return memberCountries.some( - (c) => + (c: string) => c.toUpperCase() === s.country_code?.toUpperCase(), ); } return false; }) - .reduce((sum, s) => { + .reduce((sum: number, s: TrendSeries) => { const y = s.topic_data[selectedTopic]?.find( - (yd) => yd.year === yearNum, + (yd: TopicYearlyData) => yd.year === yearNum, ); return sum + (y ? y.raw : 0); }, 0); 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 94ac41df..70e0148a 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 @@ -16,6 +16,8 @@ import { UniversityRankingsService } from '../../../api/api/university-rankings. import { InstitutionsService } from '../../../api/api/institutions.service'; import { TrendResponse, + TrendSeries, + TopicYearlyData, TopInstitutionItem, AutocompleteLocationItem, AutocompleteResponse, @@ -89,7 +91,7 @@ export class UniTrendParentComponent implements OnInit { ); const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase(); - const filteredSeries = raw.series.filter((s: any) => { + const filteredSeries = raw.series.filter((s: TrendSeries) => { const id = s.entity_id.toLowerCase(); if (s.entity_type === 'institution') { return id === defaultInstId || currentInstIds.has(id); -- 2.56.1 From f4b8d0884c370828c570e93f9b2e758282c39fc1 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 4 Jul 2026 21:01:49 +0200 Subject: [PATCH 05/13] changed and refactored university-ranking to unify ranking and trend. Removed hardcoded placeholder, Whitelisted fields to reduce response size --- service/src/main/inse/main.py | 2 +- .../src/main/inse/university_ranking/logic.py | 211 +++++++++++++++--- .../src/main/inse/university_ranking/model.py | 4 +- .../main/inse/university_ranking/router.py | 84 ------- .../main/inse/university_ranking/service.py | 84 ++++++- .../inse/university_ranking/trend_logic.py | 26 ++- .../modules/dashboard/dashboard.component.ts | 46 ++-- .../services/uni-ranking-service.ts | 95 -------- .../uni-line-chart.component.html | 6 +- .../uni-line-chart.component.ts | 87 ++++---- .../uni-trend-parent.component.ts | 29 ++- 11 files changed, 376 insertions(+), 298 deletions(-) delete mode 100644 service/src/main/inse/university_ranking/router.py delete mode 100644 webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 54a43096..24969bb8 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -24,7 +24,7 @@ from inse.exceptions import ( ) from inse.funders.service import router as funders_service_router from inse.projects.router import router as projects_router -from inse.university_ranking.router import router as university_ranking_router +from inse.university_ranking.service import router as university_ranking_router # caching from inse.middleware.etag_cache import ETagCacheMiddleware diff --git a/service/src/main/inse/university_ranking/logic.py b/service/src/main/inse/university_ranking/logic.py index 10d926ff..1accf196 100644 --- a/service/src/main/inse/university_ranking/logic.py +++ b/service/src/main/inse/university_ranking/logic.py @@ -1,65 +1,212 @@ import logging +import datetime from typing import List, Dict, Any -from .model import UniversityTopicData, YearlyData, UniversityRanking, ResearchTopic, DashboardMetric, RankingResponse +from .model import UniversityTopicData, YearlyData, UniversityRanking, DashboardMetric, RankingResponse from inse.integrations import elasticsearch +from inse.models.openalex.topic import Topic logger = logging.getLogger(__name__) -START_YEAR = 2015 -END_YEAR = 2026 +START_YEAR = 2000 +END_YEAR = datetime.datetime.now().year - 1 -async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse: +async def resolve_topic(topic_query: str) -> Topic: + """Resolves a topic display name or ID using Elasticsearch with source whitelisting.""" + if topic_query.startswith("http") or "/T" in topic_query: + query = {"term": {"id": topic_query}} + else: + query = {"match_phrase": {"display_name": topic_query}} + + try: + res = await elasticsearch.search( + index="openalex-topics", + query=query, + size=1, + source=["id", "display_name", "description", "works_count", "cited_by_count"], + cluster="nes" + ) + hits = res.get("hits", {}).get("hits", []) + if hits: + return Topic.from_dict(hits[0]["_source"]) + except Exception as e: + logger.warning("Failed to resolve topic in ES: %s", e) + + return Topic(display_name=topic_query) + +async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> RankingResponse: """ Fetches real data from Elasticsearch and computes metrics for the dashboard. """ + topic_obj = await resolve_topic(topic_query) + topic_name = topic_obj.display_name or topic_query + query = { "bool": { - "must": [ - { - "match_phrase": { - "topics.display_name": topic - } - }, - { - "term": { - "geo.country_code": "DE" - } - } - ] + "must": [ + {"term": {"type": "education"}}, + {"term": {"geo.country_code": "DE"}}, + {"match_phrase": {"topics.display_name": topic_name}} + ] } } - - # Fetch top institutions for the topic by works_count res = await elasticsearch.search( index="openalex-institutions", query=query, - size=10, - sort=[{"works_count": "desc"}], + size=50, + source=["id", "display_name", "topics"], cluster="nes" ) hits = res.get("hits", {}).get("hits", []) - timeseries: List[UniversityTopicData] = [] + candidates = [] for hit in hits: source = hit["_source"] - # Map the counts_by_year from ES to our model - # We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0 - es_counts = {c["year"]: c for c in source.get("counts_by_year", [])} + inst_id = source.get("id") + display_name = source.get("display_name", "Unknown") + # Extract topic-specific works count + exact_topic_count = 0 + for t in source.get("topics", []): + if t.get("display_name", "").lower() == topic_name.lower(): + exact_topic_count = t.get("count", 0) + break + + candidates.append({ + "id": inst_id, + "display_name": display_name, + "exact_topic_count": exact_topic_count + }) + + # Sort in Python by exact topic count descending and take the top 10 + candidates.sort(key=lambda x: x["exact_topic_count"], reverse=True) + top_10 = candidates[:10] + + # Initialize timeseries map: inst_id -> year -> (publications, citations) + years_range = list(range(START_YEAR, END_YEAR + 1)) + accumulated_data = { + inst["id"]: {yr: (0, 0) for yr in years_range} + for inst in top_10 + } + + if top_10: + # Build filter map for the single-pass aggregation query + filters_map = {} + for inst in top_10: + inst_id = inst["id"] + filters_map[inst_id] = { + "nested": { + "path": "authorships.institutions", + "query": { + "term": { + "authorships.institutions.id": inst_id + } + } + } + } + + # Topic filter clause (using topic ID if resolved, otherwise matching phrase) + topic_id = topic_obj.id + if topic_id: + topic_clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"term": {"topics.id": topic_id}}}}, + {"term": {"primary_topic.id": topic_id}} + ], + "minimum_should_match": 1 + } + } + else: + topic_clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": topic_name}}}}, + {"match_phrase": {"primary_topic.display_name": topic_name}} + ], + "minimum_should_match": 1 + } + } + + # Construct single-pass ES query on openalex-works + works_query = { + "bool": { + "must": [ + { + "range": { + "publication_year": { + "gte": START_YEAR, + "lte": END_YEAR + } + } + }, + topic_clause + ] + } + } + + aggregations = { + "institutions_agg": { + "filters": { + "filters": filters_map + }, + "aggs": { + "by_year": { + "terms": { + "field": "publication_year", + "size": len(years_range) * 2 + }, + "aggs": { + "citations_sum": { + "sum": { + "field": "cited_by_count" + } + } + } + } + } + } + } + + try: + works_res = await elasticsearch.search( + index="openalex-works*", + query=works_query, + body={"aggs": aggregations}, + size=0, + cluster="nes" + ) + + inst_buckets = works_res.get("aggregations", {}).get("institutions_agg", {}).get("buckets", {}) + for inst_id, inst_bucket in inst_buckets.items(): + year_buckets = inst_bucket.get("by_year", {}).get("buckets", []) + for yr_bucket in year_buckets: + yr = int(yr_bucket.get("key")) + pubs = int(yr_bucket.get("doc_count", 0)) + cits = int(yr_bucket.get("citations_sum", {}).get("value", 0)) + if yr in years_range: + accumulated_data[inst_id][yr] = (pubs, cits) + except Exception as e: + logger.error("Error executing ranking aggregations on openalex-works: %s", e) + + # Map the accumulated results back into the timeseries response model + timeseries: List[UniversityTopicData] = [] + inst_name_map = {inst["id"]: inst["display_name"] for inst in top_10} + + for inst_id, year_dict in accumulated_data.items(): yearly_data = [] - for year in range(START_YEAR, END_YEAR + 1): - count_item = es_counts.get(year, {}) + for yr in years_range: + pubs, cits = year_dict[yr] yearly_data.append(YearlyData( - year=year, - publications=count_item.get("works_count", 0), - citations=count_item.get("cited_by_count", 0) + year=yr, + publications=pubs, + citations=cits )) - + timeseries.append(UniversityTopicData( - university=source.get("display_name", "Unknown"), - topic=topic, + university=inst_name_map[inst_id], + topic=topic_obj, yearly_data=yearly_data )) diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py index 7a4791d7..866b04ad 100644 --- a/service/src/main/inse/university_ranking/model.py +++ b/service/src/main/inse/university_ranking/model.py @@ -1,7 +1,7 @@ from pydantic import BaseModel from typing import List, Literal, Dict, Optional +from inse.models.openalex.topic import Topic -ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology'] DashboardMetric = Literal['publications', 'citations'] class YearlyData(BaseModel): @@ -11,7 +11,7 @@ class YearlyData(BaseModel): class UniversityTopicData(BaseModel): university: str - topic: ResearchTopic + topic: Topic yearly_data: List[YearlyData] class UniversityRanking(BaseModel): diff --git a/service/src/main/inse/university_ranking/router.py b/service/src/main/inse/university_ranking/router.py deleted file mode 100644 index 67c12957..00000000 --- a/service/src/main/inse/university_ranking/router.py +++ /dev/null @@ -1,84 +0,0 @@ -import logging -from typing import List, Optional -from fastapi import APIRouter, Query, Depends, Request - -from inse.tags import Tags -from inse.database import get_session -from inse.auth import service as auth_service -from inse.auth.model import AccessToken, UserRole -from . import service, trend_logic -from .model import ( - RankingResponse, - ResearchTopic, - DashboardMetric, - TrendResponse, - TopInstitutionItem, - AutocompleteLocationItem -) - -logger = logging.getLogger(__name__) - -router = APIRouter( - prefix="/api/inse-service/university-rankings", - tags=[Tags.UNIVERSITY_RANKINGS] -) - -@router.get( - "", - response_model=RankingResponse, - summary="Returns data for the University Ranking Dashboard." -) -async def get_rankings( - topic: ResearchTopic = Query( - ..., - description="Research topic (e.g., 'Artificial Intelligence')" - ), - metric: DashboardMetric = Query("publications", description="Metric to rank by") -): - return await service.get_university_dashboard_data(topic, metric) - -@router.get( - "/trend", - response_model=TrendResponse, - summary="Returns timeseries publication data for compared institutions, countries and regions." -) -async def get_trend( - topics: List[ResearchTopic] = Query(..., description="List of topics to analyze"), - institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"), - countries: Optional[List[str]] = Query(None, description="List of country codes"), - regions: Optional[List[str]] = Query(None, description="List of region identifiers") -): - return await trend_logic.get_trend_data( - topics=topics, - institutions=institutions, - countries=countries, - regions=regions - ) - -@router.get( - "/top-institutions", - response_model=List[TopInstitutionItem], - summary="Returns top institutions filtered by country/region and sorted by topic-level publications count." -) -async def get_top_institutions( - topic: str = Query(..., description="Research topic"), - region: Optional[str] = Query(None, description="Region identifier (e.g. EU)"), - country: Optional[str] = Query(None, description="Country code (e.g. DE)"), - limit: int = Query(10, description="Max suggestions to return") -): - return await trend_logic.get_top_institutions_by_region( - topic=topic, - region=region, - country=country, - limit=limit - ) - -@router.get( - "/autocomplete-locations", - response_model=List[AutocompleteLocationItem], - summary="Returns country and continent options for autocomplete inputs." -) -async def get_autocomplete_locations( - query: str = Query(..., description="Query text to search for countries/continents") -): - return await trend_logic.autocomplete_locations(query) \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py index 4eac89e6..c81ae0ee 100644 --- a/service/src/main/inse/university_ranking/service.py +++ b/service/src/main/inse/university_ranking/service.py @@ -1,6 +1,80 @@ -from . import logic -from .model import RankingResponse, ResearchTopic, DashboardMetric +import logging +from typing import List, Optional +from fastapi import APIRouter, Query -async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse: - """Orchestrates data retrieval and computation for the dashboard.""" - return await logic.get_ranking_data(topic, metric) \ No newline at end of file +from inse.tags import Tags +from . import logic, trend_logic +from .model import ( + RankingResponse, + DashboardMetric, + TrendResponse, + TopInstitutionItem, + AutocompleteLocationItem +) + +logger = logging.getLogger(__name__) + +router = APIRouter( + prefix="/api/inse-service/university-rankings", + tags=[Tags.UNIVERSITY_RANKINGS] +) + +@router.get( + "", + response_model=RankingResponse, + summary="Returns data for the University Ranking Dashboard." +) +async def get_rankings( + topic: str = Query( + ..., + description="Research topic display name or OpenAlex ID (e.g., 'Artificial Intelligence')" + ), + metric: DashboardMetric = Query("publications", description="Metric to rank by") +): + return await logic.get_ranking_data(topic, metric) + +@router.get( + "/trend", + response_model=TrendResponse, + summary="Returns timeseries publication data for compared institutions, countries and regions." +) +async def get_trend( + topics: List[str] = Query(..., description="List of topics to analyze"), + institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"), + countries: Optional[List[str]] = Query(None, description="List of country codes"), + regions: Optional[List[str]] = Query(None, description="List of region identifiers") +): + return await trend_logic.get_trend_data( + topics=topics, + institutions=institutions, + countries=countries, + regions=regions + ) + +@router.get( + "/top-institutions", + response_model=List[TopInstitutionItem], + summary="Returns top institutions filtered by country/region and sorted by topic-level publications count." +) +async def get_top_institutions( + topic: str = Query(..., description="Research topic"), + region: Optional[str] = Query(None, description="Region identifier (e.g. EU)"), + country: Optional[str] = Query(None, description="Country code (e.g. DE)"), + limit: int = Query(10, description="Max suggestions to return") +): + return await trend_logic.get_top_institutions_by_region( + topic=topic, + region=region, + country=country, + limit=limit + ) + +@router.get( + "/autocomplete-locations", + response_model=List[AutocompleteLocationItem], + summary="Returns country and continent options for autocomplete inputs." +) +async def get_autocomplete_locations( + query: str = Query(..., description="Query text to search for countries/continents") +): + return await trend_logic.autocomplete_locations(query) \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index c025bc74..a6a482aa 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -12,7 +12,6 @@ from .model import ( TrendSeries, TopicYearlyData, TopInstitutionItem, - ResearchTopic, AutocompleteLocationItem ) @@ -29,7 +28,7 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: import asyncio - # Query countries index + # Query countries index (Idea: Instead of wildcard: use alternative names?) country_query = { "bool": { "should": [ @@ -66,8 +65,20 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: try: countries_res, continents_res = await asyncio.gather( - elasticsearch.search(index=str(ESIndex.OPENALEX_COUNTRIES), query=country_query, size=10, cluster="nes"), - elasticsearch.search(index=str(ESIndex.OPENALEX_CONTINENTS), query=continent_query, size=5, cluster="nes") + elasticsearch.search( + index=str(ESIndex.OPENALEX_COUNTRIES), + query=country_query, + size=10, + source=["id", "display_name", "country_code", "wikidata_id"], + cluster="nes" + ), + elasticsearch.search( + index=str(ESIndex.OPENALEX_CONTINENTS), + query=continent_query, + size=5, + source=["id", "display_name", "wikidata_id"], + cluster="nes" + ) ) except Exception as e: logger.error("Failed to autocomplete locations in ES: %s", e) @@ -145,6 +156,7 @@ async def get_top_institutions_by_region( index=str(ESIndex.OPENALEX_INSTITUTIONS), query=query, size=50, + source=["id", "display_name", "country_code", "works_count", "image_thumbnail_url", "topics"], sort=[{"works_count": "desc"}], cluster="nes" ) @@ -182,7 +194,7 @@ async def get_top_institutions_by_region( return candidates[:limit] async def get_trend_data( - topics: List[ResearchTopic], + topics: List[str], institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, regions: Optional[List[str]] = None @@ -220,6 +232,7 @@ async def get_trend_data( index=str(ESIndex.OPENALEX_INSTITUTIONS), query={"terms": {"id": ids_to_resolve}}, size=len(ids_to_resolve), + source=["id", "display_name", "country_code"], cluster="nes" ) for hit in name_res.get("hits", {}).get("hits", []): @@ -242,6 +255,7 @@ async def get_trend_data( index=str(ESIndex.OPENALEX_COUNTRIES), query={"terms": {"country_code": clean_countries}}, size=len(clean_countries), + source=["country_code", "display_name"], cluster="nes" ) for hit in c_res.get("hits", {}).get("hits", []): @@ -267,6 +281,7 @@ async def get_trend_data( } }, size=len(clean_regions), + source=["id", "display_name", "wikidata_id", "countries"], cluster="nes" ) for hit in r_res.get("hits", {}).get("hits", []): @@ -297,6 +312,7 @@ async def get_trend_data( } }, size=len(topics) * 2, + source=["id", "display_name"], cluster="nes" ) for hit in topic_res.get("hits", {}).get("hits", []): diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index ef967b09..3906004e 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -1,13 +1,13 @@ -import { Component, OnInit } from '@angular/core'; -import { UniversityRankingService } from '../university-ranking/services/uni-ranking-service'; +import { Component, inject, OnInit } from '@angular/core'; import { UniversityLineChartComponent } from '../university-ranking/uni-line-chart/uni-line-chart.component'; import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component'; -import { UniversityTopicData, UniversityRanking } from '../../api'; -export type ResearchTopic = - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology'; +import { + UniversityTopicData, + UniversityRanking, + UniversityRankingsService, +} from '../../api'; + +export type ResearchTopic = string; export type DashboardMetric = 'publications' | 'citations'; @Component({ @@ -17,11 +17,12 @@ export type DashboardMetric = 'publications' | 'citations'; styleUrl: './dashboard.component.scss', }) export class DashboardComponent implements OnInit { + private readonly dataService = inject(UniversityRankingsService); + topics: ResearchTopic[] = [ - 'Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', - 'Biotechnology', + 'Artificial Intelligence and Decision Support Systems', ]; selectedTopic: ResearchTopic = 'Artificial Intelligence'; metric: DashboardMetric = 'publications'; @@ -30,8 +31,6 @@ export class DashboardComponent implements OnInit { computedRankings: UniversityRanking[] = []; isLoading = false; - constructor(private dataService: UniversityRankingService) {} - ngOnInit() { this.loadData(); } @@ -49,14 +48,21 @@ export class DashboardComponent implements OnInit { private loadData() { this.isLoading = true; this.dataService - .getRankingData(this.selectedTopic, this.metric) - .subscribe((response) => { - // Map backend snake_case properties to frontend camelCase if necessary, - // though OpenAPI Generator usually handles this. - console.log(response); - this.rawDataSource = (response.timeseries as any) || []; - this.computedRankings = (response.rankings as any) || []; - this.isLoading = false; + .getRankingsApiInseServiceUniversityRankingsGet( + this.selectedTopic, + this.metric, + ) + .subscribe({ + next: (response) => { + this.rawDataSource = (response.timeseries as any) || []; + this.computedRankings = (response.rankings as any) || []; + this.isLoading = false; + }, + error: () => { + this.rawDataSource = []; + this.computedRankings = []; + this.isLoading = false; + }, }); } } diff --git a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts b/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts deleted file mode 100644 index 311fc10f..00000000 --- a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts +++ /dev/null @@ -1,95 +0,0 @@ -// src/app/modules/university-ranking/services/university-data.service.ts -import { inject, Injectable } from '@angular/core'; -import { Observable } from 'rxjs'; -import { - InstitutionsService, - UniversityRankingsService, - RankingResponse, - TrendResponse, - TopInstitutionItem, - AutocompleteResponse, - AutocompleteLocationItem, -} from '../../../api'; - -export type ResearchTopic = - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology'; -export type DashboardMetric = 'publications' | 'citations'; - -@Injectable({ providedIn: 'root' }) -export class UniversityRankingService { - private apiService = inject(InstitutionsService); - private rankingsApiService = inject(UniversityRankingsService); - - /** - * Fetches ranking and timeseries data directly from the backend. - * Calculations for growth and trends are now handled server-side. - */ - getRankingData( - topic: ResearchTopic, - metric: DashboardMetric, - ): Observable { - return this.rankingsApiService.getRankingsApiInseServiceUniversityRankingsGet( - topic, - metric, - ); - } - - //trend analysis part - /** - * Fetches the comparative trend analysis data. - */ - getTrend( - topics: string[], - institutions?: string[], - countries?: string[], - regions?: string[], - ): Observable { - return this.rankingsApiService.getTrendApiInseServiceUniversityRankingsTrendGet( - topics as any, - institutions, - countries, - regions, - ); - } - - /** - * Fetches recommendations/suggestions of top institutions based on a specific topic. - */ - getTopInstitutions( - topic: string, - region?: string, - country?: string, - limit?: number, - ): Observable { - return this.rankingsApiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( - topic, - region, - country, - limit, - ); - } - - /** - * Autocompletes institutions based on query text. - */ - autocomplete(query: string): Observable { - return this.apiService.autocompleteInstitutions( - query, - undefined, - 'education', - 10, - ); - } - - /** - * Autocompletes countries and continents. - */ - autocompleteLocations(query: string): Observable { - return this.rankingsApiService.getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( - query, - ); - } -} diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html index 41931384..09ab42d3 100644 --- a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html +++ b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html @@ -1,5 +1 @@ -
+
diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts index 799ad08f..cb123796 100644 --- a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.ts @@ -1,13 +1,13 @@ -// src/app/modules/university-ranking/components/line-chart/university-line-chart.component.ts -import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; +import { + Component, + ChangeDetectionStrategy, + input, + computed, +} from '@angular/core'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; -import { UniversityTopicData, YearlyData } from '../../../api'; -export type ResearchTopic = - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology'; +import { UniversityTopicData } from '../../../api'; + export type DashboardMetric = 'publications' | 'citations'; @Component({ @@ -15,50 +15,55 @@ export type DashboardMetric = 'publications' | 'citations'; templateUrl: './uni-line-chart.component.html', styleUrl: './uni-line-chart.component.scss', imports: [NgxEchartsDirective], - standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, }) -export class UniversityLineChartComponent implements OnChanges { - @Input() data: UniversityTopicData[] = []; - @Input() metric: DashboardMetric = 'publications'; +export class UniversityLineChartComponent { + readonly data = input(null); + readonly metric = input('publications'); - chartOption: EChartsOption = { - title: { - text: 'Research Output Over Time', - left: 'center', - textStyle: { fontWeight: 'lighter' }, - }, - tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, - legend: { bottom: 0 }, - grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }, - xAxis: { type: 'category', boundaryGap: false, data: [] }, - yAxis: { type: 'value', name: 'Volume' }, - dataZoom: [{ type: 'slider', show: true, bottom: 40 }], - series: [], - }; - - mergeOption: EChartsOption = {}; - - ngOnChanges(changes: SimpleChanges): void { - if (this.data.length > 0) { - this.updateChart(); - console.log('CHANGES!'); + readonly chartOption = computed(() => { + const rawData = this.data(); + if (!rawData || rawData.length === 0) { + return {}; } - } - private updateChart() { - const years = this.data[0].yearly_data.map((d) => d.year); - const series = this.data.map((uni) => ({ + const years = rawData[0].yearly_data.map((d) => d.year); + const chosenMetric = this.metric(); + + const series = rawData.map((uni) => ({ name: uni.university, type: 'line', smooth: true, emphasis: { focus: 'series' }, animationDuration: 2000, - data: uni.yearly_data.map((d) => d[this.metric]), + data: uni.yearly_data.map((d) => { + if (chosenMetric === 'citations') { + return d.citations || 0; + } + return d.publications || 0; + }), })); - this.mergeOption = { - xAxis: { data: years.map(String) }, + return { + title: { + text: 'Research Output Over Time', + left: 'center', + textStyle: { fontWeight: 'lighter' }, + }, + tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, + legend: { bottom: 0 }, + grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }, + xAxis: { + type: 'category', + boundaryGap: false, + data: years.map(String), + }, + yAxis: { + type: 'value', + name: chosenMetric === 'citations' ? 'Citations' : 'Publications', + }, + dataZoom: [{ type: 'slider', show: true, bottom: 40 }], series: series as any, }; - } + }); } 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 70e0148a..ae695357 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 @@ -5,6 +5,7 @@ import { computed, signal, effect, + untracked, inject, OnInit, } from '@angular/core'; @@ -12,8 +13,6 @@ import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component'; -import { UniversityRankingsService } from '../../../api/api/university-rankings.service'; -import { InstitutionsService } from '../../../api/api/institutions.service'; import { TrendResponse, TrendSeries, @@ -21,6 +20,8 @@ import { TopInstitutionItem, AutocompleteLocationItem, AutocompleteResponse, + UniversityRankingsService, + InstitutionsService, } from '../../../api'; @Component({ @@ -96,9 +97,17 @@ export class UniTrendParentComponent implements OnInit { if (s.entity_type === 'institution') { return id === defaultInstId || currentInstIds.has(id); } else if (s.entity_type === 'country') { - return currentCountryIds.has(id); + return ( + currentCountryIds.has(id) || + currentCountryIds.has('https://openalex.org/countries/' + id) || + Array.from(currentCountryIds).some((cid) => cid.endsWith('/' + id)) + ); } else if (s.entity_type === 'region') { - return currentRegionIds.has(id); + return ( + currentRegionIds.has(id) || + currentRegionIds.has('https://openalex.org/continents/' + id) || + Array.from(currentRegionIds).some((rid) => rid.endsWith('/' + id)) + ); } return false; }); @@ -159,9 +168,12 @@ export class UniTrendParentComponent implements OnInit { effect( () => { const kws = this.keywords(); + const currentSelections = untracked(() => this.selectedTrendTopics()); + const currentActive = untracked(() => this.activeChartTopic()); + if (kws.length > 0) { // Find existing selections that are still in keywords, or default to all - const validSelections = this.selectedTrendTopics().filter((t) => + const validSelections = currentSelections.filter((t) => kws.includes(t), ); if (validSelections.length > 0) { @@ -171,9 +183,10 @@ export class UniTrendParentComponent implements OnInit { } // Initialize active chart topic to the first selected topic if empty or invalid - const active = this.activeChartTopic(); - if (!active || !this.selectedTrendTopics().includes(active)) { - this.activeChartTopic.set(this.selectedTrendTopics()[0] || ''); + const active = currentActive; + const updatedSelections = untracked(() => this.selectedTrendTopics()); + if (!active || !updatedSelections.includes(active)) { + this.activeChartTopic.set(updatedSelections[0] || ''); } } else { this.selectedTrendTopics.set([]); -- 2.56.1 From 261f97eee0276943151cca9906bcbfec34b2d5b1 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 4 Jul 2026 21:04:48 +0200 Subject: [PATCH 06/13] regenerated frontend with openapi generator gradle service --- webapp/src/app/api/.openapi-generator/FILES | 6 + webapp/src/app/api/api/api.ts | 6 +- .../src/app/api/api/institutions.service.ts | 911 +++++++++++------- ...rvice.ts => universityRankings.service.ts} | 454 ++++++--- .../app/api/model/autocompleteLocationItem.ts | 19 +- webapp/src/app/api/model/models.ts | 8 +- .../src/app/api/model/topInstitutionItem.ts | 18 +- webapp/src/app/api/model/topicYearlyData.ts | 16 + webapp/src/app/api/model/trendResponse.ts | 24 +- webapp/src/app/api/model/trendSeries.ts | 27 + .../src/app/api/model/universityTopicData.ts | 23 +- 11 files changed, 1025 insertions(+), 487 deletions(-) rename webapp/src/app/api/api/{university-rankings.service.ts => universityRankings.service.ts} (54%) create mode 100644 webapp/src/app/api/model/topicYearlyData.ts create mode 100644 webapp/src/app/api/model/trendSeries.ts diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 99b72add..28dbd8c3 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -17,6 +17,7 @@ api/personNetwork.service.ts api/persons.service.ts api/projects.service.ts api/topics.service.ts +api/universityRankings.service.ts api/works.service.ts configuration.ts encoder.ts @@ -38,6 +39,7 @@ model/authorSummaryStats.ts model/authorsFilterProperties.ts model/authorsListResponse.ts model/authorship.ts +model/autocompleteLocationItem.ts model/autocompleteResponse.ts model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts @@ -164,16 +166,20 @@ model/refreshToken.ts model/score.ts model/sortDirection.ts model/tokenType.ts +model/topInstitutionItem.ts model/topic.ts model/topicCount.ts model/topicDomain.ts model/topicField.ts model/topicIds.ts model/topicSubfield.ts +model/topicYearlyData.ts model/topics.ts model/topicsByTime.ts model/topicsByYear.ts model/topicsListResponse.ts +model/trendResponse.ts +model/trendSeries.ts model/universityRanking.ts model/universityTopicData.ts model/updateAccountRequest.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 6a70a903..673b93bb 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -24,10 +24,10 @@ export * from './projects.service'; import { ProjectsService } from './projects.service'; export * from './topics.service'; import { TopicsService } from './topics.service'; +export * from './universityRankings.service'; +import { UniversityRankingsService } from './universityRankings.service'; export * from './works.service'; import { WorksService } from './works.service'; -export * from './university-rankings.service'; -import { UniversityRankingsService } from './university-rankings.service'; export const APIS = [ AuthService, CompanyConnectionsService, @@ -42,6 +42,6 @@ export const APIS = [ PersonsService, ProjectsService, TopicsService, - WorksService, UniversityRankingsService, + WorksService, ]; diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts index a4ba3d62..b837e00e 100644 --- a/webapp/src/app/api/api/institutions.service.ts +++ b/webapp/src/app/api/api/institutions.service.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -9,12 +9,18 @@ */ /* tslint:disable:no-unused-variable member-ordering */ -import { Inject, Injectable, Optional } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams, - HttpResponse, HttpEvent, HttpParameterCodec, HttpContext - } from '@angular/common/http'; -import { CustomHttpParameterCodec } from '../encoder'; -import { Observable } from 'rxjs'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; // @ts-ignore import { AutocompleteResponse } from '../model/autocompleteResponse'; @@ -26,362 +32,593 @@ import { Institution } from '../model/institution'; import { InstitutionPage } from '../model/institutionPage'; // @ts-ignore import { InstitutionsListResponse } from '../model/institutionsListResponse'; -// @ts-ignore -import { RankingResponse } from '../model/rankingResponse'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; -import { Configuration } from '../configuration'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; import { BaseService } from '../api.base.service'; - - @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class InstitutionsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } - constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { - super(basePath, configuration); + /** + * Returns institution options for autocomplete inputs. + * @endpoint get /api/inse-service/institutions/autocomplete + * @param query Institution search text, for example \'Duisburg Essen\'. + * @param countryCode Optional ISO country code filter. + * @param type Optional institution type filter. + * @param limit Maximum number of autocomplete options. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public autocompleteInstitutions( + query: string, + countryCode?: string, + type?: string, + limit?: number, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public autocompleteInstitutions( + query: string, + countryCode?: string, + type?: string, + limit?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public autocompleteInstitutions( + query: string, + countryCode?: string, + type?: string, + limit?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public autocompleteInstitutions( + query: string, + countryCode?: string, + type?: string, + limit?: number, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling autocompleteInstitutions.', + ); } - /** - * Returns institution options for autocomplete inputs. - * @endpoint get /api/inse-service/institutions/autocomplete - * @param query Institution search text, for example \'Duisburg Essen\'. - * @param countryCode Optional ISO country code filter. - * @param type Optional institution type filter. - * @param limit Maximum number of autocomplete options. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (query === null || query === undefined) { - throw new Error('Required parameter query was null or undefined when calling autocompleteInstitutions.'); - } + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + countryCode, + 'countryCode', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + type, + 'type', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - query, 'query'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - countryCode, 'countryCode'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - type, 'type'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - limit, 'limit'); + let localVarHeaders = this.defaultHeaders; - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/institutions/autocomplete`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Returns a single institution by ID. - * Returns a single institution by its OpenAlex ID. - * @endpoint get /api/inse-service/institutions/{id} - * @param id - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getInstitutionById(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getInstitutionById(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getInstitutionById(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getInstitutionById(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (id === null || id === undefined) { - throw new Error('Required parameter id was null or undefined when calling getInstitutionById.'); - } + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarHeaders = this.defaultHeaders; + const localVarTransferCache: boolean = options?.transferCache ?? true; - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - /** - * Returns data for the University Ranking Dashboard. - * @endpoint get /api/inse-service/university-rankings - * @param topic Research topic (e.g., \'Artificial Intelligence\') - * @param metric Metric to rank by - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { - if (topic === null || topic === undefined) { - throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.'); - } + let localVarPath = `/api/inse-service/institutions/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - topic, 'topic'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - metric, 'metric'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/university-rankings`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + /** + * Returns a single institution by ID. + * Returns a single institution by its OpenAlex ID. + * @endpoint get /api/inse-service/institutions/{id} + * @param id + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInstitutionById( + id: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getInstitutionById( + id: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getInstitutionById( + id: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getInstitutionById( + id: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (id === null || id === undefined) { + throw new Error( + 'Required parameter id was null or undefined when calling getInstitutionById.', + ); } - /** - * Returns a list of OpenAlex institutions. - * @endpoint get /api/inse-service/institutions - * @param search Full-text search, for example \'Duisburg Essen\'. - * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. - * @param sort Sort field, for example \'works_count:desc\'. - * @param groupBy OpenAlex group_by field, for example \'country_code\'. - * @param perPage Results per page. - * @param page Page number. Use cursor for deep pagination. - * @param cursor Cursor pagination token. Use \'*\' to start. - * @param sample Random sample size. Cannot be combined with sort or page. - * @param select Comma-separated fields to return. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + let localVarHeaders = this.defaultHeaders; - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - search, 'search'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - filter, 'filter'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sort, 'sort'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - groupBy, 'group_by'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - perPage, 'per_page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - cursor, 'cursor'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sample, 'sample'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - select, 'select'); - - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/institutions`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); } - /** - * Searches for institutions by name. - * Searches for institutions by name with pagination. - * @endpoint get /api/inse-service/institutions/search - * @param name Institution name to search for, for example \'University of Duisburg Essen\'. - * @param page Page number (0-indexed). - * @param size Number of institutions per page. - * @param sortBy Field to sort by, either \'relevance\', \'name\', \'works_count\', or \'citations_count\'. - * @param sortingDirection Sorting direction, either \'asc\' or \'desc\'. - * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress. - */ - public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); - let localVarQueryParameters = new HttpParams({encoder: this.encoder}); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - name, 'name'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - page, 'page'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - size, 'size'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortBy, 'sort_by'); - localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - sortingDirection, 'sorting_direction'); + const localVarTransferCache: boolean = options?.transferCache ?? true; - let localVarHeaders = this.defaultHeaders; - - const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ - 'application/json' - ]); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); - } - - const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - - const localVarTransferCache: boolean = options?.transferCache ?? true; - - - let responseType_: 'text' | 'json' | 'blob' = 'json'; - if (localVarHttpHeaderAcceptSelected) { - if (localVarHttpHeaderAcceptSelected.startsWith('text')) { - responseType_ = 'text'; - } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { - responseType_ = 'json'; - } else { - responseType_ = 'blob'; - } - } - - let localVarPath = `/api/inse-service/institutions/search`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), - reportProgress: reportProgress - } - ); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } + let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns a list of OpenAlex institutions. + * @endpoint get /api/inse-service/institutions + * @param search Full-text search, for example \'Duisburg Essen\'. + * @param filter OpenAlex filter, for example \'country_code:DE,type:education\'. + * @param sort Sort field, for example \'works_count:desc\'. + * @param groupBy OpenAlex group_by field, for example \'country_code\'. + * @param perPage Results per page. + * @param page Page number. Use cursor for deep pagination. + * @param cursor Cursor pagination token. Use \'*\' to start. + * @param sample Random sample size. Cannot be combined with sort or page. + * @param select Comma-separated fields to return. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public listInstitutions( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public listInstitutions( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listInstitutions( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public listInstitutions( + search?: string, + filter?: string, + sort?: string, + groupBy?: string, + perPage?: number, + page?: number, + cursor?: string, + sample?: number, + select?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + search, + 'search', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + filter, + 'filter', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sort, + 'sort', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + groupBy, + 'group_by', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + perPage, + 'per_page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + cursor, + 'cursor', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sample, + 'sample', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + select, + 'select', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Searches for institutions by name. + * Searches for institutions by name with pagination. + * @endpoint get /api/inse-service/institutions/search + * @param name Institution name to search for, for example \'University of Duisburg Essen\'. + * @param page Page number (0-indexed). + * @param size Number of institutions per page. + * @param sortBy Field to sort by, either \'relevance\', \'name\', \'works_count\', or \'citations_count\'. + * @param sortingDirection Sorting direction, either \'asc\' or \'desc\'. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public searchInstitutionsByName( + name?: string, + page?: number, + size?: number, + sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', + sortingDirection?: 'asc' | 'desc', + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public searchInstitutionsByName( + name?: string, + page?: number, + size?: number, + sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', + sortingDirection?: 'asc' | 'desc', + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchInstitutionsByName( + name?: string, + page?: number, + size?: number, + sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', + sortingDirection?: 'asc' | 'desc', + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public searchInstitutionsByName( + name?: string, + page?: number, + size?: number, + sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', + sortingDirection?: 'asc' | 'desc', + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + name, + 'name', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + page, + 'page', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + size, + 'size', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortBy, + 'sort_by', + ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + sortingDirection, + 'sorting_direction', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/institutions/search`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/api/university-rankings.service.ts b/webapp/src/app/api/api/universityRankings.service.ts similarity index 54% rename from webapp/src/app/api/api/university-rankings.service.ts rename to webapp/src/app/api/api/universityRankings.service.ts index f88965d8..4ed6111d 100644 --- a/webapp/src/app/api/api/university-rankings.service.ts +++ b/webapp/src/app/api/api/universityRankings.service.ts @@ -1,7 +1,11 @@ /** * Innovation Search Engine API * - * NOTE: This class is manually implemented to act as if it were auto-generated by OpenAPI Generator. + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. */ /* tslint:disable:no-unused-variable member-ordering */ @@ -19,13 +23,15 @@ import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore -import { RankingResponse } from '../model/rankingResponse'; +import { AutocompleteLocationItem } from '../model/autocompleteLocationItem'; // @ts-ignore -import { TrendResponse } from '../model/trendResponse'; +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { RankingResponse } from '../model/rankingResponse'; // @ts-ignore import { TopInstitutionItem } from '../model/topInstitutionItem'; // @ts-ignore -import { AutocompleteLocationItem } from '../model/autocompleteLocationItem'; +import { TrendResponse } from '../model/trendResponse'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -44,12 +50,159 @@ export class UniversityRankingsService extends BaseService { super(basePath, configuration); } + /** + * Returns country and continent options for autocomplete inputs. + * @endpoint get /api/inse-service/university-rankings/autocomplete-locations + * @param query Query text to search for countries/continents + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( + query: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (query === null || query === undefined) { + throw new Error( + 'Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + query, + 'query', + ); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/university-rankings/autocomplete-locations`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Returns data for the University Ranking Dashboard. + * @endpoint get /api/inse-service/university-rankings + * @param topic Research topic display name or OpenAlex ID (e.g., \'Artificial Intelligence\') + * @param metric Metric to rank by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ public getRankingsApiInseServiceUniversityRankingsGet( - topic: - | 'Artificial Intelligence' - | 'Quantum Computing' - | 'Renewable Energy' - | 'Biotechnology', + topic: string, + metric?: 'publications' | 'citations', + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: string, + metric?: 'publications' | 'citations', + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: string, + metric?: 'publications' | 'citations', + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getRankingsApiInseServiceUniversityRankingsGet( + topic: string, metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, @@ -78,6 +231,7 @@ export class UniversityRankingsService extends BaseService { ); let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept(['application/json']); @@ -90,8 +244,21 @@ export class UniversityRankingsService extends BaseService { const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } let localVarPath = `/api/inse-service/university-rankings`; const { basePath, withCredentials } = this.configuration; @@ -113,99 +280,55 @@ export class UniversityRankingsService extends BaseService { ); } - public getTrendApiInseServiceUniversityRankingsTrendGet( - topics: string[], - institutions?: string[], - countries?: string[], - regions?: string[], - observe: any = 'body', - reportProgress: boolean = false, + /** + * Returns top institutions filtered by country/region and sorted by topic-level publications count. + * @endpoint get /api/inse-service/university-rankings/top-institutions + * @param topic Research topic + * @param region Region identifier (e.g. EU) + * @param country Country code (e.g. DE) + * @param limit Max suggestions to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic: string, + region?: string, + country?: string, + limit?: number, + observe?: 'body', + reportProgress?: boolean, options?: { httpHeaderAccept?: 'application/json'; context?: HttpContext; transferCache?: boolean; }, - ): Observable { - if (topics === null || topics === undefined) { - throw new Error( - 'Required parameter topics was null or undefined when calling getTrendApiInseServiceUniversityRankingsTrendGet.', - ); - } - - let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - if (topics) { - topics.forEach((val) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - val, - 'topics', - ); - }); - } - if (institutions) { - institutions.forEach((val) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - val, - 'institutions', - ); - }); - } - if (countries) { - countries.forEach((val) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - val, - 'countries', - ); - }); - } - if (regions) { - regions.forEach((val) => { - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - val, - 'regions', - ); - }); - } - - let localVarHeaders = this.defaultHeaders; - const localVarHttpHeaderAcceptSelected: string | undefined = - options?.httpHeaderAccept ?? - this.configuration.selectHeaderAccept(['application/json']); - if (localVarHttpHeaderAcceptSelected !== undefined) { - localVarHeaders = localVarHeaders.set( - 'Accept', - localVarHttpHeaderAcceptSelected, - ); - } - - const localVarHttpContext: HttpContext = - options?.context ?? new HttpContext(); - const localVarTransferCache: boolean = options?.transferCache ?? true; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - - let localVarPath = `/api/inse-service/university-rankings/trend`; - const { basePath, withCredentials } = this.configuration; - return this.httpClient.request( - 'get', - `${basePath}${localVarPath}`, - { - context: localVarHttpContext, - params: localVarQueryParameters, - responseType: responseType_, - ...(withCredentials ? { withCredentials } : {}), - headers: localVarHeaders, - observe: observe, - ...(localVarTransferCache !== undefined - ? { transferCache: localVarTransferCache } - : {}), - reportProgress: reportProgress, - }, - ); - } - + ): Observable>; + public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic: string, + region?: string, + country?: string, + limit?: number, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic: string, + region?: string, + country?: string, + limit?: number, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( topic: string, region?: string, @@ -248,6 +371,7 @@ export class UniversityRankingsService extends BaseService { ); let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept(['application/json']); @@ -260,8 +384,21 @@ export class UniversityRankingsService extends BaseService { const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + const localVarTransferCache: boolean = options?.transferCache ?? true; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } let localVarPath = `/api/inse-service/university-rankings/top-institutions`; const { basePath, withCredentials } = this.configuration; @@ -283,8 +420,60 @@ export class UniversityRankingsService extends BaseService { ); } - public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet( - query: string, + /** + * Returns timeseries publication data for compared institutions, countries and regions. + * @endpoint get /api/inse-service/university-rankings/trend + * @param topics List of topics to analyze + * @param institutions List of OpenAlex Institution IDs + * @param countries List of country codes + * @param regions List of region identifiers + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getTrendApiInseServiceUniversityRankingsTrendGet( + topics: Array, + institutions?: Array, + countries?: Array, + regions?: Array, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getTrendApiInseServiceUniversityRankingsTrendGet( + topics: Array, + institutions?: Array, + countries?: Array, + regions?: Array, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTrendApiInseServiceUniversityRankingsTrendGet( + topics: Array, + institutions?: Array, + countries?: Array, + regions?: Array, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getTrendApiInseServiceUniversityRankingsTrendGet( + topics: Array, + institutions?: Array, + countries?: Array, + regions?: Array, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -293,20 +482,52 @@ export class UniversityRankingsService extends BaseService { transferCache?: boolean; }, ): Observable { - if (query === null || query === undefined) { + if (topics === null || topics === undefined) { throw new Error( - 'Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.', + 'Required parameter topics was null or undefined when calling getTrendApiInseServiceUniversityRankingsTrendGet.', ); } let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - query, - 'query', - ); + if (topics) { + topics.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'topics', + ); + }); + } + if (institutions) { + institutions.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'institutions', + ); + }); + } + if (countries) { + countries.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'countries', + ); + }); + } + if (regions) { + regions.forEach((element) => { + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + element, + 'regions', + ); + }); + } let localVarHeaders = this.defaultHeaders; + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept(['application/json']); @@ -319,12 +540,25 @@ export class UniversityRankingsService extends BaseService { const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); - const localVarTransferCache: boolean = options?.transferCache ?? true; - let responseType_: 'text' | 'json' | 'blob' = 'json'; - let localVarPath = `/api/inse-service/university-rankings/autocomplete-locations`; + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/inse-service/university-rankings/trend`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request>( + return this.httpClient.request( 'get', `${basePath}${localVarPath}`, { diff --git a/webapp/src/app/api/model/autocompleteLocationItem.ts b/webapp/src/app/api/model/autocompleteLocationItem.ts index c3fe1cdd..b07e699e 100644 --- a/webapp/src/app/api/model/autocompleteLocationItem.ts +++ b/webapp/src/app/api/model/autocompleteLocationItem.ts @@ -1,6 +1,23 @@ +/** + * 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 AutocompleteLocationItem { id: string; display_name: string; code: string; - type: 'country' | 'continent'; + type: AutocompleteLocationItem.TypeEnum; +} +export namespace AutocompleteLocationItem { + export const TypeEnum = { + Country: 'country', + Continent: 'continent', + } as const; + export type TypeEnum = (typeof TypeEnum)[keyof typeof TypeEnum]; } diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index edd20e54..2077ece1 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -14,6 +14,7 @@ export * from './authorSummaryStats'; export * from './authorsFilterProperties'; export * from './authorsListResponse'; export * from './authorship'; +export * from './autocompleteLocationItem'; export * from './autocompleteResponse'; export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; @@ -139,16 +140,20 @@ export * from './refreshToken'; export * from './score'; export * from './sortDirection'; export * from './tokenType'; +export * from './topInstitutionItem'; export * from './topic'; export * from './topicCount'; export * from './topicDomain'; export * from './topicField'; export * from './topicIds'; export * from './topicSubfield'; +export * from './topicYearlyData'; export * from './topics'; export * from './topicsByTime'; export * from './topicsByYear'; export * from './topicsListResponse'; +export * from './trendResponse'; +export * from './trendSeries'; export * from './universityRanking'; export * from './universityTopicData'; export * from './updateAccountRequest'; @@ -177,6 +182,3 @@ export * from './workTopicSubfield'; export * from './worksFilterProperties'; export * from './worksListResponse'; export * from './yearlyData'; -export * from './trendResponse'; -export * from './topInstitutionItem'; -export * from './autocompleteLocationItem'; diff --git a/webapp/src/app/api/model/topInstitutionItem.ts b/webapp/src/app/api/model/topInstitutionItem.ts index 8f1c6489..827fe6df 100644 --- a/webapp/src/app/api/model/topInstitutionItem.ts +++ b/webapp/src/app/api/model/topInstitutionItem.ts @@ -1,6 +1,20 @@ -import { DehydratedInstitution } from './dehydratedInstitution'; +/** + * 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 TopInstitutionItem extends DehydratedInstitution { +export interface TopInstitutionItem { + id?: string | null; + display_name?: string | null; + ror?: string | null; + country_code?: string | null; + type?: string | null; + lineage?: Array | null; works_count?: number | null; image_thumbnail_url?: string | null; exact_topic_count?: number | null; diff --git a/webapp/src/app/api/model/topicYearlyData.ts b/webapp/src/app/api/model/topicYearlyData.ts new file mode 100644 index 00000000..15e4c59a --- /dev/null +++ b/webapp/src/app/api/model/topicYearlyData.ts @@ -0,0 +1,16 @@ +/** + * 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 TopicYearlyData { + year: number; + raw: number; + normalized: number; + institutions_count: number; +} diff --git a/webapp/src/app/api/model/trendResponse.ts b/webapp/src/app/api/model/trendResponse.ts index 7f5589f9..e6b291c9 100644 --- a/webapp/src/app/api/model/trendResponse.ts +++ b/webapp/src/app/api/model/trendResponse.ts @@ -1,17 +1,13 @@ -export interface TopicYearlyData { - year: number; - raw: number; - normalized: number; - institutions_count: number; -} - -export interface TrendSeries { - entity_id: string; - entity_name: string; - entity_type: 'institution' | 'country' | 'region'; - country_code?: string | null; - topic_data: { [key: string]: Array }; -} +/** + * 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. + */ +import { TrendSeries } from './trendSeries'; export interface TrendResponse { series: Array; diff --git a/webapp/src/app/api/model/trendSeries.ts b/webapp/src/app/api/model/trendSeries.ts new file mode 100644 index 00000000..1dc054be --- /dev/null +++ b/webapp/src/app/api/model/trendSeries.ts @@ -0,0 +1,27 @@ +/** + * 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. + */ +import { TopicYearlyData } from './topicYearlyData'; + +export interface TrendSeries { + entity_id: string; + entity_name: string; + entity_type: TrendSeries.EntityTypeEnum; + country_code?: string | null; + topic_data: { [key: string]: Array }; +} +export namespace TrendSeries { + export const EntityTypeEnum = { + Institution: 'institution', + Country: 'country', + Region: 'region', + } as const; + export type EntityTypeEnum = + (typeof EntityTypeEnum)[keyof typeof EntityTypeEnum]; +} diff --git a/webapp/src/app/api/model/universityTopicData.ts b/webapp/src/app/api/model/universityTopicData.ts index fc517b7c..3bf43088 100644 --- a/webapp/src/app/api/model/universityTopicData.ts +++ b/webapp/src/app/api/model/universityTopicData.ts @@ -1,28 +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. */ import { YearlyData } from './yearlyData'; +import { Topic } from './topic'; - -export interface UniversityTopicData { - university: string; - topic: UniversityTopicData.TopicEnum; - yearly_data: Array; +export interface UniversityTopicData { + university: string; + topic: Topic; + yearly_data: Array; } -export namespace UniversityTopicData { - export const TopicEnum = { - ArtificialIntelligence: 'Artificial Intelligence', - QuantumComputing: 'Quantum Computing', - RenewableEnergy: 'Renewable Energy', - Biotechnology: 'Biotechnology' - } as const; - export type TopicEnum = typeof TopicEnum[keyof typeof TopicEnum]; -} - - -- 2.56.1 From 2703f465751410e2a0388ee44871f3f738bcb298 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 4 Jul 2026 23:12:03 +0200 Subject: [PATCH 07/13] Implemented scikit normalize batch, fixed blocking elastic search query, changed frontend to resize dynamically, fixed bug in dashboard --- .../src/main/inse/university_ranking/model.py | 2 +- .../inse/university_ranking/trend_logic.py | 176 +++++++++---- .../dashboard/dashboard.component.html | 4 +- .../modules/dashboard/dashboard.component.ts | 2 +- .../uni-line-chart.component.html | 6 +- .../uni-trend-chart.component.html | 6 +- .../uni-trend-chart.component.ts | 232 ++++++------------ 7 files changed, 222 insertions(+), 206 deletions(-) diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py index 866b04ad..18a2fb32 100644 --- a/service/src/main/inse/university_ranking/model.py +++ b/service/src/main/inse/university_ranking/model.py @@ -34,6 +34,7 @@ class TopicYearlyData(BaseModel): year: int raw: int normalized: float + cumulative: float institutions_count: int class TrendSeries(BaseModel): @@ -53,7 +54,6 @@ from inse.models.openalex.dehydrated_institution import DehydratedInstitution class TopInstitutionItem(DehydratedInstitution): works_count: Optional[int] = None - image_thumbnail_url: Optional[str] = None exact_topic_count: Optional[int] = None class AutocompleteLocationItem(BaseModel): diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index a6a482aa..6cf70e13 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -2,6 +2,8 @@ import logging import uuid import datetime from typing import List, Dict, Any, Optional +import numpy as np +from sklearn.preprocessing import MinMaxScaler from sqlmodel import Session from inse.integrations import elasticsearch @@ -89,10 +91,11 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: # Process continents for hit in continents_res.get("hits", {}).get("hits", []): source = hit["_source"] + code_val = source.get("wikidata_id") or source["id"].split("/")[-1] results.append(AutocompleteLocationItem( - id=source["id"], + id=code_val, display_name=source["display_name"], - code=source.get("wikidata_id") or source["id"].split("/")[-1], + code=code_val, type="continent" )) @@ -100,7 +103,7 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: for hit in countries_res.get("hits", {}).get("hits", []): source = hit["_source"] results.append(AutocompleteLocationItem( - id=source["id"], + id=source["country_code"], display_name=source["display_name"], code=source["country_code"], type="country" @@ -109,20 +112,6 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: return results -def clean_institution_id(inst_id: str) -> str: - inst_id = inst_id.strip() - if not inst_id.startswith("http"): - return f"https://openalex.org/{inst_id}" - return inst_id - -def min_max_normalize(values: List[int]) -> List[float]: - if not values: - return [] - min_val = min(values) - max_val = max(values) - if max_val == min_val: - return [0.0] * len(values) - return [float(v - min_val) / (max_val - min_val) for v in values] async def get_top_institutions_by_region( topic: str, @@ -156,7 +145,7 @@ async def get_top_institutions_by_region( index=str(ESIndex.OPENALEX_INSTITUTIONS), query=query, size=50, - source=["id", "display_name", "country_code", "works_count", "image_thumbnail_url", "topics"], + source=["id", "display_name", "country_code", "works_count", "topics"], sort=[{"works_count": "desc"}], cluster="nes" ) @@ -170,7 +159,6 @@ async def get_top_institutions_by_region( display_name = source.get("display_name", "Unknown") country_code = source.get("country_code") works_count = source.get("works_count") - image_thumbnail_url = source.get("image_thumbnail_url") # Extract exact count for the selected topic exact_topic_count = 0 @@ -184,7 +172,6 @@ async def get_top_institutions_by_region( display_name=display_name, country_code=country_code, works_count=works_count, - image_thumbnail_url=image_thumbnail_url, exact_topic_count=exact_topic_count )) @@ -217,7 +204,7 @@ async def get_trend_data( # Initialize institutions list and ensure primary is included query_institutions = [] if institutions: - query_institutions = [clean_institution_id(i) for i in institutions] + query_institutions = [i.strip() for i in institutions] if primary_inst_id not in query_institutions: query_institutions.insert(0, primary_inst_id) @@ -399,25 +386,73 @@ async def get_trend_data( topic_clauses.append(clause) topic_filters[t] = clause - # Construct the single-pass Elasticsearch query - query = { - "bool": { - "must": [ - { - "range": { - "publication_year": { - "gte": start_year, - "lte": end_year - } - } - }, - { - "bool": { - "should": topic_clauses, - "minimum_should_match": 1 + # Build query-level entity filters to optimize search performance + entity_should_clauses = [] + if query_institutions: + entity_should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": query_institutions } } - ] + } + }) + if clean_countries: + entity_should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.country_code": clean_countries + } + } + } + }) + all_continent_countries = [] + for member_ccs in continent_country_codes.values(): + all_continent_countries.extend(member_ccs) + if all_continent_countries: + entity_should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.country_code": list(set(all_continent_countries)) + } + } + } + }) + + # Construct the single-pass Elasticsearch query + must_clauses = [ + { + "range": { + "publication_year": { + "gte": start_year, + "lte": end_year + } + } + }, + { + "bool": { + "should": topic_clauses, + "minimum_should_match": 1 + } + } + ] + if entity_should_clauses: + must_clauses.append({ + "bool": { + "should": entity_should_clauses, + "minimum_should_match": 1 + } + }) + + query = { + "bool": { + "must": must_clauses } } @@ -469,6 +504,51 @@ async def get_trend_data( except Exception as e: logger.error("Error executing single-pass Elasticsearch query: %s", e) + # Construct lists of raw counts and S-Curves for all series to normalize in parallel + series_keys = [] + raw_lists = [] + cumsum_lists = [] + inst_counts_map = {} + + for entity_key, topic_dict in accumulated_data.items(): + for topic, year_dict in topic_dict.items(): + raw_counts = [] + inst_counts = [] + for yr in years_range: + count, inst_count = year_dict[yr] + raw_counts.append(count) + inst_counts.append(inst_count) + + cumulative_counts = list(np.cumsum(raw_counts)) + + series_keys.append((entity_key, topic)) + raw_lists.append(raw_counts) + cumsum_lists.append(cumulative_counts) + inst_counts_map[(entity_key, topic)] = inst_counts + + normalized_lookup = {} + if raw_lists: + # Construct matrices of shape (n_years, n_series) + raw_matrix = np.array(raw_lists, dtype=float).T + cumsum_matrix = np.array(cumsum_lists, dtype=float).T + + # Batch normalize columns in parallel using MinMaxScaler + scaler_raw = MinMaxScaler() + normalized_matrix = scaler_raw.fit_transform(raw_matrix) + + scaler_cumsum = MinMaxScaler() + normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix) + + # Transpose back to lists of shape (n_series, n_years) + normalized_lists = normalized_matrix.T.tolist() + normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist() + + for idx, (entity_key, topic) in enumerate(series_keys): + normalized_lookup[(entity_key, topic)] = { + "normalized": normalized_lists[idx], + "cumulative": normalized_cumsum_lists[idx] + } + # Process and build TrendSeries list series_list: List[TrendSeries] = [] @@ -494,22 +574,18 @@ async def get_trend_data( for topic, year_dict in topic_dict.items(): yearly_data_items: List[TopicYearlyData] = [] - # Extract raw counts and institution counts in sorted year order - raw_counts = [] - inst_counts = [] - for yr in years_range: - count, inst_count = year_dict[yr] - raw_counts.append(count) - inst_counts.append(inst_count) - - # MinMaxScaler normalization - normalized_counts = min_max_normalize(raw_counts) + lookup = normalized_lookup.get((entity_key, topic), {}) + norm_vals = lookup.get("normalized", [0.0] * len(years_range)) + cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) + inst_counts = inst_counts_map.get((entity_key, topic), [1] * len(years_range)) for idx, yr in enumerate(years_range): + count, _ = year_dict[yr] yearly_data_items.append(TopicYearlyData( year=yr, - raw=raw_counts[idx], - normalized=normalized_counts[idx], + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], institutions_count=inst_counts[idx] )) diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index fbd76a45..1c451952 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -2,7 +2,9 @@

University Performance Dashboard

- @for (t of topics; track t) { } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 3906004e..53af9fad 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -24,7 +24,7 @@ export class DashboardComponent implements OnInit { 'Renewable Energy', 'Artificial Intelligence and Decision Support Systems', ]; - selectedTopic: ResearchTopic = 'Artificial Intelligence'; + selectedTopic: ResearchTopic = 'Quantum Computing'; metric: DashboardMetric = 'publications'; rawDataSource: UniversityTopicData[] = []; diff --git a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html index 09ab42d3..059525c8 100644 --- a/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html +++ b/webapp/src/app/modules/university-ranking/uni-line-chart/uni-line-chart.component.html @@ -1 +1,5 @@ -
+
diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html index d76650ac..0ac5df9a 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html @@ -1,6 +1,10 @@
@if (data() && data()!.series && data()!.series.length > 0) { -
+
} @else {
📊
diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index f549b878..8f935aa8 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -18,10 +18,10 @@ import { TrendResponse, TrendSeries, TopicYearlyData } from '../../../api'; export class UniTrendChartComponent { // Input signals following Angular v21 standards readonly data = input(null); - readonly mode = input<'normalized' | 'total'>('total'); + readonly mode = input<'normalized' | 'total' | 'cumulative'>('normalized'); readonly activeTopic = input(null); - readonly startYear = input(2015); - readonly endYear = input(2026); + readonly startYear = input(2010); + readonly endYear = input(2025); // Computed signal to automatically rebuild ECharts options when data or mode changes readonly chartOptions = computed(() => { @@ -64,12 +64,15 @@ 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 = entityColors[entityIdx % entityColors.length]; + const yrTopicData = entity.topic_data[selectedTopic] || []; // 1. Add line series for the currently selected topic (placed in Grid 0) - const yrTopicData = entity.topic_data[selectedTopic]; const lineData = years.map((year) => { - const yrData = yrTopicData?.find((y) => y.year === year); + const yrData = yrTopicData.find((y) => y.year === year); if (!yrData) return 0; + if (currentMode === 'cumulative') { + return yrData.cumulative; + } return currentMode === 'normalized' ? yrData.normalized : yrData.raw; }); @@ -93,16 +96,15 @@ export class UniTrendChartComponent { }); // 2. Add YoY growth volume bars for the selected topic (placed in Grid 1) - const volumeData = years.map((year) => { - const yrData = yrTopicData?.find((y) => y.year === year); - return yrData ? yrData.raw : 0; - }); + const bars = years.map((year) => { + const yrData = yrTopicData.find((y) => y.year === year); + const val = yrData ? yrData.raw : 0; - const bars = years.map((year, idx) => { - const val = volumeData[idx]; - const prevVal = idx > 0 ? volumeData[idx - 1] : val; - const trendSign = val >= prevVal ? 1 : -1; - return [idx, val, trendSign]; + // Find previous year's raw count (even if previous year is outside the viewport years range!) + const prevYrData = yrTopicData.find((y) => y.year === year - 1); + const prevVal = prevYrData ? prevYrData.raw : 0; + + return val - prevVal; }); series.push({ @@ -112,35 +114,7 @@ export class UniTrendChartComponent { yAxisIndex: 1, data: bars, itemStyle: { - color: (params: any) => { - const trendSign = params.value[2]; - return trendSign >= 0 ? '#10b981' : '#ef4444'; // Green vs Red - }, - }, - }); - - // 3. Add S-Curve cumulative publications trend overlay (placed in Grid 1) - let cumulativeSum = 0; - const cumulativeData = volumeData.map((val) => { - cumulativeSum += val; - return cumulativeSum; - }); - - series.push({ - name: `${entity.entity_name} (S-Curve)`, - type: 'line', - xAxisIndex: 1, - yAxisIndex: 2, - data: cumulativeData, - smooth: true, - symbol: 'none', - lineStyle: { - width: 2, - color: color, - type: 'dashed', - }, - itemStyle: { - color: color, + color: color, // Takes the color of the institution! }, }); }); @@ -148,7 +122,9 @@ export class UniTrendChartComponent { const yAxisName = currentMode === 'normalized' ? 'Normalized Scale (0 - 1)' - : 'Publications Volume'; + : currentMode === 'cumulative' + ? 'Cumulative Publications' + : 'Publications Volume'; return { title: { @@ -180,23 +156,39 @@ export class UniTrendChartComponent { trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { const color = entityColors[entityIdx % entityColors.length]; + const yrTopicData = entity.topic_data[selectedTopic] || []; + + // Recalculate cumulative sum map for this entity + const cumulativeSumMap = new Map(); + let runningSum = 0; + trendData.years.forEach((yr) => { + const yrData = yrTopicData.find((y) => y.year === yr); + runningSum += yrData ? yrData.raw : 0; + cumulativeSumMap.set(yr, runningSum); + }); + res += `
`; res += ``; res += `${entity.entity_name}:
`; - const yrData = entity.topic_data[selectedTopic]?.find( + const yrData = yrTopicData.find( (y: TopicYearlyData) => y.year === yearNum, ); if (yrData) { const val = - currentMode === 'normalized' ? yrData.normalized : yrData.raw; + currentMode === 'normalized' + ? yrData.normalized + : currentMode === 'cumulative' + ? cumulativeSumMap.get(yearNum) || 0 + : yrData.raw; + const displayVal = currentMode === 'normalized' ? val.toFixed(2) : val.toLocaleString(); let contributionStr = ''; - if (currentMode === 'total') { + if (currentMode === 'total' || currentMode === 'cumulative') { if (entity.entity_type === 'institution') { const instCountryCode = entity.country_code?.toUpperCase(); @@ -222,7 +214,20 @@ export class UniTrendChartComponent { selectedTopic ]?.find((y: TopicYearlyData) => y.year === yearNum); if (parentYr && parentYr.raw > 0) { - const pct = (yrData.raw / parentYr.raw) * 100; + const parentCumulativeSum = + parentCountry.topic_data[selectedTopic] + ?.filter((y) => y.year <= yearNum) + .reduce((sum, y) => sum + y.raw, 0) || 0; + const instCumulativeSum = + cumulativeSumMap.get(yearNum) || 0; + const pct = + currentMode === 'cumulative' + ? parentCumulativeSum > 0 + ? (instCumulativeSum / parentCumulativeSum) * 100 + : 0 + : parentYr.raw > 0 + ? (yrData.raw / parentYr.raw) * 100 + : 0; contributionStr = ` (${pct.toFixed(1)}% of ${parentCountry.entity_name})`; } } else if (parentContinent) { @@ -230,7 +235,20 @@ export class UniTrendChartComponent { selectedTopic ]?.find((y: TopicYearlyData) => y.year === yearNum); if (parentYr && parentYr.raw > 0) { - const pct = (yrData.raw / parentYr.raw) * 100; + const parentCumulativeSum = + parentContinent.topic_data[selectedTopic] + ?.filter((y) => y.year <= yearNum) + .reduce((sum, y) => sum + y.raw, 0) || 0; + const instCumulativeSum = + cumulativeSumMap.get(yearNum) || 0; + const pct = + currentMode === 'cumulative' + ? parentCumulativeSum > 0 + ? (instCumulativeSum / parentCumulativeSum) * 100 + : 0 + : parentYr.raw > 0 + ? (yrData.raw / parentYr.raw) * 100 + : 0; contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`; } } else { @@ -249,83 +267,6 @@ export class UniTrendChartComponent { contributionStr = ` (${pct.toFixed(1)}% of compared institutions)`; } } - } else if (entity.entity_type === 'country') { - const countryCode = entity.entity_id.toUpperCase(); - - const parentContinent = trendData.series.find( - (s: TrendSeries) => { - if (s.entity_type !== 'region') return false; - const memberCountries = - trendData.location_mappings?.[s.entity_id] || []; - return memberCountries.some( - (c: string) => c.toUpperCase() === countryCode, - ); - }, - ); - - const childInstsSum = trendData.series - .filter( - (s: TrendSeries) => - s.entity_type === 'institution' && - s.country_code?.toUpperCase() === countryCode, - ) - .reduce((sum: number, s: TrendSeries) => { - const y = s.topic_data[selectedTopic]?.find( - (yd: TopicYearlyData) => yd.year === yearNum, - ); - return sum + (y ? y.raw : 0); - }, 0); - - const remainingVal = Math.max(0, yrData.raw - childInstsSum); - const remainingPct = (remainingVal / yrData.raw) * 100; - - if (parentContinent) { - const parentYr = parentContinent.topic_data[ - selectedTopic - ]?.find((y: TopicYearlyData) => y.year === yearNum); - if (parentYr && parentYr.raw > 0) { - const pct = (yrData.raw / parentYr.raw) * 100; - contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`; - } - } - - if (childInstsSum > 0) { - contributionStr += `
(excl. compared institutions: ${remainingVal.toLocaleString()} / ${remainingPct.toFixed(1)}%)`; - } - } else if (entity.entity_type === 'region') { - const continentId = entity.entity_id; - const memberCountries = - trendData.location_mappings?.[continentId] || []; - - const childSum = trendData.series - .filter((s: TrendSeries) => { - if (s.entity_type === 'country') { - return memberCountries.some( - (c: string) => - c.toUpperCase() === s.entity_id.toUpperCase(), - ); - } - if (s.entity_type === 'institution') { - return memberCountries.some( - (c: string) => - c.toUpperCase() === s.country_code?.toUpperCase(), - ); - } - return false; - }) - .reduce((sum: number, s: TrendSeries) => { - const y = s.topic_data[selectedTopic]?.find( - (yd: TopicYearlyData) => yd.year === yearNum, - ); - return sum + (y ? y.raw : 0); - }, 0); - - const remainingVal = Math.max(0, yrData.raw - childSum); - const remainingPct = (remainingVal / yrData.raw) * 100; - - if (childSum > 0) { - contributionStr = `
(excl. compared elements: ${remainingVal.toLocaleString()} / ${remainingPct.toFixed(1)}%)`; - } } } @@ -339,10 +280,14 @@ export class UniTrendChartComponent { }, }, legend: { - bottom: 5, - left: 'center', + orient: 'vertical', + right: 10, + top: 'middle', type: 'scroll', textStyle: { color: '#4b5563' }, + formatter: (name: string) => { + return name.length > 22 ? name.substring(0, 20) + '...' : name; + }, }, axisPointer: { link: [{ xAxisIndex: 'all' }], @@ -350,16 +295,16 @@ export class UniTrendChartComponent { }, grid: [ { - left: '6%', - right: '8%', - top: '12%', - height: '52%', + left: 60, + right: 220, + top: 60, + height: 250, }, { - left: '6%', - right: '8%', - top: '73%', - height: '14%', + left: 60, + right: 220, + top: 360, + height: 70, }, ], xAxis: [ @@ -405,26 +350,11 @@ export class UniTrendChartComponent { axisTick: { show: false }, splitLine: { show: false }, }, - { - scale: true, - gridIndex: 1, - position: 'right', - axisLabel: { color: '#9ca3af', show: true }, - axisLine: { lineStyle: { color: '#e5e7eb' } }, - splitLine: { show: false }, - }, ], - brush: { - toolbox: ['rect', 'lineX', 'clear'], - xAxisIndex: 'all', - brushLink: 'all', - outOfBrush: { colorAlpha: 0.15 }, - }, toolbox: { left: 'right', top: 'top', feature: { - brush: { type: ['rect', 'lineX', 'clear'] }, saveAsImage: { title: 'Save' }, }, }, -- 2.56.1 From b5d03c84c41b494ee197bc2dc9f585f307f43cce Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 6 Jul 2026 10:20:42 +0200 Subject: [PATCH 08/13] attempt to optimize backend search time and small modeltype changes --- .../src/main/inse/university_ranking/logic.py | 30 ++- .../inse/university_ranking/trend_logic.py | 182 +++++++++------ .../uni-trend-parent.component.html | 14 +- .../uni-trend-parent.component.ts | 217 +++++++++++++----- 4 files changed, 311 insertions(+), 132 deletions(-) diff --git a/service/src/main/inse/university_ranking/logic.py b/service/src/main/inse/university_ranking/logic.py index 1accf196..2f368665 100644 --- a/service/src/main/inse/university_ranking/logic.py +++ b/service/src/main/inse/university_ranking/logic.py @@ -12,7 +12,7 @@ END_YEAR = datetime.datetime.now().year - 1 async def resolve_topic(topic_query: str) -> Topic: """Resolves a topic display name or ID using Elasticsearch with source whitelisting.""" - if topic_query.startswith("http") or "/T" in topic_query: + if topic_query.startswith("https://openalex.org/"): query = {"term": {"id": topic_query}} else: query = {"match_phrase": {"display_name": topic_query}} @@ -40,12 +40,17 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking topic_obj = await resolve_topic(topic_query) topic_name = topic_obj.display_name or topic_query + if topic_obj.id: + topic_filter = {"term": {"topics.id.keyword": topic_obj.id}} + else: + topic_filter = {"match_phrase": {"topics.display_name": topic_name}} + query = { "bool": { - "must": [ + "filter": [ {"term": {"type": "education"}}, {"term": {"geo.country_code": "DE"}}, - {"match_phrase": {"topics.display_name": topic_name}} + topic_filter ] } } @@ -106,7 +111,7 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking } } - # Topic filter clause (using topic ID if resolved, otherwise matching phrase) + # Topic filter clause (using topic ID if resolved, otherwise matching display name keyword) topic_id = topic_obj.id if topic_id: topic_clause = { @@ -129,10 +134,10 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking } } - # Construct single-pass ES query on openalex-works + # Construct single-pass ES query on openalex-works in Filter Context works_query = { "bool": { - "must": [ + "filter": [ { "range": { "publication_year": { @@ -141,7 +146,17 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking } } }, - topic_clause + topic_clause, + { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [inst["id"] for inst in top_10] + } + } + } + } ] } } @@ -175,6 +190,7 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking query=works_query, body={"aggs": aggregations}, size=0, + cluster="nes" ) diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 6cf70e13..8e1365d7 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -125,20 +125,61 @@ async def get_top_institutions_by_region( """ country_codes = [] if country: - country_codes = [country] + country_codes = [country.upper()] elif region: - country_codes = REGION_MAPPINGS.get(region, []) + try: + # Query openalex-continents index to resolve continent country codes dynamically + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_CONTINENTS), + query={ + "bool": { + "should": [ + {"term": {"wikidata_id.keyword": region}}, + {"term": {"id": f"https://openalex.org/continents/{region}"}} + ] + } + }, + size=1, + source=["countries"], + cluster="nes" + ) + hits = res.get("hits", {}).get("hits", []) + if hits: + source = hits[0]["_source"] + country_codes = [ + c["id"].split("/")[-1].upper() for c in source.get("countries", []) + ] + except Exception as e: + logger.warning("Failed to resolve continent countries in get_top_institutions_by_region: %s", e) + + # Resolve the topic to get the exact ID/display name + topic_filter = {"match_phrase": {"topics.display_name": topic}} + try: + topic_res = await elasticsearch.search( + index="openalex-topics", + query={"match_phrase": {"display_name": topic}}, + size=1, + source=["id", "display_name"], + cluster="nes" + ) + hits = topic_res.get("hits", {}).get("hits", []) + if hits: + source = hits[0]["_source"] + topic_id = source["id"] + topic_filter = {"term": {"topics.id.keyword": topic_id}} + except Exception as e: + logger.warning("Failed to resolve topic in get_top_institutions_by_region: %s", e) # Query openalex-institutions for educational entities matching country and topic must_clauses: List[Dict[str, Any]] = [ {"term": {"type": "education"}}, - {"match_phrase": {"topics.display_name": topic}} + topic_filter ] if country_codes: must_clauses.append({"terms": {"geo.country_code": country_codes}}) - query = {"bool": {"must": must_clauses}} + query = {"bool": {"filter": must_clauses}} # Fetch top 50 by overall works count to cover a good pool of institutions res = await elasticsearch.search( @@ -193,8 +234,10 @@ async def get_trend_data( if not topics: return TrendResponse(series=[], years=[]) + import asyncio + start_year = 2000 - end_year = datetime.datetime.now().year -1 + end_year = datetime.datetime.now().year - 1 years_range = list(range(start_year, end_year + 1)) # Resolve primary institution (default University of Duisburg-Essen for everyone) @@ -208,61 +251,67 @@ async def get_trend_data( if primary_inst_id not in query_institutions: query_institutions.insert(0, primary_inst_id) - # Resolve institution names and country codes from openalex-institutions - resolved_names: Dict[str, str] = {primary_inst_id: primary_inst_name} - resolved_country_codes: Dict[str, str] = {} + # Prepare lists of countries and regions dynamically + 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)) - - if ids_to_resolve: + + # Define concurrent metadata lookups + async def fetch_institutions(): + names = {primary_inst_id: primary_inst_name} + codes = {} + if not ids_to_resolve: + return names, codes try: - name_res = await elasticsearch.search( + res = await elasticsearch.search( index=str(ESIndex.OPENALEX_INSTITUTIONS), query={"terms": {"id": ids_to_resolve}}, size=len(ids_to_resolve), source=["id", "display_name", "country_code"], cluster="nes" ) - for hit in name_res.get("hits", {}).get("hits", []): + for hit in res.get("hits", {}).get("hits", []): source = hit["_source"] - resolved_names[source["id"]] = source.get("display_name", source["id"]) - resolved_country_codes[source["id"]] = source.get("country_code", "") + names[source["id"]] = source.get("display_name", source["id"]) + codes[source["id"]] = source.get("country_code", "") except Exception as e: logger.warning("Failed to resolve institution details from ES: %s", e) + return names, codes - # Prepare lists of countries and regions dynamically - query_countries = countries or [] - query_regions = regions or [] - - resolved_country_names: Dict[str, str] = {} - clean_countries: List[str] = [] - if query_countries: - clean_countries = [c.split("/")[-1].upper() for c in query_countries] + async def fetch_countries(): + names = {} + if not clean_countries: + return names try: - c_res = await elasticsearch.search( + res = await elasticsearch.search( index=str(ESIndex.OPENALEX_COUNTRIES), query={"terms": {"country_code": clean_countries}}, size=len(clean_countries), source=["country_code", "display_name"], cluster="nes" ) - for hit in c_res.get("hits", {}).get("hits", []): + for hit in res.get("hits", {}).get("hits", []): source = hit["_source"] - resolved_country_names[source["country_code"]] = source["display_name"] + names[source["country_code"]] = source["display_name"] except Exception as e: logger.warning("Failed to resolve country names from ES: %s", e) + return names - resolved_continent_names: Dict[str, str] = {} - continent_country_codes: Dict[str, List[str]] = {} - location_mappings: Dict[str, List[str]] = {} - if query_regions: - clean_regions = [r.split("/")[-1] for r in query_regions] + async def fetch_continents(): + names = {} + ccodes = {} + if not clean_regions: + return names, ccodes try: - r_res = await elasticsearch.search( + res = await elasticsearch.search( index=str(ESIndex.OPENALEX_CONTINENTS), query={ "bool": { "should": [ - {"terms": {"wikidata_id": clean_regions}}, + {"terms": {"wikidata_id.keyword": clean_regions}}, {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}} ] } @@ -271,43 +320,47 @@ async def get_trend_data( source=["id", "display_name", "wikidata_id", "countries"], cluster="nes" ) - for hit in r_res.get("hits", {}).get("hits", []): + for hit in res.get("hits", {}).get("hits", []): source = hit["_source"] c_code = source.get("wikidata_id") or source["id"].split("/")[-1] - resolved_continent_names[c_code] = source["display_name"] - member_ccs = [ - c["id"].split("/")[-1].upper() for c in source.get("countries", []) - ] - continent_country_codes[c_code] = member_ccs - location_mappings[c_code] = member_ccs + names[c_code] = source["display_name"] + ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])] except Exception as e: logger.warning("Failed to resolve continent names from ES: %s", e) + return names, ccodes + + async def fetch_topics(): + t_ids = {} + try: + res = await elasticsearch.search( + index="openalex-topics", + query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}}, + size=len(topics) * 2, + source=["id", "display_name"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + source = hit["_source"] + for t in topics: + if t.lower() in source["display_name"].lower(): + t_ids[t] = source["id"] + except Exception as e: + logger.warning("Failed to resolve topic IDs from ES: %s", e) + return t_ids + + # Execute all 4 queries concurrently + ( + (resolved_names, resolved_country_codes), + resolved_country_names, + (resolved_continent_names, continent_country_codes), + resolved_topic_ids + ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics()) + + location_mappings = continent_country_codes.copy() # Map of filters inside our Elasticsearch aggregation filters_map: Dict[str, Dict[str, Any]] = {} - # Resolve the topic IDs from the openalex-topics index to enable fast term queries - resolved_topic_ids: Dict[str, str] = {} - try: - topic_res = await elasticsearch.search( - index="openalex-topics", - query={ - "bool": { - "should": [ - {"match_phrase": {"display_name": t}} for t in topics - ] - } - }, - size=len(topics) * 2, - source=["id", "display_name"], - cluster="nes" - ) - for hit in topic_res.get("hits", {}).get("hits", []): - source = hit["_source"] - resolved_topic_ids[source["display_name"]] = source["id"] - except Exception as e: - logger.warning("Failed to resolve topic IDs from ES: %s", e) - # 1. Institution Filters for inst_id in query_institutions: filters_map[f"inst_{inst_id}"] = { @@ -426,7 +479,7 @@ async def get_trend_data( }) # Construct the single-pass Elasticsearch query - must_clauses = [ + filter_clauses = [ { "range": { "publication_year": { @@ -443,7 +496,7 @@ async def get_trend_data( } ] if entity_should_clauses: - must_clauses.append({ + filter_clauses.append({ "bool": { "should": entity_should_clauses, "minimum_should_match": 1 @@ -452,7 +505,7 @@ async def get_trend_data( query = { "bool": { - "must": must_clauses + "filter": filter_clauses } } @@ -600,3 +653,4 @@ async def get_trend_data( )) return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) + 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 a6110133..9506f9bd 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 @@ -147,9 +147,13 @@ @for (result of searchResults(); track result.id) {
  • } @@ -217,6 +221,12 @@ title="Shows total absolute publication counts."> 📊 Total Volume +
    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 ae695357..dca2a6c2 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 @@ -12,6 +12,15 @@ import { import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { ActivatedRoute, Router } 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 { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component'; import { TrendResponse, @@ -20,14 +29,32 @@ import { TopInstitutionItem, AutocompleteLocationItem, AutocompleteResponse, + AutocompleteResponseResultsInner, UniversityRankingsService, InstitutionsService, } from '../../../api'; +export interface CompareItem { + id: string; + name: string; +} + @Component({ selector: 'app-uni-trend-parent', standalone: true, - imports: [CommonModule, FormsModule, UniTrendChartComponent], + imports: [ + CommonModule, + FormsModule, + UniTrendChartComponent, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + MatCheckboxModule, + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + MatAutocompleteModule, + ], templateUrl: './uni-trend-parent.component.html', styleUrl: './uni-trend-parent.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, @@ -47,19 +74,23 @@ export class UniTrendParentComponent implements OnInit { readonly primaryInstitutionName = signal( 'University of Duisburg-Essen', ); - readonly comparisonInstitutions = signal<{ id: string; name: string }[]>([]); - readonly comparisonCountries = signal<{ id: string; name: string }[]>([]); - readonly comparisonRegions = signal<{ id: string; name: string }[]>([]); - readonly startYear = signal(2015); - readonly endYear = signal(new Date().getFullYear() - 1); - readonly chartMode = signal<'normalized' | 'total'>('total'); + readonly comparisonInstitutions = signal([]); + readonly comparisonCountries = signal([ + { id: 'DE', name: 'Germany' }, + ]); + readonly comparisonRegions = signal([]); + readonly startYear = signal(2010); + readonly endYear = signal(2025); + readonly chartMode = signal<'normalized' | 'total' | 'cumulative'>( + 'normalized', + ); readonly activeChartTopic = signal(''); // Cached parameters of the last active search request to track "isDirty" readonly fetchedTopics = signal([]); - readonly fetchedInstitutions = signal<{ id: string; name: string }[]>([]); - readonly fetchedCountries = signal<{ id: string; name: string }[]>([]); - readonly fetchedRegions = signal<{ id: string; name: string }[]>([]); + readonly fetchedInstitutions = signal([]); + readonly fetchedCountries = signal([]); + readonly fetchedRegions = signal([]); // Results & Loading signals readonly rawTrendResponse = signal(null); @@ -69,7 +100,7 @@ export class UniTrendParentComponent implements OnInit { // Autocomplete UI state readonly searchQuery = signal(''); - readonly searchResults = signal([]); + readonly searchResults = signal([]); readonly locationQuery = signal(''); readonly locationSearchResults = signal([]); @@ -82,13 +113,13 @@ export class UniTrendParentComponent implements OnInit { if (!raw) return null; const currentInstIds = new Set( - this.comparisonInstitutions().map((i) => i.id.toLowerCase()), + this.comparisonInstitutions().map((i: CompareItem) => i.id.toLowerCase()), ); const currentCountryIds = new Set( - this.comparisonCountries().map((c) => c.id.toLowerCase()), + this.comparisonCountries().map((c: CompareItem) => c.id.toLowerCase()), ); const currentRegionIds = new Set( - this.comparisonRegions().map((r) => r.id.toLowerCase()), + this.comparisonRegions().map((r: CompareItem) => r.id.toLowerCase()), ); const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase(); @@ -97,17 +128,9 @@ export class UniTrendParentComponent implements OnInit { if (s.entity_type === 'institution') { return id === defaultInstId || currentInstIds.has(id); } else if (s.entity_type === 'country') { - return ( - currentCountryIds.has(id) || - currentCountryIds.has('https://openalex.org/countries/' + id) || - Array.from(currentCountryIds).some((cid) => cid.endsWith('/' + id)) - ); + return currentCountryIds.has(id); } else if (s.entity_type === 'region') { - return ( - currentRegionIds.has(id) || - currentRegionIds.has('https://openalex.org/continents/' + id) || - Array.from(currentRegionIds).some((rid) => rid.endsWith('/' + id)) - ); + return currentRegionIds.has(id); } return false; }); @@ -121,31 +144,31 @@ export class UniTrendParentComponent implements OnInit { // Computed dirty state to enable "Search" button readonly isDirty = computed(() => { const fetchedInsts = this.fetchedInstitutions() - .map((i) => i.id) + .map((i: CompareItem) => i.id) .sort() .join(','); const currentInsts = this.comparisonInstitutions() - .map((i) => i.id) + .map((i: CompareItem) => i.id) .sort() .join(','); if (fetchedInsts !== currentInsts) return true; const fetchedC = this.fetchedCountries() - .map((c) => c.id) + .map((c: CompareItem) => c.id) .sort() .join(','); const currentC = this.comparisonCountries() - .map((c) => c.id) + .map((c: CompareItem) => c.id) .sort() .join(','); if (fetchedC !== currentC) return true; const fetchedR = this.fetchedRegions() - .map((r) => r.id) + .map((r: CompareItem) => r.id) .sort() .join(','); const currentR = this.comparisonRegions() - .map((r) => r.id) + .map((r: CompareItem) => r.id) .sort() .join(','); if (fetchedR !== currentR) return true; @@ -173,7 +196,7 @@ export class UniTrendParentComponent implements OnInit { if (kws.length > 0) { // Find existing selections that are still in keywords, or default to all - const validSelections = currentSelections.filter((t) => + const validSelections = currentSelections.filter((t: string) => kws.includes(t), ); if (validSelections.length > 0) { @@ -188,6 +211,12 @@ export class UniTrendParentComponent implements OnInit { if (!active || !updatedSelections.includes(active)) { this.activeChartTopic.set(updatedSelections[0] || ''); } + + // If comparison list is empty, initialize default institutions dynamically + const currentInsts = untracked(() => this.comparisonInstitutions()); + if (currentInsts.length === 0) { + untracked(() => this.initializeDefaultInstitutions()); + } } else { this.selectedTrendTopics.set([]); } @@ -202,7 +231,7 @@ export class UniTrendParentComponent implements OnInit { const insts = Array.isArray(params['institutions']) ? params['institutions'] : [params['institutions']]; - const parsed = insts.map((i) => { + const parsed = insts.map((i: string) => { const parts = i.split('|'); return { id: parts[0], name: parts[1] || parts[0] }; }); @@ -213,7 +242,7 @@ export class UniTrendParentComponent implements OnInit { const ccs = Array.isArray(params['countries']) ? params['countries'] : [params['countries']]; - const parsed = ccs.map((c) => { + const parsed = ccs.map((c: string) => { const parts = c.split('|'); return { id: parts[0], name: parts[1] || parts[0] }; }); @@ -224,7 +253,7 @@ export class UniTrendParentComponent implements OnInit { const regs = Array.isArray(params['regions']) ? params['regions'] : [params['regions']]; - const parsed = regs.map((r) => { + const parsed = regs.map((r: string) => { const parts = r.split('|'); return { id: parts[0], name: parts[1] || parts[0] }; }); @@ -243,16 +272,69 @@ export class UniTrendParentComponent implements OnInit { if (params['active_chart_topic']) { this.activeChartTopic.set(params['active_chart_topic']); } - - // Auto-trigger load once on initial page render if keywords are present - if (this.rawTrendResponse() === null && this.keywords().length > 0) { - this.fetchTrendData(); - } }); } ngOnInit() { this.loadTrendSuggestions(); + this.initializeDefaultInstitutions(); + } + + // Dynamically load top institutions to initialize comparisons using the top-institutions service + initializeDefaultInstitutions() { + const kws = this.keywords(); + if (kws.length === 0) return; + + const topic = kws[0]; + this.isSuggestionsLoading.set(true); + + forkJoin({ + deInsts: + this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic, + undefined, + 'DE', + 2, + ), + overallInsts: + this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic, + undefined, + undefined, + 2, + ), + }).subscribe({ + next: ({ + deInsts, + overallInsts, + }: { + deInsts: Array; + overallInsts: Array; + }) => { + const uniqueInsts = new Map(); + + // Add DE ones + deInsts.forEach((inst: TopInstitutionItem) => { + if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unknown'); + }); + + // Add overall ones + overallInsts.forEach((inst: TopInstitutionItem) => { + if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unknown'); + }); + + const list = Array.from(uniqueInsts.entries()).map(([id, name]) => ({ + id, + name, + })); + this.comparisonInstitutions.set(list); + this.isSuggestionsLoading.set(false); + }, + error: (err: any) => { + console.error('Failed to load default institutions dynamically:', err); + this.isSuggestionsLoading.set(false); + }, + }); } // Fetch recommended institutions for comparison based on current topics @@ -268,11 +350,11 @@ export class UniTrendParentComponent implements OnInit { const countryFilter = this.comparisonCountries().length > 0 - ? this.comparisonCountries()[0].id.split('/').pop() + ? this.comparisonCountries()[0].id : undefined; const regionFilter = this.comparisonRegions().length > 0 - ? this.comparisonRegions()[0].name + ? this.comparisonRegions()[0].id : undefined; this.apiService @@ -283,7 +365,7 @@ export class UniTrendParentComponent implements OnInit { 6, ) .subscribe({ - next: (res) => { + next: (res: any) => { this.topSuggestions.set(res || []); this.isSuggestionsLoading.set(false); }, @@ -309,12 +391,12 @@ export class UniTrendParentComponent implements OnInit { this.apiService .getTrendApiInseServiceUniversityRankingsTrendGet( topics, - this.comparisonInstitutions().map((i) => i.id), - this.comparisonCountries().map((c) => c.id), - this.comparisonRegions().map((r) => r.id), + this.comparisonInstitutions().map((i: CompareItem) => i.id), + this.comparisonCountries().map((c: CompareItem) => c.id), + this.comparisonRegions().map((r: CompareItem) => r.id), ) .subscribe({ - next: (response) => { + next: (response: TrendResponse) => { this.rawTrendResponse.set(response); this.isTrendLoading.set(false); this.updateUrlParams(); @@ -331,15 +413,21 @@ export class UniTrendParentComponent implements OnInit { trend_topics: this.selectedTrendTopics(), institutions: this.comparisonInstitutions().length > 0 - ? this.comparisonInstitutions().map((i) => `${i.id}|${i.name}`) + ? this.comparisonInstitutions().map( + (i: CompareItem) => `${i.id}|${i.name}`, + ) : null, countries: this.comparisonCountries().length > 0 - ? this.comparisonCountries().map((c) => `${c.id}|${c.name}`) + ? this.comparisonCountries().map( + (c: CompareItem) => `${c.id}|${c.name}`, + ) : null, regions: this.comparisonRegions().length > 0 - ? this.comparisonRegions().map((r) => `${r.id}|${r.name}`) + ? this.comparisonRegions().map( + (r: CompareItem) => `${r.id}|${r.name}`, + ) : null, start_year: this.startYear(), end_year: this.endYear(), @@ -364,7 +452,9 @@ export class UniTrendParentComponent implements OnInit { updated = current.includes(topic) ? current : [...current, topic]; } else { updated = - current.length > 1 ? current.filter((t) => t !== topic) : current; + current.length > 1 + ? current.filter((t: string) => t !== topic) + : current; if (current.length === 1) { (event.target as HTMLInputElement).checked = true; } @@ -382,7 +472,10 @@ export class UniTrendParentComponent implements OnInit { // Add comparison institution addInstitution(id: string, name: string) { const current = this.comparisonInstitutions(); - if (!current.some((i) => i.id === id) && id !== this.primaryInstitution()) { + if ( + !current.some((i: CompareItem) => i.id === id) && + id !== this.primaryInstitution() + ) { this.comparisonInstitutions.set([...current, { id, name }]); } this.searchQuery.set(''); @@ -392,14 +485,16 @@ export class UniTrendParentComponent implements OnInit { // Remove comparison institution (data reuses instantly via computed) removeInstitution(id: string) { const current = this.comparisonInstitutions(); - this.comparisonInstitutions.set(current.filter((i) => i.id !== id)); + this.comparisonInstitutions.set( + current.filter((i: CompareItem) => i.id !== id), + ); } // Add country or region addLocation(loc: AutocompleteLocationItem) { if (loc.type === 'country') { const current = this.comparisonCountries(); - if (!current.some((c) => c.id === loc.id)) { + if (!current.some((c: CompareItem) => c.id === loc.id)) { this.comparisonCountries.set([ ...current, { id: loc.id, name: loc.display_name }, @@ -407,7 +502,7 @@ export class UniTrendParentComponent implements OnInit { } } else if (loc.type === 'continent') { const current = this.comparisonRegions(); - if (!current.some((r) => r.id === loc.id)) { + if (!current.some((r: CompareItem) => r.id === loc.id)) { this.comparisonRegions.set([ ...current, { id: loc.id, name: loc.display_name }, @@ -423,16 +518,20 @@ export class UniTrendParentComponent implements OnInit { removeLocation(id: string, type: 'country' | 'continent') { if (type === 'country') { const current = this.comparisonCountries(); - this.comparisonCountries.set(current.filter((c) => c.id !== id)); + this.comparisonCountries.set( + current.filter((c: CompareItem) => c.id !== id), + ); } else if (type === 'continent') { const current = this.comparisonRegions(); - this.comparisonRegions.set(current.filter((r) => r.id !== id)); + this.comparisonRegions.set( + current.filter((r: CompareItem) => r.id !== id), + ); } this.loadTrendSuggestions(); } // Scaling mode toggle (data reuses instantly) - setChartMode(mode: 'normalized' | 'total') { + setChartMode(mode: 'normalized' | 'total' | 'cumulative') { this.chartMode.set(mode); this.updateUrlParams(); } @@ -450,7 +549,7 @@ export class UniTrendParentComponent implements OnInit { this.institutionsApiService .autocompleteInstitutions(query, undefined, 'education', 10) .subscribe({ - next: (res) => { + next: (res: AutocompleteResponse) => { this.searchResults.set(res.results || []); }, error: () => { @@ -471,7 +570,7 @@ export class UniTrendParentComponent implements OnInit { query, ) .subscribe({ - next: (res) => { + next: (res: AutocompleteLocationItem[]) => { this.locationSearchResults.set(res || []); }, error: () => { -- 2.56.1 From dfb1413b05aa4c98a472a3b8f74473a8de31a6d5 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 6 Jul 2026 10:45:57 +0200 Subject: [PATCH 09/13] Changed trend frontend (Everything in German, stacking chart, y-axis overlap fix, tooltip information addition, recomended institutions layout change) --- .../keywords-search.component.html | 14 +- .../keywords-search.component.ts | 8 + .../uni-trend-chart.component.html | 6 +- .../uni-trend-chart.component.ts | 291 +++++++++++------- .../uni-trend-parent.component.html | 140 +++++---- .../uni-trend-parent.component.ts | 38 ++- 6 files changed, 308 insertions(+), 189 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index d30dc5f6..f9abedb9 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -218,8 +218,8 @@
    - -
    + +
    +
    - @if (selectedKeywords().length > 0) { + @if (showVisualization() && selectedKeywords().length > 0) {
    diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 52312b88..bdb253f8 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -85,6 +85,7 @@ export class KeywordsSearchComponent { readonly selectedKeywords = signal([]); readonly isExtracting = signal(false); readonly extractionSource = signal(null); + readonly showVisualization = signal(false); // Single place mapping a category name to its label signal and its // backing entries signal. Replaces four near-identical computed()s and @@ -505,6 +506,7 @@ export class KeywordsSearchComponent { } search(): void { + this.showVisualization.set(false); const payload = { extractedKeywords: this.getSelectedExtractedKeywordEntries(), manualKeywords: this.getSelectedManualKeywordEntries(), @@ -516,6 +518,10 @@ export class KeywordsSearchComponent { // this.router.navigate(['/search'], { state: payload }); } + visualize(): void { + this.showVisualization.set(true); + } + // --- Helpers -------------------------------------------------------------- private selectedInCategory(category: KeywordCategory): Signal { @@ -682,6 +688,8 @@ export class KeywordsSearchComponent { updateQueryParams(): void { if (this.isRestoringState) return; + this.showVisualization.set(false); + const queryParams = { mode: this.form.controls.selectedInputType.value, url: this.toNullableParam(this.form.controls.urlInput.value), diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html index 0ac5df9a..a908dda2 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html @@ -8,10 +8,10 @@ } @else {
    📊
    -

    No Trend Data Available

    +

    Keine Trenddaten verfügbar

    - Please select at least one topic and choose institutions or regions to - compare in the control panel. + Bitte wählen Sie mindestens ein Thema und Einrichtungen oder Regionen im + Kontrollfeld aus, um sie zu vergleichen.

    } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 8f935aa8..07757b0c 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -59,11 +59,22 @@ export class UniTrendChartComponent { '#8b5cf6', // Purple '#06b6d4', // Cyan '#6366f1', // Indigo + '#ef4444', // Red + '#14b8a6', // Teal + '#f97316', // Orange + '#d946ef', // Fuchsia + '#84cc16', // Lime + '#22c55e', // Green + '#a855f7', // Purple/Fuchsia + '#eab308', // Amber/Yellow Dark + '#f43f5e', // Rose ]; + const getEntityColor = (idx: number) => + entityColors[idx % entityColors.length]; // Build series: Line in top grid, growth volume bars and S-Curve in bottom grid trendData.series.forEach((entity, entityIdx) => { - const color = entityColors[entityIdx % entityColors.length]; + const color = getEntityColor(entityIdx); const yrTopicData = entity.topic_data[selectedTopic] || []; // 1. Add line series for the currently selected topic (placed in Grid 0) @@ -76,11 +87,17 @@ 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, + }, data: lineData, smooth: true, lineStyle: { @@ -91,6 +108,7 @@ export class UniTrendChartComponent { color: color, }, emphasis: { + focus: 'series', lineStyle: { width: 3.5 }, }, }); @@ -108,7 +126,7 @@ export class UniTrendChartComponent { }); series.push({ - name: `${entity.entity_name} (YoY Growth)`, + name: `${entity.entity_name} (YoY Wachstum)`, type: 'bar', xAxisIndex: 1, yAxisIndex: 1, @@ -116,19 +134,33 @@ export class UniTrendChartComponent { itemStyle: { color: color, // Takes the color of the institution! }, + markLine: + entityIdx === 0 + ? { + silent: true, + symbol: 'none', + label: { show: false }, + lineStyle: { + type: 'solid', + color: '#374151', + width: 1.5, + }, + data: [{ yAxis: 0 }], + } + : undefined, }); }); const yAxisName = currentMode === 'normalized' - ? 'Normalized Scale (0 - 1)' + ? 'Normierte Skala (0 - 1)' : currentMode === 'cumulative' - ? 'Cumulative Publications' - : 'Publications Volume'; + ? 'Kumulierte Publikationen' + : 'Publikationsvolumen'; return { title: { - text: `Publication Trends: ${selectedTopic}`, + text: `Publikationstrends: ${selectedTopic}`, left: 'left', textStyle: { fontSize: 16, @@ -138,24 +170,27 @@ export class UniTrendChartComponent { }, tooltip: { trigger: 'axis', - backgroundColor: 'rgba(255, 255, 255, 0.96)', + backgroundColor: 'rgba(255, 255, 255, 0.98)', borderColor: '#e5e7eb', borderWidth: 1, - padding: 0, + padding: 8, + confine: true, + extraCssText: + 'z-index: 9999; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); border-radius: 8px;', textStyle: { color: '#374151', - fontSize: 12, + fontSize: 11, }, formatter: (params: any) => { if (!params || params.length === 0) return ''; const yearNum = parseInt(params[0].name, 10); - let res = `
    `; - res += `Year: ${yearNum}
    `; - res += `
    `; + let res = `
    `; + res += `Jahr: ${yearNum}`; + res += `
    `; trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { - const color = entityColors[entityIdx % entityColors.length]; + const color = getEntityColor(entityIdx); const yrTopicData = entity.topic_data[selectedTopic] || []; // Recalculate cumulative sum map for this entity @@ -167,112 +202,122 @@ export class UniTrendChartComponent { cumulativeSumMap.set(yr, runningSum); }); - res += `
    `; - res += ``; - res += `${entity.entity_name}:
    `; - const yrData = yrTopicData.find( (y: TopicYearlyData) => y.year === yearNum, ); if (yrData) { - const val = - currentMode === 'normalized' - ? yrData.normalized - : currentMode === 'cumulative' - ? cumulativeSumMap.get(yearNum) || 0 - : yrData.raw; + const rawCount = yrData.raw; + const normVal = yrData.normalized.toFixed(2); + const cumVal = cumulativeSumMap.get(yearNum) || 0; - const displayVal = - currentMode === 'normalized' - ? val.toFixed(2) - : val.toLocaleString(); + // YoY growth + const prevYrData = yrTopicData.find( + (y) => y.year === yearNum - 1, + ); + const prevRawCount = prevYrData ? prevYrData.raw : 0; + const yoyGrowth = rawCount - prevRawCount; let contributionStr = ''; - if (currentMode === 'total' || currentMode === 'cumulative') { - if (entity.entity_type === 'institution') { - const instCountryCode = entity.country_code?.toUpperCase(); + if (entity.entity_type === 'institution') { + const instCountryCode = entity.country_code?.toUpperCase(); - const parentCountry = trendData.series.find( - (s: TrendSeries) => - s.entity_type === 'country' && - s.entity_id.toUpperCase() === instCountryCode, - ); + const parentCountry = trendData.series.find( + (s: TrendSeries) => + s.entity_type === 'country' && + s.entity_id.toUpperCase() === instCountryCode, + ); - const parentContinent = trendData.series.find( - (s: TrendSeries) => { - if (s.entity_type !== 'region') return false; - const memberCountries = - trendData.location_mappings?.[s.entity_id] || []; - return memberCountries.some( - (c: string) => c.toUpperCase() === instCountryCode, + const parentContinent = trendData.series.find( + (s: TrendSeries) => { + if (s.entity_type !== 'region') return false; + const memberCountries = + trendData.location_mappings?.[s.entity_id] || []; + return memberCountries.some( + (c: string) => c.toUpperCase() === instCountryCode, + ); + }, + ); + + if (parentCountry) { + const parentYr = parentCountry.topic_data[ + selectedTopic + ]?.find((y: TopicYearlyData) => y.year === yearNum); + if (parentYr && parentYr.raw > 0) { + const parentCumulativeSum = + parentCountry.topic_data[selectedTopic] + ?.filter((y) => y.year <= yearNum) + .reduce((sum, y) => sum + y.raw, 0) || 0; + const instCumulativeSum = + cumulativeSumMap.get(yearNum) || 0; + const pct = + currentMode === 'cumulative' + ? parentCumulativeSum > 0 + ? (instCumulativeSum / parentCumulativeSum) * 100 + : 0 + : parentYr.raw > 0 + ? (yrData.raw / parentYr.raw) * 100 + : 0; + contributionStr = ` (${pct.toFixed(1)} % von ${parentCountry.entity_name})`; + } + } else if (parentContinent) { + const parentYr = parentContinent.topic_data[ + selectedTopic + ]?.find((y: TopicYearlyData) => y.year === yearNum); + if (parentYr && parentYr.raw > 0) { + const parentCumulativeSum = + parentContinent.topic_data[selectedTopic] + ?.filter((y) => y.year <= yearNum) + .reduce((sum, y) => sum + y.raw, 0) || 0; + const instCumulativeSum = + cumulativeSumMap.get(yearNum) || 0; + const pct = + currentMode === 'cumulative' + ? parentCumulativeSum > 0 + ? (instCumulativeSum / parentCumulativeSum) * 100 + : 0 + : parentYr.raw > 0 + ? (yrData.raw / parentYr.raw) * 100 + : 0; + contributionStr = ` (${pct.toFixed(1)} % von ${parentContinent.entity_name})`; + } + } else { + const sumInsts = trendData.series + .filter((s: TrendSeries) => s.entity_type === 'institution') + .reduce((sum: number, s: TrendSeries) => { + const y = s.topic_data[selectedTopic]?.find( + (yd: TopicYearlyData) => yd.year === yearNum, ); - }, - ); - - if (parentCountry) { - const parentYr = parentCountry.topic_data[ - selectedTopic - ]?.find((y: TopicYearlyData) => y.year === yearNum); - if (parentYr && parentYr.raw > 0) { - const parentCumulativeSum = - parentCountry.topic_data[selectedTopic] - ?.filter((y) => y.year <= yearNum) - .reduce((sum, y) => sum + y.raw, 0) || 0; - const instCumulativeSum = - cumulativeSumMap.get(yearNum) || 0; - const pct = - currentMode === 'cumulative' - ? parentCumulativeSum > 0 - ? (instCumulativeSum / parentCumulativeSum) * 100 - : 0 - : parentYr.raw > 0 - ? (yrData.raw / parentYr.raw) * 100 - : 0; - contributionStr = ` (${pct.toFixed(1)}% of ${parentCountry.entity_name})`; - } - } else if (parentContinent) { - const parentYr = parentContinent.topic_data[ - selectedTopic - ]?.find((y: TopicYearlyData) => y.year === yearNum); - if (parentYr && parentYr.raw > 0) { - const parentCumulativeSum = - parentContinent.topic_data[selectedTopic] - ?.filter((y) => y.year <= yearNum) - .reduce((sum, y) => sum + y.raw, 0) || 0; - const instCumulativeSum = - cumulativeSumMap.get(yearNum) || 0; - const pct = - currentMode === 'cumulative' - ? parentCumulativeSum > 0 - ? (instCumulativeSum / parentCumulativeSum) * 100 - : 0 - : parentYr.raw > 0 - ? (yrData.raw / parentYr.raw) * 100 - : 0; - contributionStr = ` (${pct.toFixed(1)}% of ${parentContinent.entity_name})`; - } - } else { - const sumInsts = trendData.series - .filter( - (s: TrendSeries) => s.entity_type === 'institution', - ) - .reduce((sum: number, s: TrendSeries) => { - const y = s.topic_data[selectedTopic]?.find( - (yd: TopicYearlyData) => yd.year === yearNum, - ); - return sum + (y ? y.raw : 0); - }, 0); - if (sumInsts > 0) { - const pct = (yrData.raw / sumInsts) * 100; - contributionStr = ` (${pct.toFixed(1)}% of compared institutions)`; - } + return sum + (y ? y.raw : 0); + }, 0); + if (sumInsts > 0) { + const pct = (yrData.raw / sumInsts) * 100; + contributionStr = ` (${pct.toFixed(1)} % der verglichenen Inst.)`; } } } - res += `• ${selectedTopic}: ${displayVal}${contributionStr}
    `; + res += `
    `; + res += `
    `; + res += ``; + res += `${entity.entity_name}`; + res += `
    `; + + res += ``; + res += ``; + res += ``; + res += ``; + + const yoySign = yoyGrowth > 0 ? '+' : ''; + const yoyColor = + yoyGrowth > 0 + ? '#10b981' + : yoyGrowth < 0 + ? '#ef4444' + : '#6b7280'; + res += ``; + res += `
    • Publikationen:${rawCount.toLocaleString()}${contributionStr}
    • Normiert (0-1):${normVal}
    • Kumuliert:${cumVal.toLocaleString()}
    • YoY Wachstum:${yoySign}${yoyGrowth.toLocaleString()}
    `; + res += `
    `; } - res += `
    `; }); res += `
    `; @@ -295,13 +340,13 @@ export class UniTrendChartComponent { }, grid: [ { - left: 60, + left: 80, right: 220, - top: 60, - height: 250, + top: 80, + height: 230, }, { - left: 60, + left: 80, right: 220, top: 360, height: 70, @@ -336,26 +381,46 @@ export class UniTrendChartComponent { { scale: true, name: yAxisName, - nameTextStyle: { color: '#4b5563', padding: [0, 0, 8, 0] }, + nameLocation: 'middle', + nameRotate: 90, + nameGap: 50, + nameTextStyle: { + color: '#4b5563', + padding: [0, 0, 8, 0], + fontWeight: 'bold', + }, axisLabel: { color: '#4b5563' }, axisLine: { lineStyle: { color: '#e5e7eb' } }, splitLine: { lineStyle: { color: '#f3f4f6' } }, }, { - scale: true, + scale: false, gridIndex: 1, splitNumber: 2, - axisLabel: { show: false }, + axisLabel: { + show: true, + color: '#6b7280', + fontSize: 9, + formatter: (value: number) => { + return value > 0 ? `+${value}` : `${value}`; + }, + }, axisLine: { show: false }, axisTick: { show: false }, - splitLine: { show: false }, + splitLine: { + show: true, + lineStyle: { + color: '#e5e7eb', + type: 'dashed', + }, + }, }, ], toolbox: { left: 'right', top: 'top', feature: { - saveAsImage: { title: 'Save' }, + saveAsImage: { title: 'Speichern' }, }, }, dataZoom: [ 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 9506f9bd..df4c6f45 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 @@ -1,11 +1,11 @@
    - +
    @@ -139,7 +139,7 @@
    - -
    -

    Suggested Top Institutions

    -
    - @if (isSuggestionsLoading()) { -
    Loading suggestions...
    - } @else { - @for (item of topSuggestions(); track item.id || '') { - - } - } -
    -
    - - +
    - +
    - Visualization Scale: + Visualisierungsskala:
    @@ -234,7 +204,7 @@ @if (isTrendLoading()) {
    -

    Retrieving trend data from works index...

    +

    Trenddaten werden aus dem Publikationsverzeichnis abgerufen...

    } @if (selectedTrendTopics().length > 1) { @@ -255,5 +225,53 @@ [startYear]="startYear()" [endYear]="endYear()">
    + + +
    +

    + Empfohlene Top-Einrichtungen für das Thema: {{ activeChartTopic() }} +

    +
    + @if (isSuggestionsLoading()) { +
    +
    + Empfehlungen werden geladen... +
    + } @else { + @if (topSuggestions().length === 0) { +

    + Keine Empfehlungen für dieses Thema gefunden. +

    + } @else { +
    + @for (item of topSuggestions(); track item.id || '') { + + } +
    + } + } +
    +
    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 dca2a6c2..154437de 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 @@ -72,11 +72,11 @@ export class UniTrendParentComponent implements OnInit { readonly selectedTrendTopics = signal([]); readonly primaryInstitution = signal(null); readonly primaryInstitutionName = signal( - 'University of Duisburg-Essen', + 'Universität Duisburg-Essen', ); readonly comparisonInstitutions = signal([]); readonly comparisonCountries = signal([ - { id: 'DE', name: 'Germany' }, + { id: 'DE', name: 'Deutschland' }, ]); readonly comparisonRegions = signal([]); readonly startYear = signal(2010); @@ -224,6 +224,20 @@ export class UniTrendParentComponent implements OnInit { { allowSignalWrites: true }, ); + // Effect: load suggestions when topic or location filters change + effect( + () => { + const topic = this.activeChartTopic(); + const countries = this.comparisonCountries(); + const regions = this.comparisonRegions(); + + untracked(() => { + this.loadTrendSuggestions(); + }); + }, + { allowSignalWrites: true }, + ); + // Handle initialization and synchronization of URL state this.route.queryParams.subscribe((params) => { // Parse institutions serialized as id|name @@ -276,7 +290,6 @@ export class UniTrendParentComponent implements OnInit { } ngOnInit() { - this.loadTrendSuggestions(); this.initializeDefaultInstitutions(); } @@ -315,12 +328,14 @@ export class UniTrendParentComponent implements OnInit { // Add DE ones deInsts.forEach((inst: TopInstitutionItem) => { - if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unknown'); + if (inst.id) + uniqueInsts.set(inst.id, inst.display_name || 'Unbekannt'); }); // Add overall ones overallInsts.forEach((inst: TopInstitutionItem) => { - if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unknown'); + if (inst.id) + uniqueInsts.set(inst.id, inst.display_name || 'Unbekannt'); }); const list = Array.from(uniqueInsts.entries()).map(([id, name]) => ({ @@ -329,6 +344,11 @@ export class UniTrendParentComponent implements OnInit { })); this.comparisonInstitutions.set(list); this.isSuggestionsLoading.set(false); + + // Auto-fetch trend data on first load if we don't have it yet + if (!this.rawTrendResponse()) { + this.fetchTrendData(); + } }, error: (err: any) => { console.error('Failed to load default institutions dynamically:', err); @@ -340,13 +360,13 @@ export class UniTrendParentComponent implements OnInit { // Fetch recommended institutions for comparison based on current topics loadTrendSuggestions() { this.isSuggestionsLoading.set(true); - const topics = this.selectedTrendTopics(); const topic = - topics.length > 0 - ? topics[0] + this.activeChartTopic() || + (this.selectedTrendTopics().length > 0 + ? this.selectedTrendTopics()[0] : this.keywords().length > 0 ? this.keywords()[0] - : 'Artificial Intelligence'; + : 'Artificial Intelligence'); const countryFilter = this.comparisonCountries().length > 0 -- 2.56.1 From e9ba8741030ad60f8a388aac7815c34c13a0432e Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 6 Jul 2026 10:46:36 +0200 Subject: [PATCH 10/13] regenerated frontend service --- .../src/app/api/model/topInstitutionItem.ts | 1 - webapp/src/app/api/model/topicYearlyData.ts | 1 + .../uni-trend-parent.component.scss | 109 ++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/api/model/topInstitutionItem.ts b/webapp/src/app/api/model/topInstitutionItem.ts index 827fe6df..a98f52b8 100644 --- a/webapp/src/app/api/model/topInstitutionItem.ts +++ b/webapp/src/app/api/model/topInstitutionItem.ts @@ -16,6 +16,5 @@ export interface TopInstitutionItem { type?: string | null; lineage?: Array | null; works_count?: number | null; - image_thumbnail_url?: string | null; exact_topic_count?: number | null; } diff --git a/webapp/src/app/api/model/topicYearlyData.ts b/webapp/src/app/api/model/topicYearlyData.ts index 15e4c59a..a1fdbdc2 100644 --- a/webapp/src/app/api/model/topicYearlyData.ts +++ b/webapp/src/app/api/model/topicYearlyData.ts @@ -12,5 +12,6 @@ export interface TopicYearlyData { year: number; raw: number; normalized: number; + cumulative: number; institutions_count: number; } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 7e2eda37..92d2ed52 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -447,3 +447,112 @@ box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } } + +.suggestions-below-card { + background: white; + border-radius: 10px; + padding: 1.25rem; + border: 1px solid #e5e7eb; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); + margin-top: 1rem; + + h3 { + font-size: 0.875rem; + font-weight: 600; + color: #374151; + margin: 0 0 1rem 0; + } + + .suggestions-loader { + display: flex; + align-items: center; + gap: 0.5rem; + color: #6b7280; + font-size: 0.8125rem; + padding: 1rem 0; + + .spinner-small { + width: 16px; + height: 16px; + border: 2px solid rgba(59, 130, 246, 0.1); + border-radius: 50%; + border-top-color: #3b82f6; + animation: spin 0.8s linear infinite; + } + } + + .no-suggestions-msg { + font-size: 0.8125rem; + color: #6b7280; + text-align: center; + padding: 1rem 0; + } + + .suggestions-flex { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 0.75rem; + } +} + +.suggestion-item-horizontal { + display: flex; + align-items: center; + gap: 0.75rem; + background: #f9fafb; + border: 1px solid #e5e7eb; + border-radius: 8px; + padding: 0.6rem 0.8rem; + text-align: left; + cursor: pointer; + transition: all 0.2s ease; + width: 100%; + box-sizing: border-box; + + &:hover:not([disabled]) { + border-color: #3b82f6; + background: #f0f9ff; + transform: translateY(-1px); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); + } + + &[disabled] { + opacity: 0.5; + cursor: not-allowed; + background: #f3f4f6; + } + + .add-icon { + font-size: 1.1rem; + color: #3b82f6; + font-weight: bold; + display: flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: 50%; + background: rgba(59, 130, 246, 0.1); + flex-shrink: 0; + } + + .info { + display: flex; + flex-direction: column; + overflow: hidden; + + .name { + font-size: 0.8125rem; + color: #374151; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-weight: 600; + } + .meta { + font-size: 0.7rem; + color: #6b7280; + margin-top: 2px; + } + } +} -- 2.56.1 From 4461b26270b707f49fc82bb0df0c481cf907bd8f Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 6 Jul 2026 11:22:33 +0200 Subject: [PATCH 11/13] changed icons, to match the project icons --- .../uni-trend-chart.component.html | 7 ++- .../uni-trend-chart.component.ts | 3 +- .../uni-trend-parent.component.html | 33 +++++++------ .../uni-trend-parent.component.scss | 47 +++++++++++++++++-- 4 files changed, 70 insertions(+), 20 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html index a908dda2..60e763bc 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html @@ -7,7 +7,12 @@ class="trend-chart-render">
    } @else {
    -
    📊
    +
    + bar_chart +

    Keine Trenddaten verfügbar

    Bitte wählen Sie mindestens ein Thema und Einrichtungen oder Regionen im diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 07757b0c..9056e335 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -6,13 +6,14 @@ import { } from '@angular/core'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; +import { MatIconModule } from '@angular/material/icon'; import { TrendResponse, TrendSeries, TopicYearlyData } from '../../../api'; @Component({ selector: 'app-uni-trend-chart', templateUrl: './uni-trend-chart.component.html', styleUrl: './uni-trend-chart.component.scss', - imports: [NgxEchartsDirective], + imports: [NgxEchartsDirective, MatIconModule], changeDetection: ChangeDetectionStrategy.OnPush, }) export class UniTrendChartComponent { 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 df4c6f45..6df126cd 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 @@ -52,23 +52,27 @@ ) { @for (c of comparisonCountries(); track c.id) {

    - 🏳️ {{ c.name }} + flag {{ c.name }}
    } @for (r of comparisonRegions(); track r.id) {
    - 🌍 {{ r.name }} + public {{ r.name }}
    } @@ -119,13 +123,13 @@ @for (inst of comparisonInstitutions(); track inst.id) {
    🏫 {{ inst.name }}apartment {{ inst.name }}
    } @@ -169,7 +173,8 @@ [class.dirty]="isDirty()" [disabled]="isTrendLoading() || selectedTrendTopics().length === 0" (click)="fetchTrendData()"> - 🔍 {{ isDirty() ? 'Änderungen übernehmen' : 'Trend suchen' }} + search + {{ isDirty() ? 'Änderungen übernehmen' : 'Trend suchen' }}
    @@ -183,19 +188,19 @@ [class.active]="chartMode() === 'normalized'" (click)="setChartMode('normalized')" title="Normiert das Publikationsvolumen auf [0,1], um die Form von Wachstumstrends zu vergleichen."> - 📉 Normierte Skala + trending_down Normierte Skala
    @@ -213,7 +218,7 @@ } @@ -255,14 +260,12 @@ ? comparisonInstitutions().some((i) => i.id === item.id) : false) || primaryInstitution() === item.id "> - + + add
    {{ item.display_name }} {{ item.country_code }} • - {{ - item.exact_topic_count?.toLocaleString() - }} + {{ item.exact_topic_count?.toLocaleString() }} Publikationen
    diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss index 92d2ed52..68ec8b97 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -87,12 +87,21 @@ padding: 0.3rem 0.5rem; .item-name { + display: inline-flex; + align-items: center; + gap: 4px; font-size: 0.75rem; color: #374151; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } } .remove-btn { @@ -100,9 +109,18 @@ border: none; color: #9ca3af; cursor: pointer; - font-size: 0.7rem; padding: 1px 4px; border-radius: 3px; + display: inline-flex; + align-items: center; + justify-content: center; + + mat-icon { + font-size: 12px; + width: 12px; + height: 12px; + } + &:hover { color: #ef4444; background: #fee2e2; @@ -286,6 +304,15 @@ color: #4b5563; border-radius: 5px; cursor: pointer; + display: inline-flex; + align-items: center; + gap: 6px; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } &:hover:not(.active) { color: #111827; @@ -325,6 +352,15 @@ font-weight: 500; cursor: pointer; transition: all 0.15s ease; + display: inline-flex; + align-items: center; + gap: 4px; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } &:hover { border-color: #3b82f6; @@ -391,6 +427,12 @@ color: white; transition: all 0.2s ease; + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } + &:hover:not([disabled]) { background-color: #2563eb; border-color: #2563eb; @@ -523,9 +565,7 @@ } .add-icon { - font-size: 1.1rem; color: #3b82f6; - font-weight: bold; display: flex; align-items: center; justify-content: center; @@ -534,6 +574,7 @@ border-radius: 50%; background: rgba(59, 130, 246, 0.1); flex-shrink: 0; + font-size: 14px; } .info { -- 2.56.1 From 86bced4940e80ef51aa453418cad1d870f6af08f Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 6 Jul 2026 11:32:31 +0200 Subject: [PATCH 12/13] fixed diagramm tooltip cutoff --- .../uni-trend-chart/uni-trend-chart.component.ts | 9 ++++++--- .../uni-trend-parent/uni-trend-parent.component.html | 11 ++++++----- .../uni-trend-parent/uni-trend-parent.component.ts | 7 +++++++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 9056e335..8dfdc67b 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -171,6 +171,7 @@ export class UniTrendChartComponent { }, tooltip: { trigger: 'axis', + enterable: true, backgroundColor: 'rgba(255, 255, 255, 0.98)', borderColor: '#e5e7eb', borderWidth: 1, @@ -186,9 +187,10 @@ export class UniTrendChartComponent { if (!params || params.length === 0) return ''; const yearNum = parseInt(params[0].name, 10); - let res = `
    `; + let res = `
    `; res += `Jahr: ${yearNum}`; res += `
    `; + res += `
    `; trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { const color = getEntityColor(entityIdx); @@ -303,7 +305,7 @@ export class UniTrendChartComponent { res += `${entity.entity_name}`; res += `
    `; - res += ``; + res += `
    `; res += ``; res += ``; res += ``; @@ -321,7 +323,8 @@ export class UniTrendChartComponent { } }); - res += ``; + res += ``; // closes scrollable div + res += ``; // closes main wrapper return res; }, }, 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 6df126cd..69c6a181 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 @@ -215,11 +215,12 @@ @if (selectedTrendTopics().length > 1) {
    @for (topic of selectedTrendTopics(); track topic) { - + + }
    } 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 154437de..7d38908b 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 @@ -33,6 +33,8 @@ import { UniversityRankingsService, InstitutionsService, } from '../../../api'; +import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; +import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; export interface CompareItem { id: string; @@ -54,6 +56,7 @@ export interface CompareItem { MatIconModule, MatProgressSpinnerModule, MatAutocompleteModule, + TopicChipComponent, ], templateUrl: './uni-trend-parent.component.html', styleUrl: './uni-trend-parent.component.scss', @@ -98,6 +101,10 @@ export class UniTrendParentComponent implements OnInit { readonly topSuggestions = signal([]); readonly isSuggestionsLoading = signal(false); + getTopicColor(topic: string): string { + return topicHierarchyColor({ name: topic }); + } + // Autocomplete UI state readonly searchQuery = signal(''); readonly searchResults = signal([]); -- 2.56.1 From 9f03c92bc1dc9a377bfef6eaa31fd871366bc108 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Mon, 6 Jul 2026 11:35:53 +0200 Subject: [PATCH 13/13] updated old code to remove warnings --- .../keywords-search.component.ts | 16 ++-- .../uni-trend-parent.component.ts | 81 +++++++++---------- 2 files changed, 45 insertions(+), 52 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 2697f79b..a4442326 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -75,6 +75,13 @@ type KeywordView = 'llm' | 'topic'; styleUrl: './keywords-search.component.scss', }) export class KeywordsSearchComponent { + private readonly formBuilder = inject(FormBuilder); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly destroyRef = inject(DestroyRef); + private readonly websocketService = inject(KeywordWebSocketService); + private readonly topicsService = inject(TopicsService); + readonly form = this.formBuilder.nonNullable.group({ selectedInputType: 'url' as InputMode, urlInput: '', @@ -150,14 +157,7 @@ export class KeywordsSearchComponent { return buildTopicLegendGroups(topics); } - constructor( - private readonly formBuilder: FormBuilder, - private readonly route: ActivatedRoute, - private readonly router: Router, - private readonly destroyRef: DestroyRef, - private readonly websocketService: KeywordWebSocketService, - private readonly topicsService: TopicsService, - ) { + constructor() { this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => { if (this.isOwnNavigation) { // This emission is just the router confirming the navigation we 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 7d38908b..2aa8650c 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 @@ -43,7 +43,6 @@ export interface CompareItem { @Component({ selector: 'app-uni-trend-parent', - standalone: true, imports: [ CommonModule, FormsModule, @@ -195,55 +194,49 @@ export class UniTrendParentComponent implements OnInit { } // Effect: automatically sync checkboxes list whenever input keywords change - effect( - () => { - const kws = this.keywords(); - const currentSelections = untracked(() => this.selectedTrendTopics()); - const currentActive = untracked(() => this.activeChartTopic()); + effect(() => { + const kws = this.keywords(); + const currentSelections = untracked(() => this.selectedTrendTopics()); + const currentActive = untracked(() => this.activeChartTopic()); - if (kws.length > 0) { - // Find existing selections that are still in keywords, or default to all - const validSelections = currentSelections.filter((t: string) => - kws.includes(t), - ); - if (validSelections.length > 0) { - this.selectedTrendTopics.set(validSelections); - } else { - this.selectedTrendTopics.set(kws); - } - - // Initialize active chart topic to the first selected topic if empty or invalid - const active = currentActive; - const updatedSelections = untracked(() => this.selectedTrendTopics()); - if (!active || !updatedSelections.includes(active)) { - this.activeChartTopic.set(updatedSelections[0] || ''); - } - - // If comparison list is empty, initialize default institutions dynamically - const currentInsts = untracked(() => this.comparisonInstitutions()); - if (currentInsts.length === 0) { - untracked(() => this.initializeDefaultInstitutions()); - } + if (kws.length > 0) { + // Find existing selections that are still in keywords, or default to all + const validSelections = currentSelections.filter((t: string) => + kws.includes(t), + ); + if (validSelections.length > 0) { + this.selectedTrendTopics.set(validSelections); } else { - this.selectedTrendTopics.set([]); + this.selectedTrendTopics.set(kws); } - }, - { allowSignalWrites: true }, - ); + + // Initialize active chart topic to the first selected topic if empty or invalid + const active = currentActive; + const updatedSelections = untracked(() => this.selectedTrendTopics()); + if (!active || !updatedSelections.includes(active)) { + this.activeChartTopic.set(updatedSelections[0] || ''); + } + + // If comparison list is empty, initialize default institutions dynamically + const currentInsts = untracked(() => this.comparisonInstitutions()); + if (currentInsts.length === 0) { + untracked(() => this.initializeDefaultInstitutions()); + } + } else { + this.selectedTrendTopics.set([]); + } + }); // Effect: load suggestions when topic or location filters change - effect( - () => { - const topic = this.activeChartTopic(); - const countries = this.comparisonCountries(); - const regions = this.comparisonRegions(); + effect(() => { + const topic = this.activeChartTopic(); + const countries = this.comparisonCountries(); + const regions = this.comparisonRegions(); - untracked(() => { - this.loadTrendSuggestions(); - }); - }, - { allowSignalWrites: true }, - ); + untracked(() => { + this.loadTrendSuggestions(); + }); + }); // Handle initialization and synchronization of URL state this.route.queryParams.subscribe((params) => { -- 2.56.1
    • Publikationen:${rawCount.toLocaleString()}${contributionStr}
    • Normiert (0-1):${normVal}
    • Kumuliert:${cumVal.toLocaleString()}