diff --git a/python/python/raphtory/__init__.pyi b/python/python/raphtory/__init__.pyi index 365f49492d..bd5cdf4b67 100644 --- a/python/python/raphtory/__init__.pyi +++ b/python/python/raphtory/__init__.pyi @@ -1,6 +1,7 @@ """ Raphtory graph analytics library """ + from __future__ import annotations ############################################################################### @@ -25,8 +26,39 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['GraphView', 'Graph', 'PersistentGraph', 'Node', 'Nodes', 'PathFromNode', 'PathFromGraph', 'MutableNode', 'Edge', 'Edges', 'NestedEdges', 'MutableEdge', 'Properties', 'Metadata', 'TemporalProperties', 'PropertiesView', 'TemporalProp', 'WindowSet', 'IndexSpecBuilder', 'IndexSpec', 'version', 'graphql', 'algorithms', 'graph_loader', 'graph_gen', 'vectors', 'node_state', 'filter', 'nullmodels', 'plottingutils'] -class GraphView(object): +__all__ = [ + "GraphView", + "Graph", + "PersistentGraph", + "Node", + "Nodes", + "PathFromNode", + "PathFromGraph", + "MutableNode", + "Edge", + "Edges", + "NestedEdges", + "MutableEdge", + "Properties", + "ConstantProperties", + "TemporalProperties", + "PropertiesView", + "TemporalProp", + "Prop", + "PropertyFilter", + "WindowSet", + "graphql", + "algorithms", + "graph_loader", + "graph_gen", + "vectors", + "node_state", + "filter", + "nullmodels", + "plottingutils", +] + +class GraphView(object): """Graph view is a read-only version of a graph at a certain point in time.""" def __eq__(self, value): @@ -117,6 +149,9 @@ class GraphView(object): int: the number of temporal edges in the graph """ + def create_index(self): + """Create graph index""" + def default_layer(self) -> GraphView: """ Return a view of GraphView containing only the default edge layer @@ -249,60 +284,60 @@ class GraphView(object): WindowSet: A `WindowSet` object. """ - def filter_edges(self, filter: filter.FilterExpr) -> GraphView: + def filter_edges(self, filter: PropertyFilter) -> GraphView: """ Return a filtered view that only includes edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the edges. + filter (PropertyFilter): The filter to apply to the edge properties. Construct a + filter using `Prop`. Returns: GraphView: The filtered view """ - def filter_exploded_edges(self, filter: filter.FilterExpr) -> GraphView: + def filter_exploded_edges(self, filter: PropertyFilter) -> GraphView: """ Return a filtered view that only includes exploded edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the exploded edge properties. + filter (PropertyFilter): The filter to apply to the exploded edge properties. Construct a + filter using `Prop`. Returns: GraphView: The filtered view """ - def filter_nodes(self, filter: filter.FilterExpr) -> GraphView: + def filter_nodes(self, filter: PropertyFilter) -> GraphView: """ Return a filtered view that only includes nodes that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the nodes. + filter (PropertyFilter): The filter to apply to the node properties. Construct a + filter using `Prop`. Returns: GraphView: The filtered view """ - def find_edges(self, properties_dict: dict[str, PropValue]) -> list[Edge]: + def find_edges(self, properties_dict: dict[str, Prop]) -> list[Edge]: """ Get the edges that match the properties name and value Arguments: - properties_dict (dict[str, PropValue]): the properties name and value + properties_dict (dict[str, Prop]): the properties name and value Returns: list[Edge]: the edges that match the properties name and value """ - def find_nodes(self, properties_dict: dict[str, PropValue]) -> list[Node]: + def find_nodes(self, properties_dict: dict[str, Prop]) -> list[Node]: """ Get the nodes that match the properties name and value Arguments: - properties_dict (dict[str, PropValue]): the properties name and value + properties_dict (dict[str, Prop]): the properties name and value Returns: list[Node]: the nodes that match the properties name and value """ - def get_index_spec(self): - """Get index spec""" - def has_edge(self, src: NodeInput, dst: NodeInput) -> bool: """ Returns true if the graph contains the specified edge @@ -395,16 +430,6 @@ class GraphView(object): GraphView: Returns a graph clone """ - @property - def metadata(self) -> Metadata: - """ - Get all graph metadata - - - Returns: - Metadata: - """ - def node(self, id: NodeInput) -> Optional[Node]: """ Gets the node with the specified id @@ -572,7 +597,14 @@ class GraphView(object): GraphView: Returns the subgraph """ - def to_networkx(self, explode_edges: bool = False, include_node_properties: bool = True, include_edge_properties: bool = True, include_update_history: bool = True, include_property_history: bool = True) -> nx.MultiDiGraph: + def to_networkx( + self, + explode_edges: bool = False, + include_node_properties: bool = True, + include_edge_properties: bool = True, + include_update_history: bool = True, + include_property_history: bool = True, + ) -> nx.MultiDiGraph: """ Returns a graph with NetworkX. @@ -591,7 +623,19 @@ class GraphView(object): nx.MultiDiGraph: A Networkx MultiDiGraph. """ - def to_pyvis(self, explode_edges: bool = False, edge_color: str = '#000000', shape: str = 'dot', node_image: Optional[str] = None, edge_weight: Optional[str] = None, edge_label: Optional[str] = None, colour_nodes_by_type: bool = False, directed: bool = True, notebook: bool = False, **kwargs: Any) -> pyvis.network.Network: + def to_pyvis( + self, + explode_edges: bool = False, + edge_color: str = "#000000", + shape: str = "dot", + node_image: Optional[str] = None, + edge_weight: Optional[str] = None, + edge_label: Optional[str] = None, + colour_nodes_by_type: bool = False, + directed: bool = True, + notebook: bool = False, + **kwargs: Any, + ) -> pyvis.network.Network: """ Draw a graph with PyVis. Pyvis is a required dependency. If you intend to use this function make sure that you install Pyvis @@ -626,20 +670,6 @@ class GraphView(object): list[str]: the names of all layers in the graph """ - def valid(self) -> GraphView: - """ - Return a view of the graph that only includes valid edges - - Note: - - The semantics for `valid` depend on the time semantics of the underlying graph. - In the case of a persistent graph, an edge is valid if its last update is an addition. - In the case of an event graph, an edge is valid if it has at least one addition event. - - Returns: - GraphView: The filtered graph - """ - def valid_layers(self, names: list[str]) -> GraphView: """ Return a view of GraphView containing all layers `names` @@ -652,15 +682,28 @@ class GraphView(object): GraphView: The layered view """ - def vectorise(self, embedding: Callable[[list], list], nodes: bool | str = True, edges: bool | str = True, cache: Optional[str] = None, verbose: bool = False) -> VectorisedGraph: + def vectorise( + self, + embedding: Callable[[list], list], + cache: Optional[str] = None, + overwrite_cache: bool = False, + graph: bool | str = True, + nodes: bool | str = True, + edges: bool | str = True, + graph_name: Optional[str] = None, + verbose: bool = False, + ) -> VectorisedGraph: """ Create a VectorisedGraph from the current graph Args: embedding (Callable[[list], list]): the embedding function to translate documents to embeddings + cache (str, optional): the file to be used as a cache to avoid calling the embedding function + overwrite_cache (bool): whether or not to overwrite the cache if there are new embeddings. Defaults to False. + graph (bool | str): if the graph has to be embedded or not or the custom template to use if a str is provided. Defaults to True. nodes (bool | str): if nodes have to be embedded or not or the custom template to use if a str is provided. Defaults to True. edges (bool | str): if edges have to be embedded or not or the custom template to use if a str is provided. Defaults to True. - cache (str, optional): the path to use to store the cache for embeddings. + graph_name (str, optional): the name of the graph verbose (bool): whether or not to print logs reporting the progress. Defaults to False. Returns: @@ -688,7 +731,7 @@ class GraphView(object): Optional[int]: """ -class Graph(GraphView): +class Graph(GraphView): """ A temporal graph with event semantics. @@ -699,43 +742,56 @@ class Graph(GraphView): def __new__(cls, num_shards: Optional[int] = None) -> Graph: """Create and return a new object. See help(type) for accurate signature.""" - def __reduce__(self): - ... - - def add_edge(self, timestamp: TimeInput, src: str|int, dst: str|int, properties: Optional[PropInput] = None, layer: Optional[str] = None, secondary_index: Optional[int] = None) -> MutableEdge: + def __reduce__(self): ... + def add_constant_properties(self, properties: PropInput) -> None: """ - Adds a new edge with the given source and destination nodes and properties to the graph. + Adds static properties to the graph. Arguments: - timestamp (TimeInput): The timestamp of the edge. - src (str|int): The id of the source node. - dst (str|int): The id of the destination node. - properties (PropInput, optional): The properties of the edge, as a dict of string and properties. - layer (str, optional): The layer of the edge. - secondary_index (int, optional): The optional integer which will be used as a secondary index + properties (PropInput): The static properties of the graph. Returns: - MutableEdge: The added edge. + None: This function does not return a value, if the operation is successful. Raises: GraphError: If the operation fails. """ - def add_metadata(self, metadata: PropInput) -> None: + def add_edge( + self, + timestamp: TimeInput, + src: str | int, + dst: str | int, + properties: Optional[PropInput] = None, + layer: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> MutableEdge: """ - Adds static properties to the graph. + Adds a new edge with the given source and destination nodes and properties to the graph. Arguments: - metadata (PropInput): The static properties of the graph. + timestamp (TimeInput): The timestamp of the edge. + src (str|int): The id of the source node. + dst (str|int): The id of the destination node. + properties (PropInput, optional): The properties of the edge, as a dict of string and properties. + layer (str, optional): The layer of the edge. + secondary_index (int, optional): The optional integer which will be used as a secondary index Returns: - None: This function does not return a value, if the operation is successful. + MutableEdge: The added edge. Raises: GraphError: If the operation fails. """ - def add_node(self, timestamp: TimeInput, id: str|int, properties: Optional[PropInput] = None, node_type: Optional[str] = None, secondary_index: Optional[int] = None) -> MutableNode: + def add_node( + self, + timestamp: TimeInput, + id: str | int, + properties: Optional[PropInput] = None, + node_type: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> MutableNode: """ Adds a new node with the given id and properties to the graph. @@ -753,7 +809,12 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def add_properties(self, timestamp: TimeInput, properties: PropInput, secondary_index: Optional[int] = None) -> None: + def add_properties( + self, + timestamp: TimeInput, + properties: PropInput, + secondary_index: Optional[int] = None, + ) -> None: """ Adds properties to the graph. @@ -783,29 +844,14 @@ class Graph(GraphView): None: """ - def create_index(self): - """Create graph index""" - - def create_index_in_ram(self): - """ - Creates a graph index in memory (RAM). - - This is primarily intended for use in tests and should not be used in production environments, - as the index will not be persisted to disk. - """ - - def create_index_in_ram_with_spec(self, py_spec): - """ - Creates a graph index in memory (RAM) with the provided index spec. - - This is primarily intended for use in tests and should not be used in production environments, - as the index will not be persisted to disk. - """ - - def create_index_with_spec(self, py_spec): - """Create graph index with the provided index spec.""" - - def create_node(self, timestamp: TimeInput, id: str|int, properties: Optional[PropInput] = None, node_type: Optional[str] = None, secondary_index: Optional[int] = None) -> MutableNode: + def create_node( + self, + timestamp: TimeInput, + id: str | int, + properties: Optional[PropInput] = None, + node_type: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> MutableNode: """ Creates a new node with the given id and properties to the graph. It fails if the node already exists. @@ -835,7 +881,7 @@ class Graph(GraphView): Graph: """ - def edge(self, src: str|int, dst: str|int) -> MutableEdge: + def edge(self, src: str | int, dst: str | int) -> MutableEdge: """ Gets the edge with the specified source and destination nodes @@ -928,7 +974,9 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def import_edges_as(self, edges: List[Edge], new_ids: List[Tuple[int, int]], merge: bool = False) -> None: + def import_edges_as( + self, edges: List[Edge], new_ids: List[Tuple[int, int]], merge: bool = False + ) -> None: """ Import multiple edges into the graph with new ids. @@ -963,7 +1011,9 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def import_node_as(self, node: Node, new_id: str|int, merge: bool = False) -> MutableNode: + def import_node_as( + self, node: Node, new_id: str | int, merge: bool = False + ) -> MutableNode: """ Import a single node into the graph with new id. @@ -998,7 +1048,9 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def import_nodes_as(self, nodes: List[Node], new_ids: List[str|int], merge: bool = False) -> None: + def import_nodes_as( + self, nodes: List[Node], new_ids: List[str | int], merge: bool = False + ) -> None: """ Import multiple nodes into the graph with new ids. @@ -1043,7 +1095,16 @@ class Graph(GraphView): Graph: the loaded graph with initialised cache """ - def load_edge_props_from_pandas(self, df: DataFrame, src: str, dst: str, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edge_props_from_pandas( + self, + df: DataFrame, + src: str, + dst: str, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edge properties from a Pandas DataFrame. @@ -1051,8 +1112,8 @@ class Graph(GraphView): df (DataFrame): The Pandas DataFrame containing edge information. src (str): The column name for the source node. dst (str): The column name for the destination node. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. layer (str, optional): The edge layer name. Defaults to None. layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. @@ -1063,7 +1124,16 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def load_edge_props_from_parquet(self, parquet_path: str, src: str, dst: str, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edge_props_from_parquet( + self, + parquet_path: str, + src: str, + dst: str, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edge properties from parquet file @@ -1071,8 +1141,8 @@ class Graph(GraphView): parquet_path (str): Parquet file or directory of Parquet files path containing edge information. src (str): The column name for the source node. dst (str): The column name for the destination node. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. layer (str, optional): The edge layer name. Defaults to None. layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. @@ -1083,7 +1153,18 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def load_edges_from_pandas(self, df: DataFrame, time: str, src: str, dst: str, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edges_from_pandas( + self, + df: DataFrame, + time: str, + src: str, + dst: str, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edges from a Pandas DataFrame into the graph. @@ -1093,9 +1174,9 @@ class Graph(GraphView): src (str): The column name for the source node ids. dst (str): The column name for the destination node ids. properties (List[str], optional): List of edge property column names. Defaults to None. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. - layer (str, optional): A value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. + layer (str, optional): A constant value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. (cannot be used in combination with layer) Returns: @@ -1105,7 +1186,18 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def load_edges_from_parquet(self, parquet_path: str, time: str, src: str, dst: str, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edges_from_parquet( + self, + parquet_path: str, + time: str, + src: str, + dst: str, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edges from a Parquet file into the graph. @@ -1115,9 +1207,9 @@ class Graph(GraphView): src (str): The column name for the source node ids. dst (str): The column name for the destination node ids. properties (List[str], optional): List of edge property column names. Defaults to None. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. - layer (str, optional): A value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. + layer (str, optional): A constant value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. (cannot be used in combination with layer) Returns: @@ -1139,17 +1231,25 @@ class Graph(GraphView): Graph: """ - def load_node_props_from_pandas(self, df: DataFrame, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_node_props_from_pandas( + self, + df: DataFrame, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load node properties from a Pandas DataFrame. Arguments: df (DataFrame): The Pandas DataFrame containing node information. id(str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1158,17 +1258,25 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def load_node_props_from_parquet(self, parquet_path: str, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_node_props_from_parquet( + self, + parquet_path: str, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load node properties from a parquet file. Arguments: parquet_path (str): Parquet file or directory of Parquet files path containing node information. id(str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1177,7 +1285,17 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def load_nodes_from_pandas(self, df: DataFrame, time: str, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_nodes_from_pandas( + self, + df: DataFrame, + time: str, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load nodes from a Pandas DataFrame into the graph. @@ -1185,11 +1303,11 @@ class Graph(GraphView): df (DataFrame): The Pandas DataFrame containing the nodes. time (str): The column name for the timestamps. id (str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) properties (List[str], optional): List of node property column names. Defaults to None. - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1198,7 +1316,17 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def load_nodes_from_parquet(self, parquet_path: str, time: str, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_nodes_from_parquet( + self, + parquet_path: str, + time: str, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load nodes from a Parquet file into the graph. @@ -1206,11 +1334,11 @@ class Graph(GraphView): parquet_path (str): Parquet file or directory of Parquet files containing the nodes time (str): The column name for the timestamps. id (str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) properties (List[str], optional): List of node property column names. Defaults to None. - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1219,7 +1347,7 @@ class Graph(GraphView): GraphError: If the operation fails. """ - def node(self, id: str|int) -> MutableNode: + def node(self, id: str | int) -> MutableNode: """ Gets the node with the specified id @@ -1276,12 +1404,12 @@ class Graph(GraphView): """ - def update_metadata(self, metadata: PropInput) -> None: + def update_constant_properties(self, properties: PropInput) -> None: """ Updates static properties to the graph. Arguments: - metadata (PropInput): The static properties of the graph. + properties (PropInput): The static properties of the graph. Returns: None: This function does not return a value, if the operation is successful. @@ -1298,26 +1426,19 @@ class Graph(GraphView): None: """ -class PersistentGraph(GraphView): +class PersistentGraph(GraphView): """A temporal graph that allows edges and nodes to be deleted.""" def __new__(cls) -> PersistentGraph: """Create and return a new object. See help(type) for accurate signature.""" - def __reduce__(self): - ... - - def add_edge(self, timestamp: int, src: str | int, dst: str | int, properties: Optional[PropInput] = None, layer: Optional[str] = None, secondary_index: Optional[int] = None) -> None: + def __reduce__(self): ... + def add_constant_properties(self, properties: dict) -> None: """ - Adds a new edge with the given source and destination nodes and properties to the graph. + Adds static properties to the graph. Arguments: - timestamp (int): The timestamp of the edge. - src (str | int): The id of the source node. - dst (str | int): The id of the destination node. - properties (PropInput, optional): The properties of the edge, as a dict of string and properties - layer (str, optional): The layer of the edge. - secondary_index (int, optional): The optional integer which will be used as a secondary index + properties (dict): The static properties of the graph. Returns: None: This function does not return a value, if the operation is successful. @@ -1326,12 +1447,25 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def add_metadata(self, metadata: dict) -> None: + def add_edge( + self, + timestamp: int, + src: str | int, + dst: str | int, + properties: Optional[PropInput] = None, + layer: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> None: """ - Adds metadata to the graph. + Adds a new edge with the given source and destination nodes and properties to the graph. Arguments: - metadata (dict): The static properties of the graph. + timestamp (int): The timestamp of the edge. + src (str | int): The id of the source node. + dst (str | int): The id of the destination node. + properties (PropInput, optional): The properties of the edge, as a dict of string and properties + layer (str, optional): The layer of the edge. + secondary_index (int, optional): The optional integer which will be used as a secondary index Returns: None: This function does not return a value, if the operation is successful. @@ -1340,7 +1474,14 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def add_node(self, timestamp: TimeInput, id: str | int, properties: Optional[PropInput] = None, node_type: Optional[str] = None, secondary_index: Optional[int] = None) -> None: + def add_node( + self, + timestamp: TimeInput, + id: str | int, + properties: Optional[PropInput] = None, + node_type: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> None: """ Adds a new node with the given id and properties to the graph. @@ -1358,7 +1499,12 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def add_properties(self, timestamp: TimeInput, properties: dict, secondary_index: Optional[int] = None) -> None: + def add_properties( + self, + timestamp: TimeInput, + properties: dict, + secondary_index: Optional[int] = None, + ) -> None: """ Adds properties to the graph. @@ -1388,29 +1534,14 @@ class PersistentGraph(GraphView): None: """ - def create_index(self): - """Create graph index""" - - def create_index_in_ram(self): - """ - Creates a graph index in memory (RAM). - - This is primarily intended for use in tests and should not be used in production environments, - as the index will not be persisted to disk. - """ - - def create_index_in_ram_with_spec(self, py_spec): - """ - Creates a graph index in memory (RAM) with the provided index spec. - - This is primarily intended for use in tests and should not be used in production environments, - as the index will not be persisted to disk. - """ - - def create_index_with_spec(self, py_spec): - """Create graph index with the provided index spec.""" - - def create_node(self, timestamp: TimeInput, id: str | int, properties: Optional[PropInput] = None, node_type: Optional[str] = None, secondary_index: Optional[int] = None) -> MutableNode: + def create_node( + self, + timestamp: TimeInput, + id: str | int, + properties: Optional[PropInput] = None, + node_type: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> MutableNode: """ Creates a new node with the given id and properties to the graph. It fails if the node already exists. @@ -1428,7 +1559,14 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def delete_edge(self, timestamp: int, src: str | int, dst: str | int, layer: Optional[str] = None, secondary_index: Optional[int] = None) -> MutableEdge: + def delete_edge( + self, + timestamp: int, + src: str | int, + dst: str | int, + layer: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> MutableEdge: """ Deletes an edge given the timestamp, src and dst nodes and layer (optional) @@ -1541,7 +1679,9 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def import_edges_as(self, edges: List[Edge], new_ids: list[Tuple[GID, GID]], merge: bool = False) -> None: + def import_edges_as( + self, edges: List[Edge], new_ids: list[Tuple[GID, GID]], merge: bool = False + ) -> None: """ Import multiple edges into the graph with new ids. @@ -1578,7 +1718,9 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def import_node_as(self, node: Node, new_id: str|int, merge: bool = False) -> Node: + def import_node_as( + self, node: Node, new_id: str | int, merge: bool = False + ) -> Node: """ Import a single node into the graph with new id. @@ -1615,7 +1757,9 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def import_nodes_as(self, nodes: List[Node], new_ids: List[str|int], merge: bool = False) -> None: + def import_nodes_as( + self, nodes: List[Node], new_ids: List[str | int], merge: bool = False + ) -> None: """ Import multiple nodes into the graph with new ids. @@ -1649,7 +1793,15 @@ class PersistentGraph(GraphView): PersistentGraph: the loaded graph with initialised cache """ - def load_edge_deletions_from_pandas(self, df: DataFrame, time: str, src: str, dst: str, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edge_deletions_from_pandas( + self, + df: DataFrame, + time: str, + src: str, + dst: str, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edges deletions from a Pandas DataFrame into the graph. @@ -1658,7 +1810,7 @@ class PersistentGraph(GraphView): time (str): The column name for the update timestamps. src (str): The column name for the source node ids. dst (str): The column name for the destination node ids. - layer (str, optional): A value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) + layer (str, optional): A constant value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. (cannot be used in combination with layer) Returns: @@ -1668,7 +1820,15 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_edge_deletions_from_parquet(self, parquet_path: str, time: str, src: str, dst: str, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edge_deletions_from_parquet( + self, + parquet_path: str, + time: str, + src: str, + dst: str, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edges deletions from a Parquet file into the graph. @@ -1677,7 +1837,7 @@ class PersistentGraph(GraphView): src (str): The column name for the source node ids. dst (str): The column name for the destination node ids. time (str): The column name for the update timestamps. - layer (str, optional): A value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) + layer (str, optional): A constant value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. (cannot be used in combination with layer) Returns: @@ -1687,7 +1847,16 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_edge_props_from_pandas(self, df: DataFrame, src: str, dst: str, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edge_props_from_pandas( + self, + df: DataFrame, + src: str, + dst: str, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edge properties from a Pandas DataFrame. @@ -1695,8 +1864,8 @@ class PersistentGraph(GraphView): df (DataFrame): The Pandas DataFrame containing edge information. src (str): The column name for the source node. dst (str): The column name for the destination node. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. layer (str, optional): The edge layer name. Defaults to None. layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. @@ -1707,7 +1876,16 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_edge_props_from_parquet(self, parquet_path: str, src: str, dst: str, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edge_props_from_parquet( + self, + parquet_path: str, + src: str, + dst: str, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edge properties from parquet file @@ -1715,8 +1893,8 @@ class PersistentGraph(GraphView): parquet_path (str): Parquet file or directory of Parquet files path containing edge information. src (str): The column name for the source node. dst (str): The column name for the destination node. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. layer (str, optional): The edge layer name. Defaults to None. layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. @@ -1727,7 +1905,18 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_edges_from_pandas(self, df: DataFrame, time: str, src: str, dst: str, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edges_from_pandas( + self, + df: DataFrame, + time: str, + src: str, + dst: str, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edges from a Pandas DataFrame into the graph. @@ -1737,9 +1926,9 @@ class PersistentGraph(GraphView): src (str): The column name for the source node ids. dst (str): The column name for the destination node ids. properties (List[str], optional): List of edge property column names. Defaults to None. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. - layer (str, optional): A value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. + layer (str, optional): A constant value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. (cannot be used in combination with layer) Returns: @@ -1749,7 +1938,18 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_edges_from_parquet(self, parquet_path: str, time: str, src: str, dst: str, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None, layer: Optional[str] = None, layer_col: Optional[str] = None) -> None: + def load_edges_from_parquet( + self, + parquet_path: str, + time: str, + src: str, + dst: str, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + layer: Optional[str] = None, + layer_col: Optional[str] = None, + ) -> None: """ Load edges from a Parquet file into the graph. @@ -1759,9 +1959,9 @@ class PersistentGraph(GraphView): src (str): The column name for the source node ids. dst (str): The column name for the destination node ids. properties (List[str], optional): List of edge property column names. Defaults to None. - metadata (List[str], optional): List of edge metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every edge. Defaults to None. - layer (str, optional): A value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) + constant_properties (List[str], optional): List of constant edge property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every edge. Defaults to None. + layer (str, optional): A constant value to use as the layer for all edges. Defaults to None. (cannot be used in combination with layer_col) layer_col (str, optional): The edge layer col name in dataframe. Defaults to None. (cannot be used in combination with layer) Returns: @@ -1783,17 +1983,25 @@ class PersistentGraph(GraphView): PersistentGraph: """ - def load_node_props_from_pandas(self, df: DataFrame, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_node_props_from_pandas( + self, + df: DataFrame, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load node properties from a Pandas DataFrame. Arguments: df (DataFrame): The Pandas DataFrame containing node information. id(str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1802,17 +2010,25 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_node_props_from_parquet(self, parquet_path: str, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_node_props_from_parquet( + self, + parquet_path: str, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load node properties from a parquet file. Arguments: parquet_path (str): Parquet file or directory of Parquet files path containing node information. id(str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1821,7 +2037,17 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_nodes_from_pandas(self, df: DataFrame, time: str, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_nodes_from_pandas( + self, + df: DataFrame, + time: str, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load nodes from a Pandas DataFrame into the graph. @@ -1829,11 +2055,11 @@ class PersistentGraph(GraphView): df (DataFrame): The Pandas DataFrame containing the nodes. time (str): The column name for the timestamps. id (str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) properties (List[str], optional): List of node property column names. Defaults to None. - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1842,7 +2068,17 @@ class PersistentGraph(GraphView): GraphError: If the operation fails. """ - def load_nodes_from_parquet(self, parquet_path: str, time: str, id: str, node_type: Optional[str] = None, node_type_col: Optional[str] = None, properties: Optional[List[str]] = None, metadata: Optional[List[str]] = None, shared_metadata: Optional[PropInput] = None) -> None: + def load_nodes_from_parquet( + self, + parquet_path: str, + time: str, + id: str, + node_type: Optional[str] = None, + node_type_col: Optional[str] = None, + properties: Optional[List[str]] = None, + constant_properties: Optional[List[str]] = None, + shared_constant_properties: Optional[PropInput] = None, + ) -> None: """ Load nodes from a Parquet file into the graph. @@ -1850,11 +2086,11 @@ class PersistentGraph(GraphView): parquet_path (str): Parquet file or directory of Parquet files containing the nodes time (str): The column name for the timestamps. id (str): The column name for the node IDs. - node_type (str, optional): A value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) + node_type (str, optional): A constant value to use as the node type for all nodes. Defaults to None. (cannot be used in combination with node_type_col) node_type_col (str, optional): The node type col name in dataframe. Defaults to None. (cannot be used in combination with node_type) properties (List[str], optional): List of node property column names. Defaults to None. - metadata (List[str], optional): List of node metadata column names. Defaults to None. - shared_metadata (PropInput, optional): A dictionary of metadata properties that will be added to every node. Defaults to None. + constant_properties (List[str], optional): List of constant node property column names. Defaults to None. + shared_constant_properties (PropInput, optional): A dictionary of constant properties that will be added to every node. Defaults to None. Returns: None: This function does not return a value, if the operation is successful. @@ -1911,12 +2147,12 @@ class PersistentGraph(GraphView): bytes: """ - def update_metadata(self, metadata: dict) -> None: + def update_constant_properties(self, properties: dict) -> None: """ - Updates metadata of the graph. + Updates static properties to the graph. Arguments: - metadata (dict): The static properties of the graph. + properties (dict): The static properties of the graph. Returns: None: This function does not return a value, if the operation is successful. @@ -1933,7 +2169,7 @@ class PersistentGraph(GraphView): None: """ -class Node(object): +class Node(object): """A node (or node) in the graph.""" def __eq__(self, value): @@ -2029,14 +2265,6 @@ class Node(object): int: The earliest time that the node exists as an integer. """ - def edge_history_count(self) -> int: - """ - Get the number of edge events for this node - - Returns: - int: The number of edge events - """ - @property def edges(self) -> Edges: """ @@ -2122,34 +2350,37 @@ class Node(object): WindowSet: A `WindowSet` object. """ - def filter_edges(self, filter: filter.FilterExpr) -> Node: + def filter_edges(self, filter: PropertyFilter) -> Node: """ Return a filtered view that only includes edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the edges. + filter (PropertyFilter): The filter to apply to the edge properties. Construct a + filter using `Prop`. Returns: Node: The filtered view """ - def filter_exploded_edges(self, filter: filter.FilterExpr) -> Node: + def filter_exploded_edges(self, filter: PropertyFilter) -> Node: """ Return a filtered view that only includes exploded edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the exploded edge properties. + filter (PropertyFilter): The filter to apply to the exploded edge properties. Construct a + filter using `Prop`. Returns: Node: The filtered view """ - def filter_nodes(self, filter: filter.FilterExpr) -> Node: + def filter_nodes(self, filter: PropertyFilter) -> Node: """ Return a filtered view that only includes nodes that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the nodes. + filter (PropertyFilter): The filter to apply to the node properties. Construct a + filter using `Prop`. Returns: Node: The filtered view @@ -2184,7 +2415,7 @@ class Node(object): """ @property - def id(self) -> (str|int): + def id(self) -> str | int: """ Returns the id of the node. This is a unique identifier for the node. @@ -2279,15 +2510,6 @@ class Node(object): Node: The layered view """ - @property - def metadata(self) -> Metadata: - """ - The metadata of the node - - Returns: - Metadata: - """ - @property def name(self) -> str: """ @@ -2475,7 +2697,7 @@ class Node(object): Optional[int]: """ -class Nodes(object): +class Nodes(object): """A list of nodes that can be iterated over.""" def __bool__(self): @@ -2585,14 +2807,6 @@ class Nodes(object): EarliestTimeView: a view of the earliest active times """ - def edge_history_count(self) -> EdgeHistoryCountView: - """ - Return the number of edge updates for each node - - Returns: - EdgeHistoryCountView: a view of the edge history counts - """ - @property def edges(self) -> NestedEdges: """ @@ -2678,34 +2892,37 @@ class Nodes(object): WindowSet: A `WindowSet` object. """ - def filter_edges(self, filter: filter.FilterExpr) -> Nodes: + def filter_edges(self, filter: PropertyFilter) -> Nodes: """ Return a filtered view that only includes edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the edges. + filter (PropertyFilter): The filter to apply to the edge properties. Construct a + filter using `Prop`. Returns: Nodes: The filtered view """ - def filter_exploded_edges(self, filter: filter.FilterExpr) -> Nodes: + def filter_exploded_edges(self, filter: PropertyFilter) -> Nodes: """ Return a filtered view that only includes exploded edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the exploded edge properties. + filter (PropertyFilter): The filter to apply to the exploded edge properties. Construct a + filter using `Prop`. Returns: Nodes: The filtered view """ - def filter_nodes(self, filter: filter.FilterExpr) -> Nodes: + def filter_nodes(self, filter: PropertyFilter) -> Nodes: """ Return a filtered view that only includes nodes that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the nodes. + filter (PropertyFilter): The filter to apply to the node properties. Construct a + filter using `Prop`. Returns: Nodes: The filtered view @@ -2827,15 +3044,6 @@ class Nodes(object): Nodes: The layered view """ - @property - def metadata(self): - """ - The metadata of the node - - Returns: - MetadataView: A view of the node properties - """ - @property def name(self) -> NameView: """ @@ -2990,7 +3198,9 @@ class Nodes(object): Optional[datetime]: The earliest datetime that this Nodes is valid or None if the Nodes is valid for all times. """ - def to_df(self, include_property_history: bool = False, convert_datetime: bool = False) -> DataFrame: + def to_df( + self, include_property_history: bool = False, convert_datetime: bool = False + ) -> DataFrame: """ Converts the graph's nodes into a Pandas DataFrame. @@ -3051,8 +3261,7 @@ class Nodes(object): Optional[int]: """ -class PathFromNode(object): - +class PathFromNode(object): def __bool__(self): """True if self else False""" @@ -3120,14 +3329,6 @@ class PathFromNode(object): def earliest_time(self): """the node earliest times""" - def edge_history_count(self): - """ - Get the number of edge updates for each node - - Returns: - UsizeIterable: - """ - @property def edges(self) -> Edges: """ @@ -3213,34 +3414,37 @@ class PathFromNode(object): WindowSet: A `WindowSet` object. """ - def filter_edges(self, filter: filter.FilterExpr) -> PathFromNode: + def filter_edges(self, filter: PropertyFilter) -> PathFromNode: """ Return a filtered view that only includes edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the edges. + filter (PropertyFilter): The filter to apply to the edge properties. Construct a + filter using `Prop`. Returns: PathFromNode: The filtered view """ - def filter_exploded_edges(self, filter: filter.FilterExpr) -> PathFromNode: + def filter_exploded_edges(self, filter: PropertyFilter) -> PathFromNode: """ Return a filtered view that only includes exploded edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the exploded edge properties. + filter (PropertyFilter): The filter to apply to the exploded edge properties. Construct a + filter using `Prop`. Returns: PathFromNode: The filtered view """ - def filter_nodes(self, filter: filter.FilterExpr) -> PathFromNode: + def filter_nodes(self, filter: PropertyFilter) -> PathFromNode: """ Return a filtered view that only includes nodes that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the nodes. + filter (PropertyFilter): The filter to apply to the node properties. Construct a + filter using `Prop`. Returns: PathFromNode: The filtered view @@ -3320,10 +3524,6 @@ class PathFromNode(object): PathFromNode: The layered view """ - @property - def metadata(self): - """the node metadata""" - @property def name(self): """the node names""" @@ -3502,8 +3702,7 @@ class PathFromNode(object): Optional[int]: """ -class PathFromGraph(object): - +class PathFromGraph(object): def __bool__(self): """True if self else False""" @@ -3575,9 +3774,6 @@ class PathFromGraph(object): def earliest_time(self): """the node earliest times""" - def edge_history_count(self): - """Returns the number of edge updates for each node""" - @property def edges(self) -> NestedEdges: """ @@ -3663,34 +3859,37 @@ class PathFromGraph(object): WindowSet: A `WindowSet` object. """ - def filter_edges(self, filter: filter.FilterExpr) -> PathFromGraph: + def filter_edges(self, filter: PropertyFilter) -> PathFromGraph: """ Return a filtered view that only includes edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the edges. + filter (PropertyFilter): The filter to apply to the edge properties. Construct a + filter using `Prop`. Returns: PathFromGraph: The filtered view """ - def filter_exploded_edges(self, filter: filter.FilterExpr) -> PathFromGraph: + def filter_exploded_edges(self, filter: PropertyFilter) -> PathFromGraph: """ Return a filtered view that only includes exploded edges that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the exploded edge properties. + filter (PropertyFilter): The filter to apply to the exploded edge properties. Construct a + filter using `Prop`. Returns: PathFromGraph: The filtered view """ - def filter_nodes(self, filter: filter.FilterExpr) -> PathFromGraph: + def filter_nodes(self, filter: PropertyFilter) -> PathFromGraph: """ Return a filtered view that only includes nodes that satisfy the filter Arguments: - filter (filter.FilterExpr): The filter to apply to the nodes. + filter (PropertyFilter): The filter to apply to the node properties. Construct a + filter using `Prop`. Returns: PathFromGraph: The filtered view @@ -3780,10 +3979,6 @@ class PathFromGraph(object): PathFromGraph: The layered view """ - @property - def metadata(self): - """the node metadata""" - @property def name(self): """the node names""" @@ -3962,22 +4157,26 @@ class PathFromGraph(object): Optional[int]: """ -class MutableNode(Node): - +class MutableNode(Node): def __repr__(self): """Return repr(self).""" - def add_metadata(self, metadata: PropInput): + def add_constant_properties(self, properties: PropInput): """ - Add metadata to a node in the graph. - This function is used to add properties to a node that do not + Add constant properties to a node in the graph. + This function is used to add properties to a node that remain constant and do not change over time. These properties are fundamental attributes of the node. Parameters: - metadata (PropInput): A dictionary of properties to be added to the node. Each key is a string representing the property name, and each value is of type Prop representing the property value. + properties (PropInput): A dictionary of properties to be added to the node. Each key is a string representing the property name, and each value is of type Prop representing the property value. """ - def add_updates(self, t: TimeInput, properties: Optional[PropInput] = None, secondary_index: Optional[int] = None) -> None: + def add_updates( + self, + t: TimeInput, + properties: Optional[PropInput] = None, + secondary_index: Optional[int] = None, + ) -> None: """ Add updates to a node in the graph at a specified time. This function allows for the addition of property updates to a node within the graph. The updates are time-stamped, meaning they are applied at the specified time. @@ -4006,17 +4205,17 @@ class MutableNode(Node): new_type (str): The new type to be set """ - def update_metadata(self, metadata: PropInput): + def update_constant_properties(self, properties: PropInput): """ - Update metadata of a node in the graph overwriting existing values. - This function is used to add properties to a node that do not + Update constant properties of a node in the graph overwriting existing values. + This function is used to add properties to a node that remain constant and do not change over time. These properties are fundamental attributes of the node. Parameters: - metadata (PropInput): A dictionary of properties to be added to the node. Each key is a string representing the property name, and each value is of type Prop representing the property value. + properties (PropInput): A dictionary of properties to be added to the node. Each key is a string representing the property name, and each value is of type Prop representing the property value. """ -class Edge(object): +class Edge(object): """ PyEdge is a Python class that represents an edge in the graph. An edge is a directed connection between two nodes. @@ -4355,26 +4554,17 @@ class Edge(object): Edge: The layered view """ - @property - def metadata(self) -> Metadata: - """ - Gets the metadata of an edge - - Returns: - Metadata: - """ - @property def nbr(self): """Returns the node at the other end of the edge (same as `dst()` for out-edges and `src()` for in-edges)""" @property - def properties(self) -> Properties: + def properties(self): """ Returns a view of the properties of the edge. Returns: - Properties: Properties on the Edge. + Properties on the Edge. """ def rolling(self, window: int | str, step: int | str | None = None) -> WindowSet: @@ -4512,7 +4702,7 @@ class Edge(object): Optional[int]: """ -class Edges(object): +class Edges(object): """A list of edges that can be iterated over.""" def __bool__(self): @@ -4726,9 +4916,7 @@ class Edges(object): """ - def history_counts(self): - ... - + def history_counts(self): ... def history_date_time(self): """ Returns all timestamps of edges, when an edge is added or change to an edge is made. @@ -4742,9 +4930,7 @@ class Edges(object): def id(self): """Returns all ids of the edges.""" - def is_active(self): - ... - + def is_active(self): ... def is_deleted(self): """Check if the edges are deleted""" @@ -4822,27 +5008,13 @@ class Edges(object): Edges: The layered view """ - @property - def metadata(self): - """ - Returns all the metadata of the edges - - Returns: - MetadataView: - """ - @property def nbr(self): """Returns the node at the other end of the edge (same as `dst()` for out-edges and `src()` for in-edges)""" @property - def properties(self) -> PropertiesView: - """ - Returns all properties of the edges - - Returns: - PropertiesView: - """ + def properties(self): + """Returns all properties of the edges""" def rolling(self, window: int | str, step: int | str | None = None) -> WindowSet: """ @@ -4946,7 +5118,12 @@ class Edges(object): Time of edge """ - def to_df(self, include_property_history: bool = True, convert_datetime: bool = False, explode: bool = False) -> DataFrame: + def to_df( + self, + include_property_history: bool = True, + convert_datetime: bool = False, + explode: bool = False, + ) -> DataFrame: """ Converts the graph's edges into a Pandas DataFrame. @@ -4999,8 +5176,7 @@ class Edges(object): Optional[int]: """ -class NestedEdges(object): - +class NestedEdges(object): def __bool__(self): """True if self else False""" @@ -5195,9 +5371,7 @@ class NestedEdges(object): def id(self): """Returns all ids of the edges.""" - def is_active(self): - ... - + def is_active(self): ... def is_deleted(self): """Check if edges are deleted""" @@ -5255,10 +5429,6 @@ class NestedEdges(object): NestedEdges: The layered view """ - @property - def metadata(self): - """Get a view of the metadata only.""" - @property def nbr(self): """Returns the node at the other end of the edge (same as `dst()` for out-edges and `src()` for in-edges)""" @@ -5397,23 +5567,30 @@ class NestedEdges(object): Optional[int]: """ -class MutableEdge(Edge): - +class MutableEdge(Edge): def __repr__(self): """Return repr(self).""" - def add_metadata(self, metadata: PropInput, layer: Optional[str] = None): + def add_constant_properties( + self, properties: PropInput, layer: Optional[str] = None + ): """ - Add metadata to an edge in the graph. - This function is used to add properties to an edge that do not + Add constant properties to an edge in the graph. + This function is used to add properties to an edge that remain constant and do not change over time. These properties are fundamental attributes of the edge. Parameters: - metadata (PropInput): A dictionary of properties to be added to the edge. + properties (PropInput): A dictionary of properties to be added to the edge. layer (str, optional): The layer you want these properties to be added on to. """ - def add_updates(self, t: TimeInput, properties: Optional[PropInput] = None, layer: Optional[str] = None, secondary_index: Optional[int] = None) -> None: + def add_updates( + self, + t: TimeInput, + properties: Optional[PropInput] = None, + layer: Optional[str] = None, + secondary_index: Optional[int] = None, + ) -> None: """ Add updates to an edge in the graph at a specified time. This function allows for the addition of property updates to an edge within the graph. The updates are time-stamped, meaning they are applied at the specified time. @@ -5440,18 +5617,20 @@ class MutableEdge(Edge): layer (str, optional): The layer you want the deletion applied to . """ - def update_metadata(self, metadata: PropInput, layer: Optional[str] = None): + def update_constant_properties( + self, properties: PropInput, layer: Optional[str] = None + ): """ - Update metadata of an edge in the graph overwriting existing values. - This function is used to add properties to an edge that does not + Update constant properties of an edge in the graph overwriting existing values. + This function is used to add properties to an edge that remains constant and does not change over time. These properties are fundamental attributes of the edge. Parameters: - metadata (PropInput): A dictionary of properties to be added to the edge. + properties (PropInput): A dictionary of properties to be added to the edge. layer (str, optional): The layer you want these properties to be added on to. """ -class Properties(object): +class Properties(object): """A view of the properties of an entity""" def __contains__(self, key): @@ -5490,6 +5669,10 @@ class Properties(object): def as_dict(self): """Convert properties view to a dict""" + @property + def constant(self): + """Get a view of the constant properties (meta-data) only.""" + def get(self, key): """ Get property value. @@ -5509,10 +5692,15 @@ class Properties(object): """Get a view of the temporal properties only.""" def values(self): - """Get the values of the properties""" + """ + Get the values of the properties + + If a property exists as both temporal and static, temporal properties take priority with + fallback to the static property if the temporal value does not exist. + """ -class Metadata(object): - """A view of metadata of an entity""" +class ConstantProperties(object): + """A view of constant properties of an entity""" def __contains__(self, key): """Return bool(key in self).""" @@ -5592,7 +5780,7 @@ class Metadata(object): list | Array: the property values """ -class TemporalProperties(object): +class TemporalProperties(object): """A view of the temporal properties of an entity""" def __contains__(self, key): @@ -5628,12 +5816,14 @@ class TemporalProperties(object): def __repr__(self): """Return repr(self).""" - def get(self, key) -> TemporalProp: + def get(self, key): """ + get(key: str) -> Optional[TemporalProp] + Get property value for `key` if it exists Returns: - TemporalProp: the property view if it exists, otherwise `None` + the property view if it exists, otherwise `None` """ def histories(self) -> dict[str, list[Tuple[int, PropValue]]]: @@ -5658,12 +5848,12 @@ class TemporalProperties(object): def keys(self): """List the available property keys""" - def latest(self) -> dict[str, PropValue]: + def latest(self) -> dict[str, Any]: """ Get the latest value of all properties Returns: - dict[str, PropValue]: the mapping of property keys to latest values + dict[str, Any]: the mapping of property keys to latest values """ def values(self) -> list[TemporalProp]: @@ -5674,8 +5864,7 @@ class TemporalProperties(object): list[TemporalProp]: the list of property views """ -class PropertiesView(object): - +class PropertiesView(object): def __contains__(self, key): """Return bool(key in self).""" @@ -5709,23 +5898,37 @@ class PropertiesView(object): def as_dict(self): """Convert properties view to a dict""" + @property + def constant(self): + """Get a view of the constant properties (meta-data) only.""" + def get(self, key): - """Get property value.""" + """ + Get property value. + + First searches temporal properties and returns latest value if it exists. + If not, it falls back to constant properties. + """ def items(self): """Get a list of key-value pairs""" def keys(self): - """Get the names for all properties""" + """Get the names for all properties (includes temporal and constant properties)""" @property def temporal(self): """Get a view of the temporal properties only.""" def values(self): - """Get the values of the properties""" + """ + Get the values of the properties + + If a property exists as both temporal and constant, temporal properties take priority with + fallback to the constant property if the temporal value does not exist. + """ -class TemporalProp(object): +class TemporalProp(object): """A view of a temporal property""" def __eq__(self, value): @@ -5755,12 +5958,12 @@ class TemporalProp(object): def at(self, t): """Get the value of the property at time `t`""" - def average(self) -> PropValue: + def average(self) -> Prop: """ Compute the average of all property values. Alias for mean(). Returns: - PropValue: The average of each property values, or None if count is zero. + Prop: The average of each property values, or None if count is zero. """ def count(self) -> int: @@ -5783,135 +5986,143 @@ class TemporalProp(object): def items_date_time(self): """List update timestamps and corresponding property values""" - def max(self) -> Tuple[int, PropValue]: + def max(self): """ Find the maximum property value and its associated time. Returns: - Tuple[int, PropValue]: A tuple containing the time and the maximum property value. + (i64, Prop): A tuple containing the time and the maximum property value. """ - def mean(self) -> PropValue: + def mean(self) -> Prop: """ Compute the mean of all property values. Alias for mean(). Returns: - PropValue: The mean of each property values, or None if count is zero. + Prop: The mean of each property values, or None if count is zero. """ - def median(self) -> Tuple[int, PropValue]: + def median(self): """ Compute the median of all property values. Returns: - Tuple[int, PropValue]: A tuple containing the time and the median property value, or None if empty + (i64, Prop): A tuple containing the time and the median property value, or None if empty """ - def min(self) -> Tuple[int, PropValue]: + def min(self): """ Find the minimum property value and its associated time. Returns: - Tuple[int, PropValue]: A tuple containing the time and the minimum property value. + (i64, Prop): A tuple containing the time and the minimum property value. """ - def ordered_dedupe(self, latest_time): - """List of ordered deduplicated property values""" - - def sum(self) -> PropValue: + def ordered_dedupe(self, latest_time): ... + def sum(self) -> Prop: """ Compute the sum of all property values. Returns: - PropValue: The sum of all property values. + Prop: The sum of all property values. """ - def unique(self): - """List of unique property values""" - + def unique(self): ... def value(self): """Get the latest value of the property""" def values(self): """Get the property values for each update""" -class WindowSet(object): +class Prop(object): + """ + A reference to a property used for constructing filters - def __iter__(self): - """Implement iter(self).""" + Use `==`, `!=`, `<`, `<=`, `>`, `>=` to filter based on + property value (these filters always exclude entities that do not + have the property) or use one of the methods to construct + other kinds of filters. - def time_index(self, center: bool = False) -> Iterable: - """ - Returns the time index of this window set + Arguments: + name (str): the name of the property + """ - It uses the last time of each window as the reference or the center of each if `center` is - set to `True` + def __eq__(self, value): + """Return self==value.""" - Arguments: - center (bool): if True time indexes are centered. Defaults to False + def __ge__(self, value): + """Return self>=value.""" - Returns: - Iterable: the time index" - """ + def __gt__(self, value): + """Return self>value.""" -class IndexSpecBuilder(object): + def __le__(self, value): + """Return self<=value.""" - def __new__(cls, graph) -> IndexSpecBuilder: - """Create and return a new object. See help(type) for accurate signature.""" + def __lt__(self, value): + """Return self Prop: + """Create and return a new object. See help(type) for accurate signature.""" - def with_all_edge_properties(self): - ... + def any(self, values: set[PropValue]) -> PropertyFilter: + """ + Create a filter that keeps entities if their property value is in the set - def with_all_edge_properties_and_metadata(self): - ... + Arguments: + values (set[PropValue]): the set of values to match - def with_all_node_metadata(self): - ... + Returns: + PropertyFilter: the property filter + """ - def with_all_node_properties(self): - ... + def is_none(self) -> PropertyFilter: + """ + Create a filter that only keeps entities that do not have the property - def with_all_node_properties_and_metadata(self): - ... + Returns: + PropertyFilter: the property filter + """ - def with_edge_metadata(self, props): - ... + def is_some(self) -> PropertyFilter: + """ + Create a filter that only keeps entities if they have the property - def with_edge_properties(self, props): - ... + Returns: + PropertyFilter: the property filter + """ - def with_node_metadata(self, props): - ... + def not_any(self, values: set[PropValue]) -> PropertyFilter: + """ + Create a filter that keeps entities if their property value is not in the set or + if they don't have the property - def with_node_properties(self, props): - ... + Arguments: + values (set[PropValue]): the set of values to exclude -class IndexSpec(object): + Returns: + PropertyFilter: the property filter + """ - def __repr__(self): - """Return repr(self).""" +class PropertyFilter(object): ... - @property - def edge_metadata(self): - ... +class WindowSet(object): + def __iter__(self): + """Implement iter(self).""" - @property - def edge_properties(self): - ... + def time_index(self, center: bool = False) -> Iterable: + """ + Returns the time index of this window set - @property - def node_metadata(self): - ... + It uses the last time of each window as the reference or the center of each if `center` is + set to `True` - @property - def node_properties(self): - ... + Arguments: + center (bool): if True time indexes are centered. Defaults to False -def version(): - ... + Returns: + Iterable: the time index" + """ diff --git a/python/python/raphtory/algorithms/__init__.pyi b/python/python/raphtory/algorithms/__init__.pyi index ef2c8699ea..db5e4f97b9 100644 --- a/python/python/raphtory/algorithms/__init__.pyi +++ b/python/python/raphtory/algorithms/__init__.pyi @@ -1,6 +1,7 @@ """ Algorithmic functions that can be run on Raphtory graphs """ + from __future__ import annotations ############################################################################### @@ -25,8 +26,58 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['dijkstra_single_source_shortest_paths', 'global_reciprocity', 'betweenness_centrality', 'all_local_reciprocity', 'triplet_count', 'local_triangle_count', 'average_degree', 'directed_graph_density', 'degree_centrality', 'max_degree', 'min_degree', 'max_out_degree', 'max_in_degree', 'min_out_degree', 'min_in_degree', 'pagerank', 'single_source_shortest_path', 'global_clustering_coefficient', 'temporally_reachable_nodes', 'temporal_bipartite_graph_projection', 'local_clustering_coefficient', 'local_clustering_coefficient_batch', 'weakly_connected_components', 'strongly_connected_components', 'in_components', 'in_component', 'out_components', 'out_component', 'fast_rp', 'global_temporal_three_node_motif', 'global_temporal_three_node_motif_multi', 'local_temporal_three_node_motifs', 'hits', 'balance', 'label_propagation', 'k_core', 'temporal_SEIR', 'louvain', 'fruchterman_reingold', 'cohesive_fruchterman_reingold', 'max_weight_matching', 'Matching', 'Infected'] -def dijkstra_single_source_shortest_paths(graph: GraphView, source: NodeInput, targets: list[NodeInput], direction: Direction = "both", weight: str = 'weight') -> NodeStateWeightedSP: +__all__ = [ + "dijkstra_single_source_shortest_paths", + "global_reciprocity", + "betweenness_centrality", + "all_local_reciprocity", + "triplet_count", + "local_triangle_count", + "average_degree", + "directed_graph_density", + "degree_centrality", + "max_degree", + "min_degree", + "max_out_degree", + "max_in_degree", + "min_out_degree", + "min_in_degree", + "pagerank", + "single_source_shortest_path", + "global_clustering_coefficient", + "temporally_reachable_nodes", + "temporal_bipartite_graph_projection", + "local_clustering_coefficient", + "local_clustering_coefficient_batch", + "weakly_connected_components", + "strongly_connected_components", + "in_components", + "in_component", + "out_components", + "out_component", + "fast_rp", + "global_temporal_three_node_motif", + "global_temporal_three_node_motif_multi", + "local_temporal_three_node_motifs", + "hits", + "balance", + "label_propagation", + "temporal_SEIR", + "louvain", + "fruchterman_reingold", + "cohesive_fruchterman_reingold", + "max_weight_matching", + "Matching", + "Infected", +] + +def dijkstra_single_source_shortest_paths( + graph: GraphView, + source: NodeInput, + targets: list[NodeInput], + direction: Direction = "both", + weight: str = "weight", +) -> NodeStateWeightedSP: """ Finds the shortest paths from a single source to multiple targets in a graph. @@ -56,7 +107,9 @@ def global_reciprocity(graph: GraphView) -> float: float: reciprocity of the graph between 0 and 1. """ -def betweenness_centrality(graph: GraphView, k: Optional[int] = None, normalized: bool = True) -> NodeStateF64: +def betweenness_centrality( + graph: GraphView, k: Optional[int] = None, normalized: bool = True +) -> NodeStateF64: """ Computes the betweenness centrality for nodes in a given graph. @@ -224,7 +277,13 @@ def min_in_degree(graph: GraphView) -> int: int: value of the smallest indegree """ -def pagerank(graph: GraphView, iter_count: int = 20, max_diff: Optional[float] = None, use_l2_norm: bool = True, damping_factor: float = 0.85) -> NodeStateF64: +def pagerank( + graph: GraphView, + iter_count: int = 20, + max_diff: Optional[float] = None, + use_l2_norm: bool = True, + damping_factor: float = 0.85, +) -> NodeStateF64: """ Pagerank -- pagerank centrality value of the nodes in a graph @@ -245,7 +304,9 @@ def pagerank(graph: GraphView, iter_count: int = 20, max_diff: Optional[float] = NodeStateF64: Mapping of nodes to their pagerank value. """ -def single_source_shortest_path(graph: GraphView, source: NodeInput, cutoff: Optional[int] = None) -> NodeStateNodes: +def single_source_shortest_path( + graph: GraphView, source: NodeInput, cutoff: Optional[int] = None +) -> NodeStateNodes: """ Calculates the single source shortest paths from a given source node. @@ -276,7 +337,13 @@ def global_clustering_coefficient(graph: GraphView) -> float: [`Triplet Count`](triplet_count) """ -def temporally_reachable_nodes(graph: GraphView, max_hops: int, start_time: int, seed_nodes: list[NodeInput], stop_nodes: Optional[list[NodeInput]] = None) -> NodeStateReachability: +def temporally_reachable_nodes( + graph: GraphView, + max_hops: int, + 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. @@ -295,7 +362,9 @@ def temporally_reachable_nodes(graph: GraphView, max_hops: int, start_time: int, NodeStateReachability: Mapping of nodes to their reachability history. """ -def temporal_bipartite_graph_projection(graph: GraphView, delta: int, pivot_type: str) -> Graph: +def temporal_bipartite_graph_projection( + graph: GraphView, delta: int, pivot_type: str +) -> Graph: """ Projects a temporal bipartite graph into an undirected temporal graph over the pivot node type. Let `G` be a bipartite graph with node types `A` and `B`. Given `delta > 0`, the projection graph `G'` pivoting over type `B` nodes, 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`. @@ -323,10 +392,10 @@ def local_clustering_coefficient(graph: GraphView, v: NodeInput) -> float: float: the local clustering coefficient of node v in graph. """ -def local_clustering_coefficient_batch(graph, v): - ... - -def weakly_connected_components(graph: GraphView) -> NodeStateUsize: +def local_clustering_coefficient_batch(graph, v): ... +def weakly_connected_components( + graph: GraphView, iter_count: Optional[int] = None +) -> NodeStateUsize: """ Weakly connected components -- partitions the graph into node sets which are mutually reachable by an undirected path @@ -335,6 +404,7 @@ def weakly_connected_components(graph: GraphView) -> NodeStateUsize: Arguments: graph (GraphView): Raphtory graph + iter_count (int, optional): 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: NodeStateUsize: Mapping of nodes to their component ids. @@ -397,7 +467,14 @@ def out_component(node: Node) -> NodeStateUsize: NodeStateUsize: A NodeState mapping the nodes in the out-component to their distance from the starting node. """ -def fast_rp(graph: GraphView, embedding_dim: int, normalization_strength: float, iter_weights: list[float], seed: Optional[int] = None, threads: Optional[int] = None) -> NodeStateListF64: +def fast_rp( + graph: GraphView, + embedding_dim: int, + normalization_strength: float, + iter_weights: list[float], + seed: Optional[int] = None, + threads: Optional[int] = None, +) -> 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 @@ -413,7 +490,9 @@ def fast_rp(graph: GraphView, embedding_dim: int, normalization_strength: float, NodeStateListF64: Mapping from nodes to embedding vectors. """ -def global_temporal_three_node_motif(graph: GraphView, delta: int, threads: Optional[int] = None) -> list[int]: +def global_temporal_three_node_motif( + graph: GraphView, delta: int, threads: Optional[int] = None +) -> list[int]: """ 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. @@ -462,7 +541,9 @@ def global_temporal_three_node_motif(graph: GraphView, delta: int, threads: Opti """ -def global_temporal_three_node_motif_multi(graph: GraphView, deltas: list[int], threads: Optional[int] = None) -> list[list[int]]: +def global_temporal_three_node_motif_multi( + graph: GraphView, deltas: list[int], threads: Optional[int] = 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. @@ -475,7 +556,9 @@ def global_temporal_three_node_motif_multi(graph: GraphView, deltas: list[int], 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) -> NodeStateMotifs: +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. @@ -491,7 +574,9 @@ def local_temporal_three_node_motifs(graph: GraphView, delta: int, threads=None) the motif. For two node motifs, both constituent nodes count the motif. For triangles, all three constituent nodes count the motif. """ -def hits(graph: GraphView, iter_count: int = 20, threads: Optional[int] = None) -> NodeStateHits: +def hits( + graph: GraphView, iter_count: int = 20, threads: Optional[int] = None +) -> NodeStateHits: """ HITS (Hubs and Authority) Algorithm: @@ -510,7 +595,9 @@ def hits(graph: GraphView, iter_count: int = 20, threads: Optional[int] = None) NodeStateHits: A mapping from nodes their hub and authority scores """ -def balance(graph: GraphView, name: str = "weight", direction: Direction = "both") -> NodeStateF64: +def balance( + graph: GraphView, name: str = "weight", direction: Direction = "both" +) -> NodeStateF64: """ Sums the weights of edges in the graph based on the specified direction. @@ -529,7 +616,9 @@ def balance(graph: GraphView, name: str = "weight", direction: Direction = "both """ -def label_propagation(graph: GraphView, seed: Optional[bytes] = None) -> list[set[Node]]: +def label_propagation( + graph: GraphView, seed: Optional[bytes] = None +) -> list[set[Node]]: """ Computes components using a label propagation algorithm @@ -542,22 +631,15 @@ def label_propagation(graph: GraphView, seed: Optional[bytes] = None) -> list[se """ -def k_core(graph: GraphView, k: int, iter_count: int, threads: Optional[int] = None) -> list[Node]: - """ - Determines which nodes are in the k-core for a given value of k - - Arguments: - graph (GraphView): A reference to the graph - k (int): Value of k such that the returned nodes have degree > k (recursively) - iter_count (int): The number of iterations to run - threads (int, optional): number of threads to run on - - Returns: - list[Node]: A list of nodes in the k core - - """ - -def temporal_SEIR(graph: GraphView, seeds: int | float | list[NodeInput], infection_prob: float, initial_infection: int | str | datetime, recovery_rate: float | None = None, incubation_rate: float | None = None, rng_seed: int | None = None) -> NodeStateSEIR: +def temporal_SEIR( + graph: GraphView, + seeds: int | float | list[NodeInput], + infection_prob: float, + initial_infection: int | str | datetime, + recovery_rate: float | None = None, + incubation_rate: float | None = None, + rng_seed: int | None = None, +) -> NodeStateSEIR: """ Simulate an SEIR dynamic on the network @@ -587,7 +669,12 @@ def temporal_SEIR(graph: GraphView, seeds: int | float | list[NodeInput], infect """ -def louvain(graph: GraphView, resolution: float = 1.0, weight_prop: str | None = None, tol: None | float = None) -> NodeStateUsize: +def louvain( + graph: GraphView, + resolution: float = 1.0, + weight_prop: str | None = None, + tol: None | float = None, +) -> NodeStateUsize: """ Louvain algorithm for community detection @@ -601,7 +688,14 @@ def louvain(graph: GraphView, resolution: float = 1.0, weight_prop: str | None = NodeStateUsize: Mapping of nodes to their community assignment """ -def fruchterman_reingold(graph: GraphView, iterations: int | None = 100, scale: float | None = 1.0, node_start_size: float | None = 1.0, cooloff_factor: float | None = 0.95, dt: float | None = 0.1) -> NodeLayout: +def fruchterman_reingold( + graph: GraphView, + iterations: int | None = 100, + scale: float | None = 1.0, + node_start_size: float | None = 1.0, + cooloff_factor: float | None = 0.95, + dt: float | None = 0.1, +) -> NodeLayout: """ Fruchterman Reingold layout algorithm @@ -617,7 +711,14 @@ def fruchterman_reingold(graph: GraphView, iterations: int | None = 100, scale: NodeLayout: A mapping from nodes to their [x, y] positions """ -def cohesive_fruchterman_reingold(graph: GraphView, iter_count: int = 100, scale: float = 1.0, node_start_size: float = 1.0, cooloff_factor: float = 0.95, dt: float = 0.1) -> NodeLayout: +def cohesive_fruchterman_reingold( + graph: GraphView, + iter_count: int = 100, + scale: float = 1.0, + node_start_size: float = 1.0, + cooloff_factor: float = 0.95, + dt: float = 0.1, +) -> NodeLayout: """ Cohesive version of `fruchterman_reingold` that adds virtual edges between isolated nodes Arguments: @@ -633,7 +734,12 @@ def cohesive_fruchterman_reingold(graph: GraphView, iter_count: int = 100, scale """ -def max_weight_matching(graph: GraphView, weight_prop: Optional[str] = None, max_cardinality: bool = True, verify_optimum_flag: bool = False) -> Matching: +def max_weight_matching( + graph: GraphView, + weight_prop: Optional[str] = None, + max_cardinality: bool = True, + verify_optimum_flag: bool = False, +) -> Matching: """ Compute a maximum-weighted matching in the general undirected weighted graph given by "edges". If `max_cardinality` is true, only @@ -670,7 +776,7 @@ def max_weight_matching(graph: GraphView, weight_prop: Optional[str] = None, max Matching: The matching """ -class Matching(object): +class Matching(object): """A Matching (i.e., a set of edges that do not share any nodes)""" def __bool__(self): @@ -742,8 +848,7 @@ class Matching(object): """ -class Infected(object): - +class Infected(object): def __repr__(self): """Return repr(self).""" diff --git a/python/python/raphtory/filter/__init__.pyi b/python/python/raphtory/filter/__init__.pyi index 29d21e5b19..c2e954e827 100644 --- a/python/python/raphtory/filter/__init__.pyi +++ b/python/python/raphtory/filter/__init__.pyi @@ -22,9 +22,20 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['FilterExpr', 'PropertyFilterOps', 'NodeFilterBuilder', 'Node', 'EdgeFilterOp', 'EdgeEndpoint', 'Edge', 'Property', 'Metadata', 'TemporalPropertyFilterBuilder'] -class FilterExpr(object): - +__all__ = [ + "FilterExpr", + "PropertyFilterOps", + "NodeFilterBuilder", + "Node", + "EdgeFilterOp", + "EdgeEndpoint", + "Edge", + "Property", + "Metadata", + "TemporalPropertyFilterBuilder", +] + +class FilterExpr(object): def __and__(self, value): """Return self&value.""" @@ -40,8 +51,7 @@ class FilterExpr(object): def __ror__(self, value): """Return value|self.""" -class PropertyFilterOps(object): - +class PropertyFilterOps(object): def __eq__(self, value): """Return self==value.""" @@ -60,28 +70,15 @@ class PropertyFilterOps(object): def __ne__(self, value): """Return self!=value.""" - def contains(self, value): - ... - - def fuzzy_search(self, prop_value, levenshtein_distance, prefix_match): - ... - - def is_in(self, values): - ... - - def is_none(self): - ... - - def is_not_in(self, values): - ... + def contains(self, value): ... + def fuzzy_search(self, prop_value, levenshtein_distance, prefix_match): ... + def is_in(self, values): ... + def is_none(self): ... + def is_not_in(self, values): ... + def is_some(self): ... + def not_contains(self, value): ... - def is_some(self): - ... - - def not_contains(self, value): - ... - -class NodeFilterBuilder(object): +class NodeFilterBuilder(object): """ A builder for constructing node filters @@ -106,23 +103,13 @@ class NodeFilterBuilder(object): def __ne__(self, value): """Return self!=value.""" - def contains(self, value): - ... - - def fuzzy_search(self, value, levenshtein_distance, prefix_match): - ... - - def is_in(self, values): - ... - - def is_not_in(self, values): - ... - - def not_contains(self, value): - ... - -class Node(object): + def contains(self, value): ... + def fuzzy_search(self, value, levenshtein_distance, prefix_match): ... + def is_in(self, values): ... + def is_not_in(self, values): ... + def not_contains(self, value): ... +class Node(object): @staticmethod def name(): """ @@ -141,8 +128,7 @@ class Node(object): NodeFilterBuilder: A filter builder for filtering by node type """ -class EdgeFilterOp(object): - +class EdgeFilterOp(object): def __eq__(self, value): """Return self==value.""" @@ -161,37 +147,22 @@ class EdgeFilterOp(object): def __ne__(self, value): """Return self!=value.""" - def contains(self, value): - ... - - def fuzzy_search(self, value, levenshtein_distance, prefix_match): - ... - - def is_in(self, values): - ... - - def is_not_in(self, values): - ... - - def not_contains(self, value): - ... + def contains(self, value): ... + def fuzzy_search(self, value, levenshtein_distance, prefix_match): ... + def is_in(self, values): ... + def is_not_in(self, values): ... + def not_contains(self, value): ... -class EdgeEndpoint(object): - - def name(self): - ... - -class Edge(object): +class EdgeEndpoint(object): + def name(self): ... +class Edge(object): @staticmethod - def dst(): - ... - + def dst(): ... @staticmethod - def src(): - ... + def src(): ... -class Property(PropertyFilterOps): +class Property(PropertyFilterOps): """ Construct a property filter @@ -202,10 +173,9 @@ class Property(PropertyFilterOps): def __new__(cls, name: str) -> Property: """Create and return a new object. See help(type) for accurate signature.""" - def temporal(self): - ... + def temporal(self): ... -class Metadata(PropertyFilterOps): +class Metadata(PropertyFilterOps): """ Construct a metadata filter @@ -216,10 +186,6 @@ class Metadata(PropertyFilterOps): def __new__(cls, name: str) -> Metadata: """Create and return a new object. See help(type) for accurate signature.""" -class TemporalPropertyFilterBuilder(object): - - def any(self): - ... - - def latest(self): - ... +class TemporalPropertyFilterBuilder(object): + def any(self): ... + def latest(self): ... diff --git a/python/python/raphtory/graph_gen/__init__.pyi b/python/python/raphtory/graph_gen/__init__.pyi index 777d89e750..ee2c620e70 100644 --- a/python/python/raphtory/graph_gen/__init__.pyi +++ b/python/python/raphtory/graph_gen/__init__.pyi @@ -1,6 +1,7 @@ """ Generate Raphtory graphs from attachment models """ + from __future__ import annotations ############################################################################### @@ -26,7 +27,8 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['random_attachment', 'ba_preferential_attachment'] +__all__ = ["random_attachment", "ba_preferential_attachment"] + def random_attachment(g: Any, nodes_to_add: Any, edges_per_step: Any, seed: Any = None): """ Generates a graph using the random attachment model @@ -45,7 +47,9 @@ def random_attachment(g: Any, nodes_to_add: Any, edges_per_step: Any, seed: Any None """ -def ba_preferential_attachment(g: Any, nodes_to_add: Any, edges_per_step: Any, seed: Any = None): +def ba_preferential_attachment( + g: Any, nodes_to_add: Any, edges_per_step: Any, seed: Any = None +): """ Generates a graph using the preferential attachment model. diff --git a/python/python/raphtory/graph_loader/__init__.pyi b/python/python/raphtory/graph_loader/__init__.pyi index b3ca911330..b5fb056bbf 100644 --- a/python/python/raphtory/graph_loader/__init__.pyi +++ b/python/python/raphtory/graph_loader/__init__.pyi @@ -1,6 +1,7 @@ """ Load and save Raphtory graphs from/to file(s) """ + from __future__ import annotations ############################################################################### @@ -26,8 +27,17 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['lotr_graph', 'lotr_graph_with_props', 'neo4j_movie_graph', 'stable_coin_graph', 'reddit_hyperlink_graph', 'reddit_hyperlink_graph_local', 'karate_club_graph'] -def lotr_graph() -> Graph: +__all__ = [ + "lotr_graph", + "lotr_graph_with_props", + "neo4j_movie_graph", + "stable_coin_graph", + "reddit_hyperlink_graph", + "reddit_hyperlink_graph_local", + "karate_club_graph", +] + +def lotr_graph(): """ Load the Lord of the Rings dataset into a graph. The dataset is available at https://raw.githubusercontent.com/Raphtory/Data/main/lotr.csv @@ -43,20 +53,19 @@ def lotr_graph() -> Graph: * Number of edges (hyperlink between subreddits) 701 + Arguments: + shards: The number of shards to use for the graph + Returns: - Graph: A Graph containing the LOTR dataset + A Graph containing the LOTR dataset """ def lotr_graph_with_props(): """Same as `lotr_graph()` but with additional properties race and gender for some of the nodes""" -def neo4j_movie_graph(uri, username, password, database=...): - ... - -def stable_coin_graph(path=None, subset=None): - ... - -def reddit_hyperlink_graph(timeout_seconds: int = 600) -> Graph: +def neo4j_movie_graph(uri, username, password, database=...): ... +def stable_coin_graph(path=None, subset=None): ... +def reddit_hyperlink_graph(timeout_seconds: Any = 600) -> Graph: """ Load (a subset of) Reddit hyperlinks dataset into a graph. The dataset is available at http://snap.stanford.edu/data/soc-redditHyperlinks-title.tsv @@ -79,7 +88,7 @@ def reddit_hyperlink_graph(timeout_seconds: int = 600) -> Graph: * SOURCE_SUBREDDIT: the subreddit where the link originates * TARGET_SUBREDDIT: the subreddit where the link ends * POST_ID: the post in the source subreddit that starts the link - * TIMESTAMP: time of the post + * TIMESTAMP: time time of the post * POST_LABEL: label indicating if the source post is explicitly negative towards the target post. The value is -1 if the source is negative towards the target, and 1 if it is neutral or positive. The label is created using crowd-sourcing and training a text based classifier, and @@ -88,15 +97,14 @@ def reddit_hyperlink_graph(timeout_seconds: int = 600) -> Graph: list of comma separated numbers. This can be found on the source website Arguments: - timeout_seconds (int): The number of seconds to wait for the dataset to download. Defaults to 600. + shards: The number of shards to use for the graph + timeout_seconds: The number of seconds to wait for the dataset to download Returns: Graph: A Graph containing the Reddit hyperlinks dataset """ -def reddit_hyperlink_graph_local(file_path): - ... - +def reddit_hyperlink_graph_local(file_path): ... def karate_club_graph(): """ `karate_club_graph` constructs a karate club graph. diff --git a/python/python/raphtory/graphql/__init__.pyi b/python/python/raphtory/graphql/__init__.pyi index cd1c34a06a..a7bb00cf72 100644 --- a/python/python/raphtory/graphql/__init__.pyi +++ b/python/python/raphtory/graphql/__init__.pyi @@ -22,8 +22,68 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['GraphServer', 'RunningGraphServer', 'RaphtoryClient', 'RemoteGraph', 'RemoteEdge', 'RemoteNode', 'RemoteNodeAddition', 'RemoteUpdate', 'RemoteEdgeAddition', 'RemoteIndexSpec', 'PropsInput', 'SomePropertySpec', 'AllPropertySpec', 'encode_graph', 'decode_graph', 'schema'] -class GraphServer(object): +__all__ = [ + "GraphqlGraphs", + "GraphServer", + "RunningGraphServer", + "RaphtoryClient", + "RemoteGraph", + "RemoteEdge", + "RemoteNode", + "RemoteNodeAddition", + "RemoteUpdate", + "RemoteEdgeAddition", + "encode_graph", + "decode_graph", +] + +class GraphqlGraphs(object): + """ + A class for accessing graphs hosted in a Raphtory GraphQL server and running global search for + graph documents + """ + + def get(self, name: str) -> Optional[VectorisedGraph]: + """ + Return the `VectorisedGraph` with name `name` or `None` if it doesn't exist + + Arguments: + name (str): the name of the graph + Returns: + Optional[VectorisedGraph]: the graph if it exists + """ + + def search_graph_documents( + self, query: str, limit: int, window: Optional[Tuple[TimeInput, TimeInput]] + ) -> list[Document]: + """ + Return the top documents with the smallest cosine distance to `query` + + Arguments: + query (str): the text or the embedding to score against + limit (int): the maximum number of documents to return + window (Tuple[TimeInput, TimeInput], optional): the window where documents need to belong to in order to be considered + + Returns: + list[Document]: A list of documents + """ + + def search_graph_documents_with_scores( + self, query: str, limit: int, window: Optional[Tuple[TimeInput, TimeInput]] + ) -> list[Tuple[Document, float]]: + """ + Same as `search_graph_documents` but it also returns the scores alongside the documents + + Arguments: + query (str): the text or the embedding to score against + limit (int): the maximum number of documents to return + window (Tuple[TimeInput, TimeInput], optional): the window where documents need to belong to in order to be considered + + Returns: + list[Tuple[Document, float]]: A list of documents and their scores + """ + +class GraphServer(object): """ A class for defining and running a Raphtory GraphQL server @@ -39,7 +99,20 @@ class GraphServer(object): config_path (str | PathLike, optional): Path to the config file """ - def __new__(cls, work_dir: str | PathLike, cache_capacity: Optional[int] = None, cache_tti_seconds: Optional[int] = None, log_level: Optional[str] = None, tracing: Optional[bool] = None, otlp_agent_host: Optional[str] = None, otlp_agent_port: Optional[str] = None, otlp_tracing_service_name: Optional[str] = None, auth_public_key=None, auth_enabled_for_reads=None, config_path: Optional[str | PathLike] = None, create_index=None) -> GraphServer: + def __new__( + cls, + work_dir: str | PathLike, + cache_capacity: Optional[int] = None, + cache_tti_seconds: Optional[int] = None, + log_level: Optional[str] = None, + tracing: Optional[bool] = None, + otlp_agent_host: Optional[str] = None, + otlp_agent_port: Optional[str] = None, + otlp_tracing_service_name: Optional[str] = None, + auth_public_key=None, + auth_enabled_for_reads=None, + config_path: Optional[str | PathLike] = None, + ) -> GraphServer: """Create and return a new object. See help(type) for accurate signature.""" def run(self, port: int = 1736, timeout_ms: int = 180000) -> None: @@ -54,13 +127,21 @@ class GraphServer(object): None: """ - def set_embeddings(self, cache: str, embedding: Optional[Callable] = None, nodes: bool | str = True, edges: bool | str = True) -> GraphServer: + def set_embeddings( + self, + cache: str, + embedding: Optional[Callable] = None, + graphs: bool | str = True, + nodes: bool | str = True, + edges: bool | str = True, + ) -> GraphServer: """ Setup the server to vectorise graphs with a default template. Arguments: cache (str): the directory to use as cache for the embeddings. embedding (Callable, optional): the embedding function to translate documents to embeddings. + graphs (bool | str): if graphs have to be embedded or not or the custom template to use if a str is provided. Defaults to True. nodes (bool | str): if nodes have to be embedded or not or the custom template to use if a str is provided. Defaults to True. edges (bool | str): if edges have to be embedded or not or the custom template to use if a str is provided. Defaults to True. @@ -89,12 +170,39 @@ class GraphServer(object): GraphServer: The server with indexing disabled """ - def with_vectorised_graphs(self, graph_names: list[str], nodes: bool | str = True, edges: bool | str = True) -> GraphServer: + def with_global_search_function( + self, name: str, input: dict[str, str], function: Callable + ) -> GraphServer: + """ + Register a function in the GraphQL schema for document search among all the graphs. + + The function needs to take a `GraphqlGraphs` object as the first argument followed by a + pre-defined set of keyword arguments. Supported types are `str`, `int`, and `float`. + They have to be specified using the `input` parameter as a dict where the keys are the + names of the parameters and the values are the types, expressed as strings. + + Arguments: + name (str): the name of the function in the GraphQL schema. + input (dict[str, str]): the keyword arguments expected by the function. + function (Callable): the function to run. + + Returns: + GraphServer: A new server object with the function registered + """ + + def with_vectorised_graphs( + self, + graph_names: list[str], + graphs: bool | str = True, + nodes: bool | str = True, + edges: bool | str = True, + ) -> GraphServer: """ Vectorise a subset of the graphs of the server. Arguments: graph_names (list[str]): the names of the graphs to vectorise. All by default. + graphs (bool | str): if graphs have to be embedded or not or the custom template to use if a str is provided. Defaults to True. nodes (bool | str): if nodes have to be embedded or not or the custom template to use if a str is provided. Defaults to True. edges (bool | str): if edges have to be embedded or not or the custom template to use if a str is provided. Defaults to True. @@ -102,15 +210,11 @@ class GraphServer(object): GraphServer: A new server object containing the vectorised graphs. """ -class RunningGraphServer(object): +class RunningGraphServer(object): """A Raphtory server handler that also enables querying the server""" - def __enter__(self): - ... - - def __exit__(self, _exc_type, _exc_val, _exc_tb): - ... - + def __enter__(self): ... + def __exit__(self, _exc_type, _exc_val, _exc_tb): ... def get_client(self) -> RaphtoryClient: """ Get the client for the server @@ -127,7 +231,7 @@ class RunningGraphServer(object): None: """ -class RaphtoryClient(object): +class RaphtoryClient(object): """ A client for handling GraphQL operations in the context of Raphtory. @@ -140,7 +244,7 @@ class RaphtoryClient(object): def copy_graph(self, path: str, new_path: str) -> None: """ - Copy graph from a path path on the server to a new_path on the server + Copy graph from a path `path` on the server to a `new_path` on the server Arguments: path (str): the path of the graph to be copied @@ -150,23 +254,9 @@ class RaphtoryClient(object): None: """ - def create_index(self, path: str, index_spec: RemoteIndexSpec, in_ram: bool = True) -> None: - """ - Create Index for graph on the server at 'path' - - Arguments: - path (str): the path of the graph to be created - index_spec (RemoteIndexSpec): spec specifying the properties that need to be indexed - in_ram (bool): create index in ram - - Returns: - None: - - """ - def delete_graph(self, path: str) -> None: """ - Delete graph from a path path on the server + Delete graph from a path `path` on the server Arguments: path (str): the path of the graph to be deleted @@ -185,7 +275,7 @@ class RaphtoryClient(object): def move_graph(self, path: str, new_path: str) -> None: """ - Move graph from a path path on the server to a new_path on the server + Move graph from a path `path` on the server to a `new_path` on the server Arguments: path (str): the path of the graph to be moved @@ -197,7 +287,7 @@ class RaphtoryClient(object): def new_graph(self, path: str, graph_type: Literal["EVENT", "PERSISTENT"]) -> None: """ - Create a new empty Graph on the server at path + Create a new empty Graph on the server at `path` Arguments: path (str): the path of the graph to be created @@ -208,7 +298,9 @@ class RaphtoryClient(object): """ - def query(self, query: str, variables: Optional[dict[str, Any]] = None) -> dict[str, Any]: + def query( + self, query: str, variables: Optional[dict[str, Any]] = None + ) -> dict[str, Any]: """ Make a GraphQL query against the server. @@ -217,12 +309,12 @@ class RaphtoryClient(object): variables (dict[str, Any], optional): a dict of variables present on the query and their values. Returns: - dict[str, Any]: The data field from the graphQL response. + dict[str, Any]: The `data` field from the graphQL response. """ def receive_graph(self, path: str) -> Union[Graph, PersistentGraph]: """ - Receive graph from a path path on the server + Receive graph from a path `path` on the server Note: This downloads a copy of the graph. Modifications are not persistet to the server. @@ -236,7 +328,7 @@ class RaphtoryClient(object): def remote_graph(self, path: str) -> RemoteGraph: """ - Get a RemoteGraph reference to a graph on the server at path + Get a RemoteGraph reference to a graph on the server at `path` Arguments: path (str): the path of the graph to be created @@ -246,7 +338,9 @@ class RaphtoryClient(object): """ - def send_graph(self, path: str, graph: Graph | PersistentGraph, overwrite: bool = False) -> dict[str, Any]: + def send_graph( + self, path: str, graph: Graph | PersistentGraph, overwrite: bool = False + ) -> dict[str, Any]: """ Send a graph to the server @@ -256,12 +350,14 @@ class RaphtoryClient(object): overwrite (bool): overwrite existing graph. Defaults to False. Returns: - dict[str, Any]: The data field from the graphQL response after executing the mutation. + dict[str, Any]: The `data` field from the graphQL response after executing the mutation. """ - def upload_graph(self, path: str, file_path: str, overwrite: bool = False) -> dict[str, Any]: + def upload_graph( + self, path: str, file_path: str, overwrite: bool = False + ) -> dict[str, Any]: """ - Upload graph file from a path file_path on the client + Upload graph file from a path `file_path` on the client Arguments: path (str): the name of the graph @@ -269,12 +365,29 @@ class RaphtoryClient(object): overwrite (bool): overwrite existing graph. Defaults to False. Returns: - dict[str, Any]: The data field from the graphQL response after executing the mutation. + dict[str, Any]: The `data` field from the graphQL response after executing the mutation. """ -class RemoteGraph(object): +class RemoteGraph(object): + def add_constant_properties(self, properties: dict) -> None: + """ + Adds constant properties to the remote graph. + + Arguments: + properties (dict): The constant properties of the graph. - def add_edge(self, timestamp: int | str | datetime, src: str | int, dst: str | int, properties: Optional[dict] = None, layer: Optional[str] = None) -> RemoteEdge: + Returns: + None: + """ + + def add_edge( + self, + timestamp: int | str | datetime, + src: str | int, + dst: str | int, + properties: Optional[dict] = None, + layer: Optional[str] = None, + ) -> RemoteEdge: """ Adds a new edge with the given source and destination nodes and properties to the remote graph. @@ -300,18 +413,13 @@ class RemoteGraph(object): None: """ - def add_metadata(self, properties: dict) -> None: - """ - Adds metadata to the remote graph. - - Arguments: - properties (dict): The metadata of the graph. - - Returns: - None: - """ - - def add_node(self, timestamp: int | str | datetime, id: str | int, properties: Optional[dict] = None, node_type: Optional[str] = None) -> RemoteNode: + def add_node( + self, + timestamp: int | str | datetime, + id: str | int, + properties: Optional[dict] = None, + node_type: Optional[str] = None, + ) -> RemoteNode: """ Adds a new node with the given id and properties to the remote graph. @@ -347,7 +455,13 @@ class RemoteGraph(object): None: """ - def create_node(self, timestamp: int | str | datetime, id: str | int, properties: Optional[dict] = None, node_type: Optional[str] = None) -> RemoteNode: + def create_node( + self, + timestamp: int | str | datetime, + id: str | int, + properties: Optional[dict] = None, + node_type: Optional[str] = None, + ) -> RemoteNode: """ Create a new node with the given id and properties to the remote graph and fail if the node already exists. @@ -360,7 +474,13 @@ class RemoteGraph(object): RemoteNode: the new remote node """ - def delete_edge(self, timestamp: int, src: str | int, dst: str | int, layer: Optional[str] = None) -> RemoteEdge: + def delete_edge( + self, + timestamp: int, + src: str | int, + dst: str | int, + layer: Optional[str] = None, + ) -> RemoteEdge: """ Deletes an edge in the remote graph, given the timestamp, src and dst nodes and layer (optional) @@ -397,41 +517,46 @@ class RemoteGraph(object): RemoteNode: the remote node reference """ - def update_metadata(self, properties: dict) -> None: + def update_constant_properties(self, properties: dict) -> None: """ - Updates metadata on the remote graph. + Updates constant properties on the remote graph. Arguments: - properties (dict): The metadata of the graph. + properties (dict): The constant properties of the graph. Returns: None: """ -class RemoteEdge(object): +class RemoteEdge(object): """ A remote edge reference - Returned by [RemoteGraph.edge][raphtory.graphql.RemoteGraph.edge], - [RemoteGraph.add_edge][raphtory.graphql.RemoteGraph.add_edge], - and [RemoteGraph.delete_edge][raphtory.graphql.RemoteGraph.delete_edge]. + Returned by :meth:`RemoteGraph.edge`, :meth:`RemoteGraph.add_edge`, and :meth:`RemoteGraph.delete_edge`. """ - def add_metadata(self, properties: dict[str, PropValue], layer: Optional[str] = None) -> None: + def add_constant_properties( + self, properties: Dict[str, Prop], layer: Optional[str] = None + ) -> None: """ - Add metadata to the edge within the remote graph. - This function is used to add metadata to an edge that does not - change over time. This metadata is fundamental information of the edge. + Add constant properties to the edge within the remote graph. + This function is used to add properties to an edge that remain constant and do not + change over time. These properties are fundamental attributes of the edge. Parameters: - properties (dict[str, PropValue]): A dictionary of properties to be added to the edge. + properties (Dict[str, Prop]): A dictionary of properties to be added to the edge. layer (str, optional): The layer you want these properties to be added on to. Returns: None: """ - def add_updates(self, t: int | str | datetime, properties: Optional[dict[str, PropValue]] = None, layer: Optional[str] = None) -> None: + def add_updates( + self, + t: int | str | datetime, + properties: Optional[Dict[str, Prop]] = None, + layer: Optional[str] = None, + ) -> None: """ Add updates to an edge in the remote graph at a specified time. @@ -440,7 +565,7 @@ class RemoteEdge(object): Parameters: t (int | str | datetime): The timestamp at which the updates should be applied. - properties (dict[str, PropValue], optional): A dictionary of properties to update. + properties (Optional[Dict[str, Prop]]): A dictionary of properties to update. layer (str, optional): The layer you want the updates to be applied. Returns: @@ -459,43 +584,46 @@ class RemoteEdge(object): None: """ - def update_metadata(self, properties: dict[str, PropValue], layer: Optional[str] = None) -> None: + def update_constant_properties( + self, properties: Dict[str, Prop], layer: Optional[str] = None + ) -> None: """ - Update metadata of an edge in the remote graph overwriting existing values. - This function is used to add properties to an edge that does not + Update constant properties of an edge in the remote graph overwriting existing values. + This function is used to add properties to an edge that remains constant and does not change over time. These properties are fundamental attributes of the edge. Parameters: - properties (dict[str, PropValue]): A dictionary of properties to be added to the edge. + properties (Dict[str, Prop]): A dictionary of properties to be added to the edge. layer (str, optional): The layer you want these properties to be added on to. Returns: None: """ -class RemoteNode(object): - - def add_metadata(self, properties: dict[str, PropValue]) -> None: +class RemoteNode(object): + def add_constant_properties(self, properties: Dict[str, Prop]) -> None: """ - Add metadata to a node in the remote graph. - This function is used to add properties to a node that do not + Add constant properties to a node in the remote graph. + This function is used to add properties to a node that remain constant and does not change over time. These properties are fundamental attributes of the node. Parameters: - properties (dict[str, PropValue]): A dictionary of properties to be added to the node. + properties (Dict[str, Prop]): A dictionary of properties to be added to the node. Returns: None: """ - def add_updates(self, t: int | str | datetime, properties: Optional[dict[str, PropValue]] = None) -> None: + def add_updates( + self, t: int | str | datetime, properties: Optional[Dict[str, Prop]] = None + ) -> None: """ Add updates to a node in the remote graph at a specified time. This function allows for the addition of property updates to a node within the graph. The updates are time-stamped, meaning they are applied at the specified time. Parameters: t (int | str | datetime): The timestamp at which the updates should be applied. - properties (dict[str, PropValue], optional): A dictionary of properties to update. + properties (Dict[str, Prop], optional): A dictionary of properties to update. Returns: None: @@ -513,34 +641,40 @@ class RemoteNode(object): None: """ - def update_metadata(self, properties: dict[str, PropValue]) -> None: + def update_constant_properties(self, properties: Dict[str, Prop]) -> None: """ - Update metadata of a node in the remote graph overwriting existing values. - This function is used to add properties to a node that does not + Update constant properties of a node in the remote graph overwriting existing values. + This function is used to add properties to a node that remain constant and do not change over time. These properties are fundamental attributes of the node. Parameters: - properties (dict[str, PropValue]): A dictionary of properties to be added to the node. + properties (Dict[str, Prop]): A dictionary of properties to be added to the node. Returns: None: """ -class RemoteNodeAddition(object): +class RemoteNodeAddition(object): """ Node addition update Arguments: name (GID): the id of the node node_type (str, optional): the node type - metadata (PropInput, optional): the metadata - updates (list[RemoteUpdate], optional): the temporal updates + constant_properties (PropInput, optional): the constant properties + updates: (list[RemoteUpdate], optional): the temporal updates """ - def __new__(cls, name: GID, node_type: Optional[str] = None, metadata: Optional[PropInput] = None, updates: Optional[list[RemoteUpdate]] = None) -> RemoteNodeAddition: + def __new__( + cls, + name: GID, + node_type: Optional[str] = None, + constant_properties: Optional[PropInput] = None, + updates: Any = None, + ) -> RemoteNodeAddition: """Create and return a new object. See help(type) for accurate signature.""" -class RemoteUpdate(object): +class RemoteUpdate(object): """ A temporal update @@ -549,10 +683,12 @@ class RemoteUpdate(object): properties (PropInput, optional): the properties for the update """ - def __new__(cls, time: TimeInput, properties: Optional[PropInput] = None) -> RemoteUpdate: + def __new__( + cls, time: TimeInput, properties: Optional[PropInput] = None + ) -> RemoteUpdate: """Create and return a new object. See help(type) for accurate signature.""" -class RemoteEdgeAddition(object): +class RemoteEdgeAddition(object): """ An edge update @@ -560,82 +696,20 @@ class RemoteEdgeAddition(object): src (GID): the id of the source node dst (GID): the id of the destination node layer (str, optional): the layer for the update - metadata (PropInput, optional): the metadata for the edge + constant_properties (PropInput, optional): the constant properties for the edge updates (list[RemoteUpdate], optional): the temporal updates for the edge """ - def __new__(cls, src: GID, dst: GID, layer: Optional[str] = None, metadata: Optional[PropInput] = None, updates: Optional[list[RemoteUpdate]] = None) -> RemoteEdgeAddition: - """Create and return a new object. See help(type) for accurate signature.""" - -class RemoteIndexSpec(object): - """ - Create a RemoteIndexSpec specifying which node and edge properties to index. - - Arguments: - node_props (PropsInput): Property spec for nodes. - edge_props (PropsInput): Property spec for edges. - """ - - def __new__(cls, node_props: PropsInput, edge_props: PropsInput) -> RemoteIndexSpec: - """Create and return a new object. See help(type) for accurate signature.""" - -class PropsInput(object): - """ - Create a PropsInput by choosing to include all/some properties explicitly. - - Arguments: - all (AllPropertySpec, optional): Use a predefined spec to include all properties of a kind. - some (SomePropertySpec, optional): Explicitly list the properties to include. - - Raises: - ValueError: If neither all and some are specified. - """ - - def __new__(cls, all: Optional[AllPropertySpec] = None, some: Optional[SomePropertySpec] = None) -> PropsInput: - """Create and return a new object. See help(type) for accurate signature.""" - -class SomePropertySpec(object): - """ - Create a SomePropertySpec by explicitly listing metadata and/or temporal property names. - - Arguments: - metadata (list[str]): Metadata property names. Defaults to []. - temporal (list[str]): Temporal property names. Defaults to []. - """ - - def __new__(cls, metadata: list[str] = [], properties=...) -> SomePropertySpec: + def __new__( + cls, + src: GID, + dst: GID, + layer: Optional[str] = None, + constant_properties: Optional[PropInput] = None, + updates: Optional[list[RemoteUpdate]] = None, + ) -> RemoteEdgeAddition: """Create and return a new object. See help(type) for accurate signature.""" -class AllPropertySpec(object): - """ - Specifies that **all** properties should be included when creating an index. - Use one of the predefined variants: ALL , ALL_METADATA , or ALL_TEMPORAL . - """ - - def __eq__(self, value): - """Return self==value.""" - - def __ge__(self, value): - """Return self>=value.""" - - def __gt__(self, value): - """Return self>value.""" - - def __int__(self): - """int(self)""" - - def __le__(self, value): - """Return self<=value.""" - - def __lt__(self, value): - """Return self str: """ Encode a graph using Base64 encoding @@ -657,11 +731,3 @@ def decode_graph(graph: str) -> Union[Graph, PersistentGraph]: Returns: Union[Graph, PersistentGraph]: the decoded graph """ - -def schema(): - """ - Returns the raphtory graphql server schema - - Returns - str: Graphql schema - """ diff --git a/python/python/raphtory/node_state/__init__.pyi b/python/python/raphtory/node_state/__init__.pyi index 67d87358b6..368ed732bb 100644 --- a/python/python/raphtory/node_state/__init__.pyi +++ b/python/python/raphtory/node_state/__init__.pyi @@ -22,9 +22,40 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['NodeGroups', 'DegreeView', 'NodeStateUsize', 'NodeStateU64', 'NodeStateOptionI64', 'IdView', 'NodeStateGID', 'EarliestTimeView', 'LatestTimeView', 'NameView', 'NodeStateString', 'EarliestDateTimeView', 'LatestDateTimeView', 'NodeStateOptionDateTime', 'HistoryView', 'EdgeHistoryCountView', 'NodeStateListI64', 'HistoryDateTimeView', 'NodeStateOptionListDateTime', 'NodeTypeView', 'NodeStateOptionStr', 'NodeStateListDateTime', 'NodeStateWeightedSP', 'NodeStateF64', 'NodeStateNodes', 'NodeStateReachability', 'NodeStateListF64', 'NodeStateMotifs', 'NodeStateHits', 'NodeStateSEIR', 'NodeLayout', 'NodeStateF64String'] -class NodeGroups(object): - +__all__ = [ + "NodeGroups", + "DegreeView", + "NodeStateUsize", + "NodeStateU64", + "NodeStateOptionI64", + "IdView", + "NodeStateGID", + "EarliestTimeView", + "LatestTimeView", + "NameView", + "NodeStateString", + "EarliestDateTimeView", + "LatestDateTimeView", + "NodeStateOptionDateTime", + "HistoryView", + "NodeStateListI64", + "HistoryDateTimeView", + "NodeStateOptionListDateTime", + "NodeTypeView", + "NodeStateOptionStr", + "NodeStateListDateTime", + "NodeStateWeightedSP", + "NodeStateF64", + "NodeStateNodes", + "NodeStateReachability", + "NodeStateListF64", + "NodeStateMotifs", + "NodeStateHits", + "NodeStateSEIR", + "NodeLayout", +] + +class NodeGroups(object): def __bool__(self): """True if self else False""" @@ -67,7 +98,7 @@ class NodeGroups(object): Iterator[Tuple[Any, GraphView]]: Iterator over subgraphs with corresponding value """ -class DegreeView(object): +class DegreeView(object): """A lazy view over node values""" def __eq__(self, value): @@ -556,8 +587,7 @@ class DegreeView(object): Optional[int]: """ -class NodeStateUsize(object): - +class NodeStateUsize(object): def __eq__(self, value): """Return self==value.""" @@ -748,8 +778,7 @@ class NodeStateUsize(object): Iterator[int]: Iterator over values """ -class NodeStateU64(object): - +class NodeStateU64(object): def __eq__(self, value): """Return self==value.""" @@ -932,8 +961,7 @@ class NodeStateU64(object): Iterator[int]: Iterator over values """ -class NodeStateOptionI64(object): - +class NodeStateOptionI64(object): def __eq__(self, value): """Return self==value.""" @@ -975,7 +1003,9 @@ 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]]: + def get( + self, node: NodeInput, default: Optional[Optional[int]] = None + ) -> Optional[Optional[int]]: """ Get value for node @@ -1108,7 +1138,7 @@ class NodeStateOptionI64(object): Iterator[Optional[int]]: Iterator over values """ -class IdView(object): +class IdView(object): """A lazy view over node values""" def __eq__(self, value): @@ -1293,8 +1323,7 @@ class IdView(object): Iterator[GID]: Iterator over values """ -class NodeStateGID(object): - +class NodeStateGID(object): def __eq__(self, value): """Return self==value.""" @@ -1461,7 +1490,7 @@ class NodeStateGID(object): Iterator[GID]: Iterator over values """ -class EarliestTimeView(object): +class EarliestTimeView(object): """A lazy view over node values""" def __eq__(self, value): @@ -1636,7 +1665,9 @@ class EarliestTimeView(object): WindowSet: A `WindowSet` object. """ - def get(self, node: NodeInput, default: Optional[Optional[int]] = None) -> Optional[Optional[int]]: + def get( + self, node: NodeInput, default: Optional[Optional[int]] = None + ) -> Optional[Optional[int]]: """ Get value for node @@ -1913,7 +1944,9 @@ class EarliestTimeView(object): Iterator[Optional[int]]: Iterator over values """ - def window(self, start: TimeInput | None, end: TimeInput | None) -> EarliestTimeView: + def window( + self, start: TimeInput | None, end: TimeInput | None + ) -> EarliestTimeView: """ Create a view of the EarliestTimeView including all events between `start` (inclusive) and `end` (exclusive) @@ -1934,7 +1967,7 @@ class EarliestTimeView(object): Optional[int]: """ -class LatestTimeView(object): +class LatestTimeView(object): """A lazy view over node values""" def __eq__(self, value): @@ -2109,7 +2142,9 @@ class LatestTimeView(object): WindowSet: A `WindowSet` object. """ - def get(self, node: NodeInput, default: Optional[Optional[int]] = None) -> Optional[Optional[int]]: + def get( + self, node: NodeInput, default: Optional[Optional[int]] = None + ) -> Optional[Optional[int]]: """ Get value for node @@ -2407,7 +2442,7 @@ class LatestTimeView(object): Optional[int]: """ -class NameView(object): +class NameView(object): """A lazy view over node values""" def __eq__(self, value): @@ -2600,8 +2635,7 @@ class NameView(object): Iterator[str]: Iterator over values """ -class NodeStateString(object): - +class NodeStateString(object): def __eq__(self, value): """Return self==value.""" @@ -2776,7 +2810,7 @@ class NodeStateString(object): Iterator[str]: Iterator over values """ -class EarliestDateTimeView(object): +class EarliestDateTimeView(object): """A lazy view over node values""" def __eq__(self, value): @@ -2951,7 +2985,9 @@ class EarliestDateTimeView(object): WindowSet: A `WindowSet` object. """ - def get(self, node: NodeInput, default: Optional[Optional[datetime]] = None) -> Optional[Optional[datetime]]: + def get( + self, node: NodeInput, default: Optional[Optional[datetime]] = None + ) -> Optional[Optional[datetime]]: """ Get value for node @@ -3228,7 +3264,9 @@ class EarliestDateTimeView(object): Iterator[Optional[datetime]]: Iterator over values """ - def window(self, start: TimeInput | None, end: TimeInput | None) -> EarliestDateTimeView: + def window( + self, start: TimeInput | None, end: TimeInput | None + ) -> EarliestDateTimeView: """ Create a view of the EarliestDateTimeView including all events between `start` (inclusive) and `end` (exclusive) @@ -3249,7 +3287,7 @@ class EarliestDateTimeView(object): Optional[int]: """ -class LatestDateTimeView(object): +class LatestDateTimeView(object): """A lazy view over node values""" def __eq__(self, value): @@ -3424,7 +3462,9 @@ class LatestDateTimeView(object): WindowSet: A `WindowSet` object. """ - def get(self, node: NodeInput, default: Optional[Optional[datetime]] = None) -> Optional[Optional[datetime]]: + def get( + self, node: NodeInput, default: Optional[Optional[datetime]] = None + ) -> Optional[Optional[datetime]]: """ Get value for node @@ -3701,7 +3741,9 @@ class LatestDateTimeView(object): Iterator[Optional[datetime]]: Iterator over values """ - def window(self, start: TimeInput | None, end: TimeInput | None) -> LatestDateTimeView: + def window( + self, start: TimeInput | None, end: TimeInput | None + ) -> LatestDateTimeView: """ Create a view of the LatestDateTimeView including all events between `start` (inclusive) and `end` (exclusive) @@ -3722,8 +3764,7 @@ class LatestDateTimeView(object): Optional[int]: """ -class NodeStateOptionDateTime(object): - +class NodeStateOptionDateTime(object): def __eq__(self, value): """Return self==value.""" @@ -3765,7 +3806,9 @@ 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]]: + def get( + self, node: NodeInput, default: Optional[Optional[datetime]] = None + ) -> Optional[Optional[datetime]]: """ Get value for node @@ -3898,7 +3941,7 @@ class NodeStateOptionDateTime(object): Iterator[Optional[datetime]]: Iterator over values """ -class HistoryView(object): +class HistoryView(object): """A lazy view over node values""" def __eq__(self, value): @@ -4073,7 +4116,9 @@ class HistoryView(object): WindowSet: A `WindowSet` object. """ - def get(self, node: NodeInput, default: Optional[list[int]] = None) -> Optional[list[int]]: + def get( + self, node: NodeInput, default: Optional[list[int]] = None + ) -> Optional[list[int]]: """ Get value for node @@ -4363,489 +4408,7 @@ class HistoryView(object): Optional[int]: """ -class EdgeHistoryCountView(object): - """A lazy view over node values""" - - 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 EdgeHistoryCountView: - """ - Create a view of the EdgeHistoryCountView including all events after `start` (exclusive). - - Arguments: - start (TimeInput): The start time of the window. - - Returns: - EdgeHistoryCountView: - """ - - def at(self, time: TimeInput) -> EdgeHistoryCountView: - """ - Create a view of the EdgeHistoryCountView including all events at `time`. - - Arguments: - time (TimeInput): The time of the window. - - Returns: - EdgeHistoryCountView: - """ - - def before(self, end: TimeInput) -> EdgeHistoryCountView: - """ - Create a view of the EdgeHistoryCountView including all events before `end` (exclusive). - - Arguments: - end (TimeInput): The end time of the window. - - Returns: - EdgeHistoryCountView: - """ - - def bottom_k(self, k: int) -> EdgeHistoryCountView: - """ - Compute the k smallest values - - Arguments: - k (int): The number of values to return - - Returns: - EdgeHistoryCountView: The k smallest values as a node state - """ - - def collect(self) -> list[int]: - """ - Compute all values and return the result as a list - - Returns: - list[int]: all values as a list - """ - - def compute(self) -> EdgeHistoryCountView: - """ - Compute all values and return the result as a node view - - Returns: - EdgeHistoryCountView: the computed `NodeState` - """ - - def default_layer(self) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing only the default edge layer - Returns: - EdgeHistoryCountView: The layered view - """ - - @property - def end(self) -> Optional[int]: - """ - Gets the latest time that this EdgeHistoryCountView is valid. - - Returns: - Optional[int]: The latest time that this EdgeHistoryCountView is valid or None if the EdgeHistoryCountView is valid for all times. - """ - - @property - def end_date_time(self) -> Optional[datetime]: - """ - Gets the latest datetime that this EdgeHistoryCountView is valid - - Returns: - Optional[datetime]: The latest datetime that this EdgeHistoryCountView is valid or None if the EdgeHistoryCountView is valid for all times. - """ - - def exclude_layer(self, name: str) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing all layers except the excluded `name` - Errors if any of the layers do not exist. - - Arguments: - name (str): layer name that is excluded for the new view - - Returns: - EdgeHistoryCountView: The layered view - """ - - def exclude_layers(self, names: list[str]) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing all layers except the excluded `names` - Errors if any of the layers do not exist. - - Arguments: - names (list[str]): list of layer names that are excluded for the new view - - Returns: - EdgeHistoryCountView: The layered view - """ - - def exclude_valid_layer(self, name: str) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing all layers except the excluded `name` - Arguments: - name (str): layer name that is excluded for the new view - - Returns: - EdgeHistoryCountView: The layered view - """ - - def exclude_valid_layers(self, names: list[str]) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing all layers except the excluded `names` - Arguments: - names (list[str]): list of layer names that are excluded for the new view - - Returns: - EdgeHistoryCountView: The layered view - """ - - def expanding(self, step: int | str) -> WindowSet: - """ - Creates a `WindowSet` with the given `step` size using an expanding window. - - An expanding window is a window that grows by `step` size at each iteration. - - Arguments: - step (int | str): The step size of the window. - - Returns: - 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 has_layer(self, name: str) -> bool: - """ - Check if EdgeHistoryCountView has the layer `"name"` - - Arguments: - name (str): the name of the layer to check - - Returns: - bool: - """ - - def items(self) -> Iterator[Tuple[Node, int]]: - """ - Iterate over items - - Returns: - Iterator[Tuple[Node, int]]: Iterator over items - """ - - def latest(self) -> EdgeHistoryCountView: - """ - Create a view of the EdgeHistoryCountView including all events at the latest time. - - Returns: - EdgeHistoryCountView: - """ - - def layer(self, name: str) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing the layer `"name"` - Errors if the layer does not exist - - Arguments: - name (str): then name of the layer. - - Returns: - EdgeHistoryCountView: The layered view - """ - - def layers(self, names: list[str]) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing all layers `names` - Errors if any of the layers do not exist. - - Arguments: - names (list[str]): list of layer names for the new view - - Returns: - EdgeHistoryCountView: The layered view - """ - - def max(self) -> Optional[int]: - """ - Return the maximum value - - Returns: - Optional[int]: The maximum value or `None` if empty - """ - - def max_item(self) -> Optional[Tuple[Node, int]]: - """ - Return largest value and corresponding node - - Returns: - Optional[Tuple[Node, int]]: 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[int]: - """ - Return the median value - - Returns: - Optional[int]: - """ - - def median_item(self) -> Optional[Tuple[Node, int]]: - """ - Return median value and corresponding node - - Returns: - Optional[Tuple[Node, int]]: The median value or `None` if empty - """ - - def min(self) -> Optional[int]: - """ - Return the minimum value - - Returns: - Optional[int]: The minimum value or `None` if empty - """ - - def min_item(self) -> Optional[Tuple[Node, int]]: - """ - Return smallest value and corresponding node - - Returns: - Optional[Tuple[Node, int]]: The Node and minimum value or `None` if empty - """ - - def nodes(self) -> Nodes: - """ - Iterate over nodes - - Returns: - Nodes: The nodes - """ - - def rolling(self, window: int | str, step: int | str | None = None) -> WindowSet: - """ - Creates a `WindowSet` with the given `window` size and optional `step` using a rolling window. - - A rolling window is a window that moves forward by `step` size at each iteration. - - Arguments: - window (int | str): The size of the window. - step (int | str | None): The step size of the window. - `step` defaults to `window`. - - Returns: - WindowSet: A `WindowSet` object. - """ - - def shrink_end(self, end: TimeInput) -> EdgeHistoryCountView: - """ - Set the end of the window to the smaller of `end` and `self.end()` - - Arguments: - end (TimeInput): the new end time of the window - Returns: - EdgeHistoryCountView: - """ - - def shrink_start(self, start: TimeInput) -> EdgeHistoryCountView: - """ - Set the start of the window to the larger of `start` and `self.start()` - - Arguments: - start (TimeInput): the new start time of the window - - Returns: - EdgeHistoryCountView: - """ - - def shrink_window(self, start: TimeInput, end: TimeInput) -> EdgeHistoryCountView: - """ - Shrink both the start and end of the window (same as calling `shrink_start` followed by `shrink_end` but more efficient) - - Arguments: - start (TimeInput): the new start time for the window - end (TimeInput): the new end time for the window - - Returns: - EdgeHistoryCountView: - """ - - def snapshot_at(self, time: TimeInput) -> EdgeHistoryCountView: - """ - Create a view of the EdgeHistoryCountView including all events that have not been explicitly deleted at `time`. - - This is equivalent to `before(time + 1)` for `Graph` and `at(time)` for `PersistentGraph` - - Arguments: - time (TimeInput): The time of the window. - - Returns: - EdgeHistoryCountView: - """ - - def snapshot_latest(self) -> EdgeHistoryCountView: - """ - Create a view of the EdgeHistoryCountView including all events that have not been explicitly deleted at the latest time. - - This is equivalent to a no-op for `Graph` and `latest()` for `PersistentGraph` - - Returns: - EdgeHistoryCountView: - """ - - def sorted(self, reverse: bool = False) -> EdgeHistoryCountView: - """ - Sort by value - - Arguments: - reverse (bool): If `True`, sort in descending order, otherwise ascending. Defaults to False. - - Returns: - EdgeHistoryCountView: Sorted node state - """ - - def sorted_by_id(self) -> EdgeHistoryCountView: - """ - Sort results by node id - - Returns: - EdgeHistoryCountView: The sorted node state - """ - - @property - def start(self) -> Optional[int]: - """ - Gets the start time for rolling and expanding windows for this EdgeHistoryCountView - - Returns: - Optional[int]: The earliest time that this EdgeHistoryCountView is valid or None if the EdgeHistoryCountView is valid for all times. - """ - - @property - def start_date_time(self) -> Optional[datetime]: - """ - Gets the earliest datetime that this EdgeHistoryCountView is valid - - Returns: - Optional[datetime]: The earliest datetime that this EdgeHistoryCountView is valid or None if the EdgeHistoryCountView is valid for all times. - """ - - def sum(self) -> int: - """ - sum of values over all nodes - - Returns: - 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) -> EdgeHistoryCountView: - """ - Compute the k largest values - - Arguments: - k (int): The number of values to return - - Returns: - EdgeHistoryCountView: The k largest values as a node state - """ - - def valid_layers(self, names: list[str]) -> EdgeHistoryCountView: - """ - Return a view of EdgeHistoryCountView containing all layers `names` - Any layers that do not exist are ignored - - Arguments: - names (list[str]): list of layer names for the new view - - Returns: - EdgeHistoryCountView: The layered view - """ - - def values(self) -> Iterator[int]: - """ - Iterate over values - - Returns: - Iterator[int]: Iterator over values - """ - - def window(self, start: TimeInput | None, end: TimeInput | None) -> EdgeHistoryCountView: - """ - Create a view of the EdgeHistoryCountView including all events between `start` (inclusive) and `end` (exclusive) - - Arguments: - start (TimeInput | None): The start time of the window (unbounded if `None`). - end (TimeInput | None): The end time of the window (unbounded if `None`). - - Returns: - EdgeHistoryCountView: - """ - - @property - def window_size(self) -> Optional[int]: - """ - Get the window size (difference between start and end) for this EdgeHistoryCountView - - Returns: - Optional[int]: - """ - -class NodeStateListI64(object): - +class NodeStateListI64(object): def __eq__(self, value): """Return self==value.""" @@ -4887,7 +4450,9 @@ 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]]: + def get( + self, node: NodeInput, default: Optional[list[int]] = None + ) -> Optional[list[int]]: """ Get value for node @@ -5012,7 +4577,7 @@ class NodeStateListI64(object): Iterator[list[int]]: Iterator over values """ -class HistoryDateTimeView(object): +class HistoryDateTimeView(object): """A lazy view over node values""" def __eq__(self, value): @@ -5187,7 +4752,9 @@ class HistoryDateTimeView(object): WindowSet: A `WindowSet` object. """ - def get(self, node: NodeInput, default: Optional[Optional[list[datetime]]] = None) -> Optional[Optional[list[datetime]]]: + def get( + self, node: NodeInput, default: Optional[Optional[list[datetime]]] = None + ) -> Optional[Optional[list[datetime]]]: """ Get value for node @@ -5456,7 +5023,9 @@ class HistoryDateTimeView(object): Iterator[Optional[list[datetime]]]: Iterator over values """ - def window(self, start: TimeInput | None, end: TimeInput | None) -> HistoryDateTimeView: + def window( + self, start: TimeInput | None, end: TimeInput | None + ) -> HistoryDateTimeView: """ Create a view of the HistoryDateTimeView including all events between `start` (inclusive) and `end` (exclusive) @@ -5477,8 +5046,7 @@ class HistoryDateTimeView(object): Optional[int]: """ -class NodeStateOptionListDateTime(object): - +class NodeStateOptionListDateTime(object): def __eq__(self, value): """Return self==value.""" @@ -5520,7 +5088,9 @@ 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]]]: + def get( + self, node: NodeInput, default: Optional[Optional[list[datetime]]] = None + ) -> Optional[Optional[list[datetime]]]: """ Get value for node @@ -5645,7 +5215,7 @@ class NodeStateOptionListDateTime(object): Iterator[Optional[list[datetime]]]: Iterator over values """ -class NodeTypeView(object): +class NodeTypeView(object): """A lazy view over node values""" def __eq__(self, value): @@ -5705,7 +5275,9 @@ class NodeTypeView(object): NodeStateOptionStr: the computed `NodeState` """ - def get(self, node: NodeInput, default: Optional[Optional[str]] = None) -> Optional[Optional[str]]: + def get( + self, node: NodeInput, default: Optional[Optional[str]] = None + ) -> Optional[Optional[str]]: """ Get value for node @@ -5838,8 +5410,7 @@ class NodeTypeView(object): Iterator[Optional[str]]: Iterator over values """ -class NodeStateOptionStr(object): - +class NodeStateOptionStr(object): def __eq__(self, value): """Return self==value.""" @@ -5881,7 +5452,9 @@ 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]]: + def get( + self, node: NodeInput, default: Optional[Optional[str]] = None + ) -> Optional[Optional[str]]: """ Get value for node @@ -6014,8 +5587,7 @@ class NodeStateOptionStr(object): Iterator[Optional[str]]: Iterator over values """ -class NodeStateListDateTime(object): - +class NodeStateListDateTime(object): def __eq__(self, value): """Return self==value.""" @@ -6057,7 +5629,9 @@ 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]]: + def get( + self, node: NodeInput, default: Optional[list[datetime]] = None + ) -> Optional[list[datetime]]: """ Get value for node @@ -6182,8 +5756,7 @@ class NodeStateListDateTime(object): Iterator[list[datetime]]: Iterator over values """ -class NodeStateWeightedSP(object): - +class NodeStateWeightedSP(object): def __eq__(self, value): """Return self==value.""" @@ -6214,7 +5787,9 @@ class NodeStateWeightedSP(object): def __repr__(self): """Return repr(self).""" - def get(self, node: NodeInput, default: Optional[Tuple[float, Nodes]] = None) -> Optional[Tuple[float, Nodes]]: + def get( + self, node: NodeInput, default: Optional[Tuple[float, Nodes]] = None + ) -> Optional[Tuple[float, Nodes]]: """ Get value for node @@ -6269,8 +5844,7 @@ class NodeStateWeightedSP(object): Iterator[Tuple[float, Nodes]]: Iterator over values """ -class NodeStateF64(object): - +class NodeStateF64(object): def __eq__(self, value): """Return self==value.""" @@ -6453,8 +6027,7 @@ class NodeStateF64(object): Iterator[float]: Iterator over values """ -class NodeStateNodes(object): - +class NodeStateNodes(object): def __eq__(self, value): """Return self==value.""" @@ -6540,8 +6113,7 @@ class NodeStateNodes(object): Iterator[Nodes]: Iterator over values """ -class NodeStateReachability(object): - +class NodeStateReachability(object): def __eq__(self, value): """Return self==value.""" @@ -6572,7 +6144,9 @@ class NodeStateReachability(object): def __repr__(self): """Return repr(self).""" - def get(self, node: NodeInput, default: Optional[list[Tuple[int, str]]] = None) -> Optional[list[Tuple[int, str]]]: + def get( + self, node: NodeInput, default: Optional[list[Tuple[int, str]]] = None + ) -> Optional[list[Tuple[int, str]]]: """ Get value for node @@ -6627,8 +6201,7 @@ class NodeStateReachability(object): Iterator[list[Tuple[int, str]]]: Iterator over values """ -class NodeStateListF64(object): - +class NodeStateListF64(object): def __eq__(self, value): """Return self==value.""" @@ -6659,7 +6232,9 @@ class NodeStateListF64(object): def __repr__(self): """Return repr(self).""" - def get(self, node: NodeInput, default: Optional[list[float]] = None) -> Optional[list[float]]: + def get( + self, node: NodeInput, default: Optional[list[float]] = None + ) -> Optional[list[float]]: """ Get value for node @@ -6714,8 +6289,7 @@ class NodeStateListF64(object): Iterator[list[float]]: Iterator over values """ -class NodeStateMotifs(object): - +class NodeStateMotifs(object): def __eq__(self, value): """Return self==value.""" @@ -6757,7 +6331,9 @@ class NodeStateMotifs(object): NodeStateMotifs: The k smallest values as a node state """ - def get(self, node: NodeInput, default: Optional[list[int]] = None) -> Optional[list[int]]: + def get( + self, node: NodeInput, default: Optional[list[int]] = None + ) -> Optional[list[int]]: """ Get value for node @@ -6882,8 +6458,7 @@ class NodeStateMotifs(object): Iterator[list[int]]: Iterator over values """ -class NodeStateHits(object): - +class NodeStateHits(object): def __eq__(self, value): """Return self==value.""" @@ -6925,7 +6500,9 @@ class NodeStateHits(object): NodeStateHits: The k smallest values as a node state """ - def get(self, node: NodeInput, default: Optional[Tuple[float, float]] = None) -> Optional[Tuple[float, float]]: + def get( + self, node: NodeInput, default: Optional[Tuple[float, float]] = None + ) -> Optional[Tuple[float, float]]: """ Get value for node @@ -7050,8 +6627,7 @@ class NodeStateHits(object): Iterator[Tuple[float, float]]: Iterator over values """ -class NodeStateSEIR(object): - +class NodeStateSEIR(object): def __eq__(self, value): """Return self==value.""" @@ -7093,7 +6669,9 @@ class NodeStateSEIR(object): NodeStateSEIR: The k smallest values as a node state """ - def get(self, node: NodeInput, default: Optional[Infected] = None) -> Optional[Infected]: + def get( + self, node: NodeInput, default: Optional[Infected] = None + ) -> Optional[Infected]: """ Get value for node @@ -7218,8 +6796,7 @@ class NodeStateSEIR(object): Iterator[Infected]: Iterator over values """ -class NodeLayout(object): - +class NodeLayout(object): def __eq__(self, value): """Return self==value.""" @@ -7250,7 +6827,9 @@ class NodeLayout(object): def __repr__(self): """Return repr(self).""" - def get(self, node: NodeInput, default: Optional[list[float]] = None) -> Optional[list[float]]: + def get( + self, node: NodeInput, default: Optional[list[float]] = None + ) -> Optional[list[float]]: """ Get value for node @@ -7304,90 +6883,3 @@ class NodeLayout(object): Returns: Iterator[list[float]]: Iterator over values """ - -class NodeStateF64String(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, str]]: - """ - Get value for node - - Arguments: - node (NodeInput): the node - default (Optional[Tuple[float, str]]): the default value. Defaults to None. - - Returns: - Optional[Tuple[float, str]]: the value for the node or the default value - """ - - def items(self) -> Iterator[Tuple[Node, Tuple[float, str]]]: - """ - Iterate over items - - Returns: - Iterator[Tuple[Node, Tuple[float, str]]]: Iterator over items - """ - - def nodes(self) -> Nodes: - """ - Iterate over nodes - - Returns: - Nodes: The nodes - """ - - def sorted_by_id(self) -> NodeStateF64String: - """ - Sort results by node id - - Returns: - NodeStateF64String: 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, str]]: - """ - Iterate over values - - Returns: - Iterator[Tuple[float, str]]: Iterator over values - """ diff --git a/python/python/raphtory/vectors/__init__.pyi b/python/python/raphtory/vectors/__init__.pyi index 1f6c6ce647..d59f316584 100644 --- a/python/python/raphtory/vectors/__init__.pyi +++ b/python/python/raphtory/vectors/__init__.pyi @@ -22,10 +22,33 @@ from os import PathLike import networkx as nx # type: ignore import pyvis # type: ignore -__all__ = ['VectorisedGraph', 'Document', 'Embedding', 'VectorSelection'] -class VectorisedGraph(object): +__all__ = ["VectorisedGraph", "Document", "Embedding", "VectorSelection"] - def edges_by_similarity(self, query: str | list, limit: int, window: Optional[Tuple[int | str, int | str]] = None) -> VectorSelection: +class VectorisedGraph(object): + def documents_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> VectorSelection: + """ + Search the top scoring documents according to `query` with no more than `limit` documents + + Args: + query (str | list): the text or the embedding to score against + limit (int): the maximum number of documents to search + window (Tuple[int | str, int | str], optional): the window where documents need to belong to in order to be considered + + Returns: + VectorSelection: The vector selection resulting from the search + """ + + def edges_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> VectorSelection: """ Search the top scoring edges according to `query` with no more than `limit` edges @@ -41,7 +64,12 @@ class VectorisedGraph(object): def empty_selection(self): """Return an empty selection of documents""" - def entities_by_similarity(self, query: str | list, limit: int, window: Optional[Tuple[int | str, int | str]] = None) -> VectorSelection: + def entities_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> VectorSelection: """ Search the top scoring entities according to `query` with no more than `limit` entities @@ -54,7 +82,20 @@ class VectorisedGraph(object): VectorSelection: The vector selection resulting from the search """ - def nodes_by_similarity(self, query: str | list, limit: int, window: Optional[Tuple[int | str, int | str]] = None) -> VectorSelection: + def get_graph_documents(self) -> list[Document]: + """ + Return all the graph level documents + + Returns: + list[Document]: list of graph level documents + """ + + def nodes_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> VectorSelection: """ Search the top scoring nodes according to `query` with no more than `limit` nodes @@ -67,7 +108,10 @@ class VectorisedGraph(object): VectorSelection: The vector selection resulting from the search """ -class Document(object): + def save_embeddings(self, file): + """Save the embeddings present in this graph to `file` so they can be further used in a call to `vectorise`""" + +class Document(object): """ A Document @@ -108,13 +152,20 @@ class Document(object): Optional[Any]: """ -class Embedding(object): + @property + def life(self) -> Optional[Union[int | Tuple[int, int]]]: + """ + the life span + Returns: + Optional[Union[int | Tuple[int, int]]]: + """ + +class Embedding(object): def __repr__(self): """Return repr(self).""" -class VectorSelection(object): - +class VectorSelection(object): def add_edges(self, edges: list) -> None: """ Add all the documents associated with the `edges` to the current selection @@ -160,7 +211,9 @@ class VectorSelection(object): list[Edge]: list of edges in the current selection """ - def expand(self, hops: int, window: Optional[Tuple[int | str, int | str]] = None) -> None: + def expand( + self, hops: int, window: Optional[Tuple[int | str, int | str]] = None + ) -> None: """ Add all the documents `hops` hops away to the selection @@ -177,7 +230,39 @@ class VectorSelection(object): None: """ - def expand_edges_by_similarity(self, query: str | list, limit: int, window: Optional[Tuple[int | str, int | str]] = None) -> None: + def expand_documents_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> None: + """ + Add the top `limit` adjacent documents with higher score for `query` to the selection + + The expansion algorithm is a loop with two steps on each iteration: + 1. All the documents 1 hop away of some of the documents included on the selection (and + not already selected) are marked as candidates. + 2. Those candidates are added to the selection in descending order according to the + similarity score obtained against the `query`. + + This loops goes on until the current selection reaches a total of `limit` documents or + until no more documents are available + + Args: + query (str | list): the text or the embedding to score against + limit (int): the number of documents to add + window (Tuple[int | str, int | str], optional): the window where documents need to belong to in order to be considered + + Returns: + None: + """ + + def expand_edges_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> None: """ Add the top `limit` adjacent edges with higher score for `query` to the selection @@ -192,7 +277,12 @@ class VectorSelection(object): None: """ - def expand_entities_by_similarity(self, query: str | list, limit: int, window: Optional[Tuple[int | str, int | str]] = None) -> None: + def expand_entities_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> None: """ Add the top `limit` adjacent entities with higher score for `query` to the selection @@ -214,7 +304,12 @@ class VectorSelection(object): None: """ - def expand_nodes_by_similarity(self, query: str | list, limit: int, window: Optional[Tuple[int | str, int | str]] = None) -> None: + def expand_nodes_by_similarity( + self, + query: str | list, + limit: int, + window: Optional[Tuple[int | str, int | str]] = None, + ) -> None: """ Add the top `limit` adjacent nodes with higher score for `query` to the selection diff --git a/raphtory-graphql/schema.graphql b/raphtory-graphql/schema.graphql index 97b7ccd9bf..6054244071 100644 --- a/raphtory-graphql/schema.graphql +++ b/raphtory-graphql/schema.graphql @@ -940,8 +940,8 @@ type Graph { } type GraphAlgorithmPlugin { - shortest_path(source: String!, targets: [String!]!, direction: String): [ShortestPathOutput!]! pagerank(iterCount: Int!, threads: Int, tol: Float): [PagerankOutput!]! + shortest_path(source: String!, targets: [String!]!, direction: String): [ShortestPathOutput!]! } type GraphSchema { diff --git a/raphtory/src/graphgen/erdos_renyi.rs b/raphtory/src/graphgen/erdos_renyi.rs new file mode 100644 index 0000000000..a067138e8f --- /dev/null +++ b/raphtory/src/graphgen/erdos_renyi.rs @@ -0,0 +1,112 @@ +//! Generates a graph using the erodos renyl model +//! +//! # Examples +//! +//! ``` +//! use raphtory::prelude::*; +//! use raphtory::graphgen::erdos_renyi::erdos_renyi; +//! let graph = Graph::new(); +//! erdos_renyi(&graph, 1000, 0.1, None); +//! ``` + +use super::next_id; +use crate::{ + db::{ + api::{mutation::AdditionOps, view::*}, + graph::graph::Graph, + }, + prelude::{NodeStateOps, NO_PROPS}, +}; +use rand::{rngs::StdRng, Rng, SeedableRng}; +use tracing::error; + +/// Generates an Erdos-Renyi random graph in the provided `graph`. +/// +/// # Arguments +/// * `graph` - The graph to populate with nodes and edges. +/// * `n_nodes` - Number of nodes to create in the graph. +/// * `p` - Probability of edge creation between any two nodes (0.0 = no edges, 1.0 = fully connected). +/// * `seed` - Optional 32-byte seed for deterministic random generation. If `None`, uses entropy. +/// +/// # Behavior +/// - Adds `n_nodes` nodes to the graph. +/// - For each pair of distinct nodes, adds a directed edge with probability `p`. +/// - Uses the provided seed for reproducibility if given. +/// +/// # Example +/// ``` +/// let graph = Graph::new(); +/// erdos_renyi(&graph, 10, 0.2, None); +/// ``` +pub fn erdos_renyi(graph: &Graph, n_nodes: usize, p: f64, seed: Option<[u8; 32]>) { + let mut rng: StdRng; + if let Some(seed_value) = seed { + rng = StdRng::from_seed(seed_value); + } else { + rng = StdRng::from_entropy(); + } + let mut latest_time = graph.latest_time().unwrap_or(0); + let ids = graph.nodes().id().iter_values().collect::>(); + let mut max_id = next_id(graph, ids.iter().max().cloned()); + for _ in 0..n_nodes { + max_id = next_id(graph, Some(max_id)); + latest_time += 1; + graph + .add_node(latest_time, &max_id, NO_PROPS, None) + .map_err(|err| error!("{:?}", err)) + .ok(); + } + let all_ids = graph.nodes().id().iter_values().collect::>(); + for id in all_ids.iter() { + for other_id in all_ids.iter() { + if id != other_id && rng.gen::() < p { + latest_time += 1; + graph + .add_edge(latest_time, id, other_id, NO_PROPS, None) + .expect("Not able to add edge"); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prelude::*; + + #[test] + fn test_erdos_renyi_small_graph() { + let graph = Graph::new(); + let n_nodes = 5; + let p = 0.5; + let seed = Some([1u8; 32]); + erdos_renyi(&graph, n_nodes, p, seed); + let node_count = graph.nodes().id().iter_values().count(); + assert_eq!(node_count, n_nodes); + let edge_count = graph.edges().into_iter().count(); + assert!(edge_count > 0); + assert!(edge_count <= n_nodes * (n_nodes - 1)); + } + + #[test] + fn test_erdos_renyi_zero_probability() { + let graph = Graph::new(); + let n_nodes = 4; + let p = 0.0; + let seed = Some([2u8; 32]); + erdos_renyi(&graph, n_nodes, p, seed); + let edge_count = graph.edges().into_iter().count(); + assert_eq!(edge_count, 0); + } + + #[test] + fn test_erdos_renyi_full_probability() { + let graph = Graph::new(); + let n_nodes = 3; + let p = 1.0; + let seed = Some([3u8; 32]); + erdos_renyi(&graph, n_nodes, p, seed); + let edge_count = graph.edges().into_iter().count(); + assert_eq!(edge_count, n_nodes * (n_nodes - 1)); + } +} diff --git a/raphtory/src/graphgen/mod.rs b/raphtory/src/graphgen/mod.rs index c7021c5e2b..072006dc02 100644 --- a/raphtory/src/graphgen/mod.rs +++ b/raphtory/src/graphgen/mod.rs @@ -5,6 +5,7 @@ use raphtory_api::core::entities::GID; use crate::prelude::*; +pub mod erdos_renyi; pub mod preferential_attachment; pub mod random_attachment; diff --git a/raphtory/src/python/packages/base_modules.rs b/raphtory/src/python/packages/base_modules.rs index a2d2c8b44f..4402a404b5 100644 --- a/raphtory/src/python/packages/base_modules.rs +++ b/raphtory/src/python/packages/base_modules.rs @@ -140,6 +140,7 @@ pub fn base_graph_gen_module(py: Python<'_>) -> Result, PyErr> { &graph_gen_module, random_attachment, ba_preferential_attachment, + erdos_renyi ); Ok(graph_gen_module) } diff --git a/raphtory/src/python/packages/graph_gen.rs b/raphtory/src/python/packages/graph_gen.rs index a822065e2e..25c875215a 100644 --- a/raphtory/src/python/packages/graph_gen.rs +++ b/raphtory/src/python/packages/graph_gen.rs @@ -3,7 +3,7 @@ //! the random attachment model. use crate::{ graphgen::{ - preferential_attachment::ba_preferential_attachment as pa, + erdos_renyi::erdos_renyi as er, preferential_attachment::ba_preferential_attachment as pa, random_attachment::random_attachment as ra, }, python::graph::graph::PyGraph, @@ -67,3 +67,23 @@ pub fn ba_preferential_attachment( ) { pa(&g.graph, nodes_to_add, edges_per_step, seed); } + +/// Generates a graph using the Erdos-Renyi random graph model. +/// +/// This function adds a specified number of nodes to the given graph, and then +/// for each possible pair of distinct nodes, adds a directed edge with probability `p`. +/// The process can be made deterministic by providing a 32-byte seed. +/// +/// Arguments: +/// g: The graph you wish to add nodes and edges to +/// n_nodes: The number of nodes to add to the graph +/// p: The probability of creating an edge between any two nodes (0.0 = no edges, 1.0 = fully connected) +/// seed: Optional 32-byte array used as the random seed (for reproducibility) +/// +/// Returns: +/// None +#[pyfunction] +#[pyo3[signature = (g, n_nodes, p, seed=None)]] +pub fn erdos_renyi(g: &PyGraph, n_nodes: usize, p: f64, seed: Option<[u8; 32]>) { + er(&g.graph, n_nodes, p, seed); +}