networkx_temporal.utils

Utility functions for NetworkX static and temporal graphs.

Summary

combine_snapshots(graphs)

Returns temporal graph with combined snapshots.

get_edge_attributes(TG, attr[, default, index])

Returns attributes of edges in each snapshot.

get_node_attributes(TG, attr[, default, index])

Returns attributes of nodes in each snapshot.

get_unique_edge_attributes(TG, attr[, default])

Returns unique edge attribute values in graph.

get_unique_node_attributes(TG, attr[, default])

Returns unique node attribute values in graph.

map_attr_to_edges([TG, attr, default, index])

Maps attributes to edges in each snapshot.

map_attr_to_nodes([TG, attr, default, index])

Maps attributes to nodes in each snapshot.

map_edge_attr_to_nodes(TG, attr[, default, ...])

Returns node attributes from edge attributes.

map_node_attr_to_edges(TG, attr[, default, ...])

Returns edge attributes from node attributes.

map_partitions_to_edges(partitions[, edgelist])

Returns the mapping of edges to partition indices.

map_partitions_to_nodes(partitions[, nodelist])

Returns the mapping of nodes to partition indices.

partition_edges([TG, attr, default, index, ...])

Returns lists of edges sharing attribute values.

partition_nodes([TG, attr, default, index, ...])

Returns lists of nodes sharing attribute values.

propagate_snapshots(TG[, method, delta])

Propagates nodes and edges across snapshots.

temporal_edge_matrix(TG[, method, na_diag])

Returns matrix of edge overlap over time.

temporal_node_matrix(TG[, method, na_diag])

Returns matrix of node overlap over time.

Converters - Summary

convert.convert(G, to, *args, **kwargs)

High-level conversion function to other libraries.

convert.to_dgl(G, *args, **kwargs)

Convert from NetworkX to Deep Graph Library.

convert.to_dynetx(G[, attr])

Convert from NetworkX to DyNetX.

convert.to_graph_tool(G[, index, encoding, ...])

Convert from NetworkX to graph-tool.

convert.to_igraph(G, *args, **kwargs)

Convert from NetworkX to igraph.

convert.to_networkit(G, *args, **kwargs)

Convert from NetworkX to Networkit.

convert.to_numpy(G[, supra])

Convert from NetworkX to a dense NumPy adjacency matrix.

convert.to_scipy(G[, supra, nodelist, ...])

Convert from NetworkX to a sparse SciPy adjacency matrix.

convert.to_snap(G[, node_id, node_attrs, ...])

Convert from NetworkX to SNAP.

convert.to_stellargraph(G, *args, **kwargs)

Convert from NetworkX to StellarGraph.

convert.to_teneto(G[, attr])

Convert from NetworkX to Teneto.

convert.to_torch_geometric(G, *args, **kwargs)

Convert from NetworkX to PyTorch Geometric.

Functions

combine_snapshots(graphs: List[TemporalGraph]) TemporalGraph[source]

Returns temporal graph with combined snapshots.

Each snapshot in the resulting temporal graph is the union of the corresponding snapshots at each index \(t\) from graphs. All input temporal graphs must have the same number of snapshots.

Example

>>> import networkx_temporal as tx
>>>
>>> TG1 = tx.temporal_graph()
>>> TG2 = tx.temporal_graph()
>>>
>>> TG1.add_edge("a", "b")
>>> TG2.add_edge("c", "b")
>>>
>>> TG = tx.combine_snapshots([TG1, TG2])
>>> print(TG)
Parameters:

graphs (object) – A list of TemporalGraph objects.

Return type:

TemporalGraph

get_edge_attributes(TG: TemporalGraph, attr: str, default: Any = nan, index: bool = True) List[Any][source]

Returns attributes of edges in each snapshot.

Examples

>>> import networkx_temporal as tx
>>>
>>> TG = tx.temporal_graph(multigraph=False)
>>>
>>> TG.add_edge("a", "b", time=0)
>>> TG.add_edge("b", "c", time=1)
>>>
>>> tx.get_edge_attributes(TG, attr="time")

[{('a', 'b'): 0, ('b', 'c'): 1}]
>>> tx.get_edge_attributes(TG, attr="time", index=False)

[[0, 1]]
Parameters:
  • TG (TemporalGraph) – TemporalGraph object.

  • attr (str) – The edge attribute key.

  • default (Any) – The default value to return if the attribute is not found. Returns float('nan') if unset.

  • index (bool) – Whether to return a dictionary with edges as keys.

Return type:

List[Any]

get_node_attributes(TG: TemporalGraph, attr: str, default: Any = nan, index: bool = True) List[Any][source]

Returns attributes of nodes in each snapshot.

Examples

>>> import networkx_temporal as tx
>>>
>>> TG = tx.temporal_graph(multigraph=False)
>>>
>>> TG.add_node("a", group=0)
>>> TG.add_node("b", group=1)
>>> TG.add_node("c")
>>>
>>> tx.get_node_attributes(TG, attr="group")

[{'a': 0, 'b': 1, 'c': nan}]
>>> tx.get_node_attributes(TG, attr="group", default=None, index=None)

[[0, 1]]
Parameters:
  • TG (TemporalGraph) – TemporalGraph object.

  • attr (str) – The node attribute key.

  • default (Any) – The default value to return if the attribute is not found. Returns float('nan') if unset.

  • index (bool) – Whether to return a dictionary with nodes as keys.

Return type:

List[Any]

get_unique_edge_attributes(TG: TemporalGraph, attr: str, default: Any = nan) List[Any][source]

Returns unique edge attribute values in graph.

Example

>>> import networkx_temporal as tx
>>>
>>> TG = tx.temporal_graph(t=2, multigraph=False)
>>>
>>> TG[0].add_edge("a", "b", time=0)
>>> TG[1].add_edge("b", "c", time=1)
>>>
>>> tx.get_unique_edge_attributes(TG, attr="time")

[0, 1]
Parameters:
  • TG (TemporalGraph) – TemporalGraph object.

  • default (Any) – The default value to return if the attribute is not found. Returns float('nan') if unset.

  • attr (str) – The edge attribute key.

Return type:

List[Any]

get_unique_node_attributes(TG: TemporalGraph, attr: str, default: Any = nan) List[Any][source]

Returns unique node attribute values in graph.

Example

>>> import networkx_temporal as tx
>>>
>>> TG = tx.temporal_graph(t=2, multigraph=False)
>>>
>>> TG.add_node("a", group=0)
>>> TG.add_node("b", group=1)
>>> TG.add_node("c")
>>>
>>> tx.get_unique_node_attributes(TG, attr="group")

[0]
>>> tx.get_unique_node_attributes(TG, attr="group", default="unknown")

[0, "unknown"]
Parameters:
  • TG (TemporalGraph) – TemporalGraph object.

  • attr (str) – The node attribute key.

  • default (Any) – The default value to return if the attribute is not found. Returns float('nan') if unset.

Return type:

List[Any]

map_attr_to_edges(TG: TemporalGraph | Graph | None = None, attr: str | dict | list = None, default: Any = nan, index: bool = True) list[source]

Maps attributes to edges in each snapshot.

This function maps attributes to edges in either a static or temporal graph and is similar to get_node_attributes().

Parameters:
  • TG (object) – A TemporalGraph

  • attr (str | dict | list) – The node attribute key, list, or dictionary mapping nodes to attributes.

  • default (Any) – The default value to return if the attribute is not found. Returns float('nan') if unset.

  • index (bool)

Return type:

list

map_attr_to_nodes(TG: TemporalGraph | Graph | None = None, attr: str | dict | list = None, default: Any = nan, index: bool = True) list[source]

Maps attributes to nodes in each snapshot.

This function maps attributes to nodes in either a static or temporal graph and is similar to get_node_attributes().

Parameters:
  • TG (object) – A TemporalGraph or static NetworkX graph object.

  • attr (str | dict | list) – The node attribute key, list, or dictionary mapping nodes to attributes.

  • default (Any) – The default value to return if the attribute is not found. Returns float('nan') if unset.

  • index (bool)

Return type:

list

map_edge_attr_to_nodes(TG: TemporalGraph | Graph, attr: str, default: Any = nan, unique: bool = False) list[source]

Returns node attributes from edge attributes.

For temporal graphs, returns a list of dictionaries, one per snapshot, where each dictionary contains the aggregated edge attribute values for each node.

Example

>>> import networkx_temporal as tx
>>>
>>> TG = tx.temporal_graph(multigraph=False)
>>>
>>> TG.add_node("a", group=0)
>>> TG.add_node("b", group=1)
>>> TG.add_node("c")
>>>
>>> TG.add_edge("a", "b", time=0)
>>> TG.add_edge("b", "c", time=1)
>>>
>>> tx.map_edge_attr_to_nodes(TG, "time")

[{'a': [0], 'b': [0, 1], 'c': [1]}]
Parameters:
  • TG (object) – A TemporalGraph or static NetworkX graph object.

  • attr (str) – The edge attribute key to aggregate.

  • unique (bool) – Whether to discard duplicate attribute values. Default is False.

  • default (Any)

Return type:

list

map_node_attr_to_edges(TG: TemporalGraph | Graph, attr: str, default: Any = nan, origin: Literal['source', 'target', 'both'] = 'source', unique: bool = False) list[source]

Returns edge attributes from node attributes.

For temporal graphs, returns a list of lists, one per snapshot, where each list contains the source or target node attribute value for each edge.

Example

>>> import networkx_temporal as tx
>>>
>>> TG = tx.temporal_graph(multigraph=False)
>>>
>>> TG.add_node("a", group=0)
>>> TG.add_node("b", group=1)
>>> TG.add_node("c")
>>>
>>> TG.add_edge("a", "b", time=0)
>>> TG.add_edge("b", "c", time=1)
>>>
>>> tx.map_node_attr_to_edges(TG, attr="group", default="unknown")

[{('a', 'b'): {'group': 0}, ('b', 'c'): {'group': 1}}]
Parameters:
  • TG (object) – A TemporalGraph or static NetworkX graph object.

  • attr (str) – The node attribute key to aggregate.

  • default (Any) – The default value to return if the attribute is not found. If unset, float('nan') is returned for missing attributes. Passing None (explicitly) will skip edges with missing attributes.

  • origin (Literal['source', 'target', 'both']) – Whether to extract attributes from the 'source' or 'target' node of each edge. If 'both', returns a list with both source and target attributes for each edge.

  • unique (bool)

Return type:

list

map_partitions_to_edges(partitions, edgelist: list = None)[source]

Returns the mapping of edges to partition indices.

Parameters:
  • partitions – List of lists of edges representing the communities.

  • edgelist (list) – List of edges to include in the output mapping. Optional.

map_partitions_to_nodes(partitions, nodelist: list = None)[source]

Returns the mapping of nodes to partition indices.

Parameters:
  • partitions – List of lists of nodes representing the communities.

  • nodelist (list) – List of nodes to include in the output mapping. Optional.

partition_edges(TG: TemporalGraph | Graph | None = None, attr: str | list | dict = None, default: Any = nan, index: bool = True, unique: bool = False) list[source]

Returns lists of edges sharing attribute values.

This function returns a dictionary or list of dictionaries (one per snapshot) in case of temporal graphs, where each key is an attribute and values are the corresponding edges. By default, edges and edges with missing attributes are assigned a float('nan'); if default=None is set instead, edges and edges with missing attributes are skipped.

Example

>>> TG = tx.temporal_graph()
>>>
>>> TG.add_edge("a", "b", time=0)
>>> TG.add_edge("b", "c", time=1)
>>>
>>> TG = TG.slice(attr="time")
>>> print(TG)
>>>
>>> tx.partition_edges(TG, "time")

{0: {('a', 'b')}, 1: {('b', 'c')}}
Parameters:
  • TG (object) – A TemporalGraph or static NetworkX graph object. Required if atr is a string.

  • attr (str | list | dict) – Dictionary, list, or edge attribute key for patitioning. Passing a sequence of lists or dictionaries is accepted for temporal graphs.

  • default (Any) – The default value to return if the attribute is not found. If unset, float('nan') is returned for missing attributes. Passing None (explicitly) will skip edges with missing attributes.

  • index (bool) – Whether to return a dictionary with edges as keys.

  • unique (bool) – Whether edges may figure more than once in each set.

Return type:

list

partition_nodes(TG: TemporalGraph | Graph | None = None, attr: str | list | dict = None, default: Any = nan, index: bool = True, unique: bool = True) list[source]

Returns lists of nodes sharing attribute values.

This function returns a dictionary or list of dictionaries (one per snapshot) in case of temporal graphs, where each key is an attribute and values are the corresponding nodes. By default, nodes and edges with missing attributes are assigned a float('nan'); if default=None is set instead, nodes and edges with missing attributes are skipped.

Example

>>> TG = tx.temporal_graph()
>>>
>>> TG.add_node("a", group=0)
>>> TG.add_node("b", group=1)
>>> TG.add_node("c")
>>>
>>> tx.partition_nodes(TG, "group")

{0: {'a'}, 1: {'b'}, nan: {'c'}}
Parameters:
  • TG (object) – A TemporalGraph or static NetworkX graph object. Required if atr is a string.

  • attr (str | list | dict) – Dictionary, list, or node attribute key for patitioning. Passing a sequence of lists or dictionaries is accepted for temporal graphs.

  • default (Any) – The default value to return if the attribute is not found. If unset, float('nan') is returned for missing attributes. Passing None (explicitly) will skip nodes with missing attributes.

  • index (bool) – Whether to return a dictionary with nodes as keys.

  • unique (bool) – Whether nodes may figure more than once in each set.

Return type:

list

propagate_snapshots(TG: TemporalGraph, method: Literal['ffill', 'bfill'] = 'ffill', delta: int | None = None) TemporalGraph[source]

Propagates nodes and edges across snapshots.

Returns a temporal graph where nodes and edges are preserved among snapshots.

Parameters:
  • TG (object) – A TemporalGraph object.

  • method (Literal['ffill', 'bfill']) –

    The propagation method. Can be either:

    • 'ffill': propagates nodes and edges forward in time (from earlier to later snapshots);

    • 'bfill': propagates nodes and edges backward in time (from later to earlier snapshots).

  • delta (int | None) – The number of snapshots to propagate over. If None (default), propagates over all snapshots.

Return type:

TemporalGraph

temporal_edge_matrix(TG: TemporalGraph, method: Literal['jaccard', 'union', 'intersect', 'geometric'] = 'jaccard', na_diag: bool = False) List[list][source]

Returns matrix of edge overlap over time.

See also

The Examples → Explore → Temporal edge matrix page for an example.

Example

Loading and computing similarity among edge sets from the example_sbm_graph() dataset:

>>> import networkx_temporal as tx
>>>
>>> TG = tx.example_sbm_graph()
>>> tx.temporal_edge_matrix(TG, method="jaccard")

[[1.0,  0.11, 0.11],
 [0.11, 1.0,  0.08],
 [0.11, 0.08, 1.0 ]]
Parameters:
  • TG (object) – A TemporalGraph object.

  • method (Literal['jaccard', 'union', 'intersect', 'geometric']) –

    Measure to consider. Default is 'jaccard'. Available choices:

    • 'jaccard': Jaccard similarity (intersection over union);

    • 'intersect': intersection over size of first set;

    • 'union': union over size of first set;

    • 'geometric': geometric mean of set overlaps.

    • 'dice': Dice coefficient (2 * intersection over sum of sizes).

  • na_diag (bool) – If True, sets diagonal values to None.

Return type:

List[list]

temporal_node_matrix(TG: TemporalGraph, method: Literal['jaccard', 'union', 'intersect', 'geometric'] = 'jaccard', na_diag: bool = False) List[list][source]

Returns matrix of node overlap over time.

Example

Loading and computing similarity among node sets from the example_sbm_graph() dataset:

>>> import networkx_temporal as tx
>>>
>>> TG = tx.example_sbm_graph()
>>> tx.temporal_node_matrix(TG, method="jaccard")

[[1.0,  1.0,  0.99],
 [1.0,  1.0,  0.99],
 [0.99, 0.99, 1.0 ]]
Parameters:
  • TG (object) – A TemporalGraph object.

  • method (Literal['jaccard', 'union', 'intersect', 'geometric']) –

    Measure to consider. Default is 'jaccard'. Available choices:

    • 'jaccard': Jaccard similarity coefficient;

    • 'intersect': intersection over size of first set;

    • 'union': union over size of first set;

    • 'geometric': geometric mean of set overlaps.

    • 'dice': Dice coefficient (2 * intersection over sum of sizes).

  • na_diag (bool) – If True, sets diagonal values to None.

Return type:

List[list]

Functions - Converters

convert(G: Graph | TemporalGraph | list, to: Literal['dgl', 'dynetx', 'graph_tool', 'igraph', 'networkit', 'numpy', 'scipy', 'snap', 'stellargraph', 'torch_geometric', 'teneto'], *args, **kwargs) Any[source]

High-level conversion function to other libraries. Calls the appropriate function based on the received to parameter. The following libraries are currently supported for conversion:

Format

Parameter (Package)

Calls (Function)

Deep Graph Library

'dgl'

to_dgl()

DyNetX

'dynetx'

to_dynetx()

graph-tool

'graph_tool'

to_graph_tool()

igraph

'igraph'

to_igraph()

NetworKit

'networkit'

to_networkit()

NumPy

'numpy'

to_numpy()

PyTorch Geometric

'torch_geometric'

to_torch_geometric()

SciPy

'scipy'

to_scipy()

SNAP

'snap'

to_snap()

StellarGraph

'stellargraph'

to_stellargraph()

Teneto

'teneto'

to_teneto()

Note

To reduce package dependencies and avoid unnecessary imports, the required library is imported on function call based on the to parameter and must be separately installed.

Example

Convert the Karate Club dataset from NetworkX into a PyTorch Geometric Data object:

>>> import networkx as nx
>>> import networkx_temporal as tx
>>>
>>> G = nx.karate_club_graph()
>>> data = tx.convert(G, "torch_geometric")
>>>
>>> print(G)
>>> print(data)

Graph named "Zachary's Karate Club" with 34 nodes and 78 edges
Data(edge_index=[2, 156], club=[34], weight=[156], name='Zachary's Karate Club', num_nodes=34)
Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • to (str) – Package name or alias to convert the graph object.

  • args – Additional positional arguments for the conversion function.

  • kwargs – Additional keyword arguments for the conversion function.

Return type:

Any

Note:

Available both as a function and as a method from TemporalGraph objects.

to_dgl(G: Graph | TemporalGraph | list, *args, **kwargs)[source]

Convert from NetworkX to Deep Graph Library.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • args – Positional arguments.

  • kwargs – Keyword arguments.

Return type:

dgl.DGLGraph

Note:

Wrapper function for dgl.from_networkx.

to_dynetx(G: Graph | TemporalGraph | list, attr: str | None = None, **kwargs)[source]

Convert from NetworkX to DyNetX.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • attr (str | None) – Attribute name for the temporal edges. Optional.

  • kwargs – Keyword arguments for the DyNetX graph object.

Return type:

dynetx.DynGraph

to_graph_tool(G: Graph | TemporalGraph | list, index: str = 'id', encoding: str = 'ascii', errors: str = 'strict')[source]

Convert from NetworkX to graph-tool.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • index (str) – Property name to use as the node identifier. Default is 'id'.

  • encoding (str) – Encoding to use for string conversion. Default is 'ascii'.

  • errors (str) – Error handler for string conversion. Default is 'strict'.

Return type:

graph_tool.Graph

Note:

Original implementation by bbengfort (GitHub).

to_igraph(G: Graph | TemporalGraph | list, *args, **kwargs)[source]

Convert from NetworkX to igraph.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • args – Positional arguments.

  • kwargs – Keyword arguments.

Return type:

igraph.Graph

Note:

Wrapper function for igraph.Graph.from_networkx.

to_networkit(G: Graph | TemporalGraph | list, *args, **kwargs)[source]

Convert from NetworkX to Networkit.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • args – Positional arguments.

  • kwargs – Keyword arguments.

Return type:

networkit.Graph

Note:

Wrapper function for networkit.nxadapter.nx2nk.

to_numpy(G: Graph | TemporalGraph, supra: bool = False, **kwargs) ndarray[source]

Convert from NetworkX to a dense NumPy adjacency matrix.

If a single static graph is provided, returns a 2D NumPy array representing the adjacency matrix of the graph. If a temporal graph or a list of static graphs is provided, returns a 3D NumPy array where each slice along the first dimension corresponds to the adjacency matrix of a snapshot.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • supra (bool) – If True and a temporal graph is provided, returns the supra-adjacency matrix of the temporal graph instead of a stack of adjacency matrices for each snapshot. Default: False.

  • kwargs – Additional keyword arguments passed to networkx.to_numpy_array().

Return type:

ndarray

to_scipy(G: Graph | TemporalGraph, supra: bool = False, nodelist: list = None, dtype: Any = None, weight: str | None = 'weight', format: str = 'csr') csr_array[source]

Convert from NetworkX to a sparse SciPy adjacency matrix.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • supra (bool) – If True and a temporal graph is provided, returns the supra-adjacency matrix of the temporal graph instead of a stack of adjacency matrices for each snapshot. Default: False.

  • nodelist (list) – List of nodes specifying the order of the rows and columns in the resulting adjacency matrix. If None, the order is list(G.nodes()).

  • dtype (Any) – Data type of the resulting adjacency matrix. If None, the type is inferred.

  • weight (str | None) – The edge attribute key used to compute edge weights (default: 'weight'). If None, all edge weights are considered as 1.

  • format (str) – The sparse matrix format of the resulting adjacency matrix. Accepts 'csr' (compressed sparse row), 'csc' (compressed sparse column), 'dok' (dictionary of keys), or 'lil' (list of lists). Default is 'csr'.

Return type:

csr_array

to_snap(G: Graph | TemporalGraph | list, node_id: str | None = 'id', node_attrs: bool | list | None = True, edge_attrs: bool | list | None = True)[source]

Convert from NetworkX to SNAP.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • node_id (str | None) – Attribute key to use as node identifier. Optional. Default is 'id'.

  • node_attrs (bool | list | None) – Boolean or list of node attributes to include in the conversion. Optional. Default is True.

  • edge_attrs (bool | list | None) – Boolean or list of edge attributes to include in the conversion. Optional. Default is True.

Return type:

snap.TGraph

to_stellargraph(G: Graph | TemporalGraph | list, *args, **kwargs)[source]

Convert from NetworkX to StellarGraph.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • args – Positional arguments.

  • kwargs – Keyword arguments.

Return type:

stellargraph.StellarGraph

Note:

Wrapper function for stellargraph.StellarGraph.from_networkx.

to_teneto(G: Graph | TemporalGraph | list, attr: str = 'time')[source]

Convert from NetworkX to Teneto.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • attr (str) – Attribute name for the temporal edges. Default is 'time'.

Return type:

teneto.TemporalNetwork

to_torch_geometric(G: Graph | TemporalGraph | list, *args, **kwargs)[source]

Convert from NetworkX to PyTorch Geometric.

Parameters:
  • G (object) – Graph object. Accepts a TemporalGraph, a single static NetworkX graph, or a list of static NetworkX graphs as input.

  • args – Positional arguments.

  • kwargs – Keyword arguments.

Return type:

torch_geometric.data.Data

Note:

Wrapper function for torch_geometric.utils.from_networkx.