From d32f3f7c7b1d011b51ae13366c34689ca92b35ae Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 8 Jul 2026 13:44:20 +0200 Subject: [PATCH 01/50] add ranking endpoint for author --- service/src/main/inse/main.py | 2 ++ service/src/main/inse/ranking/__init__.py | 0 service/src/main/inse/ranking/model.py | 16 ++++++++++++++++ service/src/main/inse/ranking/router.py | 19 +++++++++++++++++++ service/src/main/inse/tags.py | 1 + 5 files changed, 38 insertions(+) create mode 100644 service/src/main/inse/ranking/__init__.py create mode 100644 service/src/main/inse/ranking/model.py create mode 100644 service/src/main/inse/ranking/router.py diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 24969bb8..bbe693f5 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -24,6 +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.ranking.router import router as ranking_router from inse.university_ranking.service import router as university_ranking_router # caching @@ -90,6 +91,7 @@ app.include_router(news_service_router) app.include_router(company_connections_router) app.include_router(patents_service_router) app.include_router(university_ranking_router) +app.include_router(ranking_router) app.include_router(projects_router) app.include_router(patents_all_router) app.include_router(keywords_service_router) diff --git a/service/src/main/inse/ranking/__init__.py b/service/src/main/inse/ranking/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py new file mode 100644 index 00000000..d46a0d24 --- /dev/null +++ b/service/src/main/inse/ranking/model.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Data models for author ranking. +""" +from typing import List + +from pydantic import BaseModel, Field + + +class RankAuthorRequest(BaseModel): + author_id: str = Field(description="The OpenAlex ID of the author to rank.") + keywords: List[str] = Field( + min_length=1, + description="One or more keywords to rank the author by.", + ) diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py new file mode 100644 index 00000000..ad933640 --- /dev/null +++ b/service/src/main/inse/ranking/router.py @@ -0,0 +1,19 @@ +import logging + +from fastapi import APIRouter + +from inse.tags import Tags +from .model import RankAuthorRequest + +logger = logging.getLogger(__name__) + +router = APIRouter( + prefix="/api/rank", + tags=[Tags.RANKING], +) + + +@router.post("/rank-author") +async def rank_author(request: RankAuthorRequest): + logger.info("rank-author author_id=%s keywords=%s", request.author_id, request.keywords) + return {"status": "ok"} diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 1b25c312..58b2a0e6 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -13,3 +13,4 @@ class Tags(StrEnum): ACCOUNT = "Account" ORGANIZATION = "Organization" UNIVERSITY_RANKINGS = "University Rankings" + RANKING = "Ranking" -- 2.56.1 From 275a6e1948e54f0a86770df487f9408648335684 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 8 Jul 2026 13:58:51 +0200 Subject: [PATCH 02/50] remove authors and add operator --- service/src/main/inse/ranking/model.py | 22 ++++- service/src/main/inse/ranking/ranking.http | 106 +++++++++++++++++++++ service/src/main/inse/ranking/router.py | 6 +- 3 files changed, 128 insertions(+), 6 deletions(-) create mode 100644 service/src/main/inse/ranking/ranking.http diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index d46a0d24..a532e161 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -3,14 +3,30 @@ """ Data models for author ranking. """ +from enum import StrEnum from typing import List -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator -class RankAuthorRequest(BaseModel): - author_id: str = Field(description="The OpenAlex ID of the author to rank.") +class KeywordOperator(StrEnum): + AND = "and" + OR = "or" + + +class KeywordToAuthorRequest(BaseModel): keywords: List[str] = Field( min_length=1, description="One or more keywords to rank the author by.", ) + operator: KeywordOperator = Field( + default=KeywordOperator.AND, + description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", + ) + + @field_validator("operator", mode="before") + @classmethod + def operator_case_insensitive(cls, value): + if isinstance(value, str): + return value.lower() + return value diff --git a/service/src/main/inse/ranking/ranking.http b/service/src/main/inse/ranking/ranking.http new file mode 100644 index 00000000..a35fd754 --- /dev/null +++ b/service/src/main/inse/ranking/ranking.http @@ -0,0 +1,106 @@ +### Autoren-Ranking: ein Keyword +POST http://localhost:8000/api/search/rank +Content-Type: application/json + +{ + "keywords": ["Computer science"], + "filter_by_university": "https://openalex.org/I62318514", + "latest_publication_year": 2025 +} + +### Autoren-Ranking: nur Autoren mit juengster Arbeit ab 2023 +POST http://localhost:8000/api/search/rank +Content-Type: application/json + +{ + "keywords": ["Computer science"], + "latest_publication_year": 2023 +} + +### Autoren-Ranking: mehrere Keywords mit OR +POST http://localhost:8000/api/search/rank +Content-Type: application/json + +{ + "keywords": ["Waste management", "Public transport"], + "operator": "or" +} + +### Autoren-Ranking: mehrere Keywords mit AND +POST http://localhost:8000/api/search/rank +Content-Type: application/json + +{ + "keywords": ["Waste management", "Public transport"], + "operator": "and" +} + +### Autoren-Ranking: gefiltert nach Career Stage (nur Senior + Established) +POST http://localhost:8000/api/search/rank +Content-Type: application/json + +{ + "keywords": ["Waste management"], + "career_stages": ["Senior", "Established"] +} + +### Autoren-Ranking: nur Autoren der Uni Duisburg-Essen +POST http://localhost:8000/api/search/rank +Content-Type: application/json + +{ + "keywords": ["Waste management"], + "filter_by_university": "https://openalex.org/I62318514" +} + +### Autoren-Ranking: alle Filter kombiniert +POST http://localhost:8000/api/search/rank +Content-Type: application/json + +{ + "keywords": ["Context-Aware Activity Recognition Systems"], + //"career_stages": ["Senior"], + "filter_by_university": "https://openalex.org/I62318514" +} + +### Autor in die Rangliste einer (fremden) Uni einsortieren (publications) +POST http://localhost:8000/api/search/rank-author +Content-Type: application/json + +{ + "author_id": "https://openalex.org/A5036533333", + "universities": ["https://openalex.org/I62318514"], + "keywords": ["Control theory (sociology)"], + "metric": "publications" +} + +### +POST http://localhost:8000/api/search/rank-author +Content-Type: application/json + +{ + "author_id": "https://openalex.org/A5036533333", + "universities": ["https://openalex.org/I8204097"], + "keywords": ["Control theory (sociology)"], + "metric": "citations" +} + +### +POST http://localhost:8000/api/search/rank-author +Content-Type: application/json + +{ + "author_id": "https://openalex.org/A5036533333", + "universities": ["https://openalex.org/I8204097"], + "keywords": ["Control theory (sociology)"], + "metric": "publications" +} + +### +POST http://localhost:8000/api/rank/rank-author +Content-Type: application/json + +{ + //"author_id": "https://openalex.org/A5036533333" + "keywords": ["Keyword 1", "Keyword 2"] +} diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index ad933640..c62f98fe 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -3,7 +3,7 @@ import logging from fastapi import APIRouter from inse.tags import Tags -from .model import RankAuthorRequest +from .model import KeywordToAuthorRequest logger = logging.getLogger(__name__) @@ -14,6 +14,6 @@ router = APIRouter( @router.post("/rank-author") -async def rank_author(request: RankAuthorRequest): - logger.info("rank-author author_id=%s keywords=%s", request.author_id, request.keywords) +async def rank_author(request: KeywordToAuthorRequest): + logger.info("rank-author keywords=%s operator=%s", request.keywords, request.operator) return {"status": "ok"} -- 2.56.1 From d39d222ea8784c0a4bf0c6d57795b9a8030a1b6f Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 8 Jul 2026 14:02:03 +0200 Subject: [PATCH 03/50] add uni filter --- service/src/main/inse/ranking/model.py | 4 ++++ service/src/main/inse/ranking/router.py | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index a532e161..6ebe7751 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -23,6 +23,10 @@ class KeywordToAuthorRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) + uni_id: str = Field( + default="https://openalex.org/I62318514", + description="The selected university ID. (Default Uni-Due)", + ) @field_validator("operator", mode="before") @classmethod diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index c62f98fe..275b6bee 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -15,5 +15,10 @@ router = APIRouter( @router.post("/rank-author") async def rank_author(request: KeywordToAuthorRequest): - logger.info("rank-author keywords=%s operator=%s", request.keywords, request.operator) + logger.info( + "rank-author keywords=%s operator=%s uni_id=%s", + request.keywords, + request.operator, + request.uni_id, + ) return {"status": "ok"} -- 2.56.1 From 164e79978f5028d317ecedb2b8d271392ef960bf Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 8 Jul 2026 14:21:10 +0200 Subject: [PATCH 04/50] add get authors based on keywords --- service/src/main/inse/ranking/logic.py | 147 ++++++++++++++++++++++++ service/src/main/inse/ranking/model.py | 6 + service/src/main/inse/ranking/router.py | 12 +- 3 files changed, 162 insertions(+), 3 deletions(-) create mode 100644 service/src/main/inse/ranking/logic.py diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py new file mode 100644 index 00000000..fed2713a --- /dev/null +++ b/service/src/main/inse/ranking/logic.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import logging +from typing import Any, List + +from inse.integrations import elasticsearch +from inse.model import ESCluster +from .. import config +from .model import KeywordOperator, RankedAuthor + +logger = logging.getLogger(__name__) + + +MAX_AUTHOR_BUCKETS = 20 + + +def _keyword_clause(keyword: str) -> dict: + """A single nested clause that matches one keyword on a work.""" + return { + "nested": { + "path": "keywords", + "query": { + "term": {"keywords.display_name.keyword": keyword}, + }, + }, + } + + +def _build_keyword_query(keywords: List[str], operator: KeywordOperator) -> dict: + """Combines the keyword clauses according to the operator. + + AND: a work must carry all keywords (every clause is required). + OR: a work must carry at least one of the keywords. + """ + clauses = [] + for keyword in keywords: + clauses.append(_keyword_clause(keyword)) + + if operator == KeywordOperator.OR: + return { + "bool": { + "should": clauses, + "minimum_should_match": 1, + }, + } + + return { + "bool": { + "must": clauses, + }, + } + + +def _institution_filter(uni_id: str) -> dict: + """Keeps only works with an authorship affiliated with the given university. + + The institutions are nested below the authorships. + """ + return { + "nested": { + "path": "authorships.institutions", + "query": { + "term": {"authorships.institutions.id": uni_id}, + }, + }, + } + + +def _build_query(keywords: List[str], operator: KeywordOperator, uni_id: str) -> dict: + + return { + "size": 0, + "query": { + "bool": { + "filter": [ + _build_keyword_query(keywords, operator), + _institution_filter(uni_id), + ], + }, + }, + "aggs": { + "authors": { + "nested": {"path": "authorships"}, + "aggs": { + "by_author": { + "terms": { + "field": "authorships.author.id", + "size": MAX_AUTHOR_BUCKETS, + }, + "aggs": { + "author_name": { + "terms": { + "field": "authorships.author.display_name.keyword", + "size": 1, + }, + }, + }, + }, + }, + }, + }, + } + + +def _display_name_from_bucket(author_bucket: dict) -> str: + """Reads the author's display name out of the name sub-aggregation.""" + name_buckets = author_bucket.get("author_name", {}).get("buckets", []) + if name_buckets: + return name_buckets[0].get("key", "") + return "" + + +def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: + return RankedAuthor( + author_id=author_bucket.get("key", ""), + display_name=_display_name_from_bucket(author_bucket), + works_count=author_bucket.get("doc_count", 0), + ) + + +async def rank_authors_by_keywords( + keywords: List[str], + operator: KeywordOperator, + uni_id: str, +) -> List[RankedAuthor]: + """Ranks the university's authors by the number of works carrying the keywords.""" + query_body = _build_query(keywords, operator, uni_id) + + response: dict[str, Any] = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=query_body, + cluster=ESCluster.NES, + ) + + author_buckets = ( + response.get("aggregations", {}) + .get("authors", {}) + .get("by_author", {}) + .get("buckets", []) + ) + + ranked_authors = [] + for author_bucket in author_buckets: + ranked_authors.append(_bucket_to_ranked_author(author_bucket)) + + return ranked_authors diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 6ebe7751..5dbfea96 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -34,3 +34,9 @@ class KeywordToAuthorRequest(BaseModel): if isinstance(value, str): return value.lower() return value + + +class RankedAuthor(BaseModel): + author_id: str = Field(description="The OpenAlex ID of the author.") + display_name: str = Field(description="The name of the author.") + works_count: int = Field(description="Number of matching works by this author.") diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 275b6bee..cdafa480 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -1,9 +1,11 @@ import logging +from typing import List from fastapi import APIRouter from inse.tags import Tags -from .model import KeywordToAuthorRequest +from . import logic +from .model import KeywordToAuthorRequest, RankedAuthor logger = logging.getLogger(__name__) @@ -13,7 +15,7 @@ router = APIRouter( ) -@router.post("/rank-author") +@router.post("/rank-author", response_model=List[RankedAuthor]) async def rank_author(request: KeywordToAuthorRequest): logger.info( "rank-author keywords=%s operator=%s uni_id=%s", @@ -21,4 +23,8 @@ async def rank_author(request: KeywordToAuthorRequest): request.operator, request.uni_id, ) - return {"status": "ok"} + return await logic.rank_authors_by_keywords( + request.keywords, + request.operator, + request.uni_id, + ) -- 2.56.1 From ccade533587665160ca057e0e075d5f1d889023b Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Wed, 8 Jul 2026 14:24:25 +0200 Subject: [PATCH 05/50] add citation count --- service/src/main/inse/ranking/logic.py | 19 +++++++++++++++++++ service/src/main/inse/ranking/model.py | 3 +++ 2 files changed, 22 insertions(+) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index fed2713a..72d14b68 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -95,6 +95,14 @@ def _build_query(keywords: List[str], operator: KeywordOperator, uni_id: str) -> "size": 1, }, }, + "to_work": { + "reverse_nested": {}, + "aggs": { + "citations": { + "sum": {"field": "cited_by_count"}, + }, + }, + }, }, }, }, @@ -111,11 +119,22 @@ def _display_name_from_bucket(author_bucket: dict) -> str: return "" +def _citations_from_bucket(author_bucket: dict) -> int: + """Reads the summed citations out of the reverse_nested sub-aggregation.""" + citations_value = ( + author_bucket.get("to_work", {}) + .get("citations", {}) + .get("value", 0) + ) + return int(citations_value) + + def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: return RankedAuthor( author_id=author_bucket.get("key", ""), display_name=_display_name_from_bucket(author_bucket), works_count=author_bucket.get("doc_count", 0), + citations_count=_citations_from_bucket(author_bucket), ) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 5dbfea96..21670e74 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -40,3 +40,6 @@ class RankedAuthor(BaseModel): author_id: str = Field(description="The OpenAlex ID of the author.") display_name: str = Field(description="The name of the author.") works_count: int = Field(description="Number of matching works by this author.") + citations_count: int = Field( + description="Total citations across this author's matching works.", + ) -- 2.56.1 From 62d3adb74593fb8125f73472b74fbb55ab9f137d Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 9 Jul 2026 08:56:46 +0200 Subject: [PATCH 06/50] add ranking weights --- service/src/main/inse/ranking/logic.py | 49 +++++++++++++++++++++---- service/src/main/inse/ranking/model.py | 17 +++++++++ service/src/main/inse/ranking/router.py | 1 + 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 72d14b68..133b6013 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -7,12 +7,16 @@ from typing import Any, List from inse.integrations import elasticsearch from inse.model import ESCluster from .. import config -from .model import KeywordOperator, RankedAuthor +from .model import KeywordOperator, RankedAuthor, RankingWeights logger = logging.getLogger(__name__) -MAX_AUTHOR_BUCKETS = 20 +# terms size: gather all matching authors as candidates before the score is +# computed, so a strong citation weight can still lift a low-works author. +CANDIDATE_POOL_SIZE = 10000 +# Number of authors to return in the final result +RESULT_SIZE = 20 def _keyword_clause(keyword: str) -> dict: @@ -67,7 +71,16 @@ def _institution_filter(uni_id: str) -> dict: } -def _build_query(keywords: List[str], operator: KeywordOperator, uni_id: str) -> dict: +def _build_query( + keywords: List[str], + operator: KeywordOperator, + uni_id: str, + weights: RankingWeights, +) -> dict: + """Builds the Elasticsearch query for ranking authors by keywords.""" + score_script = ( + f"params.works * {weights.works} + params.citations * {weights.citation}" + ) return { "size": 0, @@ -86,7 +99,7 @@ def _build_query(keywords: List[str], operator: KeywordOperator, uni_id: str) -> "by_author": { "terms": { "field": "authorships.author.id", - "size": MAX_AUTHOR_BUCKETS, + "size": CANDIDATE_POOL_SIZE, }, "aggs": { "author_name": { @@ -103,6 +116,21 @@ def _build_query(keywords: List[str], operator: KeywordOperator, uni_id: str) -> }, }, }, + "score": { + "bucket_script": { + "buckets_path": { + "works": "_count", + "citations": "to_work>citations", + }, + "script": score_script, + }, + }, + "score_sort": { + "bucket_sort": { + "sort": [{"score": {"order": "desc"}}], + "size": RESULT_SIZE, + }, + }, }, }, }, @@ -112,7 +140,7 @@ def _build_query(keywords: List[str], operator: KeywordOperator, uni_id: str) -> def _display_name_from_bucket(author_bucket: dict) -> str: - """Reads the author's display name out of the name sub-aggregation.""" + """Reads the authors display name out of the name sub-aggregation.""" name_buckets = author_bucket.get("author_name", {}).get("buckets", []) if name_buckets: return name_buckets[0].get("key", "") @@ -129,12 +157,18 @@ def _citations_from_bucket(author_bucket: dict) -> int: return int(citations_value) +def _score_from_bucket(author_bucket: dict) -> float: + """Reads the weighted score out of the bucket_script sub-aggregation.""" + return author_bucket.get("score", {}).get("value", 0.0) + + def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: return RankedAuthor( author_id=author_bucket.get("key", ""), display_name=_display_name_from_bucket(author_bucket), works_count=author_bucket.get("doc_count", 0), citations_count=_citations_from_bucket(author_bucket), + score=_score_from_bucket(author_bucket), ) @@ -142,9 +176,10 @@ async def rank_authors_by_keywords( keywords: List[str], operator: KeywordOperator, uni_id: str, + weights: RankingWeights, ) -> List[RankedAuthor]: - """Ranks the university's authors by the number of works carrying the keywords.""" - query_body = _build_query(keywords, operator, uni_id) + """Ranks the university's authors by a weighted score over works and citations.""" + query_body = _build_query(keywords, operator, uni_id, weights) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 21670e74..7dcb21bf 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -14,6 +14,19 @@ class KeywordOperator(StrEnum): OR = "or" +class RankingWeights(BaseModel): + citation: float = Field( + ge=0.0, + le=1.0, + description="Weight for the citation metric (0.0 - 1.0).", + ) + works: float = Field( + ge=0.0, + le=1.0, + description="Weight for the works metric (0.0 - 1.0).", + ) + + class KeywordToAuthorRequest(BaseModel): keywords: List[str] = Field( min_length=1, @@ -27,6 +40,9 @@ class KeywordToAuthorRequest(BaseModel): default="https://openalex.org/I62318514", description="The selected university ID. (Default Uni-Due)", ) + weights: RankingWeights = Field( + description="Weights for the ranking metrics. Required.", + ) @field_validator("operator", mode="before") @classmethod @@ -43,3 +59,4 @@ class RankedAuthor(BaseModel): citations_count: int = Field( description="Total citations across this author's matching works.", ) + score: float = Field(description="Weighted total score used for ranking.") diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index cdafa480..132c6331 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -27,4 +27,5 @@ async def rank_author(request: KeywordToAuthorRequest): request.keywords, request.operator, request.uni_id, + request.weights, ) -- 2.56.1 From 16e582e942f37beea7b9773bab6cb2bfbc372761 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 9 Jul 2026 09:25:27 +0200 Subject: [PATCH 07/50] improve es query: only rank target authors in works --- service/src/main/inse/ranking/logic.py | 62 ++++++++++++---------- service/src/main/inse/ranking/ranking.http | 11 +++- 2 files changed, 44 insertions(+), 29 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 133b6013..c5c64436 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -16,7 +16,7 @@ logger = logging.getLogger(__name__) # computed, so a strong citation weight can still lift a low-works author. CANDIDATE_POOL_SIZE = 10000 # Number of authors to return in the final result -RESULT_SIZE = 20 +RESULT_SIZE = 100 def _keyword_clause(keyword: str) -> dict: @@ -96,39 +96,44 @@ def _build_query( "authors": { "nested": {"path": "authorships"}, "aggs": { - "by_author": { - "terms": { - "field": "authorships.author.id", - "size": CANDIDATE_POOL_SIZE, - }, + "uni_only": { + "filter": _institution_filter(uni_id), "aggs": { - "author_name": { + "by_author": { "terms": { - "field": "authorships.author.display_name.keyword", - "size": 1, + "field": "authorships.author.id", + "size": CANDIDATE_POOL_SIZE, }, - }, - "to_work": { - "reverse_nested": {}, "aggs": { - "citations": { - "sum": {"field": "cited_by_count"}, + "author_name": { + "terms": { + "field": "authorships.author.display_name.keyword", + "size": 1, + }, }, - }, - }, - "score": { - "bucket_script": { - "buckets_path": { - "works": "_count", - "citations": "to_work>citations", + "to_work": { + "reverse_nested": {}, + "aggs": { + "citations": { + "sum": {"field": "cited_by_count"}, + }, + }, + }, + "score": { + "bucket_script": { + "buckets_path": { + "works": "_count", + "citations": "to_work>citations", + }, + "script": score_script, + }, + }, + "score_sort": { + "bucket_sort": { + "sort": [{"score": {"order": "desc"}}], + "size": RESULT_SIZE, + }, }, - "script": score_script, - }, - }, - "score_sort": { - "bucket_sort": { - "sort": [{"score": {"order": "desc"}}], - "size": RESULT_SIZE, }, }, }, @@ -190,6 +195,7 @@ async def rank_authors_by_keywords( author_buckets = ( response.get("aggregations", {}) .get("authors", {}) + .get("uni_only", {}) .get("by_author", {}) .get("buckets", []) ) diff --git a/service/src/main/inse/ranking/ranking.http b/service/src/main/inse/ranking/ranking.http index a35fd754..dda0e025 100644 --- a/service/src/main/inse/ranking/ranking.http +++ b/service/src/main/inse/ranking/ranking.http @@ -102,5 +102,14 @@ Content-Type: application/json { //"author_id": "https://openalex.org/A5036533333" - "keywords": ["Keyword 1", "Keyword 2"] + "keywords": ["Computer science"] } + +### +POST http://localhost:8000/api/rank/rank-author +Content-Type: application/json + +{ + "keywords": ["Computer science"], + "weights": { "citation": 0.6, "works": 0.3 } +} \ No newline at end of file -- 2.56.1 From 31b285518d943ec88df7a20879895c06618cdf79 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 9 Jul 2026 09:51:46 +0200 Subject: [PATCH 08/50] add filter for career stage --- service/src/main/inse/ranking/logic.py | 105 +++++++++++++++++++++++- service/src/main/inse/ranking/model.py | 14 ++++ service/src/main/inse/ranking/router.py | 4 +- 3 files changed, 120 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index c5c64436..c1cc33b4 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -6,8 +6,9 @@ from typing import Any, List from inse.integrations import elasticsearch from inse.model import ESCluster +from inse.persons.logic import _classify_career_stage from .. import config -from .model import KeywordOperator, RankedAuthor, RankingWeights +from .model import CareerStage, KeywordOperator, RankedAuthor, RankingWeights logger = logging.getLogger(__name__) @@ -177,13 +178,96 @@ def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: ) +def _career_query(author_ids: List[str]) -> dict: + """Query that collects each author's distinct publication years. + + The career stage is derived from all of an author's works (not only the + keyword-matching ones), so we filter the works by the author ids and + aggregate the publication years per author. + """ + return { + "size": 0, + "query": { + "nested": { + "path": "authorships", + "query": {"terms": {"authorships.author.id": author_ids}}, + }, + }, + "aggs": { + "authors": { + "nested": {"path": "authorships"}, + "aggs": { + "by_author": { + "terms": { + "field": "authorships.author.id", + "include": author_ids, + "size": len(author_ids), + }, + "aggs": { + "to_work": { + "reverse_nested": {}, + "aggs": { + "publication_years": { + "terms": { + "field": "publication_year", + "size": 1000, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + +async def _career_stages_for_authors(author_ids: List[str]) -> dict: + """Returns a mapping author_id -> CareerStage for the given authors.""" + if not author_ids: + return {} + + response: dict[str, Any] = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=_career_query(author_ids), + cluster=ESCluster.NES, + ) + + author_buckets = ( + response.get("aggregations", {}) + .get("authors", {}) + .get("by_author", {}) + .get("buckets", []) + ) + + stages = {} + for author_bucket in author_buckets: + author_id = author_bucket.get("key", "") + year_buckets = ( + author_bucket.get("to_work", {}) + .get("publication_years", {}) + .get("buckets", []) + ) + # Each bucket is one distinct publication year -> number of active years. + active_years = len(year_buckets) + stages[author_id] = CareerStage(_classify_career_stage(active_years)) + + return stages + + async def rank_authors_by_keywords( keywords: List[str], operator: KeywordOperator, uni_id: str, weights: RankingWeights, + career_stages: List[CareerStage], ) -> List[RankedAuthor]: - """Ranks the university's authors by a weighted score over works and citations.""" + """Ranks the university's authors by a weighted score over works and citations. + + When career_stages is not empty, the ranked list is filtered down to + authors whose career stage is one of the given stages. + """ query_body = _build_query(keywords, operator, uni_id, weights) response: dict[str, Any] = await elasticsearch.search( @@ -204,4 +288,21 @@ async def rank_authors_by_keywords( for author_bucket in author_buckets: ranked_authors.append(_bucket_to_ranked_author(author_bucket)) + # Enrich every ranked author with its career stage. + author_ids = [] + for author in ranked_authors: + author_ids.append(author.author_id) + + stages = await _career_stages_for_authors(author_ids) + for author in ranked_authors: + author.career_stage = stages.get(author.author_id, CareerStage.UNKNOWN) + + if career_stages: + allowed_stages = set(career_stages) + filtered_authors = [] + for author in ranked_authors: + if author.career_stage in allowed_stages: + filtered_authors.append(author) + ranked_authors = filtered_authors + return ranked_authors diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 7dcb21bf..f857afc1 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -13,6 +13,12 @@ class KeywordOperator(StrEnum): AND = "and" OR = "or" +class CareerStage(StrEnum): + UNKNOWN = "unknown" + EARLY = "Early" + EMERGING = "Emerging" + ESTABLISHED = "Established" + SENIOR = "Senior" class RankingWeights(BaseModel): citation: float = Field( @@ -43,6 +49,10 @@ class KeywordToAuthorRequest(BaseModel): weights: RankingWeights = Field( description="Weights for the ranking metrics. Required.", ) + career_stages: List[CareerStage] = Field( + default_factory=list, + description="Optional filter: only keep authors in one of these career stages. Empty = no filter.", + ) @field_validator("operator", mode="before") @classmethod @@ -60,3 +70,7 @@ class RankedAuthor(BaseModel): description="Total citations across this author's matching works.", ) score: float = Field(description="Weighted total score used for ranking.") + career_stage: CareerStage = Field( + default=CareerStage.UNKNOWN, + description="Career stage derived from the author's active publication years.", + ) diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 132c6331..74b73a57 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -18,14 +18,16 @@ router = APIRouter( @router.post("/rank-author", response_model=List[RankedAuthor]) async def rank_author(request: KeywordToAuthorRequest): logger.info( - "rank-author keywords=%s operator=%s uni_id=%s", + "rank-author keywords=%s operator=%s uni_id=%s career_stages=%s", request.keywords, request.operator, request.uni_id, + request.career_stages, ) return await logic.rank_authors_by_keywords( request.keywords, request.operator, request.uni_id, request.weights, + request.career_stages, ) -- 2.56.1 From 3b9436474e78446cfe23ee2d42c107ba83c511f0 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 9 Jul 2026 10:20:14 +0200 Subject: [PATCH 09/50] add filter publication_types to filter works --- service/src/main/inse/ranking/logic.py | 32 ++++++++++++++++++++----- service/src/main/inse/ranking/model.py | 31 ++++++++++++++++++++++++ service/src/main/inse/ranking/router.py | 4 +++- 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index c1cc33b4..1b0b4241 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -8,7 +8,13 @@ from inse.integrations import elasticsearch from inse.model import ESCluster from inse.persons.logic import _classify_career_stage from .. import config -from .model import CareerStage, KeywordOperator, RankedAuthor, RankingWeights +from .model import ( + CareerStage, + KeywordOperator, + PublicationType, + RankedAuthor, + RankingWeights, +) logger = logging.getLogger(__name__) @@ -72,25 +78,38 @@ def _institution_filter(uni_id: str) -> dict: } +def _publication_type_filter(publication_types: List[PublicationType]) -> dict: + """Keeps only works whose type is one of the given publication types.""" + type_values = [] + for publication_type in publication_types: + type_values.append(publication_type.value) + return {"terms": {"type": type_values}} + + def _build_query( keywords: List[str], operator: KeywordOperator, uni_id: str, weights: RankingWeights, + publication_types: List[PublicationType], ) -> dict: """Builds the Elasticsearch query for ranking authors by keywords.""" score_script = ( f"params.works * {weights.works} + params.citations * {weights.citation}" ) + work_filters = [ + _build_keyword_query(keywords, operator), + _institution_filter(uni_id), + ] + if publication_types: + work_filters.append(_publication_type_filter(publication_types)) + return { "size": 0, "query": { "bool": { - "filter": [ - _build_keyword_query(keywords, operator), - _institution_filter(uni_id), - ], + "filter": work_filters, }, }, "aggs": { @@ -262,13 +281,14 @@ async def rank_authors_by_keywords( uni_id: str, weights: RankingWeights, career_stages: List[CareerStage], + publication_types: List[PublicationType], ) -> List[RankedAuthor]: """Ranks the university's authors by a weighted score over works and citations. When career_stages is not empty, the ranked list is filtered down to authors whose career stage is one of the given stages. """ - query_body = _build_query(keywords, operator, uni_id, weights) + query_body = _build_query(keywords, operator, uni_id, weights, publication_types) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index f857afc1..a118496e 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -20,6 +20,33 @@ class CareerStage(StrEnum): ESTABLISHED = "Established" SENIOR = "Senior" + +class PublicationType(StrEnum): + ARTICLE = "article" + OTHER = "other" + DATASET = "dataset" + BOOK_CHAPTER = "book-chapter" + BOOK = "book" + DISSERTATION = "dissertation" + PREPRINT = "preprint" + PARATEXT = "paratext" + LIBGUIDES = "libguides" + REVIEW = "review" + LETTER = "letter" + REFERENCE_ENTRY = "reference-entry" + EDITORIAL = "editorial" + PEER_REVIEW = "peer-review" + REPORT = "report" + STANDARD = "standard" + ERRATUM = "erratum" + RETRACTION = "retraction" + SUPPLEMENTARY_MATERIALS = "supplementary-materials" + BOOK_SECTION = "book-section" + DATABASE = "database" + SOFTWARE = "software" + REPORT_COMPONENT = "report-component" + GRANT = "grant" + class RankingWeights(BaseModel): citation: float = Field( ge=0.0, @@ -53,6 +80,10 @@ class KeywordToAuthorRequest(BaseModel): default_factory=list, description="Optional filter: only keep authors in one of these career stages. Empty = no filter.", ) + publication_types: List[PublicationType] = Field( + default_factory=list, + description="Optional filter: only count works of these publication types. Empty = no filter.", + ) @field_validator("operator", mode="before") @classmethod diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 74b73a57..56d27069 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -18,11 +18,12 @@ router = APIRouter( @router.post("/rank-author", response_model=List[RankedAuthor]) async def rank_author(request: KeywordToAuthorRequest): logger.info( - "rank-author keywords=%s operator=%s uni_id=%s career_stages=%s", + "rank-author keywords=%s operator=%s uni_id=%s career_stages=%s publication_types=%s", request.keywords, request.operator, request.uni_id, request.career_stages, + request.publication_types, ) return await logic.rank_authors_by_keywords( request.keywords, @@ -30,4 +31,5 @@ async def rank_author(request: KeywordToAuthorRequest): request.uni_id, request.weights, request.career_stages, + request.publication_types, ) -- 2.56.1 From ecd21ce0a9bb1c0538c5254a2fd17d66aeafade0 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 9 Jul 2026 10:53:59 +0200 Subject: [PATCH 10/50] add filter timespan (include works from/to) --- service/src/main/inse/ranking/logic.py | 23 +++++++++++++++++++++-- service/src/main/inse/ranking/model.py | 19 +++++++++++++++++-- service/src/main/inse/ranking/router.py | 5 ++++- 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 1b0b4241..6b3ce93e 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- import logging -from typing import Any, List +from typing import Any, List, Optional from inse.integrations import elasticsearch from inse.model import ESCluster @@ -14,6 +14,7 @@ from .model import ( PublicationType, RankedAuthor, RankingWeights, + Timespan, ) logger = logging.getLogger(__name__) @@ -86,12 +87,25 @@ def _publication_type_filter(publication_types: List[PublicationType]) -> dict: return {"terms": {"type": type_values}} +def _timespan_filter(timespan: Timespan) -> dict: + """Keeps only works whose publication year is within the timespan (inclusive).""" + return { + "range": { + "publication_year": { + "gte": timespan.from_year, + "lte": timespan.to_year, + }, + }, + } + + def _build_query( keywords: List[str], operator: KeywordOperator, uni_id: str, weights: RankingWeights, publication_types: List[PublicationType], + timespan: Optional[Timespan], ) -> dict: """Builds the Elasticsearch query for ranking authors by keywords.""" score_script = ( @@ -104,6 +118,8 @@ def _build_query( ] if publication_types: work_filters.append(_publication_type_filter(publication_types)) + if timespan is not None: + work_filters.append(_timespan_filter(timespan)) return { "size": 0, @@ -282,13 +298,16 @@ async def rank_authors_by_keywords( weights: RankingWeights, career_stages: List[CareerStage], publication_types: List[PublicationType], + timespan: Optional[Timespan], ) -> List[RankedAuthor]: """Ranks the university's authors by a weighted score over works and citations. When career_stages is not empty, the ranked list is filtered down to authors whose career stage is one of the given stages. """ - query_body = _build_query(keywords, operator, uni_id, weights, publication_types) + query_body = _build_query( + keywords, operator, uni_id, weights, publication_types, timespan + ) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index a118496e..ec8402ec 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -4,9 +4,9 @@ Data models for author ranking. """ from enum import StrEnum -from typing import List +from typing import List, Optional -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, Field, field_validator, model_validator class KeywordOperator(StrEnum): @@ -47,6 +47,17 @@ class PublicationType(StrEnum): REPORT_COMPONENT = "report-component" GRANT = "grant" +class Timespan(BaseModel): + from_year: int = Field(alias="from", description="Start year (inclusive).") + to_year: int = Field(alias="to", description="End year (inclusive).") + + @model_validator(mode="after") + def check_order(self): + if self.from_year > self.to_year: + raise ValueError("timespan 'from' must not be greater than 'to'.") + return self + + class RankingWeights(BaseModel): citation: float = Field( ge=0.0, @@ -84,6 +95,10 @@ class KeywordToAuthorRequest(BaseModel): default_factory=list, description="Optional filter: only count works of these publication types. Empty = no filter.", ) + timespan: Optional[Timespan] = Field( + default=None, + description="Optional filter: only count works whose publication_year is within [from, to].", + ) @field_validator("operator", mode="before") @classmethod diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 56d27069..f8731cb2 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -18,12 +18,14 @@ router = APIRouter( @router.post("/rank-author", response_model=List[RankedAuthor]) async def rank_author(request: KeywordToAuthorRequest): logger.info( - "rank-author keywords=%s operator=%s uni_id=%s career_stages=%s publication_types=%s", + "rank-author keywords=%s operator=%s uni_id=%s career_stages=%s " + "publication_types=%s timespan=%s", request.keywords, request.operator, request.uni_id, request.career_stages, request.publication_types, + request.timespan, ) return await logic.rank_authors_by_keywords( request.keywords, @@ -32,4 +34,5 @@ async def rank_author(request: KeywordToAuthorRequest): request.weights, request.career_stages, request.publication_types, + request.timespan, ) -- 2.56.1 From 34b6979666b03641545137e35046030c2a51a84b Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 9 Jul 2026 10:56:34 +0200 Subject: [PATCH 11/50] add examples --- service/src/main/inse/ranking/ranking.http | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/service/src/main/inse/ranking/ranking.http b/service/src/main/inse/ranking/ranking.http index dda0e025..b73b3128 100644 --- a/service/src/main/inse/ranking/ranking.http +++ b/service/src/main/inse/ranking/ranking.http @@ -110,6 +110,8 @@ POST http://localhost:8000/api/rank/rank-author Content-Type: application/json { - "keywords": ["Computer science"], - "weights": { "citation": 0.6, "works": 0.3 } + "keywords": ["Middleware (distributed applications)"], + "weights": { "citation": 0.2, "works": 1.0 }, + "career_stages": ["Senior"], + "timespan": { "from": 2018, "to": 2025 } } \ No newline at end of file -- 2.56.1 From e5f48457d2c50cac4378a3918687f16787c3d695 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 12 Jul 2026 09:50:26 +0200 Subject: [PATCH 12/50] refactor: process ranking in backend instead es and improve query performance --- service/src/main/inse/ranking/logic.py | 84 ++++++++++++++------------ 1 file changed, 44 insertions(+), 40 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 6b3ce93e..998feec3 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- import logging +from time import time from typing import Any, List, Optional from inse.integrations import elasticsearch @@ -23,8 +24,6 @@ logger = logging.getLogger(__name__) # terms size: gather all matching authors as candidates before the score is # computed, so a strong citation weight can still lift a low-works author. CANDIDATE_POOL_SIZE = 10000 -# Number of authors to return in the final result -RESULT_SIZE = 100 def _keyword_clause(keyword: str) -> dict: @@ -103,15 +102,10 @@ def _build_query( keywords: List[str], operator: KeywordOperator, uni_id: str, - weights: RankingWeights, publication_types: List[PublicationType], timespan: Optional[Timespan], ) -> dict: - """Builds the Elasticsearch query for ranking authors by keywords.""" - score_script = ( - f"params.works * {weights.works} + params.citations * {weights.citation}" - ) - + """Builds the Elasticsearch query that returns the raw stats per author.""" work_filters = [ _build_keyword_query(keywords, operator), _institution_filter(uni_id), @@ -139,12 +133,14 @@ def _build_query( "terms": { "field": "authorships.author.id", "size": CANDIDATE_POOL_SIZE, + "execution_hint": "map", }, "aggs": { "author_name": { "terms": { "field": "authorships.author.display_name.keyword", "size": 1, + "execution_hint": "map", }, }, "to_work": { @@ -155,21 +151,6 @@ def _build_query( }, }, }, - "score": { - "bucket_script": { - "buckets_path": { - "works": "_count", - "citations": "to_work>citations", - }, - "script": score_script, - }, - }, - "score_sort": { - "bucket_sort": { - "sort": [{"score": {"order": "desc"}}], - "size": RESULT_SIZE, - }, - }, }, }, }, @@ -198,21 +179,28 @@ def _citations_from_bucket(author_bucket: dict) -> int: return int(citations_value) -def _score_from_bucket(author_bucket: dict) -> float: - """Reads the weighted score out of the bucket_script sub-aggregation.""" - return author_bucket.get("score", {}).get("value", 0.0) +def _weighted_score(works_count: int, citations_count: int, weights: RankingWeights) -> float: + """Computes the weighted score for an author in the backend.""" + return works_count * weights.works + citations_count * weights.citation -def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: +def _bucket_to_ranked_author(author_bucket: dict, weights: RankingWeights) -> RankedAuthor: + works_count = author_bucket.get("doc_count", 0) + citations_count = _citations_from_bucket(author_bucket) return RankedAuthor( author_id=author_bucket.get("key", ""), display_name=_display_name_from_bucket(author_bucket), - works_count=author_bucket.get("doc_count", 0), - citations_count=_citations_from_bucket(author_bucket), - score=_score_from_bucket(author_bucket), + works_count=works_count, + citations_count=citations_count, + score=_weighted_score(works_count, citations_count, weights), ) +def _author_score(author: RankedAuthor) -> float: + """Sort key: the weighted score of an author.""" + return author.score + + def _career_query(author_ids: List[str]) -> dict: """Query that collects each author's distinct publication years. @@ -305,8 +293,10 @@ async def rank_authors_by_keywords( When career_stages is not empty, the ranked list is filtered down to authors whose career stage is one of the given stages. """ + query_start_time = time() + query_body = _build_query( - keywords, operator, uni_id, weights, publication_types, timespan + keywords, operator, uni_id, publication_types, timespan ) response: dict[str, Any] = await elasticsearch.search( @@ -315,6 +305,8 @@ async def rank_authors_by_keywords( cluster=ESCluster.NES, ) + query_end_time = time() + author_buckets = ( response.get("aggregations", {}) .get("authors", {}) @@ -323,25 +315,37 @@ async def rank_authors_by_keywords( .get("buckets", []) ) + # Build the raw authors and compute the weighted score in the backend. + backend_processing_start_time = time() ranked_authors = [] for author_bucket in author_buckets: - ranked_authors.append(_bucket_to_ranked_author(author_bucket)) + ranked_authors.append(_bucket_to_ranked_author(author_bucket, weights)) - # Enrich every ranked author with its career stage. - author_ids = [] - for author in ranked_authors: - author_ids.append(author.author_id) - - stages = await _career_stages_for_authors(author_ids) - for author in ranked_authors: - author.career_stage = stages.get(author.author_id, CareerStage.UNKNOWN) + # Sort by the weighted score, highest first. + ranked_authors.sort(key=_author_score, reverse=True) + # ToDo: improve speed career stage classification + career_stages = None if career_stages: + # Enrich every ranked author with its career stage. + author_ids = [] + for author in ranked_authors: + author_ids.append(author.author_id) + + stages = await _career_stages_for_authors(author_ids) + + for author in ranked_authors: + author.career_stage = stages.get(author.author_id, CareerStage.UNKNOWN) + allowed_stages = set(career_stages) filtered_authors = [] + for author in ranked_authors: if author.career_stage in allowed_stages: filtered_authors.append(author) + ranked_authors = filtered_authors + backend_processing_end_time = time() + logger.info("Query time: %.3f s, backend processing time: %.3f s", query_end_time - query_start_time, backend_processing_end_time - backend_processing_start_time) return ranked_authors -- 2.56.1 From b2faa2bc98ec015d757e8f398bc98c1970d11d07 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 12 Jul 2026 13:22:59 +0200 Subject: [PATCH 13/50] add pandas dependency and implement normalization for author scores --- service/Dockerfile | 3 +- service/pyproject.toml | 1 + service/src/main/inse/ranking/logic.py | 59 ++++++++++++++++++++------ service/src/main/inse/ranking/model.py | 5 ++- 4 files changed, 53 insertions(+), 15 deletions(-) diff --git a/service/Dockerfile b/service/Dockerfile index e32d005c..8072f6b4 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -18,7 +18,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "websockets==12.0" \ "partial-json-parser==0.2.1.1.post7" \ "sqlmodel~=0.0.33" \ - "argon2-cffi~=25.1.0" + "argon2-cffi~=25.1.0" \ + "pandas~=2.3.3" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/pyproject.toml b/service/pyproject.toml index 118c8fe1..6e6b8cb5 100644 --- a/service/pyproject.toml +++ b/service/pyproject.toml @@ -21,6 +21,7 @@ dependencies = [ "torch", "sqlmodel~=0.0.33", "argon2-cffi~=25.1.0", + "pandas~=2.3.3", ] [[tool.uv.index]] diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 998feec3..9cd2ff90 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -5,6 +5,8 @@ import logging from time import time from typing import Any, List, Optional +import pandas as pd + from inse.integrations import elasticsearch from inse.model import ESCluster from inse.persons.logic import _classify_career_stage @@ -179,23 +181,51 @@ def _citations_from_bucket(author_bucket: dict) -> int: return int(citations_value) -def _weighted_score(works_count: int, citations_count: int, weights: RankingWeights) -> float: - """Computes the weighted score for an author in the backend.""" - return works_count * weights.works + citations_count * weights.citation - - -def _bucket_to_ranked_author(author_bucket: dict, weights: RankingWeights) -> RankedAuthor: - works_count = author_bucket.get("doc_count", 0) - citations_count = _citations_from_bucket(author_bucket) +def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: + """Converts an author bucket from the ES aggregation into a RankedAuthor.""" return RankedAuthor( author_id=author_bucket.get("key", ""), display_name=_display_name_from_bucket(author_bucket), - works_count=works_count, - citations_count=citations_count, - score=_weighted_score(works_count, citations_count, weights), + works_count=author_bucket.get("doc_count", 0), + citations_count=_citations_from_bucket(author_bucket), ) +def _min_max_normalize(values: pd.Series) -> pd.Series: + """Scales a numeric column to the range [0, 1] via min-max normalization.""" + minimum = values.min() + maximum = values.max() + # if all values are the same, return a series of 1.0 to avoid division by zero. + if maximum == minimum: + return pd.Series([1.0] * len(values)) + + return (values - minimum) / (maximum - minimum) + + +def _apply_scores(authors: List[RankedAuthor], weights: RankingWeights) -> None: + """Normalizes works and citations to [0, 1] and sets each author's weighted score.""" + if not authors: + return + + works_counts = [] + citations_counts = [] + for author in authors: + works_counts.append(author.works_count) + citations_counts.append(author.citations_count) + + frame = pd.DataFrame({ + "works": works_counts, + "citations": citations_counts, + }) + + works_normalized = _min_max_normalize(frame["works"]) + citations_normalized = _min_max_normalize(frame["citations"]) + scores = works_normalized * weights.works + citations_normalized * weights.citation + + for index, author in enumerate(authors): + author.score = float(scores.iloc[index]) + + def _author_score(author: RankedAuthor) -> float: """Sort key: the weighted score of an author.""" return author.score @@ -314,12 +344,15 @@ async def rank_authors_by_keywords( .get("by_author", {}) .get("buckets", []) ) + logger.error(author_buckets) - # Build the raw authors and compute the weighted score in the backend. + # Build the raw authors, then compute the normalized weighted score. backend_processing_start_time = time() ranked_authors = [] for author_bucket in author_buckets: - ranked_authors.append(_bucket_to_ranked_author(author_bucket, weights)) + ranked_authors.append(_bucket_to_ranked_author(author_bucket)) + + _apply_scores(ranked_authors, weights) # Sort by the weighted score, highest first. ranked_authors.sort(key=_author_score, reverse=True) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index ec8402ec..c36c46dc 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -115,7 +115,10 @@ class RankedAuthor(BaseModel): citations_count: int = Field( description="Total citations across this author's matching works.", ) - score: float = Field(description="Weighted total score used for ranking.") + score: float = Field( + default=0.0, + description="Normalized weighted score used for ranking.", + ) career_stage: CareerStage = Field( default=CareerStage.UNKNOWN, description="Career stage derived from the author's active publication years.", -- 2.56.1 From afe3038dce3eed311d9fe09471827e9bc6939b9a Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 12 Jul 2026 13:58:18 +0200 Subject: [PATCH 14/50] frontend: show author list --- webapp/src/app/api/api/api.ts | 21 ++- webapp/src/app/api/api/ranking.service.ts | 163 ++++++++++++++++++ .../app/api/model/keywordToAuthorRequest.ts | 41 +++++ webapp/src/app/api/model/models.ts | 3 + webapp/src/app/api/model/rankedAuthor.ts | 36 ++++ webapp/src/app/api/model/rankingWeights.ts | 20 +++ .../persons-results.component.html | 31 +++- .../persons-results.component.scss | 38 ++++ .../persons-results.component.ts | 99 ++++++----- 9 files changed, 406 insertions(+), 46 deletions(-) create mode 100644 webapp/src/app/api/api/ranking.service.ts create mode 100644 webapp/src/app/api/model/keywordToAuthorRequest.ts create mode 100644 webapp/src/app/api/model/rankedAuthor.ts create mode 100644 webapp/src/app/api/model/rankingWeights.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index 64e95400..d0ac182d 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -28,4 +28,23 @@ export * from './universityRankings.service'; import { UniversityRankingsService } from './universityRankings.service'; export * from './works.service'; import { WorksService } from './works.service'; -export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService]; +export * from './ranking.service'; +import { RankingService } from './ranking.service'; +export const APIS = [ + AuthService, + CompanyConnectionsService, + FundingService, + INSEServiceService, + InstitutionsService, + KeywordsService, + NewsService, + OrganizationService, + PatentsService, + PersonNetworkService, + PersonsService, + ProjectsService, + TopicsService, + UniversityRankingsService, + WorksService, + RankingService, +]; diff --git a/webapp/src/app/api/api/ranking.service.ts b/webapp/src/app/api/api/ranking.service.ts new file mode 100644 index 00000000..de2439c0 --- /dev/null +++ b/webapp/src/app/api/api/ranking.service.ts @@ -0,0 +1,163 @@ +/** + * 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 { KeywordToAuthorRequest } from '../model/keywordToAuthorRequest'; +// @ts-ignore +import { RankedAuthor } from '../model/rankedAuthor'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + +@Injectable({ + providedIn: 'root', +}) +export class RankingService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } + + /** + * Ranks a university\'s authors by a weighted score over works and citations. + * @endpoint post /api/rank/rank-author + * @param keywordToAuthorRequest + * @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 rankAuthor( + keywordToAuthorRequest: KeywordToAuthorRequest, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public rankAuthor( + keywordToAuthorRequest: KeywordToAuthorRequest, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public rankAuthor( + keywordToAuthorRequest: KeywordToAuthorRequest, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public rankAuthor( + keywordToAuthorRequest: KeywordToAuthorRequest, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + keywordToAuthorRequest === null || + keywordToAuthorRequest === undefined + ) { + throw new Error( + 'Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthor.', + ); + } + + 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; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + 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/rank/rank-author`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: keywordToAuthorRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } +} diff --git a/webapp/src/app/api/model/keywordToAuthorRequest.ts b/webapp/src/app/api/model/keywordToAuthorRequest.ts new file mode 100644 index 00000000..3eb1d8f9 --- /dev/null +++ b/webapp/src/app/api/model/keywordToAuthorRequest.ts @@ -0,0 +1,41 @@ +/** + * 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 { RankingWeights } from './rankingWeights'; + +export interface KeywordToAuthorRequest { + /** + * One or more keywords to rank the author by. + */ + keywords: Array; + /** + * Weights for the ranking metrics. Required. + */ + weights: RankingWeights; + /** + * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. + */ + operator?: string; + /** + * The selected university ID. (Default Uni-Due) + */ + uni_id?: string; + /** + * Optional filter: only keep authors in one of these career stages. + */ + career_stages?: Array; + /** + * Optional filter: only count works of these publication types. + */ + publication_types?: Array; + /** + * Optional filter: only count works whose publication_year is within [from, to]. + */ + timespan?: { from: number; to: number }; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 91abe3c5..7e0cf593 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -194,3 +194,6 @@ export * from './workTopicSubfield'; export * from './worksFilterProperties'; export * from './worksListResponse'; export * from './yearlyData'; +export * from './rankingWeights'; +export * from './rankedAuthor'; +export * from './keywordToAuthorRequest'; diff --git a/webapp/src/app/api/model/rankedAuthor.ts b/webapp/src/app/api/model/rankedAuthor.ts new file mode 100644 index 00000000..d06efd83 --- /dev/null +++ b/webapp/src/app/api/model/rankedAuthor.ts @@ -0,0 +1,36 @@ +/** + * 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 RankedAuthor { + /** + * The OpenAlex ID of the author. + */ + author_id: string; + /** + * The name of the author. + */ + display_name: string; + /** + * Number of matching works by this author. + */ + works_count: number; + /** + * Total citations across this author\'s matching works. + */ + citations_count: number; + /** + * Normalized weighted score used for ranking. + */ + score?: number; + /** + * Career stage derived from the author\'s active publication years. + */ + career_stage?: string; +} diff --git a/webapp/src/app/api/model/rankingWeights.ts b/webapp/src/app/api/model/rankingWeights.ts new file mode 100644 index 00000000..5b7bf84a --- /dev/null +++ b/webapp/src/app/api/model/rankingWeights.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 RankingWeights { + /** + * Weight for the citation metric (0.0 - 1.0). + */ + citation: number; + /** + * Weight for the works metric (0.0 - 1.0). + */ + works: number; +} diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html index a97b0264..a6597a14 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html @@ -1,11 +1,30 @@
- - groups -

Personenliste

-

- Die aktuelle Gewichtung ist unter normalized verfügbar. -

+ + @if (loading()) { +

Lädt…

+ } @else if (authors().length === 0) { +
+ groups +

Keine Autoren gefunden

+

Passe die Keywords oder die Gewichtung an.

+
+ } @else { + + }
diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss index ffeea20d..ccf3aa50 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss @@ -27,3 +27,41 @@ padding: 0.75rem; } } + +/* ============================================================ + AUTHOR LIST + ============================================================ */ +.author-list { + list-style: none; + margin: 0; + padding: 0; +} + +.author-item { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.75rem; + padding: 0.5rem 0.25rem; + border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); +} + +.author-name { + font-weight: 500; + text-decoration: none; + color: var(--sg-primary, #1565c0); + + &:hover { + text-decoration: underline; + } +} + +.author-score { + font-variant-numeric: tabular-nums; + color: var(--sg-text-secondary, rgba(0, 0, 0, 0.6)); + white-space: nowrap; +} + +.results-hint { + padding: 0.5rem 0.25rem; +} diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts index 533c28e7..290966e8 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts @@ -1,5 +1,7 @@ import { Component, inject, signal } from '@angular/core'; +import { DecimalPipe } from '@angular/common'; +import { RouterLink } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; @@ -10,36 +12,47 @@ import { WeightsSlidersValue, } from '../../../../shared/ui/weights-sliders/weights-sliders.component'; +import { + KeywordToAuthorRequest, + RankedAuthor, + RankingService, +} from '../../../../api'; + import { SearchResultsStateService } from '../search-results-state.service'; @Component({ selector: 'app-persons-results', standalone: true, - imports: [MatCardModule, MatIconModule, WeightsSlidersComponent], + imports: [ + DecimalPipe, + RouterLink, + MatCardModule, + MatIconModule, + WeightsSlidersComponent, + ], templateUrl: './persons-results.component.html', styleUrl: './persons-results.component.scss', }) export class KeywordsToPersonsResultsComponent { // injects the state set by the parent route — no duplicate parsing here private readonly state = inject(SearchResultsStateService); + private readonly rankingService = inject(RankingService); + // for now only works and citations are used as metrics/weights readonly defaultWeights: WeightMap = { - publications: 0.5, + works: 0.5, citations: 0.5, - patents: 0.5, - projects: 0.5, - mediaVisibility: 0.5, }; readonly weightOptions: WeightSliderOption[] = [ { - key: 'publications', - label: 'Publikationen', + key: 'works', + label: 'Works', icon: 'article', description: 'Gewichtet die Anzahl und Relevanz wissenschaftlicher Arbeiten.', defaultValue: 0.5, - queryParamName: 'wPublications', + queryParamName: 'wWorks', }, { key: 'citations', @@ -49,7 +62,7 @@ export class KeywordsToPersonsResultsComponent { defaultValue: 0.5, queryParamName: 'wCitations', }, - { + /*{ key: 'patents', label: 'Patente', icon: 'workspace_premium', @@ -72,24 +85,19 @@ export class KeywordsToPersonsResultsComponent { description: 'Gewichtet öffentliche und mediale Sichtbarkeit.', defaultValue: 0.5, queryParamName: 'wMedia', - }, + }, */ ]; readonly currentWeights = signal({ raw: this.defaultWeights, - normalized: { - publications: 0.2, - citations: 0.2, - patents: 0.2, - projects: 0.2, - mediaVisibility: 0.2, - }, - rawSum: 2.5, + normalized: { works: 0.5, citations: 0.5 }, + rawSum: 1, normalizedSum: 1, valid: true, }); - readonly persons = signal([]); // placeholder until the results service lands + readonly authors = signal([]); + readonly loading = signal(false); private hasLoadedInitial = false; @@ -99,37 +107,50 @@ export class KeywordsToPersonsResultsComponent { // fires once with the query-param-aware initial state — use it to load if (!this.hasLoadedInitial) { this.hasLoadedInitial = true; - this.loadPersons(); + this.loadAuthors(); } } onApplyWeights(value: WeightsSlidersValue): void { this.currentWeights.set(value); - this.loadPersons(); + this.loadAuthors(); } - private loadPersons(): void { - const weights = this.currentWeights(); + // the backend returns the full OpenAlex url; the profile route needs only the id + authorProfileId(author: RankedAuthor): string { + const parts = author.author_id.split('/'); + return parts[parts.length - 1]; + } - const requestPayload = { - manualKeywords: this.state.manualKeywords(), - extractedKeywords: this.state.extractedKeywords(), - keywords: this.state.keywords(), - softSearch: this.state.softSearch(), + private loadAuthors(): void { + const keywords = this.state.keywords(); + + if (keywords.length === 0) { + this.authors.set([]); + return; + } + + const rawWeights = this.currentWeights().raw; + const request: KeywordToAuthorRequest = { + keywords: keywords, + // all keywords are combined with AND (backend default) weights: { - raw: weights.raw, - normalized: weights.normalized, + works: rawWeights['works'], + citation: rawWeights['citations'], }, }; - console.log(requestPayload); - - /** - * TODO: - * this.personsService.searchPersons(requestPayload).subscribe({ - * next: results => this.persons.set(results), - * error: error => console.error(error), - * }); - */ + this.loading.set(true); + this.rankingService.rankAuthor(request).subscribe({ + next: (results) => { + this.authors.set(results); + this.loading.set(false); + }, + error: (error) => { + console.error(error); + this.authors.set([]); + this.loading.set(false); + }, + }); } } -- 2.56.1 From d16b1544b9817bb49fa2166dc7c939f323b3463d Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 12 Jul 2026 14:19:37 +0200 Subject: [PATCH 15/50] add silder for relevant years --- .../persons-results.component.html | 61 +++++++++++++------ .../persons-results.component.scss | 26 +++++++- .../persons-results.component.ts | 59 +++++++++++++++++- 3 files changed, 123 insertions(+), 23 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html index a6597a14..fa2c9511 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html @@ -28,23 +28,46 @@ - - - - - +
+ + + + + + + + +
+ date_range + Zeitraum: {{ timespanFrom() }} – {{ timespanTo() }} +
+ + + + +
+
+
diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss index ccf3aa50..4a8757b4 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.scss @@ -7,12 +7,21 @@ grid-template-areas: 'summary results'; gap: 0.75rem; align-items: start; + width: 100%; } -.search-summary-card { +.search-summary-card, +.controls-column { grid-area: summary; } +.controls-column { + display: flex; + flex-direction: column; + gap: 0.75rem; + min-width: 0; +} + .results-card { grid-area: results; } @@ -65,3 +74,18 @@ .results-hint { padding: 0.5rem 0.25rem; } + +/* ============================================================ + TIMESPAN + ============================================================ */ +.timespan-header { + display: flex; + align-items: center; + gap: 0.5rem; + margin-bottom: 0.25rem; + font-weight: 500; +} + +.timespan-card mat-slider { + width: 100%; +} diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts index 290966e8..835e9aef 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts @@ -1,9 +1,10 @@ -import { Component, inject, signal } from '@angular/core'; +import { Component, OnInit, inject, signal } from '@angular/core'; import { DecimalPipe } from '@angular/common'; -import { RouterLink } from '@angular/router'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; +import { MatSliderModule } from '@angular/material/slider'; import { WeightMap, @@ -28,15 +29,18 @@ import { SearchResultsStateService } from '../search-results-state.service'; RouterLink, MatCardModule, MatIconModule, + MatSliderModule, WeightsSlidersComponent, ], templateUrl: './persons-results.component.html', styleUrl: './persons-results.component.scss', }) -export class KeywordsToPersonsResultsComponent { +export class KeywordsToPersonsResultsComponent implements OnInit { // injects the state set by the parent route — no duplicate parsing here private readonly state = inject(SearchResultsStateService); private readonly rankingService = inject(RankingService); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); // for now only works and citations are used as metrics/weights readonly defaultWeights: WeightMap = { @@ -96,11 +100,47 @@ export class KeywordsToPersonsResultsComponent { valid: true, }); + // publication-year timespan filter (range slider) + readonly minYear = 1900; + readonly maxYear = 2026; + readonly timespanFrom = signal(this.minYear); + readonly timespanTo = signal(this.maxYear); + readonly authors = signal([]); readonly loading = signal(false); private hasLoadedInitial = false; + ngOnInit(): void { + // restore the timespan from the URL so the range is shareable/bookmarkable + this.timespanFrom.set(this.readYearParam('tFrom', this.minYear)); + this.timespanTo.set(this.readYearParam('tTo', this.maxYear)); + } + + // reads a year query param, clamped to the valid range; falls back on invalid input + private readYearParam(name: string, fallback: number): number { + const rawValue = this.route.snapshot.queryParamMap.get(name); + if (rawValue === null) { + return fallback; + } + + const year = Number(rawValue); + if (!Number.isFinite(year)) { + return fallback; + } + + return Math.min(this.maxYear, Math.max(this.minYear, Math.round(year))); + } + + private writeTimespanToUrl(): void { + this.router.navigate([], { + relativeTo: this.route, + queryParams: { tFrom: this.timespanFrom(), tTo: this.timespanTo() }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + onWeightsChange(value: WeightsSlidersValue): void { this.currentWeights.set(value); @@ -116,6 +156,15 @@ export class KeywordsToPersonsResultsComponent { this.loadAuthors(); } + // called when a timespan thumb is released — persist to the URL and reload + onTimespanChange(): void { + if (this.timespanFrom() > this.timespanTo()) { + return; + } + this.writeTimespanToUrl(); + this.loadAuthors(); + } + // the backend returns the full OpenAlex url; the profile route needs only the id authorProfileId(author: RankedAuthor): string { const parts = author.author_id.split('/'); @@ -138,6 +187,10 @@ export class KeywordsToPersonsResultsComponent { works: rawWeights['works'], citation: rawWeights['citations'], }, + timespan: { + from: this.timespanFrom(), + to: this.timespanTo(), + }, }; this.loading.set(true); -- 2.56.1 From 21ea772656461d187ed5531c250541f3f6781e2d Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 12 Jul 2026 16:51:20 +0200 Subject: [PATCH 16/50] filter authors by "last"_known_institutions --- service/src/main/inse/ranking/logic.py | 57 +++++++++++++++++++++----- 1 file changed, 46 insertions(+), 11 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 9cd2ff90..659ad447 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -26,6 +26,37 @@ logger = logging.getLogger(__name__) # terms size: gather all matching authors as candidates before the score is # computed, so a strong citation weight can still lift a low-works author. CANDIDATE_POOL_SIZE = 10000 +UNI_AUTHOR_LIMIT = 20000 + + +async def _get_author_ids_from_uni(uni_id: str) -> List[str]: + + query = { + "nested": { + "path": "last_known_institutions", + "query": { + "term": {"last_known_institutions.id": uni_id}, + }, + }, + } + + author_ids = [] + async for hit in elasticsearch.scan( + index="openalex-authors", + query=query, + source=["id"], + page_size=5000, + cluster=ESCluster.NES, + ): + source = hit.get("_source", {}) + author_id = source.get("id") or hit.get("_id", "") + if author_id: + author_ids.append(author_id) + if len(author_ids) >= UNI_AUTHOR_LIMIT: + break + + return author_ids + def _keyword_clause(keyword: str) -> dict: @@ -65,16 +96,13 @@ def _build_keyword_query(keywords: List[str], operator: KeywordOperator) -> dict } -def _institution_filter(uni_id: str) -> dict: - """Keeps only works with an authorship affiliated with the given university. +def _author_filter(author_ids: List[str]) -> dict: - The institutions are nested below the authorships. - """ return { "nested": { - "path": "authorships.institutions", + "path": "authorships", "query": { - "term": {"authorships.institutions.id": uni_id}, + "terms": {"authorships.author.id": author_ids}, }, }, } @@ -103,14 +131,14 @@ def _timespan_filter(timespan: Timespan) -> dict: def _build_query( keywords: List[str], operator: KeywordOperator, - uni_id: str, + author_ids: List[str], publication_types: List[PublicationType], timespan: Optional[Timespan], ) -> dict: """Builds the Elasticsearch query that returns the raw stats per author.""" work_filters = [ _build_keyword_query(keywords, operator), - _institution_filter(uni_id), + _author_filter(author_ids), ] if publication_types: work_filters.append(_publication_type_filter(publication_types)) @@ -129,7 +157,11 @@ def _build_query( "nested": {"path": "authorships"}, "aggs": { "uni_only": { - "filter": _institution_filter(uni_id), + "filter": { + "terms": { + "authorships.author.id": author_ids + } + }, "aggs": { "by_author": { "terms": { @@ -325,8 +357,12 @@ async def rank_authors_by_keywords( """ query_start_time = time() + author_ids = await _get_author_ids_from_uni(uni_id) + if not author_ids: + return [] + query_body = _build_query( - keywords, operator, uni_id, publication_types, timespan + keywords, operator, author_ids, publication_types, timespan ) response: dict[str, Any] = await elasticsearch.search( @@ -344,7 +380,6 @@ async def rank_authors_by_keywords( .get("by_author", {}) .get("buckets", []) ) - logger.error(author_buckets) # Build the raw authors, then compute the normalized weighted score. backend_processing_start_time = time() -- 2.56.1 From 64ccedf44da2eaf78f261398c27f0841fab817d7 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 12 Jul 2026 17:06:52 +0200 Subject: [PATCH 17/50] feat: implement yearly works query and endpoint for selected authors --- service/src/main/inse/ranking/logic.py | 106 ++++++++++++++++++++++++ service/src/main/inse/ranking/model.py | 34 ++++++++ service/src/main/inse/ranking/router.py | 22 ++++- 3 files changed, 161 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 659ad447..464f7ea5 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -12,12 +12,14 @@ from inse.model import ESCluster from inse.persons.logic import _classify_career_stage from .. import config from .model import ( + AuthorYearlyWorks, CareerStage, KeywordOperator, PublicationType, RankedAuthor, RankingWeights, Timespan, + YearCount, ) logger = logging.getLogger(__name__) @@ -108,6 +110,110 @@ def _author_filter(author_ids: List[str]) -> dict: } +def _yearly_works_query( + author_ids: List[str], + keywords: List[str], + operator: KeywordOperator, +) -> dict: + """Builds a query that returns, per selected author, the year distribution of their topic works.""" + return { + "size": 0, + "query": { + "bool": { + "filter": [ + _build_keyword_query(keywords, operator), + _author_filter(author_ids), + ], + }, + }, + "aggs": { + "authors": { + "nested": {"path": "authorships"}, + "aggs": { + "selected": { + # keep only the authorships of the selected authors + "filter": {"terms": {"authorships.author.id": author_ids}}, + "aggs": { + "by_author": { + "terms": { + "field": "authorships.author.id", + "size": len(author_ids), + "execution_hint": "map", + }, + "aggs": { + "to_work": { + "reverse_nested": {}, + "aggs": { + "publication_years": { + "terms": { + "field": "publication_year", + "size": 200, + "order": {"_key": "desc"}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + +async def yearly_works_for_authors( + author_ids: List[str], + keywords: List[str], + operator: KeywordOperator, +) -> List[AuthorYearlyWorks]: + """For each selected author, returns the per-year count of their works on the topic. + + Only years with at least one work are returned, newest year first. + """ + if not author_ids: + return [] + + response: dict[str, Any] = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=_yearly_works_query(author_ids, keywords, operator), + cluster=ESCluster.NES, + ) + + author_buckets = ( + response.get("aggregations", {}) + .get("authors", {}) + .get("selected", {}) + .get("by_author", {}) + .get("buckets", []) + ) + + results = [] + for author_bucket in author_buckets: + year_buckets = ( + author_bucket.get("to_work", {}) + .get("publication_years", {}) + .get("buckets", []) + ) + years = [] + for year_bucket in year_buckets: + years.append( + YearCount( + year=int(year_bucket.get("key")), + count=year_bucket.get("doc_count", 0), + ) + ) + results.append( + AuthorYearlyWorks( + author_id=author_bucket.get("key", ""), + years=years, + ) + ) + + return results + + def _publication_type_filter(publication_types: List[PublicationType]) -> dict: """Keeps only works whose type is one of the given publication types.""" type_values = [] diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index c36c46dc..6ceb7e34 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -108,6 +108,40 @@ class KeywordToAuthorRequest(BaseModel): return value +class SelectedAuthorsRequest(BaseModel): + author_ids: List[str] = Field( + min_length=1, + description="OpenAlex IDs of the authors to rank.", + ) + keywords: List[str] = Field( + min_length=1, + description="One or more keywords defining the topic.", + ) + operator: KeywordOperator = Field( + default=KeywordOperator.AND, + description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", + ) + + @field_validator("operator", mode="before") + @classmethod + def operator_case_insensitive(cls, value): + if isinstance(value, str): + return value.lower() + return value + + +class YearCount(BaseModel): + year: int = Field(description="Publication year.") + count: int = Field(description="Number of the author's works on the topic in that year.") + + +class AuthorYearlyWorks(BaseModel): + author_id: str = Field(description="The OpenAlex ID of the author.") + years: List[YearCount] = Field( + description="Per-year count of the author's works on the topic, newest year first.", + ) + + class RankedAuthor(BaseModel): author_id: str = Field(description="The OpenAlex ID of the author.") display_name: str = Field(description="The name of the author.") diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index f8731cb2..0371f441 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -5,7 +5,12 @@ from fastapi import APIRouter from inse.tags import Tags from . import logic -from .model import KeywordToAuthorRequest, RankedAuthor +from .model import ( + AuthorYearlyWorks, + KeywordToAuthorRequest, + RankedAuthor, + SelectedAuthorsRequest, +) logger = logging.getLogger(__name__) @@ -36,3 +41,18 @@ async def rank_author(request: KeywordToAuthorRequest): request.publication_types, request.timespan, ) + + +@router.post("/rank-selected-author", response_model=List[AuthorYearlyWorks]) +async def rank_selected_author(request: SelectedAuthorsRequest): + logger.info( + "rank-selected-author author_ids=%s keywords=%s operator=%s", + request.author_ids, + request.keywords, + request.operator, + ) + return await logic.yearly_works_for_authors( + request.author_ids, + request.keywords, + request.operator, + ) -- 2.56.1 From 7775400a3f1dda24e36fd6ea3c804fd41c091bec Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Mon, 13 Jul 2026 07:19:33 +0200 Subject: [PATCH 18/50] add author comparison feature with yearly works visualization --- service/src/main/inse/ranking/logic.py | 8 ++ service/src/main/inse/ranking/model.py | 1 + webapp/src/app/api/api/ranking.service.ts | 121 ++++++++++++++++++ webapp/src/app/api/model/authorYearlyWorks.ts | 24 ++++ webapp/src/app/api/model/models.ts | 2 + .../api/model/rankSelectedAuthorRequest.ts | 24 ++++ webapp/src/app/app.routes.ts | 8 ++ .../compare-authors.component.html | 23 ++++ .../compare-authors.component.scss | 18 +++ .../compare-authors.component.ts | 108 ++++++++++++++++ .../persons-results.component.html | 17 +++ .../persons-results.component.scss | 18 ++- .../persons-results.component.ts | 52 +++++++- 13 files changed, 421 insertions(+), 3 deletions(-) create mode 100644 webapp/src/app/api/model/authorYearlyWorks.ts create mode 100644 webapp/src/app/api/model/rankSelectedAuthorRequest.ts create mode 100644 webapp/src/app/modules/compare-authors/compare-authors.component.html create mode 100644 webapp/src/app/modules/compare-authors/compare-authors.component.scss create mode 100644 webapp/src/app/modules/compare-authors/compare-authors.component.ts diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 464f7ea5..c3728a0e 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -141,6 +141,13 @@ def _yearly_works_query( "execution_hint": "map", }, "aggs": { + "author_name": { + "terms": { + "field": "authorships.author.display_name.keyword", + "size": 1, + "execution_hint": "map", + }, + }, "to_work": { "reverse_nested": {}, "aggs": { @@ -207,6 +214,7 @@ async def yearly_works_for_authors( results.append( AuthorYearlyWorks( author_id=author_bucket.get("key", ""), + display_name=_display_name_from_bucket(author_bucket), years=years, ) ) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 6ceb7e34..76db4e91 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -137,6 +137,7 @@ class YearCount(BaseModel): class AuthorYearlyWorks(BaseModel): author_id: str = Field(description="The OpenAlex ID of the author.") + display_name: str = Field(description="The name of the author.") years: List[YearCount] = Field( description="Per-year count of the author's works on the topic, newest year first.", ) diff --git a/webapp/src/app/api/api/ranking.service.ts b/webapp/src/app/api/api/ranking.service.ts index de2439c0..8316fee7 100644 --- a/webapp/src/app/api/api/ranking.service.ts +++ b/webapp/src/app/api/api/ranking.service.ts @@ -26,6 +26,10 @@ import { Observable } from 'rxjs'; import { KeywordToAuthorRequest } from '../model/keywordToAuthorRequest'; // @ts-ignore import { RankedAuthor } from '../model/rankedAuthor'; +// @ts-ignore +import { RankSelectedAuthorRequest } from '../model/rankSelectedAuthorRequest'; +// @ts-ignore +import { AuthorYearlyWorks } from '../model/authorYearlyWorks'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -160,4 +164,121 @@ export class RankingService extends BaseService { }, ); } + + /** + * Returns, per selected author, the per-year count of their works on the topic. + * @endpoint post /api/rank/rank-selected-author + * @param rankSelectedAuthorRequest + * @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 rankSelectedAuthor( + rankSelectedAuthorRequest: RankSelectedAuthorRequest, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public rankSelectedAuthor( + rankSelectedAuthorRequest: RankSelectedAuthorRequest, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public rankSelectedAuthor( + rankSelectedAuthorRequest: RankSelectedAuthorRequest, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public rankSelectedAuthor( + rankSelectedAuthorRequest: RankSelectedAuthorRequest, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + rankSelectedAuthorRequest === null || + rankSelectedAuthorRequest === undefined + ) { + throw new Error( + 'Required parameter rankSelectedAuthorRequest was null or undefined when calling rankSelectedAuthor.', + ); + } + + 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; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + 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/rank/rank-selected-author`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: rankSelectedAuthorRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/model/authorYearlyWorks.ts b/webapp/src/app/api/model/authorYearlyWorks.ts new file mode 100644 index 00000000..e744734e --- /dev/null +++ b/webapp/src/app/api/model/authorYearlyWorks.ts @@ -0,0 +1,24 @@ +/** + * 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 AuthorYearlyWorks { + /** + * The OpenAlex ID of the author. + */ + author_id: string; + /** + * The name of the author. + */ + display_name: string; + /** + * Per-year count of the author\'s works on the topic, newest year first. + */ + years: Array<{ year: number; count: number }>; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 7e0cf593..5a549e5d 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -197,3 +197,5 @@ export * from './yearlyData'; export * from './rankingWeights'; export * from './rankedAuthor'; export * from './keywordToAuthorRequest'; +export * from './rankSelectedAuthorRequest'; +export * from './authorYearlyWorks'; diff --git a/webapp/src/app/api/model/rankSelectedAuthorRequest.ts b/webapp/src/app/api/model/rankSelectedAuthorRequest.ts new file mode 100644 index 00000000..9b966c2a --- /dev/null +++ b/webapp/src/app/api/model/rankSelectedAuthorRequest.ts @@ -0,0 +1,24 @@ +/** + * 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 RankSelectedAuthorRequest { + /** + * OpenAlex IDs of the authors to rank. + */ + author_ids: Array; + /** + * One or more keywords defining the topic. + */ + keywords: Array; + /** + * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. + */ + operator?: string; +} diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 21a8b833..1a8f9e18 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -68,6 +68,14 @@ export const routes: Routes = [ (mod) => mod.DashboardComponent, ), }, + { + path: 'compare', + canActivate: [userGuard], + loadComponent: () => + import('./modules/compare-authors/compare-authors.component').then( + (mod) => mod.CompareAuthorsComponent, + ), + }, { path: 'persons', canActivate: [userGuard], diff --git a/webapp/src/app/modules/compare-authors/compare-authors.component.html b/webapp/src/app/modules/compare-authors/compare-authors.component.html new file mode 100644 index 00000000..133c693a --- /dev/null +++ b/webapp/src/app/modules/compare-authors/compare-authors.component.html @@ -0,0 +1,23 @@ +
+

Autoren-Vergleich

+ + @if (keywords().length > 0) { +

Thema: {{ keywords().join(', ') }}

+ } + + @if (loading()) { +

Lädt…

+ } @else if (data().length === 0) { +

Keine Daten für die ausgewählten Autoren.

+ } @else { + + +
+
+
+ } +
diff --git a/webapp/src/app/modules/compare-authors/compare-authors.component.scss b/webapp/src/app/modules/compare-authors/compare-authors.component.scss new file mode 100644 index 00000000..b19374e6 --- /dev/null +++ b/webapp/src/app/modules/compare-authors/compare-authors.component.scss @@ -0,0 +1,18 @@ +.compare-layout { + padding: 1rem; +} + +.compare-keywords { + color: var(--sg-text-secondary, rgba(0, 0, 0, 0.6)); + margin-bottom: 1rem; +} + +.compare-hint { + padding: 0.5rem 0.25rem; +} + +/* echarts needs an explicit height or it won't render */ +.chart-container { + height: 500px; + width: 100%; +} diff --git a/webapp/src/app/modules/compare-authors/compare-authors.component.ts b/webapp/src/app/modules/compare-authors/compare-authors.component.ts new file mode 100644 index 00000000..5edb6497 --- /dev/null +++ b/webapp/src/app/modules/compare-authors/compare-authors.component.ts @@ -0,0 +1,108 @@ +import { Component, OnInit, computed, inject, signal } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { MatCardModule } from '@angular/material/card'; +import { EChartsOption } from 'echarts'; +import { NgxEchartsDirective } from 'ngx-echarts'; + +import { AuthorYearlyWorks, RankingService } from '../../api'; + +const LINE_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd']; + +@Component({ + selector: 'app-compare-authors', + standalone: true, + imports: [MatCardModule, NgxEchartsDirective], + templateUrl: './compare-authors.component.html', + styleUrl: './compare-authors.component.scss', +}) +export class CompareAuthorsComponent implements OnInit { + private readonly route = inject(ActivatedRoute); + private readonly rankingService = inject(RankingService); + + readonly keywords = signal([]); + readonly data = signal([]); + readonly loading = signal(false); + + readonly chartOption = computed(() => { + const authors = this.data(); + if (authors.length === 0) { + return {}; + } + + // shared, ascending list of every year that appears for any author + const yearSet = new Set(); + for (const author of authors) { + for (const entry of author.years) { + yearSet.add(entry.year); + } + } + const years = Array.from(yearSet).sort((a, b) => a - b); + + const series = authors.map((author, index) => { + const countByYear = new Map(); + for (const entry of author.years) { + countByYear.set(entry.year, entry.count); + } + + const color = LINE_COLORS[index % LINE_COLORS.length]; + return { + name: author.display_name, + type: 'line', + smooth: true, + emphasis: { focus: 'series' }, + lineStyle: { color }, + itemStyle: { color }, + // align every author to the shared year axis, filling gaps with 0 + data: years.map((year) => countByYear.get(year) ?? 0), + }; + }); + + return { + tooltip: { trigger: 'axis' }, + legend: { bottom: 0, type: 'scroll' }, + grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }, + xAxis: { type: 'category', boundaryGap: false, data: years.map(String) }, + yAxis: { type: 'value', name: 'Werke' }, + series: series as unknown as EChartsOption['series'], + }; + }); + + ngOnInit(): void { + // everything is read from the URL so a shared link lands on the same view + const rawAuthors = this.route.snapshot.queryParamMap.get('authors') ?? ''; + const rawKeywords = this.route.snapshot.queryParamMap.get('keywords') ?? ''; + + const authorIds = this.parseList(rawAuthors); + const keywords = this.parseList(rawKeywords); + this.keywords.set(keywords); + + if (authorIds.length === 0 || keywords.length === 0) { + return; + } + + // ids in the url are bare (A5036...); the endpoint expects full OpenAlex urls + const fullIds = authorIds.map((id) => `https://openalex.org/${id}`); + + this.loading.set(true); + this.rankingService + .rankSelectedAuthor({ author_ids: fullIds, keywords: keywords }) + .subscribe({ + next: (results) => { + this.data.set(results); + this.loading.set(false); + }, + error: (error) => { + console.error(error); + this.data.set([]); + this.loading.set(false); + }, + }); + } + + private parseList(raw: string): string[] { + return raw + .split(',') + .map((value) => value.trim()) + .filter(Boolean); + } +} diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html index fa2c9511..123b67ab 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.html @@ -10,9 +10,26 @@

Passe die Keywords oder die Gewichtung an.

} @else { +
+ + {{ selectedIds().length }} / {{ MAX_SELECTED }} ausgewählt + + +