From 386c9fdcf229b37997207671ec324af0ed32dc46 Mon Sep 17 00:00:00 2001 From: Lucas Jeub Date: Thu, 23 Jan 2025 10:49:01 +0100 Subject: [PATCH] tidy --- python/python/raphtory/__init__.pyi | 138 -- .../python/raphtory/algorithms/__init__.pyi | 231 +-- python/python/raphtory/graphql/__init__.pyi | 1 - .../python/raphtory/node_state/__init__.pyi | 1619 ++++++++++++++++- python/python/raphtory/vectors/__init__.pyi | 1 - raphtory/src/python/graph/algorithm_result.rs | 358 ---- 6 files changed, 1735 insertions(+), 613 deletions(-) delete mode 100644 raphtory/src/python/graph/algorithm_result.rs diff --git a/python/python/raphtory/__init__.pyi b/python/python/raphtory/__init__.pyi index bb5525eda..b6713d5f4 100644 --- a/python/python/raphtory/__init__.pyi +++ b/python/python/raphtory/__init__.pyi @@ -8,7 +8,6 @@ ############################################################################### from typing import * -from raphtory import * from raphtory.algorithms import * from raphtory.vectors import * from raphtory.node_state import * @@ -6070,143 +6069,6 @@ class WindowSet(object): Iterable: the time index" """ -class AlgorithmResult(object): - def __len__(self): - """Return len(self).""" - - def __repr__(self): - """Return repr(self).""" - - def get(self, key: NodeInput) -> Optional[Any]: - """ - Returns the value corresponding to the provided key - - Arguments: - key (NodeInput): The node for which the value is to be retrieved. - - Returns: - Optional[Any]: The value for the node or `None` if the value does not exist. - """ - - def get_all(self) -> dict[Node, Any]: - """ - Returns a Dict containing all the nodes (as keys) and their corresponding values (values) or none. - - Returns: - dict[Node, Any]: A dict of nodes and their values - """ - - def get_all_values(self) -> list[Any]: - """ - Get all values - - Returns: - list[Any]: the values for each node as a list - """ - - def get_all_with_names(self) -> dict[str, Any]: - """ - Returns a dict with node names and values - - Returns: - dict[str, Any]: a dict with node names and values - """ - - def group_by(self) -> dict[Any, list[str]]: - """ - Groups the `AlgorithmResult` by its values. - - Returns: - dict[Any, list[str]]: A mapping where keys are unique values from the `AlgorithmResult` and values are lists of nodes - that share the same value. - """ - - def max(self) -> Tuple[Node, Any]: - """ - Find node with maximum value - - Returns: - Tuple[Node, Any]: The node and maximum value. - """ - - def median(self): - """ - Returns a tuple of the median result with its key - - Returns: - Optional[Tuple[Node, Any]]: The node with median value or `None` if there are no nodes. - """ - - def min(self) -> Tuple[Node, Any]: - """ - Find node with minimum value - - Returns: - Tuple[Node, Any]: The node and minimum value. - """ - - def sort_by_node(self, reverse: bool = True) -> list[Tuple[Node, Any]]: - """ - Sorts by node id in ascending or descending order. - - Arguments: - reverse (bool): If `true`, sorts the result in descending order; otherwise, sorts in ascending order. Defaults to True. - - Returns: - list[Tuple[Node, Any]]: A sorted list of tuples containing nodes and values. - """ - - def sort_by_node_name(self, reverse: bool = True) -> list[Tuple[Node, Any]]: - """ - The function `sort_by_node_name` sorts a vector of tuples containing a node and an optional - value by the node name in either ascending or descending order. - - Arguments: - reverse (bool): A boolean value indicating whether the sorting should be done in reverse order or not. Defaults to True. - If reverse is true, the sorting will be done in descending order, otherwise it will be done in - ascending order. - - Returns: - list[Tuple[Node, Any]]: The function sort_by_node_name returns a vector of tuples. Each tuple contains a Node and value - """ - - def sort_by_value(self, reverse: bool = True) -> list[Tuple[Node, Any]]: - """ - Sorts the `AlgorithmResult` by its values in ascending or descending order. - - Arguments: - reverse (bool): If `true`, sorts the result in descending order, otherwise, sorts in ascending order. Defaults to True. - - Returns: - list[Tuple[Node, Any]]: A sorted vector of tuples containing Nodes and values. - """ - - def to_df(self) -> DataFrame: - """ - Creates a dataframe from the result - - Returns: - DataFrame: A `pandas.DataFrame` containing the result - """ - - def top_k( - self, k: int, percentage: bool = False, reverse: bool = True - ) -> list[Tuple[Node, Any]]: - """ - Retrieves the top-k elements from the `AlgorithmResult` based on its values. - - Arguments: - k (int): The number of elements to retrieve. - percentage (bool): If `True`, the `k` parameter is treated as a percentage of total elements. Defaults to False. - reverse (bool): If `True`, retrieves the elements in descending order, otherwise, in ascending order. Defaults to True. - - Returns: - list[Tuple[Node, Any]]: List of tuples with keys of nodes and values of type `Y`. - If percentage is true, the returned vector contains the top `k` percentage of elements. - If percentage is false, the returned vector contains the top `k` elements. - Returns None if the result is empty or if `k` is 0. - """ - class GraphIndex(object): """ A searchable Index for a `Graph`. This allows for fuzzy and exact searches of nodes and edges. diff --git a/python/python/raphtory/algorithms/__init__.pyi b/python/python/raphtory/algorithms/__init__.pyi index defa56cde..7b2bdc5fb 100644 --- a/python/python/raphtory/algorithms/__init__.pyi +++ b/python/python/raphtory/algorithms/__init__.pyi @@ -9,7 +9,6 @@ from typing import * from raphtory import * -from raphtory.algorithms import * from raphtory.vectors import * from raphtory.node_state import * from raphtory.graphql import * @@ -26,7 +25,7 @@ def dijkstra_single_source_shortest_paths( targets: list[NodeInput], direction: Direction = "both", weight: str = "weight", -) -> AlgorithmResult: +) -> NodeStateWeightedSP: """ Finds the shortest paths from a single source to multiple targets in a graph. @@ -38,11 +37,11 @@ def dijkstra_single_source_shortest_paths( weight (str): The name of the weight property for the edges. Defaults to "weight". Returns: - AlgorithmResult: Returns an `AlgorithmResult` where the key is the target node and the value is a tuple containing the total cost and a vector of nodes representing the shortest path. + NodeStateWeightedSP: Mapping from nodes to a tuple containing the total cost and the nodes representing the shortest path. """ -def global_reciprocity(graph: GraphView): +def global_reciprocity(graph: GraphView) -> float: """ Reciprocity - measure of the symmetry of relationships in a graph, the global reciprocity of the entire graph. @@ -50,15 +49,15 @@ def global_reciprocity(graph: GraphView): graph and normalizes it by the total number of directed edges. Arguments: - graph (GraphView) : a directed Raphtory graph + graph (GraphView): a directed Raphtory graph Returns: - float : reciprocity of the graph between 0 and 1. + float: reciprocity of the graph between 0 and 1. """ def betweenness_centrality( graph: GraphView, k: Optional[int] = None, normalized: bool = True -) -> AlgorithmResult: +) -> NodeStateF64: """ Computes the betweenness centrality for nodes in a given graph. @@ -66,27 +65,27 @@ def betweenness_centrality( graph (GraphView): A reference to the graph. k (int, optional): Specifies the number of nodes to consider for the centrality computation. All nodes are considered by default. - normalized (bool): Indicates whether to normalize the centrality values. + normalized (bool): Indicates whether to normalize the centrality values. Defaults to True. Returns: - AlgorithmResult: Returns an `AlgorithmResult` containing the betweenness centrality of each node. + NodeStateF64: Mapping from nodes to their betweenness centrality. """ -def all_local_reciprocity(graph: GraphView): +def all_local_reciprocity(graph: GraphView) -> NodeStateF64: """ Local reciprocity - measure of the symmetry of relationships associated with a node This measures the proportion of a node's outgoing edges which are reciprocated with an incoming edge. Arguments: - graph (GraphView) : a directed Raphtory graph + graph (GraphView): a directed Raphtory graph Returns: - AlgorithmResult : AlgorithmResult with string keys and float values mapping each node name to its reciprocity value. + NodeStateF64: Mapping of nodes to their reciprocity value. """ -def triplet_count(graph: GraphView): +def triplet_count(graph: GraphView) -> int: """ Computes the number of connected triplets within a graph @@ -94,13 +93,13 @@ def triplet_count(graph: GraphView): A-B, B-C, C-A is formed of three connected triplets. Arguments: - graph (GraphView) : a Raphtory graph, treated as undirected + graph (GraphView): a Raphtory graph, treated as undirected Returns: - int : the number of triplets in the graph + int: the number of triplets in the graph """ -def local_triangle_count(graph: GraphView, v: NodeInput): +def local_triangle_count(graph: GraphView, v: NodeInput) -> int: """ Implementations of various graph algorithms that can be run on a graph. @@ -111,15 +110,15 @@ def local_triangle_count(graph: GraphView, v: NodeInput): This function returns the number of pairs of neighbours of a given node which are themselves connected. Arguments: - graph (GraphView) : Raphtory graph, this can be directed or undirected but will be treated as undirected - v (NodeInput) : node id or name + graph (GraphView): Raphtory graph, this can be directed or undirected but will be treated as undirected + v (NodeInput): node id or name Returns: - int : number of triangles associated with node v + int: number of triangles associated with node v """ -def average_degree(graph: GraphView): +def average_degree(graph: GraphView) -> float: """ The average (undirected) degree of all nodes in the graph. @@ -127,13 +126,13 @@ def average_degree(graph: GraphView): the number of undirected edges divided by the number of nodes. Arguments: - graph (GraphView) : a Raphtory graph + graph (GraphView): a Raphtory graph Returns: - float : the average degree of the nodes in the graph + float: the average degree of the nodes in the graph """ -def directed_graph_density(graph: GraphView): +def directed_graph_density(graph: GraphView) -> float: """ Graph density - measures how dense or sparse a graph is. @@ -141,15 +140,13 @@ def directed_graph_density(graph: GraphView): edges (given by N * (N-1) where N is the number of nodes). Arguments: - graph (GraphView) : a directed Raphtory graph + graph (GraphView): a directed Raphtory graph Returns: - float : Directed graph density of graph. + float: Directed graph density of graph. """ -def degree_centrality( - graph: GraphView, threads: Optional[int] = None -) -> AlgorithmResult: +def degree_centrality(graph: GraphView) -> NodeStateF64: """ Computes the degree centrality of all nodes in the graph. The values are normalized by dividing each result with the maximum possible degree. Graphs with self-loops can have @@ -157,10 +154,9 @@ def degree_centrality( Arguments: graph (GraphView): The graph view on which the operation is to be performed. - threads (int, optional): The number of threads to be used for parallel execution. Returns: - AlgorithmResult: A result containing a mapping of node names to the computed sum of their associated degree centrality. + NodeStateF64: Mapping of nodes to their associated degree centrality. """ def max_degree(graph: GraphView) -> int: @@ -185,48 +181,48 @@ def min_degree(graph: GraphView) -> int: int: The smallest degree found """ -def max_out_degree(graph: GraphView): +def max_out_degree(graph: GraphView) -> int: """ The maximum out degree of any node in the graph. Arguments: - graph (GraphView) : a directed Raphtory graph + graph (GraphView): a directed Raphtory graph Returns: - int : value of the largest outdegree + int: value of the largest outdegree """ -def max_in_degree(graph: GraphView): +def max_in_degree(graph: GraphView) -> int: """ The maximum in degree of any node in the graph. Arguments: - graph (GraphView) : a directed Raphtory graph + graph (GraphView): a directed Raphtory graph Returns: - int : value of the largest indegree + int: value of the largest indegree """ -def min_out_degree(graph: GraphView): +def min_out_degree(graph: GraphView) -> int: """ The minimum out degree of any node in the graph. Arguments: - graph (GraphView) : a directed Raphtory graph + graph (GraphView): a directed Raphtory graph Returns: - int : value of the smallest outdegree + int: value of the smallest outdegree """ -def min_in_degree(graph: GraphView): +def min_in_degree(graph: GraphView) -> int: """ The minimum in degree of any node in the graph. Arguments: - graph (GraphView) : a directed Raphtory graph + graph (GraphView): a directed Raphtory graph Returns: - int : value of the smallest indegree + int: value of the smallest indegree """ def pagerank( @@ -235,7 +231,7 @@ def pagerank( max_diff: Optional[float] = None, use_l2_norm=True, damping_factor=0.85, -): +) -> NodeStateF64: """ Pagerank -- pagerank centrality value of the nodes in a graph @@ -244,19 +240,19 @@ def pagerank( is less than the max diff value given. Arguments: - graph (GraphView) : Raphtory graph - iter_count (int) : Maximum number of iterations to run. Note that this will terminate early if convergence is reached. - max_diff (Optional[float]) : Optional parameter providing an alternative stopping condition. + graph (GraphView): Raphtory graph + iter_count (int): Maximum number of iterations to run. Note that this will terminate early if convergence is reached. + max_diff (Optional[float]): Optional parameter providing an alternative stopping condition. The algorithm will terminate if the sum of the absolute difference in pagerank values between iterations is less than the max diff value given. Returns: - AlgorithmResult : AlgorithmResult with string keys and float values mapping node names to their pagerank value. + NodeStateF64: Mapping of nodes to their pagerank value. """ def single_source_shortest_path( graph: GraphView, source: NodeInput, cutoff: Optional[int] = None -) -> AlgorithmResult: +) -> NodeStateNodes: """ Calculates the single source shortest paths from a given source node. @@ -266,11 +262,11 @@ def single_source_shortest_path( cutoff (int, optional): An optional cutoff level. The algorithm will stop if this level is reached. Returns: - AlgorithmResult: Returns an `AlgorithmResult[str, list[str]]` containing the shortest paths from the source to all reachable nodes. + NodeStateNodes: Mapping from end node to shortest path from the source node. """ -def global_clustering_coefficient(graph: GraphView): +def global_clustering_coefficient(graph: GraphView) -> float: """ Computes the global clustering coefficient of a graph. The global clustering coefficient is defined as the number of triangles in the graph divided by the number of triplets in the graph. @@ -278,10 +274,10 @@ def global_clustering_coefficient(graph: GraphView): Note that this is also known as transitivity and is different to the average clustering coefficient. Arguments: - graph (GraphView) : a Raphtory graph, treated as undirected + graph (GraphView): a Raphtory graph, treated as undirected Returns: - float : the global clustering coefficient of the graph + float: the global clustering coefficient of the graph See also: [`Triplet Count`](triplet_count) @@ -293,7 +289,7 @@ def temporally_reachable_nodes( start_time: int, seed_nodes: list[NodeInput], stop_nodes: Optional[list[NodeInput]] = None, -): +) -> NodeStateReachability: """ Temporally reachable nodes -- the nodes that are reachable by a time respecting path followed out from a set of seed nodes at a starting time. @@ -302,14 +298,14 @@ def temporally_reachable_nodes( a sequence of edges (v_i, v_i+1, t_i) with t_i < t_i+1 for i = 1, ... , k - 1. Arguments: - graph (GraphView) : directed Raphtory graph - max_hops (int) : maximum number of hops to propagate out - start_time (int) : time at which to start the path (such that t_1 > start_time for any path starting from these seed nodes) - seed_nodes (list[NodeInput]) : list of node names or ids which should be the starting nodes - stop_nodes (Optional[list[NodeInput]]) : nodes at which a path shouldn't go any further + graph (GraphView): directed Raphtory graph + max_hops (int): maximum number of hops to propagate out + start_time (int): time at which to start the path (such that t_1 > start_time for any path starting from these seed nodes) + seed_nodes (list[NodeInput]): list of node names or ids which should be the starting nodes + stop_nodes (Optional[list[NodeInput]]): nodes at which a path shouldn't go any further Returns: - AlgorithmResult : AlgorithmResult with string keys and float values mapping node names to their pagerank value. + NodeStateReachability: Mapping of nodes to their reachability history. """ def temporal_bipartite_graph_projection( @@ -320,31 +316,31 @@ def temporal_bipartite_graph_projection( will make a connection between nodes `n1` and `n2` (of type `A`) at time `(t1 + t2)/2` if they respectively have an edge at time `t1`, `t2` with the same node of type `B` in `G`, and `|t2-t1| < delta`. Arguments: - graph (GraphView) : A directed raphtory graph + graph (GraphView): A directed raphtory graph delta (int): Time period - pivot_type (str) : node type to pivot over. If a bipartite graph has types `A` and `B`, and `B` is the pivot type, the new graph will consist of type `A` nodes. + pivot_type (str): node type to pivot over. If a bipartite graph has types `A` and `B`, and `B` is the pivot type, the new graph will consist of type `A` nodes. Returns: Graph: Projected (unipartite) temporal graph. """ -def local_clustering_coefficient(graph: GraphView, v: NodeInput): +def local_clustering_coefficient(graph: GraphView, v: NodeInput) -> float: """ Local clustering coefficient - measures the degree to which nodes in a graph tend to cluster together. The proportion of pairs of neighbours of a node who are themselves connected. Arguments: - graph (GraphView) : Raphtory graph, can be directed or undirected but will be treated as undirected. + graph (GraphView): Raphtory graph, can be directed or undirected but will be treated as undirected. v (NodeInput): node id or name Returns: - float : the local clustering coefficient of node v in graph. + float: the local clustering coefficient of node v in graph. """ def weakly_connected_components( graph: GraphView, iter_count: int = 9223372036854775807 -): +) -> NodeStateUsize: """ Weakly connected components -- partitions the graph into node sets which are mutually reachable by an undirected path @@ -352,35 +348,35 @@ def weakly_connected_components( by an undirected path. Arguments: - graph (GraphView) : Raphtory graph - iter_count (int) : Maximum number of iterations to run. Note that this will terminate early if the labels converge prior to the number of iterations being reached. + graph (GraphView): Raphtory graph + iter_count (int): Maximum number of iterations to run. Note that this will terminate early if the labels converge prior to the number of iterations being reached. Returns: - AlgorithmResult : AlgorithmResult object mapping nodes to their component ids. + NodeStateUsize: Mapping of nodes to their component ids. """ -def strongly_connected_components(graph: GraphView): +def strongly_connected_components(graph: GraphView) -> NodeStateUsize: """ Strongly connected components Partitions the graph into node sets which are mutually reachable by an directed path Arguments: - graph (GraphView) : Raphtory graph + graph (GraphView): Raphtory graph Returns: - list[list[int]] : List of strongly connected nodes identified by ids + NodeStateUsize: Mapping of nodes to their component ids """ -def in_components(graph: GraphView): +def in_components(graph: GraphView) -> NodeStateNodes: """ In components -- Finding the "in-component" of a node in a directed graph involves identifying all nodes that can be reached following only incoming edges. Arguments: - graph (GraphView) : Raphtory graph + graph (GraphView): Raphtory graph Returns: - AlgorithmResult : AlgorithmResult object mapping each node to an array containing the ids of all nodes within their 'in-component' + NodeStateNodes: Mapping of nodes to the nodes in their 'in-component' """ def in_component(node: Node): @@ -388,21 +384,21 @@ def in_component(node: Node): In component -- Finding the "in-component" of a node in a directed graph involves identifying all nodes that can be reached following only incoming edges. Arguments: - node (Node) : The node whose in-component we wish to calculate + node (Node): The node whose in-component we wish to calculate Returns: An array containing the Nodes within the given nodes in-component """ -def out_components(graph: GraphView): +def out_components(graph: GraphView) -> NodeStateNodes: """ Out components -- Finding the "out-component" of a node in a directed graph involves identifying all nodes that can be reached following only outgoing edges. Arguments: - graph (GraphView) : Raphtory graph + graph (GraphView): Raphtory graph Returns: - AlgorithmResult : AlgorithmResult object mapping each node to an array containing the ids of all nodes within their 'out-component' + NodeStateNodes: Mapping of nodes to the nodes within their 'out-component' """ def out_component(node: Node) -> NodeStateUsize: @@ -410,7 +406,7 @@ def out_component(node: Node) -> NodeStateUsize: Out component -- Finding the "out-component" of a node in a directed graph involves identifying all nodes that can be reached following only outgoing edges. Arguments: - node (Node) : The node whose out-component we wish to calculate + node (Node): The node whose out-component we wish to calculate Returns: NodeStateUsize: A NodeState mapping the nodes in the out-component to their distance from the starting node. @@ -423,7 +419,7 @@ def fast_rp( iter_weights: list[float], seed: Optional[int] = None, threads: Optional[int] = None, -) -> AlgorithmResult: +) -> NodeStateListF64: """ Computes embedding vectors for each vertex of an undirected/bidirectional graph according to the Fast RP algorithm. Original Paper: https://doi.org/10.48550/arXiv.1908.11512 @@ -436,10 +432,12 @@ def fast_rp( threads (int, optional): The number of threads to be used for parallel execution. Returns: - AlgorithmResult: Returns an AlgorithmResult containing the embedding vector of each node. + NodeStateListF64: Mapping from nodes to embedding vectors. """ -def global_temporal_three_node_motif(graph: GraphView, delta: int, threads=None): +def global_temporal_three_node_motif( + graph: GraphView, delta: int, threads=None +) -> list: """ Computes the number of three edge, up-to-three node delta-temporal motifs in the graph, using the algorithm of Paranjape et al, Motifs in Temporal Networks (2017). We point the reader to this reference for more information on the algorithm and background, but provide a short summary below. @@ -476,11 +474,11 @@ def global_temporal_three_node_motif(graph: GraphView, delta: int, threads=None) 8. i --> j, i --> k, k --> j Arguments: - graph (GraphView) : A directed raphtory graph + graph (GraphView): A directed raphtory graph delta (int): Maximum time difference between the first and last edge of the motif. NB if time for edges was given as a UNIX epoch, this should be given in seconds, otherwise milliseconds should be used (if edge times were given as string) Returns: - list : A 40 dimensional array with the counts of each motif, given in the same order as described above. Note that the two-node motif counts are symmetrical so it may be more useful just to consider the first four elements. + list: A 40 dimensional array with the counts of each motif, given in the same order as described above. Note that the two-node motif counts are symmetrical so it may be more useful just to consider the first four elements. Notes: This is achieved by calling the local motif counting algorithm, summing the resulting arrays and dealing with overcounted motifs: the triangles (by dividing each motif count by three) and two-node motifs (dividing by two). @@ -489,28 +487,30 @@ def global_temporal_three_node_motif(graph: GraphView, delta: int, threads=None) def global_temporal_three_node_motif_multi( graph: GraphView, deltas: list[int], threads=None -): +) -> list[list[int]]: """ Computes the global counts of three-edge up-to-three node temporal motifs for a range of timescales. See `global_temporal_three_node_motif` for an interpretation of each row returned. Arguments: - graph (GraphView) : A directed raphtory graph + graph (GraphView): A directed raphtory graph deltas(list[int]): A list of delta values to use. Returns: - list[list[int]] : A list of 40d arrays, each array is the motif count for a particular value of delta, returned in the order that the deltas were given as input. + list[list[int]]: A list of 40d arrays, each array is the motif count for a particular value of delta, returned in the order that the deltas were given as input. """ -def local_temporal_three_node_motifs(graph: GraphView, delta: int, threads=None): +def local_temporal_three_node_motifs( + graph: GraphView, delta: int, threads=None +) -> NodeStateMotifs: """ Computes the number of each type of motif that each node participates in. See global_temporal_three_node_motifs for a summary of the motifs involved. Arguments: - graph (GraphView) : A directed raphtory graph + graph (GraphView): A directed raphtory graph delta (int): Maximum time difference between the first and last edge of the motif. NB if time for edges was given as a UNIX epoch, this should be given in seconds, otherwise milliseconds should be used (if edge times were given as string) Returns: - dict : A dictionary with node ids as keys and a 40d array of motif counts as values (in the same order as the global motif counts) with the number of each motif that node participates in. + NodeStateMotifs: A mapping from nodes to lists of motif counts (40 counts in the same order as the global motif counts) with the number of each motif that node participates in. Notes: For this local count, a node is counted as participating in a motif in the following way. For star motifs, only the centre node counts @@ -519,7 +519,7 @@ def local_temporal_three_node_motifs(graph: GraphView, delta: int, threads=None) def hits( graph: GraphView, iter_count: int = 20, threads: Optional[int] = None -) -> AlgorithmResult: +) -> NodeStateHits: """ HITS (Hubs and Authority) Algorithm: @@ -535,15 +535,12 @@ def hits( threads (int, optional): Number of threads to use Returns: - AlgorithmResult: An AlgorithmResult object containing the mapping from node ID to the hub and authority score of the node + NodeStateHits: A mapping from nodes their hub and authority scores """ def balance( - graph: GraphView, - name: str = "weight", - direction: Direction = "both", - threads: Optional[int] = None, -) -> AlgorithmResult: + graph: GraphView, name: str = "weight", direction: Direction = "both" +) -> NodeStateF64: """ Sums the weights of edges in the graph based on the specified direction. @@ -556,10 +553,9 @@ def balance( * "out": Only consider outgoing edges. * "in": Only consider incoming edges. * "both": Consider both outgoing and incoming edges. This is the default. - threads (int, optional): The number of threads to be used for parallel execution. Returns: - AlgorithmResult: A result containing a mapping of node names to the computed sum of their associated edge weights. + NodeStateF64: Mapping of nodes to the computed sum of their associated edge weights. """ @@ -586,7 +582,7 @@ def temporal_SEIR( recovery_rate: float | None = None, incubation_rate: float | None = None, rng_seed: int | None = None, -) -> AlgorithmResult: +) -> NodeStateSEIR: """ Simulate an SEIR dynamic on the network @@ -609,13 +605,10 @@ def temporal_SEIR( rng_seed (int | None): optional seed for the random number generator Returns: - AlgorithmResult: Returns an `Infected` object for each infected node with attributes - - `infected`: the time stamp of the infection event - - `active`: the time stamp at which the node actively starts spreading the infection (i.e., the end of the incubation period) - - `recovered`: the time stamp at which the node recovered (i.e., stopped spreading the infection) + NodeStateSEIR: Mapping from nodes to `Infected` objects for each infected node with attributes + `infected`: the time stamp of the infection event + `active`: the time stamp at which the node actively starts spreading the infection (i.e., the end of the incubation period) + `recovered`: the time stamp at which the node recovered (i.e., stopped spreading the infection) """ @@ -624,7 +617,7 @@ def louvain( resolution: float = 1.0, weight_prop: str | None = None, tol: None | float = None, -): +) -> NodeStateUsize: """ Louvain algorithm for community detection @@ -633,6 +626,9 @@ def louvain( resolution (float): the resolution parameter for modularity weight_prop (str | None): the edge property to use for weights (has to be float) tol (None | float): the floating point tolerance for deciding if improvements are significant (default: 1e-8) + + Returns: + NodeStateUsize: Mapping of nodes to their community assignment """ def fruchterman_reingold( @@ -642,7 +638,7 @@ def fruchterman_reingold( node_start_size: float | None = 1.0, cooloff_factor: float | None = 0.95, dt: float | None = 0.1, -): +) -> NodeLayout: """ Fruchterman Reingold layout algorithm @@ -655,7 +651,7 @@ def fruchterman_reingold( dt (float | None): the time increment between iterations (default: 0.1) Returns: - a dict with the position for each node as a list with two numbers [x, y] + NodeLayout: A mapping from nodes to their [x, y] positions """ def cohesive_fruchterman_reingold( @@ -665,7 +661,7 @@ def cohesive_fruchterman_reingold( node_start_size: float = 1.0, cooloff_factor: float = 0.95, dt: float = 0.1, -) -> AlgorithmResult: +) -> NodeLayout: """ Cohesive version of `fruchterman_reingold` that adds virtual edges between isolated nodes Arguments: @@ -677,7 +673,7 @@ def cohesive_fruchterman_reingold( dt (float): Time step or movement factor in each iteration Returns: - AlgorithmResult: Returns an AlgorithmResult containing a mapping between vertices and a pair of coordinates. + NodeLayout: A mapping from nodes to their [x, y] positions """ @@ -793,4 +789,15 @@ class Matching(object): """ +class Infected(object): + def __repr__(self): + """Return repr(self).""" + + @property + def active(self): ... + @property + def infected(self): ... + @property + def recovered(self): ... + def connected_components(graph): ... diff --git a/python/python/raphtory/graphql/__init__.pyi b/python/python/raphtory/graphql/__init__.pyi index e0ca44eaf..66dee6c63 100644 --- a/python/python/raphtory/graphql/__init__.pyi +++ b/python/python/raphtory/graphql/__init__.pyi @@ -12,7 +12,6 @@ from raphtory import * from raphtory.algorithms import * from raphtory.vectors import * from raphtory.node_state import * -from raphtory.graphql import * from raphtory.typing import * from datetime import datetime from pandas import DataFrame diff --git a/python/python/raphtory/node_state/__init__.pyi b/python/python/raphtory/node_state/__init__.pyi index 25ba0b07b..f2e758961 100644 --- a/python/python/raphtory/node_state/__init__.pyi +++ b/python/python/raphtory/node_state/__init__.pyi @@ -11,7 +11,6 @@ from typing import * from raphtory import * from raphtory.algorithms import * from raphtory.vectors import * -from raphtory.node_state import * from raphtory.graphql import * from raphtory.typing import * from datetime import datetime @@ -238,6 +237,18 @@ class DegreeView(object): WindowSet: A `WindowSet` object. """ + def get(self, node: NodeInput, default: Optional[int] = None) -> Optional[int]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[int]): the default value. Defaults to None. + + Returns: + Optional[int]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -477,6 +488,17 @@ class DegreeView(object): int: the sum """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateUsize: """ Compute the k largest values @@ -571,6 +593,18 @@ class NodeStateUsize(object): NodeStateUsize: The k smallest values as a node state """ + def get(self, node: NodeInput, default: Optional[int] = None) -> Optional[int]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[int]): the default value. Defaults to None. + + Returns: + Optional[int]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -678,6 +712,17 @@ class NodeStateUsize(object): int: the sum """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateUsize: """ Compute the k largest values @@ -739,6 +784,18 @@ class NodeStateU64(object): NodeStateU64: The k smallest values as a node state """ + def get(self, node: NodeInput, default: Optional[int] = None) -> Optional[int]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[int]): the default value. Defaults to None. + + Returns: + Optional[int]: the value for the node or the default value + """ + def items(self) -> Iterator[Tuple[Node, int]]: """ Iterate over items @@ -838,6 +895,17 @@ class NodeStateU64(object): int: the sum """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateU64: """ Compute the k largest values @@ -899,6 +967,20 @@ class NodeStateOptionI64(object): NodeStateOptionI64: The k smallest values as a node state """ + def get( + self, node: NodeInput, default: Optional[Optional[int]] = None + ) -> Optional[Optional[int]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[int]]): the default value. Defaults to None. + + Returns: + Optional[Optional[int]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -990,6 +1072,17 @@ class NodeStateOptionI64(object): NodeStateOptionI64: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionI64: """ Compute the k largest values @@ -1069,6 +1162,18 @@ class IdView(object): NodeStateGID: the computed `NodeState` """ + def get(self, node: NodeInput, default: Optional[GID] = None) -> Optional[GID]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[GID]): the default value. Defaults to None. + + Returns: + Optional[GID]: the value for the node or the default value + """ + def items(self) -> Iterator[Tuple[Node, GID]]: """ Iterate over items @@ -1152,6 +1257,17 @@ class IdView(object): NodeStateGID: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateGID: """ Compute the k largest values @@ -1213,6 +1329,18 @@ class NodeStateGID(object): NodeStateGID: The k smallest values as a node state """ + def get(self, node: NodeInput, default: Optional[GID] = None) -> Optional[GID]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[GID]): the default value. Defaults to None. + + Returns: + Optional[GID]: the value for the node or the default value + """ + def items(self) -> Iterator[Tuple[Node, GID]]: """ Iterate over items @@ -1296,6 +1424,17 @@ class NodeStateGID(object): NodeStateGID: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateGID: """ Compute the k largest values @@ -1490,6 +1629,20 @@ class EarliestTimeView(object): WindowSet: A `WindowSet` object. """ + def get( + self, node: NodeInput, default: Optional[Optional[int]] = None + ) -> Optional[Optional[int]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[int]]): the default value. Defaults to None. + + Returns: + Optional[Optional[int]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -1713,6 +1866,17 @@ class EarliestTimeView(object): Optional[datetime]: The earliest datetime that this EarliestTimeView is valid or None if the EarliestTimeView is valid for all times. """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionI64: """ Compute the k largest values @@ -1942,6 +2106,20 @@ class LatestTimeView(object): WindowSet: A `WindowSet` object. """ + def get( + self, node: NodeInput, default: Optional[Optional[int]] = None + ) -> Optional[Optional[int]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[int]]): the default value. Defaults to None. + + Returns: + Optional[Optional[int]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -2165,6 +2343,17 @@ class LatestTimeView(object): Optional[datetime]: The earliest datetime that this LatestTimeView is valid or None if the LatestTimeView is valid for all times. """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionI64: """ Compute the k largest values @@ -2277,6 +2466,18 @@ class NameView(object): NodeStateString: the computed `NodeState` """ + def get(self, node: NodeInput, default: Optional[str] = None) -> Optional[str]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[str]): the default value. Defaults to None. + + Returns: + Optional[str]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -2368,6 +2569,17 @@ class NameView(object): NodeStateString: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateString: """ Compute the k largest values @@ -2429,6 +2641,18 @@ class NodeStateString(object): NodeStateString: The k smallest values as a node state """ + def get(self, node: NodeInput, default: Optional[str] = None) -> Optional[str]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[str]): the default value. Defaults to None. + + Returns: + Optional[str]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -2520,6 +2744,17 @@ class NodeStateString(object): NodeStateString: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateString: """ Compute the k largest values @@ -2714,6 +2949,20 @@ class EarliestDateTimeView(object): WindowSet: A `WindowSet` object. """ + def get( + self, node: NodeInput, default: Optional[Optional[datetime]] = None + ) -> Optional[Optional[datetime]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[datetime]]): the default value. Defaults to None. + + Returns: + Optional[Optional[datetime]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -2937,6 +3186,17 @@ class EarliestDateTimeView(object): Optional[datetime]: The earliest datetime that this EarliestDateTimeView is valid or None if the EarliestDateTimeView is valid for all times. """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionDateTime: """ Compute the k largest values @@ -3166,6 +3426,20 @@ class LatestDateTimeView(object): WindowSet: A `WindowSet` object. """ + def get( + self, node: NodeInput, default: Optional[Optional[datetime]] = None + ) -> Optional[Optional[datetime]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[datetime]]): the default value. Defaults to None. + + Returns: + Optional[Optional[datetime]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -3389,6 +3663,17 @@ class LatestDateTimeView(object): Optional[datetime]: The earliest datetime that this LatestDateTimeView is valid or None if the LatestDateTimeView is valid for all times. """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionDateTime: """ Compute the k largest values @@ -3485,6 +3770,20 @@ class NodeStateOptionDateTime(object): NodeStateOptionDateTime: The k smallest values as a node state """ + def get( + self, node: NodeInput, default: Optional[Optional[datetime]] = None + ) -> Optional[Optional[datetime]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[datetime]]): the default value. Defaults to None. + + Returns: + Optional[Optional[datetime]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -3576,6 +3875,17 @@ class NodeStateOptionDateTime(object): NodeStateOptionDateTime: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionDateTime: """ Compute the k largest values @@ -3770,6 +4080,20 @@ class HistoryView(object): WindowSet: A `WindowSet` object. """ + def get( + self, node: NodeInput, default: Optional[list[int]] = None + ) -> Optional[list[int]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[list[int]]): the default value. Defaults to None. + + Returns: + Optional[list[int]]: the value for the node or the default value + """ + def has_layer(self, name: str) -> bool: """ Check if HistoryView has the layer `"name"` @@ -3985,6 +4309,17 @@ class HistoryView(object): Optional[datetime]: The earliest datetime that this HistoryView is valid or None if the HistoryView is valid for all times. """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateListI64: """ Compute the k largest values @@ -4079,6 +4414,20 @@ class NodeStateListI64(object): NodeStateListI64: The k smallest values as a node state """ + def get( + self, node: NodeInput, default: Optional[list[int]] = None + ) -> Optional[list[int]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[list[int]]): the default value. Defaults to None. + + Returns: + Optional[list[int]]: the value for the node or the default value + """ + def items(self) -> Iterator[Tuple[Node, list[int]]]: """ Iterate over items @@ -4162,6 +4511,17 @@ class NodeStateListI64(object): NodeStateListI64: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateListI64: """ Compute the k largest values @@ -4356,6 +4716,20 @@ class HistoryDateTimeView(object): WindowSet: A `WindowSet` object. """ + def get( + self, node: NodeInput, default: Optional[Optional[list[datetime]]] = None + ) -> Optional[Optional[list[datetime]]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[list[datetime]]]): the default value. Defaults to None. + + Returns: + Optional[Optional[list[datetime]]]: the value for the node or the default value + """ + def has_layer(self, name: str) -> bool: """ Check if HistoryDateTimeView has the layer `"name"` @@ -4571,6 +4945,17 @@ class HistoryDateTimeView(object): Optional[datetime]: The earliest datetime that this HistoryDateTimeView is valid or None if the HistoryDateTimeView is valid for all times. """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionListDateTime: """ Compute the k largest values @@ -4667,6 +5052,20 @@ class NodeStateOptionListDateTime(object): NodeStateOptionListDateTime: The k smallest values as a node state """ + def get( + self, node: NodeInput, default: Optional[Optional[list[datetime]]] = None + ) -> Optional[Optional[list[datetime]]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[list[datetime]]]): the default value. Defaults to None. + + Returns: + Optional[Optional[list[datetime]]]: the value for the node or the default value + """ + def items(self) -> Iterator[Tuple[Node, Optional[list[datetime]]]]: """ Iterate over items @@ -4750,6 +5149,17 @@ class NodeStateOptionListDateTime(object): NodeStateOptionListDateTime: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionListDateTime: """ Compute the k largest values @@ -4829,6 +5239,20 @@ class NodeTypeView(object): NodeStateOptionStr: the computed `NodeState` """ + def get( + self, node: NodeInput, default: Optional[Optional[str]] = None + ) -> Optional[Optional[str]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[str]]): the default value. Defaults to None. + + Returns: + Optional[Optional[str]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -4920,6 +5344,17 @@ class NodeTypeView(object): NodeStateOptionStr: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionStr: """ Compute the k largest values @@ -4981,6 +5416,20 @@ class NodeStateOptionStr(object): NodeStateOptionStr: The k smallest values as a node state """ + def get( + self, node: NodeInput, default: Optional[Optional[str]] = None + ) -> Optional[Optional[str]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Optional[str]]): the default value. Defaults to None. + + Returns: + Optional[Optional[str]]: the value for the node or the default value + """ + def groups(self) -> NodeGroups: """ Group by value @@ -5072,6 +5521,17 @@ class NodeStateOptionStr(object): NodeStateOptionStr: The sorted node state """ + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + def top_k(self, k: int) -> NodeStateOptionStr: """ Compute the k largest values @@ -5133,6 +5593,20 @@ class NodeStateListDateTime(object): NodeStateListDateTime: The k smallest values as a node state """ + def get( + self, node: NodeInput, default: Optional[list[datetime]] = None + ) -> Optional[list[datetime]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[list[datetime]]): the default value. Defaults to None. + + Returns: + Optional[list[datetime]]: the value for the node or the default value + """ + def items(self) -> Iterator[Tuple[Node, list[datetime]]]: """ Iterate over items @@ -5216,9 +5690,20 @@ class NodeStateListDateTime(object): NodeStateListDateTime: The sorted node state """ - def top_k(self, k: int) -> NodeStateListDateTime: + def to_df(self) -> DataFrame: """ - Compute the k largest values + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def top_k(self, k: int) -> NodeStateListDateTime: + """ + Compute the k largest values Arguments: k (int): The number of values to return @@ -5234,3 +5719,1131 @@ class NodeStateListDateTime(object): Returns: Iterator[list[datetime]]: Iterator over values """ + +class NodeStateWeightedSP(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self Optional[Tuple[float, Nodes]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Tuple[float, Nodes]]): the default value. Defaults to None. + + Returns: + Optional[Tuple[float, Nodes]]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, Tuple[float, Nodes]]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, Tuple[float, Nodes]]]: Iterator over items + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted_by_id(self) -> NodeStateWeightedSP: + """ + Sort results by node id + + Returns: + NodeStateWeightedSP: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def values(self) -> Iterator[Tuple[float, Nodes]]: + """ + Iterate over values + + Returns: + Iterator[Tuple[float, Nodes]]: Iterator over values + """ + +class NodeStateF64(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self NodeStateF64: + """ + Compute the k smallest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateF64: The k smallest values as a node state + """ + + def get(self, node: NodeInput, default: Optional[float] = None) -> Optional[float]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[float]): the default value. Defaults to None. + + Returns: + Optional[float]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, float]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, float]]: Iterator over items + """ + + def max(self) -> Optional[float]: + """ + Return the maximum value + + Returns: + Optional[float]: The maximum value or `None` if empty + """ + + def max_item(self) -> Optional[Tuple[Node, float]]: + """ + Return largest value and corresponding node + + Returns: + Optional[Tuple[Node, float]]: The Node and maximum value or `None` if empty + """ + + def mean(self) -> float: + """ + mean of values over all nodes + + Returns: + float: mean value + """ + + def median(self) -> Optional[float]: + """ + Return the median value + + Returns: + Optional[float]: + """ + + def median_item(self) -> Optional[Tuple[Node, float]]: + """ + Return median value and corresponding node + + Returns: + Optional[Tuple[Node, float]]: The median value or `None` if empty + """ + + def min(self) -> Optional[float]: + """ + Return the minimum value + + Returns: + Optional[float]: The minimum value or `None` if empty + """ + + def min_item(self) -> Optional[Tuple[Node, float]]: + """ + Return smallest value and corresponding node + + Returns: + Optional[Tuple[Node, float]]: The Node and minimum value or `None` if empty + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted(self, reverse: bool = False) -> NodeStateF64: + """ + Sort by value + + Arguments: + reverse (bool): If `True`, sort in descending order, otherwise ascending. Defaults to False. + + Returns: + NodeStateF64: Sorted node state + """ + + def sorted_by_id(self) -> NodeStateF64: + """ + Sort results by node id + + Returns: + NodeStateF64: The sorted node state + """ + + def sum(self) -> float: + """ + sum of values over all nodes + + Returns: + float: the sum + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def top_k(self, k: int) -> NodeStateF64: + """ + Compute the k largest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateF64: The k largest values as a node state + """ + + def values(self) -> Iterator[float]: + """ + Iterate over values + + Returns: + Iterator[float]: Iterator over values + """ + +class NodeStateNodes(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self Optional[Nodes]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Nodes]): the default value. Defaults to None. + + Returns: + Optional[Nodes]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, Nodes]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, Nodes]]: Iterator over items + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted_by_id(self) -> NodeStateNodes: + """ + Sort results by node id + + Returns: + NodeStateNodes: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def values(self) -> Iterator[Nodes]: + """ + Iterate over values + + Returns: + Iterator[Nodes]: Iterator over values + """ + +class NodeStateReachability(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self Optional[list[Tuple[int, str]]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[list[Tuple[int, str]]]): the default value. Defaults to None. + + Returns: + Optional[list[Tuple[int, str]]]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, list[Tuple[int, str]]]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, list[Tuple[int, str]]]]: Iterator over items + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted_by_id(self) -> NodeStateReachability: + """ + Sort results by node id + + Returns: + NodeStateReachability: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def values(self) -> Iterator[list[Tuple[int, str]]]: + """ + Iterate over values + + Returns: + Iterator[list[Tuple[int, str]]]: Iterator over values + """ + +class NodeStateListF64(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self Optional[list[float]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[list[float]]): the default value. Defaults to None. + + Returns: + Optional[list[float]]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, list[float]]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, list[float]]]: Iterator over items + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted_by_id(self) -> NodeStateListF64: + """ + Sort results by node id + + Returns: + NodeStateListF64: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def values(self) -> Iterator[list[float]]: + """ + Iterate over values + + Returns: + Iterator[list[float]]: Iterator over values + """ + +class NodeStateMotifs(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self NodeStateMotifs: + """ + Compute the k smallest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateMotifs: The k smallest values as a node state + """ + + def get( + self, node: NodeInput, default: Optional[list[int]] = None + ) -> Optional[list[int]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[list[int]]): the default value. Defaults to None. + + Returns: + Optional[list[int]]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, list[int]]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, list[int]]]: Iterator over items + """ + + def max(self) -> Optional[list[int]]: + """ + Return the maximum value + + Returns: + Optional[list[int]]: The maximum value or `None` if empty + """ + + def max_item(self) -> Optional[Tuple[Node, list[int]]]: + """ + Return largest value and corresponding node + + Returns: + Optional[Tuple[Node, list[int]]]: The Node and maximum value or `None` if empty + """ + + def median(self) -> Optional[list[int]]: + """ + Return the median value + + Returns: + Optional[list[int]]: + """ + + def median_item(self) -> Optional[Tuple[Node, list[int]]]: + """ + Return median value and corresponding node + + Returns: + Optional[Tuple[Node, list[int]]]: The median value or `None` if empty + """ + + def min(self) -> Optional[list[int]]: + """ + Return the minimum value + + Returns: + Optional[list[int]]: The minimum value or `None` if empty + """ + + def min_item(self) -> Optional[Tuple[Node, list[int]]]: + """ + Return smallest value and corresponding node + + Returns: + Optional[Tuple[Node, list[int]]]: The Node and minimum value or `None` if empty + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted(self, reverse: bool = False) -> NodeStateMotifs: + """ + Sort by value + + Arguments: + reverse (bool): If `True`, sort in descending order, otherwise ascending. Defaults to False. + + Returns: + NodeStateMotifs: Sorted node state + """ + + def sorted_by_id(self) -> NodeStateMotifs: + """ + Sort results by node id + + Returns: + NodeStateMotifs: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def top_k(self, k: int) -> NodeStateMotifs: + """ + Compute the k largest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateMotifs: The k largest values as a node state + """ + + def values(self) -> Iterator[list[int]]: + """ + Iterate over values + + Returns: + Iterator[list[int]]: Iterator over values + """ + +class NodeStateHits(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self NodeStateHits: + """ + Compute the k smallest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateHits: The k smallest values as a node state + """ + + def get( + self, node: NodeInput, default: Optional[Tuple[float, float]] = None + ) -> Optional[Tuple[float, float]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Tuple[float, float]]): the default value. Defaults to None. + + Returns: + Optional[Tuple[float, float]]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, Tuple[float, float]]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, Tuple[float, float]]]: Iterator over items + """ + + def max(self) -> Optional[Tuple[float, float]]: + """ + Return the maximum value + + Returns: + Optional[Tuple[float, float]]: The maximum value or `None` if empty + """ + + def max_item(self) -> Optional[Tuple[Node, Tuple[float, float]]]: + """ + Return largest value and corresponding node + + Returns: + Optional[Tuple[Node, Tuple[float, float]]]: The Node and maximum value or `None` if empty + """ + + def median(self) -> Optional[Tuple[float, float]]: + """ + Return the median value + + Returns: + Optional[Tuple[float, float]]: + """ + + def median_item(self) -> Optional[Tuple[Node, Tuple[float, float]]]: + """ + Return median value and corresponding node + + Returns: + Optional[Tuple[Node, Tuple[float, float]]]: The median value or `None` if empty + """ + + def min(self) -> Optional[Tuple[float, float]]: + """ + Return the minimum value + + Returns: + Optional[Tuple[float, float]]: The minimum value or `None` if empty + """ + + def min_item(self) -> Optional[Tuple[Node, Tuple[float, float]]]: + """ + Return smallest value and corresponding node + + Returns: + Optional[Tuple[Node, Tuple[float, float]]]: The Node and minimum value or `None` if empty + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted(self, reverse: bool = False) -> NodeStateHits: + """ + Sort by value + + Arguments: + reverse (bool): If `True`, sort in descending order, otherwise ascending. Defaults to False. + + Returns: + NodeStateHits: Sorted node state + """ + + def sorted_by_id(self) -> NodeStateHits: + """ + Sort results by node id + + Returns: + NodeStateHits: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def top_k(self, k: int) -> NodeStateHits: + """ + Compute the k largest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateHits: The k largest values as a node state + """ + + def values(self) -> Iterator[Tuple[float, float]]: + """ + Iterate over values + + Returns: + Iterator[Tuple[float, float]]: Iterator over values + """ + +class NodeStateSEIR(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self NodeStateSEIR: + """ + Compute the k smallest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateSEIR: The k smallest values as a node state + """ + + def get( + self, node: NodeInput, default: Optional[Infected] = None + ) -> Optional[Infected]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[Infected]): the default value. Defaults to None. + + Returns: + Optional[Infected]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, Infected]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, Infected]]: Iterator over items + """ + + def max(self) -> Optional[Infected]: + """ + Return the maximum value + + Returns: + Optional[Infected]: The maximum value or `None` if empty + """ + + def max_item(self) -> Optional[Tuple[Node, Infected]]: + """ + Return largest value and corresponding node + + Returns: + Optional[Tuple[Node, Infected]]: The Node and maximum value or `None` if empty + """ + + def median(self) -> Optional[Infected]: + """ + Return the median value + + Returns: + Optional[Infected]: + """ + + def median_item(self) -> Optional[Tuple[Node, Infected]]: + """ + Return median value and corresponding node + + Returns: + Optional[Tuple[Node, Infected]]: The median value or `None` if empty + """ + + def min(self) -> Optional[Infected]: + """ + Return the minimum value + + Returns: + Optional[Infected]: The minimum value or `None` if empty + """ + + def min_item(self) -> Optional[Tuple[Node, Infected]]: + """ + Return smallest value and corresponding node + + Returns: + Optional[Tuple[Node, Infected]]: The Node and minimum value or `None` if empty + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted(self, reverse: bool = False) -> NodeStateSEIR: + """ + Sort by value + + Arguments: + reverse (bool): If `True`, sort in descending order, otherwise ascending. Defaults to False. + + Returns: + NodeStateSEIR: Sorted node state + """ + + def sorted_by_id(self) -> NodeStateSEIR: + """ + Sort results by node id + + Returns: + NodeStateSEIR: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def top_k(self, k: int) -> NodeStateSEIR: + """ + Compute the k largest values + + Arguments: + k (int): The number of values to return + + Returns: + NodeStateSEIR: The k largest values as a node state + """ + + def values(self) -> Iterator[Infected]: + """ + Iterate over values + + Returns: + Iterator[Infected]: Iterator over values + """ + +class NodeLayout(object): + def __eq__(self, value): + """Return self==value.""" + + def __ge__(self, value): + """Return self>=value.""" + + def __getitem__(self, key): + """Return self[key].""" + + def __gt__(self, value): + """Return self>value.""" + + def __iter__(self): + """Implement iter(self).""" + + def __le__(self, value): + """Return self<=value.""" + + def __len__(self): + """Return len(self).""" + + def __lt__(self, value): + """Return self Optional[list[float]]: + """ + Get value for node + + Arguments: + node (NodeInput): the node + default (Optional[list[float]]): the default value. Defaults to None. + + Returns: + Optional[list[float]]: the value for the node or the default value + """ + + def items(self) -> Iterator[Tuple[Node, list[float]]]: + """ + Iterate over items + + Returns: + Iterator[Tuple[Node, list[float]]]: Iterator over items + """ + + def nodes(self) -> Nodes: + """ + Iterate over nodes + + Returns: + Nodes: The nodes + """ + + def sorted_by_id(self) -> NodeLayout: + """ + Sort results by node id + + Returns: + NodeLayout: The sorted node state + """ + + def to_df(self) -> DataFrame: + """ + Convert results to pandas DataFrame + + The DataFrame has two columns, "node" with the node ids and "value" with + the corresponding values. + + Returns: + DataFrame: the pandas DataFrame + """ + + def values(self) -> Iterator[list[float]]: + """ + Iterate over values + + Returns: + Iterator[list[float]]: Iterator over values + """ diff --git a/python/python/raphtory/vectors/__init__.pyi b/python/python/raphtory/vectors/__init__.pyi index a55cd2a04..b35ddce3a 100644 --- a/python/python/raphtory/vectors/__init__.pyi +++ b/python/python/raphtory/vectors/__init__.pyi @@ -10,7 +10,6 @@ from typing import * from raphtory import * from raphtory.algorithms import * -from raphtory.vectors import * from raphtory.node_state import * from raphtory.graphql import * from raphtory.typing import * diff --git a/raphtory/src/python/graph/algorithm_result.rs b/raphtory/src/python/graph/algorithm_result.rs deleted file mode 100644 index ae7c083c2..000000000 --- a/raphtory/src/python/graph/algorithm_result.rs +++ /dev/null @@ -1,358 +0,0 @@ -use crate::{ - algorithms::algorithm_result::AlgorithmResult as AlgorithmResultRs, - core::entities::VID, - db::api::view::{internal::DynamicGraph, StaticGraphViewOps}, - python::types::repr::{Repr, StructReprBuilder}, -}; -use ordered_float::OrderedFloat; -use pyo3::prelude::*; -use raphtory_api::core::entities::GID; - -impl Repr for AlgorithmResultRs { - fn repr(&self) -> String { - let algo_name = &self.algo_repr.algo_name; - let num_nodes = &self.result.len(); - StructReprBuilder::new("AlgorithmResult") - .add_field("name", algo_name) - .add_field("num_nodes", num_nodes) - .add_field("result", self.get_all_with_names()) - .finish() - } -} - -#[macro_export] -macro_rules! py_algorithm_result { - ($objectName:ident, $rustGraph:ty, $rustValue:ty, $rustSortValue:ty) => { - #[pyclass(module = "raphtory", frozen)] - pub struct $objectName( - $crate::algorithms::algorithm_result::AlgorithmResult< - $rustGraph, - $rustValue, - $rustSortValue, - >, - ); - - impl<'py> pyo3::IntoPyObject<'py> - for $crate::algorithms::algorithm_result::AlgorithmResult< - $rustGraph, - $rustValue, - $rustSortValue, - > - { - type Target = $objectName; - type Output = >::Output; - type Error = >::Error; - - fn into_pyobject(self, py: Python<'py>) -> Result { - $objectName(self).into_pyobject(py) - } - } - }; -} - -#[macro_export] -macro_rules! py_algorithm_result_base { - ($objectName:ident, $rustGraph:ty, $rustValue:ty) => { - #[pymethods] - impl $objectName { - /// Returns a Dict containing all the nodes (as keys) and their corresponding values (values) or none. - /// - /// Returns: - /// dict[Node, Any]: A dict of nodes and their values - fn get_all( - &self, - ) -> std::collections::HashMap< - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - > { - self.0.get_all() - } - - /// Get all values - /// - /// Returns: - /// list[Any]: the values for each node as a list - fn get_all_values(&self) -> std::vec::Vec<$rustValue> { - self.0.get_all_values().clone() - } - - /// Returns the value corresponding to the provided key - /// - /// Arguments: - /// key (NodeInput): The node for which the value is to be retrieved. - /// - /// Returns: - /// Optional[Any]: The value for the node or `None` if the value does not exist. - fn get(&self, key: $crate::python::utils::PyNodeRef) -> Option<$rustValue> { - self.0.get(key).cloned() - } - - /// Returns a dict with node names and values - /// - /// Returns: - /// dict[str, Any]: a dict with node names and values - fn get_all_with_names(&self) -> std::collections::HashMap { - self.0.get_all_with_names() - } - - /// Sorts by node id in ascending or descending order. - /// - /// Arguments: - /// reverse (bool): If `true`, sorts the result in descending order; otherwise, sorts in ascending order. Defaults to True. - /// - /// Returns: - /// list[Tuple[Node, Any]]: A sorted list of tuples containing nodes and values. - #[pyo3(signature = (reverse=true))] - fn sort_by_node( - &self, - reverse: bool, - ) -> std::vec::Vec<( - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - )> { - self.0.sort_by_node(reverse) - } - - fn __len__(&self) -> usize { - self.0.len() - } - - fn __repr__(&self) -> String { - self.0.repr() - } - - /// Creates a dataframe from the result - /// - /// Returns: - /// DataFrame: A `pandas.DataFrame` containing the result - fn to_df(&self) -> PyResult { - let hashmap = &self.0.result; - let mut keys = Vec::new(); - let mut values = Vec::new(); - Python::with_gil(|py| { - for (key, value) in hashmap.iter() { - let node = $crate::db::api::view::internal::core_ops::CoreGraphOps::node_id( - &self.0.graph, - VID(*key), - ); - keys.push(node.into_pyobject(py)?.into_any().unbind()); - values.push(value.into_pyobject(py)?.into_any().unbind()); - } - let dict = pyo3::types::PyDict::new(py); - dict.set_item("Node", pyo3::types::PyList::new(py, keys.as_slice())?)?; - dict.set_item("Value", pyo3::types::PyList::new(py, values.as_slice())?)?; - let pandas = pyo3::types::PyModule::import(py, "pandas")?; - let df = pandas.getattr("DataFrame")?.call1((dict,))?; - Ok(df.unbind()) - }) - } - } - }; -} - -#[macro_export] -macro_rules! py_algorithm_result_partial_ord { - ($objectName:ident, $rustGraph:ty, $rustValue:ty) => { - #[pymethods] - impl $objectName { - /// Sorts the `AlgorithmResult` by its values in ascending or descending order. - /// - /// Arguments: - /// reverse (bool): If `true`, sorts the result in descending order, otherwise, sorts in ascending order. Defaults to True. - /// - /// Returns: - /// list[Tuple[Node, Any]]: A sorted vector of tuples containing Nodes and values. - #[pyo3(signature = (reverse=true))] - fn sort_by_value( - &self, - reverse: bool, - ) -> std::vec::Vec<( - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - )> { - self.0.sort_by_value(reverse) - } - - /// The function `sort_by_node_name` sorts a vector of tuples containing a node and an optional - /// value by the node name in either ascending or descending order. - /// - /// Arguments: - /// reverse (bool): A boolean value indicating whether the sorting should be done in reverse order or not. Defaults to True. - /// If reverse is true, the sorting will be done in descending order, otherwise it will be done in - /// ascending order. - /// - /// Returns: - /// list[Tuple[Node, Any]]: The function sort_by_node_name returns a vector of tuples. Each tuple contains a Node and value - #[pyo3(signature = (reverse=true))] - fn sort_by_node_name( - &self, - reverse: bool, - ) -> std::vec::Vec<( - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - )> { - self.0.sort_by_node_name(reverse) - } - - /// Retrieves the top-k elements from the `AlgorithmResult` based on its values. - /// - /// Arguments: - /// k (int): The number of elements to retrieve. - /// percentage (bool): If `True`, the `k` parameter is treated as a percentage of total elements. Defaults to False. - /// reverse (bool): If `True`, retrieves the elements in descending order, otherwise, in ascending order. Defaults to True. - /// - /// Returns: - /// list[Tuple[Node, Any]]: List of tuples with keys of nodes and values of type `Y`. - /// If percentage is true, the returned vector contains the top `k` percentage of elements. - /// If percentage is false, the returned vector contains the top `k` elements. - /// Returns None if the result is empty or if `k` is 0. - #[pyo3(signature = (k, percentage=false, reverse=true))] - fn top_k( - &self, - k: usize, - percentage: bool, - reverse: bool, - ) -> std::vec::Vec<( - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - )> { - self.0.top_k(k, percentage, reverse) - } - - /// Find node with minimum value - /// - /// Returns: - /// Tuple[Node, Any]: The node and minimum value. - fn min( - &self, - ) -> Option<( - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - )> { - self.0.min() - } - - /// Find node with maximum value - /// - /// Returns: - /// Tuple[Node, Any]: The node and maximum value. - fn max( - &self, - ) -> Option<( - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - )> { - self.0.max() - } - - /// Returns a tuple of the median result with its key - /// - /// Returns: - /// Optional[Tuple[Node, Any]]: The node with median value or `None` if there are no nodes. - fn median( - &self, - ) -> Option<( - $crate::db::graph::node::NodeView<$rustGraph, $rustGraph>, - $rustValue, - )> { - self.0.median() - } - } - $crate::py_algorithm_result_base!($objectName, $rustGraph, $rustValue); - }; -} - -#[macro_export] -macro_rules! py_algorithm_result_new_ord_hash_eq { - ($objectName:ident, $rustGraph:ty, $rustValue:ty) => { - #[pymethods] - impl $objectName { - /// Groups the `AlgorithmResult` by its values. - /// - /// Returns: - /// dict[Any, list[str]]: A mapping where keys are unique values from the `AlgorithmResult` and values are lists of nodes - /// that share the same value. - fn group_by(&self) -> std::collections::HashMap<$rustValue, Vec> { - self.0.group_by() - } - } - $crate::py_algorithm_result_partial_ord!($objectName, $rustGraph, $rustValue); - }; -} - -py_algorithm_result!(AlgorithmResult, DynamicGraph, String, String); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResult, DynamicGraph, String); - -py_algorithm_result!(AlgorithmResultF64, DynamicGraph, f64, OrderedFloat); -py_algorithm_result_partial_ord!(AlgorithmResultF64, DynamicGraph, f64); - -py_algorithm_result!( - AlgorithmResultPairF32, - DynamicGraph, - [f32; 2], - [OrderedFloat; 2] -); -py_algorithm_result_partial_ord!(AlgorithmResultPairF32, DynamicGraph, [f32; 2]); - -py_algorithm_result!(AlgorithmResultU64, DynamicGraph, u64, u64); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultU64, DynamicGraph, u64); - -py_algorithm_result!(AlgorithmResultGID, DynamicGraph, GID, GID); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultGID, DynamicGraph, GID); - -py_algorithm_result!( - AlgorithmResultTupleF32F32, - DynamicGraph, - (f32, f32), - (OrderedFloat, OrderedFloat) -); -py_algorithm_result_partial_ord!(AlgorithmResultTupleF32F32, DynamicGraph, (f32, f32)); - -py_algorithm_result!( - AlgorithmResultVecI64Str, - DynamicGraph, - Vec<(i64, String)>, - Vec<(i64, String)> -); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultVecI64Str, DynamicGraph, Vec<(i64, String)>); - -py_algorithm_result!( - AlgorithmResultVecF64, - DynamicGraph, - Vec, - Vec> -); -py_algorithm_result_partial_ord!(AlgorithmResultVecF64, DynamicGraph, Vec); - -py_algorithm_result!(AlgorithmResultUsize, DynamicGraph, usize, usize); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultUsize, DynamicGraph, usize); - -py_algorithm_result!( - AlgorithmResultVecUsize, - DynamicGraph, - Vec, - Vec -); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultVecUsize, DynamicGraph, Vec); - -py_algorithm_result!(AlgorithmResultU64VecU64, DynamicGraph, Vec, Vec); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultU64VecU64, DynamicGraph, Vec); - -py_algorithm_result!(AlgorithmResultGIDVecGID, DynamicGraph, Vec, Vec); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultGIDVecGID, DynamicGraph, Vec); - -py_algorithm_result!( - AlgorithmResultVecStr, - DynamicGraph, - Vec, - Vec -); -py_algorithm_result_new_ord_hash_eq!(AlgorithmResultVecStr, DynamicGraph, Vec); - -py_algorithm_result!( - AlgorithmResultPropVecStr, - DynamicGraph, - (f64, Vec), - (OrderedFloat, Vec) -); -py_algorithm_result_partial_ord!(AlgorithmResultPropVecStr, DynamicGraph, (f64, Vec));