index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
30,421
networkx.algorithms.traversal.breadth_first_search
bfs_edges
Iterate over edges in a breadth-first-search starting at source. Parameters ---------- G : NetworkX graph source : node Specify starting node for breadth-first search; this function iterates over only those edges in the component reachable from this node. reverse : bool, optional If True traverse a directed graph in the reverse direction depth_limit : int, optional(default=len(G)) Specify the maximum search depth sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Yields ------ edge: 2-tuple of nodes Yields edges resulting from the breadth-first search. Examples -------- To get the edges in a breadth-first search:: >>> G = nx.path_graph(3) >>> list(nx.bfs_edges(G, 0)) [(0, 1), (1, 2)] >>> list(nx.bfs_edges(G, source=0, depth_limit=1)) [(0, 1)] To get the nodes in a breadth-first search order:: >>> G = nx.path_graph(3) >>> root = 2 >>> edges = nx.bfs_edges(G, root) >>> nodes = [root] + [v for u, v in edges] >>> nodes [2, 1, 0] Notes ----- The naming of this function is very similar to :func:`~networkx.algorithms.traversal.edgebfs.edge_bfs`. The difference is that ``edge_bfs`` yields edges even if they extend back to an already explored node while this generator yields the edges of the tree that results from a breadth-first-search (BFS) so no edges are reported if they extend to already explored nodes. That means ``edge_bfs`` reports all edges while ``bfs_edges`` only reports those traversed by a node-based BFS. Yet another description is that ``bfs_edges`` reports the edges traversed during BFS while ``edge_bfs`` reports all edges in the order they are explored. Based on the breadth-first search implementation in PADS [1]_ by D. Eppstein, July 2004; with modifications to allow depth limits as described in [2]_. References ---------- .. [1] http://www.ics.uci.edu/~eppstein/PADS/BFS.py. .. [2] https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- bfs_tree :func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges` :func:`~networkx.algorithms.traversal.edgebfs.edge_bfs`
null
(G, source, reverse=False, depth_limit=None, sort_neighbors=None, *, backend=None, **backend_kwargs)
30,422
networkx.algorithms.traversal.breadth_first_search
bfs_labeled_edges
Iterate over edges in a breadth-first search (BFS) labeled by type. We generate triple of the form (*u*, *v*, *d*), where (*u*, *v*) is the edge being explored in the breadth-first search and *d* is one of the strings 'tree', 'forward', 'level', or 'reverse'. A 'tree' edge is one in which *v* is first discovered and placed into the layer below *u*. A 'forward' edge is one in which *u* is on the layer above *v* and *v* has already been discovered. A 'level' edge is one in which both *u* and *v* occur on the same layer. A 'reverse' edge is one in which *u* is on a layer below *v*. We emit each edge exactly once. In an undirected graph, 'reverse' edges do not occur, because each is discovered either as a 'tree' or 'forward' edge. Parameters ---------- G : NetworkX graph A graph over which to find the layers using breadth-first search. sources : node in `G` or list of nodes in `G` Starting nodes for single source or multiple sources breadth-first search Yields ------ edges: generator A generator of triples (*u*, *v*, *d*) where (*u*, *v*) is the edge being explored and *d* is described above. Examples -------- >>> G = nx.cycle_graph(4, create_using=nx.DiGraph) >>> list(nx.bfs_labeled_edges(G, 0)) [(0, 1, 'tree'), (1, 2, 'tree'), (2, 3, 'tree'), (3, 0, 'reverse')] >>> G = nx.complete_graph(3) >>> list(nx.bfs_labeled_edges(G, 0)) [(0, 1, 'tree'), (0, 2, 'tree'), (1, 2, 'level')] >>> list(nx.bfs_labeled_edges(G, [0, 1])) [(0, 1, 'level'), (0, 2, 'tree'), (1, 2, 'forward')]
null
(G, sources, *, backend=None, **backend_kwargs)
30,423
networkx.algorithms.traversal.breadth_first_search
bfs_layers
Returns an iterator of all the layers in breadth-first search traversal. Parameters ---------- G : NetworkX graph A graph over which to find the layers using breadth-first search. sources : node in `G` or list of nodes in `G` Specify starting nodes for single source or multiple sources breadth-first search Yields ------ layer: list of nodes Yields list of nodes at the same distance from sources Examples -------- >>> G = nx.path_graph(5) >>> dict(enumerate(nx.bfs_layers(G, [0, 4]))) {0: [0, 4], 1: [1, 3], 2: [2]} >>> H = nx.Graph() >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]) >>> dict(enumerate(nx.bfs_layers(H, [1]))) {0: [1], 1: [0, 3, 4], 2: [2], 3: [5, 6]} >>> dict(enumerate(nx.bfs_layers(H, [1, 6]))) {0: [1, 6], 1: [0, 3, 4, 2], 2: [5]}
null
(G, sources, *, backend=None, **backend_kwargs)
30,424
networkx.drawing.layout
bfs_layout
Position nodes according to breadth-first search algorithm. Parameters ---------- G : NetworkX graph A position will be assigned to every node in G. start : node in `G` Starting node for bfs center : array-like or None Coordinate pair around which to center the layout. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.bfs_layout(G, 0) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
def bfs_layout(G, start, *, align="vertical", scale=1, center=None): """Position nodes according to breadth-first search algorithm. Parameters ---------- G : NetworkX graph A position will be assigned to every node in G. start : node in `G` Starting node for bfs center : array-like or None Coordinate pair around which to center the layout. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.bfs_layout(G, 0) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings. """ G, center = _process_params(G, center, 2) # Compute layers with BFS layers = dict(enumerate(nx.bfs_layers(G, start))) if len(G) != sum(len(nodes) for nodes in layers.values()): raise nx.NetworkXError( "bfs_layout didn't include all nodes. Perhaps use input graph:\n" " G.subgraph(nx.node_connected_component(G, start))" ) # Compute node positions with multipartite_layout return multipartite_layout( G, subset_key=layers, align=align, scale=scale, center=center )
(G, start, *, align='vertical', scale=1, center=None)
30,425
networkx.algorithms.traversal.breadth_first_search
bfs_predecessors
Returns an iterator of predecessors in breadth-first-search from source. Parameters ---------- G : NetworkX graph source : node Specify starting node for breadth-first search depth_limit : int, optional(default=len(G)) Specify the maximum search depth sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Returns ------- pred: iterator (node, predecessor) iterator where `predecessor` is the predecessor of `node` in a breadth first search starting from `source`. Examples -------- >>> G = nx.path_graph(3) >>> dict(nx.bfs_predecessors(G, 0)) {1: 0, 2: 1} >>> H = nx.Graph() >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]) >>> dict(nx.bfs_predecessors(H, 0)) {1: 0, 2: 0, 3: 1, 4: 1, 5: 2, 6: 2} >>> M = nx.Graph() >>> nx.add_path(M, [0, 1, 2, 3, 4, 5, 6]) >>> nx.add_path(M, [2, 7, 8, 9, 10]) >>> sorted(nx.bfs_predecessors(M, source=1, depth_limit=3)) [(0, 1), (2, 1), (3, 2), (4, 3), (7, 2), (8, 7)] >>> N = nx.DiGraph() >>> nx.add_path(N, [0, 1, 2, 3, 4, 7]) >>> nx.add_path(N, [3, 5, 6, 7]) >>> sorted(nx.bfs_predecessors(N, source=2)) [(3, 2), (4, 3), (5, 3), (6, 5), (7, 4)] Notes ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004. The modifications to allow depth limits based on the Wikipedia article "`Depth-limited-search`_". .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- bfs_tree bfs_edges edge_bfs
null
(G, source, depth_limit=None, sort_neighbors=None, *, backend=None, **backend_kwargs)
30,426
networkx.algorithms.traversal.breadth_first_search
bfs_successors
Returns an iterator of successors in breadth-first-search from source. Parameters ---------- G : NetworkX graph source : node Specify starting node for breadth-first search depth_limit : int, optional(default=len(G)) Specify the maximum search depth sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Returns ------- succ: iterator (node, successors) iterator where `successors` is the non-empty list of successors of `node` in a breadth first search from `source`. To appear in the iterator, `node` must have successors. Examples -------- >>> G = nx.path_graph(3) >>> dict(nx.bfs_successors(G, 0)) {0: [1], 1: [2]} >>> H = nx.Graph() >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]) >>> dict(nx.bfs_successors(H, 0)) {0: [1, 2], 1: [3, 4], 2: [5, 6]} >>> G = nx.Graph() >>> nx.add_path(G, [0, 1, 2, 3, 4, 5, 6]) >>> nx.add_path(G, [2, 7, 8, 9, 10]) >>> dict(nx.bfs_successors(G, source=1, depth_limit=3)) {1: [0, 2], 2: [3, 7], 3: [4], 7: [8]} >>> G = nx.DiGraph() >>> nx.add_path(G, [0, 1, 2, 3, 4, 5]) >>> dict(nx.bfs_successors(G, source=3)) {3: [4], 4: [5]} Notes ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004.The modifications to allow depth limits based on the Wikipedia article "`Depth-limited-search`_". .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- bfs_tree bfs_edges edge_bfs
null
(G, source, depth_limit=None, sort_neighbors=None, *, backend=None, **backend_kwargs)
30,427
networkx.algorithms.traversal.breadth_first_search
bfs_tree
Returns an oriented tree constructed from of a breadth-first-search starting at source. Parameters ---------- G : NetworkX graph source : node Specify starting node for breadth-first search reverse : bool, optional If True traverse a directed graph in the reverse direction depth_limit : int, optional(default=len(G)) Specify the maximum search depth sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Returns ------- T: NetworkX DiGraph An oriented tree Examples -------- >>> G = nx.path_graph(3) >>> list(nx.bfs_tree(G, 1).edges()) [(1, 0), (1, 2)] >>> H = nx.Graph() >>> nx.add_path(H, [0, 1, 2, 3, 4, 5, 6]) >>> nx.add_path(H, [2, 7, 8, 9, 10]) >>> sorted(list(nx.bfs_tree(H, source=3, depth_limit=3).edges())) [(1, 0), (2, 1), (2, 7), (3, 2), (3, 4), (4, 5), (5, 6), (7, 8)] Notes ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004. The modifications to allow depth limits based on the Wikipedia article "`Depth-limited-search`_". .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- dfs_tree bfs_edges edge_bfs
null
(G, source, reverse=False, depth_limit=None, sort_neighbors=None, *, backend=None, **backend_kwargs)
30,429
networkx.algorithms.components.biconnected
biconnected_component_edges
Returns a generator of lists of edges, one list for each biconnected component of the input graph. Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component. Those nodes are articulation points, or cut vertices. However, each edge belongs to one, and only one, biconnected component. Notice that by convention a dyad is considered a biconnected component. Parameters ---------- G : NetworkX Graph An undirected graph. Returns ------- edges : generator of lists Generator of lists of edges, one list for each bicomponent. Raises ------ NetworkXNotImplemented If the input graph is not undirected. Examples -------- >>> G = nx.barbell_graph(4, 2) >>> print(nx.is_biconnected(G)) False >>> bicomponents_edges = list(nx.biconnected_component_edges(G)) >>> len(bicomponents_edges) 5 >>> G.add_edge(2, 8) >>> print(nx.is_biconnected(G)) True >>> bicomponents_edges = list(nx.biconnected_component_edges(G)) >>> len(bicomponents_edges) 1 See Also -------- is_biconnected, biconnected_components, articulation_points, Notes ----- The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points. References ---------- .. [1] Hopcroft, J.; Tarjan, R. (1973). "Efficient algorithms for graph manipulation". Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
null
(G, *, backend=None, **backend_kwargs)
30,430
networkx.algorithms.components.biconnected
biconnected_components
Returns a generator of sets of nodes, one set for each biconnected component of the graph Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component. Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number of connected components of the graph. Notice that by convention a dyad is considered a biconnected component. Parameters ---------- G : NetworkX Graph An undirected graph. Returns ------- nodes : generator Generator of sets of nodes, one set for each biconnected component. Raises ------ NetworkXNotImplemented If the input graph is not undirected. Examples -------- >>> G = nx.lollipop_graph(5, 1) >>> print(nx.is_biconnected(G)) False >>> bicomponents = list(nx.biconnected_components(G)) >>> len(bicomponents) 2 >>> G.add_edge(0, 5) >>> print(nx.is_biconnected(G)) True >>> bicomponents = list(nx.biconnected_components(G)) >>> len(bicomponents) 1 You can generate a sorted list of biconnected components, largest first, using sort. >>> G.remove_edge(0, 5) >>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)] [5, 2] If you only want the largest connected component, it's more efficient to use max instead of sort. >>> Gc = max(nx.biconnected_components(G), key=len) To create the components as subgraphs use: ``(G.subgraph(c).copy() for c in biconnected_components(G))`` See Also -------- is_biconnected articulation_points biconnected_component_edges k_components : this function is a special case where k=2 bridge_components : similar to this function, but is defined using 2-edge-connectivity instead of 2-node-connectivity. Notes ----- The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points. References ---------- .. [1] Hopcroft, J.; Tarjan, R. (1973). "Efficient algorithms for graph manipulation". Communications of the ACM 16: 372–378. doi:10.1145/362248.362272
null
(G, *, backend=None, **backend_kwargs)
30,431
networkx.algorithms.shortest_paths.weighted
bidirectional_dijkstra
Dijkstra's algorithm for shortest paths using bidirectional search. Parameters ---------- G : NetworkX graph source : node Starting node. target : node Ending node. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number or None to indicate a hidden edge. Returns ------- length, path : number and list length is the distance from source to target. path is a list of nodes on a path from source to target. Raises ------ NodeNotFound If either `source` or `target` is not in `G`. NetworkXNoPath If no path exists between source and target. Examples -------- >>> G = nx.path_graph(5) >>> length, path = nx.bidirectional_dijkstra(G, 0, 4) >>> print(length) 4 >>> print(path) [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. In practice bidirectional Dijkstra is much more than twice as fast as ordinary Dijkstra. Ordinary Dijkstra expands nodes in a sphere-like manner from the source. The radius of this sphere will eventually be the length of the shortest path. Bidirectional Dijkstra will expand nodes from both the source and the target, making two spheres of half this radius. Volume of the first sphere is `\pi*r*r` while the others are `2*\pi*r/2*r/2`, making up half the volume. This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows and roundoff errors can cause problems). See Also -------- shortest_path shortest_path_length
def _dijkstra_multisource( G, sources, weight, pred=None, paths=None, cutoff=None, target=None ): """Uses Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph sources : non-empty iterable of nodes Starting nodes for paths. If this is just an iterable containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in this iterable, the computed paths may begin from any one of the start nodes. weight: function Function with (u, v, data) input that returns that edge's weight or None to indicate a hidden edge pred: dict of lists, optional(default=None) dict to store a list of predecessors keyed by that node If None, predecessors are not stored. paths: dict, optional (default=None) dict to store the path list from source to each node, keyed by node. If None, paths are not stored. target : node label, optional Ending node for path. Search is halted when target is found. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. Returns ------- distance : dictionary A mapping from node to shortest distance to that node from one of the source nodes. Raises ------ NodeNotFound If any of `sources` is not in `G`. Notes ----- The optional predecessor and path dictionaries can be accessed by the caller through the original pred and paths objects passed as arguments. No need to explicitly return pred or paths. """ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs) push = heappush pop = heappop dist = {} # dictionary of final distances seen = {} # fringe is heapq with 3-tuples (distance,c,node) # use the count c to avoid comparing nodes (may not be able to) c = count() fringe = [] for source in sources: seen[source] = 0 push(fringe, (0, next(c), source)) while fringe: (d, _, v) = pop(fringe) if v in dist: continue # already searched this node. dist[v] = d if v == target: break for u, e in G_succ[v].items(): cost = weight(v, u, e) if cost is None: continue vu_dist = dist[v] + cost if cutoff is not None: if vu_dist > cutoff: continue if u in dist: u_dist = dist[u] if vu_dist < u_dist: raise ValueError("Contradictory paths found:", "negative weights?") elif pred is not None and vu_dist == u_dist: pred[u].append(v) elif u not in seen or vu_dist < seen[u]: seen[u] = vu_dist push(fringe, (vu_dist, next(c), u)) if paths is not None: paths[u] = paths[v] + [u] if pred is not None: pred[u] = [v] elif vu_dist == seen[u]: if pred is not None: pred[u].append(v) # The optional predecessor and path dictionaries can be accessed # by the caller via the pred and paths objects passed as arguments. return dist
(G, source, target, weight='weight', *, backend=None, **backend_kwargs)
30,432
networkx.algorithms.shortest_paths.unweighted
bidirectional_shortest_path
Returns a list of nodes in a shortest path between source and target. Parameters ---------- G : NetworkX graph source : node label starting node for path target : node label ending node for path Returns ------- path: list List of nodes in a path from source to target. Raises ------ NetworkXNoPath If no path exists between source and target. Examples -------- >>> G = nx.Graph() >>> nx.add_path(G, [0, 1, 2, 3, 0, 4, 5, 6, 7, 4]) >>> nx.bidirectional_shortest_path(G, 2, 6) [2, 1, 0, 4, 5, 6] See Also -------- shortest_path Notes ----- This algorithm is used by shortest_path(G, source, target).
null
(G, source, target, *, backend=None, **backend_kwargs)
30,434
networkx.generators.random_graphs
gnp_random_graph
Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or a binomial graph. The $G_{n,p}$ model chooses each of the possible edges with probability $p$. Parameters ---------- n : int The number of nodes. p : float Probability for edge creation. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. directed : bool, optional (default=False) If True, this function returns a directed graph. See Also -------- fast_gnp_random_graph Notes ----- This algorithm [2]_ runs in $O(n^2)$ time. For sparse graphs (that is, for small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm. :func:`binomial_graph` and :func:`erdos_renyi_graph` are aliases for :func:`gnp_random_graph`. >>> nx.binomial_graph is nx.gnp_random_graph True >>> nx.erdos_renyi_graph is nx.gnp_random_graph True References ---------- .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959). .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None): """Returns a random graph using dual Barabási–Albert preferential attachment A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that are preferentially attached to existing nodes with high degree. Parameters ---------- n : int Number of nodes m1 : int Number of edges to link each new node to existing nodes with probability $p$ m2 : int Number of edges to link each new node to existing nodes with probability $1-p$ p : float The probability of attaching $m_1$ edges (as opposed to $m_2$ edges) seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. initial_graph : Graph or None (default) Initial network for Barabási–Albert algorithm. A copy of `initial_graph` is used. It should be connected for most use cases. If None, starts from an star graph on max(m1, m2) + 1 nodes. Returns ------- G : Graph Raises ------ NetworkXError If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or `p` does not satisfy ``0 <= p <= 1``, or the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n. References ---------- .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538. """ if m1 < 1 or m1 >= n: raise nx.NetworkXError( f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}" ) if m2 < 1 or m2 >= n: raise nx.NetworkXError( f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}" ) if p < 0 or p > 1: raise nx.NetworkXError( f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}" ) # For simplicity, if p == 0 or 1, just return BA if p == 1: return barabasi_albert_graph(n, m1, seed) elif p == 0: return barabasi_albert_graph(n, m2, seed) if initial_graph is None: # Default initial graph : empty graph on max(m1, m2) nodes G = star_graph(max(m1, m2)) else: if len(initial_graph) < max(m1, m2) or len(initial_graph) > n: raise nx.NetworkXError( f"Barabási–Albert initial graph must have between " f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes" ) G = initial_graph.copy() # Target nodes for new edges targets = list(G) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes = [n for n, d in G.degree() for _ in range(d)] # Start adding the remaining nodes. source = len(G) while source < n: # Pick which m to use (m1 or m2) if seed.random() < p: m = m1 else: m = m2 # Now choose m unique nodes from the existing nodes # Pick uniformly from repeated_nodes (preferential attachment) targets = _random_subset(repeated_nodes, m, seed) # Add edges to m nodes from the source. G.add_edges_from(zip([source] * m, targets)) # Add one node to the list for each new edge just created. repeated_nodes.extend(targets) # And the new node "source" has m edges to add to the list. repeated_nodes.extend([source] * m) source += 1 return G
(n, p, seed=None, directed=False, *, backend=None, **backend_kwargs)
30,435
networkx.generators.classic
binomial_tree
Returns the Binomial Tree of order n. The binomial tree of order 0 consists of a single node. A binomial tree of order k is defined recursively by linking two binomial trees of order k-1: the root of one is the leftmost child of the root of the other. .. plot:: >>> nx.draw(nx.binomial_tree(3)) Parameters ---------- n : int Order of the binomial tree. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : NetworkX graph A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(n, create_using=None, *, backend=None, **backend_kwargs)
30,437
networkx.drawing.layout
bipartite_layout
Position nodes in two straight lines. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. nodes : list or container Nodes in one node set of the bipartite graph. This set will be placed on left or top. align : string (default='vertical') The alignment of nodes. Vertical or horizontal. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. aspect_ratio : number (default=4/3): The ratio of the width to the height of the layout. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123) >>> top = nx.bipartite.sets(G)[0] >>> pos = nx.bipartite_layout(G, top) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
def bipartite_layout( G, nodes, align="vertical", scale=1, center=None, aspect_ratio=4 / 3 ): """Position nodes in two straight lines. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. nodes : list or container Nodes in one node set of the bipartite graph. This set will be placed on left or top. align : string (default='vertical') The alignment of nodes. Vertical or horizontal. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. aspect_ratio : number (default=4/3): The ratio of the width to the height of the layout. Returns ------- pos : dict A dictionary of positions keyed by node. Examples -------- >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123) >>> top = nx.bipartite.sets(G)[0] >>> pos = nx.bipartite_layout(G, top) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings. """ import numpy as np if align not in ("vertical", "horizontal"): msg = "align must be either vertical or horizontal." raise ValueError(msg) G, center = _process_params(G, center=center, dim=2) if len(G) == 0: return {} height = 1 width = aspect_ratio * height offset = (width / 2, height / 2) top = dict.fromkeys(nodes) bottom = [v for v in G if v not in top] nodes = list(top) + bottom left_xs = np.repeat(0, len(top)) right_xs = np.repeat(width, len(bottom)) left_ys = np.linspace(0, height, len(top)) right_ys = np.linspace(0, height, len(bottom)) top_pos = np.column_stack([left_xs, left_ys]) - offset bottom_pos = np.column_stack([right_xs, right_ys]) - offset pos = np.concatenate([top_pos, bottom_pos]) pos = rescale_layout(pos, scale=scale) + center if align == "horizontal": pos = pos[:, ::-1] # swap x and y coords pos = dict(zip(nodes, pos)) return pos
(G, nodes, align='vertical', scale=1, center=None, aspect_ratio=1.3333333333333333)
30,439
networkx.algorithms.cuts
boundary_expansion
Returns the boundary expansion of the set `S`. The *boundary expansion* is the quotient of the size of the node boundary and the cardinality of *S*. [1] Parameters ---------- G : NetworkX graph S : collection A collection of nodes in `G`. Returns ------- number The boundary expansion of the set `S`. See also -------- edge_expansion mixing_expansion node_expansion References ---------- .. [1] Vadhan, Salil P. "Pseudorandomness." *Foundations and Trends in Theoretical Computer Science* 7.1–3 (2011): 1–336. <https://doi.org/10.1561/0400000010>
null
(G, S, *, backend=None, **backend_kwargs)
30,441
networkx.algorithms.bridges
bridges
Generate all bridges in a graph. A *bridge* in a graph is an edge whose removal causes the number of connected components of the graph to increase. Equivalently, a bridge is an edge that does not belong to any cycle. Bridges are also known as cut-edges, isthmuses, or cut arcs. Parameters ---------- G : undirected graph root : node (optional) A node in the graph `G`. If specified, only the bridges in the connected component containing this node will be returned. Yields ------ e : edge An edge in the graph whose removal disconnects the graph (or causes the number of connected components to increase). Raises ------ NodeNotFound If `root` is not in the graph `G`. NetworkXNotImplemented If `G` is a directed graph. Examples -------- The barbell graph with parameter zero has a single bridge: >>> G = nx.barbell_graph(10, 0) >>> list(nx.bridges(G)) [(9, 10)] Notes ----- This is an implementation of the algorithm described in [1]_. An edge is a bridge if and only if it is not contained in any chain. Chains are found using the :func:`networkx.chain_decomposition` function. The algorithm described in [1]_ requires a simple graph. If the provided graph is a multigraph, we convert it to a simple graph and verify that any bridges discovered by the chain decomposition algorithm are not multi-edges. Ignoring polylogarithmic factors, the worst-case time complexity is the same as the :func:`networkx.chain_decomposition` function, $O(m + n)$, where $n$ is the number of nodes in the graph and $m$ is the number of edges. References ---------- .. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29#Bridge-Finding_with_Chain_Decompositions
null
(G, root=None, *, backend=None, **backend_kwargs)
30,443
networkx.generators.small
bull_graph
Returns the Bull Graph The Bull Graph has 5 nodes and 5 edges. It is a planar undirected graph in the form of a triangle with two disjoint pendant edges [1]_ The name comes from the triangle and pendant edges representing respectively the body and legs of a bull. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph A bull graph with 5 nodes References ---------- .. [1] https://en.wikipedia.org/wiki/Bull_graph.
def _raise_on_directed(func): """ A decorator which inspects the `create_using` argument and raises a NetworkX exception when `create_using` is a DiGraph (class or instance) for graph generators that do not support directed outputs. """ @wraps(func) def wrapper(*args, **kwargs): if kwargs.get("create_using") is not None: G = nx.empty_graph(create_using=kwargs["create_using"]) if G.is_directed(): raise NetworkXError("Directed Graph not supported") return func(*args, **kwargs) return wrapper
(create_using=None, *, backend=None, **backend_kwargs)
30,444
networkx.algorithms.flow.capacityscaling
capacity_scaling
Find a minimum cost flow satisfying all demands in digraph G. This is a capacity scaling successive shortest augmenting path algorithm. G is a digraph with edge costs and capacities and in which nodes have demand, i.e., they want to send or receive some amount of flow. A negative demand means that the node wants to send flow, a positive demand means that the node want to receive flow. A flow on the digraph G satisfies all demand if the net flow into each node is equal to the demand of that node. Parameters ---------- G : NetworkX graph DiGraph or MultiDiGraph on which a minimum cost flow satisfying all demands is to be found. demand : string Nodes of the graph G are expected to have an attribute demand that indicates how much flow a node wants to send (negative demand) or receive (positive demand). Note that the sum of the demands should be 0 otherwise the problem in not feasible. If this attribute is not present, a node is considered to have 0 demand. Default value: 'demand'. capacity : string Edges of the graph G are expected to have an attribute capacity that indicates how much flow the edge can support. If this attribute is not present, the edge is considered to have infinite capacity. Default value: 'capacity'. weight : string Edges of the graph G are expected to have an attribute weight that indicates the cost incurred by sending one unit of flow on that edge. If not present, the weight is considered to be 0. Default value: 'weight'. heap : class Type of heap to be used in the algorithm. It should be a subclass of :class:`MinHeap` or implement a compatible interface. If a stock heap implementation is to be used, :class:`BinaryHeap` is recommended over :class:`PairingHeap` for Python implementations without optimized attribute accesses (e.g., CPython) despite a slower asymptotic running time. For Python implementations with optimized attribute accesses (e.g., PyPy), :class:`PairingHeap` provides better performance. Default value: :class:`BinaryHeap`. Returns ------- flowCost : integer Cost of a minimum cost flow satisfying all demands. flowDict : dictionary If G is a digraph, a dict-of-dicts keyed by nodes such that flowDict[u][v] is the flow on edge (u, v). If G is a MultiDiGraph, a dict-of-dicts-of-dicts keyed by nodes so that flowDict[u][v][key] is the flow on edge (u, v, key). Raises ------ NetworkXError This exception is raised if the input graph is not directed, not connected. NetworkXUnfeasible This exception is raised in the following situations: * The sum of the demands is not zero. Then, there is no flow satisfying all demands. * There is no flow satisfying all demand. NetworkXUnbounded This exception is raised if the digraph G has a cycle of negative cost and infinite capacity. Then, the cost of a flow satisfying all demands is unbounded below. Notes ----- This algorithm does not work if edge weights are floating-point numbers. See also -------- :meth:`network_simplex` Examples -------- A simple example of a min cost flow problem. >>> G = nx.DiGraph() >>> G.add_node("a", demand=-5) >>> G.add_node("d", demand=5) >>> G.add_edge("a", "b", weight=3, capacity=4) >>> G.add_edge("a", "c", weight=6, capacity=10) >>> G.add_edge("b", "d", weight=1, capacity=9) >>> G.add_edge("c", "d", weight=2, capacity=5) >>> flowCost, flowDict = nx.capacity_scaling(G) >>> flowCost 24 >>> flowDict {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}} It is possible to change the name of the attributes used for the algorithm. >>> G = nx.DiGraph() >>> G.add_node("p", spam=-4) >>> G.add_node("q", spam=2) >>> G.add_node("a", spam=-2) >>> G.add_node("d", spam=-1) >>> G.add_node("t", spam=2) >>> G.add_node("w", spam=3) >>> G.add_edge("p", "q", cost=7, vacancies=5) >>> G.add_edge("p", "a", cost=1, vacancies=4) >>> G.add_edge("q", "d", cost=2, vacancies=3) >>> G.add_edge("t", "q", cost=1, vacancies=2) >>> G.add_edge("a", "t", cost=2, vacancies=4) >>> G.add_edge("d", "w", cost=3, vacancies=4) >>> G.add_edge("t", "w", cost=4, vacancies=1) >>> flowCost, flowDict = nx.capacity_scaling( ... G, demand="spam", capacity="vacancies", weight="cost" ... ) >>> flowCost 37 >>> flowDict {'p': {'q': 2, 'a': 2}, 'q': {'d': 1}, 'a': {'t': 4}, 'd': {'w': 2}, 't': {'q': 1, 'w': 1}, 'w': {}}
null
(G, demand='demand', capacity='capacity', weight='weight', heap=<class 'networkx.utils.heaps.BinaryHeap'>, *, backend=None, **backend_kwargs)
30,445
networkx.algorithms.operators.product
cartesian_product
Returns the Cartesian product of G and H. The Cartesian product $P$ of the graphs $G$ and $H$ has a node set that is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$. $P$ has an edge $((u,v),(x,y))$ if and only if either $u$ is equal to $x$ and both $v$ and $y$ are adjacent in $H$ or if $v$ is equal to $y$ and both $u$ and $x$ are adjacent in $G$. Parameters ---------- G, H: graphs Networkx graphs. Returns ------- P: NetworkX graph The Cartesian product of G and H. P will be a multi-graph if either G or H is a multi-graph. Will be a directed if G and H are directed, and undirected if G and H are undirected. Raises ------ NetworkXError If G and H are not both directed or both undirected. Notes ----- Node attributes in P are two-tuple of the G and H node attributes. Missing attributes are assigned None. Examples -------- >>> G = nx.Graph() >>> H = nx.Graph() >>> G.add_node(0, a1=True) >>> H.add_node("a", a2="Spam") >>> P = nx.cartesian_product(G, H) >>> list(P) [(0, 'a')] Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
null
(G, H, *, backend=None, **backend_kwargs)
30,446
networkx.generators.community
caveman_graph
Returns a caveman graph of `l` cliques of size `k`. Parameters ---------- l : int Number of cliques k : int Size of cliques Returns ------- G : NetworkX Graph caveman graph Notes ----- This returns an undirected graph, it can be converted to a directed graph using :func:`nx.to_directed`, or a multigraph using ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is described in [1]_ and it is unclear which of the directed generalizations is most useful. Examples -------- >>> G = nx.caveman_graph(3, 3) See also -------- connected_caveman_graph References ---------- .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.' Amer. J. Soc. 105, 493-527, 1999.
def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed): """Returns a list of sets, each of which represents a community. ``degree_seq`` is the degree sequence that must be met by the graph. ``community_sizes`` is the community size distribution that must be met by the generated list of sets. ``mu`` is a float in the interval [0, 1] indicating the fraction of intra-community edges incident to each node. ``max_iters`` is the number of times to try to add a node to a community. This must be greater than the length of ``degree_seq``, otherwise this function will always fail. If the number of iterations exceeds this value, :exc:`~networkx.exception.ExceededMaxIterations` is raised. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. The communities returned by this are sets of integers in the set {0, ..., *n* - 1}, where *n* is the length of ``degree_seq``. """ # This assumes the nodes in the graph will be natural numbers. result = [set() for _ in community_sizes] n = len(degree_seq) free = list(range(n)) for i in range(max_iters): v = free.pop() c = seed.choice(range(len(community_sizes))) # s = int(degree_seq[v] * (1 - mu) + 0.5) s = round(degree_seq[v] * (1 - mu)) # If the community is large enough, add the node to the chosen # community. Otherwise, return it to the list of unaffiliated # nodes. if s < community_sizes[c]: result[c].add(v) else: free.append(v) # If the community is too big, remove a node from it. if len(result[c]) > community_sizes[c]: free.append(result[c].pop()) if not free: return result msg = "Could not assign communities; try increasing min_community" raise nx.ExceededMaxIterations(msg)
(l, k, *, backend=None, **backend_kwargs)
30,447
networkx.algorithms.time_dependent
cd_index
Compute the CD index for `node` within the graph `G`. Calculates the CD index for the given node of the graph, considering only its predecessors who have the `time` attribute smaller than or equal to the `time` attribute of the `node` plus `time_delta`. Parameters ---------- G : graph A directed networkx graph whose nodes have `time` attributes and optionally `weight` attributes (if a weight is not given, it is considered 1). node : node The node for which the CD index is calculated. time_delta : numeric or timedelta Amount of time after the `time` attribute of the `node`. The value of `time_delta` must support comparison with the `time` node attribute. For example, if the `time` attribute of the nodes are `datetime.datetime` objects, then `time_delta` should be a `datetime.timedelta` object. time : string (Optional, default is "time") The name of the node attribute that will be used for the calculations. weight : string (Optional, default is None) The name of the node attribute used as weight. Returns ------- float The CD index calculated for the node `node` within the graph `G`. Raises ------ NetworkXError If not all nodes have a `time` attribute or `time_delta` and `time` attribute types are not compatible or `n` equals 0. NetworkXNotImplemented If `G` is a non-directed graph or a multigraph. Examples -------- >>> from datetime import datetime, timedelta >>> G = nx.DiGraph() >>> nodes = { ... 1: {"time": datetime(2015, 1, 1)}, ... 2: {"time": datetime(2012, 1, 1), "weight": 4}, ... 3: {"time": datetime(2010, 1, 1)}, ... 4: {"time": datetime(2008, 1, 1)}, ... 5: {"time": datetime(2014, 1, 1)}, ... } >>> G.add_nodes_from([(n, nodes[n]) for n in nodes]) >>> edges = [(1, 3), (1, 4), (2, 3), (3, 4), (3, 5)] >>> G.add_edges_from(edges) >>> delta = timedelta(days=5 * 365) >>> nx.cd_index(G, 3, time_delta=delta, time="time") 0.5 >>> nx.cd_index(G, 3, time_delta=delta, time="time", weight="weight") 0.12 Integers can also be used for the time values: >>> node_times = {1: 2015, 2: 2012, 3: 2010, 4: 2008, 5: 2014} >>> nx.set_node_attributes(G, node_times, "new_time") >>> nx.cd_index(G, 3, time_delta=4, time="new_time") 0.5 >>> nx.cd_index(G, 3, time_delta=4, time="new_time", weight="weight") 0.12 Notes ----- This method implements the algorithm for calculating the CD index, as described in the paper by Funk and Owen-Smith [1]_. The CD index is used in order to check how consolidating or destabilizing a patent is, hence the nodes of the graph represent patents and the edges show the citations between these patents. The mathematical model is given below: .. math:: CD_{t}=\frac{1}{n_{t}}\sum_{i=1}^{n}\frac{-2f_{it}b_{it}+f_{it}}{w_{it}}, where `f_{it}` equals 1 if `i` cites the focal patent else 0, `b_{it}` equals 1 if `i` cites any of the focal patents successors else 0, `n_{t}` is the number of forward citations in `i` and `w_{it}` is a matrix of weight for patent `i` at time `t`. The `datetime.timedelta` package can lead to off-by-one issues when converting from years to days. In the example above `timedelta(days=5 * 365)` looks like 5 years, but it isn't because of leap year days. So it gives the same result as `timedelta(days=4 * 365)`. But using `timedelta(days=5 * 365 + 1)` gives a 5 year delta **for this choice of years** but may not if the 5 year gap has more than 1 leap year. To avoid these issues, use integers to represent years, or be very careful when you convert units of time. References ---------- .. [1] Funk, Russell J., and Jason Owen-Smith. "A dynamic network measure of technological change." Management science 63, no. 3 (2017): 791-817. http://russellfunk.org/cdindex/static/papers/funk_ms_2017.pdf
null
(G, node, time_delta, *, time='time', weight=None, backend=None, **backend_kwargs)
30,448
networkx.algorithms.distance_measures
center
Returns the center of the graph G. The center is the set of nodes with eccentricity equal to radius. Parameters ---------- G : NetworkX graph A graph e : eccentricity dictionary, optional A precomputed dictionary of eccentricities. weight : string, function, or None If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. If this is None, every edge has weight/distance/cost 1. Weights stored as floating point values can lead to small round-off errors in distances. Use integer weights to avoid this. Weights should be positive, since they are distances. Returns ------- c : list List of nodes in center Examples -------- >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)]) >>> list(nx.center(G)) [1, 3, 4] See Also -------- barycenter periphery
def effective_graph_resistance(G, weight=None, invert_weight=True): """Returns the Effective graph resistance of G. Also known as the Kirchhoff index. The effective graph resistance is defined as the sum of the resistance distance of every node pair in G [1]_. If weight is not provided, then a weight of 1 is used for all edges. The effective graph resistance of a disconnected graph is infinite. Parameters ---------- G : NetworkX graph A graph weight : string or None, optional (default=None) The edge data key used to compute the effective graph resistance. If None, then each edge has weight 1. invert_weight : boolean (default=True) Proper calculation of resistance distance requires building the Laplacian matrix with the reciprocal of the weight. Not required if the weight is already inverted. Weight cannot be zero. Returns ------- RG : float The effective graph resistance of `G`. Raises ------ NetworkXNotImplemented If `G` is a directed graph. NetworkXError If `G` does not contain any nodes. Examples -------- >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)]) >>> round(nx.effective_graph_resistance(G), 10) 10.25 Notes ----- The implementation is based on Theorem 2.2 in [2]_. Self-loops are ignored. Multi-edges are contracted in one edge with weight equal to the harmonic sum of the weights. References ---------- .. [1] Wolfram "Kirchhoff Index." https://mathworld.wolfram.com/KirchhoffIndex.html .. [2] W. Ellens, F. M. Spieksma, P. Van Mieghem, A. Jamakovic, R. E. Kooij. Effective graph resistance. Lin. Alg. Appl. 435:2491-2506, 2011. """ import numpy as np if len(G) == 0: raise nx.NetworkXError("Graph G must contain at least one node.") # Disconnected graphs have infinite Effective graph resistance if not nx.is_connected(G): return float("inf") # Invert weights G = G.copy() if invert_weight and weight is not None: if G.is_multigraph(): for u, v, k, d in G.edges(keys=True, data=True): d[weight] = 1 / d[weight] else: for u, v, d in G.edges(data=True): d[weight] = 1 / d[weight] # Get Laplacian eigenvalues mu = np.sort(nx.laplacian_spectrum(G, weight=weight)) # Compute Effective graph resistance based on spectrum of the Laplacian # Self-loops are ignored return float(np.sum(1 / mu[1:]) * G.number_of_nodes())
(G, e=None, usebounds=False, weight=None, *, backend=None, **backend_kwargs)
30,450
networkx.algorithms.chains
chain_decomposition
Returns the chain decomposition of a graph. The *chain decomposition* of a graph with respect a depth-first search tree is a set of cycles or paths derived from the set of fundamental cycles of the tree in the following manner. Consider each fundamental cycle with respect to the given tree, represented as a list of edges beginning with the nontree edge oriented away from the root of the tree. For each fundamental cycle, if it overlaps with any previous fundamental cycle, just take the initial non-overlapping segment, which is a path instead of a cycle. Each cycle or path is called a *chain*. For more information, see [1]_. Parameters ---------- G : undirected graph root : node (optional) A node in the graph `G`. If specified, only the chain decomposition for the connected component containing this node will be returned. This node indicates the root of the depth-first search tree. Yields ------ chain : list A list of edges representing a chain. There is no guarantee on the orientation of the edges in each chain (for example, if a chain includes the edge joining nodes 1 and 2, the chain may include either (1, 2) or (2, 1)). Raises ------ NodeNotFound If `root` is not in the graph `G`. Examples -------- >>> G = nx.Graph([(0, 1), (1, 4), (3, 4), (3, 5), (4, 5)]) >>> list(nx.chain_decomposition(G)) [[(4, 5), (5, 3), (3, 4)]] Notes ----- The worst-case running time of this implementation is linear in the number of nodes and number of edges [1]_. References ---------- .. [1] Jens M. Schmidt (2013). "A simple test on 2-vertex- and 2-edge-connectivity." *Information Processing Letters*, 113, 241–244. Elsevier. <https://doi.org/10.1016/j.ipl.2013.01.016>
null
(G, root=None, *, backend=None, **backend_kwargs)
30,452
networkx.algorithms.planarity
check_planarity
Check if a graph is planar and return a counterexample or an embedding. A graph is planar iff it can be drawn in a plane without any edge intersections. Parameters ---------- G : NetworkX graph counterexample : bool A Kuratowski subgraph (to proof non planarity) is only returned if set to true. Returns ------- (is_planar, certificate) : (bool, NetworkX graph) tuple is_planar is true if the graph is planar. If the graph is planar `certificate` is a PlanarEmbedding otherwise it is a Kuratowski subgraph. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2)]) >>> is_planar, P = nx.check_planarity(G) >>> print(is_planar) True When `G` is planar, a `PlanarEmbedding` instance is returned: >>> P.get_data() {0: [1, 2], 1: [0], 2: [0]} Notes ----- A (combinatorial) embedding consists of cyclic orderings of the incident edges at each vertex. Given such an embedding there are multiple approaches discussed in literature to drawing the graph (subject to various constraints, e.g. integer coordinates), see e.g. [2]. The planarity check algorithm and extraction of the combinatorial embedding is based on the Left-Right Planarity Test [1]. A counterexample is only generated if the corresponding parameter is set, because the complexity of the counterexample generation is higher. See also -------- is_planar : Check for planarity without creating a `PlanarEmbedding` or counterexample. References ---------- .. [1] Ulrik Brandes: The Left-Right Planarity Test 2009 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.217.9208 .. [2] Takao Nishizeki, Md Saidur Rahman: Planar graph drawing Lecture Notes Series on Computing: Volume 12 2004
def sign_recursive(self, e): """Recursive version of :meth:`sign`.""" if self.ref[e] is not None: self.side[e] = self.side[e] * self.sign_recursive(self.ref[e]) self.ref[e] = None return self.side[e]
(G, counterexample=False, *, backend=None, **backend_kwargs)
30,454
networkx.generators.expanders
chordal_cycle_graph
Returns the chordal cycle graph on `p` nodes. The returned graph is a cycle graph on `p` nodes with chords joining each vertex `x` to its inverse modulo `p`. This graph is a (mildly explicit) 3-regular expander [1]_. `p` *must* be a prime number. Parameters ---------- p : a prime number The number of vertices in the graph. This also indicates where the chordal edges in the cycle will be created. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : graph The constructed undirected multigraph. Raises ------ NetworkXError If `create_using` indicates directed or not a multigraph. References ---------- .. [1] Theorem 4.4.2 in A. Lubotzky. "Discrete groups, expanding graphs and invariant measures", volume 125 of Progress in Mathematics. Birkhäuser Verlag, Basel, 1994.
null
(p, create_using=None, *, backend=None, **backend_kwargs)
30,455
networkx.algorithms.chordal
chordal_graph_cliques
Returns all maximal cliques of a chordal graph. The algorithm breaks the graph in connected components and performs a maximum cardinality search in each component to get the cliques. Parameters ---------- G : graph A NetworkX graph Yields ------ frozenset of nodes Maximal cliques, each of which is a frozenset of nodes in `G`. The order of cliques is arbitrary. Raises ------ NetworkXError The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. The algorithm can only be applied to chordal graphs. If the input graph is found to be non-chordal, a :exc:`NetworkXError` is raised. Examples -------- >>> e = [ ... (1, 2), ... (1, 3), ... (2, 3), ... (2, 4), ... (3, 4), ... (3, 5), ... (3, 6), ... (4, 5), ... (4, 6), ... (5, 6), ... (7, 8), ... ] >>> G = nx.Graph(e) >>> G.add_node(9) >>> cliques = [c for c in chordal_graph_cliques(G)] >>> cliques[0] frozenset({1, 2, 3})
null
(G, *, backend=None, **backend_kwargs)
30,456
networkx.algorithms.chordal
chordal_graph_treewidth
Returns the treewidth of the chordal graph G. Parameters ---------- G : graph A NetworkX graph Returns ------- treewidth : int The size of the largest clique in the graph minus one. Raises ------ NetworkXError The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. The algorithm can only be applied to chordal graphs. If the input graph is found to be non-chordal, a :exc:`NetworkXError` is raised. Examples -------- >>> e = [ ... (1, 2), ... (1, 3), ... (2, 3), ... (2, 4), ... (3, 4), ... (3, 5), ... (3, 6), ... (4, 5), ... (4, 6), ... (5, 6), ... (7, 8), ... ] >>> G = nx.Graph(e) >>> G.add_node(9) >>> nx.chordal_graph_treewidth(G) 3 References ---------- .. [1] https://en.wikipedia.org/wiki/Tree_decomposition#Treewidth
null
(G, *, backend=None, **backend_kwargs)
30,457
networkx.algorithms.cycles
chordless_cycles
Find simple chordless cycles of a graph. A `simple cycle` is a closed path where no node appears twice. In a simple cycle, a `chord` is an additional edge between two nodes in the cycle. A `chordless cycle` is a simple cycle without chords. Said differently, a chordless cycle is a cycle C in a graph G where the number of edges in the induced graph G[C] is equal to the length of `C`. Note that some care must be taken in the case that G is not a simple graph nor a simple digraph. Some authors limit the definition of chordless cycles to have a prescribed minimum length; we do not. 1. We interpret self-loops to be chordless cycles, except in multigraphs with multiple loops in parallel. Likewise, in a chordless cycle of length greater than 1, there can be no nodes with self-loops. 2. We interpret directed two-cycles to be chordless cycles, except in multi-digraphs when any edge in a two-cycle has a parallel copy. 3. We interpret parallel pairs of undirected edges as two-cycles, except when a third (or more) parallel edge exists between the two nodes. 4. Generalizing the above, edges with parallel clones may not occur in chordless cycles. In a directed graph, two chordless cycles are distinct if they are not cyclic permutations of each other. In an undirected graph, two chordless cycles are distinct if they are not cyclic permutations of each other nor of the other's reversal. Optionally, the cycles are bounded in length. We use an algorithm strongly inspired by that of Dias et al [1]_. It has been modified in the following ways: 1. Recursion is avoided, per Python's limitations 2. The labeling function is not necessary, because the starting paths are chosen (and deleted from the host graph) to prevent multiple occurrences of the same path 3. The search is optionally bounded at a specified length 4. Support for directed graphs is provided by extending cycles along forward edges, and blocking nodes along forward and reverse edges 5. Support for multigraphs is provided by omitting digons from the set of forward edges Parameters ---------- G : NetworkX DiGraph A directed graph length_bound : int or None, optional (default=None) If length_bound is an int, generate all simple cycles of G with length at most length_bound. Otherwise, generate all simple cycles of G. Yields ------ list of nodes Each cycle is represented by a list of nodes along the cycle. Examples -------- >>> sorted(list(nx.chordless_cycles(nx.complete_graph(4)))) [[1, 0, 2], [1, 0, 3], [2, 0, 3], [2, 1, 3]] Notes ----- When length_bound is None, and the graph is simple, the time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ chordless cycles. Raises ------ ValueError when length_bound < 0. References ---------- .. [1] Efficient enumeration of chordless cycles E. Dias and D. Castonguay and H. Longo and W.A.R. Jradi https://arxiv.org/abs/1309.1051 See Also -------- simple_cycles
def recursive_simple_cycles(G): """Find simple cycles (elementary circuits) of a directed graph. A `simple cycle`, or `elementary circuit`, is a closed path where no node appears twice. Two elementary circuits are distinct if they are not cyclic permutations of each other. This version uses a recursive algorithm to build a list of cycles. You should probably use the iterator version called simple_cycles(). Warning: This recursive version uses lots of RAM! It appears in NetworkX for pedagogical value. Parameters ---------- G : NetworkX DiGraph A directed graph Returns ------- A list of cycles, where each cycle is represented by a list of nodes along the cycle. Example: >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)] >>> G = nx.DiGraph(edges) >>> nx.recursive_simple_cycles(G) [[0], [2], [0, 1, 2], [0, 2], [1, 2]] Notes ----- The implementation follows pp. 79-80 in [1]_. The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ elementary circuits. References ---------- .. [1] Finding all the elementary circuits of a directed graph. D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975. https://doi.org/10.1137/0204007 See Also -------- simple_cycles, cycle_basis """ # Jon Olav Vik, 2010-08-09 def _unblock(thisnode): """Recursively unblock and remove nodes from B[thisnode].""" if blocked[thisnode]: blocked[thisnode] = False while B[thisnode]: _unblock(B[thisnode].pop()) def circuit(thisnode, startnode, component): closed = False # set to True if elementary path is closed path.append(thisnode) blocked[thisnode] = True for nextnode in component[thisnode]: # direct successors of thisnode if nextnode == startnode: result.append(path[:]) closed = True elif not blocked[nextnode]: if circuit(nextnode, startnode, component): closed = True if closed: _unblock(thisnode) else: for nextnode in component[thisnode]: if thisnode not in B[nextnode]: # TODO: use set for speedup? B[nextnode].append(thisnode) path.pop() # remove thisnode from path return closed path = [] # stack of nodes in current path blocked = defaultdict(bool) # vertex: blocked from search? B = defaultdict(list) # graph portions that yield no elementary circuit result = [] # list to accumulate the circuits found # Johnson's algorithm exclude self cycle edges like (v, v) # To be backward compatible, we record those cycles in advance # and then remove from subG for v in G: if G.has_edge(v, v): result.append([v]) G.remove_edge(v, v) # Johnson's algorithm requires some ordering of the nodes. # They might not be sortable so we assign an arbitrary ordering. ordering = dict(zip(G, range(len(G)))) for s in ordering: # Build the subgraph induced by s and following nodes in the ordering subgraph = G.subgraph(node for node in G if ordering[node] >= ordering[s]) # Find the strongly connected component in the subgraph # that contains the least node according to the ordering strongcomp = nx.strongly_connected_components(subgraph) mincomp = min(strongcomp, key=lambda ns: min(ordering[n] for n in ns)) component = G.subgraph(mincomp) if len(component) > 1: # smallest node in the component according to the ordering startnode = min(component, key=ordering.__getitem__) for node in component: blocked[node] = False B[node][:] = [] dummy = circuit(startnode, startnode, component) return result
(G, length_bound=None, *, backend=None, **backend_kwargs)
30,458
networkx.algorithms.polynomials
chromatic_polynomial
Returns the chromatic polynomial of `G` This function computes the chromatic polynomial via an iterative version of the deletion-contraction algorithm. The chromatic polynomial `X_G(x)` is a fundamental graph polynomial invariant in one variable. Evaluating `X_G(k)` for an natural number `k` enumerates the proper k-colorings of `G`. There are several equivalent definitions; here are three: Def 1 (explicit formula): For `G` an undirected graph, `c(G)` the number of connected components of `G`, `E` the edge set of `G`, and `G(S)` the spanning subgraph of `G` with edge set `S` [1]_: .. math:: X_G(x) = \sum_{S \subseteq E} (-1)^{|S|} x^{c(G(S))} Def 2 (interpolating polynomial): For `G` an undirected graph, `n(G)` the number of vertices of `G`, `k_0 = 0`, and `k_i` the number of distinct ways to color the vertices of `G` with `i` unique colors (for `i` a natural number at most `n(G)`), `X_G(x)` is the unique Lagrange interpolating polynomial of degree `n(G)` through the points `(0, k_0), (1, k_1), \dots, (n(G), k_{n(G)})` [2]_. Def 3 (chromatic recurrence): For `G` an undirected graph, `G-e` the graph obtained from `G` by deleting edge `e`, `G/e` the graph obtained from `G` by contracting edge `e`, `n(G)` the number of vertices of `G`, and `e(G)` the number of edges of `G` [3]_: .. math:: X_G(x) = \begin{cases} x^{n(G)}, & \text{if $e(G)=0$} \\ X_{G-e}(x) - X_{G/e}(x), & \text{otherwise, for an arbitrary edge $e$} \end{cases} This formulation is also known as the Fundamental Reduction Theorem [4]_. Parameters ---------- G : NetworkX graph Returns ------- instance of `sympy.core.add.Add` A Sympy expression representing the chromatic polynomial for `G`. Examples -------- >>> C = nx.cycle_graph(5) >>> nx.chromatic_polynomial(C) x**5 - 5*x**4 + 10*x**3 - 10*x**2 + 4*x >>> G = nx.complete_graph(4) >>> nx.chromatic_polynomial(G) x**4 - 6*x**3 + 11*x**2 - 6*x Notes ----- Interpretation of the coefficients is discussed in [5]_. Several special cases are listed in [2]_. The chromatic polynomial is a specialization of the Tutte polynomial; in particular, ``X_G(x) = T_G(x, 0)`` [6]_. The chromatic polynomial may take negative arguments, though evaluations may not have chromatic interpretations. For instance, ``X_G(-1)`` enumerates the acyclic orientations of `G` [7]_. References ---------- .. [1] D. B. West, "Introduction to Graph Theory," p. 222 .. [2] E. W. Weisstein "Chromatic Polynomial" MathWorld--A Wolfram Web Resource https://mathworld.wolfram.com/ChromaticPolynomial.html .. [3] D. B. West, "Introduction to Graph Theory," p. 221 .. [4] J. Zhang, J. Goodall, "An Introduction to Chromatic Polynomials" https://math.mit.edu/~apost/courses/18.204_2018/Julie_Zhang_paper.pdf .. [5] R. C. Read, "An Introduction to Chromatic Polynomials" Journal of Combinatorial Theory, 1968 https://math.berkeley.edu/~mrklug/ReadChromatic.pdf .. [6] W. T. Tutte, "Graph-polynomials" Advances in Applied Mathematics, 2004 https://www.sciencedirect.com/science/article/pii/S0196885803000411 .. [7] R. P. Stanley, "Acyclic orientations of graphs" Discrete Mathematics, 2006 https://math.mit.edu/~rstan/pubs/pubfiles/18.pdf
null
(G, *, backend=None, **backend_kwargs)
30,459
networkx.generators.small
chvatal_graph
Returns the Chvátal Graph The Chvátal Graph is an undirected graph with 12 nodes and 24 edges [1]_. It has 370 distinct (directed) Hamiltonian cycles, giving a unique generalized LCF notation of order 4, two of order 6 , and 43 of order 1 [2]_. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph The Chvátal graph with 12 nodes and 24 edges References ---------- .. [1] https://en.wikipedia.org/wiki/Chv%C3%A1tal_graph .. [2] https://mathworld.wolfram.com/ChvatalGraph.html
def _raise_on_directed(func): """ A decorator which inspects the `create_using` argument and raises a NetworkX exception when `create_using` is a DiGraph (class or instance) for graph generators that do not support directed outputs. """ @wraps(func) def wrapper(*args, **kwargs): if kwargs.get("create_using") is not None: G = nx.empty_graph(create_using=kwargs["create_using"]) if G.is_directed(): raise NetworkXError("Directed Graph not supported") return func(*args, **kwargs) return wrapper
(create_using=None, *, backend=None, **backend_kwargs)
30,460
networkx.generators.classic
circulant_graph
Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes. The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$ such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$ for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph. .. plot:: >>> nx.draw(nx.circulant_graph(10, [1])) Parameters ---------- n : integer The number of nodes in the graph. offsets : list of integers A list of node offsets, $x_1$ up to $x_m$, as described above. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- NetworkX Graph of type create_using Examples -------- Many well-known graph families are subfamilies of the circulant graphs; for example, to create the cycle graph on n points, we connect every node to nodes on either side (with offset plus or minus one). For n = 10, >>> G = nx.circulant_graph(10, [1]) >>> edges = [ ... (0, 9), ... (0, 1), ... (1, 2), ... (2, 3), ... (3, 4), ... (4, 5), ... (5, 6), ... (6, 7), ... (7, 8), ... (8, 9), ... ] >>> sorted(edges) == sorted(G.edges()) True Similarly, we can create the complete graph on 5 points with the set of offsets [1, 2]: >>> G = nx.circulant_graph(5, [1, 2]) >>> edges = [ ... (0, 1), ... (0, 2), ... (0, 3), ... (0, 4), ... (1, 2), ... (1, 3), ... (1, 4), ... (2, 3), ... (2, 4), ... (3, 4), ... ] >>> sorted(edges) == sorted(G.edges()) True
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(n, offsets, create_using=None, *, backend=None, **backend_kwargs)
30,461
networkx.generators.classic
circular_ladder_graph
Returns the circular ladder graph $CL_n$ of length n. $CL_n$ consists of two concentric n-cycles in which each of the n pairs of concentric nodes are joined by an edge. Node labels are the integers 0 to n-1 .. plot:: >>> nx.draw(nx.circular_ladder_graph(5))
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(n, create_using=None, *, backend=None, **backend_kwargs)
30,462
networkx.drawing.layout
circular_layout
Position nodes on a circle. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int Dimension of layout. If dim>2, the remaining dimensions are set to zero in the returned positions. If dim<2, a ValueError is raised. Returns ------- pos : dict A dictionary of positions keyed by node Raises ------ ValueError If dim < 2 Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.circular_layout(G) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
def circular_layout(G, scale=1, center=None, dim=2): # dim=2 only """Position nodes on a circle. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int Dimension of layout. If dim>2, the remaining dimensions are set to zero in the returned positions. If dim<2, a ValueError is raised. Returns ------- pos : dict A dictionary of positions keyed by node Raises ------ ValueError If dim < 2 Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.circular_layout(G) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings. """ import numpy as np if dim < 2: raise ValueError("cannot handle dimensions < 2") G, center = _process_params(G, center, dim) paddims = max(0, (dim - 2)) if len(G) == 0: pos = {} elif len(G) == 1: pos = {nx.utils.arbitrary_element(G): center} else: # Discard the extra angle since it matches 0 radians. theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi theta = theta.astype(np.float32) pos = np.column_stack( [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))] ) pos = rescale_layout(pos, scale=scale) + center pos = dict(zip(G, pos)) return pos
(G, scale=1, center=None, dim=2)
30,467
networkx.algorithms.centrality.closeness
closeness_centrality
Compute closeness centrality for nodes. Closeness centrality [1]_ of a node `u` is the reciprocal of the average shortest path distance to `u` over all `n-1` reachable nodes. .. math:: C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)}, where `d(v, u)` is the shortest-path distance between `v` and `u`, and `n-1` is the number of nodes reachable from `u`. Notice that the closeness distance function computes the incoming distance to `u` for directed graphs. To use outward distance, act on `G.reverse()`. Notice that higher values of closeness indicate higher centrality. Wasserman and Faust propose an improved formula for graphs with more than one connected component. The result is "a ratio of the fraction of actors in the group who are reachable, to the average distance" from the reachable actors [2]_. You might think this scale factor is inverted but it is not. As is, nodes from small components receive a smaller closeness value. Letting `N` denote the number of nodes in the graph, .. math:: C_{WF}(u) = \frac{n-1}{N-1} \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)}, Parameters ---------- G : graph A NetworkX graph u : node, optional Return only the value for node u distance : edge attribute key, optional (default=None) Use the specified edge attribute as the edge distance in shortest path calculations. If `None` (the default) all edges have a distance of 1. Absent edge attributes are assigned a distance of 1. Note that no check is performed to ensure that edges have the provided attribute. wf_improved : bool, optional (default=True) If True, scale by the fraction of nodes reachable. This gives the Wasserman and Faust improved formula. For single component graphs it is the same as the original formula. Returns ------- nodes : dictionary Dictionary of nodes with closeness centrality as the value. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)]) >>> nx.closeness_centrality(G) {0: 1.0, 1: 1.0, 2: 0.75, 3: 0.75} See Also -------- betweenness_centrality, load_centrality, eigenvector_centrality, degree_centrality, incremental_closeness_centrality Notes ----- The closeness centrality is normalized to `(n-1)/(|G|-1)` where `n` is the number of nodes in the connected part of graph containing the node. If the graph is not completely connected, this algorithm computes the closeness centrality for each connected part separately scaled by that parts size. If the 'distance' keyword is set to an edge attribute key then the shortest-path length will be computed using Dijkstra's algorithm with that edge attribute as the edge weight. The closeness centrality uses *inward* distance to a node, not outward. If you want to use outword distances apply the function to `G.reverse()` In NetworkX 2.2 and earlier a bug caused Dijkstra's algorithm to use the outward distance rather than the inward distance. If you use a 'distance' keyword and a DiGraph, your results will change between v2.2 and v2.3. References ---------- .. [1] Linton C. Freeman: Centrality in networks: I. Conceptual clarification. Social Networks 1:215-239, 1979. https://doi.org/10.1016/0378-8733(78)90021-7 .. [2] pg. 201 of Wasserman, S. and Faust, K., Social Network Analysis: Methods and Applications, 1994, Cambridge University Press.
null
(G, u=None, distance=None, wf_improved=True, *, backend=None, **backend_kwargs)
30,468
networkx.algorithms.vitality
closeness_vitality
Returns the closeness vitality for nodes in the graph. The *closeness vitality* of a node, defined in Section 3.6.2 of [1], is the change in the sum of distances between all node pairs when excluding that node. Parameters ---------- G : NetworkX graph A strongly-connected graph. weight : string The name of the edge attribute used as weight. This is passed directly to the :func:`~networkx.wiener_index` function. node : object If specified, only the closeness vitality for this node will be returned. Otherwise, a dictionary mapping each node to its closeness vitality will be returned. Other parameters ---------------- wiener_index : number If you have already computed the Wiener index of the graph `G`, you can provide that value here. Otherwise, it will be computed for you. Returns ------- dictionary or float If `node` is None, this function returns a dictionary with nodes as keys and closeness vitality as the value. Otherwise, it returns only the closeness vitality for the specified `node`. The closeness vitality of a node may be negative infinity if removing that node would disconnect the graph. Examples -------- >>> G = nx.cycle_graph(3) >>> nx.closeness_vitality(G) {0: 2.0, 1: 2.0, 2: 2.0} See Also -------- closeness_centrality References ---------- .. [1] Ulrik Brandes, Thomas Erlebach (eds.). *Network Analysis: Methodological Foundations*. Springer, 2005. <http://books.google.com/books?id=TTNhSm7HYrIC>
null
(G, node=None, weight=None, wiener_index=None, *, backend=None, **backend_kwargs)
30,470
networkx.algorithms.cluster
clustering
Compute the clustering coefficient for nodes. For unweighted graphs, the clustering of a node :math:`u` is the fraction of possible triangles through that node that exist, .. math:: c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)}, where :math:`T(u)` is the number of triangles through node :math:`u` and :math:`deg(u)` is the degree of :math:`u`. For weighted graphs, there are several ways to define clustering [1]_. the one used here is defined as the geometric average of the subgraph edge weights [2]_, .. math:: c_u = \frac{1}{deg(u)(deg(u)-1))} \sum_{vw} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}. The edge weights :math:`\hat{w}_{uv}` are normalized by the maximum weight in the network :math:`\hat{w}_{uv} = w_{uv}/\max(w)`. The value of :math:`c_u` is assigned to 0 if :math:`deg(u) < 2`. Additionally, this weighted definition has been generalized to support negative edge weights [3]_. For directed graphs, the clustering is similarly defined as the fraction of all possible directed triangles or geometric average of the subgraph edge weights for unweighted and weighted directed graph respectively [4]_. .. math:: c_u = \frac{T(u)}{2(deg^{tot}(u)(deg^{tot}(u)-1) - 2deg^{\leftrightarrow}(u))}, where :math:`T(u)` is the number of directed triangles through node :math:`u`, :math:`deg^{tot}(u)` is the sum of in degree and out degree of :math:`u` and :math:`deg^{\leftrightarrow}(u)` is the reciprocal degree of :math:`u`. Parameters ---------- G : graph nodes : node, iterable of nodes, or None (default=None) If a singleton node, return the number of triangles for that node. If an iterable, compute the number of triangles for each of those nodes. If `None` (the default) compute the number of triangles for all nodes in `G`. weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. Returns ------- out : float, or dictionary Clustering coefficient at specified nodes Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.clustering(G, 0)) 1.0 >>> print(nx.clustering(G)) {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0} Notes ----- Self loops are ignored. References ---------- .. [1] Generalizations of the clustering coefficient to weighted complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela, K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007). http://jponnela.com/web_documents/a9.pdf .. [2] Intensity and coherence of motifs in weighted complex networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski, Physical Review E, 71(6), 065103 (2005). .. [3] Generalization of Clustering Coefficients to Signed Correlation Networks by G. Costantini and M. Perugini, PloS one, 9(2), e88669 (2014). .. [4] Clustering in complex directed networks by G. Fagiolo, Physical Review E, 76(2), 026107 (2007).
null
(G, nodes=None, weight=None, *, backend=None, **backend_kwargs)
30,471
networkx.algorithms.link_prediction
cn_soundarajan_hopcroft
Count the number of common neighbors of all node pairs in ebunch using community information. For two nodes $u$ and $v$, this function computes the number of common neighbors and bonus one for each common neighbor belonging to the same community as $u$ and $v$. Mathematically, .. math:: |\Gamma(u) \cap \Gamma(v)| + \sum_{w \in \Gamma(u) \cap \Gamma(v)} f(w) where $f(w)$ equals 1 if $w$ belongs to the same community as $u$ and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of neighbors of $u$. Parameters ---------- G : graph A NetworkX undirected graph. ebunch : iterable of node pairs, optional (default = None) The score will be computed for each pair of nodes given in the iterable. The pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then all nonexistent edges in the graph will be used. Default value: None. community : string, optional (default = 'community') Nodes attribute name containing the community information. G[u][community] identifies which community u belongs to. Each node belongs to at most one community. Default value: 'community'. Returns ------- piter : iterator An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their score. Raises ------ NetworkXNotImplemented If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`. NetworkXAlgorithmError If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`). NodeNotFound If `ebunch` has a node that is not in `G`. Examples -------- >>> G = nx.path_graph(3) >>> G.nodes[0]["community"] = 0 >>> G.nodes[1]["community"] = 0 >>> G.nodes[2]["community"] = 0 >>> preds = nx.cn_soundarajan_hopcroft(G, [(0, 2)]) >>> for u, v, p in preds: ... print(f"({u}, {v}) -> {p}") (0, 2) -> 2 References ---------- .. [1] Sucheta Soundarajan and John Hopcroft. Using community information to improve the precision of link prediction methods. In Proceedings of the 21st international conference companion on World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608. http://doi.acm.org/10.1145/2187980.2188150
null
(G, ebunch=None, community='community', *, backend=None, **backend_kwargs)
30,474
networkx.algorithms.planar_drawing
combinatorial_embedding_to_pos
Assigns every node a (x, y) position based on the given embedding The algorithm iteratively inserts nodes of the input graph in a certain order and rearranges previously inserted nodes so that the planar drawing stays valid. This is done efficiently by only maintaining relative positions during the node placements and calculating the absolute positions at the end. For more information see [1]_. Parameters ---------- embedding : nx.PlanarEmbedding This defines the order of the edges fully_triangulate : bool If set to True the algorithm adds edges to a copy of the input embedding and makes it chordal. Returns ------- pos : dict Maps each node to a tuple that defines the (x, y) position References ---------- .. [1] M. Chrobak and T.H. Payne: A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677
def combinatorial_embedding_to_pos(embedding, fully_triangulate=False): """Assigns every node a (x, y) position based on the given embedding The algorithm iteratively inserts nodes of the input graph in a certain order and rearranges previously inserted nodes so that the planar drawing stays valid. This is done efficiently by only maintaining relative positions during the node placements and calculating the absolute positions at the end. For more information see [1]_. Parameters ---------- embedding : nx.PlanarEmbedding This defines the order of the edges fully_triangulate : bool If set to True the algorithm adds edges to a copy of the input embedding and makes it chordal. Returns ------- pos : dict Maps each node to a tuple that defines the (x, y) position References ---------- .. [1] M. Chrobak and T.H. Payne: A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677 """ if len(embedding.nodes()) < 4: # Position the node in any triangle default_positions = [(0, 0), (2, 0), (1, 1)] pos = {} for i, v in enumerate(embedding.nodes()): pos[v] = default_positions[i] return pos embedding, outer_face = triangulate_embedding(embedding, fully_triangulate) # The following dicts map a node to another node # If a node is not in the key set it means that the node is not yet in G_k # If a node maps to None then the corresponding subtree does not exist left_t_child = {} right_t_child = {} # The following dicts map a node to an integer delta_x = {} y_coordinate = {} node_list = get_canonical_ordering(embedding, outer_face) # 1. Phase: Compute relative positions # Initialization v1, v2, v3 = node_list[0][0], node_list[1][0], node_list[2][0] delta_x[v1] = 0 y_coordinate[v1] = 0 right_t_child[v1] = v3 left_t_child[v1] = None delta_x[v2] = 1 y_coordinate[v2] = 0 right_t_child[v2] = None left_t_child[v2] = None delta_x[v3] = 1 y_coordinate[v3] = 1 right_t_child[v3] = v2 left_t_child[v3] = None for k in range(3, len(node_list)): vk, contour_nbrs = node_list[k] wp = contour_nbrs[0] wp1 = contour_nbrs[1] wq = contour_nbrs[-1] wq1 = contour_nbrs[-2] adds_mult_tri = len(contour_nbrs) > 2 # Stretch gaps: delta_x[wp1] += 1 delta_x[wq] += 1 delta_x_wp_wq = sum(delta_x[x] for x in contour_nbrs[1:]) # Adjust offsets delta_x[vk] = (-y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2 y_coordinate[vk] = (y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2 delta_x[wq] = delta_x_wp_wq - delta_x[vk] if adds_mult_tri: delta_x[wp1] -= delta_x[vk] # Install v_k: right_t_child[wp] = vk right_t_child[vk] = wq if adds_mult_tri: left_t_child[vk] = wp1 right_t_child[wq1] = None else: left_t_child[vk] = None # 2. Phase: Set absolute positions pos = {} pos[v1] = (0, y_coordinate[v1]) remaining_nodes = [v1] while remaining_nodes: parent_node = remaining_nodes.pop() # Calculate position for left child set_position( parent_node, left_t_child, remaining_nodes, delta_x, y_coordinate, pos ) # Calculate position for right child set_position( parent_node, right_t_child, remaining_nodes, delta_x, y_coordinate, pos ) return pos
(embedding, fully_triangulate=False)
30,475
networkx.algorithms.link_prediction
common_neighbor_centrality
Return the CCPA score for each pair of nodes. Compute the Common Neighbor and Centrality based Parameterized Algorithm(CCPA) score of all node pairs in ebunch. CCPA score of `u` and `v` is defined as .. math:: \alpha \cdot (|\Gamma (u){\cap }^{}\Gamma (v)|)+(1-\alpha )\cdot \frac{N}{{d}_{uv}} where $\Gamma(u)$ denotes the set of neighbors of $u$, $\Gamma(v)$ denotes the set of neighbors of $v$, $\alpha$ is parameter varies between [0,1], $N$ denotes total number of nodes in the Graph and ${d}_{uv}$ denotes shortest distance between $u$ and $v$. This algorithm is based on two vital properties of nodes, namely the number of common neighbors and their centrality. Common neighbor refers to the common nodes between two nodes. Centrality refers to the prestige that a node enjoys in a network. .. seealso:: :func:`common_neighbors` Parameters ---------- G : graph NetworkX undirected graph. ebunch : iterable of node pairs, optional (default = None) Preferential attachment score will be computed for each pair of nodes given in the iterable. The pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then all nonexistent edges in the graph will be used. Default value: None. alpha : Parameter defined for participation of Common Neighbor and Centrality Algorithm share. Values for alpha should normally be between 0 and 1. Default value set to 0.8 because author found better performance at 0.8 for all the dataset. Default value: 0.8 Returns ------- piter : iterator An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their Common Neighbor and Centrality based Parameterized Algorithm(CCPA) score. Raises ------ NetworkXNotImplemented If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`. NetworkXAlgorithmError If self loops exsists in `ebunch` or in `G` (if `ebunch` is `None`). NodeNotFound If `ebunch` has a node that is not in `G`. Examples -------- >>> G = nx.complete_graph(5) >>> preds = nx.common_neighbor_centrality(G, [(0, 1), (2, 3)]) >>> for u, v, p in preds: ... print(f"({u}, {v}) -> {p}") (0, 1) -> 3.4000000000000004 (2, 3) -> 3.4000000000000004 References ---------- .. [1] Ahmad, I., Akhtar, M.U., Noor, S. et al. Missing Link Prediction using Common Neighbor and Centrality based Parameterized Algorithm. Sci Rep 10, 364 (2020). https://doi.org/10.1038/s41598-019-57304-y
null
(G, ebunch=None, alpha=0.8, *, backend=None, **backend_kwargs)
30,476
networkx.classes.function
common_neighbors
Returns the common neighbors of two nodes in a graph. Parameters ---------- G : graph A NetworkX undirected graph. u, v : nodes Nodes in the graph. Returns ------- cnbors : set Set of common neighbors of u and v in the graph. Raises ------ NetworkXError If u or v is not a node in the graph. Examples -------- >>> G = nx.complete_graph(5) >>> sorted(nx.common_neighbors(G, 0, 1)) [2, 3, 4]
def set_edge_attributes(G, values, name=None): """Sets edge attributes from a given value or dictionary of values. .. Warning:: The call order of arguments `values` and `name` switched between v1.x & v2.x. Parameters ---------- G : NetworkX Graph values : scalar value, dict-like What the edge attribute should be set to. If `values` is not a dictionary, then it is treated as a single attribute value that is then applied to every edge in `G`. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the edge attribute for each edge. The attribute name will be `name`. If `values` is a dict or a dict of dict, it should be keyed by edge tuple to either an attribute value or a dict of attribute key/value pairs used to update the edge's attributes. For multigraphs, the edge tuples must be of the form ``(u, v, key)``, where `u` and `v` are nodes and `key` is the edge key. For non-multigraphs, the keys must be tuples of the form ``(u, v)``. name : string (optional, default=None) Name of the edge attribute to set if values is a scalar. Examples -------- After computing some property of the edges of a graph, you may want to assign a edge attribute to store the value of that property for each edge:: >>> G = nx.path_graph(3) >>> bb = nx.edge_betweenness_centrality(G, normalized=False) >>> nx.set_edge_attributes(G, bb, "betweenness") >>> G.edges[1, 2]["betweenness"] 2.0 If you provide a list as the second argument, updates to the list will be reflected in the edge attribute for each edge:: >>> labels = [] >>> nx.set_edge_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.edges[0, 1]["labels"] ['foo'] >>> G.edges[1, 2]["labels"] ['foo'] If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update edge attributes:: >>> G = nx.path_graph(3) >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}} >>> nx.set_edge_attributes(G, attrs) >>> G[0][1]["attr1"] 20 >>> G[0][1]["attr2"] 'nothing' >>> G[1][2]["attr2"] 3 The attributes of one Graph can be used to set those of another. >>> H = nx.path_graph(3) >>> nx.set_edge_attributes(H, G.edges) Note that if the dict contains edges that are not in `G`, they are silently ignored:: >>> G = nx.Graph([(0, 1)]) >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}}) >>> (1, 2) in G.edges() False For multigraphs, the `values` dict is expected to be keyed by 3-tuples including the edge key:: >>> MG = nx.MultiGraph() >>> edges = [(0, 1), (0, 1)] >>> MG.add_edges_from(edges) # Returns list of edge keys [0, 1] >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}} >>> nx.set_edge_attributes(MG, attributes) >>> MG[0][1][0]["cost"] 21 >>> MG[0][1][1]["cost"] 7 If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple multiedge to a 2-tuple edge and the last multiedge's attribute value will overwrite the previous values. Continuing from the previous case we get:: >>> H = nx.path_graph([0, 1, 2]) >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()}) >>> nx.get_edge_attributes(H, "cost") {(0, 1): 7} """ if name is not None: # `values` does not contain attribute names try: # if `values` is a dict using `.items()` => {edge: value} if G.is_multigraph(): for (u, v, key), value in values.items(): try: G._adj[u][v][key][name] = value except KeyError: pass else: for (u, v), value in values.items(): try: G._adj[u][v][name] = value except KeyError: pass except AttributeError: # treat `values` as a constant for u, v, data in G.edges(data=True): data[name] = values else: # `values` consists of doct-of-dict {edge: {attr: value}} shape if G.is_multigraph(): for (u, v, key), d in values.items(): try: G._adj[u][v][key].update(d) except KeyError: pass else: for (u, v), d in values.items(): try: G._adj[u][v].update(d) except KeyError: pass nx._clear_cache(G)
(G, u, v)
30,477
networkx.algorithms.communicability_alg
communicability
Returns communicability between all pairs of nodes in G. The communicability between pairs of nodes in G is the sum of walks of different lengths starting at node u and ending at node v. Parameters ---------- G: graph Returns ------- comm: dictionary of dictionaries Dictionary of dictionaries keyed by nodes with communicability as the value. Raises ------ NetworkXError If the graph is not undirected and simple. See Also -------- communicability_exp: Communicability between all pairs of nodes in G using spectral decomposition. communicability_betweenness_centrality: Communicability betweenness centrality for each node in G. Notes ----- This algorithm uses a spectral decomposition of the adjacency matrix. Let G=(V,E) be a simple undirected graph. Using the connection between the powers of the adjacency matrix and the number of walks in the graph, the communicability between nodes `u` and `v` based on the graph spectrum is [1]_ .. math:: C(u,v)=\sum_{j=1}^{n}\phi_{j}(u)\phi_{j}(v)e^{\lambda_{j}}, where `\phi_{j}(u)` is the `u\rm{th}` element of the `j\rm{th}` orthonormal eigenvector of the adjacency matrix associated with the eigenvalue `\lambda_{j}`. References ---------- .. [1] Ernesto Estrada, Naomichi Hatano, "Communicability in complex networks", Phys. Rev. E 77, 036111 (2008). https://arxiv.org/abs/0707.0756 Examples -------- >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) >>> c = nx.communicability(G)
null
(G, *, backend=None, **backend_kwargs)
30,479
networkx.algorithms.centrality.subgraph_alg
communicability_betweenness_centrality
Returns subgraph communicability for all pairs of nodes in G. Communicability betweenness measure makes use of the number of walks connecting every pair of nodes as the basis of a betweenness centrality measure. Parameters ---------- G: graph Returns ------- nodes : dictionary Dictionary of nodes with communicability betweenness as the value. Raises ------ NetworkXError If the graph is not undirected and simple. Notes ----- Let `G=(V,E)` be a simple undirected graph with `n` nodes and `m` edges, and `A` denote the adjacency matrix of `G`. Let `G(r)=(V,E(r))` be the graph resulting from removing all edges connected to node `r` but not the node itself. The adjacency matrix for `G(r)` is `A+E(r)`, where `E(r)` has nonzeros only in row and column `r`. The subraph betweenness of a node `r` is [1]_ .. math:: \omega_{r} = \frac{1}{C}\sum_{p}\sum_{q}\frac{G_{prq}}{G_{pq}}, p\neq q, q\neq r, where `G_{prq}=(e^{A}_{pq} - (e^{A+E(r)})_{pq}` is the number of walks involving node r, `G_{pq}=(e^{A})_{pq}` is the number of closed walks starting at node `p` and ending at node `q`, and `C=(n-1)^{2}-(n-1)` is a normalization factor equal to the number of terms in the sum. The resulting `\omega_{r}` takes values between zero and one. The lower bound cannot be attained for a connected graph, and the upper bound is attained in the star graph. References ---------- .. [1] Ernesto Estrada, Desmond J. Higham, Naomichi Hatano, "Communicability Betweenness in Complex Networks" Physica A 388 (2009) 764-774. https://arxiv.org/abs/0905.4102 Examples -------- >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) >>> cbc = nx.communicability_betweenness_centrality(G) >>> print([f"{node} {cbc[node]:0.2f}" for node in sorted(cbc)]) ['0 0.03', '1 0.45', '2 0.51', '3 0.45', '4 0.40', '5 0.19', '6 0.03']
null
(G, *, backend=None, **backend_kwargs)
30,480
networkx.algorithms.communicability_alg
communicability_exp
Returns communicability between all pairs of nodes in G. Communicability between pair of node (u,v) of node in G is the sum of walks of different lengths starting at node u and ending at node v. Parameters ---------- G: graph Returns ------- comm: dictionary of dictionaries Dictionary of dictionaries keyed by nodes with communicability as the value. Raises ------ NetworkXError If the graph is not undirected and simple. See Also -------- communicability: Communicability between pairs of nodes in G. communicability_betweenness_centrality: Communicability betweenness centrality for each node in G. Notes ----- This algorithm uses matrix exponentiation of the adjacency matrix. Let G=(V,E) be a simple undirected graph. Using the connection between the powers of the adjacency matrix and the number of walks in the graph, the communicability between nodes u and v is [1]_, .. math:: C(u,v) = (e^A)_{uv}, where `A` is the adjacency matrix of G. References ---------- .. [1] Ernesto Estrada, Naomichi Hatano, "Communicability in complex networks", Phys. Rev. E 77, 036111 (2008). https://arxiv.org/abs/0707.0756 Examples -------- >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)]) >>> c = nx.communicability_exp(G)
null
(G, *, backend=None, **backend_kwargs)
30,482
networkx.algorithms.operators.unary
complement
Returns the graph complement of G. Parameters ---------- G : graph A NetworkX graph Returns ------- GC : A new graph. Notes ----- Note that `complement` does not create self-loops and also does not produce parallel edges for MultiGraphs. Graph, node, and edge data are not propagated to the new graph. Examples -------- >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)]) >>> G_complement = nx.complement(G) >>> G_complement.edges() # This shows the edges of the complemented graph EdgeView([(1, 4), (1, 5), (2, 4), (2, 5), (4, 5)])
null
(G, *, backend=None, **backend_kwargs)
30,483
networkx.algorithms.bipartite.generators
complete_bipartite_graph
Returns the complete bipartite graph `K_{n_1,n_2}`. The graph is composed of two partitions with nodes 0 to (n1 - 1) in the first and nodes n1 to (n1 + n2 - 1) in the second. Each node in the first is connected to each node in the second. Parameters ---------- n1, n2 : integer or iterable container of nodes If integers, nodes are from `range(n1)` and `range(n1, n1 + n2)`. If a container, the elements are the nodes. create_using : NetworkX graph instance, (default: nx.Graph) Return graph of this type. Notes ----- Nodes are the integers 0 to `n1 + n2 - 1` unless either n1 or n2 are containers of nodes. If only one of n1 or n2 are integers, that integer is replaced by `range` of that integer. The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to. This function is not imported in the main namespace. To use it use nx.bipartite.complete_bipartite_graph
null
(n1, n2, create_using=None, *, backend=None, **backend_kwargs)
30,484
networkx.generators.classic
complete_graph
Return the complete graph `K_n` with n nodes. A complete graph on `n` nodes means that all pairs of distinct nodes have an edge connecting them. .. plot:: >>> nx.draw(nx.complete_graph(5)) Parameters ---------- n : int or iterable container of nodes If n is an integer, nodes are from range(n). If n is a container of nodes, those nodes appear in the graph. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Examples -------- >>> G = nx.complete_graph(9) >>> len(G) 9 >>> G.size() 36 >>> G = nx.complete_graph(range(11, 14)) >>> list(G.nodes()) [11, 12, 13] >>> G = nx.complete_graph(4, nx.DiGraph()) >>> G.is_directed() True
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(n, create_using=None, *, backend=None, **backend_kwargs)
30,485
networkx.generators.classic
complete_multipartite_graph
Returns the complete multipartite graph with the specified subset sizes. .. plot:: >>> nx.draw(nx.complete_multipartite_graph(1, 2, 3)) Parameters ---------- subset_sizes : tuple of integers or tuple of node iterables The arguments can either all be integer number of nodes or they can all be iterables of nodes. If integers, they represent the number of nodes in each subset of the multipartite graph. If iterables, each is used to create the nodes for that subset. The length of subset_sizes is the number of subsets. Returns ------- G : NetworkX Graph Returns the complete multipartite graph with the specified subsets. For each node, the node attribute 'subset' is an integer indicating which subset contains the node. Examples -------- Creating a complete tripartite graph, with subsets of one, two, and three nodes, respectively. >>> G = nx.complete_multipartite_graph(1, 2, 3) >>> [G.nodes[u]["subset"] for u in G] [0, 1, 1, 2, 2, 2] >>> list(G.edges(0)) [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)] >>> list(G.edges(2)) [(2, 0), (2, 3), (2, 4), (2, 5)] >>> list(G.edges(4)) [(4, 0), (4, 1), (4, 2)] >>> G = nx.complete_multipartite_graph("a", "bc", "def") >>> [G.nodes[u]["subset"] for u in sorted(G)] [0, 1, 1, 2, 2, 2] Notes ----- This function generalizes several other graph builder functions. - If no subset sizes are given, this returns the null graph. - If a single subset size `n` is given, this returns the empty graph on `n` nodes. - If two subset sizes `m` and `n` are given, this returns the complete bipartite graph on `m + n` nodes. - If subset sizes `1` and `n` are given, this returns the star graph on `n + 1` nodes. See also -------- complete_bipartite_graph
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(*subset_sizes, backend=None, **backend_kwargs)
30,486
networkx.algorithms.chordal
complete_to_chordal_graph
Return a copy of G completed to a chordal graph Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is called chordal if for each cycle with length bigger than 3, there exist two non-adjacent nodes connected by an edge (called a chord). Parameters ---------- G : NetworkX graph Undirected graph Returns ------- H : NetworkX graph The chordal enhancement of G alpha : Dictionary The elimination ordering of nodes of G Notes ----- There are different approaches to calculate the chordal enhancement of a graph. The algorithm used here is called MCS-M and gives at least minimal (local) triangulation of graph. Note that this triangulation is not necessarily a global minimum. https://en.wikipedia.org/wiki/Chordal_graph References ---------- .. [1] Berry, Anne & Blair, Jean & Heggernes, Pinar & Peyton, Barry. (2004) Maximum Cardinality Search for Computing Minimal Triangulations of Graphs. Algorithmica. 39. 287-298. 10.1007/s00453-004-1084-3. Examples -------- >>> from networkx.algorithms.chordal import complete_to_chordal_graph >>> G = nx.wheel_graph(10) >>> H, alpha = complete_to_chordal_graph(G)
null
(G, *, backend=None, **backend_kwargs)
30,488
networkx.algorithms.operators.binary
compose
Compose graph G with H by combining nodes and edges into a single graph. The node sets and edges sets do not need to be disjoint. Composing preserves the attributes of nodes and edges. Attribute values from H take precedent over attribute values from G. Parameters ---------- G, H : graph A NetworkX graph Returns ------- C: A new graph with the same type as G See Also -------- :func:`~networkx.Graph.update` union disjoint_union Notes ----- It is recommended that G and H be either both directed or both undirected. For MultiGraphs, the edges are identified by incident nodes AND edge-key. This can cause surprises (i.e., edge `(1, 2)` may or may not be the same in two graphs) if you use MultiGraph without keeping track of edge keys. If combining the attributes of common nodes is not desired, consider union(), which raises an exception for name collisions. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2)]) >>> H = nx.Graph([(0, 1), (1, 2)]) >>> R = nx.compose(G, H) >>> R.nodes NodeView((0, 1, 2)) >>> R.edges EdgeView([(0, 1), (0, 2), (1, 2)]) By default, the attributes from `H` take precedent over attributes from `G`. If you prefer another way of combining attributes, you can update them after the compose operation: >>> G = nx.Graph([(0, 1, {"weight": 2.0}), (3, 0, {"weight": 100.0})]) >>> H = nx.Graph([(0, 1, {"weight": 10.0}), (1, 2, {"weight": -1.0})]) >>> nx.set_node_attributes(G, {0: "dark", 1: "light", 3: "black"}, name="color") >>> nx.set_node_attributes(H, {0: "green", 1: "orange", 2: "yellow"}, name="color") >>> GcomposeH = nx.compose(G, H) Normally, color attribute values of nodes of GcomposeH come from H. We can workaround this as follows: >>> node_data = { ... n: G.nodes[n]["color"] + " " + H.nodes[n]["color"] for n in G.nodes & H.nodes ... } >>> nx.set_node_attributes(GcomposeH, node_data, "color") >>> print(GcomposeH.nodes[0]["color"]) dark green >>> print(GcomposeH.nodes[3]["color"]) black Similarly, we can update edge attributes after the compose operation in a way we prefer: >>> edge_data = { ... e: G.edges[e]["weight"] * H.edges[e]["weight"] for e in G.edges & H.edges ... } >>> nx.set_edge_attributes(GcomposeH, edge_data, "weight") >>> print(GcomposeH.edges[(0, 1)]["weight"]) 20.0 >>> print(GcomposeH.edges[(3, 0)]["weight"]) 100.0
null
(G, H, *, backend=None, **backend_kwargs)
30,489
networkx.algorithms.operators.all
compose_all
Returns the composition of all graphs. Composition is the simple union of the node sets and edge sets. The node sets of the supplied graphs need not be disjoint. Parameters ---------- graphs : iterable Iterable of NetworkX graphs Returns ------- C : A graph with the same type as the first graph in list Raises ------ ValueError If `graphs` is an empty list. NetworkXError In case of mixed type graphs, like MultiGraph and Graph, or directed and undirected graphs. Examples -------- >>> G1 = nx.Graph([(1, 2), (2, 3)]) >>> G2 = nx.Graph([(3, 4), (5, 6)]) >>> C = nx.compose_all([G1, G2]) >>> list(C.nodes()) [1, 2, 3, 4, 5, 6] >>> list(C.edges()) [(1, 2), (2, 3), (3, 4), (5, 6)] Notes ----- For operating on mixed type graphs, they should be converted to the same type. Graph, edge, and node attributes are propagated to the union graph. If a graph attribute is present in multiple graphs, then the value from the last graph in the list with that attribute is used.
null
(graphs, *, backend=None, **backend_kwargs)
30,490
networkx.algorithms.dag
compute_v_structures
Iterate through the graph to compute all v-structures. V-structures are triples in the directed graph where two parent nodes point to the same child and the two parent nodes are not adjacent. Parameters ---------- G : graph A networkx DiGraph. Returns ------- vstructs : iterator of tuples The v structures within the graph. Each v structure is a 3-tuple with the parent, collider, and other parent. Examples -------- >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (0, 5), (3, 1), (2, 4), (3, 1), (4, 5), (1, 5)]) >>> sorted(nx.compute_v_structures(G)) [(0, 5, 1), (0, 5, 4), (1, 5, 4)] Notes ----- `Wikipedia: Collider in causal graphs <https://en.wikipedia.org/wiki/Collider_(statistics)>`_
def transitive_closure_dag(G, topo_order=None): """Returns the transitive closure of a directed acyclic graph. This function is faster than the function `transitive_closure`, but fails if the graph has a cycle. The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that for all v, w in V there is an edge (v, w) in E+ if and only if there is a non-null path from v to w in G. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) topo_order: list or tuple, optional A topological order for G (if None, the function will compute one) Returns ------- NetworkX DiGraph The transitive closure of `G` Raises ------ NetworkXNotImplemented If `G` is not directed NetworkXUnfeasible If `G` has a cycle Examples -------- >>> DG = nx.DiGraph([(1, 2), (2, 3)]) >>> TC = nx.transitive_closure_dag(DG) >>> TC.edges() OutEdgeView([(1, 2), (1, 3), (2, 3)]) Notes ----- This algorithm is probably simple enough to be well-known but I didn't find a mention in the literature. """ if topo_order is None: topo_order = list(topological_sort(G)) TC = G.copy() # idea: traverse vertices following a reverse topological order, connecting # each vertex to its descendants at distance 2 as we go for v in reversed(topo_order): TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2)) return TC
(G, *, backend=None, **backend_kwargs)
30,491
networkx.algorithms.components.strongly_connected
condensation
Returns the condensation of G. The condensation of G is the graph with each of the strongly connected components contracted into a single node. Parameters ---------- G : NetworkX DiGraph A directed graph. scc: list or generator (optional, default=None) Strongly connected components. If provided, the elements in `scc` must partition the nodes in `G`. If not provided, it will be calculated as scc=nx.strongly_connected_components(G). Returns ------- C : NetworkX DiGraph The condensation graph C of G. The node labels are integers corresponding to the index of the component in the list of strongly connected components of G. C has a graph attribute named 'mapping' with a dictionary mapping the original nodes to the nodes in C to which they belong. Each node in C also has a node attribute 'members' with the set of original nodes in G that form the SCC that the node in C represents. Raises ------ NetworkXNotImplemented If G is undirected. Examples -------- Contracting two sets of strongly connected nodes into two distinct SCC using the barbell graph. >>> G = nx.barbell_graph(4, 0) >>> G.remove_edge(3, 4) >>> G = nx.DiGraph(G) >>> H = nx.condensation(G) >>> H.nodes.data() NodeDataView({0: {'members': {0, 1, 2, 3}}, 1: {'members': {4, 5, 6, 7}}}) >>> H.graph["mapping"] {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 1, 7: 1} Contracting a complete graph into one single SCC. >>> G = nx.complete_graph(7, create_using=nx.DiGraph) >>> H = nx.condensation(G) >>> H.nodes NodeView((0,)) >>> H.nodes.data() NodeDataView({0: {'members': {0, 1, 2, 3, 4, 5, 6}}}) Notes ----- After contracting all strongly connected components to a single node, the resulting graph is a directed acyclic graph.
null
(G, scc=None, *, backend=None, **backend_kwargs)
30,492
networkx.algorithms.cuts
conductance
Returns the conductance of two sets of nodes. The *conductance* is the quotient of the cut size and the smaller of the volumes of the two sets. [1] Parameters ---------- G : NetworkX graph S : collection A collection of nodes in `G`. T : collection A collection of nodes in `G`. weight : object Edge attribute key to use as weight. If not specified, edges have weight one. Returns ------- number The conductance between the two sets `S` and `T`. See also -------- cut_size edge_expansion normalized_cut_size volume References ---------- .. [1] David Gleich. *Hierarchical Directed Spectral Graph Partitioning*. <https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
null
(G, S, T=None, weight=None, *, backend=None, **backend_kwargs)
30,493
networkx.generators.degree_seq
configuration_model
Returns a random graph with the given degree sequence. The configuration model generates a random pseudograph (graph with parallel edges and self loops) by randomly assigning edges to match the given degree sequence. Parameters ---------- deg_sequence : list of nonnegative integers Each list entry corresponds to the degree of a node. create_using : NetworkX graph constructor, optional (default MultiGraph) Graph type to create. If graph instance, then cleared before populated. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : MultiGraph A graph with the specified degree sequence. Nodes are labeled starting at 0 with an index corresponding to the position in deg_sequence. Raises ------ NetworkXError If the degree sequence does not have an even sum. See Also -------- is_graphical Notes ----- As described by Newman [1]_. A non-graphical degree sequence (not realizable by some simple graph) is allowed since this function returns graphs with self loops and parallel edges. An exception is raised if the degree sequence does not have an even sum. This configuration model construction process can lead to duplicate edges and loops. You can remove the self-loops and parallel edges (see below) which will likely result in a graph that doesn't have the exact degree sequence specified. The density of self-loops and parallel edges tends to decrease as the number of nodes increases. However, typically the number of self-loops will approach a Poisson distribution with a nonzero mean, and similarly for the number of parallel edges. Consider a node with *k* stubs. The probability of being joined to another stub of the same node is basically (*k* - *1*) / *N*, where *k* is the degree and *N* is the number of nodes. So the probability of a self-loop scales like *c* / *N* for some constant *c*. As *N* grows, this means we expect *c* self-loops. Similarly for parallel edges. References ---------- .. [1] M.E.J. Newman, "The structure and function of complex networks", SIAM REVIEW 45-2, pp 167-256, 2003. Examples -------- You can create a degree sequence following a particular distribution by using the one of the distribution functions in :mod:`~networkx.utils.random_sequence` (or one of your own). For example, to create an undirected multigraph on one hundred nodes with degree sequence chosen from the power law distribution: >>> sequence = nx.random_powerlaw_tree_sequence(100, tries=5000) >>> G = nx.configuration_model(sequence) >>> len(G) 100 >>> actual_degrees = [d for v, d in G.degree()] >>> actual_degrees == sequence True The returned graph is a multigraph, which may have parallel edges. To remove any parallel edges from the returned graph: >>> G = nx.Graph(G) Similarly, to remove self-loops: >>> G.remove_edges_from(nx.selfloop_edges(G))
def generate(self): # remaining_degree is mapping from int->remaining degree self.remaining_degree = dict(enumerate(self.degree)) # add all nodes to make sure we get isolated nodes self.graph = nx.Graph() self.graph.add_nodes_from(self.remaining_degree) # remove zero degree nodes for n, d in list(self.remaining_degree.items()): if d == 0: del self.remaining_degree[n] if len(self.remaining_degree) > 0: # build graph in three phases according to how many unmatched edges self.phase1() self.phase2() self.phase3() return self.graph
(deg_sequence, create_using=None, seed=None, *, backend=None, **backend_kwargs)
30,495
networkx.generators.community
connected_caveman_graph
Returns a connected caveman graph of `l` cliques of size `k`. The connected caveman graph is formed by creating `n` cliques of size `k`, then a single edge in each clique is rewired to a node in an adjacent clique. Parameters ---------- l : int number of cliques k : int size of cliques (k at least 2 or NetworkXError is raised) Returns ------- G : NetworkX Graph connected caveman graph Raises ------ NetworkXError If the size of cliques `k` is smaller than 2. Notes ----- This returns an undirected graph, it can be converted to a directed graph using :func:`nx.to_directed`, or a multigraph using ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is described in [1]_ and it is unclear which of the directed generalizations is most useful. Examples -------- >>> G = nx.connected_caveman_graph(3, 3) References ---------- .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.' Amer. J. Soc. 105, 493-527, 1999.
def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed): """Returns a list of sets, each of which represents a community. ``degree_seq`` is the degree sequence that must be met by the graph. ``community_sizes`` is the community size distribution that must be met by the generated list of sets. ``mu`` is a float in the interval [0, 1] indicating the fraction of intra-community edges incident to each node. ``max_iters`` is the number of times to try to add a node to a community. This must be greater than the length of ``degree_seq``, otherwise this function will always fail. If the number of iterations exceeds this value, :exc:`~networkx.exception.ExceededMaxIterations` is raised. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. The communities returned by this are sets of integers in the set {0, ..., *n* - 1}, where *n* is the length of ``degree_seq``. """ # This assumes the nodes in the graph will be natural numbers. result = [set() for _ in community_sizes] n = len(degree_seq) free = list(range(n)) for i in range(max_iters): v = free.pop() c = seed.choice(range(len(community_sizes))) # s = int(degree_seq[v] * (1 - mu) + 0.5) s = round(degree_seq[v] * (1 - mu)) # If the community is large enough, add the node to the chosen # community. Otherwise, return it to the list of unaffiliated # nodes. if s < community_sizes[c]: result[c].add(v) else: free.append(v) # If the community is too big, remove a node from it. if len(result[c]) > community_sizes[c]: free.append(result[c].pop()) if not free: return result msg = "Could not assign communities; try increasing min_community" raise nx.ExceededMaxIterations(msg)
(l, k, *, backend=None, **backend_kwargs)
30,496
networkx.algorithms.components.connected
connected_components
Generate connected components. Parameters ---------- G : NetworkX graph An undirected graph Returns ------- comp : generator of sets A generator of sets of nodes, one for each component of G. Raises ------ NetworkXNotImplemented If G is directed. Examples -------- Generate a sorted list of connected components, largest first. >>> G = nx.path_graph(4) >>> nx.add_path(G, [10, 11, 12]) >>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)] [4, 3] If you only want the largest connected component, it's more efficient to use max instead of sort. >>> largest_cc = max(nx.connected_components(G), key=len) To create the induced subgraph of each component use: >>> S = [G.subgraph(c).copy() for c in nx.connected_components(G)] See Also -------- strongly_connected_components weakly_connected_components Notes ----- For undirected graphs only.
null
(G, *, backend=None, **backend_kwargs)
30,497
networkx.algorithms.swap
connected_double_edge_swap
Attempts the specified number of double-edge swaps in the graph `G`. A double-edge swap removes two randomly chosen edges `(u, v)` and `(x, y)` and creates the new edges `(u, x)` and `(v, y)`:: u--v u v becomes | | x--y x y If either `(u, x)` or `(v, y)` already exist, then no swap is performed so the actual number of swapped edges is always *at most* `nswap`. Parameters ---------- G : graph An undirected graph nswap : integer (optional, default=1) Number of double-edge swaps to perform _window_threshold : integer The window size below which connectedness of the graph will be checked after each swap. The "window" in this function is a dynamically updated integer that represents the number of swap attempts to make before checking if the graph remains connected. It is an optimization used to decrease the running time of the algorithm in exchange for increased complexity of implementation. If the window size is below this threshold, then the algorithm checks after each swap if the graph remains connected by checking if there is a path joining the two nodes whose edge was just removed. If the window size is above this threshold, then the algorithm performs do all the swaps in the window and only then check if the graph is still connected. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- int The number of successful swaps Raises ------ NetworkXError If the input graph is not connected, or if the graph has fewer than four nodes. Notes ----- The initial graph `G` must be connected, and the resulting graph is connected. The graph `G` is modified in place. References ---------- .. [1] C. Gkantsidis and M. Mihail and E. Zegura, The Markov chain simulation method for generating connected power law random graphs, 2003. http://citeseer.ist.psu.edu/gkantsidis03markov.html
null
(G, nswap=1, _window_threshold=3, seed=None, *, backend=None, **backend_kwargs)
30,498
networkx.generators.random_graphs
connected_watts_strogatz_graph
Returns a connected Watts–Strogatz small-world graph. Attempts to generate a connected graph by repeated generation of Watts–Strogatz small-world graphs. An exception is raised if the maximum number of tries is exceeded. Parameters ---------- n : int The number of nodes k : int Each node is joined with its `k` nearest neighbors in a ring topology. p : float The probability of rewiring each edge tries : int Number of attempts to generate a connected graph. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Notes ----- First create a ring over $n$ nodes [1]_. Then each node in the ring is joined to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd). Then shortcuts are created by replacing some edges as follows: for each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors" with probability $p$ replace it with a new edge $(u, w)$ with uniformly random choice of existing node $w$. The entire process is repeated until a connected graph results. See Also -------- newman_watts_strogatz_graph watts_strogatz_graph References ---------- .. [1] Duncan J. Watts and Steven H. Strogatz, Collective dynamics of small-world networks, Nature, 393, pp. 440--442, 1998.
def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None): """Returns a random graph using dual Barabási–Albert preferential attachment A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that are preferentially attached to existing nodes with high degree. Parameters ---------- n : int Number of nodes m1 : int Number of edges to link each new node to existing nodes with probability $p$ m2 : int Number of edges to link each new node to existing nodes with probability $1-p$ p : float The probability of attaching $m_1$ edges (as opposed to $m_2$ edges) seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. initial_graph : Graph or None (default) Initial network for Barabási–Albert algorithm. A copy of `initial_graph` is used. It should be connected for most use cases. If None, starts from an star graph on max(m1, m2) + 1 nodes. Returns ------- G : Graph Raises ------ NetworkXError If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or `p` does not satisfy ``0 <= p <= 1``, or the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n. References ---------- .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538. """ if m1 < 1 or m1 >= n: raise nx.NetworkXError( f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}" ) if m2 < 1 or m2 >= n: raise nx.NetworkXError( f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}" ) if p < 0 or p > 1: raise nx.NetworkXError( f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}" ) # For simplicity, if p == 0 or 1, just return BA if p == 1: return barabasi_albert_graph(n, m1, seed) elif p == 0: return barabasi_albert_graph(n, m2, seed) if initial_graph is None: # Default initial graph : empty graph on max(m1, m2) nodes G = star_graph(max(m1, m2)) else: if len(initial_graph) < max(m1, m2) or len(initial_graph) > n: raise nx.NetworkXError( f"Barabási–Albert initial graph must have between " f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes" ) G = initial_graph.copy() # Target nodes for new edges targets = list(G) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes = [n for n, d in G.degree() for _ in range(d)] # Start adding the remaining nodes. source = len(G) while source < n: # Pick which m to use (m1 or m2) if seed.random() < p: m = m1 else: m = m2 # Now choose m unique nodes from the existing nodes # Pick uniformly from repeated_nodes (preferential attachment) targets = _random_subset(repeated_nodes, m, seed) # Add edges to m nodes from the source. G.add_edges_from(zip([source] * m, targets)) # Add one node to the list for each new edge just created. repeated_nodes.extend(targets) # And the new node "source" has m edges to add to the list. repeated_nodes.extend([source] * m) source += 1 return G
(n, k, p, tries=100, seed=None, *, backend=None, **backend_kwargs)
30,500
networkx.algorithms.structuralholes
constraint
Returns the constraint on all nodes in the graph ``G``. The *constraint* is a measure of the extent to which a node *v* is invested in those nodes that are themselves invested in the neighbors of *v*. Formally, the *constraint on v*, denoted `c(v)`, is defined by .. math:: c(v) = \sum_{w \in N(v) \setminus \{v\}} \ell(v, w) where $N(v)$ is the subset of the neighbors of `v` that are either predecessors or successors of `v` and $\ell(v, w)$ is the local constraint on `v` with respect to `w` [1]_. For the definition of local constraint, see :func:`local_constraint`. Parameters ---------- G : NetworkX graph The graph containing ``v``. This can be either directed or undirected. nodes : container, optional Container of nodes in the graph ``G`` to compute the constraint. If None, the constraint of every node is computed. weight : None or string, optional If None, all edge weights are considered equal. Otherwise holds the name of the edge attribute used as weight. Returns ------- dict Dictionary with nodes as keys and the constraint on the node as values. See also -------- local_constraint References ---------- .. [1] Burt, Ronald S. "Structural holes and good ideas". American Journal of Sociology (110): 349–399.
null
(G, nodes=None, weight=None, *, backend=None, **backend_kwargs)
30,501
networkx.algorithms.minors.contraction
contracted_edge
Returns the graph that results from contracting the specified edge. Edge contraction identifies the two endpoints of the edge as a single node incident to any edge that was incident to the original two nodes. A graph that results from edge contraction is called a *minor* of the original graph. Parameters ---------- G : NetworkX graph The graph whose edge will be contracted. edge : tuple Must be a pair of nodes in `G`. self_loops : Boolean If this is True, any edges (including `edge`) joining the endpoints of `edge` in `G` become self-loops on the new node in the returned graph. copy : Boolean (default True) If this is True, a the contraction will be performed on a copy of `G`, otherwise the contraction will happen in place. Returns ------- Networkx graph A new graph object of the same type as `G` (leaving `G` unmodified) with endpoints of `edge` identified in a single node. The right node of `edge` will be merged into the left one, so only the left one will appear in the returned graph. Raises ------ ValueError If `edge` is not an edge in `G`. Examples -------- Attempting to contract two nonadjacent nodes yields an error: >>> G = nx.cycle_graph(4) >>> nx.contracted_edge(G, (1, 3)) Traceback (most recent call last): ... ValueError: Edge (1, 3) does not exist in graph G; cannot contract it Contracting two adjacent nodes in the cycle graph on *n* nodes yields the cycle graph on *n - 1* nodes: >>> C5 = nx.cycle_graph(5) >>> C4 = nx.cycle_graph(4) >>> M = nx.contracted_edge(C5, (0, 1), self_loops=False) >>> nx.is_isomorphic(M, C4) True See also -------- contracted_nodes quotient_graph
null
(G, edge, self_loops=True, copy=True, *, backend=None, **backend_kwargs)
30,502
networkx.algorithms.minors.contraction
contracted_nodes
Returns the graph that results from contracting `u` and `v`. Node contraction identifies the two nodes as a single node incident to any edge that was incident to the original two nodes. Parameters ---------- G : NetworkX graph The graph whose nodes will be contracted. u, v : nodes Must be nodes in `G`. self_loops : Boolean If this is True, any edges joining `u` and `v` in `G` become self-loops on the new node in the returned graph. copy : Boolean If this is True (default True), make a copy of `G` and return that instead of directly changing `G`. Returns ------- Networkx graph If Copy is True, A new graph object of the same type as `G` (leaving `G` unmodified) with `u` and `v` identified in a single node. The right node `v` will be merged into the node `u`, so only `u` will appear in the returned graph. If copy is False, Modifies `G` with `u` and `v` identified in a single node. The right node `v` will be merged into the node `u`, so only `u` will appear in the returned graph. Notes ----- For multigraphs, the edge keys for the realigned edges may not be the same as the edge keys for the old edges. This is natural because edge keys are unique only within each pair of nodes. For non-multigraphs where `u` and `v` are adjacent to a third node `w`, the edge (`v`, `w`) will be contracted into the edge (`u`, `w`) with its attributes stored into a "contraction" attribute. This function is also available as `identified_nodes`. Examples -------- Contracting two nonadjacent nodes of the cycle graph on four nodes `C_4` yields the path graph (ignoring parallel edges): >>> G = nx.cycle_graph(4) >>> M = nx.contracted_nodes(G, 1, 3) >>> P3 = nx.path_graph(3) >>> nx.is_isomorphic(M, P3) True >>> G = nx.MultiGraph(P3) >>> M = nx.contracted_nodes(G, 0, 2) >>> M.edges MultiEdgeView([(0, 1, 0), (0, 1, 1)]) >>> G = nx.Graph([(1, 2), (2, 2)]) >>> H = nx.contracted_nodes(G, 1, 2, self_loops=False) >>> list(H.nodes()) [1] >>> list(H.edges()) [(1, 1)] In a ``MultiDiGraph`` with a self loop, the in and out edges will be treated separately as edges, so while contracting a node which has a self loop the contraction will add multiple edges: >>> G = nx.MultiDiGraph([(1, 2), (2, 2)]) >>> H = nx.contracted_nodes(G, 1, 2) >>> list(H.edges()) # edge 1->2, 2->2, 2<-2 from the original Graph G [(1, 1), (1, 1), (1, 1)] >>> H = nx.contracted_nodes(G, 1, 2, self_loops=False) >>> list(H.edges()) # edge 2->2, 2<-2 from the original Graph G [(1, 1), (1, 1)] See Also -------- contracted_edge quotient_graph
null
(G, u, v, self_loops=True, copy=True, *, backend=None, **backend_kwargs)
30,505
networkx.relabel
convert_node_labels_to_integers
Returns a copy of the graph G with the nodes relabeled using consecutive integers. Parameters ---------- G : graph A NetworkX graph first_label : int, optional (default=0) An integer specifying the starting offset in numbering nodes. The new integer labels are numbered first_label, ..., n-1+first_label. ordering : string "default" : inherit node ordering from G.nodes() "sorted" : inherit node ordering from sorted(G.nodes()) "increasing degree" : nodes are sorted by increasing degree "decreasing degree" : nodes are sorted by decreasing degree label_attribute : string, optional (default=None) Name of node attribute to store old label. If None no attribute is created. Notes ----- Node and edge attribute data are copied to the new (relabeled) graph. There is no guarantee that the relabeling of nodes to integers will give the same two integers for two (even identical graphs). Use the `ordering` argument to try to preserve the order. See Also -------- relabel_nodes
null
(G, first_label=0, ordering='default', label_attribute=None, *, backend=None, **backend_kwargs)
30,507
networkx.algorithms.core
core_number
Returns the core number for each node. A k-core is a maximal subgraph that contains nodes of degree k or more. The core number of a node is the largest value k of a k-core containing that node. Parameters ---------- G : NetworkX graph An undirected or directed graph Returns ------- core_number : dictionary A dictionary keyed by node to the core number. Raises ------ NetworkXNotImplemented If `G` is a multigraph or contains self loops. Notes ----- For directed graphs the node degree is defined to be the in-degree + out-degree. Examples -------- >>> degrees = [0, 1, 2, 2, 2, 2, 3] >>> H = nx.havel_hakimi_graph(degrees) >>> nx.core_number(H) {0: 1, 1: 2, 2: 2, 3: 2, 4: 1, 5: 2, 6: 0} >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)]) >>> nx.core_number(G) {1: 2, 2: 2, 3: 2, 4: 2} References ---------- .. [1] An O(m) Algorithm for Cores Decomposition of Networks Vladimir Batagelj and Matjaz Zaversnik, 2003. https://arxiv.org/abs/cs.DS/0310049
null
(G, *, backend=None, **backend_kwargs)
30,509
networkx.algorithms.operators.product
corona_product
Returns the Corona product of G and H. The corona product of $G$ and $H$ is the graph $C = G \circ H$ obtained by taking one copy of $G$, called the center graph, $|V(G)|$ copies of $H$, called the outer graph, and making the $i$-th vertex of $G$ adjacent to every vertex of the $i$-th copy of $H$, where $1 ≤ i ≤ |V(G)|$. Parameters ---------- G, H: NetworkX graphs The graphs to take the carona product of. `G` is the center graph and `H` is the outer graph Returns ------- C: NetworkX graph The Corona product of G and H. Raises ------ NetworkXError If G and H are not both directed or both undirected. Examples -------- >>> G = nx.cycle_graph(4) >>> H = nx.path_graph(2) >>> C = nx.corona_product(G, H) >>> list(C) [0, 1, 2, 3, (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)] >>> print(C) Graph with 12 nodes and 16 edges References ---------- [1] M. Tavakoli, F. Rahbarnia, and A. R. Ashrafi, "Studying the corona product of graphs under some graph invariants," Transactions on Combinatorics, vol. 3, no. 3, pp. 43–49, Sep. 2014, doi: 10.22108/toc.2014.5542. [2] A. Faraji, "Corona Product in Graph Theory," Ali Faraji, May 11, 2021. https://blog.alifaraji.ir/math/graph-theory/corona-product.html (accessed Dec. 07, 2021).
null
(G, H, *, backend=None, **backend_kwargs)
30,511
networkx.algorithms.flow.mincost
cost_of_flow
Compute the cost of the flow given by flowDict on graph G. Note that this function does not check for the validity of the flow flowDict. This function will fail if the graph G and the flow don't have the same edge set. Parameters ---------- G : NetworkX graph DiGraph on which a minimum cost flow satisfying all demands is to be found. weight : string Edges of the graph G are expected to have an attribute weight that indicates the cost incurred by sending one unit of flow on that edge. If not present, the weight is considered to be 0. Default value: 'weight'. flowDict : dictionary Dictionary of dictionaries keyed by nodes such that flowDict[u][v] is the flow edge (u, v). Returns ------- cost : Integer, float The total cost of the flow. This is given by the sum over all edges of the product of the edge's flow and the edge's weight. See also -------- max_flow_min_cost, min_cost_flow, min_cost_flow_cost, network_simplex Notes ----- This algorithm is not guaranteed to work if edge weights or demands are floating point numbers (overflows and roundoff errors can cause problems). As a workaround you can use integer numbers by multiplying the relevant edge attributes by a convenient constant factor (eg 100). Examples -------- >>> G = nx.DiGraph() >>> G.add_node("a", demand=-5) >>> G.add_node("d", demand=5) >>> G.add_edge("a", "b", weight=3, capacity=4) >>> G.add_edge("a", "c", weight=6, capacity=10) >>> G.add_edge("b", "d", weight=1, capacity=9) >>> G.add_edge("c", "d", weight=2, capacity=5) >>> flowDict = nx.min_cost_flow(G) >>> flowDict {'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}} >>> nx.cost_of_flow(G, flowDict) 24
null
(G, flowDict, weight='weight', *, backend=None, **backend_kwargs)
30,512
networkx.algorithms.isomorphism.isomorph
could_be_isomorphic
Returns False if graphs are definitely not isomorphic. True does NOT guarantee isomorphism. Parameters ---------- G1, G2 : graphs The two graphs G1 and G2 must be the same type. Notes ----- Checks for matching degree, triangle, and number of cliques sequences. The triangle sequence contains the number of triangles each node is part of. The clique sequence contains for each node the number of maximal cliques involving that node.
null
(G1, G2, *, backend=None, **backend_kwargs)
30,514
networkx.classes.function
create_empty_copy
Returns a copy of the graph G with all of the edges removed. Parameters ---------- G : graph A NetworkX graph with_data : bool (default=True) Propagate Graph and Nodes data to the new graph. See Also -------- empty_graph
def create_empty_copy(G, with_data=True): """Returns a copy of the graph G with all of the edges removed. Parameters ---------- G : graph A NetworkX graph with_data : bool (default=True) Propagate Graph and Nodes data to the new graph. See Also -------- empty_graph """ H = G.__class__() H.add_nodes_from(G.nodes(data=with_data)) if with_data: H.graph.update(G.graph) return H
(G, with_data=True)
30,515
networkx.generators.small
cubical_graph
Returns the 3-regular Platonic Cubical Graph The skeleton of the cube (the nodes and edges) form a graph, with 8 nodes, and 12 edges. It is a special case of the hypercube graph. It is one of 5 Platonic graphs, each a skeleton of its Platonic solid [1]_. Such graphs arise in parallel processing in computers. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph A cubical graph with 8 nodes and 12 edges References ---------- .. [1] https://en.wikipedia.org/wiki/Cube#Cubical_graph
def _raise_on_directed(func): """ A decorator which inspects the `create_using` argument and raises a NetworkX exception when `create_using` is a DiGraph (class or instance) for graph generators that do not support directed outputs. """ @wraps(func) def wrapper(*args, **kwargs): if kwargs.get("create_using") is not None: G = nx.empty_graph(create_using=kwargs["create_using"]) if G.is_directed(): raise NetworkXError("Directed Graph not supported") return func(*args, **kwargs) return wrapper
(create_using=None, *, backend=None, **backend_kwargs)
30,517
networkx.algorithms.centrality.current_flow_betweenness
current_flow_betweenness_centrality
Compute current-flow betweenness centrality for nodes. Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to betweenness centrality which uses shortest paths. Current-flow betweenness centrality is also known as random-walk betweenness centrality [2]_. Parameters ---------- G : graph A NetworkX graph normalized : bool, optional (default=True) If True the betweenness values are normalized by 2/[(n-1)(n-2)] where n is the number of nodes in G. weight : string or None, optional (default=None) Key for edge data used as the edge weight. If None, then use 1 as each edge weight. The weight reflects the capacity or the strength of the edge. dtype : data type (float) Default data type for internal matrices. Set to np.float32 for lower memory consumption. solver : string (default='full') Type of linear solver to use for computing the flow matrix. Options are "full" (uses most memory), "lu" (recommended), and "cg" (uses least memory). Returns ------- nodes : dictionary Dictionary of nodes with betweenness centrality as the value. See Also -------- approximate_current_flow_betweenness_centrality betweenness_centrality edge_betweenness_centrality edge_current_flow_betweenness_centrality Notes ----- Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$ time [1]_, where $I(n-1)$ is the time needed to compute the inverse Laplacian. For a full matrix this is $O(n^3)$ but using sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the Laplacian matrix condition number. The space required is $O(nw)$ where $w$ is the width of the sparse Laplacian matrix. Worse case is $w=n$ for $O(n^2)$. If the edges have a 'weight' attribute they will be used as weights in this algorithm. Unspecified weights are set to 1. References ---------- .. [1] Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. https://doi.org/10.1007/978-3-540-31856-9_44 .. [2] A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).
null
(G, normalized=True, weight=None, dtype=<class 'float'>, solver='full', *, backend=None, **backend_kwargs)
30,518
networkx.algorithms.centrality.current_flow_betweenness_subset
current_flow_betweenness_centrality_subset
Compute current-flow betweenness centrality for subsets of nodes. Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to betweenness centrality which uses shortest paths. Current-flow betweenness centrality is also known as random-walk betweenness centrality [2]_. Parameters ---------- G : graph A NetworkX graph sources: list of nodes Nodes to use as sources for current targets: list of nodes Nodes to use as sinks for current normalized : bool, optional (default=True) If True the betweenness values are normalized by b=b/(n-1)(n-2) where n is the number of nodes in G. weight : string or None, optional (default=None) Key for edge data used as the edge weight. If None, then use 1 as each edge weight. The weight reflects the capacity or the strength of the edge. dtype: data type (float) Default data type for internal matrices. Set to np.float32 for lower memory consumption. solver: string (default='lu') Type of linear solver to use for computing the flow matrix. Options are "full" (uses most memory), "lu" (recommended), and "cg" (uses least memory). Returns ------- nodes : dictionary Dictionary of nodes with betweenness centrality as the value. See Also -------- approximate_current_flow_betweenness_centrality betweenness_centrality edge_betweenness_centrality edge_current_flow_betweenness_centrality Notes ----- Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$ time [1]_, where $I(n-1)$ is the time needed to compute the inverse Laplacian. For a full matrix this is $O(n^3)$ but using sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the Laplacian matrix condition number. The space required is $O(nw)$ where $w$ is the width of the sparse Laplacian matrix. Worse case is $w=n$ for $O(n^2)$. If the edges have a 'weight' attribute they will be used as weights in this algorithm. Unspecified weights are set to 1. References ---------- .. [1] Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. https://doi.org/10.1007/978-3-540-31856-9_44 .. [2] A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).
null
(G, sources, targets, normalized=True, weight=None, dtype=<class 'float'>, solver='lu', *, backend=None, **backend_kwargs)
30,521
networkx.algorithms.centrality.current_flow_closeness
current_flow_closeness_centrality
Compute current-flow closeness centrality for nodes. Current-flow closeness centrality is variant of closeness centrality based on effective resistance between nodes in a network. This metric is also known as information centrality. Parameters ---------- G : graph A NetworkX graph. weight : None or string, optional (default=None) If None, all edge weights are considered equal. Otherwise holds the name of the edge attribute used as weight. The weight reflects the capacity or the strength of the edge. dtype: data type (default=float) Default data type for internal matrices. Set to np.float32 for lower memory consumption. solver: string (default='lu') Type of linear solver to use for computing the flow matrix. Options are "full" (uses most memory), "lu" (recommended), and "cg" (uses least memory). Returns ------- nodes : dictionary Dictionary of nodes with current flow closeness centrality as the value. See Also -------- closeness_centrality Notes ----- The algorithm is from Brandes [1]_. See also [2]_ for the original definition of information centrality. References ---------- .. [1] Ulrik Brandes and Daniel Fleischer, Centrality Measures Based on Current Flow. Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. https://doi.org/10.1007/978-3-540-31856-9_44 .. [2] Karen Stephenson and Marvin Zelen: Rethinking centrality: Methods and examples. Social Networks 11(1):1-37, 1989. https://doi.org/10.1016/0378-8733(89)90016-6
null
(G, weight=None, dtype=<class 'float'>, solver='lu', *, backend=None, **backend_kwargs)
30,522
networkx.algorithms.cuts
cut_size
Returns the size of the cut between two sets of nodes. A *cut* is a partition of the nodes of a graph into two sets. The *cut size* is the sum of the weights of the edges "between" the two sets of nodes. Parameters ---------- G : NetworkX graph S : collection A collection of nodes in `G`. T : collection A collection of nodes in `G`. If not specified, this is taken to be the set complement of `S`. weight : object Edge attribute key to use as weight. If not specified, edges have weight one. Returns ------- number Total weight of all edges from nodes in set `S` to nodes in set `T` (and, in the case of directed graphs, all edges from nodes in `T` to nodes in `S`). Examples -------- In the graph with two cliques joined by a single edges, the natural bipartition of the graph into two blocks, one for each clique, yields a cut of weight one:: >>> G = nx.barbell_graph(3, 0) >>> S = {0, 1, 2} >>> T = {3, 4, 5} >>> nx.cut_size(G, S, T) 1 Each parallel edge in a multigraph is counted when determining the cut size:: >>> G = nx.MultiGraph(["ab", "ab"]) >>> S = {"a"} >>> T = {"b"} >>> nx.cut_size(G, S, T) 2 Notes ----- In a multigraph, the cut size is the total weight of edges including multiplicity.
null
(G, S, T=None, weight=None, *, backend=None, **backend_kwargs)
30,524
networkx.algorithms.cycles
cycle_basis
Returns a list of cycles which form a basis for cycles of G. A basis for cycles of a network is a minimal collection of cycles such that any cycle in the network can be written as a sum of cycles in the basis. Here summation of cycles is defined as "exclusive or" of the edges. Cycle bases are useful, e.g. when deriving equations for electric circuits using Kirchhoff's Laws. Parameters ---------- G : NetworkX Graph root : node, optional Specify starting node for basis. Returns ------- A list of cycle lists. Each cycle list is a list of nodes which forms a cycle (loop) in G. Examples -------- >>> G = nx.Graph() >>> nx.add_cycle(G, [0, 1, 2, 3]) >>> nx.add_cycle(G, [0, 3, 4, 5]) >>> nx.cycle_basis(G, 0) [[3, 4, 5, 0], [1, 2, 3, 0]] Notes ----- This is adapted from algorithm CACM 491 [1]_. References ---------- .. [1] Paton, K. An algorithm for finding a fundamental set of cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518. See Also -------- simple_cycles minimum_cycle_basis
def recursive_simple_cycles(G): """Find simple cycles (elementary circuits) of a directed graph. A `simple cycle`, or `elementary circuit`, is a closed path where no node appears twice. Two elementary circuits are distinct if they are not cyclic permutations of each other. This version uses a recursive algorithm to build a list of cycles. You should probably use the iterator version called simple_cycles(). Warning: This recursive version uses lots of RAM! It appears in NetworkX for pedagogical value. Parameters ---------- G : NetworkX DiGraph A directed graph Returns ------- A list of cycles, where each cycle is represented by a list of nodes along the cycle. Example: >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)] >>> G = nx.DiGraph(edges) >>> nx.recursive_simple_cycles(G) [[0], [2], [0, 1, 2], [0, 2], [1, 2]] Notes ----- The implementation follows pp. 79-80 in [1]_. The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ elementary circuits. References ---------- .. [1] Finding all the elementary circuits of a directed graph. D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975. https://doi.org/10.1137/0204007 See Also -------- simple_cycles, cycle_basis """ # Jon Olav Vik, 2010-08-09 def _unblock(thisnode): """Recursively unblock and remove nodes from B[thisnode].""" if blocked[thisnode]: blocked[thisnode] = False while B[thisnode]: _unblock(B[thisnode].pop()) def circuit(thisnode, startnode, component): closed = False # set to True if elementary path is closed path.append(thisnode) blocked[thisnode] = True for nextnode in component[thisnode]: # direct successors of thisnode if nextnode == startnode: result.append(path[:]) closed = True elif not blocked[nextnode]: if circuit(nextnode, startnode, component): closed = True if closed: _unblock(thisnode) else: for nextnode in component[thisnode]: if thisnode not in B[nextnode]: # TODO: use set for speedup? B[nextnode].append(thisnode) path.pop() # remove thisnode from path return closed path = [] # stack of nodes in current path blocked = defaultdict(bool) # vertex: blocked from search? B = defaultdict(list) # graph portions that yield no elementary circuit result = [] # list to accumulate the circuits found # Johnson's algorithm exclude self cycle edges like (v, v) # To be backward compatible, we record those cycles in advance # and then remove from subG for v in G: if G.has_edge(v, v): result.append([v]) G.remove_edge(v, v) # Johnson's algorithm requires some ordering of the nodes. # They might not be sortable so we assign an arbitrary ordering. ordering = dict(zip(G, range(len(G)))) for s in ordering: # Build the subgraph induced by s and following nodes in the ordering subgraph = G.subgraph(node for node in G if ordering[node] >= ordering[s]) # Find the strongly connected component in the subgraph # that contains the least node according to the ordering strongcomp = nx.strongly_connected_components(subgraph) mincomp = min(strongcomp, key=lambda ns: min(ordering[n] for n in ns)) component = G.subgraph(mincomp) if len(component) > 1: # smallest node in the component according to the ordering startnode = min(component, key=ordering.__getitem__) for node in component: blocked[node] = False B[node][:] = [] dummy = circuit(startnode, startnode, component) return result
(G, root=None, *, backend=None, **backend_kwargs)
30,525
networkx.generators.classic
cycle_graph
Returns the cycle graph $C_n$ of cyclically connected nodes. $C_n$ is a path with its two end-nodes connected. .. plot:: >>> nx.draw(nx.cycle_graph(5)) Parameters ---------- n : int or iterable container of nodes If n is an integer, nodes are from `range(n)`. If n is a container of nodes, those nodes appear in the graph. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- If create_using is directed, the direction is in increasing order.
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(n, create_using=None, *, backend=None, **backend_kwargs)
30,528
networkx.readwrite.json_graph.cytoscape
cytoscape_data
Returns data in Cytoscape JSON format (cyjs). Parameters ---------- G : NetworkX Graph The graph to convert to cytoscape format name : string A string which is mapped to the 'name' node element in cyjs format. Must not have the same value as `ident`. ident : string A string which is mapped to the 'id' node element in cyjs format. Must not have the same value as `name`. Returns ------- data: dict A dictionary with cyjs formatted data. Raises ------ NetworkXError If the values for `name` and `ident` are identical. See Also -------- cytoscape_graph: convert a dictionary in cyjs format to a graph References ---------- .. [1] Cytoscape user's manual: http://manual.cytoscape.org/en/stable/index.html Examples -------- >>> G = nx.path_graph(2) >>> nx.cytoscape_data(G) # doctest: +SKIP {'data': [], 'directed': False, 'multigraph': False, 'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}}, {'data': {'id': '1', 'value': 1, 'name': '1'}}], 'edges': [{'data': {'source': 0, 'target': 1}}]}}
def cytoscape_data(G, name="name", ident="id"): """Returns data in Cytoscape JSON format (cyjs). Parameters ---------- G : NetworkX Graph The graph to convert to cytoscape format name : string A string which is mapped to the 'name' node element in cyjs format. Must not have the same value as `ident`. ident : string A string which is mapped to the 'id' node element in cyjs format. Must not have the same value as `name`. Returns ------- data: dict A dictionary with cyjs formatted data. Raises ------ NetworkXError If the values for `name` and `ident` are identical. See Also -------- cytoscape_graph: convert a dictionary in cyjs format to a graph References ---------- .. [1] Cytoscape user's manual: http://manual.cytoscape.org/en/stable/index.html Examples -------- >>> G = nx.path_graph(2) >>> nx.cytoscape_data(G) # doctest: +SKIP {'data': [], 'directed': False, 'multigraph': False, 'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}}, {'data': {'id': '1', 'value': 1, 'name': '1'}}], 'edges': [{'data': {'source': 0, 'target': 1}}]}} """ if name == ident: raise nx.NetworkXError("name and ident must be different.") jsondata = {"data": list(G.graph.items())} jsondata["directed"] = G.is_directed() jsondata["multigraph"] = G.is_multigraph() jsondata["elements"] = {"nodes": [], "edges": []} nodes = jsondata["elements"]["nodes"] edges = jsondata["elements"]["edges"] for i, j in G.nodes.items(): n = {"data": j.copy()} n["data"]["id"] = j.get(ident) or str(i) n["data"]["value"] = i n["data"]["name"] = j.get(name) or str(i) nodes.append(n) if G.is_multigraph(): for e in G.edges(keys=True): n = {"data": G.adj[e[0]][e[1]][e[2]].copy()} n["data"]["source"] = e[0] n["data"]["target"] = e[1] n["data"]["key"] = e[2] edges.append(n) else: for e in G.edges(): n = {"data": G.adj[e[0]][e[1]].copy()} n["data"]["source"] = e[0] n["data"]["target"] = e[1] edges.append(n) return jsondata
(G, name='name', ident='id')
30,529
networkx.readwrite.json_graph.cytoscape
cytoscape_graph
Create a NetworkX graph from a dictionary in cytoscape JSON format. Parameters ---------- data : dict A dictionary of data conforming to cytoscape JSON format. name : string A string which is mapped to the 'name' node element in cyjs format. Must not have the same value as `ident`. ident : string A string which is mapped to the 'id' node element in cyjs format. Must not have the same value as `name`. Returns ------- graph : a NetworkX graph instance The `graph` can be an instance of `Graph`, `DiGraph`, `MultiGraph`, or `MultiDiGraph` depending on the input data. Raises ------ NetworkXError If the `name` and `ident` attributes are identical. See Also -------- cytoscape_data: convert a NetworkX graph to a dict in cyjs format References ---------- .. [1] Cytoscape user's manual: http://manual.cytoscape.org/en/stable/index.html Examples -------- >>> data_dict = { ... "data": [], ... "directed": False, ... "multigraph": False, ... "elements": { ... "nodes": [ ... {"data": {"id": "0", "value": 0, "name": "0"}}, ... {"data": {"id": "1", "value": 1, "name": "1"}}, ... ], ... "edges": [{"data": {"source": 0, "target": 1}}], ... }, ... } >>> G = nx.cytoscape_graph(data_dict) >>> G.name '' >>> G.nodes() NodeView((0, 1)) >>> G.nodes(data=True)[0] {'id': '0', 'value': 0, 'name': '0'} >>> G.edges(data=True) EdgeDataView([(0, 1, {'source': 0, 'target': 1})])
null
(data, name='name', ident='id', *, backend=None, **backend_kwargs)
30,530
networkx.algorithms.d_separation
d_separated
Return whether nodes sets ``x`` and ``y`` are d-separated by ``z``. .. deprecated:: 3.3 This function is deprecated and will be removed in NetworkX v3.5. Please use `is_d_separator(G, x, y, z)`.
def d_separated(G, x, y, z): """Return whether nodes sets ``x`` and ``y`` are d-separated by ``z``. .. deprecated:: 3.3 This function is deprecated and will be removed in NetworkX v3.5. Please use `is_d_separator(G, x, y, z)`. """ import warnings warnings.warn( "d_separated is deprecated and will be removed in NetworkX v3.5." "Please use `is_d_separator(G, x, y, z)`.", category=DeprecationWarning, stacklevel=2, ) return nx.is_d_separator(G, x, y, z)
(G, x, y, z)
30,533
networkx.algorithms.dag
dag_longest_path
Returns the longest path in a directed acyclic graph (DAG). If `G` has edges with `weight` attribute the edge data are used as weight values. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) weight : str, optional Edge data key to use for weight default_weight : int, optional The weight of edges that do not have a weight attribute topo_order: list or tuple, optional A topological order for `G` (if None, the function will compute one) Returns ------- list Longest path Raises ------ NetworkXNotImplemented If `G` is not directed Examples -------- >>> DG = nx.DiGraph([(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]) >>> list(nx.all_simple_paths(DG, 0, 2)) [[0, 1, 2], [0, 2]] >>> nx.dag_longest_path(DG) [0, 1, 2] >>> nx.dag_longest_path(DG, weight="cost") [0, 2] In the case where multiple valid topological orderings exist, `topo_order` can be used to specify a specific ordering: >>> DG = nx.DiGraph([(0, 1), (0, 2)]) >>> sorted(nx.all_topological_sorts(DG)) # Valid topological orderings [[0, 1, 2], [0, 2, 1]] >>> nx.dag_longest_path(DG, topo_order=[0, 1, 2]) [0, 1] >>> nx.dag_longest_path(DG, topo_order=[0, 2, 1]) [0, 2] See also -------- dag_longest_path_length
def transitive_closure_dag(G, topo_order=None): """Returns the transitive closure of a directed acyclic graph. This function is faster than the function `transitive_closure`, but fails if the graph has a cycle. The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that for all v, w in V there is an edge (v, w) in E+ if and only if there is a non-null path from v to w in G. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) topo_order: list or tuple, optional A topological order for G (if None, the function will compute one) Returns ------- NetworkX DiGraph The transitive closure of `G` Raises ------ NetworkXNotImplemented If `G` is not directed NetworkXUnfeasible If `G` has a cycle Examples -------- >>> DG = nx.DiGraph([(1, 2), (2, 3)]) >>> TC = nx.transitive_closure_dag(DG) >>> TC.edges() OutEdgeView([(1, 2), (1, 3), (2, 3)]) Notes ----- This algorithm is probably simple enough to be well-known but I didn't find a mention in the literature. """ if topo_order is None: topo_order = list(topological_sort(G)) TC = G.copy() # idea: traverse vertices following a reverse topological order, connecting # each vertex to its descendants at distance 2 as we go for v in reversed(topo_order): TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2)) return TC
(G, weight='weight', default_weight=1, topo_order=None, *, backend=None, **backend_kwargs)
30,534
networkx.algorithms.dag
dag_longest_path_length
Returns the longest path length in a DAG Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) weight : string, optional Edge data key to use for weight default_weight : int, optional The weight of edges that do not have a weight attribute Returns ------- int Longest path length Raises ------ NetworkXNotImplemented If `G` is not directed Examples -------- >>> DG = nx.DiGraph([(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]) >>> list(nx.all_simple_paths(DG, 0, 2)) [[0, 1, 2], [0, 2]] >>> nx.dag_longest_path_length(DG) 2 >>> nx.dag_longest_path_length(DG, weight="cost") 42 See also -------- dag_longest_path
def transitive_closure_dag(G, topo_order=None): """Returns the transitive closure of a directed acyclic graph. This function is faster than the function `transitive_closure`, but fails if the graph has a cycle. The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that for all v, w in V there is an edge (v, w) in E+ if and only if there is a non-null path from v to w in G. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) topo_order: list or tuple, optional A topological order for G (if None, the function will compute one) Returns ------- NetworkX DiGraph The transitive closure of `G` Raises ------ NetworkXNotImplemented If `G` is not directed NetworkXUnfeasible If `G` has a cycle Examples -------- >>> DG = nx.DiGraph([(1, 2), (2, 3)]) >>> TC = nx.transitive_closure_dag(DG) >>> TC.edges() OutEdgeView([(1, 2), (1, 3), (2, 3)]) Notes ----- This algorithm is probably simple enough to be well-known but I didn't find a mention in the literature. """ if topo_order is None: topo_order = list(topological_sort(G)) TC = G.copy() # idea: traverse vertices following a reverse topological order, connecting # each vertex to its descendants at distance 2 as we go for v in reversed(topo_order): TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2)) return TC
(G, weight='weight', default_weight=1, *, backend=None, **backend_kwargs)
30,535
networkx.algorithms.dag
dag_to_branching
Returns a branching representing all (overlapping) paths from root nodes to leaf nodes in the given directed acyclic graph. As described in :mod:`networkx.algorithms.tree.recognition`, a *branching* is a directed forest in which each node has at most one parent. In other words, a branching is a disjoint union of *arborescences*. For this function, each node of in-degree zero in `G` becomes a root of one of the arborescences, and there will be one leaf node for each distinct path from that root to a leaf node in `G`. Each node `v` in `G` with *k* parents becomes *k* distinct nodes in the returned branching, one for each parent, and the sub-DAG rooted at `v` is duplicated for each copy. The algorithm then recurses on the children of each copy of `v`. Parameters ---------- G : NetworkX graph A directed acyclic graph. Returns ------- DiGraph The branching in which there is a bijection between root-to-leaf paths in `G` (in which multiple paths may share the same leaf) and root-to-leaf paths in the branching (in which there is a unique path from a root to a leaf). Each node has an attribute 'source' whose value is the original node to which this node corresponds. No other graph, node, or edge attributes are copied into this new graph. Raises ------ NetworkXNotImplemented If `G` is not directed, or if `G` is a multigraph. HasACycle If `G` is not acyclic. Examples -------- To examine which nodes in the returned branching were produced by which original node in the directed acyclic graph, we can collect the mapping from source node to new nodes into a dictionary. For example, consider the directed diamond graph:: >>> from collections import defaultdict >>> from operator import itemgetter >>> >>> G = nx.DiGraph(nx.utils.pairwise("abd")) >>> G.add_edges_from(nx.utils.pairwise("acd")) >>> B = nx.dag_to_branching(G) >>> >>> sources = defaultdict(set) >>> for v, source in B.nodes(data="source"): ... sources[source].add(v) >>> len(sources["a"]) 1 >>> len(sources["d"]) 2 To copy node attributes from the original graph to the new graph, you can use a dictionary like the one constructed in the above example:: >>> for source, nodes in sources.items(): ... for v in nodes: ... B.nodes[v].update(G.nodes[source]) Notes ----- This function is not idempotent in the sense that the node labels in the returned branching may be uniquely generated each time the function is invoked. In fact, the node labels may not be integers; in order to relabel the nodes to be more readable, you can use the :func:`networkx.convert_node_labels_to_integers` function. The current implementation of this function uses :func:`networkx.prefix_tree`, so it is subject to the limitations of that function.
def transitive_closure_dag(G, topo_order=None): """Returns the transitive closure of a directed acyclic graph. This function is faster than the function `transitive_closure`, but fails if the graph has a cycle. The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that for all v, w in V there is an edge (v, w) in E+ if and only if there is a non-null path from v to w in G. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) topo_order: list or tuple, optional A topological order for G (if None, the function will compute one) Returns ------- NetworkX DiGraph The transitive closure of `G` Raises ------ NetworkXNotImplemented If `G` is not directed NetworkXUnfeasible If `G` has a cycle Examples -------- >>> DG = nx.DiGraph([(1, 2), (2, 3)]) >>> TC = nx.transitive_closure_dag(DG) >>> TC.edges() OutEdgeView([(1, 2), (1, 3), (2, 3)]) Notes ----- This algorithm is probably simple enough to be well-known but I didn't find a mention in the literature. """ if topo_order is None: topo_order = list(topological_sort(G)) TC = G.copy() # idea: traverse vertices following a reverse topological order, connecting # each vertex to its descendants at distance 2 as we go for v in reversed(topo_order): TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2)) return TC
(G, *, backend=None, **backend_kwargs)
30,536
networkx.generators.social
davis_southern_women_graph
Returns Davis Southern women social network. This is a bipartite graph. References ---------- .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South. University of Chicago Press, Chicago, IL.
null
(*, backend=None, **backend_kwargs)
30,537
networkx.algorithms.summarization
dedensify
Compresses neighborhoods around high-degree nodes Reduces the number of edges to high-degree nodes by adding compressor nodes that summarize multiple edges of the same type to high-degree nodes (nodes with a degree greater than a given threshold). Dedensification also has the added benefit of reducing the number of edges around high-degree nodes. The implementation currently supports graphs with a single edge type. Parameters ---------- G: graph A networkx graph threshold: int Minimum degree threshold of a node to be considered a high degree node. The threshold must be greater than or equal to 2. prefix: str or None, optional (default: None) An optional prefix for denoting compressor nodes copy: bool, optional (default: True) Indicates if dedensification should be done inplace Returns ------- dedensified networkx graph : (graph, set) 2-tuple of the dedensified graph and set of compressor nodes Notes ----- According to the algorithm in [1]_, removes edges in a graph by compressing/decompressing the neighborhoods around high degree nodes by adding compressor nodes that summarize multiple edges of the same type to high-degree nodes. Dedensification will only add a compressor node when doing so will reduce the total number of edges in the given graph. This implementation currently supports graphs with a single edge type. Examples -------- Dedensification will only add compressor nodes when doing so would result in fewer edges:: >>> original_graph = nx.DiGraph() >>> original_graph.add_nodes_from( ... ["1", "2", "3", "4", "5", "6", "A", "B", "C"] ... ) >>> original_graph.add_edges_from( ... [ ... ("1", "C"), ("1", "B"), ... ("2", "C"), ("2", "B"), ("2", "A"), ... ("3", "B"), ("3", "A"), ("3", "6"), ... ("4", "C"), ("4", "B"), ("4", "A"), ... ("5", "B"), ("5", "A"), ... ("6", "5"), ... ("A", "6") ... ] ... ) >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2) >>> original_graph.number_of_edges() 15 >>> c_graph.number_of_edges() 14 A dedensified, directed graph can be "densified" to reconstruct the original graph:: >>> original_graph = nx.DiGraph() >>> original_graph.add_nodes_from( ... ["1", "2", "3", "4", "5", "6", "A", "B", "C"] ... ) >>> original_graph.add_edges_from( ... [ ... ("1", "C"), ("1", "B"), ... ("2", "C"), ("2", "B"), ("2", "A"), ... ("3", "B"), ("3", "A"), ("3", "6"), ... ("4", "C"), ("4", "B"), ("4", "A"), ... ("5", "B"), ("5", "A"), ... ("6", "5"), ... ("A", "6") ... ] ... ) >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2) >>> # re-densifies the compressed graph into the original graph >>> for c_node in c_nodes: ... all_neighbors = set(nx.all_neighbors(c_graph, c_node)) ... out_neighbors = set(c_graph.neighbors(c_node)) ... for out_neighbor in out_neighbors: ... c_graph.remove_edge(c_node, out_neighbor) ... in_neighbors = all_neighbors - out_neighbors ... for in_neighbor in in_neighbors: ... c_graph.remove_edge(in_neighbor, c_node) ... for out_neighbor in out_neighbors: ... c_graph.add_edge(in_neighbor, out_neighbor) ... c_graph.remove_node(c_node) ... >>> nx.is_isomorphic(original_graph, c_graph) True References ---------- .. [1] Maccioni, A., & Abadi, D. J. (2016, August). Scalable pattern matching over compressed graphs via dedensification. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (pp. 1755-1764). http://www.cs.umd.edu/~abadi/papers/graph-dedense.pdf
null
(G, threshold, prefix=None, copy=True, *, backend=None, **backend_kwargs)
30,538
networkx.classes.function
degree
Returns a degree view of single node or of nbunch of nodes. If nbunch is omitted, then return degrees of *all* nodes. This function wraps the :func:`G.degree <networkx.Graph.degree>` property.
def degree(G, nbunch=None, weight=None): """Returns a degree view of single node or of nbunch of nodes. If nbunch is omitted, then return degrees of *all* nodes. This function wraps the :func:`G.degree <networkx.Graph.degree>` property. """ return G.degree(nbunch, weight)
(G, nbunch=None, weight=None)
30,540
networkx.algorithms.assortativity.correlation
degree_assortativity_coefficient
Compute degree assortativity of graph. Assortativity measures the similarity of connections in the graph with respect to the node degree. Parameters ---------- G : NetworkX graph x: string ('in','out') The degree type for source node (directed graphs only). y: string ('in','out') The degree type for target node (directed graphs only). weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. nodes: list or iterable (optional) Compute degree assortativity only for nodes in container. The default is all nodes. Returns ------- r : float Assortativity of graph by degree. Examples -------- >>> G = nx.path_graph(4) >>> r = nx.degree_assortativity_coefficient(G) >>> print(f"{r:3.1f}") -0.5 See Also -------- attribute_assortativity_coefficient numeric_assortativity_coefficient degree_mixing_dict degree_mixing_matrix Notes ----- This computes Eq. (21) in Ref. [1]_ , where e is the joint probability distribution (mixing matrix) of the degrees. If G is directed than the matrix e is the joint probability of the user-specified degree type for the source and target. References ---------- .. [1] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003 .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M. Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
null
(G, x='out', y='in', weight=None, nodes=None, *, backend=None, **backend_kwargs)
30,541
networkx.algorithms.centrality.degree_alg
degree_centrality
Compute the degree centrality for nodes. The degree centrality for a node v is the fraction of nodes it is connected to. Parameters ---------- G : graph A networkx graph Returns ------- nodes : dictionary Dictionary of nodes with degree centrality as the value. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)]) >>> nx.degree_centrality(G) {0: 1.0, 1: 1.0, 2: 0.6666666666666666, 3: 0.6666666666666666} See Also -------- betweenness_centrality, load_centrality, eigenvector_centrality Notes ----- The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1 where n is the number of nodes in G. For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree centrality greater than 1 are possible.
null
(G, *, backend=None, **backend_kwargs)
30,542
networkx.classes.function
degree_histogram
Returns a list of the frequency of each degree value. Parameters ---------- G : Networkx graph A graph Returns ------- hist : list A list of frequencies of degrees. The degree values are the index in the list. Notes ----- Note: the bins are width one, hence len(list) can be large (Order(number_of_edges))
def degree_histogram(G): """Returns a list of the frequency of each degree value. Parameters ---------- G : Networkx graph A graph Returns ------- hist : list A list of frequencies of degrees. The degree values are the index in the list. Notes ----- Note: the bins are width one, hence len(list) can be large (Order(number_of_edges)) """ counts = Counter(d for n, d in G.degree()) return [counts.get(i, 0) for i in range(max(counts) + 1 if counts else 0)]
(G)
30,543
networkx.algorithms.assortativity.mixing
degree_mixing_dict
Returns dictionary representation of mixing matrix for degree. Parameters ---------- G : graph NetworkX graph object. x: string ('in','out') The degree type for source node (directed graphs only). y: string ('in','out') The degree type for target node (directed graphs only). weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. normalized : bool (default=False) Return counts if False or probabilities if True. Returns ------- d: dictionary Counts or joint probability of occurrence of degree pairs.
null
(G, x='out', y='in', weight=None, nodes=None, normalized=False, *, backend=None, **backend_kwargs)
30,544
networkx.algorithms.assortativity.mixing
degree_mixing_matrix
Returns mixing matrix for attribute. Parameters ---------- G : graph NetworkX graph object. x: string ('in','out') The degree type for source node (directed graphs only). y: string ('in','out') The degree type for target node (directed graphs only). nodes: list or iterable (optional) Build the matrix using only nodes in container. The default is all nodes. weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. normalized : bool (default=True) Return counts if False or probabilities if True. mapping : dictionary, optional Mapping from node degree to integer index in matrix. If not specified, an arbitrary ordering will be used. Returns ------- m: numpy array Counts, or joint probability, of occurrence of node degree. Notes ----- Definitions of degree mixing matrix vary on whether the matrix should include rows for degree values that don't arise. Here we do not include such empty-rows. But you can force them to appear by inputting a `mapping` that includes those values. See examples. Examples -------- >>> G = nx.star_graph(3) >>> mix_mat = nx.degree_mixing_matrix(G) >>> mix_mat array([[0. , 0.5], [0.5, 0. ]]) If you want every possible degree to appear as a row, even if no nodes have that degree, use `mapping` as follows, >>> max_degree = max(deg for n, deg in G.degree) >>> mapping = {x: x for x in range(max_degree + 1)} # identity mapping >>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping) >>> mix_mat array([[0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0.5], [0. , 0. , 0. , 0. ], [0. , 0.5, 0. , 0. ]])
null
(G, x='out', y='in', weight=None, nodes=None, normalized=True, mapping=None, *, backend=None, **backend_kwargs)
30,545
networkx.algorithms.assortativity.correlation
degree_pearson_correlation_coefficient
Compute degree assortativity of graph. Assortativity measures the similarity of connections in the graph with respect to the node degree. This is the same as degree_assortativity_coefficient but uses the potentially faster scipy.stats.pearsonr function. Parameters ---------- G : NetworkX graph x: string ('in','out') The degree type for source node (directed graphs only). y: string ('in','out') The degree type for target node (directed graphs only). weight: string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. nodes: list or iterable (optional) Compute pearson correlation of degrees only for specified nodes. The default is all nodes. Returns ------- r : float Assortativity of graph by degree. Examples -------- >>> G = nx.path_graph(4) >>> r = nx.degree_pearson_correlation_coefficient(G) >>> print(f"{r:3.1f}") -0.5 Notes ----- This calls scipy.stats.pearsonr. References ---------- .. [1] M. E. J. Newman, Mixing patterns in networks Physical Review E, 67 026126, 2003 .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M. Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
null
(G, x='out', y='in', weight=None, nodes=None, *, backend=None, **backend_kwargs)
30,547
networkx.generators.degree_seq
degree_sequence_tree
Make a tree for the given degree sequence. A tree has #nodes-#edges=1 so the degree sequence must have len(deg_sequence)-sum(deg_sequence)/2=1
def generate(self): # remaining_degree is mapping from int->remaining degree self.remaining_degree = dict(enumerate(self.degree)) # add all nodes to make sure we get isolated nodes self.graph = nx.Graph() self.graph.add_nodes_from(self.remaining_degree) # remove zero degree nodes for n, d in list(self.remaining_degree.items()): if d == 0: del self.remaining_degree[n] if len(self.remaining_degree) > 0: # build graph in three phases according to how many unmatched edges self.phase1() self.phase2() self.phase3() return self.graph
(deg_sequence, create_using=None, *, backend=None, **backend_kwargs)
30,549
networkx.generators.random_graphs
dense_gnm_random_graph
Returns a $G_{n,m}$ random graph. In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set of all graphs with $n$ nodes and $m$ edges. This algorithm should be faster than :func:`gnm_random_graph` for dense graphs. Parameters ---------- n : int The number of nodes. m : int The number of edges. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. See Also -------- gnm_random_graph Notes ----- Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth's Algorithm S (Selection sampling technique), in section 3.4.2 of [1]_. References ---------- .. [1] Donald E. Knuth, The Art of Computer Programming, Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997.
def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None): """Returns a random graph using dual Barabási–Albert preferential attachment A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that are preferentially attached to existing nodes with high degree. Parameters ---------- n : int Number of nodes m1 : int Number of edges to link each new node to existing nodes with probability $p$ m2 : int Number of edges to link each new node to existing nodes with probability $1-p$ p : float The probability of attaching $m_1$ edges (as opposed to $m_2$ edges) seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. initial_graph : Graph or None (default) Initial network for Barabási–Albert algorithm. A copy of `initial_graph` is used. It should be connected for most use cases. If None, starts from an star graph on max(m1, m2) + 1 nodes. Returns ------- G : Graph Raises ------ NetworkXError If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or `p` does not satisfy ``0 <= p <= 1``, or the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n. References ---------- .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538. """ if m1 < 1 or m1 >= n: raise nx.NetworkXError( f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}" ) if m2 < 1 or m2 >= n: raise nx.NetworkXError( f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}" ) if p < 0 or p > 1: raise nx.NetworkXError( f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}" ) # For simplicity, if p == 0 or 1, just return BA if p == 1: return barabasi_albert_graph(n, m1, seed) elif p == 0: return barabasi_albert_graph(n, m2, seed) if initial_graph is None: # Default initial graph : empty graph on max(m1, m2) nodes G = star_graph(max(m1, m2)) else: if len(initial_graph) < max(m1, m2) or len(initial_graph) > n: raise nx.NetworkXError( f"Barabási–Albert initial graph must have between " f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes" ) G = initial_graph.copy() # Target nodes for new edges targets = list(G) # List of existing nodes, with nodes repeated once for each adjacent edge repeated_nodes = [n for n, d in G.degree() for _ in range(d)] # Start adding the remaining nodes. source = len(G) while source < n: # Pick which m to use (m1 or m2) if seed.random() < p: m = m1 else: m = m2 # Now choose m unique nodes from the existing nodes # Pick uniformly from repeated_nodes (preferential attachment) targets = _random_subset(repeated_nodes, m, seed) # Add edges to m nodes from the source. G.add_edges_from(zip([source] * m, targets)) # Add one node to the list for each new edge just created. repeated_nodes.extend(targets) # And the new node "source" has m edges to add to the list. repeated_nodes.extend([source] * m) source += 1 return G
(n, m, seed=None, *, backend=None, **backend_kwargs)
30,550
networkx.classes.function
density
Returns the density of a graph. The density for undirected graphs is .. math:: d = \frac{2m}{n(n-1)}, and for directed graphs is .. math:: d = \frac{m}{n(n-1)}, where `n` is the number of nodes and `m` is the number of edges in `G`. Notes ----- The density is 0 for a graph without edges and 1 for a complete graph. The density of multigraphs can be higher than 1. Self loops are counted in the total number of edges so graphs with self loops can have density higher than 1.
def density(G): r"""Returns the density of a graph. The density for undirected graphs is .. math:: d = \frac{2m}{n(n-1)}, and for directed graphs is .. math:: d = \frac{m}{n(n-1)}, where `n` is the number of nodes and `m` is the number of edges in `G`. Notes ----- The density is 0 for a graph without edges and 1 for a complete graph. The density of multigraphs can be higher than 1. Self loops are counted in the total number of edges so graphs with self loops can have density higher than 1. """ n = number_of_nodes(G) m = number_of_edges(G) if m == 0 or n <= 1: return 0 d = m / (n * (n - 1)) if not G.is_directed(): d *= 2 return d
(G)
30,552
networkx.generators.small
desargues_graph
Returns the Desargues Graph The Desargues Graph is a non-planar, distance-transitive cubic graph with 20 nodes and 30 edges [1]_. It is a symmetric graph. It can be represented in LCF notation as [5,-5,9,-9]^5 [2]_. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Desargues Graph with 20 nodes and 30 edges References ---------- .. [1] https://en.wikipedia.org/wiki/Desargues_graph .. [2] https://mathworld.wolfram.com/DesarguesGraph.html
def sedgewick_maze_graph(create_using=None): """ Return a small maze with a cycle. This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_. Nodes are numbered 0,..,7 Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Small maze with a cycle References ---------- .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick """ G = empty_graph(0, create_using) G.add_nodes_from(range(8)) G.add_edges_from([[0, 2], [0, 7], [0, 5]]) G.add_edges_from([[1, 7], [2, 6]]) G.add_edges_from([[3, 4], [3, 5]]) G.add_edges_from([[4, 5], [4, 7], [4, 6]]) G.name = "Sedgewick Maze" return G
(create_using=None, *, backend=None, **backend_kwargs)
30,553
networkx.algorithms.dag
descendants
Returns all nodes reachable from `source` in `G`. Parameters ---------- G : NetworkX Graph source : node in `G` Returns ------- set() The descendants of `source` in `G` Raises ------ NetworkXError If node `source` is not in `G`. Examples -------- >>> DG = nx.path_graph(5, create_using=nx.DiGraph) >>> sorted(nx.descendants(DG, 2)) [3, 4] The `source` node is not a descendant of itself, but can be included manually: >>> sorted(nx.descendants(DG, 2) | {2}) [2, 3, 4] See also -------- ancestors
def transitive_closure_dag(G, topo_order=None): """Returns the transitive closure of a directed acyclic graph. This function is faster than the function `transitive_closure`, but fails if the graph has a cycle. The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that for all v, w in V there is an edge (v, w) in E+ if and only if there is a non-null path from v to w in G. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) topo_order: list or tuple, optional A topological order for G (if None, the function will compute one) Returns ------- NetworkX DiGraph The transitive closure of `G` Raises ------ NetworkXNotImplemented If `G` is not directed NetworkXUnfeasible If `G` has a cycle Examples -------- >>> DG = nx.DiGraph([(1, 2), (2, 3)]) >>> TC = nx.transitive_closure_dag(DG) >>> TC.edges() OutEdgeView([(1, 2), (1, 3), (2, 3)]) Notes ----- This algorithm is probably simple enough to be well-known but I didn't find a mention in the literature. """ if topo_order is None: topo_order = list(topological_sort(G)) TC = G.copy() # idea: traverse vertices following a reverse topological order, connecting # each vertex to its descendants at distance 2 as we go for v in reversed(topo_order): TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2)) return TC
(G, source, *, backend=None, **backend_kwargs)
30,554
networkx.algorithms.traversal.breadth_first_search
descendants_at_distance
Returns all nodes at a fixed `distance` from `source` in `G`. Parameters ---------- G : NetworkX graph A graph source : node in `G` distance : the distance of the wanted nodes from `source` Returns ------- set() The descendants of `source` in `G` at the given `distance` from `source` Examples -------- >>> G = nx.path_graph(5) >>> nx.descendants_at_distance(G, 2, 2) {0, 4} >>> H = nx.DiGraph() >>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]) >>> nx.descendants_at_distance(H, 0, 2) {3, 4, 5, 6} >>> nx.descendants_at_distance(H, 5, 0) {5} >>> nx.descendants_at_distance(H, 5, 1) set()
null
(G, source, distance, *, backend=None, **backend_kwargs)
30,555
networkx.algorithms.traversal.depth_first_search
dfs_edges
Iterate over edges in a depth-first-search (DFS). Perform a depth-first-search over the nodes of `G` and yield the edges in order. This may not generate all edges in `G` (see `~networkx.algorithms.traversal.edgedfs.edge_dfs`). Parameters ---------- G : NetworkX graph source : node, optional Specify starting node for depth-first search and yield edges in the component reachable from source. depth_limit : int, optional (default=len(G)) Specify the maximum search depth. sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Yields ------ edge: 2-tuple of nodes Yields edges resulting from the depth-first-search. Examples -------- >>> G = nx.path_graph(5) >>> list(nx.dfs_edges(G, source=0)) [(0, 1), (1, 2), (2, 3), (3, 4)] >>> list(nx.dfs_edges(G, source=0, depth_limit=2)) [(0, 1), (1, 2)] Notes ----- If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched. The implementation of this function is adapted from David Eppstein's depth-first search function in PADS [1]_, with modifications to allow depth limits based on the Wikipedia article "Depth-limited search" [2]_. See Also -------- dfs_preorder_nodes dfs_postorder_nodes dfs_labeled_edges :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs` :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_edges` References ---------- .. [1] http://www.ics.uci.edu/~eppstein/PADS .. [2] https://en.wikipedia.org/wiki/Depth-limited_search
null
(G, source=None, depth_limit=None, *, sort_neighbors=None, backend=None, **backend_kwargs)
30,556
networkx.algorithms.traversal.depth_first_search
dfs_labeled_edges
Iterate over edges in a depth-first-search (DFS) labeled by type. Parameters ---------- G : NetworkX graph source : node, optional Specify starting node for depth-first search and return edges in the component reachable from source. depth_limit : int, optional (default=len(G)) Specify the maximum search depth. sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Returns ------- edges: generator A generator of triples of the form (*u*, *v*, *d*), where (*u*, *v*) is the edge being explored in the depth-first search and *d* is one of the strings 'forward', 'nontree', 'reverse', or 'reverse-depth_limit'. A 'forward' edge is one in which *u* has been visited but *v* has not. A 'nontree' edge is one in which both *u* and *v* have been visited but the edge is not in the DFS tree. A 'reverse' edge is one in which both *u* and *v* have been visited and the edge is in the DFS tree. When the `depth_limit` is reached via a 'forward' edge, a 'reverse' edge is immediately generated rather than the subtree being explored. To indicate this flavor of 'reverse' edge, the string yielded is 'reverse-depth_limit'. Examples -------- The labels reveal the complete transcript of the depth-first search algorithm in more detail than, for example, :func:`dfs_edges`:: >>> from pprint import pprint >>> >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 1)]) >>> pprint(list(nx.dfs_labeled_edges(G, source=0))) [(0, 0, 'forward'), (0, 1, 'forward'), (1, 2, 'forward'), (2, 1, 'nontree'), (1, 2, 'reverse'), (0, 1, 'reverse'), (0, 0, 'reverse')] Notes ----- If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched. The implementation of this function is adapted from David Eppstein's depth-first search function in `PADS`_, with modifications to allow depth limits based on the Wikipedia article "`Depth-limited search`_". .. _PADS: http://www.ics.uci.edu/~eppstein/PADS .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- dfs_edges dfs_preorder_nodes dfs_postorder_nodes
null
(G, source=None, depth_limit=None, *, sort_neighbors=None, backend=None, **backend_kwargs)
30,557
networkx.algorithms.traversal.depth_first_search
dfs_postorder_nodes
Generate nodes in a depth-first-search post-ordering starting at source. Parameters ---------- G : NetworkX graph source : node, optional Specify starting node for depth-first search. depth_limit : int, optional (default=len(G)) Specify the maximum search depth. sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Returns ------- nodes: generator A generator of nodes in a depth-first-search post-ordering. Examples -------- >>> G = nx.path_graph(5) >>> list(nx.dfs_postorder_nodes(G, source=0)) [4, 3, 2, 1, 0] >>> list(nx.dfs_postorder_nodes(G, source=0, depth_limit=2)) [1, 0] Notes ----- If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched. The implementation of this function is adapted from David Eppstein's depth-first search function in `PADS`_, with modifications to allow depth limits based on the Wikipedia article "`Depth-limited search`_". .. _PADS: http://www.ics.uci.edu/~eppstein/PADS .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- dfs_edges dfs_preorder_nodes dfs_labeled_edges :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs` :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
null
(G, source=None, depth_limit=None, *, sort_neighbors=None, backend=None, **backend_kwargs)
30,558
networkx.algorithms.traversal.depth_first_search
dfs_predecessors
Returns dictionary of predecessors in depth-first-search from source. Parameters ---------- G : NetworkX graph source : node, optional Specify starting node for depth-first search. Note that you will get predecessors for all nodes in the component containing `source`. This input only specifies where the DFS starts. depth_limit : int, optional (default=len(G)) Specify the maximum search depth. sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Returns ------- pred: dict A dictionary with nodes as keys and predecessor nodes as values. Examples -------- >>> G = nx.path_graph(4) >>> nx.dfs_predecessors(G, source=0) {1: 0, 2: 1, 3: 2} >>> nx.dfs_predecessors(G, source=0, depth_limit=2) {1: 0, 2: 1} Notes ----- If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched. The implementation of this function is adapted from David Eppstein's depth-first search function in `PADS`_, with modifications to allow depth limits based on the Wikipedia article "`Depth-limited search`_". .. _PADS: http://www.ics.uci.edu/~eppstein/PADS .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- dfs_preorder_nodes dfs_postorder_nodes dfs_labeled_edges :func:`~networkx.algorithms.traversal.edgedfs.edge_dfs` :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_tree`
null
(G, source=None, depth_limit=None, *, sort_neighbors=None, backend=None, **backend_kwargs)
30,559
networkx.algorithms.traversal.depth_first_search
dfs_preorder_nodes
Generate nodes in a depth-first-search pre-ordering starting at source. Parameters ---------- G : NetworkX graph source : node, optional Specify starting node for depth-first search and return nodes in the component reachable from source. depth_limit : int, optional (default=len(G)) Specify the maximum search depth. sort_neighbors : function (default=None) A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, `sorted` will sort the nodes in increasing order. Returns ------- nodes: generator A generator of nodes in a depth-first-search pre-ordering. Examples -------- >>> G = nx.path_graph(5) >>> list(nx.dfs_preorder_nodes(G, source=0)) [0, 1, 2, 3, 4] >>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=2)) [0, 1, 2] Notes ----- If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched. The implementation of this function is adapted from David Eppstein's depth-first search function in `PADS`_, with modifications to allow depth limits based on the Wikipedia article "`Depth-limited search`_". .. _PADS: http://www.ics.uci.edu/~eppstein/PADS .. _Depth-limited search: https://en.wikipedia.org/wiki/Depth-limited_search See Also -------- dfs_edges dfs_postorder_nodes dfs_labeled_edges :func:`~networkx.algorithms.traversal.breadth_first_search.bfs_edges`
null
(G, source=None, depth_limit=None, *, sort_neighbors=None, backend=None, **backend_kwargs)