diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 8313217f..1340f2ee 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -2,7 +2,6 @@ import asyncio import logging -from dataclasses import dataclass from math import floor from time import time from typing import Any @@ -21,7 +20,6 @@ from .model import ( AuthorTopicStats, CareerStage, CompanyStatusFilter, - FilterType, KeywordOperator, PublicationType, PublicationTypeCount, @@ -69,59 +67,88 @@ async def _get_author_ids_from_institution(institution_id: str) -> list[str]: -@dataclass(frozen=True) -class MatchConfig: - """Where a topic filter matches on a work: keyword display names or topic ids.""" - - path: str - match_field: str - score_field: str - - -_KEYWORD_MATCH = MatchConfig( - path="keywords", - match_field="keywords.display_name.keyword", - score_field="keywords.score", -) -_TOPIC_MATCH = MatchConfig( - path="topics", - match_field="topics.display_name.keyword", - score_field="topics.score", -) - - -def _match_config(filter_type: FilterType) -> MatchConfig: - """Resolves the request's filter_type into the single set of fields to match on.""" - if filter_type == FilterType.TOPIC: - return _TOPIC_MATCH - return _KEYWORD_MATCH - - -def _keyword_clause(value: str, config: MatchConfig = _KEYWORD_MATCH) -> dict: - """A single nested clause that matches one keyword/topic value on a work.""" +def _topics_nested_clause(should_clauses: list[dict]) -> dict: + """Wraps should-clauses on the nested topics of a work.""" return { "nested": { - "path": config.path, + "path": "topics", "query": { - "term": {config.match_field: value}, + "bool": { + "should": should_clauses, + "minimum_should_match": 1, + }, }, }, } +def _topic_id_clause(topic_id: str) -> dict: + """Matches one OpenAlex topic id against a work (fuzzy mode). + + A work matches when the topic is either its primary topic or one of its + other topics. + """ + return { + "bool": { + "should": [ + _topics_nested_clause([{"term": {"topics.id": topic_id}}]), + {"term": {"primary_topic.id": topic_id}}, + ], + "minimum_should_match": 1, + }, + } + + +def _keyword_clause(keyword: str) -> dict: + """Matches one raw keyword as a phrase against a work (non-fuzzy mode). + + The keyword has to occur as a phrase in at least one of the work's own text + fields or in one of the names of its topic hierarchy. + """ + return { + "bool": { + "should": [ + { + "nested": { + "path": "keywords", + "query": { + "match_phrase": {"keywords.display_name": keyword}, + }, + }, + }, + {"match_phrase": {"primary_topic.display_name": keyword}}, + {"match_phrase": {"title": keyword}}, + {"match_phrase": {"abstract": keyword}}, + _topics_nested_clause( + [ + {"match_phrase": {"topics.display_name": keyword}}, + {"match_phrase": {"topics.field.display_name": keyword}}, + {"match_phrase": {"topics.subfield.display_name": keyword}}, + {"match_phrase": {"topics.domain.display_name": keyword}}, + ] + ), + ], + "minimum_should_match": 1, + }, + } + + def _build_keyword_query( keywords: list[str], operator: KeywordOperator, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Combines the keyword/topic clauses according to the operator. - AND: a work must carry all values (every clause is required). - OR: a work must carry at least one of the values. + AND: a work must match all values (every clause is required). + OR: a work must match at least one of the values. """ clauses = [] for keyword in keywords: - clauses.append(_keyword_clause(keyword, config)) + if fuzzy: + clauses.append(_topic_id_clause(keyword)) + else: + clauses.append(_keyword_clause(keyword)) if operator == KeywordOperator.OR: return { @@ -156,12 +183,12 @@ def _topic_stats_query( operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds a single query with all stats for Section 1""" filters = [ - _build_keyword_query(keywords, operator, config), + _build_keyword_query(keywords, operator, fuzzy), _author_filter(author_ids), ] @@ -283,38 +310,6 @@ def _topic_stats_query( "_source": {"includes": ["cited_by_count"]}, }, }, - # works whose matched keyword/topic scores above 0.8 - "relevance_above_80": { - "filter": { - "nested": { - "path": config.path, - "query": { - "bool": { - "filter": [ - {"terms": {config.match_field: keywords}}, - {"range": {config.score_field: {"gt": 0.8}}}, - ], - }, - }, - }, - }, - }, - # average matched relevance score over the works - "matched_keywords": { - "nested": {"path": config.path}, - "aggs": { - "only_searched": { - "filter": { - "terms": {config.match_field: keywords}, - }, - "aggs": { - "avg_score": { - "avg": {"field": config.score_field}, - }, - }, - }, - }, - }, }, }, }, @@ -347,17 +342,16 @@ async def topic_stats_for_authors( operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[AuthorTopicStats]: if not author_ids: return [] - match_cfg = _match_config(filter_type) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=_topic_stats_query( - author_ids, keywords, operator, publication_types, timespan, match_cfg + author_ids, keywords, operator, publication_types, timespan, fuzzy ), cluster=ESCluster.NES, ) @@ -375,12 +369,6 @@ async def topic_stats_for_authors( for author_bucket in author_buckets: to_work = author_bucket.get("to_work", {}) avg_value = to_work.get("avg_percentile", {}).get("value") - avg_rel = ( - to_work.get("matched_keywords", {}) - .get("only_searched", {}) - .get("avg_score", {}) - .get("value") - ) positions = { bucket.get("key", ""): bucket.get("doc_count", 0) for bucket in author_bucket.get("positions", {}).get("buckets", []) @@ -413,8 +401,6 @@ async def topic_stats_for_authors( industry_works_count=to_work.get("industry_collab", {}).get("doc_count", 0), first_year=int(first_year) if first_year is not None else None, last_year=int(last_year) if last_year is not None else None, - relevance_above_80_count=to_work.get("relevance_above_80", {}).get("doc_count", 0), - avg_relevance=float(avg_rel) if avg_rel is not None else 0.0, first_author_count=positions.get("first", 0), middle_author_count=positions.get("middle", 0), last_author_count=positions.get("last", 0), @@ -424,13 +410,29 @@ async def topic_stats_for_authors( return results +def _primary_topic_match(keywords: list[str], fuzzy: bool) -> dict: + """Matches works whose primary topic is one of the searched topics/keywords.""" + if fuzzy: + return {"terms": {"primary_topic.id": keywords}} + + return { + "bool": { + "should": [ + {"match_phrase": {"primary_topic.display_name": keyword}} + for keyword in keywords + ], + "minimum_should_match": 1, + }, + } + + def _topic_profile_query( author_ids: list[str], keywords: list[str], operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds the Section 3 query""" @@ -474,14 +476,10 @@ def _topic_profile_query( "reverse_nested": {}, "aggs": { "matched": { - "filter": _build_keyword_query(keywords, operator, config), + "filter": _build_keyword_query(keywords, operator, fuzzy), "aggs": { "primary_match": { - "filter": { - "terms": { - "primary_topic.display_name.keyword": keywords, - }, - }, + "filter": _primary_topic_match(keywords, fuzzy), }, }, }, @@ -561,17 +559,16 @@ async def topic_profile_for_authors( operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[AuthorTopicProfile]: if not author_ids: return [] - match_cfg = _match_config(filter_type) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=_topic_profile_query( - author_ids, keywords, operator, publication_types, timespan, match_cfg + author_ids, keywords, operator, publication_types, timespan, fuzzy ), cluster=ESCluster.NES, ) @@ -727,11 +724,11 @@ def _build_query( author_ids: list[str], publication_types: list[PublicationType], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds the Elasticsearch query that returns the raw stats per author.""" work_filters = [ - _build_keyword_query(keywords, operator, config), + _build_keyword_query(keywords, operator, fuzzy), _author_filter(author_ids), ] if publication_types: @@ -794,7 +791,7 @@ def _build_publication_type_counts_query( operator: KeywordOperator, author_ids: list[str], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds the query that counts matching works per publication type. @@ -802,7 +799,7 @@ def _build_publication_type_counts_query( filter itself, since it aggregates over all types instead of one score. """ work_filters = [ - _build_keyword_query(keywords, operator, config), + _build_keyword_query(keywords, operator, fuzzy), _author_filter(author_ids), ] if timespan is not None: @@ -832,7 +829,7 @@ async def publication_type_counts_for_keywords( institution_id: str, career_stages: list[CareerStage], timespan: Timespan | None, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[PublicationTypeCount]: """Counts the university's matching works per publication type, largest first.""" author_ids = await _get_author_ids_from_institution(institution_id) @@ -844,7 +841,7 @@ async def publication_type_counts_for_keywords( author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages) query_body = _build_publication_type_counts_query( - keywords, operator, author_ids, timespan, _match_config(filter_type), + keywords, operator, author_ids, timespan, fuzzy, ) response: dict[str, Any] = await elasticsearch.search( @@ -1175,7 +1172,7 @@ async def rank_authors_by_keywords( publication_types: list[PublicationType], timespan: Timespan | None, company_status: CompanyStatusFilter = CompanyStatusFilter.ALL, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[RankedAuthor]: """Ranks the university's authors by a weighted score over works and citations. @@ -1193,8 +1190,7 @@ async def rank_authors_by_keywords( author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages) query_body = _build_query( - keywords, operator, author_ids, publication_types, timespan, - _match_config(filter_type), + keywords, operator, author_ids, publication_types, timespan, fuzzy, ) response: dict[str, Any] = await elasticsearch.search( diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index f4de7b12..15430231 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -12,11 +12,6 @@ class KeywordOperator(StrEnum): OR = "or" -class FilterType(StrEnum): - KEYWORD = "keyword" - TOPIC = "topic" - - class CompanyStatusFilter(StrEnum): ALL = "all" ACTIVE = "active" @@ -107,10 +102,12 @@ class KeywordToAuthorRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) - filter_type: FilterType = Field( - default=FilterType.KEYWORD, - description="What the 'keywords' values match against: 'keyword' (OpenAlex " - "keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.", + fuzzy: bool = Field( + default=False, + description="How the 'keywords' values are matched: True means they are " + "OpenAlex topic ids matched against the work's topics, False means they are " + "raw keywords matched as phrases in the work's title, abstract, keywords and " + "topic names. Defaults to False.", ) weights: RankingWeights = Field( description="Weights for the ranking metrics. Required.", @@ -133,7 +130,7 @@ class KeywordToAuthorRequest(BaseModel): "'all', only 'active' (non-deleted), or only 'deleted'.", ) - @field_validator("operator", "filter_type", mode="before") + @field_validator("operator", mode="before") @classmethod def operator_case_insensitive(cls, value): if isinstance(value, str): @@ -154,10 +151,12 @@ class SelectedAuthorsRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) - filter_type: FilterType = Field( - default=FilterType.KEYWORD, - description="What the 'keywords' values match against: 'keyword' (OpenAlex " - "keyword display names) or 'topic' (OpenAlex topic ids). Defaults to 'keyword'.", + fuzzy: bool = Field( + default=False, + description="How the 'keywords' values are matched: True means they are " + "OpenAlex topic ids matched against the work's topics, False means they are " + "raw keywords matched as phrases in the work's title, abstract, keywords and " + "topic names. Defaults to False.", ) publication_types: list[PublicationType] = Field( default_factory=list, @@ -175,13 +174,6 @@ class SelectedAuthorsRequest(BaseModel): return value.lower() return value - @field_validator("filter_type", mode="before") - @classmethod - def filter_type_case_insensitive(cls, value): - if isinstance(value, str): - return value.lower() - return value - class AuthorMetricsRequest(BaseModel): author_ids: list[str] = Field( @@ -204,10 +196,12 @@ class PublicationTypeCountsRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) - filter_type: FilterType = Field( - default=FilterType.KEYWORD, - description="What the 'keywords' values match against: 'keyword' (OpenAlex " - "keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.", + fuzzy: bool = Field( + default=False, + description="How the 'keywords' values are matched: True means they are " + "OpenAlex topic ids matched against the work's topics, False means they are " + "raw keywords matched as phrases in the work's title, abstract, keywords and " + "topic names. Defaults to False.", ) career_stages: list[CareerStage] = Field( default_factory=list, @@ -218,7 +212,7 @@ class PublicationTypeCountsRequest(BaseModel): description="Optional filter: only count works whose publication_year is within [from, to].", ) - @field_validator("operator", "filter_type", mode="before") + @field_validator("operator", mode="before") @classmethod def operator_case_insensitive(cls, value): if isinstance(value, str): @@ -290,15 +284,6 @@ class AuthorTopicStats(BaseModel): default=None, description="Latest publication year among the author's topic works.", ) - relevance_above_80_count: int = Field( - default=0, - description="Number of the author's topic works where the matched keyword's " - "relevance score is above 0.8.", - ) - avg_relevance: float = Field( - default=0.0, - description="Average matched-keyword relevance score (0-1) over the author's topic works.", - ) first_author_count: int = Field( default=0, description="Number of the author's topic works where they are the first author.", @@ -355,7 +340,7 @@ class AuthorTopicProfile(BaseModel): ) primary_topic_matches: int = Field( description="Matched works where one of the searched topics is the work's " - "primary topic (only meaningful for filter_type 'topic').", + "primary topic.", ) distinct_topics: int = Field( description="Number of distinct primary topics across all works.", diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index e0f0dd9b..a5fc843f 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -48,11 +48,11 @@ async def rank_author( ) logger.info( - "rank-author keywords=%s operator=%s filter_type=%s institution_id=%s career_stages=%s " + "rank-author keywords=%s operator=%s fuzzy=%s institution_id=%s career_stages=%s " "publication_types=%s timespan=%s", request.keywords, request.operator, - request.filter_type, + request.fuzzy, institution_id, request.career_stages, request.publication_types, @@ -67,7 +67,7 @@ async def rank_author( publication_types=request.publication_types, timespan=request.timespan, company_status=request.company_status, - filter_type=request.filter_type, + fuzzy=request.fuzzy, ) # Publication-type facet counts for the "Art der Work" filter @@ -86,11 +86,11 @@ async def publication_type_counts( ) logger.info( - "publication-type-counts keywords=%s operator=%s filter_type=%s institution_id=%s " + "publication-type-counts keywords=%s operator=%s fuzzy=%s institution_id=%s " "career_stages=%s timespan=%s", request.keywords, request.operator, - request.filter_type, + request.fuzzy, institution_id, request.career_stages, request.timespan, @@ -101,18 +101,18 @@ async def publication_type_counts( institution_id=institution_id, career_stages=request.career_stages, timespan=request.timespan, - filter_type=request.filter_type, + fuzzy=request.fuzzy, ) # Compare authors table 1 (topic stats) @router.post("/topic-stats", response_model=list[AuthorTopicStats]) async def topic_stats(request: SelectedAuthorsRequest): logger.info( - "topic-stats author_ids=%s keywords=%s operator=%s filter_type=%s publication_types=%s timespan=%s", + "topic-stats author_ids=%s keywords=%s operator=%s fuzzy=%s publication_types=%s timespan=%s", request.author_ids, request.keywords, request.operator, - request.filter_type, + request.fuzzy, request.publication_types, request.timespan, ) @@ -122,19 +122,19 @@ async def topic_stats(request: SelectedAuthorsRequest): request.operator, request.publication_types, request.timespan, - request.filter_type, + request.fuzzy, ) # Compare authors section 3 (topic profile over ALL works of each author) @router.post("/topic-profile", response_model=list[AuthorTopicProfile]) async def topic_profile(request: SelectedAuthorsRequest): logger.info( - "topic-profile author_ids=%s keywords=%s operator=%s filter_type=%s " + "topic-profile author_ids=%s keywords=%s operator=%s fuzzy=%s " "publication_types=%s timespan=%s", request.author_ids, request.keywords, request.operator, - request.filter_type, + request.fuzzy, request.publication_types, request.timespan, ) @@ -144,7 +144,7 @@ async def topic_profile(request: SelectedAuthorsRequest): request.operator, request.publication_types, request.timespan, - request.filter_type, + request.fuzzy, ) # Compare authors table 2 (author-level stats, keyword/time-independent) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index efd9cee6..8c7da681 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -138,7 +138,6 @@ model/extractedKeywordsLLM.ts model/extractedKeywordsResponse.ts model/fieldNode.ts model/fileUpload.ts -model/filterType.ts model/fp7EurosciVoc.ts model/fp7LegalBasis.ts model/fp7Organization.ts diff --git a/webapp/src/app/api/model/authorTopicProfile.ts b/webapp/src/app/api/model/authorTopicProfile.ts index fddb2ed6..075bc8ec 100644 --- a/webapp/src/app/api/model/authorTopicProfile.ts +++ b/webapp/src/app/api/model/authorTopicProfile.ts @@ -28,7 +28,7 @@ export interface AuthorTopicProfile { */ matched_works: number; /** - * Matched works where one of the searched topics is the work\'s primary topic (only meaningful for filter_type \'topic\'). + * Matched works where one of the searched topics is the work\'s primary topic. */ primary_topic_matches: number; /** diff --git a/webapp/src/app/api/model/authorTopicStats.ts b/webapp/src/app/api/model/authorTopicStats.ts index 15fac6d0..67d32eca 100644 --- a/webapp/src/app/api/model/authorTopicStats.ts +++ b/webapp/src/app/api/model/authorTopicStats.ts @@ -70,14 +70,6 @@ export interface AuthorTopicStats { industry_works_count?: number; first_year?: number | null; last_year?: number | null; - /** - * Number of the author\'s topic works where the matched keyword\'s relevance score is above 0.8. - */ - relevance_above_80_count?: number; - /** - * Average matched-keyword relevance score (0-1) over the author\'s topic works. - */ - avg_relevance?: number; /** * Number of the author\'s topic works where they are the first author. */ diff --git a/webapp/src/app/api/model/filterType.ts b/webapp/src/app/api/model/filterType.ts deleted file mode 100644 index bee9d0d7..00000000 --- a/webapp/src/app/api/model/filterType.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 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 const FilterType = { - Keyword: 'keyword', - Topic: 'topic' -} as const; -export type FilterType = typeof FilterType[keyof typeof FilterType]; - diff --git a/webapp/src/app/api/model/keywordToAuthorRequest.ts b/webapp/src/app/api/model/keywordToAuthorRequest.ts index 9821531e..4f420e16 100644 --- a/webapp/src/app/api/model/keywordToAuthorRequest.ts +++ b/webapp/src/app/api/model/keywordToAuthorRequest.ts @@ -8,7 +8,6 @@ * Do not edit the class manually. */ import { Timespan } from './timespan'; -import { FilterType } from './filterType'; import { CareerStage } from './careerStage'; import { KeywordOperator } from './keywordOperator'; import { PublicationType } from './publicationType'; @@ -25,9 +24,9 @@ export interface KeywordToAuthorRequest { */ operator?: KeywordOperator; /** - * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic display names). Defaults to \'keyword\'. + * How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False. */ - filter_type?: FilterType; + fuzzy?: boolean; /** * Weights for the ranking metrics. Required. */ diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 9c21b9fb..49619f6b 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -104,7 +104,6 @@ export * from './extractedKeywordsLLM'; export * from './extractedKeywordsResponse'; export * from './fieldNode'; export * from './fileUpload'; -export * from './filterType'; export * from './fp7EurosciVoc'; export * from './fp7LegalBasis'; export * from './fp7Organization'; diff --git a/webapp/src/app/api/model/publicationTypeCountsRequest.ts b/webapp/src/app/api/model/publicationTypeCountsRequest.ts index fe24986b..294ce4c7 100644 --- a/webapp/src/app/api/model/publicationTypeCountsRequest.ts +++ b/webapp/src/app/api/model/publicationTypeCountsRequest.ts @@ -8,7 +8,6 @@ * Do not edit the class manually. */ import { Timespan } from './timespan'; -import { FilterType } from './filterType'; import { CareerStage } from './careerStage'; import { KeywordOperator } from './keywordOperator'; @@ -22,9 +21,9 @@ export interface PublicationTypeCountsRequest { */ operator?: KeywordOperator; /** - * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic display names). Defaults to \'keyword\'. + * How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False. */ - filter_type?: FilterType; + fuzzy?: boolean; /** * Optional filter: only count works of authors in one of these career stages. Empty = no filter. */ diff --git a/webapp/src/app/api/model/selectedAuthorsRequest.ts b/webapp/src/app/api/model/selectedAuthorsRequest.ts index 79f008fe..9979fb5c 100644 --- a/webapp/src/app/api/model/selectedAuthorsRequest.ts +++ b/webapp/src/app/api/model/selectedAuthorsRequest.ts @@ -1,42 +1,37 @@ /** * 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 { Timespan } from './timespan'; -import { FilterType } from './filterType'; import { KeywordOperator } from './keywordOperator'; import { PublicationType } from './publicationType'; - -export interface SelectedAuthorsRequest { - /** - * 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?: KeywordOperator; - /** - * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic ids). Defaults to \'keyword\'. - */ - filter_type?: FilterType; - /** - * Optional filter: only count works of these publication types. Empty = no filter. - */ - publication_types?: Array; - timespan?: Timespan | null; +export interface SelectedAuthorsRequest { + /** + * 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?: KeywordOperator; + /** + * How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False. + */ + fuzzy?: boolean; + /** + * Optional filter: only count works of these publication types. Empty = no filter. + */ + publication_types?: Array; + timespan?: Timespan | null; } -export namespace SelectedAuthorsRequest { -} - - +export namespace SelectedAuthorsRequest {} diff --git a/webapp/src/app/modules/compare-authors/compare-authors.component.scss b/webapp/src/app/modules/compare-authors/compare-authors.component.scss index 150ec838..eed11771 100644 --- a/webapp/src/app/modules/compare-authors/compare-authors.component.scss +++ b/webapp/src/app/modules/compare-authors/compare-authors.component.scss @@ -220,12 +220,6 @@ app-chip mat-icon { &.pos-last { color: var(--sg-primary); } - &.rel-count { - color: var(--sg-blue-highlight); - } - &.rel-avg { - color: var(--sg-blue-highlight); - } &.cit-total { color: var(--sg-error); } diff --git a/webapp/src/app/modules/compare-authors/compare-authors.component.ts b/webapp/src/app/modules/compare-authors/compare-authors.component.ts index 5116ec2a..86c97599 100644 --- a/webapp/src/app/modules/compare-authors/compare-authors.component.ts +++ b/webapp/src/app/modules/compare-authors/compare-authors.component.ts @@ -66,9 +66,6 @@ interface AuthorSummary { // active years within the topic firstYear: number | null; lastYear: number | null; - // topic-relevance (matched keyword score) - relevanceAbove80: number | null; - avgRelevance: number | null; // author-position split (first / middle / last) firstAuthor: number | null; middleAuthor: number | null; @@ -227,8 +224,6 @@ export class CompareAuthorsComponent implements OnInit { : null, firstYear: t?.first_year ?? null, lastYear: t?.last_year ?? null, - relevanceAbove80: t?.relevance_above_80_count ?? null, - avgRelevance: t?.avg_relevance ?? null, firstAuthor: t?.first_author_count ?? null, middleAuthor: t?.middle_author_count ?? null, lastAuthor: t?.last_author_count ?? null, @@ -319,23 +314,6 @@ export class CompareAuthorsComponent implements OnInit { }, ], ), - this.buildGroupRow( - 'Themen-Relevanz', - 'Match-Score der Keywords: Werke > 80% | Ø über alle', - [ - { - label: '> 80%', - colorClass: 'rel-count', - select: (a) => a.relevanceAbove80, - }, - { - label: 'Ø', - colorClass: 'rel-avg', - decimals: true, - select: (a) => a.avgRelevance, - }, - ], - ), this.buildGroupRow( 'Autor-Position', 'Werke nach Position (Erst | Mittel | Letzt)', @@ -765,6 +743,8 @@ export class CompareAuthorsComponent implements OnInit { const rawAuthors = this.route.snapshot.queryParamMap.get('authors') ?? ''; const rawKeywords = this.route.snapshot.queryParamMap.get('keywords') ?? ''; const rawOperator = this.route.snapshot.queryParamMap.get('operator'); + const rawTopics = this.route.snapshot.queryParamMap.get('topics') ?? ''; + const fuzzy = this.route.snapshot.queryParamMap.get('fuzzy') === 'true'; const rawPubType = this.route.snapshot.queryParamMap.get('pubType'); const rawTFrom = this.route.snapshot.queryParamMap.get('tFrom'); const rawTTo = this.route.snapshot.queryParamMap.get('tTo'); @@ -793,11 +773,13 @@ export class CompareAuthorsComponent implements OnInit { const fullIds = authorIds.map((id) => `https://openalex.org/${id}`); this.authorIds.set(fullIds); + // same two match modes as the persons list: topic ids when fuzzy, raw keywords otherwise + const topicIds = this.parseList(rawTopics); const request: SelectedAuthorsRequest = { author_ids: fullIds, - keywords: keywords, + keywords: fuzzy && topicIds.length > 0 ? topicIds : keywords, operator: operator, - filter_type: 'topic', + fuzzy: fuzzy && topicIds.length > 0, publication_types: publication_types, timespan: timespan, }; 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 3a656f21..5597647d 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 @@ -29,7 +29,7 @@ + (change)="toggleSelect(author, $event)" /> 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 e9c4645e..8c8ef351 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,11 +1,15 @@ import { Component, OnInit, computed, inject, signal } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { distinctUntilChanged, map, skip } from 'rxjs'; import { DecimalPipe } from '@angular/common'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; -import { MatCheckboxModule } from '@angular/material/checkbox'; +import { + MatCheckboxChange, + MatCheckboxModule, +} from '@angular/material/checkbox'; import { MatIconModule } from '@angular/material/icon'; import { MatSnackBar } from '@angular/material/snack-bar'; import { FormsModule } from '@angular/forms'; @@ -98,6 +102,35 @@ export class KeywordsToPersonsResultsComponent implements OnInit { return p && p['size'] ? +p['size'] || 10 : 10; }); + // The ranking matches the same two ways the works tab does: with fuzzy on, + // the searched values are the OpenAlex topic ids; with fuzzy off, they are the + // raw keywords. The url is authoritative for the ids (deep links, reload), + // with the parent state as fallback. + private readonly urlTopicIds = computed(() => { + const raw = this.queryParams()?.['topics']; + if (!raw) return []; + const joined = Array.isArray(raw) ? raw.join(',') : raw; + return joined + .split(',') + .map((id: string) => id.trim()) + .filter(Boolean); + }); + + private readonly topicIds = computed(() => { + const fromUrl = this.urlTopicIds(); + return fromUrl.length > 0 ? fromUrl : this.state.topicIds(); + }); + + // fuzzy only applies when topic ids are actually available; without them the + // works tab falls back to matching the raw keywords, and so does this + private readonly fuzzyMatch = computed( + () => this.state.fuzzySearch() && this.topicIds().length > 0, + ); + + private readonly searchTerms = computed(() => + this.fuzzyMatch() ? this.topicIds() : this.state.keywordsList(), + ); + readonly paginatedAuthors = computed(() => { const all = this.authors(); const start = this.pageIndex() * this.pageSize(); @@ -297,6 +330,23 @@ export class KeywordsToPersonsResultsComponent implements OnInit { private hasLoadedInitial = false; + constructor() { + // The Fuzzy Search toggle sits in the parent component and only writes to + // the url, so the ranking has to be re-requested when the flag flips. + // skip(1) drops the state at mount, which the initial load already covers. + this.route.queryParamMap + .pipe( + map((params) => params.get('fuzzy') === 'true'), + distinctUntilChanged(), + skip(1), + takeUntilDestroyed(), + ) + .subscribe(() => { + this.loadAuthors(); + this.loadPublicationTypeCounts(); + }); + } + ngOnInit(): void { // restore the timespan from the URL so the range is shareable/bookmarkable this.timespanFrom.set(this.readYearParam('tFrom', this.minYear)); @@ -419,7 +469,7 @@ export class KeywordsToPersonsResultsComponent implements OnInit { return this.selectedIds().includes(this.authorProfileId(author)); } - toggleSelect(author: RankedAuthor): void { + toggleSelect(author: RankedAuthor, event?: MatCheckboxChange): void { const id = this.authorProfileId(author); const current = this.selectedIds(); @@ -429,6 +479,11 @@ export class KeywordsToPersonsResultsComponent implements OnInit { } if (current.length >= this.MAX_SELECTED) { + // the checkbox already toggled itself, so revert it: the [checked] input + // does not change here and would leave the box visually ticked + if (event) { + event.source.checked = false; + } this.snackBar.open( `Es können maximal ${this.MAX_SELECTED} Autoren verglichen werden.`, 'OK', @@ -449,7 +504,9 @@ export class KeywordsToPersonsResultsComponent implements OnInit { this.router.navigate(['/compare'], { queryParams: { authors: this.selectedIds().join(','), - keywords: this.state.topicsList().join(','), + keywords: this.state.keywordsList().join(','), + topics: this.fuzzyMatch() ? this.topicIds().join(',') : null, + fuzzy: this.fuzzyMatch(), operator: this.keywordOperator(), pubType: this.selectedPubTypes().length > 0 @@ -465,9 +522,9 @@ export class KeywordsToPersonsResultsComponent implements OnInit { const rawWeights = this.currentWeights().raw; const request: KeywordToAuthorRequest = { - keywords: this.state.topicsList(), + keywords: this.searchTerms(), operator: this.keywordOperator(), - filter_type: 'topic', + fuzzy: this.fuzzyMatch(), publication_types: this.selectedPubTypes().length > 0 ? this.selectedPubTypes() @@ -506,9 +563,9 @@ export class KeywordsToPersonsResultsComponent implements OnInit { // career-stage/timespan filters — drives the "Art der Work" filter options private loadPublicationTypeCounts(): void { const request: PublicationTypeCountsRequest = { - keywords: this.state.topicsList(), + keywords: this.searchTerms(), operator: this.keywordOperator(), - filter_type: 'topic', + fuzzy: this.fuzzyMatch(), career_stages: this.careerStages().length > 0 ? this.careerStages() : undefined, timespan: { diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html index 367f76e9..b66690d0 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html @@ -22,14 +22,9 @@ + [checked]="state.fuzzySearch()"> Fuzzy Search @@ -77,8 +72,8 @@ [active]="rla.isActive" [queryParams]="{ keywords: state.payload()?.keywords?.join(','), - fuzzy: tabFuzzyValue(route), - topics: tabFuzzyValue(route) ? state.topicIds() : null, + fuzzy: state.payload()?.options?.fuzzy, + topics: state.payload()?.options?.fuzzy ? state.topicIds() : null, topicId: null, }" queryParamsHandling="replace"> diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts index 6eea693b..2d73ed7b 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts @@ -1,4 +1,4 @@ -import { Component, computed, inject, signal } from '@angular/core'; +import { Component, computed, inject } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, @@ -76,8 +76,6 @@ export class KeywordsSearchResultsComponent { { path: 'trends', label: 'Visualisierung', icon: BAR_CHART_ICON }, ]; - private readonly lastUserFuzzy = signal(false); - readonly selectedKeywordCount = computed(() => this.state.keywords().length); readonly allKeywordEntries = computed(() => { const seen = new Set(); @@ -100,12 +98,7 @@ export class KeywordsSearchResultsComponent { // previous search never gets silently applied to a new one. this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe((params) => { const keywords = this.parseKeywordList(params.get('keywords')); - const onPersonsTab = this.isPersonsTab(); - const fuzzySearch = onPersonsTab || params.get('fuzzy') === 'true'; - - if (!onPersonsTab) { - this.lastUserFuzzy.set(params.get('fuzzy') === 'true'); - } + const fuzzySearch = params.get('fuzzy') === 'true'; const cached = this.readHandoffCache(); const cacheMatches = @@ -120,22 +113,9 @@ export class KeywordsSearchResultsComponent { ? cached!.patentKeywordEntries : undefined, }); - - if (onPersonsTab && params.get('fuzzy') !== 'true') { - this.updateQueryParams(true); - } }); } - // the Fuzzy Search toggle is locked on while the Personen tab is active - isPersonsTab(): boolean { - return this.route.snapshot.firstChild?.routeConfig?.path === 'persons'; - } - - tabFuzzyValue(route: { path: string }): boolean { - if (route.path === 'persons') return true; - return this.lastUserFuzzy(); - } goBackToSearch(): void { void this.router.navigate(['/keywords'], { queryParamsHandling: 'merge',