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