networkx_temporal.classes

Classes and functions for temporal graph objects.

Classes - Summary

TemporalGraph(*args[, backend])

Creates a temporal undirected graph.

TemporalDiGraph(*args[, backend])

Creates a temporal directed graph.

TemporalMultiGraph(*args[, backend])

Creates a temporal undirected multigraph.

TemporalMultiDiGraph(*args[, backend])

Creates a temporal directed multigraph.

TemporalABC(t, create_using)

Abstract base class for temporal graphs.

Factory Functions - Summary

temporal_graph([t, directed, multigraph, ...])

Creates a temporal graph with the desired properties.

empty_graph([directed, multigraph, create_using])

Returns a temporal graph without any initialized snapshots.

Functions - Summary

all_neighbors(TG, node)

Returns iterator of all node neighbors in each snapshot.

compose(G1, G2)

Returns the union of two graphs.

compose_all(graphs)

Returns the union of multiple graphs.

from_multigraph(G)

Returns a graph from a multigraph object.

is_frozen(TG)

Returns True if graph is frozen.

is_static_graph(obj)

Returns True if object is a static graph.

is_temporal_graph(obj)

Returns True if object is a temporal graph.

is_unrolled_graph(UTG)

Returns True if static graph is an unrolled temporal graph.

neighbors(TG, node)

Returns iterator of node neighbors in each snapshot.

relabel_nodes(G, mapping[, copy])

Relabels nodes of a graph according to a given mapping.

to_multigraph(G)

Returns a multigraph from a graph object.

Classes

class TemporalGraph(*args, backend=None, **kwargs)[source]

Creates a temporal undirected graph. Does not allow parallel edges among node pairs.

It inherits a static NetworkX Graph and includes all methods available from it, such as add_node(), add_edge(), neighbors(), subgraph(), to_directed(), and to_undirected(), as well as additional methods implemented for handling temporal graphs and snapshots.

This is equivalent to calling temporal_graph() with directed=False and multigraph=False.

Hint

Setting t as greater than 1 initializes a list of NetworkX graph objects, each representing a snapshot in time. Unless dynamic node attributes are required, it is recommended to use the slice() method instead, allowing to create less resource-demanding graph views on the fly.

Example

The following example demonstrates how to create a temporal graph with two snapshots:

>>> import networkx_temporal as tx
>>>
>>> TG = tx.TemporalGraph(t=2)
>>>
>>> TG[0].add_edge("a", "b")
>>> TG[1].add_edge("c", "b")
>>>
>>> print(TG)

TemporalGraph (t=2) with 4 nodes and 2 edges

See also

Parameters:

t (int) – Number of temporal graphs to initialize. Optional. Default is 1.

Note:

Documentation on inherited methods is available only if networkx>=2.8.1.

add_snapshot(G: Graph = None) Graph

Adds a snapshot to the temporal graph.

If G is None, adds an empty graph with the same properties as the temporal graph. Returns the added snapshot (i.e., the parameter G if not None, or an empty graph).

Parameters:

G (Graph) – NetworkX graph object to add as snapshot.

Return type:

Graph

add_snapshots_from(graphs: List[Graph]) None

Adds multiple snapshots to the temporal graph.

Parameters:

graphs (List[Graph]) – List of NetworkX graph objects to add as snapshots.

Return type:

None

append(G: Graph | None = None) None

Adds a new snapshot G to the temporal graph. If unset, adds an empty graph.

Parameters:

G (Graph | None) – NetworkX graph object to append. Optional.

Return type:

None

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

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.

edge(*edge) List[str] | None

Returns a dictionary mapping each edge to their temporal attributes, with snapshot indices as keys and dictionaries as values.

Return type:

List[str] | None

flatten() TemporalGraph

Returns ‘’flattened’’ version of temporal graph. Equivalent to slice() with bins=1.

This method differs from to_static() only in the sense that it returns a TemporalGraph object with a single snapshot, rather than a static NetworkX graph object (i.e., the snapshot).

Attention

As each node in a flattened graph is unique, dynamic node attributes are not preserved. Parallel edges from different snapshots are also not preserved, except for multigraphs.

Return type:

TemporalGraph

from_multigraph() TemporalGraph | Graph

Returns a graph from a multigraph object.

Parallel (multiple) edges among nodes are converted to single edges, with a weight attribute storing their total occurrences. If the attribute exists, their total sum is stored instead.

Attention

Converting a multigraph to a graph object may result in data loss: multiple pairwise edges are merged, with later attributes other than weight taking precedence over earlier ones,

Example

Converting a static multigraph to a graph, summing the weights of parallel edges:

>>> import networkx as nx
>>> from networkx_temporal import from_multigraph
>>>
>>> G = nx.MultiGraph()
>>> G.add_edge(1, 2, weight=2)
>>> G.add_edge(1, 2, weight=3)
>>>
>>> H = from_multigraph(G)
>>> print(H.edges(data=True))

[(1, 2, {'weight': 5})]
Parameters:

G (object) – TemporalGraph or static NetworkX graph object.

Return type:

TemporalGraph | Graph

get_node_data(node: Any) list

Returns a list of all attributes for a given node across all snapshots.

Parameters:

node (Any) – Node to get data for.

Return type:

list

property graph: dict

The graph property of the temporal graph.

Getter:

Returns temporal graph dictionary.

Return type:

dict

property graphs: list

The graphs property of the temporal graph.

Getter:

Returns temporal graph data.

Setter:

Sets temporal graph data. Accepts a list, tuple, or dictionary of NetworkX graphs. Passing a dictionary will set the names property to its keys.

Return type:

list

index_edge(edge: tuple, interval: range | None = None) list

Returns index of all snapshots in which an edge is present.

Parameters:
  • edge (tuple) – Edge to look for.

  • interval (range | None) – Range to consider. Optional. Defaults to all snapshots.

Return type:

list

index_node(node: Any, interval: range | None = None) list

Returns index of all snapshots in which a node is present.

Parameters:
  • node (Any) – Node to look for.

  • interval (range | None) – Range to consider. Optional. Defaults to all snapshots.

Return type:

list

index_snapshot(snapshot: Graph, interval: range | None = None) list

Returns index of all occurrences of a given snapshot.

Parameters:
  • snapshot (Graph) – Snapshot (NetworkX graph) to look for.

  • interval (range | None) – Range to consider. Optional. Defaults to all snapshots.

Return type:

list

insert(index: int, G: Graph | None = None) None

Inserts a new snapshot to the temporal graph at a given index.

Parameters:
  • index (int) – Insert graph object before index.

  • G (Graph | None) – NetworkX graph object to insert. Optional.

Return type:

None

is_directed() bool

Returns True if the temporal graph is directed.

Return type:

bool

is_multigraph() bool

Returns True if the temporal graph is a multigraph.

Return type:

bool

items() list

Returns list of snapshot name and graph pairs.

Note:

Returns pairs of names() and graphs().

Return type:

list

keys() list

Returns list of snapshot names.

Note:

Alias to names().

Return type:

list

property name: str

The name property of the temporal graph.

Getter:

Returns temporal graph name.

Setter:

Sets temporal graph name.

Return type:

str

property names: list

The names property of the temporal graph. Used to store intervals as strings on slice().

Getter:

Returns names of temporal graph snapshots.

Setter:

Sets names of temporal graph snapshots.

Return type:

list

new_snapshot() Graph

Returns a new empty snapshot of the same type as the temporal graph.

Return type:

Graph

node(node) List[str] | None

Returns a dictionary mapping each node to their temporal attributes, with snapshot indices as keys and dictionaries as values.

Return type:

List[str] | None

number_of_edges(copies: bool | None = None) int

Returns number of edges in the temporal graph.

Parameters:

copies (bool | None) – If True, consider multiple instances of the same edge in different snapshots. If False, consider unique edges. Optional.

Note:

Alias to size().

Return type:

int

number_of_neighbors(node: Any) list

Returns number of neighbors for each snapshot.

Parameters:

node (Any) – Node to get number of neighbors for.

Return type:

list

number_of_nodes(copies: bool | None = None) int

Returns number of nodes in the temporal graph.

Parameters:

copies (bool | None) – If True, consider multiple instances of the same node in different snapshots. If False, consider unique nodes. Optional.

Note:

Alias to order().

Return type:

int

number_of_snapshots() int

Returns number of elements stored in graphs().

Note:

Alias to __len__().

Return type:

int

order(copies: bool | None = None) int

Returns number of nodes in the temporal graph.

Parameters:

copies (bool | None) – If True, consider multiple instances of the same node in different snapshots. If False, consider unique nodes. Optional.

Return type:

int

pop(index: int | None = None) Graph

Removes and returns graph snapshot at index (default: last snapshot).

Parameters:

index (int | None) – Index of snapshot. Default: last snapshot.

Return type:

Graph

remove_snapshot(G: Graph) None

Removes first occurrence of snapshot G (a NetworkX graph) from the temporal graph.

Parameters:

G (Graph) – NetworkX graph object to remove.

Return type:

None

size(copies: bool | None = None) int

Returns number of edges in the temporal graph.

Parameters:

copies (bool | None) – If True, consider multiple instances of the same edge in different snapshots. If False, consider unique edges. Optional.

Return type:

int

slice(bins: int | None = None, attr: str | list | dict | DataFrame | Series | None = None, level: Literal['edge', 'node', 'source', 'target'] | None = None, axis: int = 0, qcut: bool = False, duplicates: Literal['raise', 'drop'] = 'raise', rank_first: bool | None = None, sort: bool = True, names: bool = True, as_view: bool = True, fillna: Any | None = None, apply_func: Callable[[...], Any] | None = None) TemporalGraph

Slices temporal graph into snapshots, returning a new temporal graph object.

All node interactions are preserved when using this method. Note that the returned object may contain temporal node copies, if they interact with other nodes in different intervals.

If attr is unset, the method will consider the order of appearance of edges or nodes, i.e., rank_first=True. If attr is set and bins is unset, the method will create as many snapshots as unique values found in the specified node- or edge-level attr attribute data. Alternatively, a list of 2-tuple intervals may be provided with custom time windows.

Hint

By default, views of the original graph are returned to avoid memory overhead. If the resulting snapshots need to be modified, set as_view=False to return copies instead.

Example

Slicing a temporal graph into two snapshots based on the edge-level time attribute:

>>> import networkx_temporal as tx
>>>
>>> TG = tx.TemporalGraph()
>>>
>>> TG.add_edge("a", "b", time=0)
>>> TG.add_edge("c", "b", time=1)
>>>
>>> TG = TG.slice(attr="time")
>>> print(TG)

TemporalGraph (t=2) with 3 nodes and 2 edges

Calling this method from the returned object, now with bins=1, will flatten() the graph:

>>> TG = TG.slice(bins=1)
>>> print(TG)

TemporalGraph (t=1) with 3 nodes and 2 edges

Note that a TemporalMultiGraph or TemporalMultiDiGraph object is required to store multiple edges among pairs and allow many interactions between the same nodes.

See also

The Examples → Basic Operations → Slice temporal graph page for more examples.

Parameters:
  • bins (int | None) – Number of snapshots (slices) to return. If unset, corresponds to the number of unique attribute values defined by attr. Required only if attr is unset, otherwise optional.

  • attr (str | list | dict | DataFrame | Series | None) – Node- or edge-level attribute to consider as temporal data. If unset, the method will consider the order of appearance of edges or nodes (rank_first=True).

  • level (str) –

    Whether to consider node- or edge-level data for slicing. Required if attr is a string. Defaults to 'edge' if unset. Choices:

    • 'edge': Edge-level temporal slice. This is the default.

    • 'node': Node-level temporal slice. Alias for 'source'.

    • 'source': Node-level slice with temporality defined by the source node (pairwise interaction time defined by the source node attr).

    • 'target': Node-level slice with temporality defined by the target node (pairwise interaction time defined by the target node attr).

  • axis (int) – Whether bins should be created by time intervals (0) or by number of nodes/edges (1). Default is 0.

  • qcut (bool) – If True, applies quantile-based discretization for snapshots. Only has an effect if attr is set. Default is False.

  • duplicates (str) – Control whether slices containing duplicates raise an error. Accepts 'drop' or 'raise'. Default is 'raise'.

  • rank_first (bool | None) – If True, applies rank-based sort by order of appearance of edges, nodes, or an attribute. Automatically set as True if both attr and rank_first are unset, otherwise False.

  • sort (bool) – If True, sort unique temporal values after slicing. Only applies to categorical temporal data. Default is True.

  • as_view (bool) – If False, returns copies instead of views of the original graph. Default is True.

  • fillna (Any | None) – Value to fill null values in attribute data.

  • apply_func (Callable) – Function to apply to temporal attribute values.

  • self (TemporalGraph)

  • names (bool)

Return type:

TemporalGraph

snapshots() list

Returns list of snapshots in the temporal graph.

Note:

Alias to graphs().

Return type:

list

property t: int

The t property of the temporal graph.

Returns number of snapshots. Implemented for cohesiveness with __str__ representation.

Getter:

Returns number of snapshots.

Return type:

int

Note:

Alias to __len__().

temporal_degree(nbunch: Any | None = None, weight: str | None = None) dict | int

Returns node degrees. Defined [1] for temporal graphs as the degree sum over time:

\[\text{deg}(i) = \sum_{G \in \mathcal{G}} \sum_{j \in \mathcal{N}(i)} \mathbf{A}_{ij} + \mathbf{A}_{ji},\]

where \(i\) is a node, \(j\) is a node in the neighborhood \(\mathcal{N}(i)\), \(G\) is a snapshot in the temporal graph \(\mathcal{G}\), and \(\mathbf{A}\) is the adjacency matrix, optionally weighted by an edge-level weight attribute. For multigraphs, adjacencies are weighted by the number of parallel edges, unless weight=False.

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

  • nbunch (Any | None) – One or more nodes to return. Optional.

  • weight (str | None) – Edge attribute key to consider. Optional.

Note:

Aliases: degree() and total_degree().

Return type:

dict | int

temporal_edges(copies: bool | None = None, *args, **kwargs) list | dict

Returns sequence of edges (interactions) in all snapshots.

Parameters:
  • copies (bool | None) – If True, consider multiple instances of the same edge in different snapshots. Default is True.

  • args – Additional arguments to pass to the NetworkX graph method.

  • kwargs – Additional keyword arguments to pass to the NetworkX graph method.

Return type:

list | dict

temporal_in_degree(nbunch: Any | None = None, weight: str | None = None) dict | int

Returns node in-degrees. Defined [1] for temporal graphs as the in-degree sum over time:

\[\text{deg}_{\text{in}}(i) = \sum_{G \in \mathcal{G}} \sum_{j \in \mathcal{N}(i)} \mathbf{A}_{ji},\]

where \(i\) is a node, \(j\) is a node in the neighborhood \(\mathcal{N}(i)\), \(G\) is a snapshot in the temporal graph \(\mathcal{G}\), and \(\mathbf{A}\) is the adjacency matrix, optionally weighted by an edge-level weight attribute. For multigraphs, adjacencies are weighted by the number of parallel edges, unless weight=False.

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

  • nbunch (Any | None) – One or more nodes to return. Optional.

  • weight (str | None) – Edge attribute key to consider. Optional.

Note:

Aliases: in_degree() and total_in_degree().

Return type:

dict | int

temporal_neighbors(node: Any) list

Returns single list of neighbors for a given node across all snapshots.

Parameters:

node (Any) – Node to get neighbors for.

Return type:

list

temporal_nodes(copies: bool | None = None, *args, **kwargs) dict | list

Returns sequence of nodes in all snapshots.

Parameters:
  • copies (bool | None) – If True, consider multiple instances of the same node in different snapshots. Default is False.

  • args – Additional arguments to pass to the NetworkX graph method.

  • kwargs – Additional keyword arguments to pass to the NetworkX graph method.

Return type:

dict | list

temporal_order() int

Return number of unique nodes. Equivalent to order() with copies=False.

See also

The total_order() method for the sum of the number of nodes in all snapshots.

Return type:

int

temporal_out_degree(nbunch: Any | None = None, weight: str | None = None) dict | int

Returns node out-degrees. Defined [1] for temporal graphs as the out-degree sum over time:

\[\text{deg}_{\text{out}}(i) = \sum_{G \in \mathcal{G}} \sum_{j \in \mathcal{N}(i)} \mathbf{A}_{ij},\]

where \(i\) is a node, \(j\) is a node in the neighborhood \(\mathcal{N}(i)\), \(G\) is a snapshot in the temporal graph \(\mathcal{G}\), and \(\mathbf{A}\) is the adjacency matrix, optionally weighted by an edge-level weight attribute. For multigraphs, adjacencies are weighted by the number of parallel edges, unless weight=False.

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

  • nbunch (Any | None) – One or more nodes to return. Optional.

  • weight (str | None) – Edge attribute key to consider. Optional.

Note:

Aliases: out_degree() and total_out_degree().

Return type:

dict | int

temporal_size() int

Return number of unique edges. Equivalent to size() with copies=False.

See also

The total_order() method for the sum of the number of edges in all snapshots.

Return type:

int

to_events(delta: Literal['int', 'float'] | None = None, attr: str | None = None) list

Returns a list of edge-level events.

  • 3-tuples (\(u, v, t\)), where elements are the source node, target node, and time attribute;

  • 4-tuples (\(u, v, t, \delta\)), where \(\delta\) is either an integer for edge addition (1) or deletion (-1) event, or a float defining the duration of the interaction (zero for a single snapshot).

Attention

As events are edge-based, node isolates without self-loops are not preserved.

Parameters:
  • TG (TemporalGraph) – Temporal graph object.

  • delta (Literal['int', 'float'] | None) –

    Defines which additional parameter \(\delta\) should be returned.

    • If None, returns events as 3-tuples. Default.

    • If 'int', returns events as 4-tuples with an additional parameter representing edge addition (1) or deletion (-1) events.

    • If 'float', returns events as 4-tuples with an additional parameter representing the duration of the pairwise interaction.

  • attr (str | None) – Edge attribute to consider when delta is 'float'. If provided, the attribute value is used for delta instead of the time difference between the start and end of the interaction.

Note:

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

Return type:

list

to_multigraph() TemporalGraph | Graph

Returns a multigraph from a graph object. SImilar to The from_multigraph().

A multigraph is a graph that allows multiple (parallel) edges between pairwise nodes.

Attention

This function does not duplicate edges with a weight attribute larger than one, but simply converts the graph to a multigraph format, allowing for parallel edges to be added.

Parameters:

G (object) – TemporalGraph or static NetworkX graph object.

Return type:

TemporalGraph | Graph

to_snapshots(to: Literal['dgl', 'dynetx', 'graph_tool', 'igraph', 'networkit', 'numpy', 'scipy', 'snap', 'stellargraph', 'torch_geometric', 'teneto'] | None = None, as_view: bool = True) list

Returns a list of snapshots. Each snapshot is a view of the original graph, which can be converted to a different format using the to argument, if desired.

Note

Internally, TemporalGraph already stores data as a list of graph views on slice(). This method simply returns the underlying data, unless convert() is called by setting to.

Parameters:
  • TG (TemporalGraph) – Temporal graph object.

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

  • as_view (bool) – If False, returns copies instead of views of the original graph. Default is True.

Note:

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

Return type:

list

to_static(to: Literal['dgl', 'dynetx', 'graph_tool', 'igraph', 'networkit', 'numpy', 'scipy', 'snap', 'stellargraph', 'torch_geometric', 'teneto'] | None = None, directed: bool | None = None, multigraph: bool | None = None, index: str | None = None) Graph

Returns a static graph object.

A static graph is a single object that contains all the nodes and edges of the temporal graph. If directed and multigraph are unset, the returned graph type will match that of the temporal graph. Specifying attr allows to store the time of interaction as an edge attribute.

Attention

As each node in a static graph is unique, dynamic node attributes are not preserved.

See also

The to_unrolled() method for a static representation allowing dynamic node attributes.

Parameters:
  • TG (TemporalGraph) – Temporal graph object.

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

  • directed (bool | None) – If True, returns a DiGraph. Optional.

  • multigraph (bool | None) – If True, returns a MultiGraph. Optional.

  • index (str | None) – Edge attribute to store snapshot index. Optional.

Note:

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

Return type:

Graph

to_unrolled(to: Literal['dgl', 'dynetx', 'graph_tool', 'igraph', 'networkit', 'numpy', 'scipy', 'snap', 'stellargraph', 'torch_geometric', 'teneto'] | None = None, delta: int | str | None = 0, edge_couplings: bool = True, node_copies: Literal['all', 'fill', 'persist'] | None = None, node_index: list | None = None) Graph

Returns an unrolled temporal graph.

An unrolled temporal graph is a single graph containing all nodes and edges in all snapshots, plus time-adjacent node copies and edge couplings which connect these copies.

If delta is set, edges are added between temporal nodes in sequential time steps, \((u_{t}, v_{t+\delta})\), resulting in time series representations [0] of temporal networks.

Parameters:
  • TG (TemporalGraph) – Temporal graph object.

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

  • delta (int | str | None) – Time step between temporal nodes. Accepts an integer or a string with the edge-level attribute key name. Default: 0.

  • edge_couplings (bool) – Add inter-slice edges among temporal nodes. Default: True.

  • node_copies (Literal['all', 'fill', 'persist'] | None) –

    Control inter-slice couplings among temporal node copies. Optional.

    • 'all': add temporal node copies to all snapshots.

    • 'persist': add temporal node copies to all future snapshots.

    • 'fill': add temporal node copies in between snapshots.

  • node_index (list | None) – Store node index from static graph as node-level attribute 'node_index'. Optional.

Note:

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

Return type:

Graph

total_order() int

Return sum of nodes from all snapshots. Equivalent to order() with copies=True.

See also

The temporal_order() method for the number of unique nodes in the temporal graph.

Return type:

int

total_size() int

Return sum of edges from all snapshots. Equivalent to size() with copies=True.

See also

The temporal_size() method for the number of unique edges in the temporal graph.

Return type:

int

values() list

Returns list of snapshot graphs.

Note:

Alias to graphs().

Return type:

list

class TemporalDiGraph(*args, backend=None, **kwargs)[source]

Creates a temporal directed graph. Does not allow parallel edges among node pairs.

It inherits a static NetworkX DiGraph and includes all methods available from it, such as add_node(), add_edge(), neighbors(), subgraph(), to_directed(), and to_undirected(), as well as additional methods implemented for handling temporal graphs and snapshots.

This is equivalent to calling temporal_graph() with directed=True and multigraph=False.

See also

The TemporalGraph class documentation for details on its implemented methods.

Parameters:

t (int) – Number of temporal graphs to initialize. Optional. Default is 1.

Note:

Documentation on inherited methods is available only if networkx>=2.8.1.

class TemporalMultiGraph(*args, backend=None, **kwargs)[source]

Creates a temporal undirected multigraph. Allows parallel edges among the same pair of nodes.

It inherits a static NetworkX MultiGraph and includes all methods available from it, such as add_node(), add_edge(), neighbors(), subgraph(), to_directed(), and to_undirected(), as well as additional methods implemented for handling temporal graphs and snapshots.

This is equivalent to calling temporal_graph() with directed=False and multigraph=True.

See also

The TemporalGraph class documentation for details on its implemented methods.

Parameters:

t (int) – Number of temporal graphs to initialize. Optional. Default is 1.

Note:

Documentation on inherited methods is available only if networkx>=2.8.1.

class TemporalMultiDiGraph(*args, backend=None, **kwargs)[source]

Creates a temporal directed multigraph. Allows parallel edges among the same pair of nodes.

It inherits a static NetworkX MultiDiGraph and includes all methods available from it, such as add_node(), add_edge(), neighbors(), subgraph(), to_directed(), and to_undirected(), as well as additional methods implemented for handling temporal graphs and snapshots.

This is equivalent to calling temporal_graph() with directed=True and multigraph=True.

See also

The TemporalGraph class documentation for details on its implemented methods.

Parameters:

t (int) – Number of temporal graphs to initialize. Optional. Default is 1.

Note:

Documentation on inherited methods is available only if networkx>=2.8.1.

class TemporalABC(t: int, create_using: Graph)[source]

Abstract base class for temporal graphs.

This class is not meant to be instantiated directly, but rather inherited by the classes TemporalGraph, TemporalDiGraph, TemporalMultiGraph, and TemporalMultiDiGraph.

Parameters:
  • t (int)

  • create_using (Graph)

Functions

all_neighbors(TG: TemporalGraph, node: Any) iter[source]

Returns iterator of all node neighbors in each snapshot. Does not consider edge direction.

Parameters:
Note:

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

Return type:

iter

compose(G1: TemporalGraph | Graph, G2: TemporalGraph | Graph) TemporalGraph | Graph[source]

Returns the union of two graphs. For temporal graphs, the snapshots of each graph are concatenated in order, so that the resulting object contains all input graph snapshots.

Parameters:
Return type:

TemporalGraph | Graph

compose_all(graphs: List[TemporalGraph] | List[Graph]) TemporalGraph | Graph[source]

Returns the union of multiple graphs. For temporal graphs, the snapshots of each graph are concatenated in order, so that the resulting object contains all input graph snapshots.

Parameters:

graphs (object) – A list of TemporalGraph or static NetworkX graph objects.

Return type:

TemporalGraph | Graph

create_empty_copy(G: Graph | TemporalGraph) TemporalGraph | Graph[source]

Returns a copy of the input graph structure without edge data.

Parameters:

G (object) – TemporalGraph or static NetworkX graph object.

Return type:

TemporalGraph | Graph

empty_graph(directed: bool = None, multigraph: bool = None, create_using: TemporalGraph | Graph | None = None) TemporalGraph[source]

Returns a temporal graph without any initialized snapshots.

This function is a wrapper around temporal_graph(), setting t=0.

Example

Creating an empty temporal directed multigraph, without snapshots:

>>> import networkx_temporal as tx
>>>
>>> TG = tx.empty_graph(directed=True, multigraph=True)
>>> print(TG)

TemporalMultiDiGraph (t=0) with 0 nodes and 0 edges
Parameters:
  • directed (bool) – If True, inherits a DiGraph. Defaults to False.

  • multigraph (bool) – If True, inherits a MultiGraph. Defaults to True.

  • create_using (object) – NetworkX or TemporalGraph to use as template. Optional. Does not allow setting directed and multigraph if passed.

Return type:

TemporalGraph

from_multigraph(G: Graph | TemporalGraph) TemporalGraph | Graph[source]

Returns a graph from a multigraph object.

Parallel (multiple) edges among nodes are converted to single edges, with a weight attribute storing their total occurrences. If the attribute exists, their total sum is stored instead.

Attention

Converting a multigraph to a graph object may result in data loss: multiple pairwise edges are merged, with later attributes other than weight taking precedence over earlier ones,

Example

Converting a static multigraph to a graph, summing the weights of parallel edges:

>>> import networkx as nx
>>> from networkx_temporal import from_multigraph
>>>
>>> G = nx.MultiGraph()
>>> G.add_edge(1, 2, weight=2)
>>> G.add_edge(1, 2, weight=3)
>>>
>>> H = from_multigraph(G)
>>> print(H.edges(data=True))

[(1, 2, {'weight': 5})]
Parameters:

G (object) – TemporalGraph or static NetworkX graph object.

Return type:

TemporalGraph | Graph

is_frozen(TG: TemporalGraph | Graph) bool[source]

Returns True if graph is frozen.

A frozen graph is immutable, meaning that nodes and edges cannot be added or removed. Calling copy on a frozen graph returns a (mutable) deep copy of the graph object.

Parameters:

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

Return type:

bool

is_static_graph(obj: Any) bool[source]

Returns True if object is a static graph.

Matches any of: NetworkX Graph, DiGraph, MultiGraph, MultiDiGraph.

Parameters:

obj (Any) – Object to check.

Return type:

bool

is_temporal_graph(obj: Any) bool[source]

Returns True if object is a temporal graph.

Matches any of: TemporalGraph, TemporalDiGraph, TemporalMultiGraph, TemporalMultiDiGraph.

Parameters:

obj (Any) – Object to check.

Return type:

bool

is_unrolled_graph(UTG: Graph) bool[source]

Returns True if static graph is an unrolled temporal graph.

Unrolled graphs are a static representation of temporal networks, where each node is suffixed with its temporal index (e.g., 'a_0') and inter-slice edges are added to connect copies of the same node at different time steps (e.g., 'a_0' and 'a_1').

Parameters:

UTG (object) – Static graph object.

Return type:

bool

neighbors(TG: TemporalGraph, node: Any) iter[source]

Returns iterator of node neighbors in each snapshot. Considers edge direction.

Parameters:
Note:

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

Return type:

iter

relabel_nodes(G: Graph | TemporalGraph, mapping: dict | list, copy: bool = True) Graph | TemporalGraph[source]

Relabels nodes of a graph according to a given mapping.

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

  • mapping (dict | list) – A dictionary or list defining the node relabeling.

  • copy (bool) – Whether to return a new graph object (default) or modify the input graph in place.

Return type:

Graph | TemporalGraph

set_edge_attributes(G: Graph | TemporalGraph, values: Any, name: str) TemporalGraph | Graph[source]

Sets edge attributes for a graph.

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

  • name (str) – The edge attribute key.

  • values (Any) – Edge attribute data. Can be a single value (applied to all snapshots) or a list of such values (one per snapshot).

Return type:

TemporalGraph | Graph

set_node_attributes(G: Graph | TemporalGraph, values: Any, name: str) TemporalGraph | Graph[source]

Sets node attributes for a graph.

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

  • name (str) – The node attribute key.

  • values (Any) – Node attribute data. Can be a single value (applied to all snapshots) or a list of such values (one per snapshot).

Return type:

TemporalGraph | Graph

temporal_graph(t: int | None = None, directed: bool = False, multigraph: bool = True, create_using: TemporalGraph | Graph | None = None) TemporalGraph[source]

Creates a temporal graph with the desired properties. Similar to empty_graph from NetworkX.

This is a factory function for temporal graphs. It returns a TemporalGraph, TemporalDiGraph, TemporalMultiGraph, or TemporalMultiDiGraph object, depending on the choice of parameters.

Hint

Setting t as greater than 1 initializes a list of NetworkX graph objects, each representing a snapshot in time. Unless dynamic node attributes are required, it is recommended to use the slice() method instead, allowing to create less resource-demanding graph views on the fly.

Example

Creating a temporal directed multigraph with a single snapshot:

>>> import networkx_temporal as tx
>>>
>>> TG = tx.temporal_graph(directed=True, multigraph=True)
>>> print(TG)

TemporalMultiDiGraph (t=1) with 0 nodes and 0 edges
Parameters:
  • t (int) – Number of snapshots to initialize. Optional. Default is 1.

  • directed (bool) – If True, inherits a DiGraph. Defaults to False.

  • multigraph (bool) – If True, inherits a MultiGraph. Defaults to True.

  • create_using (object) – NetworkX or TemporalGraph to use as template. Optional. Does not allow setting directed and multigraph if passed.

Return type:

TemporalGraph

to_multigraph(G: Graph | TemporalGraph) TemporalGraph | Graph[source]

Returns a multigraph from a graph object. SImilar to The from_multigraph().

A multigraph is a graph that allows multiple (parallel) edges between pairwise nodes.

Attention

This function does not duplicate edges with a weight attribute larger than one, but simply converts the graph to a multigraph format, allowing for parallel edges to be added.

Parameters:

G (object) – TemporalGraph or static NetworkX graph object.

Return type:

TemporalGraph | Graph