ZTWHHH commited on
Commit
d7e679d
·
verified ·
1 Parent(s): 87e42a7

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. janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/boundary.cpython-310.pyc +0 -0
  2. janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/simple_paths.cpython-310.pyc +0 -0
  3. janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/sparsifiers.cpython-310.pyc +0 -0
  4. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/clique.py +259 -0
  5. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/connectivity.py +412 -0
  6. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-310.pyc +0 -0
  7. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-310.pyc +0 -0
  8. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-310.pyc +0 -0
  9. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-310.pyc +0 -0
  10. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py +41 -0
  11. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py +78 -0
  12. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py +94 -0
  13. janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py +68 -0
  14. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__init__.py +5 -0
  15. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-310.pyc +0 -0
  16. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-310.pyc +0 -0
  17. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-310.pyc +0 -0
  18. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/connectivity.py +122 -0
  19. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/correlation.py +302 -0
  20. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/mixing.py +255 -0
  21. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/neighbor_degree.py +160 -0
  22. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/pairs.py +127 -0
  23. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__init__.py +0 -0
  24. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  25. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/base_test.cpython-310.pyc +0 -0
  26. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_connectivity.cpython-310.pyc +0 -0
  27. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_correlation.cpython-310.pyc +0 -0
  28. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_mixing.cpython-310.pyc +0 -0
  29. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-310.pyc +0 -0
  30. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-310.pyc +0 -0
  31. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/base_test.py +81 -0
  32. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.py +143 -0
  33. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_correlation.py +123 -0
  34. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py +176 -0
  35. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py +108 -0
  36. janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_pairs.py +87 -0
  37. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__init__.py +4 -0
  38. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/greedy_coloring.py +565 -0
  39. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py +0 -0
  40. janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/test_coloring.cpython-310.pyc +0 -0
  41. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc +0 -0
  42. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-310.pyc +0 -0
  43. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-310.pyc +0 -0
  44. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-310.pyc +0 -0
  46. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-310.pyc +0 -0
  47. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-310.pyc +0 -0
  48. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-310.pyc +0 -0
  49. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc +0 -0
  50. janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-310.pyc +0 -0
janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/boundary.cpython-310.pyc ADDED
Binary file (5.36 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/simple_paths.cpython-310.pyc ADDED
Binary file (25.8 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/__pycache__/sparsifiers.cpython-310.pyc ADDED
Binary file (6.88 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/clique.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for computing large cliques and maximum independent sets."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import ramsey
5
+ from networkx.utils import not_implemented_for
6
+
7
+ __all__ = [
8
+ "clique_removal",
9
+ "max_clique",
10
+ "large_clique_size",
11
+ "maximum_independent_set",
12
+ ]
13
+
14
+
15
+ @not_implemented_for("directed")
16
+ @not_implemented_for("multigraph")
17
+ @nx._dispatchable
18
+ def maximum_independent_set(G):
19
+ """Returns an approximate maximum independent set.
20
+
21
+ Independent set or stable set is a set of vertices in a graph, no two of
22
+ which are adjacent. That is, it is a set I of vertices such that for every
23
+ two vertices in I, there is no edge connecting the two. Equivalently, each
24
+ edge in the graph has at most one endpoint in I. The size of an independent
25
+ set is the number of vertices it contains [1]_.
26
+
27
+ A maximum independent set is a largest independent set for a given graph G
28
+ and its size is denoted $\\alpha(G)$. The problem of finding such a set is called
29
+ the maximum independent set problem and is an NP-hard optimization problem.
30
+ As such, it is unlikely that there exists an efficient algorithm for finding
31
+ a maximum independent set of a graph.
32
+
33
+ The Independent Set algorithm is based on [2]_.
34
+
35
+ Parameters
36
+ ----------
37
+ G : NetworkX graph
38
+ Undirected graph
39
+
40
+ Returns
41
+ -------
42
+ iset : Set
43
+ The apx-maximum independent set
44
+
45
+ Examples
46
+ --------
47
+ >>> G = nx.path_graph(10)
48
+ >>> nx.approximation.maximum_independent_set(G)
49
+ {0, 2, 4, 6, 9}
50
+
51
+ Raises
52
+ ------
53
+ NetworkXNotImplemented
54
+ If the graph is directed or is a multigraph.
55
+
56
+ Notes
57
+ -----
58
+ Finds the $O(|V|/(log|V|)^2)$ apx of independent set in the worst case.
59
+
60
+ References
61
+ ----------
62
+ .. [1] `Wikipedia: Independent set
63
+ <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
64
+ .. [2] Boppana, R., & Halldórsson, M. M. (1992).
65
+ Approximating maximum independent sets by excluding subgraphs.
66
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
67
+ """
68
+ iset, _ = clique_removal(G)
69
+ return iset
70
+
71
+
72
+ @not_implemented_for("directed")
73
+ @not_implemented_for("multigraph")
74
+ @nx._dispatchable
75
+ def max_clique(G):
76
+ r"""Find the Maximum Clique
77
+
78
+ Finds the $O(|V|/(log|V|)^2)$ apx of maximum clique/independent set
79
+ in the worst case.
80
+
81
+ Parameters
82
+ ----------
83
+ G : NetworkX graph
84
+ Undirected graph
85
+
86
+ Returns
87
+ -------
88
+ clique : set
89
+ The apx-maximum clique of the graph
90
+
91
+ Examples
92
+ --------
93
+ >>> G = nx.path_graph(10)
94
+ >>> nx.approximation.max_clique(G)
95
+ {8, 9}
96
+
97
+ Raises
98
+ ------
99
+ NetworkXNotImplemented
100
+ If the graph is directed or is a multigraph.
101
+
102
+ Notes
103
+ -----
104
+ A clique in an undirected graph G = (V, E) is a subset of the vertex set
105
+ `C \subseteq V` such that for every two vertices in C there exists an edge
106
+ connecting the two. This is equivalent to saying that the subgraph
107
+ induced by C is complete (in some cases, the term clique may also refer
108
+ to the subgraph).
109
+
110
+ A maximum clique is a clique of the largest possible size in a given graph.
111
+ The clique number `\omega(G)` of a graph G is the number of
112
+ vertices in a maximum clique in G. The intersection number of
113
+ G is the smallest number of cliques that together cover all edges of G.
114
+
115
+ https://en.wikipedia.org/wiki/Maximum_clique
116
+
117
+ References
118
+ ----------
119
+ .. [1] Boppana, R., & Halldórsson, M. M. (1992).
120
+ Approximating maximum independent sets by excluding subgraphs.
121
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
122
+ doi:10.1007/BF01994876
123
+ """
124
+ # finding the maximum clique in a graph is equivalent to finding
125
+ # the independent set in the complementary graph
126
+ cgraph = nx.complement(G)
127
+ iset, _ = clique_removal(cgraph)
128
+ return iset
129
+
130
+
131
+ @not_implemented_for("directed")
132
+ @not_implemented_for("multigraph")
133
+ @nx._dispatchable
134
+ def clique_removal(G):
135
+ r"""Repeatedly remove cliques from the graph.
136
+
137
+ Results in a $O(|V|/(\log |V|)^2)$ approximation of maximum clique
138
+ and independent set. Returns the largest independent set found, along
139
+ with found maximal cliques.
140
+
141
+ Parameters
142
+ ----------
143
+ G : NetworkX graph
144
+ Undirected graph
145
+
146
+ Returns
147
+ -------
148
+ max_ind_cliques : (set, list) tuple
149
+ 2-tuple of Maximal Independent Set and list of maximal cliques (sets).
150
+
151
+ Examples
152
+ --------
153
+ >>> G = nx.path_graph(10)
154
+ >>> nx.approximation.clique_removal(G)
155
+ ({0, 2, 4, 6, 9}, [{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}])
156
+
157
+ Raises
158
+ ------
159
+ NetworkXNotImplemented
160
+ If the graph is directed or is a multigraph.
161
+
162
+ References
163
+ ----------
164
+ .. [1] Boppana, R., & Halldórsson, M. M. (1992).
165
+ Approximating maximum independent sets by excluding subgraphs.
166
+ BIT Numerical Mathematics, 32(2), 180–196. Springer.
167
+ """
168
+ graph = G.copy()
169
+ c_i, i_i = ramsey.ramsey_R2(graph)
170
+ cliques = [c_i]
171
+ isets = [i_i]
172
+ while graph:
173
+ graph.remove_nodes_from(c_i)
174
+ c_i, i_i = ramsey.ramsey_R2(graph)
175
+ if c_i:
176
+ cliques.append(c_i)
177
+ if i_i:
178
+ isets.append(i_i)
179
+ # Determine the largest independent set as measured by cardinality.
180
+ maxiset = max(isets, key=len)
181
+ return maxiset, cliques
182
+
183
+
184
+ @not_implemented_for("directed")
185
+ @not_implemented_for("multigraph")
186
+ @nx._dispatchable
187
+ def large_clique_size(G):
188
+ """Find the size of a large clique in a graph.
189
+
190
+ A *clique* is a subset of nodes in which each pair of nodes is
191
+ adjacent. This function is a heuristic for finding the size of a
192
+ large clique in the graph.
193
+
194
+ Parameters
195
+ ----------
196
+ G : NetworkX graph
197
+
198
+ Returns
199
+ -------
200
+ k: integer
201
+ The size of a large clique in the graph.
202
+
203
+ Examples
204
+ --------
205
+ >>> G = nx.path_graph(10)
206
+ >>> nx.approximation.large_clique_size(G)
207
+ 2
208
+
209
+ Raises
210
+ ------
211
+ NetworkXNotImplemented
212
+ If the graph is directed or is a multigraph.
213
+
214
+ Notes
215
+ -----
216
+ This implementation is from [1]_. Its worst case time complexity is
217
+ :math:`O(n d^2)`, where *n* is the number of nodes in the graph and
218
+ *d* is the maximum degree.
219
+
220
+ This function is a heuristic, which means it may work well in
221
+ practice, but there is no rigorous mathematical guarantee on the
222
+ ratio between the returned number and the actual largest clique size
223
+ in the graph.
224
+
225
+ References
226
+ ----------
227
+ .. [1] Pattabiraman, Bharath, et al.
228
+ "Fast Algorithms for the Maximum Clique Problem on Massive Graphs
229
+ with Applications to Overlapping Community Detection."
230
+ *Internet Mathematics* 11.4-5 (2015): 421--448.
231
+ <https://doi.org/10.1080/15427951.2014.986778>
232
+
233
+ See also
234
+ --------
235
+
236
+ :func:`networkx.algorithms.approximation.clique.max_clique`
237
+ A function that returns an approximate maximum clique with a
238
+ guarantee on the approximation ratio.
239
+
240
+ :mod:`networkx.algorithms.clique`
241
+ Functions for finding the exact maximum clique in a graph.
242
+
243
+ """
244
+ degrees = G.degree
245
+
246
+ def _clique_heuristic(G, U, size, best_size):
247
+ if not U:
248
+ return max(best_size, size)
249
+ u = max(U, key=degrees)
250
+ U.remove(u)
251
+ N_prime = {v for v in G[u] if degrees[v] >= best_size}
252
+ return _clique_heuristic(G, U & N_prime, size + 1, best_size)
253
+
254
+ best_size = 0
255
+ nodes = (u for u in G if degrees[u] >= best_size)
256
+ for u in nodes:
257
+ neighbors = {v for v in G[u] if degrees[v] >= best_size}
258
+ best_size = _clique_heuristic(G, neighbors, 1, best_size)
259
+ return best_size
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/connectivity.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast approximation for node connectivity"""
2
+
3
+ import itertools
4
+ from operator import itemgetter
5
+
6
+ import networkx as nx
7
+
8
+ __all__ = [
9
+ "local_node_connectivity",
10
+ "node_connectivity",
11
+ "all_pairs_node_connectivity",
12
+ ]
13
+
14
+
15
+ @nx._dispatchable(name="approximate_local_node_connectivity")
16
+ def local_node_connectivity(G, source, target, cutoff=None):
17
+ """Compute node connectivity between source and target.
18
+
19
+ Pairwise or local node connectivity between two distinct and nonadjacent
20
+ nodes is the minimum number of nodes that must be removed (minimum
21
+ separating cutset) to disconnect them. By Menger's theorem, this is equal
22
+ to the number of node independent paths (paths that share no nodes other
23
+ than source and target). Which is what we compute in this function.
24
+
25
+ This algorithm is a fast approximation that gives an strict lower
26
+ bound on the actual number of node independent paths between two nodes [1]_.
27
+ It works for both directed and undirected graphs.
28
+
29
+ Parameters
30
+ ----------
31
+
32
+ G : NetworkX graph
33
+
34
+ source : node
35
+ Starting node for node connectivity
36
+
37
+ target : node
38
+ Ending node for node connectivity
39
+
40
+ cutoff : integer
41
+ Maximum node connectivity to consider. If None, the minimum degree
42
+ of source or target is used as a cutoff. Default value None.
43
+
44
+ Returns
45
+ -------
46
+ k: integer
47
+ pairwise node connectivity
48
+
49
+ Examples
50
+ --------
51
+ >>> # Platonic octahedral graph has node connectivity 4
52
+ >>> # for each non adjacent node pair
53
+ >>> from networkx.algorithms import approximation as approx
54
+ >>> G = nx.octahedral_graph()
55
+ >>> approx.local_node_connectivity(G, 0, 5)
56
+ 4
57
+
58
+ Notes
59
+ -----
60
+ This algorithm [1]_ finds node independents paths between two nodes by
61
+ computing their shortest path using BFS, marking the nodes of the path
62
+ found as 'used' and then searching other shortest paths excluding the
63
+ nodes marked as used until no more paths exist. It is not exact because
64
+ a shortest path could use nodes that, if the path were longer, may belong
65
+ to two different node independent paths. Thus it only guarantees an
66
+ strict lower bound on node connectivity.
67
+
68
+ Note that the authors propose a further refinement, losing accuracy and
69
+ gaining speed, which is not implemented yet.
70
+
71
+ See also
72
+ --------
73
+ all_pairs_node_connectivity
74
+ node_connectivity
75
+
76
+ References
77
+ ----------
78
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
79
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
80
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
81
+
82
+ """
83
+ if target == source:
84
+ raise nx.NetworkXError("source and target have to be different nodes.")
85
+
86
+ # Maximum possible node independent paths
87
+ if G.is_directed():
88
+ possible = min(G.out_degree(source), G.in_degree(target))
89
+ else:
90
+ possible = min(G.degree(source), G.degree(target))
91
+
92
+ K = 0
93
+ if not possible:
94
+ return K
95
+
96
+ if cutoff is None:
97
+ cutoff = float("inf")
98
+
99
+ exclude = set()
100
+ for i in range(min(possible, cutoff)):
101
+ try:
102
+ path = _bidirectional_shortest_path(G, source, target, exclude)
103
+ exclude.update(set(path))
104
+ K += 1
105
+ except nx.NetworkXNoPath:
106
+ break
107
+
108
+ return K
109
+
110
+
111
+ @nx._dispatchable(name="approximate_node_connectivity")
112
+ def node_connectivity(G, s=None, t=None):
113
+ r"""Returns an approximation for node connectivity for a graph or digraph G.
114
+
115
+ Node connectivity is equal to the minimum number of nodes that
116
+ must be removed to disconnect G or render it trivial. By Menger's theorem,
117
+ this is equal to the number of node independent paths (paths that
118
+ share no nodes other than source and target).
119
+
120
+ If source and target nodes are provided, this function returns the
121
+ local node connectivity: the minimum number of nodes that must be
122
+ removed to break all paths from source to target in G.
123
+
124
+ This algorithm is based on a fast approximation that gives an strict lower
125
+ bound on the actual number of node independent paths between two nodes [1]_.
126
+ It works for both directed and undirected graphs.
127
+
128
+ Parameters
129
+ ----------
130
+ G : NetworkX graph
131
+ Undirected graph
132
+
133
+ s : node
134
+ Source node. Optional. Default value: None.
135
+
136
+ t : node
137
+ Target node. Optional. Default value: None.
138
+
139
+ Returns
140
+ -------
141
+ K : integer
142
+ Node connectivity of G, or local node connectivity if source
143
+ and target are provided.
144
+
145
+ Examples
146
+ --------
147
+ >>> # Platonic octahedral graph is 4-node-connected
148
+ >>> from networkx.algorithms import approximation as approx
149
+ >>> G = nx.octahedral_graph()
150
+ >>> approx.node_connectivity(G)
151
+ 4
152
+
153
+ Notes
154
+ -----
155
+ This algorithm [1]_ finds node independents paths between two nodes by
156
+ computing their shortest path using BFS, marking the nodes of the path
157
+ found as 'used' and then searching other shortest paths excluding the
158
+ nodes marked as used until no more paths exist. It is not exact because
159
+ a shortest path could use nodes that, if the path were longer, may belong
160
+ to two different node independent paths. Thus it only guarantees an
161
+ strict lower bound on node connectivity.
162
+
163
+ See also
164
+ --------
165
+ all_pairs_node_connectivity
166
+ local_node_connectivity
167
+
168
+ References
169
+ ----------
170
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
171
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
172
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
173
+
174
+ """
175
+ if (s is not None and t is None) or (s is None and t is not None):
176
+ raise nx.NetworkXError("Both source and target must be specified.")
177
+
178
+ # Local node connectivity
179
+ if s is not None and t is not None:
180
+ if s not in G:
181
+ raise nx.NetworkXError(f"node {s} not in graph")
182
+ if t not in G:
183
+ raise nx.NetworkXError(f"node {t} not in graph")
184
+ return local_node_connectivity(G, s, t)
185
+
186
+ # Global node connectivity
187
+ if G.is_directed():
188
+ connected_func = nx.is_weakly_connected
189
+ iter_func = itertools.permutations
190
+
191
+ def neighbors(v):
192
+ return itertools.chain(G.predecessors(v), G.successors(v))
193
+
194
+ else:
195
+ connected_func = nx.is_connected
196
+ iter_func = itertools.combinations
197
+ neighbors = G.neighbors
198
+
199
+ if not connected_func(G):
200
+ return 0
201
+
202
+ # Choose a node with minimum degree
203
+ v, minimum_degree = min(G.degree(), key=itemgetter(1))
204
+ # Node connectivity is bounded by minimum degree
205
+ K = minimum_degree
206
+ # compute local node connectivity with all non-neighbors nodes
207
+ # and store the minimum
208
+ for w in set(G) - set(neighbors(v)) - {v}:
209
+ K = min(K, local_node_connectivity(G, v, w, cutoff=K))
210
+ # Same for non adjacent pairs of neighbors of v
211
+ for x, y in iter_func(neighbors(v), 2):
212
+ if y not in G[x] and x != y:
213
+ K = min(K, local_node_connectivity(G, x, y, cutoff=K))
214
+ return K
215
+
216
+
217
+ @nx._dispatchable(name="approximate_all_pairs_node_connectivity")
218
+ def all_pairs_node_connectivity(G, nbunch=None, cutoff=None):
219
+ """Compute node connectivity between all pairs of nodes.
220
+
221
+ Pairwise or local node connectivity between two distinct and nonadjacent
222
+ nodes is the minimum number of nodes that must be removed (minimum
223
+ separating cutset) to disconnect them. By Menger's theorem, this is equal
224
+ to the number of node independent paths (paths that share no nodes other
225
+ than source and target). Which is what we compute in this function.
226
+
227
+ This algorithm is a fast approximation that gives an strict lower
228
+ bound on the actual number of node independent paths between two nodes [1]_.
229
+ It works for both directed and undirected graphs.
230
+
231
+
232
+ Parameters
233
+ ----------
234
+ G : NetworkX graph
235
+
236
+ nbunch: container
237
+ Container of nodes. If provided node connectivity will be computed
238
+ only over pairs of nodes in nbunch.
239
+
240
+ cutoff : integer
241
+ Maximum node connectivity to consider. If None, the minimum degree
242
+ of source or target is used as a cutoff in each pair of nodes.
243
+ Default value None.
244
+
245
+ Returns
246
+ -------
247
+ K : dictionary
248
+ Dictionary, keyed by source and target, of pairwise node connectivity
249
+
250
+ Examples
251
+ --------
252
+ A 3 node cycle with one extra node attached has connectivity 2 between all
253
+ nodes in the cycle and connectivity 1 between the extra node and the rest:
254
+
255
+ >>> G = nx.cycle_graph(3)
256
+ >>> G.add_edge(2, 3)
257
+ >>> import pprint # for nice dictionary formatting
258
+ >>> pprint.pprint(nx.all_pairs_node_connectivity(G))
259
+ {0: {1: 2, 2: 2, 3: 1},
260
+ 1: {0: 2, 2: 2, 3: 1},
261
+ 2: {0: 2, 1: 2, 3: 1},
262
+ 3: {0: 1, 1: 1, 2: 1}}
263
+
264
+ See Also
265
+ --------
266
+ local_node_connectivity
267
+ node_connectivity
268
+
269
+ References
270
+ ----------
271
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
272
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
273
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
274
+ """
275
+ if nbunch is None:
276
+ nbunch = G
277
+ else:
278
+ nbunch = set(nbunch)
279
+
280
+ directed = G.is_directed()
281
+ if directed:
282
+ iter_func = itertools.permutations
283
+ else:
284
+ iter_func = itertools.combinations
285
+
286
+ all_pairs = {n: {} for n in nbunch}
287
+
288
+ for u, v in iter_func(nbunch, 2):
289
+ k = local_node_connectivity(G, u, v, cutoff=cutoff)
290
+ all_pairs[u][v] = k
291
+ if not directed:
292
+ all_pairs[v][u] = k
293
+
294
+ return all_pairs
295
+
296
+
297
+ def _bidirectional_shortest_path(G, source, target, exclude):
298
+ """Returns shortest path between source and target ignoring nodes in the
299
+ container 'exclude'.
300
+
301
+ Parameters
302
+ ----------
303
+
304
+ G : NetworkX graph
305
+
306
+ source : node
307
+ Starting node for path
308
+
309
+ target : node
310
+ Ending node for path
311
+
312
+ exclude: container
313
+ Container for nodes to exclude from the search for shortest paths
314
+
315
+ Returns
316
+ -------
317
+ path: list
318
+ Shortest path between source and target ignoring nodes in 'exclude'
319
+
320
+ Raises
321
+ ------
322
+ NetworkXNoPath
323
+ If there is no path or if nodes are adjacent and have only one path
324
+ between them
325
+
326
+ Notes
327
+ -----
328
+ This function and its helper are originally from
329
+ networkx.algorithms.shortest_paths.unweighted and are modified to
330
+ accept the extra parameter 'exclude', which is a container for nodes
331
+ already used in other paths that should be ignored.
332
+
333
+ References
334
+ ----------
335
+ .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for
336
+ Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
337
+ http://eclectic.ss.uci.edu/~drwhite/working.pdf
338
+
339
+ """
340
+ # call helper to do the real work
341
+ results = _bidirectional_pred_succ(G, source, target, exclude)
342
+ pred, succ, w = results
343
+
344
+ # build path from pred+w+succ
345
+ path = []
346
+ # from source to w
347
+ while w is not None:
348
+ path.append(w)
349
+ w = pred[w]
350
+ path.reverse()
351
+ # from w to target
352
+ w = succ[path[-1]]
353
+ while w is not None:
354
+ path.append(w)
355
+ w = succ[w]
356
+
357
+ return path
358
+
359
+
360
+ def _bidirectional_pred_succ(G, source, target, exclude):
361
+ # does BFS from both source and target and meets in the middle
362
+ # excludes nodes in the container "exclude" from the search
363
+
364
+ # handle either directed or undirected
365
+ if G.is_directed():
366
+ Gpred = G.predecessors
367
+ Gsucc = G.successors
368
+ else:
369
+ Gpred = G.neighbors
370
+ Gsucc = G.neighbors
371
+
372
+ # predecessor and successors in search
373
+ pred = {source: None}
374
+ succ = {target: None}
375
+
376
+ # initialize fringes, start with forward
377
+ forward_fringe = [source]
378
+ reverse_fringe = [target]
379
+
380
+ level = 0
381
+
382
+ while forward_fringe and reverse_fringe:
383
+ # Make sure that we iterate one step forward and one step backwards
384
+ # thus source and target will only trigger "found path" when they are
385
+ # adjacent and then they can be safely included in the container 'exclude'
386
+ level += 1
387
+ if level % 2 != 0:
388
+ this_level = forward_fringe
389
+ forward_fringe = []
390
+ for v in this_level:
391
+ for w in Gsucc(v):
392
+ if w in exclude:
393
+ continue
394
+ if w not in pred:
395
+ forward_fringe.append(w)
396
+ pred[w] = v
397
+ if w in succ:
398
+ return pred, succ, w # found path
399
+ else:
400
+ this_level = reverse_fringe
401
+ reverse_fringe = []
402
+ for v in this_level:
403
+ for w in Gpred(v):
404
+ if w in exclude:
405
+ continue
406
+ if w not in succ:
407
+ succ[w] = v
408
+ reverse_fringe.append(w)
409
+ if w in pred:
410
+ return pred, succ, w # found path
411
+
412
+ raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_approx_clust_coeff.cpython-310.pyc ADDED
Binary file (1.39 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_kcomponents.cpython-310.pyc ADDED
Binary file (9.62 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_maxcut.cpython-310.pyc ADDED
Binary file (3.02 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/__pycache__/test_steinertree.cpython-310.pyc ADDED
Binary file (8.18 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import average_clustering
3
+
4
+ # This approximation has to be exact in regular graphs
5
+ # with no triangles or with all possible triangles.
6
+
7
+
8
+ def test_petersen():
9
+ # Actual coefficient is 0
10
+ G = nx.petersen_graph()
11
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
12
+
13
+
14
+ def test_petersen_seed():
15
+ # Actual coefficient is 0
16
+ G = nx.petersen_graph()
17
+ assert average_clustering(G, trials=len(G) // 2, seed=1) == nx.average_clustering(G)
18
+
19
+
20
+ def test_tetrahedral():
21
+ # Actual coefficient is 1
22
+ G = nx.tetrahedral_graph()
23
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
24
+
25
+
26
+ def test_dodecahedral():
27
+ # Actual coefficient is 0
28
+ G = nx.dodecahedral_graph()
29
+ assert average_clustering(G, trials=len(G) // 2) == nx.average_clustering(G)
30
+
31
+
32
+ def test_empty():
33
+ G = nx.empty_graph(5)
34
+ assert average_clustering(G, trials=len(G) // 2) == 0
35
+
36
+
37
+ def test_complete():
38
+ G = nx.complete_graph(5)
39
+ assert average_clustering(G, trials=len(G) // 2) == 1
40
+ G = nx.complete_graph(7)
41
+ assert average_clustering(G, trials=len(G) // 2) == 1
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_dominating_set.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.approximation import (
5
+ min_edge_dominating_set,
6
+ min_weighted_dominating_set,
7
+ )
8
+
9
+
10
+ class TestMinWeightDominatingSet:
11
+ def test_min_weighted_dominating_set(self):
12
+ graph = nx.Graph()
13
+ graph.add_edge(1, 2)
14
+ graph.add_edge(1, 5)
15
+ graph.add_edge(2, 3)
16
+ graph.add_edge(2, 5)
17
+ graph.add_edge(3, 4)
18
+ graph.add_edge(3, 6)
19
+ graph.add_edge(5, 6)
20
+
21
+ vertices = {1, 2, 3, 4, 5, 6}
22
+ # due to ties, this might be hard to test tight bounds
23
+ dom_set = min_weighted_dominating_set(graph)
24
+ for vertex in vertices - dom_set:
25
+ neighbors = set(graph.neighbors(vertex))
26
+ assert len(neighbors & dom_set) > 0, "Non dominating set found!"
27
+
28
+ def test_star_graph(self):
29
+ """Tests that an approximate dominating set for the star graph,
30
+ even when the center node does not have the smallest integer
31
+ label, gives just the center node.
32
+
33
+ For more information, see #1527.
34
+
35
+ """
36
+ # Create a star graph in which the center node has the highest
37
+ # label instead of the lowest.
38
+ G = nx.star_graph(10)
39
+ G = nx.relabel_nodes(G, {0: 9, 9: 0})
40
+ assert min_weighted_dominating_set(G) == {9}
41
+
42
+ def test_null_graph(self):
43
+ """Tests that the unique dominating set for the null graph is an empty set"""
44
+ G = nx.Graph()
45
+ assert min_weighted_dominating_set(G) == set()
46
+
47
+ def test_min_edge_dominating_set(self):
48
+ graph = nx.path_graph(5)
49
+ dom_set = min_edge_dominating_set(graph)
50
+
51
+ # this is a crappy way to test, but good enough for now.
52
+ for edge in graph.edges():
53
+ if edge in dom_set:
54
+ continue
55
+ else:
56
+ u, v = edge
57
+ found = False
58
+ for dom_edge in dom_set:
59
+ found |= u == dom_edge[0] or u == dom_edge[1]
60
+ assert found, "Non adjacent edge found!"
61
+
62
+ graph = nx.complete_graph(10)
63
+ dom_set = min_edge_dominating_set(graph)
64
+
65
+ # this is a crappy way to test, but good enough for now.
66
+ for edge in graph.edges():
67
+ if edge in dom_set:
68
+ continue
69
+ else:
70
+ u, v = edge
71
+ found = False
72
+ for dom_edge in dom_set:
73
+ found |= u == dom_edge[0] or u == dom_edge[1]
74
+ assert found, "Non adjacent edge found!"
75
+
76
+ graph = nx.Graph() # empty Networkx graph
77
+ with pytest.raises(ValueError, match="Expected non-empty NetworkX graph!"):
78
+ min_edge_dominating_set(graph)
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_maxcut.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.approximation import maxcut
7
+
8
+
9
+ @pytest.mark.parametrize(
10
+ "f", (nx.approximation.randomized_partitioning, nx.approximation.one_exchange)
11
+ )
12
+ @pytest.mark.parametrize("graph_constructor", (nx.DiGraph, nx.MultiGraph))
13
+ def test_raises_on_directed_and_multigraphs(f, graph_constructor):
14
+ G = graph_constructor([(0, 1), (1, 2)])
15
+ with pytest.raises(nx.NetworkXNotImplemented):
16
+ f(G)
17
+
18
+
19
+ def _is_valid_cut(G, set1, set2):
20
+ union = set1.union(set2)
21
+ assert union == set(G.nodes)
22
+ assert len(set1) + len(set2) == G.number_of_nodes()
23
+
24
+
25
+ def _cut_is_locally_optimal(G, cut_size, set1):
26
+ # test if cut can be locally improved
27
+ for i, node in enumerate(set1):
28
+ cut_size_without_node = nx.algorithms.cut_size(
29
+ G, set1 - {node}, weight="weight"
30
+ )
31
+ assert cut_size_without_node <= cut_size
32
+
33
+
34
+ def test_random_partitioning():
35
+ G = nx.complete_graph(5)
36
+ _, (set1, set2) = maxcut.randomized_partitioning(G, seed=5)
37
+ _is_valid_cut(G, set1, set2)
38
+
39
+
40
+ def test_random_partitioning_all_to_one():
41
+ G = nx.complete_graph(5)
42
+ _, (set1, set2) = maxcut.randomized_partitioning(G, p=1)
43
+ _is_valid_cut(G, set1, set2)
44
+ assert len(set1) == G.number_of_nodes()
45
+ assert len(set2) == 0
46
+
47
+
48
+ def test_one_exchange_basic():
49
+ G = nx.complete_graph(5)
50
+ random.seed(5)
51
+ for u, v, w in G.edges(data=True):
52
+ w["weight"] = random.randrange(-100, 100, 1) / 10
53
+
54
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
55
+ cut_size, (set1, set2) = maxcut.one_exchange(
56
+ G, initial_cut, weight="weight", seed=5
57
+ )
58
+
59
+ _is_valid_cut(G, set1, set2)
60
+ _cut_is_locally_optimal(G, cut_size, set1)
61
+
62
+
63
+ def test_one_exchange_optimal():
64
+ # Greedy one exchange should find the optimal solution for this graph (14)
65
+ G = nx.Graph()
66
+ G.add_edge(1, 2, weight=3)
67
+ G.add_edge(1, 3, weight=3)
68
+ G.add_edge(1, 4, weight=3)
69
+ G.add_edge(1, 5, weight=3)
70
+ G.add_edge(2, 3, weight=5)
71
+
72
+ cut_size, (set1, set2) = maxcut.one_exchange(G, weight="weight", seed=5)
73
+
74
+ _is_valid_cut(G, set1, set2)
75
+ _cut_is_locally_optimal(G, cut_size, set1)
76
+ # check global optimality
77
+ assert cut_size == 14
78
+
79
+
80
+ def test_negative_weights():
81
+ G = nx.complete_graph(5)
82
+ random.seed(5)
83
+ for u, v, w in G.edges(data=True):
84
+ w["weight"] = -1 * random.random()
85
+
86
+ initial_cut = set(random.sample(sorted(G.nodes()), k=5))
87
+ cut_size, (set1, set2) = maxcut.one_exchange(G, initial_cut, weight="weight")
88
+
89
+ # make sure it is a valid cut
90
+ _is_valid_cut(G, set1, set2)
91
+ # check local optimality
92
+ _cut_is_locally_optimal(G, cut_size, set1)
93
+ # test that all nodes are in the same partition
94
+ assert len(set1) == len(G.nodes) or len(set2) == len(G.nodes)
janus/lib/python3.10/site-packages/networkx/algorithms/approximation/tests/test_vertex_cover.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ from networkx.algorithms.approximation import min_weighted_vertex_cover
3
+
4
+
5
+ def is_cover(G, node_cover):
6
+ return all({u, v} & node_cover for u, v in G.edges())
7
+
8
+
9
+ class TestMWVC:
10
+ """Unit tests for the approximate minimum weighted vertex cover
11
+ function,
12
+ :func:`~networkx.algorithms.approximation.vertex_cover.min_weighted_vertex_cover`.
13
+
14
+ """
15
+
16
+ def test_unweighted_directed(self):
17
+ # Create a star graph in which half the nodes are directed in
18
+ # and half are directed out.
19
+ G = nx.DiGraph()
20
+ G.add_edges_from((0, v) for v in range(1, 26))
21
+ G.add_edges_from((v, 0) for v in range(26, 51))
22
+ cover = min_weighted_vertex_cover(G)
23
+ assert 1 == len(cover)
24
+ assert is_cover(G, cover)
25
+
26
+ def test_unweighted_undirected(self):
27
+ # create a simple star graph
28
+ size = 50
29
+ sg = nx.star_graph(size)
30
+ cover = min_weighted_vertex_cover(sg)
31
+ assert 1 == len(cover)
32
+ assert is_cover(sg, cover)
33
+
34
+ def test_weighted(self):
35
+ wg = nx.Graph()
36
+ wg.add_node(0, weight=10)
37
+ wg.add_node(1, weight=1)
38
+ wg.add_node(2, weight=1)
39
+ wg.add_node(3, weight=1)
40
+ wg.add_node(4, weight=1)
41
+
42
+ wg.add_edge(0, 1)
43
+ wg.add_edge(0, 2)
44
+ wg.add_edge(0, 3)
45
+ wg.add_edge(0, 4)
46
+
47
+ wg.add_edge(1, 2)
48
+ wg.add_edge(2, 3)
49
+ wg.add_edge(3, 4)
50
+ wg.add_edge(4, 1)
51
+
52
+ cover = min_weighted_vertex_cover(wg, weight="weight")
53
+ csum = sum(wg.nodes[node]["weight"] for node in cover)
54
+ assert 4 == csum
55
+ assert is_cover(wg, cover)
56
+
57
+ def test_unweighted_self_loop(self):
58
+ slg = nx.Graph()
59
+ slg.add_node(0)
60
+ slg.add_node(1)
61
+ slg.add_node(2)
62
+
63
+ slg.add_edge(0, 1)
64
+ slg.add_edge(2, 2)
65
+
66
+ cover = min_weighted_vertex_cover(slg)
67
+ assert 2 == len(cover)
68
+ assert is_cover(slg, cover)
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from networkx.algorithms.assortativity.connectivity import *
2
+ from networkx.algorithms.assortativity.correlation import *
3
+ from networkx.algorithms.assortativity.mixing import *
4
+ from networkx.algorithms.assortativity.neighbor_degree import *
5
+ from networkx.algorithms.assortativity.pairs import *
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/connectivity.cpython-310.pyc ADDED
Binary file (4.02 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/correlation.cpython-310.pyc ADDED
Binary file (9.26 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/__pycache__/mixing.cpython-310.pyc ADDED
Binary file (7.59 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/connectivity.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["average_degree_connectivity"]
6
+
7
+
8
+ @nx._dispatchable(edge_attrs="weight")
9
+ def average_degree_connectivity(
10
+ G, source="in+out", target="in+out", nodes=None, weight=None
11
+ ):
12
+ r"""Compute the average degree connectivity of graph.
13
+
14
+ The average degree connectivity is the average nearest neighbor degree of
15
+ nodes with degree k. For weighted graphs, an analogous measure can
16
+ be computed using the weighted average neighbors degree defined in
17
+ [1]_, for a node `i`, as
18
+
19
+ .. math::
20
+
21
+ k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
22
+
23
+ where `s_i` is the weighted degree of node `i`,
24
+ `w_{ij}` is the weight of the edge that links `i` and `j`,
25
+ and `N(i)` are the neighbors of node `i`.
26
+
27
+ Parameters
28
+ ----------
29
+ G : NetworkX graph
30
+
31
+ source : "in"|"out"|"in+out" (default:"in+out")
32
+ Directed graphs only. Use "in"- or "out"-degree for source node.
33
+
34
+ target : "in"|"out"|"in+out" (default:"in+out"
35
+ Directed graphs only. Use "in"- or "out"-degree for target node.
36
+
37
+ nodes : list or iterable (optional)
38
+ Compute neighbor connectivity for these nodes. The default is all
39
+ nodes.
40
+
41
+ weight : string or None, optional (default=None)
42
+ The edge attribute that holds the numerical value used as a weight.
43
+ If None, then each edge has weight 1.
44
+
45
+ Returns
46
+ -------
47
+ d : dict
48
+ A dictionary keyed by degree k with the value of average connectivity.
49
+
50
+ Raises
51
+ ------
52
+ NetworkXError
53
+ If either `source` or `target` are not one of 'in',
54
+ 'out', or 'in+out'.
55
+ If either `source` or `target` is passed for an undirected graph.
56
+
57
+ Examples
58
+ --------
59
+ >>> G = nx.path_graph(4)
60
+ >>> G.edges[1, 2]["weight"] = 3
61
+ >>> nx.average_degree_connectivity(G)
62
+ {1: 2.0, 2: 1.5}
63
+ >>> nx.average_degree_connectivity(G, weight="weight")
64
+ {1: 2.0, 2: 1.75}
65
+
66
+ See Also
67
+ --------
68
+ average_neighbor_degree
69
+
70
+ References
71
+ ----------
72
+ .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
73
+ "The architecture of complex weighted networks".
74
+ PNAS 101 (11): 3747–3752 (2004).
75
+ """
76
+ # First, determine the type of neighbors and the type of degree to use.
77
+ if G.is_directed():
78
+ if source not in ("in", "out", "in+out"):
79
+ raise nx.NetworkXError('source must be one of "in", "out", or "in+out"')
80
+ if target not in ("in", "out", "in+out"):
81
+ raise nx.NetworkXError('target must be one of "in", "out", or "in+out"')
82
+ direction = {"out": G.out_degree, "in": G.in_degree, "in+out": G.degree}
83
+ neighbor_funcs = {
84
+ "out": G.successors,
85
+ "in": G.predecessors,
86
+ "in+out": G.neighbors,
87
+ }
88
+ source_degree = direction[source]
89
+ target_degree = direction[target]
90
+ neighbors = neighbor_funcs[source]
91
+ # `reverse` indicates whether to look at the in-edge when
92
+ # computing the weight of an edge.
93
+ reverse = source == "in"
94
+ else:
95
+ if source != "in+out" or target != "in+out":
96
+ raise nx.NetworkXError(
97
+ f"source and target arguments are only supported for directed graphs"
98
+ )
99
+ source_degree = G.degree
100
+ target_degree = G.degree
101
+ neighbors = G.neighbors
102
+ reverse = False
103
+ dsum = defaultdict(int)
104
+ dnorm = defaultdict(int)
105
+ # Check if `source_nodes` is actually a single node in the graph.
106
+ source_nodes = source_degree(nodes)
107
+ if nodes in G:
108
+ source_nodes = [(nodes, source_degree(nodes))]
109
+ for n, k in source_nodes:
110
+ nbrdeg = target_degree(neighbors(n))
111
+ if weight is None:
112
+ s = sum(d for n, d in nbrdeg)
113
+ else: # weight nbr degree by weight of (n,nbr) edge
114
+ if reverse:
115
+ s = sum(G[nbr][n].get(weight, 1) * d for nbr, d in nbrdeg)
116
+ else:
117
+ s = sum(G[n][nbr].get(weight, 1) * d for nbr, d in nbrdeg)
118
+ dnorm[k] += source_degree(n, weight=weight)
119
+ dsum[k] += s
120
+
121
+ # normalize
122
+ return {k: avg if dnorm[k] == 0 else avg / dnorm[k] for k, avg in dsum.items()}
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/correlation.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Node assortativity coefficients and correlation measures."""
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.assortativity.mixing import (
5
+ attribute_mixing_matrix,
6
+ degree_mixing_matrix,
7
+ )
8
+ from networkx.algorithms.assortativity.pairs import node_degree_xy
9
+
10
+ __all__ = [
11
+ "degree_pearson_correlation_coefficient",
12
+ "degree_assortativity_coefficient",
13
+ "attribute_assortativity_coefficient",
14
+ "numeric_assortativity_coefficient",
15
+ ]
16
+
17
+
18
+ @nx._dispatchable(edge_attrs="weight")
19
+ def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
20
+ """Compute degree assortativity of graph.
21
+
22
+ Assortativity measures the similarity of connections
23
+ in the graph with respect to the node degree.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ x: string ('in','out')
30
+ The degree type for source node (directed graphs only).
31
+
32
+ y: string ('in','out')
33
+ The degree type for target node (directed graphs only).
34
+
35
+ weight: string or None, optional (default=None)
36
+ The edge attribute that holds the numerical value used
37
+ as a weight. If None, then each edge has weight 1.
38
+ The degree is the sum of the edge weights adjacent to the node.
39
+
40
+ nodes: list or iterable (optional)
41
+ Compute degree assortativity only for nodes in container.
42
+ The default is all nodes.
43
+
44
+ Returns
45
+ -------
46
+ r : float
47
+ Assortativity of graph by degree.
48
+
49
+ Examples
50
+ --------
51
+ >>> G = nx.path_graph(4)
52
+ >>> r = nx.degree_assortativity_coefficient(G)
53
+ >>> print(f"{r:3.1f}")
54
+ -0.5
55
+
56
+ See Also
57
+ --------
58
+ attribute_assortativity_coefficient
59
+ numeric_assortativity_coefficient
60
+ degree_mixing_dict
61
+ degree_mixing_matrix
62
+
63
+ Notes
64
+ -----
65
+ This computes Eq. (21) in Ref. [1]_ , where e is the joint
66
+ probability distribution (mixing matrix) of the degrees. If G is
67
+ directed than the matrix e is the joint probability of the
68
+ user-specified degree type for the source and target.
69
+
70
+ References
71
+ ----------
72
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
73
+ Physical Review E, 67 026126, 2003
74
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
75
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
76
+ """
77
+ if nodes is None:
78
+ nodes = G.nodes
79
+
80
+ degrees = None
81
+
82
+ if G.is_directed():
83
+ indeg = (
84
+ {d for _, d in G.in_degree(nodes, weight=weight)}
85
+ if "in" in (x, y)
86
+ else set()
87
+ )
88
+ outdeg = (
89
+ {d for _, d in G.out_degree(nodes, weight=weight)}
90
+ if "out" in (x, y)
91
+ else set()
92
+ )
93
+ degrees = set.union(indeg, outdeg)
94
+ else:
95
+ degrees = {d for _, d in G.degree(nodes, weight=weight)}
96
+
97
+ mapping = {d: i for i, d in enumerate(degrees)}
98
+ M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
99
+
100
+ return _numeric_ac(M, mapping=mapping)
101
+
102
+
103
+ @nx._dispatchable(edge_attrs="weight")
104
+ def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
105
+ """Compute degree assortativity of graph.
106
+
107
+ Assortativity measures the similarity of connections
108
+ in the graph with respect to the node degree.
109
+
110
+ This is the same as degree_assortativity_coefficient but uses the
111
+ potentially faster scipy.stats.pearsonr function.
112
+
113
+ Parameters
114
+ ----------
115
+ G : NetworkX graph
116
+
117
+ x: string ('in','out')
118
+ The degree type for source node (directed graphs only).
119
+
120
+ y: string ('in','out')
121
+ The degree type for target node (directed graphs only).
122
+
123
+ weight: string or None, optional (default=None)
124
+ The edge attribute that holds the numerical value used
125
+ as a weight. If None, then each edge has weight 1.
126
+ The degree is the sum of the edge weights adjacent to the node.
127
+
128
+ nodes: list or iterable (optional)
129
+ Compute pearson correlation of degrees only for specified nodes.
130
+ The default is all nodes.
131
+
132
+ Returns
133
+ -------
134
+ r : float
135
+ Assortativity of graph by degree.
136
+
137
+ Examples
138
+ --------
139
+ >>> G = nx.path_graph(4)
140
+ >>> r = nx.degree_pearson_correlation_coefficient(G)
141
+ >>> print(f"{r:3.1f}")
142
+ -0.5
143
+
144
+ Notes
145
+ -----
146
+ This calls scipy.stats.pearsonr.
147
+
148
+ References
149
+ ----------
150
+ .. [1] M. E. J. Newman, Mixing patterns in networks
151
+ Physical Review E, 67 026126, 2003
152
+ .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
153
+ Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
154
+ """
155
+ import scipy as sp
156
+
157
+ xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
158
+ x, y = zip(*xy)
159
+ return float(sp.stats.pearsonr(x, y)[0])
160
+
161
+
162
+ @nx._dispatchable(node_attrs="attribute")
163
+ def attribute_assortativity_coefficient(G, attribute, nodes=None):
164
+ """Compute assortativity for node attributes.
165
+
166
+ Assortativity measures the similarity of connections
167
+ in the graph with respect to the given attribute.
168
+
169
+ Parameters
170
+ ----------
171
+ G : NetworkX graph
172
+
173
+ attribute : string
174
+ Node attribute key
175
+
176
+ nodes: list or iterable (optional)
177
+ Compute attribute assortativity for nodes in container.
178
+ The default is all nodes.
179
+
180
+ Returns
181
+ -------
182
+ r: float
183
+ Assortativity of graph for given attribute
184
+
185
+ Examples
186
+ --------
187
+ >>> G = nx.Graph()
188
+ >>> G.add_nodes_from([0, 1], color="red")
189
+ >>> G.add_nodes_from([2, 3], color="blue")
190
+ >>> G.add_edges_from([(0, 1), (2, 3)])
191
+ >>> print(nx.attribute_assortativity_coefficient(G, "color"))
192
+ 1.0
193
+
194
+ Notes
195
+ -----
196
+ This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
197
+ where M is the joint probability distribution (mixing matrix)
198
+ of the specified attribute.
199
+
200
+ References
201
+ ----------
202
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
203
+ Physical Review E, 67 026126, 2003
204
+ """
205
+ M = attribute_mixing_matrix(G, attribute, nodes)
206
+ return attribute_ac(M)
207
+
208
+
209
+ @nx._dispatchable(node_attrs="attribute")
210
+ def numeric_assortativity_coefficient(G, attribute, nodes=None):
211
+ """Compute assortativity for numerical node attributes.
212
+
213
+ Assortativity measures the similarity of connections
214
+ in the graph with respect to the given numeric attribute.
215
+
216
+ Parameters
217
+ ----------
218
+ G : NetworkX graph
219
+
220
+ attribute : string
221
+ Node attribute key.
222
+
223
+ nodes: list or iterable (optional)
224
+ Compute numeric assortativity only for attributes of nodes in
225
+ container. The default is all nodes.
226
+
227
+ Returns
228
+ -------
229
+ r: float
230
+ Assortativity of graph for given attribute
231
+
232
+ Examples
233
+ --------
234
+ >>> G = nx.Graph()
235
+ >>> G.add_nodes_from([0, 1], size=2)
236
+ >>> G.add_nodes_from([2, 3], size=3)
237
+ >>> G.add_edges_from([(0, 1), (2, 3)])
238
+ >>> print(nx.numeric_assortativity_coefficient(G, "size"))
239
+ 1.0
240
+
241
+ Notes
242
+ -----
243
+ This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
244
+ coefficient of the specified (scalar valued) attribute across edges.
245
+
246
+ References
247
+ ----------
248
+ .. [1] M. E. J. Newman, Mixing patterns in networks
249
+ Physical Review E, 67 026126, 2003
250
+ """
251
+ if nodes is None:
252
+ nodes = G.nodes
253
+ vals = {G.nodes[n][attribute] for n in nodes}
254
+ mapping = {d: i for i, d in enumerate(vals)}
255
+ M = attribute_mixing_matrix(G, attribute, nodes, mapping)
256
+ return _numeric_ac(M, mapping)
257
+
258
+
259
+ def attribute_ac(M):
260
+ """Compute assortativity for attribute matrix M.
261
+
262
+ Parameters
263
+ ----------
264
+ M : numpy.ndarray
265
+ 2D ndarray representing the attribute mixing matrix.
266
+
267
+ Notes
268
+ -----
269
+ This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
270
+ where e is the joint probability distribution (mixing matrix)
271
+ of the specified attribute.
272
+
273
+ References
274
+ ----------
275
+ .. [1] M. E. J. Newman, Mixing patterns in networks,
276
+ Physical Review E, 67 026126, 2003
277
+ """
278
+ if M.sum() != 1.0:
279
+ M = M / M.sum()
280
+ s = (M @ M).sum()
281
+ t = M.trace()
282
+ r = (t - s) / (1 - s)
283
+ return float(r)
284
+
285
+
286
+ def _numeric_ac(M, mapping):
287
+ # M is a 2D numpy array
288
+ # numeric assortativity coefficient, pearsonr
289
+ import numpy as np
290
+
291
+ if M.sum() != 1.0:
292
+ M = M / M.sum()
293
+ x = np.array(list(mapping.keys()))
294
+ y = x # x and y have the same support
295
+ idx = list(mapping.values())
296
+ a = M.sum(axis=0)
297
+ b = M.sum(axis=1)
298
+ vara = (a[idx] * x**2).sum() - ((a[idx] * x).sum()) ** 2
299
+ varb = (b[idx] * y**2).sum() - ((b[idx] * y).sum()) ** 2
300
+ xy = np.outer(x, y)
301
+ ab = np.outer(a[idx], b[idx])
302
+ return float((xy * (M - ab)).sum() / np.sqrt(vara * varb))
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/mixing.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mixing matrices for node attributes and degree.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.assortativity.pairs import node_attribute_xy, node_degree_xy
7
+ from networkx.utils import dict_to_numpy_array
8
+
9
+ __all__ = [
10
+ "attribute_mixing_matrix",
11
+ "attribute_mixing_dict",
12
+ "degree_mixing_matrix",
13
+ "degree_mixing_dict",
14
+ "mixing_dict",
15
+ ]
16
+
17
+
18
+ @nx._dispatchable(node_attrs="attribute")
19
+ def attribute_mixing_dict(G, attribute, nodes=None, normalized=False):
20
+ """Returns dictionary representation of mixing matrix for attribute.
21
+
22
+ Parameters
23
+ ----------
24
+ G : graph
25
+ NetworkX graph object.
26
+
27
+ attribute : string
28
+ Node attribute key.
29
+
30
+ nodes: list or iterable (optional)
31
+ Unse nodes in container to build the dict. The default is all nodes.
32
+
33
+ normalized : bool (default=False)
34
+ Return counts if False or probabilities if True.
35
+
36
+ Examples
37
+ --------
38
+ >>> G = nx.Graph()
39
+ >>> G.add_nodes_from([0, 1], color="red")
40
+ >>> G.add_nodes_from([2, 3], color="blue")
41
+ >>> G.add_edge(1, 3)
42
+ >>> d = nx.attribute_mixing_dict(G, "color")
43
+ >>> print(d["red"]["blue"])
44
+ 1
45
+ >>> print(d["blue"]["red"]) # d symmetric for undirected graphs
46
+ 1
47
+
48
+ Returns
49
+ -------
50
+ d : dictionary
51
+ Counts or joint probability of occurrence of attribute pairs.
52
+ """
53
+ xy_iter = node_attribute_xy(G, attribute, nodes)
54
+ return mixing_dict(xy_iter, normalized=normalized)
55
+
56
+
57
+ @nx._dispatchable(node_attrs="attribute")
58
+ def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True):
59
+ """Returns mixing matrix for attribute.
60
+
61
+ Parameters
62
+ ----------
63
+ G : graph
64
+ NetworkX graph object.
65
+
66
+ attribute : string
67
+ Node attribute key.
68
+
69
+ nodes: list or iterable (optional)
70
+ Use only nodes in container to build the matrix. The default is
71
+ all nodes.
72
+
73
+ mapping : dictionary, optional
74
+ Mapping from node attribute to integer index in matrix.
75
+ If not specified, an arbitrary ordering will be used.
76
+
77
+ normalized : bool (default=True)
78
+ Return counts if False or probabilities if True.
79
+
80
+ Returns
81
+ -------
82
+ m: numpy array
83
+ Counts or joint probability of occurrence of attribute pairs.
84
+
85
+ Notes
86
+ -----
87
+ If each node has a unique attribute value, the unnormalized mixing matrix
88
+ will be equal to the adjacency matrix. To get a denser mixing matrix,
89
+ the rounding can be performed to form groups of nodes with equal values.
90
+ For example, the exact height of persons in cm (180.79155222, 163.9080892,
91
+ 163.30095355, 167.99016217, 168.21590163, ...) can be rounded to (180, 163,
92
+ 163, 168, 168, ...).
93
+
94
+ Definitions of attribute mixing matrix vary on whether the matrix
95
+ should include rows for attribute values that don't arise. Here we
96
+ do not include such empty-rows. But you can force them to appear
97
+ by inputting a `mapping` that includes those values.
98
+
99
+ Examples
100
+ --------
101
+ >>> G = nx.path_graph(3)
102
+ >>> gender = {0: "male", 1: "female", 2: "female"}
103
+ >>> nx.set_node_attributes(G, gender, "gender")
104
+ >>> mapping = {"male": 0, "female": 1}
105
+ >>> mix_mat = nx.attribute_mixing_matrix(G, "gender", mapping=mapping)
106
+ >>> mix_mat
107
+ array([[0. , 0.25],
108
+ [0.25, 0.5 ]])
109
+ """
110
+ d = attribute_mixing_dict(G, attribute, nodes)
111
+ a = dict_to_numpy_array(d, mapping=mapping)
112
+ if normalized:
113
+ a = a / a.sum()
114
+ return a
115
+
116
+
117
+ @nx._dispatchable(edge_attrs="weight")
118
+ def degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=False):
119
+ """Returns dictionary representation of mixing matrix for degree.
120
+
121
+ Parameters
122
+ ----------
123
+ G : graph
124
+ NetworkX graph object.
125
+
126
+ x: string ('in','out')
127
+ The degree type for source node (directed graphs only).
128
+
129
+ y: string ('in','out')
130
+ The degree type for target node (directed graphs only).
131
+
132
+ weight: string or None, optional (default=None)
133
+ The edge attribute that holds the numerical value used
134
+ as a weight. If None, then each edge has weight 1.
135
+ The degree is the sum of the edge weights adjacent to the node.
136
+
137
+ normalized : bool (default=False)
138
+ Return counts if False or probabilities if True.
139
+
140
+ Returns
141
+ -------
142
+ d: dictionary
143
+ Counts or joint probability of occurrence of degree pairs.
144
+ """
145
+ xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
146
+ return mixing_dict(xy_iter, normalized=normalized)
147
+
148
+
149
+ @nx._dispatchable(edge_attrs="weight")
150
+ def degree_mixing_matrix(
151
+ G, x="out", y="in", weight=None, nodes=None, normalized=True, mapping=None
152
+ ):
153
+ """Returns mixing matrix for attribute.
154
+
155
+ Parameters
156
+ ----------
157
+ G : graph
158
+ NetworkX graph object.
159
+
160
+ x: string ('in','out')
161
+ The degree type for source node (directed graphs only).
162
+
163
+ y: string ('in','out')
164
+ The degree type for target node (directed graphs only).
165
+
166
+ nodes: list or iterable (optional)
167
+ Build the matrix using only nodes in container.
168
+ The default is all nodes.
169
+
170
+ weight: string or None, optional (default=None)
171
+ The edge attribute that holds the numerical value used
172
+ as a weight. If None, then each edge has weight 1.
173
+ The degree is the sum of the edge weights adjacent to the node.
174
+
175
+ normalized : bool (default=True)
176
+ Return counts if False or probabilities if True.
177
+
178
+ mapping : dictionary, optional
179
+ Mapping from node degree to integer index in matrix.
180
+ If not specified, an arbitrary ordering will be used.
181
+
182
+ Returns
183
+ -------
184
+ m: numpy array
185
+ Counts, or joint probability, of occurrence of node degree.
186
+
187
+ Notes
188
+ -----
189
+ Definitions of degree mixing matrix vary on whether the matrix
190
+ should include rows for degree values that don't arise. Here we
191
+ do not include such empty-rows. But you can force them to appear
192
+ by inputting a `mapping` that includes those values. See examples.
193
+
194
+ Examples
195
+ --------
196
+ >>> G = nx.star_graph(3)
197
+ >>> mix_mat = nx.degree_mixing_matrix(G)
198
+ >>> mix_mat
199
+ array([[0. , 0.5],
200
+ [0.5, 0. ]])
201
+
202
+ If you want every possible degree to appear as a row, even if no nodes
203
+ have that degree, use `mapping` as follows,
204
+
205
+ >>> max_degree = max(deg for n, deg in G.degree)
206
+ >>> mapping = {x: x for x in range(max_degree + 1)} # identity mapping
207
+ >>> mix_mat = nx.degree_mixing_matrix(G, mapping=mapping)
208
+ >>> mix_mat
209
+ array([[0. , 0. , 0. , 0. ],
210
+ [0. , 0. , 0. , 0.5],
211
+ [0. , 0. , 0. , 0. ],
212
+ [0. , 0.5, 0. , 0. ]])
213
+ """
214
+ d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight)
215
+ a = dict_to_numpy_array(d, mapping=mapping)
216
+ if normalized:
217
+ a = a / a.sum()
218
+ return a
219
+
220
+
221
+ def mixing_dict(xy, normalized=False):
222
+ """Returns a dictionary representation of mixing matrix.
223
+
224
+ Parameters
225
+ ----------
226
+ xy : list or container of two-tuples
227
+ Pairs of (x,y) items.
228
+
229
+ attribute : string
230
+ Node attribute key
231
+
232
+ normalized : bool (default=False)
233
+ Return counts if False or probabilities if True.
234
+
235
+ Returns
236
+ -------
237
+ d: dictionary
238
+ Counts or Joint probability of occurrence of values in xy.
239
+ """
240
+ d = {}
241
+ psum = 0.0
242
+ for x, y in xy:
243
+ if x not in d:
244
+ d[x] = {}
245
+ if y not in d:
246
+ d[y] = {}
247
+ v = d[x].get(y, 0)
248
+ d[x][y] = v + 1
249
+ psum += 1
250
+
251
+ if normalized:
252
+ for _, jdict in d.items():
253
+ for j in jdict:
254
+ jdict[j] /= psum
255
+ return d
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/neighbor_degree.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ __all__ = ["average_neighbor_degree"]
4
+
5
+
6
+ @nx._dispatchable(edge_attrs="weight")
7
+ def average_neighbor_degree(G, source="out", target="out", nodes=None, weight=None):
8
+ r"""Returns the average degree of the neighborhood of each node.
9
+
10
+ In an undirected graph, the neighborhood `N(i)` of node `i` contains the
11
+ nodes that are connected to `i` by an edge.
12
+
13
+ For directed graphs, `N(i)` is defined according to the parameter `source`:
14
+
15
+ - if source is 'in', then `N(i)` consists of predecessors of node `i`.
16
+ - if source is 'out', then `N(i)` consists of successors of node `i`.
17
+ - if source is 'in+out', then `N(i)` is both predecessors and successors.
18
+
19
+ The average neighborhood degree of a node `i` is
20
+
21
+ .. math::
22
+
23
+ k_{nn,i} = \frac{1}{|N(i)|} \sum_{j \in N(i)} k_j
24
+
25
+ where `N(i)` are the neighbors of node `i` and `k_j` is
26
+ the degree of node `j` which belongs to `N(i)`. For weighted
27
+ graphs, an analogous measure can be defined [1]_,
28
+
29
+ .. math::
30
+
31
+ k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
32
+
33
+ where `s_i` is the weighted degree of node `i`, `w_{ij}`
34
+ is the weight of the edge that links `i` and `j` and
35
+ `N(i)` are the neighbors of node `i`.
36
+
37
+
38
+ Parameters
39
+ ----------
40
+ G : NetworkX graph
41
+
42
+ source : string ("in"|"out"|"in+out"), optional (default="out")
43
+ Directed graphs only.
44
+ Use "in"- or "out"-neighbors of source node.
45
+
46
+ target : string ("in"|"out"|"in+out"), optional (default="out")
47
+ Directed graphs only.
48
+ Use "in"- or "out"-degree for target node.
49
+
50
+ nodes : list or iterable, optional (default=G.nodes)
51
+ Compute neighbor degree only for specified nodes.
52
+
53
+ weight : string or None, optional (default=None)
54
+ The edge attribute that holds the numerical value used as a weight.
55
+ If None, then each edge has weight 1.
56
+
57
+ Returns
58
+ -------
59
+ d: dict
60
+ A dictionary keyed by node to the average degree of its neighbors.
61
+
62
+ Raises
63
+ ------
64
+ NetworkXError
65
+ If either `source` or `target` are not one of 'in', 'out', or 'in+out'.
66
+ If either `source` or `target` is passed for an undirected graph.
67
+
68
+ Examples
69
+ --------
70
+ >>> G = nx.path_graph(4)
71
+ >>> G.edges[0, 1]["weight"] = 5
72
+ >>> G.edges[2, 3]["weight"] = 3
73
+
74
+ >>> nx.average_neighbor_degree(G)
75
+ {0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
76
+ >>> nx.average_neighbor_degree(G, weight="weight")
77
+ {0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
78
+
79
+ >>> G = nx.DiGraph()
80
+ >>> nx.add_path(G, [0, 1, 2, 3])
81
+ >>> nx.average_neighbor_degree(G, source="in", target="in")
82
+ {0: 0.0, 1: 0.0, 2: 1.0, 3: 1.0}
83
+
84
+ >>> nx.average_neighbor_degree(G, source="out", target="out")
85
+ {0: 1.0, 1: 1.0, 2: 0.0, 3: 0.0}
86
+
87
+ See Also
88
+ --------
89
+ average_degree_connectivity
90
+
91
+ References
92
+ ----------
93
+ .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
94
+ "The architecture of complex weighted networks".
95
+ PNAS 101 (11): 3747–3752 (2004).
96
+ """
97
+ if G.is_directed():
98
+ if source == "in":
99
+ source_degree = G.in_degree
100
+ elif source == "out":
101
+ source_degree = G.out_degree
102
+ elif source == "in+out":
103
+ source_degree = G.degree
104
+ else:
105
+ raise nx.NetworkXError(
106
+ f"source argument {source} must be 'in', 'out' or 'in+out'"
107
+ )
108
+
109
+ if target == "in":
110
+ target_degree = G.in_degree
111
+ elif target == "out":
112
+ target_degree = G.out_degree
113
+ elif target == "in+out":
114
+ target_degree = G.degree
115
+ else:
116
+ raise nx.NetworkXError(
117
+ f"target argument {target} must be 'in', 'out' or 'in+out'"
118
+ )
119
+ else:
120
+ if source != "out" or target != "out":
121
+ raise nx.NetworkXError(
122
+ f"source and target arguments are only supported for directed graphs"
123
+ )
124
+ source_degree = target_degree = G.degree
125
+
126
+ # precompute target degrees -- should *not* be weighted degree
127
+ t_deg = dict(target_degree())
128
+
129
+ # Set up both predecessor and successor neighbor dicts leaving empty if not needed
130
+ G_P = G_S = {n: {} for n in G}
131
+ if G.is_directed():
132
+ # "in" or "in+out" cases: G_P contains predecessors
133
+ if "in" in source:
134
+ G_P = G.pred
135
+ # "out" or "in+out" cases: G_S contains successors
136
+ if "out" in source:
137
+ G_S = G.succ
138
+ else:
139
+ # undirected leave G_P empty but G_S is the adjacency
140
+ G_S = G.adj
141
+
142
+ # Main loop: Compute average degree of neighbors
143
+ avg = {}
144
+ for n, deg in source_degree(nodes, weight=weight):
145
+ # handle degree zero average
146
+ if deg == 0:
147
+ avg[n] = 0.0
148
+ continue
149
+
150
+ # we sum over both G_P and G_S, but one of the two is usually empty.
151
+ if weight is None:
152
+ avg[n] = (
153
+ sum(t_deg[nbr] for nbr in G_S[n]) + sum(t_deg[nbr] for nbr in G_P[n])
154
+ ) / deg
155
+ else:
156
+ avg[n] = (
157
+ sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_S[n].items())
158
+ + sum(dd.get(weight, 1) * t_deg[nbr] for nbr, dd in G_P[n].items())
159
+ ) / deg
160
+ return avg
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/pairs.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators of x-y pairs of node data."""
2
+
3
+ import networkx as nx
4
+
5
+ __all__ = ["node_attribute_xy", "node_degree_xy"]
6
+
7
+
8
+ @nx._dispatchable(node_attrs="attribute")
9
+ def node_attribute_xy(G, attribute, nodes=None):
10
+ """Yields 2-tuples of node attribute values for all edges in `G`.
11
+
12
+ This generator yields, for each edge in `G` incident to a node in `nodes`,
13
+ a 2-tuple of form ``(attribute value, attribute value)`` for the parameter
14
+ specified node-attribute.
15
+
16
+ Parameters
17
+ ----------
18
+ G: NetworkX graph
19
+
20
+ attribute: key
21
+ The node attribute key.
22
+
23
+ nodes: list or iterable (optional)
24
+ Use only edges that are incident to specified nodes.
25
+ The default is all nodes.
26
+
27
+ Yields
28
+ ------
29
+ (x, y): 2-tuple
30
+ Generates 2-tuple of (attribute, attribute) values.
31
+
32
+ Examples
33
+ --------
34
+ >>> G = nx.DiGraph()
35
+ >>> G.add_node(1, color="red")
36
+ >>> G.add_node(2, color="blue")
37
+ >>> G.add_node(3, color="green")
38
+ >>> G.add_edge(1, 2)
39
+ >>> list(nx.node_attribute_xy(G, "color"))
40
+ [('red', 'blue')]
41
+
42
+ Notes
43
+ -----
44
+ For undirected graphs, each edge is produced twice, once for each edge
45
+ representation (u, v) and (v, u), with the exception of self-loop edges
46
+ which only appear once.
47
+ """
48
+ if nodes is None:
49
+ nodes = set(G)
50
+ else:
51
+ nodes = set(nodes)
52
+ Gnodes = G.nodes
53
+ for u, nbrsdict in G.adjacency():
54
+ if u not in nodes:
55
+ continue
56
+ uattr = Gnodes[u].get(attribute, None)
57
+ if G.is_multigraph():
58
+ for v, keys in nbrsdict.items():
59
+ vattr = Gnodes[v].get(attribute, None)
60
+ for _ in keys:
61
+ yield (uattr, vattr)
62
+ else:
63
+ for v in nbrsdict:
64
+ vattr = Gnodes[v].get(attribute, None)
65
+ yield (uattr, vattr)
66
+
67
+
68
+ @nx._dispatchable(edge_attrs="weight")
69
+ def node_degree_xy(G, x="out", y="in", weight=None, nodes=None):
70
+ """Yields 2-tuples of ``(degree, degree)`` values for edges in `G`.
71
+
72
+ This generator yields, for each edge in `G` incident to a node in `nodes`,
73
+ a 2-tuple of form ``(degree, degree)``. The node degrees are weighted
74
+ when a `weight` attribute is specified.
75
+
76
+ Parameters
77
+ ----------
78
+ G: NetworkX graph
79
+
80
+ x: string ('in','out')
81
+ The degree type for source node (directed graphs only).
82
+
83
+ y: string ('in','out')
84
+ The degree type for target node (directed graphs only).
85
+
86
+ weight: string or None, optional (default=None)
87
+ The edge attribute that holds the numerical value used
88
+ as a weight. If None, then each edge has weight 1.
89
+ The degree is the sum of the edge weights adjacent to the node.
90
+
91
+ nodes: list or iterable (optional)
92
+ Use only edges that are adjacency to specified nodes.
93
+ The default is all nodes.
94
+
95
+ Yields
96
+ ------
97
+ (x, y): 2-tuple
98
+ Generates 2-tuple of (degree, degree) values.
99
+
100
+ Examples
101
+ --------
102
+ >>> G = nx.DiGraph()
103
+ >>> G.add_edge(1, 2)
104
+ >>> list(nx.node_degree_xy(G, x="out", y="in"))
105
+ [(1, 1)]
106
+ >>> list(nx.node_degree_xy(G, x="in", y="out"))
107
+ [(0, 0)]
108
+
109
+ Notes
110
+ -----
111
+ For undirected graphs, each edge is produced twice, once for each edge
112
+ representation (u, v) and (v, u), with the exception of self-loop edges
113
+ which only appear once.
114
+ """
115
+ nodes = set(G) if nodes is None else set(nodes)
116
+ if G.is_directed():
117
+ direction = {"out": G.out_degree, "in": G.in_degree}
118
+ xdeg = direction[x]
119
+ ydeg = direction[y]
120
+ else:
121
+ xdeg = ydeg = G.degree
122
+
123
+ for u, degu in xdeg(nodes, weight=weight):
124
+ # use G.edges to treat multigraphs correctly
125
+ neighbors = (nbr for _, nbr in G.edges(u) if nbr in nodes)
126
+ for _, degv in ydeg(neighbors, weight=weight):
127
+ yield degu, degv
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/base_test.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_connectivity.cpython-310.pyc ADDED
Binary file (4.4 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_correlation.cpython-310.pyc ADDED
Binary file (7.08 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_mixing.cpython-310.pyc ADDED
Binary file (7.57 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_neighbor_degree.cpython-310.pyc ADDED
Binary file (3.48 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/__pycache__/test_pairs.cpython-310.pyc ADDED
Binary file (3.67 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/base_test.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+
4
+ class BaseTestAttributeMixing:
5
+ @classmethod
6
+ def setup_class(cls):
7
+ G = nx.Graph()
8
+ G.add_nodes_from([0, 1], fish="one")
9
+ G.add_nodes_from([2, 3], fish="two")
10
+ G.add_nodes_from([4], fish="red")
11
+ G.add_nodes_from([5], fish="blue")
12
+ G.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
13
+ cls.G = G
14
+
15
+ D = nx.DiGraph()
16
+ D.add_nodes_from([0, 1], fish="one")
17
+ D.add_nodes_from([2, 3], fish="two")
18
+ D.add_nodes_from([4], fish="red")
19
+ D.add_nodes_from([5], fish="blue")
20
+ D.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
21
+ cls.D = D
22
+
23
+ M = nx.MultiGraph()
24
+ M.add_nodes_from([0, 1], fish="one")
25
+ M.add_nodes_from([2, 3], fish="two")
26
+ M.add_nodes_from([4], fish="red")
27
+ M.add_nodes_from([5], fish="blue")
28
+ M.add_edges_from([(0, 1), (0, 1), (2, 3)])
29
+ cls.M = M
30
+
31
+ S = nx.Graph()
32
+ S.add_nodes_from([0, 1], fish="one")
33
+ S.add_nodes_from([2, 3], fish="two")
34
+ S.add_nodes_from([4], fish="red")
35
+ S.add_nodes_from([5], fish="blue")
36
+ S.add_edge(0, 0)
37
+ S.add_edge(2, 2)
38
+ cls.S = S
39
+
40
+ N = nx.Graph()
41
+ N.add_nodes_from([0, 1], margin=-2)
42
+ N.add_nodes_from([2, 3], margin=-2)
43
+ N.add_nodes_from([4], margin=-3)
44
+ N.add_nodes_from([5], margin=-4)
45
+ N.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
46
+ cls.N = N
47
+
48
+ F = nx.Graph()
49
+ F.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5)
50
+ F.add_edge(0, 2, weight=1)
51
+ nx.set_node_attributes(F, dict(F.degree(weight="weight")), "margin")
52
+ cls.F = F
53
+
54
+ K = nx.Graph()
55
+ K.add_nodes_from([1, 2], margin=-1)
56
+ K.add_nodes_from([3], margin=1)
57
+ K.add_nodes_from([4], margin=2)
58
+ K.add_edges_from([(3, 4), (1, 2), (1, 3)])
59
+ cls.K = K
60
+
61
+
62
+ class BaseTestDegreeMixing:
63
+ @classmethod
64
+ def setup_class(cls):
65
+ cls.P4 = nx.path_graph(4)
66
+ cls.D = nx.DiGraph()
67
+ cls.D.add_edges_from([(0, 2), (0, 3), (1, 3), (2, 3)])
68
+ cls.D2 = nx.DiGraph()
69
+ cls.D2.add_edges_from([(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 2)])
70
+ cls.M = nx.MultiGraph()
71
+ nx.add_path(cls.M, range(4))
72
+ cls.M.add_edge(0, 1)
73
+ cls.S = nx.Graph()
74
+ cls.S.add_edges_from([(0, 0), (1, 1)])
75
+ cls.W = nx.Graph()
76
+ cls.W.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5)
77
+ cls.W.add_edge(0, 2, weight=1)
78
+ S1 = nx.star_graph(4)
79
+ S2 = nx.star_graph(4)
80
+ cls.DS = nx.disjoint_union(S1, S2)
81
+ cls.DS.add_edge(4, 5)
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_connectivity.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import permutations
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestNeighborConnectivity:
9
+ def test_degree_p4(self):
10
+ G = nx.path_graph(4)
11
+ answer = {1: 2.0, 2: 1.5}
12
+ nd = nx.average_degree_connectivity(G)
13
+ assert nd == answer
14
+
15
+ D = G.to_directed()
16
+ answer = {2: 2.0, 4: 1.5}
17
+ nd = nx.average_degree_connectivity(D)
18
+ assert nd == answer
19
+
20
+ answer = {1: 2.0, 2: 1.5}
21
+ D = G.to_directed()
22
+ nd = nx.average_degree_connectivity(D, source="in", target="in")
23
+ assert nd == answer
24
+
25
+ D = G.to_directed()
26
+ nd = nx.average_degree_connectivity(D, source="in", target="in")
27
+ assert nd == answer
28
+
29
+ def test_degree_p4_weighted(self):
30
+ G = nx.path_graph(4)
31
+ G[1][2]["weight"] = 4
32
+ answer = {1: 2.0, 2: 1.8}
33
+ nd = nx.average_degree_connectivity(G, weight="weight")
34
+ assert nd == answer
35
+ answer = {1: 2.0, 2: 1.5}
36
+ nd = nx.average_degree_connectivity(G)
37
+ assert nd == answer
38
+
39
+ D = G.to_directed()
40
+ answer = {2: 2.0, 4: 1.8}
41
+ nd = nx.average_degree_connectivity(D, weight="weight")
42
+ assert nd == answer
43
+
44
+ answer = {1: 2.0, 2: 1.8}
45
+ D = G.to_directed()
46
+ nd = nx.average_degree_connectivity(
47
+ D, weight="weight", source="in", target="in"
48
+ )
49
+ assert nd == answer
50
+
51
+ D = G.to_directed()
52
+ nd = nx.average_degree_connectivity(
53
+ D, source="in", target="out", weight="weight"
54
+ )
55
+ assert nd == answer
56
+
57
+ def test_weight_keyword(self):
58
+ G = nx.path_graph(4)
59
+ G[1][2]["other"] = 4
60
+ answer = {1: 2.0, 2: 1.8}
61
+ nd = nx.average_degree_connectivity(G, weight="other")
62
+ assert nd == answer
63
+ answer = {1: 2.0, 2: 1.5}
64
+ nd = nx.average_degree_connectivity(G, weight=None)
65
+ assert nd == answer
66
+
67
+ D = G.to_directed()
68
+ answer = {2: 2.0, 4: 1.8}
69
+ nd = nx.average_degree_connectivity(D, weight="other")
70
+ assert nd == answer
71
+
72
+ answer = {1: 2.0, 2: 1.8}
73
+ D = G.to_directed()
74
+ nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in")
75
+ assert nd == answer
76
+
77
+ D = G.to_directed()
78
+ nd = nx.average_degree_connectivity(D, weight="other", source="in", target="in")
79
+ assert nd == answer
80
+
81
+ def test_degree_barrat(self):
82
+ G = nx.star_graph(5)
83
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
84
+ G[0][5]["weight"] = 5
85
+ nd = nx.average_degree_connectivity(G)[5]
86
+ assert nd == 1.8
87
+ nd = nx.average_degree_connectivity(G, weight="weight")[5]
88
+ assert nd == pytest.approx(3.222222, abs=1e-5)
89
+
90
+ def test_zero_deg(self):
91
+ G = nx.DiGraph()
92
+ G.add_edge(1, 2)
93
+ G.add_edge(1, 3)
94
+ G.add_edge(1, 4)
95
+ c = nx.average_degree_connectivity(G)
96
+ assert c == {1: 0, 3: 1}
97
+ c = nx.average_degree_connectivity(G, source="in", target="in")
98
+ assert c == {0: 0, 1: 0}
99
+ c = nx.average_degree_connectivity(G, source="in", target="out")
100
+ assert c == {0: 0, 1: 3}
101
+ c = nx.average_degree_connectivity(G, source="in", target="in+out")
102
+ assert c == {0: 0, 1: 3}
103
+ c = nx.average_degree_connectivity(G, source="out", target="out")
104
+ assert c == {0: 0, 3: 0}
105
+ c = nx.average_degree_connectivity(G, source="out", target="in")
106
+ assert c == {0: 0, 3: 1}
107
+ c = nx.average_degree_connectivity(G, source="out", target="in+out")
108
+ assert c == {0: 0, 3: 1}
109
+
110
+ def test_in_out_weight(self):
111
+ G = nx.DiGraph()
112
+ G.add_edge(1, 2, weight=1)
113
+ G.add_edge(1, 3, weight=1)
114
+ G.add_edge(3, 1, weight=1)
115
+ for s, t in permutations(["in", "out", "in+out"], 2):
116
+ c = nx.average_degree_connectivity(G, source=s, target=t)
117
+ cw = nx.average_degree_connectivity(G, source=s, target=t, weight="weight")
118
+ assert c == cw
119
+
120
+ def test_invalid_source(self):
121
+ with pytest.raises(nx.NetworkXError):
122
+ G = nx.DiGraph()
123
+ nx.average_degree_connectivity(G, source="bogus")
124
+
125
+ def test_invalid_target(self):
126
+ with pytest.raises(nx.NetworkXError):
127
+ G = nx.DiGraph()
128
+ nx.average_degree_connectivity(G, target="bogus")
129
+
130
+ def test_invalid_undirected_graph(self):
131
+ G = nx.Graph()
132
+ with pytest.raises(nx.NetworkXError):
133
+ nx.average_degree_connectivity(G, target="bogus")
134
+ with pytest.raises(nx.NetworkXError):
135
+ nx.average_degree_connectivity(G, source="bogus")
136
+
137
+ def test_single_node(self):
138
+ # TODO Is this really the intended behavior for providing a
139
+ # single node as the argument `nodes`? Shouldn't the function
140
+ # just return the connectivity value itself?
141
+ G = nx.trivial_graph()
142
+ conn = nx.average_degree_connectivity(G, nodes=0)
143
+ assert conn == {0: 0}
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_correlation.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+ pytest.importorskip("scipy")
5
+
6
+
7
+ import networkx as nx
8
+ from networkx.algorithms.assortativity.correlation import attribute_ac
9
+
10
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
11
+
12
+
13
+ class TestDegreeMixingCorrelation(BaseTestDegreeMixing):
14
+ def test_degree_assortativity_undirected(self):
15
+ r = nx.degree_assortativity_coefficient(self.P4)
16
+ np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
17
+
18
+ def test_degree_assortativity_node_kwargs(self):
19
+ G = nx.Graph()
20
+ edges = [(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (5, 9), (9, 0)]
21
+ G.add_edges_from(edges)
22
+ r = nx.degree_assortativity_coefficient(G, nodes=[1, 2, 4])
23
+ np.testing.assert_almost_equal(r, -1.0, decimal=4)
24
+
25
+ def test_degree_assortativity_directed(self):
26
+ r = nx.degree_assortativity_coefficient(self.D)
27
+ np.testing.assert_almost_equal(r, -0.57735, decimal=4)
28
+
29
+ def test_degree_assortativity_directed2(self):
30
+ """Test degree assortativity for a directed graph where the set of
31
+ in/out degree does not equal the total degree."""
32
+ r = nx.degree_assortativity_coefficient(self.D2)
33
+ np.testing.assert_almost_equal(r, 0.14852, decimal=4)
34
+
35
+ def test_degree_assortativity_multigraph(self):
36
+ r = nx.degree_assortativity_coefficient(self.M)
37
+ np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
38
+
39
+ def test_degree_pearson_assortativity_undirected(self):
40
+ r = nx.degree_pearson_correlation_coefficient(self.P4)
41
+ np.testing.assert_almost_equal(r, -1.0 / 2, decimal=4)
42
+
43
+ def test_degree_pearson_assortativity_directed(self):
44
+ r = nx.degree_pearson_correlation_coefficient(self.D)
45
+ np.testing.assert_almost_equal(r, -0.57735, decimal=4)
46
+
47
+ def test_degree_pearson_assortativity_directed2(self):
48
+ """Test degree assortativity with Pearson for a directed graph where
49
+ the set of in/out degree does not equal the total degree."""
50
+ r = nx.degree_pearson_correlation_coefficient(self.D2)
51
+ np.testing.assert_almost_equal(r, 0.14852, decimal=4)
52
+
53
+ def test_degree_pearson_assortativity_multigraph(self):
54
+ r = nx.degree_pearson_correlation_coefficient(self.M)
55
+ np.testing.assert_almost_equal(r, -1.0 / 7.0, decimal=4)
56
+
57
+ def test_degree_assortativity_weighted(self):
58
+ r = nx.degree_assortativity_coefficient(self.W, weight="weight")
59
+ np.testing.assert_almost_equal(r, -0.1429, decimal=4)
60
+
61
+ def test_degree_assortativity_double_star(self):
62
+ r = nx.degree_assortativity_coefficient(self.DS)
63
+ np.testing.assert_almost_equal(r, -0.9339, decimal=4)
64
+
65
+
66
+ class TestAttributeMixingCorrelation(BaseTestAttributeMixing):
67
+ def test_attribute_assortativity_undirected(self):
68
+ r = nx.attribute_assortativity_coefficient(self.G, "fish")
69
+ assert r == 6.0 / 22.0
70
+
71
+ def test_attribute_assortativity_directed(self):
72
+ r = nx.attribute_assortativity_coefficient(self.D, "fish")
73
+ assert r == 1.0 / 3.0
74
+
75
+ def test_attribute_assortativity_multigraph(self):
76
+ r = nx.attribute_assortativity_coefficient(self.M, "fish")
77
+ assert r == 1.0
78
+
79
+ def test_attribute_assortativity_coefficient(self):
80
+ # from "Mixing patterns in networks"
81
+ # fmt: off
82
+ a = np.array([[0.258, 0.016, 0.035, 0.013],
83
+ [0.012, 0.157, 0.058, 0.019],
84
+ [0.013, 0.023, 0.306, 0.035],
85
+ [0.005, 0.007, 0.024, 0.016]])
86
+ # fmt: on
87
+ r = attribute_ac(a)
88
+ np.testing.assert_almost_equal(r, 0.623, decimal=3)
89
+
90
+ def test_attribute_assortativity_coefficient2(self):
91
+ # fmt: off
92
+ a = np.array([[0.18, 0.02, 0.01, 0.03],
93
+ [0.02, 0.20, 0.03, 0.02],
94
+ [0.01, 0.03, 0.16, 0.01],
95
+ [0.03, 0.02, 0.01, 0.22]])
96
+ # fmt: on
97
+ r = attribute_ac(a)
98
+ np.testing.assert_almost_equal(r, 0.68, decimal=2)
99
+
100
+ def test_attribute_assortativity(self):
101
+ a = np.array([[50, 50, 0], [50, 50, 0], [0, 0, 2]])
102
+ r = attribute_ac(a)
103
+ np.testing.assert_almost_equal(r, 0.029, decimal=3)
104
+
105
+ def test_attribute_assortativity_negative(self):
106
+ r = nx.numeric_assortativity_coefficient(self.N, "margin")
107
+ np.testing.assert_almost_equal(r, -0.2903, decimal=4)
108
+
109
+ def test_assortativity_node_kwargs(self):
110
+ G = nx.Graph()
111
+ G.add_nodes_from([0, 1], size=2)
112
+ G.add_nodes_from([2, 3], size=3)
113
+ G.add_edges_from([(0, 1), (2, 3)])
114
+ r = nx.numeric_assortativity_coefficient(G, "size", nodes=[0, 3])
115
+ np.testing.assert_almost_equal(r, 1.0, decimal=4)
116
+
117
+ def test_attribute_assortativity_float(self):
118
+ r = nx.numeric_assortativity_coefficient(self.F, "margin")
119
+ np.testing.assert_almost_equal(r, -0.1429, decimal=4)
120
+
121
+ def test_attribute_assortativity_mixed(self):
122
+ r = nx.numeric_assortativity_coefficient(self.K, "margin")
123
+ np.testing.assert_almost_equal(r, 0.4340, decimal=4)
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_mixing.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+
5
+
6
+ import networkx as nx
7
+
8
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
9
+
10
+
11
+ class TestDegreeMixingDict(BaseTestDegreeMixing):
12
+ def test_degree_mixing_dict_undirected(self):
13
+ d = nx.degree_mixing_dict(self.P4)
14
+ d_result = {1: {2: 2}, 2: {1: 2, 2: 2}}
15
+ assert d == d_result
16
+
17
+ def test_degree_mixing_dict_undirected_normalized(self):
18
+ d = nx.degree_mixing_dict(self.P4, normalized=True)
19
+ d_result = {1: {2: 1.0 / 3}, 2: {1: 1.0 / 3, 2: 1.0 / 3}}
20
+ assert d == d_result
21
+
22
+ def test_degree_mixing_dict_directed(self):
23
+ d = nx.degree_mixing_dict(self.D)
24
+ print(d)
25
+ d_result = {1: {3: 2}, 2: {1: 1, 3: 1}, 3: {}}
26
+ assert d == d_result
27
+
28
+ def test_degree_mixing_dict_multigraph(self):
29
+ d = nx.degree_mixing_dict(self.M)
30
+ d_result = {1: {2: 1}, 2: {1: 1, 3: 3}, 3: {2: 3}}
31
+ assert d == d_result
32
+
33
+ def test_degree_mixing_dict_weighted(self):
34
+ d = nx.degree_mixing_dict(self.W, weight="weight")
35
+ d_result = {0.5: {1.5: 1}, 1.5: {1.5: 6, 0.5: 1}}
36
+ assert d == d_result
37
+
38
+
39
+ class TestDegreeMixingMatrix(BaseTestDegreeMixing):
40
+ def test_degree_mixing_matrix_undirected(self):
41
+ # fmt: off
42
+ a_result = np.array([[0, 2],
43
+ [2, 2]]
44
+ )
45
+ # fmt: on
46
+ a = nx.degree_mixing_matrix(self.P4, normalized=False)
47
+ np.testing.assert_equal(a, a_result)
48
+ a = nx.degree_mixing_matrix(self.P4)
49
+ np.testing.assert_equal(a, a_result / a_result.sum())
50
+
51
+ def test_degree_mixing_matrix_directed(self):
52
+ # fmt: off
53
+ a_result = np.array([[0, 0, 2],
54
+ [1, 0, 1],
55
+ [0, 0, 0]]
56
+ )
57
+ # fmt: on
58
+ a = nx.degree_mixing_matrix(self.D, normalized=False)
59
+ np.testing.assert_equal(a, a_result)
60
+ a = nx.degree_mixing_matrix(self.D)
61
+ np.testing.assert_equal(a, a_result / a_result.sum())
62
+
63
+ def test_degree_mixing_matrix_multigraph(self):
64
+ # fmt: off
65
+ a_result = np.array([[0, 1, 0],
66
+ [1, 0, 3],
67
+ [0, 3, 0]]
68
+ )
69
+ # fmt: on
70
+ a = nx.degree_mixing_matrix(self.M, normalized=False)
71
+ np.testing.assert_equal(a, a_result)
72
+ a = nx.degree_mixing_matrix(self.M)
73
+ np.testing.assert_equal(a, a_result / a_result.sum())
74
+
75
+ def test_degree_mixing_matrix_selfloop(self):
76
+ # fmt: off
77
+ a_result = np.array([[2]])
78
+ # fmt: on
79
+ a = nx.degree_mixing_matrix(self.S, normalized=False)
80
+ np.testing.assert_equal(a, a_result)
81
+ a = nx.degree_mixing_matrix(self.S)
82
+ np.testing.assert_equal(a, a_result / a_result.sum())
83
+
84
+ def test_degree_mixing_matrix_weighted(self):
85
+ a_result = np.array([[0.0, 1.0], [1.0, 6.0]])
86
+ a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False)
87
+ np.testing.assert_equal(a, a_result)
88
+ a = nx.degree_mixing_matrix(self.W, weight="weight")
89
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
90
+
91
+ def test_degree_mixing_matrix_mapping(self):
92
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
93
+ mapping = {0.5: 1, 1.5: 0}
94
+ a = nx.degree_mixing_matrix(
95
+ self.W, weight="weight", normalized=False, mapping=mapping
96
+ )
97
+ np.testing.assert_equal(a, a_result)
98
+
99
+
100
+ class TestAttributeMixingDict(BaseTestAttributeMixing):
101
+ def test_attribute_mixing_dict_undirected(self):
102
+ d = nx.attribute_mixing_dict(self.G, "fish")
103
+ d_result = {
104
+ "one": {"one": 2, "red": 1},
105
+ "two": {"two": 2, "blue": 1},
106
+ "red": {"one": 1},
107
+ "blue": {"two": 1},
108
+ }
109
+ assert d == d_result
110
+
111
+ def test_attribute_mixing_dict_directed(self):
112
+ d = nx.attribute_mixing_dict(self.D, "fish")
113
+ d_result = {
114
+ "one": {"one": 1, "red": 1},
115
+ "two": {"two": 1, "blue": 1},
116
+ "red": {},
117
+ "blue": {},
118
+ }
119
+ assert d == d_result
120
+
121
+ def test_attribute_mixing_dict_multigraph(self):
122
+ d = nx.attribute_mixing_dict(self.M, "fish")
123
+ d_result = {"one": {"one": 4}, "two": {"two": 2}}
124
+ assert d == d_result
125
+
126
+
127
+ class TestAttributeMixingMatrix(BaseTestAttributeMixing):
128
+ def test_attribute_mixing_matrix_undirected(self):
129
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
130
+ a_result = np.array([[2, 0, 1, 0], [0, 2, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])
131
+ a = nx.attribute_mixing_matrix(
132
+ self.G, "fish", mapping=mapping, normalized=False
133
+ )
134
+ np.testing.assert_equal(a, a_result)
135
+ a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping)
136
+ np.testing.assert_equal(a, a_result / a_result.sum())
137
+
138
+ def test_attribute_mixing_matrix_directed(self):
139
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
140
+ a_result = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
141
+ a = nx.attribute_mixing_matrix(
142
+ self.D, "fish", mapping=mapping, normalized=False
143
+ )
144
+ np.testing.assert_equal(a, a_result)
145
+ a = nx.attribute_mixing_matrix(self.D, "fish", mapping=mapping)
146
+ np.testing.assert_equal(a, a_result / a_result.sum())
147
+
148
+ def test_attribute_mixing_matrix_multigraph(self):
149
+ mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
150
+ a_result = np.array([[4, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
151
+ a = nx.attribute_mixing_matrix(
152
+ self.M, "fish", mapping=mapping, normalized=False
153
+ )
154
+ np.testing.assert_equal(a, a_result)
155
+ a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping)
156
+ np.testing.assert_equal(a, a_result / a_result.sum())
157
+
158
+ def test_attribute_mixing_matrix_negative(self):
159
+ mapping = {-2: 0, -3: 1, -4: 2}
160
+ a_result = np.array([[4.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
161
+ a = nx.attribute_mixing_matrix(
162
+ self.N, "margin", mapping=mapping, normalized=False
163
+ )
164
+ np.testing.assert_equal(a, a_result)
165
+ a = nx.attribute_mixing_matrix(self.N, "margin", mapping=mapping)
166
+ np.testing.assert_equal(a, a_result / float(a_result.sum()))
167
+
168
+ def test_attribute_mixing_matrix_float(self):
169
+ mapping = {0.5: 1, 1.5: 0}
170
+ a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
171
+ a = nx.attribute_mixing_matrix(
172
+ self.F, "margin", mapping=mapping, normalized=False
173
+ )
174
+ np.testing.assert_equal(a, a_result)
175
+ a = nx.attribute_mixing_matrix(self.F, "margin", mapping=mapping)
176
+ np.testing.assert_equal(a, a_result / a_result.sum())
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_neighbor_degree.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestAverageNeighbor:
7
+ def test_degree_p4(self):
8
+ G = nx.path_graph(4)
9
+ answer = {0: 2, 1: 1.5, 2: 1.5, 3: 2}
10
+ nd = nx.average_neighbor_degree(G)
11
+ assert nd == answer
12
+
13
+ D = G.to_directed()
14
+ nd = nx.average_neighbor_degree(D)
15
+ assert nd == answer
16
+
17
+ D = nx.DiGraph(G.edges(data=True))
18
+ nd = nx.average_neighbor_degree(D)
19
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
20
+ nd = nx.average_neighbor_degree(D, "in", "out")
21
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
22
+ nd = nx.average_neighbor_degree(D, "out", "in")
23
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
24
+ nd = nx.average_neighbor_degree(D, "in", "in")
25
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
26
+
27
+ def test_degree_p4_weighted(self):
28
+ G = nx.path_graph(4)
29
+ G[1][2]["weight"] = 4
30
+ answer = {0: 2, 1: 1.8, 2: 1.8, 3: 2}
31
+ nd = nx.average_neighbor_degree(G, weight="weight")
32
+ assert nd == answer
33
+
34
+ D = G.to_directed()
35
+ nd = nx.average_neighbor_degree(D, weight="weight")
36
+ assert nd == answer
37
+
38
+ D = nx.DiGraph(G.edges(data=True))
39
+ print(D.edges(data=True))
40
+ nd = nx.average_neighbor_degree(D, weight="weight")
41
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
42
+ nd = nx.average_neighbor_degree(D, "out", "out", weight="weight")
43
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
44
+ nd = nx.average_neighbor_degree(D, "in", "in", weight="weight")
45
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
46
+ nd = nx.average_neighbor_degree(D, "in", "out", weight="weight")
47
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
48
+ nd = nx.average_neighbor_degree(D, "out", "in", weight="weight")
49
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
50
+ nd = nx.average_neighbor_degree(D, source="in+out", weight="weight")
51
+ assert nd == {0: 1.0, 1: 1.0, 2: 0.8, 3: 1.0}
52
+ nd = nx.average_neighbor_degree(D, target="in+out", weight="weight")
53
+ assert nd == {0: 2.0, 1: 2.0, 2: 1.0, 3: 0.0}
54
+
55
+ D = G.to_directed()
56
+ nd = nx.average_neighbor_degree(D, weight="weight")
57
+ assert nd == answer
58
+ nd = nx.average_neighbor_degree(D, source="out", target="out", weight="weight")
59
+ assert nd == answer
60
+
61
+ D = G.to_directed()
62
+ nd = nx.average_neighbor_degree(D, source="in", target="in", weight="weight")
63
+ assert nd == answer
64
+
65
+ def test_degree_k4(self):
66
+ G = nx.complete_graph(4)
67
+ answer = {0: 3, 1: 3, 2: 3, 3: 3}
68
+ nd = nx.average_neighbor_degree(G)
69
+ assert nd == answer
70
+
71
+ D = G.to_directed()
72
+ nd = nx.average_neighbor_degree(D)
73
+ assert nd == answer
74
+
75
+ D = G.to_directed()
76
+ nd = nx.average_neighbor_degree(D)
77
+ assert nd == answer
78
+
79
+ D = G.to_directed()
80
+ nd = nx.average_neighbor_degree(D, source="in", target="in")
81
+ assert nd == answer
82
+
83
+ def test_degree_k4_nodes(self):
84
+ G = nx.complete_graph(4)
85
+ answer = {1: 3.0, 2: 3.0}
86
+ nd = nx.average_neighbor_degree(G, nodes=[1, 2])
87
+ assert nd == answer
88
+
89
+ def test_degree_barrat(self):
90
+ G = nx.star_graph(5)
91
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
92
+ G[0][5]["weight"] = 5
93
+ nd = nx.average_neighbor_degree(G)[5]
94
+ assert nd == 1.8
95
+ nd = nx.average_neighbor_degree(G, weight="weight")[5]
96
+ assert nd == pytest.approx(3.222222, abs=1e-5)
97
+
98
+ def test_error_invalid_source_target(self):
99
+ G = nx.path_graph(4)
100
+ with pytest.raises(nx.NetworkXError):
101
+ nx.average_neighbor_degree(G, "error")
102
+ with pytest.raises(nx.NetworkXError):
103
+ nx.average_neighbor_degree(G, "in", "error")
104
+ G = G.to_directed()
105
+ with pytest.raises(nx.NetworkXError):
106
+ nx.average_neighbor_degree(G, "error")
107
+ with pytest.raises(nx.NetworkXError):
108
+ nx.average_neighbor_degree(G, "in", "error")
janus/lib/python3.10/site-packages/networkx/algorithms/assortativity/tests/test_pairs.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+
3
+ from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
4
+
5
+
6
+ class TestAttributeMixingXY(BaseTestAttributeMixing):
7
+ def test_node_attribute_xy_undirected(self):
8
+ attrxy = sorted(nx.node_attribute_xy(self.G, "fish"))
9
+ attrxy_result = sorted(
10
+ [
11
+ ("one", "one"),
12
+ ("one", "one"),
13
+ ("two", "two"),
14
+ ("two", "two"),
15
+ ("one", "red"),
16
+ ("red", "one"),
17
+ ("blue", "two"),
18
+ ("two", "blue"),
19
+ ]
20
+ )
21
+ assert attrxy == attrxy_result
22
+
23
+ def test_node_attribute_xy_undirected_nodes(self):
24
+ attrxy = sorted(nx.node_attribute_xy(self.G, "fish", nodes=["one", "yellow"]))
25
+ attrxy_result = sorted([])
26
+ assert attrxy == attrxy_result
27
+
28
+ def test_node_attribute_xy_directed(self):
29
+ attrxy = sorted(nx.node_attribute_xy(self.D, "fish"))
30
+ attrxy_result = sorted(
31
+ [("one", "one"), ("two", "two"), ("one", "red"), ("two", "blue")]
32
+ )
33
+ assert attrxy == attrxy_result
34
+
35
+ def test_node_attribute_xy_multigraph(self):
36
+ attrxy = sorted(nx.node_attribute_xy(self.M, "fish"))
37
+ attrxy_result = [
38
+ ("one", "one"),
39
+ ("one", "one"),
40
+ ("one", "one"),
41
+ ("one", "one"),
42
+ ("two", "two"),
43
+ ("two", "two"),
44
+ ]
45
+ assert attrxy == attrxy_result
46
+
47
+ def test_node_attribute_xy_selfloop(self):
48
+ attrxy = sorted(nx.node_attribute_xy(self.S, "fish"))
49
+ attrxy_result = [("one", "one"), ("two", "two")]
50
+ assert attrxy == attrxy_result
51
+
52
+
53
+ class TestDegreeMixingXY(BaseTestDegreeMixing):
54
+ def test_node_degree_xy_undirected(self):
55
+ xy = sorted(nx.node_degree_xy(self.P4))
56
+ xy_result = sorted([(1, 2), (2, 1), (2, 2), (2, 2), (1, 2), (2, 1)])
57
+ assert xy == xy_result
58
+
59
+ def test_node_degree_xy_undirected_nodes(self):
60
+ xy = sorted(nx.node_degree_xy(self.P4, nodes=[0, 1, -1]))
61
+ xy_result = sorted([(1, 2), (2, 1)])
62
+ assert xy == xy_result
63
+
64
+ def test_node_degree_xy_directed(self):
65
+ xy = sorted(nx.node_degree_xy(self.D))
66
+ xy_result = sorted([(2, 1), (2, 3), (1, 3), (1, 3)])
67
+ assert xy == xy_result
68
+
69
+ def test_node_degree_xy_multigraph(self):
70
+ xy = sorted(nx.node_degree_xy(self.M))
71
+ xy_result = sorted(
72
+ [(2, 3), (2, 3), (3, 2), (3, 2), (2, 3), (3, 2), (1, 2), (2, 1)]
73
+ )
74
+ assert xy == xy_result
75
+
76
+ def test_node_degree_xy_selfloop(self):
77
+ xy = sorted(nx.node_degree_xy(self.S))
78
+ xy_result = sorted([(2, 2), (2, 2)])
79
+ assert xy == xy_result
80
+
81
+ def test_node_degree_xy_weighted(self):
82
+ G = nx.Graph()
83
+ G.add_edge(1, 2, weight=7)
84
+ G.add_edge(2, 3, weight=10)
85
+ xy = sorted(nx.node_degree_xy(G, weight="weight"))
86
+ xy_result = sorted([(7, 17), (17, 10), (17, 7), (10, 17)])
87
+ assert xy == xy_result
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from networkx.algorithms.coloring.greedy_coloring import *
2
+ from networkx.algorithms.coloring.equitable_coloring import equitable_color
3
+
4
+ __all__ = ["greedy_color", "equitable_color"]
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/greedy_coloring.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Greedy graph coloring using various strategies.
3
+ """
4
+
5
+ import itertools
6
+ from collections import defaultdict, deque
7
+
8
+ import networkx as nx
9
+ from networkx.utils import arbitrary_element, py_random_state
10
+
11
+ __all__ = [
12
+ "greedy_color",
13
+ "strategy_connected_sequential",
14
+ "strategy_connected_sequential_bfs",
15
+ "strategy_connected_sequential_dfs",
16
+ "strategy_independent_set",
17
+ "strategy_largest_first",
18
+ "strategy_random_sequential",
19
+ "strategy_saturation_largest_first",
20
+ "strategy_smallest_last",
21
+ ]
22
+
23
+
24
+ def strategy_largest_first(G, colors):
25
+ """Returns a list of the nodes of ``G`` in decreasing order by
26
+ degree.
27
+
28
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
29
+
30
+ """
31
+ return sorted(G, key=G.degree, reverse=True)
32
+
33
+
34
+ @py_random_state(2)
35
+ def strategy_random_sequential(G, colors, seed=None):
36
+ """Returns a random permutation of the nodes of ``G`` as a list.
37
+
38
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
39
+
40
+ seed : integer, random_state, or None (default)
41
+ Indicator of random number generation state.
42
+ See :ref:`Randomness<randomness>`.
43
+ """
44
+ nodes = list(G)
45
+ seed.shuffle(nodes)
46
+ return nodes
47
+
48
+
49
+ def strategy_smallest_last(G, colors):
50
+ """Returns a deque of the nodes of ``G``, "smallest" last.
51
+
52
+ Specifically, the degrees of each node are tracked in a bucket queue.
53
+ From this, the node of minimum degree is repeatedly popped from the
54
+ graph, updating its neighbors' degrees.
55
+
56
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
57
+
58
+ This implementation of the strategy runs in $O(n + m)$ time
59
+ (ignoring polylogarithmic factors), where $n$ is the number of nodes
60
+ and $m$ is the number of edges.
61
+
62
+ This strategy is related to :func:`strategy_independent_set`: if we
63
+ interpret each node removed as an independent set of size one, then
64
+ this strategy chooses an independent set of size one instead of a
65
+ maximal independent set.
66
+
67
+ """
68
+ H = G.copy()
69
+ result = deque()
70
+
71
+ # Build initial degree list (i.e. the bucket queue data structure)
72
+ degrees = defaultdict(set) # set(), for fast random-access removals
73
+ lbound = float("inf")
74
+ for node, d in H.degree():
75
+ degrees[d].add(node)
76
+ lbound = min(lbound, d) # Lower bound on min-degree.
77
+
78
+ def find_min_degree():
79
+ # Save time by starting the iterator at `lbound`, not 0.
80
+ # The value that we find will be our new `lbound`, which we set later.
81
+ return next(d for d in itertools.count(lbound) if d in degrees)
82
+
83
+ for _ in G:
84
+ # Pop a min-degree node and add it to the list.
85
+ min_degree = find_min_degree()
86
+ u = degrees[min_degree].pop()
87
+ if not degrees[min_degree]: # Clean up the degree list.
88
+ del degrees[min_degree]
89
+ result.appendleft(u)
90
+
91
+ # Update degrees of removed node's neighbors.
92
+ for v in H[u]:
93
+ degree = H.degree(v)
94
+ degrees[degree].remove(v)
95
+ if not degrees[degree]: # Clean up the degree list.
96
+ del degrees[degree]
97
+ degrees[degree - 1].add(v)
98
+
99
+ # Finally, remove the node.
100
+ H.remove_node(u)
101
+ lbound = min_degree - 1 # Subtract 1 in case of tied neighbors.
102
+
103
+ return result
104
+
105
+
106
+ def _maximal_independent_set(G):
107
+ """Returns a maximal independent set of nodes in ``G`` by repeatedly
108
+ choosing an independent node of minimum degree (with respect to the
109
+ subgraph of unchosen nodes).
110
+
111
+ """
112
+ result = set()
113
+ remaining = set(G)
114
+ while remaining:
115
+ G = G.subgraph(remaining)
116
+ v = min(remaining, key=G.degree)
117
+ result.add(v)
118
+ remaining -= set(G[v]) | {v}
119
+ return result
120
+
121
+
122
+ def strategy_independent_set(G, colors):
123
+ """Uses a greedy independent set removal strategy to determine the
124
+ colors.
125
+
126
+ This function updates ``colors`` **in-place** and return ``None``,
127
+ unlike the other strategy functions in this module.
128
+
129
+ This algorithm repeatedly finds and removes a maximal independent
130
+ set, assigning each node in the set an unused color.
131
+
132
+ ``G`` is a NetworkX graph.
133
+
134
+ This strategy is related to :func:`strategy_smallest_last`: in that
135
+ strategy, an independent set of size one is chosen at each step
136
+ instead of a maximal independent set.
137
+
138
+ """
139
+ remaining_nodes = set(G)
140
+ while len(remaining_nodes) > 0:
141
+ nodes = _maximal_independent_set(G.subgraph(remaining_nodes))
142
+ remaining_nodes -= nodes
143
+ yield from nodes
144
+
145
+
146
+ def strategy_connected_sequential_bfs(G, colors):
147
+ """Returns an iterable over nodes in ``G`` in the order given by a
148
+ breadth-first traversal.
149
+
150
+ The generated sequence has the property that for each node except
151
+ the first, at least one neighbor appeared earlier in the sequence.
152
+
153
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
154
+
155
+ """
156
+ return strategy_connected_sequential(G, colors, "bfs")
157
+
158
+
159
+ def strategy_connected_sequential_dfs(G, colors):
160
+ """Returns an iterable over nodes in ``G`` in the order given by a
161
+ depth-first traversal.
162
+
163
+ The generated sequence has the property that for each node except
164
+ the first, at least one neighbor appeared earlier in the sequence.
165
+
166
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
167
+
168
+ """
169
+ return strategy_connected_sequential(G, colors, "dfs")
170
+
171
+
172
+ def strategy_connected_sequential(G, colors, traversal="bfs"):
173
+ """Returns an iterable over nodes in ``G`` in the order given by a
174
+ breadth-first or depth-first traversal.
175
+
176
+ ``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
177
+ representing depth-first traversal or breadth-first traversal,
178
+ respectively.
179
+
180
+ The generated sequence has the property that for each node except
181
+ the first, at least one neighbor appeared earlier in the sequence.
182
+
183
+ ``G`` is a NetworkX graph. ``colors`` is ignored.
184
+
185
+ """
186
+ if traversal == "bfs":
187
+ traverse = nx.bfs_edges
188
+ elif traversal == "dfs":
189
+ traverse = nx.dfs_edges
190
+ else:
191
+ raise nx.NetworkXError(
192
+ "Please specify one of the strings 'bfs' or"
193
+ " 'dfs' for connected sequential ordering"
194
+ )
195
+ for component in nx.connected_components(G):
196
+ source = arbitrary_element(component)
197
+ # Yield the source node, then all the nodes in the specified
198
+ # traversal order.
199
+ yield source
200
+ for _, end in traverse(G.subgraph(component), source):
201
+ yield end
202
+
203
+
204
+ def strategy_saturation_largest_first(G, colors):
205
+ """Iterates over all the nodes of ``G`` in "saturation order" (also
206
+ known as "DSATUR").
207
+
208
+ ``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
209
+ ``G`` to colors, for those nodes that have already been colored.
210
+
211
+ """
212
+ distinct_colors = {v: set() for v in G}
213
+
214
+ # Add the node color assignments given in colors to the
215
+ # distinct colors set for each neighbor of that node
216
+ for node, color in colors.items():
217
+ for neighbor in G[node]:
218
+ distinct_colors[neighbor].add(color)
219
+
220
+ # Check that the color assignments in colors are valid
221
+ # i.e. no neighboring nodes have the same color
222
+ if len(colors) >= 2:
223
+ for node, color in colors.items():
224
+ if color in distinct_colors[node]:
225
+ raise nx.NetworkXError("Neighboring nodes must have different colors")
226
+
227
+ # If 0 nodes have been colored, simply choose the node of highest degree.
228
+ if not colors:
229
+ node = max(G, key=G.degree)
230
+ yield node
231
+ # Add the color 0 to the distinct colors set for each
232
+ # neighbor of that node.
233
+ for v in G[node]:
234
+ distinct_colors[v].add(0)
235
+
236
+ while len(G) != len(colors):
237
+ # Update the distinct color sets for the neighbors.
238
+ for node, color in colors.items():
239
+ for neighbor in G[node]:
240
+ distinct_colors[neighbor].add(color)
241
+
242
+ # Compute the maximum saturation and the set of nodes that
243
+ # achieve that saturation.
244
+ saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors}
245
+ # Yield the node with the highest saturation, and break ties by
246
+ # degree.
247
+ node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
248
+ yield node
249
+
250
+
251
+ #: Dictionary mapping name of a strategy as a string to the strategy function.
252
+ STRATEGIES = {
253
+ "largest_first": strategy_largest_first,
254
+ "random_sequential": strategy_random_sequential,
255
+ "smallest_last": strategy_smallest_last,
256
+ "independent_set": strategy_independent_set,
257
+ "connected_sequential_bfs": strategy_connected_sequential_bfs,
258
+ "connected_sequential_dfs": strategy_connected_sequential_dfs,
259
+ "connected_sequential": strategy_connected_sequential,
260
+ "saturation_largest_first": strategy_saturation_largest_first,
261
+ "DSATUR": strategy_saturation_largest_first,
262
+ }
263
+
264
+
265
+ @nx._dispatchable
266
+ def greedy_color(G, strategy="largest_first", interchange=False):
267
+ """Color a graph using various strategies of greedy graph coloring.
268
+
269
+ Attempts to color a graph using as few colors as possible, where no
270
+ neighbors of a node can have same color as the node itself. The
271
+ given strategy determines the order in which nodes are colored.
272
+
273
+ The strategies are described in [1]_, and smallest-last is based on
274
+ [2]_.
275
+
276
+ Parameters
277
+ ----------
278
+ G : NetworkX graph
279
+
280
+ strategy : string or function(G, colors)
281
+ A function (or a string representing a function) that provides
282
+ the coloring strategy, by returning nodes in the ordering they
283
+ should be colored. ``G`` is the graph, and ``colors`` is a
284
+ dictionary of the currently assigned colors, keyed by nodes. The
285
+ function must return an iterable over all the nodes in ``G``.
286
+
287
+ If the strategy function is an iterator generator (that is, a
288
+ function with ``yield`` statements), keep in mind that the
289
+ ``colors`` dictionary will be updated after each ``yield``, since
290
+ this function chooses colors greedily.
291
+
292
+ If ``strategy`` is a string, it must be one of the following,
293
+ each of which represents one of the built-in strategy functions.
294
+
295
+ * ``'largest_first'``
296
+ * ``'random_sequential'``
297
+ * ``'smallest_last'``
298
+ * ``'independent_set'``
299
+ * ``'connected_sequential_bfs'``
300
+ * ``'connected_sequential_dfs'``
301
+ * ``'connected_sequential'`` (alias for the previous strategy)
302
+ * ``'saturation_largest_first'``
303
+ * ``'DSATUR'`` (alias for the previous strategy)
304
+
305
+ interchange: bool
306
+ Will use the color interchange algorithm described by [3]_ if set
307
+ to ``True``.
308
+
309
+ Note that ``saturation_largest_first`` and ``independent_set``
310
+ do not work with interchange. Furthermore, if you use
311
+ interchange with your own strategy function, you cannot rely
312
+ on the values in the ``colors`` argument.
313
+
314
+ Returns
315
+ -------
316
+ A dictionary with keys representing nodes and values representing
317
+ corresponding coloring.
318
+
319
+ Examples
320
+ --------
321
+ >>> G = nx.cycle_graph(4)
322
+ >>> d = nx.coloring.greedy_color(G, strategy="largest_first")
323
+ >>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
324
+ True
325
+
326
+ Raises
327
+ ------
328
+ NetworkXPointlessConcept
329
+ If ``strategy`` is ``saturation_largest_first`` or
330
+ ``independent_set`` and ``interchange`` is ``True``.
331
+
332
+ References
333
+ ----------
334
+ .. [1] Adrian Kosowski, and Krzysztof Manuszewski,
335
+ Classical Coloring of Graphs, Graph Colorings, 2-19, 2004.
336
+ ISBN 0-8218-3458-4.
337
+ .. [2] David W. Matula, and Leland L. Beck, "Smallest-last
338
+ ordering and clustering and graph coloring algorithms." *J. ACM* 30,
339
+ 3 (July 1983), 417–427. <https://doi.org/10.1145/2402.322385>
340
+ .. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik,
341
+ Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
342
+ ISBN 0-486-45353-7.
343
+
344
+ """
345
+ if len(G) == 0:
346
+ return {}
347
+ # Determine the strategy provided by the caller.
348
+ strategy = STRATEGIES.get(strategy, strategy)
349
+ if not callable(strategy):
350
+ raise nx.NetworkXError(
351
+ f"strategy must be callable or a valid string. {strategy} not valid."
352
+ )
353
+ # Perform some validation on the arguments before executing any
354
+ # strategy functions.
355
+ if interchange:
356
+ if strategy is strategy_independent_set:
357
+ msg = "interchange cannot be used with independent_set"
358
+ raise nx.NetworkXPointlessConcept(msg)
359
+ if strategy is strategy_saturation_largest_first:
360
+ msg = "interchange cannot be used with" " saturation_largest_first"
361
+ raise nx.NetworkXPointlessConcept(msg)
362
+ colors = {}
363
+ nodes = strategy(G, colors)
364
+ if interchange:
365
+ return _greedy_coloring_with_interchange(G, nodes)
366
+ for u in nodes:
367
+ # Set to keep track of colors of neighbors
368
+ nbr_colors = {colors[v] for v in G[u] if v in colors}
369
+ # Find the first unused color.
370
+ for color in itertools.count():
371
+ if color not in nbr_colors:
372
+ break
373
+ # Assign the new color to the current node.
374
+ colors[u] = color
375
+ return colors
376
+
377
+
378
+ # Tools for coloring with interchanges
379
+ class _Node:
380
+ __slots__ = ["node_id", "color", "adj_list", "adj_color"]
381
+
382
+ def __init__(self, node_id, n):
383
+ self.node_id = node_id
384
+ self.color = -1
385
+ self.adj_list = None
386
+ self.adj_color = [None for _ in range(n)]
387
+
388
+ def __repr__(self):
389
+ return (
390
+ f"Node_id: {self.node_id}, Color: {self.color}, "
391
+ f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})"
392
+ )
393
+
394
+ def assign_color(self, adj_entry, color):
395
+ adj_entry.col_prev = None
396
+ adj_entry.col_next = self.adj_color[color]
397
+ self.adj_color[color] = adj_entry
398
+ if adj_entry.col_next is not None:
399
+ adj_entry.col_next.col_prev = adj_entry
400
+
401
+ def clear_color(self, adj_entry, color):
402
+ if adj_entry.col_prev is None:
403
+ self.adj_color[color] = adj_entry.col_next
404
+ else:
405
+ adj_entry.col_prev.col_next = adj_entry.col_next
406
+ if adj_entry.col_next is not None:
407
+ adj_entry.col_next.col_prev = adj_entry.col_prev
408
+
409
+ def iter_neighbors(self):
410
+ adj_node = self.adj_list
411
+ while adj_node is not None:
412
+ yield adj_node
413
+ adj_node = adj_node.next
414
+
415
+ def iter_neighbors_color(self, color):
416
+ adj_color_node = self.adj_color[color]
417
+ while adj_color_node is not None:
418
+ yield adj_color_node.node_id
419
+ adj_color_node = adj_color_node.col_next
420
+
421
+
422
+ class _AdjEntry:
423
+ __slots__ = ["node_id", "next", "mate", "col_next", "col_prev"]
424
+
425
+ def __init__(self, node_id):
426
+ self.node_id = node_id
427
+ self.next = None
428
+ self.mate = None
429
+ self.col_next = None
430
+ self.col_prev = None
431
+
432
+ def __repr__(self):
433
+ col_next = None if self.col_next is None else self.col_next.node_id
434
+ col_prev = None if self.col_prev is None else self.col_prev.node_id
435
+ return (
436
+ f"Node_id: {self.node_id}, Next: ({self.next}), "
437
+ f"Mate: ({self.mate.node_id}), "
438
+ f"col_next: ({col_next}), col_prev: ({col_prev})"
439
+ )
440
+
441
+
442
+ def _greedy_coloring_with_interchange(G, nodes):
443
+ """Return a coloring for `original_graph` using interchange approach
444
+
445
+ This procedure is an adaption of the algorithm described by [1]_,
446
+ and is an implementation of coloring with interchange. Please be
447
+ advised, that the datastructures used are rather complex because
448
+ they are optimized to minimize the time spent identifying
449
+ subcomponents of the graph, which are possible candidates for color
450
+ interchange.
451
+
452
+ Parameters
453
+ ----------
454
+ G : NetworkX graph
455
+ The graph to be colored
456
+
457
+ nodes : list
458
+ nodes ordered using the strategy of choice
459
+
460
+ Returns
461
+ -------
462
+ dict :
463
+ A dictionary keyed by node to a color value
464
+
465
+ References
466
+ ----------
467
+ .. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik,
468
+ Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
469
+ ISBN 0-486-45353-7.
470
+ """
471
+ n = len(G)
472
+
473
+ graph = {node: _Node(node, n) for node in G}
474
+
475
+ for node1, node2 in G.edges():
476
+ adj_entry1 = _AdjEntry(node2)
477
+ adj_entry2 = _AdjEntry(node1)
478
+ adj_entry1.mate = adj_entry2
479
+ adj_entry2.mate = adj_entry1
480
+ node1_head = graph[node1].adj_list
481
+ adj_entry1.next = node1_head
482
+ graph[node1].adj_list = adj_entry1
483
+ node2_head = graph[node2].adj_list
484
+ adj_entry2.next = node2_head
485
+ graph[node2].adj_list = adj_entry2
486
+
487
+ k = 0
488
+ for node in nodes:
489
+ # Find the smallest possible, unused color
490
+ neighbors = graph[node].iter_neighbors()
491
+ col_used = {graph[adj_node.node_id].color for adj_node in neighbors}
492
+ col_used.discard(-1)
493
+ k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count()))
494
+
495
+ # k1 is now the lowest available color
496
+ if k1 > k:
497
+ connected = True
498
+ visited = set()
499
+ col1 = -1
500
+ col2 = -1
501
+ while connected and col1 < k:
502
+ col1 += 1
503
+ neighbor_cols = graph[node].iter_neighbors_color(col1)
504
+ col1_adj = list(neighbor_cols)
505
+
506
+ col2 = col1
507
+ while connected and col2 < k:
508
+ col2 += 1
509
+ visited = set(col1_adj)
510
+ frontier = list(col1_adj)
511
+ i = 0
512
+ while i < len(frontier):
513
+ search_node = frontier[i]
514
+ i += 1
515
+ col_opp = col2 if graph[search_node].color == col1 else col1
516
+ neighbor_cols = graph[search_node].iter_neighbors_color(col_opp)
517
+
518
+ for neighbor in neighbor_cols:
519
+ if neighbor not in visited:
520
+ visited.add(neighbor)
521
+ frontier.append(neighbor)
522
+
523
+ # Search if node is not adj to any col2 vertex
524
+ connected = (
525
+ len(
526
+ visited.intersection(graph[node].iter_neighbors_color(col2))
527
+ )
528
+ > 0
529
+ )
530
+
531
+ # If connected is false then we can swap !!!
532
+ if not connected:
533
+ # Update all the nodes in the component
534
+ for search_node in visited:
535
+ graph[search_node].color = (
536
+ col2 if graph[search_node].color == col1 else col1
537
+ )
538
+ col2_adj = graph[search_node].adj_color[col2]
539
+ graph[search_node].adj_color[col2] = graph[search_node].adj_color[
540
+ col1
541
+ ]
542
+ graph[search_node].adj_color[col1] = col2_adj
543
+
544
+ # Update all the neighboring nodes
545
+ for search_node in visited:
546
+ col = graph[search_node].color
547
+ col_opp = col1 if col == col2 else col2
548
+ for adj_node in graph[search_node].iter_neighbors():
549
+ if graph[adj_node.node_id].color != col_opp:
550
+ # Direct reference to entry
551
+ adj_mate = adj_node.mate
552
+ graph[adj_node.node_id].clear_color(adj_mate, col_opp)
553
+ graph[adj_node.node_id].assign_color(adj_mate, col)
554
+ k1 = col1
555
+
556
+ # We can color this node color k1
557
+ graph[node].color = k1
558
+ k = max(k1, k)
559
+
560
+ # Update the neighbors of this node
561
+ for adj_node in graph[node].iter_neighbors():
562
+ adj_mate = adj_node.mate
563
+ graph[adj_node.node_id].assign_color(adj_mate, k1)
564
+
565
+ return {node.node_id: node.color for node in graph.values()}
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/networkx/algorithms/coloring/tests/__pycache__/test_coloring.cpython-310.pyc ADDED
Binary file (17.9 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (442 Bytes). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/connectivity.cpython-310.pyc ADDED
Binary file (26.7 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/cuts.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/disjoint_paths.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_augmentation.cpython-310.pyc ADDED
Binary file (37.8 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/edge_kcomponents.cpython-310.pyc ADDED
Binary file (18.1 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcomponents.cpython-310.pyc ADDED
Binary file (7.91 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/kcutsets.cpython-310.pyc ADDED
Binary file (6.31 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/stoerwagner.cpython-310.pyc ADDED
Binary file (4.49 kB). View file
 
janus/lib/python3.10/site-packages/networkx/algorithms/connectivity/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.17 kB). View file