From e7afd7e68a46db2ecba47145fd08f98cb7032e61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Fri, 24 Jul 2026 13:35:48 +0200 Subject: [PATCH] feat(service/collaboration-graph): created optimized v2 for collaboration graph generation --- service/src/main/inse/authors/v2/model.py | 93 +++++++ service/src/main/inse/authors/v2/router.py | 67 ++++- service/src/main/inse/authors/v2/service.py | 265 +++++++++++++++++++- 3 files changed, 422 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/authors/v2/model.py b/service/src/main/inse/authors/v2/model.py index 47a78aa7..b185af11 100644 --- a/service/src/main/inse/authors/v2/model.py +++ b/service/src/main/inse/authors/v2/model.py @@ -1,7 +1,100 @@ +from enum import StrEnum + from inse.model import Page from inse.models.openalex.author import Author +from pydantic import BaseModel, Field class AuthorPage(Page[Author]): """A paginated response containing a list of authors.""" + +class MatchMode(StrEnum): + AND = "and" + OR = "or" + + +class GraphFilterType(StrEnum): + PUBLICATION_FILTERED = "publication_filtered" + COLLABORATOR_FILTERED = "collaborator_filtered" + + +class AuthorNode(BaseModel): + id: str = Field(description="The ID of the author.") + display_name: str = Field(description="The display name of the author.") + + +class InstitutionNode(BaseModel): + id: str = Field(description="The ID of the institution.") + display_name: str = Field(description="The display name of the institution.") + + +class WorkNode(BaseModel): + id: str = Field(description="The ID of the work.") + display_name: str = Field(description="The title of the work.") + publication_year: int = Field(description="The publication year of the work.") + + +class Edge(BaseModel): + source: str = Field(description="The ID of the source node.") + target: str = Field(description="The ID of the target node.") + weight: float = Field(description="The weight of the edge.") + + +class InternalCollaborationGraph(BaseModel): + root_author_id: str = Field(description="The ID of the root author.") + authors: dict[str, AuthorNode] = Field( + default_factory=dict, + description="A dictionary of author nodes, keyed by author ID.", + ) + institutions: dict[str, InstitutionNode] = Field( + default_factory=dict, + description="A dictionary of institution nodes, keyed by institution ID.", + ) + works: dict[str, WorkNode] = Field( + default_factory=dict, + description="A dictionary of work nodes, keyed by work ID.", + ) + edges: list[Edge] = Field( + default_factory=list, description="A list of edges in the collaboration graph." + ) + + def add_author(self, author: AuthorNode) -> None: + self.authors.setdefault(author.id, author) + + def add_institution(self, institution: InstitutionNode) -> None: + self.institutions.setdefault(institution.id, institution) + + def add_work(self, work: WorkNode) -> None: + self.works.setdefault(work.id, work) + + def add_edge(self, edge: Edge) -> None: + self.edges.append(edge) + + +class CollaborationGraph(BaseModel): + root_author_id: str = Field(description="The ID of the root author.") + authors: list[AuthorNode] = Field( + default_factory=list, description="A list of author nodes." + ) + institutions: list[InstitutionNode] = Field( + default_factory=list, description="A list of institution nodes." + ) + works: list[WorkNode] = Field( + default_factory=list, description="A list of work nodes." + ) + edges: list[Edge] = Field( + default_factory=list, description="A list of edges in the collaboration graph." + ) + + @classmethod + def from_internal_graph( + cls, internal_graph: InternalCollaborationGraph + ) -> "CollaborationGraph": + return cls( + root_author_id=internal_graph.root_author_id, + authors=list(internal_graph.authors.values()), + institutions=list(internal_graph.institutions.values()), + works=list(internal_graph.works.values()), + edges=internal_graph.edges, + ) diff --git a/service/src/main/inse/authors/v2/router.py b/service/src/main/inse/authors/v2/router.py index bd385b85..0155e5e1 100644 --- a/service/src/main/inse/authors/v2/router.py +++ b/service/src/main/inse/authors/v2/router.py @@ -2,8 +2,11 @@ import logging from typing import Annotated import inse.authors.v2.service as authors_service -from fastapi import APIRouter, Query -from inse.authors.v2.model import AuthorPage +from fastapi import APIRouter, Path, Query +from inse.authors.v2.model import ( + AuthorPage, + CollaborationGraph, +) from inse.router_prefixes import RouterPrefixes from inse.tags import Tags @@ -41,3 +44,63 @@ async def autocomplete_authors_for_selector( ] = "", ) -> AuthorPage: return await authors_service.autocomplete_authors_for_selector(query=query) + + +@router.get( + "/collaboration-graph/{raw_oa_author_id}", + operation_id="getCollaborationGraph", + summary="Returns a collaboration graph for a given author ID.", +) +async def get_collaboration_graph( + raw_oa_author_id: Annotated[ + str, + Path( + description="The raw OpenAlex author ID for which to retrieve the collaboration graph." + ), + ], + year_from: Annotated[ + int | None, + Query( + description="The starting year to filter the works by (optional).", + ), + ] = None, + year_to: Annotated[ + int | None, + Query( + description="The ending year to filter the works by (optional).", + ), + ] = None, + min_collaborators: Annotated[ + int | None, + Query( + description="The minimum number of collaborators to filter the works by (optional).", + ), + ] = None, + max_collaborators: Annotated[ + int | None, + Query( + description="The maximum number of collaborators to filter the works by (optional).", + ), + ] = None, + topic_ids: Annotated[ + list[str] | None, + Query( + description="A list of topic IDs to filter the works by (optional).", + ), + ] = None, + institution_ids: Annotated[ + list[str] | None, + Query( + description="A list of institution IDs to filter the works by (optional).", + ), + ] = None, +) -> CollaborationGraph: + return await authors_service.get_collaboration_graph( + raw_oa_author_id=raw_oa_author_id, + year_from=year_from, + year_to=year_to, + min_collaborators=min_collaborators, + max_collaborators=max_collaborators, + topic_ids=topic_ids, + institution_ids=institution_ids, + ) diff --git a/service/src/main/inse/authors/v2/service.py b/service/src/main/inse/authors/v2/service.py index 5abec7bb..ab99d33d 100644 --- a/service/src/main/inse/authors/v2/service.py +++ b/service/src/main/inse/authors/v2/service.py @@ -1,10 +1,25 @@ +import logging + +import inse.works.v2.service as works_service from inse.authors.institution_membership_query import ( build_active_institution_membership_query, ) -from inse.authors.v2.model import AuthorPage +from inse.authors.v2.model import ( + AuthorNode, + AuthorPage, + CollaborationGraph, + Edge, + InstitutionNode, + InternalCollaborationGraph, + MatchMode, + WorkNode, +) from inse.integrations import elasticsearch from inse.model import ESIndex from inse.models.openalex.author import Author +from inse.works.v2.model import WorkPageV2 + +logger = logging.getLogger(__name__) async def search_authors( @@ -154,3 +169,251 @@ async def authors_currently_belong_to_institution( source=["id"], ) return {author.id for author in authors.elements if author.id} + + +def _build_collaboration_graph_query( + raw_oa_author_id: str, + year_from: int | None = None, + year_to: int | None = None, + min_collaborators: int | None = None, + max_collaborators: int | None = None, + topic_ids: list[str] | None = None, + topic_match_mode: MatchMode = MatchMode.OR, + institution_ids: list[str] | None = None, +): + """Builds an Elasticsearch query for retrieving a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs. + + Args: + raw_oa_author_id (str): The raw OpenAlex author ID for which to build the collaboration graph. + year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None. + year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None. + min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None. + max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None. + topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None. + topic_match_mode (MatchMode, optional): The mode for matching topics (optional). Defaults to MatchMode.OR. + institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None. + + Raises: + ValueError: If the topic_match_mode is not valid. + ValueError: If the topic_ids list is empty. + ValueError: If the institution_ids list is empty. + + Returns: + _type_: The built Elasticsearch query for the collaboration graph. + """ + author_id = _prefix_id(raw_oa_author_id) + + must: list[dict] = [ + { + "nested": { + "path": "authorships", + "query": {"term": {"authorships.author.id": author_id}}, + } + } + ] + + if year_from is not None or year_to is not None: + range_query: dict = {} + if year_from is not None: + range_query["gte"] = year_from + if year_to is not None: + range_query["lte"] = year_to + must.append({"range": {"publication_year": range_query}}) + + if min_collaborators is not None or max_collaborators is not None: + range_query: dict = {} + if min_collaborators is not None: + range_query["gte"] = min_collaborators + if max_collaborators is not None: + range_query["lte"] = max_collaborators + must.append({"range": {"authors_count": range_query}}) + + if topic_ids is not None: + if not topic_ids: + raise ValueError("topic_ids must be a non-empty list if provided") + if topic_match_mode not in (MatchMode.OR, MatchMode.AND): + raise ValueError('topic_match_mode must be "or" or "and"') + + if topic_match_mode == MatchMode.OR: + must.append( + { + "nested": { + "path": "topics", + "query": {"terms": {"topics.id": topic_ids}}, + } + } + ) + else: + for topic_id in topic_ids: + must.append( + { + "nested": { + "path": "topics", + "query": {"term": {"topics.id": topic_id}}, + } + } + ) + + if institution_ids is not None: + if not institution_ids: + raise ValueError("institution_ids must be a non-empty list if provided") + must.append( + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": institution_ids + } + }, + } + }, + } + } + ) + + query = { + "bool": { + "must": must, + } + } + + logger.debug("Collaboration graph query for author %s: %s", raw_oa_author_id, query) + + return query + + +COLLABORATION_GRAPH_SOURCE_FIELDS = [ + "id", + "display_name", + "publication_year", + "authors_count", + "authorships.author.id", + "authorships.author.display_name", + "authorships.institutions.id", + "authorships.institutions.display_name", +] + + +async def get_collaboration_graph( + raw_oa_author_id: str, + year_from: int | None = None, + year_to: int | None = None, + min_collaborators: int | None = None, + max_collaborators: int | None = None, + topic_ids: list[str] | None = None, + institution_ids: list[str] | None = None, +) -> CollaborationGraph: + """Gets a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs. + + Args: + raw_oa_author_id (str): The raw OpenAlex author ID for which to retrieve the collaboration graph. + year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None. + year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None. + min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None. + max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None. + topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None. + institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None. + + Returns: + CollaborationGraph: The collaboration graph for the given author ID. + """ + + query = _build_collaboration_graph_query( + raw_oa_author_id=raw_oa_author_id, + year_from=year_from, + year_to=year_to, + min_collaborators=min_collaborators, + max_collaborators=max_collaborators, + topic_ids=topic_ids, + institution_ids=institution_ids, + ) + + work_page: WorkPageV2 = await works_service.search_works( + query=query, + source=COLLABORATION_GRAPH_SOURCE_FIELDS, + page=0, + size=10000, + sort=[{"publication_year": "desc"}, {"id": "asc"}], + ) + + return _build_collaboration_graph(page=work_page, raw_oa_author_id=raw_oa_author_id) + + +def _build_collaboration_graph( + page: WorkPageV2, raw_oa_author_id: str +) -> CollaborationGraph: + """Builds a collaboration graph from a page of works and a raw OpenAlex author ID. + + Args: + page (WorkPageV2): The page of works from which to build the collaboration graph. + raw_oa_author_id (str): The raw OpenAlex author ID for which to build the collaboration graph. + + Returns: + CollaborationGraph: The built collaboration graph. + """ + works = page.elements + internal_graph = InternalCollaborationGraph( + root_author_id=_prefix_id(raw_oa_author_id) + ) + + for work in works: + if not work.id or not work.display_name or not work.publication_year: + continue + + internal_graph.add_work( + WorkNode( + id=work.id, + display_name=work.display_name, + publication_year=work.publication_year, + ) + ) + + for authorship in work.authorships or []: + author = authorship.author + if not author or not author.id or not author.display_name: + continue + + internal_graph.add_author( + AuthorNode(id=author.id, display_name=author.display_name) + ) + + for institution in authorship.institutions or []: + if ( + not institution + or not institution.id + or not institution.display_name + ): + continue + + internal_graph.add_institution( + InstitutionNode( + id=institution.id, display_name=institution.display_name + ) + ) + + internal_graph.add_edge( + Edge(source=author.id, target=institution.id, weight=1.0) + ) + + internal_graph.add_edge(Edge(source=author.id, target=work.id, weight=1.0)) + + return CollaborationGraph.from_internal_graph(internal_graph) + + +def _prefix_id(raw_oa_id: str) -> str: + """Prefixes the raw OpenAlex ID with "https://openalex.org/" if it does not already start with that prefix. + + Args: + raw_oa_id (str): The raw OpenAlex ID to prefix. + + Returns: + str: The prefixed OpenAlex ID. + """ + + if not raw_oa_id.startswith("https://openalex.org/"): + return f"https://openalex.org/{raw_oa_id}" + return raw_oa_id