applied-ai-018 commited on
Commit
af75000
·
verified ·
1 Parent(s): 1f35dc0

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/__init__.py +133 -0
  2. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/boundary.py +167 -0
  3. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bridges.py +205 -0
  4. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/chordal.py +442 -0
  5. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/clique.py +754 -0
  6. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/cluster.py +609 -0
  7. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/communicability_alg.py +162 -0
  8. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/core.py +648 -0
  9. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/covering.py +142 -0
  10. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/cuts.py +400 -0
  11. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/dag.py +1259 -0
  12. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/dominance.py +135 -0
  13. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/dominating.py +94 -0
  14. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/efficiency_measures.py +168 -0
  15. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/hierarchy.py +48 -0
  16. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/isolate.py +107 -0
  17. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/link_prediction.py +688 -0
  18. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/lowest_common_ancestors.py +268 -0
  19. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/matching.py +1151 -0
  20. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/mis.py +77 -0
  21. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/moral.py +59 -0
  22. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/non_randomness.py +96 -0
  23. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/planar_drawing.py +464 -0
  24. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/reciprocity.py +97 -0
  25. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/regular.py +214 -0
  26. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__init__.py +5 -0
  27. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/astar.py +239 -0
  28. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/dense.py +256 -0
  29. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/generic.py +729 -0
  30. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__init__.py +0 -0
  31. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_generic.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_unweighted.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_weighted.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_astar.py +248 -0
  36. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense.py +212 -0
  37. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py +89 -0
  38. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_generic.py +450 -0
  39. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_unweighted.py +149 -0
  40. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_weighted.py +972 -0
  41. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/unweighted.py +576 -0
  42. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/weighted.py +2517 -0
  43. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/smallworld.py +403 -0
  44. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/smetric.py +60 -0
  45. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/sparsifiers.py +295 -0
  46. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/summarization.py +563 -0
  47. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/swap.py +407 -0
  48. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tournament.py +406 -0
  49. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/triads.py +604 -0
  50. env-llmeval/lib/python3.10/site-packages/networkx/algorithms/vitality.py +76 -0
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/__init__.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networkx.algorithms.assortativity import *
2
+ from networkx.algorithms.asteroidal import *
3
+ from networkx.algorithms.boundary import *
4
+ from networkx.algorithms.broadcasting import *
5
+ from networkx.algorithms.bridges import *
6
+ from networkx.algorithms.chains import *
7
+ from networkx.algorithms.centrality import *
8
+ from networkx.algorithms.chordal import *
9
+ from networkx.algorithms.cluster import *
10
+ from networkx.algorithms.clique import *
11
+ from networkx.algorithms.communicability_alg import *
12
+ from networkx.algorithms.components import *
13
+ from networkx.algorithms.coloring import *
14
+ from networkx.algorithms.core import *
15
+ from networkx.algorithms.covering import *
16
+ from networkx.algorithms.cycles import *
17
+ from networkx.algorithms.cuts import *
18
+ from networkx.algorithms.d_separation import *
19
+ from networkx.algorithms.dag import *
20
+ from networkx.algorithms.distance_measures import *
21
+ from networkx.algorithms.distance_regular import *
22
+ from networkx.algorithms.dominance import *
23
+ from networkx.algorithms.dominating import *
24
+ from networkx.algorithms.efficiency_measures import *
25
+ from networkx.algorithms.euler import *
26
+ from networkx.algorithms.graphical import *
27
+ from networkx.algorithms.hierarchy import *
28
+ from networkx.algorithms.hybrid import *
29
+ from networkx.algorithms.link_analysis import *
30
+ from networkx.algorithms.link_prediction import *
31
+ from networkx.algorithms.lowest_common_ancestors import *
32
+ from networkx.algorithms.isolate import *
33
+ from networkx.algorithms.matching import *
34
+ from networkx.algorithms.minors import *
35
+ from networkx.algorithms.mis import *
36
+ from networkx.algorithms.moral import *
37
+ from networkx.algorithms.non_randomness import *
38
+ from networkx.algorithms.operators import *
39
+ from networkx.algorithms.planarity import *
40
+ from networkx.algorithms.planar_drawing import *
41
+ from networkx.algorithms.polynomials import *
42
+ from networkx.algorithms.reciprocity import *
43
+ from networkx.algorithms.regular import *
44
+ from networkx.algorithms.richclub import *
45
+ from networkx.algorithms.shortest_paths import *
46
+ from networkx.algorithms.similarity import *
47
+ from networkx.algorithms.graph_hashing import *
48
+ from networkx.algorithms.simple_paths import *
49
+ from networkx.algorithms.smallworld import *
50
+ from networkx.algorithms.smetric import *
51
+ from networkx.algorithms.structuralholes import *
52
+ from networkx.algorithms.sparsifiers import *
53
+ from networkx.algorithms.summarization import *
54
+ from networkx.algorithms.swap import *
55
+ from networkx.algorithms.time_dependent import *
56
+ from networkx.algorithms.traversal import *
57
+ from networkx.algorithms.triads import *
58
+ from networkx.algorithms.vitality import *
59
+ from networkx.algorithms.voronoi import *
60
+ from networkx.algorithms.walks import *
61
+ from networkx.algorithms.wiener import *
62
+
63
+ # Make certain subpackages available to the user as direct imports from
64
+ # the `networkx` namespace.
65
+ from networkx.algorithms import approximation
66
+ from networkx.algorithms import assortativity
67
+ from networkx.algorithms import bipartite
68
+ from networkx.algorithms import node_classification
69
+ from networkx.algorithms import centrality
70
+ from networkx.algorithms import chordal
71
+ from networkx.algorithms import cluster
72
+ from networkx.algorithms import clique
73
+ from networkx.algorithms import components
74
+ from networkx.algorithms import connectivity
75
+ from networkx.algorithms import community
76
+ from networkx.algorithms import coloring
77
+ from networkx.algorithms import flow
78
+ from networkx.algorithms import isomorphism
79
+ from networkx.algorithms import link_analysis
80
+ from networkx.algorithms import lowest_common_ancestors
81
+ from networkx.algorithms import operators
82
+ from networkx.algorithms import shortest_paths
83
+ from networkx.algorithms import tournament
84
+ from networkx.algorithms import traversal
85
+ from networkx.algorithms import tree
86
+
87
+ # Make certain functions from some of the previous subpackages available
88
+ # to the user as direct imports from the `networkx` namespace.
89
+ from networkx.algorithms.bipartite import complete_bipartite_graph
90
+ from networkx.algorithms.bipartite import is_bipartite
91
+ from networkx.algorithms.bipartite import projected_graph
92
+ from networkx.algorithms.connectivity import all_pairs_node_connectivity
93
+ from networkx.algorithms.connectivity import all_node_cuts
94
+ from networkx.algorithms.connectivity import average_node_connectivity
95
+ from networkx.algorithms.connectivity import edge_connectivity
96
+ from networkx.algorithms.connectivity import edge_disjoint_paths
97
+ from networkx.algorithms.connectivity import k_components
98
+ from networkx.algorithms.connectivity import k_edge_components
99
+ from networkx.algorithms.connectivity import k_edge_subgraphs
100
+ from networkx.algorithms.connectivity import k_edge_augmentation
101
+ from networkx.algorithms.connectivity import is_k_edge_connected
102
+ from networkx.algorithms.connectivity import minimum_edge_cut
103
+ from networkx.algorithms.connectivity import minimum_node_cut
104
+ from networkx.algorithms.connectivity import node_connectivity
105
+ from networkx.algorithms.connectivity import node_disjoint_paths
106
+ from networkx.algorithms.connectivity import stoer_wagner
107
+ from networkx.algorithms.flow import capacity_scaling
108
+ from networkx.algorithms.flow import cost_of_flow
109
+ from networkx.algorithms.flow import gomory_hu_tree
110
+ from networkx.algorithms.flow import max_flow_min_cost
111
+ from networkx.algorithms.flow import maximum_flow
112
+ from networkx.algorithms.flow import maximum_flow_value
113
+ from networkx.algorithms.flow import min_cost_flow
114
+ from networkx.algorithms.flow import min_cost_flow_cost
115
+ from networkx.algorithms.flow import minimum_cut
116
+ from networkx.algorithms.flow import minimum_cut_value
117
+ from networkx.algorithms.flow import network_simplex
118
+ from networkx.algorithms.isomorphism import could_be_isomorphic
119
+ from networkx.algorithms.isomorphism import fast_could_be_isomorphic
120
+ from networkx.algorithms.isomorphism import faster_could_be_isomorphic
121
+ from networkx.algorithms.isomorphism import is_isomorphic
122
+ from networkx.algorithms.isomorphism.vf2pp import *
123
+ from networkx.algorithms.tree.branchings import maximum_branching
124
+ from networkx.algorithms.tree.branchings import maximum_spanning_arborescence
125
+ from networkx.algorithms.tree.branchings import minimum_branching
126
+ from networkx.algorithms.tree.branchings import minimum_spanning_arborescence
127
+ from networkx.algorithms.tree.branchings import ArborescenceIterator
128
+ from networkx.algorithms.tree.coding import *
129
+ from networkx.algorithms.tree.decomposition import *
130
+ from networkx.algorithms.tree.mst import *
131
+ from networkx.algorithms.tree.operations import *
132
+ from networkx.algorithms.tree.recognition import *
133
+ from networkx.algorithms.tournament import is_tournament
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/boundary.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routines to find the boundary of a set of nodes.
2
+
3
+ An edge boundary is a set of edges, each of which has exactly one
4
+ endpoint in a given set of nodes (or, in the case of directed graphs,
5
+ the set of edges whose source node is in the set).
6
+
7
+ A node boundary of a set *S* of nodes is the set of (out-)neighbors of
8
+ nodes in *S* that are outside *S*.
9
+
10
+ """
11
+ from itertools import chain
12
+
13
+ import networkx as nx
14
+
15
+ __all__ = ["edge_boundary", "node_boundary"]
16
+
17
+
18
+ @nx._dispatchable(edge_attrs={"data": "default"}, preserve_edge_attrs="data")
19
+ def edge_boundary(G, nbunch1, nbunch2=None, data=False, keys=False, default=None):
20
+ """Returns the edge boundary of `nbunch1`.
21
+
22
+ The *edge boundary* of a set *S* with respect to a set *T* is the
23
+ set of edges (*u*, *v*) such that *u* is in *S* and *v* is in *T*.
24
+ If *T* is not specified, it is assumed to be the set of all nodes
25
+ not in *S*.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ nbunch1 : iterable
32
+ Iterable of nodes in the graph representing the set of nodes
33
+ whose edge boundary will be returned. (This is the set *S* from
34
+ the definition above.)
35
+
36
+ nbunch2 : iterable
37
+ Iterable of nodes representing the target (or "exterior") set of
38
+ nodes. (This is the set *T* from the definition above.) If not
39
+ specified, this is assumed to be the set of all nodes in `G`
40
+ not in `nbunch1`.
41
+
42
+ keys : bool
43
+ This parameter has the same meaning as in
44
+ :meth:`MultiGraph.edges`.
45
+
46
+ data : bool or object
47
+ This parameter has the same meaning as in
48
+ :meth:`MultiGraph.edges`.
49
+
50
+ default : object
51
+ This parameter has the same meaning as in
52
+ :meth:`MultiGraph.edges`.
53
+
54
+ Returns
55
+ -------
56
+ iterator
57
+ An iterator over the edges in the boundary of `nbunch1` with
58
+ respect to `nbunch2`. If `keys`, `data`, or `default`
59
+ are specified and `G` is a multigraph, then edges are returned
60
+ with keys and/or data, as in :meth:`MultiGraph.edges`.
61
+
62
+ Examples
63
+ --------
64
+ >>> G = nx.wheel_graph(6)
65
+
66
+ When nbunch2=None:
67
+
68
+ >>> list(nx.edge_boundary(G, (1, 3)))
69
+ [(1, 0), (1, 2), (1, 5), (3, 0), (3, 2), (3, 4)]
70
+
71
+ When nbunch2 is given:
72
+
73
+ >>> list(nx.edge_boundary(G, (1, 3), (2, 0)))
74
+ [(1, 0), (1, 2), (3, 0), (3, 2)]
75
+
76
+ Notes
77
+ -----
78
+ Any element of `nbunch` that is not in the graph `G` will be
79
+ ignored.
80
+
81
+ `nbunch1` and `nbunch2` are usually meant to be disjoint, but in
82
+ the interest of speed and generality, that is not required here.
83
+
84
+ """
85
+ nset1 = {n for n in nbunch1 if n in G}
86
+ # Here we create an iterator over edges incident to nodes in the set
87
+ # `nset1`. The `Graph.edges()` method does not provide a guarantee
88
+ # on the orientation of the edges, so our algorithm below must
89
+ # handle the case in which exactly one orientation, either (u, v) or
90
+ # (v, u), appears in this iterable.
91
+ if G.is_multigraph():
92
+ edges = G.edges(nset1, data=data, keys=keys, default=default)
93
+ else:
94
+ edges = G.edges(nset1, data=data, default=default)
95
+ # If `nbunch2` is not provided, then it is assumed to be the set
96
+ # complement of `nbunch1`. For the sake of efficiency, this is
97
+ # implemented by using the `not in` operator, instead of by creating
98
+ # an additional set and using the `in` operator.
99
+ if nbunch2 is None:
100
+ return (e for e in edges if (e[0] in nset1) ^ (e[1] in nset1))
101
+ nset2 = set(nbunch2)
102
+ return (
103
+ e
104
+ for e in edges
105
+ if (e[0] in nset1 and e[1] in nset2) or (e[1] in nset1 and e[0] in nset2)
106
+ )
107
+
108
+
109
+ @nx._dispatchable
110
+ def node_boundary(G, nbunch1, nbunch2=None):
111
+ """Returns the node boundary of `nbunch1`.
112
+
113
+ The *node boundary* of a set *S* with respect to a set *T* is the
114
+ set of nodes *v* in *T* such that for some *u* in *S*, there is an
115
+ edge joining *u* to *v*. If *T* is not specified, it is assumed to
116
+ be the set of all nodes not in *S*.
117
+
118
+ Parameters
119
+ ----------
120
+ G : NetworkX graph
121
+
122
+ nbunch1 : iterable
123
+ Iterable of nodes in the graph representing the set of nodes
124
+ whose node boundary will be returned. (This is the set *S* from
125
+ the definition above.)
126
+
127
+ nbunch2 : iterable
128
+ Iterable of nodes representing the target (or "exterior") set of
129
+ nodes. (This is the set *T* from the definition above.) If not
130
+ specified, this is assumed to be the set of all nodes in `G`
131
+ not in `nbunch1`.
132
+
133
+ Returns
134
+ -------
135
+ set
136
+ The node boundary of `nbunch1` with respect to `nbunch2`.
137
+
138
+ Examples
139
+ --------
140
+ >>> G = nx.wheel_graph(6)
141
+
142
+ When nbunch2=None:
143
+
144
+ >>> list(nx.node_boundary(G, (3, 4)))
145
+ [0, 2, 5]
146
+
147
+ When nbunch2 is given:
148
+
149
+ >>> list(nx.node_boundary(G, (3, 4), (0, 1, 5)))
150
+ [0, 5]
151
+
152
+ Notes
153
+ -----
154
+ Any element of `nbunch` that is not in the graph `G` will be
155
+ ignored.
156
+
157
+ `nbunch1` and `nbunch2` are usually meant to be disjoint, but in
158
+ the interest of speed and generality, that is not required here.
159
+
160
+ """
161
+ nset1 = {n for n in nbunch1 if n in G}
162
+ bdy = set(chain.from_iterable(G[v] for v in nset1)) - nset1
163
+ # If `nbunch2` is not specified, it is assumed to be the set
164
+ # complement of `nbunch1`.
165
+ if nbunch2 is not None:
166
+ bdy &= set(nbunch2)
167
+ return bdy
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/bridges.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bridge-finding algorithms."""
2
+ from itertools import chain
3
+
4
+ import networkx as nx
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = ["bridges", "has_bridges", "local_bridges"]
8
+
9
+
10
+ @not_implemented_for("directed")
11
+ @nx._dispatchable
12
+ def bridges(G, root=None):
13
+ """Generate all bridges in a graph.
14
+
15
+ A *bridge* in a graph is an edge whose removal causes the number of
16
+ connected components of the graph to increase. Equivalently, a bridge is an
17
+ edge that does not belong to any cycle. Bridges are also known as cut-edges,
18
+ isthmuses, or cut arcs.
19
+
20
+ Parameters
21
+ ----------
22
+ G : undirected graph
23
+
24
+ root : node (optional)
25
+ A node in the graph `G`. If specified, only the bridges in the
26
+ connected component containing this node will be returned.
27
+
28
+ Yields
29
+ ------
30
+ e : edge
31
+ An edge in the graph whose removal disconnects the graph (or
32
+ causes the number of connected components to increase).
33
+
34
+ Raises
35
+ ------
36
+ NodeNotFound
37
+ If `root` is not in the graph `G`.
38
+
39
+ NetworkXNotImplemented
40
+ If `G` is a directed graph.
41
+
42
+ Examples
43
+ --------
44
+ The barbell graph with parameter zero has a single bridge:
45
+
46
+ >>> G = nx.barbell_graph(10, 0)
47
+ >>> list(nx.bridges(G))
48
+ [(9, 10)]
49
+
50
+ Notes
51
+ -----
52
+ This is an implementation of the algorithm described in [1]_. An edge is a
53
+ bridge if and only if it is not contained in any chain. Chains are found
54
+ using the :func:`networkx.chain_decomposition` function.
55
+
56
+ The algorithm described in [1]_ requires a simple graph. If the provided
57
+ graph is a multigraph, we convert it to a simple graph and verify that any
58
+ bridges discovered by the chain decomposition algorithm are not multi-edges.
59
+
60
+ Ignoring polylogarithmic factors, the worst-case time complexity is the
61
+ same as the :func:`networkx.chain_decomposition` function,
62
+ $O(m + n)$, where $n$ is the number of nodes in the graph and $m$ is
63
+ the number of edges.
64
+
65
+ References
66
+ ----------
67
+ .. [1] https://en.wikipedia.org/wiki/Bridge_%28graph_theory%29#Bridge-Finding_with_Chain_Decompositions
68
+ """
69
+ multigraph = G.is_multigraph()
70
+ H = nx.Graph(G) if multigraph else G
71
+ chains = nx.chain_decomposition(H, root=root)
72
+ chain_edges = set(chain.from_iterable(chains))
73
+ H_copy = H.copy()
74
+ if root is not None:
75
+ H = H.subgraph(nx.node_connected_component(H, root)).copy()
76
+ for u, v in H.edges():
77
+ if (u, v) not in chain_edges and (v, u) not in chain_edges:
78
+ if multigraph and len(G[u][v]) > 1:
79
+ continue
80
+ yield u, v
81
+
82
+
83
+ @not_implemented_for("directed")
84
+ @nx._dispatchable
85
+ def has_bridges(G, root=None):
86
+ """Decide whether a graph has any bridges.
87
+
88
+ A *bridge* in a graph is an edge whose removal causes the number of
89
+ connected components of the graph to increase.
90
+
91
+ Parameters
92
+ ----------
93
+ G : undirected graph
94
+
95
+ root : node (optional)
96
+ A node in the graph `G`. If specified, only the bridges in the
97
+ connected component containing this node will be considered.
98
+
99
+ Returns
100
+ -------
101
+ bool
102
+ Whether the graph (or the connected component containing `root`)
103
+ has any bridges.
104
+
105
+ Raises
106
+ ------
107
+ NodeNotFound
108
+ If `root` is not in the graph `G`.
109
+
110
+ NetworkXNotImplemented
111
+ If `G` is a directed graph.
112
+
113
+ Examples
114
+ --------
115
+ The barbell graph with parameter zero has a single bridge::
116
+
117
+ >>> G = nx.barbell_graph(10, 0)
118
+ >>> nx.has_bridges(G)
119
+ True
120
+
121
+ On the other hand, the cycle graph has no bridges::
122
+
123
+ >>> G = nx.cycle_graph(5)
124
+ >>> nx.has_bridges(G)
125
+ False
126
+
127
+ Notes
128
+ -----
129
+ This implementation uses the :func:`networkx.bridges` function, so
130
+ it shares its worst-case time complexity, $O(m + n)$, ignoring
131
+ polylogarithmic factors, where $n$ is the number of nodes in the
132
+ graph and $m$ is the number of edges.
133
+
134
+ """
135
+ try:
136
+ next(bridges(G, root=root))
137
+ except StopIteration:
138
+ return False
139
+ else:
140
+ return True
141
+
142
+
143
+ @not_implemented_for("multigraph")
144
+ @not_implemented_for("directed")
145
+ @nx._dispatchable(edge_attrs="weight")
146
+ def local_bridges(G, with_span=True, weight=None):
147
+ """Iterate over local bridges of `G` optionally computing the span
148
+
149
+ A *local bridge* is an edge whose endpoints have no common neighbors.
150
+ That is, the edge is not part of a triangle in the graph.
151
+
152
+ The *span* of a *local bridge* is the shortest path length between
153
+ the endpoints if the local bridge is removed.
154
+
155
+ Parameters
156
+ ----------
157
+ G : undirected graph
158
+
159
+ with_span : bool
160
+ If True, yield a 3-tuple `(u, v, span)`
161
+
162
+ weight : function, string or None (default: None)
163
+ If function, used to compute edge weights for the span.
164
+ If string, the edge data attribute used in calculating span.
165
+ If None, all edges have weight 1.
166
+
167
+ Yields
168
+ ------
169
+ e : edge
170
+ The local bridges as an edge 2-tuple of nodes `(u, v)` or
171
+ as a 3-tuple `(u, v, span)` when `with_span is True`.
172
+
173
+ Raises
174
+ ------
175
+ NetworkXNotImplemented
176
+ If `G` is a directed graph or multigraph.
177
+
178
+ Examples
179
+ --------
180
+ A cycle graph has every edge a local bridge with span N-1.
181
+
182
+ >>> G = nx.cycle_graph(9)
183
+ >>> (0, 8, 8) in set(nx.local_bridges(G))
184
+ True
185
+ """
186
+ if with_span is not True:
187
+ for u, v in G.edges:
188
+ if not (set(G[u]) & set(G[v])):
189
+ yield u, v
190
+ else:
191
+ wt = nx.weighted._weight_function(G, weight)
192
+ for u, v in G.edges:
193
+ if not (set(G[u]) & set(G[v])):
194
+ enodes = {u, v}
195
+
196
+ def hide_edge(n, nbr, d):
197
+ if n not in enodes or nbr not in enodes:
198
+ return wt(n, nbr, d)
199
+ return None
200
+
201
+ try:
202
+ span = nx.shortest_path_length(G, u, v, weight=hide_edge)
203
+ yield u, v, span
204
+ except nx.NetworkXNoPath:
205
+ yield u, v, float("inf")
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/chordal.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Algorithms for chordal graphs.
3
+
4
+ A graph is chordal if every cycle of length at least 4 has a chord
5
+ (an edge joining two nodes not adjacent in the cycle).
6
+ https://en.wikipedia.org/wiki/Chordal_graph
7
+ """
8
+ import sys
9
+
10
+ import networkx as nx
11
+ from networkx.algorithms.components import connected_components
12
+ from networkx.utils import arbitrary_element, not_implemented_for
13
+
14
+ __all__ = [
15
+ "is_chordal",
16
+ "find_induced_nodes",
17
+ "chordal_graph_cliques",
18
+ "chordal_graph_treewidth",
19
+ "NetworkXTreewidthBoundExceeded",
20
+ "complete_to_chordal_graph",
21
+ ]
22
+
23
+
24
+ class NetworkXTreewidthBoundExceeded(nx.NetworkXException):
25
+ """Exception raised when a treewidth bound has been provided and it has
26
+ been exceeded"""
27
+
28
+
29
+ @not_implemented_for("directed")
30
+ @not_implemented_for("multigraph")
31
+ @nx._dispatchable
32
+ def is_chordal(G):
33
+ """Checks whether G is a chordal graph.
34
+
35
+ A graph is chordal if every cycle of length at least 4 has a chord
36
+ (an edge joining two nodes not adjacent in the cycle).
37
+
38
+ Parameters
39
+ ----------
40
+ G : graph
41
+ A NetworkX graph.
42
+
43
+ Returns
44
+ -------
45
+ chordal : bool
46
+ True if G is a chordal graph and False otherwise.
47
+
48
+ Raises
49
+ ------
50
+ NetworkXNotImplemented
51
+ The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
52
+
53
+ Examples
54
+ --------
55
+ >>> e = [
56
+ ... (1, 2),
57
+ ... (1, 3),
58
+ ... (2, 3),
59
+ ... (2, 4),
60
+ ... (3, 4),
61
+ ... (3, 5),
62
+ ... (3, 6),
63
+ ... (4, 5),
64
+ ... (4, 6),
65
+ ... (5, 6),
66
+ ... ]
67
+ >>> G = nx.Graph(e)
68
+ >>> nx.is_chordal(G)
69
+ True
70
+
71
+ Notes
72
+ -----
73
+ The routine tries to go through every node following maximum cardinality
74
+ search. It returns False when it finds that the separator for any node
75
+ is not a clique. Based on the algorithms in [1]_.
76
+
77
+ Self loops are ignored.
78
+
79
+ References
80
+ ----------
81
+ .. [1] R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms
82
+ to test chordality of graphs, test acyclicity of hypergraphs, and
83
+ selectively reduce acyclic hypergraphs, SIAM J. Comput., 13 (1984),
84
+ pp. 566–579.
85
+ """
86
+ if len(G.nodes) <= 3:
87
+ return True
88
+ return len(_find_chordality_breaker(G)) == 0
89
+
90
+
91
+ @nx._dispatchable
92
+ def find_induced_nodes(G, s, t, treewidth_bound=sys.maxsize):
93
+ """Returns the set of induced nodes in the path from s to t.
94
+
95
+ Parameters
96
+ ----------
97
+ G : graph
98
+ A chordal NetworkX graph
99
+ s : node
100
+ Source node to look for induced nodes
101
+ t : node
102
+ Destination node to look for induced nodes
103
+ treewidth_bound: float
104
+ Maximum treewidth acceptable for the graph H. The search
105
+ for induced nodes will end as soon as the treewidth_bound is exceeded.
106
+
107
+ Returns
108
+ -------
109
+ induced_nodes : Set of nodes
110
+ The set of induced nodes in the path from s to t in G
111
+
112
+ Raises
113
+ ------
114
+ NetworkXError
115
+ The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
116
+ If the input graph is an instance of one of these classes, a
117
+ :exc:`NetworkXError` is raised.
118
+ The algorithm can only be applied to chordal graphs. If the input
119
+ graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
120
+
121
+ Examples
122
+ --------
123
+ >>> G = nx.Graph()
124
+ >>> G = nx.generators.classic.path_graph(10)
125
+ >>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
126
+ >>> sorted(induced_nodes)
127
+ [1, 2, 3, 4, 5, 6, 7, 8, 9]
128
+
129
+ Notes
130
+ -----
131
+ G must be a chordal graph and (s,t) an edge that is not in G.
132
+
133
+ If a treewidth_bound is provided, the search for induced nodes will end
134
+ as soon as the treewidth_bound is exceeded.
135
+
136
+ The algorithm is inspired by Algorithm 4 in [1]_.
137
+ A formal definition of induced node can also be found on that reference.
138
+
139
+ Self Loops are ignored
140
+
141
+ References
142
+ ----------
143
+ .. [1] Learning Bounded Treewidth Bayesian Networks.
144
+ Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699--2731, 2008.
145
+ http://jmlr.csail.mit.edu/papers/volume9/elidan08a/elidan08a.pdf
146
+ """
147
+ if not is_chordal(G):
148
+ raise nx.NetworkXError("Input graph is not chordal.")
149
+
150
+ H = nx.Graph(G)
151
+ H.add_edge(s, t)
152
+ induced_nodes = set()
153
+ triplet = _find_chordality_breaker(H, s, treewidth_bound)
154
+ while triplet:
155
+ (u, v, w) = triplet
156
+ induced_nodes.update(triplet)
157
+ for n in triplet:
158
+ if n != s:
159
+ H.add_edge(s, n)
160
+ triplet = _find_chordality_breaker(H, s, treewidth_bound)
161
+ if induced_nodes:
162
+ # Add t and the second node in the induced path from s to t.
163
+ induced_nodes.add(t)
164
+ for u in G[s]:
165
+ if len(induced_nodes & set(G[u])) == 2:
166
+ induced_nodes.add(u)
167
+ break
168
+ return induced_nodes
169
+
170
+
171
+ @nx._dispatchable
172
+ def chordal_graph_cliques(G):
173
+ """Returns all maximal cliques of a chordal graph.
174
+
175
+ The algorithm breaks the graph in connected components and performs a
176
+ maximum cardinality search in each component to get the cliques.
177
+
178
+ Parameters
179
+ ----------
180
+ G : graph
181
+ A NetworkX graph
182
+
183
+ Yields
184
+ ------
185
+ frozenset of nodes
186
+ Maximal cliques, each of which is a frozenset of
187
+ nodes in `G`. The order of cliques is arbitrary.
188
+
189
+ Raises
190
+ ------
191
+ NetworkXError
192
+ The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
193
+ The algorithm can only be applied to chordal graphs. If the input
194
+ graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
195
+
196
+ Examples
197
+ --------
198
+ >>> e = [
199
+ ... (1, 2),
200
+ ... (1, 3),
201
+ ... (2, 3),
202
+ ... (2, 4),
203
+ ... (3, 4),
204
+ ... (3, 5),
205
+ ... (3, 6),
206
+ ... (4, 5),
207
+ ... (4, 6),
208
+ ... (5, 6),
209
+ ... (7, 8),
210
+ ... ]
211
+ >>> G = nx.Graph(e)
212
+ >>> G.add_node(9)
213
+ >>> cliques = [c for c in chordal_graph_cliques(G)]
214
+ >>> cliques[0]
215
+ frozenset({1, 2, 3})
216
+ """
217
+ for C in (G.subgraph(c).copy() for c in connected_components(G)):
218
+ if C.number_of_nodes() == 1:
219
+ if nx.number_of_selfloops(C) > 0:
220
+ raise nx.NetworkXError("Input graph is not chordal.")
221
+ yield frozenset(C.nodes())
222
+ else:
223
+ unnumbered = set(C.nodes())
224
+ v = arbitrary_element(C)
225
+ unnumbered.remove(v)
226
+ numbered = {v}
227
+ clique_wanna_be = {v}
228
+ while unnumbered:
229
+ v = _max_cardinality_node(C, unnumbered, numbered)
230
+ unnumbered.remove(v)
231
+ numbered.add(v)
232
+ new_clique_wanna_be = set(C.neighbors(v)) & numbered
233
+ sg = C.subgraph(clique_wanna_be)
234
+ if _is_complete_graph(sg):
235
+ new_clique_wanna_be.add(v)
236
+ if not new_clique_wanna_be >= clique_wanna_be:
237
+ yield frozenset(clique_wanna_be)
238
+ clique_wanna_be = new_clique_wanna_be
239
+ else:
240
+ raise nx.NetworkXError("Input graph is not chordal.")
241
+ yield frozenset(clique_wanna_be)
242
+
243
+
244
+ @nx._dispatchable
245
+ def chordal_graph_treewidth(G):
246
+ """Returns the treewidth of the chordal graph G.
247
+
248
+ Parameters
249
+ ----------
250
+ G : graph
251
+ A NetworkX graph
252
+
253
+ Returns
254
+ -------
255
+ treewidth : int
256
+ The size of the largest clique in the graph minus one.
257
+
258
+ Raises
259
+ ------
260
+ NetworkXError
261
+ The algorithm does not support DiGraph, MultiGraph and MultiDiGraph.
262
+ The algorithm can only be applied to chordal graphs. If the input
263
+ graph is found to be non-chordal, a :exc:`NetworkXError` is raised.
264
+
265
+ Examples
266
+ --------
267
+ >>> e = [
268
+ ... (1, 2),
269
+ ... (1, 3),
270
+ ... (2, 3),
271
+ ... (2, 4),
272
+ ... (3, 4),
273
+ ... (3, 5),
274
+ ... (3, 6),
275
+ ... (4, 5),
276
+ ... (4, 6),
277
+ ... (5, 6),
278
+ ... (7, 8),
279
+ ... ]
280
+ >>> G = nx.Graph(e)
281
+ >>> G.add_node(9)
282
+ >>> nx.chordal_graph_treewidth(G)
283
+ 3
284
+
285
+ References
286
+ ----------
287
+ .. [1] https://en.wikipedia.org/wiki/Tree_decomposition#Treewidth
288
+ """
289
+ if not is_chordal(G):
290
+ raise nx.NetworkXError("Input graph is not chordal.")
291
+
292
+ max_clique = -1
293
+ for clique in nx.chordal_graph_cliques(G):
294
+ max_clique = max(max_clique, len(clique))
295
+ return max_clique - 1
296
+
297
+
298
+ def _is_complete_graph(G):
299
+ """Returns True if G is a complete graph."""
300
+ if nx.number_of_selfloops(G) > 0:
301
+ raise nx.NetworkXError("Self loop found in _is_complete_graph()")
302
+ n = G.number_of_nodes()
303
+ if n < 2:
304
+ return True
305
+ e = G.number_of_edges()
306
+ max_edges = (n * (n - 1)) / 2
307
+ return e == max_edges
308
+
309
+
310
+ def _find_missing_edge(G):
311
+ """Given a non-complete graph G, returns a missing edge."""
312
+ nodes = set(G)
313
+ for u in G:
314
+ missing = nodes - set(list(G[u].keys()) + [u])
315
+ if missing:
316
+ return (u, missing.pop())
317
+
318
+
319
+ def _max_cardinality_node(G, choices, wanna_connect):
320
+ """Returns a the node in choices that has more connections in G
321
+ to nodes in wanna_connect.
322
+ """
323
+ max_number = -1
324
+ for x in choices:
325
+ number = len([y for y in G[x] if y in wanna_connect])
326
+ if number > max_number:
327
+ max_number = number
328
+ max_cardinality_node = x
329
+ return max_cardinality_node
330
+
331
+
332
+ def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize):
333
+ """Given a graph G, starts a max cardinality search
334
+ (starting from s if s is given and from an arbitrary node otherwise)
335
+ trying to find a non-chordal cycle.
336
+
337
+ If it does find one, it returns (u,v,w) where u,v,w are the three
338
+ nodes that together with s are involved in the cycle.
339
+
340
+ It ignores any self loops.
341
+ """
342
+ if len(G) == 0:
343
+ raise nx.NetworkXPointlessConcept("Graph has no nodes.")
344
+ unnumbered = set(G)
345
+ if s is None:
346
+ s = arbitrary_element(G)
347
+ unnumbered.remove(s)
348
+ numbered = {s}
349
+ current_treewidth = -1
350
+ while unnumbered: # and current_treewidth <= treewidth_bound:
351
+ v = _max_cardinality_node(G, unnumbered, numbered)
352
+ unnumbered.remove(v)
353
+ numbered.add(v)
354
+ clique_wanna_be = set(G[v]) & numbered
355
+ sg = G.subgraph(clique_wanna_be)
356
+ if _is_complete_graph(sg):
357
+ # The graph seems to be chordal by now. We update the treewidth
358
+ current_treewidth = max(current_treewidth, len(clique_wanna_be))
359
+ if current_treewidth > treewidth_bound:
360
+ raise nx.NetworkXTreewidthBoundExceeded(
361
+ f"treewidth_bound exceeded: {current_treewidth}"
362
+ )
363
+ else:
364
+ # sg is not a clique,
365
+ # look for an edge that is not included in sg
366
+ (u, w) = _find_missing_edge(sg)
367
+ return (u, v, w)
368
+ return ()
369
+
370
+
371
+ @not_implemented_for("directed")
372
+ @nx._dispatchable(returns_graph=True)
373
+ def complete_to_chordal_graph(G):
374
+ """Return a copy of G completed to a chordal graph
375
+
376
+ Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is
377
+ called chordal if for each cycle with length bigger than 3, there exist
378
+ two non-adjacent nodes connected by an edge (called a chord).
379
+
380
+ Parameters
381
+ ----------
382
+ G : NetworkX graph
383
+ Undirected graph
384
+
385
+ Returns
386
+ -------
387
+ H : NetworkX graph
388
+ The chordal enhancement of G
389
+ alpha : Dictionary
390
+ The elimination ordering of nodes of G
391
+
392
+ Notes
393
+ -----
394
+ There are different approaches to calculate the chordal
395
+ enhancement of a graph. The algorithm used here is called
396
+ MCS-M and gives at least minimal (local) triangulation of graph. Note
397
+ that this triangulation is not necessarily a global minimum.
398
+
399
+ https://en.wikipedia.org/wiki/Chordal_graph
400
+
401
+ References
402
+ ----------
403
+ .. [1] Berry, Anne & Blair, Jean & Heggernes, Pinar & Peyton, Barry. (2004)
404
+ Maximum Cardinality Search for Computing Minimal Triangulations of
405
+ Graphs. Algorithmica. 39. 287-298. 10.1007/s00453-004-1084-3.
406
+
407
+ Examples
408
+ --------
409
+ >>> from networkx.algorithms.chordal import complete_to_chordal_graph
410
+ >>> G = nx.wheel_graph(10)
411
+ >>> H, alpha = complete_to_chordal_graph(G)
412
+ """
413
+ H = G.copy()
414
+ alpha = {node: 0 for node in H}
415
+ if nx.is_chordal(H):
416
+ return H, alpha
417
+ chords = set()
418
+ weight = {node: 0 for node in H.nodes()}
419
+ unnumbered_nodes = list(H.nodes())
420
+ for i in range(len(H.nodes()), 0, -1):
421
+ # get the node in unnumbered_nodes with the maximum weight
422
+ z = max(unnumbered_nodes, key=lambda node: weight[node])
423
+ unnumbered_nodes.remove(z)
424
+ alpha[z] = i
425
+ update_nodes = []
426
+ for y in unnumbered_nodes:
427
+ if G.has_edge(y, z):
428
+ update_nodes.append(y)
429
+ else:
430
+ # y_weight will be bigger than node weights between y and z
431
+ y_weight = weight[y]
432
+ lower_nodes = [
433
+ node for node in unnumbered_nodes if weight[node] < y_weight
434
+ ]
435
+ if nx.has_path(H.subgraph(lower_nodes + [z, y]), y, z):
436
+ update_nodes.append(y)
437
+ chords.add((z, y))
438
+ # during calculation of paths the weights should not be updated
439
+ for node in update_nodes:
440
+ weight[node] += 1
441
+ H.add_edges_from(chords)
442
+ return H, alpha
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/clique.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for finding and manipulating cliques.
2
+
3
+ Finding the largest clique in a graph is NP-complete problem, so most of
4
+ these algorithms have an exponential running time; for more information,
5
+ see the Wikipedia article on the clique problem [1]_.
6
+
7
+ .. [1] clique problem:: https://en.wikipedia.org/wiki/Clique_problem
8
+
9
+ """
10
+ from collections import defaultdict, deque
11
+ from itertools import chain, combinations, islice
12
+
13
+ import networkx as nx
14
+ from networkx.utils import not_implemented_for
15
+
16
+ __all__ = [
17
+ "find_cliques",
18
+ "find_cliques_recursive",
19
+ "make_max_clique_graph",
20
+ "make_clique_bipartite",
21
+ "node_clique_number",
22
+ "number_of_cliques",
23
+ "enumerate_all_cliques",
24
+ "max_weight_clique",
25
+ ]
26
+
27
+
28
+ @not_implemented_for("directed")
29
+ @nx._dispatchable
30
+ def enumerate_all_cliques(G):
31
+ """Returns all cliques in an undirected graph.
32
+
33
+ This function returns an iterator over cliques, each of which is a
34
+ list of nodes. The iteration is ordered by cardinality of the
35
+ cliques: first all cliques of size one, then all cliques of size
36
+ two, etc.
37
+
38
+ Parameters
39
+ ----------
40
+ G : NetworkX graph
41
+ An undirected graph.
42
+
43
+ Returns
44
+ -------
45
+ iterator
46
+ An iterator over cliques, each of which is a list of nodes in
47
+ `G`. The cliques are ordered according to size.
48
+
49
+ Notes
50
+ -----
51
+ To obtain a list of all cliques, use
52
+ `list(enumerate_all_cliques(G))`. However, be aware that in the
53
+ worst-case, the length of this list can be exponential in the number
54
+ of nodes in the graph (for example, when the graph is the complete
55
+ graph). This function avoids storing all cliques in memory by only
56
+ keeping current candidate node lists in memory during its search.
57
+
58
+ The implementation is adapted from the algorithm by Zhang, et
59
+ al. (2005) [1]_ to output all cliques discovered.
60
+
61
+ This algorithm ignores self-loops and parallel edges, since cliques
62
+ are not conventionally defined with such edges.
63
+
64
+ References
65
+ ----------
66
+ .. [1] Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J.,
67
+ Langston, M.A., Samatova, N.F.,
68
+ "Genome-Scale Computational Approaches to Memory-Intensive
69
+ Applications in Systems Biology".
70
+ *Supercomputing*, 2005. Proceedings of the ACM/IEEE SC 2005
71
+ Conference, pp. 12, 12--18 Nov. 2005.
72
+ <https://doi.org/10.1109/SC.2005.29>.
73
+
74
+ """
75
+ index = {}
76
+ nbrs = {}
77
+ for u in G:
78
+ index[u] = len(index)
79
+ # Neighbors of u that appear after u in the iteration order of G.
80
+ nbrs[u] = {v for v in G[u] if v not in index}
81
+
82
+ queue = deque(([u], sorted(nbrs[u], key=index.__getitem__)) for u in G)
83
+ # Loop invariants:
84
+ # 1. len(base) is nondecreasing.
85
+ # 2. (base + cnbrs) is sorted with respect to the iteration order of G.
86
+ # 3. cnbrs is a set of common neighbors of nodes in base.
87
+ while queue:
88
+ base, cnbrs = map(list, queue.popleft())
89
+ yield base
90
+ for i, u in enumerate(cnbrs):
91
+ # Use generators to reduce memory consumption.
92
+ queue.append(
93
+ (
94
+ chain(base, [u]),
95
+ filter(nbrs[u].__contains__, islice(cnbrs, i + 1, None)),
96
+ )
97
+ )
98
+
99
+
100
+ @not_implemented_for("directed")
101
+ @nx._dispatchable
102
+ def find_cliques(G, nodes=None):
103
+ """Returns all maximal cliques in an undirected graph.
104
+
105
+ For each node *n*, a *maximal clique for n* is a largest complete
106
+ subgraph containing *n*. The largest maximal clique is sometimes
107
+ called the *maximum clique*.
108
+
109
+ This function returns an iterator over cliques, each of which is a
110
+ list of nodes. It is an iterative implementation, so should not
111
+ suffer from recursion depth issues.
112
+
113
+ This function accepts a list of `nodes` and only the maximal cliques
114
+ containing all of these `nodes` are returned. It can considerably speed up
115
+ the running time if some specific cliques are desired.
116
+
117
+ Parameters
118
+ ----------
119
+ G : NetworkX graph
120
+ An undirected graph.
121
+
122
+ nodes : list, optional (default=None)
123
+ If provided, only yield *maximal cliques* containing all nodes in `nodes`.
124
+ If `nodes` isn't a clique itself, a ValueError is raised.
125
+
126
+ Returns
127
+ -------
128
+ iterator
129
+ An iterator over maximal cliques, each of which is a list of
130
+ nodes in `G`. If `nodes` is provided, only the maximal cliques
131
+ containing all the nodes in `nodes` are returned. The order of
132
+ cliques is arbitrary.
133
+
134
+ Raises
135
+ ------
136
+ ValueError
137
+ If `nodes` is not a clique.
138
+
139
+ Examples
140
+ --------
141
+ >>> from pprint import pprint # For nice dict formatting
142
+ >>> G = nx.karate_club_graph()
143
+ >>> sum(1 for c in nx.find_cliques(G)) # The number of maximal cliques in G
144
+ 36
145
+ >>> max(nx.find_cliques(G), key=len) # The largest maximal clique in G
146
+ [0, 1, 2, 3, 13]
147
+
148
+ The size of the largest maximal clique is known as the *clique number* of
149
+ the graph, which can be found directly with:
150
+
151
+ >>> max(len(c) for c in nx.find_cliques(G))
152
+ 5
153
+
154
+ One can also compute the number of maximal cliques in `G` that contain a given
155
+ node. The following produces a dictionary keyed by node whose
156
+ values are the number of maximal cliques in `G` that contain the node:
157
+
158
+ >>> pprint({n: sum(1 for c in nx.find_cliques(G) if n in c) for n in G})
159
+ {0: 13,
160
+ 1: 6,
161
+ 2: 7,
162
+ 3: 3,
163
+ 4: 2,
164
+ 5: 3,
165
+ 6: 3,
166
+ 7: 1,
167
+ 8: 3,
168
+ 9: 2,
169
+ 10: 2,
170
+ 11: 1,
171
+ 12: 1,
172
+ 13: 2,
173
+ 14: 1,
174
+ 15: 1,
175
+ 16: 1,
176
+ 17: 1,
177
+ 18: 1,
178
+ 19: 2,
179
+ 20: 1,
180
+ 21: 1,
181
+ 22: 1,
182
+ 23: 3,
183
+ 24: 2,
184
+ 25: 2,
185
+ 26: 1,
186
+ 27: 3,
187
+ 28: 2,
188
+ 29: 2,
189
+ 30: 2,
190
+ 31: 4,
191
+ 32: 9,
192
+ 33: 14}
193
+
194
+ Or, similarly, the maximal cliques in `G` that contain a given node.
195
+ For example, the 4 maximal cliques that contain node 31:
196
+
197
+ >>> [c for c in nx.find_cliques(G) if 31 in c]
198
+ [[0, 31], [33, 32, 31], [33, 28, 31], [24, 25, 31]]
199
+
200
+ See Also
201
+ --------
202
+ find_cliques_recursive
203
+ A recursive version of the same algorithm.
204
+
205
+ Notes
206
+ -----
207
+ To obtain a list of all maximal cliques, use
208
+ `list(find_cliques(G))`. However, be aware that in the worst-case,
209
+ the length of this list can be exponential in the number of nodes in
210
+ the graph. This function avoids storing all cliques in memory by
211
+ only keeping current candidate node lists in memory during its search.
212
+
213
+ This implementation is based on the algorithm published by Bron and
214
+ Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
215
+ (2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. It
216
+ essentially unrolls the recursion used in the references to avoid
217
+ issues of recursion stack depth (for a recursive implementation, see
218
+ :func:`find_cliques_recursive`).
219
+
220
+ This algorithm ignores self-loops and parallel edges, since cliques
221
+ are not conventionally defined with such edges.
222
+
223
+ References
224
+ ----------
225
+ .. [1] Bron, C. and Kerbosch, J.
226
+ "Algorithm 457: finding all cliques of an undirected graph".
227
+ *Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
228
+ <http://portal.acm.org/citation.cfm?doid=362342.362367>
229
+
230
+ .. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
231
+ "The worst-case time complexity for generating all maximal
232
+ cliques and computational experiments",
233
+ *Theoretical Computer Science*, Volume 363, Issue 1,
234
+ Computing and Combinatorics,
235
+ 10th Annual International Conference on
236
+ Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
237
+ <https://doi.org/10.1016/j.tcs.2006.06.015>
238
+
239
+ .. [3] F. Cazals, C. Karande,
240
+ "A note on the problem of reporting maximal cliques",
241
+ *Theoretical Computer Science*,
242
+ Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
243
+ <https://doi.org/10.1016/j.tcs.2008.05.010>
244
+
245
+ """
246
+ if len(G) == 0:
247
+ return
248
+
249
+ adj = {u: {v for v in G[u] if v != u} for u in G}
250
+
251
+ # Initialize Q with the given nodes and subg, cand with their nbrs
252
+ Q = nodes[:] if nodes is not None else []
253
+ cand = set(G)
254
+ for node in Q:
255
+ if node not in cand:
256
+ raise ValueError(f"The given `nodes` {nodes} do not form a clique")
257
+ cand &= adj[node]
258
+
259
+ if not cand:
260
+ yield Q[:]
261
+ return
262
+
263
+ subg = cand.copy()
264
+ stack = []
265
+ Q.append(None)
266
+
267
+ u = max(subg, key=lambda u: len(cand & adj[u]))
268
+ ext_u = cand - adj[u]
269
+
270
+ try:
271
+ while True:
272
+ if ext_u:
273
+ q = ext_u.pop()
274
+ cand.remove(q)
275
+ Q[-1] = q
276
+ adj_q = adj[q]
277
+ subg_q = subg & adj_q
278
+ if not subg_q:
279
+ yield Q[:]
280
+ else:
281
+ cand_q = cand & adj_q
282
+ if cand_q:
283
+ stack.append((subg, cand, ext_u))
284
+ Q.append(None)
285
+ subg = subg_q
286
+ cand = cand_q
287
+ u = max(subg, key=lambda u: len(cand & adj[u]))
288
+ ext_u = cand - adj[u]
289
+ else:
290
+ Q.pop()
291
+ subg, cand, ext_u = stack.pop()
292
+ except IndexError:
293
+ pass
294
+
295
+
296
+ # TODO Should this also be not implemented for directed graphs?
297
+ @nx._dispatchable
298
+ def find_cliques_recursive(G, nodes=None):
299
+ """Returns all maximal cliques in a graph.
300
+
301
+ For each node *v*, a *maximal clique for v* is a largest complete
302
+ subgraph containing *v*. The largest maximal clique is sometimes
303
+ called the *maximum clique*.
304
+
305
+ This function returns an iterator over cliques, each of which is a
306
+ list of nodes. It is a recursive implementation, so may suffer from
307
+ recursion depth issues, but is included for pedagogical reasons.
308
+ For a non-recursive implementation, see :func:`find_cliques`.
309
+
310
+ This function accepts a list of `nodes` and only the maximal cliques
311
+ containing all of these `nodes` are returned. It can considerably speed up
312
+ the running time if some specific cliques are desired.
313
+
314
+ Parameters
315
+ ----------
316
+ G : NetworkX graph
317
+
318
+ nodes : list, optional (default=None)
319
+ If provided, only yield *maximal cliques* containing all nodes in `nodes`.
320
+ If `nodes` isn't a clique itself, a ValueError is raised.
321
+
322
+ Returns
323
+ -------
324
+ iterator
325
+ An iterator over maximal cliques, each of which is a list of
326
+ nodes in `G`. If `nodes` is provided, only the maximal cliques
327
+ containing all the nodes in `nodes` are yielded. The order of
328
+ cliques is arbitrary.
329
+
330
+ Raises
331
+ ------
332
+ ValueError
333
+ If `nodes` is not a clique.
334
+
335
+ See Also
336
+ --------
337
+ find_cliques
338
+ An iterative version of the same algorithm. See docstring for examples.
339
+
340
+ Notes
341
+ -----
342
+ To obtain a list of all maximal cliques, use
343
+ `list(find_cliques_recursive(G))`. However, be aware that in the
344
+ worst-case, the length of this list can be exponential in the number
345
+ of nodes in the graph. This function avoids storing all cliques in memory
346
+ by only keeping current candidate node lists in memory during its search.
347
+
348
+ This implementation is based on the algorithm published by Bron and
349
+ Kerbosch (1973) [1]_, as adapted by Tomita, Tanaka and Takahashi
350
+ (2006) [2]_ and discussed in Cazals and Karande (2008) [3]_. For a
351
+ non-recursive implementation, see :func:`find_cliques`.
352
+
353
+ This algorithm ignores self-loops and parallel edges, since cliques
354
+ are not conventionally defined with such edges.
355
+
356
+ References
357
+ ----------
358
+ .. [1] Bron, C. and Kerbosch, J.
359
+ "Algorithm 457: finding all cliques of an undirected graph".
360
+ *Communications of the ACM* 16, 9 (Sep. 1973), 575--577.
361
+ <http://portal.acm.org/citation.cfm?doid=362342.362367>
362
+
363
+ .. [2] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi,
364
+ "The worst-case time complexity for generating all maximal
365
+ cliques and computational experiments",
366
+ *Theoretical Computer Science*, Volume 363, Issue 1,
367
+ Computing and Combinatorics,
368
+ 10th Annual International Conference on
369
+ Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28--42
370
+ <https://doi.org/10.1016/j.tcs.2006.06.015>
371
+
372
+ .. [3] F. Cazals, C. Karande,
373
+ "A note on the problem of reporting maximal cliques",
374
+ *Theoretical Computer Science*,
375
+ Volume 407, Issues 1--3, 6 November 2008, Pages 564--568,
376
+ <https://doi.org/10.1016/j.tcs.2008.05.010>
377
+
378
+ """
379
+ if len(G) == 0:
380
+ return iter([])
381
+
382
+ adj = {u: {v for v in G[u] if v != u} for u in G}
383
+
384
+ # Initialize Q with the given nodes and subg, cand with their nbrs
385
+ Q = nodes[:] if nodes is not None else []
386
+ cand_init = set(G)
387
+ for node in Q:
388
+ if node not in cand_init:
389
+ raise ValueError(f"The given `nodes` {nodes} do not form a clique")
390
+ cand_init &= adj[node]
391
+
392
+ if not cand_init:
393
+ return iter([Q])
394
+
395
+ subg_init = cand_init.copy()
396
+
397
+ def expand(subg, cand):
398
+ u = max(subg, key=lambda u: len(cand & adj[u]))
399
+ for q in cand - adj[u]:
400
+ cand.remove(q)
401
+ Q.append(q)
402
+ adj_q = adj[q]
403
+ subg_q = subg & adj_q
404
+ if not subg_q:
405
+ yield Q[:]
406
+ else:
407
+ cand_q = cand & adj_q
408
+ if cand_q:
409
+ yield from expand(subg_q, cand_q)
410
+ Q.pop()
411
+
412
+ return expand(subg_init, cand_init)
413
+
414
+
415
+ @nx._dispatchable(returns_graph=True)
416
+ def make_max_clique_graph(G, create_using=None):
417
+ """Returns the maximal clique graph of the given graph.
418
+
419
+ The nodes of the maximal clique graph of `G` are the cliques of
420
+ `G` and an edge joins two cliques if the cliques are not disjoint.
421
+
422
+ Parameters
423
+ ----------
424
+ G : NetworkX graph
425
+
426
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
427
+ Graph type to create. If graph instance, then cleared before populated.
428
+
429
+ Returns
430
+ -------
431
+ NetworkX graph
432
+ A graph whose nodes are the cliques of `G` and whose edges
433
+ join two cliques if they are not disjoint.
434
+
435
+ Notes
436
+ -----
437
+ This function behaves like the following code::
438
+
439
+ import networkx as nx
440
+
441
+ G = nx.make_clique_bipartite(G)
442
+ cliques = [v for v in G.nodes() if G.nodes[v]["bipartite"] == 0]
443
+ G = nx.bipartite.projected_graph(G, cliques)
444
+ G = nx.relabel_nodes(G, {-v: v - 1 for v in G})
445
+
446
+ It should be faster, though, since it skips all the intermediate
447
+ steps.
448
+
449
+ """
450
+ if create_using is None:
451
+ B = G.__class__()
452
+ else:
453
+ B = nx.empty_graph(0, create_using)
454
+ cliques = list(enumerate(set(c) for c in find_cliques(G)))
455
+ # Add a numbered node for each clique.
456
+ B.add_nodes_from(i for i, c in cliques)
457
+ # Join cliques by an edge if they share a node.
458
+ clique_pairs = combinations(cliques, 2)
459
+ B.add_edges_from((i, j) for (i, c1), (j, c2) in clique_pairs if c1 & c2)
460
+ return B
461
+
462
+
463
+ @nx._dispatchable(returns_graph=True)
464
+ def make_clique_bipartite(G, fpos=None, create_using=None, name=None):
465
+ """Returns the bipartite clique graph corresponding to `G`.
466
+
467
+ In the returned bipartite graph, the "bottom" nodes are the nodes of
468
+ `G` and the "top" nodes represent the maximal cliques of `G`.
469
+ There is an edge from node *v* to clique *C* in the returned graph
470
+ if and only if *v* is an element of *C*.
471
+
472
+ Parameters
473
+ ----------
474
+ G : NetworkX graph
475
+ An undirected graph.
476
+
477
+ fpos : bool
478
+ If True or not None, the returned graph will have an
479
+ additional attribute, `pos`, a dictionary mapping node to
480
+ position in the Euclidean plane.
481
+
482
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
483
+ Graph type to create. If graph instance, then cleared before populated.
484
+
485
+ Returns
486
+ -------
487
+ NetworkX graph
488
+ A bipartite graph whose "bottom" set is the nodes of the graph
489
+ `G`, whose "top" set is the cliques of `G`, and whose edges
490
+ join nodes of `G` to the cliques that contain them.
491
+
492
+ The nodes of the graph `G` have the node attribute
493
+ 'bipartite' set to 1 and the nodes representing cliques
494
+ have the node attribute 'bipartite' set to 0, as is the
495
+ convention for bipartite graphs in NetworkX.
496
+
497
+ """
498
+ B = nx.empty_graph(0, create_using)
499
+ B.clear()
500
+ # The "bottom" nodes in the bipartite graph are the nodes of the
501
+ # original graph, G.
502
+ B.add_nodes_from(G, bipartite=1)
503
+ for i, cl in enumerate(find_cliques(G)):
504
+ # The "top" nodes in the bipartite graph are the cliques. These
505
+ # nodes get negative numbers as labels.
506
+ name = -i - 1
507
+ B.add_node(name, bipartite=0)
508
+ B.add_edges_from((v, name) for v in cl)
509
+ return B
510
+
511
+
512
+ @nx._dispatchable
513
+ def node_clique_number(G, nodes=None, cliques=None, separate_nodes=False):
514
+ """Returns the size of the largest maximal clique containing each given node.
515
+
516
+ Returns a single or list depending on input nodes.
517
+ An optional list of cliques can be input if already computed.
518
+
519
+ Parameters
520
+ ----------
521
+ G : NetworkX graph
522
+ An undirected graph.
523
+
524
+ cliques : list, optional (default=None)
525
+ A list of cliques, each of which is itself a list of nodes.
526
+ If not specified, the list of all cliques will be computed
527
+ using :func:`find_cliques`.
528
+
529
+ Returns
530
+ -------
531
+ int or dict
532
+ If `nodes` is a single node, returns the size of the
533
+ largest maximal clique in `G` containing that node.
534
+ Otherwise return a dict keyed by node to the size
535
+ of the largest maximal clique containing that node.
536
+
537
+ See Also
538
+ --------
539
+ find_cliques
540
+ find_cliques yields the maximal cliques of G.
541
+ It accepts a `nodes` argument which restricts consideration to
542
+ maximal cliques containing all the given `nodes`.
543
+ The search for the cliques is optimized for `nodes`.
544
+ """
545
+ if cliques is None:
546
+ if nodes is not None:
547
+ # Use ego_graph to decrease size of graph
548
+ # check for single node
549
+ if nodes in G:
550
+ return max(len(c) for c in find_cliques(nx.ego_graph(G, nodes)))
551
+ # handle multiple nodes
552
+ return {
553
+ n: max(len(c) for c in find_cliques(nx.ego_graph(G, n))) for n in nodes
554
+ }
555
+
556
+ # nodes is None--find all cliques
557
+ cliques = list(find_cliques(G))
558
+
559
+ # single node requested
560
+ if nodes in G:
561
+ return max(len(c) for c in cliques if nodes in c)
562
+
563
+ # multiple nodes requested
564
+ # preprocess all nodes (faster than one at a time for even 2 nodes)
565
+ size_for_n = defaultdict(int)
566
+ for c in cliques:
567
+ size_of_c = len(c)
568
+ for n in c:
569
+ if size_for_n[n] < size_of_c:
570
+ size_for_n[n] = size_of_c
571
+ if nodes is None:
572
+ return size_for_n
573
+ return {n: size_for_n[n] for n in nodes}
574
+
575
+
576
+ def number_of_cliques(G, nodes=None, cliques=None):
577
+ """Returns the number of maximal cliques for each node.
578
+
579
+ Returns a single or list depending on input nodes.
580
+ Optional list of cliques can be input if already computed.
581
+ """
582
+ if cliques is None:
583
+ cliques = list(find_cliques(G))
584
+
585
+ if nodes is None:
586
+ nodes = list(G.nodes()) # none, get entire graph
587
+
588
+ if not isinstance(nodes, list): # check for a list
589
+ v = nodes
590
+ # assume it is a single value
591
+ numcliq = len([1 for c in cliques if v in c])
592
+ else:
593
+ numcliq = {}
594
+ for v in nodes:
595
+ numcliq[v] = len([1 for c in cliques if v in c])
596
+ return numcliq
597
+
598
+
599
+ class MaxWeightClique:
600
+ """A class for the maximum weight clique algorithm.
601
+
602
+ This class is a helper for the `max_weight_clique` function. The class
603
+ should not normally be used directly.
604
+
605
+ Parameters
606
+ ----------
607
+ G : NetworkX graph
608
+ The undirected graph for which a maximum weight clique is sought
609
+ weight : string or None, optional (default='weight')
610
+ The node attribute that holds the integer value used as a weight.
611
+ If None, then each node has weight 1.
612
+
613
+ Attributes
614
+ ----------
615
+ G : NetworkX graph
616
+ The undirected graph for which a maximum weight clique is sought
617
+ node_weights: dict
618
+ The weight of each node
619
+ incumbent_nodes : list
620
+ The nodes of the incumbent clique (the best clique found so far)
621
+ incumbent_weight: int
622
+ The weight of the incumbent clique
623
+ """
624
+
625
+ def __init__(self, G, weight):
626
+ self.G = G
627
+ self.incumbent_nodes = []
628
+ self.incumbent_weight = 0
629
+
630
+ if weight is None:
631
+ self.node_weights = {v: 1 for v in G.nodes()}
632
+ else:
633
+ for v in G.nodes():
634
+ if weight not in G.nodes[v]:
635
+ errmsg = f"Node {v!r} does not have the requested weight field."
636
+ raise KeyError(errmsg)
637
+ if not isinstance(G.nodes[v][weight], int):
638
+ errmsg = f"The {weight!r} field of node {v!r} is not an integer."
639
+ raise ValueError(errmsg)
640
+ self.node_weights = {v: G.nodes[v][weight] for v in G.nodes()}
641
+
642
+ def update_incumbent_if_improved(self, C, C_weight):
643
+ """Update the incumbent if the node set C has greater weight.
644
+
645
+ C is assumed to be a clique.
646
+ """
647
+ if C_weight > self.incumbent_weight:
648
+ self.incumbent_nodes = C[:]
649
+ self.incumbent_weight = C_weight
650
+
651
+ def greedily_find_independent_set(self, P):
652
+ """Greedily find an independent set of nodes from a set of
653
+ nodes P."""
654
+ independent_set = []
655
+ P = P[:]
656
+ while P:
657
+ v = P[0]
658
+ independent_set.append(v)
659
+ P = [w for w in P if v != w and not self.G.has_edge(v, w)]
660
+ return independent_set
661
+
662
+ def find_branching_nodes(self, P, target):
663
+ """Find a set of nodes to branch on."""
664
+ residual_wt = {v: self.node_weights[v] for v in P}
665
+ total_wt = 0
666
+ P = P[:]
667
+ while P:
668
+ independent_set = self.greedily_find_independent_set(P)
669
+ min_wt_in_class = min(residual_wt[v] for v in independent_set)
670
+ total_wt += min_wt_in_class
671
+ if total_wt > target:
672
+ break
673
+ for v in independent_set:
674
+ residual_wt[v] -= min_wt_in_class
675
+ P = [v for v in P if residual_wt[v] != 0]
676
+ return P
677
+
678
+ def expand(self, C, C_weight, P):
679
+ """Look for the best clique that contains all the nodes in C and zero or
680
+ more of the nodes in P, backtracking if it can be shown that no such
681
+ clique has greater weight than the incumbent.
682
+ """
683
+ self.update_incumbent_if_improved(C, C_weight)
684
+ branching_nodes = self.find_branching_nodes(P, self.incumbent_weight - C_weight)
685
+ while branching_nodes:
686
+ v = branching_nodes.pop()
687
+ P.remove(v)
688
+ new_C = C + [v]
689
+ new_C_weight = C_weight + self.node_weights[v]
690
+ new_P = [w for w in P if self.G.has_edge(v, w)]
691
+ self.expand(new_C, new_C_weight, new_P)
692
+
693
+ def find_max_weight_clique(self):
694
+ """Find a maximum weight clique."""
695
+ # Sort nodes in reverse order of degree for speed
696
+ nodes = sorted(self.G.nodes(), key=lambda v: self.G.degree(v), reverse=True)
697
+ nodes = [v for v in nodes if self.node_weights[v] > 0]
698
+ self.expand([], 0, nodes)
699
+
700
+
701
+ @not_implemented_for("directed")
702
+ @nx._dispatchable(node_attrs="weight")
703
+ def max_weight_clique(G, weight="weight"):
704
+ """Find a maximum weight clique in G.
705
+
706
+ A *clique* in a graph is a set of nodes such that every two distinct nodes
707
+ are adjacent. The *weight* of a clique is the sum of the weights of its
708
+ nodes. A *maximum weight clique* of graph G is a clique C in G such that
709
+ no clique in G has weight greater than the weight of C.
710
+
711
+ Parameters
712
+ ----------
713
+ G : NetworkX graph
714
+ Undirected graph
715
+ weight : string or None, optional (default='weight')
716
+ The node attribute that holds the integer value used as a weight.
717
+ If None, then each node has weight 1.
718
+
719
+ Returns
720
+ -------
721
+ clique : list
722
+ the nodes of a maximum weight clique
723
+ weight : int
724
+ the weight of a maximum weight clique
725
+
726
+ Notes
727
+ -----
728
+ The implementation is recursive, and therefore it may run into recursion
729
+ depth issues if G contains a clique whose number of nodes is close to the
730
+ recursion depth limit.
731
+
732
+ At each search node, the algorithm greedily constructs a weighted
733
+ independent set cover of part of the graph in order to find a small set of
734
+ nodes on which to branch. The algorithm is very similar to the algorithm
735
+ of Tavares et al. [1]_, other than the fact that the NetworkX version does
736
+ not use bitsets. This style of algorithm for maximum weight clique (and
737
+ maximum weight independent set, which is the same problem but on the
738
+ complement graph) has a decades-long history. See Algorithm B of Warren
739
+ and Hicks [2]_ and the references in that paper.
740
+
741
+ References
742
+ ----------
743
+ .. [1] Tavares, W.A., Neto, M.B.C., Rodrigues, C.D., Michelon, P.: Um
744
+ algoritmo de branch and bound para o problema da clique máxima
745
+ ponderada. Proceedings of XLVII SBPO 1 (2015).
746
+
747
+ .. [2] Warren, Jeffrey S, Hicks, Illya V.: Combinatorial Branch-and-Bound
748
+ for the Maximum Weight Independent Set Problem. Technical Report,
749
+ Texas A&M University (2016).
750
+ """
751
+
752
+ mwc = MaxWeightClique(G, weight)
753
+ mwc.find_max_weight_clique()
754
+ return mwc.incumbent_nodes, mwc.incumbent_weight
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/cluster.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Algorithms to characterize the number of triangles in a graph."""
2
+
3
+ from collections import Counter
4
+ from itertools import chain, combinations
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for
8
+
9
+ __all__ = [
10
+ "triangles",
11
+ "average_clustering",
12
+ "clustering",
13
+ "transitivity",
14
+ "square_clustering",
15
+ "generalized_degree",
16
+ ]
17
+
18
+
19
+ @not_implemented_for("directed")
20
+ @nx._dispatchable
21
+ def triangles(G, nodes=None):
22
+ """Compute the number of triangles.
23
+
24
+ Finds the number of triangles that include a node as one vertex.
25
+
26
+ Parameters
27
+ ----------
28
+ G : graph
29
+ A networkx graph
30
+
31
+ nodes : node, iterable of nodes, or None (default=None)
32
+ If a singleton node, return the number of triangles for that node.
33
+ If an iterable, compute the number of triangles for each of those nodes.
34
+ If `None` (the default) compute the number of triangles for all nodes in `G`.
35
+
36
+ Returns
37
+ -------
38
+ out : dict or int
39
+ If `nodes` is a container of nodes, returns number of triangles keyed by node (dict).
40
+ If `nodes` is a specific node, returns number of triangles for the node (int).
41
+
42
+ Examples
43
+ --------
44
+ >>> G = nx.complete_graph(5)
45
+ >>> print(nx.triangles(G, 0))
46
+ 6
47
+ >>> print(nx.triangles(G))
48
+ {0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
49
+ >>> print(list(nx.triangles(G, [0, 1]).values()))
50
+ [6, 6]
51
+
52
+ Notes
53
+ -----
54
+ Self loops are ignored.
55
+
56
+ """
57
+ if nodes is not None:
58
+ # If `nodes` represents a single node, return only its number of triangles
59
+ if nodes in G:
60
+ return next(_triangles_and_degree_iter(G, nodes))[2] // 2
61
+
62
+ # if `nodes` is a container of nodes, then return a
63
+ # dictionary mapping node to number of triangles.
64
+ return {v: t // 2 for v, d, t, _ in _triangles_and_degree_iter(G, nodes)}
65
+
66
+ # if nodes is None, then compute triangles for the complete graph
67
+
68
+ # dict used to avoid visiting the same nodes twice
69
+ # this allows calculating/counting each triangle only once
70
+ later_nbrs = {}
71
+
72
+ # iterate over the nodes in a graph
73
+ for node, neighbors in G.adjacency():
74
+ later_nbrs[node] = {n for n in neighbors if n not in later_nbrs and n != node}
75
+
76
+ # instantiate Counter for each node to include isolated nodes
77
+ # add 1 to the count if a nodes neighbor's neighbor is also a neighbor
78
+ triangle_counts = Counter(dict.fromkeys(G, 0))
79
+ for node1, neighbors in later_nbrs.items():
80
+ for node2 in neighbors:
81
+ third_nodes = neighbors & later_nbrs[node2]
82
+ m = len(third_nodes)
83
+ triangle_counts[node1] += m
84
+ triangle_counts[node2] += m
85
+ triangle_counts.update(third_nodes)
86
+
87
+ return dict(triangle_counts)
88
+
89
+
90
+ @not_implemented_for("multigraph")
91
+ def _triangles_and_degree_iter(G, nodes=None):
92
+ """Return an iterator of (node, degree, triangles, generalized degree).
93
+
94
+ This double counts triangles so you may want to divide by 2.
95
+ See degree(), triangles() and generalized_degree() for definitions
96
+ and details.
97
+
98
+ """
99
+ if nodes is None:
100
+ nodes_nbrs = G.adj.items()
101
+ else:
102
+ nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
103
+
104
+ for v, v_nbrs in nodes_nbrs:
105
+ vs = set(v_nbrs) - {v}
106
+ gen_degree = Counter(len(vs & (set(G[w]) - {w})) for w in vs)
107
+ ntriangles = sum(k * val for k, val in gen_degree.items())
108
+ yield (v, len(vs), ntriangles, gen_degree)
109
+
110
+
111
+ @not_implemented_for("multigraph")
112
+ def _weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
113
+ """Return an iterator of (node, degree, weighted_triangles).
114
+
115
+ Used for weighted clustering.
116
+ Note: this returns the geometric average weight of edges in the triangle.
117
+ Also, each triangle is counted twice (each direction).
118
+ So you may want to divide by 2.
119
+
120
+ """
121
+ import numpy as np
122
+
123
+ if weight is None or G.number_of_edges() == 0:
124
+ max_weight = 1
125
+ else:
126
+ max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
127
+ if nodes is None:
128
+ nodes_nbrs = G.adj.items()
129
+ else:
130
+ nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))
131
+
132
+ def wt(u, v):
133
+ return G[u][v].get(weight, 1) / max_weight
134
+
135
+ for i, nbrs in nodes_nbrs:
136
+ inbrs = set(nbrs) - {i}
137
+ weighted_triangles = 0
138
+ seen = set()
139
+ for j in inbrs:
140
+ seen.add(j)
141
+ # This avoids counting twice -- we double at the end.
142
+ jnbrs = set(G[j]) - seen
143
+ # Only compute the edge weight once, before the inner inner
144
+ # loop.
145
+ wij = wt(i, j)
146
+ weighted_triangles += np.cbrt(
147
+ [(wij * wt(j, k) * wt(k, i)) for k in inbrs & jnbrs]
148
+ ).sum()
149
+ yield (i, len(inbrs), 2 * float(weighted_triangles))
150
+
151
+
152
+ @not_implemented_for("multigraph")
153
+ def _directed_triangles_and_degree_iter(G, nodes=None):
154
+ """Return an iterator of
155
+ (node, total_degree, reciprocal_degree, directed_triangles).
156
+
157
+ Used for directed clustering.
158
+ Note that unlike `_triangles_and_degree_iter()`, this function counts
159
+ directed triangles so does not count triangles twice.
160
+
161
+ """
162
+ nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
163
+
164
+ for i, preds, succs in nodes_nbrs:
165
+ ipreds = set(preds) - {i}
166
+ isuccs = set(succs) - {i}
167
+
168
+ directed_triangles = 0
169
+ for j in chain(ipreds, isuccs):
170
+ jpreds = set(G._pred[j]) - {j}
171
+ jsuccs = set(G._succ[j]) - {j}
172
+ directed_triangles += sum(
173
+ 1
174
+ for k in chain(
175
+ (ipreds & jpreds),
176
+ (ipreds & jsuccs),
177
+ (isuccs & jpreds),
178
+ (isuccs & jsuccs),
179
+ )
180
+ )
181
+ dtotal = len(ipreds) + len(isuccs)
182
+ dbidirectional = len(ipreds & isuccs)
183
+ yield (i, dtotal, dbidirectional, directed_triangles)
184
+
185
+
186
+ @not_implemented_for("multigraph")
187
+ def _directed_weighted_triangles_and_degree_iter(G, nodes=None, weight="weight"):
188
+ """Return an iterator of
189
+ (node, total_degree, reciprocal_degree, directed_weighted_triangles).
190
+
191
+ Used for directed weighted clustering.
192
+ Note that unlike `_weighted_triangles_and_degree_iter()`, this function counts
193
+ directed triangles so does not count triangles twice.
194
+
195
+ """
196
+ import numpy as np
197
+
198
+ if weight is None or G.number_of_edges() == 0:
199
+ max_weight = 1
200
+ else:
201
+ max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
202
+
203
+ nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))
204
+
205
+ def wt(u, v):
206
+ return G[u][v].get(weight, 1) / max_weight
207
+
208
+ for i, preds, succs in nodes_nbrs:
209
+ ipreds = set(preds) - {i}
210
+ isuccs = set(succs) - {i}
211
+
212
+ directed_triangles = 0
213
+ for j in ipreds:
214
+ jpreds = set(G._pred[j]) - {j}
215
+ jsuccs = set(G._succ[j]) - {j}
216
+ directed_triangles += np.cbrt(
217
+ [(wt(j, i) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
218
+ ).sum()
219
+ directed_triangles += np.cbrt(
220
+ [(wt(j, i) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
221
+ ).sum()
222
+ directed_triangles += np.cbrt(
223
+ [(wt(j, i) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
224
+ ).sum()
225
+ directed_triangles += np.cbrt(
226
+ [(wt(j, i) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
227
+ ).sum()
228
+
229
+ for j in isuccs:
230
+ jpreds = set(G._pred[j]) - {j}
231
+ jsuccs = set(G._succ[j]) - {j}
232
+ directed_triangles += np.cbrt(
233
+ [(wt(i, j) * wt(k, i) * wt(k, j)) for k in ipreds & jpreds]
234
+ ).sum()
235
+ directed_triangles += np.cbrt(
236
+ [(wt(i, j) * wt(k, i) * wt(j, k)) for k in ipreds & jsuccs]
237
+ ).sum()
238
+ directed_triangles += np.cbrt(
239
+ [(wt(i, j) * wt(i, k) * wt(k, j)) for k in isuccs & jpreds]
240
+ ).sum()
241
+ directed_triangles += np.cbrt(
242
+ [(wt(i, j) * wt(i, k) * wt(j, k)) for k in isuccs & jsuccs]
243
+ ).sum()
244
+
245
+ dtotal = len(ipreds) + len(isuccs)
246
+ dbidirectional = len(ipreds & isuccs)
247
+ yield (i, dtotal, dbidirectional, float(directed_triangles))
248
+
249
+
250
+ @nx._dispatchable(edge_attrs="weight")
251
+ def average_clustering(G, nodes=None, weight=None, count_zeros=True):
252
+ r"""Compute the average clustering coefficient for the graph G.
253
+
254
+ The clustering coefficient for the graph is the average,
255
+
256
+ .. math::
257
+
258
+ C = \frac{1}{n}\sum_{v \in G} c_v,
259
+
260
+ where :math:`n` is the number of nodes in `G`.
261
+
262
+ Parameters
263
+ ----------
264
+ G : graph
265
+
266
+ nodes : container of nodes, optional (default=all nodes in G)
267
+ Compute average clustering for nodes in this container.
268
+
269
+ weight : string or None, optional (default=None)
270
+ The edge attribute that holds the numerical value used as a weight.
271
+ If None, then each edge has weight 1.
272
+
273
+ count_zeros : bool
274
+ If False include only the nodes with nonzero clustering in the average.
275
+
276
+ Returns
277
+ -------
278
+ avg : float
279
+ Average clustering
280
+
281
+ Examples
282
+ --------
283
+ >>> G = nx.complete_graph(5)
284
+ >>> print(nx.average_clustering(G))
285
+ 1.0
286
+
287
+ Notes
288
+ -----
289
+ This is a space saving routine; it might be faster
290
+ to use the clustering function to get a list and then take the average.
291
+
292
+ Self loops are ignored.
293
+
294
+ References
295
+ ----------
296
+ .. [1] Generalizations of the clustering coefficient to weighted
297
+ complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
298
+ K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
299
+ http://jponnela.com/web_documents/a9.pdf
300
+ .. [2] Marcus Kaiser, Mean clustering coefficients: the role of isolated
301
+ nodes and leafs on clustering measures for small-world networks.
302
+ https://arxiv.org/abs/0802.2512
303
+ """
304
+ c = clustering(G, nodes, weight=weight).values()
305
+ if not count_zeros:
306
+ c = [v for v in c if abs(v) > 0]
307
+ return sum(c) / len(c)
308
+
309
+
310
+ @nx._dispatchable(edge_attrs="weight")
311
+ def clustering(G, nodes=None, weight=None):
312
+ r"""Compute the clustering coefficient for nodes.
313
+
314
+ For unweighted graphs, the clustering of a node :math:`u`
315
+ is the fraction of possible triangles through that node that exist,
316
+
317
+ .. math::
318
+
319
+ c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)},
320
+
321
+ where :math:`T(u)` is the number of triangles through node :math:`u` and
322
+ :math:`deg(u)` is the degree of :math:`u`.
323
+
324
+ For weighted graphs, there are several ways to define clustering [1]_.
325
+ the one used here is defined
326
+ as the geometric average of the subgraph edge weights [2]_,
327
+
328
+ .. math::
329
+
330
+ c_u = \frac{1}{deg(u)(deg(u)-1))}
331
+ \sum_{vw} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}.
332
+
333
+ The edge weights :math:`\hat{w}_{uv}` are normalized by the maximum weight
334
+ in the network :math:`\hat{w}_{uv} = w_{uv}/\max(w)`.
335
+
336
+ The value of :math:`c_u` is assigned to 0 if :math:`deg(u) < 2`.
337
+
338
+ Additionally, this weighted definition has been generalized to support negative edge weights [3]_.
339
+
340
+ For directed graphs, the clustering is similarly defined as the fraction
341
+ of all possible directed triangles or geometric average of the subgraph
342
+ edge weights for unweighted and weighted directed graph respectively [4]_.
343
+
344
+ .. math::
345
+
346
+ c_u = \frac{T(u)}{2(deg^{tot}(u)(deg^{tot}(u)-1) - 2deg^{\leftrightarrow}(u))},
347
+
348
+ where :math:`T(u)` is the number of directed triangles through node
349
+ :math:`u`, :math:`deg^{tot}(u)` is the sum of in degree and out degree of
350
+ :math:`u` and :math:`deg^{\leftrightarrow}(u)` is the reciprocal degree of
351
+ :math:`u`.
352
+
353
+
354
+ Parameters
355
+ ----------
356
+ G : graph
357
+
358
+ nodes : node, iterable of nodes, or None (default=None)
359
+ If a singleton node, return the number of triangles for that node.
360
+ If an iterable, compute the number of triangles for each of those nodes.
361
+ If `None` (the default) compute the number of triangles for all nodes in `G`.
362
+
363
+ weight : string or None, optional (default=None)
364
+ The edge attribute that holds the numerical value used as a weight.
365
+ If None, then each edge has weight 1.
366
+
367
+ Returns
368
+ -------
369
+ out : float, or dictionary
370
+ Clustering coefficient at specified nodes
371
+
372
+ Examples
373
+ --------
374
+ >>> G = nx.complete_graph(5)
375
+ >>> print(nx.clustering(G, 0))
376
+ 1.0
377
+ >>> print(nx.clustering(G))
378
+ {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
379
+
380
+ Notes
381
+ -----
382
+ Self loops are ignored.
383
+
384
+ References
385
+ ----------
386
+ .. [1] Generalizations of the clustering coefficient to weighted
387
+ complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
388
+ K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
389
+ http://jponnela.com/web_documents/a9.pdf
390
+ .. [2] Intensity and coherence of motifs in weighted complex
391
+ networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski,
392
+ Physical Review E, 71(6), 065103 (2005).
393
+ .. [3] Generalization of Clustering Coefficients to Signed Correlation Networks
394
+ by G. Costantini and M. Perugini, PloS one, 9(2), e88669 (2014).
395
+ .. [4] Clustering in complex directed networks by G. Fagiolo,
396
+ Physical Review E, 76(2), 026107 (2007).
397
+ """
398
+ if G.is_directed():
399
+ if weight is not None:
400
+ td_iter = _directed_weighted_triangles_and_degree_iter(G, nodes, weight)
401
+ clusterc = {
402
+ v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
403
+ for v, dt, db, t in td_iter
404
+ }
405
+ else:
406
+ td_iter = _directed_triangles_and_degree_iter(G, nodes)
407
+ clusterc = {
408
+ v: 0 if t == 0 else t / ((dt * (dt - 1) - 2 * db) * 2)
409
+ for v, dt, db, t in td_iter
410
+ }
411
+ else:
412
+ # The formula 2*T/(d*(d-1)) from docs is t/(d*(d-1)) here b/c t==2*T
413
+ if weight is not None:
414
+ td_iter = _weighted_triangles_and_degree_iter(G, nodes, weight)
415
+ clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t in td_iter}
416
+ else:
417
+ td_iter = _triangles_and_degree_iter(G, nodes)
418
+ clusterc = {v: 0 if t == 0 else t / (d * (d - 1)) for v, d, t, _ in td_iter}
419
+ if nodes in G:
420
+ # Return the value of the sole entry in the dictionary.
421
+ return clusterc[nodes]
422
+ return clusterc
423
+
424
+
425
+ @nx._dispatchable
426
+ def transitivity(G):
427
+ r"""Compute graph transitivity, the fraction of all possible triangles
428
+ present in G.
429
+
430
+ Possible triangles are identified by the number of "triads"
431
+ (two edges with a shared vertex).
432
+
433
+ The transitivity is
434
+
435
+ .. math::
436
+
437
+ T = 3\frac{\#triangles}{\#triads}.
438
+
439
+ Parameters
440
+ ----------
441
+ G : graph
442
+
443
+ Returns
444
+ -------
445
+ out : float
446
+ Transitivity
447
+
448
+ Notes
449
+ -----
450
+ Self loops are ignored.
451
+
452
+ Examples
453
+ --------
454
+ >>> G = nx.complete_graph(5)
455
+ >>> print(nx.transitivity(G))
456
+ 1.0
457
+ """
458
+ triangles_contri = [
459
+ (t, d * (d - 1)) for v, d, t, _ in _triangles_and_degree_iter(G)
460
+ ]
461
+ # If the graph is empty
462
+ if len(triangles_contri) == 0:
463
+ return 0
464
+ triangles, contri = map(sum, zip(*triangles_contri))
465
+ return 0 if triangles == 0 else triangles / contri
466
+
467
+
468
+ @nx._dispatchable
469
+ def square_clustering(G, nodes=None):
470
+ r"""Compute the squares clustering coefficient for nodes.
471
+
472
+ For each node return the fraction of possible squares that exist at
473
+ the node [1]_
474
+
475
+ .. math::
476
+ C_4(v) = \frac{ \sum_{u=1}^{k_v}
477
+ \sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v}
478
+ \sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]},
479
+
480
+ where :math:`q_v(u,w)` are the number of common neighbors of :math:`u` and
481
+ :math:`w` other than :math:`v` (ie squares), and :math:`a_v(u,w) = (k_u -
482
+ (1+q_v(u,w)+\theta_{uv})) + (k_w - (1+q_v(u,w)+\theta_{uw}))`, where
483
+ :math:`\theta_{uw} = 1` if :math:`u` and :math:`w` are connected and 0
484
+ otherwise. [2]_
485
+
486
+ Parameters
487
+ ----------
488
+ G : graph
489
+
490
+ nodes : container of nodes, optional (default=all nodes in G)
491
+ Compute clustering for nodes in this container.
492
+
493
+ Returns
494
+ -------
495
+ c4 : dictionary
496
+ A dictionary keyed by node with the square clustering coefficient value.
497
+
498
+ Examples
499
+ --------
500
+ >>> G = nx.complete_graph(5)
501
+ >>> print(nx.square_clustering(G, 0))
502
+ 1.0
503
+ >>> print(nx.square_clustering(G))
504
+ {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
505
+
506
+ Notes
507
+ -----
508
+ While :math:`C_3(v)` (triangle clustering) gives the probability that
509
+ two neighbors of node v are connected with each other, :math:`C_4(v)` is
510
+ the probability that two neighbors of node v share a common
511
+ neighbor different from v. This algorithm can be applied to both
512
+ bipartite and unipartite networks.
513
+
514
+ References
515
+ ----------
516
+ .. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005
517
+ Cycles and clustering in bipartite networks.
518
+ Physical Review E (72) 056127.
519
+ .. [2] Zhang, Peng et al. Clustering Coefficient and Community Structure of
520
+ Bipartite Networks. Physica A: Statistical Mechanics and its Applications 387.27 (2008): 6869–6875.
521
+ https://arxiv.org/abs/0710.0117v1
522
+ """
523
+ if nodes is None:
524
+ node_iter = G
525
+ else:
526
+ node_iter = G.nbunch_iter(nodes)
527
+ clustering = {}
528
+ for v in node_iter:
529
+ clustering[v] = 0
530
+ potential = 0
531
+ for u, w in combinations(G[v], 2):
532
+ squares = len((set(G[u]) & set(G[w])) - {v})
533
+ clustering[v] += squares
534
+ degm = squares + 1
535
+ if w in G[u]:
536
+ degm += 1
537
+ potential += (len(G[u]) - degm) + (len(G[w]) - degm) + squares
538
+ if potential > 0:
539
+ clustering[v] /= potential
540
+ if nodes in G:
541
+ # Return the value of the sole entry in the dictionary.
542
+ return clustering[nodes]
543
+ return clustering
544
+
545
+
546
+ @not_implemented_for("directed")
547
+ @nx._dispatchable
548
+ def generalized_degree(G, nodes=None):
549
+ r"""Compute the generalized degree for nodes.
550
+
551
+ For each node, the generalized degree shows how many edges of given
552
+ triangle multiplicity the node is connected to. The triangle multiplicity
553
+ of an edge is the number of triangles an edge participates in. The
554
+ generalized degree of node :math:`i` can be written as a vector
555
+ :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where
556
+ :math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that
557
+ participate in :math:`j` triangles.
558
+
559
+ Parameters
560
+ ----------
561
+ G : graph
562
+
563
+ nodes : container of nodes, optional (default=all nodes in G)
564
+ Compute the generalized degree for nodes in this container.
565
+
566
+ Returns
567
+ -------
568
+ out : Counter, or dictionary of Counters
569
+ Generalized degree of specified nodes. The Counter is keyed by edge
570
+ triangle multiplicity.
571
+
572
+ Examples
573
+ --------
574
+ >>> G = nx.complete_graph(5)
575
+ >>> print(nx.generalized_degree(G, 0))
576
+ Counter({3: 4})
577
+ >>> print(nx.generalized_degree(G))
578
+ {0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}
579
+
580
+ To recover the number of triangles attached to a node:
581
+
582
+ >>> k1 = nx.generalized_degree(G, 0)
583
+ >>> sum([k * v for k, v in k1.items()]) / 2 == nx.triangles(G, 0)
584
+ True
585
+
586
+ Notes
587
+ -----
588
+ Self loops are ignored.
589
+
590
+ In a network of N nodes, the highest triangle multiplicity an edge can have
591
+ is N-2.
592
+
593
+ The return value does not include a `zero` entry if no edges of a
594
+ particular triangle multiplicity are present.
595
+
596
+ The number of triangles node :math:`i` is attached to can be recovered from
597
+ the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc,
598
+ k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.
599
+
600
+ References
601
+ ----------
602
+ .. [1] Networks with arbitrary edge multiplicities by V. Zlatić,
603
+ D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters),
604
+ Volume 97, Number 2 (2012).
605
+ https://iopscience.iop.org/article/10.1209/0295-5075/97/28005
606
+ """
607
+ if nodes in G:
608
+ return next(_triangles_and_degree_iter(G, nodes))[3]
609
+ return {v: gd for v, d, t, gd in _triangles_and_degree_iter(G, nodes)}
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/communicability_alg.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Communicability.
3
+ """
4
+ import networkx as nx
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = ["communicability", "communicability_exp"]
8
+
9
+
10
+ @not_implemented_for("directed")
11
+ @not_implemented_for("multigraph")
12
+ @nx._dispatchable
13
+ def communicability(G):
14
+ r"""Returns communicability between all pairs of nodes in G.
15
+
16
+ The communicability between pairs of nodes in G is the sum of
17
+ walks of different lengths starting at node u and ending at node v.
18
+
19
+ Parameters
20
+ ----------
21
+ G: graph
22
+
23
+ Returns
24
+ -------
25
+ comm: dictionary of dictionaries
26
+ Dictionary of dictionaries keyed by nodes with communicability
27
+ as the value.
28
+
29
+ Raises
30
+ ------
31
+ NetworkXError
32
+ If the graph is not undirected and simple.
33
+
34
+ See Also
35
+ --------
36
+ communicability_exp:
37
+ Communicability between all pairs of nodes in G using spectral
38
+ decomposition.
39
+ communicability_betweenness_centrality:
40
+ Communicability betweenness centrality for each node in G.
41
+
42
+ Notes
43
+ -----
44
+ This algorithm uses a spectral decomposition of the adjacency matrix.
45
+ Let G=(V,E) be a simple undirected graph. Using the connection between
46
+ the powers of the adjacency matrix and the number of walks in the graph,
47
+ the communicability between nodes `u` and `v` based on the graph spectrum
48
+ is [1]_
49
+
50
+ .. math::
51
+ C(u,v)=\sum_{j=1}^{n}\phi_{j}(u)\phi_{j}(v)e^{\lambda_{j}},
52
+
53
+ where `\phi_{j}(u)` is the `u\rm{th}` element of the `j\rm{th}` orthonormal
54
+ eigenvector of the adjacency matrix associated with the eigenvalue
55
+ `\lambda_{j}`.
56
+
57
+ References
58
+ ----------
59
+ .. [1] Ernesto Estrada, Naomichi Hatano,
60
+ "Communicability in complex networks",
61
+ Phys. Rev. E 77, 036111 (2008).
62
+ https://arxiv.org/abs/0707.0756
63
+
64
+ Examples
65
+ --------
66
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
67
+ >>> c = nx.communicability(G)
68
+ """
69
+ import numpy as np
70
+
71
+ nodelist = list(G) # ordering of nodes in matrix
72
+ A = nx.to_numpy_array(G, nodelist)
73
+ # convert to 0-1 matrix
74
+ A[A != 0.0] = 1
75
+ w, vec = np.linalg.eigh(A)
76
+ expw = np.exp(w)
77
+ mapping = dict(zip(nodelist, range(len(nodelist))))
78
+ c = {}
79
+ # computing communicabilities
80
+ for u in G:
81
+ c[u] = {}
82
+ for v in G:
83
+ s = 0
84
+ p = mapping[u]
85
+ q = mapping[v]
86
+ for j in range(len(nodelist)):
87
+ s += vec[:, j][p] * vec[:, j][q] * expw[j]
88
+ c[u][v] = float(s)
89
+ return c
90
+
91
+
92
+ @not_implemented_for("directed")
93
+ @not_implemented_for("multigraph")
94
+ @nx._dispatchable
95
+ def communicability_exp(G):
96
+ r"""Returns communicability between all pairs of nodes in G.
97
+
98
+ Communicability between pair of node (u,v) of node in G is the sum of
99
+ walks of different lengths starting at node u and ending at node v.
100
+
101
+ Parameters
102
+ ----------
103
+ G: graph
104
+
105
+ Returns
106
+ -------
107
+ comm: dictionary of dictionaries
108
+ Dictionary of dictionaries keyed by nodes with communicability
109
+ as the value.
110
+
111
+ Raises
112
+ ------
113
+ NetworkXError
114
+ If the graph is not undirected and simple.
115
+
116
+ See Also
117
+ --------
118
+ communicability:
119
+ Communicability between pairs of nodes in G.
120
+ communicability_betweenness_centrality:
121
+ Communicability betweenness centrality for each node in G.
122
+
123
+ Notes
124
+ -----
125
+ This algorithm uses matrix exponentiation of the adjacency matrix.
126
+
127
+ Let G=(V,E) be a simple undirected graph. Using the connection between
128
+ the powers of the adjacency matrix and the number of walks in the graph,
129
+ the communicability between nodes u and v is [1]_,
130
+
131
+ .. math::
132
+ C(u,v) = (e^A)_{uv},
133
+
134
+ where `A` is the adjacency matrix of G.
135
+
136
+ References
137
+ ----------
138
+ .. [1] Ernesto Estrada, Naomichi Hatano,
139
+ "Communicability in complex networks",
140
+ Phys. Rev. E 77, 036111 (2008).
141
+ https://arxiv.org/abs/0707.0756
142
+
143
+ Examples
144
+ --------
145
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
146
+ >>> c = nx.communicability_exp(G)
147
+ """
148
+ import scipy as sp
149
+
150
+ nodelist = list(G) # ordering of nodes in matrix
151
+ A = nx.to_numpy_array(G, nodelist)
152
+ # convert to 0-1 matrix
153
+ A[A != 0.0] = 1
154
+ # communicability matrix
155
+ expA = sp.linalg.expm(A)
156
+ mapping = dict(zip(nodelist, range(len(nodelist))))
157
+ c = {}
158
+ for u in G:
159
+ c[u] = {}
160
+ for v in G:
161
+ c[u][v] = float(expA[mapping[u], mapping[v]])
162
+ return c
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/core.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Find the k-cores of a graph.
3
+
4
+ The k-core is found by recursively pruning nodes with degrees less than k.
5
+
6
+ See the following references for details:
7
+
8
+ An O(m) Algorithm for Cores Decomposition of Networks
9
+ Vladimir Batagelj and Matjaz Zaversnik, 2003.
10
+ https://arxiv.org/abs/cs.DS/0310049
11
+
12
+ Generalized Cores
13
+ Vladimir Batagelj and Matjaz Zaversnik, 2002.
14
+ https://arxiv.org/pdf/cs/0202039
15
+
16
+ For directed graphs a more general notion is that of D-cores which
17
+ looks at (k, l) restrictions on (in, out) degree. The (k, k) D-core
18
+ is the k-core.
19
+
20
+ D-cores: Measuring Collaboration of Directed Graphs Based on Degeneracy
21
+ Christos Giatsidis, Dimitrios M. Thilikos, Michalis Vazirgiannis, ICDM 2011.
22
+ http://www.graphdegeneracy.org/dcores_ICDM_2011.pdf
23
+
24
+ Multi-scale structure and topological anomaly detection via a new network \
25
+ statistic: The onion decomposition
26
+ L. Hébert-Dufresne, J. A. Grochow, and A. Allard
27
+ Scientific Reports 6, 31708 (2016)
28
+ http://doi.org/10.1038/srep31708
29
+
30
+ """
31
+ import networkx as nx
32
+
33
+ __all__ = [
34
+ "core_number",
35
+ "k_core",
36
+ "k_shell",
37
+ "k_crust",
38
+ "k_corona",
39
+ "k_truss",
40
+ "onion_layers",
41
+ ]
42
+
43
+
44
+ @nx.utils.not_implemented_for("multigraph")
45
+ @nx._dispatchable
46
+ def core_number(G):
47
+ """Returns the core number for each node.
48
+
49
+ A k-core is a maximal subgraph that contains nodes of degree k or more.
50
+
51
+ The core number of a node is the largest value k of a k-core containing
52
+ that node.
53
+
54
+ Parameters
55
+ ----------
56
+ G : NetworkX graph
57
+ An undirected or directed graph
58
+
59
+ Returns
60
+ -------
61
+ core_number : dictionary
62
+ A dictionary keyed by node to the core number.
63
+
64
+ Raises
65
+ ------
66
+ NetworkXNotImplemented
67
+ If `G` is a multigraph or contains self loops.
68
+
69
+ Notes
70
+ -----
71
+ For directed graphs the node degree is defined to be the
72
+ in-degree + out-degree.
73
+
74
+ Examples
75
+ --------
76
+ >>> degrees = [0, 1, 2, 2, 2, 2, 3]
77
+ >>> H = nx.havel_hakimi_graph(degrees)
78
+ >>> nx.core_number(H)
79
+ {0: 1, 1: 2, 2: 2, 3: 2, 4: 1, 5: 2, 6: 0}
80
+ >>> G = nx.DiGraph()
81
+ >>> G.add_edges_from([(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)])
82
+ >>> nx.core_number(G)
83
+ {1: 2, 2: 2, 3: 2, 4: 2}
84
+
85
+ References
86
+ ----------
87
+ .. [1] An O(m) Algorithm for Cores Decomposition of Networks
88
+ Vladimir Batagelj and Matjaz Zaversnik, 2003.
89
+ https://arxiv.org/abs/cs.DS/0310049
90
+ """
91
+ if nx.number_of_selfloops(G) > 0:
92
+ msg = (
93
+ "Input graph has self loops which is not permitted; "
94
+ "Consider using G.remove_edges_from(nx.selfloop_edges(G))."
95
+ )
96
+ raise nx.NetworkXNotImplemented(msg)
97
+ degrees = dict(G.degree())
98
+ # Sort nodes by degree.
99
+ nodes = sorted(degrees, key=degrees.get)
100
+ bin_boundaries = [0]
101
+ curr_degree = 0
102
+ for i, v in enumerate(nodes):
103
+ if degrees[v] > curr_degree:
104
+ bin_boundaries.extend([i] * (degrees[v] - curr_degree))
105
+ curr_degree = degrees[v]
106
+ node_pos = {v: pos for pos, v in enumerate(nodes)}
107
+ # The initial guess for the core number of a node is its degree.
108
+ core = degrees
109
+ nbrs = {v: list(nx.all_neighbors(G, v)) for v in G}
110
+ for v in nodes:
111
+ for u in nbrs[v]:
112
+ if core[u] > core[v]:
113
+ nbrs[u].remove(v)
114
+ pos = node_pos[u]
115
+ bin_start = bin_boundaries[core[u]]
116
+ node_pos[u] = bin_start
117
+ node_pos[nodes[bin_start]] = pos
118
+ nodes[bin_start], nodes[pos] = nodes[pos], nodes[bin_start]
119
+ bin_boundaries[core[u]] += 1
120
+ core[u] -= 1
121
+ return core
122
+
123
+
124
+ def _core_subgraph(G, k_filter, k=None, core=None):
125
+ """Returns the subgraph induced by nodes passing filter `k_filter`.
126
+
127
+ Parameters
128
+ ----------
129
+ G : NetworkX graph
130
+ The graph or directed graph to process
131
+ k_filter : filter function
132
+ This function filters the nodes chosen. It takes three inputs:
133
+ A node of G, the filter's cutoff, and the core dict of the graph.
134
+ The function should return a Boolean value.
135
+ k : int, optional
136
+ The order of the core. If not specified use the max core number.
137
+ This value is used as the cutoff for the filter.
138
+ core : dict, optional
139
+ Precomputed core numbers keyed by node for the graph `G`.
140
+ If not specified, the core numbers will be computed from `G`.
141
+
142
+ """
143
+ if core is None:
144
+ core = core_number(G)
145
+ if k is None:
146
+ k = max(core.values())
147
+ nodes = (v for v in core if k_filter(v, k, core))
148
+ return G.subgraph(nodes).copy()
149
+
150
+
151
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
152
+ def k_core(G, k=None, core_number=None):
153
+ """Returns the k-core of G.
154
+
155
+ A k-core is a maximal subgraph that contains nodes of degree `k` or more.
156
+
157
+ .. deprecated:: 3.3
158
+ `k_core` will not accept `MultiGraph` objects in version 3.5.
159
+
160
+ Parameters
161
+ ----------
162
+ G : NetworkX graph
163
+ A graph or directed graph
164
+ k : int, optional
165
+ The order of the core. If not specified return the main core.
166
+ core_number : dictionary, optional
167
+ Precomputed core numbers for the graph G.
168
+
169
+ Returns
170
+ -------
171
+ G : NetworkX graph
172
+ The k-core subgraph
173
+
174
+ Raises
175
+ ------
176
+ NetworkXNotImplemented
177
+ The k-core is not defined for multigraphs or graphs with self loops.
178
+
179
+ Notes
180
+ -----
181
+ The main core is the core with `k` as the largest core_number.
182
+
183
+ For directed graphs the node degree is defined to be the
184
+ in-degree + out-degree.
185
+
186
+ Graph, node, and edge attributes are copied to the subgraph.
187
+
188
+ Examples
189
+ --------
190
+ >>> degrees = [0, 1, 2, 2, 2, 2, 3]
191
+ >>> H = nx.havel_hakimi_graph(degrees)
192
+ >>> H.degree
193
+ DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
194
+ >>> nx.k_core(H).nodes
195
+ NodeView((1, 2, 3, 5))
196
+
197
+ See Also
198
+ --------
199
+ core_number
200
+
201
+ References
202
+ ----------
203
+ .. [1] An O(m) Algorithm for Cores Decomposition of Networks
204
+ Vladimir Batagelj and Matjaz Zaversnik, 2003.
205
+ https://arxiv.org/abs/cs.DS/0310049
206
+ """
207
+
208
+ import warnings
209
+
210
+ if G.is_multigraph():
211
+ warnings.warn(
212
+ (
213
+ "\n\n`k_core` will not accept `MultiGraph` objects in version 3.5.\n"
214
+ "Convert it to an undirected graph instead, using::\n\n"
215
+ "\tG = nx.Graph(G)\n"
216
+ ),
217
+ category=DeprecationWarning,
218
+ stacklevel=5,
219
+ )
220
+
221
+ def k_filter(v, k, c):
222
+ return c[v] >= k
223
+
224
+ return _core_subgraph(G, k_filter, k, core_number)
225
+
226
+
227
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
228
+ def k_shell(G, k=None, core_number=None):
229
+ """Returns the k-shell of G.
230
+
231
+ The k-shell is the subgraph induced by nodes with core number k.
232
+ That is, nodes in the k-core that are not in the (k+1)-core.
233
+
234
+ .. deprecated:: 3.3
235
+ `k_shell` will not accept `MultiGraph` objects in version 3.5.
236
+
237
+ Parameters
238
+ ----------
239
+ G : NetworkX graph
240
+ A graph or directed graph.
241
+ k : int, optional
242
+ The order of the shell. If not specified return the outer shell.
243
+ core_number : dictionary, optional
244
+ Precomputed core numbers for the graph G.
245
+
246
+
247
+ Returns
248
+ -------
249
+ G : NetworkX graph
250
+ The k-shell subgraph
251
+
252
+ Raises
253
+ ------
254
+ NetworkXNotImplemented
255
+ The k-shell is not implemented for multigraphs or graphs with self loops.
256
+
257
+ Notes
258
+ -----
259
+ This is similar to k_corona but in that case only neighbors in the
260
+ k-core are considered.
261
+
262
+ For directed graphs the node degree is defined to be the
263
+ in-degree + out-degree.
264
+
265
+ Graph, node, and edge attributes are copied to the subgraph.
266
+
267
+ Examples
268
+ --------
269
+ >>> degrees = [0, 1, 2, 2, 2, 2, 3]
270
+ >>> H = nx.havel_hakimi_graph(degrees)
271
+ >>> H.degree
272
+ DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
273
+ >>> nx.k_shell(H, k=1).nodes
274
+ NodeView((0, 4))
275
+
276
+ See Also
277
+ --------
278
+ core_number
279
+ k_corona
280
+
281
+
282
+ References
283
+ ----------
284
+ .. [1] A model of Internet topology using k-shell decomposition
285
+ Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
286
+ and Eran Shir, PNAS July 3, 2007 vol. 104 no. 27 11150-11154
287
+ http://www.pnas.org/content/104/27/11150.full
288
+ """
289
+
290
+ import warnings
291
+
292
+ if G.is_multigraph():
293
+ warnings.warn(
294
+ (
295
+ "\n\n`k_shell` will not accept `MultiGraph` objects in version 3.5.\n"
296
+ "Convert it to an undirected graph instead, using::\n\n"
297
+ "\tG = nx.Graph(G)\n"
298
+ ),
299
+ category=DeprecationWarning,
300
+ stacklevel=5,
301
+ )
302
+
303
+ def k_filter(v, k, c):
304
+ return c[v] == k
305
+
306
+ return _core_subgraph(G, k_filter, k, core_number)
307
+
308
+
309
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
310
+ def k_crust(G, k=None, core_number=None):
311
+ """Returns the k-crust of G.
312
+
313
+ The k-crust is the graph G with the edges of the k-core removed
314
+ and isolated nodes found after the removal of edges are also removed.
315
+
316
+ .. deprecated:: 3.3
317
+ `k_crust` will not accept `MultiGraph` objects in version 3.5.
318
+
319
+ Parameters
320
+ ----------
321
+ G : NetworkX graph
322
+ A graph or directed graph.
323
+ k : int, optional
324
+ The order of the shell. If not specified return the main crust.
325
+ core_number : dictionary, optional
326
+ Precomputed core numbers for the graph G.
327
+
328
+ Returns
329
+ -------
330
+ G : NetworkX graph
331
+ The k-crust subgraph
332
+
333
+ Raises
334
+ ------
335
+ NetworkXNotImplemented
336
+ The k-crust is not implemented for multigraphs or graphs with self loops.
337
+
338
+ Notes
339
+ -----
340
+ This definition of k-crust is different than the definition in [1]_.
341
+ The k-crust in [1]_ is equivalent to the k+1 crust of this algorithm.
342
+
343
+ For directed graphs the node degree is defined to be the
344
+ in-degree + out-degree.
345
+
346
+ Graph, node, and edge attributes are copied to the subgraph.
347
+
348
+ Examples
349
+ --------
350
+ >>> degrees = [0, 1, 2, 2, 2, 2, 3]
351
+ >>> H = nx.havel_hakimi_graph(degrees)
352
+ >>> H.degree
353
+ DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
354
+ >>> nx.k_crust(H, k=1).nodes
355
+ NodeView((0, 4, 6))
356
+
357
+ See Also
358
+ --------
359
+ core_number
360
+
361
+ References
362
+ ----------
363
+ .. [1] A model of Internet topology using k-shell decomposition
364
+ Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt,
365
+ and Eran Shir, PNAS July 3, 2007 vol. 104 no. 27 11150-11154
366
+ http://www.pnas.org/content/104/27/11150.full
367
+ """
368
+
369
+ import warnings
370
+
371
+ if G.is_multigraph():
372
+ warnings.warn(
373
+ (
374
+ "\n\n`k_crust` will not accept `MultiGraph` objects in version 3.5.\n"
375
+ "Convert it to an undirected graph instead, using::\n\n"
376
+ "\tG = nx.Graph(G)\n"
377
+ ),
378
+ category=DeprecationWarning,
379
+ stacklevel=5,
380
+ )
381
+
382
+ # Default for k is one less than in _core_subgraph, so just inline.
383
+ # Filter is c[v] <= k
384
+ if core_number is None:
385
+ core_number = nx.core_number(G)
386
+ if k is None:
387
+ k = max(core_number.values()) - 1
388
+ nodes = (v for v in core_number if core_number[v] <= k)
389
+ return G.subgraph(nodes).copy()
390
+
391
+
392
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
393
+ def k_corona(G, k, core_number=None):
394
+ """Returns the k-corona of G.
395
+
396
+ The k-corona is the subgraph of nodes in the k-core which have
397
+ exactly k neighbors in the k-core.
398
+
399
+ .. deprecated:: 3.3
400
+ `k_corona` will not accept `MultiGraph` objects in version 3.5.
401
+
402
+ Parameters
403
+ ----------
404
+ G : NetworkX graph
405
+ A graph or directed graph
406
+ k : int
407
+ The order of the corona.
408
+ core_number : dictionary, optional
409
+ Precomputed core numbers for the graph G.
410
+
411
+ Returns
412
+ -------
413
+ G : NetworkX graph
414
+ The k-corona subgraph
415
+
416
+ Raises
417
+ ------
418
+ NetworkXNotImplemented
419
+ The k-corona is not defined for multigraphs or graphs with self loops.
420
+
421
+ Notes
422
+ -----
423
+ For directed graphs the node degree is defined to be the
424
+ in-degree + out-degree.
425
+
426
+ Graph, node, and edge attributes are copied to the subgraph.
427
+
428
+ Examples
429
+ --------
430
+ >>> degrees = [0, 1, 2, 2, 2, 2, 3]
431
+ >>> H = nx.havel_hakimi_graph(degrees)
432
+ >>> H.degree
433
+ DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
434
+ >>> nx.k_corona(H, k=2).nodes
435
+ NodeView((1, 2, 3, 5))
436
+
437
+ See Also
438
+ --------
439
+ core_number
440
+
441
+ References
442
+ ----------
443
+ .. [1] k -core (bootstrap) percolation on complex networks:
444
+ Critical phenomena and nonlocal effects,
445
+ A. V. Goltsev, S. N. Dorogovtsev, and J. F. F. Mendes,
446
+ Phys. Rev. E 73, 056101 (2006)
447
+ http://link.aps.org/doi/10.1103/PhysRevE.73.056101
448
+ """
449
+
450
+ import warnings
451
+
452
+ if G.is_multigraph():
453
+ warnings.warn(
454
+ (
455
+ "\n\n`k_corona` will not accept `MultiGraph` objects in version 3.5.\n"
456
+ "Convert it to an undirected graph instead, using::\n\n"
457
+ "\tG = nx.Graph(G)\n"
458
+ ),
459
+ category=DeprecationWarning,
460
+ stacklevel=5,
461
+ )
462
+
463
+ def func(v, k, c):
464
+ return c[v] == k and k == sum(1 for w in G[v] if c[w] >= k)
465
+
466
+ return _core_subgraph(G, func, k, core_number)
467
+
468
+
469
+ @nx.utils.not_implemented_for("directed")
470
+ @nx.utils.not_implemented_for("multigraph")
471
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
472
+ def k_truss(G, k):
473
+ """Returns the k-truss of `G`.
474
+
475
+ The k-truss is the maximal induced subgraph of `G` which contains at least
476
+ three vertices where every edge is incident to at least `k-2` triangles.
477
+
478
+ Parameters
479
+ ----------
480
+ G : NetworkX graph
481
+ An undirected graph
482
+ k : int
483
+ The order of the truss
484
+
485
+ Returns
486
+ -------
487
+ H : NetworkX graph
488
+ The k-truss subgraph
489
+
490
+ Raises
491
+ ------
492
+ NetworkXNotImplemented
493
+ If `G` is a multigraph or directed graph or if it contains self loops.
494
+
495
+ Notes
496
+ -----
497
+ A k-clique is a (k-2)-truss and a k-truss is a (k+1)-core.
498
+
499
+ Graph, node, and edge attributes are copied to the subgraph.
500
+
501
+ K-trusses were originally defined in [2] which states that the k-truss
502
+ is the maximal induced subgraph where each edge belongs to at least
503
+ `k-2` triangles. A more recent paper, [1], uses a slightly different
504
+ definition requiring that each edge belong to at least `k` triangles.
505
+ This implementation uses the original definition of `k-2` triangles.
506
+
507
+ Examples
508
+ --------
509
+ >>> degrees = [0, 1, 2, 2, 2, 2, 3]
510
+ >>> H = nx.havel_hakimi_graph(degrees)
511
+ >>> H.degree
512
+ DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
513
+ >>> nx.k_truss(H, k=2).nodes
514
+ NodeView((0, 1, 2, 3, 4, 5))
515
+
516
+ References
517
+ ----------
518
+ .. [1] Bounds and Algorithms for k-truss. Paul Burkhardt, Vance Faber,
519
+ David G. Harris, 2018. https://arxiv.org/abs/1806.05523v2
520
+ .. [2] Trusses: Cohesive Subgraphs for Social Network Analysis. Jonathan
521
+ Cohen, 2005.
522
+ """
523
+ if nx.number_of_selfloops(G) > 0:
524
+ msg = (
525
+ "Input graph has self loops which is not permitted; "
526
+ "Consider using G.remove_edges_from(nx.selfloop_edges(G))."
527
+ )
528
+ raise nx.NetworkXNotImplemented(msg)
529
+
530
+ H = G.copy()
531
+
532
+ n_dropped = 1
533
+ while n_dropped > 0:
534
+ n_dropped = 0
535
+ to_drop = []
536
+ seen = set()
537
+ for u in H:
538
+ nbrs_u = set(H[u])
539
+ seen.add(u)
540
+ new_nbrs = [v for v in nbrs_u if v not in seen]
541
+ for v in new_nbrs:
542
+ if len(nbrs_u & set(H[v])) < (k - 2):
543
+ to_drop.append((u, v))
544
+ H.remove_edges_from(to_drop)
545
+ n_dropped = len(to_drop)
546
+ H.remove_nodes_from(list(nx.isolates(H)))
547
+
548
+ return H
549
+
550
+
551
+ @nx.utils.not_implemented_for("multigraph")
552
+ @nx.utils.not_implemented_for("directed")
553
+ @nx._dispatchable
554
+ def onion_layers(G):
555
+ """Returns the layer of each vertex in an onion decomposition of the graph.
556
+
557
+ The onion decomposition refines the k-core decomposition by providing
558
+ information on the internal organization of each k-shell. It is usually
559
+ used alongside the `core numbers`.
560
+
561
+ Parameters
562
+ ----------
563
+ G : NetworkX graph
564
+ An undirected graph without self loops.
565
+
566
+ Returns
567
+ -------
568
+ od_layers : dictionary
569
+ A dictionary keyed by node to the onion layer. The layers are
570
+ contiguous integers starting at 1.
571
+
572
+ Raises
573
+ ------
574
+ NetworkXNotImplemented
575
+ If `G` is a multigraph or directed graph or if it contains self loops.
576
+
577
+ Examples
578
+ --------
579
+ >>> degrees = [0, 1, 2, 2, 2, 2, 3]
580
+ >>> H = nx.havel_hakimi_graph(degrees)
581
+ >>> H.degree
582
+ DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
583
+ >>> nx.onion_layers(H)
584
+ {6: 1, 0: 2, 4: 3, 1: 4, 2: 4, 3: 4, 5: 4}
585
+
586
+ See Also
587
+ --------
588
+ core_number
589
+
590
+ References
591
+ ----------
592
+ .. [1] Multi-scale structure and topological anomaly detection via a new
593
+ network statistic: The onion decomposition
594
+ L. Hébert-Dufresne, J. A. Grochow, and A. Allard
595
+ Scientific Reports 6, 31708 (2016)
596
+ http://doi.org/10.1038/srep31708
597
+ .. [2] Percolation and the effective structure of complex networks
598
+ A. Allard and L. Hébert-Dufresne
599
+ Physical Review X 9, 011023 (2019)
600
+ http://doi.org/10.1103/PhysRevX.9.011023
601
+ """
602
+ if nx.number_of_selfloops(G) > 0:
603
+ msg = (
604
+ "Input graph contains self loops which is not permitted; "
605
+ "Consider using G.remove_edges_from(nx.selfloop_edges(G))."
606
+ )
607
+ raise nx.NetworkXNotImplemented(msg)
608
+ # Dictionaries to register the k-core/onion decompositions.
609
+ od_layers = {}
610
+ # Adjacency list
611
+ neighbors = {v: list(nx.all_neighbors(G, v)) for v in G}
612
+ # Effective degree of nodes.
613
+ degrees = dict(G.degree())
614
+ # Performs the onion decomposition.
615
+ current_core = 1
616
+ current_layer = 1
617
+ # Sets vertices of degree 0 to layer 1, if any.
618
+ isolated_nodes = list(nx.isolates(G))
619
+ if len(isolated_nodes) > 0:
620
+ for v in isolated_nodes:
621
+ od_layers[v] = current_layer
622
+ degrees.pop(v)
623
+ current_layer = 2
624
+ # Finds the layer for the remaining nodes.
625
+ while len(degrees) > 0:
626
+ # Sets the order for looking at nodes.
627
+ nodes = sorted(degrees, key=degrees.get)
628
+ # Sets properly the current core.
629
+ min_degree = degrees[nodes[0]]
630
+ if min_degree > current_core:
631
+ current_core = min_degree
632
+ # Identifies vertices in the current layer.
633
+ this_layer = []
634
+ for n in nodes:
635
+ if degrees[n] > current_core:
636
+ break
637
+ this_layer.append(n)
638
+ # Identifies the core/layer of the vertices in the current layer.
639
+ for v in this_layer:
640
+ od_layers[v] = current_layer
641
+ for n in neighbors[v]:
642
+ neighbors[n].remove(v)
643
+ degrees[n] = degrees[n] - 1
644
+ degrees.pop(v)
645
+ # Updates the layer count.
646
+ current_layer = current_layer + 1
647
+ # Returns the dictionaries containing the onion layer of each vertices.
648
+ return od_layers
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/covering.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Functions related to graph covers."""
2
+
3
+ from functools import partial
4
+ from itertools import chain
5
+
6
+ import networkx as nx
7
+ from networkx.utils import arbitrary_element, not_implemented_for
8
+
9
+ __all__ = ["min_edge_cover", "is_edge_cover"]
10
+
11
+
12
+ @not_implemented_for("directed")
13
+ @not_implemented_for("multigraph")
14
+ @nx._dispatchable
15
+ def min_edge_cover(G, matching_algorithm=None):
16
+ """Returns the min cardinality edge cover of the graph as a set of edges.
17
+
18
+ A smallest edge cover can be found in polynomial time by finding
19
+ a maximum matching and extending it greedily so that all nodes
20
+ are covered. This function follows that process. A maximum matching
21
+ algorithm can be specified for the first step of the algorithm.
22
+ The resulting set may return a set with one 2-tuple for each edge,
23
+ (the usual case) or with both 2-tuples `(u, v)` and `(v, u)` for
24
+ each edge. The latter is only done when a bipartite matching algorithm
25
+ is specified as `matching_algorithm`.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+ An undirected graph.
31
+
32
+ matching_algorithm : function
33
+ A function that returns a maximum cardinality matching for `G`.
34
+ The function must take one input, the graph `G`, and return
35
+ either a set of edges (with only one direction for the pair of nodes)
36
+ or a dictionary mapping each node to its mate. If not specified,
37
+ :func:`~networkx.algorithms.matching.max_weight_matching` is used.
38
+ Common bipartite matching functions include
39
+ :func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
40
+ or
41
+ :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`.
42
+
43
+ Returns
44
+ -------
45
+ min_cover : set
46
+
47
+ A set of the edges in a minimum edge cover in the form of tuples.
48
+ It contains only one of the equivalent 2-tuples `(u, v)` and `(v, u)`
49
+ for each edge. If a bipartite method is used to compute the matching,
50
+ the returned set contains both the 2-tuples `(u, v)` and `(v, u)`
51
+ for each edge of a minimum edge cover.
52
+
53
+ Examples
54
+ --------
55
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
56
+ >>> sorted(nx.min_edge_cover(G))
57
+ [(2, 1), (3, 0)]
58
+
59
+ Notes
60
+ -----
61
+ An edge cover of a graph is a set of edges such that every node of
62
+ the graph is incident to at least one edge of the set.
63
+ The minimum edge cover is an edge covering of smallest cardinality.
64
+
65
+ Due to its implementation, the worst-case running time of this algorithm
66
+ is bounded by the worst-case running time of the function
67
+ ``matching_algorithm``.
68
+
69
+ Minimum edge cover for `G` can also be found using the `min_edge_covering`
70
+ function in :mod:`networkx.algorithms.bipartite.covering` which is
71
+ simply this function with a default matching algorithm of
72
+ :func:`~networkx.algorithms.bipartite.matching.hopcraft_karp_matching`
73
+ """
74
+ if len(G) == 0:
75
+ return set()
76
+ if nx.number_of_isolates(G) > 0:
77
+ # ``min_cover`` does not exist as there is an isolated node
78
+ raise nx.NetworkXException(
79
+ "Graph has a node with no edge incident on it, so no edge cover exists."
80
+ )
81
+ if matching_algorithm is None:
82
+ matching_algorithm = partial(nx.max_weight_matching, maxcardinality=True)
83
+ maximum_matching = matching_algorithm(G)
84
+ # ``min_cover`` is superset of ``maximum_matching``
85
+ try:
86
+ # bipartite matching algs return dict so convert if needed
87
+ min_cover = set(maximum_matching.items())
88
+ bipartite_cover = True
89
+ except AttributeError:
90
+ min_cover = maximum_matching
91
+ bipartite_cover = False
92
+ # iterate for uncovered nodes
93
+ uncovered_nodes = set(G) - {v for u, v in min_cover} - {u for u, v in min_cover}
94
+ for v in uncovered_nodes:
95
+ # Since `v` is uncovered, each edge incident to `v` will join it
96
+ # with a covered node (otherwise, if there were an edge joining
97
+ # uncovered nodes `u` and `v`, the maximum matching algorithm
98
+ # would have found it), so we can choose an arbitrary edge
99
+ # incident to `v`. (This applies only in a simple graph, not a
100
+ # multigraph.)
101
+ u = arbitrary_element(G[v])
102
+ min_cover.add((u, v))
103
+ if bipartite_cover:
104
+ min_cover.add((v, u))
105
+ return min_cover
106
+
107
+
108
+ @not_implemented_for("directed")
109
+ @nx._dispatchable
110
+ def is_edge_cover(G, cover):
111
+ """Decides whether a set of edges is a valid edge cover of the graph.
112
+
113
+ Given a set of edges, whether it is an edge covering can
114
+ be decided if we just check whether all nodes of the graph
115
+ has an edge from the set, incident on it.
116
+
117
+ Parameters
118
+ ----------
119
+ G : NetworkX graph
120
+ An undirected bipartite graph.
121
+
122
+ cover : set
123
+ Set of edges to be checked.
124
+
125
+ Returns
126
+ -------
127
+ bool
128
+ Whether the set of edges is a valid edge cover of the graph.
129
+
130
+ Examples
131
+ --------
132
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
133
+ >>> cover = {(2, 1), (3, 0)}
134
+ >>> nx.is_edge_cover(G, cover)
135
+ True
136
+
137
+ Notes
138
+ -----
139
+ An edge cover of a graph is a set of edges such that every node of
140
+ the graph is incident to at least one edge of the set.
141
+ """
142
+ return set(G) <= set(chain.from_iterable(cover))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/cuts.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for finding and evaluating cuts in a graph.
2
+
3
+ """
4
+
5
+ from itertools import chain
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = [
10
+ "boundary_expansion",
11
+ "conductance",
12
+ "cut_size",
13
+ "edge_expansion",
14
+ "mixing_expansion",
15
+ "node_expansion",
16
+ "normalized_cut_size",
17
+ "volume",
18
+ ]
19
+
20
+
21
+ # TODO STILL NEED TO UPDATE ALL THE DOCUMENTATION!
22
+
23
+
24
+ @nx._dispatchable(edge_attrs="weight")
25
+ def cut_size(G, S, T=None, weight=None):
26
+ """Returns the size of the cut between two sets of nodes.
27
+
28
+ A *cut* is a partition of the nodes of a graph into two sets. The
29
+ *cut size* is the sum of the weights of the edges "between" the two
30
+ sets of nodes.
31
+
32
+ Parameters
33
+ ----------
34
+ G : NetworkX graph
35
+
36
+ S : collection
37
+ A collection of nodes in `G`.
38
+
39
+ T : collection
40
+ A collection of nodes in `G`. If not specified, this is taken to
41
+ be the set complement of `S`.
42
+
43
+ weight : object
44
+ Edge attribute key to use as weight. If not specified, edges
45
+ have weight one.
46
+
47
+ Returns
48
+ -------
49
+ number
50
+ Total weight of all edges from nodes in set `S` to nodes in
51
+ set `T` (and, in the case of directed graphs, all edges from
52
+ nodes in `T` to nodes in `S`).
53
+
54
+ Examples
55
+ --------
56
+ In the graph with two cliques joined by a single edges, the natural
57
+ bipartition of the graph into two blocks, one for each clique,
58
+ yields a cut of weight one::
59
+
60
+ >>> G = nx.barbell_graph(3, 0)
61
+ >>> S = {0, 1, 2}
62
+ >>> T = {3, 4, 5}
63
+ >>> nx.cut_size(G, S, T)
64
+ 1
65
+
66
+ Each parallel edge in a multigraph is counted when determining the
67
+ cut size::
68
+
69
+ >>> G = nx.MultiGraph(["ab", "ab"])
70
+ >>> S = {"a"}
71
+ >>> T = {"b"}
72
+ >>> nx.cut_size(G, S, T)
73
+ 2
74
+
75
+ Notes
76
+ -----
77
+ In a multigraph, the cut size is the total weight of edges including
78
+ multiplicity.
79
+
80
+ """
81
+ edges = nx.edge_boundary(G, S, T, data=weight, default=1)
82
+ if G.is_directed():
83
+ edges = chain(edges, nx.edge_boundary(G, T, S, data=weight, default=1))
84
+ return sum(weight for u, v, weight in edges)
85
+
86
+
87
+ @nx._dispatchable(edge_attrs="weight")
88
+ def volume(G, S, weight=None):
89
+ """Returns the volume of a set of nodes.
90
+
91
+ The *volume* of a set *S* is the sum of the (out-)degrees of nodes
92
+ in *S* (taking into account parallel edges in multigraphs). [1]
93
+
94
+ Parameters
95
+ ----------
96
+ G : NetworkX graph
97
+
98
+ S : collection
99
+ A collection of nodes in `G`.
100
+
101
+ weight : object
102
+ Edge attribute key to use as weight. If not specified, edges
103
+ have weight one.
104
+
105
+ Returns
106
+ -------
107
+ number
108
+ The volume of the set of nodes represented by `S` in the graph
109
+ `G`.
110
+
111
+ See also
112
+ --------
113
+ conductance
114
+ cut_size
115
+ edge_expansion
116
+ edge_boundary
117
+ normalized_cut_size
118
+
119
+ References
120
+ ----------
121
+ .. [1] David Gleich.
122
+ *Hierarchical Directed Spectral Graph Partitioning*.
123
+ <https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
124
+
125
+ """
126
+ degree = G.out_degree if G.is_directed() else G.degree
127
+ return sum(d for v, d in degree(S, weight=weight))
128
+
129
+
130
+ @nx._dispatchable(edge_attrs="weight")
131
+ def normalized_cut_size(G, S, T=None, weight=None):
132
+ """Returns the normalized size of the cut between two sets of nodes.
133
+
134
+ The *normalized cut size* is the cut size times the sum of the
135
+ reciprocal sizes of the volumes of the two sets. [1]
136
+
137
+ Parameters
138
+ ----------
139
+ G : NetworkX graph
140
+
141
+ S : collection
142
+ A collection of nodes in `G`.
143
+
144
+ T : collection
145
+ A collection of nodes in `G`.
146
+
147
+ weight : object
148
+ Edge attribute key to use as weight. If not specified, edges
149
+ have weight one.
150
+
151
+ Returns
152
+ -------
153
+ number
154
+ The normalized cut size between the two sets `S` and `T`.
155
+
156
+ Notes
157
+ -----
158
+ In a multigraph, the cut size is the total weight of edges including
159
+ multiplicity.
160
+
161
+ See also
162
+ --------
163
+ conductance
164
+ cut_size
165
+ edge_expansion
166
+ volume
167
+
168
+ References
169
+ ----------
170
+ .. [1] David Gleich.
171
+ *Hierarchical Directed Spectral Graph Partitioning*.
172
+ <https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
173
+
174
+ """
175
+ if T is None:
176
+ T = set(G) - set(S)
177
+ num_cut_edges = cut_size(G, S, T=T, weight=weight)
178
+ volume_S = volume(G, S, weight=weight)
179
+ volume_T = volume(G, T, weight=weight)
180
+ return num_cut_edges * ((1 / volume_S) + (1 / volume_T))
181
+
182
+
183
+ @nx._dispatchable(edge_attrs="weight")
184
+ def conductance(G, S, T=None, weight=None):
185
+ """Returns the conductance of two sets of nodes.
186
+
187
+ The *conductance* is the quotient of the cut size and the smaller of
188
+ the volumes of the two sets. [1]
189
+
190
+ Parameters
191
+ ----------
192
+ G : NetworkX graph
193
+
194
+ S : collection
195
+ A collection of nodes in `G`.
196
+
197
+ T : collection
198
+ A collection of nodes in `G`.
199
+
200
+ weight : object
201
+ Edge attribute key to use as weight. If not specified, edges
202
+ have weight one.
203
+
204
+ Returns
205
+ -------
206
+ number
207
+ The conductance between the two sets `S` and `T`.
208
+
209
+ See also
210
+ --------
211
+ cut_size
212
+ edge_expansion
213
+ normalized_cut_size
214
+ volume
215
+
216
+ References
217
+ ----------
218
+ .. [1] David Gleich.
219
+ *Hierarchical Directed Spectral Graph Partitioning*.
220
+ <https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
221
+
222
+ """
223
+ if T is None:
224
+ T = set(G) - set(S)
225
+ num_cut_edges = cut_size(G, S, T, weight=weight)
226
+ volume_S = volume(G, S, weight=weight)
227
+ volume_T = volume(G, T, weight=weight)
228
+ return num_cut_edges / min(volume_S, volume_T)
229
+
230
+
231
+ @nx._dispatchable(edge_attrs="weight")
232
+ def edge_expansion(G, S, T=None, weight=None):
233
+ """Returns the edge expansion between two node sets.
234
+
235
+ The *edge expansion* is the quotient of the cut size and the smaller
236
+ of the cardinalities of the two sets. [1]
237
+
238
+ Parameters
239
+ ----------
240
+ G : NetworkX graph
241
+
242
+ S : collection
243
+ A collection of nodes in `G`.
244
+
245
+ T : collection
246
+ A collection of nodes in `G`.
247
+
248
+ weight : object
249
+ Edge attribute key to use as weight. If not specified, edges
250
+ have weight one.
251
+
252
+ Returns
253
+ -------
254
+ number
255
+ The edge expansion between the two sets `S` and `T`.
256
+
257
+ See also
258
+ --------
259
+ boundary_expansion
260
+ mixing_expansion
261
+ node_expansion
262
+
263
+ References
264
+ ----------
265
+ .. [1] Fan Chung.
266
+ *Spectral Graph Theory*.
267
+ (CBMS Regional Conference Series in Mathematics, No. 92),
268
+ American Mathematical Society, 1997, ISBN 0-8218-0315-8
269
+ <http://www.math.ucsd.edu/~fan/research/revised.html>
270
+
271
+ """
272
+ if T is None:
273
+ T = set(G) - set(S)
274
+ num_cut_edges = cut_size(G, S, T=T, weight=weight)
275
+ return num_cut_edges / min(len(S), len(T))
276
+
277
+
278
+ @nx._dispatchable(edge_attrs="weight")
279
+ def mixing_expansion(G, S, T=None, weight=None):
280
+ """Returns the mixing expansion between two node sets.
281
+
282
+ The *mixing expansion* is the quotient of the cut size and twice the
283
+ number of edges in the graph. [1]
284
+
285
+ Parameters
286
+ ----------
287
+ G : NetworkX graph
288
+
289
+ S : collection
290
+ A collection of nodes in `G`.
291
+
292
+ T : collection
293
+ A collection of nodes in `G`.
294
+
295
+ weight : object
296
+ Edge attribute key to use as weight. If not specified, edges
297
+ have weight one.
298
+
299
+ Returns
300
+ -------
301
+ number
302
+ The mixing expansion between the two sets `S` and `T`.
303
+
304
+ See also
305
+ --------
306
+ boundary_expansion
307
+ edge_expansion
308
+ node_expansion
309
+
310
+ References
311
+ ----------
312
+ .. [1] Vadhan, Salil P.
313
+ "Pseudorandomness."
314
+ *Foundations and Trends
315
+ in Theoretical Computer Science* 7.1–3 (2011): 1–336.
316
+ <https://doi.org/10.1561/0400000010>
317
+
318
+ """
319
+ num_cut_edges = cut_size(G, S, T=T, weight=weight)
320
+ num_total_edges = G.number_of_edges()
321
+ return num_cut_edges / (2 * num_total_edges)
322
+
323
+
324
+ # TODO What is the generalization to two arguments, S and T? Does the
325
+ # denominator become `min(len(S), len(T))`?
326
+ @nx._dispatchable
327
+ def node_expansion(G, S):
328
+ """Returns the node expansion of the set `S`.
329
+
330
+ The *node expansion* is the quotient of the size of the node
331
+ boundary of *S* and the cardinality of *S*. [1]
332
+
333
+ Parameters
334
+ ----------
335
+ G : NetworkX graph
336
+
337
+ S : collection
338
+ A collection of nodes in `G`.
339
+
340
+ Returns
341
+ -------
342
+ number
343
+ The node expansion of the set `S`.
344
+
345
+ See also
346
+ --------
347
+ boundary_expansion
348
+ edge_expansion
349
+ mixing_expansion
350
+
351
+ References
352
+ ----------
353
+ .. [1] Vadhan, Salil P.
354
+ "Pseudorandomness."
355
+ *Foundations and Trends
356
+ in Theoretical Computer Science* 7.1–3 (2011): 1–336.
357
+ <https://doi.org/10.1561/0400000010>
358
+
359
+ """
360
+ neighborhood = set(chain.from_iterable(G.neighbors(v) for v in S))
361
+ return len(neighborhood) / len(S)
362
+
363
+
364
+ # TODO What is the generalization to two arguments, S and T? Does the
365
+ # denominator become `min(len(S), len(T))`?
366
+ @nx._dispatchable
367
+ def boundary_expansion(G, S):
368
+ """Returns the boundary expansion of the set `S`.
369
+
370
+ The *boundary expansion* is the quotient of the size
371
+ of the node boundary and the cardinality of *S*. [1]
372
+
373
+ Parameters
374
+ ----------
375
+ G : NetworkX graph
376
+
377
+ S : collection
378
+ A collection of nodes in `G`.
379
+
380
+ Returns
381
+ -------
382
+ number
383
+ The boundary expansion of the set `S`.
384
+
385
+ See also
386
+ --------
387
+ edge_expansion
388
+ mixing_expansion
389
+ node_expansion
390
+
391
+ References
392
+ ----------
393
+ .. [1] Vadhan, Salil P.
394
+ "Pseudorandomness."
395
+ *Foundations and Trends in Theoretical Computer Science*
396
+ 7.1–3 (2011): 1–336.
397
+ <https://doi.org/10.1561/0400000010>
398
+
399
+ """
400
+ return len(nx.node_boundary(G, S)) / len(S)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/dag.py ADDED
@@ -0,0 +1,1259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Algorithms for directed acyclic graphs (DAGs).
2
+
3
+ Note that most of these functions are only guaranteed to work for DAGs.
4
+ In general, these functions do not check for acyclic-ness, so it is up
5
+ to the user to check for that.
6
+ """
7
+
8
+ import heapq
9
+ from collections import deque
10
+ from functools import partial
11
+ from itertools import chain, combinations, product, starmap
12
+ from math import gcd
13
+
14
+ import networkx as nx
15
+ from networkx.utils import arbitrary_element, not_implemented_for, pairwise
16
+
17
+ __all__ = [
18
+ "descendants",
19
+ "ancestors",
20
+ "topological_sort",
21
+ "lexicographical_topological_sort",
22
+ "all_topological_sorts",
23
+ "topological_generations",
24
+ "is_directed_acyclic_graph",
25
+ "is_aperiodic",
26
+ "transitive_closure",
27
+ "transitive_closure_dag",
28
+ "transitive_reduction",
29
+ "antichains",
30
+ "dag_longest_path",
31
+ "dag_longest_path_length",
32
+ "dag_to_branching",
33
+ "compute_v_structures",
34
+ ]
35
+
36
+ chaini = chain.from_iterable
37
+
38
+
39
+ @nx._dispatchable
40
+ def descendants(G, source):
41
+ """Returns all nodes reachable from `source` in `G`.
42
+
43
+ Parameters
44
+ ----------
45
+ G : NetworkX Graph
46
+ source : node in `G`
47
+
48
+ Returns
49
+ -------
50
+ set()
51
+ The descendants of `source` in `G`
52
+
53
+ Raises
54
+ ------
55
+ NetworkXError
56
+ If node `source` is not in `G`.
57
+
58
+ Examples
59
+ --------
60
+ >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
61
+ >>> sorted(nx.descendants(DG, 2))
62
+ [3, 4]
63
+
64
+ The `source` node is not a descendant of itself, but can be included manually:
65
+
66
+ >>> sorted(nx.descendants(DG, 2) | {2})
67
+ [2, 3, 4]
68
+
69
+ See also
70
+ --------
71
+ ancestors
72
+ """
73
+ return {child for parent, child in nx.bfs_edges(G, source)}
74
+
75
+
76
+ @nx._dispatchable
77
+ def ancestors(G, source):
78
+ """Returns all nodes having a path to `source` in `G`.
79
+
80
+ Parameters
81
+ ----------
82
+ G : NetworkX Graph
83
+ source : node in `G`
84
+
85
+ Returns
86
+ -------
87
+ set()
88
+ The ancestors of `source` in `G`
89
+
90
+ Raises
91
+ ------
92
+ NetworkXError
93
+ If node `source` is not in `G`.
94
+
95
+ Examples
96
+ --------
97
+ >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
98
+ >>> sorted(nx.ancestors(DG, 2))
99
+ [0, 1]
100
+
101
+ The `source` node is not an ancestor of itself, but can be included manually:
102
+
103
+ >>> sorted(nx.ancestors(DG, 2) | {2})
104
+ [0, 1, 2]
105
+
106
+ See also
107
+ --------
108
+ descendants
109
+ """
110
+ return {child for parent, child in nx.bfs_edges(G, source, reverse=True)}
111
+
112
+
113
+ @nx._dispatchable
114
+ def has_cycle(G):
115
+ """Decides whether the directed graph has a cycle."""
116
+ try:
117
+ # Feed the entire iterator into a zero-length deque.
118
+ deque(topological_sort(G), maxlen=0)
119
+ except nx.NetworkXUnfeasible:
120
+ return True
121
+ else:
122
+ return False
123
+
124
+
125
+ @nx._dispatchable
126
+ def is_directed_acyclic_graph(G):
127
+ """Returns True if the graph `G` is a directed acyclic graph (DAG) or
128
+ False if not.
129
+
130
+ Parameters
131
+ ----------
132
+ G : NetworkX graph
133
+
134
+ Returns
135
+ -------
136
+ bool
137
+ True if `G` is a DAG, False otherwise
138
+
139
+ Examples
140
+ --------
141
+ Undirected graph::
142
+
143
+ >>> G = nx.Graph([(1, 2), (2, 3)])
144
+ >>> nx.is_directed_acyclic_graph(G)
145
+ False
146
+
147
+ Directed graph with cycle::
148
+
149
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
150
+ >>> nx.is_directed_acyclic_graph(G)
151
+ False
152
+
153
+ Directed acyclic graph::
154
+
155
+ >>> G = nx.DiGraph([(1, 2), (2, 3)])
156
+ >>> nx.is_directed_acyclic_graph(G)
157
+ True
158
+
159
+ See also
160
+ --------
161
+ topological_sort
162
+ """
163
+ return G.is_directed() and not has_cycle(G)
164
+
165
+
166
+ @nx._dispatchable
167
+ def topological_generations(G):
168
+ """Stratifies a DAG into generations.
169
+
170
+ A topological generation is node collection in which ancestors of a node in each
171
+ generation are guaranteed to be in a previous generation, and any descendants of
172
+ a node are guaranteed to be in a following generation. Nodes are guaranteed to
173
+ be in the earliest possible generation that they can belong to.
174
+
175
+ Parameters
176
+ ----------
177
+ G : NetworkX digraph
178
+ A directed acyclic graph (DAG)
179
+
180
+ Yields
181
+ ------
182
+ sets of nodes
183
+ Yields sets of nodes representing each generation.
184
+
185
+ Raises
186
+ ------
187
+ NetworkXError
188
+ Generations are defined for directed graphs only. If the graph
189
+ `G` is undirected, a :exc:`NetworkXError` is raised.
190
+
191
+ NetworkXUnfeasible
192
+ If `G` is not a directed acyclic graph (DAG) no topological generations
193
+ exist and a :exc:`NetworkXUnfeasible` exception is raised. This can also
194
+ be raised if `G` is changed while the returned iterator is being processed
195
+
196
+ RuntimeError
197
+ If `G` is changed while the returned iterator is being processed.
198
+
199
+ Examples
200
+ --------
201
+ >>> DG = nx.DiGraph([(2, 1), (3, 1)])
202
+ >>> [sorted(generation) for generation in nx.topological_generations(DG)]
203
+ [[2, 3], [1]]
204
+
205
+ Notes
206
+ -----
207
+ The generation in which a node resides can also be determined by taking the
208
+ max-path-distance from the node to the farthest leaf node. That value can
209
+ be obtained with this function using `enumerate(topological_generations(G))`.
210
+
211
+ See also
212
+ --------
213
+ topological_sort
214
+ """
215
+ if not G.is_directed():
216
+ raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
217
+
218
+ multigraph = G.is_multigraph()
219
+ indegree_map = {v: d for v, d in G.in_degree() if d > 0}
220
+ zero_indegree = [v for v, d in G.in_degree() if d == 0]
221
+
222
+ while zero_indegree:
223
+ this_generation = zero_indegree
224
+ zero_indegree = []
225
+ for node in this_generation:
226
+ if node not in G:
227
+ raise RuntimeError("Graph changed during iteration")
228
+ for child in G.neighbors(node):
229
+ try:
230
+ indegree_map[child] -= len(G[node][child]) if multigraph else 1
231
+ except KeyError as err:
232
+ raise RuntimeError("Graph changed during iteration") from err
233
+ if indegree_map[child] == 0:
234
+ zero_indegree.append(child)
235
+ del indegree_map[child]
236
+ yield this_generation
237
+
238
+ if indegree_map:
239
+ raise nx.NetworkXUnfeasible(
240
+ "Graph contains a cycle or graph changed during iteration"
241
+ )
242
+
243
+
244
+ @nx._dispatchable
245
+ def topological_sort(G):
246
+ """Returns a generator of nodes in topologically sorted order.
247
+
248
+ A topological sort is a nonunique permutation of the nodes of a
249
+ directed graph such that an edge from u to v implies that u
250
+ appears before v in the topological sort order. This ordering is
251
+ valid only if the graph has no directed cycles.
252
+
253
+ Parameters
254
+ ----------
255
+ G : NetworkX digraph
256
+ A directed acyclic graph (DAG)
257
+
258
+ Yields
259
+ ------
260
+ nodes
261
+ Yields the nodes in topological sorted order.
262
+
263
+ Raises
264
+ ------
265
+ NetworkXError
266
+ Topological sort is defined for directed graphs only. If the graph `G`
267
+ is undirected, a :exc:`NetworkXError` is raised.
268
+
269
+ NetworkXUnfeasible
270
+ If `G` is not a directed acyclic graph (DAG) no topological sort exists
271
+ and a :exc:`NetworkXUnfeasible` exception is raised. This can also be
272
+ raised if `G` is changed while the returned iterator is being processed
273
+
274
+ RuntimeError
275
+ If `G` is changed while the returned iterator is being processed.
276
+
277
+ Examples
278
+ --------
279
+ To get the reverse order of the topological sort:
280
+
281
+ >>> DG = nx.DiGraph([(1, 2), (2, 3)])
282
+ >>> list(reversed(list(nx.topological_sort(DG))))
283
+ [3, 2, 1]
284
+
285
+ If your DiGraph naturally has the edges representing tasks/inputs
286
+ and nodes representing people/processes that initiate tasks, then
287
+ topological_sort is not quite what you need. You will have to change
288
+ the tasks to nodes with dependence reflected by edges. The result is
289
+ a kind of topological sort of the edges. This can be done
290
+ with :func:`networkx.line_graph` as follows:
291
+
292
+ >>> list(nx.topological_sort(nx.line_graph(DG)))
293
+ [(1, 2), (2, 3)]
294
+
295
+ Notes
296
+ -----
297
+ This algorithm is based on a description and proof in
298
+ "Introduction to Algorithms: A Creative Approach" [1]_ .
299
+
300
+ See also
301
+ --------
302
+ is_directed_acyclic_graph, lexicographical_topological_sort
303
+
304
+ References
305
+ ----------
306
+ .. [1] Manber, U. (1989).
307
+ *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
308
+ """
309
+ for generation in nx.topological_generations(G):
310
+ yield from generation
311
+
312
+
313
+ @nx._dispatchable
314
+ def lexicographical_topological_sort(G, key=None):
315
+ """Generate the nodes in the unique lexicographical topological sort order.
316
+
317
+ Generates a unique ordering of nodes by first sorting topologically (for which there are often
318
+ multiple valid orderings) and then additionally by sorting lexicographically.
319
+
320
+ A topological sort arranges the nodes of a directed graph so that the
321
+ upstream node of each directed edge precedes the downstream node.
322
+ It is always possible to find a solution for directed graphs that have no cycles.
323
+ There may be more than one valid solution.
324
+
325
+ Lexicographical sorting is just sorting alphabetically. It is used here to break ties in the
326
+ topological sort and to determine a single, unique ordering. This can be useful in comparing
327
+ sort results.
328
+
329
+ The lexicographical order can be customized by providing a function to the `key=` parameter.
330
+ The definition of the key function is the same as used in python's built-in `sort()`.
331
+ The function takes a single argument and returns a key to use for sorting purposes.
332
+
333
+ Lexicographical sorting can fail if the node names are un-sortable. See the example below.
334
+ The solution is to provide a function to the `key=` argument that returns sortable keys.
335
+
336
+
337
+ Parameters
338
+ ----------
339
+ G : NetworkX digraph
340
+ A directed acyclic graph (DAG)
341
+
342
+ key : function, optional
343
+ A function of one argument that converts a node name to a comparison key.
344
+ It defines and resolves ambiguities in the sort order. Defaults to the identity function.
345
+
346
+ Yields
347
+ ------
348
+ nodes
349
+ Yields the nodes of G in lexicographical topological sort order.
350
+
351
+ Raises
352
+ ------
353
+ NetworkXError
354
+ Topological sort is defined for directed graphs only. If the graph `G`
355
+ is undirected, a :exc:`NetworkXError` is raised.
356
+
357
+ NetworkXUnfeasible
358
+ If `G` is not a directed acyclic graph (DAG) no topological sort exists
359
+ and a :exc:`NetworkXUnfeasible` exception is raised. This can also be
360
+ raised if `G` is changed while the returned iterator is being processed
361
+
362
+ RuntimeError
363
+ If `G` is changed while the returned iterator is being processed.
364
+
365
+ TypeError
366
+ Results from un-sortable node names.
367
+ Consider using `key=` parameter to resolve ambiguities in the sort order.
368
+
369
+ Examples
370
+ --------
371
+ >>> DG = nx.DiGraph([(2, 1), (2, 5), (1, 3), (1, 4), (5, 4)])
372
+ >>> list(nx.lexicographical_topological_sort(DG))
373
+ [2, 1, 3, 5, 4]
374
+ >>> list(nx.lexicographical_topological_sort(DG, key=lambda x: -x))
375
+ [2, 5, 1, 4, 3]
376
+
377
+ The sort will fail for any graph with integer and string nodes. Comparison of integer to strings
378
+ is not defined in python. Is 3 greater or less than 'red'?
379
+
380
+ >>> DG = nx.DiGraph([(1, "red"), (3, "red"), (1, "green"), (2, "blue")])
381
+ >>> list(nx.lexicographical_topological_sort(DG))
382
+ Traceback (most recent call last):
383
+ ...
384
+ TypeError: '<' not supported between instances of 'str' and 'int'
385
+ ...
386
+
387
+ Incomparable nodes can be resolved using a `key` function. This example function
388
+ allows comparison of integers and strings by returning a tuple where the first
389
+ element is True for `str`, False otherwise. The second element is the node name.
390
+ This groups the strings and integers separately so they can be compared only among themselves.
391
+
392
+ >>> key = lambda node: (isinstance(node, str), node)
393
+ >>> list(nx.lexicographical_topological_sort(DG, key=key))
394
+ [1, 2, 3, 'blue', 'green', 'red']
395
+
396
+ Notes
397
+ -----
398
+ This algorithm is based on a description and proof in
399
+ "Introduction to Algorithms: A Creative Approach" [1]_ .
400
+
401
+ See also
402
+ --------
403
+ topological_sort
404
+
405
+ References
406
+ ----------
407
+ .. [1] Manber, U. (1989).
408
+ *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
409
+ """
410
+ if not G.is_directed():
411
+ msg = "Topological sort not defined on undirected graphs."
412
+ raise nx.NetworkXError(msg)
413
+
414
+ if key is None:
415
+
416
+ def key(node):
417
+ return node
418
+
419
+ nodeid_map = {n: i for i, n in enumerate(G)}
420
+
421
+ def create_tuple(node):
422
+ return key(node), nodeid_map[node], node
423
+
424
+ indegree_map = {v: d for v, d in G.in_degree() if d > 0}
425
+ # These nodes have zero indegree and ready to be returned.
426
+ zero_indegree = [create_tuple(v) for v, d in G.in_degree() if d == 0]
427
+ heapq.heapify(zero_indegree)
428
+
429
+ while zero_indegree:
430
+ _, _, node = heapq.heappop(zero_indegree)
431
+
432
+ if node not in G:
433
+ raise RuntimeError("Graph changed during iteration")
434
+ for _, child in G.edges(node):
435
+ try:
436
+ indegree_map[child] -= 1
437
+ except KeyError as err:
438
+ raise RuntimeError("Graph changed during iteration") from err
439
+ if indegree_map[child] == 0:
440
+ try:
441
+ heapq.heappush(zero_indegree, create_tuple(child))
442
+ except TypeError as err:
443
+ raise TypeError(
444
+ f"{err}\nConsider using `key=` parameter to resolve ambiguities in the sort order."
445
+ )
446
+ del indegree_map[child]
447
+
448
+ yield node
449
+
450
+ if indegree_map:
451
+ msg = "Graph contains a cycle or graph changed during iteration"
452
+ raise nx.NetworkXUnfeasible(msg)
453
+
454
+
455
+ @not_implemented_for("undirected")
456
+ @nx._dispatchable
457
+ def all_topological_sorts(G):
458
+ """Returns a generator of _all_ topological sorts of the directed graph G.
459
+
460
+ A topological sort is a nonunique permutation of the nodes such that an
461
+ edge from u to v implies that u appears before v in the topological sort
462
+ order.
463
+
464
+ Parameters
465
+ ----------
466
+ G : NetworkX DiGraph
467
+ A directed graph
468
+
469
+ Yields
470
+ ------
471
+ topological_sort_order : list
472
+ a list of nodes in `G`, representing one of the topological sort orders
473
+
474
+ Raises
475
+ ------
476
+ NetworkXNotImplemented
477
+ If `G` is not directed
478
+ NetworkXUnfeasible
479
+ If `G` is not acyclic
480
+
481
+ Examples
482
+ --------
483
+ To enumerate all topological sorts of directed graph:
484
+
485
+ >>> DG = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
486
+ >>> list(nx.all_topological_sorts(DG))
487
+ [[1, 2, 4, 3], [1, 2, 3, 4]]
488
+
489
+ Notes
490
+ -----
491
+ Implements an iterative version of the algorithm given in [1].
492
+
493
+ References
494
+ ----------
495
+ .. [1] Knuth, Donald E., Szwarcfiter, Jayme L. (1974).
496
+ "A Structured Program to Generate All Topological Sorting Arrangements"
497
+ Information Processing Letters, Volume 2, Issue 6, 1974, Pages 153-157,
498
+ ISSN 0020-0190,
499
+ https://doi.org/10.1016/0020-0190(74)90001-5.
500
+ Elsevier (North-Holland), Amsterdam
501
+ """
502
+ if not G.is_directed():
503
+ raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
504
+
505
+ # the names of count and D are chosen to match the global variables in [1]
506
+ # number of edges originating in a vertex v
507
+ count = dict(G.in_degree())
508
+ # vertices with indegree 0
509
+ D = deque([v for v, d in G.in_degree() if d == 0])
510
+ # stack of first value chosen at a position k in the topological sort
511
+ bases = []
512
+ current_sort = []
513
+
514
+ # do-while construct
515
+ while True:
516
+ assert all(count[v] == 0 for v in D)
517
+
518
+ if len(current_sort) == len(G):
519
+ yield list(current_sort)
520
+
521
+ # clean-up stack
522
+ while len(current_sort) > 0:
523
+ assert len(bases) == len(current_sort)
524
+ q = current_sort.pop()
525
+
526
+ # "restores" all edges (q, x)
527
+ # NOTE: it is important to iterate over edges instead
528
+ # of successors, so count is updated correctly in multigraphs
529
+ for _, j in G.out_edges(q):
530
+ count[j] += 1
531
+ assert count[j] >= 0
532
+ # remove entries from D
533
+ while len(D) > 0 and count[D[-1]] > 0:
534
+ D.pop()
535
+
536
+ # corresponds to a circular shift of the values in D
537
+ # if the first value chosen (the base) is in the first
538
+ # position of D again, we are done and need to consider the
539
+ # previous condition
540
+ D.appendleft(q)
541
+ if D[-1] == bases[-1]:
542
+ # all possible values have been chosen at current position
543
+ # remove corresponding marker
544
+ bases.pop()
545
+ else:
546
+ # there are still elements that have not been fixed
547
+ # at the current position in the topological sort
548
+ # stop removing elements, escape inner loop
549
+ break
550
+
551
+ else:
552
+ if len(D) == 0:
553
+ raise nx.NetworkXUnfeasible("Graph contains a cycle.")
554
+
555
+ # choose next node
556
+ q = D.pop()
557
+ # "erase" all edges (q, x)
558
+ # NOTE: it is important to iterate over edges instead
559
+ # of successors, so count is updated correctly in multigraphs
560
+ for _, j in G.out_edges(q):
561
+ count[j] -= 1
562
+ assert count[j] >= 0
563
+ if count[j] == 0:
564
+ D.append(j)
565
+ current_sort.append(q)
566
+
567
+ # base for current position might _not_ be fixed yet
568
+ if len(bases) < len(current_sort):
569
+ bases.append(q)
570
+
571
+ if len(bases) == 0:
572
+ break
573
+
574
+
575
+ @nx._dispatchable
576
+ def is_aperiodic(G):
577
+ """Returns True if `G` is aperiodic.
578
+
579
+ A directed graph is aperiodic if there is no integer k > 1 that
580
+ divides the length of every cycle in the graph.
581
+
582
+ Parameters
583
+ ----------
584
+ G : NetworkX DiGraph
585
+ A directed graph
586
+
587
+ Returns
588
+ -------
589
+ bool
590
+ True if the graph is aperiodic False otherwise
591
+
592
+ Raises
593
+ ------
594
+ NetworkXError
595
+ If `G` is not directed
596
+
597
+ Examples
598
+ --------
599
+ A graph consisting of one cycle, the length of which is 2. Therefore ``k = 2``
600
+ divides the length of every cycle in the graph and thus the graph
601
+ is *not aperiodic*::
602
+
603
+ >>> DG = nx.DiGraph([(1, 2), (2, 1)])
604
+ >>> nx.is_aperiodic(DG)
605
+ False
606
+
607
+ A graph consisting of two cycles: one of length 2 and the other of length 3.
608
+ The cycle lengths are coprime, so there is no single value of k where ``k > 1``
609
+ that divides each cycle length and therefore the graph is *aperiodic*::
610
+
611
+ >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1), (1, 4), (4, 1)])
612
+ >>> nx.is_aperiodic(DG)
613
+ True
614
+
615
+ A graph consisting of two cycles: one of length 2 and the other of length 4.
616
+ The lengths of the cycles share a common factor ``k = 2``, and therefore
617
+ the graph is *not aperiodic*::
618
+
619
+ >>> DG = nx.DiGraph([(1, 2), (2, 1), (3, 4), (4, 5), (5, 6), (6, 3)])
620
+ >>> nx.is_aperiodic(DG)
621
+ False
622
+
623
+ An acyclic graph, therefore the graph is *not aperiodic*::
624
+
625
+ >>> DG = nx.DiGraph([(1, 2), (2, 3)])
626
+ >>> nx.is_aperiodic(DG)
627
+ False
628
+
629
+ Notes
630
+ -----
631
+ This uses the method outlined in [1]_, which runs in $O(m)$ time
632
+ given $m$ edges in `G`. Note that a graph is not aperiodic if it is
633
+ acyclic as every integer trivial divides length 0 cycles.
634
+
635
+ References
636
+ ----------
637
+ .. [1] Jarvis, J. P.; Shier, D. R. (1996),
638
+ "Graph-theoretic analysis of finite Markov chains,"
639
+ in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling:
640
+ A Multidisciplinary Approach, CRC Press.
641
+ """
642
+ if not G.is_directed():
643
+ raise nx.NetworkXError("is_aperiodic not defined for undirected graphs")
644
+ if len(G) == 0:
645
+ raise nx.NetworkXPointlessConcept("Graph has no nodes.")
646
+ s = arbitrary_element(G)
647
+ levels = {s: 0}
648
+ this_level = [s]
649
+ g = 0
650
+ lev = 1
651
+ while this_level:
652
+ next_level = []
653
+ for u in this_level:
654
+ for v in G[u]:
655
+ if v in levels: # Non-Tree Edge
656
+ g = gcd(g, levels[u] - levels[v] + 1)
657
+ else: # Tree Edge
658
+ next_level.append(v)
659
+ levels[v] = lev
660
+ this_level = next_level
661
+ lev += 1
662
+ if len(levels) == len(G): # All nodes in tree
663
+ return g == 1
664
+ else:
665
+ return g == 1 and nx.is_aperiodic(G.subgraph(set(G) - set(levels)))
666
+
667
+
668
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
669
+ def transitive_closure(G, reflexive=False):
670
+ """Returns transitive closure of a graph
671
+
672
+ The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
673
+ for all v, w in V there is an edge (v, w) in E+ if and only if there
674
+ is a path from v to w in G.
675
+
676
+ Handling of paths from v to v has some flexibility within this definition.
677
+ A reflexive transitive closure creates a self-loop for the path
678
+ from v to v of length 0. The usual transitive closure creates a
679
+ self-loop only if a cycle exists (a path from v to v with length > 0).
680
+ We also allow an option for no self-loops.
681
+
682
+ Parameters
683
+ ----------
684
+ G : NetworkX Graph
685
+ A directed/undirected graph/multigraph.
686
+ reflexive : Bool or None, optional (default: False)
687
+ Determines when cycles create self-loops in the Transitive Closure.
688
+ If True, trivial cycles (length 0) create self-loops. The result
689
+ is a reflexive transitive closure of G.
690
+ If False (the default) non-trivial cycles create self-loops.
691
+ If None, self-loops are not created.
692
+
693
+ Returns
694
+ -------
695
+ NetworkX graph
696
+ The transitive closure of `G`
697
+
698
+ Raises
699
+ ------
700
+ NetworkXError
701
+ If `reflexive` not in `{None, True, False}`
702
+
703
+ Examples
704
+ --------
705
+ The treatment of trivial (i.e. length 0) cycles is controlled by the
706
+ `reflexive` parameter.
707
+
708
+ Trivial (i.e. length 0) cycles do not create self-loops when
709
+ ``reflexive=False`` (the default)::
710
+
711
+ >>> DG = nx.DiGraph([(1, 2), (2, 3)])
712
+ >>> TC = nx.transitive_closure(DG, reflexive=False)
713
+ >>> TC.edges()
714
+ OutEdgeView([(1, 2), (1, 3), (2, 3)])
715
+
716
+ However, nontrivial (i.e. length greater than 0) cycles create self-loops
717
+ when ``reflexive=False`` (the default)::
718
+
719
+ >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
720
+ >>> TC = nx.transitive_closure(DG, reflexive=False)
721
+ >>> TC.edges()
722
+ OutEdgeView([(1, 2), (1, 3), (1, 1), (2, 3), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)])
723
+
724
+ Trivial cycles (length 0) create self-loops when ``reflexive=True``::
725
+
726
+ >>> DG = nx.DiGraph([(1, 2), (2, 3)])
727
+ >>> TC = nx.transitive_closure(DG, reflexive=True)
728
+ >>> TC.edges()
729
+ OutEdgeView([(1, 2), (1, 1), (1, 3), (2, 3), (2, 2), (3, 3)])
730
+
731
+ And the third option is not to create self-loops at all when ``reflexive=None``::
732
+
733
+ >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
734
+ >>> TC = nx.transitive_closure(DG, reflexive=None)
735
+ >>> TC.edges()
736
+ OutEdgeView([(1, 2), (1, 3), (2, 3), (2, 1), (3, 1), (3, 2)])
737
+
738
+ References
739
+ ----------
740
+ .. [1] https://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py
741
+ """
742
+ TC = G.copy()
743
+
744
+ if reflexive not in {None, True, False}:
745
+ raise nx.NetworkXError("Incorrect value for the parameter `reflexive`")
746
+
747
+ for v in G:
748
+ if reflexive is None:
749
+ TC.add_edges_from((v, u) for u in nx.descendants(G, v) if u not in TC[v])
750
+ elif reflexive is True:
751
+ TC.add_edges_from(
752
+ (v, u) for u in nx.descendants(G, v) | {v} if u not in TC[v]
753
+ )
754
+ elif reflexive is False:
755
+ TC.add_edges_from((v, e[1]) for e in nx.edge_bfs(G, v) if e[1] not in TC[v])
756
+
757
+ return TC
758
+
759
+
760
+ @not_implemented_for("undirected")
761
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
762
+ def transitive_closure_dag(G, topo_order=None):
763
+ """Returns the transitive closure of a directed acyclic graph.
764
+
765
+ This function is faster than the function `transitive_closure`, but fails
766
+ if the graph has a cycle.
767
+
768
+ The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
769
+ for all v, w in V there is an edge (v, w) in E+ if and only if there
770
+ is a non-null path from v to w in G.
771
+
772
+ Parameters
773
+ ----------
774
+ G : NetworkX DiGraph
775
+ A directed acyclic graph (DAG)
776
+
777
+ topo_order: list or tuple, optional
778
+ A topological order for G (if None, the function will compute one)
779
+
780
+ Returns
781
+ -------
782
+ NetworkX DiGraph
783
+ The transitive closure of `G`
784
+
785
+ Raises
786
+ ------
787
+ NetworkXNotImplemented
788
+ If `G` is not directed
789
+ NetworkXUnfeasible
790
+ If `G` has a cycle
791
+
792
+ Examples
793
+ --------
794
+ >>> DG = nx.DiGraph([(1, 2), (2, 3)])
795
+ >>> TC = nx.transitive_closure_dag(DG)
796
+ >>> TC.edges()
797
+ OutEdgeView([(1, 2), (1, 3), (2, 3)])
798
+
799
+ Notes
800
+ -----
801
+ This algorithm is probably simple enough to be well-known but I didn't find
802
+ a mention in the literature.
803
+ """
804
+ if topo_order is None:
805
+ topo_order = list(topological_sort(G))
806
+
807
+ TC = G.copy()
808
+
809
+ # idea: traverse vertices following a reverse topological order, connecting
810
+ # each vertex to its descendants at distance 2 as we go
811
+ for v in reversed(topo_order):
812
+ TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2))
813
+
814
+ return TC
815
+
816
+
817
+ @not_implemented_for("undirected")
818
+ @nx._dispatchable(returns_graph=True)
819
+ def transitive_reduction(G):
820
+ """Returns transitive reduction of a directed graph
821
+
822
+ The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that
823
+ for all v,w in V there is an edge (v,w) in E- if and only if (v,w) is
824
+ in E and there is no path from v to w in G with length greater than 1.
825
+
826
+ Parameters
827
+ ----------
828
+ G : NetworkX DiGraph
829
+ A directed acyclic graph (DAG)
830
+
831
+ Returns
832
+ -------
833
+ NetworkX DiGraph
834
+ The transitive reduction of `G`
835
+
836
+ Raises
837
+ ------
838
+ NetworkXError
839
+ If `G` is not a directed acyclic graph (DAG) transitive reduction is
840
+ not uniquely defined and a :exc:`NetworkXError` exception is raised.
841
+
842
+ Examples
843
+ --------
844
+ To perform transitive reduction on a DiGraph:
845
+
846
+ >>> DG = nx.DiGraph([(1, 2), (2, 3), (1, 3)])
847
+ >>> TR = nx.transitive_reduction(DG)
848
+ >>> list(TR.edges)
849
+ [(1, 2), (2, 3)]
850
+
851
+ To avoid unnecessary data copies, this implementation does not return a
852
+ DiGraph with node/edge data.
853
+ To perform transitive reduction on a DiGraph and transfer node/edge data:
854
+
855
+ >>> DG = nx.DiGraph()
856
+ >>> DG.add_edges_from([(1, 2), (2, 3), (1, 3)], color="red")
857
+ >>> TR = nx.transitive_reduction(DG)
858
+ >>> TR.add_nodes_from(DG.nodes(data=True))
859
+ >>> TR.add_edges_from((u, v, DG.edges[u, v]) for u, v in TR.edges)
860
+ >>> list(TR.edges(data=True))
861
+ [(1, 2, {'color': 'red'}), (2, 3, {'color': 'red'})]
862
+
863
+ References
864
+ ----------
865
+ https://en.wikipedia.org/wiki/Transitive_reduction
866
+
867
+ """
868
+ if not is_directed_acyclic_graph(G):
869
+ msg = "Directed Acyclic Graph required for transitive_reduction"
870
+ raise nx.NetworkXError(msg)
871
+ TR = nx.DiGraph()
872
+ TR.add_nodes_from(G.nodes())
873
+ descendants = {}
874
+ # count before removing set stored in descendants
875
+ check_count = dict(G.in_degree)
876
+ for u in G:
877
+ u_nbrs = set(G[u])
878
+ for v in G[u]:
879
+ if v in u_nbrs:
880
+ if v not in descendants:
881
+ descendants[v] = {y for x, y in nx.dfs_edges(G, v)}
882
+ u_nbrs -= descendants[v]
883
+ check_count[v] -= 1
884
+ if check_count[v] == 0:
885
+ del descendants[v]
886
+ TR.add_edges_from((u, v) for v in u_nbrs)
887
+ return TR
888
+
889
+
890
+ @not_implemented_for("undirected")
891
+ @nx._dispatchable
892
+ def antichains(G, topo_order=None):
893
+ """Generates antichains from a directed acyclic graph (DAG).
894
+
895
+ An antichain is a subset of a partially ordered set such that any
896
+ two elements in the subset are incomparable.
897
+
898
+ Parameters
899
+ ----------
900
+ G : NetworkX DiGraph
901
+ A directed acyclic graph (DAG)
902
+
903
+ topo_order: list or tuple, optional
904
+ A topological order for G (if None, the function will compute one)
905
+
906
+ Yields
907
+ ------
908
+ antichain : list
909
+ a list of nodes in `G` representing an antichain
910
+
911
+ Raises
912
+ ------
913
+ NetworkXNotImplemented
914
+ If `G` is not directed
915
+
916
+ NetworkXUnfeasible
917
+ If `G` contains a cycle
918
+
919
+ Examples
920
+ --------
921
+ >>> DG = nx.DiGraph([(1, 2), (1, 3)])
922
+ >>> list(nx.antichains(DG))
923
+ [[], [3], [2], [2, 3], [1]]
924
+
925
+ Notes
926
+ -----
927
+ This function was originally developed by Peter Jipsen and Franco Saliola
928
+ for the SAGE project. It's included in NetworkX with permission from the
929
+ authors. Original SAGE code at:
930
+
931
+ https://github.com/sagemath/sage/blob/master/src/sage/combinat/posets/hasse_diagram.py
932
+
933
+ References
934
+ ----------
935
+ .. [1] Free Lattices, by R. Freese, J. Jezek and J. B. Nation,
936
+ AMS, Vol 42, 1995, p. 226.
937
+ """
938
+ if topo_order is None:
939
+ topo_order = list(nx.topological_sort(G))
940
+
941
+ TC = nx.transitive_closure_dag(G, topo_order)
942
+ antichains_stacks = [([], list(reversed(topo_order)))]
943
+
944
+ while antichains_stacks:
945
+ (antichain, stack) = antichains_stacks.pop()
946
+ # Invariant:
947
+ # - the elements of antichain are independent
948
+ # - the elements of stack are independent from those of antichain
949
+ yield antichain
950
+ while stack:
951
+ x = stack.pop()
952
+ new_antichain = antichain + [x]
953
+ new_stack = [t for t in stack if not ((t in TC[x]) or (x in TC[t]))]
954
+ antichains_stacks.append((new_antichain, new_stack))
955
+
956
+
957
+ @not_implemented_for("undirected")
958
+ @nx._dispatchable(edge_attrs={"weight": "default_weight"})
959
+ def dag_longest_path(G, weight="weight", default_weight=1, topo_order=None):
960
+ """Returns the longest path in a directed acyclic graph (DAG).
961
+
962
+ If `G` has edges with `weight` attribute the edge data are used as
963
+ weight values.
964
+
965
+ Parameters
966
+ ----------
967
+ G : NetworkX DiGraph
968
+ A directed acyclic graph (DAG)
969
+
970
+ weight : str, optional
971
+ Edge data key to use for weight
972
+
973
+ default_weight : int, optional
974
+ The weight of edges that do not have a weight attribute
975
+
976
+ topo_order: list or tuple, optional
977
+ A topological order for `G` (if None, the function will compute one)
978
+
979
+ Returns
980
+ -------
981
+ list
982
+ Longest path
983
+
984
+ Raises
985
+ ------
986
+ NetworkXNotImplemented
987
+ If `G` is not directed
988
+
989
+ Examples
990
+ --------
991
+ >>> DG = nx.DiGraph([(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})])
992
+ >>> list(nx.all_simple_paths(DG, 0, 2))
993
+ [[0, 1, 2], [0, 2]]
994
+ >>> nx.dag_longest_path(DG)
995
+ [0, 1, 2]
996
+ >>> nx.dag_longest_path(DG, weight="cost")
997
+ [0, 2]
998
+
999
+ In the case where multiple valid topological orderings exist, `topo_order`
1000
+ can be used to specify a specific ordering:
1001
+
1002
+ >>> DG = nx.DiGraph([(0, 1), (0, 2)])
1003
+ >>> sorted(nx.all_topological_sorts(DG)) # Valid topological orderings
1004
+ [[0, 1, 2], [0, 2, 1]]
1005
+ >>> nx.dag_longest_path(DG, topo_order=[0, 1, 2])
1006
+ [0, 1]
1007
+ >>> nx.dag_longest_path(DG, topo_order=[0, 2, 1])
1008
+ [0, 2]
1009
+
1010
+ See also
1011
+ --------
1012
+ dag_longest_path_length
1013
+
1014
+ """
1015
+ if not G:
1016
+ return []
1017
+
1018
+ if topo_order is None:
1019
+ topo_order = nx.topological_sort(G)
1020
+
1021
+ dist = {} # stores {v : (length, u)}
1022
+ for v in topo_order:
1023
+ us = [
1024
+ (
1025
+ dist[u][0]
1026
+ + (
1027
+ max(data.values(), key=lambda x: x.get(weight, default_weight))
1028
+ if G.is_multigraph()
1029
+ else data
1030
+ ).get(weight, default_weight),
1031
+ u,
1032
+ )
1033
+ for u, data in G.pred[v].items()
1034
+ ]
1035
+
1036
+ # Use the best predecessor if there is one and its distance is
1037
+ # non-negative, otherwise terminate.
1038
+ maxu = max(us, key=lambda x: x[0]) if us else (0, v)
1039
+ dist[v] = maxu if maxu[0] >= 0 else (0, v)
1040
+
1041
+ u = None
1042
+ v = max(dist, key=lambda x: dist[x][0])
1043
+ path = []
1044
+ while u != v:
1045
+ path.append(v)
1046
+ u = v
1047
+ v = dist[v][1]
1048
+
1049
+ path.reverse()
1050
+ return path
1051
+
1052
+
1053
+ @not_implemented_for("undirected")
1054
+ @nx._dispatchable(edge_attrs={"weight": "default_weight"})
1055
+ def dag_longest_path_length(G, weight="weight", default_weight=1):
1056
+ """Returns the longest path length in a DAG
1057
+
1058
+ Parameters
1059
+ ----------
1060
+ G : NetworkX DiGraph
1061
+ A directed acyclic graph (DAG)
1062
+
1063
+ weight : string, optional
1064
+ Edge data key to use for weight
1065
+
1066
+ default_weight : int, optional
1067
+ The weight of edges that do not have a weight attribute
1068
+
1069
+ Returns
1070
+ -------
1071
+ int
1072
+ Longest path length
1073
+
1074
+ Raises
1075
+ ------
1076
+ NetworkXNotImplemented
1077
+ If `G` is not directed
1078
+
1079
+ Examples
1080
+ --------
1081
+ >>> DG = nx.DiGraph([(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})])
1082
+ >>> list(nx.all_simple_paths(DG, 0, 2))
1083
+ [[0, 1, 2], [0, 2]]
1084
+ >>> nx.dag_longest_path_length(DG)
1085
+ 2
1086
+ >>> nx.dag_longest_path_length(DG, weight="cost")
1087
+ 42
1088
+
1089
+ See also
1090
+ --------
1091
+ dag_longest_path
1092
+ """
1093
+ path = nx.dag_longest_path(G, weight, default_weight)
1094
+ path_length = 0
1095
+ if G.is_multigraph():
1096
+ for u, v in pairwise(path):
1097
+ i = max(G[u][v], key=lambda x: G[u][v][x].get(weight, default_weight))
1098
+ path_length += G[u][v][i].get(weight, default_weight)
1099
+ else:
1100
+ for u, v in pairwise(path):
1101
+ path_length += G[u][v].get(weight, default_weight)
1102
+
1103
+ return path_length
1104
+
1105
+
1106
+ @nx._dispatchable
1107
+ def root_to_leaf_paths(G):
1108
+ """Yields root-to-leaf paths in a directed acyclic graph.
1109
+
1110
+ `G` must be a directed acyclic graph. If not, the behavior of this
1111
+ function is undefined. A "root" in this graph is a node of in-degree
1112
+ zero and a "leaf" a node of out-degree zero.
1113
+
1114
+ When invoked, this function iterates over each path from any root to
1115
+ any leaf. A path is a list of nodes.
1116
+
1117
+ """
1118
+ roots = (v for v, d in G.in_degree() if d == 0)
1119
+ leaves = (v for v, d in G.out_degree() if d == 0)
1120
+ all_paths = partial(nx.all_simple_paths, G)
1121
+ # TODO In Python 3, this would be better as `yield from ...`.
1122
+ return chaini(starmap(all_paths, product(roots, leaves)))
1123
+
1124
+
1125
+ @not_implemented_for("multigraph")
1126
+ @not_implemented_for("undirected")
1127
+ @nx._dispatchable(returns_graph=True)
1128
+ def dag_to_branching(G):
1129
+ """Returns a branching representing all (overlapping) paths from
1130
+ root nodes to leaf nodes in the given directed acyclic graph.
1131
+
1132
+ As described in :mod:`networkx.algorithms.tree.recognition`, a
1133
+ *branching* is a directed forest in which each node has at most one
1134
+ parent. In other words, a branching is a disjoint union of
1135
+ *arborescences*. For this function, each node of in-degree zero in
1136
+ `G` becomes a root of one of the arborescences, and there will be
1137
+ one leaf node for each distinct path from that root to a leaf node
1138
+ in `G`.
1139
+
1140
+ Each node `v` in `G` with *k* parents becomes *k* distinct nodes in
1141
+ the returned branching, one for each parent, and the sub-DAG rooted
1142
+ at `v` is duplicated for each copy. The algorithm then recurses on
1143
+ the children of each copy of `v`.
1144
+
1145
+ Parameters
1146
+ ----------
1147
+ G : NetworkX graph
1148
+ A directed acyclic graph.
1149
+
1150
+ Returns
1151
+ -------
1152
+ DiGraph
1153
+ The branching in which there is a bijection between root-to-leaf
1154
+ paths in `G` (in which multiple paths may share the same leaf)
1155
+ and root-to-leaf paths in the branching (in which there is a
1156
+ unique path from a root to a leaf).
1157
+
1158
+ Each node has an attribute 'source' whose value is the original
1159
+ node to which this node corresponds. No other graph, node, or
1160
+ edge attributes are copied into this new graph.
1161
+
1162
+ Raises
1163
+ ------
1164
+ NetworkXNotImplemented
1165
+ If `G` is not directed, or if `G` is a multigraph.
1166
+
1167
+ HasACycle
1168
+ If `G` is not acyclic.
1169
+
1170
+ Examples
1171
+ --------
1172
+ To examine which nodes in the returned branching were produced by
1173
+ which original node in the directed acyclic graph, we can collect
1174
+ the mapping from source node to new nodes into a dictionary. For
1175
+ example, consider the directed diamond graph::
1176
+
1177
+ >>> from collections import defaultdict
1178
+ >>> from operator import itemgetter
1179
+ >>>
1180
+ >>> G = nx.DiGraph(nx.utils.pairwise("abd"))
1181
+ >>> G.add_edges_from(nx.utils.pairwise("acd"))
1182
+ >>> B = nx.dag_to_branching(G)
1183
+ >>>
1184
+ >>> sources = defaultdict(set)
1185
+ >>> for v, source in B.nodes(data="source"):
1186
+ ... sources[source].add(v)
1187
+ >>> len(sources["a"])
1188
+ 1
1189
+ >>> len(sources["d"])
1190
+ 2
1191
+
1192
+ To copy node attributes from the original graph to the new graph,
1193
+ you can use a dictionary like the one constructed in the above
1194
+ example::
1195
+
1196
+ >>> for source, nodes in sources.items():
1197
+ ... for v in nodes:
1198
+ ... B.nodes[v].update(G.nodes[source])
1199
+
1200
+ Notes
1201
+ -----
1202
+ This function is not idempotent in the sense that the node labels in
1203
+ the returned branching may be uniquely generated each time the
1204
+ function is invoked. In fact, the node labels may not be integers;
1205
+ in order to relabel the nodes to be more readable, you can use the
1206
+ :func:`networkx.convert_node_labels_to_integers` function.
1207
+
1208
+ The current implementation of this function uses
1209
+ :func:`networkx.prefix_tree`, so it is subject to the limitations of
1210
+ that function.
1211
+
1212
+ """
1213
+ if has_cycle(G):
1214
+ msg = "dag_to_branching is only defined for acyclic graphs"
1215
+ raise nx.HasACycle(msg)
1216
+ paths = root_to_leaf_paths(G)
1217
+ B = nx.prefix_tree(paths)
1218
+ # Remove the synthetic `root`(0) and `NIL`(-1) nodes from the tree
1219
+ B.remove_node(0)
1220
+ B.remove_node(-1)
1221
+ return B
1222
+
1223
+
1224
+ @not_implemented_for("undirected")
1225
+ @nx._dispatchable
1226
+ def compute_v_structures(G):
1227
+ """Iterate through the graph to compute all v-structures.
1228
+
1229
+ V-structures are triples in the directed graph where
1230
+ two parent nodes point to the same child and the two parent nodes
1231
+ are not adjacent.
1232
+
1233
+ Parameters
1234
+ ----------
1235
+ G : graph
1236
+ A networkx DiGraph.
1237
+
1238
+ Returns
1239
+ -------
1240
+ vstructs : iterator of tuples
1241
+ The v structures within the graph. Each v structure is a 3-tuple with the
1242
+ parent, collider, and other parent.
1243
+
1244
+ Examples
1245
+ --------
1246
+ >>> G = nx.DiGraph()
1247
+ >>> G.add_edges_from([(1, 2), (0, 5), (3, 1), (2, 4), (3, 1), (4, 5), (1, 5)])
1248
+ >>> sorted(nx.compute_v_structures(G))
1249
+ [(0, 5, 1), (0, 5, 4), (1, 5, 4)]
1250
+
1251
+ Notes
1252
+ -----
1253
+ `Wikipedia: Collider in causal graphs <https://en.wikipedia.org/wiki/Collider_(statistics)>`_
1254
+ """
1255
+ for collider, preds in G.pred.items():
1256
+ for common_parents in combinations(preds, r=2):
1257
+ # ensure that the colliders are the same
1258
+ common_parents = sorted(common_parents)
1259
+ yield (common_parents[0], collider, common_parents[1])
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/dominance.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dominance algorithms.
3
+ """
4
+
5
+ from functools import reduce
6
+
7
+ import networkx as nx
8
+ from networkx.utils import not_implemented_for
9
+
10
+ __all__ = ["immediate_dominators", "dominance_frontiers"]
11
+
12
+
13
+ @not_implemented_for("undirected")
14
+ @nx._dispatchable
15
+ def immediate_dominators(G, start):
16
+ """Returns the immediate dominators of all nodes of a directed graph.
17
+
18
+ Parameters
19
+ ----------
20
+ G : a DiGraph or MultiDiGraph
21
+ The graph where dominance is to be computed.
22
+
23
+ start : node
24
+ The start node of dominance computation.
25
+
26
+ Returns
27
+ -------
28
+ idom : dict keyed by nodes
29
+ A dict containing the immediate dominators of each node reachable from
30
+ `start`.
31
+
32
+ Raises
33
+ ------
34
+ NetworkXNotImplemented
35
+ If `G` is undirected.
36
+
37
+ NetworkXError
38
+ If `start` is not in `G`.
39
+
40
+ Notes
41
+ -----
42
+ Except for `start`, the immediate dominators are the parents of their
43
+ corresponding nodes in the dominator tree.
44
+
45
+ Examples
46
+ --------
47
+ >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
48
+ >>> sorted(nx.immediate_dominators(G, 1).items())
49
+ [(1, 1), (2, 1), (3, 1), (4, 3), (5, 1)]
50
+
51
+ References
52
+ ----------
53
+ .. [1] K. D. Cooper, T. J. Harvey, and K. Kennedy.
54
+ A simple, fast dominance algorithm.
55
+ Software Practice & Experience, 4:110, 2001.
56
+ """
57
+ if start not in G:
58
+ raise nx.NetworkXError("start is not in G")
59
+
60
+ idom = {start: start}
61
+
62
+ order = list(nx.dfs_postorder_nodes(G, start))
63
+ dfn = {u: i for i, u in enumerate(order)}
64
+ order.pop()
65
+ order.reverse()
66
+
67
+ def intersect(u, v):
68
+ while u != v:
69
+ while dfn[u] < dfn[v]:
70
+ u = idom[u]
71
+ while dfn[u] > dfn[v]:
72
+ v = idom[v]
73
+ return u
74
+
75
+ changed = True
76
+ while changed:
77
+ changed = False
78
+ for u in order:
79
+ new_idom = reduce(intersect, (v for v in G.pred[u] if v in idom))
80
+ if u not in idom or idom[u] != new_idom:
81
+ idom[u] = new_idom
82
+ changed = True
83
+
84
+ return idom
85
+
86
+
87
+ @nx._dispatchable
88
+ def dominance_frontiers(G, start):
89
+ """Returns the dominance frontiers of all nodes of a directed graph.
90
+
91
+ Parameters
92
+ ----------
93
+ G : a DiGraph or MultiDiGraph
94
+ The graph where dominance is to be computed.
95
+
96
+ start : node
97
+ The start node of dominance computation.
98
+
99
+ Returns
100
+ -------
101
+ df : dict keyed by nodes
102
+ A dict containing the dominance frontiers of each node reachable from
103
+ `start` as lists.
104
+
105
+ Raises
106
+ ------
107
+ NetworkXNotImplemented
108
+ If `G` is undirected.
109
+
110
+ NetworkXError
111
+ If `start` is not in `G`.
112
+
113
+ Examples
114
+ --------
115
+ >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
116
+ >>> sorted((u, sorted(df)) for u, df in nx.dominance_frontiers(G, 1).items())
117
+ [(1, []), (2, [5]), (3, [5]), (4, [5]), (5, [])]
118
+
119
+ References
120
+ ----------
121
+ .. [1] K. D. Cooper, T. J. Harvey, and K. Kennedy.
122
+ A simple, fast dominance algorithm.
123
+ Software Practice & Experience, 4:110, 2001.
124
+ """
125
+ idom = nx.immediate_dominators(G, start)
126
+
127
+ df = {u: set() for u in idom}
128
+ for u in idom:
129
+ if len(G.pred[u]) >= 2:
130
+ for v in G.pred[u]:
131
+ if v in idom:
132
+ while v != idom[u]:
133
+ df[v].add(u)
134
+ v = idom[v]
135
+ return df
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/dominating.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing dominating sets in a graph."""
2
+ from itertools import chain
3
+
4
+ import networkx as nx
5
+ from networkx.utils import arbitrary_element
6
+
7
+ __all__ = ["dominating_set", "is_dominating_set"]
8
+
9
+
10
+ @nx._dispatchable
11
+ def dominating_set(G, start_with=None):
12
+ r"""Finds a dominating set for the graph G.
13
+
14
+ A *dominating set* for a graph with node set *V* is a subset *D* of
15
+ *V* such that every node not in *D* is adjacent to at least one
16
+ member of *D* [1]_.
17
+
18
+ Parameters
19
+ ----------
20
+ G : NetworkX graph
21
+
22
+ start_with : node (default=None)
23
+ Node to use as a starting point for the algorithm.
24
+
25
+ Returns
26
+ -------
27
+ D : set
28
+ A dominating set for G.
29
+
30
+ Notes
31
+ -----
32
+ This function is an implementation of algorithm 7 in [2]_ which
33
+ finds some dominating set, not necessarily the smallest one.
34
+
35
+ See also
36
+ --------
37
+ is_dominating_set
38
+
39
+ References
40
+ ----------
41
+ .. [1] https://en.wikipedia.org/wiki/Dominating_set
42
+
43
+ .. [2] Abdol-Hossein Esfahanian. Connectivity Algorithms.
44
+ http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
45
+
46
+ """
47
+ all_nodes = set(G)
48
+ if start_with is None:
49
+ start_with = arbitrary_element(all_nodes)
50
+ if start_with not in G:
51
+ raise nx.NetworkXError(f"node {start_with} is not in G")
52
+ dominating_set = {start_with}
53
+ dominated_nodes = set(G[start_with])
54
+ remaining_nodes = all_nodes - dominated_nodes - dominating_set
55
+ while remaining_nodes:
56
+ # Choose an arbitrary node and determine its undominated neighbors.
57
+ v = remaining_nodes.pop()
58
+ undominated_nbrs = set(G[v]) - dominating_set
59
+ # Add the node to the dominating set and the neighbors to the
60
+ # dominated set. Finally, remove all of those nodes from the set
61
+ # of remaining nodes.
62
+ dominating_set.add(v)
63
+ dominated_nodes |= undominated_nbrs
64
+ remaining_nodes -= undominated_nbrs
65
+ return dominating_set
66
+
67
+
68
+ @nx._dispatchable
69
+ def is_dominating_set(G, nbunch):
70
+ """Checks if `nbunch` is a dominating set for `G`.
71
+
72
+ A *dominating set* for a graph with node set *V* is a subset *D* of
73
+ *V* such that every node not in *D* is adjacent to at least one
74
+ member of *D* [1]_.
75
+
76
+ Parameters
77
+ ----------
78
+ G : NetworkX graph
79
+
80
+ nbunch : iterable
81
+ An iterable of nodes in the graph `G`.
82
+
83
+ See also
84
+ --------
85
+ dominating_set
86
+
87
+ References
88
+ ----------
89
+ .. [1] https://en.wikipedia.org/wiki/Dominating_set
90
+
91
+ """
92
+ testset = {n for n in nbunch if n in G}
93
+ nbrs = set(chain.from_iterable(G[n] for n in testset))
94
+ return len(set(G) - testset - nbrs) == 0
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/efficiency_measures.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides functions for computing the efficiency of nodes and graphs."""
2
+
3
+ import networkx as nx
4
+ from networkx.exception import NetworkXNoPath
5
+
6
+ from ..utils import not_implemented_for
7
+
8
+ __all__ = ["efficiency", "local_efficiency", "global_efficiency"]
9
+
10
+
11
+ @not_implemented_for("directed")
12
+ @nx._dispatchable
13
+ def efficiency(G, u, v):
14
+ """Returns the efficiency of a pair of nodes in a graph.
15
+
16
+ The *efficiency* of a pair of nodes is the multiplicative inverse of the
17
+ shortest path distance between the nodes [1]_. Returns 0 if no path
18
+ between nodes.
19
+
20
+ Parameters
21
+ ----------
22
+ G : :class:`networkx.Graph`
23
+ An undirected graph for which to compute the average local efficiency.
24
+ u, v : node
25
+ Nodes in the graph ``G``.
26
+
27
+ Returns
28
+ -------
29
+ float
30
+ Multiplicative inverse of the shortest path distance between the nodes.
31
+
32
+ Examples
33
+ --------
34
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
35
+ >>> nx.efficiency(G, 2, 3) # this gives efficiency for node 2 and 3
36
+ 0.5
37
+
38
+ Notes
39
+ -----
40
+ Edge weights are ignored when computing the shortest path distances.
41
+
42
+ See also
43
+ --------
44
+ local_efficiency
45
+ global_efficiency
46
+
47
+ References
48
+ ----------
49
+ .. [1] Latora, Vito, and Massimo Marchiori.
50
+ "Efficient behavior of small-world networks."
51
+ *Physical Review Letters* 87.19 (2001): 198701.
52
+ <https://doi.org/10.1103/PhysRevLett.87.198701>
53
+
54
+ """
55
+ try:
56
+ eff = 1 / nx.shortest_path_length(G, u, v)
57
+ except NetworkXNoPath:
58
+ eff = 0
59
+ return eff
60
+
61
+
62
+ @not_implemented_for("directed")
63
+ @nx._dispatchable
64
+ def global_efficiency(G):
65
+ """Returns the average global efficiency of the graph.
66
+
67
+ The *efficiency* of a pair of nodes in a graph is the multiplicative
68
+ inverse of the shortest path distance between the nodes. The *average
69
+ global efficiency* of a graph is the average efficiency of all pairs of
70
+ nodes [1]_.
71
+
72
+ Parameters
73
+ ----------
74
+ G : :class:`networkx.Graph`
75
+ An undirected graph for which to compute the average global efficiency.
76
+
77
+ Returns
78
+ -------
79
+ float
80
+ The average global efficiency of the graph.
81
+
82
+ Examples
83
+ --------
84
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
85
+ >>> round(nx.global_efficiency(G), 12)
86
+ 0.916666666667
87
+
88
+ Notes
89
+ -----
90
+ Edge weights are ignored when computing the shortest path distances.
91
+
92
+ See also
93
+ --------
94
+ local_efficiency
95
+
96
+ References
97
+ ----------
98
+ .. [1] Latora, Vito, and Massimo Marchiori.
99
+ "Efficient behavior of small-world networks."
100
+ *Physical Review Letters* 87.19 (2001): 198701.
101
+ <https://doi.org/10.1103/PhysRevLett.87.198701>
102
+
103
+ """
104
+ n = len(G)
105
+ denom = n * (n - 1)
106
+ if denom != 0:
107
+ lengths = nx.all_pairs_shortest_path_length(G)
108
+ g_eff = 0
109
+ for source, targets in lengths:
110
+ for target, distance in targets.items():
111
+ if distance > 0:
112
+ g_eff += 1 / distance
113
+ g_eff /= denom
114
+ # g_eff = sum(1 / d for s, tgts in lengths
115
+ # for t, d in tgts.items() if d > 0) / denom
116
+ else:
117
+ g_eff = 0
118
+ # TODO This can be made more efficient by computing all pairs shortest
119
+ # path lengths in parallel.
120
+ return g_eff
121
+
122
+
123
+ @not_implemented_for("directed")
124
+ @nx._dispatchable
125
+ def local_efficiency(G):
126
+ """Returns the average local efficiency of the graph.
127
+
128
+ The *efficiency* of a pair of nodes in a graph is the multiplicative
129
+ inverse of the shortest path distance between the nodes. The *local
130
+ efficiency* of a node in the graph is the average global efficiency of the
131
+ subgraph induced by the neighbors of the node. The *average local
132
+ efficiency* is the average of the local efficiencies of each node [1]_.
133
+
134
+ Parameters
135
+ ----------
136
+ G : :class:`networkx.Graph`
137
+ An undirected graph for which to compute the average local efficiency.
138
+
139
+ Returns
140
+ -------
141
+ float
142
+ The average local efficiency of the graph.
143
+
144
+ Examples
145
+ --------
146
+ >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
147
+ >>> nx.local_efficiency(G)
148
+ 0.9166666666666667
149
+
150
+ Notes
151
+ -----
152
+ Edge weights are ignored when computing the shortest path distances.
153
+
154
+ See also
155
+ --------
156
+ global_efficiency
157
+
158
+ References
159
+ ----------
160
+ .. [1] Latora, Vito, and Massimo Marchiori.
161
+ "Efficient behavior of small-world networks."
162
+ *Physical Review Letters* 87.19 (2001): 198701.
163
+ <https://doi.org/10.1103/PhysRevLett.87.198701>
164
+
165
+ """
166
+ # TODO This summation can be trivially parallelized.
167
+ efficiency_list = (global_efficiency(G.subgraph(G[v])) for v in G)
168
+ return sum(efficiency_list) / len(G)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/hierarchy.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flow Hierarchy.
3
+ """
4
+ import networkx as nx
5
+
6
+ __all__ = ["flow_hierarchy"]
7
+
8
+
9
+ @nx._dispatchable(edge_attrs="weight")
10
+ def flow_hierarchy(G, weight=None):
11
+ """Returns the flow hierarchy of a directed network.
12
+
13
+ Flow hierarchy is defined as the fraction of edges not participating
14
+ in cycles in a directed graph [1]_.
15
+
16
+ Parameters
17
+ ----------
18
+ G : DiGraph or MultiDiGraph
19
+ A directed graph
20
+
21
+ weight : string, optional (default=None)
22
+ Attribute to use for edge weights. If None the weight defaults to 1.
23
+
24
+ Returns
25
+ -------
26
+ h : float
27
+ Flow hierarchy value
28
+
29
+ Notes
30
+ -----
31
+ The algorithm described in [1]_ computes the flow hierarchy through
32
+ exponentiation of the adjacency matrix. This function implements an
33
+ alternative approach that finds strongly connected components.
34
+ An edge is in a cycle if and only if it is in a strongly connected
35
+ component, which can be found in $O(m)$ time using Tarjan's algorithm.
36
+
37
+ References
38
+ ----------
39
+ .. [1] Luo, J.; Magee, C.L. (2011),
40
+ Detecting evolving patterns of self-organizing networks by flow
41
+ hierarchy measurement, Complexity, Volume 16 Issue 6 53-61.
42
+ DOI: 10.1002/cplx.20368
43
+ http://web.mit.edu/~cmagee/www/documents/28-DetectingEvolvingPatterns_FlowHierarchy.pdf
44
+ """
45
+ if not G.is_directed():
46
+ raise nx.NetworkXError("G must be a digraph in flow_hierarchy")
47
+ scc = nx.strongly_connected_components(G)
48
+ return 1 - sum(G.subgraph(c).size(weight) for c in scc) / G.size(weight)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/isolate.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions for identifying isolate (degree zero) nodes.
3
+ """
4
+ import networkx as nx
5
+
6
+ __all__ = ["is_isolate", "isolates", "number_of_isolates"]
7
+
8
+
9
+ @nx._dispatchable
10
+ def is_isolate(G, n):
11
+ """Determines whether a node is an isolate.
12
+
13
+ An *isolate* is a node with no neighbors (that is, with degree
14
+ zero). For directed graphs, this means no in-neighbors and no
15
+ out-neighbors.
16
+
17
+ Parameters
18
+ ----------
19
+ G : NetworkX graph
20
+
21
+ n : node
22
+ A node in `G`.
23
+
24
+ Returns
25
+ -------
26
+ is_isolate : bool
27
+ True if and only if `n` has no neighbors.
28
+
29
+ Examples
30
+ --------
31
+ >>> G = nx.Graph()
32
+ >>> G.add_edge(1, 2)
33
+ >>> G.add_node(3)
34
+ >>> nx.is_isolate(G, 2)
35
+ False
36
+ >>> nx.is_isolate(G, 3)
37
+ True
38
+ """
39
+ return G.degree(n) == 0
40
+
41
+
42
+ @nx._dispatchable
43
+ def isolates(G):
44
+ """Iterator over isolates in the graph.
45
+
46
+ An *isolate* is a node with no neighbors (that is, with degree
47
+ zero). For directed graphs, this means no in-neighbors and no
48
+ out-neighbors.
49
+
50
+ Parameters
51
+ ----------
52
+ G : NetworkX graph
53
+
54
+ Returns
55
+ -------
56
+ iterator
57
+ An iterator over the isolates of `G`.
58
+
59
+ Examples
60
+ --------
61
+ To get a list of all isolates of a graph, use the :class:`list`
62
+ constructor::
63
+
64
+ >>> G = nx.Graph()
65
+ >>> G.add_edge(1, 2)
66
+ >>> G.add_node(3)
67
+ >>> list(nx.isolates(G))
68
+ [3]
69
+
70
+ To remove all isolates in the graph, first create a list of the
71
+ isolates, then use :meth:`Graph.remove_nodes_from`::
72
+
73
+ >>> G.remove_nodes_from(list(nx.isolates(G)))
74
+ >>> list(G)
75
+ [1, 2]
76
+
77
+ For digraphs, isolates have zero in-degree and zero out_degre::
78
+
79
+ >>> G = nx.DiGraph([(0, 1), (1, 2)])
80
+ >>> G.add_node(3)
81
+ >>> list(nx.isolates(G))
82
+ [3]
83
+
84
+ """
85
+ return (n for n, d in G.degree() if d == 0)
86
+
87
+
88
+ @nx._dispatchable
89
+ def number_of_isolates(G):
90
+ """Returns the number of isolates in the graph.
91
+
92
+ An *isolate* is a node with no neighbors (that is, with degree
93
+ zero). For directed graphs, this means no in-neighbors and no
94
+ out-neighbors.
95
+
96
+ Parameters
97
+ ----------
98
+ G : NetworkX graph
99
+
100
+ Returns
101
+ -------
102
+ int
103
+ The number of degree zero nodes in the graph `G`.
104
+
105
+ """
106
+ # TODO This can be parallelized.
107
+ return sum(1 for v in isolates(G))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/link_prediction.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Link prediction algorithms.
3
+ """
4
+
5
+
6
+ from math import log
7
+
8
+ import networkx as nx
9
+ from networkx.utils import not_implemented_for
10
+
11
+ __all__ = [
12
+ "resource_allocation_index",
13
+ "jaccard_coefficient",
14
+ "adamic_adar_index",
15
+ "preferential_attachment",
16
+ "cn_soundarajan_hopcroft",
17
+ "ra_index_soundarajan_hopcroft",
18
+ "within_inter_cluster",
19
+ "common_neighbor_centrality",
20
+ ]
21
+
22
+
23
+ def _apply_prediction(G, func, ebunch=None):
24
+ """Applies the given function to each edge in the specified iterable
25
+ of edges.
26
+
27
+ `G` is an instance of :class:`networkx.Graph`.
28
+
29
+ `func` is a function on two inputs, each of which is a node in the
30
+ graph. The function can return anything, but it should return a
31
+ value representing a prediction of the likelihood of a "link"
32
+ joining the two nodes.
33
+
34
+ `ebunch` is an iterable of pairs of nodes. If not specified, all
35
+ non-edges in the graph `G` will be used.
36
+
37
+ """
38
+ if ebunch is None:
39
+ ebunch = nx.non_edges(G)
40
+ else:
41
+ for u, v in ebunch:
42
+ if u not in G:
43
+ raise nx.NodeNotFound(f"Node {u} not in G.")
44
+ if v not in G:
45
+ raise nx.NodeNotFound(f"Node {v} not in G.")
46
+ return ((u, v, func(u, v)) for u, v in ebunch)
47
+
48
+
49
+ @not_implemented_for("directed")
50
+ @not_implemented_for("multigraph")
51
+ @nx._dispatchable
52
+ def resource_allocation_index(G, ebunch=None):
53
+ r"""Compute the resource allocation index of all node pairs in ebunch.
54
+
55
+ Resource allocation index of `u` and `v` is defined as
56
+
57
+ .. math::
58
+
59
+ \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{|\Gamma(w)|}
60
+
61
+ where $\Gamma(u)$ denotes the set of neighbors of $u$.
62
+
63
+ Parameters
64
+ ----------
65
+ G : graph
66
+ A NetworkX undirected graph.
67
+
68
+ ebunch : iterable of node pairs, optional (default = None)
69
+ Resource allocation index will be computed for each pair of
70
+ nodes given in the iterable. The pairs must be given as
71
+ 2-tuples (u, v) where u and v are nodes in the graph. If ebunch
72
+ is None then all nonexistent edges in the graph will be used.
73
+ Default value: None.
74
+
75
+ Returns
76
+ -------
77
+ piter : iterator
78
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
79
+ pair of nodes and p is their resource allocation index.
80
+
81
+ Raises
82
+ ------
83
+ NetworkXNotImplemented
84
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
85
+
86
+ NodeNotFound
87
+ If `ebunch` has a node that is not in `G`.
88
+
89
+ Examples
90
+ --------
91
+ >>> G = nx.complete_graph(5)
92
+ >>> preds = nx.resource_allocation_index(G, [(0, 1), (2, 3)])
93
+ >>> for u, v, p in preds:
94
+ ... print(f"({u}, {v}) -> {p:.8f}")
95
+ (0, 1) -> 0.75000000
96
+ (2, 3) -> 0.75000000
97
+
98
+ References
99
+ ----------
100
+ .. [1] T. Zhou, L. Lu, Y.-C. Zhang.
101
+ Predicting missing links via local information.
102
+ Eur. Phys. J. B 71 (2009) 623.
103
+ https://arxiv.org/pdf/0901.0553.pdf
104
+ """
105
+
106
+ def predict(u, v):
107
+ return sum(1 / G.degree(w) for w in nx.common_neighbors(G, u, v))
108
+
109
+ return _apply_prediction(G, predict, ebunch)
110
+
111
+
112
+ @not_implemented_for("directed")
113
+ @not_implemented_for("multigraph")
114
+ @nx._dispatchable
115
+ def jaccard_coefficient(G, ebunch=None):
116
+ r"""Compute the Jaccard coefficient of all node pairs in ebunch.
117
+
118
+ Jaccard coefficient of nodes `u` and `v` is defined as
119
+
120
+ .. math::
121
+
122
+ \frac{|\Gamma(u) \cap \Gamma(v)|}{|\Gamma(u) \cup \Gamma(v)|}
123
+
124
+ where $\Gamma(u)$ denotes the set of neighbors of $u$.
125
+
126
+ Parameters
127
+ ----------
128
+ G : graph
129
+ A NetworkX undirected graph.
130
+
131
+ ebunch : iterable of node pairs, optional (default = None)
132
+ Jaccard coefficient will be computed for each pair of nodes
133
+ given in the iterable. The pairs must be given as 2-tuples
134
+ (u, v) where u and v are nodes in the graph. If ebunch is None
135
+ then all nonexistent edges in the graph will be used.
136
+ Default value: None.
137
+
138
+ Returns
139
+ -------
140
+ piter : iterator
141
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
142
+ pair of nodes and p is their Jaccard coefficient.
143
+
144
+ Raises
145
+ ------
146
+ NetworkXNotImplemented
147
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
148
+
149
+ NodeNotFound
150
+ If `ebunch` has a node that is not in `G`.
151
+
152
+ Examples
153
+ --------
154
+ >>> G = nx.complete_graph(5)
155
+ >>> preds = nx.jaccard_coefficient(G, [(0, 1), (2, 3)])
156
+ >>> for u, v, p in preds:
157
+ ... print(f"({u}, {v}) -> {p:.8f}")
158
+ (0, 1) -> 0.60000000
159
+ (2, 3) -> 0.60000000
160
+
161
+ References
162
+ ----------
163
+ .. [1] D. Liben-Nowell, J. Kleinberg.
164
+ The Link Prediction Problem for Social Networks (2004).
165
+ http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
166
+ """
167
+
168
+ def predict(u, v):
169
+ union_size = len(set(G[u]) | set(G[v]))
170
+ if union_size == 0:
171
+ return 0
172
+ return len(nx.common_neighbors(G, u, v)) / union_size
173
+
174
+ return _apply_prediction(G, predict, ebunch)
175
+
176
+
177
+ @not_implemented_for("directed")
178
+ @not_implemented_for("multigraph")
179
+ @nx._dispatchable
180
+ def adamic_adar_index(G, ebunch=None):
181
+ r"""Compute the Adamic-Adar index of all node pairs in ebunch.
182
+
183
+ Adamic-Adar index of `u` and `v` is defined as
184
+
185
+ .. math::
186
+
187
+ \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{\log |\Gamma(w)|}
188
+
189
+ where $\Gamma(u)$ denotes the set of neighbors of $u$.
190
+ This index leads to zero-division for nodes only connected via self-loops.
191
+ It is intended to be used when no self-loops are present.
192
+
193
+ Parameters
194
+ ----------
195
+ G : graph
196
+ NetworkX undirected graph.
197
+
198
+ ebunch : iterable of node pairs, optional (default = None)
199
+ Adamic-Adar index will be computed for each pair of nodes given
200
+ in the iterable. The pairs must be given as 2-tuples (u, v)
201
+ where u and v are nodes in the graph. If ebunch is None then all
202
+ nonexistent edges in the graph will be used.
203
+ Default value: None.
204
+
205
+ Returns
206
+ -------
207
+ piter : iterator
208
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
209
+ pair of nodes and p is their Adamic-Adar index.
210
+
211
+ Raises
212
+ ------
213
+ NetworkXNotImplemented
214
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
215
+
216
+ NodeNotFound
217
+ If `ebunch` has a node that is not in `G`.
218
+
219
+ Examples
220
+ --------
221
+ >>> G = nx.complete_graph(5)
222
+ >>> preds = nx.adamic_adar_index(G, [(0, 1), (2, 3)])
223
+ >>> for u, v, p in preds:
224
+ ... print(f"({u}, {v}) -> {p:.8f}")
225
+ (0, 1) -> 2.16404256
226
+ (2, 3) -> 2.16404256
227
+
228
+ References
229
+ ----------
230
+ .. [1] D. Liben-Nowell, J. Kleinberg.
231
+ The Link Prediction Problem for Social Networks (2004).
232
+ http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
233
+ """
234
+
235
+ def predict(u, v):
236
+ return sum(1 / log(G.degree(w)) for w in nx.common_neighbors(G, u, v))
237
+
238
+ return _apply_prediction(G, predict, ebunch)
239
+
240
+
241
+ @not_implemented_for("directed")
242
+ @not_implemented_for("multigraph")
243
+ @nx._dispatchable
244
+ def common_neighbor_centrality(G, ebunch=None, alpha=0.8):
245
+ r"""Return the CCPA score for each pair of nodes.
246
+
247
+ Compute the Common Neighbor and Centrality based Parameterized Algorithm(CCPA)
248
+ score of all node pairs in ebunch.
249
+
250
+ CCPA score of `u` and `v` is defined as
251
+
252
+ .. math::
253
+
254
+ \alpha \cdot (|\Gamma (u){\cap }^{}\Gamma (v)|)+(1-\alpha )\cdot \frac{N}{{d}_{uv}}
255
+
256
+ where $\Gamma(u)$ denotes the set of neighbors of $u$, $\Gamma(v)$ denotes the
257
+ set of neighbors of $v$, $\alpha$ is parameter varies between [0,1], $N$ denotes
258
+ total number of nodes in the Graph and ${d}_{uv}$ denotes shortest distance
259
+ between $u$ and $v$.
260
+
261
+ This algorithm is based on two vital properties of nodes, namely the number
262
+ of common neighbors and their centrality. Common neighbor refers to the common
263
+ nodes between two nodes. Centrality refers to the prestige that a node enjoys
264
+ in a network.
265
+
266
+ .. seealso::
267
+
268
+ :func:`common_neighbors`
269
+
270
+ Parameters
271
+ ----------
272
+ G : graph
273
+ NetworkX undirected graph.
274
+
275
+ ebunch : iterable of node pairs, optional (default = None)
276
+ Preferential attachment score will be computed for each pair of
277
+ nodes given in the iterable. The pairs must be given as
278
+ 2-tuples (u, v) where u and v are nodes in the graph. If ebunch
279
+ is None then all nonexistent edges in the graph will be used.
280
+ Default value: None.
281
+
282
+ alpha : Parameter defined for participation of Common Neighbor
283
+ and Centrality Algorithm share. Values for alpha should
284
+ normally be between 0 and 1. Default value set to 0.8
285
+ because author found better performance at 0.8 for all the
286
+ dataset.
287
+ Default value: 0.8
288
+
289
+
290
+ Returns
291
+ -------
292
+ piter : iterator
293
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
294
+ pair of nodes and p is their Common Neighbor and Centrality based
295
+ Parameterized Algorithm(CCPA) score.
296
+
297
+ Raises
298
+ ------
299
+ NetworkXNotImplemented
300
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
301
+
302
+ NetworkXAlgorithmError
303
+ If self loops exsists in `ebunch` or in `G` (if `ebunch` is `None`).
304
+
305
+ NodeNotFound
306
+ If `ebunch` has a node that is not in `G`.
307
+
308
+ Examples
309
+ --------
310
+ >>> G = nx.complete_graph(5)
311
+ >>> preds = nx.common_neighbor_centrality(G, [(0, 1), (2, 3)])
312
+ >>> for u, v, p in preds:
313
+ ... print(f"({u}, {v}) -> {p}")
314
+ (0, 1) -> 3.4000000000000004
315
+ (2, 3) -> 3.4000000000000004
316
+
317
+ References
318
+ ----------
319
+ .. [1] Ahmad, I., Akhtar, M.U., Noor, S. et al.
320
+ Missing Link Prediction using Common Neighbor and Centrality based Parameterized Algorithm.
321
+ Sci Rep 10, 364 (2020).
322
+ https://doi.org/10.1038/s41598-019-57304-y
323
+ """
324
+
325
+ # When alpha == 1, the CCPA score simplifies to the number of common neighbors.
326
+ if alpha == 1:
327
+
328
+ def predict(u, v):
329
+ if u == v:
330
+ raise nx.NetworkXAlgorithmError("Self loops are not supported")
331
+
332
+ return len(nx.common_neighbors(G, u, v))
333
+
334
+ else:
335
+ spl = dict(nx.shortest_path_length(G))
336
+ inf = float("inf")
337
+
338
+ def predict(u, v):
339
+ if u == v:
340
+ raise nx.NetworkXAlgorithmError("Self loops are not supported")
341
+ path_len = spl[u].get(v, inf)
342
+
343
+ n_nbrs = len(nx.common_neighbors(G, u, v))
344
+ return alpha * n_nbrs + (1 - alpha) * len(G) / path_len
345
+
346
+ return _apply_prediction(G, predict, ebunch)
347
+
348
+
349
+ @not_implemented_for("directed")
350
+ @not_implemented_for("multigraph")
351
+ @nx._dispatchable
352
+ def preferential_attachment(G, ebunch=None):
353
+ r"""Compute the preferential attachment score of all node pairs in ebunch.
354
+
355
+ Preferential attachment score of `u` and `v` is defined as
356
+
357
+ .. math::
358
+
359
+ |\Gamma(u)| |\Gamma(v)|
360
+
361
+ where $\Gamma(u)$ denotes the set of neighbors of $u$.
362
+
363
+ Parameters
364
+ ----------
365
+ G : graph
366
+ NetworkX undirected graph.
367
+
368
+ ebunch : iterable of node pairs, optional (default = None)
369
+ Preferential attachment score will be computed for each pair of
370
+ nodes given in the iterable. The pairs must be given as
371
+ 2-tuples (u, v) where u and v are nodes in the graph. If ebunch
372
+ is None then all nonexistent edges in the graph will be used.
373
+ Default value: None.
374
+
375
+ Returns
376
+ -------
377
+ piter : iterator
378
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
379
+ pair of nodes and p is their preferential attachment score.
380
+
381
+ Raises
382
+ ------
383
+ NetworkXNotImplemented
384
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
385
+
386
+ NodeNotFound
387
+ If `ebunch` has a node that is not in `G`.
388
+
389
+ Examples
390
+ --------
391
+ >>> G = nx.complete_graph(5)
392
+ >>> preds = nx.preferential_attachment(G, [(0, 1), (2, 3)])
393
+ >>> for u, v, p in preds:
394
+ ... print(f"({u}, {v}) -> {p}")
395
+ (0, 1) -> 16
396
+ (2, 3) -> 16
397
+
398
+ References
399
+ ----------
400
+ .. [1] D. Liben-Nowell, J. Kleinberg.
401
+ The Link Prediction Problem for Social Networks (2004).
402
+ http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
403
+ """
404
+
405
+ def predict(u, v):
406
+ return G.degree(u) * G.degree(v)
407
+
408
+ return _apply_prediction(G, predict, ebunch)
409
+
410
+
411
+ @not_implemented_for("directed")
412
+ @not_implemented_for("multigraph")
413
+ @nx._dispatchable(node_attrs="community")
414
+ def cn_soundarajan_hopcroft(G, ebunch=None, community="community"):
415
+ r"""Count the number of common neighbors of all node pairs in ebunch
416
+ using community information.
417
+
418
+ For two nodes $u$ and $v$, this function computes the number of
419
+ common neighbors and bonus one for each common neighbor belonging to
420
+ the same community as $u$ and $v$. Mathematically,
421
+
422
+ .. math::
423
+
424
+ |\Gamma(u) \cap \Gamma(v)| + \sum_{w \in \Gamma(u) \cap \Gamma(v)} f(w)
425
+
426
+ where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
427
+ and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
428
+ neighbors of $u$.
429
+
430
+ Parameters
431
+ ----------
432
+ G : graph
433
+ A NetworkX undirected graph.
434
+
435
+ ebunch : iterable of node pairs, optional (default = None)
436
+ The score will be computed for each pair of nodes given in the
437
+ iterable. The pairs must be given as 2-tuples (u, v) where u
438
+ and v are nodes in the graph. If ebunch is None then all
439
+ nonexistent edges in the graph will be used.
440
+ Default value: None.
441
+
442
+ community : string, optional (default = 'community')
443
+ Nodes attribute name containing the community information.
444
+ G[u][community] identifies which community u belongs to. Each
445
+ node belongs to at most one community. Default value: 'community'.
446
+
447
+ Returns
448
+ -------
449
+ piter : iterator
450
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
451
+ pair of nodes and p is their score.
452
+
453
+ Raises
454
+ ------
455
+ NetworkXNotImplemented
456
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
457
+
458
+ NetworkXAlgorithmError
459
+ If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
460
+
461
+ NodeNotFound
462
+ If `ebunch` has a node that is not in `G`.
463
+
464
+ Examples
465
+ --------
466
+ >>> G = nx.path_graph(3)
467
+ >>> G.nodes[0]["community"] = 0
468
+ >>> G.nodes[1]["community"] = 0
469
+ >>> G.nodes[2]["community"] = 0
470
+ >>> preds = nx.cn_soundarajan_hopcroft(G, [(0, 2)])
471
+ >>> for u, v, p in preds:
472
+ ... print(f"({u}, {v}) -> {p}")
473
+ (0, 2) -> 2
474
+
475
+ References
476
+ ----------
477
+ .. [1] Sucheta Soundarajan and John Hopcroft.
478
+ Using community information to improve the precision of link
479
+ prediction methods.
480
+ In Proceedings of the 21st international conference companion on
481
+ World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
482
+ http://doi.acm.org/10.1145/2187980.2188150
483
+ """
484
+
485
+ def predict(u, v):
486
+ Cu = _community(G, u, community)
487
+ Cv = _community(G, v, community)
488
+ cnbors = nx.common_neighbors(G, u, v)
489
+ neighbors = (
490
+ sum(_community(G, w, community) == Cu for w in cnbors) if Cu == Cv else 0
491
+ )
492
+ return len(cnbors) + neighbors
493
+
494
+ return _apply_prediction(G, predict, ebunch)
495
+
496
+
497
+ @not_implemented_for("directed")
498
+ @not_implemented_for("multigraph")
499
+ @nx._dispatchable(node_attrs="community")
500
+ def ra_index_soundarajan_hopcroft(G, ebunch=None, community="community"):
501
+ r"""Compute the resource allocation index of all node pairs in
502
+ ebunch using community information.
503
+
504
+ For two nodes $u$ and $v$, this function computes the resource
505
+ allocation index considering only common neighbors belonging to the
506
+ same community as $u$ and $v$. Mathematically,
507
+
508
+ .. math::
509
+
510
+ \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{f(w)}{|\Gamma(w)|}
511
+
512
+ where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
513
+ and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
514
+ neighbors of $u$.
515
+
516
+ Parameters
517
+ ----------
518
+ G : graph
519
+ A NetworkX undirected graph.
520
+
521
+ ebunch : iterable of node pairs, optional (default = None)
522
+ The score will be computed for each pair of nodes given in the
523
+ iterable. The pairs must be given as 2-tuples (u, v) where u
524
+ and v are nodes in the graph. If ebunch is None then all
525
+ nonexistent edges in the graph will be used.
526
+ Default value: None.
527
+
528
+ community : string, optional (default = 'community')
529
+ Nodes attribute name containing the community information.
530
+ G[u][community] identifies which community u belongs to. Each
531
+ node belongs to at most one community. Default value: 'community'.
532
+
533
+ Returns
534
+ -------
535
+ piter : iterator
536
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
537
+ pair of nodes and p is their score.
538
+
539
+ Raises
540
+ ------
541
+ NetworkXNotImplemented
542
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
543
+
544
+ NetworkXAlgorithmError
545
+ If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
546
+
547
+ NodeNotFound
548
+ If `ebunch` has a node that is not in `G`.
549
+
550
+ Examples
551
+ --------
552
+ >>> G = nx.Graph()
553
+ >>> G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
554
+ >>> G.nodes[0]["community"] = 0
555
+ >>> G.nodes[1]["community"] = 0
556
+ >>> G.nodes[2]["community"] = 1
557
+ >>> G.nodes[3]["community"] = 0
558
+ >>> preds = nx.ra_index_soundarajan_hopcroft(G, [(0, 3)])
559
+ >>> for u, v, p in preds:
560
+ ... print(f"({u}, {v}) -> {p:.8f}")
561
+ (0, 3) -> 0.50000000
562
+
563
+ References
564
+ ----------
565
+ .. [1] Sucheta Soundarajan and John Hopcroft.
566
+ Using community information to improve the precision of link
567
+ prediction methods.
568
+ In Proceedings of the 21st international conference companion on
569
+ World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
570
+ http://doi.acm.org/10.1145/2187980.2188150
571
+ """
572
+
573
+ def predict(u, v):
574
+ Cu = _community(G, u, community)
575
+ Cv = _community(G, v, community)
576
+ if Cu != Cv:
577
+ return 0
578
+ cnbors = nx.common_neighbors(G, u, v)
579
+ return sum(1 / G.degree(w) for w in cnbors if _community(G, w, community) == Cu)
580
+
581
+ return _apply_prediction(G, predict, ebunch)
582
+
583
+
584
+ @not_implemented_for("directed")
585
+ @not_implemented_for("multigraph")
586
+ @nx._dispatchable(node_attrs="community")
587
+ def within_inter_cluster(G, ebunch=None, delta=0.001, community="community"):
588
+ """Compute the ratio of within- and inter-cluster common neighbors
589
+ of all node pairs in ebunch.
590
+
591
+ For two nodes `u` and `v`, if a common neighbor `w` belongs to the
592
+ same community as them, `w` is considered as within-cluster common
593
+ neighbor of `u` and `v`. Otherwise, it is considered as
594
+ inter-cluster common neighbor of `u` and `v`. The ratio between the
595
+ size of the set of within- and inter-cluster common neighbors is
596
+ defined as the WIC measure. [1]_
597
+
598
+ Parameters
599
+ ----------
600
+ G : graph
601
+ A NetworkX undirected graph.
602
+
603
+ ebunch : iterable of node pairs, optional (default = None)
604
+ The WIC measure will be computed for each pair of nodes given in
605
+ the iterable. The pairs must be given as 2-tuples (u, v) where
606
+ u and v are nodes in the graph. If ebunch is None then all
607
+ nonexistent edges in the graph will be used.
608
+ Default value: None.
609
+
610
+ delta : float, optional (default = 0.001)
611
+ Value to prevent division by zero in case there is no
612
+ inter-cluster common neighbor between two nodes. See [1]_ for
613
+ details. Default value: 0.001.
614
+
615
+ community : string, optional (default = 'community')
616
+ Nodes attribute name containing the community information.
617
+ G[u][community] identifies which community u belongs to. Each
618
+ node belongs to at most one community. Default value: 'community'.
619
+
620
+ Returns
621
+ -------
622
+ piter : iterator
623
+ An iterator of 3-tuples in the form (u, v, p) where (u, v) is a
624
+ pair of nodes and p is their WIC measure.
625
+
626
+ Raises
627
+ ------
628
+ NetworkXNotImplemented
629
+ If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
630
+
631
+ NetworkXAlgorithmError
632
+ - If `delta` is less than or equal to zero.
633
+ - If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
634
+
635
+ NodeNotFound
636
+ If `ebunch` has a node that is not in `G`.
637
+
638
+ Examples
639
+ --------
640
+ >>> G = nx.Graph()
641
+ >>> G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 4), (2, 4), (3, 4)])
642
+ >>> G.nodes[0]["community"] = 0
643
+ >>> G.nodes[1]["community"] = 1
644
+ >>> G.nodes[2]["community"] = 0
645
+ >>> G.nodes[3]["community"] = 0
646
+ >>> G.nodes[4]["community"] = 0
647
+ >>> preds = nx.within_inter_cluster(G, [(0, 4)])
648
+ >>> for u, v, p in preds:
649
+ ... print(f"({u}, {v}) -> {p:.8f}")
650
+ (0, 4) -> 1.99800200
651
+ >>> preds = nx.within_inter_cluster(G, [(0, 4)], delta=0.5)
652
+ >>> for u, v, p in preds:
653
+ ... print(f"({u}, {v}) -> {p:.8f}")
654
+ (0, 4) -> 1.33333333
655
+
656
+ References
657
+ ----------
658
+ .. [1] Jorge Carlos Valverde-Rebaza and Alneu de Andrade Lopes.
659
+ Link prediction in complex networks based on cluster information.
660
+ In Proceedings of the 21st Brazilian conference on Advances in
661
+ Artificial Intelligence (SBIA'12)
662
+ https://doi.org/10.1007/978-3-642-34459-6_10
663
+ """
664
+ if delta <= 0:
665
+ raise nx.NetworkXAlgorithmError("Delta must be greater than zero")
666
+
667
+ def predict(u, v):
668
+ Cu = _community(G, u, community)
669
+ Cv = _community(G, v, community)
670
+ if Cu != Cv:
671
+ return 0
672
+ cnbors = nx.common_neighbors(G, u, v)
673
+ within = {w for w in cnbors if _community(G, w, community) == Cu}
674
+ inter = cnbors - within
675
+ return len(within) / (len(inter) + delta)
676
+
677
+ return _apply_prediction(G, predict, ebunch)
678
+
679
+
680
+ def _community(G, u, community):
681
+ """Get the community of the given node."""
682
+ node_u = G.nodes[u]
683
+ try:
684
+ return node_u[community]
685
+ except KeyError as err:
686
+ raise nx.NetworkXAlgorithmError(
687
+ f"No community information available for Node {u}"
688
+ ) from err
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/lowest_common_ancestors.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Algorithms for finding the lowest common ancestor of trees and DAGs."""
2
+ from collections import defaultdict
3
+ from collections.abc import Mapping, Set
4
+ from itertools import combinations_with_replacement
5
+
6
+ import networkx as nx
7
+ from networkx.utils import UnionFind, arbitrary_element, not_implemented_for
8
+
9
+ __all__ = [
10
+ "all_pairs_lowest_common_ancestor",
11
+ "tree_all_pairs_lowest_common_ancestor",
12
+ "lowest_common_ancestor",
13
+ ]
14
+
15
+
16
+ @not_implemented_for("undirected")
17
+ @nx._dispatchable
18
+ def all_pairs_lowest_common_ancestor(G, pairs=None):
19
+ """Return the lowest common ancestor of all pairs or the provided pairs
20
+
21
+ Parameters
22
+ ----------
23
+ G : NetworkX directed graph
24
+
25
+ pairs : iterable of pairs of nodes, optional (default: all pairs)
26
+ The pairs of nodes of interest.
27
+ If None, will find the LCA of all pairs of nodes.
28
+
29
+ Yields
30
+ ------
31
+ ((node1, node2), lca) : 2-tuple
32
+ Where lca is least common ancestor of node1 and node2.
33
+ Note that for the default case, the order of the node pair is not considered,
34
+ e.g. you will not get both ``(a, b)`` and ``(b, a)``
35
+
36
+ Raises
37
+ ------
38
+ NetworkXPointlessConcept
39
+ If `G` is null.
40
+ NetworkXError
41
+ If `G` is not a DAG.
42
+
43
+ Examples
44
+ --------
45
+ The default behavior is to yield the lowest common ancestor for all
46
+ possible combinations of nodes in `G`, including self-pairings:
47
+
48
+ >>> G = nx.DiGraph([(0, 1), (0, 3), (1, 2)])
49
+ >>> dict(nx.all_pairs_lowest_common_ancestor(G))
50
+ {(0, 0): 0, (0, 1): 0, (0, 3): 0, (0, 2): 0, (1, 1): 1, (1, 3): 0, (1, 2): 1, (3, 3): 3, (3, 2): 0, (2, 2): 2}
51
+
52
+ The pairs argument can be used to limit the output to only the
53
+ specified node pairings:
54
+
55
+ >>> dict(nx.all_pairs_lowest_common_ancestor(G, pairs=[(1, 2), (2, 3)]))
56
+ {(1, 2): 1, (2, 3): 0}
57
+
58
+ Notes
59
+ -----
60
+ Only defined on non-null directed acyclic graphs.
61
+
62
+ See Also
63
+ --------
64
+ lowest_common_ancestor
65
+ """
66
+ if not nx.is_directed_acyclic_graph(G):
67
+ raise nx.NetworkXError("LCA only defined on directed acyclic graphs.")
68
+ if len(G) == 0:
69
+ raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
70
+
71
+ if pairs is None:
72
+ pairs = combinations_with_replacement(G, 2)
73
+ else:
74
+ # Convert iterator to iterable, if necessary. Trim duplicates.
75
+ pairs = dict.fromkeys(pairs)
76
+ # Verify that each of the nodes in the provided pairs is in G
77
+ nodeset = set(G)
78
+ for pair in pairs:
79
+ if set(pair) - nodeset:
80
+ raise nx.NodeNotFound(
81
+ f"Node(s) {set(pair) - nodeset} from pair {pair} not in G."
82
+ )
83
+
84
+ # Once input validation is done, construct the generator
85
+ def generate_lca_from_pairs(G, pairs):
86
+ ancestor_cache = {}
87
+
88
+ for v, w in pairs:
89
+ if v not in ancestor_cache:
90
+ ancestor_cache[v] = nx.ancestors(G, v)
91
+ ancestor_cache[v].add(v)
92
+ if w not in ancestor_cache:
93
+ ancestor_cache[w] = nx.ancestors(G, w)
94
+ ancestor_cache[w].add(w)
95
+
96
+ common_ancestors = ancestor_cache[v] & ancestor_cache[w]
97
+
98
+ if common_ancestors:
99
+ common_ancestor = next(iter(common_ancestors))
100
+ while True:
101
+ successor = None
102
+ for lower_ancestor in G.successors(common_ancestor):
103
+ if lower_ancestor in common_ancestors:
104
+ successor = lower_ancestor
105
+ break
106
+ if successor is None:
107
+ break
108
+ common_ancestor = successor
109
+ yield ((v, w), common_ancestor)
110
+
111
+ return generate_lca_from_pairs(G, pairs)
112
+
113
+
114
+ @not_implemented_for("undirected")
115
+ @nx._dispatchable
116
+ def lowest_common_ancestor(G, node1, node2, default=None):
117
+ """Compute the lowest common ancestor of the given pair of nodes.
118
+
119
+ Parameters
120
+ ----------
121
+ G : NetworkX directed graph
122
+
123
+ node1, node2 : nodes in the graph.
124
+
125
+ default : object
126
+ Returned if no common ancestor between `node1` and `node2`
127
+
128
+ Returns
129
+ -------
130
+ The lowest common ancestor of node1 and node2,
131
+ or default if they have no common ancestors.
132
+
133
+ Examples
134
+ --------
135
+ >>> G = nx.DiGraph()
136
+ >>> nx.add_path(G, (0, 1, 2, 3))
137
+ >>> nx.add_path(G, (0, 4, 3))
138
+ >>> nx.lowest_common_ancestor(G, 2, 4)
139
+ 0
140
+
141
+ See Also
142
+ --------
143
+ all_pairs_lowest_common_ancestor"""
144
+
145
+ ans = list(all_pairs_lowest_common_ancestor(G, pairs=[(node1, node2)]))
146
+ if ans:
147
+ assert len(ans) == 1
148
+ return ans[0][1]
149
+ return default
150
+
151
+
152
+ @not_implemented_for("undirected")
153
+ @nx._dispatchable
154
+ def tree_all_pairs_lowest_common_ancestor(G, root=None, pairs=None):
155
+ r"""Yield the lowest common ancestor for sets of pairs in a tree.
156
+
157
+ Parameters
158
+ ----------
159
+ G : NetworkX directed graph (must be a tree)
160
+
161
+ root : node, optional (default: None)
162
+ The root of the subtree to operate on.
163
+ If None, assume the entire graph has exactly one source and use that.
164
+
165
+ pairs : iterable or iterator of pairs of nodes, optional (default: None)
166
+ The pairs of interest. If None, Defaults to all pairs of nodes
167
+ under `root` that have a lowest common ancestor.
168
+
169
+ Returns
170
+ -------
171
+ lcas : generator of tuples `((u, v), lca)` where `u` and `v` are nodes
172
+ in `pairs` and `lca` is their lowest common ancestor.
173
+
174
+ Examples
175
+ --------
176
+ >>> import pprint
177
+ >>> G = nx.DiGraph([(1, 3), (2, 4), (1, 2)])
178
+ >>> pprint.pprint(dict(nx.tree_all_pairs_lowest_common_ancestor(G)))
179
+ {(1, 1): 1,
180
+ (2, 1): 1,
181
+ (2, 2): 2,
182
+ (3, 1): 1,
183
+ (3, 2): 1,
184
+ (3, 3): 3,
185
+ (3, 4): 1,
186
+ (4, 1): 1,
187
+ (4, 2): 2,
188
+ (4, 4): 4}
189
+
190
+ We can also use `pairs` argument to specify the pairs of nodes for which we
191
+ want to compute lowest common ancestors. Here is an example:
192
+
193
+ >>> dict(nx.tree_all_pairs_lowest_common_ancestor(G, pairs=[(1, 4), (2, 3)]))
194
+ {(2, 3): 1, (1, 4): 1}
195
+
196
+ Notes
197
+ -----
198
+ Only defined on non-null trees represented with directed edges from
199
+ parents to children. Uses Tarjan's off-line lowest-common-ancestors
200
+ algorithm. Runs in time $O(4 \times (V + E + P))$ time, where 4 is the largest
201
+ value of the inverse Ackermann function likely to ever come up in actual
202
+ use, and $P$ is the number of pairs requested (or $V^2$ if all are needed).
203
+
204
+ Tarjan, R. E. (1979), "Applications of path compression on balanced trees",
205
+ Journal of the ACM 26 (4): 690-715, doi:10.1145/322154.322161.
206
+
207
+ See Also
208
+ --------
209
+ all_pairs_lowest_common_ancestor: similar routine for general DAGs
210
+ lowest_common_ancestor: just a single pair for general DAGs
211
+ """
212
+ if len(G) == 0:
213
+ raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.")
214
+
215
+ # Index pairs of interest for efficient lookup from either side.
216
+ if pairs is not None:
217
+ pair_dict = defaultdict(set)
218
+ # See note on all_pairs_lowest_common_ancestor.
219
+ if not isinstance(pairs, Mapping | Set):
220
+ pairs = set(pairs)
221
+ for u, v in pairs:
222
+ for n in (u, v):
223
+ if n not in G:
224
+ msg = f"The node {str(n)} is not in the digraph."
225
+ raise nx.NodeNotFound(msg)
226
+ pair_dict[u].add(v)
227
+ pair_dict[v].add(u)
228
+
229
+ # If root is not specified, find the exactly one node with in degree 0 and
230
+ # use it. Raise an error if none are found, or more than one is. Also check
231
+ # for any nodes with in degree larger than 1, which would imply G is not a
232
+ # tree.
233
+ if root is None:
234
+ for n, deg in G.in_degree:
235
+ if deg == 0:
236
+ if root is not None:
237
+ msg = "No root specified and tree has multiple sources."
238
+ raise nx.NetworkXError(msg)
239
+ root = n
240
+ # checking deg>1 is not sufficient for MultiDiGraphs
241
+ elif deg > 1 and len(G.pred[n]) > 1:
242
+ msg = "Tree LCA only defined on trees; use DAG routine."
243
+ raise nx.NetworkXError(msg)
244
+ if root is None:
245
+ raise nx.NetworkXError("Graph contains a cycle.")
246
+
247
+ # Iterative implementation of Tarjan's offline lca algorithm
248
+ # as described in CLRS on page 521 (2nd edition)/page 584 (3rd edition)
249
+ uf = UnionFind()
250
+ ancestors = {}
251
+ for node in G:
252
+ ancestors[node] = uf[node]
253
+
254
+ colors = defaultdict(bool)
255
+ for node in nx.dfs_postorder_nodes(G, root):
256
+ colors[node] = True
257
+ for v in pair_dict[node] if pairs is not None else G:
258
+ if colors[v]:
259
+ # If the user requested both directions of a pair, give it.
260
+ # Otherwise, just give one.
261
+ if pairs is not None and (node, v) in pairs:
262
+ yield (node, v), ancestors[uf[v]]
263
+ if pairs is None or (v, node) in pairs:
264
+ yield (v, node), ancestors[uf[v]]
265
+ if node != root:
266
+ parent = arbitrary_element(G.pred[node])
267
+ uf.union(parent, node)
268
+ ancestors[uf[parent]] = parent
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/matching.py ADDED
@@ -0,0 +1,1151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing and verifying matchings in a graph."""
2
+ from collections import Counter
3
+ from itertools import combinations, repeat
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ __all__ = [
9
+ "is_matching",
10
+ "is_maximal_matching",
11
+ "is_perfect_matching",
12
+ "max_weight_matching",
13
+ "min_weight_matching",
14
+ "maximal_matching",
15
+ ]
16
+
17
+
18
+ @not_implemented_for("multigraph")
19
+ @not_implemented_for("directed")
20
+ @nx._dispatchable
21
+ def maximal_matching(G):
22
+ r"""Find a maximal matching in the graph.
23
+
24
+ A matching is a subset of edges in which no node occurs more than once.
25
+ A maximal matching cannot add more edges and still be a matching.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+ Undirected graph
31
+
32
+ Returns
33
+ -------
34
+ matching : set
35
+ A maximal matching of the graph.
36
+
37
+ Examples
38
+ --------
39
+ >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5)])
40
+ >>> sorted(nx.maximal_matching(G))
41
+ [(1, 2), (3, 5)]
42
+
43
+ Notes
44
+ -----
45
+ The algorithm greedily selects a maximal matching M of the graph G
46
+ (i.e. no superset of M exists). It runs in $O(|E|)$ time.
47
+ """
48
+ matching = set()
49
+ nodes = set()
50
+ for edge in G.edges():
51
+ # If the edge isn't covered, add it to the matching
52
+ # then remove neighborhood of u and v from consideration.
53
+ u, v = edge
54
+ if u not in nodes and v not in nodes and u != v:
55
+ matching.add(edge)
56
+ nodes.update(edge)
57
+ return matching
58
+
59
+
60
+ def matching_dict_to_set(matching):
61
+ """Converts matching dict format to matching set format
62
+
63
+ Converts a dictionary representing a matching (as returned by
64
+ :func:`max_weight_matching`) to a set representing a matching (as
65
+ returned by :func:`maximal_matching`).
66
+
67
+ In the definition of maximal matching adopted by NetworkX,
68
+ self-loops are not allowed, so the provided dictionary is expected
69
+ to never have any mapping from a key to itself. However, the
70
+ dictionary is expected to have mirrored key/value pairs, for
71
+ example, key ``u`` with value ``v`` and key ``v`` with value ``u``.
72
+
73
+ """
74
+ edges = set()
75
+ for edge in matching.items():
76
+ u, v = edge
77
+ if (v, u) in edges or edge in edges:
78
+ continue
79
+ if u == v:
80
+ raise nx.NetworkXError(f"Selfloops cannot appear in matchings {edge}")
81
+ edges.add(edge)
82
+ return edges
83
+
84
+
85
+ @nx._dispatchable
86
+ def is_matching(G, matching):
87
+ """Return True if ``matching`` is a valid matching of ``G``
88
+
89
+ A *matching* in a graph is a set of edges in which no two distinct
90
+ edges share a common endpoint. Each node is incident to at most one
91
+ edge in the matching. The edges are said to be independent.
92
+
93
+ Parameters
94
+ ----------
95
+ G : NetworkX graph
96
+
97
+ matching : dict or set
98
+ A dictionary or set representing a matching. If a dictionary, it
99
+ must have ``matching[u] == v`` and ``matching[v] == u`` for each
100
+ edge ``(u, v)`` in the matching. If a set, it must have elements
101
+ of the form ``(u, v)``, where ``(u, v)`` is an edge in the
102
+ matching.
103
+
104
+ Returns
105
+ -------
106
+ bool
107
+ Whether the given set or dictionary represents a valid matching
108
+ in the graph.
109
+
110
+ Raises
111
+ ------
112
+ NetworkXError
113
+ If the proposed matching has an edge to a node not in G.
114
+ Or if the matching is not a collection of 2-tuple edges.
115
+
116
+ Examples
117
+ --------
118
+ >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5)])
119
+ >>> nx.is_maximal_matching(G, {1: 3, 2: 4}) # using dict to represent matching
120
+ True
121
+
122
+ >>> nx.is_matching(G, {(1, 3), (2, 4)}) # using set to represent matching
123
+ True
124
+
125
+ """
126
+ if isinstance(matching, dict):
127
+ matching = matching_dict_to_set(matching)
128
+
129
+ nodes = set()
130
+ for edge in matching:
131
+ if len(edge) != 2:
132
+ raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
133
+ u, v = edge
134
+ if u not in G or v not in G:
135
+ raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
136
+ if u == v:
137
+ return False
138
+ if not G.has_edge(u, v):
139
+ return False
140
+ if u in nodes or v in nodes:
141
+ return False
142
+ nodes.update(edge)
143
+ return True
144
+
145
+
146
+ @nx._dispatchable
147
+ def is_maximal_matching(G, matching):
148
+ """Return True if ``matching`` is a maximal matching of ``G``
149
+
150
+ A *maximal matching* in a graph is a matching in which adding any
151
+ edge would cause the set to no longer be a valid matching.
152
+
153
+ Parameters
154
+ ----------
155
+ G : NetworkX graph
156
+
157
+ matching : dict or set
158
+ A dictionary or set representing a matching. If a dictionary, it
159
+ must have ``matching[u] == v`` and ``matching[v] == u`` for each
160
+ edge ``(u, v)`` in the matching. If a set, it must have elements
161
+ of the form ``(u, v)``, where ``(u, v)`` is an edge in the
162
+ matching.
163
+
164
+ Returns
165
+ -------
166
+ bool
167
+ Whether the given set or dictionary represents a valid maximal
168
+ matching in the graph.
169
+
170
+ Examples
171
+ --------
172
+ >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
173
+ >>> nx.is_maximal_matching(G, {(1, 2), (3, 4)})
174
+ True
175
+
176
+ """
177
+ if isinstance(matching, dict):
178
+ matching = matching_dict_to_set(matching)
179
+ # If the given set is not a matching, then it is not a maximal matching.
180
+ edges = set()
181
+ nodes = set()
182
+ for edge in matching:
183
+ if len(edge) != 2:
184
+ raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
185
+ u, v = edge
186
+ if u not in G or v not in G:
187
+ raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
188
+ if u == v:
189
+ return False
190
+ if not G.has_edge(u, v):
191
+ return False
192
+ if u in nodes or v in nodes:
193
+ return False
194
+ nodes.update(edge)
195
+ edges.add(edge)
196
+ edges.add((v, u))
197
+ # A matching is maximal if adding any new edge from G to it
198
+ # causes the resulting set to match some node twice.
199
+ # Be careful to check for adding selfloops
200
+ for u, v in G.edges:
201
+ if (u, v) not in edges:
202
+ # could add edge (u, v) to edges and have a bigger matching
203
+ if u not in nodes and v not in nodes and u != v:
204
+ return False
205
+ return True
206
+
207
+
208
+ @nx._dispatchable
209
+ def is_perfect_matching(G, matching):
210
+ """Return True if ``matching`` is a perfect matching for ``G``
211
+
212
+ A *perfect matching* in a graph is a matching in which exactly one edge
213
+ is incident upon each vertex.
214
+
215
+ Parameters
216
+ ----------
217
+ G : NetworkX graph
218
+
219
+ matching : dict or set
220
+ A dictionary or set representing a matching. If a dictionary, it
221
+ must have ``matching[u] == v`` and ``matching[v] == u`` for each
222
+ edge ``(u, v)`` in the matching. If a set, it must have elements
223
+ of the form ``(u, v)``, where ``(u, v)`` is an edge in the
224
+ matching.
225
+
226
+ Returns
227
+ -------
228
+ bool
229
+ Whether the given set or dictionary represents a valid perfect
230
+ matching in the graph.
231
+
232
+ Examples
233
+ --------
234
+ >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5), (4, 6)])
235
+ >>> my_match = {1: 2, 3: 5, 4: 6}
236
+ >>> nx.is_perfect_matching(G, my_match)
237
+ True
238
+
239
+ """
240
+ if isinstance(matching, dict):
241
+ matching = matching_dict_to_set(matching)
242
+
243
+ nodes = set()
244
+ for edge in matching:
245
+ if len(edge) != 2:
246
+ raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}")
247
+ u, v = edge
248
+ if u not in G or v not in G:
249
+ raise nx.NetworkXError(f"matching contains edge {edge} with node not in G")
250
+ if u == v:
251
+ return False
252
+ if not G.has_edge(u, v):
253
+ return False
254
+ if u in nodes or v in nodes:
255
+ return False
256
+ nodes.update(edge)
257
+ return len(nodes) == len(G)
258
+
259
+
260
+ @not_implemented_for("multigraph")
261
+ @not_implemented_for("directed")
262
+ @nx._dispatchable(edge_attrs="weight")
263
+ def min_weight_matching(G, weight="weight"):
264
+ """Computing a minimum-weight maximal matching of G.
265
+
266
+ Use the maximum-weight algorithm with edge weights subtracted
267
+ from the maximum weight of all edges.
268
+
269
+ A matching is a subset of edges in which no node occurs more than once.
270
+ The weight of a matching is the sum of the weights of its edges.
271
+ A maximal matching cannot add more edges and still be a matching.
272
+ The cardinality of a matching is the number of matched edges.
273
+
274
+ This method replaces the edge weights with 1 plus the maximum edge weight
275
+ minus the original edge weight.
276
+
277
+ new_weight = (max_weight + 1) - edge_weight
278
+
279
+ then runs :func:`max_weight_matching` with the new weights.
280
+ The max weight matching with these new weights corresponds
281
+ to the min weight matching using the original weights.
282
+ Adding 1 to the max edge weight keeps all edge weights positive
283
+ and as integers if they started as integers.
284
+
285
+ You might worry that adding 1 to each weight would make the algorithm
286
+ favor matchings with more edges. But we use the parameter
287
+ `maxcardinality=True` in `max_weight_matching` to ensure that the
288
+ number of edges in the competing matchings are the same and thus
289
+ the optimum does not change due to changes in the number of edges.
290
+
291
+ Read the documentation of `max_weight_matching` for more information.
292
+
293
+ Parameters
294
+ ----------
295
+ G : NetworkX graph
296
+ Undirected graph
297
+
298
+ weight: string, optional (default='weight')
299
+ Edge data key corresponding to the edge weight.
300
+ If key not found, uses 1 as weight.
301
+
302
+ Returns
303
+ -------
304
+ matching : set
305
+ A minimal weight matching of the graph.
306
+
307
+ See Also
308
+ --------
309
+ max_weight_matching
310
+ """
311
+ if len(G.edges) == 0:
312
+ return max_weight_matching(G, maxcardinality=True, weight=weight)
313
+ G_edges = G.edges(data=weight, default=1)
314
+ max_weight = 1 + max(w for _, _, w in G_edges)
315
+ InvG = nx.Graph()
316
+ edges = ((u, v, max_weight - w) for u, v, w in G_edges)
317
+ InvG.add_weighted_edges_from(edges, weight=weight)
318
+ return max_weight_matching(InvG, maxcardinality=True, weight=weight)
319
+
320
+
321
+ @not_implemented_for("multigraph")
322
+ @not_implemented_for("directed")
323
+ @nx._dispatchable(edge_attrs="weight")
324
+ def max_weight_matching(G, maxcardinality=False, weight="weight"):
325
+ """Compute a maximum-weighted matching of G.
326
+
327
+ A matching is a subset of edges in which no node occurs more than once.
328
+ The weight of a matching is the sum of the weights of its edges.
329
+ A maximal matching cannot add more edges and still be a matching.
330
+ The cardinality of a matching is the number of matched edges.
331
+
332
+ Parameters
333
+ ----------
334
+ G : NetworkX graph
335
+ Undirected graph
336
+
337
+ maxcardinality: bool, optional (default=False)
338
+ If maxcardinality is True, compute the maximum-cardinality matching
339
+ with maximum weight among all maximum-cardinality matchings.
340
+
341
+ weight: string, optional (default='weight')
342
+ Edge data key corresponding to the edge weight.
343
+ If key not found, uses 1 as weight.
344
+
345
+
346
+ Returns
347
+ -------
348
+ matching : set
349
+ A maximal matching of the graph.
350
+
351
+ Examples
352
+ --------
353
+ >>> G = nx.Graph()
354
+ >>> edges = [(1, 2, 6), (1, 3, 2), (2, 3, 1), (2, 4, 7), (3, 5, 9), (4, 5, 3)]
355
+ >>> G.add_weighted_edges_from(edges)
356
+ >>> sorted(nx.max_weight_matching(G))
357
+ [(2, 4), (5, 3)]
358
+
359
+ Notes
360
+ -----
361
+ If G has edges with weight attributes the edge data are used as
362
+ weight values else the weights are assumed to be 1.
363
+
364
+ This function takes time O(number_of_nodes ** 3).
365
+
366
+ If all edge weights are integers, the algorithm uses only integer
367
+ computations. If floating point weights are used, the algorithm
368
+ could return a slightly suboptimal matching due to numeric
369
+ precision errors.
370
+
371
+ This method is based on the "blossom" method for finding augmenting
372
+ paths and the "primal-dual" method for finding a matching of maximum
373
+ weight, both methods invented by Jack Edmonds [1]_.
374
+
375
+ Bipartite graphs can also be matched using the functions present in
376
+ :mod:`networkx.algorithms.bipartite.matching`.
377
+
378
+ References
379
+ ----------
380
+ .. [1] "Efficient Algorithms for Finding Maximum Matching in Graphs",
381
+ Zvi Galil, ACM Computing Surveys, 1986.
382
+ """
383
+ #
384
+ # The algorithm is taken from "Efficient Algorithms for Finding Maximum
385
+ # Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
386
+ # It is based on the "blossom" method for finding augmenting paths and
387
+ # the "primal-dual" method for finding a matching of maximum weight, both
388
+ # methods invented by Jack Edmonds.
389
+ #
390
+ # A C program for maximum weight matching by Ed Rothberg was used
391
+ # extensively to validate this new code.
392
+ #
393
+ # Many terms used in the code comments are explained in the paper
394
+ # by Galil. You will probably need the paper to make sense of this code.
395
+ #
396
+
397
+ class NoNode:
398
+ """Dummy value which is different from any node."""
399
+
400
+ class Blossom:
401
+ """Representation of a non-trivial blossom or sub-blossom."""
402
+
403
+ __slots__ = ["childs", "edges", "mybestedges"]
404
+
405
+ # b.childs is an ordered list of b's sub-blossoms, starting with
406
+ # the base and going round the blossom.
407
+
408
+ # b.edges is the list of b's connecting edges, such that
409
+ # b.edges[i] = (v, w) where v is a vertex in b.childs[i]
410
+ # and w is a vertex in b.childs[wrap(i+1)].
411
+
412
+ # If b is a top-level S-blossom,
413
+ # b.mybestedges is a list of least-slack edges to neighboring
414
+ # S-blossoms, or None if no such list has been computed yet.
415
+ # This is used for efficient computation of delta3.
416
+
417
+ # Generate the blossom's leaf vertices.
418
+ def leaves(self):
419
+ stack = [*self.childs]
420
+ while stack:
421
+ t = stack.pop()
422
+ if isinstance(t, Blossom):
423
+ stack.extend(t.childs)
424
+ else:
425
+ yield t
426
+
427
+ # Get a list of vertices.
428
+ gnodes = list(G)
429
+ if not gnodes:
430
+ return set() # don't bother with empty graphs
431
+
432
+ # Find the maximum edge weight.
433
+ maxweight = 0
434
+ allinteger = True
435
+ for i, j, d in G.edges(data=True):
436
+ wt = d.get(weight, 1)
437
+ if i != j and wt > maxweight:
438
+ maxweight = wt
439
+ allinteger = allinteger and (str(type(wt)).split("'")[1] in ("int", "long"))
440
+
441
+ # If v is a matched vertex, mate[v] is its partner vertex.
442
+ # If v is a single vertex, v does not occur as a key in mate.
443
+ # Initially all vertices are single; updated during augmentation.
444
+ mate = {}
445
+
446
+ # If b is a top-level blossom,
447
+ # label.get(b) is None if b is unlabeled (free),
448
+ # 1 if b is an S-blossom,
449
+ # 2 if b is a T-blossom.
450
+ # The label of a vertex is found by looking at the label of its top-level
451
+ # containing blossom.
452
+ # If v is a vertex inside a T-blossom, label[v] is 2 iff v is reachable
453
+ # from an S-vertex outside the blossom.
454
+ # Labels are assigned during a stage and reset after each augmentation.
455
+ label = {}
456
+
457
+ # If b is a labeled top-level blossom,
458
+ # labeledge[b] = (v, w) is the edge through which b obtained its label
459
+ # such that w is a vertex in b, or None if b's base vertex is single.
460
+ # If w is a vertex inside a T-blossom and label[w] == 2,
461
+ # labeledge[w] = (v, w) is an edge through which w is reachable from
462
+ # outside the blossom.
463
+ labeledge = {}
464
+
465
+ # If v is a vertex, inblossom[v] is the top-level blossom to which v
466
+ # belongs.
467
+ # If v is a top-level vertex, inblossom[v] == v since v is itself
468
+ # a (trivial) top-level blossom.
469
+ # Initially all vertices are top-level trivial blossoms.
470
+ inblossom = dict(zip(gnodes, gnodes))
471
+
472
+ # If b is a sub-blossom,
473
+ # blossomparent[b] is its immediate parent (sub-)blossom.
474
+ # If b is a top-level blossom, blossomparent[b] is None.
475
+ blossomparent = dict(zip(gnodes, repeat(None)))
476
+
477
+ # If b is a (sub-)blossom,
478
+ # blossombase[b] is its base VERTEX (i.e. recursive sub-blossom).
479
+ blossombase = dict(zip(gnodes, gnodes))
480
+
481
+ # If w is a free vertex (or an unreached vertex inside a T-blossom),
482
+ # bestedge[w] = (v, w) is the least-slack edge from an S-vertex,
483
+ # or None if there is no such edge.
484
+ # If b is a (possibly trivial) top-level S-blossom,
485
+ # bestedge[b] = (v, w) is the least-slack edge to a different S-blossom
486
+ # (v inside b), or None if there is no such edge.
487
+ # This is used for efficient computation of delta2 and delta3.
488
+ bestedge = {}
489
+
490
+ # If v is a vertex,
491
+ # dualvar[v] = 2 * u(v) where u(v) is the v's variable in the dual
492
+ # optimization problem (if all edge weights are integers, multiplication
493
+ # by two ensures that all values remain integers throughout the algorithm).
494
+ # Initially, u(v) = maxweight / 2.
495
+ dualvar = dict(zip(gnodes, repeat(maxweight)))
496
+
497
+ # If b is a non-trivial blossom,
498
+ # blossomdual[b] = z(b) where z(b) is b's variable in the dual
499
+ # optimization problem.
500
+ blossomdual = {}
501
+
502
+ # If (v, w) in allowedge or (w, v) in allowedg, then the edge
503
+ # (v, w) is known to have zero slack in the optimization problem;
504
+ # otherwise the edge may or may not have zero slack.
505
+ allowedge = {}
506
+
507
+ # Queue of newly discovered S-vertices.
508
+ queue = []
509
+
510
+ # Return 2 * slack of edge (v, w) (does not work inside blossoms).
511
+ def slack(v, w):
512
+ return dualvar[v] + dualvar[w] - 2 * G[v][w].get(weight, 1)
513
+
514
+ # Assign label t to the top-level blossom containing vertex w,
515
+ # coming through an edge from vertex v.
516
+ def assignLabel(w, t, v):
517
+ b = inblossom[w]
518
+ assert label.get(w) is None and label.get(b) is None
519
+ label[w] = label[b] = t
520
+ if v is not None:
521
+ labeledge[w] = labeledge[b] = (v, w)
522
+ else:
523
+ labeledge[w] = labeledge[b] = None
524
+ bestedge[w] = bestedge[b] = None
525
+ if t == 1:
526
+ # b became an S-vertex/blossom; add it(s vertices) to the queue.
527
+ if isinstance(b, Blossom):
528
+ queue.extend(b.leaves())
529
+ else:
530
+ queue.append(b)
531
+ elif t == 2:
532
+ # b became a T-vertex/blossom; assign label S to its mate.
533
+ # (If b is a non-trivial blossom, its base is the only vertex
534
+ # with an external mate.)
535
+ base = blossombase[b]
536
+ assignLabel(mate[base], 1, base)
537
+
538
+ # Trace back from vertices v and w to discover either a new blossom
539
+ # or an augmenting path. Return the base vertex of the new blossom,
540
+ # or NoNode if an augmenting path was found.
541
+ def scanBlossom(v, w):
542
+ # Trace back from v and w, placing breadcrumbs as we go.
543
+ path = []
544
+ base = NoNode
545
+ while v is not NoNode:
546
+ # Look for a breadcrumb in v's blossom or put a new breadcrumb.
547
+ b = inblossom[v]
548
+ if label[b] & 4:
549
+ base = blossombase[b]
550
+ break
551
+ assert label[b] == 1
552
+ path.append(b)
553
+ label[b] = 5
554
+ # Trace one step back.
555
+ if labeledge[b] is None:
556
+ # The base of blossom b is single; stop tracing this path.
557
+ assert blossombase[b] not in mate
558
+ v = NoNode
559
+ else:
560
+ assert labeledge[b][0] == mate[blossombase[b]]
561
+ v = labeledge[b][0]
562
+ b = inblossom[v]
563
+ assert label[b] == 2
564
+ # b is a T-blossom; trace one more step back.
565
+ v = labeledge[b][0]
566
+ # Swap v and w so that we alternate between both paths.
567
+ if w is not NoNode:
568
+ v, w = w, v
569
+ # Remove breadcrumbs.
570
+ for b in path:
571
+ label[b] = 1
572
+ # Return base vertex, if we found one.
573
+ return base
574
+
575
+ # Construct a new blossom with given base, through S-vertices v and w.
576
+ # Label the new blossom as S; set its dual variable to zero;
577
+ # relabel its T-vertices to S and add them to the queue.
578
+ def addBlossom(base, v, w):
579
+ bb = inblossom[base]
580
+ bv = inblossom[v]
581
+ bw = inblossom[w]
582
+ # Create blossom.
583
+ b = Blossom()
584
+ blossombase[b] = base
585
+ blossomparent[b] = None
586
+ blossomparent[bb] = b
587
+ # Make list of sub-blossoms and their interconnecting edge endpoints.
588
+ b.childs = path = []
589
+ b.edges = edgs = [(v, w)]
590
+ # Trace back from v to base.
591
+ while bv != bb:
592
+ # Add bv to the new blossom.
593
+ blossomparent[bv] = b
594
+ path.append(bv)
595
+ edgs.append(labeledge[bv])
596
+ assert label[bv] == 2 or (
597
+ label[bv] == 1 and labeledge[bv][0] == mate[blossombase[bv]]
598
+ )
599
+ # Trace one step back.
600
+ v = labeledge[bv][0]
601
+ bv = inblossom[v]
602
+ # Add base sub-blossom; reverse lists.
603
+ path.append(bb)
604
+ path.reverse()
605
+ edgs.reverse()
606
+ # Trace back from w to base.
607
+ while bw != bb:
608
+ # Add bw to the new blossom.
609
+ blossomparent[bw] = b
610
+ path.append(bw)
611
+ edgs.append((labeledge[bw][1], labeledge[bw][0]))
612
+ assert label[bw] == 2 or (
613
+ label[bw] == 1 and labeledge[bw][0] == mate[blossombase[bw]]
614
+ )
615
+ # Trace one step back.
616
+ w = labeledge[bw][0]
617
+ bw = inblossom[w]
618
+ # Set label to S.
619
+ assert label[bb] == 1
620
+ label[b] = 1
621
+ labeledge[b] = labeledge[bb]
622
+ # Set dual variable to zero.
623
+ blossomdual[b] = 0
624
+ # Relabel vertices.
625
+ for v in b.leaves():
626
+ if label[inblossom[v]] == 2:
627
+ # This T-vertex now turns into an S-vertex because it becomes
628
+ # part of an S-blossom; add it to the queue.
629
+ queue.append(v)
630
+ inblossom[v] = b
631
+ # Compute b.mybestedges.
632
+ bestedgeto = {}
633
+ for bv in path:
634
+ if isinstance(bv, Blossom):
635
+ if bv.mybestedges is not None:
636
+ # Walk this subblossom's least-slack edges.
637
+ nblist = bv.mybestedges
638
+ # The sub-blossom won't need this data again.
639
+ bv.mybestedges = None
640
+ else:
641
+ # This subblossom does not have a list of least-slack
642
+ # edges; get the information from the vertices.
643
+ nblist = [
644
+ (v, w) for v in bv.leaves() for w in G.neighbors(v) if v != w
645
+ ]
646
+ else:
647
+ nblist = [(bv, w) for w in G.neighbors(bv) if bv != w]
648
+ for k in nblist:
649
+ (i, j) = k
650
+ if inblossom[j] == b:
651
+ i, j = j, i
652
+ bj = inblossom[j]
653
+ if (
654
+ bj != b
655
+ and label.get(bj) == 1
656
+ and ((bj not in bestedgeto) or slack(i, j) < slack(*bestedgeto[bj]))
657
+ ):
658
+ bestedgeto[bj] = k
659
+ # Forget about least-slack edge of the subblossom.
660
+ bestedge[bv] = None
661
+ b.mybestedges = list(bestedgeto.values())
662
+ # Select bestedge[b].
663
+ mybestedge = None
664
+ bestedge[b] = None
665
+ for k in b.mybestedges:
666
+ kslack = slack(*k)
667
+ if mybestedge is None or kslack < mybestslack:
668
+ mybestedge = k
669
+ mybestslack = kslack
670
+ bestedge[b] = mybestedge
671
+
672
+ # Expand the given top-level blossom.
673
+ def expandBlossom(b, endstage):
674
+ # This is an obnoxiously complicated recursive function for the sake of
675
+ # a stack-transformation. So, we hack around the complexity by using
676
+ # a trampoline pattern. By yielding the arguments to each recursive
677
+ # call, we keep the actual callstack flat.
678
+
679
+ def _recurse(b, endstage):
680
+ # Convert sub-blossoms into top-level blossoms.
681
+ for s in b.childs:
682
+ blossomparent[s] = None
683
+ if isinstance(s, Blossom):
684
+ if endstage and blossomdual[s] == 0:
685
+ # Recursively expand this sub-blossom.
686
+ yield s
687
+ else:
688
+ for v in s.leaves():
689
+ inblossom[v] = s
690
+ else:
691
+ inblossom[s] = s
692
+ # If we expand a T-blossom during a stage, its sub-blossoms must be
693
+ # relabeled.
694
+ if (not endstage) and label.get(b) == 2:
695
+ # Start at the sub-blossom through which the expanding
696
+ # blossom obtained its label, and relabel sub-blossoms untili
697
+ # we reach the base.
698
+ # Figure out through which sub-blossom the expanding blossom
699
+ # obtained its label initially.
700
+ entrychild = inblossom[labeledge[b][1]]
701
+ # Decide in which direction we will go round the blossom.
702
+ j = b.childs.index(entrychild)
703
+ if j & 1:
704
+ # Start index is odd; go forward and wrap.
705
+ j -= len(b.childs)
706
+ jstep = 1
707
+ else:
708
+ # Start index is even; go backward.
709
+ jstep = -1
710
+ # Move along the blossom until we get to the base.
711
+ v, w = labeledge[b]
712
+ while j != 0:
713
+ # Relabel the T-sub-blossom.
714
+ if jstep == 1:
715
+ p, q = b.edges[j]
716
+ else:
717
+ q, p = b.edges[j - 1]
718
+ label[w] = None
719
+ label[q] = None
720
+ assignLabel(w, 2, v)
721
+ # Step to the next S-sub-blossom and note its forward edge.
722
+ allowedge[(p, q)] = allowedge[(q, p)] = True
723
+ j += jstep
724
+ if jstep == 1:
725
+ v, w = b.edges[j]
726
+ else:
727
+ w, v = b.edges[j - 1]
728
+ # Step to the next T-sub-blossom.
729
+ allowedge[(v, w)] = allowedge[(w, v)] = True
730
+ j += jstep
731
+ # Relabel the base T-sub-blossom WITHOUT stepping through to
732
+ # its mate (so don't call assignLabel).
733
+ bw = b.childs[j]
734
+ label[w] = label[bw] = 2
735
+ labeledge[w] = labeledge[bw] = (v, w)
736
+ bestedge[bw] = None
737
+ # Continue along the blossom until we get back to entrychild.
738
+ j += jstep
739
+ while b.childs[j] != entrychild:
740
+ # Examine the vertices of the sub-blossom to see whether
741
+ # it is reachable from a neighboring S-vertex outside the
742
+ # expanding blossom.
743
+ bv = b.childs[j]
744
+ if label.get(bv) == 1:
745
+ # This sub-blossom just got label S through one of its
746
+ # neighbors; leave it be.
747
+ j += jstep
748
+ continue
749
+ if isinstance(bv, Blossom):
750
+ for v in bv.leaves():
751
+ if label.get(v):
752
+ break
753
+ else:
754
+ v = bv
755
+ # If the sub-blossom contains a reachable vertex, assign
756
+ # label T to the sub-blossom.
757
+ if label.get(v):
758
+ assert label[v] == 2
759
+ assert inblossom[v] == bv
760
+ label[v] = None
761
+ label[mate[blossombase[bv]]] = None
762
+ assignLabel(v, 2, labeledge[v][0])
763
+ j += jstep
764
+ # Remove the expanded blossom entirely.
765
+ label.pop(b, None)
766
+ labeledge.pop(b, None)
767
+ bestedge.pop(b, None)
768
+ del blossomparent[b]
769
+ del blossombase[b]
770
+ del blossomdual[b]
771
+
772
+ # Now, we apply the trampoline pattern. We simulate a recursive
773
+ # callstack by maintaining a stack of generators, each yielding a
774
+ # sequence of function arguments. We grow the stack by appending a call
775
+ # to _recurse on each argument tuple, and shrink the stack whenever a
776
+ # generator is exhausted.
777
+ stack = [_recurse(b, endstage)]
778
+ while stack:
779
+ top = stack[-1]
780
+ for s in top:
781
+ stack.append(_recurse(s, endstage))
782
+ break
783
+ else:
784
+ stack.pop()
785
+
786
+ # Swap matched/unmatched edges over an alternating path through blossom b
787
+ # between vertex v and the base vertex. Keep blossom bookkeeping
788
+ # consistent.
789
+ def augmentBlossom(b, v):
790
+ # This is an obnoxiously complicated recursive function for the sake of
791
+ # a stack-transformation. So, we hack around the complexity by using
792
+ # a trampoline pattern. By yielding the arguments to each recursive
793
+ # call, we keep the actual callstack flat.
794
+
795
+ def _recurse(b, v):
796
+ # Bubble up through the blossom tree from vertex v to an immediate
797
+ # sub-blossom of b.
798
+ t = v
799
+ while blossomparent[t] != b:
800
+ t = blossomparent[t]
801
+ # Recursively deal with the first sub-blossom.
802
+ if isinstance(t, Blossom):
803
+ yield (t, v)
804
+ # Decide in which direction we will go round the blossom.
805
+ i = j = b.childs.index(t)
806
+ if i & 1:
807
+ # Start index is odd; go forward and wrap.
808
+ j -= len(b.childs)
809
+ jstep = 1
810
+ else:
811
+ # Start index is even; go backward.
812
+ jstep = -1
813
+ # Move along the blossom until we get to the base.
814
+ while j != 0:
815
+ # Step to the next sub-blossom and augment it recursively.
816
+ j += jstep
817
+ t = b.childs[j]
818
+ if jstep == 1:
819
+ w, x = b.edges[j]
820
+ else:
821
+ x, w = b.edges[j - 1]
822
+ if isinstance(t, Blossom):
823
+ yield (t, w)
824
+ # Step to the next sub-blossom and augment it recursively.
825
+ j += jstep
826
+ t = b.childs[j]
827
+ if isinstance(t, Blossom):
828
+ yield (t, x)
829
+ # Match the edge connecting those sub-blossoms.
830
+ mate[w] = x
831
+ mate[x] = w
832
+ # Rotate the list of sub-blossoms to put the new base at the front.
833
+ b.childs = b.childs[i:] + b.childs[:i]
834
+ b.edges = b.edges[i:] + b.edges[:i]
835
+ blossombase[b] = blossombase[b.childs[0]]
836
+ assert blossombase[b] == v
837
+
838
+ # Now, we apply the trampoline pattern. We simulate a recursive
839
+ # callstack by maintaining a stack of generators, each yielding a
840
+ # sequence of function arguments. We grow the stack by appending a call
841
+ # to _recurse on each argument tuple, and shrink the stack whenever a
842
+ # generator is exhausted.
843
+ stack = [_recurse(b, v)]
844
+ while stack:
845
+ top = stack[-1]
846
+ for args in top:
847
+ stack.append(_recurse(*args))
848
+ break
849
+ else:
850
+ stack.pop()
851
+
852
+ # Swap matched/unmatched edges over an alternating path between two
853
+ # single vertices. The augmenting path runs through S-vertices v and w.
854
+ def augmentMatching(v, w):
855
+ for s, j in ((v, w), (w, v)):
856
+ # Match vertex s to vertex j. Then trace back from s
857
+ # until we find a single vertex, swapping matched and unmatched
858
+ # edges as we go.
859
+ while 1:
860
+ bs = inblossom[s]
861
+ assert label[bs] == 1
862
+ assert (labeledge[bs] is None and blossombase[bs] not in mate) or (
863
+ labeledge[bs][0] == mate[blossombase[bs]]
864
+ )
865
+ # Augment through the S-blossom from s to base.
866
+ if isinstance(bs, Blossom):
867
+ augmentBlossom(bs, s)
868
+ # Update mate[s]
869
+ mate[s] = j
870
+ # Trace one step back.
871
+ if labeledge[bs] is None:
872
+ # Reached single vertex; stop.
873
+ break
874
+ t = labeledge[bs][0]
875
+ bt = inblossom[t]
876
+ assert label[bt] == 2
877
+ # Trace one more step back.
878
+ s, j = labeledge[bt]
879
+ # Augment through the T-blossom from j to base.
880
+ assert blossombase[bt] == t
881
+ if isinstance(bt, Blossom):
882
+ augmentBlossom(bt, j)
883
+ # Update mate[j]
884
+ mate[j] = s
885
+
886
+ # Verify that the optimum solution has been reached.
887
+ def verifyOptimum():
888
+ if maxcardinality:
889
+ # Vertices may have negative dual;
890
+ # find a constant non-negative number to add to all vertex duals.
891
+ vdualoffset = max(0, -min(dualvar.values()))
892
+ else:
893
+ vdualoffset = 0
894
+ # 0. all dual variables are non-negative
895
+ assert min(dualvar.values()) + vdualoffset >= 0
896
+ assert len(blossomdual) == 0 or min(blossomdual.values()) >= 0
897
+ # 0. all edges have non-negative slack and
898
+ # 1. all matched edges have zero slack;
899
+ for i, j, d in G.edges(data=True):
900
+ wt = d.get(weight, 1)
901
+ if i == j:
902
+ continue # ignore self-loops
903
+ s = dualvar[i] + dualvar[j] - 2 * wt
904
+ iblossoms = [i]
905
+ jblossoms = [j]
906
+ while blossomparent[iblossoms[-1]] is not None:
907
+ iblossoms.append(blossomparent[iblossoms[-1]])
908
+ while blossomparent[jblossoms[-1]] is not None:
909
+ jblossoms.append(blossomparent[jblossoms[-1]])
910
+ iblossoms.reverse()
911
+ jblossoms.reverse()
912
+ for bi, bj in zip(iblossoms, jblossoms):
913
+ if bi != bj:
914
+ break
915
+ s += 2 * blossomdual[bi]
916
+ assert s >= 0
917
+ if mate.get(i) == j or mate.get(j) == i:
918
+ assert mate[i] == j and mate[j] == i
919
+ assert s == 0
920
+ # 2. all single vertices have zero dual value;
921
+ for v in gnodes:
922
+ assert (v in mate) or dualvar[v] + vdualoffset == 0
923
+ # 3. all blossoms with positive dual value are full.
924
+ for b in blossomdual:
925
+ if blossomdual[b] > 0:
926
+ assert len(b.edges) % 2 == 1
927
+ for i, j in b.edges[1::2]:
928
+ assert mate[i] == j and mate[j] == i
929
+ # Ok.
930
+
931
+ # Main loop: continue until no further improvement is possible.
932
+ while 1:
933
+ # Each iteration of this loop is a "stage".
934
+ # A stage finds an augmenting path and uses that to improve
935
+ # the matching.
936
+
937
+ # Remove labels from top-level blossoms/vertices.
938
+ label.clear()
939
+ labeledge.clear()
940
+
941
+ # Forget all about least-slack edges.
942
+ bestedge.clear()
943
+ for b in blossomdual:
944
+ b.mybestedges = None
945
+
946
+ # Loss of labeling means that we can not be sure that currently
947
+ # allowable edges remain allowable throughout this stage.
948
+ allowedge.clear()
949
+
950
+ # Make queue empty.
951
+ queue[:] = []
952
+
953
+ # Label single blossoms/vertices with S and put them in the queue.
954
+ for v in gnodes:
955
+ if (v not in mate) and label.get(inblossom[v]) is None:
956
+ assignLabel(v, 1, None)
957
+
958
+ # Loop until we succeed in augmenting the matching.
959
+ augmented = 0
960
+ while 1:
961
+ # Each iteration of this loop is a "substage".
962
+ # A substage tries to find an augmenting path;
963
+ # if found, the path is used to improve the matching and
964
+ # the stage ends. If there is no augmenting path, the
965
+ # primal-dual method is used to pump some slack out of
966
+ # the dual variables.
967
+
968
+ # Continue labeling until all vertices which are reachable
969
+ # through an alternating path have got a label.
970
+ while queue and not augmented:
971
+ # Take an S vertex from the queue.
972
+ v = queue.pop()
973
+ assert label[inblossom[v]] == 1
974
+
975
+ # Scan its neighbors:
976
+ for w in G.neighbors(v):
977
+ if w == v:
978
+ continue # ignore self-loops
979
+ # w is a neighbor to v
980
+ bv = inblossom[v]
981
+ bw = inblossom[w]
982
+ if bv == bw:
983
+ # this edge is internal to a blossom; ignore it
984
+ continue
985
+ if (v, w) not in allowedge:
986
+ kslack = slack(v, w)
987
+ if kslack <= 0:
988
+ # edge k has zero slack => it is allowable
989
+ allowedge[(v, w)] = allowedge[(w, v)] = True
990
+ if (v, w) in allowedge:
991
+ if label.get(bw) is None:
992
+ # (C1) w is a free vertex;
993
+ # label w with T and label its mate with S (R12).
994
+ assignLabel(w, 2, v)
995
+ elif label.get(bw) == 1:
996
+ # (C2) w is an S-vertex (not in the same blossom);
997
+ # follow back-links to discover either an
998
+ # augmenting path or a new blossom.
999
+ base = scanBlossom(v, w)
1000
+ if base is not NoNode:
1001
+ # Found a new blossom; add it to the blossom
1002
+ # bookkeeping and turn it into an S-blossom.
1003
+ addBlossom(base, v, w)
1004
+ else:
1005
+ # Found an augmenting path; augment the
1006
+ # matching and end this stage.
1007
+ augmentMatching(v, w)
1008
+ augmented = 1
1009
+ break
1010
+ elif label.get(w) is None:
1011
+ # w is inside a T-blossom, but w itself has not
1012
+ # yet been reached from outside the blossom;
1013
+ # mark it as reached (we need this to relabel
1014
+ # during T-blossom expansion).
1015
+ assert label[bw] == 2
1016
+ label[w] = 2
1017
+ labeledge[w] = (v, w)
1018
+ elif label.get(bw) == 1:
1019
+ # keep track of the least-slack non-allowable edge to
1020
+ # a different S-blossom.
1021
+ if bestedge.get(bv) is None or kslack < slack(*bestedge[bv]):
1022
+ bestedge[bv] = (v, w)
1023
+ elif label.get(w) is None:
1024
+ # w is a free vertex (or an unreached vertex inside
1025
+ # a T-blossom) but we can not reach it yet;
1026
+ # keep track of the least-slack edge that reaches w.
1027
+ if bestedge.get(w) is None or kslack < slack(*bestedge[w]):
1028
+ bestedge[w] = (v, w)
1029
+
1030
+ if augmented:
1031
+ break
1032
+
1033
+ # There is no augmenting path under these constraints;
1034
+ # compute delta and reduce slack in the optimization problem.
1035
+ # (Note that our vertex dual variables, edge slacks and delta's
1036
+ # are pre-multiplied by two.)
1037
+ deltatype = -1
1038
+ delta = deltaedge = deltablossom = None
1039
+
1040
+ # Compute delta1: the minimum value of any vertex dual.
1041
+ if not maxcardinality:
1042
+ deltatype = 1
1043
+ delta = min(dualvar.values())
1044
+
1045
+ # Compute delta2: the minimum slack on any edge between
1046
+ # an S-vertex and a free vertex.
1047
+ for v in G.nodes():
1048
+ if label.get(inblossom[v]) is None and bestedge.get(v) is not None:
1049
+ d = slack(*bestedge[v])
1050
+ if deltatype == -1 or d < delta:
1051
+ delta = d
1052
+ deltatype = 2
1053
+ deltaedge = bestedge[v]
1054
+
1055
+ # Compute delta3: half the minimum slack on any edge between
1056
+ # a pair of S-blossoms.
1057
+ for b in blossomparent:
1058
+ if (
1059
+ blossomparent[b] is None
1060
+ and label.get(b) == 1
1061
+ and bestedge.get(b) is not None
1062
+ ):
1063
+ kslack = slack(*bestedge[b])
1064
+ if allinteger:
1065
+ assert (kslack % 2) == 0
1066
+ d = kslack // 2
1067
+ else:
1068
+ d = kslack / 2.0
1069
+ if deltatype == -1 or d < delta:
1070
+ delta = d
1071
+ deltatype = 3
1072
+ deltaedge = bestedge[b]
1073
+
1074
+ # Compute delta4: minimum z variable of any T-blossom.
1075
+ for b in blossomdual:
1076
+ if (
1077
+ blossomparent[b] is None
1078
+ and label.get(b) == 2
1079
+ and (deltatype == -1 or blossomdual[b] < delta)
1080
+ ):
1081
+ delta = blossomdual[b]
1082
+ deltatype = 4
1083
+ deltablossom = b
1084
+
1085
+ if deltatype == -1:
1086
+ # No further improvement possible; max-cardinality optimum
1087
+ # reached. Do a final delta update to make the optimum
1088
+ # verifiable.
1089
+ assert maxcardinality
1090
+ deltatype = 1
1091
+ delta = max(0, min(dualvar.values()))
1092
+
1093
+ # Update dual variables according to delta.
1094
+ for v in gnodes:
1095
+ if label.get(inblossom[v]) == 1:
1096
+ # S-vertex: 2*u = 2*u - 2*delta
1097
+ dualvar[v] -= delta
1098
+ elif label.get(inblossom[v]) == 2:
1099
+ # T-vertex: 2*u = 2*u + 2*delta
1100
+ dualvar[v] += delta
1101
+ for b in blossomdual:
1102
+ if blossomparent[b] is None:
1103
+ if label.get(b) == 1:
1104
+ # top-level S-blossom: z = z + 2*delta
1105
+ blossomdual[b] += delta
1106
+ elif label.get(b) == 2:
1107
+ # top-level T-blossom: z = z - 2*delta
1108
+ blossomdual[b] -= delta
1109
+
1110
+ # Take action at the point where minimum delta occurred.
1111
+ if deltatype == 1:
1112
+ # No further improvement possible; optimum reached.
1113
+ break
1114
+ elif deltatype == 2:
1115
+ # Use the least-slack edge to continue the search.
1116
+ (v, w) = deltaedge
1117
+ assert label[inblossom[v]] == 1
1118
+ allowedge[(v, w)] = allowedge[(w, v)] = True
1119
+ queue.append(v)
1120
+ elif deltatype == 3:
1121
+ # Use the least-slack edge to continue the search.
1122
+ (v, w) = deltaedge
1123
+ allowedge[(v, w)] = allowedge[(w, v)] = True
1124
+ assert label[inblossom[v]] == 1
1125
+ queue.append(v)
1126
+ elif deltatype == 4:
1127
+ # Expand the least-z blossom.
1128
+ expandBlossom(deltablossom, False)
1129
+
1130
+ # End of a this substage.
1131
+
1132
+ # Paranoia check that the matching is symmetric.
1133
+ for v in mate:
1134
+ assert mate[mate[v]] == v
1135
+
1136
+ # Stop when no more augmenting path can be found.
1137
+ if not augmented:
1138
+ break
1139
+
1140
+ # End of a stage; expand all S-blossoms which have zero dual.
1141
+ for b in list(blossomdual.keys()):
1142
+ if b not in blossomdual:
1143
+ continue # already expanded
1144
+ if blossomparent[b] is None and label.get(b) == 1 and blossomdual[b] == 0:
1145
+ expandBlossom(b, True)
1146
+
1147
+ # Verify that we reached the optimum solution (only for integer weights).
1148
+ if allinteger:
1149
+ verifyOptimum()
1150
+
1151
+ return matching_dict_to_set(mate)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/mis.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Algorithm to find a maximal (not maximum) independent set.
3
+
4
+ """
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for, py_random_state
7
+
8
+ __all__ = ["maximal_independent_set"]
9
+
10
+
11
+ @not_implemented_for("directed")
12
+ @py_random_state(2)
13
+ @nx._dispatchable
14
+ def maximal_independent_set(G, nodes=None, seed=None):
15
+ """Returns a random maximal independent set guaranteed to contain
16
+ a given set of nodes.
17
+
18
+ An independent set is a set of nodes such that the subgraph
19
+ of G induced by these nodes contains no edges. A maximal
20
+ independent set is an independent set such that it is not possible
21
+ to add a new node and still get an independent set.
22
+
23
+ Parameters
24
+ ----------
25
+ G : NetworkX graph
26
+
27
+ nodes : list or iterable
28
+ Nodes that must be part of the independent set. This set of nodes
29
+ must be independent.
30
+
31
+ seed : integer, random_state, or None (default)
32
+ Indicator of random number generation state.
33
+ See :ref:`Randomness<randomness>`.
34
+
35
+ Returns
36
+ -------
37
+ indep_nodes : list
38
+ List of nodes that are part of a maximal independent set.
39
+
40
+ Raises
41
+ ------
42
+ NetworkXUnfeasible
43
+ If the nodes in the provided list are not part of the graph or
44
+ do not form an independent set, an exception is raised.
45
+
46
+ NetworkXNotImplemented
47
+ If `G` is directed.
48
+
49
+ Examples
50
+ --------
51
+ >>> G = nx.path_graph(5)
52
+ >>> nx.maximal_independent_set(G) # doctest: +SKIP
53
+ [4, 0, 2]
54
+ >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP
55
+ [1, 3]
56
+
57
+ Notes
58
+ -----
59
+ This algorithm does not solve the maximum independent set problem.
60
+
61
+ """
62
+ if not nodes:
63
+ nodes = {seed.choice(list(G))}
64
+ else:
65
+ nodes = set(nodes)
66
+ if not nodes.issubset(G):
67
+ raise nx.NetworkXUnfeasible(f"{nodes} is not a subset of the nodes of G")
68
+ neighbors = set.union(*[set(G.adj[v]) for v in nodes])
69
+ if set.intersection(neighbors, nodes):
70
+ raise nx.NetworkXUnfeasible(f"{nodes} is not an independent set of G")
71
+ indep_nodes = list(nodes)
72
+ available_nodes = set(G.nodes()).difference(neighbors.union(nodes))
73
+ while available_nodes:
74
+ node = seed.choice(list(available_nodes))
75
+ indep_nodes.append(node)
76
+ available_nodes.difference_update(list(G.adj[node]) + [node])
77
+ return indep_nodes
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/moral.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Function for computing the moral graph of a directed graph."""
2
+
3
+ import itertools
4
+
5
+ import networkx as nx
6
+ from networkx.utils import not_implemented_for
7
+
8
+ __all__ = ["moral_graph"]
9
+
10
+
11
+ @not_implemented_for("undirected")
12
+ @nx._dispatchable(returns_graph=True)
13
+ def moral_graph(G):
14
+ r"""Return the Moral Graph
15
+
16
+ Returns the moralized graph of a given directed graph.
17
+
18
+ Parameters
19
+ ----------
20
+ G : NetworkX graph
21
+ Directed graph
22
+
23
+ Returns
24
+ -------
25
+ H : NetworkX graph
26
+ The undirected moralized graph of G
27
+
28
+ Raises
29
+ ------
30
+ NetworkXNotImplemented
31
+ If `G` is undirected.
32
+
33
+ Examples
34
+ --------
35
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (2, 5), (3, 4), (4, 3)])
36
+ >>> G_moral = nx.moral_graph(G)
37
+ >>> G_moral.edges()
38
+ EdgeView([(1, 2), (2, 3), (2, 5), (2, 4), (3, 4)])
39
+
40
+ Notes
41
+ -----
42
+ A moral graph is an undirected graph H = (V, E) generated from a
43
+ directed Graph, where if a node has more than one parent node, edges
44
+ between these parent nodes are inserted and all directed edges become
45
+ undirected.
46
+
47
+ https://en.wikipedia.org/wiki/Moral_graph
48
+
49
+ References
50
+ ----------
51
+ .. [1] Wray L. Buntine. 1995. Chain graphs for learning.
52
+ In Proceedings of the Eleventh conference on Uncertainty
53
+ in artificial intelligence (UAI'95)
54
+ """
55
+ H = G.to_undirected()
56
+ for preds in G.pred.values():
57
+ predecessors_combinations = itertools.combinations(preds, r=2)
58
+ H.add_edges_from(predecessors_combinations)
59
+ return H
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/non_randomness.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r""" Computation of graph non-randomness
2
+ """
3
+
4
+ import math
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for
8
+
9
+ __all__ = ["non_randomness"]
10
+
11
+
12
+ @not_implemented_for("directed")
13
+ @not_implemented_for("multigraph")
14
+ @nx._dispatchable(edge_attrs="weight")
15
+ def non_randomness(G, k=None, weight="weight"):
16
+ """Compute the non-randomness of graph G.
17
+
18
+ The first returned value nr is the sum of non-randomness values of all
19
+ edges within the graph (where the non-randomness of an edge tends to be
20
+ small when the two nodes linked by that edge are from two different
21
+ communities).
22
+
23
+ The second computed value nr_rd is a relative measure that indicates
24
+ to what extent graph G is different from random graphs in terms
25
+ of probability. When it is close to 0, the graph tends to be more
26
+ likely generated by an Erdos Renyi model.
27
+
28
+ Parameters
29
+ ----------
30
+ G : NetworkX graph
31
+ Graph must be symmetric, connected, and without self-loops.
32
+
33
+ k : int
34
+ The number of communities in G.
35
+ If k is not set, the function will use a default community
36
+ detection algorithm to set it.
37
+
38
+ weight : string or None, optional (default=None)
39
+ The name of an edge attribute that holds the numerical value used
40
+ as a weight. If None, then each edge has weight 1, i.e., the graph is
41
+ binary.
42
+
43
+ Returns
44
+ -------
45
+ non-randomness : (float, float) tuple
46
+ Non-randomness, Relative non-randomness w.r.t.
47
+ Erdos Renyi random graphs.
48
+
49
+ Raises
50
+ ------
51
+ NetworkXException
52
+ if the input graph is not connected.
53
+ NetworkXError
54
+ if the input graph contains self-loops.
55
+
56
+ Examples
57
+ --------
58
+ >>> G = nx.karate_club_graph()
59
+ >>> nr, nr_rd = nx.non_randomness(G, 2)
60
+ >>> nr, nr_rd = nx.non_randomness(G, 2, "weight")
61
+
62
+ Notes
63
+ -----
64
+ This computes Eq. (4.4) and (4.5) in Ref. [1]_.
65
+
66
+ If a weight field is passed, this algorithm will use the eigenvalues
67
+ of the weighted adjacency matrix to compute Eq. (4.4) and (4.5).
68
+
69
+ References
70
+ ----------
71
+ .. [1] Xiaowei Ying and Xintao Wu,
72
+ On Randomness Measures for Social Networks,
73
+ SIAM International Conference on Data Mining. 2009
74
+ """
75
+ import numpy as np
76
+
77
+ if not nx.is_connected(G):
78
+ raise nx.NetworkXException("Non connected graph.")
79
+ if len(list(nx.selfloop_edges(G))) > 0:
80
+ raise nx.NetworkXError("Graph must not contain self-loops")
81
+
82
+ if k is None:
83
+ k = len(tuple(nx.community.label_propagation_communities(G)))
84
+
85
+ # eq. 4.4
86
+ eigenvalues = np.linalg.eigvals(nx.to_numpy_array(G, weight=weight))
87
+ nr = float(np.real(np.sum(eigenvalues[:k])))
88
+
89
+ n = G.number_of_nodes()
90
+ m = G.number_of_edges()
91
+ p = (2 * k * m) / (n * (n - k))
92
+
93
+ # eq. 4.5
94
+ nr_rd = (nr - ((n - 2 * k) * p + k)) / math.sqrt(2 * k * p * (1 - p))
95
+
96
+ return nr, nr_rd
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/planar_drawing.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["combinatorial_embedding_to_pos"]
6
+
7
+
8
+ def combinatorial_embedding_to_pos(embedding, fully_triangulate=False):
9
+ """Assigns every node a (x, y) position based on the given embedding
10
+
11
+ The algorithm iteratively inserts nodes of the input graph in a certain
12
+ order and rearranges previously inserted nodes so that the planar drawing
13
+ stays valid. This is done efficiently by only maintaining relative
14
+ positions during the node placements and calculating the absolute positions
15
+ at the end. For more information see [1]_.
16
+
17
+ Parameters
18
+ ----------
19
+ embedding : nx.PlanarEmbedding
20
+ This defines the order of the edges
21
+
22
+ fully_triangulate : bool
23
+ If set to True the algorithm adds edges to a copy of the input
24
+ embedding and makes it chordal.
25
+
26
+ Returns
27
+ -------
28
+ pos : dict
29
+ Maps each node to a tuple that defines the (x, y) position
30
+
31
+ References
32
+ ----------
33
+ .. [1] M. Chrobak and T.H. Payne:
34
+ A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989
35
+ http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677
36
+
37
+ """
38
+ if len(embedding.nodes()) < 4:
39
+ # Position the node in any triangle
40
+ default_positions = [(0, 0), (2, 0), (1, 1)]
41
+ pos = {}
42
+ for i, v in enumerate(embedding.nodes()):
43
+ pos[v] = default_positions[i]
44
+ return pos
45
+
46
+ embedding, outer_face = triangulate_embedding(embedding, fully_triangulate)
47
+
48
+ # The following dicts map a node to another node
49
+ # If a node is not in the key set it means that the node is not yet in G_k
50
+ # If a node maps to None then the corresponding subtree does not exist
51
+ left_t_child = {}
52
+ right_t_child = {}
53
+
54
+ # The following dicts map a node to an integer
55
+ delta_x = {}
56
+ y_coordinate = {}
57
+
58
+ node_list = get_canonical_ordering(embedding, outer_face)
59
+
60
+ # 1. Phase: Compute relative positions
61
+
62
+ # Initialization
63
+ v1, v2, v3 = node_list[0][0], node_list[1][0], node_list[2][0]
64
+
65
+ delta_x[v1] = 0
66
+ y_coordinate[v1] = 0
67
+ right_t_child[v1] = v3
68
+ left_t_child[v1] = None
69
+
70
+ delta_x[v2] = 1
71
+ y_coordinate[v2] = 0
72
+ right_t_child[v2] = None
73
+ left_t_child[v2] = None
74
+
75
+ delta_x[v3] = 1
76
+ y_coordinate[v3] = 1
77
+ right_t_child[v3] = v2
78
+ left_t_child[v3] = None
79
+
80
+ for k in range(3, len(node_list)):
81
+ vk, contour_nbrs = node_list[k]
82
+ wp = contour_nbrs[0]
83
+ wp1 = contour_nbrs[1]
84
+ wq = contour_nbrs[-1]
85
+ wq1 = contour_nbrs[-2]
86
+ adds_mult_tri = len(contour_nbrs) > 2
87
+
88
+ # Stretch gaps:
89
+ delta_x[wp1] += 1
90
+ delta_x[wq] += 1
91
+
92
+ delta_x_wp_wq = sum(delta_x[x] for x in contour_nbrs[1:])
93
+
94
+ # Adjust offsets
95
+ delta_x[vk] = (-y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2
96
+ y_coordinate[vk] = (y_coordinate[wp] + delta_x_wp_wq + y_coordinate[wq]) // 2
97
+ delta_x[wq] = delta_x_wp_wq - delta_x[vk]
98
+ if adds_mult_tri:
99
+ delta_x[wp1] -= delta_x[vk]
100
+
101
+ # Install v_k:
102
+ right_t_child[wp] = vk
103
+ right_t_child[vk] = wq
104
+ if adds_mult_tri:
105
+ left_t_child[vk] = wp1
106
+ right_t_child[wq1] = None
107
+ else:
108
+ left_t_child[vk] = None
109
+
110
+ # 2. Phase: Set absolute positions
111
+ pos = {}
112
+ pos[v1] = (0, y_coordinate[v1])
113
+ remaining_nodes = [v1]
114
+ while remaining_nodes:
115
+ parent_node = remaining_nodes.pop()
116
+
117
+ # Calculate position for left child
118
+ set_position(
119
+ parent_node, left_t_child, remaining_nodes, delta_x, y_coordinate, pos
120
+ )
121
+ # Calculate position for right child
122
+ set_position(
123
+ parent_node, right_t_child, remaining_nodes, delta_x, y_coordinate, pos
124
+ )
125
+ return pos
126
+
127
+
128
+ def set_position(parent, tree, remaining_nodes, delta_x, y_coordinate, pos):
129
+ """Helper method to calculate the absolute position of nodes."""
130
+ child = tree[parent]
131
+ parent_node_x = pos[parent][0]
132
+ if child is not None:
133
+ # Calculate pos of child
134
+ child_x = parent_node_x + delta_x[child]
135
+ pos[child] = (child_x, y_coordinate[child])
136
+ # Remember to calculate pos of its children
137
+ remaining_nodes.append(child)
138
+
139
+
140
+ def get_canonical_ordering(embedding, outer_face):
141
+ """Returns a canonical ordering of the nodes
142
+
143
+ The canonical ordering of nodes (v1, ..., vn) must fulfill the following
144
+ conditions:
145
+ (See Lemma 1 in [2]_)
146
+
147
+ - For the subgraph G_k of the input graph induced by v1, ..., vk it holds:
148
+ - 2-connected
149
+ - internally triangulated
150
+ - the edge (v1, v2) is part of the outer face
151
+ - For a node v(k+1) the following holds:
152
+ - The node v(k+1) is part of the outer face of G_k
153
+ - It has at least two neighbors in G_k
154
+ - All neighbors of v(k+1) in G_k lie consecutively on the outer face of
155
+ G_k (excluding the edge (v1, v2)).
156
+
157
+ The algorithm used here starts with G_n (containing all nodes). It first
158
+ selects the nodes v1 and v2. And then tries to find the order of the other
159
+ nodes by checking which node can be removed in order to fulfill the
160
+ conditions mentioned above. This is done by calculating the number of
161
+ chords of nodes on the outer face. For more information see [1]_.
162
+
163
+ Parameters
164
+ ----------
165
+ embedding : nx.PlanarEmbedding
166
+ The embedding must be triangulated
167
+ outer_face : list
168
+ The nodes on the outer face of the graph
169
+
170
+ Returns
171
+ -------
172
+ ordering : list
173
+ A list of tuples `(vk, wp_wq)`. Here `vk` is the node at this position
174
+ in the canonical ordering. The element `wp_wq` is a list of nodes that
175
+ make up the outer face of G_k.
176
+
177
+ References
178
+ ----------
179
+ .. [1] Steven Chaplick.
180
+ Canonical Orders of Planar Graphs and (some of) Their Applications 2015
181
+ https://wuecampus2.uni-wuerzburg.de/moodle/pluginfile.php/545727/mod_resource/content/0/vg-ss15-vl03-canonical-orders-druckversion.pdf
182
+ .. [2] M. Chrobak and T.H. Payne:
183
+ A Linear-time Algorithm for Drawing a Planar Graph on a Grid 1989
184
+ http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.6677
185
+
186
+ """
187
+ v1 = outer_face[0]
188
+ v2 = outer_face[1]
189
+ chords = defaultdict(int) # Maps nodes to the number of their chords
190
+ marked_nodes = set()
191
+ ready_to_pick = set(outer_face)
192
+
193
+ # Initialize outer_face_ccw_nbr (do not include v1 -> v2)
194
+ outer_face_ccw_nbr = {}
195
+ prev_nbr = v2
196
+ for idx in range(2, len(outer_face)):
197
+ outer_face_ccw_nbr[prev_nbr] = outer_face[idx]
198
+ prev_nbr = outer_face[idx]
199
+ outer_face_ccw_nbr[prev_nbr] = v1
200
+
201
+ # Initialize outer_face_cw_nbr (do not include v2 -> v1)
202
+ outer_face_cw_nbr = {}
203
+ prev_nbr = v1
204
+ for idx in range(len(outer_face) - 1, 0, -1):
205
+ outer_face_cw_nbr[prev_nbr] = outer_face[idx]
206
+ prev_nbr = outer_face[idx]
207
+
208
+ def is_outer_face_nbr(x, y):
209
+ if x not in outer_face_ccw_nbr:
210
+ return outer_face_cw_nbr[x] == y
211
+ if x not in outer_face_cw_nbr:
212
+ return outer_face_ccw_nbr[x] == y
213
+ return outer_face_ccw_nbr[x] == y or outer_face_cw_nbr[x] == y
214
+
215
+ def is_on_outer_face(x):
216
+ return x not in marked_nodes and (x in outer_face_ccw_nbr or x == v1)
217
+
218
+ # Initialize number of chords
219
+ for v in outer_face:
220
+ for nbr in embedding.neighbors_cw_order(v):
221
+ if is_on_outer_face(nbr) and not is_outer_face_nbr(v, nbr):
222
+ chords[v] += 1
223
+ ready_to_pick.discard(v)
224
+
225
+ # Initialize canonical_ordering
226
+ canonical_ordering = [None] * len(embedding.nodes())
227
+ canonical_ordering[0] = (v1, [])
228
+ canonical_ordering[1] = (v2, [])
229
+ ready_to_pick.discard(v1)
230
+ ready_to_pick.discard(v2)
231
+
232
+ for k in range(len(embedding.nodes()) - 1, 1, -1):
233
+ # 1. Pick v from ready_to_pick
234
+ v = ready_to_pick.pop()
235
+ marked_nodes.add(v)
236
+
237
+ # v has exactly two neighbors on the outer face (wp and wq)
238
+ wp = None
239
+ wq = None
240
+ # Iterate over neighbors of v to find wp and wq
241
+ nbr_iterator = iter(embedding.neighbors_cw_order(v))
242
+ while True:
243
+ nbr = next(nbr_iterator)
244
+ if nbr in marked_nodes:
245
+ # Only consider nodes that are not yet removed
246
+ continue
247
+ if is_on_outer_face(nbr):
248
+ # nbr is either wp or wq
249
+ if nbr == v1:
250
+ wp = v1
251
+ elif nbr == v2:
252
+ wq = v2
253
+ else:
254
+ if outer_face_cw_nbr[nbr] == v:
255
+ # nbr is wp
256
+ wp = nbr
257
+ else:
258
+ # nbr is wq
259
+ wq = nbr
260
+ if wp is not None and wq is not None:
261
+ # We don't need to iterate any further
262
+ break
263
+
264
+ # Obtain new nodes on outer face (neighbors of v from wp to wq)
265
+ wp_wq = [wp]
266
+ nbr = wp
267
+ while nbr != wq:
268
+ # Get next neighbor (clockwise on the outer face)
269
+ next_nbr = embedding[v][nbr]["ccw"]
270
+ wp_wq.append(next_nbr)
271
+ # Update outer face
272
+ outer_face_cw_nbr[nbr] = next_nbr
273
+ outer_face_ccw_nbr[next_nbr] = nbr
274
+ # Move to next neighbor of v
275
+ nbr = next_nbr
276
+
277
+ if len(wp_wq) == 2:
278
+ # There was a chord between wp and wq, decrease number of chords
279
+ chords[wp] -= 1
280
+ if chords[wp] == 0:
281
+ ready_to_pick.add(wp)
282
+ chords[wq] -= 1
283
+ if chords[wq] == 0:
284
+ ready_to_pick.add(wq)
285
+ else:
286
+ # Update all chords involving w_(p+1) to w_(q-1)
287
+ new_face_nodes = set(wp_wq[1:-1])
288
+ for w in new_face_nodes:
289
+ # If we do not find a chord for w later we can pick it next
290
+ ready_to_pick.add(w)
291
+ for nbr in embedding.neighbors_cw_order(w):
292
+ if is_on_outer_face(nbr) and not is_outer_face_nbr(w, nbr):
293
+ # There is a chord involving w
294
+ chords[w] += 1
295
+ ready_to_pick.discard(w)
296
+ if nbr not in new_face_nodes:
297
+ # Also increase chord for the neighbor
298
+ # We only iterator over new_face_nodes
299
+ chords[nbr] += 1
300
+ ready_to_pick.discard(nbr)
301
+ # Set the canonical ordering node and the list of contour neighbors
302
+ canonical_ordering[k] = (v, wp_wq)
303
+
304
+ return canonical_ordering
305
+
306
+
307
+ def triangulate_face(embedding, v1, v2):
308
+ """Triangulates the face given by half edge (v, w)
309
+
310
+ Parameters
311
+ ----------
312
+ embedding : nx.PlanarEmbedding
313
+ v1 : node
314
+ The half-edge (v1, v2) belongs to the face that gets triangulated
315
+ v2 : node
316
+ """
317
+ _, v3 = embedding.next_face_half_edge(v1, v2)
318
+ _, v4 = embedding.next_face_half_edge(v2, v3)
319
+ if v1 in (v2, v3):
320
+ # The component has less than 3 nodes
321
+ return
322
+ while v1 != v4:
323
+ # Add edge if not already present on other side
324
+ if embedding.has_edge(v1, v3):
325
+ # Cannot triangulate at this position
326
+ v1, v2, v3 = v2, v3, v4
327
+ else:
328
+ # Add edge for triangulation
329
+ embedding.add_half_edge(v1, v3, ccw=v2)
330
+ embedding.add_half_edge(v3, v1, cw=v2)
331
+ v1, v2, v3 = v1, v3, v4
332
+ # Get next node
333
+ _, v4 = embedding.next_face_half_edge(v2, v3)
334
+
335
+
336
+ def triangulate_embedding(embedding, fully_triangulate=True):
337
+ """Triangulates the embedding.
338
+
339
+ Traverses faces of the embedding and adds edges to a copy of the
340
+ embedding to triangulate it.
341
+ The method also ensures that the resulting graph is 2-connected by adding
342
+ edges if the same vertex is contained twice on a path around a face.
343
+
344
+ Parameters
345
+ ----------
346
+ embedding : nx.PlanarEmbedding
347
+ The input graph must contain at least 3 nodes.
348
+
349
+ fully_triangulate : bool
350
+ If set to False the face with the most nodes is chooses as outer face.
351
+ This outer face does not get triangulated.
352
+
353
+ Returns
354
+ -------
355
+ (embedding, outer_face) : (nx.PlanarEmbedding, list) tuple
356
+ The element `embedding` is a new embedding containing all edges from
357
+ the input embedding and the additional edges to triangulate the graph.
358
+ The element `outer_face` is a list of nodes that lie on the outer face.
359
+ If the graph is fully triangulated these are three arbitrary connected
360
+ nodes.
361
+
362
+ """
363
+ if len(embedding.nodes) <= 1:
364
+ return embedding, list(embedding.nodes)
365
+ embedding = nx.PlanarEmbedding(embedding)
366
+
367
+ # Get a list with a node for each connected component
368
+ component_nodes = [next(iter(x)) for x in nx.connected_components(embedding)]
369
+
370
+ # 1. Make graph a single component (add edge between components)
371
+ for i in range(len(component_nodes) - 1):
372
+ v1 = component_nodes[i]
373
+ v2 = component_nodes[i + 1]
374
+ embedding.connect_components(v1, v2)
375
+
376
+ # 2. Calculate faces, ensure 2-connectedness and determine outer face
377
+ outer_face = [] # A face with the most number of nodes
378
+ face_list = []
379
+ edges_visited = set() # Used to keep track of already visited faces
380
+ for v in embedding.nodes():
381
+ for w in embedding.neighbors_cw_order(v):
382
+ new_face = make_bi_connected(embedding, v, w, edges_visited)
383
+ if new_face:
384
+ # Found a new face
385
+ face_list.append(new_face)
386
+ if len(new_face) > len(outer_face):
387
+ # The face is a candidate to be the outer face
388
+ outer_face = new_face
389
+
390
+ # 3. Triangulate (internal) faces
391
+ for face in face_list:
392
+ if face is not outer_face or fully_triangulate:
393
+ # Triangulate this face
394
+ triangulate_face(embedding, face[0], face[1])
395
+
396
+ if fully_triangulate:
397
+ v1 = outer_face[0]
398
+ v2 = outer_face[1]
399
+ v3 = embedding[v2][v1]["ccw"]
400
+ outer_face = [v1, v2, v3]
401
+
402
+ return embedding, outer_face
403
+
404
+
405
+ def make_bi_connected(embedding, starting_node, outgoing_node, edges_counted):
406
+ """Triangulate a face and make it 2-connected
407
+
408
+ This method also adds all edges on the face to `edges_counted`.
409
+
410
+ Parameters
411
+ ----------
412
+ embedding: nx.PlanarEmbedding
413
+ The embedding that defines the faces
414
+ starting_node : node
415
+ A node on the face
416
+ outgoing_node : node
417
+ A node such that the half edge (starting_node, outgoing_node) belongs
418
+ to the face
419
+ edges_counted: set
420
+ Set of all half-edges that belong to a face that have been visited
421
+
422
+ Returns
423
+ -------
424
+ face_nodes: list
425
+ A list of all nodes at the border of this face
426
+ """
427
+
428
+ # Check if the face has already been calculated
429
+ if (starting_node, outgoing_node) in edges_counted:
430
+ # This face was already counted
431
+ return []
432
+ edges_counted.add((starting_node, outgoing_node))
433
+
434
+ # Add all edges to edges_counted which have this face to their left
435
+ v1 = starting_node
436
+ v2 = outgoing_node
437
+ face_list = [starting_node] # List of nodes around the face
438
+ face_set = set(face_list) # Set for faster queries
439
+ _, v3 = embedding.next_face_half_edge(v1, v2)
440
+
441
+ # Move the nodes v1, v2, v3 around the face:
442
+ while v2 != starting_node or v3 != outgoing_node:
443
+ if v1 == v2:
444
+ raise nx.NetworkXException("Invalid half-edge")
445
+ # cycle is not completed yet
446
+ if v2 in face_set:
447
+ # v2 encountered twice: Add edge to ensure 2-connectedness
448
+ embedding.add_half_edge(v1, v3, ccw=v2)
449
+ embedding.add_half_edge(v3, v1, cw=v2)
450
+ edges_counted.add((v2, v3))
451
+ edges_counted.add((v3, v1))
452
+ v2 = v1
453
+ else:
454
+ face_set.add(v2)
455
+ face_list.append(v2)
456
+
457
+ # set next edge
458
+ v1 = v2
459
+ v2, v3 = embedding.next_face_half_edge(v2, v3)
460
+
461
+ # remember that this edge has been counted
462
+ edges_counted.add((v1, v2))
463
+
464
+ return face_list
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/reciprocity.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Algorithms to calculate reciprocity in a directed graph."""
2
+ import networkx as nx
3
+ from networkx import NetworkXError
4
+
5
+ from ..utils import not_implemented_for
6
+
7
+ __all__ = ["reciprocity", "overall_reciprocity"]
8
+
9
+
10
+ @not_implemented_for("undirected", "multigraph")
11
+ @nx._dispatchable
12
+ def reciprocity(G, nodes=None):
13
+ r"""Compute the reciprocity in a directed graph.
14
+
15
+ The reciprocity of a directed graph is defined as the ratio
16
+ of the number of edges pointing in both directions to the total
17
+ number of edges in the graph.
18
+ Formally, $r = |{(u,v) \in G|(v,u) \in G}| / |{(u,v) \in G}|$.
19
+
20
+ The reciprocity of a single node u is defined similarly,
21
+ it is the ratio of the number of edges in both directions to
22
+ the total number of edges attached to node u.
23
+
24
+ Parameters
25
+ ----------
26
+ G : graph
27
+ A networkx directed graph
28
+ nodes : container of nodes, optional (default=whole graph)
29
+ Compute reciprocity for nodes in this container.
30
+
31
+ Returns
32
+ -------
33
+ out : dictionary
34
+ Reciprocity keyed by node label.
35
+
36
+ Notes
37
+ -----
38
+ The reciprocity is not defined for isolated nodes.
39
+ In such cases this function will return None.
40
+
41
+ """
42
+ # If `nodes` is not specified, calculate the reciprocity of the graph.
43
+ if nodes is None:
44
+ return overall_reciprocity(G)
45
+
46
+ # If `nodes` represents a single node in the graph, return only its
47
+ # reciprocity.
48
+ if nodes in G:
49
+ reciprocity = next(_reciprocity_iter(G, nodes))[1]
50
+ if reciprocity is None:
51
+ raise NetworkXError("Not defined for isolated nodes.")
52
+ else:
53
+ return reciprocity
54
+
55
+ # Otherwise, `nodes` represents an iterable of nodes, so return a
56
+ # dictionary mapping node to its reciprocity.
57
+ return dict(_reciprocity_iter(G, nodes))
58
+
59
+
60
+ def _reciprocity_iter(G, nodes):
61
+ """Return an iterator of (node, reciprocity)."""
62
+ n = G.nbunch_iter(nodes)
63
+ for node in n:
64
+ pred = set(G.predecessors(node))
65
+ succ = set(G.successors(node))
66
+ overlap = pred & succ
67
+ n_total = len(pred) + len(succ)
68
+
69
+ # Reciprocity is not defined for isolated nodes.
70
+ # Return None.
71
+ if n_total == 0:
72
+ yield (node, None)
73
+ else:
74
+ reciprocity = 2 * len(overlap) / n_total
75
+ yield (node, reciprocity)
76
+
77
+
78
+ @not_implemented_for("undirected", "multigraph")
79
+ @nx._dispatchable
80
+ def overall_reciprocity(G):
81
+ """Compute the reciprocity for the whole graph.
82
+
83
+ See the doc of reciprocity for the definition.
84
+
85
+ Parameters
86
+ ----------
87
+ G : graph
88
+ A networkx graph
89
+
90
+ """
91
+ n_all_edge = G.number_of_edges()
92
+ n_overlap_edge = (n_all_edge - G.to_undirected().number_of_edges()) * 2
93
+
94
+ if n_all_edge == 0:
95
+ raise NetworkXError("Not defined for empty graphs")
96
+
97
+ return n_overlap_edge / n_all_edge
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/regular.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing and verifying regular graphs."""
2
+ import networkx as nx
3
+ from networkx.utils import not_implemented_for
4
+
5
+ __all__ = ["is_regular", "is_k_regular", "k_factor"]
6
+
7
+
8
+ @nx._dispatchable
9
+ def is_regular(G):
10
+ """Determines whether the graph ``G`` is a regular graph.
11
+
12
+ A regular graph is a graph where each vertex has the same degree. A
13
+ regular digraph is a graph where the indegree and outdegree of each
14
+ vertex are equal.
15
+
16
+ Parameters
17
+ ----------
18
+ G : NetworkX graph
19
+
20
+ Returns
21
+ -------
22
+ bool
23
+ Whether the given graph or digraph is regular.
24
+
25
+ Examples
26
+ --------
27
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 1)])
28
+ >>> nx.is_regular(G)
29
+ True
30
+
31
+ """
32
+ if len(G) == 0:
33
+ raise nx.NetworkXPointlessConcept("Graph has no nodes.")
34
+ n1 = nx.utils.arbitrary_element(G)
35
+ if not G.is_directed():
36
+ d1 = G.degree(n1)
37
+ return all(d1 == d for _, d in G.degree)
38
+ else:
39
+ d_in = G.in_degree(n1)
40
+ in_regular = all(d_in == d for _, d in G.in_degree)
41
+ d_out = G.out_degree(n1)
42
+ out_regular = all(d_out == d for _, d in G.out_degree)
43
+ return in_regular and out_regular
44
+
45
+
46
+ @not_implemented_for("directed")
47
+ @nx._dispatchable
48
+ def is_k_regular(G, k):
49
+ """Determines whether the graph ``G`` is a k-regular graph.
50
+
51
+ A k-regular graph is a graph where each vertex has degree k.
52
+
53
+ Parameters
54
+ ----------
55
+ G : NetworkX graph
56
+
57
+ Returns
58
+ -------
59
+ bool
60
+ Whether the given graph is k-regular.
61
+
62
+ Examples
63
+ --------
64
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 1)])
65
+ >>> nx.is_k_regular(G, k=3)
66
+ False
67
+
68
+ """
69
+ return all(d == k for n, d in G.degree)
70
+
71
+
72
+ @not_implemented_for("directed")
73
+ @not_implemented_for("multigraph")
74
+ @nx._dispatchable(preserve_edge_attrs=True, returns_graph=True)
75
+ def k_factor(G, k, matching_weight="weight"):
76
+ """Compute a k-factor of G
77
+
78
+ A k-factor of a graph is a spanning k-regular subgraph.
79
+ A spanning k-regular subgraph of G is a subgraph that contains
80
+ each vertex of G and a subset of the edges of G such that each
81
+ vertex has degree k.
82
+
83
+ Parameters
84
+ ----------
85
+ G : NetworkX graph
86
+ Undirected graph
87
+
88
+ matching_weight: string, optional (default='weight')
89
+ Edge data key corresponding to the edge weight.
90
+ Used for finding the max-weighted perfect matching.
91
+ If key not found, uses 1 as weight.
92
+
93
+ Returns
94
+ -------
95
+ G2 : NetworkX graph
96
+ A k-factor of G
97
+
98
+ Examples
99
+ --------
100
+ >>> G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 1)])
101
+ >>> G2 = nx.k_factor(G, k=1)
102
+ >>> G2.edges()
103
+ EdgeView([(1, 2), (3, 4)])
104
+
105
+ References
106
+ ----------
107
+ .. [1] "An algorithm for computing simple k-factors.",
108
+ Meijer, Henk, Yurai Núñez-Rodríguez, and David Rappaport,
109
+ Information processing letters, 2009.
110
+ """
111
+
112
+ from networkx.algorithms.matching import is_perfect_matching, max_weight_matching
113
+
114
+ class LargeKGadget:
115
+ def __init__(self, k, degree, node, g):
116
+ self.original = node
117
+ self.g = g
118
+ self.k = k
119
+ self.degree = degree
120
+
121
+ self.outer_vertices = [(node, x) for x in range(degree)]
122
+ self.core_vertices = [(node, x + degree) for x in range(degree - k)]
123
+
124
+ def replace_node(self):
125
+ adj_view = self.g[self.original]
126
+ neighbors = list(adj_view.keys())
127
+ edge_attrs = list(adj_view.values())
128
+ for outer, neighbor, edge_attrs in zip(
129
+ self.outer_vertices, neighbors, edge_attrs
130
+ ):
131
+ self.g.add_edge(outer, neighbor, **edge_attrs)
132
+ for core in self.core_vertices:
133
+ for outer in self.outer_vertices:
134
+ self.g.add_edge(core, outer)
135
+ self.g.remove_node(self.original)
136
+
137
+ def restore_node(self):
138
+ self.g.add_node(self.original)
139
+ for outer in self.outer_vertices:
140
+ adj_view = self.g[outer]
141
+ for neighbor, edge_attrs in list(adj_view.items()):
142
+ if neighbor not in self.core_vertices:
143
+ self.g.add_edge(self.original, neighbor, **edge_attrs)
144
+ break
145
+ g.remove_nodes_from(self.outer_vertices)
146
+ g.remove_nodes_from(self.core_vertices)
147
+
148
+ class SmallKGadget:
149
+ def __init__(self, k, degree, node, g):
150
+ self.original = node
151
+ self.k = k
152
+ self.degree = degree
153
+ self.g = g
154
+
155
+ self.outer_vertices = [(node, x) for x in range(degree)]
156
+ self.inner_vertices = [(node, x + degree) for x in range(degree)]
157
+ self.core_vertices = [(node, x + 2 * degree) for x in range(k)]
158
+
159
+ def replace_node(self):
160
+ adj_view = self.g[self.original]
161
+ for outer, inner, (neighbor, edge_attrs) in zip(
162
+ self.outer_vertices, self.inner_vertices, list(adj_view.items())
163
+ ):
164
+ self.g.add_edge(outer, inner)
165
+ self.g.add_edge(outer, neighbor, **edge_attrs)
166
+ for core in self.core_vertices:
167
+ for inner in self.inner_vertices:
168
+ self.g.add_edge(core, inner)
169
+ self.g.remove_node(self.original)
170
+
171
+ def restore_node(self):
172
+ self.g.add_node(self.original)
173
+ for outer in self.outer_vertices:
174
+ adj_view = self.g[outer]
175
+ for neighbor, edge_attrs in adj_view.items():
176
+ if neighbor not in self.core_vertices:
177
+ self.g.add_edge(self.original, neighbor, **edge_attrs)
178
+ break
179
+ self.g.remove_nodes_from(self.outer_vertices)
180
+ self.g.remove_nodes_from(self.inner_vertices)
181
+ self.g.remove_nodes_from(self.core_vertices)
182
+
183
+ # Step 1
184
+ if any(d < k for _, d in G.degree):
185
+ raise nx.NetworkXUnfeasible("Graph contains a vertex with degree less than k")
186
+ g = G.copy()
187
+
188
+ # Step 2
189
+ gadgets = []
190
+ for node, degree in list(g.degree):
191
+ if k < degree / 2.0:
192
+ gadget = SmallKGadget(k, degree, node, g)
193
+ else:
194
+ gadget = LargeKGadget(k, degree, node, g)
195
+ gadget.replace_node()
196
+ gadgets.append(gadget)
197
+
198
+ # Step 3
199
+ matching = max_weight_matching(g, maxcardinality=True, weight=matching_weight)
200
+
201
+ # Step 4
202
+ if not is_perfect_matching(g, matching):
203
+ raise nx.NetworkXUnfeasible(
204
+ "Cannot find k-factor because no perfect matching exists"
205
+ )
206
+
207
+ for edge in g.edges():
208
+ if edge not in matching and (edge[1], edge[0]) not in matching:
209
+ g.remove_edge(edge[0], edge[1])
210
+
211
+ for gadget in gadgets:
212
+ gadget.restore_node()
213
+
214
+ return g
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from networkx.algorithms.shortest_paths.generic import *
2
+ from networkx.algorithms.shortest_paths.unweighted import *
3
+ from networkx.algorithms.shortest_paths.weighted import *
4
+ from networkx.algorithms.shortest_paths.astar import *
5
+ from networkx.algorithms.shortest_paths.dense import *
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/astar.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shortest paths and path lengths using the A* ("A star") algorithm.
2
+ """
3
+ from heapq import heappop, heappush
4
+ from itertools import count
5
+
6
+ import networkx as nx
7
+ from networkx.algorithms.shortest_paths.weighted import _weight_function
8
+
9
+ __all__ = ["astar_path", "astar_path_length"]
10
+
11
+
12
+ @nx._dispatchable(edge_attrs="weight", preserve_node_attrs="heuristic")
13
+ def astar_path(G, source, target, heuristic=None, weight="weight", *, cutoff=None):
14
+ """Returns a list of nodes in a shortest path between source and target
15
+ using the A* ("A-star") algorithm.
16
+
17
+ There may be more than one shortest path. This returns only one.
18
+
19
+ Parameters
20
+ ----------
21
+ G : NetworkX graph
22
+
23
+ source : node
24
+ Starting node for path
25
+
26
+ target : node
27
+ Ending node for path
28
+
29
+ heuristic : function
30
+ A function to evaluate the estimate of the distance
31
+ from the a node to the target. The function takes
32
+ two nodes arguments and must return a number.
33
+ If the heuristic is inadmissible (if it might
34
+ overestimate the cost of reaching the goal from a node),
35
+ the result may not be a shortest path.
36
+ The algorithm does not support updating heuristic
37
+ values for the same node due to caching the first
38
+ heuristic calculation per node.
39
+
40
+ weight : string or function
41
+ If this is a string, then edge weights will be accessed via the
42
+ edge attribute with this key (that is, the weight of the edge
43
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
44
+ such edge attribute exists, the weight of the edge is assumed to
45
+ be one.
46
+ If this is a function, the weight of an edge is the value
47
+ returned by the function. The function must accept exactly three
48
+ positional arguments: the two endpoints of an edge and the
49
+ dictionary of edge attributes for that edge. The function must
50
+ return a number or None to indicate a hidden edge.
51
+
52
+ cutoff : float, optional
53
+ If this is provided, the search will be bounded to this value. I.e. if
54
+ the evaluation function surpasses this value for a node n, the node will not
55
+ be expanded further and will be ignored. More formally, let h'(n) be the
56
+ heuristic function, and g(n) be the cost of reaching n from the source node. Then,
57
+ if g(n) + h'(n) > cutoff, the node will not be explored further.
58
+ Note that if the heuristic is inadmissible, it is possible that paths
59
+ are ignored even though they satisfy the cutoff.
60
+
61
+ Raises
62
+ ------
63
+ NetworkXNoPath
64
+ If no path exists between source and target.
65
+
66
+ Examples
67
+ --------
68
+ >>> G = nx.path_graph(5)
69
+ >>> print(nx.astar_path(G, 0, 4))
70
+ [0, 1, 2, 3, 4]
71
+ >>> G = nx.grid_graph(dim=[3, 3]) # nodes are two-tuples (x,y)
72
+ >>> nx.set_edge_attributes(G, {e: e[1][0] * 2 for e in G.edges()}, "cost")
73
+ >>> def dist(a, b):
74
+ ... (x1, y1) = a
75
+ ... (x2, y2) = b
76
+ ... return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
77
+ >>> print(nx.astar_path(G, (0, 0), (2, 2), heuristic=dist, weight="cost"))
78
+ [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
79
+
80
+ Notes
81
+ -----
82
+ Edge weight attributes must be numerical.
83
+ Distances are calculated as sums of weighted edges traversed.
84
+
85
+ The weight function can be used to hide edges by returning None.
86
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
87
+ will find the shortest red path.
88
+
89
+ See Also
90
+ --------
91
+ shortest_path, dijkstra_path
92
+
93
+ """
94
+ if source not in G or target not in G:
95
+ msg = f"Either source {source} or target {target} is not in G"
96
+ raise nx.NodeNotFound(msg)
97
+
98
+ if heuristic is None:
99
+ # The default heuristic is h=0 - same as Dijkstra's algorithm
100
+ def heuristic(u, v):
101
+ return 0
102
+
103
+ push = heappush
104
+ pop = heappop
105
+ weight = _weight_function(G, weight)
106
+
107
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
108
+
109
+ # The queue stores priority, node, cost to reach, and parent.
110
+ # Uses Python heapq to keep in priority order.
111
+ # Add a counter to the queue to prevent the underlying heap from
112
+ # attempting to compare the nodes themselves. The hash breaks ties in the
113
+ # priority and is guaranteed unique for all nodes in the graph.
114
+ c = count()
115
+ queue = [(0, next(c), source, 0, None)]
116
+
117
+ # Maps enqueued nodes to distance of discovered paths and the
118
+ # computed heuristics to target. We avoid computing the heuristics
119
+ # more than once and inserting the node into the queue too many times.
120
+ enqueued = {}
121
+ # Maps explored nodes to parent closest to the source.
122
+ explored = {}
123
+
124
+ while queue:
125
+ # Pop the smallest item from queue.
126
+ _, __, curnode, dist, parent = pop(queue)
127
+
128
+ if curnode == target:
129
+ path = [curnode]
130
+ node = parent
131
+ while node is not None:
132
+ path.append(node)
133
+ node = explored[node]
134
+ path.reverse()
135
+ return path
136
+
137
+ if curnode in explored:
138
+ # Do not override the parent of starting node
139
+ if explored[curnode] is None:
140
+ continue
141
+
142
+ # Skip bad paths that were enqueued before finding a better one
143
+ qcost, h = enqueued[curnode]
144
+ if qcost < dist:
145
+ continue
146
+
147
+ explored[curnode] = parent
148
+
149
+ for neighbor, w in G_succ[curnode].items():
150
+ cost = weight(curnode, neighbor, w)
151
+ if cost is None:
152
+ continue
153
+ ncost = dist + cost
154
+ if neighbor in enqueued:
155
+ qcost, h = enqueued[neighbor]
156
+ # if qcost <= ncost, a less costly path from the
157
+ # neighbor to the source was already determined.
158
+ # Therefore, we won't attempt to push this neighbor
159
+ # to the queue
160
+ if qcost <= ncost:
161
+ continue
162
+ else:
163
+ h = heuristic(neighbor, target)
164
+
165
+ if cutoff and ncost + h > cutoff:
166
+ continue
167
+
168
+ enqueued[neighbor] = ncost, h
169
+ push(queue, (ncost + h, next(c), neighbor, ncost, curnode))
170
+
171
+ raise nx.NetworkXNoPath(f"Node {target} not reachable from {source}")
172
+
173
+
174
+ @nx._dispatchable(edge_attrs="weight", preserve_node_attrs="heuristic")
175
+ def astar_path_length(
176
+ G, source, target, heuristic=None, weight="weight", *, cutoff=None
177
+ ):
178
+ """Returns the length of the shortest path between source and target using
179
+ the A* ("A-star") algorithm.
180
+
181
+ Parameters
182
+ ----------
183
+ G : NetworkX graph
184
+
185
+ source : node
186
+ Starting node for path
187
+
188
+ target : node
189
+ Ending node for path
190
+
191
+ heuristic : function
192
+ A function to evaluate the estimate of the distance
193
+ from the a node to the target. The function takes
194
+ two nodes arguments and must return a number.
195
+ If the heuristic is inadmissible (if it might
196
+ overestimate the cost of reaching the goal from a node),
197
+ the result may not be a shortest path.
198
+ The algorithm does not support updating heuristic
199
+ values for the same node due to caching the first
200
+ heuristic calculation per node.
201
+
202
+ weight : string or function
203
+ If this is a string, then edge weights will be accessed via the
204
+ edge attribute with this key (that is, the weight of the edge
205
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
206
+ such edge attribute exists, the weight of the edge is assumed to
207
+ be one.
208
+ If this is a function, the weight of an edge is the value
209
+ returned by the function. The function must accept exactly three
210
+ positional arguments: the two endpoints of an edge and the
211
+ dictionary of edge attributes for that edge. The function must
212
+ return a number or None to indicate a hidden edge.
213
+
214
+ cutoff : float, optional
215
+ If this is provided, the search will be bounded to this value. I.e. if
216
+ the evaluation function surpasses this value for a node n, the node will not
217
+ be expanded further and will be ignored. More formally, let h'(n) be the
218
+ heuristic function, and g(n) be the cost of reaching n from the source node. Then,
219
+ if g(n) + h'(n) > cutoff, the node will not be explored further.
220
+ Note that if the heuristic is inadmissible, it is possible that paths
221
+ are ignored even though they satisfy the cutoff.
222
+
223
+ Raises
224
+ ------
225
+ NetworkXNoPath
226
+ If no path exists between source and target.
227
+
228
+ See Also
229
+ --------
230
+ astar_path
231
+
232
+ """
233
+ if source not in G or target not in G:
234
+ msg = f"Either source {source} or target {target} is not in G"
235
+ raise nx.NodeNotFound(msg)
236
+
237
+ weight = _weight_function(G, weight)
238
+ path = astar_path(G, source, target, heuristic, weight, cutoff=cutoff)
239
+ return sum(weight(u, v, G[u][v]) for u, v in zip(path[:-1], path[1:]))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/dense.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Floyd-Warshall algorithm for shortest paths.
2
+ """
3
+ import networkx as nx
4
+
5
+ __all__ = [
6
+ "floyd_warshall",
7
+ "floyd_warshall_predecessor_and_distance",
8
+ "reconstruct_path",
9
+ "floyd_warshall_numpy",
10
+ ]
11
+
12
+
13
+ @nx._dispatchable(edge_attrs="weight")
14
+ def floyd_warshall_numpy(G, nodelist=None, weight="weight"):
15
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
16
+
17
+ This algorithm for finding shortest paths takes advantage of
18
+ matrix representations of a graph and works well for dense
19
+ graphs where all-pairs shortest path lengths are desired.
20
+ The results are returned as a NumPy array, distance[i, j],
21
+ where i and j are the indexes of two nodes in nodelist.
22
+ The entry distance[i, j] is the distance along a shortest
23
+ path from i to j. If no path exists the distance is Inf.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ nodelist : list, optional (default=G.nodes)
30
+ The rows and columns are ordered by the nodes in nodelist.
31
+ If nodelist is None then the ordering is produced by G.nodes.
32
+ Nodelist should include all nodes in G.
33
+
34
+ weight: string, optional (default='weight')
35
+ Edge data key corresponding to the edge weight.
36
+
37
+ Returns
38
+ -------
39
+ distance : 2D numpy.ndarray
40
+ A numpy array of shortest path distances between nodes.
41
+ If there is no path between two nodes the value is Inf.
42
+
43
+ Examples
44
+ --------
45
+ >>> G = nx.DiGraph()
46
+ >>> G.add_weighted_edges_from([(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)])
47
+ >>> nx.floyd_warshall_numpy(G)
48
+ array([[ 0., 5., 7., 4.],
49
+ [inf, 0., 2., -1.],
50
+ [inf, inf, 0., -3.],
51
+ [inf, inf, 8., 0.]])
52
+
53
+ Notes
54
+ -----
55
+ Floyd's algorithm is appropriate for finding shortest paths in
56
+ dense graphs or graphs with negative weights when Dijkstra's
57
+ algorithm fails. This algorithm can still fail if there are negative
58
+ cycles. It has running time $O(n^3)$ with running space of $O(n^2)$.
59
+
60
+ Raises
61
+ ------
62
+ NetworkXError
63
+ If nodelist is not a list of the nodes in G.
64
+ """
65
+ import numpy as np
66
+
67
+ if nodelist is not None:
68
+ if not (len(nodelist) == len(G) == len(set(nodelist))):
69
+ raise nx.NetworkXError(
70
+ "nodelist must contain every node in G with no repeats."
71
+ "If you wanted a subgraph of G use G.subgraph(nodelist)"
72
+ )
73
+
74
+ # To handle cases when an edge has weight=0, we must make sure that
75
+ # nonedges are not given the value 0 as well.
76
+ A = nx.to_numpy_array(
77
+ G, nodelist, multigraph_weight=min, weight=weight, nonedge=np.inf
78
+ )
79
+ n, m = A.shape
80
+ np.fill_diagonal(A, 0) # diagonal elements should be zero
81
+ for i in range(n):
82
+ # The second term has the same shape as A due to broadcasting
83
+ A = np.minimum(A, A[i, :][np.newaxis, :] + A[:, i][:, np.newaxis])
84
+ return A
85
+
86
+
87
+ @nx._dispatchable(edge_attrs="weight")
88
+ def floyd_warshall_predecessor_and_distance(G, weight="weight"):
89
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
90
+
91
+ Parameters
92
+ ----------
93
+ G : NetworkX graph
94
+
95
+ weight: string, optional (default= 'weight')
96
+ Edge data key corresponding to the edge weight.
97
+
98
+ Returns
99
+ -------
100
+ predecessor,distance : dictionaries
101
+ Dictionaries, keyed by source and target, of predecessors and distances
102
+ in the shortest path.
103
+
104
+ Examples
105
+ --------
106
+ >>> G = nx.DiGraph()
107
+ >>> G.add_weighted_edges_from(
108
+ ... [
109
+ ... ("s", "u", 10),
110
+ ... ("s", "x", 5),
111
+ ... ("u", "v", 1),
112
+ ... ("u", "x", 2),
113
+ ... ("v", "y", 1),
114
+ ... ("x", "u", 3),
115
+ ... ("x", "v", 5),
116
+ ... ("x", "y", 2),
117
+ ... ("y", "s", 7),
118
+ ... ("y", "v", 6),
119
+ ... ]
120
+ ... )
121
+ >>> predecessors, _ = nx.floyd_warshall_predecessor_and_distance(G)
122
+ >>> print(nx.reconstruct_path("s", "v", predecessors))
123
+ ['s', 'x', 'u', 'v']
124
+
125
+ Notes
126
+ -----
127
+ Floyd's algorithm is appropriate for finding shortest paths
128
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
129
+ fails. This algorithm can still fail if there are negative cycles.
130
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
131
+
132
+ See Also
133
+ --------
134
+ floyd_warshall
135
+ floyd_warshall_numpy
136
+ all_pairs_shortest_path
137
+ all_pairs_shortest_path_length
138
+ """
139
+ from collections import defaultdict
140
+
141
+ # dictionary-of-dictionaries representation for dist and pred
142
+ # use some defaultdict magick here
143
+ # for dist the default is the floating point inf value
144
+ dist = defaultdict(lambda: defaultdict(lambda: float("inf")))
145
+ for u in G:
146
+ dist[u][u] = 0
147
+ pred = defaultdict(dict)
148
+ # initialize path distance dictionary to be the adjacency matrix
149
+ # also set the distance to self to 0 (zero diagonal)
150
+ undirected = not G.is_directed()
151
+ for u, v, d in G.edges(data=True):
152
+ e_weight = d.get(weight, 1.0)
153
+ dist[u][v] = min(e_weight, dist[u][v])
154
+ pred[u][v] = u
155
+ if undirected:
156
+ dist[v][u] = min(e_weight, dist[v][u])
157
+ pred[v][u] = v
158
+ for w in G:
159
+ dist_w = dist[w] # save recomputation
160
+ for u in G:
161
+ dist_u = dist[u] # save recomputation
162
+ for v in G:
163
+ d = dist_u[w] + dist_w[v]
164
+ if dist_u[v] > d:
165
+ dist_u[v] = d
166
+ pred[u][v] = pred[w][v]
167
+ return dict(pred), dict(dist)
168
+
169
+
170
+ @nx._dispatchable(graphs=None)
171
+ def reconstruct_path(source, target, predecessors):
172
+ """Reconstruct a path from source to target using the predecessors
173
+ dict as returned by floyd_warshall_predecessor_and_distance
174
+
175
+ Parameters
176
+ ----------
177
+ source : node
178
+ Starting node for path
179
+
180
+ target : node
181
+ Ending node for path
182
+
183
+ predecessors: dictionary
184
+ Dictionary, keyed by source and target, of predecessors in the
185
+ shortest path, as returned by floyd_warshall_predecessor_and_distance
186
+
187
+ Returns
188
+ -------
189
+ path : list
190
+ A list of nodes containing the shortest path from source to target
191
+
192
+ If source and target are the same, an empty list is returned
193
+
194
+ Notes
195
+ -----
196
+ This function is meant to give more applicability to the
197
+ floyd_warshall_predecessor_and_distance function
198
+
199
+ See Also
200
+ --------
201
+ floyd_warshall_predecessor_and_distance
202
+ """
203
+ if source == target:
204
+ return []
205
+ prev = predecessors[source]
206
+ curr = prev[target]
207
+ path = [target, curr]
208
+ while curr != source:
209
+ curr = prev[curr]
210
+ path.append(curr)
211
+ return list(reversed(path))
212
+
213
+
214
+ @nx._dispatchable(edge_attrs="weight")
215
+ def floyd_warshall(G, weight="weight"):
216
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
217
+
218
+ Parameters
219
+ ----------
220
+ G : NetworkX graph
221
+
222
+ weight: string, optional (default= 'weight')
223
+ Edge data key corresponding to the edge weight.
224
+
225
+
226
+ Returns
227
+ -------
228
+ distance : dict
229
+ A dictionary, keyed by source and target, of shortest paths distances
230
+ between nodes.
231
+
232
+ Examples
233
+ --------
234
+ >>> G = nx.DiGraph()
235
+ >>> G.add_weighted_edges_from([(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)])
236
+ >>> fw = nx.floyd_warshall(G, weight="weight")
237
+ >>> results = {a: dict(b) for a, b in fw.items()}
238
+ >>> print(results)
239
+ {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}}
240
+
241
+ Notes
242
+ -----
243
+ Floyd's algorithm is appropriate for finding shortest paths
244
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
245
+ fails. This algorithm can still fail if there are negative cycles.
246
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
247
+
248
+ See Also
249
+ --------
250
+ floyd_warshall_predecessor_and_distance
251
+ floyd_warshall_numpy
252
+ all_pairs_shortest_path
253
+ all_pairs_shortest_path_length
254
+ """
255
+ # could make this its own function to reduce memory costs
256
+ return floyd_warshall_predecessor_and_distance(G, weight=weight)[1]
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/generic.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Compute the shortest paths and path lengths between nodes in the graph.
3
+
4
+ These algorithms work with undirected and directed graphs.
5
+
6
+ """
7
+ import warnings
8
+
9
+ import networkx as nx
10
+
11
+ __all__ = [
12
+ "shortest_path",
13
+ "all_shortest_paths",
14
+ "single_source_all_shortest_paths",
15
+ "all_pairs_all_shortest_paths",
16
+ "shortest_path_length",
17
+ "average_shortest_path_length",
18
+ "has_path",
19
+ ]
20
+
21
+
22
+ @nx._dispatchable
23
+ def has_path(G, source, target):
24
+ """Returns *True* if *G* has a path from *source* to *target*.
25
+
26
+ Parameters
27
+ ----------
28
+ G : NetworkX graph
29
+
30
+ source : node
31
+ Starting node for path
32
+
33
+ target : node
34
+ Ending node for path
35
+ """
36
+ try:
37
+ nx.shortest_path(G, source, target)
38
+ except nx.NetworkXNoPath:
39
+ return False
40
+ return True
41
+
42
+
43
+ @nx._dispatchable(edge_attrs="weight")
44
+ def shortest_path(G, source=None, target=None, weight=None, method="dijkstra"):
45
+ """Compute shortest paths in the graph.
46
+
47
+ Parameters
48
+ ----------
49
+ G : NetworkX graph
50
+
51
+ source : node, optional
52
+ Starting node for path. If not specified, compute shortest
53
+ paths for each possible starting node.
54
+
55
+ target : node, optional
56
+ Ending node for path. If not specified, compute shortest
57
+ paths to all possible nodes.
58
+
59
+ weight : None, string or function, optional (default = None)
60
+ If None, every edge has weight/distance/cost 1.
61
+ If a string, use this edge attribute as the edge weight.
62
+ Any edge attribute not present defaults to 1.
63
+ If this is a function, the weight of an edge is the value
64
+ returned by the function. The function must accept exactly
65
+ three positional arguments: the two endpoints of an edge and
66
+ the dictionary of edge attributes for that edge.
67
+ The function must return a number.
68
+
69
+ method : string, optional (default = 'dijkstra')
70
+ The algorithm to use to compute the path.
71
+ Supported options: 'dijkstra', 'bellman-ford'.
72
+ Other inputs produce a ValueError.
73
+ If `weight` is None, unweighted graph methods are used, and this
74
+ suggestion is ignored.
75
+
76
+ Returns
77
+ -------
78
+ path: list or dictionary
79
+ All returned paths include both the source and target in the path.
80
+
81
+ If the source and target are both specified, return a single list
82
+ of nodes in a shortest path from the source to the target.
83
+
84
+ If only the source is specified, return a dictionary keyed by
85
+ targets with a list of nodes in a shortest path from the source
86
+ to one of the targets.
87
+
88
+ If only the target is specified, return a dictionary keyed by
89
+ sources with a list of nodes in a shortest path from one of the
90
+ sources to the target.
91
+
92
+ If neither the source nor target are specified return a dictionary
93
+ of dictionaries with path[source][target]=[list of nodes in path].
94
+
95
+ Raises
96
+ ------
97
+ NodeNotFound
98
+ If `source` is not in `G`.
99
+
100
+ ValueError
101
+ If `method` is not among the supported options.
102
+
103
+ Examples
104
+ --------
105
+ >>> G = nx.path_graph(5)
106
+ >>> print(nx.shortest_path(G, source=0, target=4))
107
+ [0, 1, 2, 3, 4]
108
+ >>> p = nx.shortest_path(G, source=0) # target not specified
109
+ >>> p[3] # shortest path from source=0 to target=3
110
+ [0, 1, 2, 3]
111
+ >>> p = nx.shortest_path(G, target=4) # source not specified
112
+ >>> p[1] # shortest path from source=1 to target=4
113
+ [1, 2, 3, 4]
114
+ >>> p = dict(nx.shortest_path(G)) # source, target not specified
115
+ >>> p[2][4] # shortest path from source=2 to target=4
116
+ [2, 3, 4]
117
+
118
+ Notes
119
+ -----
120
+ There may be more than one shortest path between a source and target.
121
+ This returns only one of them.
122
+
123
+ See Also
124
+ --------
125
+ all_pairs_shortest_path
126
+ all_pairs_dijkstra_path
127
+ all_pairs_bellman_ford_path
128
+ single_source_shortest_path
129
+ single_source_dijkstra_path
130
+ single_source_bellman_ford_path
131
+ """
132
+ if method not in ("dijkstra", "bellman-ford"):
133
+ # so we don't need to check in each branch later
134
+ raise ValueError(f"method not supported: {method}")
135
+ method = "unweighted" if weight is None else method
136
+ if source is None:
137
+ if target is None:
138
+ warnings.warn(
139
+ (
140
+ "\n\nshortest_path will return an iterator that yields\n"
141
+ "(node, path) pairs instead of a dictionary when source\n"
142
+ "and target are unspecified beginning in version 3.5\n\n"
143
+ "To keep the current behavior, use:\n\n"
144
+ "\tdict(nx.shortest_path(G))"
145
+ ),
146
+ FutureWarning,
147
+ stacklevel=3,
148
+ )
149
+
150
+ # Find paths between all pairs.
151
+ if method == "unweighted":
152
+ paths = dict(nx.all_pairs_shortest_path(G))
153
+ elif method == "dijkstra":
154
+ paths = dict(nx.all_pairs_dijkstra_path(G, weight=weight))
155
+ else: # method == 'bellman-ford':
156
+ paths = dict(nx.all_pairs_bellman_ford_path(G, weight=weight))
157
+ else:
158
+ # Find paths from all nodes co-accessible to the target.
159
+ if G.is_directed():
160
+ G = G.reverse(copy=False)
161
+ if method == "unweighted":
162
+ paths = nx.single_source_shortest_path(G, target)
163
+ elif method == "dijkstra":
164
+ paths = nx.single_source_dijkstra_path(G, target, weight=weight)
165
+ else: # method == 'bellman-ford':
166
+ paths = nx.single_source_bellman_ford_path(G, target, weight=weight)
167
+ # Now flip the paths so they go from a source to the target.
168
+ for target in paths:
169
+ paths[target] = list(reversed(paths[target]))
170
+ else:
171
+ if target is None:
172
+ # Find paths to all nodes accessible from the source.
173
+ if method == "unweighted":
174
+ paths = nx.single_source_shortest_path(G, source)
175
+ elif method == "dijkstra":
176
+ paths = nx.single_source_dijkstra_path(G, source, weight=weight)
177
+ else: # method == 'bellman-ford':
178
+ paths = nx.single_source_bellman_ford_path(G, source, weight=weight)
179
+ else:
180
+ # Find shortest source-target path.
181
+ if method == "unweighted":
182
+ paths = nx.bidirectional_shortest_path(G, source, target)
183
+ elif method == "dijkstra":
184
+ _, paths = nx.bidirectional_dijkstra(G, source, target, weight)
185
+ else: # method == 'bellman-ford':
186
+ paths = nx.bellman_ford_path(G, source, target, weight)
187
+ return paths
188
+
189
+
190
+ @nx._dispatchable(edge_attrs="weight")
191
+ def shortest_path_length(G, source=None, target=None, weight=None, method="dijkstra"):
192
+ """Compute shortest path lengths in the graph.
193
+
194
+ Parameters
195
+ ----------
196
+ G : NetworkX graph
197
+
198
+ source : node, optional
199
+ Starting node for path.
200
+ If not specified, compute shortest path lengths using all nodes as
201
+ source nodes.
202
+
203
+ target : node, optional
204
+ Ending node for path.
205
+ If not specified, compute shortest path lengths using all nodes as
206
+ target nodes.
207
+
208
+ weight : None, string or function, optional (default = None)
209
+ If None, every edge has weight/distance/cost 1.
210
+ If a string, use this edge attribute as the edge weight.
211
+ Any edge attribute not present defaults to 1.
212
+ If this is a function, the weight of an edge is the value
213
+ returned by the function. The function must accept exactly
214
+ three positional arguments: the two endpoints of an edge and
215
+ the dictionary of edge attributes for that edge.
216
+ The function must return a number.
217
+
218
+ method : string, optional (default = 'dijkstra')
219
+ The algorithm to use to compute the path length.
220
+ Supported options: 'dijkstra', 'bellman-ford'.
221
+ Other inputs produce a ValueError.
222
+ If `weight` is None, unweighted graph methods are used, and this
223
+ suggestion is ignored.
224
+
225
+ Returns
226
+ -------
227
+ length: int or iterator
228
+ If the source and target are both specified, return the length of
229
+ the shortest path from the source to the target.
230
+
231
+ If only the source is specified, return a dict keyed by target
232
+ to the shortest path length from the source to that target.
233
+
234
+ If only the target is specified, return a dict keyed by source
235
+ to the shortest path length from that source to the target.
236
+
237
+ If neither the source nor target are specified, return an iterator
238
+ over (source, dictionary) where dictionary is keyed by target to
239
+ shortest path length from source to that target.
240
+
241
+ Raises
242
+ ------
243
+ NodeNotFound
244
+ If `source` is not in `G`.
245
+
246
+ NetworkXNoPath
247
+ If no path exists between source and target.
248
+
249
+ ValueError
250
+ If `method` is not among the supported options.
251
+
252
+ Examples
253
+ --------
254
+ >>> G = nx.path_graph(5)
255
+ >>> nx.shortest_path_length(G, source=0, target=4)
256
+ 4
257
+ >>> p = nx.shortest_path_length(G, source=0) # target not specified
258
+ >>> p[4]
259
+ 4
260
+ >>> p = nx.shortest_path_length(G, target=4) # source not specified
261
+ >>> p[0]
262
+ 4
263
+ >>> p = dict(nx.shortest_path_length(G)) # source,target not specified
264
+ >>> p[0][4]
265
+ 4
266
+
267
+ Notes
268
+ -----
269
+ The length of the path is always 1 less than the number of nodes involved
270
+ in the path since the length measures the number of edges followed.
271
+
272
+ For digraphs this returns the shortest directed path length. To find path
273
+ lengths in the reverse direction use G.reverse(copy=False) first to flip
274
+ the edge orientation.
275
+
276
+ See Also
277
+ --------
278
+ all_pairs_shortest_path_length
279
+ all_pairs_dijkstra_path_length
280
+ all_pairs_bellman_ford_path_length
281
+ single_source_shortest_path_length
282
+ single_source_dijkstra_path_length
283
+ single_source_bellman_ford_path_length
284
+ """
285
+ if method not in ("dijkstra", "bellman-ford"):
286
+ # so we don't need to check in each branch later
287
+ raise ValueError(f"method not supported: {method}")
288
+ method = "unweighted" if weight is None else method
289
+ if source is None:
290
+ if target is None:
291
+ # Find paths between all pairs.
292
+ if method == "unweighted":
293
+ paths = nx.all_pairs_shortest_path_length(G)
294
+ elif method == "dijkstra":
295
+ paths = nx.all_pairs_dijkstra_path_length(G, weight=weight)
296
+ else: # method == 'bellman-ford':
297
+ paths = nx.all_pairs_bellman_ford_path_length(G, weight=weight)
298
+ else:
299
+ # Find paths from all nodes co-accessible to the target.
300
+ if G.is_directed():
301
+ G = G.reverse(copy=False)
302
+ if method == "unweighted":
303
+ path_length = nx.single_source_shortest_path_length
304
+ paths = path_length(G, target)
305
+ elif method == "dijkstra":
306
+ path_length = nx.single_source_dijkstra_path_length
307
+ paths = path_length(G, target, weight=weight)
308
+ else: # method == 'bellman-ford':
309
+ path_length = nx.single_source_bellman_ford_path_length
310
+ paths = path_length(G, target, weight=weight)
311
+ else:
312
+ if target is None:
313
+ # Find paths to all nodes accessible from the source.
314
+ if method == "unweighted":
315
+ paths = nx.single_source_shortest_path_length(G, source)
316
+ elif method == "dijkstra":
317
+ path_length = nx.single_source_dijkstra_path_length
318
+ paths = path_length(G, source, weight=weight)
319
+ else: # method == 'bellman-ford':
320
+ path_length = nx.single_source_bellman_ford_path_length
321
+ paths = path_length(G, source, weight=weight)
322
+ else:
323
+ # Find shortest source-target path.
324
+ if method == "unweighted":
325
+ p = nx.bidirectional_shortest_path(G, source, target)
326
+ paths = len(p) - 1
327
+ elif method == "dijkstra":
328
+ paths = nx.dijkstra_path_length(G, source, target, weight)
329
+ else: # method == 'bellman-ford':
330
+ paths = nx.bellman_ford_path_length(G, source, target, weight)
331
+ return paths
332
+
333
+
334
+ @nx._dispatchable(edge_attrs="weight")
335
+ def average_shortest_path_length(G, weight=None, method=None):
336
+ r"""Returns the average shortest path length.
337
+
338
+ The average shortest path length is
339
+
340
+ .. math::
341
+
342
+ a =\sum_{\substack{s,t \in V \\ s\neq t}} \frac{d(s, t)}{n(n-1)}
343
+
344
+ where `V` is the set of nodes in `G`,
345
+ `d(s, t)` is the shortest path from `s` to `t`,
346
+ and `n` is the number of nodes in `G`.
347
+
348
+ .. versionchanged:: 3.0
349
+ An exception is raised for directed graphs that are not strongly
350
+ connected.
351
+
352
+ Parameters
353
+ ----------
354
+ G : NetworkX graph
355
+
356
+ weight : None, string or function, optional (default = None)
357
+ If None, every edge has weight/distance/cost 1.
358
+ If a string, use this edge attribute as the edge weight.
359
+ Any edge attribute not present defaults to 1.
360
+ If this is a function, the weight of an edge is the value
361
+ returned by the function. The function must accept exactly
362
+ three positional arguments: the two endpoints of an edge and
363
+ the dictionary of edge attributes for that edge.
364
+ The function must return a number.
365
+
366
+ method : string, optional (default = 'unweighted' or 'dijkstra')
367
+ The algorithm to use to compute the path lengths.
368
+ Supported options are 'unweighted', 'dijkstra', 'bellman-ford',
369
+ 'floyd-warshall' and 'floyd-warshall-numpy'.
370
+ Other method values produce a ValueError.
371
+ The default method is 'unweighted' if `weight` is None,
372
+ otherwise the default method is 'dijkstra'.
373
+
374
+ Raises
375
+ ------
376
+ NetworkXPointlessConcept
377
+ If `G` is the null graph (that is, the graph on zero nodes).
378
+
379
+ NetworkXError
380
+ If `G` is not connected (or not strongly connected, in the case
381
+ of a directed graph).
382
+
383
+ ValueError
384
+ If `method` is not among the supported options.
385
+
386
+ Examples
387
+ --------
388
+ >>> G = nx.path_graph(5)
389
+ >>> nx.average_shortest_path_length(G)
390
+ 2.0
391
+
392
+ For disconnected graphs, you can compute the average shortest path
393
+ length for each component
394
+
395
+ >>> G = nx.Graph([(1, 2), (3, 4)])
396
+ >>> for C in (G.subgraph(c).copy() for c in nx.connected_components(G)):
397
+ ... print(nx.average_shortest_path_length(C))
398
+ 1.0
399
+ 1.0
400
+
401
+ """
402
+ single_source_methods = ["unweighted", "dijkstra", "bellman-ford"]
403
+ all_pairs_methods = ["floyd-warshall", "floyd-warshall-numpy"]
404
+ supported_methods = single_source_methods + all_pairs_methods
405
+
406
+ if method is None:
407
+ method = "unweighted" if weight is None else "dijkstra"
408
+ if method not in supported_methods:
409
+ raise ValueError(f"method not supported: {method}")
410
+
411
+ n = len(G)
412
+ # For the special case of the null graph, raise an exception, since
413
+ # there are no paths in the null graph.
414
+ if n == 0:
415
+ msg = (
416
+ "the null graph has no paths, thus there is no average "
417
+ "shortest path length"
418
+ )
419
+ raise nx.NetworkXPointlessConcept(msg)
420
+ # For the special case of the trivial graph, return zero immediately.
421
+ if n == 1:
422
+ return 0
423
+ # Shortest path length is undefined if the graph is not strongly connected.
424
+ if G.is_directed() and not nx.is_strongly_connected(G):
425
+ raise nx.NetworkXError("Graph is not strongly connected.")
426
+ # Shortest path length is undefined if the graph is not connected.
427
+ if not G.is_directed() and not nx.is_connected(G):
428
+ raise nx.NetworkXError("Graph is not connected.")
429
+
430
+ # Compute all-pairs shortest paths.
431
+ def path_length(v):
432
+ if method == "unweighted":
433
+ return nx.single_source_shortest_path_length(G, v)
434
+ elif method == "dijkstra":
435
+ return nx.single_source_dijkstra_path_length(G, v, weight=weight)
436
+ elif method == "bellman-ford":
437
+ return nx.single_source_bellman_ford_path_length(G, v, weight=weight)
438
+
439
+ if method in single_source_methods:
440
+ # Sum the distances for each (ordered) pair of source and target node.
441
+ s = sum(l for u in G for l in path_length(u).values())
442
+ else:
443
+ if method == "floyd-warshall":
444
+ all_pairs = nx.floyd_warshall(G, weight=weight)
445
+ s = sum(sum(t.values()) for t in all_pairs.values())
446
+ elif method == "floyd-warshall-numpy":
447
+ s = float(nx.floyd_warshall_numpy(G, weight=weight).sum())
448
+ return s / (n * (n - 1))
449
+
450
+
451
+ @nx._dispatchable(edge_attrs="weight")
452
+ def all_shortest_paths(G, source, target, weight=None, method="dijkstra"):
453
+ """Compute all shortest simple paths in the graph.
454
+
455
+ Parameters
456
+ ----------
457
+ G : NetworkX graph
458
+
459
+ source : node
460
+ Starting node for path.
461
+
462
+ target : node
463
+ Ending node for path.
464
+
465
+ weight : None, string or function, optional (default = None)
466
+ If None, every edge has weight/distance/cost 1.
467
+ If a string, use this edge attribute as the edge weight.
468
+ Any edge attribute not present defaults to 1.
469
+ If this is a function, the weight of an edge is the value
470
+ returned by the function. The function must accept exactly
471
+ three positional arguments: the two endpoints of an edge and
472
+ the dictionary of edge attributes for that edge.
473
+ The function must return a number.
474
+
475
+ method : string, optional (default = 'dijkstra')
476
+ The algorithm to use to compute the path lengths.
477
+ Supported options: 'dijkstra', 'bellman-ford'.
478
+ Other inputs produce a ValueError.
479
+ If `weight` is None, unweighted graph methods are used, and this
480
+ suggestion is ignored.
481
+
482
+ Returns
483
+ -------
484
+ paths : generator of lists
485
+ A generator of all paths between source and target.
486
+
487
+ Raises
488
+ ------
489
+ ValueError
490
+ If `method` is not among the supported options.
491
+
492
+ NetworkXNoPath
493
+ If `target` cannot be reached from `source`.
494
+
495
+ Examples
496
+ --------
497
+ >>> G = nx.Graph()
498
+ >>> nx.add_path(G, [0, 1, 2])
499
+ >>> nx.add_path(G, [0, 10, 2])
500
+ >>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)])
501
+ [[0, 1, 2], [0, 10, 2]]
502
+
503
+ Notes
504
+ -----
505
+ There may be many shortest paths between the source and target. If G
506
+ contains zero-weight cycles, this function will not produce all shortest
507
+ paths because doing so would produce infinitely many paths of unbounded
508
+ length -- instead, we only produce the shortest simple paths.
509
+
510
+ See Also
511
+ --------
512
+ shortest_path
513
+ single_source_shortest_path
514
+ all_pairs_shortest_path
515
+ """
516
+ method = "unweighted" if weight is None else method
517
+ if method == "unweighted":
518
+ pred = nx.predecessor(G, source)
519
+ elif method == "dijkstra":
520
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight)
521
+ elif method == "bellman-ford":
522
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight)
523
+ else:
524
+ raise ValueError(f"method not supported: {method}")
525
+
526
+ return _build_paths_from_predecessors({source}, target, pred)
527
+
528
+
529
+ @nx._dispatchable(edge_attrs="weight")
530
+ def single_source_all_shortest_paths(G, source, weight=None, method="dijkstra"):
531
+ """Compute all shortest simple paths from the given source in the graph.
532
+
533
+ Parameters
534
+ ----------
535
+ G : NetworkX graph
536
+
537
+ source : node
538
+ Starting node for path.
539
+
540
+ weight : None, string or function, optional (default = None)
541
+ If None, every edge has weight/distance/cost 1.
542
+ If a string, use this edge attribute as the edge weight.
543
+ Any edge attribute not present defaults to 1.
544
+ If this is a function, the weight of an edge is the value
545
+ returned by the function. The function must accept exactly
546
+ three positional arguments: the two endpoints of an edge and
547
+ the dictionary of edge attributes for that edge.
548
+ The function must return a number.
549
+
550
+ method : string, optional (default = 'dijkstra')
551
+ The algorithm to use to compute the path lengths.
552
+ Supported options: 'dijkstra', 'bellman-ford'.
553
+ Other inputs produce a ValueError.
554
+ If `weight` is None, unweighted graph methods are used, and this
555
+ suggestion is ignored.
556
+
557
+ Returns
558
+ -------
559
+ paths : generator of dictionary
560
+ A generator of all paths between source and all nodes in the graph.
561
+
562
+ Raises
563
+ ------
564
+ ValueError
565
+ If `method` is not among the supported options.
566
+
567
+ Examples
568
+ --------
569
+ >>> G = nx.Graph()
570
+ >>> nx.add_path(G, [0, 1, 2, 3, 0])
571
+ >>> dict(nx.single_source_all_shortest_paths(G, source=0))
572
+ {0: [[0]], 1: [[0, 1]], 2: [[0, 1, 2], [0, 3, 2]], 3: [[0, 3]]}
573
+
574
+ Notes
575
+ -----
576
+ There may be many shortest paths between the source and target. If G
577
+ contains zero-weight cycles, this function will not produce all shortest
578
+ paths because doing so would produce infinitely many paths of unbounded
579
+ length -- instead, we only produce the shortest simple paths.
580
+
581
+ See Also
582
+ --------
583
+ shortest_path
584
+ all_shortest_paths
585
+ single_source_shortest_path
586
+ all_pairs_shortest_path
587
+ all_pairs_all_shortest_paths
588
+ """
589
+ method = "unweighted" if weight is None else method
590
+ if method == "unweighted":
591
+ pred = nx.predecessor(G, source)
592
+ elif method == "dijkstra":
593
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight)
594
+ elif method == "bellman-ford":
595
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight)
596
+ else:
597
+ raise ValueError(f"method not supported: {method}")
598
+ for n in G:
599
+ try:
600
+ yield n, list(_build_paths_from_predecessors({source}, n, pred))
601
+ except nx.NetworkXNoPath:
602
+ pass
603
+
604
+
605
+ @nx._dispatchable(edge_attrs="weight")
606
+ def all_pairs_all_shortest_paths(G, weight=None, method="dijkstra"):
607
+ """Compute all shortest paths between all nodes.
608
+
609
+ Parameters
610
+ ----------
611
+ G : NetworkX graph
612
+
613
+ weight : None, string or function, optional (default = None)
614
+ If None, every edge has weight/distance/cost 1.
615
+ If a string, use this edge attribute as the edge weight.
616
+ Any edge attribute not present defaults to 1.
617
+ If this is a function, the weight of an edge is the value
618
+ returned by the function. The function must accept exactly
619
+ three positional arguments: the two endpoints of an edge and
620
+ the dictionary of edge attributes for that edge.
621
+ The function must return a number.
622
+
623
+ method : string, optional (default = 'dijkstra')
624
+ The algorithm to use to compute the path lengths.
625
+ Supported options: 'dijkstra', 'bellman-ford'.
626
+ Other inputs produce a ValueError.
627
+ If `weight` is None, unweighted graph methods are used, and this
628
+ suggestion is ignored.
629
+
630
+ Returns
631
+ -------
632
+ paths : generator of dictionary
633
+ Dictionary of arrays, keyed by source and target, of all shortest paths.
634
+
635
+ Raises
636
+ ------
637
+ ValueError
638
+ If `method` is not among the supported options.
639
+
640
+ Examples
641
+ --------
642
+ >>> G = nx.cycle_graph(4)
643
+ >>> dict(nx.all_pairs_all_shortest_paths(G))[0][2]
644
+ [[0, 1, 2], [0, 3, 2]]
645
+ >>> dict(nx.all_pairs_all_shortest_paths(G))[0][3]
646
+ [[0, 3]]
647
+
648
+ Notes
649
+ -----
650
+ There may be multiple shortest paths with equal lengths. Unlike
651
+ all_pairs_shortest_path, this method returns all shortest paths.
652
+
653
+ See Also
654
+ --------
655
+ all_pairs_shortest_path
656
+ single_source_all_shortest_paths
657
+ """
658
+ for n in G:
659
+ yield (
660
+ n,
661
+ dict(single_source_all_shortest_paths(G, n, weight=weight, method=method)),
662
+ )
663
+
664
+
665
+ def _build_paths_from_predecessors(sources, target, pred):
666
+ """Compute all simple paths to target, given the predecessors found in
667
+ pred, terminating when any source in sources is found.
668
+
669
+ Parameters
670
+ ----------
671
+ sources : set
672
+ Starting nodes for path.
673
+
674
+ target : node
675
+ Ending node for path.
676
+
677
+ pred : dict
678
+ A dictionary of predecessor lists, keyed by node
679
+
680
+ Returns
681
+ -------
682
+ paths : generator of lists
683
+ A generator of all paths between source and target.
684
+
685
+ Raises
686
+ ------
687
+ NetworkXNoPath
688
+ If `target` cannot be reached from `source`.
689
+
690
+ Notes
691
+ -----
692
+ There may be many paths between the sources and target. If there are
693
+ cycles among the predecessors, this function will not produce all
694
+ possible paths because doing so would produce infinitely many paths
695
+ of unbounded length -- instead, we only produce simple paths.
696
+
697
+ See Also
698
+ --------
699
+ shortest_path
700
+ single_source_shortest_path
701
+ all_pairs_shortest_path
702
+ all_shortest_paths
703
+ bellman_ford_path
704
+ """
705
+ if target not in pred:
706
+ raise nx.NetworkXNoPath(f"Target {target} cannot be reached from given sources")
707
+
708
+ seen = {target}
709
+ stack = [[target, 0]]
710
+ top = 0
711
+ while top >= 0:
712
+ node, i = stack[top]
713
+ if node in sources:
714
+ yield [p for p, n in reversed(stack[: top + 1])]
715
+ if len(pred[node]) > i:
716
+ stack[top][1] = i + 1
717
+ next = pred[node][i]
718
+ if next in seen:
719
+ continue
720
+ else:
721
+ seen.add(next)
722
+ top += 1
723
+ if top == len(stack):
724
+ stack.append([next, 0])
725
+ else:
726
+ stack[top][:] = [next, 0]
727
+ else:
728
+ seen.discard(node)
729
+ top -= 1
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (205 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_generic.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_unweighted.cpython-310.pyc ADDED
Binary file (7.04 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/__pycache__/test_weighted.cpython-310.pyc ADDED
Binary file (30 kB). View file
 
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_astar.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import pairwise
5
+
6
+
7
+ class TestAStar:
8
+ @classmethod
9
+ def setup_class(cls):
10
+ edges = [
11
+ ("s", "u", 10),
12
+ ("s", "x", 5),
13
+ ("u", "v", 1),
14
+ ("u", "x", 2),
15
+ ("v", "y", 1),
16
+ ("x", "u", 3),
17
+ ("x", "v", 5),
18
+ ("x", "y", 2),
19
+ ("y", "s", 7),
20
+ ("y", "v", 6),
21
+ ]
22
+ cls.XG = nx.DiGraph()
23
+ cls.XG.add_weighted_edges_from(edges)
24
+
25
+ def test_multiple_optimal_paths(self):
26
+ """Tests that A* algorithm finds any of multiple optimal paths"""
27
+ heuristic_values = {"a": 1.35, "b": 1.18, "c": 0.67, "d": 0}
28
+
29
+ def h(u, v):
30
+ return heuristic_values[u]
31
+
32
+ graph = nx.Graph()
33
+ points = ["a", "b", "c", "d"]
34
+ edges = [("a", "b", 0.18), ("a", "c", 0.68), ("b", "c", 0.50), ("c", "d", 0.67)]
35
+
36
+ graph.add_nodes_from(points)
37
+ graph.add_weighted_edges_from(edges)
38
+
39
+ path1 = ["a", "c", "d"]
40
+ path2 = ["a", "b", "c", "d"]
41
+ assert nx.astar_path(graph, "a", "d", h) in (path1, path2)
42
+
43
+ def test_astar_directed(self):
44
+ assert nx.astar_path(self.XG, "s", "v") == ["s", "x", "u", "v"]
45
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
46
+
47
+ def test_astar_directed_weight_function(self):
48
+ w1 = lambda u, v, d: d["weight"]
49
+ assert nx.astar_path(self.XG, "x", "u", weight=w1) == ["x", "u"]
50
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w1) == 3
51
+ assert nx.astar_path(self.XG, "s", "v", weight=w1) == ["s", "x", "u", "v"]
52
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w1) == 9
53
+
54
+ w2 = lambda u, v, d: None if (u, v) == ("x", "u") else d["weight"]
55
+ assert nx.astar_path(self.XG, "x", "u", weight=w2) == ["x", "y", "s", "u"]
56
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w2) == 19
57
+ assert nx.astar_path(self.XG, "s", "v", weight=w2) == ["s", "x", "v"]
58
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w2) == 10
59
+
60
+ w3 = lambda u, v, d: d["weight"] + 10
61
+ assert nx.astar_path(self.XG, "x", "u", weight=w3) == ["x", "u"]
62
+ assert nx.astar_path_length(self.XG, "x", "u", weight=w3) == 13
63
+ assert nx.astar_path(self.XG, "s", "v", weight=w3) == ["s", "x", "v"]
64
+ assert nx.astar_path_length(self.XG, "s", "v", weight=w3) == 30
65
+
66
+ def test_astar_multigraph(self):
67
+ G = nx.MultiDiGraph(self.XG)
68
+ G.add_weighted_edges_from((u, v, 1000) for (u, v) in list(G.edges()))
69
+ assert nx.astar_path(G, "s", "v") == ["s", "x", "u", "v"]
70
+ assert nx.astar_path_length(G, "s", "v") == 9
71
+
72
+ def test_astar_undirected(self):
73
+ GG = self.XG.to_undirected()
74
+ # make sure we get lower weight
75
+ # to_undirected might choose either edge with weight 2 or weight 3
76
+ GG["u"]["x"]["weight"] = 2
77
+ GG["y"]["v"]["weight"] = 2
78
+ assert nx.astar_path(GG, "s", "v") == ["s", "x", "u", "v"]
79
+ assert nx.astar_path_length(GG, "s", "v") == 8
80
+
81
+ def test_astar_directed2(self):
82
+ XG2 = nx.DiGraph()
83
+ edges = [
84
+ (1, 4, 1),
85
+ (4, 5, 1),
86
+ (5, 6, 1),
87
+ (6, 3, 1),
88
+ (1, 3, 50),
89
+ (1, 2, 100),
90
+ (2, 3, 100),
91
+ ]
92
+ XG2.add_weighted_edges_from(edges)
93
+ assert nx.astar_path(XG2, 1, 3) == [1, 4, 5, 6, 3]
94
+
95
+ def test_astar_undirected2(self):
96
+ XG3 = nx.Graph()
97
+ edges = [(0, 1, 2), (1, 2, 12), (2, 3, 1), (3, 4, 5), (4, 5, 1), (5, 0, 10)]
98
+ XG3.add_weighted_edges_from(edges)
99
+ assert nx.astar_path(XG3, 0, 3) == [0, 1, 2, 3]
100
+ assert nx.astar_path_length(XG3, 0, 3) == 15
101
+
102
+ def test_astar_undirected3(self):
103
+ XG4 = nx.Graph()
104
+ edges = [
105
+ (0, 1, 2),
106
+ (1, 2, 2),
107
+ (2, 3, 1),
108
+ (3, 4, 1),
109
+ (4, 5, 1),
110
+ (5, 6, 1),
111
+ (6, 7, 1),
112
+ (7, 0, 1),
113
+ ]
114
+ XG4.add_weighted_edges_from(edges)
115
+ assert nx.astar_path(XG4, 0, 2) == [0, 1, 2]
116
+ assert nx.astar_path_length(XG4, 0, 2) == 4
117
+
118
+ """ Tests that A* finds correct path when multiple paths exist
119
+ and the best one is not expanded first (GH issue #3464)
120
+ """
121
+
122
+ def test_astar_directed3(self):
123
+ heuristic_values = {"n5": 36, "n2": 4, "n1": 0, "n0": 0}
124
+
125
+ def h(u, v):
126
+ return heuristic_values[u]
127
+
128
+ edges = [("n5", "n1", 11), ("n5", "n2", 9), ("n2", "n1", 1), ("n1", "n0", 32)]
129
+ graph = nx.DiGraph()
130
+ graph.add_weighted_edges_from(edges)
131
+ answer = ["n5", "n2", "n1", "n0"]
132
+ assert nx.astar_path(graph, "n5", "n0", h) == answer
133
+
134
+ """ Tests that parent is not wrongly overridden when a node
135
+ is re-explored multiple times.
136
+ """
137
+
138
+ def test_astar_directed4(self):
139
+ edges = [
140
+ ("a", "b", 1),
141
+ ("a", "c", 1),
142
+ ("b", "d", 2),
143
+ ("c", "d", 1),
144
+ ("d", "e", 1),
145
+ ]
146
+ graph = nx.DiGraph()
147
+ graph.add_weighted_edges_from(edges)
148
+ assert nx.astar_path(graph, "a", "e") == ["a", "c", "d", "e"]
149
+
150
+ # >>> MXG4=NX.MultiGraph(XG4)
151
+ # >>> MXG4.add_edge(0,1,3)
152
+ # >>> NX.dijkstra_path(MXG4,0,2)
153
+ # [0, 1, 2]
154
+
155
+ def test_astar_w1(self):
156
+ G = nx.DiGraph()
157
+ G.add_edges_from(
158
+ [
159
+ ("s", "u"),
160
+ ("s", "x"),
161
+ ("u", "v"),
162
+ ("u", "x"),
163
+ ("v", "y"),
164
+ ("x", "u"),
165
+ ("x", "w"),
166
+ ("w", "v"),
167
+ ("x", "y"),
168
+ ("y", "s"),
169
+ ("y", "v"),
170
+ ]
171
+ )
172
+ assert nx.astar_path(G, "s", "v") == ["s", "u", "v"]
173
+ assert nx.astar_path_length(G, "s", "v") == 2
174
+
175
+ def test_astar_nopath(self):
176
+ with pytest.raises(nx.NodeNotFound):
177
+ nx.astar_path(self.XG, "s", "moon")
178
+
179
+ def test_astar_cutoff(self):
180
+ with pytest.raises(nx.NetworkXNoPath):
181
+ # optimal path_length in XG is 9
182
+ nx.astar_path(self.XG, "s", "v", cutoff=8.0)
183
+ with pytest.raises(nx.NetworkXNoPath):
184
+ nx.astar_path_length(self.XG, "s", "v", cutoff=8.0)
185
+
186
+ def test_astar_admissible_heuristic_with_cutoff(self):
187
+ heuristic_values = {"s": 36, "y": 4, "x": 0, "u": 0, "v": 0}
188
+
189
+ def h(u, v):
190
+ return heuristic_values[u]
191
+
192
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
193
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h) == 9
194
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=12) == 9
195
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=9) == 9
196
+ with pytest.raises(nx.NetworkXNoPath):
197
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=8)
198
+
199
+ def test_astar_inadmissible_heuristic_with_cutoff(self):
200
+ heuristic_values = {"s": 36, "y": 14, "x": 10, "u": 10, "v": 0}
201
+
202
+ def h(u, v):
203
+ return heuristic_values[u]
204
+
205
+ # optimal path_length in XG is 9. This heuristic gives over-estimate.
206
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h) == 10
207
+ assert nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=15) == 10
208
+ with pytest.raises(nx.NetworkXNoPath):
209
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=9)
210
+ with pytest.raises(nx.NetworkXNoPath):
211
+ nx.astar_path_length(self.XG, "s", "v", heuristic=h, cutoff=12)
212
+
213
+ def test_astar_cutoff2(self):
214
+ assert nx.astar_path(self.XG, "s", "v", cutoff=10.0) == ["s", "x", "u", "v"]
215
+ assert nx.astar_path_length(self.XG, "s", "v") == 9
216
+
217
+ def test_cycle(self):
218
+ C = nx.cycle_graph(7)
219
+ assert nx.astar_path(C, 0, 3) == [0, 1, 2, 3]
220
+ assert nx.dijkstra_path(C, 0, 4) == [0, 6, 5, 4]
221
+
222
+ def test_unorderable_nodes(self):
223
+ """Tests that A* accommodates nodes that are not orderable.
224
+
225
+ For more information, see issue #554.
226
+
227
+ """
228
+ # Create the cycle graph on four nodes, with nodes represented
229
+ # as (unorderable) Python objects.
230
+ nodes = [object() for n in range(4)]
231
+ G = nx.Graph()
232
+ G.add_edges_from(pairwise(nodes, cyclic=True))
233
+ path = nx.astar_path(G, nodes[0], nodes[2])
234
+ assert len(path) == 3
235
+
236
+ def test_astar_NetworkXNoPath(self):
237
+ """Tests that exception is raised when there exists no
238
+ path between source and target"""
239
+ G = nx.gnp_random_graph(10, 0.2, seed=10)
240
+ with pytest.raises(nx.NetworkXNoPath):
241
+ nx.astar_path(G, 4, 9)
242
+
243
+ def test_astar_NodeNotFound(self):
244
+ """Tests that exception is raised when either
245
+ source or target is not in graph"""
246
+ G = nx.gnp_random_graph(10, 0.2, seed=10)
247
+ with pytest.raises(nx.NodeNotFound):
248
+ nx.astar_path_length(G, 11, 9)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestFloyd:
7
+ @classmethod
8
+ def setup_class(cls):
9
+ pass
10
+
11
+ def test_floyd_warshall_predecessor_and_distance(self):
12
+ XG = nx.DiGraph()
13
+ XG.add_weighted_edges_from(
14
+ [
15
+ ("s", "u", 10),
16
+ ("s", "x", 5),
17
+ ("u", "v", 1),
18
+ ("u", "x", 2),
19
+ ("v", "y", 1),
20
+ ("x", "u", 3),
21
+ ("x", "v", 5),
22
+ ("x", "y", 2),
23
+ ("y", "s", 7),
24
+ ("y", "v", 6),
25
+ ]
26
+ )
27
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
28
+ assert dist["s"]["v"] == 9
29
+ assert path["s"]["v"] == "u"
30
+ assert dist == {
31
+ "y": {"y": 0, "x": 12, "s": 7, "u": 15, "v": 6},
32
+ "x": {"y": 2, "x": 0, "s": 9, "u": 3, "v": 4},
33
+ "s": {"y": 7, "x": 5, "s": 0, "u": 8, "v": 9},
34
+ "u": {"y": 2, "x": 2, "s": 9, "u": 0, "v": 1},
35
+ "v": {"y": 1, "x": 13, "s": 8, "u": 16, "v": 0},
36
+ }
37
+
38
+ GG = XG.to_undirected()
39
+ # make sure we get lower weight
40
+ # to_undirected might choose either edge with weight 2 or weight 3
41
+ GG["u"]["x"]["weight"] = 2
42
+ path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
43
+ assert dist["s"]["v"] == 8
44
+ # skip this test, could be alternate path s-u-v
45
+ # assert_equal(path['s']['v'],'y')
46
+
47
+ G = nx.DiGraph() # no weights
48
+ G.add_edges_from(
49
+ [
50
+ ("s", "u"),
51
+ ("s", "x"),
52
+ ("u", "v"),
53
+ ("u", "x"),
54
+ ("v", "y"),
55
+ ("x", "u"),
56
+ ("x", "v"),
57
+ ("x", "y"),
58
+ ("y", "s"),
59
+ ("y", "v"),
60
+ ]
61
+ )
62
+ path, dist = nx.floyd_warshall_predecessor_and_distance(G)
63
+ assert dist["s"]["v"] == 2
64
+ # skip this test, could be alternate path s-u-v
65
+ # assert_equal(path['s']['v'],'x')
66
+
67
+ # alternate interface
68
+ dist = nx.floyd_warshall(G)
69
+ assert dist["s"]["v"] == 2
70
+
71
+ # floyd_warshall_predecessor_and_distance returns
72
+ # dicts-of-defautdicts
73
+ # make sure we don't get empty dictionary
74
+ XG = nx.DiGraph()
75
+ XG.add_weighted_edges_from(
76
+ [("v", "x", 5.0), ("y", "x", 5.0), ("v", "y", 6.0), ("x", "u", 2.0)]
77
+ )
78
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
79
+ inf = float("inf")
80
+ assert dist == {
81
+ "v": {"v": 0, "x": 5.0, "y": 6.0, "u": 7.0},
82
+ "x": {"x": 0, "u": 2.0, "v": inf, "y": inf},
83
+ "y": {"y": 0, "x": 5.0, "v": inf, "u": 7.0},
84
+ "u": {"u": 0, "v": inf, "x": inf, "y": inf},
85
+ }
86
+ assert path == {
87
+ "v": {"x": "v", "y": "v", "u": "x"},
88
+ "x": {"u": "x"},
89
+ "y": {"x": "y", "u": "x"},
90
+ }
91
+
92
+ def test_reconstruct_path(self):
93
+ with pytest.raises(KeyError):
94
+ XG = nx.DiGraph()
95
+ XG.add_weighted_edges_from(
96
+ [
97
+ ("s", "u", 10),
98
+ ("s", "x", 5),
99
+ ("u", "v", 1),
100
+ ("u", "x", 2),
101
+ ("v", "y", 1),
102
+ ("x", "u", 3),
103
+ ("x", "v", 5),
104
+ ("x", "y", 2),
105
+ ("y", "s", 7),
106
+ ("y", "v", 6),
107
+ ]
108
+ )
109
+ predecessors, _ = nx.floyd_warshall_predecessor_and_distance(XG)
110
+
111
+ path = nx.reconstruct_path("s", "v", predecessors)
112
+ assert path == ["s", "x", "u", "v"]
113
+
114
+ path = nx.reconstruct_path("s", "s", predecessors)
115
+ assert path == []
116
+
117
+ # this part raises the keyError
118
+ nx.reconstruct_path("1", "2", predecessors)
119
+
120
+ def test_cycle(self):
121
+ path, dist = nx.floyd_warshall_predecessor_and_distance(nx.cycle_graph(7))
122
+ assert dist[0][3] == 3
123
+ assert path[0][3] == 2
124
+ assert dist[0][4] == 3
125
+
126
+ def test_weighted(self):
127
+ XG3 = nx.Graph()
128
+ XG3.add_weighted_edges_from(
129
+ [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
130
+ )
131
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG3)
132
+ assert dist[0][3] == 15
133
+ assert path[0][3] == 2
134
+
135
+ def test_weighted2(self):
136
+ XG4 = nx.Graph()
137
+ XG4.add_weighted_edges_from(
138
+ [
139
+ [0, 1, 2],
140
+ [1, 2, 2],
141
+ [2, 3, 1],
142
+ [3, 4, 1],
143
+ [4, 5, 1],
144
+ [5, 6, 1],
145
+ [6, 7, 1],
146
+ [7, 0, 1],
147
+ ]
148
+ )
149
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG4)
150
+ assert dist[0][2] == 4
151
+ assert path[0][2] == 1
152
+
153
+ def test_weight_parameter(self):
154
+ XG4 = nx.Graph()
155
+ XG4.add_edges_from(
156
+ [
157
+ (0, 1, {"heavy": 2}),
158
+ (1, 2, {"heavy": 2}),
159
+ (2, 3, {"heavy": 1}),
160
+ (3, 4, {"heavy": 1}),
161
+ (4, 5, {"heavy": 1}),
162
+ (5, 6, {"heavy": 1}),
163
+ (6, 7, {"heavy": 1}),
164
+ (7, 0, {"heavy": 1}),
165
+ ]
166
+ )
167
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG4, weight="heavy")
168
+ assert dist[0][2] == 4
169
+ assert path[0][2] == 1
170
+
171
+ def test_zero_distance(self):
172
+ XG = nx.DiGraph()
173
+ XG.add_weighted_edges_from(
174
+ [
175
+ ("s", "u", 10),
176
+ ("s", "x", 5),
177
+ ("u", "v", 1),
178
+ ("u", "x", 2),
179
+ ("v", "y", 1),
180
+ ("x", "u", 3),
181
+ ("x", "v", 5),
182
+ ("x", "y", 2),
183
+ ("y", "s", 7),
184
+ ("y", "v", 6),
185
+ ]
186
+ )
187
+ path, dist = nx.floyd_warshall_predecessor_and_distance(XG)
188
+
189
+ for u in XG:
190
+ assert dist[u][u] == 0
191
+
192
+ GG = XG.to_undirected()
193
+ # make sure we get lower weight
194
+ # to_undirected might choose either edge with weight 2 or weight 3
195
+ GG["u"]["x"]["weight"] = 2
196
+ path, dist = nx.floyd_warshall_predecessor_and_distance(GG)
197
+
198
+ for u in GG:
199
+ dist[u][u] = 0
200
+
201
+ def test_zero_weight(self):
202
+ G = nx.DiGraph()
203
+ edges = [(1, 2, -2), (2, 3, -4), (1, 5, 1), (5, 4, 0), (4, 3, -5), (2, 5, -7)]
204
+ G.add_weighted_edges_from(edges)
205
+ dist = nx.floyd_warshall(G)
206
+ assert dist[1][3] == -14
207
+
208
+ G = nx.MultiDiGraph()
209
+ edges.append((2, 5, -7))
210
+ G.add_weighted_edges_from(edges)
211
+ dist = nx.floyd_warshall(G)
212
+ assert dist[1][3] == -14
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+
5
+
6
+ import networkx as nx
7
+
8
+
9
+ def test_cycle_numpy():
10
+ dist = nx.floyd_warshall_numpy(nx.cycle_graph(7))
11
+ assert dist[0, 3] == 3
12
+ assert dist[0, 4] == 3
13
+
14
+
15
+ def test_weighted_numpy_three_edges():
16
+ XG3 = nx.Graph()
17
+ XG3.add_weighted_edges_from(
18
+ [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
19
+ )
20
+ dist = nx.floyd_warshall_numpy(XG3)
21
+ assert dist[0, 3] == 15
22
+
23
+
24
+ def test_weighted_numpy_two_edges():
25
+ XG4 = nx.Graph()
26
+ XG4.add_weighted_edges_from(
27
+ [
28
+ [0, 1, 2],
29
+ [1, 2, 2],
30
+ [2, 3, 1],
31
+ [3, 4, 1],
32
+ [4, 5, 1],
33
+ [5, 6, 1],
34
+ [6, 7, 1],
35
+ [7, 0, 1],
36
+ ]
37
+ )
38
+ dist = nx.floyd_warshall_numpy(XG4)
39
+ assert dist[0, 2] == 4
40
+
41
+
42
+ def test_weight_parameter_numpy():
43
+ XG4 = nx.Graph()
44
+ XG4.add_edges_from(
45
+ [
46
+ (0, 1, {"heavy": 2}),
47
+ (1, 2, {"heavy": 2}),
48
+ (2, 3, {"heavy": 1}),
49
+ (3, 4, {"heavy": 1}),
50
+ (4, 5, {"heavy": 1}),
51
+ (5, 6, {"heavy": 1}),
52
+ (6, 7, {"heavy": 1}),
53
+ (7, 0, {"heavy": 1}),
54
+ ]
55
+ )
56
+ dist = nx.floyd_warshall_numpy(XG4, weight="heavy")
57
+ assert dist[0, 2] == 4
58
+
59
+
60
+ def test_directed_cycle_numpy():
61
+ G = nx.DiGraph()
62
+ nx.add_cycle(G, [0, 1, 2, 3])
63
+ pred, dist = nx.floyd_warshall_predecessor_and_distance(G)
64
+ D = nx.utils.dict_to_numpy_array(dist)
65
+ np.testing.assert_equal(nx.floyd_warshall_numpy(G), D)
66
+
67
+
68
+ def test_zero_weight():
69
+ G = nx.DiGraph()
70
+ edges = [(1, 2, -2), (2, 3, -4), (1, 5, 1), (5, 4, 0), (4, 3, -5), (2, 5, -7)]
71
+ G.add_weighted_edges_from(edges)
72
+ dist = nx.floyd_warshall_numpy(G)
73
+ assert int(np.min(dist)) == -14
74
+
75
+ G = nx.MultiDiGraph()
76
+ edges.append((2, 5, -7))
77
+ G.add_weighted_edges_from(edges)
78
+ dist = nx.floyd_warshall_numpy(G)
79
+ assert int(np.min(dist)) == -14
80
+
81
+
82
+ def test_nodelist():
83
+ G = nx.path_graph(7)
84
+ dist = nx.floyd_warshall_numpy(G, nodelist=[3, 5, 4, 6, 2, 1, 0])
85
+ assert dist[0, 3] == 3
86
+ assert dist[0, 1] == 2
87
+ assert dist[6, 2] == 4
88
+ pytest.raises(nx.NetworkXError, nx.floyd_warshall_numpy, G, [1, 3])
89
+ pytest.raises(nx.NetworkXError, nx.floyd_warshall_numpy, G, list(range(9)))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_generic.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def validate_grid_path(r, c, s, t, p):
7
+ assert isinstance(p, list)
8
+ assert p[0] == s
9
+ assert p[-1] == t
10
+ s = ((s - 1) // c, (s - 1) % c)
11
+ t = ((t - 1) // c, (t - 1) % c)
12
+ assert len(p) == abs(t[0] - s[0]) + abs(t[1] - s[1]) + 1
13
+ p = [((u - 1) // c, (u - 1) % c) for u in p]
14
+ for u in p:
15
+ assert 0 <= u[0] < r
16
+ assert 0 <= u[1] < c
17
+ for u, v in zip(p[:-1], p[1:]):
18
+ assert (abs(v[0] - u[0]), abs(v[1] - u[1])) in [(0, 1), (1, 0)]
19
+
20
+
21
+ class TestGenericPath:
22
+ @classmethod
23
+ def setup_class(cls):
24
+ from networkx import convert_node_labels_to_integers as cnlti
25
+
26
+ cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
27
+ cls.cycle = nx.cycle_graph(7)
28
+ cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
29
+ cls.neg_weights = nx.DiGraph()
30
+ cls.neg_weights.add_edge(0, 1, weight=1)
31
+ cls.neg_weights.add_edge(0, 2, weight=3)
32
+ cls.neg_weights.add_edge(1, 3, weight=1)
33
+ cls.neg_weights.add_edge(2, 3, weight=-2)
34
+
35
+ def test_shortest_path(self):
36
+ assert nx.shortest_path(self.cycle, 0, 3) == [0, 1, 2, 3]
37
+ assert nx.shortest_path(self.cycle, 0, 4) == [0, 6, 5, 4]
38
+ validate_grid_path(4, 4, 1, 12, nx.shortest_path(self.grid, 1, 12))
39
+ assert nx.shortest_path(self.directed_cycle, 0, 3) == [0, 1, 2, 3]
40
+ # now with weights
41
+ assert nx.shortest_path(self.cycle, 0, 3, weight="weight") == [0, 1, 2, 3]
42
+ assert nx.shortest_path(self.cycle, 0, 4, weight="weight") == [0, 6, 5, 4]
43
+ validate_grid_path(
44
+ 4, 4, 1, 12, nx.shortest_path(self.grid, 1, 12, weight="weight")
45
+ )
46
+ assert nx.shortest_path(self.directed_cycle, 0, 3, weight="weight") == [
47
+ 0,
48
+ 1,
49
+ 2,
50
+ 3,
51
+ ]
52
+ # weights and method specified
53
+ assert nx.shortest_path(
54
+ self.directed_cycle, 0, 3, weight="weight", method="dijkstra"
55
+ ) == [0, 1, 2, 3]
56
+ assert nx.shortest_path(
57
+ self.directed_cycle, 0, 3, weight="weight", method="bellman-ford"
58
+ ) == [0, 1, 2, 3]
59
+ # when Dijkstra's will probably (depending on precise implementation)
60
+ # incorrectly return [0, 1, 3] instead
61
+ assert nx.shortest_path(
62
+ self.neg_weights, 0, 3, weight="weight", method="bellman-ford"
63
+ ) == [0, 2, 3]
64
+ # confirm bad method rejection
65
+ pytest.raises(ValueError, nx.shortest_path, self.cycle, method="SPAM")
66
+ # confirm absent source rejection
67
+ pytest.raises(nx.NodeNotFound, nx.shortest_path, self.cycle, 8)
68
+
69
+ def test_shortest_path_target(self):
70
+ answer = {0: [0, 1], 1: [1], 2: [2, 1]}
71
+ sp = nx.shortest_path(nx.path_graph(3), target=1)
72
+ assert sp == answer
73
+ # with weights
74
+ sp = nx.shortest_path(nx.path_graph(3), target=1, weight="weight")
75
+ assert sp == answer
76
+ # weights and method specified
77
+ sp = nx.shortest_path(
78
+ nx.path_graph(3), target=1, weight="weight", method="dijkstra"
79
+ )
80
+ assert sp == answer
81
+ sp = nx.shortest_path(
82
+ nx.path_graph(3), target=1, weight="weight", method="bellman-ford"
83
+ )
84
+ assert sp == answer
85
+
86
+ def test_shortest_path_length(self):
87
+ assert nx.shortest_path_length(self.cycle, 0, 3) == 3
88
+ assert nx.shortest_path_length(self.grid, 1, 12) == 5
89
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4) == 4
90
+ # now with weights
91
+ assert nx.shortest_path_length(self.cycle, 0, 3, weight="weight") == 3
92
+ assert nx.shortest_path_length(self.grid, 1, 12, weight="weight") == 5
93
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4, weight="weight") == 4
94
+ # weights and method specified
95
+ assert (
96
+ nx.shortest_path_length(
97
+ self.cycle, 0, 3, weight="weight", method="dijkstra"
98
+ )
99
+ == 3
100
+ )
101
+ assert (
102
+ nx.shortest_path_length(
103
+ self.cycle, 0, 3, weight="weight", method="bellman-ford"
104
+ )
105
+ == 3
106
+ )
107
+ # confirm bad method rejection
108
+ pytest.raises(ValueError, nx.shortest_path_length, self.cycle, method="SPAM")
109
+ # confirm absent source rejection
110
+ pytest.raises(nx.NodeNotFound, nx.shortest_path_length, self.cycle, 8)
111
+
112
+ def test_shortest_path_length_target(self):
113
+ answer = {0: 1, 1: 0, 2: 1}
114
+ sp = dict(nx.shortest_path_length(nx.path_graph(3), target=1))
115
+ assert sp == answer
116
+ # with weights
117
+ sp = nx.shortest_path_length(nx.path_graph(3), target=1, weight="weight")
118
+ assert sp == answer
119
+ # weights and method specified
120
+ sp = nx.shortest_path_length(
121
+ nx.path_graph(3), target=1, weight="weight", method="dijkstra"
122
+ )
123
+ assert sp == answer
124
+ sp = nx.shortest_path_length(
125
+ nx.path_graph(3), target=1, weight="weight", method="bellman-ford"
126
+ )
127
+ assert sp == answer
128
+
129
+ def test_single_source_shortest_path(self):
130
+ p = nx.shortest_path(self.cycle, 0)
131
+ assert p[3] == [0, 1, 2, 3]
132
+ assert p == nx.single_source_shortest_path(self.cycle, 0)
133
+ p = nx.shortest_path(self.grid, 1)
134
+ validate_grid_path(4, 4, 1, 12, p[12])
135
+ # now with weights
136
+ p = nx.shortest_path(self.cycle, 0, weight="weight")
137
+ assert p[3] == [0, 1, 2, 3]
138
+ assert p == nx.single_source_dijkstra_path(self.cycle, 0)
139
+ p = nx.shortest_path(self.grid, 1, weight="weight")
140
+ validate_grid_path(4, 4, 1, 12, p[12])
141
+ # weights and method specified
142
+ p = nx.shortest_path(self.cycle, 0, method="dijkstra", weight="weight")
143
+ assert p[3] == [0, 1, 2, 3]
144
+ assert p == nx.single_source_shortest_path(self.cycle, 0)
145
+ p = nx.shortest_path(self.cycle, 0, method="bellman-ford", weight="weight")
146
+ assert p[3] == [0, 1, 2, 3]
147
+ assert p == nx.single_source_shortest_path(self.cycle, 0)
148
+
149
+ def test_single_source_shortest_path_length(self):
150
+ ans = dict(nx.shortest_path_length(self.cycle, 0))
151
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
152
+ assert ans == dict(nx.single_source_shortest_path_length(self.cycle, 0))
153
+ ans = dict(nx.shortest_path_length(self.grid, 1))
154
+ assert ans[16] == 6
155
+ # now with weights
156
+ ans = dict(nx.shortest_path_length(self.cycle, 0, weight="weight"))
157
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
158
+ assert ans == dict(nx.single_source_dijkstra_path_length(self.cycle, 0))
159
+ ans = dict(nx.shortest_path_length(self.grid, 1, weight="weight"))
160
+ assert ans[16] == 6
161
+ # weights and method specified
162
+ ans = dict(
163
+ nx.shortest_path_length(self.cycle, 0, weight="weight", method="dijkstra")
164
+ )
165
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
166
+ assert ans == dict(nx.single_source_dijkstra_path_length(self.cycle, 0))
167
+ ans = dict(
168
+ nx.shortest_path_length(
169
+ self.cycle, 0, weight="weight", method="bellman-ford"
170
+ )
171
+ )
172
+ assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
173
+ assert ans == dict(nx.single_source_bellman_ford_path_length(self.cycle, 0))
174
+
175
+ def test_single_source_all_shortest_paths(self):
176
+ cycle_ans = {0: [[0]], 1: [[0, 1]], 2: [[0, 1, 2], [0, 3, 2]], 3: [[0, 3]]}
177
+ ans = dict(nx.single_source_all_shortest_paths(nx.cycle_graph(4), 0))
178
+ assert sorted(ans[2]) == cycle_ans[2]
179
+ ans = dict(nx.single_source_all_shortest_paths(self.grid, 1))
180
+ grid_ans = [
181
+ [1, 2, 3, 7, 11],
182
+ [1, 2, 6, 7, 11],
183
+ [1, 2, 6, 10, 11],
184
+ [1, 5, 6, 7, 11],
185
+ [1, 5, 6, 10, 11],
186
+ [1, 5, 9, 10, 11],
187
+ ]
188
+ assert sorted(ans[11]) == grid_ans
189
+ ans = dict(
190
+ nx.single_source_all_shortest_paths(nx.cycle_graph(4), 0, weight="weight")
191
+ )
192
+ assert sorted(ans[2]) == cycle_ans[2]
193
+ ans = dict(
194
+ nx.single_source_all_shortest_paths(
195
+ nx.cycle_graph(4), 0, method="bellman-ford", weight="weight"
196
+ )
197
+ )
198
+ assert sorted(ans[2]) == cycle_ans[2]
199
+ ans = dict(nx.single_source_all_shortest_paths(self.grid, 1, weight="weight"))
200
+ assert sorted(ans[11]) == grid_ans
201
+ ans = dict(
202
+ nx.single_source_all_shortest_paths(
203
+ self.grid, 1, method="bellman-ford", weight="weight"
204
+ )
205
+ )
206
+ assert sorted(ans[11]) == grid_ans
207
+ G = nx.cycle_graph(4)
208
+ G.add_node(4)
209
+ ans = dict(nx.single_source_all_shortest_paths(G, 0))
210
+ assert sorted(ans[2]) == [[0, 1, 2], [0, 3, 2]]
211
+ ans = dict(nx.single_source_all_shortest_paths(G, 4))
212
+ assert sorted(ans[4]) == [[4]]
213
+
214
+ def test_all_pairs_shortest_path(self):
215
+ # shortest_path w/o source and target will return a generator instead of
216
+ # a dict beginning in version 3.5. Only the first call needs changed here.
217
+ p = nx.shortest_path(self.cycle)
218
+ assert p[0][3] == [0, 1, 2, 3]
219
+ assert p == dict(nx.all_pairs_shortest_path(self.cycle))
220
+ p = dict(nx.shortest_path(self.grid))
221
+ validate_grid_path(4, 4, 1, 12, p[1][12])
222
+ # now with weights
223
+ p = dict(nx.shortest_path(self.cycle, weight="weight"))
224
+ assert p[0][3] == [0, 1, 2, 3]
225
+ assert p == dict(nx.all_pairs_dijkstra_path(self.cycle))
226
+ p = dict(nx.shortest_path(self.grid, weight="weight"))
227
+ validate_grid_path(4, 4, 1, 12, p[1][12])
228
+ # weights and method specified
229
+ p = dict(nx.shortest_path(self.cycle, weight="weight", method="dijkstra"))
230
+ assert p[0][3] == [0, 1, 2, 3]
231
+ assert p == dict(nx.all_pairs_dijkstra_path(self.cycle))
232
+ p = dict(nx.shortest_path(self.cycle, weight="weight", method="bellman-ford"))
233
+ assert p[0][3] == [0, 1, 2, 3]
234
+ assert p == dict(nx.all_pairs_bellman_ford_path(self.cycle))
235
+
236
+ def test_all_pairs_shortest_path_length(self):
237
+ ans = dict(nx.shortest_path_length(self.cycle))
238
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
239
+ assert ans == dict(nx.all_pairs_shortest_path_length(self.cycle))
240
+ ans = dict(nx.shortest_path_length(self.grid))
241
+ assert ans[1][16] == 6
242
+ # now with weights
243
+ ans = dict(nx.shortest_path_length(self.cycle, weight="weight"))
244
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
245
+ assert ans == dict(nx.all_pairs_dijkstra_path_length(self.cycle))
246
+ ans = dict(nx.shortest_path_length(self.grid, weight="weight"))
247
+ assert ans[1][16] == 6
248
+ # weights and method specified
249
+ ans = dict(
250
+ nx.shortest_path_length(self.cycle, weight="weight", method="dijkstra")
251
+ )
252
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
253
+ assert ans == dict(nx.all_pairs_dijkstra_path_length(self.cycle))
254
+ ans = dict(
255
+ nx.shortest_path_length(self.cycle, weight="weight", method="bellman-ford")
256
+ )
257
+ assert ans[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
258
+ assert ans == dict(nx.all_pairs_bellman_ford_path_length(self.cycle))
259
+
260
+ def test_all_pairs_all_shortest_paths(self):
261
+ ans = dict(nx.all_pairs_all_shortest_paths(nx.cycle_graph(4)))
262
+ assert sorted(ans[1][3]) == [[1, 0, 3], [1, 2, 3]]
263
+ ans = dict(nx.all_pairs_all_shortest_paths(nx.cycle_graph(4)), weight="weight")
264
+ assert sorted(ans[1][3]) == [[1, 0, 3], [1, 2, 3]]
265
+ ans = dict(
266
+ nx.all_pairs_all_shortest_paths(nx.cycle_graph(4)),
267
+ method="bellman-ford",
268
+ weight="weight",
269
+ )
270
+ assert sorted(ans[1][3]) == [[1, 0, 3], [1, 2, 3]]
271
+ G = nx.cycle_graph(4)
272
+ G.add_node(4)
273
+ ans = dict(nx.all_pairs_all_shortest_paths(G))
274
+ assert sorted(ans[4][4]) == [[4]]
275
+
276
+ def test_has_path(self):
277
+ G = nx.Graph()
278
+ nx.add_path(G, range(3))
279
+ nx.add_path(G, range(3, 5))
280
+ assert nx.has_path(G, 0, 2)
281
+ assert not nx.has_path(G, 0, 4)
282
+
283
+ def test_has_path_singleton(self):
284
+ G = nx.empty_graph(1)
285
+ assert nx.has_path(G, 0, 0)
286
+
287
+ def test_all_shortest_paths(self):
288
+ G = nx.Graph()
289
+ nx.add_path(G, [0, 1, 2, 3])
290
+ nx.add_path(G, [0, 10, 20, 3])
291
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(nx.all_shortest_paths(G, 0, 3))
292
+ # with weights
293
+ G = nx.Graph()
294
+ nx.add_path(G, [0, 1, 2, 3])
295
+ nx.add_path(G, [0, 10, 20, 3])
296
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(
297
+ nx.all_shortest_paths(G, 0, 3, weight="weight")
298
+ )
299
+ # weights and method specified
300
+ G = nx.Graph()
301
+ nx.add_path(G, [0, 1, 2, 3])
302
+ nx.add_path(G, [0, 10, 20, 3])
303
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(
304
+ nx.all_shortest_paths(G, 0, 3, weight="weight", method="dijkstra")
305
+ )
306
+ G = nx.Graph()
307
+ nx.add_path(G, [0, 1, 2, 3])
308
+ nx.add_path(G, [0, 10, 20, 3])
309
+ assert [[0, 1, 2, 3], [0, 10, 20, 3]] == sorted(
310
+ nx.all_shortest_paths(G, 0, 3, weight="weight", method="bellman-ford")
311
+ )
312
+
313
+ def test_all_shortest_paths_raise(self):
314
+ with pytest.raises(nx.NetworkXNoPath):
315
+ G = nx.path_graph(4)
316
+ G.add_node(4)
317
+ list(nx.all_shortest_paths(G, 0, 4))
318
+
319
+ def test_bad_method(self):
320
+ with pytest.raises(ValueError):
321
+ G = nx.path_graph(2)
322
+ list(nx.all_shortest_paths(G, 0, 1, weight="weight", method="SPAM"))
323
+
324
+ def test_single_source_all_shortest_paths_bad_method(self):
325
+ with pytest.raises(ValueError):
326
+ G = nx.path_graph(2)
327
+ dict(
328
+ nx.single_source_all_shortest_paths(
329
+ G, 0, weight="weight", method="SPAM"
330
+ )
331
+ )
332
+
333
+ def test_all_shortest_paths_zero_weight_edge(self):
334
+ g = nx.Graph()
335
+ nx.add_path(g, [0, 1, 3])
336
+ nx.add_path(g, [0, 1, 2, 3])
337
+ g.edges[1, 2]["weight"] = 0
338
+ paths30d = list(
339
+ nx.all_shortest_paths(g, 3, 0, weight="weight", method="dijkstra")
340
+ )
341
+ paths03d = list(
342
+ nx.all_shortest_paths(g, 0, 3, weight="weight", method="dijkstra")
343
+ )
344
+ paths30b = list(
345
+ nx.all_shortest_paths(g, 3, 0, weight="weight", method="bellman-ford")
346
+ )
347
+ paths03b = list(
348
+ nx.all_shortest_paths(g, 0, 3, weight="weight", method="bellman-ford")
349
+ )
350
+ assert sorted(paths03d) == sorted(p[::-1] for p in paths30d)
351
+ assert sorted(paths03d) == sorted(p[::-1] for p in paths30b)
352
+ assert sorted(paths03b) == sorted(p[::-1] for p in paths30b)
353
+
354
+
355
+ class TestAverageShortestPathLength:
356
+ def test_cycle_graph(self):
357
+ ans = nx.average_shortest_path_length(nx.cycle_graph(7))
358
+ assert ans == pytest.approx(2, abs=1e-7)
359
+
360
+ def test_path_graph(self):
361
+ ans = nx.average_shortest_path_length(nx.path_graph(5))
362
+ assert ans == pytest.approx(2, abs=1e-7)
363
+
364
+ def test_weighted(self):
365
+ G = nx.Graph()
366
+ nx.add_cycle(G, range(7), weight=2)
367
+ ans = nx.average_shortest_path_length(G, weight="weight")
368
+ assert ans == pytest.approx(4, abs=1e-7)
369
+ G = nx.Graph()
370
+ nx.add_path(G, range(5), weight=2)
371
+ ans = nx.average_shortest_path_length(G, weight="weight")
372
+ assert ans == pytest.approx(4, abs=1e-7)
373
+
374
+ def test_specified_methods(self):
375
+ G = nx.Graph()
376
+ nx.add_cycle(G, range(7), weight=2)
377
+ ans = nx.average_shortest_path_length(G, weight="weight", method="dijkstra")
378
+ assert ans == pytest.approx(4, abs=1e-7)
379
+ ans = nx.average_shortest_path_length(G, weight="weight", method="bellman-ford")
380
+ assert ans == pytest.approx(4, abs=1e-7)
381
+ ans = nx.average_shortest_path_length(
382
+ G, weight="weight", method="floyd-warshall"
383
+ )
384
+ assert ans == pytest.approx(4, abs=1e-7)
385
+
386
+ G = nx.Graph()
387
+ nx.add_path(G, range(5), weight=2)
388
+ ans = nx.average_shortest_path_length(G, weight="weight", method="dijkstra")
389
+ assert ans == pytest.approx(4, abs=1e-7)
390
+ ans = nx.average_shortest_path_length(G, weight="weight", method="bellman-ford")
391
+ assert ans == pytest.approx(4, abs=1e-7)
392
+ ans = nx.average_shortest_path_length(
393
+ G, weight="weight", method="floyd-warshall"
394
+ )
395
+ assert ans == pytest.approx(4, abs=1e-7)
396
+
397
+ def test_directed_not_strongly_connected(self):
398
+ G = nx.DiGraph([(0, 1)])
399
+ with pytest.raises(nx.NetworkXError, match="Graph is not strongly connected"):
400
+ nx.average_shortest_path_length(G)
401
+
402
+ def test_undirected_not_connected(self):
403
+ g = nx.Graph()
404
+ g.add_nodes_from(range(3))
405
+ g.add_edge(0, 1)
406
+ pytest.raises(nx.NetworkXError, nx.average_shortest_path_length, g)
407
+
408
+ def test_trivial_graph(self):
409
+ """Tests that the trivial graph has average path length zero,
410
+ since there is exactly one path of length zero in the trivial
411
+ graph.
412
+
413
+ For more information, see issue #1960.
414
+
415
+ """
416
+ G = nx.trivial_graph()
417
+ assert nx.average_shortest_path_length(G) == 0
418
+
419
+ def test_null_graph(self):
420
+ with pytest.raises(nx.NetworkXPointlessConcept):
421
+ nx.average_shortest_path_length(nx.null_graph())
422
+
423
+ def test_bad_method(self):
424
+ with pytest.raises(ValueError):
425
+ G = nx.path_graph(2)
426
+ nx.average_shortest_path_length(G, weight="weight", method="SPAM")
427
+
428
+
429
+ class TestAverageShortestPathLengthNumpy:
430
+ @classmethod
431
+ def setup_class(cls):
432
+ global np
433
+ import pytest
434
+
435
+ np = pytest.importorskip("numpy")
436
+
437
+ def test_specified_methods_numpy(self):
438
+ G = nx.Graph()
439
+ nx.add_cycle(G, range(7), weight=2)
440
+ ans = nx.average_shortest_path_length(
441
+ G, weight="weight", method="floyd-warshall-numpy"
442
+ )
443
+ np.testing.assert_almost_equal(ans, 4)
444
+
445
+ G = nx.Graph()
446
+ nx.add_path(G, range(5), weight=2)
447
+ ans = nx.average_shortest_path_length(
448
+ G, weight="weight", method="floyd-warshall-numpy"
449
+ )
450
+ np.testing.assert_almost_equal(ans, 4)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_unweighted.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def validate_grid_path(r, c, s, t, p):
7
+ assert isinstance(p, list)
8
+ assert p[0] == s
9
+ assert p[-1] == t
10
+ s = ((s - 1) // c, (s - 1) % c)
11
+ t = ((t - 1) // c, (t - 1) % c)
12
+ assert len(p) == abs(t[0] - s[0]) + abs(t[1] - s[1]) + 1
13
+ p = [((u - 1) // c, (u - 1) % c) for u in p]
14
+ for u in p:
15
+ assert 0 <= u[0] < r
16
+ assert 0 <= u[1] < c
17
+ for u, v in zip(p[:-1], p[1:]):
18
+ assert (abs(v[0] - u[0]), abs(v[1] - u[1])) in [(0, 1), (1, 0)]
19
+
20
+
21
+ class TestUnweightedPath:
22
+ @classmethod
23
+ def setup_class(cls):
24
+ from networkx import convert_node_labels_to_integers as cnlti
25
+
26
+ cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
27
+ cls.cycle = nx.cycle_graph(7)
28
+ cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
29
+
30
+ def test_bidirectional_shortest_path(self):
31
+ assert nx.bidirectional_shortest_path(self.cycle, 0, 3) == [0, 1, 2, 3]
32
+ assert nx.bidirectional_shortest_path(self.cycle, 0, 4) == [0, 6, 5, 4]
33
+ validate_grid_path(
34
+ 4, 4, 1, 12, nx.bidirectional_shortest_path(self.grid, 1, 12)
35
+ )
36
+ assert nx.bidirectional_shortest_path(self.directed_cycle, 0, 3) == [0, 1, 2, 3]
37
+ # test source = target
38
+ assert nx.bidirectional_shortest_path(self.cycle, 3, 3) == [3]
39
+
40
+ @pytest.mark.parametrize(
41
+ ("src", "tgt"),
42
+ (
43
+ (8, 3), # source not in graph
44
+ (3, 8), # target not in graph
45
+ (8, 10), # neither source nor target in graph
46
+ (8, 8), # src == tgt, neither in graph - tests order of input checks
47
+ ),
48
+ )
49
+ def test_bidirectional_shortest_path_src_tgt_not_in_graph(self, src, tgt):
50
+ with pytest.raises(
51
+ nx.NodeNotFound,
52
+ match=f"Either source {src} or target {tgt} is not in G",
53
+ ):
54
+ nx.bidirectional_shortest_path(self.cycle, src, tgt)
55
+
56
+ def test_shortest_path_length(self):
57
+ assert nx.shortest_path_length(self.cycle, 0, 3) == 3
58
+ assert nx.shortest_path_length(self.grid, 1, 12) == 5
59
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4) == 4
60
+ # now with weights
61
+ assert nx.shortest_path_length(self.cycle, 0, 3, weight=True) == 3
62
+ assert nx.shortest_path_length(self.grid, 1, 12, weight=True) == 5
63
+ assert nx.shortest_path_length(self.directed_cycle, 0, 4, weight=True) == 4
64
+
65
+ def test_single_source_shortest_path(self):
66
+ p = nx.single_source_shortest_path(self.directed_cycle, 3)
67
+ assert p[0] == [3, 4, 5, 6, 0]
68
+ p = nx.single_source_shortest_path(self.cycle, 0)
69
+ assert p[3] == [0, 1, 2, 3]
70
+ p = nx.single_source_shortest_path(self.cycle, 0, cutoff=0)
71
+ assert p == {0: [0]}
72
+
73
+ def test_single_source_shortest_path_length(self):
74
+ pl = nx.single_source_shortest_path_length
75
+ lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
76
+ assert dict(pl(self.cycle, 0)) == lengths
77
+ lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
78
+ assert dict(pl(self.directed_cycle, 0)) == lengths
79
+
80
+ def test_single_target_shortest_path(self):
81
+ p = nx.single_target_shortest_path(self.directed_cycle, 0)
82
+ assert p[3] == [3, 4, 5, 6, 0]
83
+ p = nx.single_target_shortest_path(self.cycle, 0)
84
+ assert p[3] == [3, 2, 1, 0]
85
+ p = nx.single_target_shortest_path(self.cycle, 0, cutoff=0)
86
+ assert p == {0: [0]}
87
+ # test missing targets
88
+ target = 8
89
+ with pytest.raises(nx.NodeNotFound, match=f"Target {target} not in G"):
90
+ nx.single_target_shortest_path(self.cycle, target)
91
+
92
+ def test_single_target_shortest_path_length(self):
93
+ pl = nx.single_target_shortest_path_length
94
+ lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
95
+ assert dict(pl(self.cycle, 0)) == lengths
96
+ lengths = {0: 0, 1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
97
+ assert dict(pl(self.directed_cycle, 0)) == lengths
98
+ # test missing targets
99
+ target = 8
100
+ with pytest.raises(nx.NodeNotFound, match=f"Target {target} is not in G"):
101
+ nx.single_target_shortest_path_length(self.cycle, target)
102
+
103
+ def test_all_pairs_shortest_path(self):
104
+ p = dict(nx.all_pairs_shortest_path(self.cycle))
105
+ assert p[0][3] == [0, 1, 2, 3]
106
+ p = dict(nx.all_pairs_shortest_path(self.grid))
107
+ validate_grid_path(4, 4, 1, 12, p[1][12])
108
+
109
+ def test_all_pairs_shortest_path_length(self):
110
+ l = dict(nx.all_pairs_shortest_path_length(self.cycle))
111
+ assert l[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
112
+ l = dict(nx.all_pairs_shortest_path_length(self.grid))
113
+ assert l[1][16] == 6
114
+
115
+ def test_predecessor_path(self):
116
+ G = nx.path_graph(4)
117
+ assert nx.predecessor(G, 0) == {0: [], 1: [0], 2: [1], 3: [2]}
118
+ assert nx.predecessor(G, 0, 3) == [2]
119
+
120
+ def test_predecessor_cycle(self):
121
+ G = nx.cycle_graph(4)
122
+ pred = nx.predecessor(G, 0)
123
+ assert pred[0] == []
124
+ assert pred[1] == [0]
125
+ assert pred[2] in [[1, 3], [3, 1]]
126
+ assert pred[3] == [0]
127
+
128
+ def test_predecessor_cutoff(self):
129
+ G = nx.path_graph(4)
130
+ p = nx.predecessor(G, 0, 3)
131
+ assert 4 not in p
132
+
133
+ def test_predecessor_target(self):
134
+ G = nx.path_graph(4)
135
+ p = nx.predecessor(G, 0, 3)
136
+ assert p == [2]
137
+ p = nx.predecessor(G, 0, 3, cutoff=2)
138
+ assert p == []
139
+ p, s = nx.predecessor(G, 0, 3, return_seen=True)
140
+ assert p == [2]
141
+ assert s == 3
142
+ p, s = nx.predecessor(G, 0, 3, cutoff=2, return_seen=True)
143
+ assert p == []
144
+ assert s == -1
145
+
146
+ def test_predecessor_missing_source(self):
147
+ source = 8
148
+ with pytest.raises(nx.NodeNotFound, match=f"Source {source} not in G"):
149
+ nx.predecessor(self.cycle, source)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/tests/test_weighted.py ADDED
@@ -0,0 +1,972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import pairwise
5
+
6
+
7
+ def validate_path(G, s, t, soln_len, path, weight="weight"):
8
+ assert path[0] == s
9
+ assert path[-1] == t
10
+
11
+ if callable(weight):
12
+ weight_f = weight
13
+ else:
14
+ if G.is_multigraph():
15
+
16
+ def weight_f(u, v, d):
17
+ return min(e.get(weight, 1) for e in d.values())
18
+
19
+ else:
20
+
21
+ def weight_f(u, v, d):
22
+ return d.get(weight, 1)
23
+
24
+ computed = sum(weight_f(u, v, G[u][v]) for u, v in pairwise(path))
25
+ assert soln_len == computed
26
+
27
+
28
+ def validate_length_path(G, s, t, soln_len, length, path, weight="weight"):
29
+ assert soln_len == length
30
+ validate_path(G, s, t, length, path, weight=weight)
31
+
32
+
33
+ class WeightedTestBase:
34
+ """Base class for test classes that test functions for computing
35
+ shortest paths in weighted graphs.
36
+
37
+ """
38
+
39
+ def setup_method(self):
40
+ """Creates some graphs for use in the unit tests."""
41
+ cnlti = nx.convert_node_labels_to_integers
42
+ self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
43
+ self.cycle = nx.cycle_graph(7)
44
+ self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
45
+ self.XG = nx.DiGraph()
46
+ self.XG.add_weighted_edges_from(
47
+ [
48
+ ("s", "u", 10),
49
+ ("s", "x", 5),
50
+ ("u", "v", 1),
51
+ ("u", "x", 2),
52
+ ("v", "y", 1),
53
+ ("x", "u", 3),
54
+ ("x", "v", 5),
55
+ ("x", "y", 2),
56
+ ("y", "s", 7),
57
+ ("y", "v", 6),
58
+ ]
59
+ )
60
+ self.MXG = nx.MultiDiGraph(self.XG)
61
+ self.MXG.add_edge("s", "u", weight=15)
62
+ self.XG2 = nx.DiGraph()
63
+ self.XG2.add_weighted_edges_from(
64
+ [
65
+ [1, 4, 1],
66
+ [4, 5, 1],
67
+ [5, 6, 1],
68
+ [6, 3, 1],
69
+ [1, 3, 50],
70
+ [1, 2, 100],
71
+ [2, 3, 100],
72
+ ]
73
+ )
74
+
75
+ self.XG3 = nx.Graph()
76
+ self.XG3.add_weighted_edges_from(
77
+ [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]
78
+ )
79
+
80
+ self.XG4 = nx.Graph()
81
+ self.XG4.add_weighted_edges_from(
82
+ [
83
+ [0, 1, 2],
84
+ [1, 2, 2],
85
+ [2, 3, 1],
86
+ [3, 4, 1],
87
+ [4, 5, 1],
88
+ [5, 6, 1],
89
+ [6, 7, 1],
90
+ [7, 0, 1],
91
+ ]
92
+ )
93
+ self.MXG4 = nx.MultiGraph(self.XG4)
94
+ self.MXG4.add_edge(0, 1, weight=3)
95
+ self.G = nx.DiGraph() # no weights
96
+ self.G.add_edges_from(
97
+ [
98
+ ("s", "u"),
99
+ ("s", "x"),
100
+ ("u", "v"),
101
+ ("u", "x"),
102
+ ("v", "y"),
103
+ ("x", "u"),
104
+ ("x", "v"),
105
+ ("x", "y"),
106
+ ("y", "s"),
107
+ ("y", "v"),
108
+ ]
109
+ )
110
+
111
+
112
+ class TestWeightedPath(WeightedTestBase):
113
+ def test_dijkstra(self):
114
+ (D, P) = nx.single_source_dijkstra(self.XG, "s")
115
+ validate_path(self.XG, "s", "v", 9, P["v"])
116
+ assert D["v"] == 9
117
+
118
+ validate_path(
119
+ self.XG, "s", "v", 9, nx.single_source_dijkstra_path(self.XG, "s")["v"]
120
+ )
121
+ assert dict(nx.single_source_dijkstra_path_length(self.XG, "s"))["v"] == 9
122
+
123
+ validate_path(
124
+ self.XG, "s", "v", 9, nx.single_source_dijkstra(self.XG, "s")[1]["v"]
125
+ )
126
+ validate_path(
127
+ self.MXG, "s", "v", 9, nx.single_source_dijkstra_path(self.MXG, "s")["v"]
128
+ )
129
+
130
+ GG = self.XG.to_undirected()
131
+ # make sure we get lower weight
132
+ # to_undirected might choose either edge with weight 2 or weight 3
133
+ GG["u"]["x"]["weight"] = 2
134
+ (D, P) = nx.single_source_dijkstra(GG, "s")
135
+ validate_path(GG, "s", "v", 8, P["v"])
136
+ assert D["v"] == 8 # uses lower weight of 2 on u<->x edge
137
+ validate_path(GG, "s", "v", 8, nx.dijkstra_path(GG, "s", "v"))
138
+ assert nx.dijkstra_path_length(GG, "s", "v") == 8
139
+
140
+ validate_path(self.XG2, 1, 3, 4, nx.dijkstra_path(self.XG2, 1, 3))
141
+ validate_path(self.XG3, 0, 3, 15, nx.dijkstra_path(self.XG3, 0, 3))
142
+ assert nx.dijkstra_path_length(self.XG3, 0, 3) == 15
143
+ validate_path(self.XG4, 0, 2, 4, nx.dijkstra_path(self.XG4, 0, 2))
144
+ assert nx.dijkstra_path_length(self.XG4, 0, 2) == 4
145
+ validate_path(self.MXG4, 0, 2, 4, nx.dijkstra_path(self.MXG4, 0, 2))
146
+ validate_path(
147
+ self.G, "s", "v", 2, nx.single_source_dijkstra(self.G, "s", "v")[1]
148
+ )
149
+ validate_path(
150
+ self.G, "s", "v", 2, nx.single_source_dijkstra(self.G, "s")[1]["v"]
151
+ )
152
+
153
+ validate_path(self.G, "s", "v", 2, nx.dijkstra_path(self.G, "s", "v"))
154
+ assert nx.dijkstra_path_length(self.G, "s", "v") == 2
155
+
156
+ # NetworkXError: node s not reachable from moon
157
+ pytest.raises(nx.NetworkXNoPath, nx.dijkstra_path, self.G, "s", "moon")
158
+ pytest.raises(nx.NetworkXNoPath, nx.dijkstra_path_length, self.G, "s", "moon")
159
+
160
+ validate_path(self.cycle, 0, 3, 3, nx.dijkstra_path(self.cycle, 0, 3))
161
+ validate_path(self.cycle, 0, 4, 3, nx.dijkstra_path(self.cycle, 0, 4))
162
+
163
+ assert nx.single_source_dijkstra(self.cycle, 0, 0) == (0, [0])
164
+
165
+ def test_bidirectional_dijkstra(self):
166
+ validate_length_path(
167
+ self.XG, "s", "v", 9, *nx.bidirectional_dijkstra(self.XG, "s", "v")
168
+ )
169
+ validate_length_path(
170
+ self.G, "s", "v", 2, *nx.bidirectional_dijkstra(self.G, "s", "v")
171
+ )
172
+ validate_length_path(
173
+ self.cycle, 0, 3, 3, *nx.bidirectional_dijkstra(self.cycle, 0, 3)
174
+ )
175
+ validate_length_path(
176
+ self.cycle, 0, 4, 3, *nx.bidirectional_dijkstra(self.cycle, 0, 4)
177
+ )
178
+ validate_length_path(
179
+ self.XG3, 0, 3, 15, *nx.bidirectional_dijkstra(self.XG3, 0, 3)
180
+ )
181
+ validate_length_path(
182
+ self.XG4, 0, 2, 4, *nx.bidirectional_dijkstra(self.XG4, 0, 2)
183
+ )
184
+
185
+ # need more tests here
186
+ P = nx.single_source_dijkstra_path(self.XG, "s")["v"]
187
+ validate_path(
188
+ self.XG,
189
+ "s",
190
+ "v",
191
+ sum(self.XG[u][v]["weight"] for u, v in zip(P[:-1], P[1:])),
192
+ nx.dijkstra_path(self.XG, "s", "v"),
193
+ )
194
+
195
+ # check absent source
196
+ G = nx.path_graph(2)
197
+ pytest.raises(nx.NodeNotFound, nx.bidirectional_dijkstra, G, 3, 0)
198
+
199
+ def test_weight_functions(self):
200
+ def heuristic(*z):
201
+ return sum(val**2 for val in z)
202
+
203
+ def getpath(pred, v, s):
204
+ return [v] if v == s else getpath(pred, pred[v], s) + [v]
205
+
206
+ def goldberg_radzik(g, s, t, weight="weight"):
207
+ pred, dist = nx.goldberg_radzik(g, s, weight=weight)
208
+ dist = dist[t]
209
+ return dist, getpath(pred, t, s)
210
+
211
+ def astar(g, s, t, weight="weight"):
212
+ path = nx.astar_path(g, s, t, heuristic, weight=weight)
213
+ dist = nx.astar_path_length(g, s, t, heuristic, weight=weight)
214
+ return dist, path
215
+
216
+ def vlp(G, s, t, l, F, w):
217
+ res = F(G, s, t, weight=w)
218
+ validate_length_path(G, s, t, l, *res, weight=w)
219
+
220
+ G = self.cycle
221
+ s = 6
222
+ t = 4
223
+ path = [6] + list(range(t + 1))
224
+
225
+ def weight(u, v, _):
226
+ return 1 + v**2
227
+
228
+ length = sum(weight(u, v, None) for u, v in pairwise(path))
229
+ vlp(G, s, t, length, nx.bidirectional_dijkstra, weight)
230
+ vlp(G, s, t, length, nx.single_source_dijkstra, weight)
231
+ vlp(G, s, t, length, nx.single_source_bellman_ford, weight)
232
+ vlp(G, s, t, length, goldberg_radzik, weight)
233
+ vlp(G, s, t, length, astar, weight)
234
+
235
+ def weight(u, v, _):
236
+ return 2 ** (u * v)
237
+
238
+ length = sum(weight(u, v, None) for u, v in pairwise(path))
239
+ vlp(G, s, t, length, nx.bidirectional_dijkstra, weight)
240
+ vlp(G, s, t, length, nx.single_source_dijkstra, weight)
241
+ vlp(G, s, t, length, nx.single_source_bellman_ford, weight)
242
+ vlp(G, s, t, length, goldberg_radzik, weight)
243
+ vlp(G, s, t, length, astar, weight)
244
+
245
+ def test_bidirectional_dijkstra_no_path(self):
246
+ with pytest.raises(nx.NetworkXNoPath):
247
+ G = nx.Graph()
248
+ nx.add_path(G, [1, 2, 3])
249
+ nx.add_path(G, [4, 5, 6])
250
+ path = nx.bidirectional_dijkstra(G, 1, 6)
251
+
252
+ @pytest.mark.parametrize(
253
+ "fn",
254
+ (
255
+ nx.dijkstra_path,
256
+ nx.dijkstra_path_length,
257
+ nx.single_source_dijkstra_path,
258
+ nx.single_source_dijkstra_path_length,
259
+ nx.single_source_dijkstra,
260
+ nx.dijkstra_predecessor_and_distance,
261
+ ),
262
+ )
263
+ def test_absent_source(self, fn):
264
+ G = nx.path_graph(2)
265
+ with pytest.raises(nx.NodeNotFound):
266
+ fn(G, 3, 0)
267
+ # Test when source == target, which is handled specially by some functions
268
+ with pytest.raises(nx.NodeNotFound):
269
+ fn(G, 3, 3)
270
+
271
+ def test_dijkstra_predecessor1(self):
272
+ G = nx.path_graph(4)
273
+ assert nx.dijkstra_predecessor_and_distance(G, 0) == (
274
+ {0: [], 1: [0], 2: [1], 3: [2]},
275
+ {0: 0, 1: 1, 2: 2, 3: 3},
276
+ )
277
+
278
+ def test_dijkstra_predecessor2(self):
279
+ # 4-cycle
280
+ G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)])
281
+ pred, dist = nx.dijkstra_predecessor_and_distance(G, (0))
282
+ assert pred[0] == []
283
+ assert pred[1] == [0]
284
+ assert pred[2] in [[1, 3], [3, 1]]
285
+ assert pred[3] == [0]
286
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
287
+
288
+ def test_dijkstra_predecessor3(self):
289
+ XG = nx.DiGraph()
290
+ XG.add_weighted_edges_from(
291
+ [
292
+ ("s", "u", 10),
293
+ ("s", "x", 5),
294
+ ("u", "v", 1),
295
+ ("u", "x", 2),
296
+ ("v", "y", 1),
297
+ ("x", "u", 3),
298
+ ("x", "v", 5),
299
+ ("x", "y", 2),
300
+ ("y", "s", 7),
301
+ ("y", "v", 6),
302
+ ]
303
+ )
304
+ (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s")
305
+ assert P["v"] == ["u"]
306
+ assert D["v"] == 9
307
+ (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s", cutoff=8)
308
+ assert "v" not in D
309
+
310
+ def test_single_source_dijkstra_path_length(self):
311
+ pl = nx.single_source_dijkstra_path_length
312
+ assert dict(pl(self.MXG4, 0))[2] == 4
313
+ spl = pl(self.MXG4, 0, cutoff=2)
314
+ assert 2 not in spl
315
+
316
+ def test_bidirectional_dijkstra_multigraph(self):
317
+ G = nx.MultiGraph()
318
+ G.add_edge("a", "b", weight=10)
319
+ G.add_edge("a", "b", weight=100)
320
+ dp = nx.bidirectional_dijkstra(G, "a", "b")
321
+ assert dp == (10, ["a", "b"])
322
+
323
+ def test_dijkstra_pred_distance_multigraph(self):
324
+ G = nx.MultiGraph()
325
+ G.add_edge("a", "b", key="short", foo=5, weight=100)
326
+ G.add_edge("a", "b", key="long", bar=1, weight=110)
327
+ p, d = nx.dijkstra_predecessor_and_distance(G, "a")
328
+ assert p == {"a": [], "b": ["a"]}
329
+ assert d == {"a": 0, "b": 100}
330
+
331
+ def test_negative_edge_cycle(self):
332
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
333
+ assert not nx.negative_edge_cycle(G)
334
+ G.add_edge(8, 9, weight=-7)
335
+ G.add_edge(9, 8, weight=3)
336
+ graph_size = len(G)
337
+ assert nx.negative_edge_cycle(G)
338
+ assert graph_size == len(G)
339
+ pytest.raises(ValueError, nx.single_source_dijkstra_path_length, G, 8)
340
+ pytest.raises(ValueError, nx.single_source_dijkstra, G, 8)
341
+ pytest.raises(ValueError, nx.dijkstra_predecessor_and_distance, G, 8)
342
+ G.add_edge(9, 10)
343
+ pytest.raises(ValueError, nx.bidirectional_dijkstra, G, 8, 10)
344
+ G = nx.MultiDiGraph()
345
+ G.add_edge(2, 2, weight=-1)
346
+ assert nx.negative_edge_cycle(G)
347
+
348
+ def test_negative_edge_cycle_empty(self):
349
+ G = nx.DiGraph()
350
+ assert not nx.negative_edge_cycle(G)
351
+
352
+ def test_negative_edge_cycle_custom_weight_key(self):
353
+ d = nx.DiGraph()
354
+ d.add_edge("a", "b", w=-2)
355
+ d.add_edge("b", "a", w=-1)
356
+ assert nx.negative_edge_cycle(d, weight="w")
357
+
358
+ def test_weight_function(self):
359
+ """Tests that a callable weight is interpreted as a weight
360
+ function instead of an edge attribute.
361
+
362
+ """
363
+ # Create a triangle in which the edge from node 0 to node 2 has
364
+ # a large weight and the other two edges have a small weight.
365
+ G = nx.complete_graph(3)
366
+ G.adj[0][2]["weight"] = 10
367
+ G.adj[0][1]["weight"] = 1
368
+ G.adj[1][2]["weight"] = 1
369
+
370
+ # The weight function will take the multiplicative inverse of
371
+ # the weights on the edges. This way, weights that were large
372
+ # before now become small and vice versa.
373
+
374
+ def weight(u, v, d):
375
+ return 1 / d["weight"]
376
+
377
+ # The shortest path from 0 to 2 using the actual weights on the
378
+ # edges should be [0, 1, 2].
379
+ distance, path = nx.single_source_dijkstra(G, 0, 2)
380
+ assert distance == 2
381
+ assert path == [0, 1, 2]
382
+ # However, with the above weight function, the shortest path
383
+ # should be [0, 2], since that has a very small weight.
384
+ distance, path = nx.single_source_dijkstra(G, 0, 2, weight=weight)
385
+ assert distance == 1 / 10
386
+ assert path == [0, 2]
387
+
388
+ def test_all_pairs_dijkstra_path(self):
389
+ cycle = nx.cycle_graph(7)
390
+ p = dict(nx.all_pairs_dijkstra_path(cycle))
391
+ assert p[0][3] == [0, 1, 2, 3]
392
+
393
+ cycle[1][2]["weight"] = 10
394
+ p = dict(nx.all_pairs_dijkstra_path(cycle))
395
+ assert p[0][3] == [0, 6, 5, 4, 3]
396
+
397
+ def test_all_pairs_dijkstra_path_length(self):
398
+ cycle = nx.cycle_graph(7)
399
+ pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
400
+ assert pl[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
401
+
402
+ cycle[1][2]["weight"] = 10
403
+ pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
404
+ assert pl[0] == {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
405
+
406
+ def test_all_pairs_dijkstra(self):
407
+ cycle = nx.cycle_graph(7)
408
+ out = dict(nx.all_pairs_dijkstra(cycle))
409
+ assert out[0][0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
410
+ assert out[0][1][3] == [0, 1, 2, 3]
411
+
412
+ cycle[1][2]["weight"] = 10
413
+ out = dict(nx.all_pairs_dijkstra(cycle))
414
+ assert out[0][0] == {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
415
+ assert out[0][1][3] == [0, 6, 5, 4, 3]
416
+
417
+
418
+ class TestDijkstraPathLength:
419
+ """Unit tests for the :func:`networkx.dijkstra_path_length`
420
+ function.
421
+
422
+ """
423
+
424
+ def test_weight_function(self):
425
+ """Tests for computing the length of the shortest path using
426
+ Dijkstra's algorithm with a user-defined weight function.
427
+
428
+ """
429
+ # Create a triangle in which the edge from node 0 to node 2 has
430
+ # a large weight and the other two edges have a small weight.
431
+ G = nx.complete_graph(3)
432
+ G.adj[0][2]["weight"] = 10
433
+ G.adj[0][1]["weight"] = 1
434
+ G.adj[1][2]["weight"] = 1
435
+
436
+ # The weight function will take the multiplicative inverse of
437
+ # the weights on the edges. This way, weights that were large
438
+ # before now become small and vice versa.
439
+
440
+ def weight(u, v, d):
441
+ return 1 / d["weight"]
442
+
443
+ # The shortest path from 0 to 2 using the actual weights on the
444
+ # edges should be [0, 1, 2]. However, with the above weight
445
+ # function, the shortest path should be [0, 2], since that has a
446
+ # very small weight.
447
+ length = nx.dijkstra_path_length(G, 0, 2, weight=weight)
448
+ assert length == 1 / 10
449
+
450
+
451
+ class TestMultiSourceDijkstra:
452
+ """Unit tests for the multi-source dialect of Dijkstra's shortest
453
+ path algorithms.
454
+
455
+ """
456
+
457
+ def test_no_sources(self):
458
+ with pytest.raises(ValueError):
459
+ nx.multi_source_dijkstra(nx.Graph(), {})
460
+
461
+ def test_path_no_sources(self):
462
+ with pytest.raises(ValueError):
463
+ nx.multi_source_dijkstra_path(nx.Graph(), {})
464
+
465
+ def test_path_length_no_sources(self):
466
+ with pytest.raises(ValueError):
467
+ nx.multi_source_dijkstra_path_length(nx.Graph(), {})
468
+
469
+ @pytest.mark.parametrize(
470
+ "fn",
471
+ (
472
+ nx.multi_source_dijkstra_path,
473
+ nx.multi_source_dijkstra_path_length,
474
+ nx.multi_source_dijkstra,
475
+ ),
476
+ )
477
+ def test_absent_source(self, fn):
478
+ G = nx.path_graph(2)
479
+ with pytest.raises(nx.NodeNotFound):
480
+ fn(G, [3], 0)
481
+ with pytest.raises(nx.NodeNotFound):
482
+ fn(G, [3], 3)
483
+
484
+ def test_two_sources(self):
485
+ edges = [(0, 1, 1), (1, 2, 1), (2, 3, 10), (3, 4, 1)]
486
+ G = nx.Graph()
487
+ G.add_weighted_edges_from(edges)
488
+ sources = {0, 4}
489
+ distances, paths = nx.multi_source_dijkstra(G, sources)
490
+ expected_distances = {0: 0, 1: 1, 2: 2, 3: 1, 4: 0}
491
+ expected_paths = {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [4, 3], 4: [4]}
492
+ assert distances == expected_distances
493
+ assert paths == expected_paths
494
+
495
+ def test_simple_paths(self):
496
+ G = nx.path_graph(4)
497
+ lengths = nx.multi_source_dijkstra_path_length(G, [0])
498
+ assert lengths == {n: n for n in G}
499
+ paths = nx.multi_source_dijkstra_path(G, [0])
500
+ assert paths == {n: list(range(n + 1)) for n in G}
501
+
502
+
503
+ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
504
+ def test_single_node_graph(self):
505
+ G = nx.DiGraph()
506
+ G.add_node(0)
507
+ assert nx.single_source_bellman_ford_path(G, 0) == {0: [0]}
508
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {0: 0}
509
+ assert nx.single_source_bellman_ford(G, 0) == ({0: 0}, {0: [0]})
510
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == ({0: []}, {0: 0})
511
+ assert nx.goldberg_radzik(G, 0) == ({0: None}, {0: 0})
512
+
513
+ def test_absent_source_bellman_ford(self):
514
+ # the check is in _bellman_ford; this provides regression testing
515
+ # against later changes to "client" Bellman-Ford functions
516
+ G = nx.path_graph(2)
517
+ for fn in (
518
+ nx.bellman_ford_predecessor_and_distance,
519
+ nx.bellman_ford_path,
520
+ nx.bellman_ford_path_length,
521
+ nx.single_source_bellman_ford_path,
522
+ nx.single_source_bellman_ford_path_length,
523
+ nx.single_source_bellman_ford,
524
+ ):
525
+ pytest.raises(nx.NodeNotFound, fn, G, 3, 0)
526
+ pytest.raises(nx.NodeNotFound, fn, G, 3, 3)
527
+
528
+ def test_absent_source_goldberg_radzik(self):
529
+ with pytest.raises(nx.NodeNotFound):
530
+ G = nx.path_graph(2)
531
+ nx.goldberg_radzik(G, 3, 0)
532
+
533
+ def test_negative_cycle_heuristic(self):
534
+ G = nx.DiGraph()
535
+ G.add_edge(0, 1, weight=-1)
536
+ G.add_edge(1, 2, weight=-1)
537
+ G.add_edge(2, 3, weight=-1)
538
+ G.add_edge(3, 0, weight=3)
539
+ assert not nx.negative_edge_cycle(G, heuristic=True)
540
+ G.add_edge(2, 0, weight=1.999)
541
+ assert nx.negative_edge_cycle(G, heuristic=True)
542
+ G.edges[2, 0]["weight"] = 2
543
+ assert not nx.negative_edge_cycle(G, heuristic=True)
544
+
545
+ def test_negative_cycle_consistency(self):
546
+ import random
547
+
548
+ unif = random.uniform
549
+ for random_seed in range(2): # range(20):
550
+ random.seed(random_seed)
551
+ for density in [0.1, 0.9]: # .3, .7, .9]:
552
+ for N in [1, 10, 20]: # range(1, 60 - int(30 * density)):
553
+ for max_cost in [1, 90]: # [1, 10, 40, 90]:
554
+ G = nx.binomial_graph(N, density, seed=4, directed=True)
555
+ edges = ((u, v, unif(-1, max_cost)) for u, v in G.edges)
556
+ G.add_weighted_edges_from(edges)
557
+
558
+ no_heuristic = nx.negative_edge_cycle(G, heuristic=False)
559
+ with_heuristic = nx.negative_edge_cycle(G, heuristic=True)
560
+ assert no_heuristic == with_heuristic
561
+
562
+ def test_negative_cycle(self):
563
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
564
+ G.add_edge(1, 2, weight=-7)
565
+ for i in range(5):
566
+ pytest.raises(
567
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, i
568
+ )
569
+ pytest.raises(
570
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i
571
+ )
572
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i)
573
+ pytest.raises(
574
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i
575
+ )
576
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
577
+ G = nx.cycle_graph(5) # undirected Graph
578
+ G.add_edge(1, 2, weight=-3)
579
+ for i in range(5):
580
+ pytest.raises(
581
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, i
582
+ )
583
+ pytest.raises(
584
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i
585
+ )
586
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i)
587
+ pytest.raises(
588
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i
589
+ )
590
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
591
+ G = nx.DiGraph([(1, 1, {"weight": -1})])
592
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, 1)
593
+ pytest.raises(
594
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, 1
595
+ )
596
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, 1)
597
+ pytest.raises(
598
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1
599
+ )
600
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
601
+ G = nx.MultiDiGraph([(1, 1, {"weight": -1})])
602
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, 1)
603
+ pytest.raises(
604
+ nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, 1
605
+ )
606
+ pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, 1)
607
+ pytest.raises(
608
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1
609
+ )
610
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
611
+
612
+ def test_zero_cycle(self):
613
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
614
+ G.add_edge(2, 3, weight=-4)
615
+ # check that zero cycle doesn't raise
616
+ nx.goldberg_radzik(G, 1)
617
+ nx.bellman_ford_predecessor_and_distance(G, 1)
618
+
619
+ G.add_edge(2, 3, weight=-4.0001)
620
+ # check that negative cycle does raise
621
+ pytest.raises(
622
+ nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1
623
+ )
624
+ pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
625
+
626
+ def test_find_negative_cycle_longer_cycle(self):
627
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
628
+ nx.add_cycle(G, [3, 5, 6, 7, 8, 9])
629
+ G.add_edge(1, 2, weight=-30)
630
+ assert nx.find_negative_cycle(G, 1) == [0, 1, 2, 3, 4, 0]
631
+ assert nx.find_negative_cycle(G, 7) == [2, 3, 4, 0, 1, 2]
632
+
633
+ def test_find_negative_cycle_no_cycle(self):
634
+ G = nx.path_graph(5, create_using=nx.DiGraph())
635
+ pytest.raises(nx.NetworkXError, nx.find_negative_cycle, G, 3)
636
+
637
+ def test_find_negative_cycle_single_edge(self):
638
+ G = nx.Graph()
639
+ G.add_edge(0, 1, weight=-1)
640
+ assert nx.find_negative_cycle(G, 1) == [1, 0, 1]
641
+
642
+ def test_negative_weight(self):
643
+ G = nx.cycle_graph(5, create_using=nx.DiGraph())
644
+ G.add_edge(1, 2, weight=-3)
645
+ assert nx.single_source_bellman_ford_path(G, 0) == {
646
+ 0: [0],
647
+ 1: [0, 1],
648
+ 2: [0, 1, 2],
649
+ 3: [0, 1, 2, 3],
650
+ 4: [0, 1, 2, 3, 4],
651
+ }
652
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {
653
+ 0: 0,
654
+ 1: 1,
655
+ 2: -2,
656
+ 3: -1,
657
+ 4: 0,
658
+ }
659
+ assert nx.single_source_bellman_ford(G, 0) == (
660
+ {0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
661
+ {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]},
662
+ )
663
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
664
+ {0: [], 1: [0], 2: [1], 3: [2], 4: [3]},
665
+ {0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
666
+ )
667
+ assert nx.goldberg_radzik(G, 0) == (
668
+ {0: None, 1: 0, 2: 1, 3: 2, 4: 3},
669
+ {0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
670
+ )
671
+
672
+ def test_not_connected(self):
673
+ G = nx.complete_graph(6)
674
+ G.add_edge(10, 11)
675
+ G.add_edge(10, 12)
676
+ assert nx.single_source_bellman_ford_path(G, 0) == {
677
+ 0: [0],
678
+ 1: [0, 1],
679
+ 2: [0, 2],
680
+ 3: [0, 3],
681
+ 4: [0, 4],
682
+ 5: [0, 5],
683
+ }
684
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {
685
+ 0: 0,
686
+ 1: 1,
687
+ 2: 1,
688
+ 3: 1,
689
+ 4: 1,
690
+ 5: 1,
691
+ }
692
+ assert nx.single_source_bellman_ford(G, 0) == (
693
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
694
+ {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]},
695
+ )
696
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
697
+ {0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
698
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
699
+ )
700
+ assert nx.goldberg_radzik(G, 0) == (
701
+ {0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
702
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
703
+ )
704
+
705
+ # not connected, with a component not containing the source that
706
+ # contains a negative cycle.
707
+ G = nx.complete_graph(6)
708
+ G.add_edges_from(
709
+ [
710
+ ("A", "B", {"load": 3}),
711
+ ("B", "C", {"load": -10}),
712
+ ("C", "A", {"load": 2}),
713
+ ]
714
+ )
715
+ assert nx.single_source_bellman_ford_path(G, 0, weight="load") == {
716
+ 0: [0],
717
+ 1: [0, 1],
718
+ 2: [0, 2],
719
+ 3: [0, 3],
720
+ 4: [0, 4],
721
+ 5: [0, 5],
722
+ }
723
+ assert nx.single_source_bellman_ford_path_length(G, 0, weight="load") == {
724
+ 0: 0,
725
+ 1: 1,
726
+ 2: 1,
727
+ 3: 1,
728
+ 4: 1,
729
+ 5: 1,
730
+ }
731
+ assert nx.single_source_bellman_ford(G, 0, weight="load") == (
732
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
733
+ {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]},
734
+ )
735
+ assert nx.bellman_ford_predecessor_and_distance(G, 0, weight="load") == (
736
+ {0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
737
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
738
+ )
739
+ assert nx.goldberg_radzik(G, 0, weight="load") == (
740
+ {0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
741
+ {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
742
+ )
743
+
744
+ def test_multigraph(self):
745
+ assert nx.bellman_ford_path(self.MXG, "s", "v") == ["s", "x", "u", "v"]
746
+ assert nx.bellman_ford_path_length(self.MXG, "s", "v") == 9
747
+ assert nx.single_source_bellman_ford_path(self.MXG, "s")["v"] == [
748
+ "s",
749
+ "x",
750
+ "u",
751
+ "v",
752
+ ]
753
+ assert nx.single_source_bellman_ford_path_length(self.MXG, "s")["v"] == 9
754
+ D, P = nx.single_source_bellman_ford(self.MXG, "s", target="v")
755
+ assert D == 9
756
+ assert P == ["s", "x", "u", "v"]
757
+ P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, "s")
758
+ assert P["v"] == ["u"]
759
+ assert D["v"] == 9
760
+ P, D = nx.goldberg_radzik(self.MXG, "s")
761
+ assert P["v"] == "u"
762
+ assert D["v"] == 9
763
+ assert nx.bellman_ford_path(self.MXG4, 0, 2) == [0, 1, 2]
764
+ assert nx.bellman_ford_path_length(self.MXG4, 0, 2) == 4
765
+ assert nx.single_source_bellman_ford_path(self.MXG4, 0)[2] == [0, 1, 2]
766
+ assert nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2] == 4
767
+ D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2)
768
+ assert D == 4
769
+ assert P == [0, 1, 2]
770
+ P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0)
771
+ assert P[2] == [1]
772
+ assert D[2] == 4
773
+ P, D = nx.goldberg_radzik(self.MXG4, 0)
774
+ assert P[2] == 1
775
+ assert D[2] == 4
776
+
777
+ def test_others(self):
778
+ assert nx.bellman_ford_path(self.XG, "s", "v") == ["s", "x", "u", "v"]
779
+ assert nx.bellman_ford_path_length(self.XG, "s", "v") == 9
780
+ assert nx.single_source_bellman_ford_path(self.XG, "s")["v"] == [
781
+ "s",
782
+ "x",
783
+ "u",
784
+ "v",
785
+ ]
786
+ assert nx.single_source_bellman_ford_path_length(self.XG, "s")["v"] == 9
787
+ D, P = nx.single_source_bellman_ford(self.XG, "s", target="v")
788
+ assert D == 9
789
+ assert P == ["s", "x", "u", "v"]
790
+ (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, "s")
791
+ assert P["v"] == ["u"]
792
+ assert D["v"] == 9
793
+ (P, D) = nx.goldberg_radzik(self.XG, "s")
794
+ assert P["v"] == "u"
795
+ assert D["v"] == 9
796
+
797
+ def test_path_graph(self):
798
+ G = nx.path_graph(4)
799
+ assert nx.single_source_bellman_ford_path(G, 0) == {
800
+ 0: [0],
801
+ 1: [0, 1],
802
+ 2: [0, 1, 2],
803
+ 3: [0, 1, 2, 3],
804
+ }
805
+ assert nx.single_source_bellman_ford_path_length(G, 0) == {
806
+ 0: 0,
807
+ 1: 1,
808
+ 2: 2,
809
+ 3: 3,
810
+ }
811
+ assert nx.single_source_bellman_ford(G, 0) == (
812
+ {0: 0, 1: 1, 2: 2, 3: 3},
813
+ {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]},
814
+ )
815
+ assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
816
+ {0: [], 1: [0], 2: [1], 3: [2]},
817
+ {0: 0, 1: 1, 2: 2, 3: 3},
818
+ )
819
+ assert nx.goldberg_radzik(G, 0) == (
820
+ {0: None, 1: 0, 2: 1, 3: 2},
821
+ {0: 0, 1: 1, 2: 2, 3: 3},
822
+ )
823
+ assert nx.single_source_bellman_ford_path(G, 3) == {
824
+ 0: [3, 2, 1, 0],
825
+ 1: [3, 2, 1],
826
+ 2: [3, 2],
827
+ 3: [3],
828
+ }
829
+ assert nx.single_source_bellman_ford_path_length(G, 3) == {
830
+ 0: 3,
831
+ 1: 2,
832
+ 2: 1,
833
+ 3: 0,
834
+ }
835
+ assert nx.single_source_bellman_ford(G, 3) == (
836
+ {0: 3, 1: 2, 2: 1, 3: 0},
837
+ {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]},
838
+ )
839
+ assert nx.bellman_ford_predecessor_and_distance(G, 3) == (
840
+ {0: [1], 1: [2], 2: [3], 3: []},
841
+ {0: 3, 1: 2, 2: 1, 3: 0},
842
+ )
843
+ assert nx.goldberg_radzik(G, 3) == (
844
+ {0: 1, 1: 2, 2: 3, 3: None},
845
+ {0: 3, 1: 2, 2: 1, 3: 0},
846
+ )
847
+
848
+ def test_4_cycle(self):
849
+ # 4-cycle
850
+ G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)])
851
+ dist, path = nx.single_source_bellman_ford(G, 0)
852
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
853
+ assert path[0] == [0]
854
+ assert path[1] == [0, 1]
855
+ assert path[2] in [[0, 1, 2], [0, 3, 2]]
856
+ assert path[3] == [0, 3]
857
+
858
+ pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0)
859
+ assert pred[0] == []
860
+ assert pred[1] == [0]
861
+ assert pred[2] in [[1, 3], [3, 1]]
862
+ assert pred[3] == [0]
863
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
864
+
865
+ pred, dist = nx.goldberg_radzik(G, 0)
866
+ assert pred[0] is None
867
+ assert pred[1] == 0
868
+ assert pred[2] in [1, 3]
869
+ assert pred[3] == 0
870
+ assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
871
+
872
+ def test_negative_weight_bf_path(self):
873
+ G = nx.DiGraph()
874
+ G.add_nodes_from("abcd")
875
+ G.add_edge("a", "d", weight=0)
876
+ G.add_edge("a", "b", weight=1)
877
+ G.add_edge("b", "c", weight=-3)
878
+ G.add_edge("c", "d", weight=1)
879
+
880
+ assert nx.bellman_ford_path(G, "a", "d") == ["a", "b", "c", "d"]
881
+ assert nx.bellman_ford_path_length(G, "a", "d") == -1
882
+
883
+ def test_zero_cycle_smoke(self):
884
+ D = nx.DiGraph()
885
+ D.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 1, -2)])
886
+
887
+ nx.bellman_ford_path(D, 1, 3)
888
+ nx.dijkstra_path(D, 1, 3)
889
+ nx.bidirectional_dijkstra(D, 1, 3)
890
+ # FIXME nx.goldberg_radzik(D, 1)
891
+
892
+
893
+ class TestJohnsonAlgorithm(WeightedTestBase):
894
+ def test_single_node_graph(self):
895
+ G = nx.DiGraph()
896
+ G.add_node(0)
897
+ assert nx.johnson(G) == {0: {0: [0]}}
898
+
899
+ def test_negative_cycle(self):
900
+ G = nx.DiGraph()
901
+ G.add_weighted_edges_from(
902
+ [
903
+ ("0", "3", 3),
904
+ ("0", "1", -5),
905
+ ("1", "0", -5),
906
+ ("0", "2", 2),
907
+ ("1", "2", 4),
908
+ ("2", "3", 1),
909
+ ]
910
+ )
911
+ pytest.raises(nx.NetworkXUnbounded, nx.johnson, G)
912
+ G = nx.Graph()
913
+ G.add_weighted_edges_from(
914
+ [
915
+ ("0", "3", 3),
916
+ ("0", "1", -5),
917
+ ("1", "0", -5),
918
+ ("0", "2", 2),
919
+ ("1", "2", 4),
920
+ ("2", "3", 1),
921
+ ]
922
+ )
923
+ pytest.raises(nx.NetworkXUnbounded, nx.johnson, G)
924
+
925
+ def test_negative_weights(self):
926
+ G = nx.DiGraph()
927
+ G.add_weighted_edges_from(
928
+ [("0", "3", 3), ("0", "1", -5), ("0", "2", 2), ("1", "2", 4), ("2", "3", 1)]
929
+ )
930
+ paths = nx.johnson(G)
931
+ assert paths == {
932
+ "1": {"1": ["1"], "3": ["1", "2", "3"], "2": ["1", "2"]},
933
+ "0": {
934
+ "1": ["0", "1"],
935
+ "0": ["0"],
936
+ "3": ["0", "1", "2", "3"],
937
+ "2": ["0", "1", "2"],
938
+ },
939
+ "3": {"3": ["3"]},
940
+ "2": {"3": ["2", "3"], "2": ["2"]},
941
+ }
942
+
943
+ def test_unweighted_graph(self):
944
+ G = nx.Graph()
945
+ G.add_edges_from([(1, 0), (2, 1)])
946
+ H = G.copy()
947
+ nx.set_edge_attributes(H, values=1, name="weight")
948
+ assert nx.johnson(G) == nx.johnson(H)
949
+
950
+ def test_partially_weighted_graph_with_negative_edges(self):
951
+ G = nx.DiGraph()
952
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (1, 0)])
953
+ G[1][0]["weight"] = -2
954
+ G[0][1]["weight"] = 3
955
+ G[1][2]["weight"] = -4
956
+
957
+ H = G.copy()
958
+ H[2][0]["weight"] = 1
959
+
960
+ I = G.copy()
961
+ I[2][0]["weight"] = 8
962
+
963
+ assert nx.johnson(G) == nx.johnson(H)
964
+ assert nx.johnson(G) != nx.johnson(I)
965
+
966
+ def test_graphs(self):
967
+ validate_path(self.XG, "s", "v", 9, nx.johnson(self.XG)["s"]["v"])
968
+ validate_path(self.MXG, "s", "v", 9, nx.johnson(self.MXG)["s"]["v"])
969
+ validate_path(self.XG2, 1, 3, 4, nx.johnson(self.XG2)[1][3])
970
+ validate_path(self.XG3, 0, 3, 15, nx.johnson(self.XG3)[0][3])
971
+ validate_path(self.XG4, 0, 2, 4, nx.johnson(self.XG4)[0][2])
972
+ validate_path(self.MXG4, 0, 2, 4, nx.johnson(self.MXG4)[0][2])
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/unweighted.py ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shortest path algorithms for unweighted graphs.
3
+ """
4
+ import warnings
5
+
6
+ import networkx as nx
7
+
8
+ __all__ = [
9
+ "bidirectional_shortest_path",
10
+ "single_source_shortest_path",
11
+ "single_source_shortest_path_length",
12
+ "single_target_shortest_path",
13
+ "single_target_shortest_path_length",
14
+ "all_pairs_shortest_path",
15
+ "all_pairs_shortest_path_length",
16
+ "predecessor",
17
+ ]
18
+
19
+
20
+ @nx._dispatchable
21
+ def single_source_shortest_path_length(G, source, cutoff=None):
22
+ """Compute the shortest path lengths from source to all reachable nodes.
23
+
24
+ Parameters
25
+ ----------
26
+ G : NetworkX graph
27
+
28
+ source : node
29
+ Starting node for path
30
+
31
+ cutoff : integer, optional
32
+ Depth to stop the search. Only paths of length <= cutoff are returned.
33
+
34
+ Returns
35
+ -------
36
+ lengths : dict
37
+ Dict keyed by node to shortest path length to source.
38
+
39
+ Examples
40
+ --------
41
+ >>> G = nx.path_graph(5)
42
+ >>> length = nx.single_source_shortest_path_length(G, 0)
43
+ >>> length[4]
44
+ 4
45
+ >>> for node in length:
46
+ ... print(f"{node}: {length[node]}")
47
+ 0: 0
48
+ 1: 1
49
+ 2: 2
50
+ 3: 3
51
+ 4: 4
52
+
53
+ See Also
54
+ --------
55
+ shortest_path_length
56
+ """
57
+ if source not in G:
58
+ raise nx.NodeNotFound(f"Source {source} is not in G")
59
+ if cutoff is None:
60
+ cutoff = float("inf")
61
+ nextlevel = [source]
62
+ return dict(_single_shortest_path_length(G._adj, nextlevel, cutoff))
63
+
64
+
65
+ def _single_shortest_path_length(adj, firstlevel, cutoff):
66
+ """Yields (node, level) in a breadth first search
67
+
68
+ Shortest Path Length helper function
69
+ Parameters
70
+ ----------
71
+ adj : dict
72
+ Adjacency dict or view
73
+ firstlevel : list
74
+ starting nodes, e.g. [source] or [target]
75
+ cutoff : int or float
76
+ level at which we stop the process
77
+ """
78
+ seen = set(firstlevel)
79
+ nextlevel = firstlevel
80
+ level = 0
81
+ n = len(adj)
82
+ for v in nextlevel:
83
+ yield (v, level)
84
+ while nextlevel and cutoff > level:
85
+ level += 1
86
+ thislevel = nextlevel
87
+ nextlevel = []
88
+ for v in thislevel:
89
+ for w in adj[v]:
90
+ if w not in seen:
91
+ seen.add(w)
92
+ nextlevel.append(w)
93
+ yield (w, level)
94
+ if len(seen) == n:
95
+ return
96
+
97
+
98
+ @nx._dispatchable
99
+ def single_target_shortest_path_length(G, target, cutoff=None):
100
+ """Compute the shortest path lengths to target from all reachable nodes.
101
+
102
+ Parameters
103
+ ----------
104
+ G : NetworkX graph
105
+
106
+ target : node
107
+ Target node for path
108
+
109
+ cutoff : integer, optional
110
+ Depth to stop the search. Only paths of length <= cutoff are returned.
111
+
112
+ Returns
113
+ -------
114
+ lengths : iterator
115
+ (source, shortest path length) iterator
116
+
117
+ Examples
118
+ --------
119
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
120
+ >>> length = dict(nx.single_target_shortest_path_length(G, 4))
121
+ >>> length[0]
122
+ 4
123
+ >>> for node in range(5):
124
+ ... print(f"{node}: {length[node]}")
125
+ 0: 4
126
+ 1: 3
127
+ 2: 2
128
+ 3: 1
129
+ 4: 0
130
+
131
+ See Also
132
+ --------
133
+ single_source_shortest_path_length, shortest_path_length
134
+ """
135
+ if target not in G:
136
+ raise nx.NodeNotFound(f"Target {target} is not in G")
137
+
138
+ warnings.warn(
139
+ (
140
+ "\n\nsingle_target_shortest_path_length will return a dict instead of"
141
+ "\nan iterator in version 3.5"
142
+ ),
143
+ FutureWarning,
144
+ stacklevel=3,
145
+ )
146
+
147
+ if cutoff is None:
148
+ cutoff = float("inf")
149
+ # handle either directed or undirected
150
+ adj = G._pred if G.is_directed() else G._adj
151
+ nextlevel = [target]
152
+ # for version 3.3 we will return a dict like this:
153
+ # return dict(_single_shortest_path_length(adj, nextlevel, cutoff))
154
+ return _single_shortest_path_length(adj, nextlevel, cutoff)
155
+
156
+
157
+ @nx._dispatchable
158
+ def all_pairs_shortest_path_length(G, cutoff=None):
159
+ """Computes the shortest path lengths between all nodes in `G`.
160
+
161
+ Parameters
162
+ ----------
163
+ G : NetworkX graph
164
+
165
+ cutoff : integer, optional
166
+ Depth at which to stop the search. Only paths of length at most
167
+ `cutoff` are returned.
168
+
169
+ Returns
170
+ -------
171
+ lengths : iterator
172
+ (source, dictionary) iterator with dictionary keyed by target and
173
+ shortest path length as the key value.
174
+
175
+ Notes
176
+ -----
177
+ The iterator returned only has reachable node pairs.
178
+
179
+ Examples
180
+ --------
181
+ >>> G = nx.path_graph(5)
182
+ >>> length = dict(nx.all_pairs_shortest_path_length(G))
183
+ >>> for node in [0, 1, 2, 3, 4]:
184
+ ... print(f"1 - {node}: {length[1][node]}")
185
+ 1 - 0: 1
186
+ 1 - 1: 0
187
+ 1 - 2: 1
188
+ 1 - 3: 2
189
+ 1 - 4: 3
190
+ >>> length[3][2]
191
+ 1
192
+ >>> length[2][2]
193
+ 0
194
+
195
+ """
196
+ length = single_source_shortest_path_length
197
+ # TODO This can be trivially parallelized.
198
+ for n in G:
199
+ yield (n, length(G, n, cutoff=cutoff))
200
+
201
+
202
+ @nx._dispatchable
203
+ def bidirectional_shortest_path(G, source, target):
204
+ """Returns a list of nodes in a shortest path between source and target.
205
+
206
+ Parameters
207
+ ----------
208
+ G : NetworkX graph
209
+
210
+ source : node label
211
+ starting node for path
212
+
213
+ target : node label
214
+ ending node for path
215
+
216
+ Returns
217
+ -------
218
+ path: list
219
+ List of nodes in a path from source to target.
220
+
221
+ Raises
222
+ ------
223
+ NetworkXNoPath
224
+ If no path exists between source and target.
225
+
226
+ Examples
227
+ --------
228
+ >>> G = nx.Graph()
229
+ >>> nx.add_path(G, [0, 1, 2, 3, 0, 4, 5, 6, 7, 4])
230
+ >>> nx.bidirectional_shortest_path(G, 2, 6)
231
+ [2, 1, 0, 4, 5, 6]
232
+
233
+ See Also
234
+ --------
235
+ shortest_path
236
+
237
+ Notes
238
+ -----
239
+ This algorithm is used by shortest_path(G, source, target).
240
+ """
241
+
242
+ if source not in G or target not in G:
243
+ msg = f"Either source {source} or target {target} is not in G"
244
+ raise nx.NodeNotFound(msg)
245
+
246
+ # call helper to do the real work
247
+ results = _bidirectional_pred_succ(G, source, target)
248
+ pred, succ, w = results
249
+
250
+ # build path from pred+w+succ
251
+ path = []
252
+ # from source to w
253
+ while w is not None:
254
+ path.append(w)
255
+ w = pred[w]
256
+ path.reverse()
257
+ # from w to target
258
+ w = succ[path[-1]]
259
+ while w is not None:
260
+ path.append(w)
261
+ w = succ[w]
262
+
263
+ return path
264
+
265
+
266
+ def _bidirectional_pred_succ(G, source, target):
267
+ """Bidirectional shortest path helper.
268
+
269
+ Returns (pred, succ, w) where
270
+ pred is a dictionary of predecessors from w to the source, and
271
+ succ is a dictionary of successors from w to the target.
272
+ """
273
+ # does BFS from both source and target and meets in the middle
274
+ if target == source:
275
+ return ({target: None}, {source: None}, source)
276
+
277
+ # handle either directed or undirected
278
+ if G.is_directed():
279
+ Gpred = G.pred
280
+ Gsucc = G.succ
281
+ else:
282
+ Gpred = G.adj
283
+ Gsucc = G.adj
284
+
285
+ # predecessor and successors in search
286
+ pred = {source: None}
287
+ succ = {target: None}
288
+
289
+ # initialize fringes, start with forward
290
+ forward_fringe = [source]
291
+ reverse_fringe = [target]
292
+
293
+ while forward_fringe and reverse_fringe:
294
+ if len(forward_fringe) <= len(reverse_fringe):
295
+ this_level = forward_fringe
296
+ forward_fringe = []
297
+ for v in this_level:
298
+ for w in Gsucc[v]:
299
+ if w not in pred:
300
+ forward_fringe.append(w)
301
+ pred[w] = v
302
+ if w in succ: # path found
303
+ return pred, succ, w
304
+ else:
305
+ this_level = reverse_fringe
306
+ reverse_fringe = []
307
+ for v in this_level:
308
+ for w in Gpred[v]:
309
+ if w not in succ:
310
+ succ[w] = v
311
+ reverse_fringe.append(w)
312
+ if w in pred: # found path
313
+ return pred, succ, w
314
+
315
+ raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
316
+
317
+
318
+ @nx._dispatchable
319
+ def single_source_shortest_path(G, source, cutoff=None):
320
+ """Compute shortest path between source
321
+ and all other nodes reachable from source.
322
+
323
+ Parameters
324
+ ----------
325
+ G : NetworkX graph
326
+
327
+ source : node label
328
+ Starting node for path
329
+
330
+ cutoff : integer, optional
331
+ Depth to stop the search. Only paths of length <= cutoff are returned.
332
+
333
+ Returns
334
+ -------
335
+ paths : dictionary
336
+ Dictionary, keyed by target, of shortest paths.
337
+
338
+ Examples
339
+ --------
340
+ >>> G = nx.path_graph(5)
341
+ >>> path = nx.single_source_shortest_path(G, 0)
342
+ >>> path[4]
343
+ [0, 1, 2, 3, 4]
344
+
345
+ Notes
346
+ -----
347
+ The shortest path is not necessarily unique. So there can be multiple
348
+ paths between the source and each target node, all of which have the
349
+ same 'shortest' length. For each target node, this function returns
350
+ only one of those paths.
351
+
352
+ See Also
353
+ --------
354
+ shortest_path
355
+ """
356
+ if source not in G:
357
+ raise nx.NodeNotFound(f"Source {source} not in G")
358
+
359
+ def join(p1, p2):
360
+ return p1 + p2
361
+
362
+ if cutoff is None:
363
+ cutoff = float("inf")
364
+ nextlevel = {source: 1} # list of nodes to check at next level
365
+ paths = {source: [source]} # paths dictionary (paths to key from source)
366
+ return dict(_single_shortest_path(G.adj, nextlevel, paths, cutoff, join))
367
+
368
+
369
+ def _single_shortest_path(adj, firstlevel, paths, cutoff, join):
370
+ """Returns shortest paths
371
+
372
+ Shortest Path helper function
373
+ Parameters
374
+ ----------
375
+ adj : dict
376
+ Adjacency dict or view
377
+ firstlevel : dict
378
+ starting nodes, e.g. {source: 1} or {target: 1}
379
+ paths : dict
380
+ paths for starting nodes, e.g. {source: [source]}
381
+ cutoff : int or float
382
+ level at which we stop the process
383
+ join : function
384
+ function to construct a path from two partial paths. Requires two
385
+ list inputs `p1` and `p2`, and returns a list. Usually returns
386
+ `p1 + p2` (forward from source) or `p2 + p1` (backward from target)
387
+ """
388
+ level = 0 # the current level
389
+ nextlevel = firstlevel
390
+ while nextlevel and cutoff > level:
391
+ thislevel = nextlevel
392
+ nextlevel = {}
393
+ for v in thislevel:
394
+ for w in adj[v]:
395
+ if w not in paths:
396
+ paths[w] = join(paths[v], [w])
397
+ nextlevel[w] = 1
398
+ level += 1
399
+ return paths
400
+
401
+
402
+ @nx._dispatchable
403
+ def single_target_shortest_path(G, target, cutoff=None):
404
+ """Compute shortest path to target from all nodes that reach target.
405
+
406
+ Parameters
407
+ ----------
408
+ G : NetworkX graph
409
+
410
+ target : node label
411
+ Target node for path
412
+
413
+ cutoff : integer, optional
414
+ Depth to stop the search. Only paths of length <= cutoff are returned.
415
+
416
+ Returns
417
+ -------
418
+ paths : dictionary
419
+ Dictionary, keyed by target, of shortest paths.
420
+
421
+ Examples
422
+ --------
423
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
424
+ >>> path = nx.single_target_shortest_path(G, 4)
425
+ >>> path[0]
426
+ [0, 1, 2, 3, 4]
427
+
428
+ Notes
429
+ -----
430
+ The shortest path is not necessarily unique. So there can be multiple
431
+ paths between the source and each target node, all of which have the
432
+ same 'shortest' length. For each target node, this function returns
433
+ only one of those paths.
434
+
435
+ See Also
436
+ --------
437
+ shortest_path, single_source_shortest_path
438
+ """
439
+ if target not in G:
440
+ raise nx.NodeNotFound(f"Target {target} not in G")
441
+
442
+ def join(p1, p2):
443
+ return p2 + p1
444
+
445
+ # handle undirected graphs
446
+ adj = G.pred if G.is_directed() else G.adj
447
+ if cutoff is None:
448
+ cutoff = float("inf")
449
+ nextlevel = {target: 1} # list of nodes to check at next level
450
+ paths = {target: [target]} # paths dictionary (paths to key from source)
451
+ return dict(_single_shortest_path(adj, nextlevel, paths, cutoff, join))
452
+
453
+
454
+ @nx._dispatchable
455
+ def all_pairs_shortest_path(G, cutoff=None):
456
+ """Compute shortest paths between all nodes.
457
+
458
+ Parameters
459
+ ----------
460
+ G : NetworkX graph
461
+
462
+ cutoff : integer, optional
463
+ Depth at which to stop the search. Only paths of length at most
464
+ `cutoff` are returned.
465
+
466
+ Returns
467
+ -------
468
+ paths : iterator
469
+ Dictionary, keyed by source and target, of shortest paths.
470
+
471
+ Examples
472
+ --------
473
+ >>> G = nx.path_graph(5)
474
+ >>> path = dict(nx.all_pairs_shortest_path(G))
475
+ >>> print(path[0][4])
476
+ [0, 1, 2, 3, 4]
477
+
478
+ Notes
479
+ -----
480
+ There may be multiple shortest paths with the same length between
481
+ two nodes. For each pair, this function returns only one of those paths.
482
+
483
+ See Also
484
+ --------
485
+ floyd_warshall
486
+ all_pairs_all_shortest_paths
487
+
488
+ """
489
+ # TODO This can be trivially parallelized.
490
+ for n in G:
491
+ yield (n, single_source_shortest_path(G, n, cutoff=cutoff))
492
+
493
+
494
+ @nx._dispatchable
495
+ def predecessor(G, source, target=None, cutoff=None, return_seen=None):
496
+ """Returns dict of predecessors for the path from source to all nodes in G.
497
+
498
+ Parameters
499
+ ----------
500
+ G : NetworkX graph
501
+
502
+ source : node label
503
+ Starting node for path
504
+
505
+ target : node label, optional
506
+ Ending node for path. If provided only predecessors between
507
+ source and target are returned
508
+
509
+ cutoff : integer, optional
510
+ Depth to stop the search. Only paths of length <= cutoff are returned.
511
+
512
+ return_seen : bool, optional (default=None)
513
+ Whether to return a dictionary, keyed by node, of the level (number of
514
+ hops) to reach the node (as seen during breadth-first-search).
515
+
516
+ Returns
517
+ -------
518
+ pred : dictionary
519
+ Dictionary, keyed by node, of predecessors in the shortest path.
520
+
521
+
522
+ (pred, seen): tuple of dictionaries
523
+ If `return_seen` argument is set to `True`, then a tuple of dictionaries
524
+ is returned. The first element is the dictionary, keyed by node, of
525
+ predecessors in the shortest path. The second element is the dictionary,
526
+ keyed by node, of the level (number of hops) to reach the node (as seen
527
+ during breadth-first-search).
528
+
529
+ Examples
530
+ --------
531
+ >>> G = nx.path_graph(4)
532
+ >>> list(G)
533
+ [0, 1, 2, 3]
534
+ >>> nx.predecessor(G, 0)
535
+ {0: [], 1: [0], 2: [1], 3: [2]}
536
+ >>> nx.predecessor(G, 0, return_seen=True)
537
+ ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})
538
+
539
+
540
+ """
541
+ if source not in G:
542
+ raise nx.NodeNotFound(f"Source {source} not in G")
543
+
544
+ level = 0 # the current level
545
+ nextlevel = [source] # list of nodes to check at next level
546
+ seen = {source: level} # level (number of hops) when seen in BFS
547
+ pred = {source: []} # predecessor dictionary
548
+ while nextlevel:
549
+ level = level + 1
550
+ thislevel = nextlevel
551
+ nextlevel = []
552
+ for v in thislevel:
553
+ for w in G[v]:
554
+ if w not in seen:
555
+ pred[w] = [v]
556
+ seen[w] = level
557
+ nextlevel.append(w)
558
+ elif seen[w] == level: # add v to predecessor list if it
559
+ pred[w].append(v) # is at the correct level
560
+ if cutoff and cutoff <= level:
561
+ break
562
+
563
+ if target is not None:
564
+ if return_seen:
565
+ if target not in pred:
566
+ return ([], -1) # No predecessor
567
+ return (pred[target], seen[target])
568
+ else:
569
+ if target not in pred:
570
+ return [] # No predecessor
571
+ return pred[target]
572
+ else:
573
+ if return_seen:
574
+ return (pred, seen)
575
+ else:
576
+ return pred
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/shortest_paths/weighted.py ADDED
@@ -0,0 +1,2517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shortest path algorithms for weighted graphs.
3
+ """
4
+
5
+ from collections import deque
6
+ from heapq import heappop, heappush
7
+ from itertools import count
8
+
9
+ import networkx as nx
10
+ from networkx.algorithms.shortest_paths.generic import _build_paths_from_predecessors
11
+
12
+ __all__ = [
13
+ "dijkstra_path",
14
+ "dijkstra_path_length",
15
+ "bidirectional_dijkstra",
16
+ "single_source_dijkstra",
17
+ "single_source_dijkstra_path",
18
+ "single_source_dijkstra_path_length",
19
+ "multi_source_dijkstra",
20
+ "multi_source_dijkstra_path",
21
+ "multi_source_dijkstra_path_length",
22
+ "all_pairs_dijkstra",
23
+ "all_pairs_dijkstra_path",
24
+ "all_pairs_dijkstra_path_length",
25
+ "dijkstra_predecessor_and_distance",
26
+ "bellman_ford_path",
27
+ "bellman_ford_path_length",
28
+ "single_source_bellman_ford",
29
+ "single_source_bellman_ford_path",
30
+ "single_source_bellman_ford_path_length",
31
+ "all_pairs_bellman_ford_path",
32
+ "all_pairs_bellman_ford_path_length",
33
+ "bellman_ford_predecessor_and_distance",
34
+ "negative_edge_cycle",
35
+ "find_negative_cycle",
36
+ "goldberg_radzik",
37
+ "johnson",
38
+ ]
39
+
40
+
41
+ def _weight_function(G, weight):
42
+ """Returns a function that returns the weight of an edge.
43
+
44
+ The returned function is specifically suitable for input to
45
+ functions :func:`_dijkstra` and :func:`_bellman_ford_relaxation`.
46
+
47
+ Parameters
48
+ ----------
49
+ G : NetworkX graph.
50
+
51
+ weight : string or function
52
+ If it is callable, `weight` itself is returned. If it is a string,
53
+ it is assumed to be the name of the edge attribute that represents
54
+ the weight of an edge. In that case, a function is returned that
55
+ gets the edge weight according to the specified edge attribute.
56
+
57
+ Returns
58
+ -------
59
+ function
60
+ This function returns a callable that accepts exactly three inputs:
61
+ a node, an node adjacent to the first one, and the edge attribute
62
+ dictionary for the eedge joining those nodes. That function returns
63
+ a number representing the weight of an edge.
64
+
65
+ If `G` is a multigraph, and `weight` is not callable, the
66
+ minimum edge weight over all parallel edges is returned. If any edge
67
+ does not have an attribute with key `weight`, it is assumed to
68
+ have weight one.
69
+
70
+ """
71
+ if callable(weight):
72
+ return weight
73
+ # If the weight keyword argument is not callable, we assume it is a
74
+ # string representing the edge attribute containing the weight of
75
+ # the edge.
76
+ if G.is_multigraph():
77
+ return lambda u, v, d: min(attr.get(weight, 1) for attr in d.values())
78
+ return lambda u, v, data: data.get(weight, 1)
79
+
80
+
81
+ @nx._dispatchable(edge_attrs="weight")
82
+ def dijkstra_path(G, source, target, weight="weight"):
83
+ """Returns the shortest weighted path from source to target in G.
84
+
85
+ Uses Dijkstra's Method to compute the shortest weighted path
86
+ between two nodes in a graph.
87
+
88
+ Parameters
89
+ ----------
90
+ G : NetworkX graph
91
+
92
+ source : node
93
+ Starting node
94
+
95
+ target : node
96
+ Ending node
97
+
98
+ weight : string or function
99
+ If this is a string, then edge weights will be accessed via the
100
+ edge attribute with this key (that is, the weight of the edge
101
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
102
+ such edge attribute exists, the weight of the edge is assumed to
103
+ be one.
104
+
105
+ If this is a function, the weight of an edge is the value
106
+ returned by the function. The function must accept exactly three
107
+ positional arguments: the two endpoints of an edge and the
108
+ dictionary of edge attributes for that edge. The function must
109
+ return a number or None to indicate a hidden edge.
110
+
111
+ Returns
112
+ -------
113
+ path : list
114
+ List of nodes in a shortest path.
115
+
116
+ Raises
117
+ ------
118
+ NodeNotFound
119
+ If `source` is not in `G`.
120
+
121
+ NetworkXNoPath
122
+ If no path exists between source and target.
123
+
124
+ Examples
125
+ --------
126
+ >>> G = nx.path_graph(5)
127
+ >>> print(nx.dijkstra_path(G, 0, 4))
128
+ [0, 1, 2, 3, 4]
129
+
130
+ Find edges of shortest path in Multigraph
131
+
132
+ >>> G = nx.MultiDiGraph()
133
+ >>> G.add_weighted_edges_from([(1, 2, 0.75), (1, 2, 0.5), (2, 3, 0.5), (1, 3, 1.5)])
134
+ >>> nodes = nx.dijkstra_path(G, 1, 3)
135
+ >>> edges = nx.utils.pairwise(nodes)
136
+ >>> list(
137
+ ... (u, v, min(G[u][v], key=lambda k: G[u][v][k].get("weight", 1)))
138
+ ... for u, v in edges
139
+ ... )
140
+ [(1, 2, 1), (2, 3, 0)]
141
+
142
+ Notes
143
+ -----
144
+ Edge weight attributes must be numerical.
145
+ Distances are calculated as sums of weighted edges traversed.
146
+
147
+ The weight function can be used to hide edges by returning None.
148
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
149
+ will find the shortest red path.
150
+
151
+ The weight function can be used to include node weights.
152
+
153
+ >>> def func(u, v, d):
154
+ ... node_u_wt = G.nodes[u].get("node_weight", 1)
155
+ ... node_v_wt = G.nodes[v].get("node_weight", 1)
156
+ ... edge_wt = d.get("weight", 1)
157
+ ... return node_u_wt / 2 + node_v_wt / 2 + edge_wt
158
+
159
+ In this example we take the average of start and end node
160
+ weights of an edge and add it to the weight of the edge.
161
+
162
+ The function :func:`single_source_dijkstra` computes both
163
+ path and length-of-path if you need both, use that.
164
+
165
+ See Also
166
+ --------
167
+ bidirectional_dijkstra
168
+ bellman_ford_path
169
+ single_source_dijkstra
170
+ """
171
+ (length, path) = single_source_dijkstra(G, source, target=target, weight=weight)
172
+ return path
173
+
174
+
175
+ @nx._dispatchable(edge_attrs="weight")
176
+ def dijkstra_path_length(G, source, target, weight="weight"):
177
+ """Returns the shortest weighted path length in G from source to target.
178
+
179
+ Uses Dijkstra's Method to compute the shortest weighted path length
180
+ between two nodes in a graph.
181
+
182
+ Parameters
183
+ ----------
184
+ G : NetworkX graph
185
+
186
+ source : node label
187
+ starting node for path
188
+
189
+ target : node label
190
+ ending node for path
191
+
192
+ weight : string or function
193
+ If this is a string, then edge weights will be accessed via the
194
+ edge attribute with this key (that is, the weight of the edge
195
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
196
+ such edge attribute exists, the weight of the edge is assumed to
197
+ be one.
198
+
199
+ If this is a function, the weight of an edge is the value
200
+ returned by the function. The function must accept exactly three
201
+ positional arguments: the two endpoints of an edge and the
202
+ dictionary of edge attributes for that edge. The function must
203
+ return a number or None to indicate a hidden edge.
204
+
205
+ Returns
206
+ -------
207
+ length : number
208
+ Shortest path length.
209
+
210
+ Raises
211
+ ------
212
+ NodeNotFound
213
+ If `source` is not in `G`.
214
+
215
+ NetworkXNoPath
216
+ If no path exists between source and target.
217
+
218
+ Examples
219
+ --------
220
+ >>> G = nx.path_graph(5)
221
+ >>> nx.dijkstra_path_length(G, 0, 4)
222
+ 4
223
+
224
+ Notes
225
+ -----
226
+ Edge weight attributes must be numerical.
227
+ Distances are calculated as sums of weighted edges traversed.
228
+
229
+ The weight function can be used to hide edges by returning None.
230
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
231
+ will find the shortest red path.
232
+
233
+ The function :func:`single_source_dijkstra` computes both
234
+ path and length-of-path if you need both, use that.
235
+
236
+ See Also
237
+ --------
238
+ bidirectional_dijkstra
239
+ bellman_ford_path_length
240
+ single_source_dijkstra
241
+
242
+ """
243
+ if source not in G:
244
+ raise nx.NodeNotFound(f"Node {source} not found in graph")
245
+ if source == target:
246
+ return 0
247
+ weight = _weight_function(G, weight)
248
+ length = _dijkstra(G, source, weight, target=target)
249
+ try:
250
+ return length[target]
251
+ except KeyError as err:
252
+ raise nx.NetworkXNoPath(f"Node {target} not reachable from {source}") from err
253
+
254
+
255
+ @nx._dispatchable(edge_attrs="weight")
256
+ def single_source_dijkstra_path(G, source, cutoff=None, weight="weight"):
257
+ """Find shortest weighted paths in G from a source node.
258
+
259
+ Compute shortest path between source and all other reachable
260
+ nodes for a weighted graph.
261
+
262
+ Parameters
263
+ ----------
264
+ G : NetworkX graph
265
+
266
+ source : node
267
+ Starting node for path.
268
+
269
+ cutoff : integer or float, optional
270
+ Length (sum of edge weights) at which the search is stopped.
271
+ If cutoff is provided, only return paths with summed weight <= cutoff.
272
+
273
+ weight : string or function
274
+ If this is a string, then edge weights will be accessed via the
275
+ edge attribute with this key (that is, the weight of the edge
276
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
277
+ such edge attribute exists, the weight of the edge is assumed to
278
+ be one.
279
+
280
+ If this is a function, the weight of an edge is the value
281
+ returned by the function. The function must accept exactly three
282
+ positional arguments: the two endpoints of an edge and the
283
+ dictionary of edge attributes for that edge. The function must
284
+ return a number or None to indicate a hidden edge.
285
+
286
+ Returns
287
+ -------
288
+ paths : dictionary
289
+ Dictionary of shortest path lengths keyed by target.
290
+
291
+ Raises
292
+ ------
293
+ NodeNotFound
294
+ If `source` is not in `G`.
295
+
296
+ Examples
297
+ --------
298
+ >>> G = nx.path_graph(5)
299
+ >>> path = nx.single_source_dijkstra_path(G, 0)
300
+ >>> path[4]
301
+ [0, 1, 2, 3, 4]
302
+
303
+ Notes
304
+ -----
305
+ Edge weight attributes must be numerical.
306
+ Distances are calculated as sums of weighted edges traversed.
307
+
308
+ The weight function can be used to hide edges by returning None.
309
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
310
+ will find the shortest red path.
311
+
312
+ See Also
313
+ --------
314
+ single_source_dijkstra, single_source_bellman_ford
315
+
316
+ """
317
+ return multi_source_dijkstra_path(G, {source}, cutoff=cutoff, weight=weight)
318
+
319
+
320
+ @nx._dispatchable(edge_attrs="weight")
321
+ def single_source_dijkstra_path_length(G, source, cutoff=None, weight="weight"):
322
+ """Find shortest weighted path lengths in G from a source node.
323
+
324
+ Compute the shortest path length between source and all other
325
+ reachable nodes for a weighted graph.
326
+
327
+ Parameters
328
+ ----------
329
+ G : NetworkX graph
330
+
331
+ source : node label
332
+ Starting node for path
333
+
334
+ cutoff : integer or float, optional
335
+ Length (sum of edge weights) at which the search is stopped.
336
+ If cutoff is provided, only return paths with summed weight <= cutoff.
337
+
338
+ weight : string or function
339
+ If this is a string, then edge weights will be accessed via the
340
+ edge attribute with this key (that is, the weight of the edge
341
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
342
+ such edge attribute exists, the weight of the edge is assumed to
343
+ be one.
344
+
345
+ If this is a function, the weight of an edge is the value
346
+ returned by the function. The function must accept exactly three
347
+ positional arguments: the two endpoints of an edge and the
348
+ dictionary of edge attributes for that edge. The function must
349
+ return a number or None to indicate a hidden edge.
350
+
351
+ Returns
352
+ -------
353
+ length : dict
354
+ Dict keyed by node to shortest path length from source.
355
+
356
+ Raises
357
+ ------
358
+ NodeNotFound
359
+ If `source` is not in `G`.
360
+
361
+ Examples
362
+ --------
363
+ >>> G = nx.path_graph(5)
364
+ >>> length = nx.single_source_dijkstra_path_length(G, 0)
365
+ >>> length[4]
366
+ 4
367
+ >>> for node in [0, 1, 2, 3, 4]:
368
+ ... print(f"{node}: {length[node]}")
369
+ 0: 0
370
+ 1: 1
371
+ 2: 2
372
+ 3: 3
373
+ 4: 4
374
+
375
+ Notes
376
+ -----
377
+ Edge weight attributes must be numerical.
378
+ Distances are calculated as sums of weighted edges traversed.
379
+
380
+ The weight function can be used to hide edges by returning None.
381
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
382
+ will find the shortest red path.
383
+
384
+ See Also
385
+ --------
386
+ single_source_dijkstra, single_source_bellman_ford_path_length
387
+
388
+ """
389
+ return multi_source_dijkstra_path_length(G, {source}, cutoff=cutoff, weight=weight)
390
+
391
+
392
+ @nx._dispatchable(edge_attrs="weight")
393
+ def single_source_dijkstra(G, source, target=None, cutoff=None, weight="weight"):
394
+ """Find shortest weighted paths and lengths from a source node.
395
+
396
+ Compute the shortest path length between source and all other
397
+ reachable nodes for a weighted graph.
398
+
399
+ Uses Dijkstra's algorithm to compute shortest paths and lengths
400
+ between a source and all other reachable nodes in a weighted graph.
401
+
402
+ Parameters
403
+ ----------
404
+ G : NetworkX graph
405
+
406
+ source : node label
407
+ Starting node for path
408
+
409
+ target : node label, optional
410
+ Ending node for path
411
+
412
+ cutoff : integer or float, optional
413
+ Length (sum of edge weights) at which the search is stopped.
414
+ If cutoff is provided, only return paths with summed weight <= cutoff.
415
+
416
+
417
+ weight : string or function
418
+ If this is a string, then edge weights will be accessed via the
419
+ edge attribute with this key (that is, the weight of the edge
420
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
421
+ such edge attribute exists, the weight of the edge is assumed to
422
+ be one.
423
+
424
+ If this is a function, the weight of an edge is the value
425
+ returned by the function. The function must accept exactly three
426
+ positional arguments: the two endpoints of an edge and the
427
+ dictionary of edge attributes for that edge. The function must
428
+ return a number or None to indicate a hidden edge.
429
+
430
+ Returns
431
+ -------
432
+ distance, path : pair of dictionaries, or numeric and list.
433
+ If target is None, paths and lengths to all nodes are computed.
434
+ The return value is a tuple of two dictionaries keyed by target nodes.
435
+ The first dictionary stores distance to each target node.
436
+ The second stores the path to each target node.
437
+ If target is not None, returns a tuple (distance, path), where
438
+ distance is the distance from source to target and path is a list
439
+ representing the path from source to target.
440
+
441
+ Raises
442
+ ------
443
+ NodeNotFound
444
+ If `source` is not in `G`.
445
+
446
+ Examples
447
+ --------
448
+ >>> G = nx.path_graph(5)
449
+ >>> length, path = nx.single_source_dijkstra(G, 0)
450
+ >>> length[4]
451
+ 4
452
+ >>> for node in [0, 1, 2, 3, 4]:
453
+ ... print(f"{node}: {length[node]}")
454
+ 0: 0
455
+ 1: 1
456
+ 2: 2
457
+ 3: 3
458
+ 4: 4
459
+ >>> path[4]
460
+ [0, 1, 2, 3, 4]
461
+ >>> length, path = nx.single_source_dijkstra(G, 0, 1)
462
+ >>> length
463
+ 1
464
+ >>> path
465
+ [0, 1]
466
+
467
+ Notes
468
+ -----
469
+ Edge weight attributes must be numerical.
470
+ Distances are calculated as sums of weighted edges traversed.
471
+
472
+ The weight function can be used to hide edges by returning None.
473
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
474
+ will find the shortest red path.
475
+
476
+ Based on the Python cookbook recipe (119466) at
477
+ https://code.activestate.com/recipes/119466/
478
+
479
+ This algorithm is not guaranteed to work if edge weights
480
+ are negative or are floating point numbers
481
+ (overflows and roundoff errors can cause problems).
482
+
483
+ See Also
484
+ --------
485
+ single_source_dijkstra_path
486
+ single_source_dijkstra_path_length
487
+ single_source_bellman_ford
488
+ """
489
+ return multi_source_dijkstra(
490
+ G, {source}, cutoff=cutoff, target=target, weight=weight
491
+ )
492
+
493
+
494
+ @nx._dispatchable(edge_attrs="weight")
495
+ def multi_source_dijkstra_path(G, sources, cutoff=None, weight="weight"):
496
+ """Find shortest weighted paths in G from a given set of source
497
+ nodes.
498
+
499
+ Compute shortest path between any of the source nodes and all other
500
+ reachable nodes for a weighted graph.
501
+
502
+ Parameters
503
+ ----------
504
+ G : NetworkX graph
505
+
506
+ sources : non-empty set of nodes
507
+ Starting nodes for paths. If this is just a set containing a
508
+ single node, then all paths computed by this function will start
509
+ from that node. If there are two or more nodes in the set, the
510
+ computed paths may begin from any one of the start nodes.
511
+
512
+ cutoff : integer or float, optional
513
+ Length (sum of edge weights) at which the search is stopped.
514
+ If cutoff is provided, only return paths with summed weight <= cutoff.
515
+
516
+ weight : string or function
517
+ If this is a string, then edge weights will be accessed via the
518
+ edge attribute with this key (that is, the weight of the edge
519
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
520
+ such edge attribute exists, the weight of the edge is assumed to
521
+ be one.
522
+
523
+ If this is a function, the weight of an edge is the value
524
+ returned by the function. The function must accept exactly three
525
+ positional arguments: the two endpoints of an edge and the
526
+ dictionary of edge attributes for that edge. The function must
527
+ return a number or None to indicate a hidden edge.
528
+
529
+ Returns
530
+ -------
531
+ paths : dictionary
532
+ Dictionary of shortest paths keyed by target.
533
+
534
+ Examples
535
+ --------
536
+ >>> G = nx.path_graph(5)
537
+ >>> path = nx.multi_source_dijkstra_path(G, {0, 4})
538
+ >>> path[1]
539
+ [0, 1]
540
+ >>> path[3]
541
+ [4, 3]
542
+
543
+ Notes
544
+ -----
545
+ Edge weight attributes must be numerical.
546
+ Distances are calculated as sums of weighted edges traversed.
547
+
548
+ The weight function can be used to hide edges by returning None.
549
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
550
+ will find the shortest red path.
551
+
552
+ Raises
553
+ ------
554
+ ValueError
555
+ If `sources` is empty.
556
+ NodeNotFound
557
+ If any of `sources` is not in `G`.
558
+
559
+ See Also
560
+ --------
561
+ multi_source_dijkstra, multi_source_bellman_ford
562
+
563
+ """
564
+ length, path = multi_source_dijkstra(G, sources, cutoff=cutoff, weight=weight)
565
+ return path
566
+
567
+
568
+ @nx._dispatchable(edge_attrs="weight")
569
+ def multi_source_dijkstra_path_length(G, sources, cutoff=None, weight="weight"):
570
+ """Find shortest weighted path lengths in G from a given set of
571
+ source nodes.
572
+
573
+ Compute the shortest path length between any of the source nodes and
574
+ all other reachable nodes for a weighted graph.
575
+
576
+ Parameters
577
+ ----------
578
+ G : NetworkX graph
579
+
580
+ sources : non-empty set of nodes
581
+ Starting nodes for paths. If this is just a set containing a
582
+ single node, then all paths computed by this function will start
583
+ from that node. If there are two or more nodes in the set, the
584
+ computed paths may begin from any one of the start nodes.
585
+
586
+ cutoff : integer or float, optional
587
+ Length (sum of edge weights) at which the search is stopped.
588
+ If cutoff is provided, only return paths with summed weight <= cutoff.
589
+
590
+ weight : string or function
591
+ If this is a string, then edge weights will be accessed via the
592
+ edge attribute with this key (that is, the weight of the edge
593
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
594
+ such edge attribute exists, the weight of the edge is assumed to
595
+ be one.
596
+
597
+ If this is a function, the weight of an edge is the value
598
+ returned by the function. The function must accept exactly three
599
+ positional arguments: the two endpoints of an edge and the
600
+ dictionary of edge attributes for that edge. The function must
601
+ return a number or None to indicate a hidden edge.
602
+
603
+ Returns
604
+ -------
605
+ length : dict
606
+ Dict keyed by node to shortest path length to nearest source.
607
+
608
+ Examples
609
+ --------
610
+ >>> G = nx.path_graph(5)
611
+ >>> length = nx.multi_source_dijkstra_path_length(G, {0, 4})
612
+ >>> for node in [0, 1, 2, 3, 4]:
613
+ ... print(f"{node}: {length[node]}")
614
+ 0: 0
615
+ 1: 1
616
+ 2: 2
617
+ 3: 1
618
+ 4: 0
619
+
620
+ Notes
621
+ -----
622
+ Edge weight attributes must be numerical.
623
+ Distances are calculated as sums of weighted edges traversed.
624
+
625
+ The weight function can be used to hide edges by returning None.
626
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
627
+ will find the shortest red path.
628
+
629
+ Raises
630
+ ------
631
+ ValueError
632
+ If `sources` is empty.
633
+ NodeNotFound
634
+ If any of `sources` is not in `G`.
635
+
636
+ See Also
637
+ --------
638
+ multi_source_dijkstra
639
+
640
+ """
641
+ if not sources:
642
+ raise ValueError("sources must not be empty")
643
+ for s in sources:
644
+ if s not in G:
645
+ raise nx.NodeNotFound(f"Node {s} not found in graph")
646
+ weight = _weight_function(G, weight)
647
+ return _dijkstra_multisource(G, sources, weight, cutoff=cutoff)
648
+
649
+
650
+ @nx._dispatchable(edge_attrs="weight")
651
+ def multi_source_dijkstra(G, sources, target=None, cutoff=None, weight="weight"):
652
+ """Find shortest weighted paths and lengths from a given set of
653
+ source nodes.
654
+
655
+ Uses Dijkstra's algorithm to compute the shortest paths and lengths
656
+ between one of the source nodes and the given `target`, or all other
657
+ reachable nodes if not specified, for a weighted graph.
658
+
659
+ Parameters
660
+ ----------
661
+ G : NetworkX graph
662
+
663
+ sources : non-empty set of nodes
664
+ Starting nodes for paths. If this is just a set containing a
665
+ single node, then all paths computed by this function will start
666
+ from that node. If there are two or more nodes in the set, the
667
+ computed paths may begin from any one of the start nodes.
668
+
669
+ target : node label, optional
670
+ Ending node for path
671
+
672
+ cutoff : integer or float, optional
673
+ Length (sum of edge weights) at which the search is stopped.
674
+ If cutoff is provided, only return paths with summed weight <= cutoff.
675
+
676
+ weight : string or function
677
+ If this is a string, then edge weights will be accessed via the
678
+ edge attribute with this key (that is, the weight of the edge
679
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
680
+ such edge attribute exists, the weight of the edge is assumed to
681
+ be one.
682
+
683
+ If this is a function, the weight of an edge is the value
684
+ returned by the function. The function must accept exactly three
685
+ positional arguments: the two endpoints of an edge and the
686
+ dictionary of edge attributes for that edge. The function must
687
+ return a number or None to indicate a hidden edge.
688
+
689
+ Returns
690
+ -------
691
+ distance, path : pair of dictionaries, or numeric and list
692
+ If target is None, returns a tuple of two dictionaries keyed by node.
693
+ The first dictionary stores distance from one of the source nodes.
694
+ The second stores the path from one of the sources to that node.
695
+ If target is not None, returns a tuple of (distance, path) where
696
+ distance is the distance from source to target and path is a list
697
+ representing the path from source to target.
698
+
699
+ Examples
700
+ --------
701
+ >>> G = nx.path_graph(5)
702
+ >>> length, path = nx.multi_source_dijkstra(G, {0, 4})
703
+ >>> for node in [0, 1, 2, 3, 4]:
704
+ ... print(f"{node}: {length[node]}")
705
+ 0: 0
706
+ 1: 1
707
+ 2: 2
708
+ 3: 1
709
+ 4: 0
710
+ >>> path[1]
711
+ [0, 1]
712
+ >>> path[3]
713
+ [4, 3]
714
+
715
+ >>> length, path = nx.multi_source_dijkstra(G, {0, 4}, 1)
716
+ >>> length
717
+ 1
718
+ >>> path
719
+ [0, 1]
720
+
721
+ Notes
722
+ -----
723
+ Edge weight attributes must be numerical.
724
+ Distances are calculated as sums of weighted edges traversed.
725
+
726
+ The weight function can be used to hide edges by returning None.
727
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
728
+ will find the shortest red path.
729
+
730
+ Based on the Python cookbook recipe (119466) at
731
+ https://code.activestate.com/recipes/119466/
732
+
733
+ This algorithm is not guaranteed to work if edge weights
734
+ are negative or are floating point numbers
735
+ (overflows and roundoff errors can cause problems).
736
+
737
+ Raises
738
+ ------
739
+ ValueError
740
+ If `sources` is empty.
741
+ NodeNotFound
742
+ If any of `sources` is not in `G`.
743
+
744
+ See Also
745
+ --------
746
+ multi_source_dijkstra_path
747
+ multi_source_dijkstra_path_length
748
+
749
+ """
750
+ if not sources:
751
+ raise ValueError("sources must not be empty")
752
+ for s in sources:
753
+ if s not in G:
754
+ raise nx.NodeNotFound(f"Node {s} not found in graph")
755
+ if target in sources:
756
+ return (0, [target])
757
+ weight = _weight_function(G, weight)
758
+ paths = {source: [source] for source in sources} # dictionary of paths
759
+ dist = _dijkstra_multisource(
760
+ G, sources, weight, paths=paths, cutoff=cutoff, target=target
761
+ )
762
+ if target is None:
763
+ return (dist, paths)
764
+ try:
765
+ return (dist[target], paths[target])
766
+ except KeyError as err:
767
+ raise nx.NetworkXNoPath(f"No path to {target}.") from err
768
+
769
+
770
+ def _dijkstra(G, source, weight, pred=None, paths=None, cutoff=None, target=None):
771
+ """Uses Dijkstra's algorithm to find shortest weighted paths from a
772
+ single source.
773
+
774
+ This is a convenience function for :func:`_dijkstra_multisource`
775
+ with all the arguments the same, except the keyword argument
776
+ `sources` set to ``[source]``.
777
+
778
+ """
779
+ return _dijkstra_multisource(
780
+ G, [source], weight, pred=pred, paths=paths, cutoff=cutoff, target=target
781
+ )
782
+
783
+
784
+ def _dijkstra_multisource(
785
+ G, sources, weight, pred=None, paths=None, cutoff=None, target=None
786
+ ):
787
+ """Uses Dijkstra's algorithm to find shortest weighted paths
788
+
789
+ Parameters
790
+ ----------
791
+ G : NetworkX graph
792
+
793
+ sources : non-empty iterable of nodes
794
+ Starting nodes for paths. If this is just an iterable containing
795
+ a single node, then all paths computed by this function will
796
+ start from that node. If there are two or more nodes in this
797
+ iterable, the computed paths may begin from any one of the start
798
+ nodes.
799
+
800
+ weight: function
801
+ Function with (u, v, data) input that returns that edge's weight
802
+ or None to indicate a hidden edge
803
+
804
+ pred: dict of lists, optional(default=None)
805
+ dict to store a list of predecessors keyed by that node
806
+ If None, predecessors are not stored.
807
+
808
+ paths: dict, optional (default=None)
809
+ dict to store the path list from source to each node, keyed by node.
810
+ If None, paths are not stored.
811
+
812
+ target : node label, optional
813
+ Ending node for path. Search is halted when target is found.
814
+
815
+ cutoff : integer or float, optional
816
+ Length (sum of edge weights) at which the search is stopped.
817
+ If cutoff is provided, only return paths with summed weight <= cutoff.
818
+
819
+ Returns
820
+ -------
821
+ distance : dictionary
822
+ A mapping from node to shortest distance to that node from one
823
+ of the source nodes.
824
+
825
+ Raises
826
+ ------
827
+ NodeNotFound
828
+ If any of `sources` is not in `G`.
829
+
830
+ Notes
831
+ -----
832
+ The optional predecessor and path dictionaries can be accessed by
833
+ the caller through the original pred and paths objects passed
834
+ as arguments. No need to explicitly return pred or paths.
835
+
836
+ """
837
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
838
+
839
+ push = heappush
840
+ pop = heappop
841
+ dist = {} # dictionary of final distances
842
+ seen = {}
843
+ # fringe is heapq with 3-tuples (distance,c,node)
844
+ # use the count c to avoid comparing nodes (may not be able to)
845
+ c = count()
846
+ fringe = []
847
+ for source in sources:
848
+ seen[source] = 0
849
+ push(fringe, (0, next(c), source))
850
+ while fringe:
851
+ (d, _, v) = pop(fringe)
852
+ if v in dist:
853
+ continue # already searched this node.
854
+ dist[v] = d
855
+ if v == target:
856
+ break
857
+ for u, e in G_succ[v].items():
858
+ cost = weight(v, u, e)
859
+ if cost is None:
860
+ continue
861
+ vu_dist = dist[v] + cost
862
+ if cutoff is not None:
863
+ if vu_dist > cutoff:
864
+ continue
865
+ if u in dist:
866
+ u_dist = dist[u]
867
+ if vu_dist < u_dist:
868
+ raise ValueError("Contradictory paths found:", "negative weights?")
869
+ elif pred is not None and vu_dist == u_dist:
870
+ pred[u].append(v)
871
+ elif u not in seen or vu_dist < seen[u]:
872
+ seen[u] = vu_dist
873
+ push(fringe, (vu_dist, next(c), u))
874
+ if paths is not None:
875
+ paths[u] = paths[v] + [u]
876
+ if pred is not None:
877
+ pred[u] = [v]
878
+ elif vu_dist == seen[u]:
879
+ if pred is not None:
880
+ pred[u].append(v)
881
+
882
+ # The optional predecessor and path dictionaries can be accessed
883
+ # by the caller via the pred and paths objects passed as arguments.
884
+ return dist
885
+
886
+
887
+ @nx._dispatchable(edge_attrs="weight")
888
+ def dijkstra_predecessor_and_distance(G, source, cutoff=None, weight="weight"):
889
+ """Compute weighted shortest path length and predecessors.
890
+
891
+ Uses Dijkstra's Method to obtain the shortest weighted paths
892
+ and return dictionaries of predecessors for each node and
893
+ distance for each node from the `source`.
894
+
895
+ Parameters
896
+ ----------
897
+ G : NetworkX graph
898
+
899
+ source : node label
900
+ Starting node for path
901
+
902
+ cutoff : integer or float, optional
903
+ Length (sum of edge weights) at which the search is stopped.
904
+ If cutoff is provided, only return paths with summed weight <= cutoff.
905
+
906
+ weight : string or function
907
+ If this is a string, then edge weights will be accessed via the
908
+ edge attribute with this key (that is, the weight of the edge
909
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
910
+ such edge attribute exists, the weight of the edge is assumed to
911
+ be one.
912
+
913
+ If this is a function, the weight of an edge is the value
914
+ returned by the function. The function must accept exactly three
915
+ positional arguments: the two endpoints of an edge and the
916
+ dictionary of edge attributes for that edge. The function must
917
+ return a number or None to indicate a hidden edge.
918
+
919
+ Returns
920
+ -------
921
+ pred, distance : dictionaries
922
+ Returns two dictionaries representing a list of predecessors
923
+ of a node and the distance to each node.
924
+
925
+ Raises
926
+ ------
927
+ NodeNotFound
928
+ If `source` is not in `G`.
929
+
930
+ Notes
931
+ -----
932
+ Edge weight attributes must be numerical.
933
+ Distances are calculated as sums of weighted edges traversed.
934
+
935
+ The list of predecessors contains more than one element only when
936
+ there are more than one shortest paths to the key node.
937
+
938
+ Examples
939
+ --------
940
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
941
+ >>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0)
942
+ >>> sorted(pred.items())
943
+ [(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
944
+ >>> sorted(dist.items())
945
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
946
+
947
+ >>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0, 1)
948
+ >>> sorted(pred.items())
949
+ [(0, []), (1, [0])]
950
+ >>> sorted(dist.items())
951
+ [(0, 0), (1, 1)]
952
+ """
953
+ if source not in G:
954
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
955
+ weight = _weight_function(G, weight)
956
+ pred = {source: []} # dictionary of predecessors
957
+ return (pred, _dijkstra(G, source, weight, pred=pred, cutoff=cutoff))
958
+
959
+
960
+ @nx._dispatchable(edge_attrs="weight")
961
+ def all_pairs_dijkstra(G, cutoff=None, weight="weight"):
962
+ """Find shortest weighted paths and lengths between all nodes.
963
+
964
+ Parameters
965
+ ----------
966
+ G : NetworkX graph
967
+
968
+ cutoff : integer or float, optional
969
+ Length (sum of edge weights) at which the search is stopped.
970
+ If cutoff is provided, only return paths with summed weight <= cutoff.
971
+
972
+ weight : string or function
973
+ If this is a string, then edge weights will be accessed via the
974
+ edge attribute with this key (that is, the weight of the edge
975
+ joining `u` to `v` will be ``G.edge[u][v][weight]``). If no
976
+ such edge attribute exists, the weight of the edge is assumed to
977
+ be one.
978
+
979
+ If this is a function, the weight of an edge is the value
980
+ returned by the function. The function must accept exactly three
981
+ positional arguments: the two endpoints of an edge and the
982
+ dictionary of edge attributes for that edge. The function must
983
+ return a number or None to indicate a hidden edge.
984
+
985
+ Yields
986
+ ------
987
+ (node, (distance, path)) : (node obj, (dict, dict))
988
+ Each source node has two associated dicts. The first holds distance
989
+ keyed by target and the second holds paths keyed by target.
990
+ (See single_source_dijkstra for the source/target node terminology.)
991
+ If desired you can apply `dict()` to this function to create a dict
992
+ keyed by source node to the two dicts.
993
+
994
+ Examples
995
+ --------
996
+ >>> G = nx.path_graph(5)
997
+ >>> len_path = dict(nx.all_pairs_dijkstra(G))
998
+ >>> len_path[3][0][1]
999
+ 2
1000
+ >>> for node in [0, 1, 2, 3, 4]:
1001
+ ... print(f"3 - {node}: {len_path[3][0][node]}")
1002
+ 3 - 0: 3
1003
+ 3 - 1: 2
1004
+ 3 - 2: 1
1005
+ 3 - 3: 0
1006
+ 3 - 4: 1
1007
+ >>> len_path[3][1][1]
1008
+ [3, 2, 1]
1009
+ >>> for n, (dist, path) in nx.all_pairs_dijkstra(G):
1010
+ ... print(path[1])
1011
+ [0, 1]
1012
+ [1]
1013
+ [2, 1]
1014
+ [3, 2, 1]
1015
+ [4, 3, 2, 1]
1016
+
1017
+ Notes
1018
+ -----
1019
+ Edge weight attributes must be numerical.
1020
+ Distances are calculated as sums of weighted edges traversed.
1021
+
1022
+ The yielded dicts only have keys for reachable nodes.
1023
+ """
1024
+ for n in G:
1025
+ dist, path = single_source_dijkstra(G, n, cutoff=cutoff, weight=weight)
1026
+ yield (n, (dist, path))
1027
+
1028
+
1029
+ @nx._dispatchable(edge_attrs="weight")
1030
+ def all_pairs_dijkstra_path_length(G, cutoff=None, weight="weight"):
1031
+ """Compute shortest path lengths between all nodes in a weighted graph.
1032
+
1033
+ Parameters
1034
+ ----------
1035
+ G : NetworkX graph
1036
+
1037
+ cutoff : integer or float, optional
1038
+ Length (sum of edge weights) at which the search is stopped.
1039
+ If cutoff is provided, only return paths with summed weight <= cutoff.
1040
+
1041
+ weight : string or function
1042
+ If this is a string, then edge weights will be accessed via the
1043
+ edge attribute with this key (that is, the weight of the edge
1044
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1045
+ such edge attribute exists, the weight of the edge is assumed to
1046
+ be one.
1047
+
1048
+ If this is a function, the weight of an edge is the value
1049
+ returned by the function. The function must accept exactly three
1050
+ positional arguments: the two endpoints of an edge and the
1051
+ dictionary of edge attributes for that edge. The function must
1052
+ return a number or None to indicate a hidden edge.
1053
+
1054
+ Returns
1055
+ -------
1056
+ distance : iterator
1057
+ (source, dictionary) iterator with dictionary keyed by target and
1058
+ shortest path length as the key value.
1059
+
1060
+ Examples
1061
+ --------
1062
+ >>> G = nx.path_graph(5)
1063
+ >>> length = dict(nx.all_pairs_dijkstra_path_length(G))
1064
+ >>> for node in [0, 1, 2, 3, 4]:
1065
+ ... print(f"1 - {node}: {length[1][node]}")
1066
+ 1 - 0: 1
1067
+ 1 - 1: 0
1068
+ 1 - 2: 1
1069
+ 1 - 3: 2
1070
+ 1 - 4: 3
1071
+ >>> length[3][2]
1072
+ 1
1073
+ >>> length[2][2]
1074
+ 0
1075
+
1076
+ Notes
1077
+ -----
1078
+ Edge weight attributes must be numerical.
1079
+ Distances are calculated as sums of weighted edges traversed.
1080
+
1081
+ The dictionary returned only has keys for reachable node pairs.
1082
+ """
1083
+ length = single_source_dijkstra_path_length
1084
+ for n in G:
1085
+ yield (n, length(G, n, cutoff=cutoff, weight=weight))
1086
+
1087
+
1088
+ @nx._dispatchable(edge_attrs="weight")
1089
+ def all_pairs_dijkstra_path(G, cutoff=None, weight="weight"):
1090
+ """Compute shortest paths between all nodes in a weighted graph.
1091
+
1092
+ Parameters
1093
+ ----------
1094
+ G : NetworkX graph
1095
+
1096
+ cutoff : integer or float, optional
1097
+ Length (sum of edge weights) at which the search is stopped.
1098
+ If cutoff is provided, only return paths with summed weight <= cutoff.
1099
+
1100
+ weight : string or function
1101
+ If this is a string, then edge weights will be accessed via the
1102
+ edge attribute with this key (that is, the weight of the edge
1103
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1104
+ such edge attribute exists, the weight of the edge is assumed to
1105
+ be one.
1106
+
1107
+ If this is a function, the weight of an edge is the value
1108
+ returned by the function. The function must accept exactly three
1109
+ positional arguments: the two endpoints of an edge and the
1110
+ dictionary of edge attributes for that edge. The function must
1111
+ return a number or None to indicate a hidden edge.
1112
+
1113
+ Returns
1114
+ -------
1115
+ paths : iterator
1116
+ (source, dictionary) iterator with dictionary keyed by target and
1117
+ shortest path as the key value.
1118
+
1119
+ Examples
1120
+ --------
1121
+ >>> G = nx.path_graph(5)
1122
+ >>> path = dict(nx.all_pairs_dijkstra_path(G))
1123
+ >>> path[0][4]
1124
+ [0, 1, 2, 3, 4]
1125
+
1126
+ Notes
1127
+ -----
1128
+ Edge weight attributes must be numerical.
1129
+ Distances are calculated as sums of weighted edges traversed.
1130
+
1131
+ See Also
1132
+ --------
1133
+ floyd_warshall, all_pairs_bellman_ford_path
1134
+
1135
+ """
1136
+ path = single_source_dijkstra_path
1137
+ # TODO This can be trivially parallelized.
1138
+ for n in G:
1139
+ yield (n, path(G, n, cutoff=cutoff, weight=weight))
1140
+
1141
+
1142
+ @nx._dispatchable(edge_attrs="weight")
1143
+ def bellman_ford_predecessor_and_distance(
1144
+ G, source, target=None, weight="weight", heuristic=False
1145
+ ):
1146
+ """Compute shortest path lengths and predecessors on shortest paths
1147
+ in weighted graphs.
1148
+
1149
+ The algorithm has a running time of $O(mn)$ where $n$ is the number of
1150
+ nodes and $m$ is the number of edges. It is slower than Dijkstra but
1151
+ can handle negative edge weights.
1152
+
1153
+ If a negative cycle is detected, you can use :func:`find_negative_cycle`
1154
+ to return the cycle and examine it. Shortest paths are not defined when
1155
+ a negative cycle exists because once reached, the path can cycle forever
1156
+ to build up arbitrarily low weights.
1157
+
1158
+ Parameters
1159
+ ----------
1160
+ G : NetworkX graph
1161
+ The algorithm works for all types of graphs, including directed
1162
+ graphs and multigraphs.
1163
+
1164
+ source: node label
1165
+ Starting node for path
1166
+
1167
+ target : node label, optional
1168
+ Ending node for path
1169
+
1170
+ weight : string or function
1171
+ If this is a string, then edge weights will be accessed via the
1172
+ edge attribute with this key (that is, the weight of the edge
1173
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1174
+ such edge attribute exists, the weight of the edge is assumed to
1175
+ be one.
1176
+
1177
+ If this is a function, the weight of an edge is the value
1178
+ returned by the function. The function must accept exactly three
1179
+ positional arguments: the two endpoints of an edge and the
1180
+ dictionary of edge attributes for that edge. The function must
1181
+ return a number.
1182
+
1183
+ heuristic : bool
1184
+ Determines whether to use a heuristic to early detect negative
1185
+ cycles at a hopefully negligible cost.
1186
+
1187
+ Returns
1188
+ -------
1189
+ pred, dist : dictionaries
1190
+ Returns two dictionaries keyed by node to predecessor in the
1191
+ path and to the distance from the source respectively.
1192
+
1193
+ Raises
1194
+ ------
1195
+ NodeNotFound
1196
+ If `source` is not in `G`.
1197
+
1198
+ NetworkXUnbounded
1199
+ If the (di)graph contains a negative (di)cycle, the
1200
+ algorithm raises an exception to indicate the presence of the
1201
+ negative (di)cycle. Note: any negative weight edge in an
1202
+ undirected graph is a negative cycle.
1203
+
1204
+ Examples
1205
+ --------
1206
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
1207
+ >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0)
1208
+ >>> sorted(pred.items())
1209
+ [(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
1210
+ >>> sorted(dist.items())
1211
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
1212
+
1213
+ >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0, 1)
1214
+ >>> sorted(pred.items())
1215
+ [(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
1216
+ >>> sorted(dist.items())
1217
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
1218
+
1219
+ >>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
1220
+ >>> G[1][2]["weight"] = -7
1221
+ >>> nx.bellman_ford_predecessor_and_distance(G, 0)
1222
+ Traceback (most recent call last):
1223
+ ...
1224
+ networkx.exception.NetworkXUnbounded: Negative cycle detected.
1225
+
1226
+ See Also
1227
+ --------
1228
+ find_negative_cycle
1229
+
1230
+ Notes
1231
+ -----
1232
+ Edge weight attributes must be numerical.
1233
+ Distances are calculated as sums of weighted edges traversed.
1234
+
1235
+ The dictionaries returned only have keys for nodes reachable from
1236
+ the source.
1237
+
1238
+ In the case where the (di)graph is not connected, if a component
1239
+ not containing the source contains a negative (di)cycle, it
1240
+ will not be detected.
1241
+
1242
+ In NetworkX v2.1 and prior, the source node had predecessor `[None]`.
1243
+ In NetworkX v2.2 this changed to the source node having predecessor `[]`
1244
+ """
1245
+ if source not in G:
1246
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
1247
+ weight = _weight_function(G, weight)
1248
+ if G.is_multigraph():
1249
+ if any(
1250
+ weight(u, v, {k: d}) < 0
1251
+ for u, v, k, d in nx.selfloop_edges(G, keys=True, data=True)
1252
+ ):
1253
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
1254
+ else:
1255
+ if any(weight(u, v, d) < 0 for u, v, d in nx.selfloop_edges(G, data=True)):
1256
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
1257
+
1258
+ dist = {source: 0}
1259
+ pred = {source: []}
1260
+
1261
+ if len(G) == 1:
1262
+ return pred, dist
1263
+
1264
+ weight = _weight_function(G, weight)
1265
+
1266
+ dist = _bellman_ford(
1267
+ G, [source], weight, pred=pred, dist=dist, target=target, heuristic=heuristic
1268
+ )
1269
+ return (pred, dist)
1270
+
1271
+
1272
+ def _bellman_ford(
1273
+ G,
1274
+ source,
1275
+ weight,
1276
+ pred=None,
1277
+ paths=None,
1278
+ dist=None,
1279
+ target=None,
1280
+ heuristic=True,
1281
+ ):
1282
+ """Calls relaxation loop for Bellman–Ford algorithm and builds paths
1283
+
1284
+ This is an implementation of the SPFA variant.
1285
+ See https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm
1286
+
1287
+ Parameters
1288
+ ----------
1289
+ G : NetworkX graph
1290
+
1291
+ source: list
1292
+ List of source nodes. The shortest path from any of the source
1293
+ nodes will be found if multiple sources are provided.
1294
+
1295
+ weight : function
1296
+ The weight of an edge is the value returned by the function. The
1297
+ function must accept exactly three positional arguments: the two
1298
+ endpoints of an edge and the dictionary of edge attributes for
1299
+ that edge. The function must return a number.
1300
+
1301
+ pred: dict of lists, optional (default=None)
1302
+ dict to store a list of predecessors keyed by that node
1303
+ If None, predecessors are not stored
1304
+
1305
+ paths: dict, optional (default=None)
1306
+ dict to store the path list from source to each node, keyed by node
1307
+ If None, paths are not stored
1308
+
1309
+ dist: dict, optional (default=None)
1310
+ dict to store distance from source to the keyed node
1311
+ If None, returned dist dict contents default to 0 for every node in the
1312
+ source list
1313
+
1314
+ target: node label, optional
1315
+ Ending node for path. Path lengths to other destinations may (and
1316
+ probably will) be incorrect.
1317
+
1318
+ heuristic : bool
1319
+ Determines whether to use a heuristic to early detect negative
1320
+ cycles at a hopefully negligible cost.
1321
+
1322
+ Returns
1323
+ -------
1324
+ dist : dict
1325
+ Returns a dict keyed by node to the distance from the source.
1326
+ Dicts for paths and pred are in the mutated input dicts by those names.
1327
+
1328
+ Raises
1329
+ ------
1330
+ NodeNotFound
1331
+ If any of `source` is not in `G`.
1332
+
1333
+ NetworkXUnbounded
1334
+ If the (di)graph contains a negative (di)cycle, the
1335
+ algorithm raises an exception to indicate the presence of the
1336
+ negative (di)cycle. Note: any negative weight edge in an
1337
+ undirected graph is a negative cycle
1338
+ """
1339
+ if pred is None:
1340
+ pred = {v: [] for v in source}
1341
+
1342
+ if dist is None:
1343
+ dist = {v: 0 for v in source}
1344
+
1345
+ negative_cycle_found = _inner_bellman_ford(
1346
+ G,
1347
+ source,
1348
+ weight,
1349
+ pred,
1350
+ dist,
1351
+ heuristic,
1352
+ )
1353
+ if negative_cycle_found is not None:
1354
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
1355
+
1356
+ if paths is not None:
1357
+ sources = set(source)
1358
+ dsts = [target] if target is not None else pred
1359
+ for dst in dsts:
1360
+ gen = _build_paths_from_predecessors(sources, dst, pred)
1361
+ paths[dst] = next(gen)
1362
+
1363
+ return dist
1364
+
1365
+
1366
+ def _inner_bellman_ford(
1367
+ G,
1368
+ sources,
1369
+ weight,
1370
+ pred,
1371
+ dist=None,
1372
+ heuristic=True,
1373
+ ):
1374
+ """Inner Relaxation loop for Bellman–Ford algorithm.
1375
+
1376
+ This is an implementation of the SPFA variant.
1377
+ See https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm
1378
+
1379
+ Parameters
1380
+ ----------
1381
+ G : NetworkX graph
1382
+
1383
+ source: list
1384
+ List of source nodes. The shortest path from any of the source
1385
+ nodes will be found if multiple sources are provided.
1386
+
1387
+ weight : function
1388
+ The weight of an edge is the value returned by the function. The
1389
+ function must accept exactly three positional arguments: the two
1390
+ endpoints of an edge and the dictionary of edge attributes for
1391
+ that edge. The function must return a number.
1392
+
1393
+ pred: dict of lists
1394
+ dict to store a list of predecessors keyed by that node
1395
+
1396
+ dist: dict, optional (default=None)
1397
+ dict to store distance from source to the keyed node
1398
+ If None, returned dist dict contents default to 0 for every node in the
1399
+ source list
1400
+
1401
+ heuristic : bool
1402
+ Determines whether to use a heuristic to early detect negative
1403
+ cycles at a hopefully negligible cost.
1404
+
1405
+ Returns
1406
+ -------
1407
+ node or None
1408
+ Return a node `v` where processing discovered a negative cycle.
1409
+ If no negative cycle found, return None.
1410
+
1411
+ Raises
1412
+ ------
1413
+ NodeNotFound
1414
+ If any of `source` is not in `G`.
1415
+ """
1416
+ for s in sources:
1417
+ if s not in G:
1418
+ raise nx.NodeNotFound(f"Source {s} not in G")
1419
+
1420
+ if pred is None:
1421
+ pred = {v: [] for v in sources}
1422
+
1423
+ if dist is None:
1424
+ dist = {v: 0 for v in sources}
1425
+
1426
+ # Heuristic Storage setup. Note: use None because nodes cannot be None
1427
+ nonexistent_edge = (None, None)
1428
+ pred_edge = {v: None for v in sources}
1429
+ recent_update = {v: nonexistent_edge for v in sources}
1430
+
1431
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
1432
+ inf = float("inf")
1433
+ n = len(G)
1434
+
1435
+ count = {}
1436
+ q = deque(sources)
1437
+ in_q = set(sources)
1438
+ while q:
1439
+ u = q.popleft()
1440
+ in_q.remove(u)
1441
+
1442
+ # Skip relaxations if any of the predecessors of u is in the queue.
1443
+ if all(pred_u not in in_q for pred_u in pred[u]):
1444
+ dist_u = dist[u]
1445
+ for v, e in G_succ[u].items():
1446
+ dist_v = dist_u + weight(u, v, e)
1447
+
1448
+ if dist_v < dist.get(v, inf):
1449
+ # In this conditional branch we are updating the path with v.
1450
+ # If it happens that some earlier update also added node v
1451
+ # that implies the existence of a negative cycle since
1452
+ # after the update node v would lie on the update path twice.
1453
+ # The update path is stored up to one of the source nodes,
1454
+ # therefore u is always in the dict recent_update
1455
+ if heuristic:
1456
+ if v in recent_update[u]:
1457
+ # Negative cycle found!
1458
+ pred[v].append(u)
1459
+ return v
1460
+
1461
+ # Transfer the recent update info from u to v if the
1462
+ # same source node is the head of the update path.
1463
+ # If the source node is responsible for the cost update,
1464
+ # then clear the history and use it instead.
1465
+ if v in pred_edge and pred_edge[v] == u:
1466
+ recent_update[v] = recent_update[u]
1467
+ else:
1468
+ recent_update[v] = (u, v)
1469
+
1470
+ if v not in in_q:
1471
+ q.append(v)
1472
+ in_q.add(v)
1473
+ count_v = count.get(v, 0) + 1
1474
+ if count_v == n:
1475
+ # Negative cycle found!
1476
+ return v
1477
+
1478
+ count[v] = count_v
1479
+ dist[v] = dist_v
1480
+ pred[v] = [u]
1481
+ pred_edge[v] = u
1482
+
1483
+ elif dist.get(v) is not None and dist_v == dist.get(v):
1484
+ pred[v].append(u)
1485
+
1486
+ # successfully found shortest_path. No negative cycles found.
1487
+ return None
1488
+
1489
+
1490
+ @nx._dispatchable(edge_attrs="weight")
1491
+ def bellman_ford_path(G, source, target, weight="weight"):
1492
+ """Returns the shortest path from source to target in a weighted graph G.
1493
+
1494
+ Parameters
1495
+ ----------
1496
+ G : NetworkX graph
1497
+
1498
+ source : node
1499
+ Starting node
1500
+
1501
+ target : node
1502
+ Ending node
1503
+
1504
+ weight : string or function (default="weight")
1505
+ If this is a string, then edge weights will be accessed via the
1506
+ edge attribute with this key (that is, the weight of the edge
1507
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1508
+ such edge attribute exists, the weight of the edge is assumed to
1509
+ be one.
1510
+
1511
+ If this is a function, the weight of an edge is the value
1512
+ returned by the function. The function must accept exactly three
1513
+ positional arguments: the two endpoints of an edge and the
1514
+ dictionary of edge attributes for that edge. The function must
1515
+ return a number.
1516
+
1517
+ Returns
1518
+ -------
1519
+ path : list
1520
+ List of nodes in a shortest path.
1521
+
1522
+ Raises
1523
+ ------
1524
+ NodeNotFound
1525
+ If `source` is not in `G`.
1526
+
1527
+ NetworkXNoPath
1528
+ If no path exists between source and target.
1529
+
1530
+ Examples
1531
+ --------
1532
+ >>> G = nx.path_graph(5)
1533
+ >>> nx.bellman_ford_path(G, 0, 4)
1534
+ [0, 1, 2, 3, 4]
1535
+
1536
+ Notes
1537
+ -----
1538
+ Edge weight attributes must be numerical.
1539
+ Distances are calculated as sums of weighted edges traversed.
1540
+
1541
+ See Also
1542
+ --------
1543
+ dijkstra_path, bellman_ford_path_length
1544
+ """
1545
+ length, path = single_source_bellman_ford(G, source, target=target, weight=weight)
1546
+ return path
1547
+
1548
+
1549
+ @nx._dispatchable(edge_attrs="weight")
1550
+ def bellman_ford_path_length(G, source, target, weight="weight"):
1551
+ """Returns the shortest path length from source to target
1552
+ in a weighted graph.
1553
+
1554
+ Parameters
1555
+ ----------
1556
+ G : NetworkX graph
1557
+
1558
+ source : node label
1559
+ starting node for path
1560
+
1561
+ target : node label
1562
+ ending node for path
1563
+
1564
+ weight : string or function (default="weight")
1565
+ If this is a string, then edge weights will be accessed via the
1566
+ edge attribute with this key (that is, the weight of the edge
1567
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1568
+ such edge attribute exists, the weight of the edge is assumed to
1569
+ be one.
1570
+
1571
+ If this is a function, the weight of an edge is the value
1572
+ returned by the function. The function must accept exactly three
1573
+ positional arguments: the two endpoints of an edge and the
1574
+ dictionary of edge attributes for that edge. The function must
1575
+ return a number.
1576
+
1577
+ Returns
1578
+ -------
1579
+ length : number
1580
+ Shortest path length.
1581
+
1582
+ Raises
1583
+ ------
1584
+ NodeNotFound
1585
+ If `source` is not in `G`.
1586
+
1587
+ NetworkXNoPath
1588
+ If no path exists between source and target.
1589
+
1590
+ Examples
1591
+ --------
1592
+ >>> G = nx.path_graph(5)
1593
+ >>> nx.bellman_ford_path_length(G, 0, 4)
1594
+ 4
1595
+
1596
+ Notes
1597
+ -----
1598
+ Edge weight attributes must be numerical.
1599
+ Distances are calculated as sums of weighted edges traversed.
1600
+
1601
+ See Also
1602
+ --------
1603
+ dijkstra_path_length, bellman_ford_path
1604
+ """
1605
+ if source == target:
1606
+ if source not in G:
1607
+ raise nx.NodeNotFound(f"Node {source} not found in graph")
1608
+ return 0
1609
+
1610
+ weight = _weight_function(G, weight)
1611
+
1612
+ length = _bellman_ford(G, [source], weight, target=target)
1613
+
1614
+ try:
1615
+ return length[target]
1616
+ except KeyError as err:
1617
+ raise nx.NetworkXNoPath(f"node {target} not reachable from {source}") from err
1618
+
1619
+
1620
+ @nx._dispatchable(edge_attrs="weight")
1621
+ def single_source_bellman_ford_path(G, source, weight="weight"):
1622
+ """Compute shortest path between source and all other reachable
1623
+ nodes for a weighted graph.
1624
+
1625
+ Parameters
1626
+ ----------
1627
+ G : NetworkX graph
1628
+
1629
+ source : node
1630
+ Starting node for path.
1631
+
1632
+ weight : string or function (default="weight")
1633
+ If this is a string, then edge weights will be accessed via the
1634
+ edge attribute with this key (that is, the weight of the edge
1635
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1636
+ such edge attribute exists, the weight of the edge is assumed to
1637
+ be one.
1638
+
1639
+ If this is a function, the weight of an edge is the value
1640
+ returned by the function. The function must accept exactly three
1641
+ positional arguments: the two endpoints of an edge and the
1642
+ dictionary of edge attributes for that edge. The function must
1643
+ return a number.
1644
+
1645
+ Returns
1646
+ -------
1647
+ paths : dictionary
1648
+ Dictionary of shortest path lengths keyed by target.
1649
+
1650
+ Raises
1651
+ ------
1652
+ NodeNotFound
1653
+ If `source` is not in `G`.
1654
+
1655
+ Examples
1656
+ --------
1657
+ >>> G = nx.path_graph(5)
1658
+ >>> path = nx.single_source_bellman_ford_path(G, 0)
1659
+ >>> path[4]
1660
+ [0, 1, 2, 3, 4]
1661
+
1662
+ Notes
1663
+ -----
1664
+ Edge weight attributes must be numerical.
1665
+ Distances are calculated as sums of weighted edges traversed.
1666
+
1667
+ See Also
1668
+ --------
1669
+ single_source_dijkstra, single_source_bellman_ford
1670
+
1671
+ """
1672
+ (length, path) = single_source_bellman_ford(G, source, weight=weight)
1673
+ return path
1674
+
1675
+
1676
+ @nx._dispatchable(edge_attrs="weight")
1677
+ def single_source_bellman_ford_path_length(G, source, weight="weight"):
1678
+ """Compute the shortest path length between source and all other
1679
+ reachable nodes for a weighted graph.
1680
+
1681
+ Parameters
1682
+ ----------
1683
+ G : NetworkX graph
1684
+
1685
+ source : node label
1686
+ Starting node for path
1687
+
1688
+ weight : string or function (default="weight")
1689
+ If this is a string, then edge weights will be accessed via the
1690
+ edge attribute with this key (that is, the weight of the edge
1691
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1692
+ such edge attribute exists, the weight of the edge is assumed to
1693
+ be one.
1694
+
1695
+ If this is a function, the weight of an edge is the value
1696
+ returned by the function. The function must accept exactly three
1697
+ positional arguments: the two endpoints of an edge and the
1698
+ dictionary of edge attributes for that edge. The function must
1699
+ return a number.
1700
+
1701
+ Returns
1702
+ -------
1703
+ length : dictionary
1704
+ Dictionary of shortest path length keyed by target
1705
+
1706
+ Raises
1707
+ ------
1708
+ NodeNotFound
1709
+ If `source` is not in `G`.
1710
+
1711
+ Examples
1712
+ --------
1713
+ >>> G = nx.path_graph(5)
1714
+ >>> length = nx.single_source_bellman_ford_path_length(G, 0)
1715
+ >>> length[4]
1716
+ 4
1717
+ >>> for node in [0, 1, 2, 3, 4]:
1718
+ ... print(f"{node}: {length[node]}")
1719
+ 0: 0
1720
+ 1: 1
1721
+ 2: 2
1722
+ 3: 3
1723
+ 4: 4
1724
+
1725
+ Notes
1726
+ -----
1727
+ Edge weight attributes must be numerical.
1728
+ Distances are calculated as sums of weighted edges traversed.
1729
+
1730
+ See Also
1731
+ --------
1732
+ single_source_dijkstra, single_source_bellman_ford
1733
+
1734
+ """
1735
+ weight = _weight_function(G, weight)
1736
+ return _bellman_ford(G, [source], weight)
1737
+
1738
+
1739
+ @nx._dispatchable(edge_attrs="weight")
1740
+ def single_source_bellman_ford(G, source, target=None, weight="weight"):
1741
+ """Compute shortest paths and lengths in a weighted graph G.
1742
+
1743
+ Uses Bellman-Ford algorithm for shortest paths.
1744
+
1745
+ Parameters
1746
+ ----------
1747
+ G : NetworkX graph
1748
+
1749
+ source : node label
1750
+ Starting node for path
1751
+
1752
+ target : node label, optional
1753
+ Ending node for path
1754
+
1755
+ weight : string or function
1756
+ If this is a string, then edge weights will be accessed via the
1757
+ edge attribute with this key (that is, the weight of the edge
1758
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1759
+ such edge attribute exists, the weight of the edge is assumed to
1760
+ be one.
1761
+
1762
+ If this is a function, the weight of an edge is the value
1763
+ returned by the function. The function must accept exactly three
1764
+ positional arguments: the two endpoints of an edge and the
1765
+ dictionary of edge attributes for that edge. The function must
1766
+ return a number.
1767
+
1768
+ Returns
1769
+ -------
1770
+ distance, path : pair of dictionaries, or numeric and list
1771
+ If target is None, returns a tuple of two dictionaries keyed by node.
1772
+ The first dictionary stores distance from one of the source nodes.
1773
+ The second stores the path from one of the sources to that node.
1774
+ If target is not None, returns a tuple of (distance, path) where
1775
+ distance is the distance from source to target and path is a list
1776
+ representing the path from source to target.
1777
+
1778
+ Raises
1779
+ ------
1780
+ NodeNotFound
1781
+ If `source` is not in `G`.
1782
+
1783
+ Examples
1784
+ --------
1785
+ >>> G = nx.path_graph(5)
1786
+ >>> length, path = nx.single_source_bellman_ford(G, 0)
1787
+ >>> length[4]
1788
+ 4
1789
+ >>> for node in [0, 1, 2, 3, 4]:
1790
+ ... print(f"{node}: {length[node]}")
1791
+ 0: 0
1792
+ 1: 1
1793
+ 2: 2
1794
+ 3: 3
1795
+ 4: 4
1796
+ >>> path[4]
1797
+ [0, 1, 2, 3, 4]
1798
+ >>> length, path = nx.single_source_bellman_ford(G, 0, 1)
1799
+ >>> length
1800
+ 1
1801
+ >>> path
1802
+ [0, 1]
1803
+
1804
+ Notes
1805
+ -----
1806
+ Edge weight attributes must be numerical.
1807
+ Distances are calculated as sums of weighted edges traversed.
1808
+
1809
+ See Also
1810
+ --------
1811
+ single_source_dijkstra
1812
+ single_source_bellman_ford_path
1813
+ single_source_bellman_ford_path_length
1814
+ """
1815
+ if source == target:
1816
+ if source not in G:
1817
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
1818
+ return (0, [source])
1819
+
1820
+ weight = _weight_function(G, weight)
1821
+
1822
+ paths = {source: [source]} # dictionary of paths
1823
+ dist = _bellman_ford(G, [source], weight, paths=paths, target=target)
1824
+ if target is None:
1825
+ return (dist, paths)
1826
+ try:
1827
+ return (dist[target], paths[target])
1828
+ except KeyError as err:
1829
+ msg = f"Node {target} not reachable from {source}"
1830
+ raise nx.NetworkXNoPath(msg) from err
1831
+
1832
+
1833
+ @nx._dispatchable(edge_attrs="weight")
1834
+ def all_pairs_bellman_ford_path_length(G, weight="weight"):
1835
+ """Compute shortest path lengths between all nodes in a weighted graph.
1836
+
1837
+ Parameters
1838
+ ----------
1839
+ G : NetworkX graph
1840
+
1841
+ weight : string or function (default="weight")
1842
+ If this is a string, then edge weights will be accessed via the
1843
+ edge attribute with this key (that is, the weight of the edge
1844
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1845
+ such edge attribute exists, the weight of the edge is assumed to
1846
+ be one.
1847
+
1848
+ If this is a function, the weight of an edge is the value
1849
+ returned by the function. The function must accept exactly three
1850
+ positional arguments: the two endpoints of an edge and the
1851
+ dictionary of edge attributes for that edge. The function must
1852
+ return a number.
1853
+
1854
+ Returns
1855
+ -------
1856
+ distance : iterator
1857
+ (source, dictionary) iterator with dictionary keyed by target and
1858
+ shortest path length as the key value.
1859
+
1860
+ Examples
1861
+ --------
1862
+ >>> G = nx.path_graph(5)
1863
+ >>> length = dict(nx.all_pairs_bellman_ford_path_length(G))
1864
+ >>> for node in [0, 1, 2, 3, 4]:
1865
+ ... print(f"1 - {node}: {length[1][node]}")
1866
+ 1 - 0: 1
1867
+ 1 - 1: 0
1868
+ 1 - 2: 1
1869
+ 1 - 3: 2
1870
+ 1 - 4: 3
1871
+ >>> length[3][2]
1872
+ 1
1873
+ >>> length[2][2]
1874
+ 0
1875
+
1876
+ Notes
1877
+ -----
1878
+ Edge weight attributes must be numerical.
1879
+ Distances are calculated as sums of weighted edges traversed.
1880
+
1881
+ The dictionary returned only has keys for reachable node pairs.
1882
+ """
1883
+ length = single_source_bellman_ford_path_length
1884
+ for n in G:
1885
+ yield (n, dict(length(G, n, weight=weight)))
1886
+
1887
+
1888
+ @nx._dispatchable(edge_attrs="weight")
1889
+ def all_pairs_bellman_ford_path(G, weight="weight"):
1890
+ """Compute shortest paths between all nodes in a weighted graph.
1891
+
1892
+ Parameters
1893
+ ----------
1894
+ G : NetworkX graph
1895
+
1896
+ weight : string or function (default="weight")
1897
+ If this is a string, then edge weights will be accessed via the
1898
+ edge attribute with this key (that is, the weight of the edge
1899
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1900
+ such edge attribute exists, the weight of the edge is assumed to
1901
+ be one.
1902
+
1903
+ If this is a function, the weight of an edge is the value
1904
+ returned by the function. The function must accept exactly three
1905
+ positional arguments: the two endpoints of an edge and the
1906
+ dictionary of edge attributes for that edge. The function must
1907
+ return a number.
1908
+
1909
+ Returns
1910
+ -------
1911
+ paths : iterator
1912
+ (source, dictionary) iterator with dictionary keyed by target and
1913
+ shortest path as the key value.
1914
+
1915
+ Examples
1916
+ --------
1917
+ >>> G = nx.path_graph(5)
1918
+ >>> path = dict(nx.all_pairs_bellman_ford_path(G))
1919
+ >>> path[0][4]
1920
+ [0, 1, 2, 3, 4]
1921
+
1922
+ Notes
1923
+ -----
1924
+ Edge weight attributes must be numerical.
1925
+ Distances are calculated as sums of weighted edges traversed.
1926
+
1927
+ See Also
1928
+ --------
1929
+ floyd_warshall, all_pairs_dijkstra_path
1930
+
1931
+ """
1932
+ path = single_source_bellman_ford_path
1933
+ # TODO This can be trivially parallelized.
1934
+ for n in G:
1935
+ yield (n, path(G, n, weight=weight))
1936
+
1937
+
1938
+ @nx._dispatchable(edge_attrs="weight")
1939
+ def goldberg_radzik(G, source, weight="weight"):
1940
+ """Compute shortest path lengths and predecessors on shortest paths
1941
+ in weighted graphs.
1942
+
1943
+ The algorithm has a running time of $O(mn)$ where $n$ is the number of
1944
+ nodes and $m$ is the number of edges. It is slower than Dijkstra but
1945
+ can handle negative edge weights.
1946
+
1947
+ Parameters
1948
+ ----------
1949
+ G : NetworkX graph
1950
+ The algorithm works for all types of graphs, including directed
1951
+ graphs and multigraphs.
1952
+
1953
+ source: node label
1954
+ Starting node for path
1955
+
1956
+ weight : string or function
1957
+ If this is a string, then edge weights will be accessed via the
1958
+ edge attribute with this key (that is, the weight of the edge
1959
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
1960
+ such edge attribute exists, the weight of the edge is assumed to
1961
+ be one.
1962
+
1963
+ If this is a function, the weight of an edge is the value
1964
+ returned by the function. The function must accept exactly three
1965
+ positional arguments: the two endpoints of an edge and the
1966
+ dictionary of edge attributes for that edge. The function must
1967
+ return a number.
1968
+
1969
+ Returns
1970
+ -------
1971
+ pred, dist : dictionaries
1972
+ Returns two dictionaries keyed by node to predecessor in the
1973
+ path and to the distance from the source respectively.
1974
+
1975
+ Raises
1976
+ ------
1977
+ NodeNotFound
1978
+ If `source` is not in `G`.
1979
+
1980
+ NetworkXUnbounded
1981
+ If the (di)graph contains a negative (di)cycle, the
1982
+ algorithm raises an exception to indicate the presence of the
1983
+ negative (di)cycle. Note: any negative weight edge in an
1984
+ undirected graph is a negative cycle.
1985
+
1986
+ As of NetworkX v3.2, a zero weight cycle is no longer
1987
+ incorrectly reported as a negative weight cycle.
1988
+
1989
+
1990
+ Examples
1991
+ --------
1992
+ >>> G = nx.path_graph(5, create_using=nx.DiGraph())
1993
+ >>> pred, dist = nx.goldberg_radzik(G, 0)
1994
+ >>> sorted(pred.items())
1995
+ [(0, None), (1, 0), (2, 1), (3, 2), (4, 3)]
1996
+ >>> sorted(dist.items())
1997
+ [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
1998
+
1999
+ >>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
2000
+ >>> G[1][2]["weight"] = -7
2001
+ >>> nx.goldberg_radzik(G, 0)
2002
+ Traceback (most recent call last):
2003
+ ...
2004
+ networkx.exception.NetworkXUnbounded: Negative cycle detected.
2005
+
2006
+ Notes
2007
+ -----
2008
+ Edge weight attributes must be numerical.
2009
+ Distances are calculated as sums of weighted edges traversed.
2010
+
2011
+ The dictionaries returned only have keys for nodes reachable from
2012
+ the source.
2013
+
2014
+ In the case where the (di)graph is not connected, if a component
2015
+ not containing the source contains a negative (di)cycle, it
2016
+ will not be detected.
2017
+
2018
+ """
2019
+ if source not in G:
2020
+ raise nx.NodeNotFound(f"Node {source} is not found in the graph")
2021
+ weight = _weight_function(G, weight)
2022
+ if G.is_multigraph():
2023
+ if any(
2024
+ weight(u, v, {k: d}) < 0
2025
+ for u, v, k, d in nx.selfloop_edges(G, keys=True, data=True)
2026
+ ):
2027
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
2028
+ else:
2029
+ if any(weight(u, v, d) < 0 for u, v, d in nx.selfloop_edges(G, data=True)):
2030
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
2031
+
2032
+ if len(G) == 1:
2033
+ return {source: None}, {source: 0}
2034
+
2035
+ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
2036
+
2037
+ inf = float("inf")
2038
+ d = {u: inf for u in G}
2039
+ d[source] = 0
2040
+ pred = {source: None}
2041
+
2042
+ def topo_sort(relabeled):
2043
+ """Topologically sort nodes relabeled in the previous round and detect
2044
+ negative cycles.
2045
+ """
2046
+ # List of nodes to scan in this round. Denoted by A in Goldberg and
2047
+ # Radzik's paper.
2048
+ to_scan = []
2049
+ # In the DFS in the loop below, neg_count records for each node the
2050
+ # number of edges of negative reduced costs on the path from a DFS root
2051
+ # to the node in the DFS forest. The reduced cost of an edge (u, v) is
2052
+ # defined as d[u] + weight[u][v] - d[v].
2053
+ #
2054
+ # neg_count also doubles as the DFS visit marker array.
2055
+ neg_count = {}
2056
+ for u in relabeled:
2057
+ # Skip visited nodes.
2058
+ if u in neg_count:
2059
+ continue
2060
+ d_u = d[u]
2061
+ # Skip nodes without out-edges of negative reduced costs.
2062
+ if all(d_u + weight(u, v, e) >= d[v] for v, e in G_succ[u].items()):
2063
+ continue
2064
+ # Nonrecursive DFS that inserts nodes reachable from u via edges of
2065
+ # nonpositive reduced costs into to_scan in (reverse) topological
2066
+ # order.
2067
+ stack = [(u, iter(G_succ[u].items()))]
2068
+ in_stack = {u}
2069
+ neg_count[u] = 0
2070
+ while stack:
2071
+ u, it = stack[-1]
2072
+ try:
2073
+ v, e = next(it)
2074
+ except StopIteration:
2075
+ to_scan.append(u)
2076
+ stack.pop()
2077
+ in_stack.remove(u)
2078
+ continue
2079
+ t = d[u] + weight(u, v, e)
2080
+ d_v = d[v]
2081
+ if t < d_v:
2082
+ is_neg = t < d_v
2083
+ d[v] = t
2084
+ pred[v] = u
2085
+ if v not in neg_count:
2086
+ neg_count[v] = neg_count[u] + int(is_neg)
2087
+ stack.append((v, iter(G_succ[v].items())))
2088
+ in_stack.add(v)
2089
+ elif v in in_stack and neg_count[u] + int(is_neg) > neg_count[v]:
2090
+ # (u, v) is a back edge, and the cycle formed by the
2091
+ # path v to u and (u, v) contains at least one edge of
2092
+ # negative reduced cost. The cycle must be of negative
2093
+ # cost.
2094
+ raise nx.NetworkXUnbounded("Negative cycle detected.")
2095
+ to_scan.reverse()
2096
+ return to_scan
2097
+
2098
+ def relax(to_scan):
2099
+ """Relax out-edges of relabeled nodes."""
2100
+ relabeled = set()
2101
+ # Scan nodes in to_scan in topological order and relax incident
2102
+ # out-edges. Add the relabled nodes to labeled.
2103
+ for u in to_scan:
2104
+ d_u = d[u]
2105
+ for v, e in G_succ[u].items():
2106
+ w_e = weight(u, v, e)
2107
+ if d_u + w_e < d[v]:
2108
+ d[v] = d_u + w_e
2109
+ pred[v] = u
2110
+ relabeled.add(v)
2111
+ return relabeled
2112
+
2113
+ # Set of nodes relabled in the last round of scan operations. Denoted by B
2114
+ # in Goldberg and Radzik's paper.
2115
+ relabeled = {source}
2116
+
2117
+ while relabeled:
2118
+ to_scan = topo_sort(relabeled)
2119
+ relabeled = relax(to_scan)
2120
+
2121
+ d = {u: d[u] for u in pred}
2122
+ return pred, d
2123
+
2124
+
2125
+ @nx._dispatchable(edge_attrs="weight")
2126
+ def negative_edge_cycle(G, weight="weight", heuristic=True):
2127
+ """Returns True if there exists a negative edge cycle anywhere in G.
2128
+
2129
+ Parameters
2130
+ ----------
2131
+ G : NetworkX graph
2132
+
2133
+ weight : string or function
2134
+ If this is a string, then edge weights will be accessed via the
2135
+ edge attribute with this key (that is, the weight of the edge
2136
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2137
+ such edge attribute exists, the weight of the edge is assumed to
2138
+ be one.
2139
+
2140
+ If this is a function, the weight of an edge is the value
2141
+ returned by the function. The function must accept exactly three
2142
+ positional arguments: the two endpoints of an edge and the
2143
+ dictionary of edge attributes for that edge. The function must
2144
+ return a number.
2145
+
2146
+ heuristic : bool
2147
+ Determines whether to use a heuristic to early detect negative
2148
+ cycles at a negligible cost. In case of graphs with a negative cycle,
2149
+ the performance of detection increases by at least an order of magnitude.
2150
+
2151
+ Returns
2152
+ -------
2153
+ negative_cycle : bool
2154
+ True if a negative edge cycle exists, otherwise False.
2155
+
2156
+ Examples
2157
+ --------
2158
+ >>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
2159
+ >>> print(nx.negative_edge_cycle(G))
2160
+ False
2161
+ >>> G[1][2]["weight"] = -7
2162
+ >>> print(nx.negative_edge_cycle(G))
2163
+ True
2164
+
2165
+ Notes
2166
+ -----
2167
+ Edge weight attributes must be numerical.
2168
+ Distances are calculated as sums of weighted edges traversed.
2169
+
2170
+ This algorithm uses bellman_ford_predecessor_and_distance() but finds
2171
+ negative cycles on any component by first adding a new node connected to
2172
+ every node, and starting bellman_ford_predecessor_and_distance on that
2173
+ node. It then removes that extra node.
2174
+ """
2175
+ if G.size() == 0:
2176
+ return False
2177
+
2178
+ # find unused node to use temporarily
2179
+ newnode = -1
2180
+ while newnode in G:
2181
+ newnode -= 1
2182
+ # connect it to all nodes
2183
+ G.add_edges_from([(newnode, n) for n in G])
2184
+
2185
+ try:
2186
+ bellman_ford_predecessor_and_distance(
2187
+ G, newnode, weight=weight, heuristic=heuristic
2188
+ )
2189
+ except nx.NetworkXUnbounded:
2190
+ return True
2191
+ finally:
2192
+ G.remove_node(newnode)
2193
+ return False
2194
+
2195
+
2196
+ @nx._dispatchable(edge_attrs="weight")
2197
+ def find_negative_cycle(G, source, weight="weight"):
2198
+ """Returns a cycle with negative total weight if it exists.
2199
+
2200
+ Bellman-Ford is used to find shortest_paths. That algorithm
2201
+ stops if there exists a negative cycle. This algorithm
2202
+ picks up from there and returns the found negative cycle.
2203
+
2204
+ The cycle consists of a list of nodes in the cycle order. The last
2205
+ node equals the first to make it a cycle.
2206
+ You can look up the edge weights in the original graph. In the case
2207
+ of multigraphs the relevant edge is the minimal weight edge between
2208
+ the nodes in the 2-tuple.
2209
+
2210
+ If the graph has no negative cycle, a NetworkXError is raised.
2211
+
2212
+ Parameters
2213
+ ----------
2214
+ G : NetworkX graph
2215
+
2216
+ source: node label
2217
+ The search for the negative cycle will start from this node.
2218
+
2219
+ weight : string or function
2220
+ If this is a string, then edge weights will be accessed via the
2221
+ edge attribute with this key (that is, the weight of the edge
2222
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2223
+ such edge attribute exists, the weight of the edge is assumed to
2224
+ be one.
2225
+
2226
+ If this is a function, the weight of an edge is the value
2227
+ returned by the function. The function must accept exactly three
2228
+ positional arguments: the two endpoints of an edge and the
2229
+ dictionary of edge attributes for that edge. The function must
2230
+ return a number.
2231
+
2232
+ Examples
2233
+ --------
2234
+ >>> G = nx.DiGraph()
2235
+ >>> G.add_weighted_edges_from([(0, 1, 2), (1, 2, 2), (2, 0, 1), (1, 4, 2), (4, 0, -5)])
2236
+ >>> nx.find_negative_cycle(G, 0)
2237
+ [4, 0, 1, 4]
2238
+
2239
+ Returns
2240
+ -------
2241
+ cycle : list
2242
+ A list of nodes in the order of the cycle found. The last node
2243
+ equals the first to indicate a cycle.
2244
+
2245
+ Raises
2246
+ ------
2247
+ NetworkXError
2248
+ If no negative cycle is found.
2249
+ """
2250
+ weight = _weight_function(G, weight)
2251
+ pred = {source: []}
2252
+
2253
+ v = _inner_bellman_ford(G, [source], weight, pred=pred)
2254
+ if v is None:
2255
+ raise nx.NetworkXError("No negative cycles detected.")
2256
+
2257
+ # negative cycle detected... find it
2258
+ neg_cycle = []
2259
+ stack = [(v, list(pred[v]))]
2260
+ seen = {v}
2261
+ while stack:
2262
+ node, preds = stack[-1]
2263
+ if v in preds:
2264
+ # found the cycle
2265
+ neg_cycle.extend([node, v])
2266
+ neg_cycle = list(reversed(neg_cycle))
2267
+ return neg_cycle
2268
+
2269
+ if preds:
2270
+ nbr = preds.pop()
2271
+ if nbr not in seen:
2272
+ stack.append((nbr, list(pred[nbr])))
2273
+ neg_cycle.append(node)
2274
+ seen.add(nbr)
2275
+ else:
2276
+ stack.pop()
2277
+ if neg_cycle:
2278
+ neg_cycle.pop()
2279
+ else:
2280
+ if v in G[v] and weight(G, v, v) < 0:
2281
+ return [v, v]
2282
+ # should not reach here
2283
+ raise nx.NetworkXError("Negative cycle is detected but not found")
2284
+ # should not get here...
2285
+ msg = "negative cycle detected but not identified"
2286
+ raise nx.NetworkXUnbounded(msg)
2287
+
2288
+
2289
+ @nx._dispatchable(edge_attrs="weight")
2290
+ def bidirectional_dijkstra(G, source, target, weight="weight"):
2291
+ r"""Dijkstra's algorithm for shortest paths using bidirectional search.
2292
+
2293
+ Parameters
2294
+ ----------
2295
+ G : NetworkX graph
2296
+
2297
+ source : node
2298
+ Starting node.
2299
+
2300
+ target : node
2301
+ Ending node.
2302
+
2303
+ weight : string or function
2304
+ If this is a string, then edge weights will be accessed via the
2305
+ edge attribute with this key (that is, the weight of the edge
2306
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2307
+ such edge attribute exists, the weight of the edge is assumed to
2308
+ be one.
2309
+
2310
+ If this is a function, the weight of an edge is the value
2311
+ returned by the function. The function must accept exactly three
2312
+ positional arguments: the two endpoints of an edge and the
2313
+ dictionary of edge attributes for that edge. The function must
2314
+ return a number or None to indicate a hidden edge.
2315
+
2316
+ Returns
2317
+ -------
2318
+ length, path : number and list
2319
+ length is the distance from source to target.
2320
+ path is a list of nodes on a path from source to target.
2321
+
2322
+ Raises
2323
+ ------
2324
+ NodeNotFound
2325
+ If either `source` or `target` is not in `G`.
2326
+
2327
+ NetworkXNoPath
2328
+ If no path exists between source and target.
2329
+
2330
+ Examples
2331
+ --------
2332
+ >>> G = nx.path_graph(5)
2333
+ >>> length, path = nx.bidirectional_dijkstra(G, 0, 4)
2334
+ >>> print(length)
2335
+ 4
2336
+ >>> print(path)
2337
+ [0, 1, 2, 3, 4]
2338
+
2339
+ Notes
2340
+ -----
2341
+ Edge weight attributes must be numerical.
2342
+ Distances are calculated as sums of weighted edges traversed.
2343
+
2344
+ The weight function can be used to hide edges by returning None.
2345
+ So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
2346
+ will find the shortest red path.
2347
+
2348
+ In practice bidirectional Dijkstra is much more than twice as fast as
2349
+ ordinary Dijkstra.
2350
+
2351
+ Ordinary Dijkstra expands nodes in a sphere-like manner from the
2352
+ source. The radius of this sphere will eventually be the length
2353
+ of the shortest path. Bidirectional Dijkstra will expand nodes
2354
+ from both the source and the target, making two spheres of half
2355
+ this radius. Volume of the first sphere is `\pi*r*r` while the
2356
+ others are `2*\pi*r/2*r/2`, making up half the volume.
2357
+
2358
+ This algorithm is not guaranteed to work if edge weights
2359
+ are negative or are floating point numbers
2360
+ (overflows and roundoff errors can cause problems).
2361
+
2362
+ See Also
2363
+ --------
2364
+ shortest_path
2365
+ shortest_path_length
2366
+ """
2367
+ if source not in G or target not in G:
2368
+ msg = f"Either source {source} or target {target} is not in G"
2369
+ raise nx.NodeNotFound(msg)
2370
+
2371
+ if source == target:
2372
+ return (0, [source])
2373
+
2374
+ weight = _weight_function(G, weight)
2375
+ push = heappush
2376
+ pop = heappop
2377
+ # Init: [Forward, Backward]
2378
+ dists = [{}, {}] # dictionary of final distances
2379
+ paths = [{source: [source]}, {target: [target]}] # dictionary of paths
2380
+ fringe = [[], []] # heap of (distance, node) for choosing node to expand
2381
+ seen = [{source: 0}, {target: 0}] # dict of distances to seen nodes
2382
+ c = count()
2383
+ # initialize fringe heap
2384
+ push(fringe[0], (0, next(c), source))
2385
+ push(fringe[1], (0, next(c), target))
2386
+ # neighs for extracting correct neighbor information
2387
+ if G.is_directed():
2388
+ neighs = [G._succ, G._pred]
2389
+ else:
2390
+ neighs = [G._adj, G._adj]
2391
+ # variables to hold shortest discovered path
2392
+ # finaldist = 1e30000
2393
+ finalpath = []
2394
+ dir = 1
2395
+ while fringe[0] and fringe[1]:
2396
+ # choose direction
2397
+ # dir == 0 is forward direction and dir == 1 is back
2398
+ dir = 1 - dir
2399
+ # extract closest to expand
2400
+ (dist, _, v) = pop(fringe[dir])
2401
+ if v in dists[dir]:
2402
+ # Shortest path to v has already been found
2403
+ continue
2404
+ # update distance
2405
+ dists[dir][v] = dist # equal to seen[dir][v]
2406
+ if v in dists[1 - dir]:
2407
+ # if we have scanned v in both directions we are done
2408
+ # we have now discovered the shortest path
2409
+ return (finaldist, finalpath)
2410
+
2411
+ for w, d in neighs[dir][v].items():
2412
+ # weight(v, w, d) for forward and weight(w, v, d) for back direction
2413
+ cost = weight(v, w, d) if dir == 0 else weight(w, v, d)
2414
+ if cost is None:
2415
+ continue
2416
+ vwLength = dists[dir][v] + cost
2417
+ if w in dists[dir]:
2418
+ if vwLength < dists[dir][w]:
2419
+ raise ValueError("Contradictory paths found: negative weights?")
2420
+ elif w not in seen[dir] or vwLength < seen[dir][w]:
2421
+ # relaxing
2422
+ seen[dir][w] = vwLength
2423
+ push(fringe[dir], (vwLength, next(c), w))
2424
+ paths[dir][w] = paths[dir][v] + [w]
2425
+ if w in seen[0] and w in seen[1]:
2426
+ # see if this path is better than the already
2427
+ # discovered shortest path
2428
+ totaldist = seen[0][w] + seen[1][w]
2429
+ if finalpath == [] or finaldist > totaldist:
2430
+ finaldist = totaldist
2431
+ revpath = paths[1][w][:]
2432
+ revpath.reverse()
2433
+ finalpath = paths[0][w] + revpath[1:]
2434
+ raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
2435
+
2436
+
2437
+ @nx._dispatchable(edge_attrs="weight")
2438
+ def johnson(G, weight="weight"):
2439
+ r"""Uses Johnson's Algorithm to compute shortest paths.
2440
+
2441
+ Johnson's Algorithm finds a shortest path between each pair of
2442
+ nodes in a weighted graph even if negative weights are present.
2443
+
2444
+ Parameters
2445
+ ----------
2446
+ G : NetworkX graph
2447
+
2448
+ weight : string or function
2449
+ If this is a string, then edge weights will be accessed via the
2450
+ edge attribute with this key (that is, the weight of the edge
2451
+ joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
2452
+ such edge attribute exists, the weight of the edge is assumed to
2453
+ be one.
2454
+
2455
+ If this is a function, the weight of an edge is the value
2456
+ returned by the function. The function must accept exactly three
2457
+ positional arguments: the two endpoints of an edge and the
2458
+ dictionary of edge attributes for that edge. The function must
2459
+ return a number.
2460
+
2461
+ Returns
2462
+ -------
2463
+ distance : dictionary
2464
+ Dictionary, keyed by source and target, of shortest paths.
2465
+
2466
+ Examples
2467
+ --------
2468
+ >>> graph = nx.DiGraph()
2469
+ >>> graph.add_weighted_edges_from(
2470
+ ... [("0", "3", 3), ("0", "1", -5), ("0", "2", 2), ("1", "2", 4), ("2", "3", 1)]
2471
+ ... )
2472
+ >>> paths = nx.johnson(graph, weight="weight")
2473
+ >>> paths["0"]["2"]
2474
+ ['0', '1', '2']
2475
+
2476
+ Notes
2477
+ -----
2478
+ Johnson's algorithm is suitable even for graphs with negative weights. It
2479
+ works by using the Bellman–Ford algorithm to compute a transformation of
2480
+ the input graph that removes all negative weights, allowing Dijkstra's
2481
+ algorithm to be used on the transformed graph.
2482
+
2483
+ The time complexity of this algorithm is $O(n^2 \log n + n m)$,
2484
+ where $n$ is the number of nodes and $m$ the number of edges in the
2485
+ graph. For dense graphs, this may be faster than the Floyd–Warshall
2486
+ algorithm.
2487
+
2488
+ See Also
2489
+ --------
2490
+ floyd_warshall_predecessor_and_distance
2491
+ floyd_warshall_numpy
2492
+ all_pairs_shortest_path
2493
+ all_pairs_shortest_path_length
2494
+ all_pairs_dijkstra_path
2495
+ bellman_ford_predecessor_and_distance
2496
+ all_pairs_bellman_ford_path
2497
+ all_pairs_bellman_ford_path_length
2498
+
2499
+ """
2500
+ dist = {v: 0 for v in G}
2501
+ pred = {v: [] for v in G}
2502
+ weight = _weight_function(G, weight)
2503
+
2504
+ # Calculate distance of shortest paths
2505
+ dist_bellman = _bellman_ford(G, list(G), weight, pred=pred, dist=dist)
2506
+
2507
+ # Update the weight function to take into account the Bellman--Ford
2508
+ # relaxation distances.
2509
+ def new_weight(u, v, d):
2510
+ return weight(u, v, d) + dist_bellman[u] - dist_bellman[v]
2511
+
2512
+ def dist_path(v):
2513
+ paths = {v: [v]}
2514
+ _dijkstra(G, v, new_weight, paths=paths)
2515
+ return paths
2516
+
2517
+ return {v: dist_path(v) for v in G}
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/smallworld.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for estimating the small-world-ness of graphs.
2
+
3
+ A small world network is characterized by a small average shortest path length,
4
+ and a large clustering coefficient.
5
+
6
+ Small-worldness is commonly measured with the coefficient sigma or omega.
7
+
8
+ Both coefficients compare the average clustering coefficient and shortest path
9
+ length of a given graph against the same quantities for an equivalent random
10
+ or lattice graph.
11
+
12
+ For more information, see the Wikipedia article on small-world network [1]_.
13
+
14
+ .. [1] Small-world network:: https://en.wikipedia.org/wiki/Small-world_network
15
+
16
+ """
17
+ import networkx as nx
18
+ from networkx.utils import not_implemented_for, py_random_state
19
+
20
+ __all__ = ["random_reference", "lattice_reference", "sigma", "omega"]
21
+
22
+
23
+ @not_implemented_for("directed")
24
+ @not_implemented_for("multigraph")
25
+ @py_random_state(3)
26
+ @nx._dispatchable(returns_graph=True)
27
+ def random_reference(G, niter=1, connectivity=True, seed=None):
28
+ """Compute a random graph by swapping edges of a given graph.
29
+
30
+ Parameters
31
+ ----------
32
+ G : graph
33
+ An undirected graph with 4 or more nodes.
34
+
35
+ niter : integer (optional, default=1)
36
+ An edge is rewired approximately `niter` times.
37
+
38
+ connectivity : boolean (optional, default=True)
39
+ When True, ensure connectivity for the randomized graph.
40
+
41
+ seed : integer, random_state, or None (default)
42
+ Indicator of random number generation state.
43
+ See :ref:`Randomness<randomness>`.
44
+
45
+ Returns
46
+ -------
47
+ G : graph
48
+ The randomized graph.
49
+
50
+ Raises
51
+ ------
52
+ NetworkXError
53
+ If there are fewer than 4 nodes or 2 edges in `G`
54
+
55
+ Notes
56
+ -----
57
+ The implementation is adapted from the algorithm by Maslov and Sneppen
58
+ (2002) [1]_.
59
+
60
+ References
61
+ ----------
62
+ .. [1] Maslov, Sergei, and Kim Sneppen.
63
+ "Specificity and stability in topology of protein networks."
64
+ Science 296.5569 (2002): 910-913.
65
+ """
66
+ if len(G) < 4:
67
+ raise nx.NetworkXError("Graph has fewer than four nodes.")
68
+ if len(G.edges) < 2:
69
+ raise nx.NetworkXError("Graph has fewer that 2 edges")
70
+
71
+ from networkx.utils import cumulative_distribution, discrete_sequence
72
+
73
+ local_conn = nx.connectivity.local_edge_connectivity
74
+
75
+ G = G.copy()
76
+ keys, degrees = zip(*G.degree()) # keys, degree
77
+ cdf = cumulative_distribution(degrees) # cdf of degree
78
+ nnodes = len(G)
79
+ nedges = nx.number_of_edges(G)
80
+ niter = niter * nedges
81
+ ntries = int(nnodes * nedges / (nnodes * (nnodes - 1) / 2))
82
+ swapcount = 0
83
+
84
+ for i in range(niter):
85
+ n = 0
86
+ while n < ntries:
87
+ # pick two random edges without creating edge list
88
+ # choose source node indices from discrete distribution
89
+ (ai, ci) = discrete_sequence(2, cdistribution=cdf, seed=seed)
90
+ if ai == ci:
91
+ continue # same source, skip
92
+ a = keys[ai] # convert index to label
93
+ c = keys[ci]
94
+ # choose target uniformly from neighbors
95
+ b = seed.choice(list(G.neighbors(a)))
96
+ d = seed.choice(list(G.neighbors(c)))
97
+ if b in [a, c, d] or d in [a, b, c]:
98
+ continue # all vertices should be different
99
+
100
+ # don't create parallel edges
101
+ if (d not in G[a]) and (b not in G[c]):
102
+ G.add_edge(a, d)
103
+ G.add_edge(c, b)
104
+ G.remove_edge(a, b)
105
+ G.remove_edge(c, d)
106
+
107
+ # Check if the graph is still connected
108
+ if connectivity and local_conn(G, a, b) == 0:
109
+ # Not connected, revert the swap
110
+ G.remove_edge(a, d)
111
+ G.remove_edge(c, b)
112
+ G.add_edge(a, b)
113
+ G.add_edge(c, d)
114
+ else:
115
+ swapcount += 1
116
+ break
117
+ n += 1
118
+ return G
119
+
120
+
121
+ @not_implemented_for("directed")
122
+ @not_implemented_for("multigraph")
123
+ @py_random_state(4)
124
+ @nx._dispatchable(returns_graph=True)
125
+ def lattice_reference(G, niter=5, D=None, connectivity=True, seed=None):
126
+ """Latticize the given graph by swapping edges.
127
+
128
+ Parameters
129
+ ----------
130
+ G : graph
131
+ An undirected graph.
132
+
133
+ niter : integer (optional, default=1)
134
+ An edge is rewired approximately niter times.
135
+
136
+ D : numpy.array (optional, default=None)
137
+ Distance to the diagonal matrix.
138
+
139
+ connectivity : boolean (optional, default=True)
140
+ Ensure connectivity for the latticized graph when set to True.
141
+
142
+ seed : integer, random_state, or None (default)
143
+ Indicator of random number generation state.
144
+ See :ref:`Randomness<randomness>`.
145
+
146
+ Returns
147
+ -------
148
+ G : graph
149
+ The latticized graph.
150
+
151
+ Raises
152
+ ------
153
+ NetworkXError
154
+ If there are fewer than 4 nodes or 2 edges in `G`
155
+
156
+ Notes
157
+ -----
158
+ The implementation is adapted from the algorithm by Sporns et al. [1]_.
159
+ which is inspired from the original work by Maslov and Sneppen(2002) [2]_.
160
+
161
+ References
162
+ ----------
163
+ .. [1] Sporns, Olaf, and Jonathan D. Zwi.
164
+ "The small world of the cerebral cortex."
165
+ Neuroinformatics 2.2 (2004): 145-162.
166
+ .. [2] Maslov, Sergei, and Kim Sneppen.
167
+ "Specificity and stability in topology of protein networks."
168
+ Science 296.5569 (2002): 910-913.
169
+ """
170
+ import numpy as np
171
+
172
+ from networkx.utils import cumulative_distribution, discrete_sequence
173
+
174
+ local_conn = nx.connectivity.local_edge_connectivity
175
+
176
+ if len(G) < 4:
177
+ raise nx.NetworkXError("Graph has fewer than four nodes.")
178
+ if len(G.edges) < 2:
179
+ raise nx.NetworkXError("Graph has fewer that 2 edges")
180
+ # Instead of choosing uniformly at random from a generated edge list,
181
+ # this algorithm chooses nonuniformly from the set of nodes with
182
+ # probability weighted by degree.
183
+ G = G.copy()
184
+ keys, degrees = zip(*G.degree()) # keys, degree
185
+ cdf = cumulative_distribution(degrees) # cdf of degree
186
+
187
+ nnodes = len(G)
188
+ nedges = nx.number_of_edges(G)
189
+ if D is None:
190
+ D = np.zeros((nnodes, nnodes))
191
+ un = np.arange(1, nnodes)
192
+ um = np.arange(nnodes - 1, 0, -1)
193
+ u = np.append((0,), np.where(un < um, un, um))
194
+
195
+ for v in range(int(np.ceil(nnodes / 2))):
196
+ D[nnodes - v - 1, :] = np.append(u[v + 1 :], u[: v + 1])
197
+ D[v, :] = D[nnodes - v - 1, :][::-1]
198
+
199
+ niter = niter * nedges
200
+ # maximal number of rewiring attempts per 'niter'
201
+ max_attempts = int(nnodes * nedges / (nnodes * (nnodes - 1) / 2))
202
+
203
+ for _ in range(niter):
204
+ n = 0
205
+ while n < max_attempts:
206
+ # pick two random edges without creating edge list
207
+ # choose source node indices from discrete distribution
208
+ (ai, ci) = discrete_sequence(2, cdistribution=cdf, seed=seed)
209
+ if ai == ci:
210
+ continue # same source, skip
211
+ a = keys[ai] # convert index to label
212
+ c = keys[ci]
213
+ # choose target uniformly from neighbors
214
+ b = seed.choice(list(G.neighbors(a)))
215
+ d = seed.choice(list(G.neighbors(c)))
216
+ bi = keys.index(b)
217
+ di = keys.index(d)
218
+
219
+ if b in [a, c, d] or d in [a, b, c]:
220
+ continue # all vertices should be different
221
+
222
+ # don't create parallel edges
223
+ if (d not in G[a]) and (b not in G[c]):
224
+ if D[ai, bi] + D[ci, di] >= D[ai, ci] + D[bi, di]:
225
+ # only swap if we get closer to the diagonal
226
+ G.add_edge(a, d)
227
+ G.add_edge(c, b)
228
+ G.remove_edge(a, b)
229
+ G.remove_edge(c, d)
230
+
231
+ # Check if the graph is still connected
232
+ if connectivity and local_conn(G, a, b) == 0:
233
+ # Not connected, revert the swap
234
+ G.remove_edge(a, d)
235
+ G.remove_edge(c, b)
236
+ G.add_edge(a, b)
237
+ G.add_edge(c, d)
238
+ else:
239
+ break
240
+ n += 1
241
+
242
+ return G
243
+
244
+
245
+ @not_implemented_for("directed")
246
+ @not_implemented_for("multigraph")
247
+ @py_random_state(3)
248
+ @nx._dispatchable
249
+ def sigma(G, niter=100, nrand=10, seed=None):
250
+ """Returns the small-world coefficient (sigma) of the given graph.
251
+
252
+ The small-world coefficient is defined as:
253
+ sigma = C/Cr / L/Lr
254
+ where C and L are respectively the average clustering coefficient and
255
+ average shortest path length of G. Cr and Lr are respectively the average
256
+ clustering coefficient and average shortest path length of an equivalent
257
+ random graph.
258
+
259
+ A graph is commonly classified as small-world if sigma>1.
260
+
261
+ Parameters
262
+ ----------
263
+ G : NetworkX graph
264
+ An undirected graph.
265
+ niter : integer (optional, default=100)
266
+ Approximate number of rewiring per edge to compute the equivalent
267
+ random graph.
268
+ nrand : integer (optional, default=10)
269
+ Number of random graphs generated to compute the average clustering
270
+ coefficient (Cr) and average shortest path length (Lr).
271
+ seed : integer, random_state, or None (default)
272
+ Indicator of random number generation state.
273
+ See :ref:`Randomness<randomness>`.
274
+
275
+ Returns
276
+ -------
277
+ sigma : float
278
+ The small-world coefficient of G.
279
+
280
+ Notes
281
+ -----
282
+ The implementation is adapted from Humphries et al. [1]_ [2]_.
283
+
284
+ References
285
+ ----------
286
+ .. [1] The brainstem reticular formation is a small-world, not scale-free,
287
+ network M. D. Humphries, K. Gurney and T. J. Prescott,
288
+ Proc. Roy. Soc. B 2006 273, 503-511, doi:10.1098/rspb.2005.3354.
289
+ .. [2] Humphries and Gurney (2008).
290
+ "Network 'Small-World-Ness': A Quantitative Method for Determining
291
+ Canonical Network Equivalence".
292
+ PLoS One. 3 (4). PMID 18446219. doi:10.1371/journal.pone.0002051.
293
+ """
294
+ import numpy as np
295
+
296
+ # Compute the mean clustering coefficient and average shortest path length
297
+ # for an equivalent random graph
298
+ randMetrics = {"C": [], "L": []}
299
+ for i in range(nrand):
300
+ Gr = random_reference(G, niter=niter, seed=seed)
301
+ randMetrics["C"].append(nx.transitivity(Gr))
302
+ randMetrics["L"].append(nx.average_shortest_path_length(Gr))
303
+
304
+ C = nx.transitivity(G)
305
+ L = nx.average_shortest_path_length(G)
306
+ Cr = np.mean(randMetrics["C"])
307
+ Lr = np.mean(randMetrics["L"])
308
+
309
+ sigma = (C / Cr) / (L / Lr)
310
+
311
+ return float(sigma)
312
+
313
+
314
+ @not_implemented_for("directed")
315
+ @not_implemented_for("multigraph")
316
+ @py_random_state(3)
317
+ @nx._dispatchable
318
+ def omega(G, niter=5, nrand=10, seed=None):
319
+ """Returns the small-world coefficient (omega) of a graph
320
+
321
+ The small-world coefficient of a graph G is:
322
+
323
+ omega = Lr/L - C/Cl
324
+
325
+ where C and L are respectively the average clustering coefficient and
326
+ average shortest path length of G. Lr is the average shortest path length
327
+ of an equivalent random graph and Cl is the average clustering coefficient
328
+ of an equivalent lattice graph.
329
+
330
+ The small-world coefficient (omega) measures how much G is like a lattice
331
+ or a random graph. Negative values mean G is similar to a lattice whereas
332
+ positive values mean G is a random graph.
333
+ Values close to 0 mean that G has small-world characteristics.
334
+
335
+ Parameters
336
+ ----------
337
+ G : NetworkX graph
338
+ An undirected graph.
339
+
340
+ niter: integer (optional, default=5)
341
+ Approximate number of rewiring per edge to compute the equivalent
342
+ random graph.
343
+
344
+ nrand: integer (optional, default=10)
345
+ Number of random graphs generated to compute the maximal clustering
346
+ coefficient (Cr) and average shortest path length (Lr).
347
+
348
+ seed : integer, random_state, or None (default)
349
+ Indicator of random number generation state.
350
+ See :ref:`Randomness<randomness>`.
351
+
352
+
353
+ Returns
354
+ -------
355
+ omega : float
356
+ The small-world coefficient (omega)
357
+
358
+ Notes
359
+ -----
360
+ The implementation is adapted from the algorithm by Telesford et al. [1]_.
361
+
362
+ References
363
+ ----------
364
+ .. [1] Telesford, Joyce, Hayasaka, Burdette, and Laurienti (2011).
365
+ "The Ubiquity of Small-World Networks".
366
+ Brain Connectivity. 1 (0038): 367-75. PMC 3604768. PMID 22432451.
367
+ doi:10.1089/brain.2011.0038.
368
+ """
369
+ import numpy as np
370
+
371
+ # Compute the mean clustering coefficient and average shortest path length
372
+ # for an equivalent random graph
373
+ randMetrics = {"C": [], "L": []}
374
+
375
+ # Calculate initial average clustering coefficient which potentially will
376
+ # get replaced by higher clustering coefficients from generated lattice
377
+ # reference graphs
378
+ Cl = nx.average_clustering(G)
379
+
380
+ niter_lattice_reference = niter
381
+ niter_random_reference = niter * 2
382
+
383
+ for _ in range(nrand):
384
+ # Generate random graph
385
+ Gr = random_reference(G, niter=niter_random_reference, seed=seed)
386
+ randMetrics["L"].append(nx.average_shortest_path_length(Gr))
387
+
388
+ # Generate lattice graph
389
+ Gl = lattice_reference(G, niter=niter_lattice_reference, seed=seed)
390
+
391
+ # Replace old clustering coefficient, if clustering is higher in
392
+ # generated lattice reference
393
+ Cl_temp = nx.average_clustering(Gl)
394
+ if Cl_temp > Cl:
395
+ Cl = Cl_temp
396
+
397
+ C = nx.average_clustering(G)
398
+ L = nx.average_shortest_path_length(G)
399
+ Lr = np.mean(randMetrics["L"])
400
+
401
+ omega = (Lr / L) - (C / Cl)
402
+
403
+ return float(omega)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/smetric.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["s_metric"]
4
+
5
+
6
+ @nx._dispatchable
7
+ def s_metric(G, **kwargs):
8
+ """Returns the s-metric [1]_ of graph.
9
+
10
+ The s-metric is defined as the sum of the products ``deg(u) * deg(v)``
11
+ for every edge ``(u, v)`` in `G`.
12
+
13
+ Parameters
14
+ ----------
15
+ G : graph
16
+ The graph used to compute the s-metric.
17
+ normalized : bool (optional)
18
+ Normalize the value.
19
+
20
+ .. deprecated:: 3.2
21
+
22
+ The `normalized` keyword argument is deprecated and will be removed
23
+ in the future
24
+
25
+ Returns
26
+ -------
27
+ s : float
28
+ The s-metric of the graph.
29
+
30
+ References
31
+ ----------
32
+ .. [1] Lun Li, David Alderson, John C. Doyle, and Walter Willinger,
33
+ Towards a Theory of Scale-Free Graphs:
34
+ Definition, Properties, and Implications (Extended Version), 2005.
35
+ https://arxiv.org/abs/cond-mat/0501169
36
+ """
37
+ # NOTE: This entire code block + the **kwargs in the signature can all be
38
+ # removed when the deprecation expires.
39
+ # Normalized is always False, since all `normalized=True` did was raise
40
+ # a NotImplementedError
41
+ if kwargs:
42
+ # Warn for `normalize`, raise for any other kwarg
43
+ if "normalized" in kwargs:
44
+ import warnings
45
+
46
+ warnings.warn(
47
+ "\n\nThe `normalized` keyword is deprecated and will be removed\n"
48
+ "in the future. To silence this warning, remove `normalized`\n"
49
+ "when calling `s_metric`.\n\n"
50
+ "The value of `normalized` is ignored.",
51
+ DeprecationWarning,
52
+ stacklevel=3,
53
+ )
54
+ else:
55
+ # Typical raising behavior for Python when kwarg not recognized
56
+ raise TypeError(
57
+ f"s_metric got an unexpected keyword argument '{list(kwargs.keys())[0]}'"
58
+ )
59
+
60
+ return float(sum(G.degree(u) * G.degree(v) for (u, v) in G.edges()))
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/sparsifiers.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing sparsifiers of graphs."""
2
+ import math
3
+
4
+ import networkx as nx
5
+ from networkx.utils import not_implemented_for, py_random_state
6
+
7
+ __all__ = ["spanner"]
8
+
9
+
10
+ @not_implemented_for("directed")
11
+ @not_implemented_for("multigraph")
12
+ @py_random_state(3)
13
+ @nx._dispatchable(edge_attrs="weight", returns_graph=True)
14
+ def spanner(G, stretch, weight=None, seed=None):
15
+ """Returns a spanner of the given graph with the given stretch.
16
+
17
+ A spanner of a graph G = (V, E) with stretch t is a subgraph
18
+ H = (V, E_S) such that E_S is a subset of E and the distance between
19
+ any pair of nodes in H is at most t times the distance between the
20
+ nodes in G.
21
+
22
+ Parameters
23
+ ----------
24
+ G : NetworkX graph
25
+ An undirected simple graph.
26
+
27
+ stretch : float
28
+ The stretch of the spanner.
29
+
30
+ weight : object
31
+ The edge attribute to use as distance.
32
+
33
+ seed : integer, random_state, or None (default)
34
+ Indicator of random number generation state.
35
+ See :ref:`Randomness<randomness>`.
36
+
37
+ Returns
38
+ -------
39
+ NetworkX graph
40
+ A spanner of the given graph with the given stretch.
41
+
42
+ Raises
43
+ ------
44
+ ValueError
45
+ If a stretch less than 1 is given.
46
+
47
+ Notes
48
+ -----
49
+ This function implements the spanner algorithm by Baswana and Sen,
50
+ see [1].
51
+
52
+ This algorithm is a randomized las vegas algorithm: The expected
53
+ running time is O(km) where k = (stretch + 1) // 2 and m is the
54
+ number of edges in G. The returned graph is always a spanner of the
55
+ given graph with the specified stretch. For weighted graphs the
56
+ number of edges in the spanner is O(k * n^(1 + 1 / k)) where k is
57
+ defined as above and n is the number of nodes in G. For unweighted
58
+ graphs the number of edges is O(n^(1 + 1 / k) + kn).
59
+
60
+ References
61
+ ----------
62
+ [1] S. Baswana, S. Sen. A Simple and Linear Time Randomized
63
+ Algorithm for Computing Sparse Spanners in Weighted Graphs.
64
+ Random Struct. Algorithms 30(4): 532-563 (2007).
65
+ """
66
+ if stretch < 1:
67
+ raise ValueError("stretch must be at least 1")
68
+
69
+ k = (stretch + 1) // 2
70
+
71
+ # initialize spanner H with empty edge set
72
+ H = nx.empty_graph()
73
+ H.add_nodes_from(G.nodes)
74
+
75
+ # phase 1: forming the clusters
76
+ # the residual graph has V' from the paper as its node set
77
+ # and E' from the paper as its edge set
78
+ residual_graph = _setup_residual_graph(G, weight)
79
+ # clustering is a dictionary that maps nodes in a cluster to the
80
+ # cluster center
81
+ clustering = {v: v for v in G.nodes}
82
+ sample_prob = math.pow(G.number_of_nodes(), -1 / k)
83
+ size_limit = 2 * math.pow(G.number_of_nodes(), 1 + 1 / k)
84
+
85
+ i = 0
86
+ while i < k - 1:
87
+ # step 1: sample centers
88
+ sampled_centers = set()
89
+ for center in set(clustering.values()):
90
+ if seed.random() < sample_prob:
91
+ sampled_centers.add(center)
92
+
93
+ # combined loop for steps 2 and 3
94
+ edges_to_add = set()
95
+ edges_to_remove = set()
96
+ new_clustering = {}
97
+ for v in residual_graph.nodes:
98
+ if clustering[v] in sampled_centers:
99
+ continue
100
+
101
+ # step 2: find neighboring (sampled) clusters and
102
+ # lightest edges to them
103
+ lightest_edge_neighbor, lightest_edge_weight = _lightest_edge_dicts(
104
+ residual_graph, clustering, v
105
+ )
106
+ neighboring_sampled_centers = (
107
+ set(lightest_edge_weight.keys()) & sampled_centers
108
+ )
109
+
110
+ # step 3: add edges to spanner
111
+ if not neighboring_sampled_centers:
112
+ # connect to each neighboring center via lightest edge
113
+ for neighbor in lightest_edge_neighbor.values():
114
+ edges_to_add.add((v, neighbor))
115
+ # remove all incident edges
116
+ for neighbor in residual_graph.adj[v]:
117
+ edges_to_remove.add((v, neighbor))
118
+
119
+ else: # there is a neighboring sampled center
120
+ closest_center = min(
121
+ neighboring_sampled_centers, key=lightest_edge_weight.get
122
+ )
123
+ closest_center_weight = lightest_edge_weight[closest_center]
124
+ closest_center_neighbor = lightest_edge_neighbor[closest_center]
125
+
126
+ edges_to_add.add((v, closest_center_neighbor))
127
+ new_clustering[v] = closest_center
128
+
129
+ # connect to centers with edge weight less than
130
+ # closest_center_weight
131
+ for center, edge_weight in lightest_edge_weight.items():
132
+ if edge_weight < closest_center_weight:
133
+ neighbor = lightest_edge_neighbor[center]
134
+ edges_to_add.add((v, neighbor))
135
+
136
+ # remove edges to centers with edge weight less than
137
+ # closest_center_weight
138
+ for neighbor in residual_graph.adj[v]:
139
+ nbr_cluster = clustering[neighbor]
140
+ nbr_weight = lightest_edge_weight[nbr_cluster]
141
+ if (
142
+ nbr_cluster == closest_center
143
+ or nbr_weight < closest_center_weight
144
+ ):
145
+ edges_to_remove.add((v, neighbor))
146
+
147
+ # check whether iteration added too many edges to spanner,
148
+ # if so repeat
149
+ if len(edges_to_add) > size_limit:
150
+ # an iteration is repeated O(1) times on expectation
151
+ continue
152
+
153
+ # iteration succeeded
154
+ i = i + 1
155
+
156
+ # actually add edges to spanner
157
+ for u, v in edges_to_add:
158
+ _add_edge_to_spanner(H, residual_graph, u, v, weight)
159
+
160
+ # actually delete edges from residual graph
161
+ residual_graph.remove_edges_from(edges_to_remove)
162
+
163
+ # copy old clustering data to new_clustering
164
+ for node, center in clustering.items():
165
+ if center in sampled_centers:
166
+ new_clustering[node] = center
167
+ clustering = new_clustering
168
+
169
+ # step 4: remove intra-cluster edges
170
+ for u in residual_graph.nodes:
171
+ for v in list(residual_graph.adj[u]):
172
+ if clustering[u] == clustering[v]:
173
+ residual_graph.remove_edge(u, v)
174
+
175
+ # update residual graph node set
176
+ for v in list(residual_graph.nodes):
177
+ if v not in clustering:
178
+ residual_graph.remove_node(v)
179
+
180
+ # phase 2: vertex-cluster joining
181
+ for v in residual_graph.nodes:
182
+ lightest_edge_neighbor, _ = _lightest_edge_dicts(residual_graph, clustering, v)
183
+ for neighbor in lightest_edge_neighbor.values():
184
+ _add_edge_to_spanner(H, residual_graph, v, neighbor, weight)
185
+
186
+ return H
187
+
188
+
189
+ def _setup_residual_graph(G, weight):
190
+ """Setup residual graph as a copy of G with unique edges weights.
191
+
192
+ The node set of the residual graph corresponds to the set V' from
193
+ the Baswana-Sen paper and the edge set corresponds to the set E'
194
+ from the paper.
195
+
196
+ This function associates distinct weights to the edges of the
197
+ residual graph (even for unweighted input graphs), as required by
198
+ the algorithm.
199
+
200
+ Parameters
201
+ ----------
202
+ G : NetworkX graph
203
+ An undirected simple graph.
204
+
205
+ weight : object
206
+ The edge attribute to use as distance.
207
+
208
+ Returns
209
+ -------
210
+ NetworkX graph
211
+ The residual graph used for the Baswana-Sen algorithm.
212
+ """
213
+ residual_graph = G.copy()
214
+
215
+ # establish unique edge weights, even for unweighted graphs
216
+ for u, v in G.edges():
217
+ if not weight:
218
+ residual_graph[u][v]["weight"] = (id(u), id(v))
219
+ else:
220
+ residual_graph[u][v]["weight"] = (G[u][v][weight], id(u), id(v))
221
+
222
+ return residual_graph
223
+
224
+
225
+ def _lightest_edge_dicts(residual_graph, clustering, node):
226
+ """Find the lightest edge to each cluster.
227
+
228
+ Searches for the minimum-weight edge to each cluster adjacent to
229
+ the given node.
230
+
231
+ Parameters
232
+ ----------
233
+ residual_graph : NetworkX graph
234
+ The residual graph used by the Baswana-Sen algorithm.
235
+
236
+ clustering : dictionary
237
+ The current clustering of the nodes.
238
+
239
+ node : node
240
+ The node from which the search originates.
241
+
242
+ Returns
243
+ -------
244
+ lightest_edge_neighbor, lightest_edge_weight : dictionary, dictionary
245
+ lightest_edge_neighbor is a dictionary that maps a center C to
246
+ a node v in the corresponding cluster such that the edge from
247
+ the given node to v is the lightest edge from the given node to
248
+ any node in cluster. lightest_edge_weight maps a center C to the
249
+ weight of the aforementioned edge.
250
+
251
+ Notes
252
+ -----
253
+ If a cluster has no node that is adjacent to the given node in the
254
+ residual graph then the center of the cluster is not a key in the
255
+ returned dictionaries.
256
+ """
257
+ lightest_edge_neighbor = {}
258
+ lightest_edge_weight = {}
259
+ for neighbor in residual_graph.adj[node]:
260
+ nbr_center = clustering[neighbor]
261
+ weight = residual_graph[node][neighbor]["weight"]
262
+ if (
263
+ nbr_center not in lightest_edge_weight
264
+ or weight < lightest_edge_weight[nbr_center]
265
+ ):
266
+ lightest_edge_neighbor[nbr_center] = neighbor
267
+ lightest_edge_weight[nbr_center] = weight
268
+ return lightest_edge_neighbor, lightest_edge_weight
269
+
270
+
271
+ def _add_edge_to_spanner(H, residual_graph, u, v, weight):
272
+ """Add the edge {u, v} to the spanner H and take weight from
273
+ the residual graph.
274
+
275
+ Parameters
276
+ ----------
277
+ H : NetworkX graph
278
+ The spanner under construction.
279
+
280
+ residual_graph : NetworkX graph
281
+ The residual graph used by the Baswana-Sen algorithm. The weight
282
+ for the edge is taken from this graph.
283
+
284
+ u : node
285
+ One endpoint of the edge.
286
+
287
+ v : node
288
+ The other endpoint of the edge.
289
+
290
+ weight : object
291
+ The edge attribute to use as distance.
292
+ """
293
+ H.add_edge(u, v)
294
+ if weight:
295
+ H[u][v][weight] = residual_graph[u][v]["weight"][0]
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/summarization.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Graph summarization finds smaller representations of graphs resulting in faster
3
+ runtime of algorithms, reduced storage needs, and noise reduction.
4
+ Summarization has applications in areas such as visualization, pattern mining,
5
+ clustering and community detection, and more. Core graph summarization
6
+ techniques are grouping/aggregation, bit-compression,
7
+ simplification/sparsification, and influence based. Graph summarization
8
+ algorithms often produce either summary graphs in the form of supergraphs or
9
+ sparsified graphs, or a list of independent structures. Supergraphs are the
10
+ most common product, which consist of supernodes and original nodes and are
11
+ connected by edges and superedges, which represent aggregate edges between
12
+ nodes and supernodes.
13
+
14
+ Grouping/aggregation based techniques compress graphs by representing
15
+ close/connected nodes and edges in a graph by a single node/edge in a
16
+ supergraph. Nodes can be grouped together into supernodes based on their
17
+ structural similarities or proximity within a graph to reduce the total number
18
+ of nodes in a graph. Edge-grouping techniques group edges into lossy/lossless
19
+ nodes called compressor or virtual nodes to reduce the total number of edges in
20
+ a graph. Edge-grouping techniques can be lossless, meaning that they can be
21
+ used to re-create the original graph, or techniques can be lossy, requiring
22
+ less space to store the summary graph, but at the expense of lower
23
+ reconstruction accuracy of the original graph.
24
+
25
+ Bit-compression techniques minimize the amount of information needed to
26
+ describe the original graph, while revealing structural patterns in the
27
+ original graph. The two-part minimum description length (MDL) is often used to
28
+ represent the model and the original graph in terms of the model. A key
29
+ difference between graph compression and graph summarization is that graph
30
+ summarization focuses on finding structural patterns within the original graph,
31
+ whereas graph compression focuses on compressions the original graph to be as
32
+ small as possible. **NOTE**: Some bit-compression methods exist solely to
33
+ compress a graph without creating a summary graph or finding comprehensible
34
+ structural patterns.
35
+
36
+ Simplification/Sparsification techniques attempt to create a sparse
37
+ representation of a graph by removing unimportant nodes and edges from the
38
+ graph. Sparsified graphs differ from supergraphs created by
39
+ grouping/aggregation by only containing a subset of the original nodes and
40
+ edges of the original graph.
41
+
42
+ Influence based techniques aim to find a high-level description of influence
43
+ propagation in a large graph. These methods are scarce and have been mostly
44
+ applied to social graphs.
45
+
46
+ *dedensification* is a grouping/aggregation based technique to compress the
47
+ neighborhoods around high-degree nodes in unweighted graphs by adding
48
+ compressor nodes that summarize multiple edges of the same type to
49
+ high-degree nodes (nodes with a degree greater than a given threshold).
50
+ Dedensification was developed for the purpose of increasing performance of
51
+ query processing around high-degree nodes in graph databases and enables direct
52
+ operations on the compressed graph. The structural patterns surrounding
53
+ high-degree nodes in the original is preserved while using fewer edges and
54
+ adding a small number of compressor nodes. The degree of nodes present in the
55
+ original graph is also preserved. The current implementation of dedensification
56
+ supports graphs with one edge type.
57
+
58
+ For more information on graph summarization, see `Graph Summarization Methods
59
+ and Applications: A Survey <https://dl.acm.org/doi/abs/10.1145/3186727>`_
60
+ """
61
+ from collections import Counter, defaultdict
62
+
63
+ import networkx as nx
64
+
65
+ __all__ = ["dedensify", "snap_aggregation"]
66
+
67
+
68
+ @nx._dispatchable(mutates_input={"not copy": 3}, returns_graph=True)
69
+ def dedensify(G, threshold, prefix=None, copy=True):
70
+ """Compresses neighborhoods around high-degree nodes
71
+
72
+ Reduces the number of edges to high-degree nodes by adding compressor nodes
73
+ that summarize multiple edges of the same type to high-degree nodes (nodes
74
+ with a degree greater than a given threshold). Dedensification also has
75
+ the added benefit of reducing the number of edges around high-degree nodes.
76
+ The implementation currently supports graphs with a single edge type.
77
+
78
+ Parameters
79
+ ----------
80
+ G: graph
81
+ A networkx graph
82
+ threshold: int
83
+ Minimum degree threshold of a node to be considered a high degree node.
84
+ The threshold must be greater than or equal to 2.
85
+ prefix: str or None, optional (default: None)
86
+ An optional prefix for denoting compressor nodes
87
+ copy: bool, optional (default: True)
88
+ Indicates if dedensification should be done inplace
89
+
90
+ Returns
91
+ -------
92
+ dedensified networkx graph : (graph, set)
93
+ 2-tuple of the dedensified graph and set of compressor nodes
94
+
95
+ Notes
96
+ -----
97
+ According to the algorithm in [1]_, removes edges in a graph by
98
+ compressing/decompressing the neighborhoods around high degree nodes by
99
+ adding compressor nodes that summarize multiple edges of the same type
100
+ to high-degree nodes. Dedensification will only add a compressor node when
101
+ doing so will reduce the total number of edges in the given graph. This
102
+ implementation currently supports graphs with a single edge type.
103
+
104
+ Examples
105
+ --------
106
+ Dedensification will only add compressor nodes when doing so would result
107
+ in fewer edges::
108
+
109
+ >>> original_graph = nx.DiGraph()
110
+ >>> original_graph.add_nodes_from(
111
+ ... ["1", "2", "3", "4", "5", "6", "A", "B", "C"]
112
+ ... )
113
+ >>> original_graph.add_edges_from(
114
+ ... [
115
+ ... ("1", "C"), ("1", "B"),
116
+ ... ("2", "C"), ("2", "B"), ("2", "A"),
117
+ ... ("3", "B"), ("3", "A"), ("3", "6"),
118
+ ... ("4", "C"), ("4", "B"), ("4", "A"),
119
+ ... ("5", "B"), ("5", "A"),
120
+ ... ("6", "5"),
121
+ ... ("A", "6")
122
+ ... ]
123
+ ... )
124
+ >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2)
125
+ >>> original_graph.number_of_edges()
126
+ 15
127
+ >>> c_graph.number_of_edges()
128
+ 14
129
+
130
+ A dedensified, directed graph can be "densified" to reconstruct the
131
+ original graph::
132
+
133
+ >>> original_graph = nx.DiGraph()
134
+ >>> original_graph.add_nodes_from(
135
+ ... ["1", "2", "3", "4", "5", "6", "A", "B", "C"]
136
+ ... )
137
+ >>> original_graph.add_edges_from(
138
+ ... [
139
+ ... ("1", "C"), ("1", "B"),
140
+ ... ("2", "C"), ("2", "B"), ("2", "A"),
141
+ ... ("3", "B"), ("3", "A"), ("3", "6"),
142
+ ... ("4", "C"), ("4", "B"), ("4", "A"),
143
+ ... ("5", "B"), ("5", "A"),
144
+ ... ("6", "5"),
145
+ ... ("A", "6")
146
+ ... ]
147
+ ... )
148
+ >>> c_graph, c_nodes = nx.dedensify(original_graph, threshold=2)
149
+ >>> # re-densifies the compressed graph into the original graph
150
+ >>> for c_node in c_nodes:
151
+ ... all_neighbors = set(nx.all_neighbors(c_graph, c_node))
152
+ ... out_neighbors = set(c_graph.neighbors(c_node))
153
+ ... for out_neighbor in out_neighbors:
154
+ ... c_graph.remove_edge(c_node, out_neighbor)
155
+ ... in_neighbors = all_neighbors - out_neighbors
156
+ ... for in_neighbor in in_neighbors:
157
+ ... c_graph.remove_edge(in_neighbor, c_node)
158
+ ... for out_neighbor in out_neighbors:
159
+ ... c_graph.add_edge(in_neighbor, out_neighbor)
160
+ ... c_graph.remove_node(c_node)
161
+ ...
162
+ >>> nx.is_isomorphic(original_graph, c_graph)
163
+ True
164
+
165
+ References
166
+ ----------
167
+ .. [1] Maccioni, A., & Abadi, D. J. (2016, August).
168
+ Scalable pattern matching over compressed graphs via dedensification.
169
+ In Proceedings of the 22nd ACM SIGKDD International Conference on
170
+ Knowledge Discovery and Data Mining (pp. 1755-1764).
171
+ http://www.cs.umd.edu/~abadi/papers/graph-dedense.pdf
172
+ """
173
+ if threshold < 2:
174
+ raise nx.NetworkXError("The degree threshold must be >= 2")
175
+
176
+ degrees = G.in_degree if G.is_directed() else G.degree
177
+ # Group nodes based on degree threshold
178
+ high_degree_nodes = {n for n, d in degrees if d > threshold}
179
+ low_degree_nodes = G.nodes() - high_degree_nodes
180
+
181
+ auxiliary = {}
182
+ for node in G:
183
+ high_degree_nbrs = frozenset(high_degree_nodes & set(G[node]))
184
+ if high_degree_nbrs:
185
+ if high_degree_nbrs in auxiliary:
186
+ auxiliary[high_degree_nbrs].add(node)
187
+ else:
188
+ auxiliary[high_degree_nbrs] = {node}
189
+
190
+ if copy:
191
+ G = G.copy()
192
+
193
+ compressor_nodes = set()
194
+ for index, (high_degree_nodes, low_degree_nodes) in enumerate(auxiliary.items()):
195
+ low_degree_node_count = len(low_degree_nodes)
196
+ high_degree_node_count = len(high_degree_nodes)
197
+ old_edges = high_degree_node_count * low_degree_node_count
198
+ new_edges = high_degree_node_count + low_degree_node_count
199
+ if old_edges <= new_edges:
200
+ continue
201
+ compression_node = "".join(str(node) for node in high_degree_nodes)
202
+ if prefix:
203
+ compression_node = str(prefix) + compression_node
204
+ for node in low_degree_nodes:
205
+ for high_node in high_degree_nodes:
206
+ if G.has_edge(node, high_node):
207
+ G.remove_edge(node, high_node)
208
+
209
+ G.add_edge(node, compression_node)
210
+ for node in high_degree_nodes:
211
+ G.add_edge(compression_node, node)
212
+ compressor_nodes.add(compression_node)
213
+ return G, compressor_nodes
214
+
215
+
216
+ def _snap_build_graph(
217
+ G,
218
+ groups,
219
+ node_attributes,
220
+ edge_attributes,
221
+ neighbor_info,
222
+ edge_types,
223
+ prefix,
224
+ supernode_attribute,
225
+ superedge_attribute,
226
+ ):
227
+ """
228
+ Build the summary graph from the data structures produced in the SNAP aggregation algorithm
229
+
230
+ Used in the SNAP aggregation algorithm to build the output summary graph and supernode
231
+ lookup dictionary. This process uses the original graph and the data structures to
232
+ create the supernodes with the correct node attributes, and the superedges with the correct
233
+ edge attributes
234
+
235
+ Parameters
236
+ ----------
237
+ G: networkx.Graph
238
+ the original graph to be summarized
239
+ groups: dict
240
+ A dictionary of unique group IDs and their corresponding node groups
241
+ node_attributes: iterable
242
+ An iterable of the node attributes considered in the summarization process
243
+ edge_attributes: iterable
244
+ An iterable of the edge attributes considered in the summarization process
245
+ neighbor_info: dict
246
+ A data structure indicating the number of edges a node has with the
247
+ groups in the current summarization of each edge type
248
+ edge_types: dict
249
+ dictionary of edges in the graph and their corresponding attributes recognized
250
+ in the summarization
251
+ prefix: string
252
+ The prefix to be added to all supernodes
253
+ supernode_attribute: str
254
+ The node attribute for recording the supernode groupings of nodes
255
+ superedge_attribute: str
256
+ The edge attribute for recording the edge types represented by superedges
257
+
258
+ Returns
259
+ -------
260
+ summary graph: Networkx graph
261
+ """
262
+ output = G.__class__()
263
+ node_label_lookup = {}
264
+ for index, group_id in enumerate(groups):
265
+ group_set = groups[group_id]
266
+ supernode = f"{prefix}{index}"
267
+ node_label_lookup[group_id] = supernode
268
+ supernode_attributes = {
269
+ attr: G.nodes[next(iter(group_set))][attr] for attr in node_attributes
270
+ }
271
+ supernode_attributes[supernode_attribute] = group_set
272
+ output.add_node(supernode, **supernode_attributes)
273
+
274
+ for group_id in groups:
275
+ group_set = groups[group_id]
276
+ source_supernode = node_label_lookup[group_id]
277
+ for other_group, group_edge_types in neighbor_info[
278
+ next(iter(group_set))
279
+ ].items():
280
+ if group_edge_types:
281
+ target_supernode = node_label_lookup[other_group]
282
+ summary_graph_edge = (source_supernode, target_supernode)
283
+
284
+ edge_types = [
285
+ dict(zip(edge_attributes, edge_type))
286
+ for edge_type in group_edge_types
287
+ ]
288
+
289
+ has_edge = output.has_edge(*summary_graph_edge)
290
+ if output.is_multigraph():
291
+ if not has_edge:
292
+ for edge_type in edge_types:
293
+ output.add_edge(*summary_graph_edge, **edge_type)
294
+ elif not output.is_directed():
295
+ existing_edge_data = output.get_edge_data(*summary_graph_edge)
296
+ for edge_type in edge_types:
297
+ if edge_type not in existing_edge_data.values():
298
+ output.add_edge(*summary_graph_edge, **edge_type)
299
+ else:
300
+ superedge_attributes = {superedge_attribute: edge_types}
301
+ output.add_edge(*summary_graph_edge, **superedge_attributes)
302
+
303
+ return output
304
+
305
+
306
+ def _snap_eligible_group(G, groups, group_lookup, edge_types):
307
+ """
308
+ Determines if a group is eligible to be split.
309
+
310
+ A group is eligible to be split if all nodes in the group have edges of the same type(s)
311
+ with the same other groups.
312
+
313
+ Parameters
314
+ ----------
315
+ G: graph
316
+ graph to be summarized
317
+ groups: dict
318
+ A dictionary of unique group IDs and their corresponding node groups
319
+ group_lookup: dict
320
+ dictionary of nodes and their current corresponding group ID
321
+ edge_types: dict
322
+ dictionary of edges in the graph and their corresponding attributes recognized
323
+ in the summarization
324
+
325
+ Returns
326
+ -------
327
+ tuple: group ID to split, and neighbor-groups participation_counts data structure
328
+ """
329
+ nbr_info = {node: {gid: Counter() for gid in groups} for node in group_lookup}
330
+ for group_id in groups:
331
+ current_group = groups[group_id]
332
+
333
+ # build nbr_info for nodes in group
334
+ for node in current_group:
335
+ nbr_info[node] = {group_id: Counter() for group_id in groups}
336
+ edges = G.edges(node, keys=True) if G.is_multigraph() else G.edges(node)
337
+ for edge in edges:
338
+ neighbor = edge[1]
339
+ edge_type = edge_types[edge]
340
+ neighbor_group_id = group_lookup[neighbor]
341
+ nbr_info[node][neighbor_group_id][edge_type] += 1
342
+
343
+ # check if group_id is eligible to be split
344
+ group_size = len(current_group)
345
+ for other_group_id in groups:
346
+ edge_counts = Counter()
347
+ for node in current_group:
348
+ edge_counts.update(nbr_info[node][other_group_id].keys())
349
+
350
+ if not all(count == group_size for count in edge_counts.values()):
351
+ # only the nbr_info of the returned group_id is required for handling group splits
352
+ return group_id, nbr_info
353
+
354
+ # if no eligible groups, complete nbr_info is calculated
355
+ return None, nbr_info
356
+
357
+
358
+ def _snap_split(groups, neighbor_info, group_lookup, group_id):
359
+ """
360
+ Splits a group based on edge types and updates the groups accordingly
361
+
362
+ Splits the group with the given group_id based on the edge types
363
+ of the nodes so that each new grouping will all have the same
364
+ edges with other nodes.
365
+
366
+ Parameters
367
+ ----------
368
+ groups: dict
369
+ A dictionary of unique group IDs and their corresponding node groups
370
+ neighbor_info: dict
371
+ A data structure indicating the number of edges a node has with the
372
+ groups in the current summarization of each edge type
373
+ edge_types: dict
374
+ dictionary of edges in the graph and their corresponding attributes recognized
375
+ in the summarization
376
+ group_lookup: dict
377
+ dictionary of nodes and their current corresponding group ID
378
+ group_id: object
379
+ ID of group to be split
380
+
381
+ Returns
382
+ -------
383
+ dict
384
+ The updated groups based on the split
385
+ """
386
+ new_group_mappings = defaultdict(set)
387
+ for node in groups[group_id]:
388
+ signature = tuple(
389
+ frozenset(edge_types) for edge_types in neighbor_info[node].values()
390
+ )
391
+ new_group_mappings[signature].add(node)
392
+
393
+ # leave the biggest new_group as the original group
394
+ new_groups = sorted(new_group_mappings.values(), key=len)
395
+ for new_group in new_groups[:-1]:
396
+ # Assign unused integer as the new_group_id
397
+ # ids are tuples, so will not interact with the original group_ids
398
+ new_group_id = len(groups)
399
+ groups[new_group_id] = new_group
400
+ groups[group_id] -= new_group
401
+ for node in new_group:
402
+ group_lookup[node] = new_group_id
403
+
404
+ return groups
405
+
406
+
407
+ @nx._dispatchable(
408
+ node_attrs="[node_attributes]", edge_attrs="[edge_attributes]", returns_graph=True
409
+ )
410
+ def snap_aggregation(
411
+ G,
412
+ node_attributes,
413
+ edge_attributes=(),
414
+ prefix="Supernode-",
415
+ supernode_attribute="group",
416
+ superedge_attribute="types",
417
+ ):
418
+ """Creates a summary graph based on attributes and connectivity.
419
+
420
+ This function uses the Summarization by Grouping Nodes on Attributes
421
+ and Pairwise edges (SNAP) algorithm for summarizing a given
422
+ graph by grouping nodes by node attributes and their edge attributes
423
+ into supernodes in a summary graph. This name SNAP should not be
424
+ confused with the Stanford Network Analysis Project (SNAP).
425
+
426
+ Here is a high-level view of how this algorithm works:
427
+
428
+ 1) Group nodes by node attribute values.
429
+
430
+ 2) Iteratively split groups until all nodes in each group have edges
431
+ to nodes in the same groups. That is, until all the groups are homogeneous
432
+ in their member nodes' edges to other groups. For example,
433
+ if all the nodes in group A only have edge to nodes in group B, then the
434
+ group is homogeneous and does not need to be split. If all nodes in group B
435
+ have edges with nodes in groups {A, C}, but some also have edges with other
436
+ nodes in B, then group B is not homogeneous and needs to be split into
437
+ groups have edges with {A, C} and a group of nodes having
438
+ edges with {A, B, C}. This way, viewers of the summary graph can
439
+ assume that all nodes in the group have the exact same node attributes and
440
+ the exact same edges.
441
+
442
+ 3) Build the output summary graph, where the groups are represented by
443
+ super-nodes. Edges represent the edges shared between all the nodes in each
444
+ respective groups.
445
+
446
+ A SNAP summary graph can be used to visualize graphs that are too large to display
447
+ or visually analyze, or to efficiently identify sets of similar nodes with similar connectivity
448
+ patterns to other sets of similar nodes based on specified node and/or edge attributes in a graph.
449
+
450
+ Parameters
451
+ ----------
452
+ G: graph
453
+ Networkx Graph to be summarized
454
+ node_attributes: iterable, required
455
+ An iterable of the node attributes used to group nodes in the summarization process. Nodes
456
+ with the same values for these attributes will be grouped together in the summary graph.
457
+ edge_attributes: iterable, optional
458
+ An iterable of the edge attributes considered in the summarization process. If provided, unique
459
+ combinations of the attribute values found in the graph are used to
460
+ determine the edge types in the graph. If not provided, all edges
461
+ are considered to be of the same type.
462
+ prefix: str
463
+ The prefix used to denote supernodes in the summary graph. Defaults to 'Supernode-'.
464
+ supernode_attribute: str
465
+ The node attribute for recording the supernode groupings of nodes. Defaults to 'group'.
466
+ superedge_attribute: str
467
+ The edge attribute for recording the edge types of multiple edges. Defaults to 'types'.
468
+
469
+ Returns
470
+ -------
471
+ networkx.Graph: summary graph
472
+
473
+ Examples
474
+ --------
475
+ SNAP aggregation takes a graph and summarizes it in the context of user-provided
476
+ node and edge attributes such that a viewer can more easily extract and
477
+ analyze the information represented by the graph
478
+
479
+ >>> nodes = {
480
+ ... "A": dict(color="Red"),
481
+ ... "B": dict(color="Red"),
482
+ ... "C": dict(color="Red"),
483
+ ... "D": dict(color="Red"),
484
+ ... "E": dict(color="Blue"),
485
+ ... "F": dict(color="Blue"),
486
+ ... }
487
+ >>> edges = [
488
+ ... ("A", "E", "Strong"),
489
+ ... ("B", "F", "Strong"),
490
+ ... ("C", "E", "Weak"),
491
+ ... ("D", "F", "Weak"),
492
+ ... ]
493
+ >>> G = nx.Graph()
494
+ >>> for node in nodes:
495
+ ... attributes = nodes[node]
496
+ ... G.add_node(node, **attributes)
497
+ >>> for source, target, type in edges:
498
+ ... G.add_edge(source, target, type=type)
499
+ >>> node_attributes = ("color",)
500
+ >>> edge_attributes = ("type",)
501
+ >>> summary_graph = nx.snap_aggregation(
502
+ ... G, node_attributes=node_attributes, edge_attributes=edge_attributes
503
+ ... )
504
+
505
+ Notes
506
+ -----
507
+ The summary graph produced is called a maximum Attribute-edge
508
+ compatible (AR-compatible) grouping. According to [1]_, an
509
+ AR-compatible grouping means that all nodes in each group have the same
510
+ exact node attribute values and the same exact edges and
511
+ edge types to one or more nodes in the same groups. The maximal
512
+ AR-compatible grouping is the grouping with the minimal cardinality.
513
+
514
+ The AR-compatible grouping is the most detailed grouping provided by
515
+ any of the SNAP algorithms.
516
+
517
+ References
518
+ ----------
519
+ .. [1] Y. Tian, R. A. Hankins, and J. M. Patel. Efficient aggregation
520
+ for graph summarization. In Proc. 2008 ACM-SIGMOD Int. Conf.
521
+ Management of Data (SIGMOD’08), pages 567–580, Vancouver, Canada,
522
+ June 2008.
523
+ """
524
+ edge_types = {
525
+ edge: tuple(attrs.get(attr) for attr in edge_attributes)
526
+ for edge, attrs in G.edges.items()
527
+ }
528
+ if not G.is_directed():
529
+ if G.is_multigraph():
530
+ # list is needed to avoid mutating while iterating
531
+ edges = [((v, u, k), etype) for (u, v, k), etype in edge_types.items()]
532
+ else:
533
+ # list is needed to avoid mutating while iterating
534
+ edges = [((v, u), etype) for (u, v), etype in edge_types.items()]
535
+ edge_types.update(edges)
536
+
537
+ group_lookup = {
538
+ node: tuple(attrs[attr] for attr in node_attributes)
539
+ for node, attrs in G.nodes.items()
540
+ }
541
+ groups = defaultdict(set)
542
+ for node, node_type in group_lookup.items():
543
+ groups[node_type].add(node)
544
+
545
+ eligible_group_id, nbr_info = _snap_eligible_group(
546
+ G, groups, group_lookup, edge_types
547
+ )
548
+ while eligible_group_id:
549
+ groups = _snap_split(groups, nbr_info, group_lookup, eligible_group_id)
550
+ eligible_group_id, nbr_info = _snap_eligible_group(
551
+ G, groups, group_lookup, edge_types
552
+ )
553
+ return _snap_build_graph(
554
+ G,
555
+ groups,
556
+ node_attributes,
557
+ edge_attributes,
558
+ nbr_info,
559
+ edge_types,
560
+ prefix,
561
+ supernode_attribute,
562
+ superedge_attribute,
563
+ )
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/swap.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Swap edges in a graph.
2
+ """
3
+
4
+ import math
5
+
6
+ import networkx as nx
7
+ from networkx.utils import py_random_state
8
+
9
+ __all__ = ["double_edge_swap", "connected_double_edge_swap", "directed_edge_swap"]
10
+
11
+
12
+ @nx.utils.not_implemented_for("undirected")
13
+ @py_random_state(3)
14
+ @nx._dispatchable(mutates_input=True, returns_graph=True)
15
+ def directed_edge_swap(G, *, nswap=1, max_tries=100, seed=None):
16
+ """Swap three edges in a directed graph while keeping the node degrees fixed.
17
+
18
+ A directed edge swap swaps three edges such that a -> b -> c -> d becomes
19
+ a -> c -> b -> d. This pattern of swapping allows all possible states with the
20
+ same in- and out-degree distribution in a directed graph to be reached.
21
+
22
+ If the swap would create parallel edges (e.g. if a -> c already existed in the
23
+ previous example), another attempt is made to find a suitable trio of edges.
24
+
25
+ Parameters
26
+ ----------
27
+ G : DiGraph
28
+ A directed graph
29
+
30
+ nswap : integer (optional, default=1)
31
+ Number of three-edge (directed) swaps to perform
32
+
33
+ max_tries : integer (optional, default=100)
34
+ Maximum number of attempts to swap edges
35
+
36
+ seed : integer, random_state, or None (default)
37
+ Indicator of random number generation state.
38
+ See :ref:`Randomness<randomness>`.
39
+
40
+ Returns
41
+ -------
42
+ G : DiGraph
43
+ The graph after the edges are swapped.
44
+
45
+ Raises
46
+ ------
47
+ NetworkXError
48
+ If `G` is not directed, or
49
+ If nswap > max_tries, or
50
+ If there are fewer than 4 nodes or 3 edges in `G`.
51
+ NetworkXAlgorithmError
52
+ If the number of swap attempts exceeds `max_tries` before `nswap` swaps are made
53
+
54
+ Notes
55
+ -----
56
+ Does not enforce any connectivity constraints.
57
+
58
+ The graph G is modified in place.
59
+
60
+ A later swap is allowed to undo a previous swap.
61
+
62
+ References
63
+ ----------
64
+ .. [1] Erdős, Péter L., et al. “A Simple Havel-Hakimi Type Algorithm to Realize
65
+ Graphical Degree Sequences of Directed Graphs.” ArXiv:0905.4913 [Math],
66
+ Jan. 2010. https://doi.org/10.48550/arXiv.0905.4913.
67
+ Published 2010 in Elec. J. Combinatorics (17(1)). R66.
68
+ http://www.combinatorics.org/Volume_17/PDF/v17i1r66.pdf
69
+ .. [2] “Combinatorics - Reaching All Possible Simple Directed Graphs with a given
70
+ Degree Sequence with 2-Edge Swaps.” Mathematics Stack Exchange,
71
+ https://math.stackexchange.com/questions/22272/. Accessed 30 May 2022.
72
+ """
73
+ if nswap > max_tries:
74
+ raise nx.NetworkXError("Number of swaps > number of tries allowed.")
75
+ if len(G) < 4:
76
+ raise nx.NetworkXError("DiGraph has fewer than four nodes.")
77
+ if len(G.edges) < 3:
78
+ raise nx.NetworkXError("DiGraph has fewer than 3 edges")
79
+
80
+ # Instead of choosing uniformly at random from a generated edge list,
81
+ # this algorithm chooses nonuniformly from the set of nodes with
82
+ # probability weighted by degree.
83
+ tries = 0
84
+ swapcount = 0
85
+ keys, degrees = zip(*G.degree()) # keys, degree
86
+ cdf = nx.utils.cumulative_distribution(degrees) # cdf of degree
87
+ discrete_sequence = nx.utils.discrete_sequence
88
+
89
+ while swapcount < nswap:
90
+ # choose source node index from discrete distribution
91
+ start_index = discrete_sequence(1, cdistribution=cdf, seed=seed)[0]
92
+ start = keys[start_index]
93
+ tries += 1
94
+
95
+ if tries > max_tries:
96
+ msg = f"Maximum number of swap attempts ({tries}) exceeded before desired swaps achieved ({nswap})."
97
+ raise nx.NetworkXAlgorithmError(msg)
98
+
99
+ # If the given node doesn't have any out edges, then there isn't anything to swap
100
+ if G.out_degree(start) == 0:
101
+ continue
102
+ second = seed.choice(list(G.succ[start]))
103
+ if start == second:
104
+ continue
105
+
106
+ if G.out_degree(second) == 0:
107
+ continue
108
+ third = seed.choice(list(G.succ[second]))
109
+ if second == third:
110
+ continue
111
+
112
+ if G.out_degree(third) == 0:
113
+ continue
114
+ fourth = seed.choice(list(G.succ[third]))
115
+ if third == fourth:
116
+ continue
117
+
118
+ if (
119
+ third not in G.succ[start]
120
+ and fourth not in G.succ[second]
121
+ and second not in G.succ[third]
122
+ ):
123
+ # Swap nodes
124
+ G.add_edge(start, third)
125
+ G.add_edge(third, second)
126
+ G.add_edge(second, fourth)
127
+ G.remove_edge(start, second)
128
+ G.remove_edge(second, third)
129
+ G.remove_edge(third, fourth)
130
+ swapcount += 1
131
+
132
+ return G
133
+
134
+
135
+ @py_random_state(3)
136
+ @nx._dispatchable(mutates_input=True, returns_graph=True)
137
+ def double_edge_swap(G, nswap=1, max_tries=100, seed=None):
138
+ """Swap two edges in the graph while keeping the node degrees fixed.
139
+
140
+ A double-edge swap removes two randomly chosen edges u-v and x-y
141
+ and creates the new edges u-x and v-y::
142
+
143
+ u--v u v
144
+ becomes | |
145
+ x--y x y
146
+
147
+ If either the edge u-x or v-y already exist no swap is performed
148
+ and another attempt is made to find a suitable edge pair.
149
+
150
+ Parameters
151
+ ----------
152
+ G : graph
153
+ An undirected graph
154
+
155
+ nswap : integer (optional, default=1)
156
+ Number of double-edge swaps to perform
157
+
158
+ max_tries : integer (optional)
159
+ Maximum number of attempts to swap edges
160
+
161
+ seed : integer, random_state, or None (default)
162
+ Indicator of random number generation state.
163
+ See :ref:`Randomness<randomness>`.
164
+
165
+ Returns
166
+ -------
167
+ G : graph
168
+ The graph after double edge swaps.
169
+
170
+ Raises
171
+ ------
172
+ NetworkXError
173
+ If `G` is directed, or
174
+ If `nswap` > `max_tries`, or
175
+ If there are fewer than 4 nodes or 2 edges in `G`.
176
+ NetworkXAlgorithmError
177
+ If the number of swap attempts exceeds `max_tries` before `nswap` swaps are made
178
+
179
+ Notes
180
+ -----
181
+ Does not enforce any connectivity constraints.
182
+
183
+ The graph G is modified in place.
184
+ """
185
+ if G.is_directed():
186
+ raise nx.NetworkXError(
187
+ "double_edge_swap() not defined for directed graphs. Use directed_edge_swap instead."
188
+ )
189
+ if nswap > max_tries:
190
+ raise nx.NetworkXError("Number of swaps > number of tries allowed.")
191
+ if len(G) < 4:
192
+ raise nx.NetworkXError("Graph has fewer than four nodes.")
193
+ if len(G.edges) < 2:
194
+ raise nx.NetworkXError("Graph has fewer than 2 edges")
195
+ # Instead of choosing uniformly at random from a generated edge list,
196
+ # this algorithm chooses nonuniformly from the set of nodes with
197
+ # probability weighted by degree.
198
+ n = 0
199
+ swapcount = 0
200
+ keys, degrees = zip(*G.degree()) # keys, degree
201
+ cdf = nx.utils.cumulative_distribution(degrees) # cdf of degree
202
+ discrete_sequence = nx.utils.discrete_sequence
203
+ while swapcount < nswap:
204
+ # if random.random() < 0.5: continue # trick to avoid periodicities?
205
+ # pick two random edges without creating edge list
206
+ # choose source node indices from discrete distribution
207
+ (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed)
208
+ if ui == xi:
209
+ continue # same source, skip
210
+ u = keys[ui] # convert index to label
211
+ x = keys[xi]
212
+ # choose target uniformly from neighbors
213
+ v = seed.choice(list(G[u]))
214
+ y = seed.choice(list(G[x]))
215
+ if v == y:
216
+ continue # same target, skip
217
+ if (x not in G[u]) and (y not in G[v]): # don't create parallel edges
218
+ G.add_edge(u, x)
219
+ G.add_edge(v, y)
220
+ G.remove_edge(u, v)
221
+ G.remove_edge(x, y)
222
+ swapcount += 1
223
+ if n >= max_tries:
224
+ e = (
225
+ f"Maximum number of swap attempts ({n}) exceeded "
226
+ f"before desired swaps achieved ({nswap})."
227
+ )
228
+ raise nx.NetworkXAlgorithmError(e)
229
+ n += 1
230
+ return G
231
+
232
+
233
+ @py_random_state(3)
234
+ @nx._dispatchable(mutates_input=True)
235
+ def connected_double_edge_swap(G, nswap=1, _window_threshold=3, seed=None):
236
+ """Attempts the specified number of double-edge swaps in the graph `G`.
237
+
238
+ A double-edge swap removes two randomly chosen edges `(u, v)` and `(x,
239
+ y)` and creates the new edges `(u, x)` and `(v, y)`::
240
+
241
+ u--v u v
242
+ becomes | |
243
+ x--y x y
244
+
245
+ If either `(u, x)` or `(v, y)` already exist, then no swap is performed
246
+ so the actual number of swapped edges is always *at most* `nswap`.
247
+
248
+ Parameters
249
+ ----------
250
+ G : graph
251
+ An undirected graph
252
+
253
+ nswap : integer (optional, default=1)
254
+ Number of double-edge swaps to perform
255
+
256
+ _window_threshold : integer
257
+
258
+ The window size below which connectedness of the graph will be checked
259
+ after each swap.
260
+
261
+ The "window" in this function is a dynamically updated integer that
262
+ represents the number of swap attempts to make before checking if the
263
+ graph remains connected. It is an optimization used to decrease the
264
+ running time of the algorithm in exchange for increased complexity of
265
+ implementation.
266
+
267
+ If the window size is below this threshold, then the algorithm checks
268
+ after each swap if the graph remains connected by checking if there is a
269
+ path joining the two nodes whose edge was just removed. If the window
270
+ size is above this threshold, then the algorithm performs do all the
271
+ swaps in the window and only then check if the graph is still connected.
272
+
273
+ seed : integer, random_state, or None (default)
274
+ Indicator of random number generation state.
275
+ See :ref:`Randomness<randomness>`.
276
+
277
+ Returns
278
+ -------
279
+ int
280
+ The number of successful swaps
281
+
282
+ Raises
283
+ ------
284
+
285
+ NetworkXError
286
+
287
+ If the input graph is not connected, or if the graph has fewer than four
288
+ nodes.
289
+
290
+ Notes
291
+ -----
292
+
293
+ The initial graph `G` must be connected, and the resulting graph is
294
+ connected. The graph `G` is modified in place.
295
+
296
+ References
297
+ ----------
298
+ .. [1] C. Gkantsidis and M. Mihail and E. Zegura,
299
+ The Markov chain simulation method for generating connected
300
+ power law random graphs, 2003.
301
+ http://citeseer.ist.psu.edu/gkantsidis03markov.html
302
+ """
303
+ if not nx.is_connected(G):
304
+ raise nx.NetworkXError("Graph not connected")
305
+ if len(G) < 4:
306
+ raise nx.NetworkXError("Graph has fewer than four nodes.")
307
+ n = 0
308
+ swapcount = 0
309
+ deg = G.degree()
310
+ # Label key for nodes
311
+ dk = [n for n, d in G.degree()]
312
+ cdf = nx.utils.cumulative_distribution([d for n, d in G.degree()])
313
+ discrete_sequence = nx.utils.discrete_sequence
314
+ window = 1
315
+ while n < nswap:
316
+ wcount = 0
317
+ swapped = []
318
+ # If the window is small, we just check each time whether the graph is
319
+ # connected by checking if the nodes that were just separated are still
320
+ # connected.
321
+ if window < _window_threshold:
322
+ # This Boolean keeps track of whether there was a failure or not.
323
+ fail = False
324
+ while wcount < window and n < nswap:
325
+ # Pick two random edges without creating the edge list. Choose
326
+ # source nodes from the discrete degree distribution.
327
+ (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed)
328
+ # If the source nodes are the same, skip this pair.
329
+ if ui == xi:
330
+ continue
331
+ # Convert an index to a node label.
332
+ u = dk[ui]
333
+ x = dk[xi]
334
+ # Choose targets uniformly from neighbors.
335
+ v = seed.choice(list(G.neighbors(u)))
336
+ y = seed.choice(list(G.neighbors(x)))
337
+ # If the target nodes are the same, skip this pair.
338
+ if v == y:
339
+ continue
340
+ if x not in G[u] and y not in G[v]:
341
+ G.remove_edge(u, v)
342
+ G.remove_edge(x, y)
343
+ G.add_edge(u, x)
344
+ G.add_edge(v, y)
345
+ swapped.append((u, v, x, y))
346
+ swapcount += 1
347
+ n += 1
348
+ # If G remains connected...
349
+ if nx.has_path(G, u, v):
350
+ wcount += 1
351
+ # Otherwise, undo the changes.
352
+ else:
353
+ G.add_edge(u, v)
354
+ G.add_edge(x, y)
355
+ G.remove_edge(u, x)
356
+ G.remove_edge(v, y)
357
+ swapcount -= 1
358
+ fail = True
359
+ # If one of the swaps failed, reduce the window size.
360
+ if fail:
361
+ window = math.ceil(window / 2)
362
+ else:
363
+ window += 1
364
+ # If the window is large, then there is a good chance that a bunch of
365
+ # swaps will work. It's quicker to do all those swaps first and then
366
+ # check if the graph remains connected.
367
+ else:
368
+ while wcount < window and n < nswap:
369
+ # Pick two random edges without creating the edge list. Choose
370
+ # source nodes from the discrete degree distribution.
371
+ (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed)
372
+ # If the source nodes are the same, skip this pair.
373
+ if ui == xi:
374
+ continue
375
+ # Convert an index to a node label.
376
+ u = dk[ui]
377
+ x = dk[xi]
378
+ # Choose targets uniformly from neighbors.
379
+ v = seed.choice(list(G.neighbors(u)))
380
+ y = seed.choice(list(G.neighbors(x)))
381
+ # If the target nodes are the same, skip this pair.
382
+ if v == y:
383
+ continue
384
+ if x not in G[u] and y not in G[v]:
385
+ G.remove_edge(u, v)
386
+ G.remove_edge(x, y)
387
+ G.add_edge(u, x)
388
+ G.add_edge(v, y)
389
+ swapped.append((u, v, x, y))
390
+ swapcount += 1
391
+ n += 1
392
+ wcount += 1
393
+ # If the graph remains connected, increase the window size.
394
+ if nx.is_connected(G):
395
+ window += 1
396
+ # Otherwise, undo the changes from the previous window and decrease
397
+ # the window size.
398
+ else:
399
+ while swapped:
400
+ (u, v, x, y) = swapped.pop()
401
+ G.add_edge(u, v)
402
+ G.add_edge(x, y)
403
+ G.remove_edge(u, x)
404
+ G.remove_edge(v, y)
405
+ swapcount -= 1
406
+ window = math.ceil(window / 2)
407
+ return swapcount
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/tournament.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions concerning tournament graphs.
2
+
3
+ A `tournament graph`_ is a complete oriented graph. In other words, it
4
+ is a directed graph in which there is exactly one directed edge joining
5
+ each pair of distinct nodes. For each function in this module that
6
+ accepts a graph as input, you must provide a tournament graph. The
7
+ responsibility is on the caller to ensure that the graph is a tournament
8
+ graph:
9
+
10
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
11
+ >>> nx.is_tournament(G)
12
+ True
13
+
14
+ To access the functions in this module, you must access them through the
15
+ :mod:`networkx.tournament` module::
16
+
17
+ >>> nx.tournament.is_reachable(G, 0, 1)
18
+ True
19
+
20
+ .. _tournament graph: https://en.wikipedia.org/wiki/Tournament_%28graph_theory%29
21
+
22
+ """
23
+ from itertools import combinations
24
+
25
+ import networkx as nx
26
+ from networkx.algorithms.simple_paths import is_simple_path as is_path
27
+ from networkx.utils import arbitrary_element, not_implemented_for, py_random_state
28
+
29
+ __all__ = [
30
+ "hamiltonian_path",
31
+ "is_reachable",
32
+ "is_strongly_connected",
33
+ "is_tournament",
34
+ "random_tournament",
35
+ "score_sequence",
36
+ ]
37
+
38
+
39
+ def index_satisfying(iterable, condition):
40
+ """Returns the index of the first element in `iterable` that
41
+ satisfies the given condition.
42
+
43
+ If no such element is found (that is, when the iterable is
44
+ exhausted), this returns the length of the iterable (that is, one
45
+ greater than the last index of the iterable).
46
+
47
+ `iterable` must not be empty. If `iterable` is empty, this
48
+ function raises :exc:`ValueError`.
49
+
50
+ """
51
+ # Pre-condition: iterable must not be empty.
52
+ for i, x in enumerate(iterable):
53
+ if condition(x):
54
+ return i
55
+ # If we reach the end of the iterable without finding an element
56
+ # that satisfies the condition, return the length of the iterable,
57
+ # which is one greater than the index of its last element. If the
58
+ # iterable was empty, `i` will not be defined, so we raise an
59
+ # exception.
60
+ try:
61
+ return i + 1
62
+ except NameError as err:
63
+ raise ValueError("iterable must be non-empty") from err
64
+
65
+
66
+ @not_implemented_for("undirected")
67
+ @not_implemented_for("multigraph")
68
+ @nx._dispatchable
69
+ def is_tournament(G):
70
+ """Returns True if and only if `G` is a tournament.
71
+
72
+ A tournament is a directed graph, with neither self-loops nor
73
+ multi-edges, in which there is exactly one directed edge joining
74
+ each pair of distinct nodes.
75
+
76
+ Parameters
77
+ ----------
78
+ G : NetworkX graph
79
+ A directed graph representing a tournament.
80
+
81
+ Returns
82
+ -------
83
+ bool
84
+ Whether the given graph is a tournament graph.
85
+
86
+ Examples
87
+ --------
88
+ >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 0)])
89
+ >>> nx.is_tournament(G)
90
+ True
91
+
92
+ Notes
93
+ -----
94
+ Some definitions require a self-loop on each node, but that is not
95
+ the convention used here.
96
+
97
+ """
98
+ # In a tournament, there is exactly one directed edge joining each pair.
99
+ return (
100
+ all((v in G[u]) ^ (u in G[v]) for u, v in combinations(G, 2))
101
+ and nx.number_of_selfloops(G) == 0
102
+ )
103
+
104
+
105
+ @not_implemented_for("undirected")
106
+ @not_implemented_for("multigraph")
107
+ @nx._dispatchable
108
+ def hamiltonian_path(G):
109
+ """Returns a Hamiltonian path in the given tournament graph.
110
+
111
+ Each tournament has a Hamiltonian path. If furthermore, the
112
+ tournament is strongly connected, then the returned Hamiltonian path
113
+ is a Hamiltonian cycle (by joining the endpoints of the path).
114
+
115
+ Parameters
116
+ ----------
117
+ G : NetworkX graph
118
+ A directed graph representing a tournament.
119
+
120
+ Returns
121
+ -------
122
+ path : list
123
+ A list of nodes which form a Hamiltonian path in `G`.
124
+
125
+ Examples
126
+ --------
127
+ >>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)])
128
+ >>> nx.is_tournament(G)
129
+ True
130
+ >>> nx.tournament.hamiltonian_path(G)
131
+ [0, 1, 2, 3]
132
+
133
+ Notes
134
+ -----
135
+ This is a recursive implementation with an asymptotic running time
136
+ of $O(n^2)$, ignoring multiplicative polylogarithmic factors, where
137
+ $n$ is the number of nodes in the graph.
138
+
139
+ """
140
+ if len(G) == 0:
141
+ return []
142
+ if len(G) == 1:
143
+ return [arbitrary_element(G)]
144
+ v = arbitrary_element(G)
145
+ hampath = hamiltonian_path(G.subgraph(set(G) - {v}))
146
+ # Get the index of the first node in the path that does *not* have
147
+ # an edge to `v`, then insert `v` before that node.
148
+ index = index_satisfying(hampath, lambda u: v not in G[u])
149
+ hampath.insert(index, v)
150
+ return hampath
151
+
152
+
153
+ @py_random_state(1)
154
+ @nx._dispatchable(graphs=None, returns_graph=True)
155
+ def random_tournament(n, seed=None):
156
+ r"""Returns a random tournament graph on `n` nodes.
157
+
158
+ Parameters
159
+ ----------
160
+ n : int
161
+ The number of nodes in the returned graph.
162
+ seed : integer, random_state, or None (default)
163
+ Indicator of random number generation state.
164
+ See :ref:`Randomness<randomness>`.
165
+
166
+ Returns
167
+ -------
168
+ G : DiGraph
169
+ A tournament on `n` nodes, with exactly one directed edge joining
170
+ each pair of distinct nodes.
171
+
172
+ Notes
173
+ -----
174
+ This algorithm adds, for each pair of distinct nodes, an edge with
175
+ uniformly random orientation. In other words, `\binom{n}{2}` flips
176
+ of an unbiased coin decide the orientations of the edges in the
177
+ graph.
178
+
179
+ """
180
+ # Flip an unbiased coin for each pair of distinct nodes.
181
+ coins = (seed.random() for i in range((n * (n - 1)) // 2))
182
+ pairs = combinations(range(n), 2)
183
+ edges = ((u, v) if r < 0.5 else (v, u) for (u, v), r in zip(pairs, coins))
184
+ return nx.DiGraph(edges)
185
+
186
+
187
+ @not_implemented_for("undirected")
188
+ @not_implemented_for("multigraph")
189
+ @nx._dispatchable
190
+ def score_sequence(G):
191
+ """Returns the score sequence for the given tournament graph.
192
+
193
+ The score sequence is the sorted list of the out-degrees of the
194
+ nodes of the graph.
195
+
196
+ Parameters
197
+ ----------
198
+ G : NetworkX graph
199
+ A directed graph representing a tournament.
200
+
201
+ Returns
202
+ -------
203
+ list
204
+ A sorted list of the out-degrees of the nodes of `G`.
205
+
206
+ Examples
207
+ --------
208
+ >>> G = nx.DiGraph([(1, 0), (1, 3), (0, 2), (0, 3), (2, 1), (3, 2)])
209
+ >>> nx.is_tournament(G)
210
+ True
211
+ >>> nx.tournament.score_sequence(G)
212
+ [1, 1, 2, 2]
213
+
214
+ """
215
+ return sorted(d for v, d in G.out_degree())
216
+
217
+
218
+ @not_implemented_for("undirected")
219
+ @not_implemented_for("multigraph")
220
+ @nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
221
+ def tournament_matrix(G):
222
+ r"""Returns the tournament matrix for the given tournament graph.
223
+
224
+ This function requires SciPy.
225
+
226
+ The *tournament matrix* of a tournament graph with edge set *E* is
227
+ the matrix *T* defined by
228
+
229
+ .. math::
230
+
231
+ T_{i j} =
232
+ \begin{cases}
233
+ +1 & \text{if } (i, j) \in E \\
234
+ -1 & \text{if } (j, i) \in E \\
235
+ 0 & \text{if } i == j.
236
+ \end{cases}
237
+
238
+ An equivalent definition is `T = A - A^T`, where *A* is the
239
+ adjacency matrix of the graph `G`.
240
+
241
+ Parameters
242
+ ----------
243
+ G : NetworkX graph
244
+ A directed graph representing a tournament.
245
+
246
+ Returns
247
+ -------
248
+ SciPy sparse array
249
+ The tournament matrix of the tournament graph `G`.
250
+
251
+ Raises
252
+ ------
253
+ ImportError
254
+ If SciPy is not available.
255
+
256
+ """
257
+ A = nx.adjacency_matrix(G)
258
+ return A - A.T
259
+
260
+
261
+ @not_implemented_for("undirected")
262
+ @not_implemented_for("multigraph")
263
+ @nx._dispatchable
264
+ def is_reachable(G, s, t):
265
+ """Decides whether there is a path from `s` to `t` in the
266
+ tournament.
267
+
268
+ This function is more theoretically efficient than the reachability
269
+ checks than the shortest path algorithms in
270
+ :mod:`networkx.algorithms.shortest_paths`.
271
+
272
+ The given graph **must** be a tournament, otherwise this function's
273
+ behavior is undefined.
274
+
275
+ Parameters
276
+ ----------
277
+ G : NetworkX graph
278
+ A directed graph representing a tournament.
279
+
280
+ s : node
281
+ A node in the graph.
282
+
283
+ t : node
284
+ A node in the graph.
285
+
286
+ Returns
287
+ -------
288
+ bool
289
+ Whether there is a path from `s` to `t` in `G`.
290
+
291
+ Examples
292
+ --------
293
+ >>> G = nx.DiGraph([(1, 0), (1, 3), (1, 2), (2, 3), (2, 0), (3, 0)])
294
+ >>> nx.is_tournament(G)
295
+ True
296
+ >>> nx.tournament.is_reachable(G, 1, 3)
297
+ True
298
+ >>> nx.tournament.is_reachable(G, 3, 2)
299
+ False
300
+
301
+ Notes
302
+ -----
303
+ Although this function is more theoretically efficient than the
304
+ generic shortest path functions, a speedup requires the use of
305
+ parallelism. Though it may in the future, the current implementation
306
+ does not use parallelism, thus you may not see much of a speedup.
307
+
308
+ This algorithm comes from [1].
309
+
310
+ References
311
+ ----------
312
+ .. [1] Tantau, Till.
313
+ "A note on the complexity of the reachability problem for
314
+ tournaments."
315
+ *Electronic Colloquium on Computational Complexity*. 2001.
316
+ <http://eccc.hpi-web.de/report/2001/092/>
317
+ """
318
+
319
+ def two_neighborhood(G, v):
320
+ """Returns the set of nodes at distance at most two from `v`.
321
+
322
+ `G` must be a graph and `v` a node in that graph.
323
+
324
+ The returned set includes the nodes at distance zero (that is,
325
+ the node `v` itself), the nodes at distance one (that is, the
326
+ out-neighbors of `v`), and the nodes at distance two.
327
+
328
+ """
329
+ # TODO This is trivially parallelizable.
330
+ return {
331
+ x for x in G if x == v or x in G[v] or any(is_path(G, [v, z, x]) for z in G)
332
+ }
333
+
334
+ def is_closed(G, nodes):
335
+ """Decides whether the given set of nodes is closed.
336
+
337
+ A set *S* of nodes is *closed* if for each node *u* in the graph
338
+ not in *S* and for each node *v* in *S*, there is an edge from
339
+ *u* to *v*.
340
+
341
+ """
342
+ # TODO This is trivially parallelizable.
343
+ return all(v in G[u] for u in set(G) - nodes for v in nodes)
344
+
345
+ # TODO This is trivially parallelizable.
346
+ neighborhoods = [two_neighborhood(G, v) for v in G]
347
+ return all(not (is_closed(G, S) and s in S and t not in S) for S in neighborhoods)
348
+
349
+
350
+ @not_implemented_for("undirected")
351
+ @not_implemented_for("multigraph")
352
+ @nx._dispatchable(name="tournament_is_strongly_connected")
353
+ def is_strongly_connected(G):
354
+ """Decides whether the given tournament is strongly connected.
355
+
356
+ This function is more theoretically efficient than the
357
+ :func:`~networkx.algorithms.components.is_strongly_connected`
358
+ function.
359
+
360
+ The given graph **must** be a tournament, otherwise this function's
361
+ behavior is undefined.
362
+
363
+ Parameters
364
+ ----------
365
+ G : NetworkX graph
366
+ A directed graph representing a tournament.
367
+
368
+ Returns
369
+ -------
370
+ bool
371
+ Whether the tournament is strongly connected.
372
+
373
+ Examples
374
+ --------
375
+ >>> G = nx.DiGraph([(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 0)])
376
+ >>> nx.is_tournament(G)
377
+ True
378
+ >>> nx.tournament.is_strongly_connected(G)
379
+ True
380
+ >>> G.remove_edge(3, 0)
381
+ >>> G.add_edge(0, 3)
382
+ >>> nx.is_tournament(G)
383
+ True
384
+ >>> nx.tournament.is_strongly_connected(G)
385
+ False
386
+
387
+ Notes
388
+ -----
389
+ Although this function is more theoretically efficient than the
390
+ generic strong connectivity function, a speedup requires the use of
391
+ parallelism. Though it may in the future, the current implementation
392
+ does not use parallelism, thus you may not see much of a speedup.
393
+
394
+ This algorithm comes from [1].
395
+
396
+ References
397
+ ----------
398
+ .. [1] Tantau, Till.
399
+ "A note on the complexity of the reachability problem for
400
+ tournaments."
401
+ *Electronic Colloquium on Computational Complexity*. 2001.
402
+ <http://eccc.hpi-web.de/report/2001/092/>
403
+
404
+ """
405
+ # TODO This is trivially parallelizable.
406
+ return all(is_reachable(G, u, v) for u in G for v in G)
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/triads.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://github.com/networkx/networkx/pull/1474
2
+ # Copyright 2011 Reya Group <http://www.reyagroup.com>
3
+ # Copyright 2011 Alex Levenson <[email protected]>
4
+ # Copyright 2011 Diederik van Liere <[email protected]>
5
+ """Functions for analyzing triads of a graph."""
6
+
7
+ from collections import defaultdict
8
+ from itertools import combinations, permutations
9
+
10
+ import networkx as nx
11
+ from networkx.utils import not_implemented_for, py_random_state
12
+
13
+ __all__ = [
14
+ "triadic_census",
15
+ "is_triad",
16
+ "all_triplets",
17
+ "all_triads",
18
+ "triads_by_type",
19
+ "triad_type",
20
+ "random_triad",
21
+ ]
22
+
23
+ #: The integer codes representing each type of triad.
24
+ #:
25
+ #: Triads that are the same up to symmetry have the same code.
26
+ TRICODES = (
27
+ 1,
28
+ 2,
29
+ 2,
30
+ 3,
31
+ 2,
32
+ 4,
33
+ 6,
34
+ 8,
35
+ 2,
36
+ 6,
37
+ 5,
38
+ 7,
39
+ 3,
40
+ 8,
41
+ 7,
42
+ 11,
43
+ 2,
44
+ 6,
45
+ 4,
46
+ 8,
47
+ 5,
48
+ 9,
49
+ 9,
50
+ 13,
51
+ 6,
52
+ 10,
53
+ 9,
54
+ 14,
55
+ 7,
56
+ 14,
57
+ 12,
58
+ 15,
59
+ 2,
60
+ 5,
61
+ 6,
62
+ 7,
63
+ 6,
64
+ 9,
65
+ 10,
66
+ 14,
67
+ 4,
68
+ 9,
69
+ 9,
70
+ 12,
71
+ 8,
72
+ 13,
73
+ 14,
74
+ 15,
75
+ 3,
76
+ 7,
77
+ 8,
78
+ 11,
79
+ 7,
80
+ 12,
81
+ 14,
82
+ 15,
83
+ 8,
84
+ 14,
85
+ 13,
86
+ 15,
87
+ 11,
88
+ 15,
89
+ 15,
90
+ 16,
91
+ )
92
+
93
+ #: The names of each type of triad. The order of the elements is
94
+ #: important: it corresponds to the tricodes given in :data:`TRICODES`.
95
+ TRIAD_NAMES = (
96
+ "003",
97
+ "012",
98
+ "102",
99
+ "021D",
100
+ "021U",
101
+ "021C",
102
+ "111D",
103
+ "111U",
104
+ "030T",
105
+ "030C",
106
+ "201",
107
+ "120D",
108
+ "120U",
109
+ "120C",
110
+ "210",
111
+ "300",
112
+ )
113
+
114
+
115
+ #: A dictionary mapping triad code to triad name.
116
+ TRICODE_TO_NAME = {i: TRIAD_NAMES[code - 1] for i, code in enumerate(TRICODES)}
117
+
118
+
119
+ def _tricode(G, v, u, w):
120
+ """Returns the integer code of the given triad.
121
+
122
+ This is some fancy magic that comes from Batagelj and Mrvar's paper. It
123
+ treats each edge joining a pair of `v`, `u`, and `w` as a bit in
124
+ the binary representation of an integer.
125
+
126
+ """
127
+ combos = ((v, u, 1), (u, v, 2), (v, w, 4), (w, v, 8), (u, w, 16), (w, u, 32))
128
+ return sum(x for u, v, x in combos if v in G[u])
129
+
130
+
131
+ @not_implemented_for("undirected")
132
+ @nx._dispatchable
133
+ def triadic_census(G, nodelist=None):
134
+ """Determines the triadic census of a directed graph.
135
+
136
+ The triadic census is a count of how many of the 16 possible types of
137
+ triads are present in a directed graph. If a list of nodes is passed, then
138
+ only those triads are taken into account which have elements of nodelist in them.
139
+
140
+ Parameters
141
+ ----------
142
+ G : digraph
143
+ A NetworkX DiGraph
144
+ nodelist : list
145
+ List of nodes for which you want to calculate triadic census
146
+
147
+ Returns
148
+ -------
149
+ census : dict
150
+ Dictionary with triad type as keys and number of occurrences as values.
151
+
152
+ Examples
153
+ --------
154
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1), (3, 4), (4, 1), (4, 2)])
155
+ >>> triadic_census = nx.triadic_census(G)
156
+ >>> for key, value in triadic_census.items():
157
+ ... print(f"{key}: {value}")
158
+ 003: 0
159
+ 012: 0
160
+ 102: 0
161
+ 021D: 0
162
+ 021U: 0
163
+ 021C: 0
164
+ 111D: 0
165
+ 111U: 0
166
+ 030T: 2
167
+ 030C: 2
168
+ 201: 0
169
+ 120D: 0
170
+ 120U: 0
171
+ 120C: 0
172
+ 210: 0
173
+ 300: 0
174
+
175
+ Notes
176
+ -----
177
+ This algorithm has complexity $O(m)$ where $m$ is the number of edges in
178
+ the graph.
179
+
180
+ For undirected graphs, the triadic census can be computed by first converting
181
+ the graph into a directed graph using the ``G.to_directed()`` method.
182
+ After this conversion, only the triad types 003, 102, 201 and 300 will be
183
+ present in the undirected scenario.
184
+
185
+ Raises
186
+ ------
187
+ ValueError
188
+ If `nodelist` contains duplicate nodes or nodes not in `G`.
189
+ If you want to ignore this you can preprocess with `set(nodelist) & G.nodes`
190
+
191
+ See also
192
+ --------
193
+ triad_graph
194
+
195
+ References
196
+ ----------
197
+ .. [1] Vladimir Batagelj and Andrej Mrvar, A subquadratic triad census
198
+ algorithm for large sparse networks with small maximum degree,
199
+ University of Ljubljana,
200
+ http://vlado.fmf.uni-lj.si/pub/networks/doc/triads/triads.pdf
201
+
202
+ """
203
+ nodeset = set(G.nbunch_iter(nodelist))
204
+ if nodelist is not None and len(nodelist) != len(nodeset):
205
+ raise ValueError("nodelist includes duplicate nodes or nodes not in G")
206
+
207
+ N = len(G)
208
+ Nnot = N - len(nodeset) # can signal special counting for subset of nodes
209
+
210
+ # create an ordering of nodes with nodeset nodes first
211
+ m = {n: i for i, n in enumerate(nodeset)}
212
+ if Nnot:
213
+ # add non-nodeset nodes later in the ordering
214
+ not_nodeset = G.nodes - nodeset
215
+ m.update((n, i + N) for i, n in enumerate(not_nodeset))
216
+
217
+ # build all_neighbor dicts for easy counting
218
+ # After Python 3.8 can leave off these keys(). Speedup also using G._pred
219
+ # nbrs = {n: G._pred[n].keys() | G._succ[n].keys() for n in G}
220
+ nbrs = {n: G.pred[n].keys() | G.succ[n].keys() for n in G}
221
+ dbl_nbrs = {n: G.pred[n].keys() & G.succ[n].keys() for n in G}
222
+
223
+ if Nnot:
224
+ sgl_nbrs = {n: G.pred[n].keys() ^ G.succ[n].keys() for n in not_nodeset}
225
+ # find number of edges not incident to nodes in nodeset
226
+ sgl = sum(1 for n in not_nodeset for nbr in sgl_nbrs[n] if nbr not in nodeset)
227
+ sgl_edges_outside = sgl // 2
228
+ dbl = sum(1 for n in not_nodeset for nbr in dbl_nbrs[n] if nbr not in nodeset)
229
+ dbl_edges_outside = dbl // 2
230
+
231
+ # Initialize the count for each triad to be zero.
232
+ census = {name: 0 for name in TRIAD_NAMES}
233
+ # Main loop over nodes
234
+ for v in nodeset:
235
+ vnbrs = nbrs[v]
236
+ dbl_vnbrs = dbl_nbrs[v]
237
+ if Nnot:
238
+ # set up counts of edges attached to v.
239
+ sgl_unbrs_bdy = sgl_unbrs_out = dbl_unbrs_bdy = dbl_unbrs_out = 0
240
+ for u in vnbrs:
241
+ if m[u] <= m[v]:
242
+ continue
243
+ unbrs = nbrs[u]
244
+ neighbors = (vnbrs | unbrs) - {u, v}
245
+ # Count connected triads.
246
+ for w in neighbors:
247
+ if m[u] < m[w] or (m[v] < m[w] < m[u] and v not in nbrs[w]):
248
+ code = _tricode(G, v, u, w)
249
+ census[TRICODE_TO_NAME[code]] += 1
250
+
251
+ # Use a formula for dyadic triads with edge incident to v
252
+ if u in dbl_vnbrs:
253
+ census["102"] += N - len(neighbors) - 2
254
+ else:
255
+ census["012"] += N - len(neighbors) - 2
256
+
257
+ # Count edges attached to v. Subtract later to get triads with v isolated
258
+ # _out are (u,unbr) for unbrs outside boundary of nodeset
259
+ # _bdy are (u,unbr) for unbrs on boundary of nodeset (get double counted)
260
+ if Nnot and u not in nodeset:
261
+ sgl_unbrs = sgl_nbrs[u]
262
+ sgl_unbrs_bdy += len(sgl_unbrs & vnbrs - nodeset)
263
+ sgl_unbrs_out += len(sgl_unbrs - vnbrs - nodeset)
264
+ dbl_unbrs = dbl_nbrs[u]
265
+ dbl_unbrs_bdy += len(dbl_unbrs & vnbrs - nodeset)
266
+ dbl_unbrs_out += len(dbl_unbrs - vnbrs - nodeset)
267
+ # if nodeset == G.nodes, skip this b/c we will find the edge later.
268
+ if Nnot:
269
+ # Count edges outside nodeset not connected with v (v isolated triads)
270
+ census["012"] += sgl_edges_outside - (sgl_unbrs_out + sgl_unbrs_bdy // 2)
271
+ census["102"] += dbl_edges_outside - (dbl_unbrs_out + dbl_unbrs_bdy // 2)
272
+
273
+ # calculate null triads: "003"
274
+ # null triads = total number of possible triads - all found triads
275
+ total_triangles = (N * (N - 1) * (N - 2)) // 6
276
+ triangles_without_nodeset = (Nnot * (Nnot - 1) * (Nnot - 2)) // 6
277
+ total_census = total_triangles - triangles_without_nodeset
278
+ census["003"] = total_census - sum(census.values())
279
+
280
+ return census
281
+
282
+
283
+ @nx._dispatchable
284
+ def is_triad(G):
285
+ """Returns True if the graph G is a triad, else False.
286
+
287
+ Parameters
288
+ ----------
289
+ G : graph
290
+ A NetworkX Graph
291
+
292
+ Returns
293
+ -------
294
+ istriad : boolean
295
+ Whether G is a valid triad
296
+
297
+ Examples
298
+ --------
299
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
300
+ >>> nx.is_triad(G)
301
+ True
302
+ >>> G.add_edge(0, 1)
303
+ >>> nx.is_triad(G)
304
+ False
305
+ """
306
+ if isinstance(G, nx.Graph):
307
+ if G.order() == 3 and nx.is_directed(G):
308
+ if not any((n, n) in G.edges() for n in G.nodes()):
309
+ return True
310
+ return False
311
+
312
+
313
+ @not_implemented_for("undirected")
314
+ @nx._dispatchable
315
+ def all_triplets(G):
316
+ """Returns a generator of all possible sets of 3 nodes in a DiGraph.
317
+
318
+ .. deprecated:: 3.3
319
+
320
+ all_triplets is deprecated and will be removed in NetworkX version 3.5.
321
+ Use `itertools.combinations` instead::
322
+
323
+ all_triplets = itertools.combinations(G, 3)
324
+
325
+ Parameters
326
+ ----------
327
+ G : digraph
328
+ A NetworkX DiGraph
329
+
330
+ Returns
331
+ -------
332
+ triplets : generator of 3-tuples
333
+ Generator of tuples of 3 nodes
334
+
335
+ Examples
336
+ --------
337
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
338
+ >>> list(nx.all_triplets(G))
339
+ [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
340
+
341
+ """
342
+ import warnings
343
+
344
+ warnings.warn(
345
+ (
346
+ "\n\nall_triplets is deprecated and will be rmoved in v3.5.\n"
347
+ "Use `itertools.combinations(G, 3)` instead."
348
+ ),
349
+ category=DeprecationWarning,
350
+ stacklevel=4,
351
+ )
352
+ triplets = combinations(G.nodes(), 3)
353
+ return triplets
354
+
355
+
356
+ @not_implemented_for("undirected")
357
+ @nx._dispatchable(returns_graph=True)
358
+ def all_triads(G):
359
+ """A generator of all possible triads in G.
360
+
361
+ Parameters
362
+ ----------
363
+ G : digraph
364
+ A NetworkX DiGraph
365
+
366
+ Returns
367
+ -------
368
+ all_triads : generator of DiGraphs
369
+ Generator of triads (order-3 DiGraphs)
370
+
371
+ Examples
372
+ --------
373
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1), (3, 4), (4, 1), (4, 2)])
374
+ >>> for triad in nx.all_triads(G):
375
+ ... print(triad.edges)
376
+ [(1, 2), (2, 3), (3, 1)]
377
+ [(1, 2), (4, 1), (4, 2)]
378
+ [(3, 1), (3, 4), (4, 1)]
379
+ [(2, 3), (3, 4), (4, 2)]
380
+
381
+ """
382
+ triplets = combinations(G.nodes(), 3)
383
+ for triplet in triplets:
384
+ yield G.subgraph(triplet).copy()
385
+
386
+
387
+ @not_implemented_for("undirected")
388
+ @nx._dispatchable
389
+ def triads_by_type(G):
390
+ """Returns a list of all triads for each triad type in a directed graph.
391
+ There are exactly 16 different types of triads possible. Suppose 1, 2, 3 are three
392
+ nodes, they will be classified as a particular triad type if their connections
393
+ are as follows:
394
+
395
+ - 003: 1, 2, 3
396
+ - 012: 1 -> 2, 3
397
+ - 102: 1 <-> 2, 3
398
+ - 021D: 1 <- 2 -> 3
399
+ - 021U: 1 -> 2 <- 3
400
+ - 021C: 1 -> 2 -> 3
401
+ - 111D: 1 <-> 2 <- 3
402
+ - 111U: 1 <-> 2 -> 3
403
+ - 030T: 1 -> 2 -> 3, 1 -> 3
404
+ - 030C: 1 <- 2 <- 3, 1 -> 3
405
+ - 201: 1 <-> 2 <-> 3
406
+ - 120D: 1 <- 2 -> 3, 1 <-> 3
407
+ - 120U: 1 -> 2 <- 3, 1 <-> 3
408
+ - 120C: 1 -> 2 -> 3, 1 <-> 3
409
+ - 210: 1 -> 2 <-> 3, 1 <-> 3
410
+ - 300: 1 <-> 2 <-> 3, 1 <-> 3
411
+
412
+ Refer to the :doc:`example gallery </auto_examples/graph/plot_triad_types>`
413
+ for visual examples of the triad types.
414
+
415
+ Parameters
416
+ ----------
417
+ G : digraph
418
+ A NetworkX DiGraph
419
+
420
+ Returns
421
+ -------
422
+ tri_by_type : dict
423
+ Dictionary with triad types as keys and lists of triads as values.
424
+
425
+ Examples
426
+ --------
427
+ >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 1), (5, 6), (5, 4), (6, 7)])
428
+ >>> dict = nx.triads_by_type(G)
429
+ >>> dict["120C"][0].edges()
430
+ OutEdgeView([(1, 2), (1, 3), (2, 3), (3, 1)])
431
+ >>> dict["012"][0].edges()
432
+ OutEdgeView([(1, 2)])
433
+
434
+ References
435
+ ----------
436
+ .. [1] Snijders, T. (2012). "Transitivity and triads." University of
437
+ Oxford.
438
+ https://web.archive.org/web/20170830032057/http://www.stats.ox.ac.uk/~snijders/Trans_Triads_ha.pdf
439
+ """
440
+ # num_triads = o * (o - 1) * (o - 2) // 6
441
+ # if num_triads > TRIAD_LIMIT: print(WARNING)
442
+ all_tri = all_triads(G)
443
+ tri_by_type = defaultdict(list)
444
+ for triad in all_tri:
445
+ name = triad_type(triad)
446
+ tri_by_type[name].append(triad)
447
+ return tri_by_type
448
+
449
+
450
+ @not_implemented_for("undirected")
451
+ @nx._dispatchable
452
+ def triad_type(G):
453
+ """Returns the sociological triad type for a triad.
454
+
455
+ Parameters
456
+ ----------
457
+ G : digraph
458
+ A NetworkX DiGraph with 3 nodes
459
+
460
+ Returns
461
+ -------
462
+ triad_type : str
463
+ A string identifying the triad type
464
+
465
+ Examples
466
+ --------
467
+ >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
468
+ >>> nx.triad_type(G)
469
+ '030C'
470
+ >>> G.add_edge(1, 3)
471
+ >>> nx.triad_type(G)
472
+ '120C'
473
+
474
+ Notes
475
+ -----
476
+ There can be 6 unique edges in a triad (order-3 DiGraph) (so 2^^6=64 unique
477
+ triads given 3 nodes). These 64 triads each display exactly 1 of 16
478
+ topologies of triads (topologies can be permuted). These topologies are
479
+ identified by the following notation:
480
+
481
+ {m}{a}{n}{type} (for example: 111D, 210, 102)
482
+
483
+ Here:
484
+
485
+ {m} = number of mutual ties (takes 0, 1, 2, 3); a mutual tie is (0,1)
486
+ AND (1,0)
487
+ {a} = number of asymmetric ties (takes 0, 1, 2, 3); an asymmetric tie
488
+ is (0,1) BUT NOT (1,0) or vice versa
489
+ {n} = number of null ties (takes 0, 1, 2, 3); a null tie is NEITHER
490
+ (0,1) NOR (1,0)
491
+ {type} = a letter (takes U, D, C, T) corresponding to up, down, cyclical
492
+ and transitive. This is only used for topologies that can have
493
+ more than one form (eg: 021D and 021U).
494
+
495
+ References
496
+ ----------
497
+ .. [1] Snijders, T. (2012). "Transitivity and triads." University of
498
+ Oxford.
499
+ https://web.archive.org/web/20170830032057/http://www.stats.ox.ac.uk/~snijders/Trans_Triads_ha.pdf
500
+ """
501
+ if not is_triad(G):
502
+ raise nx.NetworkXAlgorithmError("G is not a triad (order-3 DiGraph)")
503
+ num_edges = len(G.edges())
504
+ if num_edges == 0:
505
+ return "003"
506
+ elif num_edges == 1:
507
+ return "012"
508
+ elif num_edges == 2:
509
+ e1, e2 = G.edges()
510
+ if set(e1) == set(e2):
511
+ return "102"
512
+ elif e1[0] == e2[0]:
513
+ return "021D"
514
+ elif e1[1] == e2[1]:
515
+ return "021U"
516
+ elif e1[1] == e2[0] or e2[1] == e1[0]:
517
+ return "021C"
518
+ elif num_edges == 3:
519
+ for e1, e2, e3 in permutations(G.edges(), 3):
520
+ if set(e1) == set(e2):
521
+ if e3[0] in e1:
522
+ return "111U"
523
+ # e3[1] in e1:
524
+ return "111D"
525
+ elif set(e1).symmetric_difference(set(e2)) == set(e3):
526
+ if {e1[0], e2[0], e3[0]} == {e1[0], e2[0], e3[0]} == set(G.nodes()):
527
+ return "030C"
528
+ # e3 == (e1[0], e2[1]) and e2 == (e1[1], e3[1]):
529
+ return "030T"
530
+ elif num_edges == 4:
531
+ for e1, e2, e3, e4 in permutations(G.edges(), 4):
532
+ if set(e1) == set(e2):
533
+ # identify pair of symmetric edges (which necessarily exists)
534
+ if set(e3) == set(e4):
535
+ return "201"
536
+ if {e3[0]} == {e4[0]} == set(e3).intersection(set(e4)):
537
+ return "120D"
538
+ if {e3[1]} == {e4[1]} == set(e3).intersection(set(e4)):
539
+ return "120U"
540
+ if e3[1] == e4[0]:
541
+ return "120C"
542
+ elif num_edges == 5:
543
+ return "210"
544
+ elif num_edges == 6:
545
+ return "300"
546
+
547
+
548
+ @not_implemented_for("undirected")
549
+ @py_random_state(1)
550
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
551
+ def random_triad(G, seed=None):
552
+ """Returns a random triad from a directed graph.
553
+
554
+ .. deprecated:: 3.3
555
+
556
+ random_triad is deprecated and will be removed in version 3.5.
557
+ Use random sampling directly instead::
558
+
559
+ G.subgraph(random.sample(list(G), 3))
560
+
561
+ Parameters
562
+ ----------
563
+ G : digraph
564
+ A NetworkX DiGraph
565
+ seed : integer, random_state, or None (default)
566
+ Indicator of random number generation state.
567
+ See :ref:`Randomness<randomness>`.
568
+
569
+ Returns
570
+ -------
571
+ G2 : subgraph
572
+ A randomly selected triad (order-3 NetworkX DiGraph)
573
+
574
+ Raises
575
+ ------
576
+ NetworkXError
577
+ If the input Graph has less than 3 nodes.
578
+
579
+ Examples
580
+ --------
581
+ >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 1), (5, 6), (5, 4), (6, 7)])
582
+ >>> triad = nx.random_triad(G, seed=1)
583
+ >>> triad.edges
584
+ OutEdgeView([(1, 2)])
585
+
586
+ """
587
+ import warnings
588
+
589
+ warnings.warn(
590
+ (
591
+ "\n\nrandom_triad is deprecated and will be removed in NetworkX v3.5.\n"
592
+ "Use random.sample instead, e.g.::\n\n"
593
+ "\tG.subgraph(random.sample(list(G), 3))\n"
594
+ ),
595
+ category=DeprecationWarning,
596
+ stacklevel=5,
597
+ )
598
+ if len(G) < 3:
599
+ raise nx.NetworkXError(
600
+ f"G needs at least 3 nodes to form a triad; (it has {len(G)} nodes)"
601
+ )
602
+ nodes = seed.sample(list(G.nodes()), 3)
603
+ G2 = G.subgraph(nodes)
604
+ return G2
env-llmeval/lib/python3.10/site-packages/networkx/algorithms/vitality.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vitality measures.
3
+ """
4
+ from functools import partial
5
+
6
+ import networkx as nx
7
+
8
+ __all__ = ["closeness_vitality"]
9
+
10
+
11
+ @nx._dispatchable(edge_attrs="weight")
12
+ def closeness_vitality(G, node=None, weight=None, wiener_index=None):
13
+ """Returns the closeness vitality for nodes in the graph.
14
+
15
+ The *closeness vitality* of a node, defined in Section 3.6.2 of [1],
16
+ is the change in the sum of distances between all node pairs when
17
+ excluding that node.
18
+
19
+ Parameters
20
+ ----------
21
+ G : NetworkX graph
22
+ A strongly-connected graph.
23
+
24
+ weight : string
25
+ The name of the edge attribute used as weight. This is passed
26
+ directly to the :func:`~networkx.wiener_index` function.
27
+
28
+ node : object
29
+ If specified, only the closeness vitality for this node will be
30
+ returned. Otherwise, a dictionary mapping each node to its
31
+ closeness vitality will be returned.
32
+
33
+ Other parameters
34
+ ----------------
35
+ wiener_index : number
36
+ If you have already computed the Wiener index of the graph
37
+ `G`, you can provide that value here. Otherwise, it will be
38
+ computed for you.
39
+
40
+ Returns
41
+ -------
42
+ dictionary or float
43
+ If `node` is None, this function returns a dictionary
44
+ with nodes as keys and closeness vitality as the
45
+ value. Otherwise, it returns only the closeness vitality for the
46
+ specified `node`.
47
+
48
+ The closeness vitality of a node may be negative infinity if
49
+ removing that node would disconnect the graph.
50
+
51
+ Examples
52
+ --------
53
+ >>> G = nx.cycle_graph(3)
54
+ >>> nx.closeness_vitality(G)
55
+ {0: 2.0, 1: 2.0, 2: 2.0}
56
+
57
+ See Also
58
+ --------
59
+ closeness_centrality
60
+
61
+ References
62
+ ----------
63
+ .. [1] Ulrik Brandes, Thomas Erlebach (eds.).
64
+ *Network Analysis: Methodological Foundations*.
65
+ Springer, 2005.
66
+ <http://books.google.com/books?id=TTNhSm7HYrIC>
67
+
68
+ """
69
+ if wiener_index is None:
70
+ wiener_index = nx.wiener_index(G, weight=weight)
71
+ if node is not None:
72
+ after = nx.wiener_index(G.subgraph(set(G) - {node}), weight=weight)
73
+ return wiener_index - after
74
+ vitality = partial(closeness_vitality, G, weight=weight, wiener_index=wiener_index)
75
+ # TODO This can be trivially parallelized.
76
+ return {v: vitality(node=v) for v in G}