Reference¶
networkg.graph¶
Graph data structure.
-
class
networkg.graph.Graph(size=0)¶ Graph data structure.
-
add_edge(n1, n2)¶ Adds an edge between the nodes n1 and n2.
Both of the nodes need to exist in the graph.
- Parameters
n1 (
int) – A node indexn2 (
int) – A node index
Examples
>>> g = Graph(2) >>> g.nodes[0] [] >>> g.add_edge(0, 1) >>> g.nodes[0] [1]
- Return type
None
-
add_edges(edges)¶ Adds multiple edges.
Adds an edge between each pair of nodes in edges.
- Parameters
edges (
Iterable[Tuple[int,int]]) – An iterable of node pairs
Examples
>>> g = Graph(4) >>> g.add_edges([(0, 1), (0, 2), (1, 3)])
- Return type
None
-
classmethod
from_csv(path, size, delimiter)¶ Creates a graph from a csv-file.
Each row of the csv-file should contain exactly one node pair, represented by their indices.
Indices should be positive integers in the range [0, size).
- Parameters
path (
str) – Path to the csv.size (
int) – The number of nodes the graph should have.delimiter (
str) – The character used as delimiter in the csv-file.
- Return type
- Returns
A graph with edges read from path.
-
classmethod
fully_connected(size)¶ Creates a fully connected graph with size nodes.
- Parameters
size (
int) – The number of nodes the graph should have.- Return type
- Returns
A fully connected graph with size nodes.
-
property
nodes¶ A list of all nodes in the graph, represented as an adjacency list.
- Return type
List[List[int]]
-
single_source_shortest_path_length(source, cutoff=None)¶ Calculates the shortest path lengths from source to all reachable nodes.
- Parameters
source (
int) – Node index from which to calculate shortest path lengths.cutoff (
Optional[int]) – Stop search at this path length. No paths longer than cutoff are returned.
- Return type
Dict[int,int]- Returns
A dictionary mapping each node reachable from source to the shortest path length between them.
Examples
Basic usage: >>> g = Graph(4) >>> g.add_edges([(0, 1), (1, 2)]) >>> g.single_source_shortest_path_length(0) == {0: 0, 1: 1, 2: 2} True
With cutoff: >>> g = Graph(4) >>> g.add_edges([(0, 1), (1, 2)]) >>> g.single_source_shortest_path_length(0, cutoff=1) == {0: 0, 1: 1} True
-
property
size¶ The number of nodes in the graph.
- Return type
int
-