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/model.py b/service/src/main/inse/model.py index 222d9603..f360fd31 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/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/logic.py b/service/src/main/inse/university_ranking/logic.py index 10d926ff..2f368665 100644 --- a/service/src/main/inse/university_ranking/logic.py +++ b/service/src/main/inse/university_ranking/logic.py @@ -1,65 +1,228 @@ 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("https://openalex.org/"): + 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 + + 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": [ - { - "match_phrase": { - "topics.display_name": topic - } - }, - { - "term": { - "geo.country_code": "DE" - } - } - ] + "filter": [ + {"term": {"type": "education"}}, + {"term": {"geo.country_code": "DE"}}, + topic_filter + ] } } - - # 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 display name keyword) + 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 in Filter Context + works_query = { + "bool": { + "filter": [ + { + "range": { + "publication_year": { + "gte": START_YEAR, + "lte": END_YEAR + } + } + }, + topic_clause, + { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [inst["id"] for inst in top_10] + } + } + } + } + ] + } + } + + 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 1b4b8605..18a2fb32 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 +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): @@ -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 + cumulative: 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 + 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 deleted file mode 100644 index 60c52c9d..00000000 --- a/service/src/main/inse/university_ranking/router.py +++ /dev/null @@ -1,23 +0,0 @@ -from fastapi import APIRouter, Query -from . import service -from .model import RankingResponse, ResearchTopic, DashboardMetric -from inse.tags import Tags - -router = APIRouter( - prefix="/api/inse-service/university-rankings", - tags=[Tags.INSTITUTIONS] -) - -@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) \ 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 new file mode 100644 index 00000000..8e1365d7 --- /dev/null +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -0,0 +1,656 @@ +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 +from inse.model import ESIndex +from inse.auth.model import AccessToken, Organization +from .model import ( + TrendResponse, + TrendSeries, + TopicYearlyData, + TopInstitutionItem, + 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 (Idea: Instead of wildcard: use alternative names?) + 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, + 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) + return [] + + results = [] + + # 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=code_val, + display_name=source["display_name"], + code=code_val, + type="continent" + )) + + # Process countries + for hit in countries_res.get("hits", {}).get("hits", []): + source = hit["_source"] + results.append(AutocompleteLocationItem( + id=source["country_code"], + display_name=source["display_name"], + code=source["country_code"], + type="country" + )) + + return results + + + +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.upper()] + elif 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"}}, + topic_filter + ] + + if country_codes: + must_clauses.append({"terms": {"geo.country_code": country_codes}}) + + query = {"bool": {"filter": 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, + source=["id", "display_name", "country_code", "works_count", "topics"], + 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") + + # 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, + 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[str], + 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=[]) + + import asyncio + + 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 = [i.strip() for i in institutions] + if primary_inst_id not in query_institutions: + query_institutions.insert(0, primary_inst_id) + + # 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)) + + # 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: + 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 res.get("hits", {}).get("hits", []): + source = hit["_source"] + 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 + + async def fetch_countries(): + names = {} + if not clean_countries: + return names + try: + 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 res.get("hits", {}).get("hits", []): + source = hit["_source"] + names[source["country_code"]] = source["display_name"] + except Exception as e: + logger.warning("Failed to resolve country names from ES: %s", e) + return names + + async def fetch_continents(): + names = {} + ccodes = {} + if not clean_regions: + return names, ccodes + try: + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_CONTINENTS), + query={ + "bool": { + "should": [ + {"terms": {"wikidata_id.keyword": clean_regions}}, + {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}} + ] + } + }, + size=len(clean_regions), + source=["id", "display_name", "wikidata_id", "countries"], + cluster="nes" + ) + for hit in res.get("hits", {}).get("hits", []): + source = hit["_source"] + c_code = source.get("wikidata_id") or source["id"].split("/")[-1] + 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]] = {} + + # 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 + + # 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 + filter_clauses = [ + { + "range": { + "publication_year": { + "gte": start_year, + "lte": end_year + } + } + }, + { + "bool": { + "should": topic_clauses, + "minimum_should_match": 1 + } + } + ] + if entity_should_clauses: + filter_clauses.append({ + "bool": { + "should": entity_should_clauses, + "minimum_should_match": 1 + } + }) + + query = { + "bool": { + "filter": filter_clauses + } + } + + # 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) + + # 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] = [] + + 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] = [] + + 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=count, + normalized=norm_vals[idx], + cumulative=cum_vals[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) + diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index f9ac2e32..16c53b86 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/rankingResponse.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 8ea55e0b..673b93bb 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -24,6 +24,8 @@ 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 const APIS = [ @@ -40,5 +42,6 @@ export const APIS = [ PersonsService, ProjectsService, TopicsService, + UniversityRankingsService, WorksService, ]; diff --git a/webapp/src/app/api/api/institutions.service.ts b/webapp/src/app/api/api/institutions.service.ts index 8b27a539..b837e00e 100644 --- a/webapp/src/app/api/api/institutions.service.ts +++ b/webapp/src/app/api/api/institutions.service.ts @@ -32,8 +32,6 @@ 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'; @@ -295,142 +293,6 @@ export class InstitutionsService extends BaseService { ); } - /** - * 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 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 list of OpenAlex institutions. * @endpoint get /api/inse-service/institutions diff --git a/webapp/src/app/api/api/universityRankings.service.ts b/webapp/src/app/api/api/universityRankings.service.ts new file mode 100644 index 00000000..4ed6111d --- /dev/null +++ b/webapp/src/app/api/api/universityRankings.service.ts @@ -0,0 +1,578 @@ +/** + * 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. + */ +/* 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 { AutocompleteLocationItem } from '../model/autocompleteLocationItem'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { RankingResponse } from '../model/rankingResponse'; +// @ts-ignore +import { TopInstitutionItem } from '../model/topInstitutionItem'; +// @ts-ignore +import { TrendResponse } from '../model/trendResponse'; + +// @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); + } + + /** + * 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: 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, + 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'; + 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 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>; + 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, + 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'; + 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; + 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 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?: { + 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((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']); + 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/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, + }, + ); + } +} diff --git a/webapp/src/app/api/model/autocompleteLocationItem.ts b/webapp/src/app/api/model/autocompleteLocationItem.ts new file mode 100644 index 00000000..b07e699e --- /dev/null +++ b/webapp/src/app/api/model/autocompleteLocationItem.ts @@ -0,0 +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: 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 3bf537d5..a99176b9 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 './rankingResponse'; 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'; diff --git a/webapp/src/app/api/model/topInstitutionItem.ts b/webapp/src/app/api/model/topInstitutionItem.ts new file mode 100644 index 00000000..a98f52b8 --- /dev/null +++ b/webapp/src/app/api/model/topInstitutionItem.ts @@ -0,0 +1,20 @@ +/** + * 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 { + id?: string | null; + display_name?: string | null; + ror?: string | null; + country_code?: string | null; + type?: string | null; + lineage?: Array | null; + works_count?: number | 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..a1fdbdc2 --- /dev/null +++ b/webapp/src/app/api/model/topicYearlyData.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface TopicYearlyData { + year: number; + raw: number; + normalized: number; + cumulative: number; + institutions_count: number; +} diff --git a/webapp/src/app/api/model/trendResponse.ts b/webapp/src/app/api/model/trendResponse.ts new file mode 100644 index 00000000..e6b291c9 --- /dev/null +++ b/webapp/src/app/api/model/trendResponse.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. + */ +import { TrendSeries } from './trendSeries'; + +export interface TrendResponse { + series: Array; + years: Array; + location_mappings?: { [key: string]: Array } | null; +} 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 f5436445..3bf43088 100644 --- a/webapp/src/app/api/model/universityTopicData.ts +++ b/webapp/src/app/api/model/universityTopicData.ts @@ -8,18 +8,10 @@ * Do not edit the class manually. */ import { YearlyData } from './yearlyData'; +import { Topic } from './topic'; export interface UniversityTopicData { university: string; - topic: UniversityTopicData.TopicEnum; + 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]; -} 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 ef967b09..53af9fad 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,21 +17,20 @@ 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'; + selectedTopic: ResearchTopic = 'Quantum Computing'; metric: DashboardMetric = 'publications'; rawDataSource: UniversityTopicData[] = []; 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/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index dbb9f941..e313d794 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -384,8 +384,8 @@
- -
+ +
+ +
+ } + + + @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 4870cd4b..a4442326 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -22,6 +22,8 @@ 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'; + import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component'; import { Topic } from '../../api/model/topic'; @@ -60,6 +62,7 @@ type KeywordView = 'llm' | 'topic'; MatExpansionModule, MatProgressBarModule, TopicAutocompleteComponent, + UniTrendParentComponent, TopicChipComponent, TopicLegendComponent, MatButtonToggleModule, @@ -72,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: '', @@ -104,6 +114,7 @@ export class KeywordsSearchComponent { readonly isExtracting = signal(false); readonly loadingNewKeyword = signal(false); readonly extractionSource = signal(null); + readonly showVisualization = signal(false); readonly keywordsExist = computed( () => @@ -146,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 @@ -548,6 +552,7 @@ export class KeywordsSearchComponent { } search(): void { + this.showVisualization.set(false); const payload = { extractedKeywords: this.getSelectedExtractedKeywordEntries(), manualKeywords: this.getSelectedManualKeywordEntries(), @@ -559,6 +564,10 @@ export class KeywordsSearchComponent { // this.router.navigate(['/search'], { state: payload }); } + visualize(): void { + this.showVisualization.set(true); + } + // --- Helpers -------------------------------------------------------------- private applyExtractedKeywords(keywords: ExtractedKeywords): void { @@ -818,6 +827,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), @@ -953,6 +964,7 @@ export class KeywordsSearchComponent { seenKeywords.add(normalized); uniqueValues.push(value.trim()); } + return uniqueValues; } 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 ece71b78..00000000 --- a/webapp/src/app/modules/university-ranking/services/uni-ranking-service.ts +++ /dev/null @@ -1,29 +0,0 @@ -// 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'; -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); - - /** - * 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.apiService.getRankingsApiInseServiceUniversityRankingsGet( - topic, - metric, - ); - } -} 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..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,5 +1,5 @@
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-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..60e763bc --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.html @@ -0,0 +1,23 @@ +
+ @if (data() && data()!.series && data()!.series.length > 0) { +
+ } @else { +
+
+ bar_chart +
+

Keine Trenddaten verfügbar

+

+ 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.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..8dfdc67b --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -0,0 +1,457 @@ +import { + Component, + ChangeDetectionStrategy, + input, + computed, +} 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, MatIconModule], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class UniTrendChartComponent { + // Input signals following Angular v21 standards + readonly data = input(null); + readonly mode = input<'normalized' | 'total' | 'cumulative'>('normalized'); + readonly activeTopic = input(null); + readonly startYear = input(2010); + readonly endYear = input(2025); + + // 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 + '#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 = getEntityColor(entityIdx); + const yrTopicData = entity.topic_data[selectedTopic] || []; + + // 1. Add line series for the currently selected topic (placed in Grid 0) + const lineData = years.map((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; + }); + + 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: { + width: 2.5, + color: color, + }, + itemStyle: { + color: color, + }, + emphasis: { + focus: 'series', + lineStyle: { width: 3.5 }, + }, + }); + + // 2. Add YoY growth volume bars for the selected topic (placed in Grid 1) + const bars = years.map((year) => { + const yrData = yrTopicData.find((y) => y.year === year); + const val = yrData ? yrData.raw : 0; + + // 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({ + name: `${entity.entity_name} (YoY Wachstum)`, + type: 'bar', + xAxisIndex: 1, + yAxisIndex: 1, + data: bars, + 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' + ? 'Normierte Skala (0 - 1)' + : currentMode === 'cumulative' + ? 'Kumulierte Publikationen' + : 'Publikationsvolumen'; + + return { + title: { + text: `Publikationstrends: ${selectedTopic}`, + left: 'left', + textStyle: { + fontSize: 16, + fontWeight: 600, + color: '#1f2937', + }, + }, + tooltip: { + trigger: 'axis', + enterable: true, + backgroundColor: 'rgba(255, 255, 255, 0.98)', + borderColor: '#e5e7eb', + borderWidth: 1, + 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: 11, + }, + formatter: (params: any) => { + if (!params || params.length === 0) return ''; + const yearNum = parseInt(params[0].name, 10); + + let res = `
`; + res += `Jahr: ${yearNum}`; + res += `
`; + res += `
`; + + trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { + const color = getEntityColor(entityIdx); + 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); + }); + + const yrData = yrTopicData.find( + (y: TopicYearlyData) => y.year === yearNum, + ); + if (yrData) { + const rawCount = yrData.raw; + const normVal = yrData.normalized.toFixed(2); + const cumVal = cumulativeSumMap.get(yearNum) || 0; + + // YoY growth + const prevYrData = yrTopicData.find( + (y) => y.year === yearNum - 1, + ); + const prevRawCount = prevYrData ? prevYrData.raw : 0; + const yoyGrowth = rawCount - prevRawCount; + + let contributionStr = ''; + 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 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, + ); + return sum + (y ? y.raw : 0); + }, 0); + if (sumInsts > 0) { + const pct = (yrData.raw / sumInsts) * 100; + contributionStr = ` (${pct.toFixed(1)} % der verglichenen Inst.)`; + } + } + } + + 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 += `
`; // closes scrollable div + res += `
`; // closes main wrapper + return res; + }, + }, + legend: { + 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' }], + label: { backgroundColor: '#777' }, + }, + grid: [ + { + left: 80, + right: 220, + top: 80, + height: 230, + }, + { + left: 80, + right: 220, + top: 360, + height: 70, + }, + ], + 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, + 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: false, + gridIndex: 1, + splitNumber: 2, + axisLabel: { + show: true, + color: '#6b7280', + fontSize: 9, + formatter: (value: number) => { + return value > 0 ? `+${value}` : `${value}`; + }, + }, + axisLine: { show: false }, + axisTick: { show: false }, + splitLine: { + show: true, + lineStyle: { + color: '#e5e7eb', + type: 'dashed', + }, + }, + }, + ], + toolbox: { + left: 'right', + top: 'top', + feature: { + saveAsImage: { title: 'Speichern' }, + }, + }, + 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, + }; + }); +} 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..69c6a181 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -0,0 +1,281 @@ +
+ + + + +
+
+ Visualisierungsskala: +
+ + + +
+
+ +
+ @if (isTrendLoading()) { +
+
+

Trenddaten werden aus dem Publikationsverzeichnis abgerufen...

+
+ } + @if (selectedTrendTopics().length > 1) { +
+ @for (topic of selectedTrendTopics(); track topic) { + + + } +
+ } + +
+ + +
+

+ 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.scss b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss new file mode 100644 index 00000000..68ec8b97 --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.scss @@ -0,0 +1,599 @@ +.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 { + 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 { + background: none; + border: none; + color: #9ca3af; + cursor: pointer; + 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; + } + } + + &.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; + display: inline-flex; + align-items: center; + gap: 6px; + + mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + + &: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; + display: inline-flex; + align-items: center; + gap: 4px; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + + &: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; + + mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } + + &: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); + } +} + +.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 { + color: #3b82f6; + 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; + font-size: 14px; + } + + .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; + } + } +} 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..2aa8650c --- /dev/null +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -0,0 +1,604 @@ +import { + Component, + ChangeDetectionStrategy, + input, + computed, + signal, + effect, + untracked, + inject, + OnInit, +} from '@angular/core'; +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, + TrendSeries, + TopicYearlyData, + TopInstitutionItem, + AutocompleteLocationItem, + AutocompleteResponse, + AutocompleteResponseResultsInner, + 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; + name: string; +} + +@Component({ + selector: 'app-uni-trend-parent', + imports: [ + CommonModule, + FormsModule, + UniTrendChartComponent, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + MatCheckboxModule, + MatButtonModule, + MatIconModule, + MatProgressSpinnerModule, + MatAutocompleteModule, + TopicChipComponent, + ], + 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( + 'Universität Duisburg-Essen', + ); + readonly comparisonInstitutions = signal([]); + readonly comparisonCountries = signal([ + { id: 'DE', name: 'Deutschland' }, + ]); + 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([]); + readonly fetchedCountries = signal([]); + readonly fetchedRegions = signal([]); + + // Results & Loading signals + readonly rawTrendResponse = signal(null); + readonly isTrendLoading = signal(false); + readonly topSuggestions = signal([]); + readonly isSuggestionsLoading = signal(false); + + getTopicColor(topic: string): string { + return topicHierarchyColor({ name: topic }); + } + + // 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: CompareItem) => i.id.toLowerCase()), + ); + const currentCountryIds = new Set( + this.comparisonCountries().map((c: CompareItem) => c.id.toLowerCase()), + ); + const currentRegionIds = new Set( + this.comparisonRegions().map((r: CompareItem) => r.id.toLowerCase()), + ); + const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase(); + + const filteredSeries = raw.series.filter((s: TrendSeries) => { + 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: CompareItem) => i.id) + .sort() + .join(','); + const currentInsts = this.comparisonInstitutions() + .map((i: CompareItem) => i.id) + .sort() + .join(','); + if (fetchedInsts !== currentInsts) return true; + + const fetchedC = this.fetchedCountries() + .map((c: CompareItem) => c.id) + .sort() + .join(','); + const currentC = this.comparisonCountries() + .map((c: CompareItem) => c.id) + .sort() + .join(','); + if (fetchedC !== currentC) return true; + + const fetchedR = this.fetchedRegions() + .map((r: CompareItem) => r.id) + .sort() + .join(','); + const currentR = this.comparisonRegions() + .map((r: CompareItem) => 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(); + 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()); + } + } 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(); + + untracked(() => { + this.loadTrendSuggestions(); + }); + }); + + // 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: string) => { + 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: string) => { + 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: string) => { + 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']); + } + }); + } + + ngOnInit() { + 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 || 'Unbekannt'); + }); + + // Add overall ones + overallInsts.forEach((inst: TopInstitutionItem) => { + if (inst.id) + uniqueInsts.set(inst.id, inst.display_name || 'Unbekannt'); + }); + + const list = Array.from(uniqueInsts.entries()).map(([id, name]) => ({ + id, + name, + })); + 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); + this.isSuggestionsLoading.set(false); + }, + }); + } + + // Fetch recommended institutions for comparison based on current topics + loadTrendSuggestions() { + this.isSuggestionsLoading.set(true); + const topic = + this.activeChartTopic() || + (this.selectedTrendTopics().length > 0 + ? this.selectedTrendTopics()[0] + : this.keywords().length > 0 + ? this.keywords()[0] + : 'Artificial Intelligence'); + + const countryFilter = + this.comparisonCountries().length > 0 + ? this.comparisonCountries()[0].id + : undefined; + const regionFilter = + this.comparisonRegions().length > 0 + ? this.comparisonRegions()[0].id + : undefined; + + this.apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + topic, + regionFilter, + countryFilter, + 6, + ) + .subscribe({ + next: (res: any) => { + 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: CompareItem) => i.id), + this.comparisonCountries().map((c: CompareItem) => c.id), + this.comparisonRegions().map((r: CompareItem) => r.id), + ) + .subscribe({ + next: (response: TrendResponse) => { + 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: CompareItem) => `${i.id}|${i.name}`, + ) + : null, + countries: + this.comparisonCountries().length > 0 + ? this.comparisonCountries().map( + (c: CompareItem) => `${c.id}|${c.name}`, + ) + : null, + regions: + this.comparisonRegions().length > 0 + ? this.comparisonRegions().map( + (r: CompareItem) => `${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: string) => 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: CompareItem) => 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: CompareItem) => i.id !== id), + ); + } + + // Add country or region + addLocation(loc: AutocompleteLocationItem) { + if (loc.type === 'country') { + const current = this.comparisonCountries(); + if (!current.some((c: CompareItem) => 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: CompareItem) => 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: CompareItem) => c.id !== id), + ); + } else if (type === 'continent') { + const current = this.comparisonRegions(); + this.comparisonRegions.set( + current.filter((r: CompareItem) => r.id !== id), + ); + } + this.loadTrendSuggestions(); + } + + // Scaling mode toggle (data reuses instantly) + setChartMode(mode: 'normalized' | 'total' | 'cumulative') { + 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: AutocompleteResponse) => { + 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: AutocompleteLocationItem[]) => { + this.locationSearchResults.set(res || []); + }, + error: () => { + this.locationSearchResults.set([]); + }, + }); + } else { + this.locationSearchResults.set([]); + } + } +}