fix(collaboration-graph-v2)removed deprecated service and models
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Mats Paul Tončik
2026-07-25 17:52:26 +02:00
parent be556f09ad
commit d29028a5bd
22 changed files with 29 additions and 1601 deletions
@@ -1,43 +0,0 @@
from typing import Annotated, Optional
from fastapi import APIRouter, Body, Path, status
from inse.collaboration_network.schemas import (
CollaborationNetwork,
FilterProperties,
)
from inse.tags import Tags
import inse.collaboration_network.service as collaboration_network_service
router = APIRouter(
prefix="/api/person/network", tags=[Tags.PERSON_NETWORK]
)
@router.post(
"/{raw_user_id}",
summary="Get a person's collaboration network.",
description="Returns a person's collaboration network based on their works and co-authors.",
operation_id="getCollaborationNetwork",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": CollaborationNetwork,
},
status.HTTP_404_NOT_FOUND: {"description": "Person not found"},
},
)
async def get_collaboration_network(
raw_user_id: Annotated[str, Path(description="The raw user ID of the person.")],
filter_properties: Annotated[
Optional[FilterProperties],
Body(
description="The filter properties for the collaboration network.",
),
] = None,
) -> CollaborationNetwork:
return await collaboration_network_service.get_collaboration_network(
raw_user_id=raw_user_id,
filter_properties=filter_properties,
)
@@ -1,273 +0,0 @@
from enum import Enum
from typing import List, Optional, Set
from pydantic import BaseModel, Field
from inse.models.openalex.work_topic import WorkTopic
from inse.utils import extract_raw_topic_id
class InstitutionInformation(BaseModel):
raw_id: str = Field(
title="Raw Institution ID",
description="The raw institution ID of the institution.",
)
display_name: str = Field(
title="Institution Display Name",
description="The display name of the institution.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, InstitutionInformation):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class WorkTopicInformation(BaseModel):
raw_topic_id: str = Field(
title="Topic ID",
description="The ID of the topic.",
)
display_name: str = Field(
title="Topic Name",
description="The name of the topic.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, WorkTopicInformation):
return self.raw_topic_id == value.raw_topic_id
return False
def __hash__(self) -> int:
return hash(self.raw_topic_id)
@classmethod
def from_topic(cls, topic: WorkTopic) -> "WorkTopicInformation":
"""Creates a WorkTopicInformation instance from a WorkTopic instance.
Args:
topic (WorkTopic): The WorkTopic instance to create the WorkTopicInformation from.
Returns:
WorkTopicInformation: The created WorkTopicInformation instance.
"""
return cls(
raw_topic_id=extract_raw_topic_id(str(topic.id)),
display_name=str(topic.display_name),
)
class CollaborationNetworkNodeType(str, Enum):
AUTHOR = "author"
INSTITUTION = "institution"
WORK = "work"
class FilterInformation(BaseModel):
min_possible_year: int = Field(
title="Minimum Year",
description="The minimum publication year of the works in the collaboration network.",
)
max_possible_year: int = Field(
title="Maximum Year",
description="The maximum publication year of the works in the collaboration network.",
)
institutions: List[InstitutionInformation] = Field(
title="Institutions",
description="The list of institutions associated with the works in the collaboration network.",
)
topics: List[WorkTopicInformation] = Field(
title="Topics",
description="The list of topics associated with the works in the collaboration network.",
)
class WorksFilterProperties(BaseModel):
start_year: int = Field(
default=0,
title="Start Year",
description="The start publication year for the works to include in the collaboration network.",
)
end_year: int = Field(
default=9999,
title="End Year",
description="The end publication year for the works to include in the collaboration network.",
)
allowed_topics: List[str] = Field(
default_factory=list,
title="Allowed Topics",
description="The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included.",
)
min_contributors: int = Field(
default=1,
title="Minimum Contributors",
description="The minimum number of contributors required for a work to be included in the collaboration network.",
)
max_contributors: int = Field(
default=100,
title="Maximum Contributors",
description="The maximum number of contributors allowed for a work to be included in the collaboration network.",
)
class AuthorsFilterProperties(BaseModel):
allowed_institutions: List[str] = Field(
default_factory=list,
title="Allowed Institutions",
description="The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included.",
)
min_collaborations: int = Field(
default=1,
title="Minimum Collaborations",
description="The minimum number of collaborations required for an author to be included in the collaboration network.",
)
max_collaborations: int = Field(
default=1000,
title="Maximum Collaborations",
description="The maximum number of collaborations allowed for an author to be included in the collaboration network.",
)
class FilterProperties(BaseModel):
filter_by: str = Field(
default="works",
title="Filter By",
description="The type of filter to apply when generating the collaboration network. Can be either 'works' or 'authors'. If 'works', the filter properties in the 'works_filter_properties' field will be used. If 'authors', the filter properties in the 'authors_filter_properties' field will be used.",
)
works_filter_properties: Optional[WorksFilterProperties] = Field(
title="Works Filter Properties",
description="The filter properties to apply when filtering works for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'works'.",
)
authors_filter_properties: Optional[AuthorsFilterProperties] = Field(
title="Authors Filter Properties",
description="The filter properties to apply when filtering authors for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'authors'.",
)
class CollaborationNetworkNode(BaseModel):
raw_id: str = Field(
title="Raw ID",
description="The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID.",
)
display_name: str = Field(
title="Display Name", description="The display name of the node."
)
category: CollaborationNetworkNodeType = Field(
title="Category",
description="The category of the node, either 'author', 'institution', or 'work'.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, CollaborationNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class WorkNetworkNode(CollaborationNetworkNode):
publication_year: Optional[int] = Field(
title="Publication Year",
description="The publication year of the work represented by this node. This field is only applicable if the category of the node is 'work'.",
)
work_topics_information: Optional[Set[WorkTopicInformation]] = Field(
title="Work Topics Information",
description="The list of topic information associated with the work represented by this node. This field is only applicable if the category of the node is 'work'.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, WorkNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class AuthorNetworkNode(CollaborationNetworkNode):
def __eq__(self, value: object) -> bool:
if isinstance(value, AuthorNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class InstitutionNetworkNode(CollaborationNetworkNode):
def __eq__(self, value: object) -> bool:
if isinstance(value, InstitutionNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class CollaborationNetworkEdge(BaseModel):
raw_source_id: str = Field(
title="Source Raw ID",
description="The raw ID of the source node.",
)
raw_target_id: str = Field(
title="Target Raw ID",
description="The raw ID of the target node.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, CollaborationNetworkEdge):
return self.same_collaboration(self, value)
return False
def __hash__(self) -> int:
return hash((self.raw_source_id, self.raw_target_id))
@classmethod
def same_collaboration(
cls, edge1: "CollaborationNetworkEdge", edge2: "CollaborationNetworkEdge"
) -> bool:
"""Checks if two edges have the same source and target person IDs, regardless of order.
Args:
edge1 (CollaborationNetworkEdge): The first collaboration edge.
edge2 (CollaborationNetworkEdge): The second collaboration edge.
Returns:
bool: True if the edges have the same source and target person IDs (undirected), False otherwise.
"""
return (
edge1.raw_source_id == edge2.raw_source_id
and edge1.raw_target_id == edge2.raw_target_id
) or (
edge1.raw_source_id == edge2.raw_target_id
and edge1.raw_target_id == edge2.raw_source_id
)
class CollaborationNetwork(BaseModel):
raw_person_id: str = Field(
title="Raw Person ID",
description="The raw person ID of the person whose collaboration network this is.",
)
work_nodes: List[WorkNetworkNode] = Field(
title="Collaboration Network Work Nodes",
description="The work nodes in the collaboration network.",
)
author_nodes: List[AuthorNetworkNode] = Field(
title="Collaboration Network Author Nodes",
description="The author nodes in the collaboration network.",
)
institution_nodes: List[InstitutionNetworkNode] = Field(
title="Collaboration Network Institution Nodes",
description="The institution nodes in the collaboration network.",
)
collaboration_edges: List[CollaborationNetworkEdge] = Field(
title="Collaboration Network Edges",
description="The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I",
)
filter_information: FilterInformation = Field(
title="Filter Information",
description="The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network.",
)
@@ -1,708 +0,0 @@
from collections import defaultdict
import logging
from typing import List, Optional, Set, Tuple
from inse.collaboration_network.schemas import (
AuthorNetworkNode,
AuthorsFilterProperties,
CollaborationNetwork,
CollaborationNetworkEdge,
CollaborationNetworkNodeType,
FilterInformation,
FilterProperties,
InstitutionInformation,
InstitutionNetworkNode,
WorkNetworkNode,
WorkTopicInformation,
WorksFilterProperties,
)
from inse.works import logic as work_logic
from inse.works.model import Work
from inse.utils import (
extract_raw_author_id,
extract_raw_institution_id,
extract_raw_topic_id,
extract_raw_work_id,
)
from inse.models.openalex.author import Author
from inse.models.openalex.authorship import Authorship
from inse.models.openalex.dehydrated_author import DehydratedAuthor
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_collaboration_network(
raw_user_id: str,
filter_properties: FilterProperties,
) -> CollaborationNetwork:
"""Generates a collaboration network for a given user ID based on the works associated with that user, and applies filtering to the network based on the specified filter properties, which may include criteria such as publication year range, allowed topics, minimum/maximum number of contributors, and minimum/maximum number of collaborations.
The function returns a collaboration network that includes the works, authors, and institutions that are relevant to the specified user and meet the filtering criteria defined in the filter properties.
Args:
raw_user_id (str): The raw user ID for whom to generate the collaboration network.
filter_properties (FilterProperties): The filter properties for the collaboration network.
Returns:
CollaborationNetwork: The collaboration network for the given user.
"""
raw_user_id = raw_user_id.strip().upper()
work_page = await work_logic.get_all_author_works(author_id=raw_user_id)
works: List[Work] = work_page.results or []
collaboration_network = build_collaboration_network(
raw_user_id=raw_user_id, works=works
)
if filter_properties.filter_by == "works":
if not filter_properties.works_filter_properties:
filter_properties.works_filter_properties = WorksFilterProperties()
return filter_collaboration_network_by_works(
raw_user_id=raw_user_id,
collaboration_network=collaboration_network,
works_filter_properties=filter_properties.works_filter_properties,
)
elif filter_properties.filter_by == "authors":
if not filter_properties.authors_filter_properties:
filter_properties.authors_filter_properties = AuthorsFilterProperties()
return filter_collaboration_network_by_authors(
raw_user_id=raw_user_id,
collaboration_network=collaboration_network,
filter_properties=filter_properties.authors_filter_properties,
)
else:
logger.warning(
f"Invalid filter_by value in filter properties: {filter_properties.filter_by}. Expected 'works' or 'authors'. No additional filtering will be applied."
)
return collaboration_network
def filter_collaboration_network_by_authors(
raw_user_id: str,
collaboration_network: CollaborationNetwork,
filter_properties: AuthorsFilterProperties,
) -> CollaborationNetwork:
"""Filters the given collaboration network based on the specified author filter properties, which may include criteria such as allowed institutions and minimum/maximum number of collaborations.
The function returns a new collaboration network that only includes authors that meet the specified criteria, along with their associated works and institutions.
Args:
raw_user_id (str): The raw user ID for whom to filter the collaboration network.
collaboration_network (CollaborationNetwork): The collaboration network to filter.
filter_properties (AuthorsFilterProperties): The filter properties for the author filtering.
Returns:
CollaborationNetwork: The filtered collaboration network.
"""
logger.debug(
f"Filtering collaboration network for user {raw_user_id} with author filter properties: {filter_properties}"
)
all_author_nodes = set(collaboration_network.author_nodes)
remaining_author_ids = {node.raw_id for node in all_author_nodes}
remaining_institution_nodes = set(collaboration_network.institution_nodes)
logger.debug(f"Remaining author IDs before filtering: {remaining_author_ids}")
# 1. Filter author nodes based on allowed institutions in filter properties
if len(filter_properties.allowed_institutions) > 0:
logger.debug(
f"Filtering author nodes based on allowed institutions: {filter_properties.allowed_institutions}"
)
remaining_author_ids = {
edge.raw_source_id
for edge in collaboration_network.collaboration_edges
if edge.raw_target_id in filter_properties.allowed_institutions
}
remaining_institution_nodes = {
node
for node in collaboration_network.institution_nodes
if node.raw_id in filter_properties.allowed_institutions
}
logger.debug(
f"Remaining author IDs after filtering by allowed institutions: {remaining_author_ids}"
)
# 2. Filter out collaboration edges that are associated with author nodes that have been filtered out
remaining_work_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("w")
}
logger.debug(
f"Remaining work edges after filtering by allowed institutions: {len(remaining_work_edges)}"
)
works_per_author = defaultdict(set)
for edge in remaining_work_edges:
if (
edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("w")
):
works_per_author[edge.raw_source_id].add(edge.raw_target_id)
logger.debug(
f"Works per author after filtering by allowed institutions: {dict(works_per_author)}"
)
# 3. Filter out author that do not have enough collaborations based on the filter properties
remaining_author_ids = {
author_id
for author_id, work_ids in works_per_author.items()
if filter_properties.min_collaborations
<= len(work_ids)
<= filter_properties.max_collaborations
}
remaining_author_ids.add(raw_user_id) # main author always included
remaining_author_nodes = {
node
for node in collaboration_network.author_nodes
if node.raw_id in remaining_author_ids
}
remaining_institutions_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("i")
}
# 4. Remove institution nodes that are not connected to any of the remaining author nodes
institution_ids_with_remaining_authors = {
edge.raw_target_id
for edge in remaining_institutions_edges
if edge.raw_source_id in remaining_author_ids
}
remaining_institution_nodes = {
node
for node in remaining_institution_nodes
if node.raw_id in institution_ids_with_remaining_authors
}
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=collaboration_network.work_nodes,
author_nodes=list(remaining_author_nodes),
institution_nodes=list(remaining_institution_nodes),
collaboration_edges=list(remaining_work_edges)
+ list(remaining_institutions_edges),
filter_information=collaboration_network.filter_information,
)
def filter_collaboration_network_by_works(
raw_user_id: str,
collaboration_network: CollaborationNetwork,
works_filter_properties: WorksFilterProperties,
) -> CollaborationNetwork:
"""Filters the given collaboration network based on the specified works filter properties, which may include criteria such as publication year range, allowed topics, and minimum/maximum number of contributors.
The function returns a new collaboration network that only includes works that meet the specified criteria, along with their associated authors and institutions.
Args:
raw_user_id (str): _description_
collaboration_network (CollaborationNetwork): _description_
works_filter_properties (WorksFilterProperties): _description_
Returns:
CollaborationNetwork: The filtered collaboration network.
"""
if not works_filter_properties:
return collaboration_network
all_work_nodes = set(collaboration_network.work_nodes)
valid_work_ids = {node.raw_id for node in all_work_nodes}
# 1. Filter out works that are not in the specified year range or do not have allowed topics, and update valid_work_ids accordingly
valid_work_ids = filter_works_by_year_and_topic(
works=all_work_nodes,
filter_properties=works_filter_properties,
valid_work_ids=valid_work_ids,
)
# 2. Filter out works that do not have enough collaborators based on the filter properties, and update valid_work_ids accordingly
if (
works_filter_properties.min_contributors
or works_filter_properties.max_contributors
):
contributors_per_work = defaultdict(set)
for edge in collaboration_network.collaboration_edges:
if (
edge.raw_target_id.lower().startswith("w")
and edge.raw_target_id in valid_work_ids
):
contributors_per_work[edge.raw_target_id].add(edge.raw_source_id)
valid_work_ids = set()
for work_id, contributors in contributors_per_work.items():
contributors_count = len(contributors)
if has_enough_contributors(
contributors_count=contributors_count,
filter_properties=works_filter_properties,
):
valid_work_ids.add(work_id)
# 3. Filter out collaboration edges that are associated with works that have been filtered out
remaining_work_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_target_id in valid_work_ids
and edge.raw_target_id.lower().startswith("w")
}
# 4. Identify author nodes that are still valid based on their association with the remaining valid works
author_ids_with_valid_works = {edge.raw_source_id for edge in remaining_work_edges}
# 5. Identify institution nodes that are still valid based on their association with the remaining valid author nodes
institution_ids_with_valid_authors = {
edge.raw_target_id
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id.lower().startswith("i")
}
remaining_collaboration_edges = {
edge
for edge in collaboration_network.collaboration_edges
if (
edge.raw_target_id in valid_work_ids
and edge.raw_target_id.lower().startswith("w")
)
or (
edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id.lower().startswith("i")
)
or (
edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id in institution_ids_with_valid_authors
)
}
remaining_work_nodes = {
node
for node in collaboration_network.work_nodes
if node.raw_id in valid_work_ids
}
remaining_author_nodes = {
node
for node in collaboration_network.author_nodes
if node.raw_id in author_ids_with_valid_works
}
remaining_institution_nodes = {
node
for node in collaboration_network.institution_nodes
if node.raw_id in institution_ids_with_valid_authors
}
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=list(remaining_work_nodes),
author_nodes=list(remaining_author_nodes),
institution_nodes=list(remaining_institution_nodes),
collaboration_edges=list(remaining_collaboration_edges),
filter_information=collaboration_network.filter_information,
)
def filter_works_by_year_and_topic(
works: Set[WorkNetworkNode],
filter_properties: WorksFilterProperties,
valid_work_ids: Set[str],
):
"""Determines the set of valid work IDs by filtering the given set of works based on the specified year range and allowed topics defined in the filter properties.
Args:
works (Set[WorkNetworkNode]): The set of works to filter.
filter_properties (WorksFilterProperties): The filter properties containing the year range and allowed topics.
valid_work_ids (Set[str]): The set of valid work IDs to update.
Returns:
Set[str]: The updated set of valid work IDs.
"""
if not any(
[
filter_properties.start_year,
filter_properties.end_year,
filter_properties.allowed_topics,
]
):
return valid_work_ids
for work in works:
if not is_in_year_range(
year=work.publication_year or -1,
works_filter_properties=filter_properties,
) or not has_allowed_topic(work, filter_properties):
valid_work_ids.discard(work.raw_id)
return valid_work_ids
def is_in_year_range(year: int, works_filter_properties: WorksFilterProperties) -> bool:
"""Determines whether a given year falls within the specified year range defined in the filter properties.
Args:
year (int): The year to check.
works_filter_properties (WorksFilterProperties): The filter properties containing the year range.
Returns:
bool: True if the year falls within the specified range, False otherwise.
"""
# no year extracted, excluding work by default
if year == -1:
return False
if works_filter_properties.start_year and year < works_filter_properties.start_year:
return False
if works_filter_properties.end_year and year > works_filter_properties.end_year:
return False
return True
def has_allowed_topic(
work: WorkNetworkNode, filter_properties: WorksFilterProperties
) -> bool:
"""Determines whether a given work has at least one topic that is included in the allowed topics specified in the filter properties.
Args:
work (WorkNetworkNode): The work for which to check the topics.
filter_properties (WorksFilterProperties): The filter properties containing the allowed topics.
Returns:
bool: True if the work has at least one allowed topic, False otherwise.
"""
if len(filter_properties.allowed_topics) == 0:
return True
return any(
topic.raw_topic_id in filter_properties.allowed_topics
for topic in work.work_topics_information or set()
)
def has_enough_contributors(
contributors_count: int, filter_properties: WorksFilterProperties
) -> bool:
"""Determines whether a given number of contributors meets the specified minimum and maximum contributor requirements defined in the filter properties.
Args:
contributors_count (int): The number of contributors to check.
filter_properties (WorksFilterProperties): The filter properties containing the contributor requirements.
Returns:
bool: True if the contributor count meets the requirements, False otherwise.
"""
if filter_properties and contributors_count < filter_properties.min_contributors:
return False
if (
filter_properties.max_contributors
and contributors_count > filter_properties.max_contributors
):
return False
return True
def build_collaboration_network(
raw_user_id: str,
works: List[Work],
) -> CollaborationNetwork:
"""Builds a collaboration network for a given user ID based on the provided list of works.
Args:
raw_user_id (str): The raw ID of the user for whom to build the collaboration network.
works (List[Work]): The list of works for which to build the collaboration network.
Returns:
CollaborationNetwork: The built collaboration network.
"""
min_possible_year = float("inf")
max_possible_year = float("-inf")
work_nodes: Set[WorkNetworkNode] = set()
all_author_nodes: Set[AuthorNetworkNode] = set()
all_institution_nodes: Set[InstitutionNetworkNode] = set()
all_collaboration_edges: Set[CollaborationNetworkEdge] = set()
work_topics_information: Set[WorkTopicInformation] = set()
for work in works:
work_node, author_nodes, institution_nodes, collaboration_edges = process_work(
work=work
)
if not work_node:
continue
min_possible_year = min(
min_possible_year, work_node.publication_year or float("inf")
)
max_possible_year = max(
max_possible_year, work_node.publication_year or float("-inf")
)
work_topics_information.update(work_node.work_topics_information or set())
work_nodes.add(work_node)
all_author_nodes.update(author_nodes)
all_institution_nodes.update(institution_nodes)
all_collaboration_edges.update(collaboration_edges)
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=list(work_nodes),
author_nodes=list(all_author_nodes),
institution_nodes=list(all_institution_nodes),
collaboration_edges=list(all_collaboration_edges),
filter_information=FilterInformation(
min_possible_year=int(min_possible_year),
max_possible_year=int(max_possible_year),
institutions=sorted(
{
InstitutionInformation(
raw_id=institution.raw_id, display_name=institution.display_name
)
for institution in all_institution_nodes
},
key=lambda inst: inst.display_name,
),
topics=sorted(
work_topics_information, key=lambda topic: topic.display_name
),
),
)
def process_work(
work: Work,
) -> Tuple[
Optional[WorkNetworkNode],
Set[AuthorNetworkNode],
Set[InstitutionNetworkNode],
Set[CollaborationNetworkEdge],
]:
"""Processes a given work to extract the associated work node, author nodes, institution nodes, and collaboration edges for the collaboration network.
Args:
work (Work): The work to process.
Returns:
Tuple[ Optional[WorkNetworkNode], Set[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated work node, author nodes, institution nodes, and collaboration edges.
"""
year = get_work_year(work)
topics_information = extract_topics_information(work=work)
work_node = create_work_node(
work=work, year=year, work_topics_information=topics_information
)
if not work_node:
return None, set(), set(), set()
authorships = work.authorships
if not authorships:
return work_node, set(), set(), set()
author_nodes: Set[AuthorNetworkNode] = set()
institution_nodes: Set[InstitutionNetworkNode] = set()
collaboration_edges: Set[CollaborationNetworkEdge] = set()
for authorship in authorships:
author_node, institution_nodes, associated_institution_edges = (
process_authorship(authorship=authorship)
)
if not author_node:
continue
work_author_edge = CollaborationNetworkEdge(
raw_source_id=author_node.raw_id,
raw_target_id=work_node.raw_id,
)
author_nodes.add(author_node)
collaboration_edges.add(work_author_edge)
institution_nodes.update(institution_nodes)
collaboration_edges.update(associated_institution_edges)
return (
work_node,
author_nodes,
institution_nodes,
collaboration_edges,
)
def get_work_year(work: Work) -> int:
"""Extracts the publication year from a given work.
Args:
work (Work): The work from which to extract the publication year.
Returns:
int: The publication year of the work, or -1 if it cannot be extracted.
"""
if not work.publication_year:
return -1
try:
return int(work.publication_year)
except ValueError:
return -1
def create_work_node(
work: Work, year: int, work_topics_information: Set[WorkTopicInformation]
) -> Optional[WorkNetworkNode]:
"""Creates a collaboration network node representing a work based on the provided work data, publication year, and topic information.
Args:
work (Work): The work from which to create the collaboration network node.
year (int): The publication year of the work.
work_topics_information (Set[WorkTopicInformation]): The topic information of the work.
Returns:
Optional[WorkNetworkNode]: The collaboration network node representing the work, or None if the work data is invalid.
"""
if not work or not work.id or not work.display_name:
return None
work_id = extract_raw_work_id(work.id)
display_name = work.display_name
return WorkNetworkNode(
raw_id=work_id,
display_name=display_name,
category=CollaborationNetworkNodeType.WORK,
publication_year=year,
work_topics_information=work_topics_information,
)
def extract_topics_information(work: Work) -> Set[WorkTopicInformation]:
"""Extracts the topic information from a given work and returns it as a set of WorkTopicInformation objects.
Args:
work (Work): The work from which to extract topic information.
Returns:
Set[WorkTopicInformation]: A set of WorkTopicInformation objects representing the topics of the work.
"""
topics_information: Set[WorkTopicInformation] = set()
for topic in work.topics or []:
if not topic.id or not topic.display_name:
continue
raw_topic_id = extract_raw_topic_id(topic.id)
topics_information.add(
WorkTopicInformation(
raw_topic_id=raw_topic_id, display_name=topic.display_name
)
)
return topics_information
def process_authorship(
authorship: Authorship,
) -> Tuple[
Optional[AuthorNetworkNode],
Set[InstitutionNetworkNode],
Set[CollaborationNetworkEdge],
]:
"""Processes a given authorship to extract the associated author node, institution nodes, and collaboration edges.
Args:
authorship (Authorship): The authorship data to process.
Returns:
Tuple[ Optional[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated author node, institution nodes, and collaboration edges.
"""
author = authorship.author
if not author or not author.id or not author.display_name:
return None, set(), set()
author_node = create_author_node(author)
if not author_node:
return None, set(), set()
institution_nodes: Set[InstitutionNetworkNode] = set()
for institution in authorship.institutions or []:
institution_id = extract_raw_institution_id(institution.id or "")
if not institution_id or not institution.display_name:
continue
institution_node = create_institution_node(institution)
if institution_node:
institution_nodes.add(institution_node)
associated_institution_edges = create_associated_institution_edges(
author_node=author_node, institution_nodes=institution_nodes
)
return author_node, institution_nodes, associated_institution_edges
def create_associated_institution_edges(
author_node: AuthorNetworkNode,
institution_nodes: Set[InstitutionNetworkNode],
) -> Set[CollaborationNetworkEdge]:
"""Creates a set of collaboration network edges representing the associations between an author and their affiliated institutions.
Args:
author_node (AuthorNetworkNode): The collaboration network node representing the author.
institution_nodes (Set[InstitutionNetworkNode]): A set of collaboration network nodes representing the institutions affiliated with the author.
Returns:
Set[CollaborationNetworkEdge]: A set of collaboration network edges representing the associations between the author and their affiliated institutions.
"""
return {
CollaborationNetworkEdge(
raw_source_id=author_node.raw_id,
raw_target_id=institution_node.raw_id,
)
for institution_node in institution_nodes
}
def create_author_node(
author: Author | DehydratedAuthor,
) -> Optional[AuthorNetworkNode]:
"""Creates a collaboration network node representing an author based on the provided author data.
Args:
author (Author | DehydratedAuthor): The author data from which to create the collaboration network node.
Returns:
Optional[AuthorNetworkNode]: The collaboration network node representing the author, or None if the author data is invalid.
"""
if not author or not author.id or not author.display_name:
return None
author_id = extract_raw_author_id(author.id)
display_name = author.display_name
return AuthorNetworkNode(
raw_id=author_id,
display_name=display_name,
category=CollaborationNetworkNodeType.AUTHOR,
)
def create_institution_node(
institution: Institution | DehydratedInstitution,
) -> Optional[InstitutionNetworkNode]:
"""Creates a collaboration network node representing an institution based on the provided institution data.
Args:
institution (Institution | DehydratedInstitution): The institution data from which to create the collaboration network node.
Returns:
Optional[InstitutionNetworkNode]: The collaboration network node representing the institution, or None if the institution data is invalid.
"""
if not institution or not institution.id or not institution.display_name:
return None
institution_id = extract_raw_institution_id(institution.id)
display_name = institution.display_name
return InstitutionNetworkNode(
raw_id=institution_id,
display_name=display_name,
category=CollaborationNetworkNodeType.INSTITUTION,
)
+28 -31
View File
@@ -1,68 +1,66 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the bootstrapping code
for fastapi that loads the service and the
webapp.
"""
from contextlib import asynccontextmanager, contextmanager
import logging
from contextlib import asynccontextmanager, contextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from inse.collaboration_network.router import router as collaboration_network_router
from inse.account_management.router import router as account_management_router
from inse.auth.router import router as auth_router
from inse.auth.service import create_predefined_accounts
from inse.authors.v2.router import router as authors_v2_router
from inse.bookmarks.router import router as bookmarks_router
from inse.company_connections.service import router as company_connections_router
from inse.dashboard.router import router as dashboard_router
from inse.database import create_db_and_tables, get_session
from inse.exceptions import (
NotFoundException,
BadRequestException,
ElasticsearchException,
MissingApiKeyError,
NotFoundException,
UpstreamAPIException,
BadRequestException,
)
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
from inse.institutions.router import router as institutions_router
from inse.institutions.v2.router import router as institutions_v2_router
from inse.keywords.service import router as keywords_service_router
from inse.patents.keywords.service import router as keywords_patents_router
# caching
from inse.middleware.etag_cache import ETagCacheMiddleware
from inse.persons.service import router as persons_service_router
from inse.topics.service import router as topics_service_router
from inse.works.service import router as works_service_router
from inse.news.service import router as news_service_router
from inse.auth.router import router as auth_router
from inse.account_management.router import router as account_management_router
from inse.organization_management.router import router as organization_management_router
from inse.dashboard.router import router as dashboard_router
from inse.bookmarks.router import router as bookmarks_router
from inse.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session
from inse.auth.service import create_predefined_accounts
from . import config
from .service import router as service_router
from inse.patents.keywords.service import router as keywords_patents_router
from inse.patents.org.service import router as org_patents_router
from inse.patents.service import (
institution_patents_router,
)
from inse.patents.service import (
patents_router as patents_all_router,
)
from inse.patents.service import (
router as patents_service_router,
)
from inse.works.v2.router import router as works_v2_router
from inse.authors.v2.router import router as authors_v2_router
from inse.institutions.v2.router import router as institutions_v2_router
from inse.topics.v2.router import router as topics_v2_router
from inse.persons.service import router as persons_service_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router
from inse.projects.router import router as projects_router
from inse.ranking.router import router as ranking_router
from inse.topics.service import router as topics_service_router
from inse.topics.v2.router import router as topics_v2_router
from inse.university_ranking.service import router as university_ranking_router
from inse.works.service import router as works_service_router
from inse.works.v2.router import router as works_v2_router
from . import config
from .service import router as service_router
logger = logging.getLogger(__name__)
@@ -89,7 +87,6 @@ app = FastAPI(
servers=settings.servers,
lifespan=lifespan,
)
app.include_router(collaboration_network_router)
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
@@ -19,7 +19,6 @@ api/keywords.service.ts
api/news.service.ts
api/organization.service.ts
api/patents.service.ts
api/personNetwork.service.ts
api/persons.service.ts
api/projects.service.ts
api/ranking.service.ts
@@ -42,7 +41,6 @@ model/authorAffiliationsInner.ts
model/authorCountsByYearInner.ts
model/authorIds.ts
model/authorMetricsRequest.ts
model/authorNetworkNode.ts
model/authorNode.ts
model/authorPage.ts
model/authorParsedLongestName.ts
@@ -51,7 +49,6 @@ model/authorStaticStats.ts
model/authorSummaryStats.ts
model/authorTopicProfile.ts
model/authorTopicStats.ts
model/authorsFilterProperties.ts
model/authorsListResponse.ts
model/authorship.ts
model/autocompleteLocationItem.ts
@@ -73,9 +70,6 @@ model/careerStage.ts
model/collaborationGraph.ts
model/collaborationGraphStatus.ts
model/collaborationGraphStatusResponse.ts
model/collaborationNetwork.ts
model/collaborationNetworkEdge.ts
model/collaborationNetworkNodeType.ts
model/companyConnection.ts
model/companyConnectionsAvailability.ts
model/companyConnectionsResponse.ts
@@ -119,8 +113,6 @@ model/extractedKeywords.ts
model/extractedKeywordsLLM.ts
model/extractedKeywordsResponse.ts
model/fileUpload.ts
model/filterInformation.ts
model/filterProperties.ts
model/filterType.ts
model/fp7EurosciVoc.ts
model/fp7LegalBasis.ts
@@ -164,8 +156,6 @@ model/institution.ts
model/institutionFunderSummary.ts
model/institutionGeo.ts
model/institutionIds.ts
model/institutionInformation.ts
model/institutionNetworkNode.ts
model/institutionNode.ts
model/institutionPage.ts
model/institutionPageV2.ts
@@ -282,7 +272,6 @@ model/workHasContent.ts
model/workIds.ts
model/workKeyword.ts
model/workMeshInner.ts
model/workNetworkNode.ts
model/workNode.ts
model/workPage.ts
model/workPageV2.ts
@@ -292,9 +281,7 @@ model/workSustainableDevelopmentGoalsInner.ts
model/workTopic.ts
model/workTopicDomain.ts
model/workTopicField.ts
model/workTopicInformation.ts
model/workTopicSubfield.ts
model/worksFilterProperties.ts
model/worksListResponse.ts
model/yearlyData.ts
param.ts
+1 -3
View File
@@ -28,8 +28,6 @@ export * from './organization.service';
import { OrganizationService } from './organization.service';
export * from './patents.service';
import { PatentsService } from './patents.service';
export * from './personNetwork.service';
import { PersonNetworkService } from './personNetwork.service';
export * from './persons.service';
import { PersonsService } from './persons.service';
export * from './projects.service';
@@ -46,4 +44,4 @@ export * from './works.service';
import { WorksService } from './works.service';
export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, AuthorsV2Service, BookmarksService, CompanyConnectionsService, DFGInstitutionsService, DFGPersonsService, DashboardService, FundingService, INSEServiceService, InstitutionsService, InstitutionsV2Service, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, RankingService, TopicsService, TopicsV2Service, UniversityRankingsService, WorksService, WorksV2Service];
export const APIS = [AuthService, AuthorsV2Service, BookmarksService, CompanyConnectionsService, DFGInstitutionsService, DFGPersonsService, DashboardService, FundingService, INSEServiceService, InstitutionsService, InstitutionsV2Service, KeywordsService, NewsService, OrganizationService, PatentsService, PersonsService, ProjectsService, RankingService, TopicsService, TopicsV2Service, UniversityRankingsService, WorksService, WorksV2Service];
@@ -1,109 +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.
*/
/* 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 { CollaborationNetwork } from '../model/collaborationNetwork';
// @ts-ignore
import { FilterProperties } from '../model/filterProperties';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class PersonNetworkService extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Get a person\&#39;s collaboration network.
* Returns a person\&#39;s collaboration network based on their works and co-authors.
* @endpoint post /api/person/network/{raw_user_id}
* @param rawUserId The raw user ID of the person.
* @param filterProperties
* @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 getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CollaborationNetwork>;
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CollaborationNetwork>>;
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CollaborationNetwork>>;
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawUserId === null || rawUserId === undefined) {
throw new Error('Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.');
}
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/person/network/${this.configuration.encodeParam({name: "rawUserId", value: rawUserId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CollaborationNetwork>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: filterProperties,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
@@ -1,30 +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.
*/
import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType';
export interface AuthorNetworkNode {
/**
* The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID.
*/
raw_id: string;
/**
* The display name of the node.
*/
display_name: string;
/**
* The category of the node, either \'author\', \'institution\', or \'work\'.
*/
category: CollaborationNetworkNodeType;
}
export namespace AuthorNetworkNode {
}
@@ -1,26 +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 interface AuthorsFilterProperties {
/**
* The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included.
*/
allowed_institutions?: Array<string>;
/**
* The minimum number of collaborations required for an author to be included in the collaboration network.
*/
min_collaborations?: number;
/**
* The maximum number of collaborations allowed for an author to be included in the collaboration network.
*/
max_collaborations?: number;
}
@@ -1,43 +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.
*/
import { FilterInformation } from './filterInformation';
import { WorkNetworkNode } from './workNetworkNode';
import { CollaborationNetworkEdge } from './collaborationNetworkEdge';
import { InstitutionNetworkNode } from './institutionNetworkNode';
import { AuthorNetworkNode } from './authorNetworkNode';
export interface CollaborationNetwork {
/**
* The raw person ID of the person whose collaboration network this is.
*/
raw_person_id: string;
/**
* The work nodes in the collaboration network.
*/
work_nodes: Array<WorkNetworkNode>;
/**
* The author nodes in the collaboration network.
*/
author_nodes: Array<AuthorNetworkNode>;
/**
* The institution nodes in the collaboration network.
*/
institution_nodes: Array<InstitutionNetworkNode>;
/**
* The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I
*/
collaboration_edges: Array<CollaborationNetworkEdge>;
/**
* The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network.
*/
filter_information: FilterInformation;
}
@@ -1,22 +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 interface CollaborationNetworkEdge {
/**
* The raw ID of the source node.
*/
raw_source_id: string;
/**
* The raw ID of the target node.
*/
raw_target_id: string;
}
@@ -1,18 +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 CollaborationNetworkNodeType = {
Author: 'author',
Institution: 'institution',
Work: 'work'
} as const;
export type CollaborationNetworkNodeType = typeof CollaborationNetworkNodeType[keyof typeof CollaborationNetworkNodeType];
@@ -1,32 +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.
*/
import { InstitutionInformation } from './institutionInformation';
import { WorkTopicInformation } from './workTopicInformation';
export interface FilterInformation {
/**
* The minimum publication year of the works in the collaboration network.
*/
min_possible_year: number;
/**
* The maximum publication year of the works in the collaboration network.
*/
max_possible_year: number;
/**
* The list of institutions associated with the works in the collaboration network.
*/
institutions: Array<InstitutionInformation>;
/**
* The list of topics associated with the works in the collaboration network.
*/
topics: Array<WorkTopicInformation>;
}
@@ -1,22 +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.
*/
import { WorksFilterProperties } from './worksFilterProperties';
import { AuthorsFilterProperties } from './authorsFilterProperties';
export interface FilterProperties {
/**
* The type of filter to apply when generating the collaboration network. Can be either \'works\' or \'authors\'. If \'works\', the filter properties in the \'works_filter_properties\' field will be used. If \'authors\', the filter properties in the \'authors_filter_properties\' field will be used.
*/
filter_by?: string;
works_filter_properties: WorksFilterProperties | null;
authors_filter_properties: AuthorsFilterProperties | null;
}
@@ -1,22 +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 interface InstitutionInformation {
/**
* The raw institution ID of the institution.
*/
raw_id: string;
/**
* The display name of the institution.
*/
display_name: string;
}
@@ -1,30 +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.
*/
import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType';
export interface InstitutionNetworkNode {
/**
* The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID.
*/
raw_id: string;
/**
* The display name of the node.
*/
display_name: string;
/**
* The category of the node, either \'author\', \'institution\', or \'work\'.
*/
category: CollaborationNetworkNodeType;
}
export namespace InstitutionNetworkNode {
}
-12
View File
@@ -8,7 +8,6 @@ export * from './authorAffiliationsInner';
export * from './authorCountsByYearInner';
export * from './authorIds';
export * from './authorMetricsRequest';
export * from './authorNetworkNode';
export * from './authorNode';
export * from './authorPage';
export * from './authorParsedLongestName';
@@ -17,7 +16,6 @@ export * from './authorStaticStats';
export * from './authorSummaryStats';
export * from './authorTopicProfile';
export * from './authorTopicStats';
export * from './authorsFilterProperties';
export * from './authorsListResponse';
export * from './authorship';
export * from './autocompleteLocationItem';
@@ -39,9 +37,6 @@ export * from './careerStage';
export * from './collaborationGraph';
export * from './collaborationGraphStatus';
export * from './collaborationGraphStatusResponse';
export * from './collaborationNetwork';
export * from './collaborationNetworkEdge';
export * from './collaborationNetworkNodeType';
export * from './companyConnection';
export * from './companyConnectionsAvailability';
export * from './companyConnectionsResponse';
@@ -85,8 +80,6 @@ export * from './extractedKeywords';
export * from './extractedKeywordsLLM';
export * from './extractedKeywordsResponse';
export * from './fileUpload';
export * from './filterInformation';
export * from './filterProperties';
export * from './filterType';
export * from './fp7EurosciVoc';
export * from './fp7LegalBasis';
@@ -130,8 +123,6 @@ export * from './institution';
export * from './institutionFunderSummary';
export * from './institutionGeo';
export * from './institutionIds';
export * from './institutionInformation';
export * from './institutionNetworkNode';
export * from './institutionNode';
export * from './institutionPage';
export * from './institutionPageV2';
@@ -247,7 +238,6 @@ export * from './workHasContent';
export * from './workIds';
export * from './workKeyword';
export * from './workMeshInner';
export * from './workNetworkNode';
export * from './workNode';
export * from './workPage';
export * from './workPageV2';
@@ -257,8 +247,6 @@ export * from './workSustainableDevelopmentGoalsInner';
export * from './workTopic';
export * from './workTopicDomain';
export * from './workTopicField';
export * from './workTopicInformation';
export * from './workTopicSubfield';
export * from './worksFilterProperties';
export * from './worksListResponse';
export * from './yearlyData';
@@ -1,33 +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.
*/
import { WorkTopicInformation } from './workTopicInformation';
import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType';
export interface WorkNetworkNode {
/**
* The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID.
*/
raw_id: string;
/**
* The display name of the node.
*/
display_name: string;
/**
* The category of the node, either \'author\', \'institution\', or \'work\'.
*/
category: CollaborationNetworkNodeType;
publication_year: number | null;
work_topics_information: Set<WorkTopicInformation> | null;
}
export namespace WorkNetworkNode {
}
@@ -1,22 +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 interface WorkTopicInformation {
/**
* The ID of the topic.
*/
raw_topic_id: string;
/**
* The name of the topic.
*/
display_name: string;
}
@@ -1,34 +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 interface WorksFilterProperties {
/**
* The start publication year for the works to include in the collaboration network.
*/
start_year?: number;
/**
* The end publication year for the works to include in the collaboration network.
*/
end_year?: number;
/**
* The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included.
*/
allowed_topics?: Array<string>;
/**
* The minimum number of contributors required for a work to be included in the collaboration network.
*/
min_contributors?: number;
/**
* The maximum number of contributors allowed for a work to be included in the collaboration network.
*/
max_contributors?: number;
}
@@ -1,75 +0,0 @@
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import {
AuthorsFilterProperties,
CollaborationNetwork,
FilterProperties,
PersonNetworkService,
WorksFilterProperties,
} from '../api';
const DEFAULT_MIN_CONTRIBUTORS = 2;
const DEFAULT_MAX_CONTRIBUTORS = 10;
const DEFAULT_MIN_COLLABORATIONS = 1;
const DEFAULT_MAX_COLLABORATIONS = 100;
export const collaborationNetworkResolver: ResolveFn<CollaborationNetwork> = (
route,
state,
) => {
const rawAuthorId = route.parent?.params['id'];
if (!rawAuthorId) {
throw new Error('Author ID is required to resolve collaboration network');
}
const startYear = route.queryParamMap.get('start_year');
const endYear = route.queryParamMap.get('end_year');
const minContributors = route.queryParamMap.get('min_contributors');
const maxContributors = route.queryParamMap.get('max_contributors');
const minCollaborations = route.queryParamMap.get('min_collaborations');
const maxCollaborations = route.queryParamMap.get('max_collaborations');
const institutions = route.queryParamMap.get('institutions');
const topics = route.queryParamMap.get('topics');
const filterBy = route.queryParamMap.get('filter_by') || 'works';
if (filterBy !== 'works' && filterBy !== 'authors') {
throw new Error("Invalid filter_by value. Expected 'works' or 'authors'.");
}
let worksFilterProperties: WorksFilterProperties | null = null;
let authorsFilterProperties: AuthorsFilterProperties | null = null;
if (filterBy === 'works') {
worksFilterProperties = {
start_year: startYear ? Number.parseInt(startYear, 10) : undefined,
end_year: endYear ? Number.parseInt(endYear, 10) : undefined,
min_contributors: minContributors
? Number.parseInt(minContributors, 10)
: DEFAULT_MIN_CONTRIBUTORS,
max_contributors: maxContributors
? Number.parseInt(maxContributors, 10)
: DEFAULT_MAX_CONTRIBUTORS,
allowed_topics: topics ? topics.split(',') : undefined,
};
}
if (filterBy === 'authors') {
authorsFilterProperties = {
min_collaborations: minCollaborations
? Number.parseInt(minCollaborations, 10)
: DEFAULT_MIN_COLLABORATIONS,
max_collaborations: maxCollaborations
? Number.parseInt(maxCollaborations, 10)
: DEFAULT_MAX_COLLABORATIONS,
allowed_institutions: institutions ? institutions.split(',') : undefined,
};
}
const filterProperties: FilterProperties = {
filter_by: filterBy,
works_filter_properties: worksFilterProperties,
authors_filter_properties: authorsFilterProperties,
};
return inject(PersonNetworkService).getCollaborationNetwork(
rawAuthorId,
filterProperties,
);
};