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,560 | networkx.algorithms.traversal.depth_first_search | dfs_successors | Returns dictionary of successors 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 successors 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
-------
succ: dict
A dictionary with nodes as keys and list of successor nodes as values.
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.dfs_successors(G, source=0)
{0: [1], 1: [2], 2: [3], 3: [4]}
>>> nx.dfs_successors(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`_, 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,561 | networkx.algorithms.traversal.depth_first_search | dfs_tree | Returns oriented tree constructed from a depth-first-search from 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
-------
T : NetworkX DiGraph
An oriented tree
Examples
--------
>>> G = nx.path_graph(5)
>>> T = nx.dfs_tree(G, source=0, depth_limit=2)
>>> list(T.edges())
[(0, 1), (1, 2)]
>>> T = nx.dfs_tree(G, source=0)
>>> list(T.edges())
[(0, 1), (1, 2), (2, 3), (3, 4)]
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,562 | networkx.algorithms.distance_measures | diameter | Returns the diameter of the graph G.
The diameter is the maximum eccentricity.
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
-------
d : integer
Diameter of graph
Examples
--------
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
>>> nx.diameter(G)
3
See Also
--------
eccentricity
| 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,563 | networkx.generators.small | diamond_graph |
Returns the Diamond graph
The Diamond Graph is planar undirected graph with 4 nodes and 5 edges.
It is also sometimes known as the double triangle graph or kite graph [1]_.
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
Diamond Graph with 4 nodes and 5 edges
References
----------
.. [1] https://mathworld.wolfram.com/DiamondGraph.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,564 | networkx.algorithms.operators.binary | difference | Returns a new graph that contains the edges that exist in G but not in H.
The node sets of H and G must be the same.
Parameters
----------
G,H : graph
A NetworkX graph. G and H must have the same node sets.
Returns
-------
D : A new graph with the same type as G.
Notes
-----
Attributes from the graph, nodes, and edges are not copied to the new
graph. If you want a new graph of the difference of G and H with
the attributes (including edge data) from G use remove_nodes_from()
as follows:
>>> G = nx.path_graph(3)
>>> H = nx.path_graph(5)
>>> R = G.copy()
>>> R.remove_nodes_from(n for n in G if n in H)
Examples
--------
>>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3)])
>>> H = nx.Graph([(0, 1), (1, 2), (0, 3)])
>>> R = nx.difference(G, H)
>>> R.nodes
NodeView((0, 1, 2, 3))
>>> R.edges
EdgeView([(0, 2), (1, 3)])
| null | (G, H, *, backend=None, **backend_kwargs) |
30,566 | networkx.algorithms.shortest_paths.weighted | dijkstra_path | Returns the shortest weighted path from source to target in G.
Uses Dijkstra's Method to compute the shortest weighted path
between two nodes in a graph.
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
-------
path : list
List of nodes in a shortest path.
Raises
------
NodeNotFound
If `source` is not in `G`.
NetworkXNoPath
If no path exists between source and target.
Examples
--------
>>> G = nx.path_graph(5)
>>> print(nx.dijkstra_path(G, 0, 4))
[0, 1, 2, 3, 4]
Find edges of shortest path in Multigraph
>>> G = nx.MultiDiGraph()
>>> G.add_weighted_edges_from([(1, 2, 0.75), (1, 2, 0.5), (2, 3, 0.5), (1, 3, 1.5)])
>>> nodes = nx.dijkstra_path(G, 1, 3)
>>> edges = nx.utils.pairwise(nodes)
>>> list(
... (u, v, min(G[u][v], key=lambda k: G[u][v][k].get("weight", 1)))
... for u, v in edges
... )
[(1, 2, 1), (2, 3, 0)]
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.
The weight function can be used to include node weights.
>>> def func(u, v, d):
... node_u_wt = G.nodes[u].get("node_weight", 1)
... node_v_wt = G.nodes[v].get("node_weight", 1)
... edge_wt = d.get("weight", 1)
... return node_u_wt / 2 + node_v_wt / 2 + edge_wt
In this example we take the average of start and end node
weights of an edge and add it to the weight of the edge.
The function :func:`single_source_dijkstra` computes both
path and length-of-path if you need both, use that.
See Also
--------
bidirectional_dijkstra
bellman_ford_path
single_source_dijkstra
| 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,567 | networkx.algorithms.shortest_paths.weighted | dijkstra_path_length | Returns the shortest weighted path length in G from source to target.
Uses Dijkstra's Method to compute the shortest weighted path length
between two nodes in a graph.
Parameters
----------
G : NetworkX graph
source : node label
starting node for path
target : node label
ending node for path
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 : number
Shortest path length.
Raises
------
NodeNotFound
If `source` is not in `G`.
NetworkXNoPath
If no path exists between source and target.
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.dijkstra_path_length(G, 0, 4)
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.
The function :func:`single_source_dijkstra` computes both
path and length-of-path if you need both, use that.
See Also
--------
bidirectional_dijkstra
bellman_ford_path_length
single_source_dijkstra
| 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,568 | networkx.algorithms.shortest_paths.weighted | dijkstra_predecessor_and_distance | Compute weighted shortest path length and predecessors.
Uses Dijkstra's Method to obtain the shortest weighted paths
and return dictionaries of predecessors for each node and
distance for each node from the `source`.
Parameters
----------
G : NetworkX graph
source : node label
Starting node for path
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.
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
-------
pred, distance : dictionaries
Returns two dictionaries representing a list of predecessors
of a node and the distance to each node.
Raises
------
NodeNotFound
If `source` is not in `G`.
Notes
-----
Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The list of predecessors contains more than one element only when
there are more than one shortest paths to the key node.
Examples
--------
>>> G = nx.path_graph(5, create_using=nx.DiGraph())
>>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0)
>>> sorted(pred.items())
[(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
>>> sorted(dist.items())
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0, 1)
>>> sorted(pred.items())
[(0, []), (1, [0])]
>>> sorted(dist.items())
[(0, 0), (1, 1)]
| 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, cutoff=None, weight='weight', *, backend=None, **backend_kwargs) |
30,570 | networkx.linalg.laplacianmatrix | directed_combinatorial_laplacian_matrix | Return the directed combinatorial Laplacian matrix of G.
The graph directed combinatorial Laplacian is the matrix
.. math::
L = \Phi - \frac{1}{2} \left (\Phi P + P^T \Phi \right)
where `P` is the transition matrix of the graph and `\Phi` a matrix
with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.
Depending on the value of walk_type, `P` can be the transition matrix
induced by a random walk, a lazy random walk, or a random walk with
teleportation (PageRank).
Parameters
----------
G : DiGraph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
walk_type : string or None, optional (default=None)
One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
(the default), then a value is selected according to the properties of `G`:
- ``walk_type="random"`` if `G` is strongly connected and aperiodic
- ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
- ``walk_type="pagerank"`` for all other cases.
alpha : real
(1 - alpha) is the teleportation probability used with pagerank
Returns
-------
L : NumPy matrix
Combinatorial Laplacian of G.
Notes
-----
Only implemented for DiGraphs
The result is always a symmetric matrix.
This calculation uses the out-degree of the graph `G`. To use the
in-degree for calculations instead, use `G.reverse(copy=False)` and
take the transpose.
See Also
--------
laplacian_matrix
normalized_laplacian_matrix
directed_laplacian_matrix
References
----------
.. [1] Fan Chung (2005).
Laplacians and the Cheeger inequality for directed graphs.
Annals of Combinatorics, 9(1), 2005
| null | (G, nodelist=None, weight='weight', walk_type=None, alpha=0.95, *, backend=None, **backend_kwargs) |
30,571 | networkx.generators.degree_seq | directed_configuration_model | Returns a directed_random graph with the given degree sequences.
The configuration model generates a random directed pseudograph
(graph with parallel edges and self loops) by randomly assigning
edges to match the given degree sequences.
Parameters
----------
in_degree_sequence : list of nonnegative integers
Each list entry corresponds to the in-degree of a node.
out_degree_sequence : list of nonnegative integers
Each list entry corresponds to the out-degree of a node.
create_using : NetworkX graph constructor, optional (default MultiDiGraph)
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 : MultiDiGraph
A graph with the specified degree sequences.
Nodes are labeled starting at 0 with an index
corresponding to the position in deg_sequence.
Raises
------
NetworkXError
If the degree sequences do not have the same sum.
See Also
--------
configuration_model
Notes
-----
Algorithm 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
sequences does not have the same 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. This
"finite-size effect" decreases as the size of the graph increases.
References
----------
.. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J.
Random graphs with arbitrary degree distributions and their applications
Phys. Rev. E, 64, 026118 (2001)
Examples
--------
One can modify the in- and out-degree sequences from an existing
directed graph in order to create a new directed graph. For example,
here we modify the directed path graph:
>>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
>>> din = list(d for n, d in D.in_degree())
>>> dout = list(d for n, d in D.out_degree())
>>> din.append(1)
>>> dout[0] = 2
>>> # We now expect an edge from node 0 to a new node, node 3.
... D = nx.directed_configuration_model(din, dout)
The returned graph is a directed multigraph, which may have parallel
edges. To remove any parallel edges from the returned graph:
>>> D = nx.DiGraph(D)
Similarly, to remove self-loops:
>>> D.remove_edges_from(nx.selfloop_edges(D))
| 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
| (in_degree_sequence, out_degree_sequence, create_using=None, seed=None, *, backend=None, **backend_kwargs) |
30,572 | networkx.algorithms.swap | directed_edge_swap | Swap three edges in a directed graph while keeping the node degrees fixed.
A directed edge swap swaps three edges such that a -> b -> c -> d becomes
a -> c -> b -> d. This pattern of swapping allows all possible states with the
same in- and out-degree distribution in a directed graph to be reached.
If the swap would create parallel edges (e.g. if a -> c already existed in the
previous example), another attempt is made to find a suitable trio of edges.
Parameters
----------
G : DiGraph
A directed graph
nswap : integer (optional, default=1)
Number of three-edge (directed) swaps to perform
max_tries : integer (optional, default=100)
Maximum number of attempts to swap edges
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : DiGraph
The graph after the edges are swapped.
Raises
------
NetworkXError
If `G` is not directed, or
If nswap > max_tries, or
If there are fewer than 4 nodes or 3 edges in `G`.
NetworkXAlgorithmError
If the number of swap attempts exceeds `max_tries` before `nswap` swaps are made
Notes
-----
Does not enforce any connectivity constraints.
The graph G is modified in place.
A later swap is allowed to undo a previous swap.
References
----------
.. [1] Erdős, Péter L., et al. “A Simple Havel-Hakimi Type Algorithm to Realize
Graphical Degree Sequences of Directed Graphs.” ArXiv:0905.4913 [Math],
Jan. 2010. https://doi.org/10.48550/arXiv.0905.4913.
Published 2010 in Elec. J. Combinatorics (17(1)). R66.
http://www.combinatorics.org/Volume_17/PDF/v17i1r66.pdf
.. [2] “Combinatorics - Reaching All Possible Simple Directed Graphs with a given
Degree Sequence with 2-Edge Swaps.” Mathematics Stack Exchange,
https://math.stackexchange.com/questions/22272/. Accessed 30 May 2022.
| null | (G, *, nswap=1, max_tries=100, seed=None, backend=None, **backend_kwargs) |
30,573 | networkx.generators.degree_seq | directed_havel_hakimi_graph | Returns a directed graph with the given degree sequences.
Parameters
----------
in_deg_sequence : list of integers
Each list entry corresponds to the in-degree of a node.
out_deg_sequence : list of integers
Each list entry corresponds to the out-degree of a node.
create_using : NetworkX graph constructor, optional (default DiGraph)
Graph type to create. If graph instance, then cleared before populated.
Returns
-------
G : DiGraph
A graph with the specified degree sequences.
Nodes are labeled starting at 0 with an index
corresponding to the position in deg_sequence
Raises
------
NetworkXError
If the degree sequences are not digraphical.
See Also
--------
configuration_model
Notes
-----
Algorithm as described by Kleitman and Wang [1]_.
References
----------
.. [1] D.J. Kleitman and D.L. Wang
Algorithms for Constructing Graphs and Digraphs with Given Valences
and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
| 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
| (in_deg_sequence, out_deg_sequence, create_using=None, *, backend=None, **backend_kwargs) |
30,574 | networkx.generators.joint_degree_seq | directed_joint_degree_graph | Generates a random simple directed graph with the joint degree.
Parameters
----------
degree_seq : list of tuples (of size 3)
degree sequence contains tuples of nodes with node id, in degree and
out degree.
nkk : dictionary of dictionary of integers
directed joint degree dictionary, for nodes of out degree k (first
level of dict) and nodes of in degree l (second level of dict)
describes the number of edges.
seed : hashable object, optional
Seed for random number generator.
Returns
-------
G : Graph
A directed graph with the specified inputs.
Raises
------
NetworkXError
If degree_seq and nkk are not realizable as a simple directed graph.
Notes
-----
Similarly to the undirected version:
In each iteration of the "while loop" the algorithm picks two disconnected
nodes v and w, of degree k and l correspondingly, for which nkk[k][l] has
not reached its target yet i.e. (for given k,l): n_edges_add < nkk[k][l].
It then adds edge (v,w) and always increases the number of edges in graph G
by one.
The intelligence of the algorithm lies in the fact that it is always
possible to add an edge between disconnected nodes v and w, for which
nkk[degree(v)][degree(w)] has not reached its target, even if one or both
nodes do not have free stubs. If either node v or w does not have a free
stub, we perform a "neighbor switch", an edge rewiring move that releases a
free stub while keeping nkk the same.
The difference for the directed version lies in the fact that neighbor
switches might not be able to rewire, but in these cases unsaturated nodes
can be reassigned to use instead, see [1] for detailed description and
proofs.
The algorithm continues for E (number of edges in the graph) iterations of
the "while loop", at which point all entries of the given nkk[k][l] have
reached their target values and the construction is complete.
References
----------
[1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
"Construction of Directed 2K Graphs". In Proc. of KDD 2017.
Examples
--------
>>> in_degrees = [0, 1, 1, 2]
>>> out_degrees = [1, 1, 1, 1]
>>> nkk = {1: {1: 2, 2: 2}}
>>> G = nx.directed_joint_degree_graph(in_degrees, out_degrees, nkk)
>>>
| null | (in_degrees, out_degrees, nkk, seed=None, *, backend=None, **backend_kwargs) |
30,575 | networkx.linalg.laplacianmatrix | directed_laplacian_matrix | Returns the directed Laplacian matrix of G.
The graph directed Laplacian is the matrix
.. math::
L = I - \frac{1}{2} \left (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} \right )
where `I` is the identity matrix, `P` is the transition matrix of the
graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and
zeros elsewhere [1]_.
Depending on the value of walk_type, `P` can be the transition matrix
induced by a random walk, a lazy random walk, or a random walk with
teleportation (PageRank).
Parameters
----------
G : DiGraph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
walk_type : string or None, optional (default=None)
One of ``"random"``, ``"lazy"``, or ``"pagerank"``. If ``walk_type=None``
(the default), then a value is selected according to the properties of `G`:
- ``walk_type="random"`` if `G` is strongly connected and aperiodic
- ``walk_type="lazy"`` if `G` is strongly connected but not aperiodic
- ``walk_type="pagerank"`` for all other cases.
alpha : real
(1 - alpha) is the teleportation probability used with pagerank
Returns
-------
L : NumPy matrix
Normalized Laplacian of G.
Notes
-----
Only implemented for DiGraphs
The result is always a symmetric matrix.
This calculation uses the out-degree of the graph `G`. To use the
in-degree for calculations instead, use `G.reverse(copy=False)` and
take the transpose.
See Also
--------
laplacian_matrix
normalized_laplacian_matrix
directed_combinatorial_laplacian_matrix
References
----------
.. [1] Fan Chung (2005).
Laplacians and the Cheeger inequality for directed graphs.
Annals of Combinatorics, 9(1), 2005
| null | (G, nodelist=None, weight='weight', walk_type=None, alpha=0.95, *, backend=None, **backend_kwargs) |
30,576 | networkx.linalg.modularitymatrix | directed_modularity_matrix | Returns the directed modularity matrix of G.
The modularity matrix is the matrix B = A - <A>, where A is the adjacency
matrix and <A> is the expected adjacency matrix, assuming that the graph
is described by the configuration model.
More specifically, the element B_ij of B is defined as
.. math::
B_{ij} = A_{ij} - k_i^{out} k_j^{in} / m
where :math:`k_i^{in}` is the in degree of node i, and :math:`k_j^{out}` is the out degree
of node j, with m the number of edges in the graph. When weight is set
to a name of an attribute edge, Aij, k_i, k_j and m are computed using
its value.
Parameters
----------
G : DiGraph
A NetworkX DiGraph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used for
the edge weight. If None then all edge weights are 1.
Returns
-------
B : Numpy array
The modularity matrix of G.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_edges_from(
... (
... (1, 2),
... (1, 3),
... (3, 1),
... (3, 2),
... (3, 5),
... (4, 5),
... (4, 6),
... (5, 4),
... (5, 6),
... (6, 4),
... )
... )
>>> B = nx.directed_modularity_matrix(G)
Notes
-----
NetworkX defines the element A_ij of the adjacency matrix as 1 if there
is a link going from node i to node j. Leicht and Newman use the opposite
definition. This explains the different expression for B_ij.
See Also
--------
to_numpy_array
modularity_spectrum
adjacency_matrix
modularity_matrix
References
----------
.. [1] E. A. Leicht, M. E. J. Newman,
"Community structure in directed networks",
Phys. Rev Lett., vol. 100, no. 11, p. 118703, 2008.
| null | (G, nodelist=None, weight=None, *, backend=None, **backend_kwargs) |
30,577 | networkx.algorithms.operators.binary | disjoint_union | Combine graphs G and H. The nodes are assumed to be unique (disjoint).
This algorithm automatically relabels nodes to avoid name collisions.
Parameters
----------
G,H : graph
A NetworkX graph
Returns
-------
U : A union graph with the same type as G.
See Also
--------
union
compose
:func:`~networkx.Graph.update`
Notes
-----
A new graph is created, of the same class as G. It is recommended
that G and H be either both directed or both undirected.
The nodes of G are relabeled 0 to len(G)-1, and the nodes of H are
relabeled len(G) to len(G)+len(H)-1.
Renumbering forces G and H to be disjoint, so no exception is ever raised for a name collision.
To preserve the check for common nodes, use union().
Edge and node attributes are propagated from G and H to the union graph.
Graph attributes are also propagated, but if they are present in both G and H,
then the value from H is used.
To combine graphs that have common nodes, consider compose(G, H)
or the method, Graph.update().
Examples
--------
>>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
>>> H = nx.Graph([(0, 3), (1, 2), (2, 3)])
>>> G.nodes[0]["key1"] = 5
>>> H.nodes[0]["key2"] = 10
>>> U = nx.disjoint_union(G, H)
>>> U.nodes(data=True)
NodeDataView({0: {'key1': 5}, 1: {}, 2: {}, 3: {'key2': 10}, 4: {}, 5: {}, 6: {}})
>>> U.edges
EdgeView([(0, 1), (0, 2), (1, 2), (3, 4), (4, 6), (5, 6)])
| null | (G, H, *, backend=None, **backend_kwargs) |
30,578 | networkx.algorithms.operators.all | disjoint_union_all | Returns the disjoint union of all graphs.
This operation forces distinct integer node labels starting with 0
for the first graph in the list and numbering consecutively.
Parameters
----------
graphs : iterable
Iterable of NetworkX graphs
Returns
-------
U : 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([(4, 5), (5, 6)])
>>> U = nx.disjoint_union_all([G1, G2])
>>> list(U.nodes())
[0, 1, 2, 3, 4, 5]
>>> list(U.edges())
[(0, 1), (1, 2), (3, 4), (4, 5)]
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,579 | networkx.algorithms.centrality.dispersion | dispersion | Calculate dispersion between `u` and `v` in `G`.
A link between two actors (`u` and `v`) has a high dispersion when their
mutual ties (`s` and `t`) are not well connected with each other.
Parameters
----------
G : graph
A NetworkX graph.
u : node, optional
The source for the dispersion score (e.g. ego node of the network).
v : node, optional
The target of the dispersion score if specified.
normalized : bool
If True (default) normalize by the embeddedness of the nodes (u and v).
alpha, b, c : float
Parameters for the normalization procedure. When `normalized` is True,
the dispersion value is normalized by::
result = ((dispersion + b) ** alpha) / (embeddedness + c)
as long as the denominator is nonzero.
Returns
-------
nodes : dictionary
If u (v) is specified, returns a dictionary of nodes with dispersion
score for all "target" ("source") nodes. If neither u nor v is
specified, returns a dictionary of dictionaries for all nodes 'u' in the
graph with a dispersion score for each node 'v'.
Notes
-----
This implementation follows Lars Backstrom and Jon Kleinberg [1]_. Typical
usage would be to run dispersion on the ego network $G_u$ if $u$ were
specified. Running :func:`dispersion` with neither $u$ nor $v$ specified
can take some time to complete.
References
----------
.. [1] Romantic Partnerships and the Dispersion of Social Ties:
A Network Analysis of Relationship Status on Facebook.
Lars Backstrom, Jon Kleinberg.
https://arxiv.org/pdf/1310.6753v1.pdf
| null | (G, u=None, v=None, normalized=True, alpha=1.0, b=0.0, c=0.0, *, backend=None, **backend_kwargs) |
30,582 | networkx.generators.small | dodecahedral_graph |
Returns the Platonic Dodecahedral graph.
The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the
dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_.
It can be described in LCF notation as:
``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [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
Dodecahedral Graph with 20 nodes and 30 edges
References
----------
.. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph
.. [2] https://mathworld.wolfram.com/DodecahedralGraph.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,584 | networkx.algorithms.dominance | dominance_frontiers | Returns the dominance frontiers of all nodes of a directed graph.
Parameters
----------
G : a DiGraph or MultiDiGraph
The graph where dominance is to be computed.
start : node
The start node of dominance computation.
Returns
-------
df : dict keyed by nodes
A dict containing the dominance frontiers of each node reachable from
`start` as lists.
Raises
------
NetworkXNotImplemented
If `G` is undirected.
NetworkXError
If `start` is not in `G`.
Examples
--------
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
>>> sorted((u, sorted(df)) for u, df in nx.dominance_frontiers(G, 1).items())
[(1, []), (2, [5]), (3, [5]), (4, [5]), (5, [])]
References
----------
.. [1] K. D. Cooper, T. J. Harvey, and K. Kennedy.
A simple, fast dominance algorithm.
Software Practice & Experience, 4:110, 2001.
| null | (G, start, *, backend=None, **backend_kwargs) |
30,586 | networkx.algorithms.dominating | dominating_set | Finds a dominating set for the graph G.
A *dominating set* for a graph with node set *V* is a subset *D* of
*V* such that every node not in *D* is adjacent to at least one
member of *D* [1]_.
Parameters
----------
G : NetworkX graph
start_with : node (default=None)
Node to use as a starting point for the algorithm.
Returns
-------
D : set
A dominating set for G.
Notes
-----
This function is an implementation of algorithm 7 in [2]_ which
finds some dominating set, not necessarily the smallest one.
See also
--------
is_dominating_set
References
----------
.. [1] https://en.wikipedia.org/wiki/Dominating_set
.. [2] Abdol-Hossein Esfahanian. Connectivity Algorithms.
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
| null | (G, start_with=None, *, backend=None, **backend_kwargs) |
30,587 | networkx.generators.classic | dorogovtsev_goltsev_mendes_graph | Returns the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.
The Dorogovtsev-Goltsev-Mendes [1]_ procedure produces a scale-free graph
deterministically with the following properties for a given `n`:
- Total number of nodes = ``3 * (3**n + 1) / 2``
- Total number of edges = ``3 ** (n + 1)``
.. plot::
>>> nx.draw(nx.dorogovtsev_goltsev_mendes_graph(3))
Parameters
----------
n : integer
The generation number.
create_using : NetworkX Graph, optional
Graph type to be returned. Directed graphs and multi graphs are not
supported.
Returns
-------
G : NetworkX Graph
Examples
--------
>>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
>>> G.number_of_nodes()
15
>>> G.number_of_edges()
27
>>> nx.is_planar(G)
True
References
----------
.. [1] S. N. Dorogovtsev, A. V. Goltsev and J. F. F. Mendes,
"Pseudofractal scale-free web", Physical Review E 65, 066122, 2002.
https://arxiv.org/pdf/cond-mat/0112143.pdf
| 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,588 | networkx.algorithms.swap | double_edge_swap | Swap two edges in the graph while keeping the node degrees fixed.
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 the edge u-x or v-y already exist no swap is performed
and another attempt is made to find a suitable edge pair.
Parameters
----------
G : graph
An undirected graph
nswap : integer (optional, default=1)
Number of double-edge swaps to perform
max_tries : integer (optional)
Maximum number of attempts to swap edges
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : graph
The graph after double edge swaps.
Raises
------
NetworkXError
If `G` is directed, or
If `nswap` > `max_tries`, or
If there are fewer than 4 nodes or 2 edges in `G`.
NetworkXAlgorithmError
If the number of swap attempts exceeds `max_tries` before `nswap` swaps are made
Notes
-----
Does not enforce any connectivity constraints.
The graph G is modified in place.
| null | (G, nswap=1, max_tries=100, seed=None, *, backend=None, **backend_kwargs) |
30,589 | networkx.drawing.nx_pylab | draw | Draw the graph G with Matplotlib.
Draw the graph as a simple representation with no node
labels or edge labels and using the full Matplotlib figure area
and no axis labels by default. See draw_networkx() for more
full-featured drawing that allows title, axis labels etc.
Parameters
----------
G : graph
A networkx graph
pos : dictionary, optional
A dictionary with nodes as keys and positions as values.
If not specified a spring layout positioning will be computed.
See :py:mod:`networkx.drawing.layout` for functions that
compute node positions.
ax : Matplotlib Axes object, optional
Draw the graph in specified Matplotlib axes.
kwds : optional keywords
See networkx.draw_networkx() for a description of optional keywords.
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
See Also
--------
draw_networkx
draw_networkx_nodes
draw_networkx_edges
draw_networkx_labels
draw_networkx_edge_labels
Notes
-----
This function has the same name as pylab.draw and pyplot.draw
so beware when using `from networkx import *`
since you might overwrite the pylab.draw function.
With pyplot use
>>> import matplotlib.pyplot as plt
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G) # networkx draw()
>>> plt.draw() # pyplot draw()
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
| def draw(G, pos=None, ax=None, **kwds):
"""Draw the graph G with Matplotlib.
Draw the graph as a simple representation with no node
labels or edge labels and using the full Matplotlib figure area
and no axis labels by default. See draw_networkx() for more
full-featured drawing that allows title, axis labels etc.
Parameters
----------
G : graph
A networkx graph
pos : dictionary, optional
A dictionary with nodes as keys and positions as values.
If not specified a spring layout positioning will be computed.
See :py:mod:`networkx.drawing.layout` for functions that
compute node positions.
ax : Matplotlib Axes object, optional
Draw the graph in specified Matplotlib axes.
kwds : optional keywords
See networkx.draw_networkx() for a description of optional keywords.
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
See Also
--------
draw_networkx
draw_networkx_nodes
draw_networkx_edges
draw_networkx_labels
draw_networkx_edge_labels
Notes
-----
This function has the same name as pylab.draw and pyplot.draw
so beware when using `from networkx import *`
since you might overwrite the pylab.draw function.
With pyplot use
>>> import matplotlib.pyplot as plt
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G) # networkx draw()
>>> plt.draw() # pyplot draw()
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
"""
import matplotlib.pyplot as plt
if ax is None:
cf = plt.gcf()
else:
cf = ax.get_figure()
cf.set_facecolor("w")
if ax is None:
if cf.axes:
ax = cf.gca()
else:
ax = cf.add_axes((0, 0, 1, 1))
if "with_labels" not in kwds:
kwds["with_labels"] = "labels" in kwds
draw_networkx(G, pos=pos, ax=ax, **kwds)
ax.set_axis_off()
plt.draw_if_interactive()
return
| (G, pos=None, ax=None, **kwds) |
30,590 | networkx.drawing.nx_pylab | draw_circular | Draw the graph `G` with a circular layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.circular_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called. For
repeated drawing it is much more efficient to call
`~networkx.drawing.layout.circular_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.circular_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.draw_circular(G)
See Also
--------
:func:`~networkx.drawing.layout.circular_layout`
| def draw_circular(G, **kwargs):
"""Draw the graph `G` with a circular layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.circular_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called. For
repeated drawing it is much more efficient to call
`~networkx.drawing.layout.circular_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.circular_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.draw_circular(G)
See Also
--------
:func:`~networkx.drawing.layout.circular_layout`
"""
draw(G, circular_layout(G), **kwargs)
| (G, **kwargs) |
30,591 | networkx.drawing.nx_pylab | draw_kamada_kawai | Draw the graph `G` with a Kamada-Kawai force-directed layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.kamada_kawai_layout` directly and reuse the
result::
>>> G = nx.complete_graph(5)
>>> pos = nx.kamada_kawai_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.draw_kamada_kawai(G)
See Also
--------
:func:`~networkx.drawing.layout.kamada_kawai_layout`
| def draw_kamada_kawai(G, **kwargs):
"""Draw the graph `G` with a Kamada-Kawai force-directed layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.kamada_kawai_layout` directly and reuse the
result::
>>> G = nx.complete_graph(5)
>>> pos = nx.kamada_kawai_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.draw_kamada_kawai(G)
See Also
--------
:func:`~networkx.drawing.layout.kamada_kawai_layout`
"""
draw(G, kamada_kawai_layout(G), **kwargs)
| (G, **kwargs) |
30,592 | networkx.drawing.nx_pylab | draw_networkx | Draw the graph G using Matplotlib.
Draw the graph with Matplotlib with options for node positions,
labeling, titles, and many other drawing features.
See draw() for simple drawing without labels or axes.
Parameters
----------
G : graph
A networkx graph
pos : dictionary, optional
A dictionary with nodes as keys and positions as values.
If not specified a spring layout positioning will be computed.
See :py:mod:`networkx.drawing.layout` for functions that
compute node positions.
arrows : bool or None, optional (default=None)
If `None`, directed graphs draw arrowheads with
`~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
via `~matplotlib.collections.LineCollection` for speed.
If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
If `False`, draw edges using LineCollection (linear and fast).
For directed graphs, if True draw arrowheads.
Note: Arrows will be the same color as edges.
arrowstyle : str (default='-\|>' for directed graphs)
For directed graphs, choose the style of the arrowsheads.
For undirected graphs default to '-'
See `matplotlib.patches.ArrowStyle` for more options.
arrowsize : int or list (default=10)
For directed graphs, choose the size of the arrow head's length and
width. A list of values can be passed in to assign a different size for arrow head's length and width.
See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale`
for more info.
with_labels : bool (default=True)
Set to True to draw labels on the nodes.
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
nodelist : list (default=list(G))
Draw only specified nodes
edgelist : list (default=list(G.edges()))
Draw only specified edges
node_size : scalar or array (default=300)
Size of nodes. If an array is specified it must be the
same length as nodelist.
node_color : color or array of colors (default='#1f78b4')
Node color. Can be a single color or a sequence of colors with the same
length as nodelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the cmap and vmin,vmax parameters. See
matplotlib.scatter for more details.
node_shape : string (default='o')
The shape of the node. Specification is as matplotlib.scatter
marker, one of 'so^>v<dph8'.
alpha : float or None (default=None)
The node and edge transparency
cmap : Matplotlib colormap, optional
Colormap for mapping intensities of nodes
vmin,vmax : float, optional
Minimum and maximum for node colormap scaling
linewidths : scalar or sequence (default=1.0)
Line width of symbol border
width : float or array of floats (default=1.0)
Line width of edges
edge_color : color or array of colors (default='k')
Edge color. Can be a single color or a sequence of colors with the same
length as edgelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
edge_cmap : Matplotlib colormap, optional
Colormap for mapping intensities of edges
edge_vmin,edge_vmax : floats, optional
Minimum and maximum for edge colormap scaling
style : string (default=solid line)
Edge line style e.g.: '-', '--', '-.', ':'
or words like 'solid' or 'dashed'.
(See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
labels : dictionary (default=None)
Node labels in a dictionary of text labels keyed by node
font_size : int (default=12 for nodes, 10 for edges)
Font size for text labels
font_color : color (default='k' black)
Font color string. Color can be string or rgb (or rgba) tuple of
floats from 0-1.
font_weight : string (default='normal')
Font weight
font_family : string (default='sans-serif')
Font family
label : string, optional
Label for graph legend
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
kwds : optional keywords
See networkx.draw_networkx_nodes(), networkx.draw_networkx_edges(), and
networkx.draw_networkx_labels() for a description of optional keywords.
Notes
-----
For directed graphs, arrows are drawn at the head end. Arrows can be
turned off with keyword arrows=False.
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
>>> import matplotlib.pyplot as plt
>>> limits = plt.axis("off") # turn off axis
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx_nodes
draw_networkx_edges
draw_networkx_labels
draw_networkx_edge_labels
| def draw_networkx(G, pos=None, arrows=None, with_labels=True, **kwds):
r"""Draw the graph G using Matplotlib.
Draw the graph with Matplotlib with options for node positions,
labeling, titles, and many other drawing features.
See draw() for simple drawing without labels or axes.
Parameters
----------
G : graph
A networkx graph
pos : dictionary, optional
A dictionary with nodes as keys and positions as values.
If not specified a spring layout positioning will be computed.
See :py:mod:`networkx.drawing.layout` for functions that
compute node positions.
arrows : bool or None, optional (default=None)
If `None`, directed graphs draw arrowheads with
`~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
via `~matplotlib.collections.LineCollection` for speed.
If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
If `False`, draw edges using LineCollection (linear and fast).
For directed graphs, if True draw arrowheads.
Note: Arrows will be the same color as edges.
arrowstyle : str (default='-\|>' for directed graphs)
For directed graphs, choose the style of the arrowsheads.
For undirected graphs default to '-'
See `matplotlib.patches.ArrowStyle` for more options.
arrowsize : int or list (default=10)
For directed graphs, choose the size of the arrow head's length and
width. A list of values can be passed in to assign a different size for arrow head's length and width.
See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale`
for more info.
with_labels : bool (default=True)
Set to True to draw labels on the nodes.
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
nodelist : list (default=list(G))
Draw only specified nodes
edgelist : list (default=list(G.edges()))
Draw only specified edges
node_size : scalar or array (default=300)
Size of nodes. If an array is specified it must be the
same length as nodelist.
node_color : color or array of colors (default='#1f78b4')
Node color. Can be a single color or a sequence of colors with the same
length as nodelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the cmap and vmin,vmax parameters. See
matplotlib.scatter for more details.
node_shape : string (default='o')
The shape of the node. Specification is as matplotlib.scatter
marker, one of 'so^>v<dph8'.
alpha : float or None (default=None)
The node and edge transparency
cmap : Matplotlib colormap, optional
Colormap for mapping intensities of nodes
vmin,vmax : float, optional
Minimum and maximum for node colormap scaling
linewidths : scalar or sequence (default=1.0)
Line width of symbol border
width : float or array of floats (default=1.0)
Line width of edges
edge_color : color or array of colors (default='k')
Edge color. Can be a single color or a sequence of colors with the same
length as edgelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
edge_cmap : Matplotlib colormap, optional
Colormap for mapping intensities of edges
edge_vmin,edge_vmax : floats, optional
Minimum and maximum for edge colormap scaling
style : string (default=solid line)
Edge line style e.g.: '-', '--', '-.', ':'
or words like 'solid' or 'dashed'.
(See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
labels : dictionary (default=None)
Node labels in a dictionary of text labels keyed by node
font_size : int (default=12 for nodes, 10 for edges)
Font size for text labels
font_color : color (default='k' black)
Font color string. Color can be string or rgb (or rgba) tuple of
floats from 0-1.
font_weight : string (default='normal')
Font weight
font_family : string (default='sans-serif')
Font family
label : string, optional
Label for graph legend
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
kwds : optional keywords
See networkx.draw_networkx_nodes(), networkx.draw_networkx_edges(), and
networkx.draw_networkx_labels() for a description of optional keywords.
Notes
-----
For directed graphs, arrows are drawn at the head end. Arrows can be
turned off with keyword arrows=False.
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
>>> import matplotlib.pyplot as plt
>>> limits = plt.axis("off") # turn off axis
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx_nodes
draw_networkx_edges
draw_networkx_labels
draw_networkx_edge_labels
"""
from inspect import signature
import matplotlib.pyplot as plt
# Get all valid keywords by inspecting the signatures of draw_networkx_nodes,
# draw_networkx_edges, draw_networkx_labels
valid_node_kwds = signature(draw_networkx_nodes).parameters.keys()
valid_edge_kwds = signature(draw_networkx_edges).parameters.keys()
valid_label_kwds = signature(draw_networkx_labels).parameters.keys()
# Create a set with all valid keywords across the three functions and
# remove the arguments of this function (draw_networkx)
valid_kwds = (valid_node_kwds | valid_edge_kwds | valid_label_kwds) - {
"G",
"pos",
"arrows",
"with_labels",
}
if any(k not in valid_kwds for k in kwds):
invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
raise ValueError(f"Received invalid argument(s): {invalid_args}")
node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}
if pos is None:
pos = nx.drawing.spring_layout(G) # default to spring layout
draw_networkx_nodes(G, pos, **node_kwds)
draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
if with_labels:
draw_networkx_labels(G, pos, **label_kwds)
plt.draw_if_interactive()
| (G, pos=None, arrows=None, with_labels=True, **kwds) |
30,593 | networkx.drawing.nx_pylab | draw_networkx_edge_labels | Draw edge labels.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
edge_labels : dictionary (default=None)
Edge labels in a dictionary of labels keyed by edge two-tuple.
Only labels for the keys in the dictionary are drawn.
label_pos : float (default=0.5)
Position of edge label along edge (0=head, 0.5=center, 1=tail)
font_size : int (default=10)
Font size for text labels
font_color : color (default='k' black)
Font color string. Color can be string or rgb (or rgba) tuple of
floats from 0-1.
font_weight : string (default='normal')
Font weight
font_family : string (default='sans-serif')
Font family
alpha : float or None (default=None)
The text transparency
bbox : Matplotlib bbox, optional
Specify text box properties (e.g. shape, color etc.) for edge labels.
Default is {boxstyle='round', ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}.
horizontalalignment : string (default='center')
Horizontal alignment {'center', 'right', 'left'}
verticalalignment : string (default='center')
Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
rotate : bool (default=True)
Rotate edge labels to lie parallel to edges
clip_on : bool (default=True)
Turn on clipping of edge labels at axis boundaries
node_size : scalar or array (default=300)
Size of nodes. If an array it must be the same length as nodelist.
nodelist : list, optional (default=G.nodes())
This provides the node order for the `node_size` array (if it is an array).
connectionstyle : string or iterable of strings (default="arc3")
Pass the connectionstyle parameter to create curved arc of rounding
radius rad. For example, connectionstyle='arc3,rad=0.2'.
See `matplotlib.patches.ConnectionStyle` and
`matplotlib.patches.FancyArrowPatch` for more info.
If Iterable, index indicates i'th edge key of MultiGraph
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
dict
`dict` of labels keyed by edge
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_nodes
draw_networkx_edges
draw_networkx_labels
| def draw_networkx_edge_labels(
G,
pos,
edge_labels=None,
label_pos=0.5,
font_size=10,
font_color="k",
font_family="sans-serif",
font_weight="normal",
alpha=None,
bbox=None,
horizontalalignment="center",
verticalalignment="center",
ax=None,
rotate=True,
clip_on=True,
node_size=300,
nodelist=None,
connectionstyle="arc3",
hide_ticks=True,
):
"""Draw edge labels.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
edge_labels : dictionary (default=None)
Edge labels in a dictionary of labels keyed by edge two-tuple.
Only labels for the keys in the dictionary are drawn.
label_pos : float (default=0.5)
Position of edge label along edge (0=head, 0.5=center, 1=tail)
font_size : int (default=10)
Font size for text labels
font_color : color (default='k' black)
Font color string. Color can be string or rgb (or rgba) tuple of
floats from 0-1.
font_weight : string (default='normal')
Font weight
font_family : string (default='sans-serif')
Font family
alpha : float or None (default=None)
The text transparency
bbox : Matplotlib bbox, optional
Specify text box properties (e.g. shape, color etc.) for edge labels.
Default is {boxstyle='round', ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}.
horizontalalignment : string (default='center')
Horizontal alignment {'center', 'right', 'left'}
verticalalignment : string (default='center')
Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
rotate : bool (default=True)
Rotate edge labels to lie parallel to edges
clip_on : bool (default=True)
Turn on clipping of edge labels at axis boundaries
node_size : scalar or array (default=300)
Size of nodes. If an array it must be the same length as nodelist.
nodelist : list, optional (default=G.nodes())
This provides the node order for the `node_size` array (if it is an array).
connectionstyle : string or iterable of strings (default="arc3")
Pass the connectionstyle parameter to create curved arc of rounding
radius rad. For example, connectionstyle='arc3,rad=0.2'.
See `matplotlib.patches.ConnectionStyle` and
`matplotlib.patches.FancyArrowPatch` for more info.
If Iterable, index indicates i'th edge key of MultiGraph
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
dict
`dict` of labels keyed by edge
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_nodes
draw_networkx_edges
draw_networkx_labels
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
class CurvedArrowText(mpl.text.Text):
def __init__(
self,
arrow,
*args,
label_pos=0.5,
labels_horizontal=False,
ax=None,
**kwargs,
):
# Bind to FancyArrowPatch
self.arrow = arrow
# how far along the text should be on the curve,
# 0 is at start, 1 is at end etc.
self.label_pos = label_pos
self.labels_horizontal = labels_horizontal
if ax is None:
ax = plt.gca()
self.ax = ax
self.x, self.y, self.angle = self._update_text_pos_angle(arrow)
# Create text object
super().__init__(self.x, self.y, *args, rotation=self.angle, **kwargs)
# Bind to axis
self.ax.add_artist(self)
def _get_arrow_path_disp(self, arrow):
"""
This is part of FancyArrowPatch._get_path_in_displaycoord
It omits the second part of the method where path is converted
to polygon based on width
The transform is taken from ax, not the object, as the object
has not been added yet, and doesn't have transform
"""
dpi_cor = arrow._dpi_cor
# trans_data = arrow.get_transform()
trans_data = self.ax.transData
if arrow._posA_posB is not None:
posA = arrow._convert_xy_units(arrow._posA_posB[0])
posB = arrow._convert_xy_units(arrow._posA_posB[1])
(posA, posB) = trans_data.transform((posA, posB))
_path = arrow.get_connectionstyle()(
posA,
posB,
patchA=arrow.patchA,
patchB=arrow.patchB,
shrinkA=arrow.shrinkA * dpi_cor,
shrinkB=arrow.shrinkB * dpi_cor,
)
else:
_path = trans_data.transform_path(arrow._path_original)
# Return is in display coordinates
return _path
def _update_text_pos_angle(self, arrow):
# Fractional label position
path_disp = self._get_arrow_path_disp(arrow)
(x1, y1), (cx, cy), (x2, y2) = path_disp.vertices
# Text position at a proportion t along the line in display coords
# default is 0.5 so text appears at the halfway point
t = self.label_pos
tt = 1 - t
x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
if self.labels_horizontal:
# Horizontal text labels
angle = 0
else:
# Labels parallel to curve
change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
angle = (np.arctan2(change_y, change_x) / (2 * np.pi)) * 360
# Text is "right way up"
if angle > 90:
angle -= 180
if angle < -90:
angle += 180
(x, y) = self.ax.transData.inverted().transform((x, y))
return x, y, angle
def draw(self, renderer):
# recalculate the text position and angle
self.x, self.y, self.angle = self._update_text_pos_angle(self.arrow)
self.set_position((self.x, self.y))
self.set_rotation(self.angle)
# redraw text
super().draw(renderer)
# use default box of white with white border
if bbox is None:
bbox = {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)}
if isinstance(connectionstyle, str):
connectionstyle = [connectionstyle]
elif np.iterable(connectionstyle):
connectionstyle = list(connectionstyle)
else:
raise nx.NetworkXError(
"draw_networkx_edges arg `connectionstyle` must be"
"string or iterable of strings"
)
if ax is None:
ax = plt.gca()
if edge_labels is None:
kwds = {"keys": True} if G.is_multigraph() else {}
edge_labels = {tuple(edge): d for *edge, d in G.edges(data=True, **kwds)}
# NOTHING TO PLOT
if not edge_labels:
return {}
edgelist, labels = zip(*edge_labels.items())
if nodelist is None:
nodelist = list(G.nodes())
# set edge positions
edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
if G.is_multigraph():
key_count = collections.defaultdict(lambda: itertools.count(0))
edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
else:
edge_indices = [0] * len(edgelist)
# Used to determine self loop mid-point
# Note, that this will not be accurate,
# if not drawing edge_labels for all edges drawn
h = 0
if edge_labels:
miny = np.amin(np.ravel(edge_pos[:, :, 1]))
maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
h = maxy - miny
selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
fancy_arrow_factory = FancyArrowFactory(
edge_pos,
edgelist,
nodelist,
edge_indices,
node_size,
selfloop_height,
connectionstyle,
ax=ax,
)
text_items = {}
for i, (edge, label) in enumerate(zip(edgelist, labels)):
if not isinstance(label, str):
label = str(label) # this makes "1" and 1 labeled the same
n1, n2 = edge[:2]
arrow = fancy_arrow_factory(i)
if n1 == n2:
connectionstyle_obj = arrow.get_connectionstyle()
posA = ax.transData.transform(pos[n1])
path_disp = connectionstyle_obj(posA, posA)
path_data = ax.transData.inverted().transform_path(path_disp)
x, y = path_data.vertices[0]
text_items[edge] = ax.text(
x,
y,
label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
alpha=alpha,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
rotation=0,
transform=ax.transData,
bbox=bbox,
zorder=1,
clip_on=clip_on,
)
else:
text_items[edge] = CurvedArrowText(
arrow,
label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
alpha=alpha,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
transform=ax.transData,
bbox=bbox,
zorder=1,
clip_on=clip_on,
label_pos=label_pos,
labels_horizontal=not rotate,
ax=ax,
)
if hide_ticks:
ax.tick_params(
axis="both",
which="both",
bottom=False,
left=False,
labelbottom=False,
labelleft=False,
)
return text_items
| (G, pos, edge_labels=None, label_pos=0.5, font_size=10, font_color='k', font_family='sans-serif', font_weight='normal', alpha=None, bbox=None, horizontalalignment='center', verticalalignment='center', ax=None, rotate=True, clip_on=True, node_size=300, nodelist=None, connectionstyle='arc3', hide_ticks=True) |
30,594 | networkx.drawing.nx_pylab | draw_networkx_edges | Draw the edges of the graph G.
This draws only the edges of the graph G.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
edgelist : collection of edge tuples (default=G.edges())
Draw only specified edges
width : float or array of floats (default=1.0)
Line width of edges
edge_color : color or array of colors (default='k')
Edge color. Can be a single color or a sequence of colors with the same
length as edgelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
style : string or array of strings (default='solid')
Edge line style e.g.: '-', '--', '-.', ':'
or words like 'solid' or 'dashed'.
Can be a single style or a sequence of styles with the same
length as the edge list.
If less styles than edges are given the styles will cycle.
If more styles than edges are given the styles will be used sequentially
and not be exhausted.
Also, `(offset, onoffseq)` tuples can be used as style instead of a strings.
(See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
alpha : float or array of floats (default=None)
The edge transparency. This can be a single alpha value,
in which case it will be applied to all specified edges. Otherwise,
if it is an array, the elements of alpha will be applied to the colors
in order (cycling through alpha multiple times if necessary).
edge_cmap : Matplotlib colormap, optional
Colormap for mapping intensities of edges
edge_vmin,edge_vmax : floats, optional
Minimum and maximum for edge colormap scaling
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
arrows : bool or None, optional (default=None)
If `None`, directed graphs draw arrowheads with
`~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
via `~matplotlib.collections.LineCollection` for speed.
If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
If `False`, draw edges using LineCollection (linear and fast).
Note: Arrowheads will be the same color as edges.
arrowstyle : str (default='-\|>' for directed graphs)
For directed graphs and `arrows==True` defaults to '-\|>',
For undirected graphs default to '-'.
See `matplotlib.patches.ArrowStyle` for more options.
arrowsize : int (default=10)
For directed graphs, choose the size of the arrow head's length and
width. See `matplotlib.patches.FancyArrowPatch` for attribute
`mutation_scale` for more info.
connectionstyle : string or iterable of strings (default="arc3")
Pass the connectionstyle parameter to create curved arc of rounding
radius rad. For example, connectionstyle='arc3,rad=0.2'.
See `matplotlib.patches.ConnectionStyle` and
`matplotlib.patches.FancyArrowPatch` for more info.
If Iterable, index indicates i'th edge key of MultiGraph
node_size : scalar or array (default=300)
Size of nodes. Though the nodes are not drawn with this function, the
node size is used in determining edge positioning.
nodelist : list, optional (default=G.nodes())
This provides the node order for the `node_size` array (if it is an array).
node_shape : string (default='o')
The marker used for nodes, used in determining edge positioning.
Specification is as a `matplotlib.markers` marker, e.g. one of 'so^>v<dph8'.
label : None or string
Label for legend
min_source_margin : int (default=0)
The minimum margin (gap) at the beginning of the edge at the source.
min_target_margin : int (default=0)
The minimum margin (gap) at the end of the edge at the target.
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
matplotlib.collections.LineCollection or a list of matplotlib.patches.FancyArrowPatch
If ``arrows=True``, a list of FancyArrowPatches is returned.
If ``arrows=False``, a LineCollection is returned.
If ``arrows=None`` (the default), then a LineCollection is returned if
`G` is undirected, otherwise returns a list of FancyArrowPatches.
Notes
-----
For directed graphs, arrows are drawn at the head end. Arrows can be
turned off with keyword arrows=False or by passing an arrowstyle without
an arrow on the end.
Be sure to include `node_size` as a keyword argument; arrows are
drawn considering the size of nodes.
Self-loops are always drawn with `~matplotlib.patches.FancyArrowPatch`
regardless of the value of `arrows` or whether `G` is directed.
When ``arrows=False`` or ``arrows=None`` and `G` is undirected, the
FancyArrowPatches corresponding to the self-loops are not explicitly
returned. They should instead be accessed via the ``Axes.patches``
attribute (see examples).
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
>>> G = nx.DiGraph()
>>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
>>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
>>> alphas = [0.3, 0.4, 0.5]
>>> for i, arc in enumerate(arcs): # change alpha values of arcs
... arc.set_alpha(alphas[i])
The FancyArrowPatches corresponding to self-loops are not always
returned, but can always be accessed via the ``patches`` attribute of the
`matplotlib.Axes` object.
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> G = nx.Graph([(0, 1), (0, 0)]) # Self-loop at node 0
>>> edge_collection = nx.draw_networkx_edges(G, pos=nx.circular_layout(G), ax=ax)
>>> self_loop_fap = ax.patches[0]
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_nodes
draw_networkx_labels
draw_networkx_edge_labels
| def draw_networkx_edges(
G,
pos,
edgelist=None,
width=1.0,
edge_color="k",
style="solid",
alpha=None,
arrowstyle=None,
arrowsize=10,
edge_cmap=None,
edge_vmin=None,
edge_vmax=None,
ax=None,
arrows=None,
label=None,
node_size=300,
nodelist=None,
node_shape="o",
connectionstyle="arc3",
min_source_margin=0,
min_target_margin=0,
hide_ticks=True,
):
r"""Draw the edges of the graph G.
This draws only the edges of the graph G.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
edgelist : collection of edge tuples (default=G.edges())
Draw only specified edges
width : float or array of floats (default=1.0)
Line width of edges
edge_color : color or array of colors (default='k')
Edge color. Can be a single color or a sequence of colors with the same
length as edgelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
style : string or array of strings (default='solid')
Edge line style e.g.: '-', '--', '-.', ':'
or words like 'solid' or 'dashed'.
Can be a single style or a sequence of styles with the same
length as the edge list.
If less styles than edges are given the styles will cycle.
If more styles than edges are given the styles will be used sequentially
and not be exhausted.
Also, `(offset, onoffseq)` tuples can be used as style instead of a strings.
(See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
alpha : float or array of floats (default=None)
The edge transparency. This can be a single alpha value,
in which case it will be applied to all specified edges. Otherwise,
if it is an array, the elements of alpha will be applied to the colors
in order (cycling through alpha multiple times if necessary).
edge_cmap : Matplotlib colormap, optional
Colormap for mapping intensities of edges
edge_vmin,edge_vmax : floats, optional
Minimum and maximum for edge colormap scaling
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
arrows : bool or None, optional (default=None)
If `None`, directed graphs draw arrowheads with
`~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
via `~matplotlib.collections.LineCollection` for speed.
If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
If `False`, draw edges using LineCollection (linear and fast).
Note: Arrowheads will be the same color as edges.
arrowstyle : str (default='-\|>' for directed graphs)
For directed graphs and `arrows==True` defaults to '-\|>',
For undirected graphs default to '-'.
See `matplotlib.patches.ArrowStyle` for more options.
arrowsize : int (default=10)
For directed graphs, choose the size of the arrow head's length and
width. See `matplotlib.patches.FancyArrowPatch` for attribute
`mutation_scale` for more info.
connectionstyle : string or iterable of strings (default="arc3")
Pass the connectionstyle parameter to create curved arc of rounding
radius rad. For example, connectionstyle='arc3,rad=0.2'.
See `matplotlib.patches.ConnectionStyle` and
`matplotlib.patches.FancyArrowPatch` for more info.
If Iterable, index indicates i'th edge key of MultiGraph
node_size : scalar or array (default=300)
Size of nodes. Though the nodes are not drawn with this function, the
node size is used in determining edge positioning.
nodelist : list, optional (default=G.nodes())
This provides the node order for the `node_size` array (if it is an array).
node_shape : string (default='o')
The marker used for nodes, used in determining edge positioning.
Specification is as a `matplotlib.markers` marker, e.g. one of 'so^>v<dph8'.
label : None or string
Label for legend
min_source_margin : int (default=0)
The minimum margin (gap) at the beginning of the edge at the source.
min_target_margin : int (default=0)
The minimum margin (gap) at the end of the edge at the target.
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
matplotlib.collections.LineCollection or a list of matplotlib.patches.FancyArrowPatch
If ``arrows=True``, a list of FancyArrowPatches is returned.
If ``arrows=False``, a LineCollection is returned.
If ``arrows=None`` (the default), then a LineCollection is returned if
`G` is undirected, otherwise returns a list of FancyArrowPatches.
Notes
-----
For directed graphs, arrows are drawn at the head end. Arrows can be
turned off with keyword arrows=False or by passing an arrowstyle without
an arrow on the end.
Be sure to include `node_size` as a keyword argument; arrows are
drawn considering the size of nodes.
Self-loops are always drawn with `~matplotlib.patches.FancyArrowPatch`
regardless of the value of `arrows` or whether `G` is directed.
When ``arrows=False`` or ``arrows=None`` and `G` is undirected, the
FancyArrowPatches corresponding to the self-loops are not explicitly
returned. They should instead be accessed via the ``Axes.patches``
attribute (see examples).
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
>>> G = nx.DiGraph()
>>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
>>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
>>> alphas = [0.3, 0.4, 0.5]
>>> for i, arc in enumerate(arcs): # change alpha values of arcs
... arc.set_alpha(alphas[i])
The FancyArrowPatches corresponding to self-loops are not always
returned, but can always be accessed via the ``patches`` attribute of the
`matplotlib.Axes` object.
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> G = nx.Graph([(0, 1), (0, 0)]) # Self-loop at node 0
>>> edge_collection = nx.draw_networkx_edges(G, pos=nx.circular_layout(G), ax=ax)
>>> self_loop_fap = ax.patches[0]
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_nodes
draw_networkx_labels
draw_networkx_edge_labels
"""
import warnings
import matplotlib as mpl
import matplotlib.collections # call as mpl.collections
import matplotlib.colors # call as mpl.colors
import matplotlib.pyplot as plt
import numpy as np
# The default behavior is to use LineCollection to draw edges for
# undirected graphs (for performance reasons) and use FancyArrowPatches
# for directed graphs.
# The `arrows` keyword can be used to override the default behavior
if arrows is None:
use_linecollection = not (G.is_directed() or G.is_multigraph())
else:
if not isinstance(arrows, bool):
raise TypeError("Argument `arrows` must be of type bool or None")
use_linecollection = not arrows
if isinstance(connectionstyle, str):
connectionstyle = [connectionstyle]
elif np.iterable(connectionstyle):
connectionstyle = list(connectionstyle)
else:
msg = "draw_networkx_edges arg `connectionstyle` must be str or iterable"
raise nx.NetworkXError(msg)
# Some kwargs only apply to FancyArrowPatches. Warn users when they use
# non-default values for these kwargs when LineCollection is being used
# instead of silently ignoring the specified option
if use_linecollection:
msg = (
"\n\nThe {0} keyword argument is not applicable when drawing edges\n"
"with LineCollection.\n\n"
"To make this warning go away, either specify `arrows=True` to\n"
"force FancyArrowPatches or use the default values.\n"
"Note that using FancyArrowPatches may be slow for large graphs.\n"
)
if arrowstyle is not None:
warnings.warn(msg.format("arrowstyle"), category=UserWarning, stacklevel=2)
if arrowsize != 10:
warnings.warn(msg.format("arrowsize"), category=UserWarning, stacklevel=2)
if min_source_margin != 0:
warnings.warn(
msg.format("min_source_margin"), category=UserWarning, stacklevel=2
)
if min_target_margin != 0:
warnings.warn(
msg.format("min_target_margin"), category=UserWarning, stacklevel=2
)
if any(cs != "arc3" for cs in connectionstyle):
warnings.warn(
msg.format("connectionstyle"), category=UserWarning, stacklevel=2
)
# NOTE: Arrowstyle modification must occur after the warnings section
if arrowstyle is None:
arrowstyle = "-|>" if G.is_directed() else "-"
if ax is None:
ax = plt.gca()
if edgelist is None:
edgelist = list(G.edges) # (u, v, k) for multigraph (u, v) otherwise
if len(edgelist):
if G.is_multigraph():
key_count = collections.defaultdict(lambda: itertools.count(0))
edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
else:
edge_indices = [0] * len(edgelist)
else: # no edges!
return []
if nodelist is None:
nodelist = list(G.nodes())
# FancyArrowPatch handles color=None different from LineCollection
if edge_color is None:
edge_color = "k"
# set edge positions
edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
# Check if edge_color is an array of floats and map to edge_cmap.
# This is the only case handled differently from matplotlib
if (
np.iterable(edge_color)
and (len(edge_color) == len(edge_pos))
and np.all([isinstance(c, Number) for c in edge_color])
):
if edge_cmap is not None:
assert isinstance(edge_cmap, mpl.colors.Colormap)
else:
edge_cmap = plt.get_cmap()
if edge_vmin is None:
edge_vmin = min(edge_color)
if edge_vmax is None:
edge_vmax = max(edge_color)
color_normal = mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax)
edge_color = [edge_cmap(color_normal(e)) for e in edge_color]
# compute initial view
minx = np.amin(np.ravel(edge_pos[:, :, 0]))
maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
miny = np.amin(np.ravel(edge_pos[:, :, 1]))
maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
w = maxx - minx
h = maxy - miny
# Self-loops are scaled by view extent, except in cases the extent
# is 0, e.g. for a single node. In this case, fall back to scaling
# by the maximum node size
selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
fancy_arrow_factory = FancyArrowFactory(
edge_pos,
edgelist,
nodelist,
edge_indices,
node_size,
selfloop_height,
connectionstyle,
node_shape,
arrowstyle,
arrowsize,
edge_color,
alpha,
width,
style,
min_source_margin,
min_target_margin,
ax=ax,
)
# Draw the edges
if use_linecollection:
edge_collection = mpl.collections.LineCollection(
edge_pos,
colors=edge_color,
linewidths=width,
antialiaseds=(1,),
linestyle=style,
alpha=alpha,
)
edge_collection.set_cmap(edge_cmap)
edge_collection.set_clim(edge_vmin, edge_vmax)
edge_collection.set_zorder(1) # edges go behind nodes
edge_collection.set_label(label)
ax.add_collection(edge_collection)
edge_viz_obj = edge_collection
# Make sure selfloop edges are also drawn
# ---------------------------------------
selfloops_to_draw = [loop for loop in nx.selfloop_edges(G) if loop in edgelist]
if selfloops_to_draw:
edgelist_tuple = list(map(tuple, edgelist))
arrow_collection = []
for loop in selfloops_to_draw:
i = edgelist_tuple.index(loop)
arrow = fancy_arrow_factory(i)
arrow_collection.append(arrow)
ax.add_patch(arrow)
else:
edge_viz_obj = []
for i in range(len(edgelist)):
arrow = fancy_arrow_factory(i)
ax.add_patch(arrow)
edge_viz_obj.append(arrow)
# update view after drawing
padx, pady = 0.05 * w, 0.05 * h
corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
ax.update_datalim(corners)
ax.autoscale_view()
if hide_ticks:
ax.tick_params(
axis="both",
which="both",
bottom=False,
left=False,
labelbottom=False,
labelleft=False,
)
return edge_viz_obj
| (G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=None, arrowstyle=None, arrowsize=10, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=None, label=None, node_size=300, nodelist=None, node_shape='o', connectionstyle='arc3', min_source_margin=0, min_target_margin=0, hide_ticks=True) |
30,595 | networkx.drawing.nx_pylab | draw_networkx_labels | Draw node labels on the graph G.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
labels : dictionary (default={n: n for n in G})
Node labels in a dictionary of text labels keyed by node.
Node-keys in labels should appear as keys in `pos`.
If needed use: `{n:lab for n,lab in labels.items() if n in pos}`
font_size : int (default=12)
Font size for text labels
font_color : color (default='k' black)
Font color string. Color can be string or rgb (or rgba) tuple of
floats from 0-1.
font_weight : string (default='normal')
Font weight
font_family : string (default='sans-serif')
Font family
alpha : float or None (default=None)
The text transparency
bbox : Matplotlib bbox, (default is Matplotlib's ax.text default)
Specify text box properties (e.g. shape, color etc.) for node labels.
horizontalalignment : string (default='center')
Horizontal alignment {'center', 'right', 'left'}
verticalalignment : string (default='center')
Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
clip_on : bool (default=True)
Turn on clipping of node labels at axis boundaries
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
dict
`dict` of labels keyed on the nodes
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_nodes
draw_networkx_edges
draw_networkx_edge_labels
| def draw_networkx_labels(
G,
pos,
labels=None,
font_size=12,
font_color="k",
font_family="sans-serif",
font_weight="normal",
alpha=None,
bbox=None,
horizontalalignment="center",
verticalalignment="center",
ax=None,
clip_on=True,
hide_ticks=True,
):
"""Draw node labels on the graph G.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
labels : dictionary (default={n: n for n in G})
Node labels in a dictionary of text labels keyed by node.
Node-keys in labels should appear as keys in `pos`.
If needed use: `{n:lab for n,lab in labels.items() if n in pos}`
font_size : int (default=12)
Font size for text labels
font_color : color (default='k' black)
Font color string. Color can be string or rgb (or rgba) tuple of
floats from 0-1.
font_weight : string (default='normal')
Font weight
font_family : string (default='sans-serif')
Font family
alpha : float or None (default=None)
The text transparency
bbox : Matplotlib bbox, (default is Matplotlib's ax.text default)
Specify text box properties (e.g. shape, color etc.) for node labels.
horizontalalignment : string (default='center')
Horizontal alignment {'center', 'right', 'left'}
verticalalignment : string (default='center')
Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
clip_on : bool (default=True)
Turn on clipping of node labels at axis boundaries
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
dict
`dict` of labels keyed on the nodes
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_nodes
draw_networkx_edges
draw_networkx_edge_labels
"""
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
if labels is None:
labels = {n: n for n in G.nodes()}
text_items = {} # there is no text collection so we'll fake one
for n, label in labels.items():
(x, y) = pos[n]
if not isinstance(label, str):
label = str(label) # this makes "1" and 1 labeled the same
t = ax.text(
x,
y,
label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
alpha=alpha,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
transform=ax.transData,
bbox=bbox,
clip_on=clip_on,
)
text_items[n] = t
if hide_ticks:
ax.tick_params(
axis="both",
which="both",
bottom=False,
left=False,
labelbottom=False,
labelleft=False,
)
return text_items
| (G, pos, labels=None, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=None, bbox=None, horizontalalignment='center', verticalalignment='center', ax=None, clip_on=True, hide_ticks=True) |
30,596 | networkx.drawing.nx_pylab | draw_networkx_nodes | Draw the nodes of the graph G.
This draws only the nodes of the graph G.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
nodelist : list (default list(G))
Draw only specified nodes
node_size : scalar or array (default=300)
Size of nodes. If an array it must be the same length as nodelist.
node_color : color or array of colors (default='#1f78b4')
Node color. Can be a single color or a sequence of colors with the same
length as nodelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the cmap and vmin,vmax parameters. See
matplotlib.scatter for more details.
node_shape : string (default='o')
The shape of the node. Specification is as matplotlib.scatter
marker, one of 'so^>v<dph8'.
alpha : float or array of floats (default=None)
The node transparency. This can be a single alpha value,
in which case it will be applied to all the nodes of color. Otherwise,
if it is an array, the elements of alpha will be applied to the colors
in order (cycling through alpha multiple times if necessary).
cmap : Matplotlib colormap (default=None)
Colormap for mapping intensities of nodes
vmin,vmax : floats or None (default=None)
Minimum and maximum for node colormap scaling
linewidths : [None | scalar | sequence] (default=1.0)
Line width of symbol border
edgecolors : [None | scalar | sequence] (default = node_color)
Colors of node borders. Can be a single color or a sequence of colors with the
same length as nodelist. Color can be string or rgb (or rgba) tuple of floats
from 0-1. If numeric values are specified they will be mapped to colors
using the cmap and vmin,vmax parameters. See `~matplotlib.pyplot.scatter` for more details.
label : [None | string]
Label for legend
margins : float or 2-tuple, optional
Sets the padding for axis autoscaling. Increase margin to prevent
clipping for nodes that are near the edges of an image. Values should
be in the range ``[0, 1]``. See :meth:`matplotlib.axes.Axes.margins`
for details. The default is `None`, which uses the Matplotlib default.
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
matplotlib.collections.PathCollection
`PathCollection` of the nodes.
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_edges
draw_networkx_labels
draw_networkx_edge_labels
| def draw_networkx_nodes(
G,
pos,
nodelist=None,
node_size=300,
node_color="#1f78b4",
node_shape="o",
alpha=None,
cmap=None,
vmin=None,
vmax=None,
ax=None,
linewidths=None,
edgecolors=None,
label=None,
margins=None,
hide_ticks=True,
):
"""Draw the nodes of the graph G.
This draws only the nodes of the graph G.
Parameters
----------
G : graph
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values.
Positions should be sequences of length 2.
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
nodelist : list (default list(G))
Draw only specified nodes
node_size : scalar or array (default=300)
Size of nodes. If an array it must be the same length as nodelist.
node_color : color or array of colors (default='#1f78b4')
Node color. Can be a single color or a sequence of colors with the same
length as nodelist. Color can be string or rgb (or rgba) tuple of
floats from 0-1. If numeric values are specified they will be
mapped to colors using the cmap and vmin,vmax parameters. See
matplotlib.scatter for more details.
node_shape : string (default='o')
The shape of the node. Specification is as matplotlib.scatter
marker, one of 'so^>v<dph8'.
alpha : float or array of floats (default=None)
The node transparency. This can be a single alpha value,
in which case it will be applied to all the nodes of color. Otherwise,
if it is an array, the elements of alpha will be applied to the colors
in order (cycling through alpha multiple times if necessary).
cmap : Matplotlib colormap (default=None)
Colormap for mapping intensities of nodes
vmin,vmax : floats or None (default=None)
Minimum and maximum for node colormap scaling
linewidths : [None | scalar | sequence] (default=1.0)
Line width of symbol border
edgecolors : [None | scalar | sequence] (default = node_color)
Colors of node borders. Can be a single color or a sequence of colors with the
same length as nodelist. Color can be string or rgb (or rgba) tuple of floats
from 0-1. If numeric values are specified they will be mapped to colors
using the cmap and vmin,vmax parameters. See `~matplotlib.pyplot.scatter` for more details.
label : [None | string]
Label for legend
margins : float or 2-tuple, optional
Sets the padding for axis autoscaling. Increase margin to prevent
clipping for nodes that are near the edges of an image. Values should
be in the range ``[0, 1]``. See :meth:`matplotlib.axes.Axes.margins`
for details. The default is `None`, which uses the Matplotlib default.
hide_ticks : bool, optional
Hide ticks of axes. When `True` (the default), ticks and ticklabels
are removed from the axes. To set ticks and tick labels to the pyplot default,
use ``hide_ticks=False``.
Returns
-------
matplotlib.collections.PathCollection
`PathCollection` of the nodes.
Examples
--------
>>> G = nx.dodecahedral_graph()
>>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
Also see the NetworkX drawing examples at
https://networkx.org/documentation/latest/auto_examples/index.html
See Also
--------
draw
draw_networkx
draw_networkx_edges
draw_networkx_labels
draw_networkx_edge_labels
"""
from collections.abc import Iterable
import matplotlib as mpl
import matplotlib.collections # call as mpl.collections
import matplotlib.pyplot as plt
import numpy as np
if ax is None:
ax = plt.gca()
if nodelist is None:
nodelist = list(G)
if len(nodelist) == 0: # empty nodelist, no drawing
return mpl.collections.PathCollection(None)
try:
xy = np.asarray([pos[v] for v in nodelist])
except KeyError as err:
raise nx.NetworkXError(f"Node {err} has no position.") from err
if isinstance(alpha, Iterable):
node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax)
alpha = None
node_collection = ax.scatter(
xy[:, 0],
xy[:, 1],
s=node_size,
c=node_color,
marker=node_shape,
cmap=cmap,
vmin=vmin,
vmax=vmax,
alpha=alpha,
linewidths=linewidths,
edgecolors=edgecolors,
label=label,
)
if hide_ticks:
ax.tick_params(
axis="both",
which="both",
bottom=False,
left=False,
labelbottom=False,
labelleft=False,
)
if margins is not None:
if isinstance(margins, Iterable):
ax.margins(*margins)
else:
ax.margins(margins)
node_collection.set_zorder(2)
return node_collection
| (G, pos, nodelist=None, node_size=300, node_color='#1f78b4', node_shape='o', alpha=None, cmap=None, vmin=None, vmax=None, ax=None, linewidths=None, edgecolors=None, label=None, margins=None, hide_ticks=True) |
30,597 | networkx.drawing.nx_pylab | draw_planar | Draw a planar networkx graph `G` with planar layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.planar_layout(G), **kwargs)
Parameters
----------
G : graph
A planar networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Raises
------
NetworkXException
When `G` is not planar
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.planar_layout` directly and reuse the result::
>>> G = nx.path_graph(5)
>>> pos = nx.planar_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.draw_planar(G)
See Also
--------
:func:`~networkx.drawing.layout.planar_layout`
| def draw_planar(G, **kwargs):
"""Draw a planar networkx graph `G` with planar layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.planar_layout(G), **kwargs)
Parameters
----------
G : graph
A planar networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Raises
------
NetworkXException
When `G` is not planar
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.planar_layout` directly and reuse the result::
>>> G = nx.path_graph(5)
>>> pos = nx.planar_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.draw_planar(G)
See Also
--------
:func:`~networkx.drawing.layout.planar_layout`
"""
draw(G, planar_layout(G), **kwargs)
| (G, **kwargs) |
30,598 | networkx.drawing.nx_pylab | draw_random | Draw the graph `G` with a random layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.random_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.random_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.random_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.lollipop_graph(4, 3)
>>> nx.draw_random(G)
See Also
--------
:func:`~networkx.drawing.layout.random_layout`
| def draw_random(G, **kwargs):
"""Draw the graph `G` with a random layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.random_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.random_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.random_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.lollipop_graph(4, 3)
>>> nx.draw_random(G)
See Also
--------
:func:`~networkx.drawing.layout.random_layout`
"""
draw(G, random_layout(G), **kwargs)
| (G, **kwargs) |
30,599 | networkx.drawing.nx_pylab | draw_shell | Draw networkx graph `G` with shell layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
Parameters
----------
G : graph
A networkx graph
nlist : list of list of nodes, optional
A list containing lists of nodes representing the shells.
Default is `None`, meaning all nodes are in a single shell.
See `~networkx.drawing.layout.shell_layout` for details.
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.shell_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.shell_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(4)
>>> shells = [[0], [1, 2, 3]]
>>> nx.draw_shell(G, nlist=shells)
See Also
--------
:func:`~networkx.drawing.layout.shell_layout`
| def draw_shell(G, nlist=None, **kwargs):
"""Draw networkx graph `G` with shell layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
Parameters
----------
G : graph
A networkx graph
nlist : list of list of nodes, optional
A list containing lists of nodes representing the shells.
Default is `None`, meaning all nodes are in a single shell.
See `~networkx.drawing.layout.shell_layout` for details.
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.shell_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.shell_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(4)
>>> shells = [[0], [1, 2, 3]]
>>> nx.draw_shell(G, nlist=shells)
See Also
--------
:func:`~networkx.drawing.layout.shell_layout`
"""
draw(G, shell_layout(G, nlist=nlist), **kwargs)
| (G, nlist=None, **kwargs) |
30,600 | networkx.drawing.nx_pylab | draw_spectral | Draw the graph `G` with a spectral 2D layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.spectral_layout(G), **kwargs)
For more information about how node positions are determined, see
`~networkx.drawing.layout.spectral_layout`.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.spectral_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.spectral_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.draw_spectral(G)
See Also
--------
:func:`~networkx.drawing.layout.spectral_layout`
| def draw_spectral(G, **kwargs):
"""Draw the graph `G` with a spectral 2D layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.spectral_layout(G), **kwargs)
For more information about how node positions are determined, see
`~networkx.drawing.layout.spectral_layout`.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.spectral_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.spectral_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(5)
>>> nx.draw_spectral(G)
See Also
--------
:func:`~networkx.drawing.layout.spectral_layout`
"""
draw(G, spectral_layout(G), **kwargs)
| (G, **kwargs) |
30,601 | networkx.drawing.nx_pylab | draw_spring | Draw the graph `G` with a spring layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.spring_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
`~networkx.drawing.layout.spring_layout` is also the default layout for
`draw`, so this function is equivalent to `draw`.
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.spring_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.spring_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(20)
>>> nx.draw_spring(G)
See Also
--------
draw
:func:`~networkx.drawing.layout.spring_layout`
| def draw_spring(G, **kwargs):
"""Draw the graph `G` with a spring layout.
This is a convenience function equivalent to::
nx.draw(G, pos=nx.spring_layout(G), **kwargs)
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See `draw_networkx` for a description of optional keywords.
Notes
-----
`~networkx.drawing.layout.spring_layout` is also the default layout for
`draw`, so this function is equivalent to `draw`.
The layout is computed each time this function is called.
For repeated drawing it is much more efficient to call
`~networkx.drawing.layout.spring_layout` directly and reuse the result::
>>> G = nx.complete_graph(5)
>>> pos = nx.spring_layout(G)
>>> nx.draw(G, pos=pos) # Draw the original graph
>>> # Draw a subgraph, reusing the same node positions
>>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
Examples
--------
>>> G = nx.path_graph(20)
>>> nx.draw_spring(G)
See Also
--------
draw
:func:`~networkx.drawing.layout.spring_layout`
"""
draw(G, spring_layout(G), **kwargs)
| (G, **kwargs) |
30,603 | networkx.generators.random_graphs | dual_barabasi_albert_graph | 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.
| 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, m1, m2, p, seed=None, initial_graph=None, *, backend=None, **backend_kwargs) |
30,605 | networkx.generators.duplication | duplication_divergence_graph | Returns an undirected graph using the duplication-divergence model.
A graph of `n` nodes is created by duplicating the initial nodes
and retaining edges incident to the original nodes with a retention
probability `p`.
Parameters
----------
n : int
The desired number of nodes in the graph.
p : float
The probability for retaining the edge of the replicated node.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `p` is not a valid probability.
If `n` is less than 2.
Notes
-----
This algorithm appears in [1].
This implementation disallows the possibility of generating
disconnected graphs.
References
----------
.. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
"Duplication-divergence model of protein interaction network",
Phys. Rev. E, 71, 061911, 2005.
| null | (n, p, seed=None, *, backend=None, **backend_kwargs) |
30,606 | networkx.algorithms.distance_measures | eccentricity | Returns the eccentricity of nodes in G.
The eccentricity of a node v is the maximum distance from v to
all other nodes in G.
Parameters
----------
G : NetworkX graph
A graph
v : node, optional
Return value of specified node
sp : dict of dicts, optional
All pairs shortest path lengths as a dictionary of dictionaries
weight : string, function, or None (default=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
-------
ecc : dictionary
A dictionary of eccentricity values keyed by node.
Examples
--------
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
>>> dict(nx.eccentricity(G))
{1: 2, 2: 3, 3: 2, 4: 2, 5: 3}
>>> dict(nx.eccentricity(G, v=[1, 5])) # This returns the eccentricity of node 1 & 5
{1: 2, 5: 3}
| 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, v=None, sp=None, weight=None, *, backend=None, **backend_kwargs) |
30,607 | networkx.algorithms.centrality.betweenness | edge_betweenness_centrality | Compute betweenness centrality for edges.
Betweenness centrality of an edge $e$ is the sum of the
fraction of all-pairs shortest paths that pass through $e$
.. math::
c_B(e) =\sum_{s,t \in V} \frac{\sigma(s, t|e)}{\sigma(s, t)}
where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
shortest $(s, t)$-paths, and $\sigma(s, t|e)$ is the number of
those paths passing through edge $e$ [2]_.
Parameters
----------
G : graph
A NetworkX graph.
k : int, optional (default=None)
If k is not None use k node samples to estimate betweenness.
The value of k <= n where n is the number of nodes in the graph.
Higher values give better approximation.
normalized : bool, optional
If True the betweenness values are normalized by $2/(n(n-1))$
for graphs, and $1/(n(n-1))$ for directed graphs where $n$
is the number of nodes in G.
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.
Weights are used to calculate weighted shortest paths, so they are
interpreted as distances.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Note that this is only used if k is not None.
Returns
-------
edges : dictionary
Dictionary of edges with betweenness centrality as the value.
See Also
--------
betweenness_centrality
edge_load
Notes
-----
The algorithm is from Ulrik Brandes [1]_.
For weighted graphs the edge weights must be greater than zero.
Zero edge weights can produce an infinite number of equal length
paths between pairs of nodes.
References
----------
.. [1] A Faster Algorithm for Betweenness Centrality. Ulrik Brandes,
Journal of Mathematical Sociology 25(2):163-177, 2001.
https://doi.org/10.1080/0022250X.2001.9990249
.. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
Centrality and their Generic Computation.
Social Networks 30(2):136-145, 2008.
https://doi.org/10.1016/j.socnet.2007.11.001
| null | (G, k=None, normalized=True, weight=None, seed=None, *, backend=None, **backend_kwargs) |
30,608 | networkx.algorithms.centrality.betweenness_subset | edge_betweenness_centrality_subset | Compute betweenness centrality for edges for a subset of nodes.
.. math::
c_B(v) =\sum_{s\in S,t \in T} \frac{\sigma(s, t|e)}{\sigma(s, t)}
where $S$ is the set of sources, $T$ is the set of targets,
$\sigma(s, t)$ is the number of shortest $(s, t)$-paths,
and $\sigma(s, t|e)$ is the number of those paths
passing through edge $e$ [2]_.
Parameters
----------
G : graph
A networkx graph.
sources: list of nodes
Nodes to use as sources for shortest paths in betweenness
targets: list of nodes
Nodes to use as targets for shortest paths in betweenness
normalized : bool, optional
If True the betweenness values are normalized by `2/(n(n-1))`
for graphs, and `1/(n(n-1))` for directed graphs where `n`
is the number of nodes in G.
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.
Weights are used to calculate weighted shortest paths, so they are
interpreted as distances.
Returns
-------
edges : dictionary
Dictionary of edges with Betweenness centrality as the value.
See Also
--------
betweenness_centrality
edge_load
Notes
-----
The basic algorithm is from [1]_.
For weighted graphs the edge weights must be greater than zero.
Zero edge weights can produce an infinite number of equal length
paths between pairs of nodes.
The normalization might seem a little strange but it is the same
as in edge_betweenness_centrality() and is designed to make
edge_betweenness_centrality(G) be the same as
edge_betweenness_centrality_subset(G,sources=G.nodes(),targets=G.nodes()).
References
----------
.. [1] Ulrik Brandes, A Faster Algorithm for Betweenness Centrality.
Journal of Mathematical Sociology 25(2):163-177, 2001.
https://doi.org/10.1080/0022250X.2001.9990249
.. [2] Ulrik Brandes: On Variants of Shortest-Path Betweenness
Centrality and their Generic Computation.
Social Networks 30(2):136-145, 2008.
https://doi.org/10.1016/j.socnet.2007.11.001
| null | (G, sources, targets, normalized=False, weight=None, *, backend=None, **backend_kwargs) |
30,609 | networkx.algorithms.traversal.edgebfs | edge_bfs | A directed, breadth-first-search of edges in `G`, beginning at `source`.
Yield the edges of G in a breadth-first-search order continuing until
all edges are generated.
Parameters
----------
G : graph
A directed/undirected graph/multigraph.
source : node, list of nodes
The node from which the traversal begins. If None, then a source
is chosen arbitrarily and repeatedly until all edges from each node in
the graph are searched.
orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
For directed graphs and directed multigraphs, edge traversals need not
respect the original orientation of the edges.
When set to 'reverse' every edge is traversed in the reverse direction.
When set to 'ignore', every edge is treated as undirected.
When set to 'original', every edge is treated as directed.
In all three cases, the yielded edge tuples add a last entry to
indicate the direction in which that edge was traversed.
If orientation is None, the yielded edge has no direction indicated.
The direction is respected, but not reported.
Yields
------
edge : directed edge
A directed edge indicating the path taken by the breadth-first-search.
For graphs, `edge` is of the form `(u, v)` where `u` and `v`
are the tail and head of the edge as determined by the traversal.
For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
the key of the edge. When the graph is directed, then `u` and `v`
are always in the order of the actual directed edge.
If orientation is not None then the edge tuple is extended to include
the direction of traversal ('forward' or 'reverse') on that edge.
Examples
--------
>>> nodes = [0, 1, 2, 3]
>>> edges = [(0, 1), (1, 0), (1, 0), (2, 0), (2, 1), (3, 1)]
>>> list(nx.edge_bfs(nx.Graph(edges), nodes))
[(0, 1), (0, 2), (1, 2), (1, 3)]
>>> list(nx.edge_bfs(nx.DiGraph(edges), nodes))
[(0, 1), (1, 0), (2, 0), (2, 1), (3, 1)]
>>> list(nx.edge_bfs(nx.MultiGraph(edges), nodes))
[(0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (1, 2, 0), (1, 3, 0)]
>>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes))
[(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 0, 0), (2, 1, 0), (3, 1, 0)]
>>> list(nx.edge_bfs(nx.DiGraph(edges), nodes, orientation="ignore"))
[(0, 1, 'forward'), (1, 0, 'reverse'), (2, 0, 'reverse'), (2, 1, 'reverse'), (3, 1, 'reverse')]
>>> list(nx.edge_bfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
[(0, 1, 0, 'forward'), (1, 0, 0, 'reverse'), (1, 0, 1, 'reverse'), (2, 0, 0, 'reverse'), (2, 1, 0, 'reverse'), (3, 1, 0, 'reverse')]
Notes
-----
The goal of this function is to visit edges. It differs from the more
familiar breadth-first-search of nodes, as provided by
:func:`networkx.algorithms.traversal.breadth_first_search.bfs_edges`, in
that it does not stop once every node has been visited. In a directed graph
with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
if not for the functionality provided by this function.
The naming of this function is very similar to bfs_edges. The difference
is that 'edge_bfs' yields edges even if they extend back to an already
explored node while 'bfs_edges' 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 report 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.
See Also
--------
bfs_edges
bfs_tree
edge_dfs
| null | (G, source=None, orientation=None, *, backend=None, **backend_kwargs) |
30,610 | networkx.algorithms.boundary | edge_boundary | Returns the edge boundary of `nbunch1`.
The *edge boundary* of a set *S* with respect to a set *T* is the
set of edges (*u*, *v*) such that *u* is in *S* and *v* is in *T*.
If *T* is not specified, it is assumed to be the set of all nodes
not in *S*.
Parameters
----------
G : NetworkX graph
nbunch1 : iterable
Iterable of nodes in the graph representing the set of nodes
whose edge boundary will be returned. (This is the set *S* from
the definition above.)
nbunch2 : iterable
Iterable of nodes representing the target (or "exterior") set of
nodes. (This is the set *T* from the definition above.) If not
specified, this is assumed to be the set of all nodes in `G`
not in `nbunch1`.
keys : bool
This parameter has the same meaning as in
:meth:`MultiGraph.edges`.
data : bool or object
This parameter has the same meaning as in
:meth:`MultiGraph.edges`.
default : object
This parameter has the same meaning as in
:meth:`MultiGraph.edges`.
Returns
-------
iterator
An iterator over the edges in the boundary of `nbunch1` with
respect to `nbunch2`. If `keys`, `data`, or `default`
are specified and `G` is a multigraph, then edges are returned
with keys and/or data, as in :meth:`MultiGraph.edges`.
Examples
--------
>>> G = nx.wheel_graph(6)
When nbunch2=None:
>>> list(nx.edge_boundary(G, (1, 3)))
[(1, 0), (1, 2), (1, 5), (3, 0), (3, 2), (3, 4)]
When nbunch2 is given:
>>> list(nx.edge_boundary(G, (1, 3), (2, 0)))
[(1, 0), (1, 2), (3, 0), (3, 2)]
Notes
-----
Any element of `nbunch` that is not in the graph `G` will be
ignored.
`nbunch1` and `nbunch2` are usually meant to be disjoint, but in
the interest of speed and generality, that is not required here.
| null | (G, nbunch1, nbunch2=None, data=False, keys=False, default=None, *, backend=None, **backend_kwargs) |
30,611 | networkx.algorithms.connectivity.connectivity | edge_connectivity | Returns the edge connectivity of the graph or digraph G.
The edge connectivity is equal to the minimum number of edges that
must be removed to disconnect G or render it trivial. If source
and target nodes are provided, this function returns the local edge
connectivity: the minimum number of edges that must be removed to
break all paths from source to target in G.
Parameters
----------
G : NetworkX graph
Undirected or directed graph
s : node
Source node. Optional. Default value: None.
t : node
Target node. Optional. Default value: None.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. See below for details. The
choice of the default function may change from version
to version and should not be relied on. Default value: None.
cutoff : integer, float, or None (default: None)
If specified, the maximum flow algorithm will terminate when the
flow value reaches or exceeds the cutoff. This only works for flows
that support the cutoff parameter (most do) and is ignored otherwise.
Returns
-------
K : integer
Edge connectivity for G, or local edge connectivity if source
and target were provided
Examples
--------
>>> # Platonic icosahedral graph is 5-edge-connected
>>> G = nx.icosahedral_graph()
>>> nx.edge_connectivity(G)
5
You can use alternative flow algorithms for the underlying
maximum flow computation. In dense networks the algorithm
:meth:`shortest_augmenting_path` will usually perform better
than the default :meth:`edmonds_karp`, which is faster for
sparse networks with highly skewed degree distributions.
Alternative flow functions have to be explicitly imported
from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
5
If you specify a pair of nodes (source and target) as parameters,
this function returns the value of local edge connectivity.
>>> nx.edge_connectivity(G, 3, 7)
5
If you need to perform several local computations among different
pairs of nodes on the same graph, it is recommended that you reuse
the data structures used in the maximum flow computations. See
:meth:`local_edge_connectivity` for details.
Notes
-----
This is a flow based implementation of global edge connectivity.
For undirected graphs the algorithm works by finding a 'small'
dominating set of nodes of G (see algorithm 7 in [1]_ ) and
computing local maximum flow (see :meth:`local_edge_connectivity`)
between an arbitrary node in the dominating set and the rest of
nodes in it. This is an implementation of algorithm 6 in [1]_ .
For directed graphs, the algorithm does n calls to the maximum
flow function. This is an implementation of algorithm 8 in [1]_ .
See also
--------
:meth:`local_edge_connectivity`
:meth:`local_node_connectivity`
:meth:`node_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
:meth:`k_edge_components`
:meth:`k_edge_subgraphs`
References
----------
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
| @nx._dispatchable
def edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None):
r"""Returns the edge connectivity of the graph or digraph G.
The edge connectivity is equal to the minimum number of edges that
must be removed to disconnect G or render it trivial. If source
and target nodes are provided, this function returns the local edge
connectivity: the minimum number of edges that must be removed to
break all paths from source to target in G.
Parameters
----------
G : NetworkX graph
Undirected or directed graph
s : node
Source node. Optional. Default value: None.
t : node
Target node. Optional. Default value: None.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. See below for details. The
choice of the default function may change from version
to version and should not be relied on. Default value: None.
cutoff : integer, float, or None (default: None)
If specified, the maximum flow algorithm will terminate when the
flow value reaches or exceeds the cutoff. This only works for flows
that support the cutoff parameter (most do) and is ignored otherwise.
Returns
-------
K : integer
Edge connectivity for G, or local edge connectivity if source
and target were provided
Examples
--------
>>> # Platonic icosahedral graph is 5-edge-connected
>>> G = nx.icosahedral_graph()
>>> nx.edge_connectivity(G)
5
You can use alternative flow algorithms for the underlying
maximum flow computation. In dense networks the algorithm
:meth:`shortest_augmenting_path` will usually perform better
than the default :meth:`edmonds_karp`, which is faster for
sparse networks with highly skewed degree distributions.
Alternative flow functions have to be explicitly imported
from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
5
If you specify a pair of nodes (source and target) as parameters,
this function returns the value of local edge connectivity.
>>> nx.edge_connectivity(G, 3, 7)
5
If you need to perform several local computations among different
pairs of nodes on the same graph, it is recommended that you reuse
the data structures used in the maximum flow computations. See
:meth:`local_edge_connectivity` for details.
Notes
-----
This is a flow based implementation of global edge connectivity.
For undirected graphs the algorithm works by finding a 'small'
dominating set of nodes of G (see algorithm 7 in [1]_ ) and
computing local maximum flow (see :meth:`local_edge_connectivity`)
between an arbitrary node in the dominating set and the rest of
nodes in it. This is an implementation of algorithm 6 in [1]_ .
For directed graphs, the algorithm does n calls to the maximum
flow function. This is an implementation of algorithm 8 in [1]_ .
See also
--------
:meth:`local_edge_connectivity`
:meth:`local_node_connectivity`
:meth:`node_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
:meth:`k_edge_components`
:meth:`k_edge_subgraphs`
References
----------
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
"""
if (s is not None and t is None) or (s is None and t is not None):
raise nx.NetworkXError("Both source and target must be specified.")
# Local edge connectivity
if s is not None and t is not None:
if s not in G:
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError(f"node {t} not in graph")
return local_edge_connectivity(G, s, t, flow_func=flow_func, cutoff=cutoff)
# Global edge connectivity
# reuse auxiliary digraph and residual network
H = build_auxiliary_edge_connectivity(G)
R = build_residual_network(H, "capacity")
kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
if G.is_directed():
# Algorithm 8 in [1]
if not nx.is_weakly_connected(G):
return 0
# initial value for \lambda is minimum degree
L = min(d for n, d in G.degree())
nodes = list(G)
n = len(nodes)
if cutoff is not None:
L = min(cutoff, L)
for i in range(n):
kwargs["cutoff"] = L
try:
L = min(L, local_edge_connectivity(G, nodes[i], nodes[i + 1], **kwargs))
except IndexError: # last node!
L = min(L, local_edge_connectivity(G, nodes[i], nodes[0], **kwargs))
return L
else: # undirected
# Algorithm 6 in [1]
if not nx.is_connected(G):
return 0
# initial value for \lambda is minimum degree
L = min(d for n, d in G.degree())
if cutoff is not None:
L = min(cutoff, L)
# A dominating set is \lambda-covering
# We need a dominating set with at least two nodes
for node in G:
D = nx.dominating_set(G, start_with=node)
v = D.pop()
if D:
break
else:
# in complete graphs the dominating sets will always be of one node
# thus we return min degree
return L
for w in D:
kwargs["cutoff"] = L
L = min(L, local_edge_connectivity(G, v, w, **kwargs))
return L
| (G, s=None, t=None, flow_func=None, cutoff=None, *, backend=None, **backend_kwargs) |
30,612 | networkx.algorithms.centrality.current_flow_betweenness | edge_current_flow_betweenness_centrality | Compute current-flow betweenness centrality for edges.
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 (default=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 edge tuples with betweenness centrality as the value.
Raises
------
NetworkXError
The algorithm does not support DiGraphs.
If the input graph is an instance of DiGraph class, NetworkXError
is raised.
See Also
--------
betweenness_centrality
edge_betweenness_centrality
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,613 | networkx.algorithms.centrality.current_flow_betweenness_subset | edge_current_flow_betweenness_centrality_subset | Compute current-flow betweenness centrality for edges using 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 : dict
Dictionary of edge tuples with betweenness centrality as the value.
See Also
--------
betweenness_centrality
edge_betweenness_centrality
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,614 | networkx.algorithms.traversal.edgedfs | edge_dfs | A directed, depth-first-search of edges in `G`, beginning at `source`.
Yield the edges of G in a depth-first-search order continuing until
all edges are generated.
Parameters
----------
G : graph
A directed/undirected graph/multigraph.
source : node, list of nodes
The node from which the traversal begins. If None, then a source
is chosen arbitrarily and repeatedly until all edges from each node in
the graph are searched.
orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
For directed graphs and directed multigraphs, edge traversals need not
respect the original orientation of the edges.
When set to 'reverse' every edge is traversed in the reverse direction.
When set to 'ignore', every edge is treated as undirected.
When set to 'original', every edge is treated as directed.
In all three cases, the yielded edge tuples add a last entry to
indicate the direction in which that edge was traversed.
If orientation is None, the yielded edge has no direction indicated.
The direction is respected, but not reported.
Yields
------
edge : directed edge
A directed edge indicating the path taken by the depth-first traversal.
For graphs, `edge` is of the form `(u, v)` where `u` and `v`
are the tail and head of the edge as determined by the traversal.
For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
the key of the edge. When the graph is directed, then `u` and `v`
are always in the order of the actual directed edge.
If orientation is not None then the edge tuple is extended to include
the direction of traversal ('forward' or 'reverse') on that edge.
Examples
--------
>>> nodes = [0, 1, 2, 3]
>>> edges = [(0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
>>> list(nx.edge_dfs(nx.Graph(edges), nodes))
[(0, 1), (1, 2), (1, 3)]
>>> list(nx.edge_dfs(nx.DiGraph(edges), nodes))
[(0, 1), (1, 0), (2, 1), (3, 1)]
>>> list(nx.edge_dfs(nx.MultiGraph(edges), nodes))
[(0, 1, 0), (1, 0, 1), (0, 1, 2), (1, 2, 0), (1, 3, 0)]
>>> list(nx.edge_dfs(nx.MultiDiGraph(edges), nodes))
[(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 1, 0), (3, 1, 0)]
>>> list(nx.edge_dfs(nx.DiGraph(edges), nodes, orientation="ignore"))
[(0, 1, 'forward'), (1, 0, 'forward'), (2, 1, 'reverse'), (3, 1, 'reverse')]
>>> list(nx.edge_dfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
[(0, 1, 0, 'forward'), (1, 0, 0, 'forward'), (1, 0, 1, 'reverse'), (2, 1, 0, 'reverse'), (3, 1, 0, 'reverse')]
Notes
-----
The goal of this function is to visit edges. It differs from the more
familiar depth-first traversal of nodes, as provided by
:func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`, in
that it does not stop once every node has been visited. In a directed graph
with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
if not for the functionality provided by this function.
See Also
--------
:func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`
| null | (G, source=None, orientation=None, *, backend=None, **backend_kwargs) |
30,615 | networkx.algorithms.connectivity.disjoint_paths | edge_disjoint_paths | Returns the edges disjoint paths between source and target.
Edge disjoint paths are paths that do not share any edge. The
number of edge disjoint paths between source and target is equal
to their edge connectivity.
Parameters
----------
G : NetworkX graph
s : node
Source node for the flow.
t : node
Sink node for the flow.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. The choice of the default function
may change from version to version and should not be relied on.
Default value: None.
cutoff : integer or None (default: None)
Maximum number of paths to yield. If specified, the maximum flow
algorithm will terminate when the flow value reaches or exceeds the
cutoff. This only works for flows that support the cutoff parameter
(most do) and is ignored otherwise.
auxiliary : NetworkX DiGraph
Auxiliary digraph to compute flow based edge connectivity. It has
to have a graph attribute called mapping with a dictionary mapping
node names in G and in the auxiliary digraph. If provided
it will be reused instead of recreated. Default value: None.
residual : NetworkX DiGraph
Residual network to compute maximum flow. If provided it will be
reused instead of recreated. Default value: None.
Returns
-------
paths : generator
A generator of edge independent paths.
Raises
------
NetworkXNoPath
If there is no path between source and target.
NetworkXError
If source or target are not in the graph G.
See also
--------
:meth:`node_disjoint_paths`
:meth:`edge_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
Examples
--------
We use in this example the platonic icosahedral graph, which has node
edge connectivity 5, thus there are 5 edge disjoint paths between any
pair of nodes.
>>> G = nx.icosahedral_graph()
>>> len(list(nx.edge_disjoint_paths(G, 0, 6)))
5
If you need to compute edge disjoint paths on several pairs of
nodes in the same graph, it is recommended that you reuse the
data structures that NetworkX uses in the computation: the
auxiliary digraph for edge connectivity, and the residual
network for the underlying maximum flow computation.
Example of how to compute edge disjoint paths among all pairs of
nodes of the platonic icosahedral graph reusing the data
structures.
>>> import itertools
>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from networkx.algorithms.connectivity import build_auxiliary_edge_connectivity
>>> H = build_auxiliary_edge_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from networkx.algorithms.flow import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> result = {n: {} for n in G}
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as arguments
>>> for u, v in itertools.combinations(G, 2):
... k = len(list(nx.edge_disjoint_paths(G, u, v, auxiliary=H, residual=R)))
... result[u][v] = k
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
True
You can also use alternative flow algorithms for computing edge disjoint
paths. For instance, in dense networks the algorithm
:meth:`shortest_augmenting_path` will usually perform better than
the default :meth:`edmonds_karp` which is faster for sparse
networks with highly skewed degree distributions. Alternative flow
functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> len(list(nx.edge_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
5
Notes
-----
This is a flow based implementation of edge disjoint paths. We compute
the maximum flow between source and target on an auxiliary directed
network. The saturated edges in the residual network after running the
maximum flow algorithm correspond to edge disjoint paths between source
and target in the original network. This function handles both directed
and undirected graphs, and can use all flow algorithms from NetworkX flow
package.
| null | (G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None, *, backend=None, **backend_kwargs) |
30,616 | networkx.algorithms.cuts | edge_expansion | Returns the edge expansion between two node sets.
The *edge expansion* is the quotient of the cut size and the smaller
of the cardinalities 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 edge expansion between the two sets `S` and `T`.
See also
--------
boundary_expansion
mixing_expansion
node_expansion
References
----------
.. [1] Fan Chung.
*Spectral Graph Theory*.
(CBMS Regional Conference Series in Mathematics, No. 92),
American Mathematical Society, 1997, ISBN 0-8218-0315-8
<http://www.math.ucsd.edu/~fan/research/revised.html>
| null | (G, S, T=None, weight=None, *, backend=None, **backend_kwargs) |
30,617 | networkx.algorithms.centrality.load | edge_load_centrality | Compute edge load.
WARNING: This concept of edge load has not been analysed
or discussed outside of NetworkX that we know of.
It is based loosely on load_centrality in the sense that
it counts the number of shortest paths which cross each edge.
This function is for demonstration and testing purposes.
Parameters
----------
G : graph
A networkx graph
cutoff : bool, optional (default=False)
If specified, only consider paths of length <= cutoff.
Returns
-------
A dict keyed by edge 2-tuple to the number of shortest paths
which use that edge. Where more than one path is shortest
the count is divided equally among paths.
| null | (G, cutoff=False, *, backend=None, **backend_kwargs) |
30,618 | networkx.classes.function | edge_subgraph | Returns a view of the subgraph induced by the specified edges.
The induced subgraph contains each edge in `edges` and each
node incident to any of those edges.
Parameters
----------
G : NetworkX Graph
edges : iterable
An iterable of edges. Edges not present in `G` are ignored.
Returns
-------
subgraph : SubGraph View
A read-only edge-induced subgraph of `G`.
Changes to `G` are reflected in the view.
Notes
-----
To create a mutable subgraph with its own copies of nodes
edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
If you create a subgraph of a subgraph recursively you can end up
with a chain of subgraphs that becomes very slow with about 15
nested subgraph views. Luckily the edge_subgraph filter nests
nicely so you can use the original graph as G in this function
to avoid chains. We do not rule out chains programmatically so
that odd cases like an `edge_subgraph` of a `restricted_view`
can be created.
Examples
--------
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list(H.nodes)
[0, 1, 3, 4]
>>> list(H.edges)
[(0, 1), (3, 4)]
| def edge_subgraph(G, edges):
"""Returns a view of the subgraph induced by the specified edges.
The induced subgraph contains each edge in `edges` and each
node incident to any of those edges.
Parameters
----------
G : NetworkX Graph
edges : iterable
An iterable of edges. Edges not present in `G` are ignored.
Returns
-------
subgraph : SubGraph View
A read-only edge-induced subgraph of `G`.
Changes to `G` are reflected in the view.
Notes
-----
To create a mutable subgraph with its own copies of nodes
edges and attributes use `subgraph.copy()` or `Graph(subgraph)`
If you create a subgraph of a subgraph recursively you can end up
with a chain of subgraphs that becomes very slow with about 15
nested subgraph views. Luckily the edge_subgraph filter nests
nicely so you can use the original graph as G in this function
to avoid chains. We do not rule out chains programmatically so
that odd cases like an `edge_subgraph` of a `restricted_view`
can be created.
Examples
--------
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list(H.nodes)
[0, 1, 3, 4]
>>> list(H.edges)
[(0, 1), (3, 4)]
"""
nxf = nx.filters
edges = set(edges)
nodes = set()
for e in edges:
nodes.update(e[:2])
induced_nodes = nxf.show_nodes(nodes)
if G.is_multigraph():
if G.is_directed():
induced_edges = nxf.show_multidiedges(edges)
else:
induced_edges = nxf.show_multiedges(edges)
else:
if G.is_directed():
induced_edges = nxf.show_diedges(edges)
else:
induced_edges = nxf.show_edges(edges)
return nx.subgraph_view(G, filter_node=induced_nodes, filter_edge=induced_edges)
| (G, edges) |
30,622 | networkx.classes.function | edges | Returns an edge view of edges incident to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
This function wraps the :func:`G.edges <networkx.Graph.edges>` property.
| def edges(G, nbunch=None):
"""Returns an edge view of edges incident to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
This function wraps the :func:`G.edges <networkx.Graph.edges>` property.
"""
return G.edges(nbunch)
| (G, nbunch=None) |
30,623 | networkx.algorithms.distance_measures | effective_graph_resistance | 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.
| 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, weight=None, invert_weight=True, *, backend=None, **backend_kwargs) |
30,624 | networkx.algorithms.structuralholes | effective_size | Returns the effective size of all nodes in the graph ``G``.
The *effective size* of a node's ego network is based on the concept
of redundancy. A person's ego network has redundancy to the extent
that her contacts are connected to each other as well. The
nonredundant part of a person's relationships is the effective
size of her ego network [1]_. Formally, the effective size of a
node $u$, denoted $e(u)$, is defined by
.. math::
e(u) = \sum_{v \in N(u) \setminus \{u\}}
\left(1 - \sum_{w \in N(v)} p_{uw} m_{vw}\right)
where $N(u)$ is the set of neighbors of $u$ and $p_{uw}$ is the
normalized mutual weight of the (directed or undirected) edges
joining $u$ and $v$, for each vertex $u$ and $v$ [1]_. And $m_{vw}$
is the mutual weight of $v$ and $w$ divided by $v$ highest mutual
weight with any of its neighbors. The *mutual weight* of $u$ and $v$
is the sum of the weights of edges joining them (edge weights are
assumed to be one if the graph is unweighted).
For the case of unweighted and undirected graphs, Borgatti proposed
a simplified formula to compute effective size [2]_
.. math::
e(u) = n - \frac{2t}{n}
where `t` is the number of ties in the ego network (not including
ties to ego) and `n` is the number of nodes (excluding ego).
Parameters
----------
G : NetworkX graph
The graph containing ``v``. Directed graphs are treated like
undirected graphs when computing neighbors of ``v``.
nodes : container, optional
Container of nodes in the graph ``G`` to compute the effective size.
If None, the effective size 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 effective size of the node as values.
Notes
-----
Burt also defined the related concept of *efficiency* of a node's ego
network, which is its effective size divided by the degree of that
node [1]_. So you can easily compute efficiency:
>>> G = nx.DiGraph()
>>> G.add_edges_from([(0, 1), (0, 2), (1, 0), (2, 1)])
>>> esize = nx.effective_size(G)
>>> efficiency = {n: v / G.degree(n) for n, v in esize.items()}
See also
--------
constraint
References
----------
.. [1] Burt, Ronald S.
*Structural Holes: The Social Structure of Competition.*
Cambridge: Harvard University Press, 1995.
.. [2] Borgatti, S.
"Structural Holes: Unpacking Burt's Redundancy Measures"
CONNECTIONS 20(1):35-38.
http://www.analytictech.com/connections/v20(1)/holes.htm
| null | (G, nodes=None, weight=None, *, backend=None, **backend_kwargs) |
30,625 | networkx.algorithms.efficiency_measures | efficiency | Returns the efficiency of a pair of nodes in a graph.
The *efficiency* of a pair of nodes is the multiplicative inverse of the
shortest path distance between the nodes [1]_. Returns 0 if no path
between nodes.
Parameters
----------
G : :class:`networkx.Graph`
An undirected graph for which to compute the average local efficiency.
u, v : node
Nodes in the graph ``G``.
Returns
-------
float
Multiplicative inverse of the shortest path distance between the nodes.
Examples
--------
>>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
>>> nx.efficiency(G, 2, 3) # this gives efficiency for node 2 and 3
0.5
Notes
-----
Edge weights are ignored when computing the shortest path distances.
See also
--------
local_efficiency
global_efficiency
References
----------
.. [1] Latora, Vito, and Massimo Marchiori.
"Efficient behavior of small-world networks."
*Physical Review Letters* 87.19 (2001): 198701.
<https://doi.org/10.1103/PhysRevLett.87.198701>
| null | (G, u, v, *, backend=None, **backend_kwargs) |
30,628 | networkx.generators.ego | ego_graph | Returns induced subgraph of neighbors centered at node n within
a given radius.
Parameters
----------
G : graph
A NetworkX Graph or DiGraph
n : node
A single node
radius : number, optional
Include all neighbors of distance<=radius from n.
center : bool, optional
If False, do not include center node in graph
undirected : bool, optional
If True use both in- and out-neighbors of directed graphs.
distance : key, optional
Use specified edge data key as distance. For example, setting
distance='weight' will use the edge weight to measure the
distance from the node n.
Notes
-----
For directed graphs D this produces the "out" neighborhood
or successors. If you want the neighborhood of predecessors
first reverse the graph with D.reverse(). If you want both
directions use the keyword argument undirected=True.
Node, edge, and graph attributes are copied to the returned subgraph.
| null | (G, n, radius=1, center=True, undirected=False, distance=None, *, backend=None, **backend_kwargs) |
30,630 | networkx.algorithms.centrality.eigenvector | eigenvector_centrality | Compute the eigenvector centrality for the graph G.
Eigenvector centrality computes the centrality for a node by adding
the centrality of its predecessors. The centrality for node $i$ is the
$i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
of maximum modulus that is positive. Such an eigenvector $x$ is
defined up to a multiplicative constant by the equation
.. math::
\lambda x^T = x^T A,
where $A$ is the adjacency matrix of the graph G. By definition of
row-column product, the equation above is equivalent to
.. math::
\lambda x_i = \sum_{j\to i}x_j.
That is, adding the eigenvector centralities of the predecessors of
$i$ one obtains the eigenvector centrality of $i$ multiplied by
$\lambda$. In the case of undirected graphs, $x$ also solves the familiar
right-eigenvector equation $Ax = \lambda x$.
By virtue of the Perron–Frobenius theorem [1]_, if G is strongly
connected there is a unique eigenvector $x$, and all its entries
are strictly positive.
If G is not strongly connected there might be several left
eigenvectors associated with $\lambda$, and some of their elements
might be zero.
Parameters
----------
G : graph
A networkx graph.
max_iter : integer, optional (default=100)
Maximum number of power iterations.
tol : float, optional (default=1.0e-6)
Error tolerance (in Euclidean norm) used to check convergence in
power iteration.
nstart : dictionary, optional (default=None)
Starting value of power iteration for each node. Must have a nonzero
projection on the desired eigenvector for the power method to converge.
If None, this implementation uses an all-ones vector, which is a safe
choice.
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. In this measure the
weight is interpreted as the connection strength.
Returns
-------
nodes : dictionary
Dictionary of nodes with eigenvector centrality as the value. The
associated vector has unit Euclidean norm and the values are
nonegative.
Examples
--------
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> sorted((v, f"{c:0.2f}") for v, c in centrality.items())
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]
Raises
------
NetworkXPointlessConcept
If the graph G is the null graph.
NetworkXError
If each value in `nstart` is zero.
PowerIterationFailedConvergence
If the algorithm fails to converge to the specified tolerance
within the specified number of iterations of the power iteration
method.
See Also
--------
eigenvector_centrality_numpy
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`
Notes
-----
Eigenvector centrality was introduced by Landau [2]_ for chess
tournaments. It was later rediscovered by Wei [3]_ and then
popularized by Kendall [4]_ in the context of sport ranking. Berge
introduced a general definition for graphs based on social connections
[5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
it popular in link analysis.
This function computes the left dominant eigenvector, which corresponds
to adding the centrality of predecessors: this is the usual approach.
To add the centrality of successors first reverse the graph with
``G.reverse()``.
The implementation uses power iteration [7]_ to compute a dominant
eigenvector starting from the provided vector `nstart`. Convergence is
guaranteed as long as `nstart` has a nonzero projection on a dominant
eigenvector, which certainly happens using the default value.
The method stops when the change in the computed vector between two
iterations is smaller than an error tolerance of ``G.number_of_nodes()
* tol`` or after ``max_iter`` iterations, but in the second case it
raises an exception.
This implementation uses $(A + I)$ rather than the adjacency matrix
$A$ because the change preserves eigenvectors, but it shifts the
spectrum, thus guaranteeing convergence even for networks with
negative eigenvalues of maximum modulus.
References
----------
.. [1] Abraham Berman and Robert J. Plemmons.
"Nonnegative Matrices in the Mathematical Sciences."
Classics in Applied Mathematics. SIAM, 1994.
.. [2] Edmund Landau.
"Zur relativen Wertbemessung der Turnierresultate."
Deutsches Wochenschach, 11:366–369, 1895.
.. [3] Teh-Hsing Wei.
"The Algebraic Foundations of Ranking Theory."
PhD thesis, University of Cambridge, 1952.
.. [4] Maurice G. Kendall.
"Further contributions to the theory of paired comparisons."
Biometrics, 11(1):43–62, 1955.
https://www.jstor.org/stable/3001479
.. [5] Claude Berge
"Théorie des graphes et ses applications."
Dunod, Paris, France, 1958.
.. [6] Phillip Bonacich.
"Technique for analyzing overlapping memberships."
Sociological Methodology, 4:176–185, 1972.
https://www.jstor.org/stable/270732
.. [7] Power iteration:: https://en.wikipedia.org/wiki/Power_iteration
| null | (G, max_iter=100, tol=1e-06, nstart=None, weight=None, *, backend=None, **backend_kwargs) |
30,631 | networkx.algorithms.centrality.eigenvector | eigenvector_centrality_numpy | Compute the eigenvector centrality for the graph G.
Eigenvector centrality computes the centrality for a node by adding
the centrality of its predecessors. The centrality for node $i$ is the
$i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
of maximum modulus that is positive. Such an eigenvector $x$ is
defined up to a multiplicative constant by the equation
.. math::
\lambda x^T = x^T A,
where $A$ is the adjacency matrix of the graph G. By definition of
row-column product, the equation above is equivalent to
.. math::
\lambda x_i = \sum_{j\to i}x_j.
That is, adding the eigenvector centralities of the predecessors of
$i$ one obtains the eigenvector centrality of $i$ multiplied by
$\lambda$. In the case of undirected graphs, $x$ also solves the familiar
right-eigenvector equation $Ax = \lambda x$.
By virtue of the Perron–Frobenius theorem [1]_, if G is strongly
connected there is a unique eigenvector $x$, and all its entries
are strictly positive.
If G is not strongly connected there might be several left
eigenvectors associated with $\lambda$, and some of their elements
might be zero.
Parameters
----------
G : graph
A networkx graph.
max_iter : integer, optional (default=50)
Maximum number of Arnoldi update iterations allowed.
tol : float, optional (default=0)
Relative accuracy for eigenvalues (stopping criterion).
The default value of 0 implies machine precision.
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. In this measure the
weight is interpreted as the connection strength.
Returns
-------
nodes : dictionary
Dictionary of nodes with eigenvector centrality as the value. The
associated vector has unit Euclidean norm and the values are
nonegative.
Examples
--------
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality_numpy(G)
>>> print([f"{node} {centrality[node]:0.2f}" for node in centrality])
['0 0.37', '1 0.60', '2 0.60', '3 0.37']
Raises
------
NetworkXPointlessConcept
If the graph G is the null graph.
ArpackNoConvergence
When the requested convergence is not obtained. The currently
converged eigenvalues and eigenvectors can be found as
eigenvalues and eigenvectors attributes of the exception object.
See Also
--------
:func:`scipy.sparse.linalg.eigs`
eigenvector_centrality
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`
Notes
-----
Eigenvector centrality was introduced by Landau [2]_ for chess
tournaments. It was later rediscovered by Wei [3]_ and then
popularized by Kendall [4]_ in the context of sport ranking. Berge
introduced a general definition for graphs based on social connections
[5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
it popular in link analysis.
This function computes the left dominant eigenvector, which corresponds
to adding the centrality of predecessors: this is the usual approach.
To add the centrality of successors first reverse the graph with
``G.reverse()``.
This implementation uses the
:func:`SciPy sparse eigenvalue solver<scipy.sparse.linalg.eigs>` (ARPACK)
to find the largest eigenvalue/eigenvector pair using Arnoldi iterations
[7]_.
References
----------
.. [1] Abraham Berman and Robert J. Plemmons.
"Nonnegative Matrices in the Mathematical Sciences."
Classics in Applied Mathematics. SIAM, 1994.
.. [2] Edmund Landau.
"Zur relativen Wertbemessung der Turnierresultate."
Deutsches Wochenschach, 11:366–369, 1895.
.. [3] Teh-Hsing Wei.
"The Algebraic Foundations of Ranking Theory."
PhD thesis, University of Cambridge, 1952.
.. [4] Maurice G. Kendall.
"Further contributions to the theory of paired comparisons."
Biometrics, 11(1):43–62, 1955.
https://www.jstor.org/stable/3001479
.. [5] Claude Berge
"Théorie des graphes et ses applications."
Dunod, Paris, France, 1958.
.. [6] Phillip Bonacich.
"Technique for analyzing overlapping memberships."
Sociological Methodology, 4:176–185, 1972.
https://www.jstor.org/stable/270732
.. [7] Arnoldi iteration:: https://en.wikipedia.org/wiki/Arnoldi_iteration
| null | (G, weight=None, max_iter=50, tol=0, *, backend=None, **backend_kwargs) |
30,632 | networkx.generators.classic | empty_graph | Returns the empty graph with n nodes and zero edges.
.. plot::
>>> nx.draw(nx.empty_graph(5))
Parameters
----------
n : int or iterable container of nodes (default = 0)
If n is an integer, nodes are from `range(n)`.
If n is a container of nodes, those nodes appear in the graph.
create_using : Graph Instance, Constructor or None
Indicator of type of graph to return.
If a Graph-type instance, then clear and use it.
If None, use the `default` constructor.
If a constructor, call it to create an empty graph.
default : Graph constructor (optional, default = nx.Graph)
The constructor to use if create_using is None.
If None, then nx.Graph is used.
This is used when passing an unknown `create_using` value
through your home-grown function to `empty_graph` and
you want a default constructor other than nx.Graph.
Examples
--------
>>> G = nx.empty_graph(10)
>>> G.number_of_nodes()
10
>>> G.number_of_edges()
0
>>> G = nx.empty_graph("ABC")
>>> G.number_of_nodes()
3
>>> sorted(G)
['A', 'B', 'C']
Notes
-----
The variable create_using should be a Graph Constructor or a
"graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
will be used to create the returned graph. "graph"-like objects
will be cleared (nodes and edges will be removed) and refitted as
an empty "graph" with nodes specified in n. This capability
is useful for specifying the class-nature of the resulting empty
"graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
The variable create_using has three main uses:
Firstly, the variable create_using can be used to create an
empty digraph, multigraph, etc. For example,
>>> n = 10
>>> G = nx.empty_graph(n, create_using=nx.DiGraph)
will create an empty digraph on n nodes.
Secondly, one can pass an existing graph (digraph, multigraph,
etc.) via create_using. For example, if G is an existing graph
(resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
will empty G (i.e. delete all nodes and edges using G.clear())
and then add n nodes and zero edges, and return the modified graph.
Thirdly, when constructing your home-grown graph creation function
you can use empty_graph to construct the graph by passing a user
defined create_using to empty_graph. In this case, if you want the
default constructor to be other than nx.Graph, specify `default`.
>>> def mygraph(n, create_using=None):
... G = nx.empty_graph(n, create_using, nx.MultiGraph)
... G.add_edges_from([(0, 1), (0, 1)])
... return G
>>> G = mygraph(3)
>>> G.is_multigraph()
True
>>> G = mygraph(3, nx.Graph)
>>> G.is_multigraph()
False
See also create_empty_copy(G).
| 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=0, create_using=None, default=<class 'networkx.classes.graph.Graph'>, *, backend=None, **backend_kwargs) |
30,633 | networkx.algorithms.clique | enumerate_all_cliques | Returns all cliques in an undirected graph.
This function returns an iterator over cliques, each of which is a
list of nodes. The iteration is ordered by cardinality of the
cliques: first all cliques of size one, then all cliques of size
two, etc.
Parameters
----------
G : NetworkX graph
An undirected graph.
Returns
-------
iterator
An iterator over cliques, each of which is a list of nodes in
`G`. The cliques are ordered according to size.
Notes
-----
To obtain a list of all cliques, use
`list(enumerate_all_cliques(G))`. However, be aware that in the
worst-case, the length of this list can be exponential in the number
of nodes in the graph (for example, when the graph is the complete
graph). This function avoids storing all cliques in memory by only
keeping current candidate node lists in memory during its search.
The implementation is adapted from the algorithm by Zhang, et
al. (2005) [1]_ to output all cliques discovered.
This algorithm ignores self-loops and parallel edges, since cliques
are not conventionally defined with such edges.
References
----------
.. [1] Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J.,
Langston, M.A., Samatova, N.F.,
"Genome-Scale Computational Approaches to Memory-Intensive
Applications in Systems Biology".
*Supercomputing*, 2005. Proceedings of the ACM/IEEE SC 2005
Conference, pp. 12, 12--18 Nov. 2005.
<https://doi.org/10.1109/SC.2005.29>.
| null | (G, *, backend=None, **backend_kwargs) |
30,634 | networkx.algorithms.coloring.equitable_coloring | equitable_color | Provides an equitable coloring for nodes of `G`.
Attempts to color a graph using `num_colors` colors, where no neighbors of
a node can have same color as the node itself and the number of nodes with
each color differ by at most 1. `num_colors` must be greater than the
maximum degree of `G`. The algorithm is described in [1]_ and has
complexity O(num_colors * n**2).
Parameters
----------
G : networkX graph
The nodes of this graph will be colored.
num_colors : number of colors to use
This number must be at least one more than the maximum degree of nodes
in the graph.
Returns
-------
A dictionary with keys representing nodes and values representing
corresponding coloring.
Examples
--------
>>> G = nx.cycle_graph(4)
>>> nx.coloring.equitable_color(G, num_colors=3) # doctest: +SKIP
{0: 2, 1: 1, 2: 2, 3: 0}
Raises
------
NetworkXAlgorithmError
If `num_colors` is not at least the maximum degree of the graph `G`
References
----------
.. [1] Kierstead, H. A., Kostochka, A. V., Mydlarz, M., & Szemerédi, E.
(2010). A fast algorithm for equitable coloring. Combinatorica, 30(2),
217-224.
| null | (G, num_colors, *, backend=None, **backend_kwargs) |
30,635 | networkx.algorithms.minors.contraction | equivalence_classes | Returns equivalence classes of `relation` when applied to `iterable`.
The equivalence classes, or blocks, consist of objects from `iterable`
which are all equivalent. They are defined to be equivalent if the
`relation` function returns `True` when passed any two objects from that
class, and `False` otherwise. To define an equivalence relation the
function must be reflexive, symmetric and transitive.
Parameters
----------
iterable : list, tuple, or set
An iterable of elements/nodes.
relation : function
A Boolean-valued function that implements an equivalence relation
(reflexive, symmetric, transitive binary relation) on the elements
of `iterable` - it must take two elements and return `True` if
they are related, or `False` if not.
Returns
-------
set of frozensets
A set of frozensets representing the partition induced by the equivalence
relation function `relation` on the elements of `iterable`. Each
member set in the return set represents an equivalence class, or
block, of the partition.
Duplicate elements will be ignored so it makes the most sense for
`iterable` to be a :class:`set`.
Notes
-----
This function does not check that `relation` represents an equivalence
relation. You can check that your equivalence classes provide a partition
using `is_partition`.
Examples
--------
Let `X` be the set of integers from `0` to `9`, and consider an equivalence
relation `R` on `X` of congruence modulo `3`: this means that two integers
`x` and `y` in `X` are equivalent under `R` if they leave the same
remainder when divided by `3`, i.e. `(x - y) mod 3 = 0`.
The equivalence classes of this relation are `{0, 3, 6, 9}`, `{1, 4, 7}`,
`{2, 5, 8}`: `0`, `3`, `6`, `9` are all divisible by `3` and leave zero
remainder; `1`, `4`, `7` leave remainder `1`; while `2`, `5` and `8` leave
remainder `2`. We can see this by calling `equivalence_classes` with
`X` and a function implementation of `R`.
>>> X = set(range(10))
>>> def mod3(x, y):
... return (x - y) % 3 == 0
>>> equivalence_classes(X, mod3) # doctest: +SKIP
{frozenset({1, 4, 7}), frozenset({8, 2, 5}), frozenset({0, 9, 3, 6})}
| def equivalence_classes(iterable, relation):
"""Returns equivalence classes of `relation` when applied to `iterable`.
The equivalence classes, or blocks, consist of objects from `iterable`
which are all equivalent. They are defined to be equivalent if the
`relation` function returns `True` when passed any two objects from that
class, and `False` otherwise. To define an equivalence relation the
function must be reflexive, symmetric and transitive.
Parameters
----------
iterable : list, tuple, or set
An iterable of elements/nodes.
relation : function
A Boolean-valued function that implements an equivalence relation
(reflexive, symmetric, transitive binary relation) on the elements
of `iterable` - it must take two elements and return `True` if
they are related, or `False` if not.
Returns
-------
set of frozensets
A set of frozensets representing the partition induced by the equivalence
relation function `relation` on the elements of `iterable`. Each
member set in the return set represents an equivalence class, or
block, of the partition.
Duplicate elements will be ignored so it makes the most sense for
`iterable` to be a :class:`set`.
Notes
-----
This function does not check that `relation` represents an equivalence
relation. You can check that your equivalence classes provide a partition
using `is_partition`.
Examples
--------
Let `X` be the set of integers from `0` to `9`, and consider an equivalence
relation `R` on `X` of congruence modulo `3`: this means that two integers
`x` and `y` in `X` are equivalent under `R` if they leave the same
remainder when divided by `3`, i.e. `(x - y) mod 3 = 0`.
The equivalence classes of this relation are `{0, 3, 6, 9}`, `{1, 4, 7}`,
`{2, 5, 8}`: `0`, `3`, `6`, `9` are all divisible by `3` and leave zero
remainder; `1`, `4`, `7` leave remainder `1`; while `2`, `5` and `8` leave
remainder `2`. We can see this by calling `equivalence_classes` with
`X` and a function implementation of `R`.
>>> X = set(range(10))
>>> def mod3(x, y):
... return (x - y) % 3 == 0
>>> equivalence_classes(X, mod3) # doctest: +SKIP
{frozenset({1, 4, 7}), frozenset({8, 2, 5}), frozenset({0, 9, 3, 6})}
"""
# For simplicity of implementation, we initialize the return value as a
# list of lists, then convert it to a set of sets at the end of the
# function.
blocks = []
# Determine the equivalence class for each element of the iterable.
for y in iterable:
# Each element y must be in *exactly one* equivalence class.
#
# Each block is guaranteed to be non-empty
for block in blocks:
x = arbitrary_element(block)
if relation(x, y):
block.append(y)
break
else:
# If the element y is not part of any known equivalence class, it
# must be in its own, so we create a new singleton equivalence
# class for it.
blocks.append([y])
return {frozenset(block) for block in blocks}
| (iterable, relation) |
30,637 | networkx.algorithms.centrality.subgraph_alg | estrada_index | Returns the Estrada index of a the graph G.
The Estrada Index is a topological index of folding or 3D "compactness" ([1]_).
Parameters
----------
G: graph
Returns
-------
estrada index: float
Raises
------
NetworkXError
If the graph is not undirected and simple.
Notes
-----
Let `G=(V,E)` be a simple undirected graph with `n` nodes and let
`\lambda_{1}\leq\lambda_{2}\leq\cdots\lambda_{n}`
be a non-increasing ordering of the eigenvalues of its adjacency
matrix `A`. The Estrada index is ([1]_, [2]_)
.. math::
EE(G)=\sum_{j=1}^n e^{\lambda _j}.
References
----------
.. [1] E. Estrada, "Characterization of 3D molecular structure",
Chem. Phys. Lett. 319, 713 (2000).
https://doi.org/10.1016/S0009-2614(00)00158-5
.. [2] José Antonio de la Peñaa, Ivan Gutman, Juan Rada,
"Estimating the Estrada index",
Linear Algebra and its Applications. 427, 1 (2007).
https://doi.org/10.1016/j.laa.2007.06.020
Examples
--------
>>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> ei = nx.estrada_index(G)
>>> print(f"{ei:0.5}")
20.55
| null | (G, *, backend=None, **backend_kwargs) |
30,639 | networkx.algorithms.euler | eulerian_circuit | Returns an iterator over the edges of an Eulerian circuit in `G`.
An *Eulerian circuit* is a closed walk that includes each edge of a
graph exactly once.
Parameters
----------
G : NetworkX graph
A graph, either directed or undirected.
source : node, optional
Starting node for circuit.
keys : bool
If False, edges generated by this function will be of the form
``(u, v)``. Otherwise, edges will be of the form ``(u, v, k)``.
This option is ignored unless `G` is a multigraph.
Returns
-------
edges : iterator
An iterator over edges in the Eulerian circuit.
Raises
------
NetworkXError
If the graph is not Eulerian.
See Also
--------
is_eulerian
Notes
-----
This is a linear time implementation of an algorithm adapted from [1]_.
For general information about Euler tours, see [2]_.
References
----------
.. [1] J. Edmonds, E. L. Johnson.
Matching, Euler tours and the Chinese postman.
Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
.. [2] https://en.wikipedia.org/wiki/Eulerian_path
Examples
--------
To get an Eulerian circuit in an undirected graph::
>>> G = nx.complete_graph(3)
>>> list(nx.eulerian_circuit(G))
[(0, 2), (2, 1), (1, 0)]
>>> list(nx.eulerian_circuit(G, source=1))
[(1, 2), (2, 0), (0, 1)]
To get the sequence of vertices in an Eulerian circuit::
>>> [u for u, v in nx.eulerian_circuit(G)]
[0, 2, 1]
| null | (G, source=None, keys=False, *, backend=None, **backend_kwargs) |
30,640 | networkx.algorithms.euler | eulerian_path | Return an iterator over the edges of an Eulerian path in `G`.
Parameters
----------
G : NetworkX Graph
The graph in which to look for an eulerian path.
source : node or None (default: None)
The node at which to start the search. None means search over all
starting nodes.
keys : Bool (default: False)
Indicates whether to yield edge 3-tuples (u, v, edge_key).
The default yields edge 2-tuples
Yields
------
Edge tuples along the eulerian path.
Warning: If `source` provided is not the start node of an Euler path
will raise error even if an Euler Path exists.
| null | (G, source=None, keys=False, *, backend=None, **backend_kwargs) |
30,641 | networkx.algorithms.euler | eulerize | Transforms a graph into an Eulerian graph.
If `G` is Eulerian the result is `G` as a MultiGraph, otherwise the result is a smallest
(in terms of the number of edges) multigraph whose underlying simple graph is `G`.
Parameters
----------
G : NetworkX graph
An undirected graph
Returns
-------
G : NetworkX multigraph
Raises
------
NetworkXError
If the graph is not connected.
See Also
--------
is_eulerian
eulerian_circuit
References
----------
.. [1] J. Edmonds, E. L. Johnson.
Matching, Euler tours and the Chinese postman.
Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
.. [2] https://en.wikipedia.org/wiki/Eulerian_path
.. [3] http://web.math.princeton.edu/math_alive/5/Notes1.pdf
Examples
--------
>>> G = nx.complete_graph(10)
>>> H = nx.eulerize(G)
>>> nx.is_eulerian(H)
True
| null | (G, *, backend=None, **backend_kwargs) |
30,644 | networkx.generators.degree_seq | expected_degree_graph | Returns a random graph with given expected degrees.
Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$
of length $n$ this algorithm assigns an edge between node $u$ and
node $v$ with probability
.. math::
p_{uv} = \frac{w_u w_v}{\sum_k w_k} .
Parameters
----------
w : list
The list of expected degrees.
selfloops: bool (default=True)
Set to False to remove the possibility of self-loop edges.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
Graph
Examples
--------
>>> z = [10 for i in range(100)]
>>> G = nx.expected_degree_graph(z)
Notes
-----
The nodes have integer labels corresponding to index of expected degrees
input sequence.
The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the
number of nodes and $m$ is the expected number of edges.
The model in [1]_ includes the possibility of self-loop edges.
Set selfloops=False to produce a graph without self loops.
For finite graphs this model doesn't produce exactly the given
expected degree sequence. Instead the expected degrees are as
follows.
For the case without self loops (selfloops=False),
.. math::
E[deg(u)] = \sum_{v \ne u} p_{uv}
= w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .
NetworkX uses the standard convention that a self-loop edge counts 2
in the degree of a node, so with self loops (selfloops=True),
.. math::
E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu}
= w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .
References
----------
.. [1] Fan Chung and L. Lu, Connected components in random graphs with
given expected degree sequences, Ann. Combinatorics, 6,
pp. 125-145, 2002.
.. [2] Joel Miller and Aric Hagberg,
Efficient generation of networks with given expected degrees,
in Algorithms and Models for the Web-Graph (WAW 2011),
Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,
pp. 115-126, 2011.
| 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
| (w, seed=None, selfloops=True, *, backend=None, **backend_kwargs) |
30,645 | networkx.generators.random_graphs | extended_barabasi_albert_graph | Returns an extended Barabási–Albert model graph.
An extended Barabási–Albert model graph is a random graph constructed
using preferential attachment. The extended model allows new edges,
rewired edges or new nodes. Based on the probabilities $p$ and $q$
with $p + q < 1$, the growing behavior of the graph is determined as:
1) With $p$ probability, $m$ new edges are added to the graph,
starting from randomly chosen existing nodes and attached preferentially at the other end.
2) With $q$ probability, $m$ existing edges are rewired
by randomly choosing an edge and rewiring one end to a preferentially chosen node.
3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph
with edges attached preferentially.
When $p = q = 0$, the model behaves just like the Barabási–Alber model.
Parameters
----------
n : int
Number of nodes
m : int
Number of edges with which a new node attaches to existing nodes
p : float
Probability value for adding an edge between existing nodes. p + q < 1
q : float
Probability value of rewiring of existing edges. p + q < 1
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q``
References
----------
.. [1] Albert, R., & Barabási, A. L. (2000)
Topology of evolving networks: local events and universality
Physical review letters, 85(24), 5234.
| 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, p, q, seed=None, *, backend=None, **backend_kwargs) |
30,646 | networkx.algorithms.isomorphism.isomorph | fast_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 and triangle sequences. The triangle
sequence contains the number of triangles each node is part of.
| null | (G1, G2, *, backend=None, **backend_kwargs) |
30,647 | networkx.generators.random_graphs | fast_gnp_random_graph | Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
a binomial graph.
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.
Notes
-----
The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
(undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.
This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
edges, which equals $p n (n - 1) / 2$. This should be faster than
:func:`gnp_random_graph` when $p$ is small and the expected number of edges
is small (that is, the graph is sparse).
See Also
--------
gnp_random_graph
References
----------
.. [1] Vladimir Batagelj and Ulrik Brandes,
"Efficient generation of large random networks",
Phys. Rev. E, 71, 036113, 2005.
| 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,648 | networkx.algorithms.isomorphism.isomorph | faster_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 sequences.
| null | (G1, G2, *, backend=None, **backend_kwargs) |
30,649 | networkx.linalg.algebraicconnectivity | fiedler_vector | Returns the Fiedler vector of a connected undirected graph.
The Fiedler vector of a connected undirected graph is the eigenvector
corresponding to the second smallest eigenvalue of the Laplacian matrix
of the graph.
Parameters
----------
G : NetworkX graph
An undirected graph.
weight : object, optional (default: None)
The data key used to determine the weight of each edge. If None, then
each edge has unit weight.
normalized : bool, optional (default: False)
Whether the normalized Laplacian matrix is used.
tol : float, optional (default: 1e-8)
Tolerance of relative residual in eigenvalue computation.
method : string, optional (default: 'tracemin_pcg')
Method of eigenvalue computation. It must be one of the tracemin
options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
or 'lobpcg' (LOBPCG).
The TraceMIN algorithm uses a linear system solver. The following
values allow specifying the solver to be used.
=============== ========================================
Value Solver
=============== ========================================
'tracemin_pcg' Preconditioned conjugate gradient method
'tracemin_lu' LU factorization
=============== ========================================
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
fiedler_vector : NumPy array of floats.
Fiedler vector.
Raises
------
NetworkXNotImplemented
If G is directed.
NetworkXError
If G has less than two nodes or is not connected.
Notes
-----
Edge weights are interpreted by their absolute values. For MultiGraph's,
weights of parallel edges are summed. Zero-weighted edges are ignored.
See Also
--------
laplacian_matrix
Examples
--------
Given a connected graph the signs of the values in the Fiedler vector can be
used to partition the graph into two components.
>>> G = nx.barbell_graph(5, 0)
>>> nx.fiedler_vector(G, normalized=True, seed=1)
array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899,
0.26072899, 0.32864129, 0.32864129, 0.32864129, 0.32864129])
The connected components are the two 5-node cliques of the barbell graph.
| null | (G, weight='weight', normalized=False, tol=1e-08, method='tracemin_pcg', seed=None, *, backend=None, **backend_kwargs) |
30,651 | networkx.algorithms.asteroidal | find_asteroidal_triple | Find an asteroidal triple in the given graph.
An asteroidal triple is a triple of non-adjacent vertices such that
there exists a path between any two of them which avoids the closed
neighborhood of the third. It checks all independent triples of vertices
and whether they are an asteroidal triple or not. This is done with the
help of a data structure called a component structure.
A component structure encodes information about which vertices belongs to
the same connected component when the closed neighborhood of a given vertex
is removed from the graph. The algorithm used to check is the trivial
one, outlined in [1]_, which has a runtime of
:math:`O(|V||\overline{E} + |V||E|)`, where the second term is the
creation of the component structure.
Parameters
----------
G : NetworkX Graph
The graph to check whether is AT-free or not
Returns
-------
list or None
An asteroidal triple is returned as a list of nodes. If no asteroidal
triple exists, i.e. the graph is AT-free, then None is returned.
The returned value depends on the certificate parameter. The default
option is a bool which is True if the graph is AT-free, i.e. the
given graph contains no asteroidal triples, and False otherwise, i.e.
if the graph contains at least one asteroidal triple.
Notes
-----
The component structure and the algorithm is described in [1]_. The current
implementation implements the trivial algorithm for simple graphs.
References
----------
.. [1] Ekkehard Köhler,
"Recognizing Graphs without asteroidal triples",
Journal of Discrete Algorithms 2, pages 439-452, 2004.
https://www.sciencedirect.com/science/article/pii/S157086670400019X
| null | (G, *, backend=None, **backend_kwargs) |
30,652 | networkx.algorithms.clique | find_cliques | Returns all maximal cliques in an undirected graph.
For each node *n*, a *maximal clique for n* is a largest complete
subgraph containing *n*. The largest maximal clique is sometimes
called the *maximum clique*.
This function returns an iterator over cliques, each of which is a
list of nodes. It is an iterative implementation, so should not
suffer from recursion depth issues.
This function accepts a list of `nodes` and only the maximal cliques
containing all of these `nodes` are returned. It can considerably speed up
the running time if some specific cliques are desired.
Parameters
----------
G : NetworkX graph
An undirected graph.
nodes : list, optional (default=None)
If provided, only yield *maximal cliques* containing all nodes in `nodes`.
If `nodes` isn't a clique itself, a ValueError is raised.
Returns
-------
iterator
An iterator over maximal cliques, each of which is a list of
nodes in `G`. If `nodes` is provided, only the maximal cliques
containing all the nodes in `nodes` are returned. The order of
cliques is arbitrary.
Raises
------
ValueError
If `nodes` is not a clique.
Examples
--------
>>> from pprint import pprint # For nice dict formatting
>>> G = nx.karate_club_graph()
>>> sum(1 for c in nx.find_cliques(G)) # The number of maximal cliques in G
36
>>> max(nx.find_cliques(G), key=len) # The largest maximal clique in G
[0, 1, 2, 3, 13]
The size of the largest maximal clique is known as the *clique number* of
the graph, which can be found directly with:
>>> max(len(c) for c in nx.find_cliques(G))
5
One can also compute the number of maximal cliques in `G` that contain a given
node. The following produces a dictionary keyed by node whose
values are the number of maximal cliques in `G` that contain the node:
>>> pprint({n: sum(1 for c in nx.find_cliques(G) if n in c) for n in G})
{0: 13,
1: 6,
2: 7,
3: 3,
4: 2,
5: 3,
6: 3,
7: 1,
8: 3,
9: 2,
10: 2,
11: 1,
12: 1,
13: 2,
14: 1,
15: 1,
16: 1,
17: 1,
18: 1,
19: 2,
20: 1,
21: 1,
22: 1,
23: 3,
24: 2,
25: 2,
26: 1,
27: 3,
28: 2,
29: 2,
30: 2,
31: 4,
32: 9,
33: 14}
Or, similarly, the maximal cliques in `G` that contain a given node.
For example, the 4 maximal cliques that contain node 31:
>>> [c for c in nx.find_cliques(G) if 31 in c]
[[0, 31], [33, 32, 31], [33, 28, 31], [24, 25, 31]]
See Also
--------
find_cliques_recursive
A recursive version of the same algorithm.
Notes
-----
To obtain a list of all maximal cliques, use
`list(find_cliques(G))`. However, be aware that in the worst-case,
the length of this list can be exponential in the number of nodes in
the graph. This function avoids storing all cliques in memory by
only keeping current candidate node lists in memory during its search.
This implementation is based on the algorithm published by Bron and
Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
(2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. It
essentially unrolls the recursion used in the references to avoid
issues of recursion stack depth (for a recursive implementation, see
:func:`find_cliques_recursive`).
This algorithm ignores self-loops and parallel edges, since cliques
are not conventionally defined with such edges.
References
----------
.. [1] Bron, C. and Kerbosch, J.
"Algorithm 457: finding all cliques of an undirected graph".
*Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
<http://portal.acm.org/citation.cfm?doid=362342.362367>
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
"The worst-case time complexity for generating all maximal
cliques and computational experiments",
*Theoretical Computer Science*, Volume 363, Issue 1,
Computing and Combinatorics,
10th Annual International Conference on
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
<https://doi.org/10.1016/j.tcs.2006.06.015>
.. [3] F. Cazals, C. Karande,
"A note on the problem of reporting maximal cliques",
*Theoretical Computer Science*,
Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
<https://doi.org/10.1016/j.tcs.2008.05.010>
| null | (G, nodes=None, *, backend=None, **backend_kwargs) |
30,653 | networkx.algorithms.clique | find_cliques_recursive | Returns all maximal cliques in a graph.
For each node *v*, a *maximal clique for v* is a largest complete
subgraph containing *v*. The largest maximal clique is sometimes
called the *maximum clique*.
This function returns an iterator over cliques, each of which is a
list of nodes. It is a recursive implementation, so may suffer from
recursion depth issues, but is included for pedagogical reasons.
For a non-recursive implementation, see :func:`find_cliques`.
This function accepts a list of `nodes` and only the maximal cliques
containing all of these `nodes` are returned. It can considerably speed up
the running time if some specific cliques are desired.
Parameters
----------
G : NetworkX graph
nodes : list, optional (default=None)
If provided, only yield *maximal cliques* containing all nodes in `nodes`.
If `nodes` isn't a clique itself, a ValueError is raised.
Returns
-------
iterator
An iterator over maximal cliques, each of which is a list of
nodes in `G`. If `nodes` is provided, only the maximal cliques
containing all the nodes in `nodes` are yielded. The order of
cliques is arbitrary.
Raises
------
ValueError
If `nodes` is not a clique.
See Also
--------
find_cliques
An iterative version of the same algorithm. See docstring for examples.
Notes
-----
To obtain a list of all maximal cliques, use
`list(find_cliques_recursive(G))`. However, be aware that in the
worst-case, the length of this list can be exponential in the number
of nodes in the graph. This function avoids storing all cliques in memory
by only keeping current candidate node lists in memory during its search.
This implementation is based on the algorithm published by Bron and
Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
(2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. For a
non-recursive implementation, see :func:`find_cliques`.
This algorithm ignores self-loops and parallel edges, since cliques
are not conventionally defined with such edges.
References
----------
.. [1] Bron, C. and Kerbosch, J.
"Algorithm 457: finding all cliques of an undirected graph".
*Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
<http://portal.acm.org/citation.cfm?doid=362342.362367>
.. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
"The worst-case time complexity for generating all maximal
cliques and computational experiments",
*Theoretical Computer Science*, Volume 363, Issue 1,
Computing and Combinatorics,
10th Annual International Conference on
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
<https://doi.org/10.1016/j.tcs.2006.06.015>
.. [3] F. Cazals, C. Karande,
"A note on the problem of reporting maximal cliques",
*Theoretical Computer Science*,
Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
<https://doi.org/10.1016/j.tcs.2008.05.010>
| null | (G, nodes=None, *, backend=None, **backend_kwargs) |
30,654 | networkx.algorithms.cycles | find_cycle | Returns a cycle found via depth-first traversal.
The cycle is a list of edges indicating the cyclic path.
Orientation of directed edges is controlled by `orientation`.
Parameters
----------
G : graph
A directed/undirected graph/multigraph.
source : node, list of nodes
The node from which the traversal begins. If None, then a source
is chosen arbitrarily and repeatedly until all edges from each node in
the graph are searched.
orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
For directed graphs and directed multigraphs, edge traversals need not
respect the original orientation of the edges.
When set to 'reverse' every edge is traversed in the reverse direction.
When set to 'ignore', every edge is treated as undirected.
When set to 'original', every edge is treated as directed.
In all three cases, the yielded edge tuples add a last entry to
indicate the direction in which that edge was traversed.
If orientation is None, the yielded edge has no direction indicated.
The direction is respected, but not reported.
Returns
-------
edges : directed edges
A list of directed edges indicating the path taken for the loop.
If no cycle is found, then an exception is raised.
For graphs, an edge is of the form `(u, v)` where `u` and `v`
are the tail and head of the edge as determined by the traversal.
For multigraphs, an edge is of the form `(u, v, key)`, where `key` is
the key of the edge. When the graph is directed, then `u` and `v`
are always in the order of the actual directed edge.
If orientation is not None then the edge tuple is extended to include
the direction of traversal ('forward' or 'reverse') on that edge.
Raises
------
NetworkXNoCycle
If no cycle was found.
Examples
--------
In this example, we construct a DAG and find, in the first call, that there
are no directed cycles, and so an exception is raised. In the second call,
we ignore edge orientations and find that there is an undirected cycle.
Note that the second call finds a directed cycle while effectively
traversing an undirected graph, and so, we found an "undirected cycle".
This means that this DAG structure does not form a directed tree (which
is also known as a polytree).
>>> G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
>>> nx.find_cycle(G, orientation="original")
Traceback (most recent call last):
...
networkx.exception.NetworkXNoCycle: No cycle found.
>>> list(nx.find_cycle(G, orientation="ignore"))
[(0, 1, 'forward'), (1, 2, 'forward'), (0, 2, 'reverse')]
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, source=None, orientation=None, *, backend=None, **backend_kwargs) |
30,655 | networkx.algorithms.chordal | find_induced_nodes | Returns the set of induced nodes in the path from s to t.
Parameters
----------
G : graph
A chordal NetworkX graph
s : node
Source node to look for induced nodes
t : node
Destination node to look for induced nodes
treewidth_bound: float
Maximum treewidth acceptable for the graph H. The search
for induced nodes will end as soon as the treewidth_bound is exceeded.
Returns
-------
induced_nodes : Set of nodes
The set of induced nodes in the path from s to t in G
Raises
------
NetworkXError
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
If the input graph is an instance of one of these classes, a
:exc:`NetworkXError` is raised.
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
--------
>>> G = nx.Graph()
>>> G = nx.generators.classic.path_graph(10)
>>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
>>> sorted(induced_nodes)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Notes
-----
G must be a chordal graph and (s,t) an edge that is not in G.
If a treewidth_bound is provided, the search for induced nodes will end
as soon as the treewidth_bound is exceeded.
The algorithm is inspired by Algorithm 4 in [1]_.
A formal definition of induced node can also be found on that reference.
Self Loops are ignored
References
----------
.. [1] Learning Bounded Treewidth Bayesian Networks.
Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699--2731, 2008.
http://jmlr.csail.mit.edu/papers/volume9/elidan08a/elidan08a.pdf
| null | (G, s, t, treewidth_bound=9223372036854775807, *, backend=None, **backend_kwargs) |
30,656 | networkx.algorithms.d_separation | find_minimal_d_separator | Returns a minimal d-separating set between `x` and `y` if possible
A d-separating set in a DAG is a set of nodes that blocks all
paths between the two sets of nodes, `x` and `y`. This function
constructs a d-separating set that is "minimal", meaning no nodes can
be removed without it losing the d-separating property for `x` and `y`.
If no d-separating sets exist for `x` and `y`, this returns `None`.
In a DAG there may be more than one minimal d-separator between two
sets of nodes. Minimal d-separators are not always unique. This function
returns one minimal d-separator, or `None` if no d-separator exists.
Uses the algorithm presented in [1]_. The complexity of the algorithm
is :math:`O(m)`, where :math:`m` stands for the number of edges in
the subgraph of G consisting of only the ancestors of `x` and `y`.
For full details, see [1]_.
Parameters
----------
G : graph
A networkx DAG.
x : set | node
A node or set of nodes in the graph.
y : set | node
A node or set of nodes in the graph.
included : set | node | None
A node or set of nodes which must be included in the found separating set,
default is None, which means the empty set.
restricted : set | node | None
Restricted node or set of nodes to consider. Only these nodes can be in
the found separating set, default is None meaning all nodes in ``G``.
Returns
-------
z : set | None
The minimal d-separating set, if at least one d-separating set exists,
otherwise None.
Raises
------
NetworkXError
Raises a :exc:`NetworkXError` if the input graph is not a DAG
or if node sets `x`, `y`, and `included` are not disjoint.
NodeNotFound
If any of the input nodes are not found in the graph,
a :exc:`NodeNotFound` exception is raised.
References
----------
.. [1] van der Zander, Benito, and Maciej Liśkiewicz. "Finding
minimal d-separators in linear time and applications." In
Uncertainty in Artificial Intelligence, pp. 637-647. PMLR, 2020.
| null | (G, x, y, *, included=None, restricted=None, backend=None, **backend_kwargs) |
30,657 | networkx.algorithms.shortest_paths.weighted | find_negative_cycle | Returns a cycle with negative total weight if it exists.
Bellman-Ford is used to find shortest_paths. That algorithm
stops if there exists a negative cycle. This algorithm
picks up from there and returns the found negative cycle.
The cycle consists of a list of nodes in the cycle order. The last
node equals the first to make it a cycle.
You can look up the edge weights in the original graph. In the case
of multigraphs the relevant edge is the minimal weight edge between
the nodes in the 2-tuple.
If the graph has no negative cycle, a NetworkXError is raised.
Parameters
----------
G : NetworkX graph
source: node label
The search for the negative cycle will start from this 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.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from([(0, 1, 2), (1, 2, 2), (2, 0, 1), (1, 4, 2), (4, 0, -5)])
>>> nx.find_negative_cycle(G, 0)
[4, 0, 1, 4]
Returns
-------
cycle : list
A list of nodes in the order of the cycle found. The last node
equals the first to indicate a cycle.
Raises
------
NetworkXError
If no negative cycle is found.
| 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, weight='weight', *, backend=None, **backend_kwargs) |
30,658 | networkx.generators.social | florentine_families_graph | Returns Florentine families graph.
References
----------
.. [1] Ronald L. Breiger and Philippa E. Pattison
Cumulated social roles: The duality of persons and their algebras,1
Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256
| null | (*, backend=None, **backend_kwargs) |
30,660 | networkx.algorithms.hierarchy | flow_hierarchy | Returns the flow hierarchy of a directed network.
Flow hierarchy is defined as the fraction of edges not participating
in cycles in a directed graph [1]_.
Parameters
----------
G : DiGraph or MultiDiGraph
A directed graph
weight : string, optional (default=None)
Attribute to use for edge weights. If None the weight defaults to 1.
Returns
-------
h : float
Flow hierarchy value
Notes
-----
The algorithm described in [1]_ computes the flow hierarchy through
exponentiation of the adjacency matrix. This function implements an
alternative approach that finds strongly connected components.
An edge is in a cycle if and only if it is in a strongly connected
component, which can be found in $O(m)$ time using Tarjan's algorithm.
References
----------
.. [1] Luo, J.; Magee, C.L. (2011),
Detecting evolving patterns of self-organizing networks by flow
hierarchy measurement, Complexity, Volume 16 Issue 6 53-61.
DOI: 10.1002/cplx.20368
http://web.mit.edu/~cmagee/www/documents/28-DetectingEvolvingPatterns_FlowHierarchy.pdf
| null | (G, weight=None, *, backend=None, **backend_kwargs) |
30,662 | networkx.algorithms.shortest_paths.dense | floyd_warshall | Find all-pairs shortest path lengths using Floyd's algorithm.
Parameters
----------
G : NetworkX graph
weight: string, optional (default= 'weight')
Edge data key corresponding to the edge weight.
Returns
-------
distance : dict
A dictionary, keyed by source and target, of shortest paths distances
between nodes.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from([(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)])
>>> fw = nx.floyd_warshall(G, weight="weight")
>>> results = {a: dict(b) for a, b in fw.items()}
>>> print(results)
{0: {0: 0, 1: 5, 2: 7, 3: 4}, 1: {1: 0, 2: 2, 3: -1, 0: inf}, 2: {2: 0, 3: -3, 0: inf, 1: inf}, 3: {3: 0, 2: 8, 0: inf, 1: inf}}
Notes
-----
Floyd's algorithm is appropriate for finding shortest paths
in dense graphs or graphs with negative weights when Dijkstra's algorithm
fails. This algorithm can still fail if there are negative cycles.
It has running time $O(n^3)$ with running space of $O(n^2)$.
See Also
--------
floyd_warshall_predecessor_and_distance
floyd_warshall_numpy
all_pairs_shortest_path
all_pairs_shortest_path_length
| null | (G, weight='weight', *, backend=None, **backend_kwargs) |
30,663 | networkx.algorithms.shortest_paths.dense | floyd_warshall_numpy | Find all-pairs shortest path lengths using Floyd's algorithm.
This algorithm for finding shortest paths takes advantage of
matrix representations of a graph and works well for dense
graphs where all-pairs shortest path lengths are desired.
The results are returned as a NumPy array, distance[i, j],
where i and j are the indexes of two nodes in nodelist.
The entry distance[i, j] is the distance along a shortest
path from i to j. If no path exists the distance is Inf.
Parameters
----------
G : NetworkX graph
nodelist : list, optional (default=G.nodes)
The rows and columns are ordered by the nodes in nodelist.
If nodelist is None then the ordering is produced by G.nodes.
Nodelist should include all nodes in G.
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight.
Returns
-------
distance : 2D numpy.ndarray
A numpy array of shortest path distances between nodes.
If there is no path between two nodes the value is Inf.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from([(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)])
>>> nx.floyd_warshall_numpy(G)
array([[ 0., 5., 7., 4.],
[inf, 0., 2., -1.],
[inf, inf, 0., -3.],
[inf, inf, 8., 0.]])
Notes
-----
Floyd's algorithm is appropriate for finding shortest paths in
dense graphs or graphs with negative weights when Dijkstra's
algorithm fails. This algorithm can still fail if there are negative
cycles. It has running time $O(n^3)$ with running space of $O(n^2)$.
Raises
------
NetworkXError
If nodelist is not a list of the nodes in G.
| null | (G, nodelist=None, weight='weight', *, backend=None, **backend_kwargs) |
30,664 | networkx.algorithms.shortest_paths.dense | floyd_warshall_predecessor_and_distance | Find all-pairs shortest path lengths using Floyd's algorithm.
Parameters
----------
G : NetworkX graph
weight: string, optional (default= 'weight')
Edge data key corresponding to the edge weight.
Returns
-------
predecessor,distance : dictionaries
Dictionaries, keyed by source and target, of predecessors and distances
in the shortest path.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from(
... [
... ("s", "u", 10),
... ("s", "x", 5),
... ("u", "v", 1),
... ("u", "x", 2),
... ("v", "y", 1),
... ("x", "u", 3),
... ("x", "v", 5),
... ("x", "y", 2),
... ("y", "s", 7),
... ("y", "v", 6),
... ]
... )
>>> predecessors, _ = nx.floyd_warshall_predecessor_and_distance(G)
>>> print(nx.reconstruct_path("s", "v", predecessors))
['s', 'x', 'u', 'v']
Notes
-----
Floyd's algorithm is appropriate for finding shortest paths
in dense graphs or graphs with negative weights when Dijkstra's algorithm
fails. This algorithm can still fail if there are negative cycles.
It has running time $O(n^3)$ with running space of $O(n^2)$.
See Also
--------
floyd_warshall
floyd_warshall_numpy
all_pairs_shortest_path
all_pairs_shortest_path_length
| null | (G, weight='weight', *, backend=None, **backend_kwargs) |
30,665 | networkx.readwrite.text | forest_str | Creates a nice utf8 representation of a forest
This function has been superseded by
:func:`nx.readwrite.text.generate_network_text`, which should be used
instead.
Parameters
----------
graph : nx.DiGraph | nx.Graph
Graph to represent (must be a tree, forest, or the empty graph)
with_labels : bool
If True will use the "label" attribute of a node to display if it
exists otherwise it will use the node value itself. Defaults to True.
sources : List
Mainly relevant for undirected forests, specifies which nodes to list
first. If unspecified the root nodes of each tree will be used for
directed forests; for undirected forests this defaults to the nodes
with the smallest degree.
write : callable
Function to use to write to, if None new lines are appended to
a list and returned. If set to the `print` function, lines will
be written to stdout as they are generated. If specified,
this function will return None. Defaults to None.
ascii_only : Boolean
If True only ASCII characters are used to construct the visualization
Returns
-------
str | None :
utf8 representation of the tree / forest
Examples
--------
>>> graph = nx.balanced_tree(r=2, h=3, create_using=nx.DiGraph)
>>> print(nx.forest_str(graph))
╙── 0
├─╼ 1
│ ├─╼ 3
│ │ ├─╼ 7
│ │ └─╼ 8
│ └─╼ 4
│ ├─╼ 9
│ └─╼ 10
└─╼ 2
├─╼ 5
│ ├─╼ 11
│ └─╼ 12
└─╼ 6
├─╼ 13
└─╼ 14
>>> graph = nx.balanced_tree(r=1, h=2, create_using=nx.Graph)
>>> print(nx.forest_str(graph))
╙── 0
└── 1
└── 2
>>> print(nx.forest_str(graph, ascii_only=True))
+-- 0
L-- 1
L-- 2
| def forest_str(graph, with_labels=True, sources=None, write=None, ascii_only=False):
"""Creates a nice utf8 representation of a forest
This function has been superseded by
:func:`nx.readwrite.text.generate_network_text`, which should be used
instead.
Parameters
----------
graph : nx.DiGraph | nx.Graph
Graph to represent (must be a tree, forest, or the empty graph)
with_labels : bool
If True will use the "label" attribute of a node to display if it
exists otherwise it will use the node value itself. Defaults to True.
sources : List
Mainly relevant for undirected forests, specifies which nodes to list
first. If unspecified the root nodes of each tree will be used for
directed forests; for undirected forests this defaults to the nodes
with the smallest degree.
write : callable
Function to use to write to, if None new lines are appended to
a list and returned. If set to the `print` function, lines will
be written to stdout as they are generated. If specified,
this function will return None. Defaults to None.
ascii_only : Boolean
If True only ASCII characters are used to construct the visualization
Returns
-------
str | None :
utf8 representation of the tree / forest
Examples
--------
>>> graph = nx.balanced_tree(r=2, h=3, create_using=nx.DiGraph)
>>> print(nx.forest_str(graph))
╙── 0
├─╼ 1
│ ├─╼ 3
│ │ ├─╼ 7
│ │ └─╼ 8
│ └─╼ 4
│ ├─╼ 9
│ └─╼ 10
└─╼ 2
├─╼ 5
│ ├─╼ 11
│ └─╼ 12
└─╼ 6
├─╼ 13
└─╼ 14
>>> graph = nx.balanced_tree(r=1, h=2, create_using=nx.Graph)
>>> print(nx.forest_str(graph))
╙── 0
└── 1
└── 2
>>> print(nx.forest_str(graph, ascii_only=True))
+-- 0
L-- 1
L-- 2
"""
msg = (
"\nforest_str is deprecated as of version 3.1 and will be removed "
"in version 3.3. Use generate_network_text or write_network_text "
"instead.\n"
)
warnings.warn(msg, DeprecationWarning)
if len(graph.nodes) > 0:
if not nx.is_forest(graph):
raise nx.NetworkXNotImplemented("input must be a forest or the empty graph")
printbuf = []
if write is None:
_write = printbuf.append
else:
_write = write
write_network_text(
graph,
_write,
with_labels=with_labels,
sources=sources,
ascii_only=ascii_only,
end="",
)
if write is None:
# Only return a string if the custom write function was not specified
return "\n".join(printbuf)
| (graph, with_labels=True, sources=None, write=None, ascii_only=False) |
30,666 | networkx.classes.function | freeze | Modify graph to prevent further change by adding or removing
nodes or edges.
Node and edge data can still be modified.
Parameters
----------
G : graph
A NetworkX graph
Examples
--------
>>> G = nx.path_graph(4)
>>> G = nx.freeze(G)
>>> try:
... G.add_edge(4, 5)
... except nx.NetworkXError as err:
... print(str(err))
Frozen graph can't be modified
Notes
-----
To "unfreeze" a graph you must make a copy by creating a new graph object:
>>> graph = nx.path_graph(4)
>>> frozen_graph = nx.freeze(graph)
>>> unfrozen_graph = nx.Graph(frozen_graph)
>>> nx.is_frozen(unfrozen_graph)
False
See Also
--------
is_frozen
| def freeze(G):
"""Modify graph to prevent further change by adding or removing
nodes or edges.
Node and edge data can still be modified.
Parameters
----------
G : graph
A NetworkX graph
Examples
--------
>>> G = nx.path_graph(4)
>>> G = nx.freeze(G)
>>> try:
... G.add_edge(4, 5)
... except nx.NetworkXError as err:
... print(str(err))
Frozen graph can't be modified
Notes
-----
To "unfreeze" a graph you must make a copy by creating a new graph object:
>>> graph = nx.path_graph(4)
>>> frozen_graph = nx.freeze(graph)
>>> unfrozen_graph = nx.Graph(frozen_graph)
>>> nx.is_frozen(unfrozen_graph)
False
See Also
--------
is_frozen
"""
G.add_node = frozen
G.add_nodes_from = frozen
G.remove_node = frozen
G.remove_nodes_from = frozen
G.add_edge = frozen
G.add_edges_from = frozen
G.add_weighted_edges_from = frozen
G.remove_edge = frozen
G.remove_edges_from = frozen
G.clear = frozen
G.clear_edges = frozen
G.frozen = True
return G
| (G) |
30,667 | networkx.convert | from_dict_of_dicts | Returns a graph from a dictionary of dictionaries.
Parameters
----------
d : dictionary of dictionaries
A dictionary of dictionaries adjacency representation.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
multigraph_input : bool (default False)
When True, the dict `d` is assumed
to be a dict-of-dict-of-dict-of-dict structure keyed by
node to neighbor to edge keys to edge data for multi-edges.
Otherwise this routine assumes dict-of-dict-of-dict keyed by
node to neighbor to edge data.
Examples
--------
>>> dod = {0: {1: {"weight": 1}}} # single edge (0,1)
>>> G = nx.from_dict_of_dicts(dod)
or
>>> G = nx.Graph(dod) # use Graph constructor
| null | (d, create_using=None, multigraph_input=False, *, backend=None, **backend_kwargs) |
30,668 | networkx.convert | from_dict_of_lists | Returns a graph from a dictionary of lists.
Parameters
----------
d : dictionary of lists
A dictionary of lists adjacency representation.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
Examples
--------
>>> dol = {0: [1]} # single edge (0,1)
>>> G = nx.from_dict_of_lists(dol)
or
>>> G = nx.Graph(dol) # use Graph constructor
| null | (d, create_using=None, *, backend=None, **backend_kwargs) |
30,669 | networkx.convert | from_edgelist | Returns a graph from a list of edges.
Parameters
----------
edgelist : list or iterator
Edge tuples
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
Examples
--------
>>> edgelist = [(0, 1)] # single edge (0,1)
>>> G = nx.from_edgelist(edgelist)
or
>>> G = nx.Graph(edgelist) # use Graph constructor
| null | (edgelist, create_using=None, *, backend=None, **backend_kwargs) |
30,670 | networkx.readwrite.graph6 | from_graph6_bytes | Read a simple undirected graph in graph6 format from bytes.
Parameters
----------
bytes_in : bytes
Data in graph6 format, without a trailing newline.
Returns
-------
G : Graph
Raises
------
NetworkXError
If bytes_in is unable to be parsed in graph6 format
ValueError
If any character ``c`` in bytes_in does not satisfy
``63 <= ord(c) < 127``.
Examples
--------
>>> G = nx.from_graph6_bytes(b"A_")
>>> sorted(G.edges())
[(0, 1)]
See Also
--------
read_graph6, write_graph6
References
----------
.. [1] Graph6 specification
<http://users.cecs.anu.edu.au/~bdm/data/formats.html>
| null | (bytes_in, *, backend=None, **backend_kwargs) |
30,671 | networkx.algorithms.tree.coding | from_nested_tuple | Returns the rooted tree corresponding to the given nested tuple.
The nested tuple representation of a tree is defined
recursively. The tree with one node and no edges is represented by
the empty tuple, ``()``. A tree with ``k`` subtrees is represented
by a tuple of length ``k`` in which each element is the nested tuple
representation of a subtree.
Parameters
----------
sequence : tuple
A nested tuple representing a rooted tree.
sensible_relabeling : bool
Whether to relabel the nodes of the tree so that nodes are
labeled in increasing order according to their breadth-first
search order from the root node.
Returns
-------
NetworkX graph
The tree corresponding to the given nested tuple, whose root
node is node 0. If ``sensible_labeling`` is ``True``, nodes will
be labeled in breadth-first search order starting from the root
node.
Notes
-----
This function is *not* the inverse of :func:`to_nested_tuple`; the
only guarantee is that the rooted trees are isomorphic.
See also
--------
to_nested_tuple
from_prufer_sequence
Examples
--------
Sensible relabeling ensures that the nodes are labeled from the root
starting at 0::
>>> balanced = (((), ()), ((), ()))
>>> T = nx.from_nested_tuple(balanced, sensible_relabeling=True)
>>> edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
>>> all((u, v) in T.edges() or (v, u) in T.edges() for (u, v) in edges)
True
| null | (sequence, sensible_relabeling=False, *, backend=None, **backend_kwargs) |
30,672 | networkx.convert_matrix | from_numpy_array | Returns a graph from a 2D NumPy array.
The 2D NumPy array is interpreted as an adjacency matrix for the graph.
Parameters
----------
A : a 2D numpy.ndarray
An adjacency matrix representation of a graph
parallel_edges : Boolean
If this is True, `create_using` is a multigraph, and `A` is an
integer array, then entry *(i, j)* in the array is interpreted as the
number of parallel edges joining vertices *i* and *j* in the graph.
If it is False, then the entries in the array are interpreted as
the weight of a single edge joining the vertices.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
edge_attr : String, optional (default="weight")
The attribute to which the array values are assigned on each edge. If
it is None, edge attributes will not be assigned.
Notes
-----
For directed graphs, explicitly mention create_using=nx.DiGraph,
and entry i,j of A corresponds to an edge from i to j.
If `create_using` is :class:`networkx.MultiGraph` or
:class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the
entries of `A` are of type :class:`int`, then this function returns a
multigraph (of the same type as `create_using`) with parallel edges.
If `create_using` indicates an undirected multigraph, then only the edges
indicated by the upper triangle of the array `A` will be added to the
graph.
If `edge_attr` is Falsy (False or None), edge attributes will not be
assigned, and the array data will be treated like a binary mask of
edge presence or absence. Otherwise, the attributes will be assigned
as follows:
If the NumPy array has a single data type for each array entry it
will be converted to an appropriate Python data type.
If the NumPy array has a user-specified compound data type the names
of the data fields will be used as attribute keys in the resulting
NetworkX graph.
See Also
--------
to_numpy_array
Examples
--------
Simple integer weights on edges:
>>> import numpy as np
>>> A = np.array([[1, 1], [2, 1]])
>>> G = nx.from_numpy_array(A)
>>> G.edges(data=True)
EdgeDataView([(0, 0, {'weight': 1}), (0, 1, {'weight': 2}), (1, 1, {'weight': 1})])
If `create_using` indicates a multigraph and the array has only integer
entries and `parallel_edges` is False, then the entries will be treated
as weights for edges joining the nodes (without creating parallel edges):
>>> A = np.array([[1, 1], [1, 2]])
>>> G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
>>> G[1][1]
AtlasView({0: {'weight': 2}})
If `create_using` indicates a multigraph and the array has only integer
entries and `parallel_edges` is True, then the entries will be treated
as the number of parallel edges joining those two vertices:
>>> A = np.array([[1, 1], [1, 2]])
>>> temp = nx.MultiGraph()
>>> G = nx.from_numpy_array(A, parallel_edges=True, create_using=temp)
>>> G[1][1]
AtlasView({0: {'weight': 1}, 1: {'weight': 1}})
User defined compound data type on edges:
>>> dt = [("weight", float), ("cost", int)]
>>> A = np.array([[(1.0, 2)]], dtype=dt)
>>> G = nx.from_numpy_array(A)
>>> G.edges()
EdgeView([(0, 0)])
>>> G[0][0]["cost"]
2
>>> G[0][0]["weight"]
1.0
| def to_numpy_array(
G,
nodelist=None,
dtype=None,
order=None,
multigraph_weight=sum,
weight="weight",
nonedge=0.0,
):
"""Returns the graph adjacency matrix as a NumPy array.
Parameters
----------
G : graph
The NetworkX graph used to construct the NumPy array.
nodelist : list, optional
The rows and columns are ordered according to the nodes in `nodelist`.
If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``.
dtype : NumPy data type, optional
A NumPy data type used to initialize the array. If None, then the NumPy
default is used. The dtype can be structured if `weight=None`, in which
case the dtype field names are used to look up edge attributes. The
result is a structured array where each named field in the dtype
corresponds to the adjacency for that edge attribute. See examples for
details.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. If None, then the NumPy default
is used.
multigraph_weight : callable, optional
An function that determines how weights in multigraphs are handled.
The function should accept a sequence of weights and return a single
value. The default is to sum the weights of the multiple edges.
weight : string or None optional (default = 'weight')
The edge attribute that holds the numerical value used for
the edge weight. If an edge does not have that attribute, then the
value 1 is used instead. `weight` must be ``None`` if a structured
dtype is used.
nonedge : array_like (default = 0.0)
The value used to represent non-edges in the adjacency matrix.
The array values corresponding to nonedges are typically set to zero.
However, this could be undesirable if there are array values
corresponding to actual edges that also have the value zero. If so,
one might prefer nonedges to have some other value, such as ``nan``.
Returns
-------
A : NumPy ndarray
Graph adjacency matrix
Raises
------
NetworkXError
If `dtype` is a structured dtype and `G` is a multigraph
ValueError
If `dtype` is a structured dtype and `weight` is not `None`
See Also
--------
from_numpy_array
Notes
-----
For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
Entries in the adjacency matrix are given by the `weight` edge attribute.
When an edge does not have a weight attribute, the value of the entry is
set to the number 1. For multiple (parallel) edges, the values of the
entries are determined by the `multigraph_weight` parameter. The default is
to sum the weight attributes for each of the parallel edges.
When `nodelist` does not contain every node in `G`, the adjacency matrix is
built from the subgraph of `G` that is induced by the nodes in `nodelist`.
The convention used for self-loop edges in graphs is to assign the
diagonal array entry value to the weight attribute of the edge
(or the number 1 if the edge has no weight attribute). If the
alternate convention of doubling the edge weight is desired the
resulting NumPy array can be modified as follows:
>>> import numpy as np
>>> G = nx.Graph([(1, 1)])
>>> A = nx.to_numpy_array(G)
>>> A
array([[1.]])
>>> A[np.diag_indices_from(A)] *= 2
>>> A
array([[2.]])
Examples
--------
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_numpy_array(G, nodelist=[0, 1, 2])
array([[0., 2., 0.],
[1., 0., 0.],
[0., 0., 4.]])
When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist`
and their edges are not included in the adjacency matrix. Here is an example:
>>> G = nx.Graph()
>>> G.add_edge(3, 1)
>>> G.add_edge(2, 0)
>>> G.add_edge(2, 1)
>>> G.add_edge(3, 0)
>>> nx.to_numpy_array(G, nodelist=[1, 2, 3])
array([[0., 1., 1.],
[1., 0., 0.],
[1., 0., 0.]])
This function can also be used to create adjacency matrices for multiple
edge attributes with structured dtypes:
>>> G = nx.Graph()
>>> G.add_edge(0, 1, weight=10)
>>> G.add_edge(1, 2, cost=5)
>>> G.add_edge(2, 3, weight=3, cost=-4.0)
>>> dtype = np.dtype([("weight", int), ("cost", float)])
>>> A = nx.to_numpy_array(G, dtype=dtype, weight=None)
>>> A["weight"]
array([[ 0, 10, 0, 0],
[10, 0, 1, 0],
[ 0, 1, 0, 3],
[ 0, 0, 3, 0]])
>>> A["cost"]
array([[ 0., 1., 0., 0.],
[ 1., 0., 5., 0.],
[ 0., 5., 0., -4.],
[ 0., 0., -4., 0.]])
As stated above, the argument "nonedge" is useful especially when there are
actually edges with weight 0 in the graph. Setting a nonedge value different than 0,
makes it much clearer to differentiate such 0-weighted edges and actual nonedge values.
>>> G = nx.Graph()
>>> G.add_edge(3, 1, weight=2)
>>> G.add_edge(2, 0, weight=0)
>>> G.add_edge(2, 1, weight=0)
>>> G.add_edge(3, 0, weight=1)
>>> nx.to_numpy_array(G, nonedge=-1.0)
array([[-1., 2., -1., 1.],
[ 2., -1., 0., -1.],
[-1., 0., -1., 0.],
[ 1., -1., 0., -1.]])
"""
import numpy as np
if nodelist is None:
nodelist = list(G)
nlen = len(nodelist)
# Input validation
nodeset = set(nodelist)
if nodeset - set(G):
raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G")
if len(nodeset) < nlen:
raise nx.NetworkXError("nodelist contains duplicates.")
A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order)
# Corner cases: empty nodelist or graph without any edges
if nlen == 0 or G.number_of_edges() == 0:
return A
# If dtype is structured and weight is None, use dtype field names as
# edge attributes
edge_attrs = None # Only single edge attribute by default
if A.dtype.names:
if weight is None:
edge_attrs = dtype.names
else:
raise ValueError(
"Specifying `weight` not supported for structured dtypes\n."
"To create adjacency matrices from structured dtypes, use `weight=None`."
)
# Map nodes to row/col in matrix
idx = dict(zip(nodelist, range(nlen)))
if len(nodelist) < len(G):
G = G.subgraph(nodelist).copy()
# Collect all edge weights and reduce with `multigraph_weights`
if G.is_multigraph():
if edge_attrs:
raise nx.NetworkXError(
"Structured arrays are not supported for MultiGraphs"
)
d = defaultdict(list)
for u, v, wt in G.edges(data=weight, default=1.0):
d[(idx[u], idx[v])].append(wt)
i, j = np.array(list(d.keys())).T # indices
wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights
else:
i, j, wts = [], [], []
# Special branch: multi-attr adjacency from structured dtypes
if edge_attrs:
# Extract edges with all data
for u, v, data in G.edges(data=True):
i.append(idx[u])
j.append(idx[v])
wts.append(data)
# Map each attribute to the appropriate named field in the
# structured dtype
for attr in edge_attrs:
attr_data = [wt.get(attr, 1.0) for wt in wts]
A[attr][i, j] = attr_data
if not G.is_directed():
A[attr][j, i] = attr_data
return A
for u, v, wt in G.edges(data=weight, default=1.0):
i.append(idx[u])
j.append(idx[v])
wts.append(wt)
# Set array values with advanced indexing
A[i, j] = wts
if not G.is_directed():
A[j, i] = wts
return A
| (A, parallel_edges=False, create_using=None, edge_attr='weight', *, backend=None, **backend_kwargs) |
30,673 | networkx.convert_matrix | from_pandas_adjacency | Returns a graph from Pandas DataFrame.
The Pandas DataFrame is interpreted as an adjacency matrix for the graph.
Parameters
----------
df : Pandas DataFrame
An adjacency matrix representation of a graph
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
Notes
-----
For directed graphs, explicitly mention create_using=nx.DiGraph,
and entry i,j of df corresponds to an edge from i to j.
If `df` has a single data type for each entry it will be converted to an
appropriate Python data type.
If you have node attributes stored in a separate dataframe `df_nodes`,
you can load those attributes to the graph `G` using the following code:
```
df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]})
G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows())
```
If `df` has a user-specified compound data type the names
of the data fields will be used as attribute keys in the resulting
NetworkX graph.
See Also
--------
to_pandas_adjacency
Examples
--------
Simple integer weights on edges:
>>> import pandas as pd
>>> pd.options.display.max_columns = 20
>>> df = pd.DataFrame([[1, 1], [2, 1]])
>>> df
0 1
0 1 1
1 2 1
>>> G = nx.from_pandas_adjacency(df)
>>> G.name = "Graph from pandas adjacency matrix"
>>> print(G)
Graph named 'Graph from pandas adjacency matrix' with 2 nodes and 3 edges
| def to_numpy_array(
G,
nodelist=None,
dtype=None,
order=None,
multigraph_weight=sum,
weight="weight",
nonedge=0.0,
):
"""Returns the graph adjacency matrix as a NumPy array.
Parameters
----------
G : graph
The NetworkX graph used to construct the NumPy array.
nodelist : list, optional
The rows and columns are ordered according to the nodes in `nodelist`.
If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``.
dtype : NumPy data type, optional
A NumPy data type used to initialize the array. If None, then the NumPy
default is used. The dtype can be structured if `weight=None`, in which
case the dtype field names are used to look up edge attributes. The
result is a structured array where each named field in the dtype
corresponds to the adjacency for that edge attribute. See examples for
details.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. If None, then the NumPy default
is used.
multigraph_weight : callable, optional
An function that determines how weights in multigraphs are handled.
The function should accept a sequence of weights and return a single
value. The default is to sum the weights of the multiple edges.
weight : string or None optional (default = 'weight')
The edge attribute that holds the numerical value used for
the edge weight. If an edge does not have that attribute, then the
value 1 is used instead. `weight` must be ``None`` if a structured
dtype is used.
nonedge : array_like (default = 0.0)
The value used to represent non-edges in the adjacency matrix.
The array values corresponding to nonedges are typically set to zero.
However, this could be undesirable if there are array values
corresponding to actual edges that also have the value zero. If so,
one might prefer nonedges to have some other value, such as ``nan``.
Returns
-------
A : NumPy ndarray
Graph adjacency matrix
Raises
------
NetworkXError
If `dtype` is a structured dtype and `G` is a multigraph
ValueError
If `dtype` is a structured dtype and `weight` is not `None`
See Also
--------
from_numpy_array
Notes
-----
For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
Entries in the adjacency matrix are given by the `weight` edge attribute.
When an edge does not have a weight attribute, the value of the entry is
set to the number 1. For multiple (parallel) edges, the values of the
entries are determined by the `multigraph_weight` parameter. The default is
to sum the weight attributes for each of the parallel edges.
When `nodelist` does not contain every node in `G`, the adjacency matrix is
built from the subgraph of `G` that is induced by the nodes in `nodelist`.
The convention used for self-loop edges in graphs is to assign the
diagonal array entry value to the weight attribute of the edge
(or the number 1 if the edge has no weight attribute). If the
alternate convention of doubling the edge weight is desired the
resulting NumPy array can be modified as follows:
>>> import numpy as np
>>> G = nx.Graph([(1, 1)])
>>> A = nx.to_numpy_array(G)
>>> A
array([[1.]])
>>> A[np.diag_indices_from(A)] *= 2
>>> A
array([[2.]])
Examples
--------
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_numpy_array(G, nodelist=[0, 1, 2])
array([[0., 2., 0.],
[1., 0., 0.],
[0., 0., 4.]])
When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist`
and their edges are not included in the adjacency matrix. Here is an example:
>>> G = nx.Graph()
>>> G.add_edge(3, 1)
>>> G.add_edge(2, 0)
>>> G.add_edge(2, 1)
>>> G.add_edge(3, 0)
>>> nx.to_numpy_array(G, nodelist=[1, 2, 3])
array([[0., 1., 1.],
[1., 0., 0.],
[1., 0., 0.]])
This function can also be used to create adjacency matrices for multiple
edge attributes with structured dtypes:
>>> G = nx.Graph()
>>> G.add_edge(0, 1, weight=10)
>>> G.add_edge(1, 2, cost=5)
>>> G.add_edge(2, 3, weight=3, cost=-4.0)
>>> dtype = np.dtype([("weight", int), ("cost", float)])
>>> A = nx.to_numpy_array(G, dtype=dtype, weight=None)
>>> A["weight"]
array([[ 0, 10, 0, 0],
[10, 0, 1, 0],
[ 0, 1, 0, 3],
[ 0, 0, 3, 0]])
>>> A["cost"]
array([[ 0., 1., 0., 0.],
[ 1., 0., 5., 0.],
[ 0., 5., 0., -4.],
[ 0., 0., -4., 0.]])
As stated above, the argument "nonedge" is useful especially when there are
actually edges with weight 0 in the graph. Setting a nonedge value different than 0,
makes it much clearer to differentiate such 0-weighted edges and actual nonedge values.
>>> G = nx.Graph()
>>> G.add_edge(3, 1, weight=2)
>>> G.add_edge(2, 0, weight=0)
>>> G.add_edge(2, 1, weight=0)
>>> G.add_edge(3, 0, weight=1)
>>> nx.to_numpy_array(G, nonedge=-1.0)
array([[-1., 2., -1., 1.],
[ 2., -1., 0., -1.],
[-1., 0., -1., 0.],
[ 1., -1., 0., -1.]])
"""
import numpy as np
if nodelist is None:
nodelist = list(G)
nlen = len(nodelist)
# Input validation
nodeset = set(nodelist)
if nodeset - set(G):
raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G")
if len(nodeset) < nlen:
raise nx.NetworkXError("nodelist contains duplicates.")
A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order)
# Corner cases: empty nodelist or graph without any edges
if nlen == 0 or G.number_of_edges() == 0:
return A
# If dtype is structured and weight is None, use dtype field names as
# edge attributes
edge_attrs = None # Only single edge attribute by default
if A.dtype.names:
if weight is None:
edge_attrs = dtype.names
else:
raise ValueError(
"Specifying `weight` not supported for structured dtypes\n."
"To create adjacency matrices from structured dtypes, use `weight=None`."
)
# Map nodes to row/col in matrix
idx = dict(zip(nodelist, range(nlen)))
if len(nodelist) < len(G):
G = G.subgraph(nodelist).copy()
# Collect all edge weights and reduce with `multigraph_weights`
if G.is_multigraph():
if edge_attrs:
raise nx.NetworkXError(
"Structured arrays are not supported for MultiGraphs"
)
d = defaultdict(list)
for u, v, wt in G.edges(data=weight, default=1.0):
d[(idx[u], idx[v])].append(wt)
i, j = np.array(list(d.keys())).T # indices
wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights
else:
i, j, wts = [], [], []
# Special branch: multi-attr adjacency from structured dtypes
if edge_attrs:
# Extract edges with all data
for u, v, data in G.edges(data=True):
i.append(idx[u])
j.append(idx[v])
wts.append(data)
# Map each attribute to the appropriate named field in the
# structured dtype
for attr in edge_attrs:
attr_data = [wt.get(attr, 1.0) for wt in wts]
A[attr][i, j] = attr_data
if not G.is_directed():
A[attr][j, i] = attr_data
return A
for u, v, wt in G.edges(data=weight, default=1.0):
i.append(idx[u])
j.append(idx[v])
wts.append(wt)
# Set array values with advanced indexing
A[i, j] = wts
if not G.is_directed():
A[j, i] = wts
return A
| (df, create_using=None, *, backend=None, **backend_kwargs) |
30,674 | networkx.convert_matrix | from_pandas_edgelist | Returns a graph from Pandas DataFrame containing an edge list.
The Pandas DataFrame should contain at least two columns of node names and
zero or more columns of edge attributes. Each row will be processed as one
edge instance.
Note: This function iterates over DataFrame.values, which is not
guaranteed to retain the data type across columns in the row. This is only
a problem if your row is entirely numeric and a mix of ints and floats. In
that case, all values will be returned as floats. See the
DataFrame.iterrows documentation for an example.
Parameters
----------
df : Pandas DataFrame
An edge list representation of a graph
source : str or int
A valid column name (string or integer) for the source nodes (for the
directed case).
target : str or int
A valid column name (string or integer) for the target nodes (for the
directed case).
edge_attr : str or int, iterable, True, or None
A valid column name (str or int) or iterable of column names that are
used to retrieve items and add them to the graph as edge attributes.
If `True`, all of the remaining columns will be added.
If `None`, no edge attributes are added to the graph.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
edge_key : str or None, optional (default=None)
A valid column name for the edge keys (for a MultiGraph). The values in
this column are used for the edge keys when adding edges if create_using
is a multigraph.
If you have node attributes stored in a separate dataframe `df_nodes`,
you can load those attributes to the graph `G` using the following code:
```
df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]})
G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows())
```
See Also
--------
to_pandas_edgelist
Examples
--------
Simple integer weights on edges:
>>> import pandas as pd
>>> pd.options.display.max_columns = 20
>>> import numpy as np
>>> rng = np.random.RandomState(seed=5)
>>> ints = rng.randint(1, 11, size=(3, 2))
>>> a = ["A", "B", "C"]
>>> b = ["D", "A", "E"]
>>> df = pd.DataFrame(ints, columns=["weight", "cost"])
>>> df[0] = a
>>> df["b"] = b
>>> df[["weight", "cost", 0, "b"]]
weight cost 0 b
0 4 7 A D
1 7 1 B A
2 10 9 C E
>>> G = nx.from_pandas_edgelist(df, 0, "b", ["weight", "cost"])
>>> G["E"]["C"]["weight"]
10
>>> G["E"]["C"]["cost"]
9
>>> edges = pd.DataFrame(
... {
... "source": [0, 1, 2],
... "target": [2, 2, 3],
... "weight": [3, 4, 5],
... "color": ["red", "blue", "blue"],
... }
... )
>>> G = nx.from_pandas_edgelist(edges, edge_attr=True)
>>> G[0][2]["color"]
'red'
Build multigraph with custom keys:
>>> edges = pd.DataFrame(
... {
... "source": [0, 1, 2, 0],
... "target": [2, 2, 3, 2],
... "my_edge_key": ["A", "B", "C", "D"],
... "weight": [3, 4, 5, 6],
... "color": ["red", "blue", "blue", "blue"],
... }
... )
>>> G = nx.from_pandas_edgelist(
... edges,
... edge_key="my_edge_key",
... edge_attr=["weight", "color"],
... create_using=nx.MultiGraph(),
... )
>>> G[0][2]
AtlasView({'A': {'weight': 3, 'color': 'red'}, 'D': {'weight': 6, 'color': 'blue'}})
| def to_numpy_array(
G,
nodelist=None,
dtype=None,
order=None,
multigraph_weight=sum,
weight="weight",
nonedge=0.0,
):
"""Returns the graph adjacency matrix as a NumPy array.
Parameters
----------
G : graph
The NetworkX graph used to construct the NumPy array.
nodelist : list, optional
The rows and columns are ordered according to the nodes in `nodelist`.
If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``.
dtype : NumPy data type, optional
A NumPy data type used to initialize the array. If None, then the NumPy
default is used. The dtype can be structured if `weight=None`, in which
case the dtype field names are used to look up edge attributes. The
result is a structured array where each named field in the dtype
corresponds to the adjacency for that edge attribute. See examples for
details.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. If None, then the NumPy default
is used.
multigraph_weight : callable, optional
An function that determines how weights in multigraphs are handled.
The function should accept a sequence of weights and return a single
value. The default is to sum the weights of the multiple edges.
weight : string or None optional (default = 'weight')
The edge attribute that holds the numerical value used for
the edge weight. If an edge does not have that attribute, then the
value 1 is used instead. `weight` must be ``None`` if a structured
dtype is used.
nonedge : array_like (default = 0.0)
The value used to represent non-edges in the adjacency matrix.
The array values corresponding to nonedges are typically set to zero.
However, this could be undesirable if there are array values
corresponding to actual edges that also have the value zero. If so,
one might prefer nonedges to have some other value, such as ``nan``.
Returns
-------
A : NumPy ndarray
Graph adjacency matrix
Raises
------
NetworkXError
If `dtype` is a structured dtype and `G` is a multigraph
ValueError
If `dtype` is a structured dtype and `weight` is not `None`
See Also
--------
from_numpy_array
Notes
-----
For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
Entries in the adjacency matrix are given by the `weight` edge attribute.
When an edge does not have a weight attribute, the value of the entry is
set to the number 1. For multiple (parallel) edges, the values of the
entries are determined by the `multigraph_weight` parameter. The default is
to sum the weight attributes for each of the parallel edges.
When `nodelist` does not contain every node in `G`, the adjacency matrix is
built from the subgraph of `G` that is induced by the nodes in `nodelist`.
The convention used for self-loop edges in graphs is to assign the
diagonal array entry value to the weight attribute of the edge
(or the number 1 if the edge has no weight attribute). If the
alternate convention of doubling the edge weight is desired the
resulting NumPy array can be modified as follows:
>>> import numpy as np
>>> G = nx.Graph([(1, 1)])
>>> A = nx.to_numpy_array(G)
>>> A
array([[1.]])
>>> A[np.diag_indices_from(A)] *= 2
>>> A
array([[2.]])
Examples
--------
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_numpy_array(G, nodelist=[0, 1, 2])
array([[0., 2., 0.],
[1., 0., 0.],
[0., 0., 4.]])
When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist`
and their edges are not included in the adjacency matrix. Here is an example:
>>> G = nx.Graph()
>>> G.add_edge(3, 1)
>>> G.add_edge(2, 0)
>>> G.add_edge(2, 1)
>>> G.add_edge(3, 0)
>>> nx.to_numpy_array(G, nodelist=[1, 2, 3])
array([[0., 1., 1.],
[1., 0., 0.],
[1., 0., 0.]])
This function can also be used to create adjacency matrices for multiple
edge attributes with structured dtypes:
>>> G = nx.Graph()
>>> G.add_edge(0, 1, weight=10)
>>> G.add_edge(1, 2, cost=5)
>>> G.add_edge(2, 3, weight=3, cost=-4.0)
>>> dtype = np.dtype([("weight", int), ("cost", float)])
>>> A = nx.to_numpy_array(G, dtype=dtype, weight=None)
>>> A["weight"]
array([[ 0, 10, 0, 0],
[10, 0, 1, 0],
[ 0, 1, 0, 3],
[ 0, 0, 3, 0]])
>>> A["cost"]
array([[ 0., 1., 0., 0.],
[ 1., 0., 5., 0.],
[ 0., 5., 0., -4.],
[ 0., 0., -4., 0.]])
As stated above, the argument "nonedge" is useful especially when there are
actually edges with weight 0 in the graph. Setting a nonedge value different than 0,
makes it much clearer to differentiate such 0-weighted edges and actual nonedge values.
>>> G = nx.Graph()
>>> G.add_edge(3, 1, weight=2)
>>> G.add_edge(2, 0, weight=0)
>>> G.add_edge(2, 1, weight=0)
>>> G.add_edge(3, 0, weight=1)
>>> nx.to_numpy_array(G, nonedge=-1.0)
array([[-1., 2., -1., 1.],
[ 2., -1., 0., -1.],
[-1., 0., -1., 0.],
[ 1., -1., 0., -1.]])
"""
import numpy as np
if nodelist is None:
nodelist = list(G)
nlen = len(nodelist)
# Input validation
nodeset = set(nodelist)
if nodeset - set(G):
raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G")
if len(nodeset) < nlen:
raise nx.NetworkXError("nodelist contains duplicates.")
A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order)
# Corner cases: empty nodelist or graph without any edges
if nlen == 0 or G.number_of_edges() == 0:
return A
# If dtype is structured and weight is None, use dtype field names as
# edge attributes
edge_attrs = None # Only single edge attribute by default
if A.dtype.names:
if weight is None:
edge_attrs = dtype.names
else:
raise ValueError(
"Specifying `weight` not supported for structured dtypes\n."
"To create adjacency matrices from structured dtypes, use `weight=None`."
)
# Map nodes to row/col in matrix
idx = dict(zip(nodelist, range(nlen)))
if len(nodelist) < len(G):
G = G.subgraph(nodelist).copy()
# Collect all edge weights and reduce with `multigraph_weights`
if G.is_multigraph():
if edge_attrs:
raise nx.NetworkXError(
"Structured arrays are not supported for MultiGraphs"
)
d = defaultdict(list)
for u, v, wt in G.edges(data=weight, default=1.0):
d[(idx[u], idx[v])].append(wt)
i, j = np.array(list(d.keys())).T # indices
wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights
else:
i, j, wts = [], [], []
# Special branch: multi-attr adjacency from structured dtypes
if edge_attrs:
# Extract edges with all data
for u, v, data in G.edges(data=True):
i.append(idx[u])
j.append(idx[v])
wts.append(data)
# Map each attribute to the appropriate named field in the
# structured dtype
for attr in edge_attrs:
attr_data = [wt.get(attr, 1.0) for wt in wts]
A[attr][i, j] = attr_data
if not G.is_directed():
A[attr][j, i] = attr_data
return A
for u, v, wt in G.edges(data=weight, default=1.0):
i.append(idx[u])
j.append(idx[v])
wts.append(wt)
# Set array values with advanced indexing
A[i, j] = wts
if not G.is_directed():
A[j, i] = wts
return A
| (df, source='source', target='target', edge_attr=None, create_using=None, edge_key=None, *, backend=None, **backend_kwargs) |
30,675 | networkx.algorithms.tree.coding | from_prufer_sequence | Returns the tree corresponding to the given Prüfer sequence.
A *Prüfer sequence* is a list of *n* - 2 numbers between 0 and
*n* - 1, inclusive. The tree corresponding to a given Prüfer
sequence can be recovered by repeatedly joining a node in the
sequence with a node with the smallest potential degree according to
the sequence.
Parameters
----------
sequence : list
A Prüfer sequence, which is a list of *n* - 2 integers between
zero and *n* - 1, inclusive.
Returns
-------
NetworkX graph
The tree corresponding to the given Prüfer sequence.
Raises
------
NetworkXError
If the Prüfer sequence is not valid.
Notes
-----
There is a bijection from labeled trees to Prüfer sequences. This
function is the inverse of the :func:`from_prufer_sequence` function.
Sometimes Prüfer sequences use nodes labeled from 1 to *n* instead
of from 0 to *n* - 1. This function requires nodes to be labeled in
the latter form. You can use :func:`networkx.relabel_nodes` to
relabel the nodes of your tree to the appropriate format.
This implementation is from [1]_ and has a running time of
$O(n)$.
References
----------
.. [1] Wang, Xiaodong, Lei Wang, and Yingjie Wu.
"An optimal algorithm for Prufer codes."
*Journal of Software Engineering and Applications* 2.02 (2009): 111.
<https://doi.org/10.4236/jsea.2009.22016>
See also
--------
from_nested_tuple
to_prufer_sequence
Examples
--------
There is a bijection between Prüfer sequences and labeled trees, so
this function is the inverse of the :func:`to_prufer_sequence`
function:
>>> edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)]
>>> tree = nx.Graph(edges)
>>> sequence = nx.to_prufer_sequence(tree)
>>> sequence
[3, 3, 3, 4]
>>> tree2 = nx.from_prufer_sequence(sequence)
>>> list(tree2.edges()) == edges
True
| null | (sequence, *, backend=None, **backend_kwargs) |
30,676 | networkx.convert_matrix | from_scipy_sparse_array | Creates a new graph from an adjacency matrix given as a SciPy sparse
array.
Parameters
----------
A: scipy.sparse array
An adjacency matrix representation of a graph
parallel_edges : Boolean
If this is True, `create_using` is a multigraph, and `A` is an
integer matrix, then entry *(i, j)* in the matrix is interpreted as the
number of parallel edges joining vertices *i* and *j* in the graph.
If it is False, then the entries in the matrix are interpreted as
the weight of a single edge joining the vertices.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
edge_attribute: string
Name of edge attribute to store matrix numeric value. The data will
have the same type as the matrix entry (int, float, (real,imag)).
Notes
-----
For directed graphs, explicitly mention create_using=nx.DiGraph,
and entry i,j of A corresponds to an edge from i to j.
If `create_using` is :class:`networkx.MultiGraph` or
:class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the
entries of `A` are of type :class:`int`, then this function returns a
multigraph (constructed from `create_using`) with parallel edges.
In this case, `edge_attribute` will be ignored.
If `create_using` indicates an undirected multigraph, then only the edges
indicated by the upper triangle of the matrix `A` will be added to the
graph.
Examples
--------
>>> import scipy as sp
>>> A = sp.sparse.eye(2, 2, 1)
>>> G = nx.from_scipy_sparse_array(A)
If `create_using` indicates a multigraph and the matrix has only integer
entries and `parallel_edges` is False, then the entries will be treated
as weights for edges joining the nodes (without creating parallel edges):
>>> A = sp.sparse.csr_array([[1, 1], [1, 2]])
>>> G = nx.from_scipy_sparse_array(A, create_using=nx.MultiGraph)
>>> G[1][1]
AtlasView({0: {'weight': 2}})
If `create_using` indicates a multigraph and the matrix has only integer
entries and `parallel_edges` is True, then the entries will be treated
as the number of parallel edges joining those two vertices:
>>> A = sp.sparse.csr_array([[1, 1], [1, 2]])
>>> G = nx.from_scipy_sparse_array(A, parallel_edges=True, create_using=nx.MultiGraph)
>>> G[1][1]
AtlasView({0: {'weight': 1}, 1: {'weight': 1}})
| def to_numpy_array(
G,
nodelist=None,
dtype=None,
order=None,
multigraph_weight=sum,
weight="weight",
nonedge=0.0,
):
"""Returns the graph adjacency matrix as a NumPy array.
Parameters
----------
G : graph
The NetworkX graph used to construct the NumPy array.
nodelist : list, optional
The rows and columns are ordered according to the nodes in `nodelist`.
If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``.
dtype : NumPy data type, optional
A NumPy data type used to initialize the array. If None, then the NumPy
default is used. The dtype can be structured if `weight=None`, in which
case the dtype field names are used to look up edge attributes. The
result is a structured array where each named field in the dtype
corresponds to the adjacency for that edge attribute. See examples for
details.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. If None, then the NumPy default
is used.
multigraph_weight : callable, optional
An function that determines how weights in multigraphs are handled.
The function should accept a sequence of weights and return a single
value. The default is to sum the weights of the multiple edges.
weight : string or None optional (default = 'weight')
The edge attribute that holds the numerical value used for
the edge weight. If an edge does not have that attribute, then the
value 1 is used instead. `weight` must be ``None`` if a structured
dtype is used.
nonedge : array_like (default = 0.0)
The value used to represent non-edges in the adjacency matrix.
The array values corresponding to nonedges are typically set to zero.
However, this could be undesirable if there are array values
corresponding to actual edges that also have the value zero. If so,
one might prefer nonedges to have some other value, such as ``nan``.
Returns
-------
A : NumPy ndarray
Graph adjacency matrix
Raises
------
NetworkXError
If `dtype` is a structured dtype and `G` is a multigraph
ValueError
If `dtype` is a structured dtype and `weight` is not `None`
See Also
--------
from_numpy_array
Notes
-----
For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``.
Entries in the adjacency matrix are given by the `weight` edge attribute.
When an edge does not have a weight attribute, the value of the entry is
set to the number 1. For multiple (parallel) edges, the values of the
entries are determined by the `multigraph_weight` parameter. The default is
to sum the weight attributes for each of the parallel edges.
When `nodelist` does not contain every node in `G`, the adjacency matrix is
built from the subgraph of `G` that is induced by the nodes in `nodelist`.
The convention used for self-loop edges in graphs is to assign the
diagonal array entry value to the weight attribute of the edge
(or the number 1 if the edge has no weight attribute). If the
alternate convention of doubling the edge weight is desired the
resulting NumPy array can be modified as follows:
>>> import numpy as np
>>> G = nx.Graph([(1, 1)])
>>> A = nx.to_numpy_array(G)
>>> A
array([[1.]])
>>> A[np.diag_indices_from(A)] *= 2
>>> A
array([[2.]])
Examples
--------
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_numpy_array(G, nodelist=[0, 1, 2])
array([[0., 2., 0.],
[1., 0., 0.],
[0., 0., 4.]])
When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist`
and their edges are not included in the adjacency matrix. Here is an example:
>>> G = nx.Graph()
>>> G.add_edge(3, 1)
>>> G.add_edge(2, 0)
>>> G.add_edge(2, 1)
>>> G.add_edge(3, 0)
>>> nx.to_numpy_array(G, nodelist=[1, 2, 3])
array([[0., 1., 1.],
[1., 0., 0.],
[1., 0., 0.]])
This function can also be used to create adjacency matrices for multiple
edge attributes with structured dtypes:
>>> G = nx.Graph()
>>> G.add_edge(0, 1, weight=10)
>>> G.add_edge(1, 2, cost=5)
>>> G.add_edge(2, 3, weight=3, cost=-4.0)
>>> dtype = np.dtype([("weight", int), ("cost", float)])
>>> A = nx.to_numpy_array(G, dtype=dtype, weight=None)
>>> A["weight"]
array([[ 0, 10, 0, 0],
[10, 0, 1, 0],
[ 0, 1, 0, 3],
[ 0, 0, 3, 0]])
>>> A["cost"]
array([[ 0., 1., 0., 0.],
[ 1., 0., 5., 0.],
[ 0., 5., 0., -4.],
[ 0., 0., -4., 0.]])
As stated above, the argument "nonedge" is useful especially when there are
actually edges with weight 0 in the graph. Setting a nonedge value different than 0,
makes it much clearer to differentiate such 0-weighted edges and actual nonedge values.
>>> G = nx.Graph()
>>> G.add_edge(3, 1, weight=2)
>>> G.add_edge(2, 0, weight=0)
>>> G.add_edge(2, 1, weight=0)
>>> G.add_edge(3, 0, weight=1)
>>> nx.to_numpy_array(G, nonedge=-1.0)
array([[-1., 2., -1., 1.],
[ 2., -1., 0., -1.],
[-1., 0., -1., 0.],
[ 1., -1., 0., -1.]])
"""
import numpy as np
if nodelist is None:
nodelist = list(G)
nlen = len(nodelist)
# Input validation
nodeset = set(nodelist)
if nodeset - set(G):
raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G")
if len(nodeset) < nlen:
raise nx.NetworkXError("nodelist contains duplicates.")
A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order)
# Corner cases: empty nodelist or graph without any edges
if nlen == 0 or G.number_of_edges() == 0:
return A
# If dtype is structured and weight is None, use dtype field names as
# edge attributes
edge_attrs = None # Only single edge attribute by default
if A.dtype.names:
if weight is None:
edge_attrs = dtype.names
else:
raise ValueError(
"Specifying `weight` not supported for structured dtypes\n."
"To create adjacency matrices from structured dtypes, use `weight=None`."
)
# Map nodes to row/col in matrix
idx = dict(zip(nodelist, range(nlen)))
if len(nodelist) < len(G):
G = G.subgraph(nodelist).copy()
# Collect all edge weights and reduce with `multigraph_weights`
if G.is_multigraph():
if edge_attrs:
raise nx.NetworkXError(
"Structured arrays are not supported for MultiGraphs"
)
d = defaultdict(list)
for u, v, wt in G.edges(data=weight, default=1.0):
d[(idx[u], idx[v])].append(wt)
i, j = np.array(list(d.keys())).T # indices
wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights
else:
i, j, wts = [], [], []
# Special branch: multi-attr adjacency from structured dtypes
if edge_attrs:
# Extract edges with all data
for u, v, data in G.edges(data=True):
i.append(idx[u])
j.append(idx[v])
wts.append(data)
# Map each attribute to the appropriate named field in the
# structured dtype
for attr in edge_attrs:
attr_data = [wt.get(attr, 1.0) for wt in wts]
A[attr][i, j] = attr_data
if not G.is_directed():
A[attr][j, i] = attr_data
return A
for u, v, wt in G.edges(data=weight, default=1.0):
i.append(idx[u])
j.append(idx[v])
wts.append(wt)
# Set array values with advanced indexing
A[i, j] = wts
if not G.is_directed():
A[j, i] = wts
return A
| (A, parallel_edges=False, create_using=None, edge_attribute='weight', *, backend=None, **backend_kwargs) |
30,677 | networkx.readwrite.sparse6 | from_sparse6_bytes | Read an undirected graph in sparse6 format from string.
Parameters
----------
string : string
Data in sparse6 format
Returns
-------
G : Graph
Raises
------
NetworkXError
If the string is unable to be parsed in sparse6 format
Examples
--------
>>> G = nx.from_sparse6_bytes(b":A_")
>>> sorted(G.edges())
[(0, 1), (0, 1), (0, 1)]
See Also
--------
read_sparse6, write_sparse6
References
----------
.. [1] Sparse6 specification
<https://users.cecs.anu.edu.au/~bdm/data/formats.html>
| null | (string, *, backend=None, **backend_kwargs) |
30,678 | networkx.generators.small | frucht_graph |
Returns the Frucht Graph.
The Frucht Graph is the smallest cubical graph whose
automorphism group consists only of the identity element [1]_.
It has 12 nodes and 18 edges and no nontrivial symmetries.
It is planar and Hamiltonian [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
Frucht Graph with 12 nodes and 18 edges
References
----------
.. [1] https://en.wikipedia.org/wiki/Frucht_graph
.. [2] https://mathworld.wolfram.com/FruchtGraph.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,679 | networkx.drawing.layout | spring_layout | Position nodes using Fruchterman-Reingold force-directed algorithm.
The algorithm simulates a force-directed representation of the network
treating edges as springs holding nodes close, while treating nodes
as repelling objects, sometimes called an anti-gravity force.
Simulation continues until the positions are close to an equilibrium.
There are some hard-coded values: minimal distance between
nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
During the simulation, `k` helps determine the distance between nodes,
though `scale` and `center` determine the size and place after
rescaling occurs at the end of the simulation.
Fixing some nodes doesn't allow them to move in the simulation.
It also turns off the rescaling feature at the simulation's end.
In addition, setting `scale` to `None` turns off rescaling.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G.
k : float (default=None)
Optimal distance between nodes. If None the distance is set to
1/sqrt(n) where n is the number of nodes. Increase this value
to move nodes farther apart.
pos : dict or None optional (default=None)
Initial positions for nodes as a dictionary with node as keys
and values as a coordinate list or tuple. If None, then use
random initial positions.
fixed : list or None optional (default=None)
Nodes to keep fixed at initial position.
Nodes not in ``G.nodes`` are ignored.
ValueError raised if `fixed` specified and `pos` not.
iterations : int optional (default=50)
Maximum number of iterations taken
threshold: float optional (default = 1e-4)
Threshold for relative error in node position changes.
The iteration stops if the error is below this threshold.
weight : string or None optional (default='weight')
The edge attribute that holds the numerical value used for
the edge weight. Larger means a stronger attractive force.
If None, then all edge weights are 1.
scale : number or None (default: 1)
Scale factor for positions. Not used unless `fixed is None`.
If scale is None, no rescaling is performed.
center : array-like or None
Coordinate pair around which to center the layout.
Not used unless `fixed is None`.
dim : int
Dimension of layout.
seed : int, RandomState instance or None optional (default=None)
Set the random state for deterministic node layouts.
If int, `seed` is the seed used by the random number generator,
if numpy.random.RandomState instance, `seed` is the random
number generator,
if None, the random number generator is the RandomState instance used
by numpy.random.
Returns
-------
pos : dict
A dictionary of positions keyed by node
Examples
--------
>>> G = nx.path_graph(4)
>>> pos = nx.spring_layout(G)
# The same using longer but equivalent function name
>>> pos = nx.fruchterman_reingold_layout(G)
| def spectral_layout(G, weight="weight", scale=1, center=None, dim=2):
"""Position nodes using the eigenvectors of the graph Laplacian.
Using the unnormalized Laplacian, the layout shows possible clusters of
nodes which are an approximation of the ratio cut. If dim is the number of
dimensions then the positions are the entries of the dim eigenvectors
corresponding to the ascending eigenvalues starting from the second one.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G.
weight : string or None optional (default='weight')
The edge attribute that holds the numerical value used for
the edge weight. If None, then all edge weights are 1.
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.
Returns
-------
pos : dict
A dictionary of positions keyed by node
Examples
--------
>>> G = nx.path_graph(4)
>>> pos = nx.spectral_layout(G)
Notes
-----
Directed graphs will be considered as undirected graphs when
positioning the nodes.
For larger graphs (>500 nodes) this will use the SciPy sparse
eigenvalue solver (ARPACK).
"""
# handle some special cases that break the eigensolvers
import numpy as np
G, center = _process_params(G, center, dim)
if len(G) <= 2:
if len(G) == 0:
pos = np.array([])
elif len(G) == 1:
pos = np.array([center])
else:
pos = np.array([np.zeros(dim), np.array(center) * 2.0])
return dict(zip(G, pos))
try:
# Sparse matrix
if len(G) < 500: # dense solver is faster for small graphs
raise ValueError
A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
# Symmetrize directed graphs
if G.is_directed():
A = A + np.transpose(A)
pos = _sparse_spectral(A, dim)
except (ImportError, ValueError):
# Dense matrix
A = nx.to_numpy_array(G, weight=weight)
# Symmetrize directed graphs
if G.is_directed():
A += A.T
pos = _spectral(A, dim)
pos = rescale_layout(pos, scale=scale) + center
pos = dict(zip(G, pos))
return pos
| (G, k=None, pos=None, fixed=None, iterations=50, threshold=0.0001, weight='weight', scale=1, center=None, dim=2, seed=None) |
30,680 | networkx.algorithms.operators.binary | full_join | Returns the full join of graphs G and H.
Full join is the union of G and H in which all edges between
G and H are added.
The node sets of G and H must be disjoint,
otherwise an exception is raised.
Parameters
----------
G, H : graph
A NetworkX graph
rename : tuple , default=(None, None)
Node names of G and H can be changed by specifying the tuple
rename=('G-','H-') (for example). Node "u" in G is then renamed
"G-u" and "v" in H is renamed "H-v".
Returns
-------
U : The full join graph with the same type as G.
Notes
-----
It is recommended that G and H be either both directed or both undirected.
If G is directed, then edges from G to H are added as well as from H to G.
Note that full_join() does not produce parallel edges for MultiGraphs.
The full join operation of graphs G and H is the same as getting
their complement, performing a disjoint union, and finally getting
the complement of the resulting graph.
Graph, edge, and node attributes are propagated from G and H
to the union graph. If a graph attribute is present in both
G and H the value from H is used.
Examples
--------
>>> G = nx.Graph([(0, 1), (0, 2)])
>>> H = nx.Graph([(3, 4)])
>>> R = nx.full_join(G, H, rename=("G", "H"))
>>> R.nodes
NodeView(('G0', 'G1', 'G2', 'H3', 'H4'))
>>> R.edges
EdgeView([('G0', 'G1'), ('G0', 'G2'), ('G0', 'H3'), ('G0', 'H4'), ('G1', 'H3'), ('G1', 'H4'), ('G2', 'H3'), ('G2', 'H4'), ('H3', 'H4')])
See Also
--------
union
disjoint_union
| null | (G, H, rename=(None, None), *, backend=None, **backend_kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.