ZTWHHH commited on
Commit
9f0c790
·
verified ·
1 Parent(s): f60f8a9

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. evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gl1.gpickle.bz2 +3 -0
  2. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__init__.py +34 -0
  3. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/atlas.py +180 -0
  4. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/cographs.py +68 -0
  5. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/community.py +1070 -0
  6. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/degree_seq.py +867 -0
  7. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/ego.py +66 -0
  8. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/expanders.py +474 -0
  9. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/geometric.py +1048 -0
  10. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/internet_as_graphs.py +441 -0
  11. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/intersection.py +125 -0
  12. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/joint_degree_seq.py +664 -0
  13. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/lattice.py +367 -0
  14. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/line.py +500 -0
  15. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/mycielski.py +110 -0
  16. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/random_graphs.py +1400 -0
  17. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/stochastic.py +54 -0
  18. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__init__.py +0 -0
  19. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_atlas.py +75 -0
  20. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_cographs.py +18 -0
  21. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_community.py +362 -0
  22. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_degree_seq.py +230 -0
  23. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_intersection.py +28 -0
  24. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_mycielski.py +30 -0
  25. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_small.py +208 -0
  26. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_spectral_graph_forge.py +49 -0
  27. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_sudoku.py +92 -0
  28. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/time_series.py +74 -0
  29. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/trees.py +1071 -0
  30. evalkit_tf446/lib/python3.10/site-packages/networkx/generators/triads.py +94 -0
  31. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  32. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_all_random_functions.cpython-310.pyc +0 -0
  33. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert.cpython-310.pyc +0 -0
  34. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_numpy.cpython-310.pyc +0 -0
  35. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_pandas.cpython-310.pyc +0 -0
  36. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_scipy.cpython-310.pyc +0 -0
  37. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_exceptions.cpython-310.pyc +0 -0
  38. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_import.cpython-310.pyc +0 -0
  39. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_lazy_imports.cpython-310.pyc +0 -0
  40. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_relabel.cpython-310.pyc +0 -0
  41. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_convert_numpy.py +532 -0
  42. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_convert_pandas.py +349 -0
  43. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_convert_scipy.py +282 -0
  44. evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_import.py +11 -0
  45. evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__init__.py +8 -0
  46. evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  47. evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/backends.cpython-310.pyc +0 -0
  48. evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/configs.cpython-310.pyc +0 -0
  49. evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/decorators.cpython-310.pyc +0 -0
  50. evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/heaps.cpython-310.pyc +0 -0
evalkit_tf446/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gl1.gpickle.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf8f81ceb5eaaee1621aa60b892d83e596a6173f6f6517359b679ff3daa1b0f8
3
+ size 44623
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A package for generating various graphs in networkx.
3
+
4
+ """
5
+
6
+ from networkx.generators.atlas import *
7
+ from networkx.generators.classic import *
8
+ from networkx.generators.cographs import *
9
+ from networkx.generators.community import *
10
+ from networkx.generators.degree_seq import *
11
+ from networkx.generators.directed import *
12
+ from networkx.generators.duplication import *
13
+ from networkx.generators.ego import *
14
+ from networkx.generators.expanders import *
15
+ from networkx.generators.geometric import *
16
+ from networkx.generators.harary_graph import *
17
+ from networkx.generators.internet_as_graphs import *
18
+ from networkx.generators.intersection import *
19
+ from networkx.generators.interval_graph import *
20
+ from networkx.generators.joint_degree_seq import *
21
+ from networkx.generators.lattice import *
22
+ from networkx.generators.line import *
23
+ from networkx.generators.mycielski import *
24
+ from networkx.generators.nonisomorphic_trees import *
25
+ from networkx.generators.random_clustered import *
26
+ from networkx.generators.random_graphs import *
27
+ from networkx.generators.small import *
28
+ from networkx.generators.social import *
29
+ from networkx.generators.spectral_graph_forge import *
30
+ from networkx.generators.stochastic import *
31
+ from networkx.generators.sudoku import *
32
+ from networkx.generators.time_series import *
33
+ from networkx.generators.trees import *
34
+ from networkx.generators.triads import *
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/atlas.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for the small graph atlas.
3
+ """
4
+
5
+ import gzip
6
+ import importlib.resources
7
+ import os
8
+ import os.path
9
+ from itertools import islice
10
+
11
+ import networkx as nx
12
+
13
+ __all__ = ["graph_atlas", "graph_atlas_g"]
14
+
15
+ #: The total number of graphs in the atlas.
16
+ #:
17
+ #: The graphs are labeled starting from 0 and extending to (but not
18
+ #: including) this number.
19
+ NUM_GRAPHS = 1253
20
+
21
+ #: The path to the data file containing the graph edge lists.
22
+ #:
23
+ #: This is the absolute path of the gzipped text file containing the
24
+ #: edge list for each graph in the atlas. The file contains one entry
25
+ #: per graph in the atlas, in sequential order, starting from graph
26
+ #: number 0 and extending through graph number 1252 (see
27
+ #: :data:`NUM_GRAPHS`). Each entry looks like
28
+ #:
29
+ #: .. sourcecode:: text
30
+ #:
31
+ #: GRAPH 6
32
+ #: NODES 3
33
+ #: 0 1
34
+ #: 0 2
35
+ #:
36
+ #: where the first two lines are the graph's index in the atlas and the
37
+ #: number of nodes in the graph, and the remaining lines are the edge
38
+ #: list.
39
+ #:
40
+ #: This file was generated from a Python list of graphs via code like
41
+ #: the following::
42
+ #:
43
+ #: import gzip
44
+ #: from networkx.generators.atlas import graph_atlas_g
45
+ #: from networkx.readwrite.edgelist import write_edgelist
46
+ #:
47
+ #: with gzip.open('atlas.dat.gz', 'wb') as f:
48
+ #: for i, G in enumerate(graph_atlas_g()):
49
+ #: f.write(bytes(f'GRAPH {i}\n', encoding='utf-8'))
50
+ #: f.write(bytes(f'NODES {len(G)}\n', encoding='utf-8'))
51
+ #: write_edgelist(G, f, data=False)
52
+ #:
53
+
54
+ # Path to the atlas file
55
+ ATLAS_FILE = importlib.resources.files("networkx.generators") / "atlas.dat.gz"
56
+
57
+
58
+ def _generate_graphs():
59
+ """Sequentially read the file containing the edge list data for the
60
+ graphs in the atlas and generate the graphs one at a time.
61
+
62
+ This function reads the file given in :data:`.ATLAS_FILE`.
63
+
64
+ """
65
+ with gzip.open(ATLAS_FILE, "rb") as f:
66
+ line = f.readline()
67
+ while line and line.startswith(b"GRAPH"):
68
+ # The first two lines of each entry tell us the index of the
69
+ # graph in the list and the number of nodes in the graph.
70
+ # They look like this:
71
+ #
72
+ # GRAPH 3
73
+ # NODES 2
74
+ #
75
+ graph_index = int(line[6:].rstrip())
76
+ line = f.readline()
77
+ num_nodes = int(line[6:].rstrip())
78
+ # The remaining lines contain the edge list, until the next
79
+ # GRAPH line (or until the end of the file).
80
+ edgelist = []
81
+ line = f.readline()
82
+ while line and not line.startswith(b"GRAPH"):
83
+ edgelist.append(line.rstrip())
84
+ line = f.readline()
85
+ G = nx.Graph()
86
+ G.name = f"G{graph_index}"
87
+ G.add_nodes_from(range(num_nodes))
88
+ G.add_edges_from(tuple(map(int, e.split())) for e in edgelist)
89
+ yield G
90
+
91
+
92
+ @nx._dispatchable(graphs=None, returns_graph=True)
93
+ def graph_atlas(i):
94
+ """Returns graph number `i` from the Graph Atlas.
95
+
96
+ For more information, see :func:`.graph_atlas_g`.
97
+
98
+ Parameters
99
+ ----------
100
+ i : int
101
+ The index of the graph from the atlas to get. The graph at index
102
+ 0 is assumed to be the null graph.
103
+
104
+ Returns
105
+ -------
106
+ list
107
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
108
+ corresponding to the graph *i* in the Graph Atlas.
109
+
110
+ See also
111
+ --------
112
+ graph_atlas_g
113
+
114
+ Notes
115
+ -----
116
+ The time required by this function increases linearly with the
117
+ argument `i`, since it reads a large file sequentially in order to
118
+ generate the graph [1]_.
119
+
120
+ References
121
+ ----------
122
+ .. [1] Ronald C. Read and Robin J. Wilson, *An Atlas of Graphs*.
123
+ Oxford University Press, 1998.
124
+
125
+ """
126
+ if not (0 <= i < NUM_GRAPHS):
127
+ raise ValueError(f"index must be between 0 and {NUM_GRAPHS}")
128
+ return next(islice(_generate_graphs(), i, None))
129
+
130
+
131
+ @nx._dispatchable(graphs=None, returns_graph=True)
132
+ def graph_atlas_g():
133
+ """Returns the list of all graphs with up to seven nodes named in the
134
+ Graph Atlas.
135
+
136
+ The graphs are listed in increasing order by
137
+
138
+ 1. number of nodes,
139
+ 2. number of edges,
140
+ 3. degree sequence (for example 111223 < 112222),
141
+ 4. number of automorphisms,
142
+
143
+ in that order, with three exceptions as described in the *Notes*
144
+ section below. This causes the list to correspond with the index of
145
+ the graphs in the Graph Atlas [atlas]_, with the first graph,
146
+ ``G[0]``, being the null graph.
147
+
148
+ Returns
149
+ -------
150
+ list
151
+ A list of :class:`~networkx.Graph` objects, the one at index *i*
152
+ corresponding to the graph *i* in the Graph Atlas.
153
+
154
+ See also
155
+ --------
156
+ graph_atlas
157
+
158
+ Notes
159
+ -----
160
+ This function may be expensive in both time and space, since it
161
+ reads a large file sequentially in order to populate the list.
162
+
163
+ Although the NetworkX atlas functions match the order of graphs
164
+ given in the "Atlas of Graphs" book, there are (at least) three
165
+ errors in the ordering described in the book. The following three
166
+ pairs of nodes violate the lexicographically nondecreasing sorted
167
+ degree sequence rule:
168
+
169
+ - graphs 55 and 56 with degree sequences 001111 and 000112,
170
+ - graphs 1007 and 1008 with degree sequences 3333444 and 3333336,
171
+ - graphs 1012 and 1213 with degree sequences 1244555 and 1244456.
172
+
173
+ References
174
+ ----------
175
+ .. [atlas] Ronald C. Read and Robin J. Wilson,
176
+ *An Atlas of Graphs*.
177
+ Oxford University Press, 1998.
178
+
179
+ """
180
+ return list(_generate_graphs())
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/cographs.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Generators for cographs
2
+
3
+ A cograph is a graph containing no path on four vertices.
4
+ Cographs or $P_4$-free graphs can be obtained from a single vertex
5
+ by disjoint union and complementation operations.
6
+
7
+ References
8
+ ----------
9
+ .. [0] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
10
+ "Complement reducible graphs",
11
+ Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
12
+ ISSN 0166-218X.
13
+ """
14
+
15
+ import networkx as nx
16
+ from networkx.utils import py_random_state
17
+
18
+ __all__ = ["random_cograph"]
19
+
20
+
21
+ @py_random_state(1)
22
+ @nx._dispatchable(graphs=None, returns_graph=True)
23
+ def random_cograph(n, seed=None):
24
+ r"""Returns a random cograph with $2 ^ n$ nodes.
25
+
26
+ A cograph is a graph containing no path on four vertices.
27
+ Cographs or $P_4$-free graphs can be obtained from a single vertex
28
+ by disjoint union and complementation operations.
29
+
30
+ This generator starts off from a single vertex and performs disjoint
31
+ union and full join operations on itself.
32
+ The decision on which operation will take place is random.
33
+
34
+ Parameters
35
+ ----------
36
+ n : int
37
+ The order of the cograph.
38
+ seed : integer, random_state, or None (default)
39
+ Indicator of random number generation state.
40
+ See :ref:`Randomness<randomness>`.
41
+
42
+ Returns
43
+ -------
44
+ G : A random graph containing no path on four vertices.
45
+
46
+ See Also
47
+ --------
48
+ full_join
49
+ union
50
+
51
+ References
52
+ ----------
53
+ .. [1] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
54
+ "Complement reducible graphs",
55
+ Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
56
+ ISSN 0166-218X.
57
+ """
58
+ R = nx.empty_graph(1)
59
+
60
+ for i in range(n):
61
+ RR = nx.relabel_nodes(R.copy(), lambda x: x + len(R))
62
+
63
+ if seed.randint(0, 1) == 0:
64
+ R = nx.full_join(R, RR)
65
+ else:
66
+ R = nx.disjoint_union(R, RR)
67
+
68
+ return R
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/community.py ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for classes of graphs used in studying social networks."""
2
+
3
+ import itertools
4
+ import math
5
+
6
+ import networkx as nx
7
+ from networkx.utils import py_random_state
8
+
9
+ __all__ = [
10
+ "caveman_graph",
11
+ "connected_caveman_graph",
12
+ "relaxed_caveman_graph",
13
+ "random_partition_graph",
14
+ "planted_partition_graph",
15
+ "gaussian_random_partition_graph",
16
+ "ring_of_cliques",
17
+ "windmill_graph",
18
+ "stochastic_block_model",
19
+ "LFR_benchmark_graph",
20
+ ]
21
+
22
+
23
+ @nx._dispatchable(graphs=None, returns_graph=True)
24
+ def caveman_graph(l, k):
25
+ """Returns a caveman graph of `l` cliques of size `k`.
26
+
27
+ Parameters
28
+ ----------
29
+ l : int
30
+ Number of cliques
31
+ k : int
32
+ Size of cliques
33
+
34
+ Returns
35
+ -------
36
+ G : NetworkX Graph
37
+ caveman graph
38
+
39
+ Notes
40
+ -----
41
+ This returns an undirected graph, it can be converted to a directed
42
+ graph using :func:`nx.to_directed`, or a multigraph using
43
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
44
+ described in [1]_ and it is unclear which of the directed
45
+ generalizations is most useful.
46
+
47
+ Examples
48
+ --------
49
+ >>> G = nx.caveman_graph(3, 3)
50
+
51
+ See also
52
+ --------
53
+
54
+ connected_caveman_graph
55
+
56
+ References
57
+ ----------
58
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
59
+ Amer. J. Soc. 105, 493-527, 1999.
60
+ """
61
+ # l disjoint cliques of size k
62
+ G = nx.empty_graph(l * k)
63
+ if k > 1:
64
+ for start in range(0, l * k, k):
65
+ edges = itertools.combinations(range(start, start + k), 2)
66
+ G.add_edges_from(edges)
67
+ return G
68
+
69
+
70
+ @nx._dispatchable(graphs=None, returns_graph=True)
71
+ def connected_caveman_graph(l, k):
72
+ """Returns a connected caveman graph of `l` cliques of size `k`.
73
+
74
+ The connected caveman graph is formed by creating `n` cliques of size
75
+ `k`, then a single edge in each clique is rewired to a node in an
76
+ adjacent clique.
77
+
78
+ Parameters
79
+ ----------
80
+ l : int
81
+ number of cliques
82
+ k : int
83
+ size of cliques (k at least 2 or NetworkXError is raised)
84
+
85
+ Returns
86
+ -------
87
+ G : NetworkX Graph
88
+ connected caveman graph
89
+
90
+ Raises
91
+ ------
92
+ NetworkXError
93
+ If the size of cliques `k` is smaller than 2.
94
+
95
+ Notes
96
+ -----
97
+ This returns an undirected graph, it can be converted to a directed
98
+ graph using :func:`nx.to_directed`, or a multigraph using
99
+ ``nx.MultiGraph(nx.caveman_graph(l, k))``. Only the undirected version is
100
+ described in [1]_ and it is unclear which of the directed
101
+ generalizations is most useful.
102
+
103
+ Examples
104
+ --------
105
+ >>> G = nx.connected_caveman_graph(3, 3)
106
+
107
+ References
108
+ ----------
109
+ .. [1] Watts, D. J. 'Networks, Dynamics, and the Small-World Phenomenon.'
110
+ Amer. J. Soc. 105, 493-527, 1999.
111
+ """
112
+ if k < 2:
113
+ raise nx.NetworkXError(
114
+ "The size of cliques in a connected caveman graph must be at least 2."
115
+ )
116
+
117
+ G = nx.caveman_graph(l, k)
118
+ for start in range(0, l * k, k):
119
+ G.remove_edge(start, start + 1)
120
+ G.add_edge(start, (start - 1) % (l * k))
121
+ return G
122
+
123
+
124
+ @py_random_state(3)
125
+ @nx._dispatchable(graphs=None, returns_graph=True)
126
+ def relaxed_caveman_graph(l, k, p, seed=None):
127
+ """Returns a relaxed caveman graph.
128
+
129
+ A relaxed caveman graph starts with `l` cliques of size `k`. Edges are
130
+ then randomly rewired with probability `p` to link different cliques.
131
+
132
+ Parameters
133
+ ----------
134
+ l : int
135
+ Number of groups
136
+ k : int
137
+ Size of cliques
138
+ p : float
139
+ Probability of rewiring each edge.
140
+ seed : integer, random_state, or None (default)
141
+ Indicator of random number generation state.
142
+ See :ref:`Randomness<randomness>`.
143
+
144
+ Returns
145
+ -------
146
+ G : NetworkX Graph
147
+ Relaxed Caveman Graph
148
+
149
+ Raises
150
+ ------
151
+ NetworkXError
152
+ If p is not in [0,1]
153
+
154
+ Examples
155
+ --------
156
+ >>> G = nx.relaxed_caveman_graph(2, 3, 0.1, seed=42)
157
+
158
+ References
159
+ ----------
160
+ .. [1] Santo Fortunato, Community Detection in Graphs,
161
+ Physics Reports Volume 486, Issues 3-5, February 2010, Pages 75-174.
162
+ https://arxiv.org/abs/0906.0612
163
+ """
164
+ G = nx.caveman_graph(l, k)
165
+ nodes = list(G)
166
+ for u, v in G.edges():
167
+ if seed.random() < p: # rewire the edge
168
+ x = seed.choice(nodes)
169
+ if G.has_edge(u, x):
170
+ continue
171
+ G.remove_edge(u, v)
172
+ G.add_edge(u, x)
173
+ return G
174
+
175
+
176
+ @py_random_state(3)
177
+ @nx._dispatchable(graphs=None, returns_graph=True)
178
+ def random_partition_graph(sizes, p_in, p_out, seed=None, directed=False):
179
+ """Returns the random partition graph with a partition of sizes.
180
+
181
+ A partition graph is a graph of communities with sizes defined by
182
+ s in sizes. Nodes in the same group are connected with probability
183
+ p_in and nodes of different groups are connected with probability
184
+ p_out.
185
+
186
+ Parameters
187
+ ----------
188
+ sizes : list of ints
189
+ Sizes of groups
190
+ p_in : float
191
+ probability of edges with in groups
192
+ p_out : float
193
+ probability of edges between groups
194
+ directed : boolean optional, default=False
195
+ Whether to create a directed graph
196
+ seed : integer, random_state, or None (default)
197
+ Indicator of random number generation state.
198
+ See :ref:`Randomness<randomness>`.
199
+
200
+ Returns
201
+ -------
202
+ G : NetworkX Graph or DiGraph
203
+ random partition graph of size sum(gs)
204
+
205
+ Raises
206
+ ------
207
+ NetworkXError
208
+ If p_in or p_out is not in [0,1]
209
+
210
+ Examples
211
+ --------
212
+ >>> G = nx.random_partition_graph([10, 10, 10], 0.25, 0.01)
213
+ >>> len(G)
214
+ 30
215
+ >>> partition = G.graph["partition"]
216
+ >>> len(partition)
217
+ 3
218
+
219
+ Notes
220
+ -----
221
+ This is a generalization of the planted-l-partition described in
222
+ [1]_. It allows for the creation of groups of any size.
223
+
224
+ The partition is store as a graph attribute 'partition'.
225
+
226
+ References
227
+ ----------
228
+ .. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
229
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
230
+ """
231
+ # Use geometric method for O(n+m) complexity algorithm
232
+ # partition = nx.community_sets(nx.get_node_attributes(G, 'affiliation'))
233
+ if not 0.0 <= p_in <= 1.0:
234
+ raise nx.NetworkXError("p_in must be in [0,1]")
235
+ if not 0.0 <= p_out <= 1.0:
236
+ raise nx.NetworkXError("p_out must be in [0,1]")
237
+
238
+ # create connection matrix
239
+ num_blocks = len(sizes)
240
+ p = [[p_out for s in range(num_blocks)] for r in range(num_blocks)]
241
+ for r in range(num_blocks):
242
+ p[r][r] = p_in
243
+
244
+ return stochastic_block_model(
245
+ sizes,
246
+ p,
247
+ nodelist=None,
248
+ seed=seed,
249
+ directed=directed,
250
+ selfloops=False,
251
+ sparse=True,
252
+ )
253
+
254
+
255
+ @py_random_state(4)
256
+ @nx._dispatchable(graphs=None, returns_graph=True)
257
+ def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
258
+ """Returns the planted l-partition graph.
259
+
260
+ This model partitions a graph with n=l*k vertices in
261
+ l groups with k vertices each. Vertices of the same
262
+ group are linked with a probability p_in, and vertices
263
+ of different groups are linked with probability p_out.
264
+
265
+ Parameters
266
+ ----------
267
+ l : int
268
+ Number of groups
269
+ k : int
270
+ Number of vertices in each group
271
+ p_in : float
272
+ probability of connecting vertices within a group
273
+ p_out : float
274
+ probability of connected vertices between groups
275
+ seed : integer, random_state, or None (default)
276
+ Indicator of random number generation state.
277
+ See :ref:`Randomness<randomness>`.
278
+ directed : bool,optional (default=False)
279
+ If True return a directed graph
280
+
281
+ Returns
282
+ -------
283
+ G : NetworkX Graph or DiGraph
284
+ planted l-partition graph
285
+
286
+ Raises
287
+ ------
288
+ NetworkXError
289
+ If `p_in`, `p_out` are not in `[0, 1]`
290
+
291
+ Examples
292
+ --------
293
+ >>> G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42)
294
+
295
+ See Also
296
+ --------
297
+ random_partition_model
298
+
299
+ References
300
+ ----------
301
+ .. [1] A. Condon, R.M. Karp, Algorithms for graph partitioning
302
+ on the planted partition model,
303
+ Random Struct. Algor. 18 (2001) 116-140.
304
+
305
+ .. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
306
+ Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
307
+ """
308
+ return random_partition_graph([k] * l, p_in, p_out, seed=seed, directed=directed)
309
+
310
+
311
+ @py_random_state(6)
312
+ @nx._dispatchable(graphs=None, returns_graph=True)
313
+ def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=None):
314
+ """Generate a Gaussian random partition graph.
315
+
316
+ A Gaussian random partition graph is created by creating k partitions
317
+ each with a size drawn from a normal distribution with mean s and variance
318
+ s/v. Nodes are connected within clusters with probability p_in and
319
+ between clusters with probability p_out[1]
320
+
321
+ Parameters
322
+ ----------
323
+ n : int
324
+ Number of nodes in the graph
325
+ s : float
326
+ Mean cluster size
327
+ v : float
328
+ Shape parameter. The variance of cluster size distribution is s/v.
329
+ p_in : float
330
+ Probability of intra cluster connection.
331
+ p_out : float
332
+ Probability of inter cluster connection.
333
+ directed : boolean, optional default=False
334
+ Whether to create a directed graph or not
335
+ seed : integer, random_state, or None (default)
336
+ Indicator of random number generation state.
337
+ See :ref:`Randomness<randomness>`.
338
+
339
+ Returns
340
+ -------
341
+ G : NetworkX Graph or DiGraph
342
+ gaussian random partition graph
343
+
344
+ Raises
345
+ ------
346
+ NetworkXError
347
+ If s is > n
348
+ If p_in or p_out is not in [0,1]
349
+
350
+ Notes
351
+ -----
352
+ Note the number of partitions is dependent on s,v and n, and that the
353
+ last partition may be considerably smaller, as it is sized to simply
354
+ fill out the nodes [1]
355
+
356
+ See Also
357
+ --------
358
+ random_partition_graph
359
+
360
+ Examples
361
+ --------
362
+ >>> G = nx.gaussian_random_partition_graph(100, 10, 10, 0.25, 0.1)
363
+ >>> len(G)
364
+ 100
365
+
366
+ References
367
+ ----------
368
+ .. [1] Ulrik Brandes, Marco Gaertler, Dorothea Wagner,
369
+ Experiments on Graph Clustering Algorithms,
370
+ In the proceedings of the 11th Europ. Symp. Algorithms, 2003.
371
+ """
372
+ if s > n:
373
+ raise nx.NetworkXError("s must be <= n")
374
+ assigned = 0
375
+ sizes = []
376
+ while True:
377
+ size = int(seed.gauss(s, s / v + 0.5))
378
+ if size < 1: # how to handle 0 or negative sizes?
379
+ continue
380
+ if assigned + size >= n:
381
+ sizes.append(n - assigned)
382
+ break
383
+ assigned += size
384
+ sizes.append(size)
385
+ return random_partition_graph(sizes, p_in, p_out, seed=seed, directed=directed)
386
+
387
+
388
+ @nx._dispatchable(graphs=None, returns_graph=True)
389
+ def ring_of_cliques(num_cliques, clique_size):
390
+ """Defines a "ring of cliques" graph.
391
+
392
+ A ring of cliques graph is consisting of cliques, connected through single
393
+ links. Each clique is a complete graph.
394
+
395
+ Parameters
396
+ ----------
397
+ num_cliques : int
398
+ Number of cliques
399
+ clique_size : int
400
+ Size of cliques
401
+
402
+ Returns
403
+ -------
404
+ G : NetworkX Graph
405
+ ring of cliques graph
406
+
407
+ Raises
408
+ ------
409
+ NetworkXError
410
+ If the number of cliques is lower than 2 or
411
+ if the size of cliques is smaller than 2.
412
+
413
+ Examples
414
+ --------
415
+ >>> G = nx.ring_of_cliques(8, 4)
416
+
417
+ See Also
418
+ --------
419
+ connected_caveman_graph
420
+
421
+ Notes
422
+ -----
423
+ The `connected_caveman_graph` graph removes a link from each clique to
424
+ connect it with the next clique. Instead, the `ring_of_cliques` graph
425
+ simply adds the link without removing any link from the cliques.
426
+ """
427
+ if num_cliques < 2:
428
+ raise nx.NetworkXError("A ring of cliques must have at least two cliques")
429
+ if clique_size < 2:
430
+ raise nx.NetworkXError("The cliques must have at least two nodes")
431
+
432
+ G = nx.Graph()
433
+ for i in range(num_cliques):
434
+ edges = itertools.combinations(
435
+ range(i * clique_size, i * clique_size + clique_size), 2
436
+ )
437
+ G.add_edges_from(edges)
438
+ G.add_edge(
439
+ i * clique_size + 1, (i + 1) * clique_size % (num_cliques * clique_size)
440
+ )
441
+ return G
442
+
443
+
444
+ @nx._dispatchable(graphs=None, returns_graph=True)
445
+ def windmill_graph(n, k):
446
+ """Generate a windmill graph.
447
+ A windmill graph is a graph of `n` cliques each of size `k` that are all
448
+ joined at one node.
449
+ It can be thought of as taking a disjoint union of `n` cliques of size `k`,
450
+ selecting one point from each, and contracting all of the selected points.
451
+ Alternatively, one could generate `n` cliques of size `k-1` and one node
452
+ that is connected to all other nodes in the graph.
453
+
454
+ Parameters
455
+ ----------
456
+ n : int
457
+ Number of cliques
458
+ k : int
459
+ Size of cliques
460
+
461
+ Returns
462
+ -------
463
+ G : NetworkX Graph
464
+ windmill graph with n cliques of size k
465
+
466
+ Raises
467
+ ------
468
+ NetworkXError
469
+ If the number of cliques is less than two
470
+ If the size of the cliques are less than two
471
+
472
+ Examples
473
+ --------
474
+ >>> G = nx.windmill_graph(4, 5)
475
+
476
+ Notes
477
+ -----
478
+ The node labeled `0` will be the node connected to all other nodes.
479
+ Note that windmill graphs are usually denoted `Wd(k,n)`, so the parameters
480
+ are in the opposite order as the parameters of this method.
481
+ """
482
+ if n < 2:
483
+ msg = "A windmill graph must have at least two cliques"
484
+ raise nx.NetworkXError(msg)
485
+ if k < 2:
486
+ raise nx.NetworkXError("The cliques must have at least two nodes")
487
+
488
+ G = nx.disjoint_union_all(
489
+ itertools.chain(
490
+ [nx.complete_graph(k)], (nx.complete_graph(k - 1) for _ in range(n - 1))
491
+ )
492
+ )
493
+ G.add_edges_from((0, i) for i in range(k, G.number_of_nodes()))
494
+ return G
495
+
496
+
497
+ @py_random_state(3)
498
+ @nx._dispatchable(graphs=None, returns_graph=True)
499
+ def stochastic_block_model(
500
+ sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True
501
+ ):
502
+ """Returns a stochastic block model graph.
503
+
504
+ This model partitions the nodes in blocks of arbitrary sizes, and places
505
+ edges between pairs of nodes independently, with a probability that depends
506
+ on the blocks.
507
+
508
+ Parameters
509
+ ----------
510
+ sizes : list of ints
511
+ Sizes of blocks
512
+ p : list of list of floats
513
+ Element (r,s) gives the density of edges going from the nodes
514
+ of group r to nodes of group s.
515
+ p must match the number of groups (len(sizes) == len(p)),
516
+ and it must be symmetric if the graph is undirected.
517
+ nodelist : list, optional
518
+ The block tags are assigned according to the node identifiers
519
+ in nodelist. If nodelist is None, then the ordering is the
520
+ range [0,sum(sizes)-1].
521
+ seed : integer, random_state, or None (default)
522
+ Indicator of random number generation state.
523
+ See :ref:`Randomness<randomness>`.
524
+ directed : boolean optional, default=False
525
+ Whether to create a directed graph or not.
526
+ selfloops : boolean optional, default=False
527
+ Whether to include self-loops or not.
528
+ sparse: boolean optional, default=True
529
+ Use the sparse heuristic to speed up the generator.
530
+
531
+ Returns
532
+ -------
533
+ g : NetworkX Graph or DiGraph
534
+ Stochastic block model graph of size sum(sizes)
535
+
536
+ Raises
537
+ ------
538
+ NetworkXError
539
+ If probabilities are not in [0,1].
540
+ If the probability matrix is not square (directed case).
541
+ If the probability matrix is not symmetric (undirected case).
542
+ If the sizes list does not match nodelist or the probability matrix.
543
+ If nodelist contains duplicate.
544
+
545
+ Examples
546
+ --------
547
+ >>> sizes = [75, 75, 300]
548
+ >>> probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
549
+ >>> g = nx.stochastic_block_model(sizes, probs, seed=0)
550
+ >>> len(g)
551
+ 450
552
+ >>> H = nx.quotient_graph(g, g.graph["partition"], relabel=True)
553
+ >>> for v in H.nodes(data=True):
554
+ ... print(round(v[1]["density"], 3))
555
+ 0.245
556
+ 0.348
557
+ 0.405
558
+ >>> for v in H.edges(data=True):
559
+ ... print(round(1.0 * v[2]["weight"] / (sizes[v[0]] * sizes[v[1]]), 3))
560
+ 0.051
561
+ 0.022
562
+ 0.07
563
+
564
+ See Also
565
+ --------
566
+ random_partition_graph
567
+ planted_partition_graph
568
+ gaussian_random_partition_graph
569
+ gnp_random_graph
570
+
571
+ References
572
+ ----------
573
+ .. [1] Holland, P. W., Laskey, K. B., & Leinhardt, S.,
574
+ "Stochastic blockmodels: First steps",
575
+ Social networks, 5(2), 109-137, 1983.
576
+ """
577
+ # Check if dimensions match
578
+ if len(sizes) != len(p):
579
+ raise nx.NetworkXException("'sizes' and 'p' do not match.")
580
+ # Check for probability symmetry (undirected) and shape (directed)
581
+ for row in p:
582
+ if len(p) != len(row):
583
+ raise nx.NetworkXException("'p' must be a square matrix.")
584
+ if not directed:
585
+ p_transpose = [list(i) for i in zip(*p)]
586
+ for i in zip(p, p_transpose):
587
+ for j in zip(i[0], i[1]):
588
+ if abs(j[0] - j[1]) > 1e-08:
589
+ raise nx.NetworkXException("'p' must be symmetric.")
590
+ # Check for probability range
591
+ for row in p:
592
+ for prob in row:
593
+ if prob < 0 or prob > 1:
594
+ raise nx.NetworkXException("Entries of 'p' not in [0,1].")
595
+ # Check for nodelist consistency
596
+ if nodelist is not None:
597
+ if len(nodelist) != sum(sizes):
598
+ raise nx.NetworkXException("'nodelist' and 'sizes' do not match.")
599
+ if len(nodelist) != len(set(nodelist)):
600
+ raise nx.NetworkXException("nodelist contains duplicate.")
601
+ else:
602
+ nodelist = range(sum(sizes))
603
+
604
+ # Setup the graph conditionally to the directed switch.
605
+ block_range = range(len(sizes))
606
+ if directed:
607
+ g = nx.DiGraph()
608
+ block_iter = itertools.product(block_range, block_range)
609
+ else:
610
+ g = nx.Graph()
611
+ block_iter = itertools.combinations_with_replacement(block_range, 2)
612
+ # Split nodelist in a partition (list of sets).
613
+ size_cumsum = [sum(sizes[0:x]) for x in range(len(sizes) + 1)]
614
+ g.graph["partition"] = [
615
+ set(nodelist[size_cumsum[x] : size_cumsum[x + 1]])
616
+ for x in range(len(size_cumsum) - 1)
617
+ ]
618
+ # Setup nodes and graph name
619
+ for block_id, nodes in enumerate(g.graph["partition"]):
620
+ for node in nodes:
621
+ g.add_node(node, block=block_id)
622
+
623
+ g.name = "stochastic_block_model"
624
+
625
+ # Test for edge existence
626
+ parts = g.graph["partition"]
627
+ for i, j in block_iter:
628
+ if i == j:
629
+ if directed:
630
+ if selfloops:
631
+ edges = itertools.product(parts[i], parts[i])
632
+ else:
633
+ edges = itertools.permutations(parts[i], 2)
634
+ else:
635
+ edges = itertools.combinations(parts[i], 2)
636
+ if selfloops:
637
+ edges = itertools.chain(edges, zip(parts[i], parts[i]))
638
+ for e in edges:
639
+ if seed.random() < p[i][j]:
640
+ g.add_edge(*e)
641
+ else:
642
+ edges = itertools.product(parts[i], parts[j])
643
+ if sparse:
644
+ if p[i][j] == 1: # Test edges cases p_ij = 0 or 1
645
+ for e in edges:
646
+ g.add_edge(*e)
647
+ elif p[i][j] > 0:
648
+ while True:
649
+ try:
650
+ logrand = math.log(seed.random())
651
+ skip = math.floor(logrand / math.log(1 - p[i][j]))
652
+ # consume "skip" edges
653
+ next(itertools.islice(edges, skip, skip), None)
654
+ e = next(edges)
655
+ g.add_edge(*e) # __safe
656
+ except StopIteration:
657
+ break
658
+ else:
659
+ for e in edges:
660
+ if seed.random() < p[i][j]:
661
+ g.add_edge(*e) # __safe
662
+ return g
663
+
664
+
665
+ def _zipf_rv_below(gamma, xmin, threshold, seed):
666
+ """Returns a random value chosen from the bounded Zipf distribution.
667
+
668
+ Repeatedly draws values from the Zipf distribution until the
669
+ threshold is met, then returns that value.
670
+ """
671
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
672
+ while result > threshold:
673
+ result = nx.utils.zipf_rv(gamma, xmin, seed)
674
+ return result
675
+
676
+
677
+ def _powerlaw_sequence(gamma, low, high, condition, length, max_iters, seed):
678
+ """Returns a list of numbers obeying a constrained power law distribution.
679
+
680
+ ``gamma`` and ``low`` are the parameters for the Zipf distribution.
681
+
682
+ ``high`` is the maximum allowed value for values draw from the Zipf
683
+ distribution. For more information, see :func:`_zipf_rv_below`.
684
+
685
+ ``condition`` and ``length`` are Boolean-valued functions on
686
+ lists. While generating the list, random values are drawn and
687
+ appended to the list until ``length`` is satisfied by the created
688
+ list. Once ``condition`` is satisfied, the sequence generated in
689
+ this way is returned.
690
+
691
+ ``max_iters`` indicates the number of times to generate a list
692
+ satisfying ``length``. If the number of iterations exceeds this
693
+ value, :exc:`~networkx.exception.ExceededMaxIterations` is raised.
694
+
695
+ seed : integer, random_state, or None (default)
696
+ Indicator of random number generation state.
697
+ See :ref:`Randomness<randomness>`.
698
+ """
699
+ for i in range(max_iters):
700
+ seq = []
701
+ while not length(seq):
702
+ seq.append(_zipf_rv_below(gamma, low, high, seed))
703
+ if condition(seq):
704
+ return seq
705
+ raise nx.ExceededMaxIterations("Could not create power law sequence")
706
+
707
+
708
+ def _hurwitz_zeta(x, q, tolerance):
709
+ """The Hurwitz zeta function, or the Riemann zeta function of two arguments.
710
+
711
+ ``x`` must be greater than one and ``q`` must be positive.
712
+
713
+ This function repeatedly computes subsequent partial sums until
714
+ convergence, as decided by ``tolerance``.
715
+ """
716
+ z = 0
717
+ z_prev = -float("inf")
718
+ k = 0
719
+ while abs(z - z_prev) > tolerance:
720
+ z_prev = z
721
+ z += 1 / ((k + q) ** x)
722
+ k += 1
723
+ return z
724
+
725
+
726
+ def _generate_min_degree(gamma, average_degree, max_degree, tolerance, max_iters):
727
+ """Returns a minimum degree from the given average degree."""
728
+ # Defines zeta function whether or not Scipy is available
729
+ try:
730
+ from scipy.special import zeta
731
+ except ImportError:
732
+
733
+ def zeta(x, q):
734
+ return _hurwitz_zeta(x, q, tolerance)
735
+
736
+ min_deg_top = max_degree
737
+ min_deg_bot = 1
738
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
739
+ itrs = 0
740
+ mid_avg_deg = 0
741
+ while abs(mid_avg_deg - average_degree) > tolerance:
742
+ if itrs > max_iters:
743
+ raise nx.ExceededMaxIterations("Could not match average_degree")
744
+ mid_avg_deg = 0
745
+ for x in range(int(min_deg_mid), max_degree + 1):
746
+ mid_avg_deg += (x ** (-gamma + 1)) / zeta(gamma, min_deg_mid)
747
+ if mid_avg_deg > average_degree:
748
+ min_deg_top = min_deg_mid
749
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
750
+ else:
751
+ min_deg_bot = min_deg_mid
752
+ min_deg_mid = (min_deg_top - min_deg_bot) / 2 + min_deg_bot
753
+ itrs += 1
754
+ # return int(min_deg_mid + 0.5)
755
+ return round(min_deg_mid)
756
+
757
+
758
+ def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed):
759
+ """Returns a list of sets, each of which represents a community.
760
+
761
+ ``degree_seq`` is the degree sequence that must be met by the
762
+ graph.
763
+
764
+ ``community_sizes`` is the community size distribution that must be
765
+ met by the generated list of sets.
766
+
767
+ ``mu`` is a float in the interval [0, 1] indicating the fraction of
768
+ intra-community edges incident to each node.
769
+
770
+ ``max_iters`` is the number of times to try to add a node to a
771
+ community. This must be greater than the length of
772
+ ``degree_seq``, otherwise this function will always fail. If
773
+ the number of iterations exceeds this value,
774
+ :exc:`~networkx.exception.ExceededMaxIterations` is raised.
775
+
776
+ seed : integer, random_state, or None (default)
777
+ Indicator of random number generation state.
778
+ See :ref:`Randomness<randomness>`.
779
+
780
+ The communities returned by this are sets of integers in the set {0,
781
+ ..., *n* - 1}, where *n* is the length of ``degree_seq``.
782
+
783
+ """
784
+ # This assumes the nodes in the graph will be natural numbers.
785
+ result = [set() for _ in community_sizes]
786
+ n = len(degree_seq)
787
+ free = list(range(n))
788
+ for i in range(max_iters):
789
+ v = free.pop()
790
+ c = seed.choice(range(len(community_sizes)))
791
+ # s = int(degree_seq[v] * (1 - mu) + 0.5)
792
+ s = round(degree_seq[v] * (1 - mu))
793
+ # If the community is large enough, add the node to the chosen
794
+ # community. Otherwise, return it to the list of unaffiliated
795
+ # nodes.
796
+ if s < community_sizes[c]:
797
+ result[c].add(v)
798
+ else:
799
+ free.append(v)
800
+ # If the community is too big, remove a node from it.
801
+ if len(result[c]) > community_sizes[c]:
802
+ free.append(result[c].pop())
803
+ if not free:
804
+ return result
805
+ msg = "Could not assign communities; try increasing min_community"
806
+ raise nx.ExceededMaxIterations(msg)
807
+
808
+
809
+ @py_random_state(11)
810
+ @nx._dispatchable(graphs=None, returns_graph=True)
811
+ def LFR_benchmark_graph(
812
+ n,
813
+ tau1,
814
+ tau2,
815
+ mu,
816
+ average_degree=None,
817
+ min_degree=None,
818
+ max_degree=None,
819
+ min_community=None,
820
+ max_community=None,
821
+ tol=1.0e-7,
822
+ max_iters=500,
823
+ seed=None,
824
+ ):
825
+ r"""Returns the LFR benchmark graph.
826
+
827
+ This algorithm proceeds as follows:
828
+
829
+ 1) Find a degree sequence with a power law distribution, and minimum
830
+ value ``min_degree``, which has approximate average degree
831
+ ``average_degree``. This is accomplished by either
832
+
833
+ a) specifying ``min_degree`` and not ``average_degree``,
834
+ b) specifying ``average_degree`` and not ``min_degree``, in which
835
+ case a suitable minimum degree will be found.
836
+
837
+ ``max_degree`` can also be specified, otherwise it will be set to
838
+ ``n``. Each node *u* will have $\mu \mathrm{deg}(u)$ edges
839
+ joining it to nodes in communities other than its own and $(1 -
840
+ \mu) \mathrm{deg}(u)$ edges joining it to nodes in its own
841
+ community.
842
+ 2) Generate community sizes according to a power law distribution
843
+ with exponent ``tau2``. If ``min_community`` and
844
+ ``max_community`` are not specified they will be selected to be
845
+ ``min_degree`` and ``max_degree``, respectively. Community sizes
846
+ are generated until the sum of their sizes equals ``n``.
847
+ 3) Each node will be randomly assigned a community with the
848
+ condition that the community is large enough for the node's
849
+ intra-community degree, $(1 - \mu) \mathrm{deg}(u)$ as
850
+ described in step 2. If a community grows too large, a random node
851
+ will be selected for reassignment to a new community, until all
852
+ nodes have been assigned a community.
853
+ 4) Each node *u* then adds $(1 - \mu) \mathrm{deg}(u)$
854
+ intra-community edges and $\mu \mathrm{deg}(u)$ inter-community
855
+ edges.
856
+
857
+ Parameters
858
+ ----------
859
+ n : int
860
+ Number of nodes in the created graph.
861
+
862
+ tau1 : float
863
+ Power law exponent for the degree distribution of the created
864
+ graph. This value must be strictly greater than one.
865
+
866
+ tau2 : float
867
+ Power law exponent for the community size distribution in the
868
+ created graph. This value must be strictly greater than one.
869
+
870
+ mu : float
871
+ Fraction of inter-community edges incident to each node. This
872
+ value must be in the interval [0, 1].
873
+
874
+ average_degree : float
875
+ Desired average degree of nodes in the created graph. This value
876
+ must be in the interval [0, *n*]. Exactly one of this and
877
+ ``min_degree`` must be specified, otherwise a
878
+ :exc:`NetworkXError` is raised.
879
+
880
+ min_degree : int
881
+ Minimum degree of nodes in the created graph. This value must be
882
+ in the interval [0, *n*]. Exactly one of this and
883
+ ``average_degree`` must be specified, otherwise a
884
+ :exc:`NetworkXError` is raised.
885
+
886
+ max_degree : int
887
+ Maximum degree of nodes in the created graph. If not specified,
888
+ this is set to ``n``, the total number of nodes in the graph.
889
+
890
+ min_community : int
891
+ Minimum size of communities in the graph. If not specified, this
892
+ is set to ``min_degree``.
893
+
894
+ max_community : int
895
+ Maximum size of communities in the graph. If not specified, this
896
+ is set to ``n``, the total number of nodes in the graph.
897
+
898
+ tol : float
899
+ Tolerance when comparing floats, specifically when comparing
900
+ average degree values.
901
+
902
+ max_iters : int
903
+ Maximum number of iterations to try to create the community sizes,
904
+ degree distribution, and community affiliations.
905
+
906
+ seed : integer, random_state, or None (default)
907
+ Indicator of random number generation state.
908
+ See :ref:`Randomness<randomness>`.
909
+
910
+ Returns
911
+ -------
912
+ G : NetworkX graph
913
+ The LFR benchmark graph generated according to the specified
914
+ parameters.
915
+
916
+ Each node in the graph has a node attribute ``'community'`` that
917
+ stores the community (that is, the set of nodes) that includes
918
+ it.
919
+
920
+ Raises
921
+ ------
922
+ NetworkXError
923
+ If any of the parameters do not meet their upper and lower bounds:
924
+
925
+ - ``tau1`` and ``tau2`` must be strictly greater than 1.
926
+ - ``mu`` must be in [0, 1].
927
+ - ``max_degree`` must be in {1, ..., *n*}.
928
+ - ``min_community`` and ``max_community`` must be in {0, ...,
929
+ *n*}.
930
+
931
+ If not exactly one of ``average_degree`` and ``min_degree`` is
932
+ specified.
933
+
934
+ If ``min_degree`` is not specified and a suitable ``min_degree``
935
+ cannot be found.
936
+
937
+ ExceededMaxIterations
938
+ If a valid degree sequence cannot be created within
939
+ ``max_iters`` number of iterations.
940
+
941
+ If a valid set of community sizes cannot be created within
942
+ ``max_iters`` number of iterations.
943
+
944
+ If a valid community assignment cannot be created within ``10 *
945
+ n * max_iters`` number of iterations.
946
+
947
+ Examples
948
+ --------
949
+ Basic usage::
950
+
951
+ >>> from networkx.generators.community import LFR_benchmark_graph
952
+ >>> n = 250
953
+ >>> tau1 = 3
954
+ >>> tau2 = 1.5
955
+ >>> mu = 0.1
956
+ >>> G = LFR_benchmark_graph(
957
+ ... n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
958
+ ... )
959
+
960
+ Continuing the example above, you can get the communities from the
961
+ node attributes of the graph::
962
+
963
+ >>> communities = {frozenset(G.nodes[v]["community"]) for v in G}
964
+
965
+ Notes
966
+ -----
967
+ This algorithm differs slightly from the original way it was
968
+ presented in [1].
969
+
970
+ 1) Rather than connecting the graph via a configuration model then
971
+ rewiring to match the intra-community and inter-community
972
+ degrees, we do this wiring explicitly at the end, which should be
973
+ equivalent.
974
+ 2) The code posted on the author's website [2] calculates the random
975
+ power law distributed variables and their average using
976
+ continuous approximations, whereas we use the discrete
977
+ distributions here as both degree and community size are
978
+ discrete.
979
+
980
+ Though the authors describe the algorithm as quite robust, testing
981
+ during development indicates that a somewhat narrower parameter set
982
+ is likely to successfully produce a graph. Some suggestions have
983
+ been provided in the event of exceptions.
984
+
985
+ References
986
+ ----------
987
+ .. [1] "Benchmark graphs for testing community detection algorithms",
988
+ Andrea Lancichinetti, Santo Fortunato, and Filippo Radicchi,
989
+ Phys. Rev. E 78, 046110 2008
990
+ .. [2] https://www.santofortunato.net/resources
991
+
992
+ """
993
+ # Perform some basic parameter validation.
994
+ if not tau1 > 1:
995
+ raise nx.NetworkXError("tau1 must be greater than one")
996
+ if not tau2 > 1:
997
+ raise nx.NetworkXError("tau2 must be greater than one")
998
+ if not 0 <= mu <= 1:
999
+ raise nx.NetworkXError("mu must be in the interval [0, 1]")
1000
+
1001
+ # Validate parameters for generating the degree sequence.
1002
+ if max_degree is None:
1003
+ max_degree = n
1004
+ elif not 0 < max_degree <= n:
1005
+ raise nx.NetworkXError("max_degree must be in the interval (0, n]")
1006
+ if not ((min_degree is None) ^ (average_degree is None)):
1007
+ raise nx.NetworkXError(
1008
+ "Must assign exactly one of min_degree and average_degree"
1009
+ )
1010
+ if min_degree is None:
1011
+ min_degree = _generate_min_degree(
1012
+ tau1, average_degree, max_degree, tol, max_iters
1013
+ )
1014
+
1015
+ # Generate a degree sequence with a power law distribution.
1016
+ low, high = min_degree, max_degree
1017
+
1018
+ def condition(seq):
1019
+ return sum(seq) % 2 == 0
1020
+
1021
+ def length(seq):
1022
+ return len(seq) >= n
1023
+
1024
+ deg_seq = _powerlaw_sequence(tau1, low, high, condition, length, max_iters, seed)
1025
+
1026
+ # Validate parameters for generating the community size sequence.
1027
+ if min_community is None:
1028
+ min_community = min(deg_seq)
1029
+ if max_community is None:
1030
+ max_community = max(deg_seq)
1031
+
1032
+ # Generate a community size sequence with a power law distribution.
1033
+ #
1034
+ # TODO The original code incremented the number of iterations each
1035
+ # time a new Zipf random value was drawn from the distribution. This
1036
+ # differed from the way the number of iterations was incremented in
1037
+ # `_powerlaw_degree_sequence`, so this code was changed to match
1038
+ # that one. As a result, this code is allowed many more chances to
1039
+ # generate a valid community size sequence.
1040
+ low, high = min_community, max_community
1041
+
1042
+ def condition(seq):
1043
+ return sum(seq) == n
1044
+
1045
+ def length(seq):
1046
+ return sum(seq) >= n
1047
+
1048
+ comms = _powerlaw_sequence(tau2, low, high, condition, length, max_iters, seed)
1049
+
1050
+ # Generate the communities based on the given degree sequence and
1051
+ # community sizes.
1052
+ max_iters *= 10 * n
1053
+ communities = _generate_communities(deg_seq, comms, mu, max_iters, seed)
1054
+
1055
+ # Finally, generate the benchmark graph based on the given
1056
+ # communities, joining nodes according to the intra- and
1057
+ # inter-community degrees.
1058
+ G = nx.Graph()
1059
+ G.add_nodes_from(range(n))
1060
+ for c in communities:
1061
+ for u in c:
1062
+ while G.degree(u) < round(deg_seq[u] * (1 - mu)):
1063
+ v = seed.choice(list(c))
1064
+ G.add_edge(u, v)
1065
+ while G.degree(u) < deg_seq[u]:
1066
+ v = seed.choice(range(n))
1067
+ if v not in c:
1068
+ G.add_edge(u, v)
1069
+ G.nodes[u]["community"] = c
1070
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/degree_seq.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with a given degree sequence or expected degree sequence."""
2
+
3
+ import heapq
4
+ import math
5
+ from itertools import chain, combinations, zip_longest
6
+ from operator import itemgetter
7
+
8
+ import networkx as nx
9
+ from networkx.utils import py_random_state, random_weighted_sample
10
+
11
+ __all__ = [
12
+ "configuration_model",
13
+ "directed_configuration_model",
14
+ "expected_degree_graph",
15
+ "havel_hakimi_graph",
16
+ "directed_havel_hakimi_graph",
17
+ "degree_sequence_tree",
18
+ "random_degree_sequence_graph",
19
+ ]
20
+
21
+ chaini = chain.from_iterable
22
+
23
+
24
+ def _to_stublist(degree_sequence):
25
+ """Returns a list of degree-repeated node numbers.
26
+
27
+ ``degree_sequence`` is a list of nonnegative integers representing
28
+ the degrees of nodes in a graph.
29
+
30
+ This function returns a list of node numbers with multiplicities
31
+ according to the given degree sequence. For example, if the first
32
+ element of ``degree_sequence`` is ``3``, then the first node number,
33
+ ``0``, will appear at the head of the returned list three times. The
34
+ node numbers are assumed to be the numbers zero through
35
+ ``len(degree_sequence) - 1``.
36
+
37
+ Examples
38
+ --------
39
+
40
+ >>> degree_sequence = [1, 2, 3]
41
+ >>> _to_stublist(degree_sequence)
42
+ [0, 1, 1, 2, 2, 2]
43
+
44
+ If a zero appears in the sequence, that means the node exists but
45
+ has degree zero, so that number will be skipped in the returned
46
+ list::
47
+
48
+ >>> degree_sequence = [2, 0, 1]
49
+ >>> _to_stublist(degree_sequence)
50
+ [0, 0, 2]
51
+
52
+ """
53
+ return list(chaini([n] * d for n, d in enumerate(degree_sequence)))
54
+
55
+
56
+ def _configuration_model(
57
+ deg_sequence, create_using, directed=False, in_deg_sequence=None, seed=None
58
+ ):
59
+ """Helper function for generating either undirected or directed
60
+ configuration model graphs.
61
+
62
+ ``deg_sequence`` is a list of nonnegative integers representing the
63
+ degree of the node whose label is the index of the list element.
64
+
65
+ ``create_using`` see :func:`~networkx.empty_graph`.
66
+
67
+ ``directed`` and ``in_deg_sequence`` are required if you want the
68
+ returned graph to be generated using the directed configuration
69
+ model algorithm. If ``directed`` is ``False``, then ``deg_sequence``
70
+ is interpreted as the degree sequence of an undirected graph and
71
+ ``in_deg_sequence`` is ignored. Otherwise, if ``directed`` is
72
+ ``True``, then ``deg_sequence`` is interpreted as the out-degree
73
+ sequence and ``in_deg_sequence`` as the in-degree sequence of a
74
+ directed graph.
75
+
76
+ .. note::
77
+
78
+ ``deg_sequence`` and ``in_deg_sequence`` need not be the same
79
+ length.
80
+
81
+ ``seed`` is a random.Random or numpy.random.RandomState instance
82
+
83
+ This function returns a graph, directed if and only if ``directed``
84
+ is ``True``, generated according to the configuration model
85
+ algorithm. For more information on the algorithm, see the
86
+ :func:`configuration_model` or :func:`directed_configuration_model`
87
+ functions.
88
+
89
+ """
90
+ n = len(deg_sequence)
91
+ G = nx.empty_graph(n, create_using)
92
+ # If empty, return the null graph immediately.
93
+ if n == 0:
94
+ return G
95
+ # Build a list of available degree-repeated nodes. For example,
96
+ # for degree sequence [3, 2, 1, 1, 1], the "stub list" is
97
+ # initially [0, 0, 0, 1, 1, 2, 3, 4], that is, node 0 has degree
98
+ # 3 and thus is repeated 3 times, etc.
99
+ #
100
+ # Also, shuffle the stub list in order to get a random sequence of
101
+ # node pairs.
102
+ if directed:
103
+ pairs = zip_longest(deg_sequence, in_deg_sequence, fillvalue=0)
104
+ # Unzip the list of pairs into a pair of lists.
105
+ out_deg, in_deg = zip(*pairs)
106
+
107
+ out_stublist = _to_stublist(out_deg)
108
+ in_stublist = _to_stublist(in_deg)
109
+
110
+ seed.shuffle(out_stublist)
111
+ seed.shuffle(in_stublist)
112
+ else:
113
+ stublist = _to_stublist(deg_sequence)
114
+ # Choose a random balanced bipartition of the stublist, which
115
+ # gives a random pairing of nodes. In this implementation, we
116
+ # shuffle the list and then split it in half.
117
+ n = len(stublist)
118
+ half = n // 2
119
+ seed.shuffle(stublist)
120
+ out_stublist, in_stublist = stublist[:half], stublist[half:]
121
+ G.add_edges_from(zip(out_stublist, in_stublist))
122
+ return G
123
+
124
+
125
+ @py_random_state(2)
126
+ @nx._dispatchable(graphs=None, returns_graph=True)
127
+ def configuration_model(deg_sequence, create_using=None, seed=None):
128
+ """Returns a random graph with the given degree sequence.
129
+
130
+ The configuration model generates a random pseudograph (graph with
131
+ parallel edges and self loops) by randomly assigning edges to
132
+ match the given degree sequence.
133
+
134
+ Parameters
135
+ ----------
136
+ deg_sequence : list of nonnegative integers
137
+ Each list entry corresponds to the degree of a node.
138
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
139
+ Graph type to create. If graph instance, then cleared before populated.
140
+ seed : integer, random_state, or None (default)
141
+ Indicator of random number generation state.
142
+ See :ref:`Randomness<randomness>`.
143
+
144
+ Returns
145
+ -------
146
+ G : MultiGraph
147
+ A graph with the specified degree sequence.
148
+ Nodes are labeled starting at 0 with an index
149
+ corresponding to the position in deg_sequence.
150
+
151
+ Raises
152
+ ------
153
+ NetworkXError
154
+ If the degree sequence does not have an even sum.
155
+
156
+ See Also
157
+ --------
158
+ is_graphical
159
+
160
+ Notes
161
+ -----
162
+ As described by Newman [1]_.
163
+
164
+ A non-graphical degree sequence (not realizable by some simple
165
+ graph) is allowed since this function returns graphs with self
166
+ loops and parallel edges. An exception is raised if the degree
167
+ sequence does not have an even sum.
168
+
169
+ This configuration model construction process can lead to
170
+ duplicate edges and loops. You can remove the self-loops and
171
+ parallel edges (see below) which will likely result in a graph
172
+ that doesn't have the exact degree sequence specified.
173
+
174
+ The density of self-loops and parallel edges tends to decrease as
175
+ the number of nodes increases. However, typically the number of
176
+ self-loops will approach a Poisson distribution with a nonzero mean,
177
+ and similarly for the number of parallel edges. Consider a node
178
+ with *k* stubs. The probability of being joined to another stub of
179
+ the same node is basically (*k* - *1*) / *N*, where *k* is the
180
+ degree and *N* is the number of nodes. So the probability of a
181
+ self-loop scales like *c* / *N* for some constant *c*. As *N* grows,
182
+ this means we expect *c* self-loops. Similarly for parallel edges.
183
+
184
+ References
185
+ ----------
186
+ .. [1] M.E.J. Newman, "The structure and function of complex networks",
187
+ SIAM REVIEW 45-2, pp 167-256, 2003.
188
+
189
+ Examples
190
+ --------
191
+ You can create a degree sequence following a particular distribution
192
+ by using the one of the distribution functions in
193
+ :mod:`~networkx.utils.random_sequence` (or one of your own). For
194
+ example, to create an undirected multigraph on one hundred nodes
195
+ with degree sequence chosen from the power law distribution:
196
+
197
+ >>> sequence = nx.random_powerlaw_tree_sequence(100, tries=5000)
198
+ >>> G = nx.configuration_model(sequence)
199
+ >>> len(G)
200
+ 100
201
+ >>> actual_degrees = [d for v, d in G.degree()]
202
+ >>> actual_degrees == sequence
203
+ True
204
+
205
+ The returned graph is a multigraph, which may have parallel
206
+ edges. To remove any parallel edges from the returned graph:
207
+
208
+ >>> G = nx.Graph(G)
209
+
210
+ Similarly, to remove self-loops:
211
+
212
+ >>> G.remove_edges_from(nx.selfloop_edges(G))
213
+
214
+ """
215
+ if sum(deg_sequence) % 2 != 0:
216
+ msg = "Invalid degree sequence: sum of degrees must be even, not odd"
217
+ raise nx.NetworkXError(msg)
218
+
219
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
220
+ if G.is_directed():
221
+ raise nx.NetworkXNotImplemented("not implemented for directed graphs")
222
+
223
+ G = _configuration_model(deg_sequence, G, seed=seed)
224
+
225
+ return G
226
+
227
+
228
+ @py_random_state(3)
229
+ @nx._dispatchable(graphs=None, returns_graph=True)
230
+ def directed_configuration_model(
231
+ in_degree_sequence, out_degree_sequence, create_using=None, seed=None
232
+ ):
233
+ """Returns a directed_random graph with the given degree sequences.
234
+
235
+ The configuration model generates a random directed pseudograph
236
+ (graph with parallel edges and self loops) by randomly assigning
237
+ edges to match the given degree sequences.
238
+
239
+ Parameters
240
+ ----------
241
+ in_degree_sequence : list of nonnegative integers
242
+ Each list entry corresponds to the in-degree of a node.
243
+ out_degree_sequence : list of nonnegative integers
244
+ Each list entry corresponds to the out-degree of a node.
245
+ create_using : NetworkX graph constructor, optional (default MultiDiGraph)
246
+ Graph type to create. If graph instance, then cleared before populated.
247
+ seed : integer, random_state, or None (default)
248
+ Indicator of random number generation state.
249
+ See :ref:`Randomness<randomness>`.
250
+
251
+ Returns
252
+ -------
253
+ G : MultiDiGraph
254
+ A graph with the specified degree sequences.
255
+ Nodes are labeled starting at 0 with an index
256
+ corresponding to the position in deg_sequence.
257
+
258
+ Raises
259
+ ------
260
+ NetworkXError
261
+ If the degree sequences do not have the same sum.
262
+
263
+ See Also
264
+ --------
265
+ configuration_model
266
+
267
+ Notes
268
+ -----
269
+ Algorithm as described by Newman [1]_.
270
+
271
+ A non-graphical degree sequence (not realizable by some simple
272
+ graph) is allowed since this function returns graphs with self
273
+ loops and parallel edges. An exception is raised if the degree
274
+ sequences does not have the same sum.
275
+
276
+ This configuration model construction process can lead to
277
+ duplicate edges and loops. You can remove the self-loops and
278
+ parallel edges (see below) which will likely result in a graph
279
+ that doesn't have the exact degree sequence specified. This
280
+ "finite-size effect" decreases as the size of the graph increases.
281
+
282
+ References
283
+ ----------
284
+ .. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J.
285
+ Random graphs with arbitrary degree distributions and their applications
286
+ Phys. Rev. E, 64, 026118 (2001)
287
+
288
+ Examples
289
+ --------
290
+ One can modify the in- and out-degree sequences from an existing
291
+ directed graph in order to create a new directed graph. For example,
292
+ here we modify the directed path graph:
293
+
294
+ >>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
295
+ >>> din = list(d for n, d in D.in_degree())
296
+ >>> dout = list(d for n, d in D.out_degree())
297
+ >>> din.append(1)
298
+ >>> dout[0] = 2
299
+ >>> # We now expect an edge from node 0 to a new node, node 3.
300
+ ... D = nx.directed_configuration_model(din, dout)
301
+
302
+ The returned graph is a directed multigraph, which may have parallel
303
+ edges. To remove any parallel edges from the returned graph:
304
+
305
+ >>> D = nx.DiGraph(D)
306
+
307
+ Similarly, to remove self-loops:
308
+
309
+ >>> D.remove_edges_from(nx.selfloop_edges(D))
310
+
311
+ """
312
+ if sum(in_degree_sequence) != sum(out_degree_sequence):
313
+ msg = "Invalid degree sequences: sequences must have equal sums"
314
+ raise nx.NetworkXError(msg)
315
+
316
+ if create_using is None:
317
+ create_using = nx.MultiDiGraph
318
+
319
+ G = _configuration_model(
320
+ out_degree_sequence,
321
+ create_using,
322
+ directed=True,
323
+ in_deg_sequence=in_degree_sequence,
324
+ seed=seed,
325
+ )
326
+
327
+ name = "directed configuration_model {} nodes {} edges"
328
+ return G
329
+
330
+
331
+ @py_random_state(1)
332
+ @nx._dispatchable(graphs=None, returns_graph=True)
333
+ def expected_degree_graph(w, seed=None, selfloops=True):
334
+ r"""Returns a random graph with given expected degrees.
335
+
336
+ Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$
337
+ of length $n$ this algorithm assigns an edge between node $u$ and
338
+ node $v$ with probability
339
+
340
+ .. math::
341
+
342
+ p_{uv} = \frac{w_u w_v}{\sum_k w_k} .
343
+
344
+ Parameters
345
+ ----------
346
+ w : list
347
+ The list of expected degrees.
348
+ selfloops: bool (default=True)
349
+ Set to False to remove the possibility of self-loop edges.
350
+ seed : integer, random_state, or None (default)
351
+ Indicator of random number generation state.
352
+ See :ref:`Randomness<randomness>`.
353
+
354
+ Returns
355
+ -------
356
+ Graph
357
+
358
+ Examples
359
+ --------
360
+ >>> z = [10 for i in range(100)]
361
+ >>> G = nx.expected_degree_graph(z)
362
+
363
+ Notes
364
+ -----
365
+ The nodes have integer labels corresponding to index of expected degrees
366
+ input sequence.
367
+
368
+ The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the
369
+ number of nodes and $m$ is the expected number of edges.
370
+
371
+ The model in [1]_ includes the possibility of self-loop edges.
372
+ Set selfloops=False to produce a graph without self loops.
373
+
374
+ For finite graphs this model doesn't produce exactly the given
375
+ expected degree sequence. Instead the expected degrees are as
376
+ follows.
377
+
378
+ For the case without self loops (selfloops=False),
379
+
380
+ .. math::
381
+
382
+ E[deg(u)] = \sum_{v \ne u} p_{uv}
383
+ = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .
384
+
385
+
386
+ NetworkX uses the standard convention that a self-loop edge counts 2
387
+ in the degree of a node, so with self loops (selfloops=True),
388
+
389
+ .. math::
390
+
391
+ E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu}
392
+ = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .
393
+
394
+ References
395
+ ----------
396
+ .. [1] Fan Chung and L. Lu, Connected components in random graphs with
397
+ given expected degree sequences, Ann. Combinatorics, 6,
398
+ pp. 125-145, 2002.
399
+ .. [2] Joel Miller and Aric Hagberg,
400
+ Efficient generation of networks with given expected degrees,
401
+ in Algorithms and Models for the Web-Graph (WAW 2011),
402
+ Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,
403
+ pp. 115-126, 2011.
404
+ """
405
+ n = len(w)
406
+ G = nx.empty_graph(n)
407
+
408
+ # If there are no nodes are no edges in the graph, return the empty graph.
409
+ if n == 0 or max(w) == 0:
410
+ return G
411
+
412
+ rho = 1 / sum(w)
413
+ # Sort the weights in decreasing order. The original order of the
414
+ # weights dictates the order of the (integer) node labels, so we
415
+ # need to remember the permutation applied in the sorting.
416
+ order = sorted(enumerate(w), key=itemgetter(1), reverse=True)
417
+ mapping = {c: u for c, (u, v) in enumerate(order)}
418
+ seq = [v for u, v in order]
419
+ last = n
420
+ if not selfloops:
421
+ last -= 1
422
+ for u in range(last):
423
+ v = u
424
+ if not selfloops:
425
+ v += 1
426
+ factor = seq[u] * rho
427
+ p = min(seq[v] * factor, 1)
428
+ while v < n and p > 0:
429
+ if p != 1:
430
+ r = seed.random()
431
+ v += math.floor(math.log(r, 1 - p))
432
+ if v < n:
433
+ q = min(seq[v] * factor, 1)
434
+ if seed.random() < q / p:
435
+ G.add_edge(mapping[u], mapping[v])
436
+ v += 1
437
+ p = q
438
+ return G
439
+
440
+
441
+ @nx._dispatchable(graphs=None, returns_graph=True)
442
+ def havel_hakimi_graph(deg_sequence, create_using=None):
443
+ """Returns a simple graph with given degree sequence constructed
444
+ using the Havel-Hakimi algorithm.
445
+
446
+ Parameters
447
+ ----------
448
+ deg_sequence: list of integers
449
+ Each integer corresponds to the degree of a node (need not be sorted).
450
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
451
+ Graph type to create. If graph instance, then cleared before populated.
452
+ Directed graphs are not allowed.
453
+
454
+ Raises
455
+ ------
456
+ NetworkXException
457
+ For a non-graphical degree sequence (i.e. one
458
+ not realizable by some simple graph).
459
+
460
+ Notes
461
+ -----
462
+ The Havel-Hakimi algorithm constructs a simple graph by
463
+ successively connecting the node of highest degree to other nodes
464
+ of highest degree, resorting remaining nodes by degree, and
465
+ repeating the process. The resulting graph has a high
466
+ degree-associativity. Nodes are labeled 1,.., len(deg_sequence),
467
+ corresponding to their position in deg_sequence.
468
+
469
+ The basic algorithm is from Hakimi [1]_ and was generalized by
470
+ Kleitman and Wang [2]_.
471
+
472
+ References
473
+ ----------
474
+ .. [1] Hakimi S., On Realizability of a Set of Integers as
475
+ Degrees of the Vertices of a Linear Graph. I,
476
+ Journal of SIAM, 10(3), pp. 496-506 (1962)
477
+ .. [2] Kleitman D.J. and Wang D.L.
478
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
479
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
480
+ """
481
+ if not nx.is_graphical(deg_sequence):
482
+ raise nx.NetworkXError("Invalid degree sequence")
483
+
484
+ p = len(deg_sequence)
485
+ G = nx.empty_graph(p, create_using)
486
+ if G.is_directed():
487
+ raise nx.NetworkXError("Directed graphs are not supported")
488
+ num_degs = [[] for i in range(p)]
489
+ dmax, dsum, n = 0, 0, 0
490
+ for d in deg_sequence:
491
+ # Process only the non-zero integers
492
+ if d > 0:
493
+ num_degs[d].append(n)
494
+ dmax, dsum, n = max(dmax, d), dsum + d, n + 1
495
+ # Return graph if no edges
496
+ if n == 0:
497
+ return G
498
+
499
+ modstubs = [(0, 0)] * (dmax + 1)
500
+ # Successively reduce degree sequence by removing the maximum degree
501
+ while n > 0:
502
+ # Retrieve the maximum degree in the sequence
503
+ while len(num_degs[dmax]) == 0:
504
+ dmax -= 1
505
+ # If there are not enough stubs to connect to, then the sequence is
506
+ # not graphical
507
+ if dmax > n - 1:
508
+ raise nx.NetworkXError("Non-graphical integer sequence")
509
+
510
+ # Remove largest stub in list
511
+ source = num_degs[dmax].pop()
512
+ n -= 1
513
+ # Reduce the next dmax largest stubs
514
+ mslen = 0
515
+ k = dmax
516
+ for i in range(dmax):
517
+ while len(num_degs[k]) == 0:
518
+ k -= 1
519
+ target = num_degs[k].pop()
520
+ G.add_edge(source, target)
521
+ n -= 1
522
+ if k > 1:
523
+ modstubs[mslen] = (k - 1, target)
524
+ mslen += 1
525
+ # Add back to the list any nonzero stubs that were removed
526
+ for i in range(mslen):
527
+ (stubval, stubtarget) = modstubs[i]
528
+ num_degs[stubval].append(stubtarget)
529
+ n += 1
530
+
531
+ return G
532
+
533
+
534
+ @nx._dispatchable(graphs=None, returns_graph=True)
535
+ def directed_havel_hakimi_graph(in_deg_sequence, out_deg_sequence, create_using=None):
536
+ """Returns a directed graph with the given degree sequences.
537
+
538
+ Parameters
539
+ ----------
540
+ in_deg_sequence : list of integers
541
+ Each list entry corresponds to the in-degree of a node.
542
+ out_deg_sequence : list of integers
543
+ Each list entry corresponds to the out-degree of a node.
544
+ create_using : NetworkX graph constructor, optional (default DiGraph)
545
+ Graph type to create. If graph instance, then cleared before populated.
546
+
547
+ Returns
548
+ -------
549
+ G : DiGraph
550
+ A graph with the specified degree sequences.
551
+ Nodes are labeled starting at 0 with an index
552
+ corresponding to the position in deg_sequence
553
+
554
+ Raises
555
+ ------
556
+ NetworkXError
557
+ If the degree sequences are not digraphical.
558
+
559
+ See Also
560
+ --------
561
+ configuration_model
562
+
563
+ Notes
564
+ -----
565
+ Algorithm as described by Kleitman and Wang [1]_.
566
+
567
+ References
568
+ ----------
569
+ .. [1] D.J. Kleitman and D.L. Wang
570
+ Algorithms for Constructing Graphs and Digraphs with Given Valences
571
+ and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
572
+ """
573
+ in_deg_sequence = nx.utils.make_list_of_ints(in_deg_sequence)
574
+ out_deg_sequence = nx.utils.make_list_of_ints(out_deg_sequence)
575
+
576
+ # Process the sequences and form two heaps to store degree pairs with
577
+ # either zero or nonzero out degrees
578
+ sumin, sumout = 0, 0
579
+ nin, nout = len(in_deg_sequence), len(out_deg_sequence)
580
+ maxn = max(nin, nout)
581
+ G = nx.empty_graph(maxn, create_using, default=nx.DiGraph)
582
+ if maxn == 0:
583
+ return G
584
+ maxin = 0
585
+ stubheap, zeroheap = [], []
586
+ for n in range(maxn):
587
+ in_deg, out_deg = 0, 0
588
+ if n < nout:
589
+ out_deg = out_deg_sequence[n]
590
+ if n < nin:
591
+ in_deg = in_deg_sequence[n]
592
+ if in_deg < 0 or out_deg < 0:
593
+ raise nx.NetworkXError(
594
+ "Invalid degree sequences. Sequence values must be positive."
595
+ )
596
+ sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg)
597
+ if in_deg > 0:
598
+ stubheap.append((-1 * out_deg, -1 * in_deg, n))
599
+ elif out_deg > 0:
600
+ zeroheap.append((-1 * out_deg, n))
601
+ if sumin != sumout:
602
+ raise nx.NetworkXError(
603
+ "Invalid degree sequences. Sequences must have equal sums."
604
+ )
605
+ heapq.heapify(stubheap)
606
+ heapq.heapify(zeroheap)
607
+
608
+ modstubs = [(0, 0, 0)] * (maxin + 1)
609
+ # Successively reduce degree sequence by removing the maximum
610
+ while stubheap:
611
+ # Remove first value in the sequence with a non-zero in degree
612
+ (freeout, freein, target) = heapq.heappop(stubheap)
613
+ freein *= -1
614
+ if freein > len(stubheap) + len(zeroheap):
615
+ raise nx.NetworkXError("Non-digraphical integer sequence")
616
+
617
+ # Attach arcs from the nodes with the most stubs
618
+ mslen = 0
619
+ for i in range(freein):
620
+ if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0][0]):
621
+ (stubout, stubsource) = heapq.heappop(zeroheap)
622
+ stubin = 0
623
+ else:
624
+ (stubout, stubin, stubsource) = heapq.heappop(stubheap)
625
+ if stubout == 0:
626
+ raise nx.NetworkXError("Non-digraphical integer sequence")
627
+ G.add_edge(stubsource, target)
628
+ # Check if source is now totally connected
629
+ if stubout + 1 < 0 or stubin < 0:
630
+ modstubs[mslen] = (stubout + 1, stubin, stubsource)
631
+ mslen += 1
632
+
633
+ # Add the nodes back to the heaps that still have available stubs
634
+ for i in range(mslen):
635
+ stub = modstubs[i]
636
+ if stub[1] < 0:
637
+ heapq.heappush(stubheap, stub)
638
+ else:
639
+ heapq.heappush(zeroheap, (stub[0], stub[2]))
640
+ if freeout < 0:
641
+ heapq.heappush(zeroheap, (freeout, target))
642
+
643
+ return G
644
+
645
+
646
+ @nx._dispatchable(graphs=None, returns_graph=True)
647
+ def degree_sequence_tree(deg_sequence, create_using=None):
648
+ """Make a tree for the given degree sequence.
649
+
650
+ A tree has #nodes-#edges=1 so
651
+ the degree sequence must have
652
+ len(deg_sequence)-sum(deg_sequence)/2=1
653
+ """
654
+ # The sum of the degree sequence must be even (for any undirected graph).
655
+ degree_sum = sum(deg_sequence)
656
+ if degree_sum % 2 != 0:
657
+ msg = "Invalid degree sequence: sum of degrees must be even, not odd"
658
+ raise nx.NetworkXError(msg)
659
+ if len(deg_sequence) - degree_sum // 2 != 1:
660
+ msg = (
661
+ "Invalid degree sequence: tree must have number of nodes equal"
662
+ " to one less than the number of edges"
663
+ )
664
+ raise nx.NetworkXError(msg)
665
+ G = nx.empty_graph(0, create_using)
666
+ if G.is_directed():
667
+ raise nx.NetworkXError("Directed Graph not supported")
668
+
669
+ # Sort all degrees greater than 1 in decreasing order.
670
+ #
671
+ # TODO Does this need to be sorted in reverse order?
672
+ deg = sorted((s for s in deg_sequence if s > 1), reverse=True)
673
+
674
+ # make path graph as backbone
675
+ n = len(deg) + 2
676
+ nx.add_path(G, range(n))
677
+ last = n
678
+
679
+ # add the leaves
680
+ for source in range(1, n - 1):
681
+ nedges = deg.pop() - 2
682
+ for target in range(last, last + nedges):
683
+ G.add_edge(source, target)
684
+ last += nedges
685
+
686
+ # in case we added one too many
687
+ if len(G) > len(deg_sequence):
688
+ G.remove_node(0)
689
+ return G
690
+
691
+
692
+ @py_random_state(1)
693
+ @nx._dispatchable(graphs=None, returns_graph=True)
694
+ def random_degree_sequence_graph(sequence, seed=None, tries=10):
695
+ r"""Returns a simple random graph with the given degree sequence.
696
+
697
+ If the maximum degree $d_m$ in the sequence is $O(m^{1/4})$ then the
698
+ algorithm produces almost uniform random graphs in $O(m d_m)$ time
699
+ where $m$ is the number of edges.
700
+
701
+ Parameters
702
+ ----------
703
+ sequence : list of integers
704
+ Sequence of degrees
705
+ seed : integer, random_state, or None (default)
706
+ Indicator of random number generation state.
707
+ See :ref:`Randomness<randomness>`.
708
+ tries : int, optional
709
+ Maximum number of tries to create a graph
710
+
711
+ Returns
712
+ -------
713
+ G : Graph
714
+ A graph with the specified degree sequence.
715
+ Nodes are labeled starting at 0 with an index
716
+ corresponding to the position in the sequence.
717
+
718
+ Raises
719
+ ------
720
+ NetworkXUnfeasible
721
+ If the degree sequence is not graphical.
722
+ NetworkXError
723
+ If a graph is not produced in specified number of tries
724
+
725
+ See Also
726
+ --------
727
+ is_graphical, configuration_model
728
+
729
+ Notes
730
+ -----
731
+ The generator algorithm [1]_ is not guaranteed to produce a graph.
732
+
733
+ References
734
+ ----------
735
+ .. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi,
736
+ A sequential algorithm for generating random graphs.
737
+ Algorithmica, Volume 58, Number 4, 860-910,
738
+ DOI: 10.1007/s00453-009-9340-1
739
+
740
+ Examples
741
+ --------
742
+ >>> sequence = [1, 2, 2, 3]
743
+ >>> G = nx.random_degree_sequence_graph(sequence, seed=42)
744
+ >>> sorted(d for n, d in G.degree())
745
+ [1, 2, 2, 3]
746
+ """
747
+ DSRG = DegreeSequenceRandomGraph(sequence, seed)
748
+ for try_n in range(tries):
749
+ try:
750
+ return DSRG.generate()
751
+ except nx.NetworkXUnfeasible:
752
+ pass
753
+ raise nx.NetworkXError(f"failed to generate graph in {tries} tries")
754
+
755
+
756
+ class DegreeSequenceRandomGraph:
757
+ # class to generate random graphs with a given degree sequence
758
+ # use random_degree_sequence_graph()
759
+ def __init__(self, degree, rng):
760
+ if not nx.is_graphical(degree):
761
+ raise nx.NetworkXUnfeasible("degree sequence is not graphical")
762
+ self.rng = rng
763
+ self.degree = list(degree)
764
+ # node labels are integers 0,...,n-1
765
+ self.m = sum(self.degree) / 2.0 # number of edges
766
+ try:
767
+ self.dmax = max(self.degree) # maximum degree
768
+ except ValueError:
769
+ self.dmax = 0
770
+
771
+ def generate(self):
772
+ # remaining_degree is mapping from int->remaining degree
773
+ self.remaining_degree = dict(enumerate(self.degree))
774
+ # add all nodes to make sure we get isolated nodes
775
+ self.graph = nx.Graph()
776
+ self.graph.add_nodes_from(self.remaining_degree)
777
+ # remove zero degree nodes
778
+ for n, d in list(self.remaining_degree.items()):
779
+ if d == 0:
780
+ del self.remaining_degree[n]
781
+ if len(self.remaining_degree) > 0:
782
+ # build graph in three phases according to how many unmatched edges
783
+ self.phase1()
784
+ self.phase2()
785
+ self.phase3()
786
+ return self.graph
787
+
788
+ def update_remaining(self, u, v, aux_graph=None):
789
+ # decrement remaining nodes, modify auxiliary graph if in phase3
790
+ if aux_graph is not None:
791
+ # remove edges from auxiliary graph
792
+ aux_graph.remove_edge(u, v)
793
+ if self.remaining_degree[u] == 1:
794
+ del self.remaining_degree[u]
795
+ if aux_graph is not None:
796
+ aux_graph.remove_node(u)
797
+ else:
798
+ self.remaining_degree[u] -= 1
799
+ if self.remaining_degree[v] == 1:
800
+ del self.remaining_degree[v]
801
+ if aux_graph is not None:
802
+ aux_graph.remove_node(v)
803
+ else:
804
+ self.remaining_degree[v] -= 1
805
+
806
+ def p(self, u, v):
807
+ # degree probability
808
+ return 1 - self.degree[u] * self.degree[v] / (4.0 * self.m)
809
+
810
+ def q(self, u, v):
811
+ # remaining degree probability
812
+ norm = max(self.remaining_degree.values()) ** 2
813
+ return self.remaining_degree[u] * self.remaining_degree[v] / norm
814
+
815
+ def suitable_edge(self):
816
+ """Returns True if and only if an arbitrary remaining node can
817
+ potentially be joined with some other remaining node.
818
+
819
+ """
820
+ nodes = iter(self.remaining_degree)
821
+ u = next(nodes)
822
+ return any(v not in self.graph[u] for v in nodes)
823
+
824
+ def phase1(self):
825
+ # choose node pairs from (degree) weighted distribution
826
+ rem_deg = self.remaining_degree
827
+ while sum(rem_deg.values()) >= 2 * self.dmax**2:
828
+ u, v = sorted(random_weighted_sample(rem_deg, 2, self.rng))
829
+ if self.graph.has_edge(u, v):
830
+ continue
831
+ if self.rng.random() < self.p(u, v): # accept edge
832
+ self.graph.add_edge(u, v)
833
+ self.update_remaining(u, v)
834
+
835
+ def phase2(self):
836
+ # choose remaining nodes uniformly at random and use rejection sampling
837
+ remaining_deg = self.remaining_degree
838
+ rng = self.rng
839
+ while len(remaining_deg) >= 2 * self.dmax:
840
+ while True:
841
+ u, v = sorted(rng.sample(list(remaining_deg.keys()), 2))
842
+ if self.graph.has_edge(u, v):
843
+ continue
844
+ if rng.random() < self.q(u, v):
845
+ break
846
+ if rng.random() < self.p(u, v): # accept edge
847
+ self.graph.add_edge(u, v)
848
+ self.update_remaining(u, v)
849
+
850
+ def phase3(self):
851
+ # build potential remaining edges and choose with rejection sampling
852
+ potential_edges = combinations(self.remaining_degree, 2)
853
+ # build auxiliary graph of potential edges not already in graph
854
+ H = nx.Graph(
855
+ [(u, v) for (u, v) in potential_edges if not self.graph.has_edge(u, v)]
856
+ )
857
+ rng = self.rng
858
+ while self.remaining_degree:
859
+ if not self.suitable_edge():
860
+ raise nx.NetworkXUnfeasible("no suitable edges left")
861
+ while True:
862
+ u, v = sorted(rng.choice(list(H.edges())))
863
+ if rng.random() < self.q(u, v):
864
+ break
865
+ if rng.random() < self.p(u, v): # accept edge
866
+ self.graph.add_edge(u, v)
867
+ self.update_remaining(u, v, aux_graph=H)
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/ego.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ego graph.
3
+ """
4
+
5
+ __all__ = ["ego_graph"]
6
+
7
+ import networkx as nx
8
+
9
+
10
+ @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
11
+ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
12
+ """Returns induced subgraph of neighbors centered at node n within
13
+ a given radius.
14
+
15
+ Parameters
16
+ ----------
17
+ G : graph
18
+ A NetworkX Graph or DiGraph
19
+
20
+ n : node
21
+ A single node
22
+
23
+ radius : number, optional
24
+ Include all neighbors of distance<=radius from n.
25
+
26
+ center : bool, optional
27
+ If False, do not include center node in graph
28
+
29
+ undirected : bool, optional
30
+ If True use both in- and out-neighbors of directed graphs.
31
+
32
+ distance : key, optional
33
+ Use specified edge data key as distance. For example, setting
34
+ distance='weight' will use the edge weight to measure the
35
+ distance from the node n.
36
+
37
+ Notes
38
+ -----
39
+ For directed graphs D this produces the "out" neighborhood
40
+ or successors. If you want the neighborhood of predecessors
41
+ first reverse the graph with D.reverse(). If you want both
42
+ directions use the keyword argument undirected=True.
43
+
44
+ Node, edge, and graph attributes are copied to the returned subgraph.
45
+ """
46
+ if undirected:
47
+ if distance is not None:
48
+ sp, _ = nx.single_source_dijkstra(
49
+ G.to_undirected(), n, cutoff=radius, weight=distance
50
+ )
51
+ else:
52
+ sp = dict(
53
+ nx.single_source_shortest_path_length(
54
+ G.to_undirected(), n, cutoff=radius
55
+ )
56
+ )
57
+ else:
58
+ if distance is not None:
59
+ sp, _ = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
60
+ else:
61
+ sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))
62
+
63
+ H = G.subgraph(sp).copy()
64
+ if not center:
65
+ H.remove_node(n)
66
+ return H
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/expanders.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides explicit constructions of expander graphs."""
2
+
3
+ import itertools
4
+
5
+ import networkx as nx
6
+
7
+ __all__ = [
8
+ "margulis_gabber_galil_graph",
9
+ "chordal_cycle_graph",
10
+ "paley_graph",
11
+ "maybe_regular_expander",
12
+ "is_regular_expander",
13
+ "random_regular_expander_graph",
14
+ ]
15
+
16
+
17
+ # Other discrete torus expanders can be constructed by using the following edge
18
+ # sets. For more information, see Chapter 4, "Expander Graphs", in
19
+ # "Pseudorandomness", by Salil Vadhan.
20
+ #
21
+ # For a directed expander, add edges from (x, y) to:
22
+ #
23
+ # (x, y),
24
+ # ((x + 1) % n, y),
25
+ # (x, (y + 1) % n),
26
+ # (x, (x + y) % n),
27
+ # (-y % n, x)
28
+ #
29
+ # For an undirected expander, add the reverse edges.
30
+ #
31
+ # Also appearing in the paper of Gabber and Galil:
32
+ #
33
+ # (x, y),
34
+ # (x, (x + y) % n),
35
+ # (x, (x + y + 1) % n),
36
+ # ((x + y) % n, y),
37
+ # ((x + y + 1) % n, y)
38
+ #
39
+ # and:
40
+ #
41
+ # (x, y),
42
+ # ((x + 2*y) % n, y),
43
+ # ((x + (2*y + 1)) % n, y),
44
+ # ((x + (2*y + 2)) % n, y),
45
+ # (x, (y + 2*x) % n),
46
+ # (x, (y + (2*x + 1)) % n),
47
+ # (x, (y + (2*x + 2)) % n),
48
+ #
49
+ @nx._dispatchable(graphs=None, returns_graph=True)
50
+ def margulis_gabber_galil_graph(n, create_using=None):
51
+ r"""Returns the Margulis-Gabber-Galil undirected MultiGraph on `n^2` nodes.
52
+
53
+ The undirected MultiGraph is regular with degree `8`. Nodes are integer
54
+ pairs. The second-largest eigenvalue of the adjacency matrix of the graph
55
+ is at most `5 \sqrt{2}`, regardless of `n`.
56
+
57
+ Parameters
58
+ ----------
59
+ n : int
60
+ Determines the number of nodes in the graph: `n^2`.
61
+ create_using : NetworkX graph constructor, optional (default MultiGraph)
62
+ Graph type to create. If graph instance, then cleared before populated.
63
+
64
+ Returns
65
+ -------
66
+ G : graph
67
+ The constructed undirected multigraph.
68
+
69
+ Raises
70
+ ------
71
+ NetworkXError
72
+ If the graph is directed or not a multigraph.
73
+
74
+ """
75
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
76
+ if G.is_directed() or not G.is_multigraph():
77
+ msg = "`create_using` must be an undirected multigraph."
78
+ raise nx.NetworkXError(msg)
79
+
80
+ for x, y in itertools.product(range(n), repeat=2):
81
+ for u, v in (
82
+ ((x + 2 * y) % n, y),
83
+ ((x + (2 * y + 1)) % n, y),
84
+ (x, (y + 2 * x) % n),
85
+ (x, (y + (2 * x + 1)) % n),
86
+ ):
87
+ G.add_edge((x, y), (u, v))
88
+ G.graph["name"] = f"margulis_gabber_galil_graph({n})"
89
+ return G
90
+
91
+
92
+ @nx._dispatchable(graphs=None, returns_graph=True)
93
+ def chordal_cycle_graph(p, create_using=None):
94
+ """Returns the chordal cycle graph on `p` nodes.
95
+
96
+ The returned graph is a cycle graph on `p` nodes with chords joining each
97
+ vertex `x` to its inverse modulo `p`. This graph is a (mildly explicit)
98
+ 3-regular expander [1]_.
99
+
100
+ `p` *must* be a prime number.
101
+
102
+ Parameters
103
+ ----------
104
+ p : a prime number
105
+
106
+ The number of vertices in the graph. This also indicates where the
107
+ chordal edges in the cycle will be created.
108
+
109
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
110
+ Graph type to create. If graph instance, then cleared before populated.
111
+
112
+ Returns
113
+ -------
114
+ G : graph
115
+ The constructed undirected multigraph.
116
+
117
+ Raises
118
+ ------
119
+ NetworkXError
120
+
121
+ If `create_using` indicates directed or not a multigraph.
122
+
123
+ References
124
+ ----------
125
+
126
+ .. [1] Theorem 4.4.2 in A. Lubotzky. "Discrete groups, expanding graphs and
127
+ invariant measures", volume 125 of Progress in Mathematics.
128
+ Birkhäuser Verlag, Basel, 1994.
129
+
130
+ """
131
+ G = nx.empty_graph(0, create_using, default=nx.MultiGraph)
132
+ if G.is_directed() or not G.is_multigraph():
133
+ msg = "`create_using` must be an undirected multigraph."
134
+ raise nx.NetworkXError(msg)
135
+
136
+ for x in range(p):
137
+ left = (x - 1) % p
138
+ right = (x + 1) % p
139
+ # Here we apply Fermat's Little Theorem to compute the multiplicative
140
+ # inverse of x in Z/pZ. By Fermat's Little Theorem,
141
+ #
142
+ # x^p = x (mod p)
143
+ #
144
+ # Therefore,
145
+ #
146
+ # x * x^(p - 2) = 1 (mod p)
147
+ #
148
+ # The number 0 is a special case: we just let its inverse be itself.
149
+ chord = pow(x, p - 2, p) if x > 0 else 0
150
+ for y in (left, right, chord):
151
+ G.add_edge(x, y)
152
+ G.graph["name"] = f"chordal_cycle_graph({p})"
153
+ return G
154
+
155
+
156
+ @nx._dispatchable(graphs=None, returns_graph=True)
157
+ def paley_graph(p, create_using=None):
158
+ r"""Returns the Paley $\frac{(p-1)}{2}$ -regular graph on $p$ nodes.
159
+
160
+ The returned graph is a graph on $\mathbb{Z}/p\mathbb{Z}$ with edges between $x$ and $y$
161
+ if and only if $x-y$ is a nonzero square in $\mathbb{Z}/p\mathbb{Z}$.
162
+
163
+ If $p \equiv 1 \pmod 4$, $-1$ is a square in $\mathbb{Z}/p\mathbb{Z}$ and therefore $x-y$ is a square if and
164
+ only if $y-x$ is also a square, i.e the edges in the Paley graph are symmetric.
165
+
166
+ If $p \equiv 3 \pmod 4$, $-1$ is not a square in $\mathbb{Z}/p\mathbb{Z}$ and therefore either $x-y$ or $y-x$
167
+ is a square in $\mathbb{Z}/p\mathbb{Z}$ but not both.
168
+
169
+ Note that a more general definition of Paley graphs extends this construction
170
+ to graphs over $q=p^n$ vertices, by using the finite field $F_q$ instead of $\mathbb{Z}/p\mathbb{Z}$.
171
+ This construction requires to compute squares in general finite fields and is
172
+ not what is implemented here (i.e `paley_graph(25)` does not return the true
173
+ Paley graph associated with $5^2$).
174
+
175
+ Parameters
176
+ ----------
177
+ p : int, an odd prime number.
178
+
179
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
180
+ Graph type to create. If graph instance, then cleared before populated.
181
+
182
+ Returns
183
+ -------
184
+ G : graph
185
+ The constructed directed graph.
186
+
187
+ Raises
188
+ ------
189
+ NetworkXError
190
+ If the graph is a multigraph.
191
+
192
+ References
193
+ ----------
194
+ Chapter 13 in B. Bollobas, Random Graphs. Second edition.
195
+ Cambridge Studies in Advanced Mathematics, 73.
196
+ Cambridge University Press, Cambridge (2001).
197
+ """
198
+ G = nx.empty_graph(0, create_using, default=nx.DiGraph)
199
+ if G.is_multigraph():
200
+ msg = "`create_using` cannot be a multigraph."
201
+ raise nx.NetworkXError(msg)
202
+
203
+ # Compute the squares in Z/pZ.
204
+ # Make it a set to uniquify (there are exactly (p-1)/2 squares in Z/pZ
205
+ # when is prime).
206
+ square_set = {(x**2) % p for x in range(1, p) if (x**2) % p != 0}
207
+
208
+ for x in range(p):
209
+ for x2 in square_set:
210
+ G.add_edge(x, (x + x2) % p)
211
+ G.graph["name"] = f"paley({p})"
212
+ return G
213
+
214
+
215
+ @nx.utils.decorators.np_random_state("seed")
216
+ @nx._dispatchable(graphs=None, returns_graph=True)
217
+ def maybe_regular_expander(n, d, *, create_using=None, max_tries=100, seed=None):
218
+ r"""Utility for creating a random regular expander.
219
+
220
+ Returns a random $d$-regular graph on $n$ nodes which is an expander
221
+ graph with very good probability.
222
+
223
+ Parameters
224
+ ----------
225
+ n : int
226
+ The number of nodes.
227
+ d : int
228
+ The degree of each node.
229
+ create_using : Graph Instance or Constructor
230
+ Indicator of type of graph to return.
231
+ If a Graph-type instance, then clear and use it.
232
+ If a constructor, call it to create an empty graph.
233
+ Use the Graph constructor by default.
234
+ max_tries : int. (default: 100)
235
+ The number of allowed loops when generating each independent cycle
236
+ seed : (default: None)
237
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
238
+
239
+ Notes
240
+ -----
241
+ The nodes are numbered from $0$ to $n - 1$.
242
+
243
+ The graph is generated by taking $d / 2$ random independent cycles.
244
+
245
+ Joel Friedman proved that in this model the resulting
246
+ graph is an expander with probability
247
+ $1 - O(n^{-\tau})$ where $\tau = \lceil (\sqrt{d - 1}) / 2 \rceil - 1$. [1]_
248
+
249
+ Examples
250
+ --------
251
+ >>> G = nx.maybe_regular_expander(n=200, d=6, seed=8020)
252
+
253
+ Returns
254
+ -------
255
+ G : graph
256
+ The constructed undirected graph.
257
+
258
+ Raises
259
+ ------
260
+ NetworkXError
261
+ If $d % 2 != 0$ as the degree must be even.
262
+ If $n - 1$ is less than $ 2d $ as the graph is complete at most.
263
+ If max_tries is reached
264
+
265
+ See Also
266
+ --------
267
+ is_regular_expander
268
+ random_regular_expander_graph
269
+
270
+ References
271
+ ----------
272
+ .. [1] Joel Friedman,
273
+ A Proof of Alon’s Second Eigenvalue Conjecture and Related Problems, 2004
274
+ https://arxiv.org/abs/cs/0405020
275
+
276
+ """
277
+
278
+ import numpy as np
279
+
280
+ if n < 1:
281
+ raise nx.NetworkXError("n must be a positive integer")
282
+
283
+ if not (d >= 2):
284
+ raise nx.NetworkXError("d must be greater than or equal to 2")
285
+
286
+ if not (d % 2 == 0):
287
+ raise nx.NetworkXError("d must be even")
288
+
289
+ if not (n - 1 >= d):
290
+ raise nx.NetworkXError(
291
+ f"Need n-1>= d to have room for {d//2} independent cycles with {n} nodes"
292
+ )
293
+
294
+ G = nx.empty_graph(n, create_using)
295
+
296
+ if n < 2:
297
+ return G
298
+
299
+ cycles = []
300
+ edges = set()
301
+
302
+ # Create d / 2 cycles
303
+ for i in range(d // 2):
304
+ iterations = max_tries
305
+ # Make sure the cycles are independent to have a regular graph
306
+ while len(edges) != (i + 1) * n:
307
+ iterations -= 1
308
+ # Faster than random.permutation(n) since there are only
309
+ # (n-1)! distinct cycles against n! permutations of size n
310
+ cycle = seed.permutation(n - 1).tolist()
311
+ cycle.append(n - 1)
312
+
313
+ new_edges = {
314
+ (u, v)
315
+ for u, v in nx.utils.pairwise(cycle, cyclic=True)
316
+ if (u, v) not in edges and (v, u) not in edges
317
+ }
318
+ # If the new cycle has no edges in common with previous cycles
319
+ # then add it to the list otherwise try again
320
+ if len(new_edges) == n:
321
+ cycles.append(cycle)
322
+ edges.update(new_edges)
323
+
324
+ if iterations == 0:
325
+ raise nx.NetworkXError("Too many iterations in maybe_regular_expander")
326
+
327
+ G.add_edges_from(edges)
328
+
329
+ return G
330
+
331
+
332
+ @nx.utils.not_implemented_for("directed")
333
+ @nx.utils.not_implemented_for("multigraph")
334
+ @nx._dispatchable(preserve_edge_attrs={"G": {"weight": 1}})
335
+ def is_regular_expander(G, *, epsilon=0):
336
+ r"""Determines whether the graph G is a regular expander. [1]_
337
+
338
+ An expander graph is a sparse graph with strong connectivity properties.
339
+
340
+ More precisely, this helper checks whether the graph is a
341
+ regular $(n, d, \lambda)$-expander with $\lambda$ close to
342
+ the Alon-Boppana bound and given by
343
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$. [2]_
344
+
345
+ In the case where $\epsilon = 0$ then if the graph successfully passes the test
346
+ it is a Ramanujan graph. [3]_
347
+
348
+ A Ramanujan graph has spectral gap almost as large as possible, which makes them
349
+ excellent expanders.
350
+
351
+ Parameters
352
+ ----------
353
+ G : NetworkX graph
354
+ epsilon : int, float, default=0
355
+
356
+ Returns
357
+ -------
358
+ bool
359
+ Whether the given graph is a regular $(n, d, \lambda)$-expander
360
+ where $\lambda = 2 \sqrt{d - 1} + \epsilon$.
361
+
362
+ Examples
363
+ --------
364
+ >>> G = nx.random_regular_expander_graph(20, 4)
365
+ >>> nx.is_regular_expander(G)
366
+ True
367
+
368
+ See Also
369
+ --------
370
+ maybe_regular_expander
371
+ random_regular_expander_graph
372
+
373
+ References
374
+ ----------
375
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
376
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
377
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
378
+
379
+ """
380
+
381
+ import numpy as np
382
+ from scipy.sparse.linalg import eigsh
383
+
384
+ if epsilon < 0:
385
+ raise nx.NetworkXError("epsilon must be non negative")
386
+
387
+ if not nx.is_regular(G):
388
+ return False
389
+
390
+ _, d = nx.utils.arbitrary_element(G.degree)
391
+
392
+ A = nx.adjacency_matrix(G, dtype=float)
393
+ lams = eigsh(A, which="LM", k=2, return_eigenvectors=False)
394
+
395
+ # lambda2 is the second biggest eigenvalue
396
+ lambda2 = min(lams)
397
+
398
+ # Use bool() to convert numpy scalar to Python Boolean
399
+ return bool(abs(lambda2) < 2 ** np.sqrt(d - 1) + epsilon)
400
+
401
+
402
+ @nx.utils.decorators.np_random_state("seed")
403
+ @nx._dispatchable(graphs=None, returns_graph=True)
404
+ def random_regular_expander_graph(
405
+ n, d, *, epsilon=0, create_using=None, max_tries=100, seed=None
406
+ ):
407
+ r"""Returns a random regular expander graph on $n$ nodes with degree $d$.
408
+
409
+ An expander graph is a sparse graph with strong connectivity properties. [1]_
410
+
411
+ More precisely the returned graph is a $(n, d, \lambda)$-expander with
412
+ $\lambda = 2 \sqrt{d - 1} + \epsilon$, close to the Alon-Boppana bound. [2]_
413
+
414
+ In the case where $\epsilon = 0$ it returns a Ramanujan graph.
415
+ A Ramanujan graph has spectral gap almost as large as possible,
416
+ which makes them excellent expanders. [3]_
417
+
418
+ Parameters
419
+ ----------
420
+ n : int
421
+ The number of nodes.
422
+ d : int
423
+ The degree of each node.
424
+ epsilon : int, float, default=0
425
+ max_tries : int, (default: 100)
426
+ The number of allowed loops, also used in the maybe_regular_expander utility
427
+ seed : (default: None)
428
+ Seed used to set random number generation state. See :ref`Randomness<randomness>`.
429
+
430
+ Raises
431
+ ------
432
+ NetworkXError
433
+ If max_tries is reached
434
+
435
+ Examples
436
+ --------
437
+ >>> G = nx.random_regular_expander_graph(20, 4)
438
+ >>> nx.is_regular_expander(G)
439
+ True
440
+
441
+ Notes
442
+ -----
443
+ This loops over `maybe_regular_expander` and can be slow when
444
+ $n$ is too big or $\epsilon$ too small.
445
+
446
+ See Also
447
+ --------
448
+ maybe_regular_expander
449
+ is_regular_expander
450
+
451
+ References
452
+ ----------
453
+ .. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
454
+ .. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
455
+ .. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
456
+
457
+ """
458
+ G = maybe_regular_expander(
459
+ n, d, create_using=create_using, max_tries=max_tries, seed=seed
460
+ )
461
+ iterations = max_tries
462
+
463
+ while not is_regular_expander(G, epsilon=epsilon):
464
+ iterations -= 1
465
+ G = maybe_regular_expander(
466
+ n=n, d=d, create_using=create_using, max_tries=max_tries, seed=seed
467
+ )
468
+
469
+ if iterations == 0:
470
+ raise nx.NetworkXError(
471
+ "Too many iterations in random_regular_expander_graph"
472
+ )
473
+
474
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/geometric.py ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generators for geometric graphs."""
2
+
3
+ import math
4
+ from bisect import bisect_left
5
+ from itertools import accumulate, combinations, product
6
+
7
+ import networkx as nx
8
+ from networkx.utils import py_random_state
9
+
10
+ __all__ = [
11
+ "geometric_edges",
12
+ "geographical_threshold_graph",
13
+ "navigable_small_world_graph",
14
+ "random_geometric_graph",
15
+ "soft_random_geometric_graph",
16
+ "thresholded_random_geometric_graph",
17
+ "waxman_graph",
18
+ "geometric_soft_configuration_graph",
19
+ ]
20
+
21
+
22
+ @nx._dispatchable(node_attrs="pos_name")
23
+ def geometric_edges(G, radius, p=2, *, pos_name="pos"):
24
+ """Returns edge list of node pairs within `radius` of each other.
25
+
26
+ Parameters
27
+ ----------
28
+ G : networkx graph
29
+ The graph from which to generate the edge list. The nodes in `G` should
30
+ have an attribute ``pos`` corresponding to the node position, which is
31
+ used to compute the distance to other nodes.
32
+ radius : scalar
33
+ The distance threshold. Edges are included in the edge list if the
34
+ distance between the two nodes is less than `radius`.
35
+ pos_name : string, default="pos"
36
+ The name of the node attribute which represents the position of each
37
+ node in 2D coordinates. Every node in the Graph must have this attribute.
38
+ p : scalar, default=2
39
+ The `Minkowski distance metric
40
+ <https://en.wikipedia.org/wiki/Minkowski_distance>`_ used to compute
41
+ distances. The default value is 2, i.e. Euclidean distance.
42
+
43
+ Returns
44
+ -------
45
+ edges : list
46
+ List of edges whose distances are less than `radius`
47
+
48
+ Notes
49
+ -----
50
+ Radius uses Minkowski distance metric `p`.
51
+ If scipy is available, `scipy.spatial.cKDTree` is used to speed computation.
52
+
53
+ Examples
54
+ --------
55
+ Create a graph with nodes that have a "pos" attribute representing 2D
56
+ coordinates.
57
+
58
+ >>> G = nx.Graph()
59
+ >>> G.add_nodes_from(
60
+ ... [
61
+ ... (0, {"pos": (0, 0)}),
62
+ ... (1, {"pos": (3, 0)}),
63
+ ... (2, {"pos": (8, 0)}),
64
+ ... ]
65
+ ... )
66
+ >>> nx.geometric_edges(G, radius=1)
67
+ []
68
+ >>> nx.geometric_edges(G, radius=4)
69
+ [(0, 1)]
70
+ >>> nx.geometric_edges(G, radius=6)
71
+ [(0, 1), (1, 2)]
72
+ >>> nx.geometric_edges(G, radius=9)
73
+ [(0, 1), (0, 2), (1, 2)]
74
+ """
75
+ # Input validation - every node must have a "pos" attribute
76
+ for n, pos in G.nodes(data=pos_name):
77
+ if pos is None:
78
+ raise nx.NetworkXError(
79
+ f"Node {n} (and all nodes) must have a '{pos_name}' attribute."
80
+ )
81
+
82
+ # NOTE: See _geometric_edges for the actual implementation. The reason this
83
+ # is split into two functions is to avoid the overhead of input validation
84
+ # every time the function is called internally in one of the other
85
+ # geometric generators
86
+ return _geometric_edges(G, radius, p, pos_name)
87
+
88
+
89
+ def _geometric_edges(G, radius, p, pos_name):
90
+ """
91
+ Implements `geometric_edges` without input validation. See `geometric_edges`
92
+ for complete docstring.
93
+ """
94
+ nodes_pos = G.nodes(data=pos_name)
95
+ try:
96
+ import scipy as sp
97
+ except ImportError:
98
+ # no scipy KDTree so compute by for-loop
99
+ radius_p = radius**p
100
+ edges = [
101
+ (u, v)
102
+ for (u, pu), (v, pv) in combinations(nodes_pos, 2)
103
+ if sum(abs(a - b) ** p for a, b in zip(pu, pv)) <= radius_p
104
+ ]
105
+ return edges
106
+ # scipy KDTree is available
107
+ nodes, coords = list(zip(*nodes_pos))
108
+ kdtree = sp.spatial.cKDTree(coords) # Cannot provide generator.
109
+ edge_indexes = kdtree.query_pairs(radius, p)
110
+ edges = [(nodes[u], nodes[v]) for u, v in sorted(edge_indexes)]
111
+ return edges
112
+
113
+
114
+ @py_random_state(5)
115
+ @nx._dispatchable(graphs=None, returns_graph=True)
116
+ def random_geometric_graph(
117
+ n, radius, dim=2, pos=None, p=2, seed=None, *, pos_name="pos"
118
+ ):
119
+ """Returns a random geometric graph in the unit cube of dimensions `dim`.
120
+
121
+ The random geometric graph model places `n` nodes uniformly at
122
+ random in the unit cube. Two nodes are joined by an edge if the
123
+ distance between the nodes is at most `radius`.
124
+
125
+ Edges are determined using a KDTree when SciPy is available.
126
+ This reduces the time complexity from $O(n^2)$ to $O(n)$.
127
+
128
+ Parameters
129
+ ----------
130
+ n : int or iterable
131
+ Number of nodes or iterable of nodes
132
+ radius: float
133
+ Distance threshold value
134
+ dim : int, optional
135
+ Dimension of graph
136
+ pos : dict, optional
137
+ A dictionary keyed by node with node positions as values.
138
+ p : float, optional
139
+ Which Minkowski distance metric to use. `p` has to meet the condition
140
+ ``1 <= p <= infinity``.
141
+
142
+ If this argument is not specified, the :math:`L^2` metric
143
+ (the Euclidean distance metric), p = 2 is used.
144
+ This should not be confused with the `p` of an Erdős-Rényi random
145
+ graph, which represents probability.
146
+ seed : integer, random_state, or None (default)
147
+ Indicator of random number generation state.
148
+ See :ref:`Randomness<randomness>`.
149
+ pos_name : string, default="pos"
150
+ The name of the node attribute which represents the position
151
+ in 2D coordinates of the node in the returned graph.
152
+
153
+ Returns
154
+ -------
155
+ Graph
156
+ A random geometric graph, undirected and without self-loops.
157
+ Each node has a node attribute ``'pos'`` that stores the
158
+ position of that node in Euclidean space as provided by the
159
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
160
+ generated by this function.
161
+
162
+ Examples
163
+ --------
164
+ Create a random geometric graph on twenty nodes where nodes are joined by
165
+ an edge if their distance is at most 0.1::
166
+
167
+ >>> G = nx.random_geometric_graph(20, 0.1)
168
+
169
+ Notes
170
+ -----
171
+ This uses a *k*-d tree to build the graph.
172
+
173
+ The `pos` keyword argument can be used to specify node positions so you
174
+ can create an arbitrary distribution and domain for positions.
175
+
176
+ For example, to use a 2D Gaussian distribution of node positions with mean
177
+ (0, 0) and standard deviation 2::
178
+
179
+ >>> import random
180
+ >>> n = 20
181
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
182
+ >>> G = nx.random_geometric_graph(n, 0.2, pos=pos)
183
+
184
+ References
185
+ ----------
186
+ .. [1] Penrose, Mathew, *Random Geometric Graphs*,
187
+ Oxford Studies in Probability, 5, 2003.
188
+
189
+ """
190
+ # TODO Is this function just a special case of the geographical
191
+ # threshold graph?
192
+ #
193
+ # half_radius = {v: radius / 2 for v in n}
194
+ # return geographical_threshold_graph(nodes, theta=1, alpha=1,
195
+ # weight=half_radius)
196
+ #
197
+ G = nx.empty_graph(n)
198
+ # If no positions are provided, choose uniformly random vectors in
199
+ # Euclidean space of the specified dimension.
200
+ if pos is None:
201
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
202
+ nx.set_node_attributes(G, pos, pos_name)
203
+
204
+ G.add_edges_from(_geometric_edges(G, radius, p, pos_name))
205
+ return G
206
+
207
+
208
+ @py_random_state(6)
209
+ @nx._dispatchable(graphs=None, returns_graph=True)
210
+ def soft_random_geometric_graph(
211
+ n, radius, dim=2, pos=None, p=2, p_dist=None, seed=None, *, pos_name="pos"
212
+ ):
213
+ r"""Returns a soft random geometric graph in the unit cube.
214
+
215
+ The soft random geometric graph [1] model places `n` nodes uniformly at
216
+ random in the unit cube in dimension `dim`. Two nodes of distance, `dist`,
217
+ computed by the `p`-Minkowski distance metric are joined by an edge with
218
+ probability `p_dist` if the computed distance metric value of the nodes
219
+ is at most `radius`, otherwise they are not joined.
220
+
221
+ Edges within `radius` of each other are determined using a KDTree when
222
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
223
+ to :math:`O(n)`.
224
+
225
+ Parameters
226
+ ----------
227
+ n : int or iterable
228
+ Number of nodes or iterable of nodes
229
+ radius: float
230
+ Distance threshold value
231
+ dim : int, optional
232
+ Dimension of graph
233
+ pos : dict, optional
234
+ A dictionary keyed by node with node positions as values.
235
+ p : float, optional
236
+ Which Minkowski distance metric to use.
237
+ `p` has to meet the condition ``1 <= p <= infinity``.
238
+
239
+ If this argument is not specified, the :math:`L^2` metric
240
+ (the Euclidean distance metric), p = 2 is used.
241
+
242
+ This should not be confused with the `p` of an Erdős-Rényi random
243
+ graph, which represents probability.
244
+ p_dist : function, optional
245
+ A probability density function computing the probability of
246
+ connecting two nodes that are of distance, dist, computed by the
247
+ Minkowski distance metric. The probability density function, `p_dist`,
248
+ must be any function that takes the metric value as input
249
+ and outputs a single probability value between 0-1. The scipy.stats
250
+ package has many probability distribution functions implemented and
251
+ tools for custom probability distribution definitions [2], and passing
252
+ the .pdf method of scipy.stats distributions can be used here. If the
253
+ probability function, `p_dist`, is not supplied, the default function
254
+ is an exponential distribution with rate parameter :math:`\lambda=1`.
255
+ seed : integer, random_state, or None (default)
256
+ Indicator of random number generation state.
257
+ See :ref:`Randomness<randomness>`.
258
+ pos_name : string, default="pos"
259
+ The name of the node attribute which represents the position
260
+ in 2D coordinates of the node in the returned graph.
261
+
262
+ Returns
263
+ -------
264
+ Graph
265
+ A soft random geometric graph, undirected and without self-loops.
266
+ Each node has a node attribute ``'pos'`` that stores the
267
+ position of that node in Euclidean space as provided by the
268
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
269
+ generated by this function.
270
+
271
+ Examples
272
+ --------
273
+ Default Graph:
274
+
275
+ G = nx.soft_random_geometric_graph(50, 0.2)
276
+
277
+ Custom Graph:
278
+
279
+ Create a soft random geometric graph on 100 uniformly distributed nodes
280
+ where nodes are joined by an edge with probability computed from an
281
+ exponential distribution with rate parameter :math:`\lambda=1` if their
282
+ Euclidean distance is at most 0.2.
283
+
284
+ Notes
285
+ -----
286
+ This uses a *k*-d tree to build the graph.
287
+
288
+ The `pos` keyword argument can be used to specify node positions so you
289
+ can create an arbitrary distribution and domain for positions.
290
+
291
+ For example, to use a 2D Gaussian distribution of node positions with mean
292
+ (0, 0) and standard deviation 2
293
+
294
+ The scipy.stats package can be used to define the probability distribution
295
+ with the .pdf method used as `p_dist`.
296
+
297
+ ::
298
+
299
+ >>> import random
300
+ >>> import math
301
+ >>> n = 100
302
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
303
+ >>> p_dist = lambda dist: math.exp(-dist)
304
+ >>> G = nx.soft_random_geometric_graph(n, 0.2, pos=pos, p_dist=p_dist)
305
+
306
+ References
307
+ ----------
308
+ .. [1] Penrose, Mathew D. "Connectivity of soft random geometric graphs."
309
+ The Annals of Applied Probability 26.2 (2016): 986-1028.
310
+ .. [2] scipy.stats -
311
+ https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html
312
+
313
+ """
314
+ G = nx.empty_graph(n)
315
+ G.name = f"soft_random_geometric_graph({n}, {radius}, {dim})"
316
+ # If no positions are provided, choose uniformly random vectors in
317
+ # Euclidean space of the specified dimension.
318
+ if pos is None:
319
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
320
+ nx.set_node_attributes(G, pos, pos_name)
321
+
322
+ # if p_dist function not supplied the default function is an exponential
323
+ # distribution with rate parameter :math:`\lambda=1`.
324
+ if p_dist is None:
325
+
326
+ def p_dist(dist):
327
+ return math.exp(-dist)
328
+
329
+ def should_join(edge):
330
+ u, v = edge
331
+ dist = (sum(abs(a - b) ** p for a, b in zip(pos[u], pos[v]))) ** (1 / p)
332
+ return seed.random() < p_dist(dist)
333
+
334
+ G.add_edges_from(filter(should_join, _geometric_edges(G, radius, p, pos_name)))
335
+ return G
336
+
337
+
338
+ @py_random_state(7)
339
+ @nx._dispatchable(graphs=None, returns_graph=True)
340
+ def geographical_threshold_graph(
341
+ n,
342
+ theta,
343
+ dim=2,
344
+ pos=None,
345
+ weight=None,
346
+ metric=None,
347
+ p_dist=None,
348
+ seed=None,
349
+ *,
350
+ pos_name="pos",
351
+ weight_name="weight",
352
+ ):
353
+ r"""Returns a geographical threshold graph.
354
+
355
+ The geographical threshold graph model places $n$ nodes uniformly at
356
+ random in a rectangular domain. Each node $u$ is assigned a weight
357
+ $w_u$. Two nodes $u$ and $v$ are joined by an edge if
358
+
359
+ .. math::
360
+
361
+ (w_u + w_v)p_{dist}(r) \ge \theta
362
+
363
+ where `r` is the distance between `u` and `v`, `p_dist` is any function of
364
+ `r`, and :math:`\theta` as the threshold parameter. `p_dist` is used to
365
+ give weight to the distance between nodes when deciding whether or not
366
+ they should be connected. The larger `p_dist` is, the more prone nodes
367
+ separated by `r` are to be connected, and vice versa.
368
+
369
+ Parameters
370
+ ----------
371
+ n : int or iterable
372
+ Number of nodes or iterable of nodes
373
+ theta: float
374
+ Threshold value
375
+ dim : int, optional
376
+ Dimension of graph
377
+ pos : dict
378
+ Node positions as a dictionary of tuples keyed by node.
379
+ weight : dict
380
+ Node weights as a dictionary of numbers keyed by node.
381
+ metric : function
382
+ A metric on vectors of numbers (represented as lists or
383
+ tuples). This must be a function that accepts two lists (or
384
+ tuples) as input and yields a number as output. The function
385
+ must also satisfy the four requirements of a `metric`_.
386
+ Specifically, if $d$ is the function and $x$, $y$,
387
+ and $z$ are vectors in the graph, then $d$ must satisfy
388
+
389
+ 1. $d(x, y) \ge 0$,
390
+ 2. $d(x, y) = 0$ if and only if $x = y$,
391
+ 3. $d(x, y) = d(y, x)$,
392
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
393
+
394
+ If this argument is not specified, the Euclidean distance metric is
395
+ used.
396
+
397
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
398
+ p_dist : function, optional
399
+ Any function used to give weight to the distance between nodes when
400
+ deciding whether or not they should be connected. `p_dist` was
401
+ originally conceived as a probability density function giving the
402
+ probability of connecting two nodes that are of metric distance `r`
403
+ apart. The implementation here allows for more arbitrary definitions
404
+ of `p_dist` that do not need to correspond to valid probability
405
+ density functions. The :mod:`scipy.stats` package has many
406
+ probability density functions implemented and tools for custom
407
+ probability density definitions, and passing the ``.pdf`` method of
408
+ scipy.stats distributions can be used here. If ``p_dist=None``
409
+ (the default), the exponential function :math:`r^{-2}` is used.
410
+ seed : integer, random_state, or None (default)
411
+ Indicator of random number generation state.
412
+ See :ref:`Randomness<randomness>`.
413
+ pos_name : string, default="pos"
414
+ The name of the node attribute which represents the position
415
+ in 2D coordinates of the node in the returned graph.
416
+ weight_name : string, default="weight"
417
+ The name of the node attribute which represents the weight
418
+ of the node in the returned graph.
419
+
420
+ Returns
421
+ -------
422
+ Graph
423
+ A random geographic threshold graph, undirected and without
424
+ self-loops.
425
+
426
+ Each node has a node attribute ``pos`` that stores the
427
+ position of that node in Euclidean space as provided by the
428
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
429
+ generated by this function. Similarly, each node has a node
430
+ attribute ``weight`` that stores the weight of that node as
431
+ provided or as generated.
432
+
433
+ Examples
434
+ --------
435
+ Specify an alternate distance metric using the ``metric`` keyword
436
+ argument. For example, to use the `taxicab metric`_ instead of the
437
+ default `Euclidean metric`_::
438
+
439
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
440
+ >>> G = nx.geographical_threshold_graph(10, 0.1, metric=dist)
441
+
442
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
443
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
444
+
445
+ Notes
446
+ -----
447
+ If weights are not specified they are assigned to nodes by drawing randomly
448
+ from the exponential distribution with rate parameter $\lambda=1$.
449
+ To specify weights from a different distribution, use the `weight` keyword
450
+ argument::
451
+
452
+ >>> import random
453
+ >>> n = 20
454
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
455
+ >>> G = nx.geographical_threshold_graph(20, 50, weight=w)
456
+
457
+ If node positions are not specified they are randomly assigned from the
458
+ uniform distribution.
459
+
460
+ References
461
+ ----------
462
+ .. [1] Masuda, N., Miwa, H., Konno, N.:
463
+ Geographical threshold graphs with small-world and scale-free
464
+ properties.
465
+ Physical Review E 71, 036108 (2005)
466
+ .. [2] Milan Bradonjić, Aric Hagberg and Allon G. Percus,
467
+ Giant component and connectivity in geographical threshold graphs,
468
+ in Algorithms and Models for the Web-Graph (WAW 2007),
469
+ Antony Bonato and Fan Chung (Eds), pp. 209--216, 2007
470
+ """
471
+ G = nx.empty_graph(n)
472
+ # If no weights are provided, choose them from an exponential
473
+ # distribution.
474
+ if weight is None:
475
+ weight = {v: seed.expovariate(1) for v in G}
476
+ # If no positions are provided, choose uniformly random vectors in
477
+ # Euclidean space of the specified dimension.
478
+ if pos is None:
479
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
480
+ # If no distance metric is provided, use Euclidean distance.
481
+ if metric is None:
482
+ metric = math.dist
483
+ nx.set_node_attributes(G, weight, weight_name)
484
+ nx.set_node_attributes(G, pos, pos_name)
485
+
486
+ # if p_dist is not supplied, use default r^-2
487
+ if p_dist is None:
488
+
489
+ def p_dist(r):
490
+ return r**-2
491
+
492
+ # Returns ``True`` if and only if the nodes whose attributes are
493
+ # ``du`` and ``dv`` should be joined, according to the threshold
494
+ # condition.
495
+ def should_join(pair):
496
+ u, v = pair
497
+ u_pos, v_pos = pos[u], pos[v]
498
+ u_weight, v_weight = weight[u], weight[v]
499
+ return (u_weight + v_weight) * p_dist(metric(u_pos, v_pos)) >= theta
500
+
501
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
502
+ return G
503
+
504
+
505
+ @py_random_state(6)
506
+ @nx._dispatchable(graphs=None, returns_graph=True)
507
+ def waxman_graph(
508
+ n,
509
+ beta=0.4,
510
+ alpha=0.1,
511
+ L=None,
512
+ domain=(0, 0, 1, 1),
513
+ metric=None,
514
+ seed=None,
515
+ *,
516
+ pos_name="pos",
517
+ ):
518
+ r"""Returns a Waxman random graph.
519
+
520
+ The Waxman random graph model places `n` nodes uniformly at random
521
+ in a rectangular domain. Each pair of nodes at distance `d` is
522
+ joined by an edge with probability
523
+
524
+ .. math::
525
+ p = \beta \exp(-d / \alpha L).
526
+
527
+ This function implements both Waxman models, using the `L` keyword
528
+ argument.
529
+
530
+ * Waxman-1: if `L` is not specified, it is set to be the maximum distance
531
+ between any pair of nodes.
532
+ * Waxman-2: if `L` is specified, the distance between a pair of nodes is
533
+ chosen uniformly at random from the interval `[0, L]`.
534
+
535
+ Parameters
536
+ ----------
537
+ n : int or iterable
538
+ Number of nodes or iterable of nodes
539
+ beta: float
540
+ Model parameter
541
+ alpha: float
542
+ Model parameter
543
+ L : float, optional
544
+ Maximum distance between nodes. If not specified, the actual distance
545
+ is calculated.
546
+ domain : four-tuple of numbers, optional
547
+ Domain size, given as a tuple of the form `(x_min, y_min, x_max,
548
+ y_max)`.
549
+ metric : function
550
+ A metric on vectors of numbers (represented as lists or
551
+ tuples). This must be a function that accepts two lists (or
552
+ tuples) as input and yields a number as output. The function
553
+ must also satisfy the four requirements of a `metric`_.
554
+ Specifically, if $d$ is the function and $x$, $y$,
555
+ and $z$ are vectors in the graph, then $d$ must satisfy
556
+
557
+ 1. $d(x, y) \ge 0$,
558
+ 2. $d(x, y) = 0$ if and only if $x = y$,
559
+ 3. $d(x, y) = d(y, x)$,
560
+ 4. $d(x, z) \le d(x, y) + d(y, z)$.
561
+
562
+ If this argument is not specified, the Euclidean distance metric is
563
+ used.
564
+
565
+ .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29
566
+
567
+ seed : integer, random_state, or None (default)
568
+ Indicator of random number generation state.
569
+ See :ref:`Randomness<randomness>`.
570
+ pos_name : string, default="pos"
571
+ The name of the node attribute which represents the position
572
+ in 2D coordinates of the node in the returned graph.
573
+
574
+ Returns
575
+ -------
576
+ Graph
577
+ A random Waxman graph, undirected and without self-loops. Each
578
+ node has a node attribute ``'pos'`` that stores the position of
579
+ that node in Euclidean space as generated by this function.
580
+
581
+ Examples
582
+ --------
583
+ Specify an alternate distance metric using the ``metric`` keyword
584
+ argument. For example, to use the "`taxicab metric`_" instead of the
585
+ default `Euclidean metric`_::
586
+
587
+ >>> dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y))
588
+ >>> G = nx.waxman_graph(10, 0.5, 0.1, metric=dist)
589
+
590
+ .. _taxicab metric: https://en.wikipedia.org/wiki/Taxicab_geometry
591
+ .. _Euclidean metric: https://en.wikipedia.org/wiki/Euclidean_distance
592
+
593
+ Notes
594
+ -----
595
+ Starting in NetworkX 2.0 the parameters alpha and beta align with their
596
+ usual roles in the probability distribution. In earlier versions their
597
+ positions in the expression were reversed. Their position in the calling
598
+ sequence reversed as well to minimize backward incompatibility.
599
+
600
+ References
601
+ ----------
602
+ .. [1] B. M. Waxman, *Routing of multipoint connections*.
603
+ IEEE J. Select. Areas Commun. 6(9),(1988) 1617--1622.
604
+ """
605
+ G = nx.empty_graph(n)
606
+ (xmin, ymin, xmax, ymax) = domain
607
+ # Each node gets a uniformly random position in the given rectangle.
608
+ pos = {v: (seed.uniform(xmin, xmax), seed.uniform(ymin, ymax)) for v in G}
609
+ nx.set_node_attributes(G, pos, pos_name)
610
+ # If no distance metric is provided, use Euclidean distance.
611
+ if metric is None:
612
+ metric = math.dist
613
+ # If the maximum distance L is not specified (that is, we are in the
614
+ # Waxman-1 model), then find the maximum distance between any pair
615
+ # of nodes.
616
+ #
617
+ # In the Waxman-1 model, join nodes randomly based on distance. In
618
+ # the Waxman-2 model, join randomly based on random l.
619
+ if L is None:
620
+ L = max(metric(x, y) for x, y in combinations(pos.values(), 2))
621
+
622
+ def dist(u, v):
623
+ return metric(pos[u], pos[v])
624
+
625
+ else:
626
+
627
+ def dist(u, v):
628
+ return seed.random() * L
629
+
630
+ # `pair` is the pair of nodes to decide whether to join.
631
+ def should_join(pair):
632
+ return seed.random() < beta * math.exp(-dist(*pair) / (alpha * L))
633
+
634
+ G.add_edges_from(filter(should_join, combinations(G, 2)))
635
+ return G
636
+
637
+
638
+ @py_random_state(5)
639
+ @nx._dispatchable(graphs=None, returns_graph=True)
640
+ def navigable_small_world_graph(n, p=1, q=1, r=2, dim=2, seed=None):
641
+ r"""Returns a navigable small-world graph.
642
+
643
+ A navigable small-world graph is a directed grid with additional long-range
644
+ connections that are chosen randomly.
645
+
646
+ [...] we begin with a set of nodes [...] that are identified with the set
647
+ of lattice points in an $n \times n$ square,
648
+ $\{(i, j): i \in \{1, 2, \ldots, n\}, j \in \{1, 2, \ldots, n\}\}$,
649
+ and we define the *lattice distance* between two nodes $(i, j)$ and
650
+ $(k, l)$ to be the number of "lattice steps" separating them:
651
+ $d((i, j), (k, l)) = |k - i| + |l - j|$.
652
+
653
+ For a universal constant $p >= 1$, the node $u$ has a directed edge to
654
+ every other node within lattice distance $p$---these are its *local
655
+ contacts*. For universal constants $q >= 0$ and $r >= 0$ we also
656
+ construct directed edges from $u$ to $q$ other nodes (the *long-range
657
+ contacts*) using independent random trials; the $i$th directed edge from
658
+ $u$ has endpoint $v$ with probability proportional to $[d(u,v)]^{-r}$.
659
+
660
+ -- [1]_
661
+
662
+ Parameters
663
+ ----------
664
+ n : int
665
+ The length of one side of the lattice; the number of nodes in
666
+ the graph is therefore $n^2$.
667
+ p : int
668
+ The diameter of short range connections. Each node is joined with every
669
+ other node within this lattice distance.
670
+ q : int
671
+ The number of long-range connections for each node.
672
+ r : float
673
+ Exponent for decaying probability of connections. The probability of
674
+ connecting to a node at lattice distance $d$ is $1/d^r$.
675
+ dim : int
676
+ Dimension of grid
677
+ seed : integer, random_state, or None (default)
678
+ Indicator of random number generation state.
679
+ See :ref:`Randomness<randomness>`.
680
+
681
+ References
682
+ ----------
683
+ .. [1] J. Kleinberg. The small-world phenomenon: An algorithmic
684
+ perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000.
685
+ """
686
+ if p < 1:
687
+ raise nx.NetworkXException("p must be >= 1")
688
+ if q < 0:
689
+ raise nx.NetworkXException("q must be >= 0")
690
+ if r < 0:
691
+ raise nx.NetworkXException("r must be >= 0")
692
+
693
+ G = nx.DiGraph()
694
+ nodes = list(product(range(n), repeat=dim))
695
+ for p1 in nodes:
696
+ probs = [0]
697
+ for p2 in nodes:
698
+ if p1 == p2:
699
+ continue
700
+ d = sum((abs(b - a) for a, b in zip(p1, p2)))
701
+ if d <= p:
702
+ G.add_edge(p1, p2)
703
+ probs.append(d**-r)
704
+ cdf = list(accumulate(probs))
705
+ for _ in range(q):
706
+ target = nodes[bisect_left(cdf, seed.uniform(0, cdf[-1]))]
707
+ G.add_edge(p1, target)
708
+ return G
709
+
710
+
711
+ @py_random_state(7)
712
+ @nx._dispatchable(graphs=None, returns_graph=True)
713
+ def thresholded_random_geometric_graph(
714
+ n,
715
+ radius,
716
+ theta,
717
+ dim=2,
718
+ pos=None,
719
+ weight=None,
720
+ p=2,
721
+ seed=None,
722
+ *,
723
+ pos_name="pos",
724
+ weight_name="weight",
725
+ ):
726
+ r"""Returns a thresholded random geometric graph in the unit cube.
727
+
728
+ The thresholded random geometric graph [1] model places `n` nodes
729
+ uniformly at random in the unit cube of dimensions `dim`. Each node
730
+ `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are
731
+ joined by an edge if they are within the maximum connection distance,
732
+ `radius` computed by the `p`-Minkowski distance and the summation of
733
+ weights :math:`w_u` + :math:`w_v` is greater than or equal
734
+ to the threshold parameter `theta`.
735
+
736
+ Edges within `radius` of each other are determined using a KDTree when
737
+ SciPy is available. This reduces the time complexity from :math:`O(n^2)`
738
+ to :math:`O(n)`.
739
+
740
+ Parameters
741
+ ----------
742
+ n : int or iterable
743
+ Number of nodes or iterable of nodes
744
+ radius: float
745
+ Distance threshold value
746
+ theta: float
747
+ Threshold value
748
+ dim : int, optional
749
+ Dimension of graph
750
+ pos : dict, optional
751
+ A dictionary keyed by node with node positions as values.
752
+ weight : dict, optional
753
+ Node weights as a dictionary of numbers keyed by node.
754
+ p : float, optional (default 2)
755
+ Which Minkowski distance metric to use. `p` has to meet the condition
756
+ ``1 <= p <= infinity``.
757
+
758
+ If this argument is not specified, the :math:`L^2` metric
759
+ (the Euclidean distance metric), p = 2 is used.
760
+
761
+ This should not be confused with the `p` of an Erdős-Rényi random
762
+ graph, which represents probability.
763
+ seed : integer, random_state, or None (default)
764
+ Indicator of random number generation state.
765
+ See :ref:`Randomness<randomness>`.
766
+ pos_name : string, default="pos"
767
+ The name of the node attribute which represents the position
768
+ in 2D coordinates of the node in the returned graph.
769
+ weight_name : string, default="weight"
770
+ The name of the node attribute which represents the weight
771
+ of the node in the returned graph.
772
+
773
+ Returns
774
+ -------
775
+ Graph
776
+ A thresholded random geographic graph, undirected and without
777
+ self-loops.
778
+
779
+ Each node has a node attribute ``'pos'`` that stores the
780
+ position of that node in Euclidean space as provided by the
781
+ ``pos`` keyword argument or, if ``pos`` was not provided, as
782
+ generated by this function. Similarly, each node has a nodethre
783
+ attribute ``'weight'`` that stores the weight of that node as
784
+ provided or as generated.
785
+
786
+ Examples
787
+ --------
788
+ Default Graph:
789
+
790
+ G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1)
791
+
792
+ Custom Graph:
793
+
794
+ Create a thresholded random geometric graph on 50 uniformly distributed
795
+ nodes where nodes are joined by an edge if their sum weights drawn from
796
+ a exponential distribution with rate = 5 are >= theta = 0.1 and their
797
+ Euclidean distance is at most 0.2.
798
+
799
+ Notes
800
+ -----
801
+ This uses a *k*-d tree to build the graph.
802
+
803
+ The `pos` keyword argument can be used to specify node positions so you
804
+ can create an arbitrary distribution and domain for positions.
805
+
806
+ For example, to use a 2D Gaussian distribution of node positions with mean
807
+ (0, 0) and standard deviation 2
808
+
809
+ If weights are not specified they are assigned to nodes by drawing randomly
810
+ from the exponential distribution with rate parameter :math:`\lambda=1`.
811
+ To specify weights from a different distribution, use the `weight` keyword
812
+ argument::
813
+
814
+ ::
815
+
816
+ >>> import random
817
+ >>> import math
818
+ >>> n = 50
819
+ >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
820
+ >>> w = {i: random.expovariate(5.0) for i in range(n)}
821
+ >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w)
822
+
823
+ References
824
+ ----------
825
+ .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf
826
+
827
+ """
828
+ G = nx.empty_graph(n)
829
+ G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})"
830
+ # If no weights are provided, choose them from an exponential
831
+ # distribution.
832
+ if weight is None:
833
+ weight = {v: seed.expovariate(1) for v in G}
834
+ # If no positions are provided, choose uniformly random vectors in
835
+ # Euclidean space of the specified dimension.
836
+ if pos is None:
837
+ pos = {v: [seed.random() for i in range(dim)] for v in G}
838
+ # If no distance metric is provided, use Euclidean distance.
839
+ nx.set_node_attributes(G, weight, weight_name)
840
+ nx.set_node_attributes(G, pos, pos_name)
841
+
842
+ edges = (
843
+ (u, v)
844
+ for u, v in _geometric_edges(G, radius, p, pos_name)
845
+ if weight[u] + weight[v] >= theta
846
+ )
847
+ G.add_edges_from(edges)
848
+ return G
849
+
850
+
851
+ @py_random_state(5)
852
+ @nx._dispatchable(graphs=None, returns_graph=True)
853
+ def geometric_soft_configuration_graph(
854
+ *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None
855
+ ):
856
+ r"""Returns a random graph from the geometric soft configuration model.
857
+
858
+ The $\mathbb{S}^1$ model [1]_ is the geometric soft configuration model
859
+ which is able to explain many fundamental features of real networks such as
860
+ small-world property, heteregenous degree distributions, high level of
861
+ clustering, and self-similarity.
862
+
863
+ In the geometric soft configuration model, a node $i$ is assigned two hidden
864
+ variables: a hidden degree $\kappa_i$, quantifying its popularity, influence,
865
+ or importance, and an angular position $\theta_i$ in a circle abstracting the
866
+ similarity space, where angular distances between nodes are a proxy for their
867
+ similarity. Focusing on the angular position, this model is often called
868
+ the $\mathbb{S}^1$ model (a one-dimensional sphere). The circle's radius is
869
+ adjusted to $R = N/2\pi$, where $N$ is the number of nodes, so that the density
870
+ is set to 1 without loss of generality.
871
+
872
+ The connection probability between any pair of nodes increases with
873
+ the product of their hidden degrees (i.e., their combined popularities),
874
+ and decreases with the angular distance between the two nodes.
875
+ Specifically, nodes $i$ and $j$ are connected with the probability
876
+
877
+ $p_{ij} = \frac{1}{1 + \frac{d_{ij}^\beta}{\left(\mu \kappa_i \kappa_j\right)^{\max(1, \beta)}}}$
878
+
879
+ where $d_{ij} = R\Delta\theta_{ij}$ is the arc length of the circle between
880
+ nodes $i$ and $j$ separated by an angular distance $\Delta\theta_{ij}$.
881
+ Parameters $\mu$ and $\beta$ (also called inverse temperature) control the
882
+ average degree and the clustering coefficient, respectively.
883
+
884
+ It can be shown [2]_ that the model undergoes a structural phase transition
885
+ at $\beta=1$ so that for $\beta<1$ networks are unclustered in the thermodynamic
886
+ limit (when $N\to \infty$) whereas for $\beta>1$ the ensemble generates
887
+ networks with finite clustering coefficient.
888
+
889
+ The $\mathbb{S}^1$ model can be expressed as a purely geometric model
890
+ $\mathbb{H}^2$ in the hyperbolic plane [3]_ by mapping the hidden degree of
891
+ each node into a radial coordinate as
892
+
893
+ $r_i = \hat{R} - \frac{2 \max(1, \beta)}{\beta \zeta} \ln \left(\frac{\kappa_i}{\kappa_0}\right)$
894
+
895
+ where $\hat{R}$ is the radius of the hyperbolic disk and $\zeta$ is the curvature,
896
+
897
+ $\hat{R} = \frac{2}{\zeta} \ln \left(\frac{N}{\pi}\right)
898
+ - \frac{2\max(1, \beta)}{\beta \zeta} \ln (\mu \kappa_0^2)$
899
+
900
+ The connection probability then reads
901
+
902
+ $p_{ij} = \frac{1}{1 + \exp\left({\frac{\beta\zeta}{2} (x_{ij} - \hat{R})}\right)}$
903
+
904
+ where
905
+
906
+ $x_{ij} = r_i + r_j + \frac{2}{\zeta} \ln \frac{\Delta\theta_{ij}}{2}$
907
+
908
+ is a good approximation of the hyperbolic distance between two nodes separated
909
+ by an angular distance $\Delta\theta_{ij}$ with radial coordinates $r_i$ and $r_j$.
910
+ For $\beta > 1$, the curvature $\zeta = 1$, for $\beta < 1$, $\zeta = \beta^{-1}$.
911
+
912
+
913
+ Parameters
914
+ ----------
915
+ Either `n`, `gamma`, `mean_degree` are provided or `kappas`. The values of
916
+ `n`, `gamma`, `mean_degree` (if provided) are used to construct a random
917
+ kappa-dict keyed by node with values sampled from a power-law distribution.
918
+
919
+ beta : positive number
920
+ Inverse temperature, controlling the clustering coefficient.
921
+ n : int (default: None)
922
+ Size of the network (number of nodes).
923
+ If not provided, `kappas` must be provided and holds the nodes.
924
+ gamma : float (default: None)
925
+ Exponent of the power-law distribution for hidden degrees `kappas`.
926
+ If not provided, `kappas` must be provided directly.
927
+ mean_degree : float (default: None)
928
+ The mean degree in the network.
929
+ If not provided, `kappas` must be provided directly.
930
+ kappas : dict (default: None)
931
+ A dict keyed by node to its hidden degree value.
932
+ If not provided, random values are computed based on a power-law
933
+ distribution using `n`, `gamma` and `mean_degree`.
934
+ seed : int, random_state, or None (default)
935
+ Indicator of random number generation state.
936
+ See :ref:`Randomness<randomness>`.
937
+
938
+ Returns
939
+ -------
940
+ Graph
941
+ A random geometric soft configuration graph (undirected with no self-loops).
942
+ Each node has three node-attributes:
943
+
944
+ - ``kappa`` that represents the hidden degree.
945
+
946
+ - ``theta`` the position in the similarity space ($\mathbb{S}^1$) which is
947
+ also the angular position in the hyperbolic plane.
948
+
949
+ - ``radius`` the radial position in the hyperbolic plane
950
+ (based on the hidden degree).
951
+
952
+
953
+ Examples
954
+ --------
955
+ Generate a network with specified parameters:
956
+
957
+ >>> G = nx.geometric_soft_configuration_graph(
958
+ ... beta=1.5, n=100, gamma=2.7, mean_degree=5
959
+ ... )
960
+
961
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
962
+ is set to 1.5 and the exponent of the powerlaw distribution of the hidden
963
+ degrees is 2.7 with mean value of 5.
964
+
965
+ Generate a network with predefined hidden degrees:
966
+
967
+ >>> kappas = {i: 10 for i in range(100)}
968
+ >>> G = nx.geometric_soft_configuration_graph(beta=2.5, kappas=kappas)
969
+
970
+ Create a geometric soft configuration graph with 100 nodes. The $\beta$ parameter
971
+ is set to 2.5 and all nodes with hidden degree $\kappa=10$.
972
+
973
+
974
+ References
975
+ ----------
976
+ .. [1] Serrano, M. Á., Krioukov, D., & Boguñá, M. (2008). Self-similarity
977
+ of complex networks and hidden metric spaces. Physical review letters, 100(7), 078701.
978
+
979
+ .. [2] van der Kolk, J., Serrano, M. Á., & Boguñá, M. (2022). An anomalous
980
+ topological phase transition in spatial random graphs. Communications Physics, 5(1), 245.
981
+
982
+ .. [3] Krioukov, D., Papadopoulos, F., Kitsak, M., Vahdat, A., & Boguná, M. (2010).
983
+ Hyperbolic geometry of complex networks. Physical Review E, 82(3), 036106.
984
+
985
+ """
986
+ if beta <= 0:
987
+ raise nx.NetworkXError("The parameter beta cannot be smaller or equal to 0.")
988
+
989
+ if kappas is not None:
990
+ if not all((n is None, gamma is None, mean_degree is None)):
991
+ raise nx.NetworkXError(
992
+ "When kappas is input, n, gamma and mean_degree must not be."
993
+ )
994
+
995
+ n = len(kappas)
996
+ mean_degree = sum(kappas) / len(kappas)
997
+ else:
998
+ if any((n is None, gamma is None, mean_degree is None)):
999
+ raise nx.NetworkXError(
1000
+ "Please provide either kappas, or all 3 of: n, gamma and mean_degree."
1001
+ )
1002
+
1003
+ # Generate `n` hidden degrees from a powerlaw distribution
1004
+ # with given exponent `gamma` and mean value `mean_degree`
1005
+ gam_ratio = (gamma - 2) / (gamma - 1)
1006
+ kappa_0 = mean_degree * gam_ratio * (1 - 1 / n) / (1 - 1 / n**gam_ratio)
1007
+ base = 1 - 1 / n
1008
+ power = 1 / (1 - gamma)
1009
+ kappas = {i: kappa_0 * (1 - seed.random() * base) ** power for i in range(n)}
1010
+
1011
+ G = nx.Graph()
1012
+ R = n / (2 * math.pi)
1013
+
1014
+ # Approximate values for mu in the thermodynamic limit (when n -> infinity)
1015
+ if beta > 1:
1016
+ mu = beta * math.sin(math.pi / beta) / (2 * math.pi * mean_degree)
1017
+ elif beta == 1:
1018
+ mu = 1 / (2 * mean_degree * math.log(n))
1019
+ else:
1020
+ mu = (1 - beta) / (2**beta * mean_degree * n ** (1 - beta))
1021
+
1022
+ # Generate random positions on a circle
1023
+ thetas = {k: seed.uniform(0, 2 * math.pi) for k in kappas}
1024
+
1025
+ for u in kappas:
1026
+ for v in list(G):
1027
+ angle = math.pi - math.fabs(math.pi - math.fabs(thetas[u] - thetas[v]))
1028
+ dij = math.pow(R * angle, beta)
1029
+ mu_kappas = math.pow(mu * kappas[u] * kappas[v], max(1, beta))
1030
+ p_ij = 1 / (1 + dij / mu_kappas)
1031
+
1032
+ # Create an edge with a certain connection probability
1033
+ if seed.random() < p_ij:
1034
+ G.add_edge(u, v)
1035
+ G.add_node(u)
1036
+
1037
+ nx.set_node_attributes(G, thetas, "theta")
1038
+ nx.set_node_attributes(G, kappas, "kappa")
1039
+
1040
+ # Map hidden degrees into the radial coordinates
1041
+ zeta = 1 if beta > 1 else 1 / beta
1042
+ kappa_min = min(kappas.values())
1043
+ R_c = 2 * max(1, beta) / (beta * zeta)
1044
+ R_hat = (2 / zeta) * math.log(n / math.pi) - R_c * math.log(mu * kappa_min)
1045
+ radii = {node: R_hat - R_c * math.log(kappa) for node, kappa in kappas.items()}
1046
+ nx.set_node_attributes(G, radii, "radius")
1047
+
1048
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/internet_as_graphs.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates graphs resembling the Internet Autonomous System network"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = ["random_internet_as_graph"]
7
+
8
+
9
+ def uniform_int_from_avg(a, m, seed):
10
+ """Pick a random integer with uniform probability.
11
+
12
+ Returns a random integer uniformly taken from a distribution with
13
+ minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where
14
+ b = 2*m - a.
15
+
16
+ Notes
17
+ -----
18
+ p = (b-floor(b))/2
19
+ X = X1 + X2; X1~U(a,floor(b)), X2~B(p)
20
+ E[X] = E[X1] + E[X2] = (floor(b)+a)/2 + (b-floor(b))/2 = (b+a)/2 = m
21
+ """
22
+
23
+ from math import floor
24
+
25
+ assert m >= a
26
+ b = 2 * m - a
27
+ p = (b - floor(b)) / 2
28
+ X1 = round(seed.random() * (floor(b) - a) + a)
29
+ if seed.random() < p:
30
+ X2 = 1
31
+ else:
32
+ X2 = 0
33
+ return X1 + X2
34
+
35
+
36
+ def choose_pref_attach(degs, seed):
37
+ """Pick a random value, with a probability given by its weight.
38
+
39
+ Returns a random choice among degs keys, each of which has a
40
+ probability proportional to the corresponding dictionary value.
41
+
42
+ Parameters
43
+ ----------
44
+ degs: dictionary
45
+ It contains the possible values (keys) and the corresponding
46
+ probabilities (values)
47
+ seed: random state
48
+
49
+ Returns
50
+ -------
51
+ v: object
52
+ A key of degs or None if degs is empty
53
+ """
54
+
55
+ if len(degs) == 0:
56
+ return None
57
+ s = sum(degs.values())
58
+ if s == 0:
59
+ return seed.choice(list(degs.keys()))
60
+ v = seed.random() * s
61
+
62
+ nodes = list(degs.keys())
63
+ i = 0
64
+ acc = degs[nodes[i]]
65
+ while v > acc:
66
+ i += 1
67
+ acc += degs[nodes[i]]
68
+ return nodes[i]
69
+
70
+
71
+ class AS_graph_generator:
72
+ """Generates random internet AS graphs."""
73
+
74
+ def __init__(self, n, seed):
75
+ """Initializes variables. Immediate numbers are taken from [1].
76
+
77
+ Parameters
78
+ ----------
79
+ n: integer
80
+ Number of graph nodes
81
+ seed: random state
82
+ Indicator of random number generation state.
83
+ See :ref:`Randomness<randomness>`.
84
+
85
+ Returns
86
+ -------
87
+ GG: AS_graph_generator object
88
+
89
+ References
90
+ ----------
91
+ [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
92
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
93
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
94
+ """
95
+
96
+ self.seed = seed
97
+ self.n_t = min(n, round(self.seed.random() * 2 + 4)) # num of T nodes
98
+ self.n_m = round(0.15 * n) # number of M nodes
99
+ self.n_cp = round(0.05 * n) # number of CP nodes
100
+ self.n_c = max(0, n - self.n_t - self.n_m - self.n_cp) # number of C nodes
101
+
102
+ self.d_m = 2 + (2.5 * n) / 10000 # average multihoming degree for M nodes
103
+ self.d_cp = 2 + (1.5 * n) / 10000 # avg multihoming degree for CP nodes
104
+ self.d_c = 1 + (5 * n) / 100000 # average multihoming degree for C nodes
105
+
106
+ self.p_m_m = 1 + (2 * n) / 10000 # avg num of peer edges between M and M
107
+ self.p_cp_m = 0.2 + (2 * n) / 10000 # avg num of peer edges between CP, M
108
+ self.p_cp_cp = 0.05 + (2 * n) / 100000 # avg num of peer edges btwn CP, CP
109
+
110
+ self.t_m = 0.375 # probability M's provider is T
111
+ self.t_cp = 0.375 # probability CP's provider is T
112
+ self.t_c = 0.125 # probability C's provider is T
113
+
114
+ def t_graph(self):
115
+ """Generates the core mesh network of tier one nodes of a AS graph.
116
+
117
+ Returns
118
+ -------
119
+ G: Networkx Graph
120
+ Core network
121
+ """
122
+
123
+ self.G = nx.Graph()
124
+ for i in range(self.n_t):
125
+ self.G.add_node(i, type="T")
126
+ for r in self.regions:
127
+ self.regions[r].add(i)
128
+ for j in self.G.nodes():
129
+ if i != j:
130
+ self.add_edge(i, j, "peer")
131
+ self.customers[i] = set()
132
+ self.providers[i] = set()
133
+ return self.G
134
+
135
+ def add_edge(self, i, j, kind):
136
+ if kind == "transit":
137
+ customer = str(i)
138
+ else:
139
+ customer = "none"
140
+ self.G.add_edge(i, j, type=kind, customer=customer)
141
+
142
+ def choose_peer_pref_attach(self, node_list):
143
+ """Pick a node with a probability weighted by its peer degree.
144
+
145
+ Pick a node from node_list with preferential attachment
146
+ computed only on their peer degree
147
+ """
148
+
149
+ d = {}
150
+ for n in node_list:
151
+ d[n] = self.G.nodes[n]["peers"]
152
+ return choose_pref_attach(d, self.seed)
153
+
154
+ def choose_node_pref_attach(self, node_list):
155
+ """Pick a node with a probability weighted by its degree.
156
+
157
+ Pick a node from node_list with preferential attachment
158
+ computed on their degree
159
+ """
160
+
161
+ degs = dict(self.G.degree(node_list))
162
+ return choose_pref_attach(degs, self.seed)
163
+
164
+ def add_customer(self, i, j):
165
+ """Keep the dictionaries 'customers' and 'providers' consistent."""
166
+
167
+ self.customers[j].add(i)
168
+ self.providers[i].add(j)
169
+ for z in self.providers[j]:
170
+ self.customers[z].add(i)
171
+ self.providers[i].add(z)
172
+
173
+ def add_node(self, i, kind, reg2prob, avg_deg, t_edge_prob):
174
+ """Add a node and its customer transit edges to the graph.
175
+
176
+ Parameters
177
+ ----------
178
+ i: object
179
+ Identifier of the new node
180
+ kind: string
181
+ Type of the new node. Options are: 'M' for middle node, 'CP' for
182
+ content provider and 'C' for customer.
183
+ reg2prob: float
184
+ Probability the new node can be in two different regions.
185
+ avg_deg: float
186
+ Average number of transit nodes of which node i is customer.
187
+ t_edge_prob: float
188
+ Probability node i establish a customer transit edge with a tier
189
+ one (T) node
190
+
191
+ Returns
192
+ -------
193
+ i: object
194
+ Identifier of the new node
195
+ """
196
+
197
+ regs = 1 # regions in which node resides
198
+ if self.seed.random() < reg2prob: # node is in two regions
199
+ regs = 2
200
+ node_options = set()
201
+
202
+ self.G.add_node(i, type=kind, peers=0)
203
+ self.customers[i] = set()
204
+ self.providers[i] = set()
205
+ self.nodes[kind].add(i)
206
+ for r in self.seed.sample(list(self.regions), regs):
207
+ node_options = node_options.union(self.regions[r])
208
+ self.regions[r].add(i)
209
+
210
+ edge_num = uniform_int_from_avg(1, avg_deg, self.seed)
211
+
212
+ t_options = node_options.intersection(self.nodes["T"])
213
+ m_options = node_options.intersection(self.nodes["M"])
214
+ if i in m_options:
215
+ m_options.remove(i)
216
+ d = 0
217
+ while d < edge_num and (len(t_options) > 0 or len(m_options) > 0):
218
+ if len(m_options) == 0 or (
219
+ len(t_options) > 0 and self.seed.random() < t_edge_prob
220
+ ): # add edge to a T node
221
+ j = self.choose_node_pref_attach(t_options)
222
+ t_options.remove(j)
223
+ else:
224
+ j = self.choose_node_pref_attach(m_options)
225
+ m_options.remove(j)
226
+ self.add_edge(i, j, "transit")
227
+ self.add_customer(i, j)
228
+ d += 1
229
+
230
+ return i
231
+
232
+ def add_m_peering_link(self, m, to_kind):
233
+ """Add a peering link between two middle tier (M) nodes.
234
+
235
+ Target node j is drawn considering a preferential attachment based on
236
+ other M node peering degree.
237
+
238
+ Parameters
239
+ ----------
240
+ m: object
241
+ Node identifier
242
+ to_kind: string
243
+ type for target node j (must be always M)
244
+
245
+ Returns
246
+ -------
247
+ success: boolean
248
+ """
249
+
250
+ # candidates are of type 'M' and are not customers of m
251
+ node_options = self.nodes["M"].difference(self.customers[m])
252
+ # candidates are not providers of m
253
+ node_options = node_options.difference(self.providers[m])
254
+ # remove self
255
+ if m in node_options:
256
+ node_options.remove(m)
257
+
258
+ # remove candidates we are already connected to
259
+ for j in self.G.neighbors(m):
260
+ if j in node_options:
261
+ node_options.remove(j)
262
+
263
+ if len(node_options) > 0:
264
+ j = self.choose_peer_pref_attach(node_options)
265
+ self.add_edge(m, j, "peer")
266
+ self.G.nodes[m]["peers"] += 1
267
+ self.G.nodes[j]["peers"] += 1
268
+ return True
269
+ else:
270
+ return False
271
+
272
+ def add_cp_peering_link(self, cp, to_kind):
273
+ """Add a peering link to a content provider (CP) node.
274
+
275
+ Target node j can be CP or M and it is drawn uniformly among the nodes
276
+ belonging to the same region as cp.
277
+
278
+ Parameters
279
+ ----------
280
+ cp: object
281
+ Node identifier
282
+ to_kind: string
283
+ type for target node j (must be M or CP)
284
+
285
+ Returns
286
+ -------
287
+ success: boolean
288
+ """
289
+
290
+ node_options = set()
291
+ for r in self.regions: # options include nodes in the same region(s)
292
+ if cp in self.regions[r]:
293
+ node_options = node_options.union(self.regions[r])
294
+
295
+ # options are restricted to the indicated kind ('M' or 'CP')
296
+ node_options = self.nodes[to_kind].intersection(node_options)
297
+
298
+ # remove self
299
+ if cp in node_options:
300
+ node_options.remove(cp)
301
+
302
+ # remove nodes that are cp's providers
303
+ node_options = node_options.difference(self.providers[cp])
304
+
305
+ # remove nodes we are already connected to
306
+ for j in self.G.neighbors(cp):
307
+ if j in node_options:
308
+ node_options.remove(j)
309
+
310
+ if len(node_options) > 0:
311
+ j = self.seed.sample(list(node_options), 1)[0]
312
+ self.add_edge(cp, j, "peer")
313
+ self.G.nodes[cp]["peers"] += 1
314
+ self.G.nodes[j]["peers"] += 1
315
+ return True
316
+ else:
317
+ return False
318
+
319
+ def graph_regions(self, rn):
320
+ """Initializes AS network regions.
321
+
322
+ Parameters
323
+ ----------
324
+ rn: integer
325
+ Number of regions
326
+ """
327
+
328
+ self.regions = {}
329
+ for i in range(rn):
330
+ self.regions["REG" + str(i)] = set()
331
+
332
+ def add_peering_links(self, from_kind, to_kind):
333
+ """Utility function to add peering links among node groups."""
334
+ peer_link_method = None
335
+ if from_kind == "M":
336
+ peer_link_method = self.add_m_peering_link
337
+ m = self.p_m_m
338
+ if from_kind == "CP":
339
+ peer_link_method = self.add_cp_peering_link
340
+ if to_kind == "M":
341
+ m = self.p_cp_m
342
+ else:
343
+ m = self.p_cp_cp
344
+
345
+ for i in self.nodes[from_kind]:
346
+ num = uniform_int_from_avg(0, m, self.seed)
347
+ for _ in range(num):
348
+ peer_link_method(i, to_kind)
349
+
350
+ def generate(self):
351
+ """Generates a random AS network graph as described in [1].
352
+
353
+ Returns
354
+ -------
355
+ G: Graph object
356
+
357
+ Notes
358
+ -----
359
+ The process steps are the following: first we create the core network
360
+ of tier one nodes, then we add the middle tier (M), the content
361
+ provider (CP) and the customer (C) nodes along with their transit edges
362
+ (link i,j means i is customer of j). Finally we add peering links
363
+ between M nodes, between M and CP nodes and between CP node couples.
364
+ For a detailed description of the algorithm, please refer to [1].
365
+
366
+ References
367
+ ----------
368
+ [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
369
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
370
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
371
+ """
372
+
373
+ self.graph_regions(5)
374
+ self.customers = {}
375
+ self.providers = {}
376
+ self.nodes = {"T": set(), "M": set(), "CP": set(), "C": set()}
377
+
378
+ self.t_graph()
379
+ self.nodes["T"] = set(self.G.nodes())
380
+
381
+ i = len(self.nodes["T"])
382
+ for _ in range(self.n_m):
383
+ self.nodes["M"].add(self.add_node(i, "M", 0.2, self.d_m, self.t_m))
384
+ i += 1
385
+ for _ in range(self.n_cp):
386
+ self.nodes["CP"].add(self.add_node(i, "CP", 0.05, self.d_cp, self.t_cp))
387
+ i += 1
388
+ for _ in range(self.n_c):
389
+ self.nodes["C"].add(self.add_node(i, "C", 0, self.d_c, self.t_c))
390
+ i += 1
391
+
392
+ self.add_peering_links("M", "M")
393
+ self.add_peering_links("CP", "M")
394
+ self.add_peering_links("CP", "CP")
395
+
396
+ return self.G
397
+
398
+
399
+ @py_random_state(1)
400
+ @nx._dispatchable(graphs=None, returns_graph=True)
401
+ def random_internet_as_graph(n, seed=None):
402
+ """Generates a random undirected graph resembling the Internet AS network
403
+
404
+ Parameters
405
+ ----------
406
+ n: integer in [1000, 10000]
407
+ Number of graph nodes
408
+ seed : integer, random_state, or None (default)
409
+ Indicator of random number generation state.
410
+ See :ref:`Randomness<randomness>`.
411
+
412
+ Returns
413
+ -------
414
+ G: Networkx Graph object
415
+ A randomly generated undirected graph
416
+
417
+ Notes
418
+ -----
419
+ This algorithm returns an undirected graph resembling the Internet
420
+ Autonomous System (AS) network, it uses the approach by Elmokashfi et al.
421
+ [1]_ and it grants the properties described in the related paper [1]_.
422
+
423
+ Each node models an autonomous system, with an attribute 'type' specifying
424
+ its kind; tier-1 (T), mid-level (M), customer (C) or content-provider (CP).
425
+ Each edge models an ADV communication link (hence, bidirectional) with
426
+ attributes:
427
+
428
+ - type: transit|peer, the kind of commercial agreement between nodes;
429
+ - customer: <node id>, the identifier of the node acting as customer
430
+ ('none' if type is peer).
431
+
432
+ References
433
+ ----------
434
+ .. [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
435
+ BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
436
+ in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
437
+ """
438
+
439
+ GG = AS_graph_generator(n, seed)
440
+ G = GG.generate()
441
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/intersection.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random intersection graphs.
3
+ """
4
+
5
+ import networkx as nx
6
+ from networkx.utils import py_random_state
7
+
8
+ __all__ = [
9
+ "uniform_random_intersection_graph",
10
+ "k_random_intersection_graph",
11
+ "general_random_intersection_graph",
12
+ ]
13
+
14
+
15
+ @py_random_state(3)
16
+ @nx._dispatchable(graphs=None, returns_graph=True)
17
+ def uniform_random_intersection_graph(n, m, p, seed=None):
18
+ """Returns a uniform random intersection graph.
19
+
20
+ Parameters
21
+ ----------
22
+ n : int
23
+ The number of nodes in the first bipartite set (nodes)
24
+ m : int
25
+ The number of nodes in the second bipartite set (attributes)
26
+ p : float
27
+ Probability of connecting nodes between bipartite sets
28
+ seed : integer, random_state, or None (default)
29
+ Indicator of random number generation state.
30
+ See :ref:`Randomness<randomness>`.
31
+
32
+ See Also
33
+ --------
34
+ gnp_random_graph
35
+
36
+ References
37
+ ----------
38
+ .. [1] K.B. Singer-Cohen, Random Intersection Graphs, 1995,
39
+ PhD thesis, Johns Hopkins University
40
+ .. [2] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B.,
41
+ Random intersection graphs when m = !(n):
42
+ An equivalence theorem relating the evolution of the g(n, m, p)
43
+ and g(n, p) models. Random Struct. Algorithms 16, 2 (2000), 156–176.
44
+ """
45
+ from networkx.algorithms import bipartite
46
+
47
+ G = bipartite.random_graph(n, m, p, seed)
48
+ return nx.projected_graph(G, range(n))
49
+
50
+
51
+ @py_random_state(3)
52
+ @nx._dispatchable(graphs=None, returns_graph=True)
53
+ def k_random_intersection_graph(n, m, k, seed=None):
54
+ """Returns a intersection graph with randomly chosen attribute sets for
55
+ each node that are of equal size (k).
56
+
57
+ Parameters
58
+ ----------
59
+ n : int
60
+ The number of nodes in the first bipartite set (nodes)
61
+ m : int
62
+ The number of nodes in the second bipartite set (attributes)
63
+ k : float
64
+ Size of attribute set to assign to each node.
65
+ seed : integer, random_state, or None (default)
66
+ Indicator of random number generation state.
67
+ See :ref:`Randomness<randomness>`.
68
+
69
+ See Also
70
+ --------
71
+ gnp_random_graph, uniform_random_intersection_graph
72
+
73
+ References
74
+ ----------
75
+ .. [1] Godehardt, E., and Jaworski, J.
76
+ Two models of random intersection graphs and their applications.
77
+ Electronic Notes in Discrete Mathematics 10 (2001), 129--132.
78
+ """
79
+ G = nx.empty_graph(n + m)
80
+ mset = range(n, n + m)
81
+ for v in range(n):
82
+ targets = seed.sample(mset, k)
83
+ G.add_edges_from(zip([v] * len(targets), targets))
84
+ return nx.projected_graph(G, range(n))
85
+
86
+
87
+ @py_random_state(3)
88
+ @nx._dispatchable(graphs=None, returns_graph=True)
89
+ def general_random_intersection_graph(n, m, p, seed=None):
90
+ """Returns a random intersection graph with independent probabilities
91
+ for connections between node and attribute sets.
92
+
93
+ Parameters
94
+ ----------
95
+ n : int
96
+ The number of nodes in the first bipartite set (nodes)
97
+ m : int
98
+ The number of nodes in the second bipartite set (attributes)
99
+ p : list of floats of length m
100
+ Probabilities for connecting nodes to each attribute
101
+ seed : integer, random_state, or None (default)
102
+ Indicator of random number generation state.
103
+ See :ref:`Randomness<randomness>`.
104
+
105
+ See Also
106
+ --------
107
+ gnp_random_graph, uniform_random_intersection_graph
108
+
109
+ References
110
+ ----------
111
+ .. [1] Nikoletseas, S. E., Raptopoulos, C., and Spirakis, P. G.
112
+ The existence and efficient construction of large independent sets
113
+ in general random intersection graphs. In ICALP (2004), J. D´ıaz,
114
+ J. Karhum¨aki, A. Lepist¨o, and D. Sannella, Eds., vol. 3142
115
+ of Lecture Notes in Computer Science, Springer, pp. 1029–1040.
116
+ """
117
+ if len(p) != m:
118
+ raise ValueError("Probability list p must have m elements.")
119
+ G = nx.empty_graph(n + m)
120
+ mset = range(n, n + m)
121
+ for u in range(n):
122
+ for v, q in zip(mset, p):
123
+ if seed.random() < q:
124
+ G.add_edge(u, v)
125
+ return nx.projected_graph(G, range(n))
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/joint_degree_seq.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate graphs with a given joint degree and directed joint degree"""
2
+
3
+ import networkx as nx
4
+ from networkx.utils import py_random_state
5
+
6
+ __all__ = [
7
+ "is_valid_joint_degree",
8
+ "is_valid_directed_joint_degree",
9
+ "joint_degree_graph",
10
+ "directed_joint_degree_graph",
11
+ ]
12
+
13
+
14
+ @nx._dispatchable(graphs=None)
15
+ def is_valid_joint_degree(joint_degrees):
16
+ """Checks whether the given joint degree dictionary is realizable.
17
+
18
+ A *joint degree dictionary* is a dictionary of dictionaries, in
19
+ which entry ``joint_degrees[k][l]`` is an integer representing the
20
+ number of edges joining nodes of degree *k* with nodes of degree
21
+ *l*. Such a dictionary is realizable as a simple graph if and only
22
+ if the following conditions are satisfied.
23
+
24
+ - each entry must be an integer,
25
+ - the total number of nodes of degree *k*, computed by
26
+ ``sum(joint_degrees[k].values()) / k``, must be an integer,
27
+ - the total number of edges joining nodes of degree *k* with
28
+ nodes of degree *l* cannot exceed the total number of possible edges,
29
+ - each diagonal entry ``joint_degrees[k][k]`` must be even (this is
30
+ a convention assumed by the :func:`joint_degree_graph` function).
31
+
32
+
33
+ Parameters
34
+ ----------
35
+ joint_degrees : dictionary of dictionary of integers
36
+ A joint degree dictionary in which entry ``joint_degrees[k][l]``
37
+ is the number of edges joining nodes of degree *k* with nodes of
38
+ degree *l*.
39
+
40
+ Returns
41
+ -------
42
+ bool
43
+ Whether the given joint degree dictionary is realizable as a
44
+ simple graph.
45
+
46
+ References
47
+ ----------
48
+ .. [1] M. Gjoka, M. Kurant, A. Markopoulou, "2.5K Graphs: from Sampling
49
+ to Generation", IEEE Infocom, 2013.
50
+ .. [2] I. Stanton, A. Pinar, "Constructing and sampling graphs with a
51
+ prescribed joint degree distribution", Journal of Experimental
52
+ Algorithmics, 2012.
53
+ """
54
+
55
+ degree_count = {}
56
+ for k in joint_degrees:
57
+ if k > 0:
58
+ k_size = sum(joint_degrees[k].values()) / k
59
+ if not k_size.is_integer():
60
+ return False
61
+ degree_count[k] = k_size
62
+
63
+ for k in joint_degrees:
64
+ for l in joint_degrees[k]:
65
+ if not float(joint_degrees[k][l]).is_integer():
66
+ return False
67
+
68
+ if (k != l) and (joint_degrees[k][l] > degree_count[k] * degree_count[l]):
69
+ return False
70
+ elif k == l:
71
+ if joint_degrees[k][k] > degree_count[k] * (degree_count[k] - 1):
72
+ return False
73
+ if joint_degrees[k][k] % 2 != 0:
74
+ return False
75
+
76
+ # if all above conditions have been satisfied then the input
77
+ # joint degree is realizable as a simple graph.
78
+ return True
79
+
80
+
81
+ def _neighbor_switch(G, w, unsat, h_node_residual, avoid_node_id=None):
82
+ """Releases one free stub for ``w``, while preserving joint degree in G.
83
+
84
+ Parameters
85
+ ----------
86
+ G : NetworkX graph
87
+ Graph in which the neighbor switch will take place.
88
+ w : integer
89
+ Node id for which we will execute this neighbor switch.
90
+ unsat : set of integers
91
+ Set of unsaturated node ids that have the same degree as w.
92
+ h_node_residual: dictionary of integers
93
+ Keeps track of the remaining stubs for a given node.
94
+ avoid_node_id: integer
95
+ Node id to avoid when selecting w_prime.
96
+
97
+ Notes
98
+ -----
99
+ First, it selects *w_prime*, an unsaturated node that has the same degree
100
+ as ``w``. Second, it selects *switch_node*, a neighbor node of ``w`` that
101
+ is not connected to *w_prime*. Then it executes an edge swap i.e. removes
102
+ (``w``,*switch_node*) and adds (*w_prime*,*switch_node*). Gjoka et. al. [1]
103
+ prove that such an edge swap is always possible.
104
+
105
+ References
106
+ ----------
107
+ .. [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
108
+ Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
109
+ """
110
+
111
+ if (avoid_node_id is None) or (h_node_residual[avoid_node_id] > 1):
112
+ # select unsaturated node w_prime that has the same degree as w
113
+ w_prime = next(iter(unsat))
114
+ else:
115
+ # assume that the node pair (v,w) has been selected for connection. if
116
+ # - neighbor_switch is called for node w,
117
+ # - nodes v and w have the same degree,
118
+ # - node v=avoid_node_id has only one stub left,
119
+ # then prevent v=avoid_node_id from being selected as w_prime.
120
+
121
+ iter_var = iter(unsat)
122
+ while True:
123
+ w_prime = next(iter_var)
124
+ if w_prime != avoid_node_id:
125
+ break
126
+
127
+ # select switch_node, a neighbor of w, that is not connected to w_prime
128
+ w_prime_neighbs = G[w_prime] # slightly faster declaring this variable
129
+ for v in G[w]:
130
+ if (v not in w_prime_neighbs) and (v != w_prime):
131
+ switch_node = v
132
+ break
133
+
134
+ # remove edge (w,switch_node), add edge (w_prime,switch_node) and update
135
+ # data structures
136
+ G.remove_edge(w, switch_node)
137
+ G.add_edge(w_prime, switch_node)
138
+ h_node_residual[w] += 1
139
+ h_node_residual[w_prime] -= 1
140
+ if h_node_residual[w_prime] == 0:
141
+ unsat.remove(w_prime)
142
+
143
+
144
+ @py_random_state(1)
145
+ @nx._dispatchable(graphs=None, returns_graph=True)
146
+ def joint_degree_graph(joint_degrees, seed=None):
147
+ """Generates a random simple graph with the given joint degree dictionary.
148
+
149
+ Parameters
150
+ ----------
151
+ joint_degrees : dictionary of dictionary of integers
152
+ A joint degree dictionary in which entry ``joint_degrees[k][l]`` is the
153
+ number of edges joining nodes of degree *k* with nodes of degree *l*.
154
+ seed : integer, random_state, or None (default)
155
+ Indicator of random number generation state.
156
+ See :ref:`Randomness<randomness>`.
157
+
158
+ Returns
159
+ -------
160
+ G : Graph
161
+ A graph with the specified joint degree dictionary.
162
+
163
+ Raises
164
+ ------
165
+ NetworkXError
166
+ If *joint_degrees* dictionary is not realizable.
167
+
168
+ Notes
169
+ -----
170
+ In each iteration of the "while loop" the algorithm picks two disconnected
171
+ nodes *v* and *w*, of degree *k* and *l* correspondingly, for which
172
+ ``joint_degrees[k][l]`` has not reached its target yet. It then adds
173
+ edge (*v*, *w*) and increases the number of edges in graph G by one.
174
+
175
+ The intelligence of the algorithm lies in the fact that it is always
176
+ possible to add an edge between such disconnected nodes *v* and *w*,
177
+ even if one or both nodes do not have free stubs. That is made possible by
178
+ executing a "neighbor switch", an edge rewiring move that releases
179
+ a free stub while keeping the joint degree of G the same.
180
+
181
+ The algorithm continues for E (number of edges) iterations of
182
+ the "while loop", at the which point all entries of the given
183
+ ``joint_degrees[k][l]`` have reached their target values and the
184
+ construction is complete.
185
+
186
+ References
187
+ ----------
188
+ .. [1] M. Gjoka, B. Tillman, A. Markopoulou, "Construction of Simple
189
+ Graphs with a Target Joint Degree Matrix and Beyond", IEEE Infocom, '15
190
+
191
+ Examples
192
+ --------
193
+ >>> joint_degrees = {
194
+ ... 1: {4: 1},
195
+ ... 2: {2: 2, 3: 2, 4: 2},
196
+ ... 3: {2: 2, 4: 1},
197
+ ... 4: {1: 1, 2: 2, 3: 1},
198
+ ... }
199
+ >>> G = nx.joint_degree_graph(joint_degrees)
200
+ >>>
201
+ """
202
+
203
+ if not is_valid_joint_degree(joint_degrees):
204
+ msg = "Input joint degree dict not realizable as a simple graph"
205
+ raise nx.NetworkXError(msg)
206
+
207
+ # compute degree count from joint_degrees
208
+ degree_count = {k: sum(l.values()) // k for k, l in joint_degrees.items() if k > 0}
209
+
210
+ # start with empty N-node graph
211
+ N = sum(degree_count.values())
212
+ G = nx.empty_graph(N)
213
+
214
+ # for a given degree group, keep the list of all node ids
215
+ h_degree_nodelist = {}
216
+
217
+ # for a given node, keep track of the remaining stubs
218
+ h_node_residual = {}
219
+
220
+ # populate h_degree_nodelist and h_node_residual
221
+ nodeid = 0
222
+ for degree, num_nodes in degree_count.items():
223
+ h_degree_nodelist[degree] = range(nodeid, nodeid + num_nodes)
224
+ for v in h_degree_nodelist[degree]:
225
+ h_node_residual[v] = degree
226
+ nodeid += int(num_nodes)
227
+
228
+ # iterate over every degree pair (k,l) and add the number of edges given
229
+ # for each pair
230
+ for k in joint_degrees:
231
+ for l in joint_degrees[k]:
232
+ # n_edges_add is the number of edges to add for the
233
+ # degree pair (k,l)
234
+ n_edges_add = joint_degrees[k][l]
235
+
236
+ if (n_edges_add > 0) and (k >= l):
237
+ # number of nodes with degree k and l
238
+ k_size = degree_count[k]
239
+ l_size = degree_count[l]
240
+
241
+ # k_nodes and l_nodes consist of all nodes of degree k and l
242
+ k_nodes = h_degree_nodelist[k]
243
+ l_nodes = h_degree_nodelist[l]
244
+
245
+ # k_unsat and l_unsat consist of nodes of degree k and l that
246
+ # are unsaturated (nodes that have at least 1 available stub)
247
+ k_unsat = {v for v in k_nodes if h_node_residual[v] > 0}
248
+
249
+ if k != l:
250
+ l_unsat = {w for w in l_nodes if h_node_residual[w] > 0}
251
+ else:
252
+ l_unsat = k_unsat
253
+ n_edges_add = joint_degrees[k][l] // 2
254
+
255
+ while n_edges_add > 0:
256
+ # randomly pick nodes v and w that have degrees k and l
257
+ v = k_nodes[seed.randrange(k_size)]
258
+ w = l_nodes[seed.randrange(l_size)]
259
+
260
+ # if nodes v and w are disconnected then attempt to connect
261
+ if not G.has_edge(v, w) and (v != w):
262
+ # if node v has no free stubs then do neighbor switch
263
+ if h_node_residual[v] == 0:
264
+ _neighbor_switch(G, v, k_unsat, h_node_residual)
265
+
266
+ # if node w has no free stubs then do neighbor switch
267
+ if h_node_residual[w] == 0:
268
+ if k != l:
269
+ _neighbor_switch(G, w, l_unsat, h_node_residual)
270
+ else:
271
+ _neighbor_switch(
272
+ G, w, l_unsat, h_node_residual, avoid_node_id=v
273
+ )
274
+
275
+ # add edge (v, w) and update data structures
276
+ G.add_edge(v, w)
277
+ h_node_residual[v] -= 1
278
+ h_node_residual[w] -= 1
279
+ n_edges_add -= 1
280
+
281
+ if h_node_residual[v] == 0:
282
+ k_unsat.discard(v)
283
+ if h_node_residual[w] == 0:
284
+ l_unsat.discard(w)
285
+ return G
286
+
287
+
288
+ @nx._dispatchable(graphs=None)
289
+ def is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
290
+ """Checks whether the given directed joint degree input is realizable
291
+
292
+ Parameters
293
+ ----------
294
+ in_degrees : list of integers
295
+ in degree sequence contains the in degrees of nodes.
296
+ out_degrees : list of integers
297
+ out degree sequence contains the out degrees of nodes.
298
+ nkk : dictionary of dictionary of integers
299
+ directed joint degree dictionary. for nodes of out degree k (first
300
+ level of dict) and nodes of in degree l (second level of dict)
301
+ describes the number of edges.
302
+
303
+ Returns
304
+ -------
305
+ boolean
306
+ returns true if given input is realizable, else returns false.
307
+
308
+ Notes
309
+ -----
310
+ Here is the list of conditions that the inputs (in/out degree sequences,
311
+ nkk) need to satisfy for simple directed graph realizability:
312
+
313
+ - Condition 0: in_degrees and out_degrees have the same length
314
+ - Condition 1: nkk[k][l] is integer for all k,l
315
+ - Condition 2: sum(nkk[k])/k = number of nodes with partition id k, is an
316
+ integer and matching degree sequence
317
+ - Condition 3: number of edges and non-chords between k and l cannot exceed
318
+ maximum possible number of edges
319
+
320
+
321
+ References
322
+ ----------
323
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
324
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
325
+ """
326
+ V = {} # number of nodes with in/out degree.
327
+ forbidden = {}
328
+ if len(in_degrees) != len(out_degrees):
329
+ return False
330
+
331
+ for idx in range(len(in_degrees)):
332
+ i = in_degrees[idx]
333
+ o = out_degrees[idx]
334
+ V[(i, 0)] = V.get((i, 0), 0) + 1
335
+ V[(o, 1)] = V.get((o, 1), 0) + 1
336
+
337
+ forbidden[(o, i)] = forbidden.get((o, i), 0) + 1
338
+
339
+ S = {} # number of edges going from in/out degree nodes.
340
+ for k in nkk:
341
+ for l in nkk[k]:
342
+ val = nkk[k][l]
343
+ if not float(val).is_integer(): # condition 1
344
+ return False
345
+
346
+ if val > 0:
347
+ S[(k, 1)] = S.get((k, 1), 0) + val
348
+ S[(l, 0)] = S.get((l, 0), 0) + val
349
+ # condition 3
350
+ if val + forbidden.get((k, l), 0) > V[(k, 1)] * V[(l, 0)]:
351
+ return False
352
+
353
+ return all(S[s] / s[0] == V[s] for s in S)
354
+
355
+
356
+ def _directed_neighbor_switch(
357
+ G, w, unsat, h_node_residual_out, chords, h_partition_in, partition
358
+ ):
359
+ """Releases one free stub for node w, while preserving joint degree in G.
360
+
361
+ Parameters
362
+ ----------
363
+ G : networkx directed graph
364
+ graph within which the edge swap will take place.
365
+ w : integer
366
+ node id for which we need to perform a neighbor switch.
367
+ unsat: set of integers
368
+ set of node ids that have the same degree as w and are unsaturated.
369
+ h_node_residual_out: dict of integers
370
+ for a given node, keeps track of the remaining stubs to be added.
371
+ chords: set of tuples
372
+ keeps track of available positions to add edges.
373
+ h_partition_in: dict of integers
374
+ for a given node, keeps track of its partition id (in degree).
375
+ partition: integer
376
+ partition id to check if chords have to be updated.
377
+
378
+ Notes
379
+ -----
380
+ First, it selects node w_prime that (1) has the same degree as w and
381
+ (2) is unsaturated. Then, it selects node v, a neighbor of w, that is
382
+ not connected to w_prime and does an edge swap i.e. removes (w,v) and
383
+ adds (w_prime,v). If neighbor switch is not possible for w using
384
+ w_prime and v, then return w_prime; in [1] it's proven that
385
+ such unsaturated nodes can be used.
386
+
387
+ References
388
+ ----------
389
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
390
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
391
+ """
392
+ w_prime = unsat.pop()
393
+ unsat.add(w_prime)
394
+ # select node t, a neighbor of w, that is not connected to w_prime
395
+ w_neighbs = list(G.successors(w))
396
+ # slightly faster declaring this variable
397
+ w_prime_neighbs = list(G.successors(w_prime))
398
+
399
+ for v in w_neighbs:
400
+ if (v not in w_prime_neighbs) and w_prime != v:
401
+ # removes (w,v), add (w_prime,v) and update data structures
402
+ G.remove_edge(w, v)
403
+ G.add_edge(w_prime, v)
404
+
405
+ if h_partition_in[v] == partition:
406
+ chords.add((w, v))
407
+ chords.discard((w_prime, v))
408
+
409
+ h_node_residual_out[w] += 1
410
+ h_node_residual_out[w_prime] -= 1
411
+ if h_node_residual_out[w_prime] == 0:
412
+ unsat.remove(w_prime)
413
+ return None
414
+
415
+ # If neighbor switch didn't work, use unsaturated node
416
+ return w_prime
417
+
418
+
419
+ def _directed_neighbor_switch_rev(
420
+ G, w, unsat, h_node_residual_in, chords, h_partition_out, partition
421
+ ):
422
+ """The reverse of directed_neighbor_switch.
423
+
424
+ Parameters
425
+ ----------
426
+ G : networkx directed graph
427
+ graph within which the edge swap will take place.
428
+ w : integer
429
+ node id for which we need to perform a neighbor switch.
430
+ unsat: set of integers
431
+ set of node ids that have the same degree as w and are unsaturated.
432
+ h_node_residual_in: dict of integers
433
+ for a given node, keeps track of the remaining stubs to be added.
434
+ chords: set of tuples
435
+ keeps track of available positions to add edges.
436
+ h_partition_out: dict of integers
437
+ for a given node, keeps track of its partition id (out degree).
438
+ partition: integer
439
+ partition id to check if chords have to be updated.
440
+
441
+ Notes
442
+ -----
443
+ Same operation as directed_neighbor_switch except it handles this operation
444
+ for incoming edges instead of outgoing.
445
+ """
446
+ w_prime = unsat.pop()
447
+ unsat.add(w_prime)
448
+ # slightly faster declaring these as variables.
449
+ w_neighbs = list(G.predecessors(w))
450
+ w_prime_neighbs = list(G.predecessors(w_prime))
451
+ # select node v, a neighbor of w, that is not connected to w_prime.
452
+ for v in w_neighbs:
453
+ if (v not in w_prime_neighbs) and w_prime != v:
454
+ # removes (v,w), add (v,w_prime) and update data structures.
455
+ G.remove_edge(v, w)
456
+ G.add_edge(v, w_prime)
457
+ if h_partition_out[v] == partition:
458
+ chords.add((v, w))
459
+ chords.discard((v, w_prime))
460
+
461
+ h_node_residual_in[w] += 1
462
+ h_node_residual_in[w_prime] -= 1
463
+ if h_node_residual_in[w_prime] == 0:
464
+ unsat.remove(w_prime)
465
+ return None
466
+
467
+ # If neighbor switch didn't work, use the unsaturated node.
468
+ return w_prime
469
+
470
+
471
+ @py_random_state(3)
472
+ @nx._dispatchable(graphs=None, returns_graph=True)
473
+ def directed_joint_degree_graph(in_degrees, out_degrees, nkk, seed=None):
474
+ """Generates a random simple directed graph with the joint degree.
475
+
476
+ Parameters
477
+ ----------
478
+ degree_seq : list of tuples (of size 3)
479
+ degree sequence contains tuples of nodes with node id, in degree and
480
+ out degree.
481
+ nkk : dictionary of dictionary of integers
482
+ directed joint degree dictionary, for nodes of out degree k (first
483
+ level of dict) and nodes of in degree l (second level of dict)
484
+ describes the number of edges.
485
+ seed : hashable object, optional
486
+ Seed for random number generator.
487
+
488
+ Returns
489
+ -------
490
+ G : Graph
491
+ A directed graph with the specified inputs.
492
+
493
+ Raises
494
+ ------
495
+ NetworkXError
496
+ If degree_seq and nkk are not realizable as a simple directed graph.
497
+
498
+
499
+ Notes
500
+ -----
501
+ Similarly to the undirected version:
502
+ In each iteration of the "while loop" the algorithm picks two disconnected
503
+ nodes v and w, of degree k and l correspondingly, for which nkk[k][l] has
504
+ not reached its target yet i.e. (for given k,l): n_edges_add < nkk[k][l].
505
+ It then adds edge (v,w) and always increases the number of edges in graph G
506
+ by one.
507
+
508
+ The intelligence of the algorithm lies in the fact that it is always
509
+ possible to add an edge between disconnected nodes v and w, for which
510
+ nkk[degree(v)][degree(w)] has not reached its target, even if one or both
511
+ nodes do not have free stubs. If either node v or w does not have a free
512
+ stub, we perform a "neighbor switch", an edge rewiring move that releases a
513
+ free stub while keeping nkk the same.
514
+
515
+ The difference for the directed version lies in the fact that neighbor
516
+ switches might not be able to rewire, but in these cases unsaturated nodes
517
+ can be reassigned to use instead, see [1] for detailed description and
518
+ proofs.
519
+
520
+ The algorithm continues for E (number of edges in the graph) iterations of
521
+ the "while loop", at which point all entries of the given nkk[k][l] have
522
+ reached their target values and the construction is complete.
523
+
524
+ References
525
+ ----------
526
+ [1] B. Tillman, A. Markopoulou, C. T. Butts & M. Gjoka,
527
+ "Construction of Directed 2K Graphs". In Proc. of KDD 2017.
528
+
529
+ Examples
530
+ --------
531
+ >>> in_degrees = [0, 1, 1, 2]
532
+ >>> out_degrees = [1, 1, 1, 1]
533
+ >>> nkk = {1: {1: 2, 2: 2}}
534
+ >>> G = nx.directed_joint_degree_graph(in_degrees, out_degrees, nkk)
535
+ >>>
536
+ """
537
+ if not is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
538
+ msg = "Input is not realizable as a simple graph"
539
+ raise nx.NetworkXError(msg)
540
+
541
+ # start with an empty directed graph.
542
+ G = nx.DiGraph()
543
+
544
+ # for a given group, keep the list of all node ids.
545
+ h_degree_nodelist_in = {}
546
+ h_degree_nodelist_out = {}
547
+ # for a given group, keep the list of all unsaturated node ids.
548
+ h_degree_nodelist_in_unsat = {}
549
+ h_degree_nodelist_out_unsat = {}
550
+ # for a given node, keep track of the remaining stubs to be added.
551
+ h_node_residual_out = {}
552
+ h_node_residual_in = {}
553
+ # for a given node, keep track of the partition id.
554
+ h_partition_out = {}
555
+ h_partition_in = {}
556
+ # keep track of non-chords between pairs of partition ids.
557
+ non_chords = {}
558
+
559
+ # populate data structures
560
+ for idx, i in enumerate(in_degrees):
561
+ idx = int(idx)
562
+ if i > 0:
563
+ h_degree_nodelist_in.setdefault(i, [])
564
+ h_degree_nodelist_in_unsat.setdefault(i, set())
565
+ h_degree_nodelist_in[i].append(idx)
566
+ h_degree_nodelist_in_unsat[i].add(idx)
567
+ h_node_residual_in[idx] = i
568
+ h_partition_in[idx] = i
569
+
570
+ for idx, o in enumerate(out_degrees):
571
+ o = out_degrees[idx]
572
+ non_chords[(o, in_degrees[idx])] = non_chords.get((o, in_degrees[idx]), 0) + 1
573
+ idx = int(idx)
574
+ if o > 0:
575
+ h_degree_nodelist_out.setdefault(o, [])
576
+ h_degree_nodelist_out_unsat.setdefault(o, set())
577
+ h_degree_nodelist_out[o].append(idx)
578
+ h_degree_nodelist_out_unsat[o].add(idx)
579
+ h_node_residual_out[idx] = o
580
+ h_partition_out[idx] = o
581
+
582
+ G.add_node(idx)
583
+
584
+ nk_in = {}
585
+ nk_out = {}
586
+ for p in h_degree_nodelist_in:
587
+ nk_in[p] = len(h_degree_nodelist_in[p])
588
+ for p in h_degree_nodelist_out:
589
+ nk_out[p] = len(h_degree_nodelist_out[p])
590
+
591
+ # iterate over every degree pair (k,l) and add the number of edges given
592
+ # for each pair.
593
+ for k in nkk:
594
+ for l in nkk[k]:
595
+ n_edges_add = nkk[k][l]
596
+
597
+ if n_edges_add > 0:
598
+ # chords contains a random set of potential edges.
599
+ chords = set()
600
+
601
+ k_len = nk_out[k]
602
+ l_len = nk_in[l]
603
+ chords_sample = seed.sample(
604
+ range(k_len * l_len), n_edges_add + non_chords.get((k, l), 0)
605
+ )
606
+
607
+ num = 0
608
+ while len(chords) < n_edges_add:
609
+ i = h_degree_nodelist_out[k][chords_sample[num] % k_len]
610
+ j = h_degree_nodelist_in[l][chords_sample[num] // k_len]
611
+ num += 1
612
+ if i != j:
613
+ chords.add((i, j))
614
+
615
+ # k_unsat and l_unsat consist of nodes of in/out degree k and l
616
+ # that are unsaturated i.e. those nodes that have at least one
617
+ # available stub
618
+ k_unsat = h_degree_nodelist_out_unsat[k]
619
+ l_unsat = h_degree_nodelist_in_unsat[l]
620
+
621
+ while n_edges_add > 0:
622
+ v, w = chords.pop()
623
+ chords.add((v, w))
624
+
625
+ # if node v has no free stubs then do neighbor switch.
626
+ if h_node_residual_out[v] == 0:
627
+ _v = _directed_neighbor_switch(
628
+ G,
629
+ v,
630
+ k_unsat,
631
+ h_node_residual_out,
632
+ chords,
633
+ h_partition_in,
634
+ l,
635
+ )
636
+ if _v is not None:
637
+ v = _v
638
+
639
+ # if node w has no free stubs then do neighbor switch.
640
+ if h_node_residual_in[w] == 0:
641
+ _w = _directed_neighbor_switch_rev(
642
+ G,
643
+ w,
644
+ l_unsat,
645
+ h_node_residual_in,
646
+ chords,
647
+ h_partition_out,
648
+ k,
649
+ )
650
+ if _w is not None:
651
+ w = _w
652
+
653
+ # add edge (v,w) and update data structures.
654
+ G.add_edge(v, w)
655
+ h_node_residual_out[v] -= 1
656
+ h_node_residual_in[w] -= 1
657
+ n_edges_add -= 1
658
+ chords.discard((v, w))
659
+
660
+ if h_node_residual_out[v] == 0:
661
+ k_unsat.discard(v)
662
+ if h_node_residual_in[w] == 0:
663
+ l_unsat.discard(w)
664
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/lattice.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating grid graphs and lattices
2
+
3
+ The :func:`grid_2d_graph`, :func:`triangular_lattice_graph`, and
4
+ :func:`hexagonal_lattice_graph` functions correspond to the three
5
+ `regular tilings of the plane`_, the square, triangular, and hexagonal
6
+ tilings, respectively. :func:`grid_graph` and :func:`hypercube_graph`
7
+ are similar for arbitrary dimensions. Useful relevant discussion can
8
+ be found about `Triangular Tiling`_, and `Square, Hex and Triangle Grids`_
9
+
10
+ .. _regular tilings of the plane: https://en.wikipedia.org/wiki/List_of_regular_polytopes_and_compounds#Euclidean_tilings
11
+ .. _Square, Hex and Triangle Grids: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
12
+ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
13
+
14
+ """
15
+
16
+ from itertools import repeat
17
+ from math import sqrt
18
+
19
+ import networkx as nx
20
+ from networkx.classes import set_node_attributes
21
+ from networkx.exception import NetworkXError
22
+ from networkx.generators.classic import cycle_graph, empty_graph, path_graph
23
+ from networkx.relabel import relabel_nodes
24
+ from networkx.utils import flatten, nodes_or_number, pairwise
25
+
26
+ __all__ = [
27
+ "grid_2d_graph",
28
+ "grid_graph",
29
+ "hypercube_graph",
30
+ "triangular_lattice_graph",
31
+ "hexagonal_lattice_graph",
32
+ ]
33
+
34
+
35
+ @nx._dispatchable(graphs=None, returns_graph=True)
36
+ @nodes_or_number([0, 1])
37
+ def grid_2d_graph(m, n, periodic=False, create_using=None):
38
+ """Returns the two-dimensional grid graph.
39
+
40
+ The grid graph has each node connected to its four nearest neighbors.
41
+
42
+ Parameters
43
+ ----------
44
+ m, n : int or iterable container of nodes
45
+ If an integer, nodes are from `range(n)`.
46
+ If a container, elements become the coordinate of the nodes.
47
+
48
+ periodic : bool or iterable
49
+ If `periodic` is True, both dimensions are periodic. If False, none
50
+ are periodic. If `periodic` is iterable, it should yield 2 bool
51
+ values indicating whether the 1st and 2nd axes, respectively, are
52
+ periodic.
53
+
54
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
55
+ Graph type to create. If graph instance, then cleared before populated.
56
+
57
+ Returns
58
+ -------
59
+ NetworkX graph
60
+ The (possibly periodic) grid graph of the specified dimensions.
61
+
62
+ """
63
+ G = empty_graph(0, create_using)
64
+ row_name, rows = m
65
+ col_name, cols = n
66
+ G.add_nodes_from((i, j) for i in rows for j in cols)
67
+ G.add_edges_from(((i, j), (pi, j)) for pi, i in pairwise(rows) for j in cols)
68
+ G.add_edges_from(((i, j), (i, pj)) for i in rows for pj, j in pairwise(cols))
69
+
70
+ try:
71
+ periodic_r, periodic_c = periodic
72
+ except TypeError:
73
+ periodic_r = periodic_c = periodic
74
+
75
+ if periodic_r and len(rows) > 2:
76
+ first = rows[0]
77
+ last = rows[-1]
78
+ G.add_edges_from(((first, j), (last, j)) for j in cols)
79
+ if periodic_c and len(cols) > 2:
80
+ first = cols[0]
81
+ last = cols[-1]
82
+ G.add_edges_from(((i, first), (i, last)) for i in rows)
83
+ # both directions for directed
84
+ if G.is_directed():
85
+ G.add_edges_from((v, u) for u, v in G.edges())
86
+ return G
87
+
88
+
89
+ @nx._dispatchable(graphs=None, returns_graph=True)
90
+ def grid_graph(dim, periodic=False):
91
+ """Returns the *n*-dimensional grid graph.
92
+
93
+ The dimension *n* is the length of the list `dim` and the size in
94
+ each dimension is the value of the corresponding list element.
95
+
96
+ Parameters
97
+ ----------
98
+ dim : list or tuple of numbers or iterables of nodes
99
+ 'dim' is a tuple or list with, for each dimension, either a number
100
+ that is the size of that dimension or an iterable of nodes for
101
+ that dimension. The dimension of the grid_graph is the length
102
+ of `dim`.
103
+
104
+ periodic : bool or iterable
105
+ If `periodic` is True, all dimensions are periodic. If False all
106
+ dimensions are not periodic. If `periodic` is iterable, it should
107
+ yield `dim` bool values each of which indicates whether the
108
+ corresponding axis is periodic.
109
+
110
+ Returns
111
+ -------
112
+ NetworkX graph
113
+ The (possibly periodic) grid graph of the specified dimensions.
114
+
115
+ Examples
116
+ --------
117
+ To produce a 2 by 3 by 4 grid graph, a graph on 24 nodes:
118
+
119
+ >>> from networkx import grid_graph
120
+ >>> G = grid_graph(dim=(2, 3, 4))
121
+ >>> len(G)
122
+ 24
123
+ >>> G = grid_graph(dim=(range(7, 9), range(3, 6)))
124
+ >>> len(G)
125
+ 6
126
+ """
127
+ from networkx.algorithms.operators.product import cartesian_product
128
+
129
+ if not dim:
130
+ return empty_graph(0)
131
+
132
+ try:
133
+ func = (cycle_graph if p else path_graph for p in periodic)
134
+ except TypeError:
135
+ func = repeat(cycle_graph if periodic else path_graph)
136
+
137
+ G = next(func)(dim[0])
138
+ for current_dim in dim[1:]:
139
+ Gnew = next(func)(current_dim)
140
+ G = cartesian_product(Gnew, G)
141
+ # graph G is done but has labels of the form (1, (2, (3, 1))) so relabel
142
+ H = relabel_nodes(G, flatten)
143
+ return H
144
+
145
+
146
+ @nx._dispatchable(graphs=None, returns_graph=True)
147
+ def hypercube_graph(n):
148
+ """Returns the *n*-dimensional hypercube graph.
149
+
150
+ The nodes are the integers between 0 and ``2 ** n - 1``, inclusive.
151
+
152
+ For more information on the hypercube graph, see the Wikipedia
153
+ article `Hypercube graph`_.
154
+
155
+ .. _Hypercube graph: https://en.wikipedia.org/wiki/Hypercube_graph
156
+
157
+ Parameters
158
+ ----------
159
+ n : int
160
+ The dimension of the hypercube.
161
+ The number of nodes in the graph will be ``2 ** n``.
162
+
163
+ Returns
164
+ -------
165
+ NetworkX graph
166
+ The hypercube graph of dimension *n*.
167
+ """
168
+ dim = n * [2]
169
+ G = grid_graph(dim)
170
+ return G
171
+
172
+
173
+ @nx._dispatchable(graphs=None, returns_graph=True)
174
+ def triangular_lattice_graph(
175
+ m, n, periodic=False, with_positions=True, create_using=None
176
+ ):
177
+ r"""Returns the $m$ by $n$ triangular lattice graph.
178
+
179
+ The `triangular lattice graph`_ is a two-dimensional `grid graph`_ in
180
+ which each square unit has a diagonal edge (each grid unit has a chord).
181
+
182
+ The returned graph has $m$ rows and $n$ columns of triangles. Rows and
183
+ columns include both triangles pointing up and down. Rows form a strip
184
+ of constant height. Columns form a series of diamond shapes, staggered
185
+ with the columns on either side. Another way to state the size is that
186
+ the nodes form a grid of `m+1` rows and `(n + 1) // 2` columns.
187
+ The odd row nodes are shifted horizontally relative to the even rows.
188
+
189
+ Directed graph types have edges pointed up or right.
190
+
191
+ Positions of nodes are computed by default or `with_positions is True`.
192
+ The position of each node (embedded in a euclidean plane) is stored in
193
+ the graph using equilateral triangles with sidelength 1.
194
+ The height between rows of nodes is thus $\sqrt(3)/2$.
195
+ Nodes lie in the first quadrant with the node $(0, 0)$ at the origin.
196
+
197
+ .. _triangular lattice graph: http://mathworld.wolfram.com/TriangularGrid.html
198
+ .. _grid graph: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
199
+ .. _Triangular Tiling: https://en.wikipedia.org/wiki/Triangular_tiling
200
+
201
+ Parameters
202
+ ----------
203
+ m : int
204
+ The number of rows in the lattice.
205
+
206
+ n : int
207
+ The number of columns in the lattice.
208
+
209
+ periodic : bool (default: False)
210
+ If True, join the boundary vertices of the grid using periodic
211
+ boundary conditions. The join between boundaries is the final row
212
+ and column of triangles. This means there is one row and one column
213
+ fewer nodes for the periodic lattice. Periodic lattices require
214
+ `m >= 3`, `n >= 5` and are allowed but misaligned if `m` or `n` are odd
215
+
216
+ with_positions : bool (default: True)
217
+ Store the coordinates of each node in the graph node attribute 'pos'.
218
+ The coordinates provide a lattice with equilateral triangles.
219
+ Periodic positions shift the nodes vertically in a nonlinear way so
220
+ the edges don't overlap so much.
221
+
222
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
223
+ Graph type to create. If graph instance, then cleared before populated.
224
+
225
+ Returns
226
+ -------
227
+ NetworkX graph
228
+ The *m* by *n* triangular lattice graph.
229
+ """
230
+ H = empty_graph(0, create_using)
231
+ if n == 0 or m == 0:
232
+ return H
233
+ if periodic:
234
+ if n < 5 or m < 3:
235
+ msg = f"m > 2 and n > 4 required for periodic. m={m}, n={n}"
236
+ raise NetworkXError(msg)
237
+
238
+ N = (n + 1) // 2 # number of nodes in row
239
+ rows = range(m + 1)
240
+ cols = range(N + 1)
241
+ # Make grid
242
+ H.add_edges_from(((i, j), (i + 1, j)) for j in rows for i in cols[:N])
243
+ H.add_edges_from(((i, j), (i, j + 1)) for j in rows[:m] for i in cols)
244
+ # add diagonals
245
+ H.add_edges_from(((i, j), (i + 1, j + 1)) for j in rows[1:m:2] for i in cols[:N])
246
+ H.add_edges_from(((i + 1, j), (i, j + 1)) for j in rows[:m:2] for i in cols[:N])
247
+ # identify boundary nodes if periodic
248
+ from networkx.algorithms.minors import contracted_nodes
249
+
250
+ if periodic is True:
251
+ for i in cols:
252
+ H = contracted_nodes(H, (i, 0), (i, m))
253
+ for j in rows[:m]:
254
+ H = contracted_nodes(H, (0, j), (N, j))
255
+ elif n % 2:
256
+ # remove extra nodes
257
+ H.remove_nodes_from((N, j) for j in rows[1::2])
258
+
259
+ # Add position node attributes
260
+ if with_positions:
261
+ ii = (i for i in cols for j in rows)
262
+ jj = (j for i in cols for j in rows)
263
+ xx = (0.5 * (j % 2) + i for i in cols for j in rows)
264
+ h = sqrt(3) / 2
265
+ if periodic:
266
+ yy = (h * j + 0.01 * i * i for i in cols for j in rows)
267
+ else:
268
+ yy = (h * j for i in cols for j in rows)
269
+ pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in H}
270
+ set_node_attributes(H, pos, "pos")
271
+ return H
272
+
273
+
274
+ @nx._dispatchable(graphs=None, returns_graph=True)
275
+ def hexagonal_lattice_graph(
276
+ m, n, periodic=False, with_positions=True, create_using=None
277
+ ):
278
+ """Returns an `m` by `n` hexagonal lattice graph.
279
+
280
+ The *hexagonal lattice graph* is a graph whose nodes and edges are
281
+ the `hexagonal tiling`_ of the plane.
282
+
283
+ The returned graph will have `m` rows and `n` columns of hexagons.
284
+ `Odd numbered columns`_ are shifted up relative to even numbered columns.
285
+
286
+ Positions of nodes are computed by default or `with_positions is True`.
287
+ Node positions creating the standard embedding in the plane
288
+ with sidelength 1 and are stored in the node attribute 'pos'.
289
+ `pos = nx.get_node_attributes(G, 'pos')` creates a dict ready for drawing.
290
+
291
+ .. _hexagonal tiling: https://en.wikipedia.org/wiki/Hexagonal_tiling
292
+ .. _Odd numbered columns: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/
293
+
294
+ Parameters
295
+ ----------
296
+ m : int
297
+ The number of rows of hexagons in the lattice.
298
+
299
+ n : int
300
+ The number of columns of hexagons in the lattice.
301
+
302
+ periodic : bool
303
+ Whether to make a periodic grid by joining the boundary vertices.
304
+ For this to work `n` must be even and both `n > 1` and `m > 1`.
305
+ The periodic connections create another row and column of hexagons
306
+ so these graphs have fewer nodes as boundary nodes are identified.
307
+
308
+ with_positions : bool (default: True)
309
+ Store the coordinates of each node in the graph node attribute 'pos'.
310
+ The coordinates provide a lattice with vertical columns of hexagons
311
+ offset to interleave and cover the plane.
312
+ Periodic positions shift the nodes vertically in a nonlinear way so
313
+ the edges don't overlap so much.
314
+
315
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
316
+ Graph type to create. If graph instance, then cleared before populated.
317
+ If graph is directed, edges will point up or right.
318
+
319
+ Returns
320
+ -------
321
+ NetworkX graph
322
+ The *m* by *n* hexagonal lattice graph.
323
+ """
324
+ G = empty_graph(0, create_using)
325
+ if m == 0 or n == 0:
326
+ return G
327
+ if periodic and (n % 2 == 1 or m < 2 or n < 2):
328
+ msg = "periodic hexagonal lattice needs m > 1, n > 1 and even n"
329
+ raise NetworkXError(msg)
330
+
331
+ M = 2 * m # twice as many nodes as hexagons vertically
332
+ rows = range(M + 2)
333
+ cols = range(n + 1)
334
+ # make lattice
335
+ col_edges = (((i, j), (i, j + 1)) for i in cols for j in rows[: M + 1])
336
+ row_edges = (((i, j), (i + 1, j)) for i in cols[:n] for j in rows if i % 2 == j % 2)
337
+ G.add_edges_from(col_edges)
338
+ G.add_edges_from(row_edges)
339
+ # Remove corner nodes with one edge
340
+ G.remove_node((0, M + 1))
341
+ G.remove_node((n, (M + 1) * (n % 2)))
342
+
343
+ # identify boundary nodes if periodic
344
+ from networkx.algorithms.minors import contracted_nodes
345
+
346
+ if periodic:
347
+ for i in cols[:n]:
348
+ G = contracted_nodes(G, (i, 0), (i, M))
349
+ for i in cols[1:]:
350
+ G = contracted_nodes(G, (i, 1), (i, M + 1))
351
+ for j in rows[1:M]:
352
+ G = contracted_nodes(G, (0, j), (n, j))
353
+ G.remove_node((n, M))
354
+
355
+ # calc position in embedded space
356
+ ii = (i for i in cols for j in rows)
357
+ jj = (j for i in cols for j in rows)
358
+ xx = (0.5 + i + i // 2 + (j % 2) * ((i % 2) - 0.5) for i in cols for j in rows)
359
+ h = sqrt(3) / 2
360
+ if periodic:
361
+ yy = (h * j + 0.01 * i * i for i in cols for j in rows)
362
+ else:
363
+ yy = (h * j for i in cols for j in rows)
364
+ # exclude nodes not in G
365
+ pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in G}
366
+ set_node_attributes(G, pos, "pos")
367
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/line.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating line graphs."""
2
+
3
+ from collections import defaultdict
4
+ from functools import partial
5
+ from itertools import combinations
6
+
7
+ import networkx as nx
8
+ from networkx.utils import arbitrary_element
9
+ from networkx.utils.decorators import not_implemented_for
10
+
11
+ __all__ = ["line_graph", "inverse_line_graph"]
12
+
13
+
14
+ @nx._dispatchable(returns_graph=True)
15
+ def line_graph(G, create_using=None):
16
+ r"""Returns the line graph of the graph or digraph `G`.
17
+
18
+ The line graph of a graph `G` has a node for each edge in `G` and an
19
+ edge joining those nodes if the two edges in `G` share a common node. For
20
+ directed graphs, nodes are adjacent exactly when the edges they represent
21
+ form a directed path of length two.
22
+
23
+ The nodes of the line graph are 2-tuples of nodes in the original graph (or
24
+ 3-tuples for multigraphs, with the key of the edge as the third element).
25
+
26
+ For information about self-loops and more discussion, see the **Notes**
27
+ section below.
28
+
29
+ Parameters
30
+ ----------
31
+ G : graph
32
+ A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
33
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
34
+ Graph type to create. If graph instance, then cleared before populated.
35
+
36
+ Returns
37
+ -------
38
+ L : graph
39
+ The line graph of G.
40
+
41
+ Examples
42
+ --------
43
+ >>> G = nx.star_graph(3)
44
+ >>> L = nx.line_graph(G)
45
+ >>> print(sorted(map(sorted, L.edges()))) # makes a 3-clique, K3
46
+ [[(0, 1), (0, 2)], [(0, 1), (0, 3)], [(0, 2), (0, 3)]]
47
+
48
+ Edge attributes from `G` are not copied over as node attributes in `L`, but
49
+ attributes can be copied manually:
50
+
51
+ >>> G = nx.path_graph(4)
52
+ >>> G.add_edges_from((u, v, {"tot": u + v}) for u, v in G.edges)
53
+ >>> G.edges(data=True)
54
+ EdgeDataView([(0, 1, {'tot': 1}), (1, 2, {'tot': 3}), (2, 3, {'tot': 5})])
55
+ >>> H = nx.line_graph(G)
56
+ >>> H.add_nodes_from((node, G.edges[node]) for node in H)
57
+ >>> H.nodes(data=True)
58
+ NodeDataView({(0, 1): {'tot': 1}, (2, 3): {'tot': 5}, (1, 2): {'tot': 3}})
59
+
60
+ Notes
61
+ -----
62
+ Graph, node, and edge data are not propagated to the new graph. For
63
+ undirected graphs, the nodes in G must be sortable, otherwise the
64
+ constructed line graph may not be correct.
65
+
66
+ *Self-loops in undirected graphs*
67
+
68
+ For an undirected graph `G` without multiple edges, each edge can be
69
+ written as a set `\{u, v\}`. Its line graph `L` has the edges of `G` as
70
+ its nodes. If `x` and `y` are two nodes in `L`, then `\{x, y\}` is an edge
71
+ in `L` if and only if the intersection of `x` and `y` is nonempty. Thus,
72
+ the set of all edges is determined by the set of all pairwise intersections
73
+ of edges in `G`.
74
+
75
+ Trivially, every edge in G would have a nonzero intersection with itself,
76
+ and so every node in `L` should have a self-loop. This is not so
77
+ interesting, and the original context of line graphs was with simple
78
+ graphs, which had no self-loops or multiple edges. The line graph was also
79
+ meant to be a simple graph and thus, self-loops in `L` are not part of the
80
+ standard definition of a line graph. In a pairwise intersection matrix,
81
+ this is analogous to excluding the diagonal entries from the line graph
82
+ definition.
83
+
84
+ Self-loops and multiple edges in `G` add nodes to `L` in a natural way, and
85
+ do not require any fundamental changes to the definition. It might be
86
+ argued that the self-loops we excluded before should now be included.
87
+ However, the self-loops are still "trivial" in some sense and thus, are
88
+ usually excluded.
89
+
90
+ *Self-loops in directed graphs*
91
+
92
+ For a directed graph `G` without multiple edges, each edge can be written
93
+ as a tuple `(u, v)`. Its line graph `L` has the edges of `G` as its
94
+ nodes. If `x` and `y` are two nodes in `L`, then `(x, y)` is an edge in `L`
95
+ if and only if the tail of `x` matches the head of `y`, for example, if `x
96
+ = (a, b)` and `y = (b, c)` for some vertices `a`, `b`, and `c` in `G`.
97
+
98
+ Due to the directed nature of the edges, it is no longer the case that
99
+ every edge in `G` should have a self-loop in `L`. Now, the only time
100
+ self-loops arise is if a node in `G` itself has a self-loop. So such
101
+ self-loops are no longer "trivial" but instead, represent essential
102
+ features of the topology of `G`. For this reason, the historical
103
+ development of line digraphs is such that self-loops are included. When the
104
+ graph `G` has multiple edges, once again only superficial changes are
105
+ required to the definition.
106
+
107
+ References
108
+ ----------
109
+ * Harary, Frank, and Norman, Robert Z., "Some properties of line digraphs",
110
+ Rend. Circ. Mat. Palermo, II. Ser. 9 (1960), 161--168.
111
+ * Hemminger, R. L.; Beineke, L. W. (1978), "Line graphs and line digraphs",
112
+ in Beineke, L. W.; Wilson, R. J., Selected Topics in Graph Theory,
113
+ Academic Press Inc., pp. 271--305.
114
+
115
+ """
116
+ if G.is_directed():
117
+ L = _lg_directed(G, create_using=create_using)
118
+ else:
119
+ L = _lg_undirected(G, selfloops=False, create_using=create_using)
120
+ return L
121
+
122
+
123
+ def _lg_directed(G, create_using=None):
124
+ """Returns the line graph L of the (multi)digraph G.
125
+
126
+ Edges in G appear as nodes in L, represented as tuples of the form (u,v)
127
+ or (u,v,key) if G is a multidigraph. A node in L corresponding to the edge
128
+ (u,v) is connected to every node corresponding to an edge (v,w).
129
+
130
+ Parameters
131
+ ----------
132
+ G : digraph
133
+ A directed graph or directed multigraph.
134
+ create_using : NetworkX graph constructor, optional
135
+ Graph type to create. If graph instance, then cleared before populated.
136
+ Default is to use the same graph class as `G`.
137
+
138
+ """
139
+ L = nx.empty_graph(0, create_using, default=G.__class__)
140
+
141
+ # Create a graph specific edge function.
142
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
143
+
144
+ for from_node in get_edges():
145
+ # from_node is: (u,v) or (u,v,key)
146
+ L.add_node(from_node)
147
+ for to_node in get_edges(from_node[1]):
148
+ L.add_edge(from_node, to_node)
149
+
150
+ return L
151
+
152
+
153
+ def _lg_undirected(G, selfloops=False, create_using=None):
154
+ """Returns the line graph L of the (multi)graph G.
155
+
156
+ Edges in G appear as nodes in L, represented as sorted tuples of the form
157
+ (u,v), or (u,v,key) if G is a multigraph. A node in L corresponding to
158
+ the edge {u,v} is connected to every node corresponding to an edge that
159
+ involves u or v.
160
+
161
+ Parameters
162
+ ----------
163
+ G : graph
164
+ An undirected graph or multigraph.
165
+ selfloops : bool
166
+ If `True`, then self-loops are included in the line graph. If `False`,
167
+ they are excluded.
168
+ create_using : NetworkX graph constructor, optional (default=nx.Graph)
169
+ Graph type to create. If graph instance, then cleared before populated.
170
+
171
+ Notes
172
+ -----
173
+ The standard algorithm for line graphs of undirected graphs does not
174
+ produce self-loops.
175
+
176
+ """
177
+ L = nx.empty_graph(0, create_using, default=G.__class__)
178
+
179
+ # Graph specific functions for edges.
180
+ get_edges = partial(G.edges, keys=True) if G.is_multigraph() else G.edges
181
+
182
+ # Determine if we include self-loops or not.
183
+ shift = 0 if selfloops else 1
184
+
185
+ # Introduce numbering of nodes
186
+ node_index = {n: i for i, n in enumerate(G)}
187
+
188
+ # Lift canonical representation of nodes to edges in line graph
189
+ edge_key_function = lambda edge: (node_index[edge[0]], node_index[edge[1]])
190
+
191
+ edges = set()
192
+ for u in G:
193
+ # Label nodes as a sorted tuple of nodes in original graph.
194
+ # Decide on representation of {u, v} as (u, v) or (v, u) depending on node_index.
195
+ # -> This ensures a canonical representation and avoids comparing values of different types.
196
+ nodes = [tuple(sorted(x[:2], key=node_index.get)) + x[2:] for x in get_edges(u)]
197
+
198
+ if len(nodes) == 1:
199
+ # Then the edge will be an isolated node in L.
200
+ L.add_node(nodes[0])
201
+
202
+ # Add a clique of `nodes` to graph. To prevent double adding edges,
203
+ # especially important for multigraphs, we store the edges in
204
+ # canonical form in a set.
205
+ for i, a in enumerate(nodes):
206
+ edges.update(
207
+ [
208
+ tuple(sorted((a, b), key=edge_key_function))
209
+ for b in nodes[i + shift :]
210
+ ]
211
+ )
212
+
213
+ L.add_edges_from(edges)
214
+ return L
215
+
216
+
217
+ @not_implemented_for("directed")
218
+ @not_implemented_for("multigraph")
219
+ @nx._dispatchable(returns_graph=True)
220
+ def inverse_line_graph(G):
221
+ """Returns the inverse line graph of graph G.
222
+
223
+ If H is a graph, and G is the line graph of H, such that G = L(H).
224
+ Then H is the inverse line graph of G.
225
+
226
+ Not all graphs are line graphs and these do not have an inverse line graph.
227
+ In these cases this function raises a NetworkXError.
228
+
229
+ Parameters
230
+ ----------
231
+ G : graph
232
+ A NetworkX Graph
233
+
234
+ Returns
235
+ -------
236
+ H : graph
237
+ The inverse line graph of G.
238
+
239
+ Raises
240
+ ------
241
+ NetworkXNotImplemented
242
+ If G is directed or a multigraph
243
+
244
+ NetworkXError
245
+ If G is not a line graph
246
+
247
+ Notes
248
+ -----
249
+ This is an implementation of the Roussopoulos algorithm[1]_.
250
+
251
+ If G consists of multiple components, then the algorithm doesn't work.
252
+ You should invert every component separately:
253
+
254
+ >>> K5 = nx.complete_graph(5)
255
+ >>> P4 = nx.Graph([("a", "b"), ("b", "c"), ("c", "d")])
256
+ >>> G = nx.union(K5, P4)
257
+ >>> root_graphs = []
258
+ >>> for comp in nx.connected_components(G):
259
+ ... root_graphs.append(nx.inverse_line_graph(G.subgraph(comp)))
260
+ >>> len(root_graphs)
261
+ 2
262
+
263
+ References
264
+ ----------
265
+ .. [1] Roussopoulos, N.D. , "A max {m, n} algorithm for determining the graph H from
266
+ its line graph G", Information Processing Letters 2, (1973), 108--112, ISSN 0020-0190,
267
+ `DOI link <https://doi.org/10.1016/0020-0190(73)90029-X>`_
268
+
269
+ """
270
+ if G.number_of_nodes() == 0:
271
+ return nx.empty_graph(1)
272
+ elif G.number_of_nodes() == 1:
273
+ v = arbitrary_element(G)
274
+ a = (v, 0)
275
+ b = (v, 1)
276
+ H = nx.Graph([(a, b)])
277
+ return H
278
+ elif G.number_of_nodes() > 1 and G.number_of_edges() == 0:
279
+ msg = (
280
+ "inverse_line_graph() doesn't work on an edgeless graph. "
281
+ "Please use this function on each component separately."
282
+ )
283
+ raise nx.NetworkXError(msg)
284
+
285
+ if nx.number_of_selfloops(G) != 0:
286
+ msg = (
287
+ "A line graph as generated by NetworkX has no selfloops, so G has no "
288
+ "inverse line graph. Please remove the selfloops from G and try again."
289
+ )
290
+ raise nx.NetworkXError(msg)
291
+
292
+ starting_cell = _select_starting_cell(G)
293
+ P = _find_partition(G, starting_cell)
294
+ # count how many times each vertex appears in the partition set
295
+ P_count = {u: 0 for u in G.nodes}
296
+ for p in P:
297
+ for u in p:
298
+ P_count[u] += 1
299
+
300
+ if max(P_count.values()) > 2:
301
+ msg = "G is not a line graph (vertex found in more than two partition cells)"
302
+ raise nx.NetworkXError(msg)
303
+ W = tuple((u,) for u in P_count if P_count[u] == 1)
304
+ H = nx.Graph()
305
+ H.add_nodes_from(P)
306
+ H.add_nodes_from(W)
307
+ for a, b in combinations(H.nodes, 2):
308
+ if any(a_bit in b for a_bit in a):
309
+ H.add_edge(a, b)
310
+ return H
311
+
312
+
313
+ def _triangles(G, e):
314
+ """Return list of all triangles containing edge e"""
315
+ u, v = e
316
+ if u not in G:
317
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
318
+ if v not in G[u]:
319
+ raise nx.NetworkXError(f"Edge ({u}, {v}) not in graph")
320
+ triangle_list = []
321
+ for x in G[u]:
322
+ if x in G[v]:
323
+ triangle_list.append((u, v, x))
324
+ return triangle_list
325
+
326
+
327
+ def _odd_triangle(G, T):
328
+ """Test whether T is an odd triangle in G
329
+
330
+ Parameters
331
+ ----------
332
+ G : NetworkX Graph
333
+ T : 3-tuple of vertices forming triangle in G
334
+
335
+ Returns
336
+ -------
337
+ True is T is an odd triangle
338
+ False otherwise
339
+
340
+ Raises
341
+ ------
342
+ NetworkXError
343
+ T is not a triangle in G
344
+
345
+ Notes
346
+ -----
347
+ An odd triangle is one in which there exists another vertex in G which is
348
+ adjacent to either exactly one or exactly all three of the vertices in the
349
+ triangle.
350
+
351
+ """
352
+ for u in T:
353
+ if u not in G.nodes():
354
+ raise nx.NetworkXError(f"Vertex {u} not in graph")
355
+ for e in list(combinations(T, 2)):
356
+ if e[0] not in G[e[1]]:
357
+ raise nx.NetworkXError(f"Edge ({e[0]}, {e[1]}) not in graph")
358
+
359
+ T_nbrs = defaultdict(int)
360
+ for t in T:
361
+ for v in G[t]:
362
+ if v not in T:
363
+ T_nbrs[v] += 1
364
+ return any(T_nbrs[v] in [1, 3] for v in T_nbrs)
365
+
366
+
367
+ def _find_partition(G, starting_cell):
368
+ """Find a partition of the vertices of G into cells of complete graphs
369
+
370
+ Parameters
371
+ ----------
372
+ G : NetworkX Graph
373
+ starting_cell : tuple of vertices in G which form a cell
374
+
375
+ Returns
376
+ -------
377
+ List of tuples of vertices of G
378
+
379
+ Raises
380
+ ------
381
+ NetworkXError
382
+ If a cell is not a complete subgraph then G is not a line graph
383
+ """
384
+ G_partition = G.copy()
385
+ P = [starting_cell] # partition set
386
+ G_partition.remove_edges_from(list(combinations(starting_cell, 2)))
387
+ # keep list of partitioned nodes which might have an edge in G_partition
388
+ partitioned_vertices = list(starting_cell)
389
+ while G_partition.number_of_edges() > 0:
390
+ # there are still edges left and so more cells to be made
391
+ u = partitioned_vertices.pop()
392
+ deg_u = len(G_partition[u])
393
+ if deg_u != 0:
394
+ # if u still has edges then we need to find its other cell
395
+ # this other cell must be a complete subgraph or else G is
396
+ # not a line graph
397
+ new_cell = [u] + list(G_partition[u])
398
+ for u in new_cell:
399
+ for v in new_cell:
400
+ if (u != v) and (v not in G_partition[u]):
401
+ msg = (
402
+ "G is not a line graph "
403
+ "(partition cell not a complete subgraph)"
404
+ )
405
+ raise nx.NetworkXError(msg)
406
+ P.append(tuple(new_cell))
407
+ G_partition.remove_edges_from(list(combinations(new_cell, 2)))
408
+ partitioned_vertices += new_cell
409
+ return P
410
+
411
+
412
+ def _select_starting_cell(G, starting_edge=None):
413
+ """Select a cell to initiate _find_partition
414
+
415
+ Parameters
416
+ ----------
417
+ G : NetworkX Graph
418
+ starting_edge: an edge to build the starting cell from
419
+
420
+ Returns
421
+ -------
422
+ Tuple of vertices in G
423
+
424
+ Raises
425
+ ------
426
+ NetworkXError
427
+ If it is determined that G is not a line graph
428
+
429
+ Notes
430
+ -----
431
+ If starting edge not specified then pick an arbitrary edge - doesn't
432
+ matter which. However, this function may call itself requiring a
433
+ specific starting edge. Note that the r, s notation for counting
434
+ triangles is the same as in the Roussopoulos paper cited above.
435
+ """
436
+ if starting_edge is None:
437
+ e = arbitrary_element(G.edges())
438
+ else:
439
+ e = starting_edge
440
+ if e[0] not in G.nodes():
441
+ raise nx.NetworkXError(f"Vertex {e[0]} not in graph")
442
+ if e[1] not in G[e[0]]:
443
+ msg = f"starting_edge ({e[0]}, {e[1]}) is not in the Graph"
444
+ raise nx.NetworkXError(msg)
445
+ e_triangles = _triangles(G, e)
446
+ r = len(e_triangles)
447
+ if r == 0:
448
+ # there are no triangles containing e, so the starting cell is just e
449
+ starting_cell = e
450
+ elif r == 1:
451
+ # there is exactly one triangle, T, containing e. If other 2 edges
452
+ # of T belong only to this triangle then T is starting cell
453
+ T = e_triangles[0]
454
+ a, b, c = T
455
+ # ab was original edge so check the other 2 edges
456
+ ac_edges = len(_triangles(G, (a, c)))
457
+ bc_edges = len(_triangles(G, (b, c)))
458
+ if ac_edges == 1:
459
+ if bc_edges == 1:
460
+ starting_cell = T
461
+ else:
462
+ return _select_starting_cell(G, starting_edge=(b, c))
463
+ else:
464
+ return _select_starting_cell(G, starting_edge=(a, c))
465
+ else:
466
+ # r >= 2 so we need to count the number of odd triangles, s
467
+ s = 0
468
+ odd_triangles = []
469
+ for T in e_triangles:
470
+ if _odd_triangle(G, T):
471
+ s += 1
472
+ odd_triangles.append(T)
473
+ if r == 2 and s == 0:
474
+ # in this case either triangle works, so just use T
475
+ starting_cell = T
476
+ elif r - 1 <= s <= r:
477
+ # check if odd triangles containing e form complete subgraph
478
+ triangle_nodes = set()
479
+ for T in odd_triangles:
480
+ for x in T:
481
+ triangle_nodes.add(x)
482
+
483
+ for u in triangle_nodes:
484
+ for v in triangle_nodes:
485
+ if u != v and (v not in G[u]):
486
+ msg = (
487
+ "G is not a line graph (odd triangles "
488
+ "do not form complete subgraph)"
489
+ )
490
+ raise nx.NetworkXError(msg)
491
+ # otherwise then we can use this as the starting cell
492
+ starting_cell = tuple(triangle_nodes)
493
+
494
+ else:
495
+ msg = (
496
+ "G is not a line graph (incorrect number of "
497
+ "odd triangles around starting edge)"
498
+ )
499
+ raise nx.NetworkXError(msg)
500
+ return starting_cell
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/mycielski.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions related to the Mycielski Operation and the Mycielskian family
2
+ of graphs.
3
+
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.utils import not_implemented_for
8
+
9
+ __all__ = ["mycielskian", "mycielski_graph"]
10
+
11
+
12
+ @not_implemented_for("directed")
13
+ @not_implemented_for("multigraph")
14
+ @nx._dispatchable(returns_graph=True)
15
+ def mycielskian(G, iterations=1):
16
+ r"""Returns the Mycielskian of a simple, undirected graph G
17
+
18
+ The Mycielskian of graph preserves a graph's triangle free
19
+ property while increasing the chromatic number by 1.
20
+
21
+ The Mycielski Operation on a graph, :math:`G=(V, E)`, constructs a new
22
+ graph with :math:`2|V| + 1` nodes and :math:`3|E| + |V|` edges.
23
+
24
+ The construction is as follows:
25
+
26
+ Let :math:`V = {0, ..., n-1}`. Construct another vertex set
27
+ :math:`U = {n, ..., 2n}` and a vertex, `w`.
28
+ Construct a new graph, `M`, with vertices :math:`U \bigcup V \bigcup w`.
29
+ For edges, :math:`(u, v) \in E` add edges :math:`(u, v), (u, v + n)`, and
30
+ :math:`(u + n, v)` to M. Finally, for all vertices :math:`u \in U`, add
31
+ edge :math:`(u, w)` to M.
32
+
33
+ The Mycielski Operation can be done multiple times by repeating the above
34
+ process iteratively.
35
+
36
+ More information can be found at https://en.wikipedia.org/wiki/Mycielskian
37
+
38
+ Parameters
39
+ ----------
40
+ G : graph
41
+ A simple, undirected NetworkX graph
42
+ iterations : int
43
+ The number of iterations of the Mycielski operation to
44
+ perform on G. Defaults to 1. Must be a non-negative integer.
45
+
46
+ Returns
47
+ -------
48
+ M : graph
49
+ The Mycielskian of G after the specified number of iterations.
50
+
51
+ Notes
52
+ -----
53
+ Graph, node, and edge data are not necessarily propagated to the new graph.
54
+
55
+ """
56
+
57
+ M = nx.convert_node_labels_to_integers(G)
58
+
59
+ for i in range(iterations):
60
+ n = M.number_of_nodes()
61
+ M.add_nodes_from(range(n, 2 * n))
62
+ old_edges = list(M.edges())
63
+ M.add_edges_from((u, v + n) for u, v in old_edges)
64
+ M.add_edges_from((u + n, v) for u, v in old_edges)
65
+ M.add_node(2 * n)
66
+ M.add_edges_from((u + n, 2 * n) for u in range(n))
67
+
68
+ return M
69
+
70
+
71
+ @nx._dispatchable(graphs=None, returns_graph=True)
72
+ def mycielski_graph(n):
73
+ """Generator for the n_th Mycielski Graph.
74
+
75
+ The Mycielski family of graphs is an infinite set of graphs.
76
+ :math:`M_1` is the singleton graph, :math:`M_2` is two vertices with an
77
+ edge, and, for :math:`i > 2`, :math:`M_i` is the Mycielskian of
78
+ :math:`M_{i-1}`.
79
+
80
+ More information can be found at
81
+ http://mathworld.wolfram.com/MycielskiGraph.html
82
+
83
+ Parameters
84
+ ----------
85
+ n : int
86
+ The desired Mycielski Graph.
87
+
88
+ Returns
89
+ -------
90
+ M : graph
91
+ The n_th Mycielski Graph
92
+
93
+ Notes
94
+ -----
95
+ The first graph in the Mycielski sequence is the singleton graph.
96
+ The Mycielskian of this graph is not the :math:`P_2` graph, but rather the
97
+ :math:`P_2` graph with an extra, isolated vertex. The second Mycielski
98
+ graph is the :math:`P_2` graph, so the first two are hard coded.
99
+ The remaining graphs are generated using the Mycielski operation.
100
+
101
+ """
102
+
103
+ if n < 1:
104
+ raise nx.NetworkXError("must satisfy n >= 1")
105
+
106
+ if n == 1:
107
+ return nx.empty_graph(1)
108
+
109
+ else:
110
+ return mycielskian(nx.path_graph(2), n - 2)
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/random_graphs.py ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generators for random graphs.
3
+
4
+ """
5
+
6
+ import itertools
7
+ import math
8
+ from collections import defaultdict
9
+
10
+ import networkx as nx
11
+ from networkx.utils import py_random_state
12
+
13
+ from ..utils.misc import check_create_using
14
+ from .classic import complete_graph, empty_graph, path_graph, star_graph
15
+ from .degree_seq import degree_sequence_tree
16
+
17
+ __all__ = [
18
+ "fast_gnp_random_graph",
19
+ "gnp_random_graph",
20
+ "dense_gnm_random_graph",
21
+ "gnm_random_graph",
22
+ "erdos_renyi_graph",
23
+ "binomial_graph",
24
+ "newman_watts_strogatz_graph",
25
+ "watts_strogatz_graph",
26
+ "connected_watts_strogatz_graph",
27
+ "random_regular_graph",
28
+ "barabasi_albert_graph",
29
+ "dual_barabasi_albert_graph",
30
+ "extended_barabasi_albert_graph",
31
+ "powerlaw_cluster_graph",
32
+ "random_lobster",
33
+ "random_shell_graph",
34
+ "random_powerlaw_tree",
35
+ "random_powerlaw_tree_sequence",
36
+ "random_kernel_graph",
37
+ ]
38
+
39
+
40
+ @py_random_state(2)
41
+ @nx._dispatchable(graphs=None, returns_graph=True)
42
+ def fast_gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
43
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
44
+ a binomial graph.
45
+
46
+ Parameters
47
+ ----------
48
+ n : int
49
+ The number of nodes.
50
+ p : float
51
+ Probability for edge creation.
52
+ seed : integer, random_state, or None (default)
53
+ Indicator of random number generation state.
54
+ See :ref:`Randomness<randomness>`.
55
+ directed : bool, optional (default=False)
56
+ If True, this function returns a directed graph.
57
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
58
+ Graph type to create. If graph instance, then cleared before populated.
59
+ Multigraph types are not supported and raise a ``NetworkXError``.
60
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
61
+
62
+ Notes
63
+ -----
64
+ The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
65
+ (undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.
66
+
67
+ This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
68
+ edges, which equals $p n (n - 1) / 2$. This should be faster than
69
+ :func:`gnp_random_graph` when $p$ is small and the expected number of edges
70
+ is small (that is, the graph is sparse).
71
+
72
+ See Also
73
+ --------
74
+ gnp_random_graph
75
+
76
+ References
77
+ ----------
78
+ .. [1] Vladimir Batagelj and Ulrik Brandes,
79
+ "Efficient generation of large random networks",
80
+ Phys. Rev. E, 71, 036113, 2005.
81
+ """
82
+ default = nx.DiGraph if directed else nx.Graph
83
+ create_using = check_create_using(
84
+ create_using, directed=directed, multigraph=False, default=default
85
+ )
86
+ if p <= 0 or p >= 1:
87
+ return nx.gnp_random_graph(
88
+ n, p, seed=seed, directed=directed, create_using=create_using
89
+ )
90
+
91
+ G = empty_graph(n, create_using=create_using)
92
+
93
+ lp = math.log(1.0 - p)
94
+
95
+ if directed:
96
+ v = 1
97
+ w = -1
98
+ while v < n:
99
+ lr = math.log(1.0 - seed.random())
100
+ w = w + 1 + int(lr / lp)
101
+ while w >= v and v < n:
102
+ w = w - v
103
+ v = v + 1
104
+ if v < n:
105
+ G.add_edge(w, v)
106
+
107
+ # Nodes in graph are from 0,n-1 (start with v as the second node index).
108
+ v = 1
109
+ w = -1
110
+ while v < n:
111
+ lr = math.log(1.0 - seed.random())
112
+ w = w + 1 + int(lr / lp)
113
+ while w >= v and v < n:
114
+ w = w - v
115
+ v = v + 1
116
+ if v < n:
117
+ G.add_edge(v, w)
118
+ return G
119
+
120
+
121
+ @py_random_state(2)
122
+ @nx._dispatchable(graphs=None, returns_graph=True)
123
+ def gnp_random_graph(n, p, seed=None, directed=False, *, create_using=None):
124
+ """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph
125
+ or a binomial graph.
126
+
127
+ The $G_{n,p}$ model chooses each of the possible edges with probability $p$.
128
+
129
+ Parameters
130
+ ----------
131
+ n : int
132
+ The number of nodes.
133
+ p : float
134
+ Probability for edge creation.
135
+ seed : integer, random_state, or None (default)
136
+ Indicator of random number generation state.
137
+ See :ref:`Randomness<randomness>`.
138
+ directed : bool, optional (default=False)
139
+ If True, this function returns a directed graph.
140
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
141
+ Graph type to create. If graph instance, then cleared before populated.
142
+ Multigraph types are not supported and raise a ``NetworkXError``.
143
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
144
+
145
+ See Also
146
+ --------
147
+ fast_gnp_random_graph
148
+
149
+ Notes
150
+ -----
151
+ This algorithm [2]_ runs in $O(n^2)$ time. For sparse graphs (that is, for
152
+ small values of $p$), :func:`fast_gnp_random_graph` is a faster algorithm.
153
+
154
+ :func:`binomial_graph` and :func:`erdos_renyi_graph` are
155
+ aliases for :func:`gnp_random_graph`.
156
+
157
+ >>> nx.binomial_graph is nx.gnp_random_graph
158
+ True
159
+ >>> nx.erdos_renyi_graph is nx.gnp_random_graph
160
+ True
161
+
162
+ References
163
+ ----------
164
+ .. [1] P. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
165
+ .. [2] E. N. Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
166
+ """
167
+ default = nx.DiGraph if directed else nx.Graph
168
+ create_using = check_create_using(
169
+ create_using, directed=directed, multigraph=False, default=default
170
+ )
171
+ if p >= 1:
172
+ return complete_graph(n, create_using=create_using)
173
+
174
+ G = nx.empty_graph(n, create_using=create_using)
175
+ if p <= 0:
176
+ return G
177
+
178
+ edgetool = itertools.permutations if directed else itertools.combinations
179
+ for e in edgetool(range(n), 2):
180
+ if seed.random() < p:
181
+ G.add_edge(*e)
182
+ return G
183
+
184
+
185
+ # add some aliases to common names
186
+ binomial_graph = gnp_random_graph
187
+ erdos_renyi_graph = gnp_random_graph
188
+
189
+
190
+ @py_random_state(2)
191
+ @nx._dispatchable(graphs=None, returns_graph=True)
192
+ def dense_gnm_random_graph(n, m, seed=None, *, create_using=None):
193
+ """Returns a $G_{n,m}$ random graph.
194
+
195
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
196
+ of all graphs with $n$ nodes and $m$ edges.
197
+
198
+ This algorithm should be faster than :func:`gnm_random_graph` for dense
199
+ graphs.
200
+
201
+ Parameters
202
+ ----------
203
+ n : int
204
+ The number of nodes.
205
+ m : int
206
+ The number of edges.
207
+ seed : integer, random_state, or None (default)
208
+ Indicator of random number generation state.
209
+ See :ref:`Randomness<randomness>`.
210
+ create_using : Graph constructor, optional (default=nx.Graph)
211
+ Graph type to create. If graph instance, then cleared before populated.
212
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
213
+
214
+ See Also
215
+ --------
216
+ gnm_random_graph
217
+
218
+ Notes
219
+ -----
220
+ Algorithm by Keith M. Briggs Mar 31, 2006.
221
+ Inspired by Knuth's Algorithm S (Selection sampling technique),
222
+ in section 3.4.2 of [1]_.
223
+
224
+ References
225
+ ----------
226
+ .. [1] Donald E. Knuth, The Art of Computer Programming,
227
+ Volume 2/Seminumerical algorithms, Third Edition, Addison-Wesley, 1997.
228
+ """
229
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
230
+ mmax = n * (n - 1) // 2
231
+ if m >= mmax:
232
+ return complete_graph(n, create_using)
233
+ G = empty_graph(n, create_using)
234
+
235
+ if n == 1:
236
+ return G
237
+
238
+ u = 0
239
+ v = 1
240
+ t = 0
241
+ k = 0
242
+ while True:
243
+ if seed.randrange(mmax - t) < m - k:
244
+ G.add_edge(u, v)
245
+ k += 1
246
+ if k == m:
247
+ return G
248
+ t += 1
249
+ v += 1
250
+ if v == n: # go to next row of adjacency matrix
251
+ u += 1
252
+ v = u + 1
253
+
254
+
255
+ @py_random_state(2)
256
+ @nx._dispatchable(graphs=None, returns_graph=True)
257
+ def gnm_random_graph(n, m, seed=None, directed=False, *, create_using=None):
258
+ """Returns a $G_{n,m}$ random graph.
259
+
260
+ In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
261
+ of all graphs with $n$ nodes and $m$ edges.
262
+
263
+ This algorithm should be faster than :func:`dense_gnm_random_graph` for
264
+ sparse graphs.
265
+
266
+ Parameters
267
+ ----------
268
+ n : int
269
+ The number of nodes.
270
+ m : int
271
+ The number of edges.
272
+ seed : integer, random_state, or None (default)
273
+ Indicator of random number generation state.
274
+ See :ref:`Randomness<randomness>`.
275
+ directed : bool, optional (default=False)
276
+ If True return a directed graph
277
+ create_using : Graph constructor, optional (default=nx.Graph or nx.DiGraph)
278
+ Graph type to create. If graph instance, then cleared before populated.
279
+ Multigraph types are not supported and raise a ``NetworkXError``.
280
+ By default NetworkX Graph or DiGraph are used depending on `directed`.
281
+
282
+ See also
283
+ --------
284
+ dense_gnm_random_graph
285
+
286
+ """
287
+ default = nx.DiGraph if directed else nx.Graph
288
+ create_using = check_create_using(
289
+ create_using, directed=directed, multigraph=False, default=default
290
+ )
291
+ if n == 1:
292
+ return nx.empty_graph(n, create_using=create_using)
293
+ max_edges = n * (n - 1) if directed else n * (n - 1) / 2.0
294
+ if m >= max_edges:
295
+ return complete_graph(n, create_using=create_using)
296
+
297
+ G = nx.empty_graph(n, create_using=create_using)
298
+ nlist = list(G)
299
+ edge_count = 0
300
+ while edge_count < m:
301
+ # generate random edge,u,v
302
+ u = seed.choice(nlist)
303
+ v = seed.choice(nlist)
304
+ if u == v or G.has_edge(u, v):
305
+ continue
306
+ else:
307
+ G.add_edge(u, v)
308
+ edge_count = edge_count + 1
309
+ return G
310
+
311
+
312
+ @py_random_state(3)
313
+ @nx._dispatchable(graphs=None, returns_graph=True)
314
+ def newman_watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
315
+ """Returns a Newman–Watts–Strogatz small-world graph.
316
+
317
+ Parameters
318
+ ----------
319
+ n : int
320
+ The number of nodes.
321
+ k : int
322
+ Each node is joined with its `k` nearest neighbors in a ring
323
+ topology.
324
+ p : float
325
+ The probability of adding a new edge for each edge.
326
+ seed : integer, random_state, or None (default)
327
+ Indicator of random number generation state.
328
+ See :ref:`Randomness<randomness>`.
329
+ create_using : Graph constructor, optional (default=nx.Graph)
330
+ Graph type to create. If graph instance, then cleared before populated.
331
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
332
+
333
+ Notes
334
+ -----
335
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is
336
+ connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$
337
+ is odd). Then shortcuts are created by adding new edges as follows: for
338
+ each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest
339
+ neighbors" with probability $p$ add a new edge $(u, w)$ with
340
+ randomly-chosen existing node $w$. In contrast with
341
+ :func:`watts_strogatz_graph`, no edges are removed.
342
+
343
+ See Also
344
+ --------
345
+ watts_strogatz_graph
346
+
347
+ References
348
+ ----------
349
+ .. [1] M. E. J. Newman and D. J. Watts,
350
+ Renormalization group analysis of the small-world network model,
351
+ Physics Letters A, 263, 341, 1999.
352
+ https://doi.org/10.1016/S0375-9601(99)00757-4
353
+ """
354
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
355
+ if k > n:
356
+ raise nx.NetworkXError("k>=n, choose smaller k or larger n")
357
+
358
+ # If k == n the graph return is a complete graph
359
+ if k == n:
360
+ return nx.complete_graph(n, create_using)
361
+
362
+ G = empty_graph(n, create_using)
363
+ nlist = list(G.nodes())
364
+ fromv = nlist
365
+ # connect the k/2 neighbors
366
+ for j in range(1, k // 2 + 1):
367
+ tov = fromv[j:] + fromv[0:j] # the first j are now last
368
+ for i in range(len(fromv)):
369
+ G.add_edge(fromv[i], tov[i])
370
+ # for each edge u-v, with probability p, randomly select existing
371
+ # node w and add new edge u-w
372
+ e = list(G.edges())
373
+ for u, v in e:
374
+ if seed.random() < p:
375
+ w = seed.choice(nlist)
376
+ # no self-loops and reject if edge u-w exists
377
+ # is that the correct NWS model?
378
+ while w == u or G.has_edge(u, w):
379
+ w = seed.choice(nlist)
380
+ if G.degree(u) >= n - 1:
381
+ break # skip this rewiring
382
+ else:
383
+ G.add_edge(u, w)
384
+ return G
385
+
386
+
387
+ @py_random_state(3)
388
+ @nx._dispatchable(graphs=None, returns_graph=True)
389
+ def watts_strogatz_graph(n, k, p, seed=None, *, create_using=None):
390
+ """Returns a Watts–Strogatz small-world graph.
391
+
392
+ Parameters
393
+ ----------
394
+ n : int
395
+ The number of nodes
396
+ k : int
397
+ Each node is joined with its `k` nearest neighbors in a ring
398
+ topology.
399
+ p : float
400
+ The probability of rewiring each edge
401
+ seed : integer, random_state, or None (default)
402
+ Indicator of random number generation state.
403
+ See :ref:`Randomness<randomness>`.
404
+ create_using : Graph constructor, optional (default=nx.Graph)
405
+ Graph type to create. If graph instance, then cleared before populated.
406
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
407
+
408
+ See Also
409
+ --------
410
+ newman_watts_strogatz_graph
411
+ connected_watts_strogatz_graph
412
+
413
+ Notes
414
+ -----
415
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
416
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
417
+ Then shortcuts are created by replacing some edges as follows: for each
418
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
419
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
420
+ random choice of existing node $w$.
421
+
422
+ In contrast with :func:`newman_watts_strogatz_graph`, the random rewiring
423
+ does not increase the number of edges. The rewired graph is not guaranteed
424
+ to be connected as in :func:`connected_watts_strogatz_graph`.
425
+
426
+ References
427
+ ----------
428
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
429
+ Collective dynamics of small-world networks,
430
+ Nature, 393, pp. 440--442, 1998.
431
+ """
432
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
433
+ if k > n:
434
+ raise nx.NetworkXError("k>n, choose smaller k or larger n")
435
+
436
+ # If k == n, the graph is complete not Watts-Strogatz
437
+ if k == n:
438
+ G = nx.complete_graph(n, create_using)
439
+ return G
440
+
441
+ G = nx.empty_graph(n, create_using=create_using)
442
+ nodes = list(range(n)) # nodes are labeled 0 to n-1
443
+ # connect each node to k/2 neighbors
444
+ for j in range(1, k // 2 + 1):
445
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
446
+ G.add_edges_from(zip(nodes, targets))
447
+ # rewire edges from each node
448
+ # loop over all nodes in order (label) and neighbors in order (distance)
449
+ # no self loops or multiple edges allowed
450
+ for j in range(1, k // 2 + 1): # outer loop is neighbors
451
+ targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list
452
+ # inner loop in node order
453
+ for u, v in zip(nodes, targets):
454
+ if seed.random() < p:
455
+ w = seed.choice(nodes)
456
+ # Enforce no self-loops or multiple edges
457
+ while w == u or G.has_edge(u, w):
458
+ w = seed.choice(nodes)
459
+ if G.degree(u) >= n - 1:
460
+ break # skip this rewiring
461
+ else:
462
+ G.remove_edge(u, v)
463
+ G.add_edge(u, w)
464
+ return G
465
+
466
+
467
+ @py_random_state(4)
468
+ @nx._dispatchable(graphs=None, returns_graph=True)
469
+ def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None, *, create_using=None):
470
+ """Returns a connected Watts–Strogatz small-world graph.
471
+
472
+ Attempts to generate a connected graph by repeated generation of
473
+ Watts–Strogatz small-world graphs. An exception is raised if the maximum
474
+ number of tries is exceeded.
475
+
476
+ Parameters
477
+ ----------
478
+ n : int
479
+ The number of nodes
480
+ k : int
481
+ Each node is joined with its `k` nearest neighbors in a ring
482
+ topology.
483
+ p : float
484
+ The probability of rewiring each edge
485
+ tries : int
486
+ Number of attempts to generate a connected graph.
487
+ seed : integer, random_state, or None (default)
488
+ Indicator of random number generation state.
489
+ See :ref:`Randomness<randomness>`.
490
+ create_using : Graph constructor, optional (default=nx.Graph)
491
+ Graph type to create. If graph instance, then cleared before populated.
492
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
493
+
494
+ Notes
495
+ -----
496
+ First create a ring over $n$ nodes [1]_. Then each node in the ring is joined
497
+ to its $k$ nearest neighbors (or $k - 1$ neighbors if $k$ is odd).
498
+ Then shortcuts are created by replacing some edges as follows: for each
499
+ edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest neighbors"
500
+ with probability $p$ replace it with a new edge $(u, w)$ with uniformly
501
+ random choice of existing node $w$.
502
+ The entire process is repeated until a connected graph results.
503
+
504
+ See Also
505
+ --------
506
+ newman_watts_strogatz_graph
507
+ watts_strogatz_graph
508
+
509
+ References
510
+ ----------
511
+ .. [1] Duncan J. Watts and Steven H. Strogatz,
512
+ Collective dynamics of small-world networks,
513
+ Nature, 393, pp. 440--442, 1998.
514
+ """
515
+ for i in range(tries):
516
+ # seed is an RNG so should change sequence each call
517
+ G = watts_strogatz_graph(n, k, p, seed, create_using=create_using)
518
+ if nx.is_connected(G):
519
+ return G
520
+ raise nx.NetworkXError("Maximum number of tries exceeded")
521
+
522
+
523
+ @py_random_state(2)
524
+ @nx._dispatchable(graphs=None, returns_graph=True)
525
+ def random_regular_graph(d, n, seed=None, *, create_using=None):
526
+ r"""Returns a random $d$-regular graph on $n$ nodes.
527
+
528
+ A regular graph is a graph where each node has the same number of neighbors.
529
+
530
+ The resulting graph has no self-loops or parallel edges.
531
+
532
+ Parameters
533
+ ----------
534
+ d : int
535
+ The degree of each node.
536
+ n : integer
537
+ The number of nodes. The value of $n \times d$ must be even.
538
+ seed : integer, random_state, or None (default)
539
+ Indicator of random number generation state.
540
+ See :ref:`Randomness<randomness>`.
541
+ create_using : Graph constructor, optional (default=nx.Graph)
542
+ Graph type to create. If graph instance, then cleared before populated.
543
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
544
+
545
+ Notes
546
+ -----
547
+ The nodes are numbered from $0$ to $n - 1$.
548
+
549
+ Kim and Vu's paper [2]_ shows that this algorithm samples in an
550
+ asymptotically uniform way from the space of random graphs when
551
+ $d = O(n^{1 / 3 - \epsilon})$.
552
+
553
+ Raises
554
+ ------
555
+
556
+ NetworkXError
557
+ If $n \times d$ is odd or $d$ is greater than or equal to $n$.
558
+
559
+ References
560
+ ----------
561
+ .. [1] A. Steger and N. Wormald,
562
+ Generating random regular graphs quickly,
563
+ Probability and Computing 8 (1999), 377-396, 1999.
564
+ https://doi.org/10.1017/S0963548399003867
565
+
566
+ .. [2] Jeong Han Kim and Van H. Vu,
567
+ Generating random regular graphs,
568
+ Proceedings of the thirty-fifth ACM symposium on Theory of computing,
569
+ San Diego, CA, USA, pp 213--222, 2003.
570
+ http://portal.acm.org/citation.cfm?id=780542.780576
571
+ """
572
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
573
+ if (n * d) % 2 != 0:
574
+ raise nx.NetworkXError("n * d must be even")
575
+
576
+ if not 0 <= d < n:
577
+ raise nx.NetworkXError("the 0 <= d < n inequality must be satisfied")
578
+
579
+ G = nx.empty_graph(n, create_using=create_using)
580
+
581
+ if d == 0:
582
+ return G
583
+
584
+ def _suitable(edges, potential_edges):
585
+ # Helper subroutine to check if there are suitable edges remaining
586
+ # If False, the generation of the graph has failed
587
+ if not potential_edges:
588
+ return True
589
+ for s1 in potential_edges:
590
+ for s2 in potential_edges:
591
+ # Two iterators on the same dictionary are guaranteed
592
+ # to visit it in the same order if there are no
593
+ # intervening modifications.
594
+ if s1 == s2:
595
+ # Only need to consider s1-s2 pair one time
596
+ break
597
+ if s1 > s2:
598
+ s1, s2 = s2, s1
599
+ if (s1, s2) not in edges:
600
+ return True
601
+ return False
602
+
603
+ def _try_creation():
604
+ # Attempt to create an edge set
605
+
606
+ edges = set()
607
+ stubs = list(range(n)) * d
608
+
609
+ while stubs:
610
+ potential_edges = defaultdict(lambda: 0)
611
+ seed.shuffle(stubs)
612
+ stubiter = iter(stubs)
613
+ for s1, s2 in zip(stubiter, stubiter):
614
+ if s1 > s2:
615
+ s1, s2 = s2, s1
616
+ if s1 != s2 and ((s1, s2) not in edges):
617
+ edges.add((s1, s2))
618
+ else:
619
+ potential_edges[s1] += 1
620
+ potential_edges[s2] += 1
621
+
622
+ if not _suitable(edges, potential_edges):
623
+ return None # failed to find suitable edge set
624
+
625
+ stubs = [
626
+ node
627
+ for node, potential in potential_edges.items()
628
+ for _ in range(potential)
629
+ ]
630
+ return edges
631
+
632
+ # Even though a suitable edge set exists,
633
+ # the generation of such a set is not guaranteed.
634
+ # Try repeatedly to find one.
635
+ edges = _try_creation()
636
+ while edges is None:
637
+ edges = _try_creation()
638
+ G.add_edges_from(edges)
639
+
640
+ return G
641
+
642
+
643
+ def _random_subset(seq, m, rng):
644
+ """Return m unique elements from seq.
645
+
646
+ This differs from random.sample which can return repeated
647
+ elements if seq holds repeated elements.
648
+
649
+ Note: rng is a random.Random or numpy.random.RandomState instance.
650
+ """
651
+ targets = set()
652
+ while len(targets) < m:
653
+ x = rng.choice(seq)
654
+ targets.add(x)
655
+ return targets
656
+
657
+
658
+ @py_random_state(2)
659
+ @nx._dispatchable(graphs=None, returns_graph=True)
660
+ def barabasi_albert_graph(n, m, seed=None, initial_graph=None, *, create_using=None):
661
+ """Returns a random graph using Barabási–Albert preferential attachment
662
+
663
+ A graph of $n$ nodes is grown by attaching new nodes each with $m$
664
+ edges that are preferentially attached to existing nodes with high degree.
665
+
666
+ Parameters
667
+ ----------
668
+ n : int
669
+ Number of nodes
670
+ m : int
671
+ Number of edges to attach from a new node to existing nodes
672
+ seed : integer, random_state, or None (default)
673
+ Indicator of random number generation state.
674
+ See :ref:`Randomness<randomness>`.
675
+ initial_graph : Graph or None (default)
676
+ Initial network for Barabási–Albert algorithm.
677
+ It should be a connected graph for most use cases.
678
+ A copy of `initial_graph` is used.
679
+ If None, starts from a star graph on (m+1) nodes.
680
+ create_using : Graph constructor, optional (default=nx.Graph)
681
+ Graph type to create. If graph instance, then cleared before populated.
682
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
683
+
684
+ Returns
685
+ -------
686
+ G : Graph
687
+
688
+ Raises
689
+ ------
690
+ NetworkXError
691
+ If `m` does not satisfy ``1 <= m < n``, or
692
+ the initial graph number of nodes m0 does not satisfy ``m <= m0 <= n``.
693
+
694
+ References
695
+ ----------
696
+ .. [1] A. L. Barabási and R. Albert "Emergence of scaling in
697
+ random networks", Science 286, pp 509-512, 1999.
698
+ """
699
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
700
+ if m < 1 or m >= n:
701
+ raise nx.NetworkXError(
702
+ f"Barabási–Albert network must have m >= 1 and m < n, m = {m}, n = {n}"
703
+ )
704
+
705
+ if initial_graph is None:
706
+ # Default initial graph : star graph on (m + 1) nodes
707
+ G = star_graph(m, create_using)
708
+ else:
709
+ if len(initial_graph) < m or len(initial_graph) > n:
710
+ raise nx.NetworkXError(
711
+ f"Barabási–Albert initial graph needs between m={m} and n={n} nodes"
712
+ )
713
+ G = initial_graph.copy()
714
+
715
+ # List of existing nodes, with nodes repeated once for each adjacent edge
716
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
717
+ # Start adding the other n - m0 nodes.
718
+ source = len(G)
719
+ while source < n:
720
+ # Now choose m unique nodes from the existing nodes
721
+ # Pick uniformly from repeated_nodes (preferential attachment)
722
+ targets = _random_subset(repeated_nodes, m, seed)
723
+ # Add edges to m nodes from the source.
724
+ G.add_edges_from(zip([source] * m, targets))
725
+ # Add one node to the list for each new edge just created.
726
+ repeated_nodes.extend(targets)
727
+ # And the new node "source" has m edges to add to the list.
728
+ repeated_nodes.extend([source] * m)
729
+
730
+ source += 1
731
+ return G
732
+
733
+
734
+ @py_random_state(4)
735
+ @nx._dispatchable(graphs=None, returns_graph=True)
736
+ def dual_barabasi_albert_graph(
737
+ n, m1, m2, p, seed=None, initial_graph=None, *, create_using=None
738
+ ):
739
+ """Returns a random graph using dual Barabási–Albert preferential attachment
740
+
741
+ A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
742
+ edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
743
+ are preferentially attached to existing nodes with high degree.
744
+
745
+ Parameters
746
+ ----------
747
+ n : int
748
+ Number of nodes
749
+ m1 : int
750
+ Number of edges to link each new node to existing nodes with probability $p$
751
+ m2 : int
752
+ Number of edges to link each new node to existing nodes with probability $1-p$
753
+ p : float
754
+ The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
755
+ seed : integer, random_state, or None (default)
756
+ Indicator of random number generation state.
757
+ See :ref:`Randomness<randomness>`.
758
+ initial_graph : Graph or None (default)
759
+ Initial network for Barabási–Albert algorithm.
760
+ A copy of `initial_graph` is used.
761
+ It should be connected for most use cases.
762
+ If None, starts from an star graph on max(m1, m2) + 1 nodes.
763
+ create_using : Graph constructor, optional (default=nx.Graph)
764
+ Graph type to create. If graph instance, then cleared before populated.
765
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
766
+
767
+ Returns
768
+ -------
769
+ G : Graph
770
+
771
+ Raises
772
+ ------
773
+ NetworkXError
774
+ If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
775
+ `p` does not satisfy ``0 <= p <= 1``, or
776
+ the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
777
+
778
+ References
779
+ ----------
780
+ .. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
781
+ """
782
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
783
+ if m1 < 1 or m1 >= n:
784
+ raise nx.NetworkXError(
785
+ f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
786
+ )
787
+ if m2 < 1 or m2 >= n:
788
+ raise nx.NetworkXError(
789
+ f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
790
+ )
791
+ if p < 0 or p > 1:
792
+ raise nx.NetworkXError(
793
+ f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
794
+ )
795
+
796
+ # For simplicity, if p == 0 or 1, just return BA
797
+ if p == 1:
798
+ return barabasi_albert_graph(n, m1, seed, create_using=create_using)
799
+ elif p == 0:
800
+ return barabasi_albert_graph(n, m2, seed, create_using=create_using)
801
+
802
+ if initial_graph is None:
803
+ # Default initial graph : star graph on max(m1, m2) nodes
804
+ G = star_graph(max(m1, m2), create_using)
805
+ else:
806
+ if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
807
+ raise nx.NetworkXError(
808
+ f"Barabási–Albert initial graph must have between "
809
+ f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
810
+ )
811
+ G = initial_graph.copy()
812
+
813
+ # Target nodes for new edges
814
+ targets = list(G)
815
+ # List of existing nodes, with nodes repeated once for each adjacent edge
816
+ repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
817
+ # Start adding the remaining nodes.
818
+ source = len(G)
819
+ while source < n:
820
+ # Pick which m to use (m1 or m2)
821
+ if seed.random() < p:
822
+ m = m1
823
+ else:
824
+ m = m2
825
+ # Now choose m unique nodes from the existing nodes
826
+ # Pick uniformly from repeated_nodes (preferential attachment)
827
+ targets = _random_subset(repeated_nodes, m, seed)
828
+ # Add edges to m nodes from the source.
829
+ G.add_edges_from(zip([source] * m, targets))
830
+ # Add one node to the list for each new edge just created.
831
+ repeated_nodes.extend(targets)
832
+ # And the new node "source" has m edges to add to the list.
833
+ repeated_nodes.extend([source] * m)
834
+
835
+ source += 1
836
+ return G
837
+
838
+
839
+ @py_random_state(4)
840
+ @nx._dispatchable(graphs=None, returns_graph=True)
841
+ def extended_barabasi_albert_graph(n, m, p, q, seed=None, *, create_using=None):
842
+ """Returns an extended Barabási–Albert model graph.
843
+
844
+ An extended Barabási–Albert model graph is a random graph constructed
845
+ using preferential attachment. The extended model allows new edges,
846
+ rewired edges or new nodes. Based on the probabilities $p$ and $q$
847
+ with $p + q < 1$, the growing behavior of the graph is determined as:
848
+
849
+ 1) With $p$ probability, $m$ new edges are added to the graph,
850
+ starting from randomly chosen existing nodes and attached preferentially at the
851
+ other end.
852
+
853
+ 2) With $q$ probability, $m$ existing edges are rewired
854
+ by randomly choosing an edge and rewiring one end to a preferentially chosen node.
855
+
856
+ 3) With $(1 - p - q)$ probability, $m$ new nodes are added to the graph
857
+ with edges attached preferentially.
858
+
859
+ When $p = q = 0$, the model behaves just like the Barabási–Alber model.
860
+
861
+ Parameters
862
+ ----------
863
+ n : int
864
+ Number of nodes
865
+ m : int
866
+ Number of edges with which a new node attaches to existing nodes
867
+ p : float
868
+ Probability value for adding an edge between existing nodes. p + q < 1
869
+ q : float
870
+ Probability value of rewiring of existing edges. p + q < 1
871
+ seed : integer, random_state, or None (default)
872
+ Indicator of random number generation state.
873
+ See :ref:`Randomness<randomness>`.
874
+ create_using : Graph constructor, optional (default=nx.Graph)
875
+ Graph type to create. If graph instance, then cleared before populated.
876
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
877
+
878
+ Returns
879
+ -------
880
+ G : Graph
881
+
882
+ Raises
883
+ ------
884
+ NetworkXError
885
+ If `m` does not satisfy ``1 <= m < n`` or ``1 >= p + q``
886
+
887
+ References
888
+ ----------
889
+ .. [1] Albert, R., & Barabási, A. L. (2000)
890
+ Topology of evolving networks: local events and universality
891
+ Physical review letters, 85(24), 5234.
892
+ """
893
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
894
+ if m < 1 or m >= n:
895
+ msg = f"Extended Barabasi-Albert network needs m>=1 and m<n, m={m}, n={n}"
896
+ raise nx.NetworkXError(msg)
897
+ if p + q >= 1:
898
+ msg = f"Extended Barabasi-Albert network needs p + q <= 1, p={p}, q={q}"
899
+ raise nx.NetworkXError(msg)
900
+
901
+ # Add m initial nodes (m0 in barabasi-speak)
902
+ G = empty_graph(m, create_using)
903
+
904
+ # List of nodes to represent the preferential attachment random selection.
905
+ # At the creation of the graph, all nodes are added to the list
906
+ # so that even nodes that are not connected have a chance to get selected,
907
+ # for rewiring and adding of edges.
908
+ # With each new edge, nodes at the ends of the edge are added to the list.
909
+ attachment_preference = []
910
+ attachment_preference.extend(range(m))
911
+
912
+ # Start adding the other n-m nodes. The first node is m.
913
+ new_node = m
914
+ while new_node < n:
915
+ a_probability = seed.random()
916
+
917
+ # Total number of edges of a Clique of all the nodes
918
+ clique_degree = len(G) - 1
919
+ clique_size = (len(G) * clique_degree) / 2
920
+
921
+ # Adding m new edges, if there is room to add them
922
+ if a_probability < p and G.size() <= clique_size - m:
923
+ # Select the nodes where an edge can be added
924
+ eligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]
925
+ for i in range(m):
926
+ # Choosing a random source node from eligible_nodes
927
+ src_node = seed.choice(eligible_nodes)
928
+
929
+ # Picking a possible node that is not 'src_node' or
930
+ # neighbor with 'src_node', with preferential attachment
931
+ prohibited_nodes = list(G[src_node])
932
+ prohibited_nodes.append(src_node)
933
+ # This will raise an exception if the sequence is empty
934
+ dest_node = seed.choice(
935
+ [nd for nd in attachment_preference if nd not in prohibited_nodes]
936
+ )
937
+ # Adding the new edge
938
+ G.add_edge(src_node, dest_node)
939
+
940
+ # Appending both nodes to add to their preferential attachment
941
+ attachment_preference.append(src_node)
942
+ attachment_preference.append(dest_node)
943
+
944
+ # Adjusting the eligible nodes. Degree may be saturated.
945
+ if G.degree(src_node) == clique_degree:
946
+ eligible_nodes.remove(src_node)
947
+ if G.degree(dest_node) == clique_degree and dest_node in eligible_nodes:
948
+ eligible_nodes.remove(dest_node)
949
+
950
+ # Rewiring m edges, if there are enough edges
951
+ elif p <= a_probability < (p + q) and m <= G.size() < clique_size:
952
+ # Selecting nodes that have at least 1 edge but that are not
953
+ # fully connected to ALL other nodes (center of star).
954
+ # These nodes are the pivot nodes of the edges to rewire
955
+ eligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]
956
+ for i in range(m):
957
+ # Choosing a random source node
958
+ node = seed.choice(eligible_nodes)
959
+
960
+ # The available nodes do have a neighbor at least.
961
+ nbr_nodes = list(G[node])
962
+
963
+ # Choosing the other end that will get detached
964
+ src_node = seed.choice(nbr_nodes)
965
+
966
+ # Picking a target node that is not 'node' or
967
+ # neighbor with 'node', with preferential attachment
968
+ nbr_nodes.append(node)
969
+ dest_node = seed.choice(
970
+ [nd for nd in attachment_preference if nd not in nbr_nodes]
971
+ )
972
+ # Rewire
973
+ G.remove_edge(node, src_node)
974
+ G.add_edge(node, dest_node)
975
+
976
+ # Adjusting the preferential attachment list
977
+ attachment_preference.remove(src_node)
978
+ attachment_preference.append(dest_node)
979
+
980
+ # Adjusting the eligible nodes.
981
+ # nodes may be saturated or isolated.
982
+ if G.degree(src_node) == 0 and src_node in eligible_nodes:
983
+ eligible_nodes.remove(src_node)
984
+ if dest_node in eligible_nodes:
985
+ if G.degree(dest_node) == clique_degree:
986
+ eligible_nodes.remove(dest_node)
987
+ else:
988
+ if G.degree(dest_node) == 1:
989
+ eligible_nodes.append(dest_node)
990
+
991
+ # Adding new node with m edges
992
+ else:
993
+ # Select the edges' nodes by preferential attachment
994
+ targets = _random_subset(attachment_preference, m, seed)
995
+ G.add_edges_from(zip([new_node] * m, targets))
996
+
997
+ # Add one node to the list for each new edge just created.
998
+ attachment_preference.extend(targets)
999
+ # The new node has m edges to it, plus itself: m + 1
1000
+ attachment_preference.extend([new_node] * (m + 1))
1001
+ new_node += 1
1002
+ return G
1003
+
1004
+
1005
+ @py_random_state(3)
1006
+ @nx._dispatchable(graphs=None, returns_graph=True)
1007
+ def powerlaw_cluster_graph(n, m, p, seed=None, *, create_using=None):
1008
+ """Holme and Kim algorithm for growing graphs with powerlaw
1009
+ degree distribution and approximate average clustering.
1010
+
1011
+ Parameters
1012
+ ----------
1013
+ n : int
1014
+ the number of nodes
1015
+ m : int
1016
+ the number of random edges to add for each new node
1017
+ p : float,
1018
+ Probability of adding a triangle after adding a random edge
1019
+ seed : integer, random_state, or None (default)
1020
+ Indicator of random number generation state.
1021
+ See :ref:`Randomness<randomness>`.
1022
+ create_using : Graph constructor, optional (default=nx.Graph)
1023
+ Graph type to create. If graph instance, then cleared before populated.
1024
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1025
+
1026
+ Notes
1027
+ -----
1028
+ The average clustering has a hard time getting above a certain
1029
+ cutoff that depends on `m`. This cutoff is often quite low. The
1030
+ transitivity (fraction of triangles to possible triangles) seems to
1031
+ decrease with network size.
1032
+
1033
+ It is essentially the Barabási–Albert (BA) growth model with an
1034
+ extra step that each random edge is followed by a chance of
1035
+ making an edge to one of its neighbors too (and thus a triangle).
1036
+
1037
+ This algorithm improves on BA in the sense that it enables a
1038
+ higher average clustering to be attained if desired.
1039
+
1040
+ It seems possible to have a disconnected graph with this algorithm
1041
+ since the initial `m` nodes may not be all linked to a new node
1042
+ on the first iteration like the BA model.
1043
+
1044
+ Raises
1045
+ ------
1046
+ NetworkXError
1047
+ If `m` does not satisfy ``1 <= m <= n`` or `p` does not
1048
+ satisfy ``0 <= p <= 1``.
1049
+
1050
+ References
1051
+ ----------
1052
+ .. [1] P. Holme and B. J. Kim,
1053
+ "Growing scale-free networks with tunable clustering",
1054
+ Phys. Rev. E, 65, 026107, 2002.
1055
+ """
1056
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1057
+ if m < 1 or n < m:
1058
+ raise nx.NetworkXError(f"NetworkXError must have m>1 and m<n, m={m},n={n}")
1059
+
1060
+ if p > 1 or p < 0:
1061
+ raise nx.NetworkXError(f"NetworkXError p must be in [0,1], p={p}")
1062
+
1063
+ G = empty_graph(m, create_using) # add m initial nodes (m0 in barabasi-speak)
1064
+ repeated_nodes = list(G) # list of existing nodes to sample from
1065
+ # with nodes repeated once for each adjacent edge
1066
+ source = m # next node is m
1067
+ while source < n: # Now add the other n-1 nodes
1068
+ possible_targets = _random_subset(repeated_nodes, m, seed)
1069
+ # do one preferential attachment for new node
1070
+ target = possible_targets.pop()
1071
+ G.add_edge(source, target)
1072
+ repeated_nodes.append(target) # add one node to list for each new link
1073
+ count = 1
1074
+ while count < m: # add m-1 more new links
1075
+ if seed.random() < p: # clustering step: add triangle
1076
+ neighborhood = [
1077
+ nbr
1078
+ for nbr in G.neighbors(target)
1079
+ if not G.has_edge(source, nbr) and nbr != source
1080
+ ]
1081
+ if neighborhood: # if there is a neighbor without a link
1082
+ nbr = seed.choice(neighborhood)
1083
+ G.add_edge(source, nbr) # add triangle
1084
+ repeated_nodes.append(nbr)
1085
+ count = count + 1
1086
+ continue # go to top of while loop
1087
+ # else do preferential attachment step if above fails
1088
+ target = possible_targets.pop()
1089
+ G.add_edge(source, target)
1090
+ repeated_nodes.append(target)
1091
+ count = count + 1
1092
+
1093
+ repeated_nodes.extend([source] * m) # add source node to list m times
1094
+ source += 1
1095
+ return G
1096
+
1097
+
1098
+ @py_random_state(3)
1099
+ @nx._dispatchable(graphs=None, returns_graph=True)
1100
+ def random_lobster(n, p1, p2, seed=None, *, create_using=None):
1101
+ """Returns a random lobster graph.
1102
+
1103
+ A lobster is a tree that reduces to a caterpillar when pruning all
1104
+ leaf nodes. A caterpillar is a tree that reduces to a path graph
1105
+ when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
1106
+
1107
+ This implementation iterates on the probabilities `p1` and `p2` to add
1108
+ edges at levels 1 and 2, respectively. Graphs are therefore constructed
1109
+ iteratively with uniform randomness at each level rather than being selected
1110
+ uniformly at random from the set of all possible lobsters.
1111
+
1112
+ Parameters
1113
+ ----------
1114
+ n : int
1115
+ The expected number of nodes in the backbone
1116
+ p1 : float
1117
+ Probability of adding an edge to the backbone
1118
+ p2 : float
1119
+ Probability of adding an edge one level beyond backbone
1120
+ seed : integer, random_state, or None (default)
1121
+ Indicator of random number generation state.
1122
+ See :ref:`Randomness<randomness>`.
1123
+ create_using : Graph constructor, optional (default=nx.Grap)
1124
+ Graph type to create. If graph instance, then cleared before populated.
1125
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1126
+
1127
+ Raises
1128
+ ------
1129
+ NetworkXError
1130
+ If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
1131
+ """
1132
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1133
+ p1, p2 = abs(p1), abs(p2)
1134
+ if any(p >= 1 for p in [p1, p2]):
1135
+ raise nx.NetworkXError("Probability values for `p1` and `p2` must both be < 1.")
1136
+
1137
+ # a necessary ingredient in any self-respecting graph library
1138
+ llen = int(2 * seed.random() * n + 0.5)
1139
+ L = path_graph(llen, create_using)
1140
+ # build caterpillar: add edges to path graph with probability p1
1141
+ current_node = llen - 1
1142
+ for n in range(llen):
1143
+ while seed.random() < p1: # add fuzzy caterpillar parts
1144
+ current_node += 1
1145
+ L.add_edge(n, current_node)
1146
+ cat_node = current_node
1147
+ while seed.random() < p2: # add crunchy lobster bits
1148
+ current_node += 1
1149
+ L.add_edge(cat_node, current_node)
1150
+ return L # voila, un lobster!
1151
+
1152
+
1153
+ @py_random_state(1)
1154
+ @nx._dispatchable(graphs=None, returns_graph=True)
1155
+ def random_shell_graph(constructor, seed=None, *, create_using=None):
1156
+ """Returns a random shell graph for the constructor given.
1157
+
1158
+ Parameters
1159
+ ----------
1160
+ constructor : list of three-tuples
1161
+ Represents the parameters for a shell, starting at the center
1162
+ shell. Each element of the list must be of the form `(n, m,
1163
+ d)`, where `n` is the number of nodes in the shell, `m` is
1164
+ the number of edges in the shell, and `d` is the ratio of
1165
+ inter-shell (next) edges to intra-shell edges. If `d` is zero,
1166
+ there will be no intra-shell edges, and if `d` is one there
1167
+ will be all possible intra-shell edges.
1168
+ seed : integer, random_state, or None (default)
1169
+ Indicator of random number generation state.
1170
+ See :ref:`Randomness<randomness>`.
1171
+ create_using : Graph constructor, optional (default=nx.Graph)
1172
+ Graph type to create. Graph instances are not supported.
1173
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1174
+
1175
+ Examples
1176
+ --------
1177
+ >>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]
1178
+ >>> G = nx.random_shell_graph(constructor)
1179
+
1180
+ """
1181
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1182
+ G = empty_graph(0, create_using)
1183
+
1184
+ glist = []
1185
+ intra_edges = []
1186
+ nnodes = 0
1187
+ # create gnm graphs for each shell
1188
+ for n, m, d in constructor:
1189
+ inter_edges = int(m * d)
1190
+ intra_edges.append(m - inter_edges)
1191
+ g = nx.convert_node_labels_to_integers(
1192
+ gnm_random_graph(n, inter_edges, seed=seed, create_using=G.__class__),
1193
+ first_label=nnodes,
1194
+ )
1195
+ glist.append(g)
1196
+ nnodes += n
1197
+ G = nx.operators.union(G, g)
1198
+
1199
+ # connect the shells randomly
1200
+ for gi in range(len(glist) - 1):
1201
+ nlist1 = list(glist[gi])
1202
+ nlist2 = list(glist[gi + 1])
1203
+ total_edges = intra_edges[gi]
1204
+ edge_count = 0
1205
+ while edge_count < total_edges:
1206
+ u = seed.choice(nlist1)
1207
+ v = seed.choice(nlist2)
1208
+ if u == v or G.has_edge(u, v):
1209
+ continue
1210
+ else:
1211
+ G.add_edge(u, v)
1212
+ edge_count = edge_count + 1
1213
+ return G
1214
+
1215
+
1216
+ @py_random_state(2)
1217
+ @nx._dispatchable(graphs=None, returns_graph=True)
1218
+ def random_powerlaw_tree(n, gamma=3, seed=None, tries=100, *, create_using=None):
1219
+ """Returns a tree with a power law degree distribution.
1220
+
1221
+ Parameters
1222
+ ----------
1223
+ n : int
1224
+ The number of nodes.
1225
+ gamma : float
1226
+ Exponent of the power law.
1227
+ seed : integer, random_state, or None (default)
1228
+ Indicator of random number generation state.
1229
+ See :ref:`Randomness<randomness>`.
1230
+ tries : int
1231
+ Number of attempts to adjust the sequence to make it a tree.
1232
+ create_using : Graph constructor, optional (default=nx.Graph)
1233
+ Graph type to create. If graph instance, then cleared before populated.
1234
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1235
+
1236
+ Raises
1237
+ ------
1238
+ NetworkXError
1239
+ If no valid sequence is found within the maximum number of
1240
+ attempts.
1241
+
1242
+ Notes
1243
+ -----
1244
+ A trial power law degree sequence is chosen and then elements are
1245
+ swapped with new elements from a powerlaw distribution until the
1246
+ sequence makes a tree (by checking, for example, that the number of
1247
+ edges is one smaller than the number of nodes).
1248
+
1249
+ """
1250
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1251
+ # This call may raise a NetworkXError if the number of tries is succeeded.
1252
+ seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)
1253
+ G = degree_sequence_tree(seq, create_using)
1254
+ return G
1255
+
1256
+
1257
+ @py_random_state(2)
1258
+ @nx._dispatchable(graphs=None)
1259
+ def random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):
1260
+ """Returns a degree sequence for a tree with a power law distribution.
1261
+
1262
+ Parameters
1263
+ ----------
1264
+ n : int,
1265
+ The number of nodes.
1266
+ gamma : float
1267
+ Exponent of the power law.
1268
+ seed : integer, random_state, or None (default)
1269
+ Indicator of random number generation state.
1270
+ See :ref:`Randomness<randomness>`.
1271
+ tries : int
1272
+ Number of attempts to adjust the sequence to make it a tree.
1273
+
1274
+ Raises
1275
+ ------
1276
+ NetworkXError
1277
+ If no valid sequence is found within the maximum number of
1278
+ attempts.
1279
+
1280
+ Notes
1281
+ -----
1282
+ A trial power law degree sequence is chosen and then elements are
1283
+ swapped with new elements from a power law distribution until
1284
+ the sequence makes a tree (by checking, for example, that the number of
1285
+ edges is one smaller than the number of nodes).
1286
+
1287
+ """
1288
+ # get trial sequence
1289
+ z = nx.utils.powerlaw_sequence(n, exponent=gamma, seed=seed)
1290
+ # round to integer values in the range [0,n]
1291
+ zseq = [min(n, max(round(s), 0)) for s in z]
1292
+
1293
+ # another sequence to swap values from
1294
+ z = nx.utils.powerlaw_sequence(tries, exponent=gamma, seed=seed)
1295
+ # round to integer values in the range [0,n]
1296
+ swap = [min(n, max(round(s), 0)) for s in z]
1297
+
1298
+ for deg in swap:
1299
+ # If this degree sequence can be the degree sequence of a tree, return
1300
+ # it. It can be a tree if the number of edges is one fewer than the
1301
+ # number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We
1302
+ # use an equivalent condition below that avoids floating point
1303
+ # operations.
1304
+ if 2 * n - sum(zseq) == 2:
1305
+ return zseq
1306
+ index = seed.randint(0, n - 1)
1307
+ zseq[index] = swap.pop()
1308
+
1309
+ raise nx.NetworkXError(
1310
+ f"Exceeded max ({tries}) attempts for a valid tree sequence."
1311
+ )
1312
+
1313
+
1314
+ @py_random_state(3)
1315
+ @nx._dispatchable(graphs=None, returns_graph=True)
1316
+ def random_kernel_graph(
1317
+ n, kernel_integral, kernel_root=None, seed=None, *, create_using=None
1318
+ ):
1319
+ r"""Returns an random graph based on the specified kernel.
1320
+
1321
+ The algorithm chooses each of the $[n(n-1)]/2$ possible edges with
1322
+ probability specified by a kernel $\kappa(x,y)$ [1]_. The kernel
1323
+ $\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,
1324
+ bounded function.
1325
+
1326
+ Parameters
1327
+ ----------
1328
+ n : int
1329
+ The number of nodes
1330
+ kernel_integral : function
1331
+ Function that returns the definite integral of the kernel $\kappa(x,y)$,
1332
+ $F(y,a,b) := \int_a^b \kappa(x,y)dx$
1333
+ kernel_root: function (optional)
1334
+ Function that returns the root $b$ of the equation $F(y,a,b) = r$.
1335
+ If None, the root is found using :func:`scipy.optimize.brentq`
1336
+ (this requires SciPy).
1337
+ seed : integer, random_state, or None (default)
1338
+ Indicator of random number generation state.
1339
+ See :ref:`Randomness<randomness>`.
1340
+ create_using : Graph constructor, optional (default=nx.Graph)
1341
+ Graph type to create. If graph instance, then cleared before populated.
1342
+ Multigraph and directed types are not supported and raise a ``NetworkXError``.
1343
+
1344
+ Notes
1345
+ -----
1346
+ The kernel is specified through its definite integral which must be
1347
+ provided as one of the arguments. If the integral and root of the
1348
+ kernel integral can be found in $O(1)$ time then this algorithm runs in
1349
+ time $O(n+m)$ where m is the expected number of edges [2]_.
1350
+
1351
+ The nodes are set to integers from $0$ to $n-1$.
1352
+
1353
+ Examples
1354
+ --------
1355
+ Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel
1356
+ $\kappa(x,y)=c$ where $c$ is the mean expected degree.
1357
+
1358
+ >>> def integral(u, w, z):
1359
+ ... return c * (z - w)
1360
+ >>> def root(u, w, r):
1361
+ ... return r / c + w
1362
+ >>> c = 1
1363
+ >>> graph = nx.random_kernel_graph(1000, integral, root)
1364
+
1365
+ See Also
1366
+ --------
1367
+ gnp_random_graph
1368
+ expected_degree_graph
1369
+
1370
+ References
1371
+ ----------
1372
+ .. [1] Bollobás, Béla, Janson, S. and Riordan, O.
1373
+ "The phase transition in inhomogeneous random graphs",
1374
+ *Random Structures Algorithms*, 31, 3--122, 2007.
1375
+
1376
+ .. [2] Hagberg A, Lemons N (2015),
1377
+ "Fast Generation of Sparse Random Kernel Graphs".
1378
+ PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177
1379
+ """
1380
+ create_using = check_create_using(create_using, directed=False, multigraph=False)
1381
+ if kernel_root is None:
1382
+ import scipy as sp
1383
+
1384
+ def kernel_root(y, a, r):
1385
+ def my_function(b):
1386
+ return kernel_integral(y, a, b) - r
1387
+
1388
+ return sp.optimize.brentq(my_function, a, 1)
1389
+
1390
+ graph = nx.empty_graph(create_using=create_using)
1391
+ graph.add_nodes_from(range(n))
1392
+ (i, j) = (1, 1)
1393
+ while i < n:
1394
+ r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]
1395
+ if kernel_integral(i / n, j / n, 1) <= r:
1396
+ i, j = i + 1, i + 1
1397
+ else:
1398
+ j = math.ceil(n * kernel_root(i / n, j / n, r))
1399
+ graph.add_edge(i - 1, j - 1)
1400
+ return graph
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/stochastic.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating stochastic graphs from a given weighted directed
2
+ graph.
3
+
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.classes import DiGraph, MultiDiGraph
8
+ from networkx.utils import not_implemented_for
9
+
10
+ __all__ = ["stochastic_graph"]
11
+
12
+
13
+ @not_implemented_for("undirected")
14
+ @nx._dispatchable(
15
+ edge_attrs="weight", mutates_input={"not copy": 1}, returns_graph=True
16
+ )
17
+ def stochastic_graph(G, copy=True, weight="weight"):
18
+ """Returns a right-stochastic representation of directed graph `G`.
19
+
20
+ A right-stochastic graph is a weighted digraph in which for each
21
+ node, the sum of the weights of all the out-edges of that node is
22
+ 1. If the graph is already weighted (for example, via a 'weight'
23
+ edge attribute), the reweighting takes that into account.
24
+
25
+ Parameters
26
+ ----------
27
+ G : directed graph
28
+ A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.
29
+
30
+ copy : boolean, optional
31
+ If this is True, then this function returns a new graph with
32
+ the stochastic reweighting. Otherwise, the original graph is
33
+ modified in-place (and also returned, for convenience).
34
+
35
+ weight : edge attribute key (optional, default='weight')
36
+ Edge attribute key used for reading the existing weight and
37
+ setting the new weight. If no attribute with this key is found
38
+ for an edge, then the edge weight is assumed to be 1. If an edge
39
+ has a weight, it must be a positive number.
40
+
41
+ """
42
+ if copy:
43
+ G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
44
+ # There is a tradeoff here: the dictionary of node degrees may
45
+ # require a lot of memory, whereas making a call to `G.out_degree`
46
+ # inside the loop may be costly in computation time.
47
+ degree = dict(G.out_degree(weight=weight))
48
+ for u, v, d in G.edges(data=True):
49
+ if degree[u] == 0:
50
+ d[weight] = 0
51
+ else:
52
+ d[weight] = d.get(weight, 1) / degree[u]
53
+ nx._clear_cache(G)
54
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/__init__.py ADDED
File without changes
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_atlas.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import groupby
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx import graph_atlas, graph_atlas_g
7
+ from networkx.generators.atlas import NUM_GRAPHS
8
+ from networkx.utils import edges_equal, nodes_equal, pairwise
9
+
10
+
11
+ class TestAtlasGraph:
12
+ """Unit tests for the :func:`~networkx.graph_atlas` function."""
13
+
14
+ def test_index_too_small(self):
15
+ with pytest.raises(ValueError):
16
+ graph_atlas(-1)
17
+
18
+ def test_index_too_large(self):
19
+ with pytest.raises(ValueError):
20
+ graph_atlas(NUM_GRAPHS)
21
+
22
+ def test_graph(self):
23
+ G = graph_atlas(6)
24
+ assert nodes_equal(G.nodes(), range(3))
25
+ assert edges_equal(G.edges(), [(0, 1), (0, 2)])
26
+
27
+
28
+ class TestAtlasGraphG:
29
+ """Unit tests for the :func:`~networkx.graph_atlas_g` function."""
30
+
31
+ @classmethod
32
+ def setup_class(cls):
33
+ cls.GAG = graph_atlas_g()
34
+
35
+ def test_sizes(self):
36
+ G = self.GAG[0]
37
+ assert G.number_of_nodes() == 0
38
+ assert G.number_of_edges() == 0
39
+
40
+ G = self.GAG[7]
41
+ assert G.number_of_nodes() == 3
42
+ assert G.number_of_edges() == 3
43
+
44
+ def test_names(self):
45
+ for i, G in enumerate(self.GAG):
46
+ assert int(G.name[1:]) == i
47
+
48
+ def test_nondecreasing_nodes(self):
49
+ # check for nondecreasing number of nodes
50
+ for n1, n2 in pairwise(map(len, self.GAG)):
51
+ assert n2 <= n1 + 1
52
+
53
+ def test_nondecreasing_edges(self):
54
+ # check for nondecreasing number of edges (for fixed number of
55
+ # nodes)
56
+ for n, group in groupby(self.GAG, key=nx.number_of_nodes):
57
+ for m1, m2 in pairwise(map(nx.number_of_edges, group)):
58
+ assert m2 <= m1 + 1
59
+
60
+ def test_nondecreasing_degree_sequence(self):
61
+ # Check for lexicographically nondecreasing degree sequences
62
+ # (for fixed number of nodes and edges).
63
+ #
64
+ # There are three exceptions to this rule in the order given in
65
+ # the "Atlas of Graphs" book, so we need to manually exclude
66
+ # those.
67
+ exceptions = [("G55", "G56"), ("G1007", "G1008"), ("G1012", "G1013")]
68
+ for n, group in groupby(self.GAG, key=nx.number_of_nodes):
69
+ for m, group in groupby(group, key=nx.number_of_edges):
70
+ for G1, G2 in pairwise(group):
71
+ if (G1.name, G2.name) in exceptions:
72
+ continue
73
+ d1 = sorted(d for v, d in G1.degree())
74
+ d2 = sorted(d for v, d in G2.degree())
75
+ assert d1 <= d2
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_cographs.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.cographs` module."""
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_random_cograph():
7
+ n = 3
8
+ G = nx.random_cograph(n)
9
+
10
+ assert len(G) == 2**n
11
+
12
+ # Every connected subgraph of G has diameter <= 2
13
+ if nx.is_connected(G):
14
+ assert nx.diameter(G) <= 2
15
+ else:
16
+ components = nx.connected_components(G)
17
+ for component in components:
18
+ assert nx.diameter(G.subgraph(component)) <= 2
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_community.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_random_partition_graph():
7
+ G = nx.random_partition_graph([3, 3, 3], 1, 0, seed=42)
8
+ C = G.graph["partition"]
9
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
10
+ assert len(G) == 9
11
+ assert len(list(G.edges())) == 9
12
+
13
+ G = nx.random_partition_graph([3, 3, 3], 0, 1)
14
+ C = G.graph["partition"]
15
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
16
+ assert len(G) == 9
17
+ assert len(list(G.edges())) == 27
18
+
19
+ G = nx.random_partition_graph([3, 3, 3], 1, 0, directed=True)
20
+ C = G.graph["partition"]
21
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
22
+ assert len(G) == 9
23
+ assert len(list(G.edges())) == 18
24
+
25
+ G = nx.random_partition_graph([3, 3, 3], 0, 1, directed=True)
26
+ C = G.graph["partition"]
27
+ assert C == [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}]
28
+ assert len(G) == 9
29
+ assert len(list(G.edges())) == 54
30
+
31
+ G = nx.random_partition_graph([1, 2, 3, 4, 5], 0.5, 0.1)
32
+ C = G.graph["partition"]
33
+ assert C == [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}, {10, 11, 12, 13, 14}]
34
+ assert len(G) == 15
35
+
36
+ rpg = nx.random_partition_graph
37
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 1.1, 0.1)
38
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], -0.1, 0.1)
39
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, 1.1)
40
+ pytest.raises(nx.NetworkXError, rpg, [1, 2, 3], 0.1, -0.1)
41
+
42
+
43
+ def test_planted_partition_graph():
44
+ G = nx.planted_partition_graph(4, 3, 1, 0, seed=42)
45
+ C = G.graph["partition"]
46
+ assert len(C) == 4
47
+ assert len(G) == 12
48
+ assert len(list(G.edges())) == 12
49
+
50
+ G = nx.planted_partition_graph(4, 3, 0, 1)
51
+ C = G.graph["partition"]
52
+ assert len(C) == 4
53
+ assert len(G) == 12
54
+ assert len(list(G.edges())) == 54
55
+
56
+ G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42)
57
+ C = G.graph["partition"]
58
+ assert len(C) == 10
59
+ assert len(G) == 40
60
+
61
+ G = nx.planted_partition_graph(4, 3, 1, 0, directed=True)
62
+ C = G.graph["partition"]
63
+ assert len(C) == 4
64
+ assert len(G) == 12
65
+ assert len(list(G.edges())) == 24
66
+
67
+ G = nx.planted_partition_graph(4, 3, 0, 1, directed=True)
68
+ C = G.graph["partition"]
69
+ assert len(C) == 4
70
+ assert len(G) == 12
71
+ assert len(list(G.edges())) == 108
72
+
73
+ G = nx.planted_partition_graph(10, 4, 0.5, 0.1, seed=42, directed=True)
74
+ C = G.graph["partition"]
75
+ assert len(C) == 10
76
+ assert len(G) == 40
77
+
78
+ ppg = nx.planted_partition_graph
79
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 1.1, 0.1)
80
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, -0.1, 0.1)
81
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, 1.1)
82
+ pytest.raises(nx.NetworkXError, ppg, 3, 3, 0.1, -0.1)
83
+
84
+
85
+ def test_relaxed_caveman_graph():
86
+ G = nx.relaxed_caveman_graph(4, 3, 0)
87
+ assert len(G) == 12
88
+ G = nx.relaxed_caveman_graph(4, 3, 1)
89
+ assert len(G) == 12
90
+ G = nx.relaxed_caveman_graph(4, 3, 0.5)
91
+ assert len(G) == 12
92
+ G = nx.relaxed_caveman_graph(4, 3, 0.5, seed=42)
93
+ assert len(G) == 12
94
+
95
+
96
+ def test_connected_caveman_graph():
97
+ G = nx.connected_caveman_graph(4, 3)
98
+ assert len(G) == 12
99
+
100
+ G = nx.connected_caveman_graph(1, 5)
101
+ K5 = nx.complete_graph(5)
102
+ K5.remove_edge(3, 4)
103
+ assert nx.is_isomorphic(G, K5)
104
+
105
+ # need at least 2 nodes in each clique
106
+ pytest.raises(nx.NetworkXError, nx.connected_caveman_graph, 4, 1)
107
+
108
+
109
+ def test_caveman_graph():
110
+ G = nx.caveman_graph(4, 3)
111
+ assert len(G) == 12
112
+
113
+ G = nx.caveman_graph(5, 1)
114
+ E5 = nx.empty_graph(5)
115
+ assert nx.is_isomorphic(G, E5)
116
+
117
+ G = nx.caveman_graph(1, 5)
118
+ K5 = nx.complete_graph(5)
119
+ assert nx.is_isomorphic(G, K5)
120
+
121
+
122
+ def test_gaussian_random_partition_graph():
123
+ G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01)
124
+ assert len(G) == 100
125
+ G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True)
126
+ assert len(G) == 100
127
+ G = nx.gaussian_random_partition_graph(
128
+ 100, 10, 10, 0.3, 0.01, directed=False, seed=42
129
+ )
130
+ assert len(G) == 100
131
+ assert not isinstance(G, nx.DiGraph)
132
+ G = nx.gaussian_random_partition_graph(
133
+ 100, 10, 10, 0.3, 0.01, directed=True, seed=42
134
+ )
135
+ assert len(G) == 100
136
+ assert isinstance(G, nx.DiGraph)
137
+ pytest.raises(
138
+ nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0
139
+ )
140
+ # Test when clusters are likely less than 1
141
+ G = nx.gaussian_random_partition_graph(10, 0.5, 0.5, 0.5, 0.5, seed=1)
142
+ assert len(G) == 10
143
+
144
+
145
+ def test_ring_of_cliques():
146
+ for i in range(2, 20, 3):
147
+ for j in range(2, 20, 3):
148
+ G = nx.ring_of_cliques(i, j)
149
+ assert G.number_of_nodes() == i * j
150
+ if i != 2 or j != 1:
151
+ expected_num_edges = i * (((j * (j - 1)) // 2) + 1)
152
+ else:
153
+ # the edge that already exists cannot be duplicated
154
+ expected_num_edges = i * (((j * (j - 1)) // 2) + 1) - 1
155
+ assert G.number_of_edges() == expected_num_edges
156
+ with pytest.raises(
157
+ nx.NetworkXError, match="A ring of cliques must have at least two cliques"
158
+ ):
159
+ nx.ring_of_cliques(1, 5)
160
+ with pytest.raises(
161
+ nx.NetworkXError, match="The cliques must have at least two nodes"
162
+ ):
163
+ nx.ring_of_cliques(3, 0)
164
+
165
+
166
+ def test_windmill_graph():
167
+ for n in range(2, 20, 3):
168
+ for k in range(2, 20, 3):
169
+ G = nx.windmill_graph(n, k)
170
+ assert G.number_of_nodes() == (k - 1) * n + 1
171
+ assert G.number_of_edges() == n * k * (k - 1) / 2
172
+ assert G.degree(0) == G.number_of_nodes() - 1
173
+ for i in range(1, G.number_of_nodes()):
174
+ assert G.degree(i) == k - 1
175
+ with pytest.raises(
176
+ nx.NetworkXError, match="A windmill graph must have at least two cliques"
177
+ ):
178
+ nx.windmill_graph(1, 3)
179
+ with pytest.raises(
180
+ nx.NetworkXError, match="The cliques must have at least two nodes"
181
+ ):
182
+ nx.windmill_graph(3, 0)
183
+
184
+
185
+ def test_stochastic_block_model():
186
+ sizes = [75, 75, 300]
187
+ probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
188
+ G = nx.stochastic_block_model(sizes, probs, seed=0)
189
+ C = G.graph["partition"]
190
+ assert len(C) == 3
191
+ assert len(G) == 450
192
+ assert G.size() == 22160
193
+
194
+ GG = nx.stochastic_block_model(sizes, probs, range(450), seed=0)
195
+ assert G.nodes == GG.nodes
196
+
197
+ # Test Exceptions
198
+ sbm = nx.stochastic_block_model
199
+ badnodelist = list(range(400)) # not enough nodes to match sizes
200
+ badprobs1 = [[0.25, 0.05, 1.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]
201
+ badprobs2 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
202
+ probs_rect1 = [[0.25, 0.05, 0.02], [0.05, -0.35, 0.07]]
203
+ probs_rect2 = [[0.25, 0.05], [0.05, -0.35], [0.02, 0.07]]
204
+ asymprobs = [[0.25, 0.05, 0.01], [0.05, -0.35, 0.07], [0.02, 0.07, 0.40]]
205
+ pytest.raises(nx.NetworkXException, sbm, sizes, badprobs1)
206
+ pytest.raises(nx.NetworkXException, sbm, sizes, badprobs2)
207
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect1, directed=True)
208
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs_rect2, directed=True)
209
+ pytest.raises(nx.NetworkXException, sbm, sizes, asymprobs, directed=False)
210
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs, badnodelist)
211
+ nodelist = [0] + list(range(449)) # repeated node name in nodelist
212
+ pytest.raises(nx.NetworkXException, sbm, sizes, probs, nodelist)
213
+
214
+ # Extra keyword arguments test
215
+ GG = nx.stochastic_block_model(sizes, probs, seed=0, selfloops=True)
216
+ assert G.nodes == GG.nodes
217
+ GG = nx.stochastic_block_model(sizes, probs, selfloops=True, directed=True)
218
+ assert G.nodes == GG.nodes
219
+ GG = nx.stochastic_block_model(sizes, probs, seed=0, sparse=False)
220
+ assert G.nodes == GG.nodes
221
+
222
+
223
+ def test_generator():
224
+ n = 250
225
+ tau1 = 3
226
+ tau2 = 1.5
227
+ mu = 0.1
228
+ G = nx.LFR_benchmark_graph(
229
+ n, tau1, tau2, mu, average_degree=5, min_community=20, seed=10
230
+ )
231
+ assert len(G) == 250
232
+ C = {frozenset(G.nodes[v]["community"]) for v in G}
233
+ assert nx.community.is_partition(G.nodes(), C)
234
+
235
+
236
+ def test_invalid_tau1():
237
+ with pytest.raises(nx.NetworkXError, match="tau2 must be greater than one"):
238
+ n = 100
239
+ tau1 = 2
240
+ tau2 = 1
241
+ mu = 0.1
242
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
243
+
244
+
245
+ def test_invalid_tau2():
246
+ with pytest.raises(nx.NetworkXError, match="tau1 must be greater than one"):
247
+ n = 100
248
+ tau1 = 1
249
+ tau2 = 2
250
+ mu = 0.1
251
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
252
+
253
+
254
+ def test_mu_too_large():
255
+ with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
256
+ n = 100
257
+ tau1 = 2
258
+ tau2 = 2
259
+ mu = 1.1
260
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
261
+
262
+
263
+ def test_mu_too_small():
264
+ with pytest.raises(nx.NetworkXError, match="mu must be in the interval \\[0, 1\\]"):
265
+ n = 100
266
+ tau1 = 2
267
+ tau2 = 2
268
+ mu = -1
269
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2)
270
+
271
+
272
+ def test_both_degrees_none():
273
+ with pytest.raises(
274
+ nx.NetworkXError,
275
+ match="Must assign exactly one of min_degree and average_degree",
276
+ ):
277
+ n = 100
278
+ tau1 = 2
279
+ tau2 = 2
280
+ mu = 1
281
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu)
282
+
283
+
284
+ def test_neither_degrees_none():
285
+ with pytest.raises(
286
+ nx.NetworkXError,
287
+ match="Must assign exactly one of min_degree and average_degree",
288
+ ):
289
+ n = 100
290
+ tau1 = 2
291
+ tau2 = 2
292
+ mu = 1
293
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, average_degree=5)
294
+
295
+
296
+ def test_max_iters_exceeded():
297
+ with pytest.raises(
298
+ nx.ExceededMaxIterations,
299
+ match="Could not assign communities; try increasing min_community",
300
+ ):
301
+ n = 10
302
+ tau1 = 2
303
+ tau2 = 2
304
+ mu = 0.1
305
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=10, seed=1)
306
+
307
+
308
+ def test_max_deg_out_of_range():
309
+ with pytest.raises(
310
+ nx.NetworkXError, match="max_degree must be in the interval \\(0, n\\]"
311
+ ):
312
+ n = 10
313
+ tau1 = 2
314
+ tau2 = 2
315
+ mu = 0.1
316
+ nx.LFR_benchmark_graph(
317
+ n, tau1, tau2, mu, max_degree=n + 1, max_iters=10, seed=1
318
+ )
319
+
320
+
321
+ def test_max_community():
322
+ n = 250
323
+ tau1 = 3
324
+ tau2 = 1.5
325
+ mu = 0.1
326
+ G = nx.LFR_benchmark_graph(
327
+ n,
328
+ tau1,
329
+ tau2,
330
+ mu,
331
+ average_degree=5,
332
+ max_degree=100,
333
+ min_community=50,
334
+ max_community=200,
335
+ seed=10,
336
+ )
337
+ assert len(G) == 250
338
+ C = {frozenset(G.nodes[v]["community"]) for v in G}
339
+ assert nx.community.is_partition(G.nodes(), C)
340
+
341
+
342
+ def test_powerlaw_iterations_exceeded():
343
+ with pytest.raises(
344
+ nx.ExceededMaxIterations, match="Could not create power law sequence"
345
+ ):
346
+ n = 100
347
+ tau1 = 2
348
+ tau2 = 2
349
+ mu = 1
350
+ nx.LFR_benchmark_graph(n, tau1, tau2, mu, min_degree=2, max_iters=0)
351
+
352
+
353
+ def test_no_scipy_zeta():
354
+ zeta2 = 1.6449340668482264
355
+ assert abs(zeta2 - nx.generators.community._hurwitz_zeta(2, 1, 0.0001)) < 0.01
356
+
357
+
358
+ def test_generate_min_degree_itr():
359
+ with pytest.raises(
360
+ nx.ExceededMaxIterations, match="Could not match average_degree"
361
+ ):
362
+ nx.generators.community._generate_min_degree(2, 2, 1, 0.01, 0)
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_degree_seq.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestConfigurationModel:
7
+ """Unit tests for the :func:`~networkx.configuration_model`
8
+ function.
9
+
10
+ """
11
+
12
+ def test_empty_degree_sequence(self):
13
+ """Tests that an empty degree sequence yields the null graph."""
14
+ G = nx.configuration_model([])
15
+ assert len(G) == 0
16
+
17
+ def test_degree_zero(self):
18
+ """Tests that a degree sequence of all zeros yields the empty
19
+ graph.
20
+
21
+ """
22
+ G = nx.configuration_model([0, 0, 0])
23
+ assert len(G) == 3
24
+ assert G.number_of_edges() == 0
25
+
26
+ def test_degree_sequence(self):
27
+ """Tests that the degree sequence of the generated graph matches
28
+ the input degree sequence.
29
+
30
+ """
31
+ deg_seq = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
32
+ G = nx.configuration_model(deg_seq, seed=12345678)
33
+ assert sorted((d for n, d in G.degree()), reverse=True) == [
34
+ 5,
35
+ 3,
36
+ 3,
37
+ 3,
38
+ 3,
39
+ 2,
40
+ 2,
41
+ 2,
42
+ 1,
43
+ 1,
44
+ 1,
45
+ ]
46
+ assert sorted((d for n, d in G.degree(range(len(deg_seq)))), reverse=True) == [
47
+ 5,
48
+ 3,
49
+ 3,
50
+ 3,
51
+ 3,
52
+ 2,
53
+ 2,
54
+ 2,
55
+ 1,
56
+ 1,
57
+ 1,
58
+ ]
59
+
60
+ def test_random_seed(self):
61
+ """Tests that each call with the same random seed generates the
62
+ same graph.
63
+
64
+ """
65
+ deg_seq = [3] * 12
66
+ G1 = nx.configuration_model(deg_seq, seed=1000)
67
+ G2 = nx.configuration_model(deg_seq, seed=1000)
68
+ assert nx.is_isomorphic(G1, G2)
69
+ G1 = nx.configuration_model(deg_seq, seed=10)
70
+ G2 = nx.configuration_model(deg_seq, seed=10)
71
+ assert nx.is_isomorphic(G1, G2)
72
+
73
+ def test_directed_disallowed(self):
74
+ """Tests that attempting to create a configuration model graph
75
+ using a directed graph yields an exception.
76
+
77
+ """
78
+ with pytest.raises(nx.NetworkXNotImplemented):
79
+ nx.configuration_model([], create_using=nx.DiGraph())
80
+
81
+ def test_odd_degree_sum(self):
82
+ """Tests that a degree sequence whose sum is odd yields an
83
+ exception.
84
+
85
+ """
86
+ with pytest.raises(nx.NetworkXError):
87
+ nx.configuration_model([1, 2])
88
+
89
+
90
+ def test_directed_configuration_raise_unequal():
91
+ with pytest.raises(nx.NetworkXError):
92
+ zin = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1]
93
+ zout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 2]
94
+ nx.directed_configuration_model(zin, zout)
95
+
96
+
97
+ def test_directed_configuration_model():
98
+ G = nx.directed_configuration_model([], [], seed=0)
99
+ assert len(G) == 0
100
+
101
+
102
+ def test_simple_directed_configuration_model():
103
+ G = nx.directed_configuration_model([1, 1], [1, 1], seed=0)
104
+ assert len(G) == 2
105
+
106
+
107
+ def test_expected_degree_graph_empty():
108
+ # empty graph has empty degree sequence
109
+ deg_seq = []
110
+ G = nx.expected_degree_graph(deg_seq)
111
+ assert dict(G.degree()) == {}
112
+
113
+
114
+ def test_expected_degree_graph():
115
+ # test that fixed seed delivers the same graph
116
+ deg_seq = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
117
+ G1 = nx.expected_degree_graph(deg_seq, seed=1000)
118
+ assert len(G1) == 12
119
+
120
+ G2 = nx.expected_degree_graph(deg_seq, seed=1000)
121
+ assert nx.is_isomorphic(G1, G2)
122
+
123
+ G1 = nx.expected_degree_graph(deg_seq, seed=10)
124
+ G2 = nx.expected_degree_graph(deg_seq, seed=10)
125
+ assert nx.is_isomorphic(G1, G2)
126
+
127
+
128
+ def test_expected_degree_graph_selfloops():
129
+ deg_seq = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
130
+ G1 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
131
+ G2 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False)
132
+ assert nx.is_isomorphic(G1, G2)
133
+ assert len(G1) == 12
134
+
135
+
136
+ def test_expected_degree_graph_skew():
137
+ deg_seq = [10, 2, 2, 2, 2]
138
+ G1 = nx.expected_degree_graph(deg_seq, seed=1000)
139
+ G2 = nx.expected_degree_graph(deg_seq, seed=1000)
140
+ assert nx.is_isomorphic(G1, G2)
141
+ assert len(G1) == 5
142
+
143
+
144
+ def test_havel_hakimi_construction():
145
+ G = nx.havel_hakimi_graph([])
146
+ assert len(G) == 0
147
+
148
+ z = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
149
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
150
+ z = ["A", 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
151
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
152
+
153
+ z = [5, 4, 3, 3, 3, 2, 2, 2]
154
+ G = nx.havel_hakimi_graph(z)
155
+ G = nx.configuration_model(z)
156
+ z = [6, 5, 4, 4, 2, 1, 1, 1]
157
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z)
158
+
159
+ z = [10, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2]
160
+
161
+ G = nx.havel_hakimi_graph(z)
162
+
163
+ pytest.raises(nx.NetworkXError, nx.havel_hakimi_graph, z, create_using=nx.DiGraph())
164
+
165
+
166
+ def test_directed_havel_hakimi():
167
+ # Test range of valid directed degree sequences
168
+ n, r = 100, 10
169
+ p = 1.0 / r
170
+ for i in range(r):
171
+ G1 = nx.erdos_renyi_graph(n, p * (i + 1), None, True)
172
+ din1 = [d for n, d in G1.in_degree()]
173
+ dout1 = [d for n, d in G1.out_degree()]
174
+ G2 = nx.directed_havel_hakimi_graph(din1, dout1)
175
+ din2 = [d for n, d in G2.in_degree()]
176
+ dout2 = [d for n, d in G2.out_degree()]
177
+ assert sorted(din1) == sorted(din2)
178
+ assert sorted(dout1) == sorted(dout2)
179
+
180
+ # Test non-graphical sequence
181
+ dout = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
182
+ din = [103, 102, 102, 102, 102, 102, 102, 102, 102, 102]
183
+ pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
184
+ # Test valid sequences
185
+ dout = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
186
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 0, 2]
187
+ G2 = nx.directed_havel_hakimi_graph(din, dout)
188
+ dout2 = (d for n, d in G2.out_degree())
189
+ din2 = (d for n, d in G2.in_degree())
190
+ assert sorted(dout) == sorted(dout2)
191
+ assert sorted(din) == sorted(din2)
192
+ # Test unequal sums
193
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
194
+ pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
195
+ # Test for negative values
196
+ din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -2]
197
+ pytest.raises(nx.exception.NetworkXError, nx.directed_havel_hakimi_graph, din, dout)
198
+
199
+
200
+ def test_degree_sequence_tree():
201
+ z = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
202
+ G = nx.degree_sequence_tree(z)
203
+ assert len(G) == len(z)
204
+ assert len(list(G.edges())) == sum(z) / 2
205
+
206
+ pytest.raises(
207
+ nx.NetworkXError, nx.degree_sequence_tree, z, create_using=nx.DiGraph()
208
+ )
209
+
210
+ z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
211
+ pytest.raises(nx.NetworkXError, nx.degree_sequence_tree, z)
212
+
213
+
214
+ def test_random_degree_sequence_graph():
215
+ d = [1, 2, 2, 3]
216
+ G = nx.random_degree_sequence_graph(d, seed=42)
217
+ assert d == sorted(d for n, d in G.degree())
218
+
219
+
220
+ def test_random_degree_sequence_graph_raise():
221
+ z = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
222
+ pytest.raises(nx.NetworkXUnfeasible, nx.random_degree_sequence_graph, z)
223
+
224
+
225
+ def test_random_degree_sequence_large():
226
+ G1 = nx.fast_gnp_random_graph(100, 0.1, seed=42)
227
+ d1 = (d for n, d in G1.degree())
228
+ G2 = nx.random_degree_sequence_graph(d1, seed=42)
229
+ d2 = (d for n, d in G2.degree())
230
+ assert sorted(d1) == sorted(d2)
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_intersection.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestIntersectionGraph:
7
+ def test_random_intersection_graph(self):
8
+ G = nx.uniform_random_intersection_graph(10, 5, 0.5)
9
+ assert len(G) == 10
10
+
11
+ def test_k_random_intersection_graph(self):
12
+ G = nx.k_random_intersection_graph(10, 5, 2)
13
+ assert len(G) == 10
14
+
15
+ def test_k_random_intersection_graph_seeded(self):
16
+ G = nx.k_random_intersection_graph(10, 5, 2, seed=1234)
17
+ assert len(G) == 10
18
+
19
+ def test_general_random_intersection_graph(self):
20
+ G = nx.general_random_intersection_graph(10, 5, [0.1, 0.2, 0.2, 0.1, 0.1])
21
+ assert len(G) == 10
22
+ pytest.raises(
23
+ ValueError,
24
+ nx.general_random_intersection_graph,
25
+ 10,
26
+ 5,
27
+ [0.1, 0.2, 0.2, 0.1],
28
+ )
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_mycielski.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.mycielski` module."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestMycielski:
9
+ def test_construction(self):
10
+ G = nx.path_graph(2)
11
+ M = nx.mycielskian(G)
12
+ assert nx.is_isomorphic(M, nx.cycle_graph(5))
13
+
14
+ def test_size(self):
15
+ G = nx.path_graph(2)
16
+ M = nx.mycielskian(G, 2)
17
+ assert len(M) == 11
18
+ assert M.size() == 20
19
+
20
+ def test_mycielski_graph_generator(self):
21
+ G = nx.mycielski_graph(1)
22
+ assert nx.is_isomorphic(G, nx.empty_graph(1))
23
+ G = nx.mycielski_graph(2)
24
+ assert nx.is_isomorphic(G, nx.path_graph(2))
25
+ G = nx.mycielski_graph(3)
26
+ assert nx.is_isomorphic(G, nx.cycle_graph(5))
27
+ G = nx.mycielski_graph(4)
28
+ assert nx.is_isomorphic(G, nx.mycielskian(nx.cycle_graph(5)))
29
+ with pytest.raises(nx.NetworkXError, match="must satisfy n >= 1"):
30
+ nx.mycielski_graph(0)
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_small.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic
5
+
6
+ is_isomorphic = graph_could_be_isomorphic
7
+
8
+ """Generators - Small
9
+ =====================
10
+
11
+ Some small graphs
12
+ """
13
+
14
+ null = nx.null_graph()
15
+
16
+
17
+ class TestGeneratorsSmall:
18
+ def test__LCF_graph(self):
19
+ # If n<=0, then return the null_graph
20
+ G = nx.LCF_graph(-10, [1, 2], 100)
21
+ assert is_isomorphic(G, null)
22
+ G = nx.LCF_graph(0, [1, 2], 3)
23
+ assert is_isomorphic(G, null)
24
+ G = nx.LCF_graph(0, [1, 2], 10)
25
+ assert is_isomorphic(G, null)
26
+
27
+ # Test that LCF(n,[],0) == cycle_graph(n)
28
+ for a, b, c in [(5, [], 0), (10, [], 0), (5, [], 1), (10, [], 10)]:
29
+ G = nx.LCF_graph(a, b, c)
30
+ assert is_isomorphic(G, nx.cycle_graph(a))
31
+
32
+ # Generate the utility graph K_{3,3}
33
+ G = nx.LCF_graph(6, [3, -3], 3)
34
+ utility_graph = nx.complete_bipartite_graph(3, 3)
35
+ assert is_isomorphic(G, utility_graph)
36
+
37
+ with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
38
+ G = nx.LCF_graph(6, [3, -3], 3, create_using=nx.DiGraph)
39
+
40
+ def test_properties_named_small_graphs(self):
41
+ G = nx.bull_graph()
42
+ assert sorted(G) == list(range(5))
43
+ assert G.number_of_edges() == 5
44
+ assert sorted(d for n, d in G.degree()) == [1, 1, 2, 3, 3]
45
+ assert nx.diameter(G) == 3
46
+ assert nx.radius(G) == 2
47
+
48
+ G = nx.chvatal_graph()
49
+ assert sorted(G) == list(range(12))
50
+ assert G.number_of_edges() == 24
51
+ assert [d for n, d in G.degree()] == 12 * [4]
52
+ assert nx.diameter(G) == 2
53
+ assert nx.radius(G) == 2
54
+
55
+ G = nx.cubical_graph()
56
+ assert sorted(G) == list(range(8))
57
+ assert G.number_of_edges() == 12
58
+ assert [d for n, d in G.degree()] == 8 * [3]
59
+ assert nx.diameter(G) == 3
60
+ assert nx.radius(G) == 3
61
+
62
+ G = nx.desargues_graph()
63
+ assert sorted(G) == list(range(20))
64
+ assert G.number_of_edges() == 30
65
+ assert [d for n, d in G.degree()] == 20 * [3]
66
+
67
+ G = nx.diamond_graph()
68
+ assert sorted(G) == list(range(4))
69
+ assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3]
70
+ assert nx.diameter(G) == 2
71
+ assert nx.radius(G) == 1
72
+
73
+ G = nx.dodecahedral_graph()
74
+ assert sorted(G) == list(range(20))
75
+ assert G.number_of_edges() == 30
76
+ assert [d for n, d in G.degree()] == 20 * [3]
77
+ assert nx.diameter(G) == 5
78
+ assert nx.radius(G) == 5
79
+
80
+ G = nx.frucht_graph()
81
+ assert sorted(G) == list(range(12))
82
+ assert G.number_of_edges() == 18
83
+ assert [d for n, d in G.degree()] == 12 * [3]
84
+ assert nx.diameter(G) == 4
85
+ assert nx.radius(G) == 3
86
+
87
+ G = nx.heawood_graph()
88
+ assert sorted(G) == list(range(14))
89
+ assert G.number_of_edges() == 21
90
+ assert [d for n, d in G.degree()] == 14 * [3]
91
+ assert nx.diameter(G) == 3
92
+ assert nx.radius(G) == 3
93
+
94
+ G = nx.hoffman_singleton_graph()
95
+ assert sorted(G) == list(range(50))
96
+ assert G.number_of_edges() == 175
97
+ assert [d for n, d in G.degree()] == 50 * [7]
98
+ assert nx.diameter(G) == 2
99
+ assert nx.radius(G) == 2
100
+
101
+ G = nx.house_graph()
102
+ assert sorted(G) == list(range(5))
103
+ assert G.number_of_edges() == 6
104
+ assert sorted(d for n, d in G.degree()) == [2, 2, 2, 3, 3]
105
+ assert nx.diameter(G) == 2
106
+ assert nx.radius(G) == 2
107
+
108
+ G = nx.house_x_graph()
109
+ assert sorted(G) == list(range(5))
110
+ assert G.number_of_edges() == 8
111
+ assert sorted(d for n, d in G.degree()) == [2, 3, 3, 4, 4]
112
+ assert nx.diameter(G) == 2
113
+ assert nx.radius(G) == 1
114
+
115
+ G = nx.icosahedral_graph()
116
+ assert sorted(G) == list(range(12))
117
+ assert G.number_of_edges() == 30
118
+ assert [d for n, d in G.degree()] == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
119
+ assert nx.diameter(G) == 3
120
+ assert nx.radius(G) == 3
121
+
122
+ G = nx.krackhardt_kite_graph()
123
+ assert sorted(G) == list(range(10))
124
+ assert G.number_of_edges() == 18
125
+ assert sorted(d for n, d in G.degree()) == [1, 2, 3, 3, 3, 4, 4, 5, 5, 6]
126
+
127
+ G = nx.moebius_kantor_graph()
128
+ assert sorted(G) == list(range(16))
129
+ assert G.number_of_edges() == 24
130
+ assert [d for n, d in G.degree()] == 16 * [3]
131
+ assert nx.diameter(G) == 4
132
+
133
+ G = nx.octahedral_graph()
134
+ assert sorted(G) == list(range(6))
135
+ assert G.number_of_edges() == 12
136
+ assert [d for n, d in G.degree()] == 6 * [4]
137
+ assert nx.diameter(G) == 2
138
+ assert nx.radius(G) == 2
139
+
140
+ G = nx.pappus_graph()
141
+ assert sorted(G) == list(range(18))
142
+ assert G.number_of_edges() == 27
143
+ assert [d for n, d in G.degree()] == 18 * [3]
144
+ assert nx.diameter(G) == 4
145
+
146
+ G = nx.petersen_graph()
147
+ assert sorted(G) == list(range(10))
148
+ assert G.number_of_edges() == 15
149
+ assert [d for n, d in G.degree()] == 10 * [3]
150
+ assert nx.diameter(G) == 2
151
+ assert nx.radius(G) == 2
152
+
153
+ G = nx.sedgewick_maze_graph()
154
+ assert sorted(G) == list(range(8))
155
+ assert G.number_of_edges() == 10
156
+ assert sorted(d for n, d in G.degree()) == [1, 2, 2, 2, 3, 3, 3, 4]
157
+
158
+ G = nx.tetrahedral_graph()
159
+ assert sorted(G) == list(range(4))
160
+ assert G.number_of_edges() == 6
161
+ assert [d for n, d in G.degree()] == [3, 3, 3, 3]
162
+ assert nx.diameter(G) == 1
163
+ assert nx.radius(G) == 1
164
+
165
+ G = nx.truncated_cube_graph()
166
+ assert sorted(G) == list(range(24))
167
+ assert G.number_of_edges() == 36
168
+ assert [d for n, d in G.degree()] == 24 * [3]
169
+
170
+ G = nx.truncated_tetrahedron_graph()
171
+ assert sorted(G) == list(range(12))
172
+ assert G.number_of_edges() == 18
173
+ assert [d for n, d in G.degree()] == 12 * [3]
174
+
175
+ G = nx.tutte_graph()
176
+ assert sorted(G) == list(range(46))
177
+ assert G.number_of_edges() == 69
178
+ assert [d for n, d in G.degree()] == 46 * [3]
179
+
180
+ # Test create_using with directed or multigraphs on small graphs
181
+ pytest.raises(nx.NetworkXError, nx.tutte_graph, create_using=nx.DiGraph)
182
+ MG = nx.tutte_graph(create_using=nx.MultiGraph)
183
+ assert sorted(MG.edges()) == sorted(G.edges())
184
+
185
+
186
+ @pytest.mark.parametrize(
187
+ "fn",
188
+ (
189
+ nx.bull_graph,
190
+ nx.chvatal_graph,
191
+ nx.cubical_graph,
192
+ nx.diamond_graph,
193
+ nx.house_graph,
194
+ nx.house_x_graph,
195
+ nx.icosahedral_graph,
196
+ nx.krackhardt_kite_graph,
197
+ nx.octahedral_graph,
198
+ nx.petersen_graph,
199
+ nx.truncated_cube_graph,
200
+ nx.tutte_graph,
201
+ ),
202
+ )
203
+ @pytest.mark.parametrize(
204
+ "create_using", (nx.DiGraph, nx.MultiDiGraph, nx.DiGraph([(0, 1)]))
205
+ )
206
+ def tests_raises_with_directed_create_using(fn, create_using):
207
+ with pytest.raises(nx.NetworkXError, match="Directed Graph not supported"):
208
+ fn(create_using=create_using)
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_spectral_graph_forge.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ pytest.importorskip("numpy")
4
+ pytest.importorskip("scipy")
5
+
6
+
7
+ from networkx import is_isomorphic
8
+ from networkx.exception import NetworkXError
9
+ from networkx.generators import karate_club_graph
10
+ from networkx.generators.spectral_graph_forge import spectral_graph_forge
11
+ from networkx.utils import nodes_equal
12
+
13
+
14
+ def test_spectral_graph_forge():
15
+ G = karate_club_graph()
16
+
17
+ seed = 54321
18
+
19
+ # common cases, just checking node number preserving and difference
20
+ # between identity and modularity cases
21
+ H = spectral_graph_forge(G, 0.1, transformation="identity", seed=seed)
22
+ assert nodes_equal(G, H)
23
+
24
+ I = spectral_graph_forge(G, 0.1, transformation="identity", seed=seed)
25
+ assert nodes_equal(G, H)
26
+ assert is_isomorphic(I, H)
27
+
28
+ I = spectral_graph_forge(G, 0.1, transformation="modularity", seed=seed)
29
+ assert nodes_equal(G, I)
30
+
31
+ assert not is_isomorphic(I, H)
32
+
33
+ # with all the eigenvectors, output graph is identical to the input one
34
+ H = spectral_graph_forge(G, 1, transformation="modularity", seed=seed)
35
+ assert nodes_equal(G, H)
36
+ assert is_isomorphic(G, H)
37
+
38
+ # invalid alpha input value, it is silently truncated in [0,1]
39
+ H = spectral_graph_forge(G, -1, transformation="identity", seed=seed)
40
+ assert nodes_equal(G, H)
41
+
42
+ H = spectral_graph_forge(G, 10, transformation="identity", seed=seed)
43
+ assert nodes_equal(G, H)
44
+ assert is_isomorphic(G, H)
45
+
46
+ # invalid transformation mode, checking the error raising
47
+ pytest.raises(
48
+ NetworkXError, spectral_graph_forge, G, 0.1, transformation="unknown", seed=seed
49
+ )
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/tests/test_sudoku.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.generators.sudoku_graph` module."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ def test_sudoku_negative():
9
+ """Raise an error when generating a Sudoku graph of order -1."""
10
+ pytest.raises(nx.NetworkXError, nx.sudoku_graph, n=-1)
11
+
12
+
13
+ @pytest.mark.parametrize("n", [0, 1, 2, 3, 4])
14
+ def test_sudoku_generator(n):
15
+ """Generate Sudoku graphs of various sizes and verify their properties."""
16
+ G = nx.sudoku_graph(n)
17
+ expected_nodes = n**4
18
+ expected_degree = (n - 1) * (3 * n + 1)
19
+ expected_edges = expected_nodes * expected_degree // 2
20
+ assert not G.is_directed()
21
+ assert not G.is_multigraph()
22
+ assert G.number_of_nodes() == expected_nodes
23
+ assert G.number_of_edges() == expected_edges
24
+ assert all(d == expected_degree for _, d in G.degree)
25
+
26
+ if n == 2:
27
+ assert sorted(G.neighbors(6)) == [2, 3, 4, 5, 7, 10, 14]
28
+ elif n == 3:
29
+ assert sorted(G.neighbors(42)) == [
30
+ 6,
31
+ 15,
32
+ 24,
33
+ 33,
34
+ 34,
35
+ 35,
36
+ 36,
37
+ 37,
38
+ 38,
39
+ 39,
40
+ 40,
41
+ 41,
42
+ 43,
43
+ 44,
44
+ 51,
45
+ 52,
46
+ 53,
47
+ 60,
48
+ 69,
49
+ 78,
50
+ ]
51
+ elif n == 4:
52
+ assert sorted(G.neighbors(0)) == [
53
+ 1,
54
+ 2,
55
+ 3,
56
+ 4,
57
+ 5,
58
+ 6,
59
+ 7,
60
+ 8,
61
+ 9,
62
+ 10,
63
+ 11,
64
+ 12,
65
+ 13,
66
+ 14,
67
+ 15,
68
+ 16,
69
+ 17,
70
+ 18,
71
+ 19,
72
+ 32,
73
+ 33,
74
+ 34,
75
+ 35,
76
+ 48,
77
+ 49,
78
+ 50,
79
+ 51,
80
+ 64,
81
+ 80,
82
+ 96,
83
+ 112,
84
+ 128,
85
+ 144,
86
+ 160,
87
+ 176,
88
+ 192,
89
+ 208,
90
+ 224,
91
+ 240,
92
+ ]
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/time_series.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Time Series Graphs
3
+ """
4
+
5
+ import itertools
6
+
7
+ import networkx as nx
8
+
9
+ __all__ = ["visibility_graph"]
10
+
11
+
12
+ @nx._dispatchable(graphs=None, returns_graph=True)
13
+ def visibility_graph(series):
14
+ """
15
+ Return a Visibility Graph of an input Time Series.
16
+
17
+ A visibility graph converts a time series into a graph. The constructed graph
18
+ uses integer nodes to indicate which event in the series the node represents.
19
+ Edges are formed as follows: consider a bar plot of the series and view that
20
+ as a side view of a landscape with a node at the top of each bar. An edge
21
+ means that the nodes can be connected by a straight "line-of-sight" without
22
+ being obscured by any bars between the nodes.
23
+
24
+ The resulting graph inherits several properties of the series in its structure.
25
+ Thereby, periodic series convert into regular graphs, random series convert
26
+ into random graphs, and fractal series convert into scale-free networks [1]_.
27
+
28
+ Parameters
29
+ ----------
30
+ series : Sequence[Number]
31
+ A Time Series sequence (iterable and sliceable) of numeric values
32
+ representing times.
33
+
34
+ Returns
35
+ -------
36
+ NetworkX Graph
37
+ The Visibility Graph of the input series
38
+
39
+ Examples
40
+ --------
41
+ >>> series_list = [range(10), [2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1, 3]]
42
+ >>> for s in series_list:
43
+ ... g = nx.visibility_graph(s)
44
+ ... print(g)
45
+ Graph with 10 nodes and 9 edges
46
+ Graph with 12 nodes and 18 edges
47
+
48
+ References
49
+ ----------
50
+ .. [1] Lacasa, Lucas, Bartolo Luque, Fernando Ballesteros, Jordi Luque, and Juan Carlos Nuno.
51
+ "From time series to complex networks: The visibility graph." Proceedings of the
52
+ National Academy of Sciences 105, no. 13 (2008): 4972-4975.
53
+ https://www.pnas.org/doi/10.1073/pnas.0709247105
54
+ """
55
+
56
+ # Sequential values are always connected
57
+ G = nx.path_graph(len(series))
58
+ nx.set_node_attributes(G, dict(enumerate(series)), "value")
59
+
60
+ # Check all combinations of nodes n series
61
+ for (n1, t1), (n2, t2) in itertools.combinations(enumerate(series), 2):
62
+ # check if any value between obstructs line of sight
63
+ slope = (t2 - t1) / (n2 - n1)
64
+ offset = t2 - slope * n2
65
+
66
+ obstructed = any(
67
+ t >= slope * n + offset
68
+ for n, t in enumerate(series[n1 + 1 : n2], start=n1 + 1)
69
+ )
70
+
71
+ if not obstructed:
72
+ G.add_edge(n1, n2)
73
+
74
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/trees.py ADDED
@@ -0,0 +1,1071 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for generating trees.
2
+
3
+ The functions sampling trees at random in this module come
4
+ in two variants: labeled and unlabeled. The labeled variants
5
+ sample from every possible tree with the given number of nodes
6
+ uniformly at random. The unlabeled variants sample from every
7
+ possible *isomorphism class* of trees with the given number
8
+ of nodes uniformly at random.
9
+
10
+ To understand the difference, consider the following example.
11
+ There are two isomorphism classes of trees with four nodes.
12
+ One is that of the path graph, the other is that of the
13
+ star graph. The unlabeled variant will return a line graph or
14
+ a star graph with probability 1/2.
15
+
16
+ The labeled variant will return the line graph
17
+ with probability 3/4 and the star graph with probability 1/4,
18
+ because there are more labeled variants of the line graph
19
+ than of the star graph. More precisely, the line graph has
20
+ an automorphism group of order 2, whereas the star graph has
21
+ an automorphism group of order 6, so the line graph has three
22
+ times as many labeled variants as the star graph, and thus
23
+ three more chances to be drawn.
24
+
25
+ Additionally, some functions in this module can sample rooted
26
+ trees and forests uniformly at random. A rooted tree is a tree
27
+ with a designated root node. A rooted forest is a disjoint union
28
+ of rooted trees.
29
+ """
30
+
31
+ import warnings
32
+ from collections import Counter, defaultdict
33
+ from math import comb, factorial
34
+
35
+ import networkx as nx
36
+ from networkx.utils import py_random_state
37
+
38
+ __all__ = [
39
+ "prefix_tree",
40
+ "prefix_tree_recursive",
41
+ "random_labeled_tree",
42
+ "random_labeled_rooted_tree",
43
+ "random_labeled_rooted_forest",
44
+ "random_unlabeled_tree",
45
+ "random_unlabeled_rooted_tree",
46
+ "random_unlabeled_rooted_forest",
47
+ ]
48
+
49
+
50
+ @nx._dispatchable(graphs=None, returns_graph=True)
51
+ def prefix_tree(paths):
52
+ """Creates a directed prefix tree from a list of paths.
53
+
54
+ Usually the paths are described as strings or lists of integers.
55
+
56
+ A "prefix tree" represents the prefix structure of the strings.
57
+ Each node represents a prefix of some string. The root represents
58
+ the empty prefix with children for the single letter prefixes which
59
+ in turn have children for each double letter prefix starting with
60
+ the single letter corresponding to the parent node, and so on.
61
+
62
+ More generally the prefixes do not need to be strings. A prefix refers
63
+ to the start of a sequence. The root has children for each one element
64
+ prefix and they have children for each two element prefix that starts
65
+ with the one element sequence of the parent, and so on.
66
+
67
+ Note that this implementation uses integer nodes with an attribute.
68
+ Each node has an attribute "source" whose value is the original element
69
+ of the path to which this node corresponds. For example, suppose `paths`
70
+ consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
71
+ this path have "source" values "c", "a" and "n".
72
+
73
+ All the descendants of a node have a common prefix in the sequence/path
74
+ associated with that node. From the returned tree, the prefix for each
75
+ node can be constructed by traversing the tree up to the root and
76
+ accumulating the "source" values along the way.
77
+
78
+ The root node is always `0` and has "source" attribute `None`.
79
+ The root is the only node with in-degree zero.
80
+ The nil node is always `-1` and has "source" attribute `"NIL"`.
81
+ The nil node is the only node with out-degree zero.
82
+
83
+
84
+ Parameters
85
+ ----------
86
+ paths: iterable of paths
87
+ An iterable of paths which are themselves sequences.
88
+ Matching prefixes among these sequences are identified with
89
+ nodes of the prefix tree. One leaf of the tree is associated
90
+ with each path. (Identical paths are associated with the same
91
+ leaf of the tree.)
92
+
93
+
94
+ Returns
95
+ -------
96
+ tree: DiGraph
97
+ A directed graph representing an arborescence consisting of the
98
+ prefix tree generated by `paths`. Nodes are directed "downward",
99
+ from parent to child. A special "synthetic" root node is added
100
+ to be the parent of the first node in each path. A special
101
+ "synthetic" leaf node, the "nil" node `-1`, is added to be the child
102
+ of all nodes representing the last element in a path. (The
103
+ addition of this nil node technically makes this not an
104
+ arborescence but a directed acyclic graph; removing the nil node
105
+ makes it an arborescence.)
106
+
107
+
108
+ Notes
109
+ -----
110
+ The prefix tree is also known as a *trie*.
111
+
112
+
113
+ Examples
114
+ --------
115
+ Create a prefix tree from a list of strings with common prefixes::
116
+
117
+ >>> paths = ["ab", "abs", "ad"]
118
+ >>> T = nx.prefix_tree(paths)
119
+ >>> list(T.edges)
120
+ [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]
121
+
122
+ The leaf nodes can be obtained as predecessors of the nil node::
123
+
124
+ >>> root, NIL = 0, -1
125
+ >>> list(T.predecessors(NIL))
126
+ [2, 3, 4]
127
+
128
+ To recover the original paths that generated the prefix tree,
129
+ traverse up the tree from the node `-1` to the node `0`::
130
+
131
+ >>> recovered = []
132
+ >>> for v in T.predecessors(NIL):
133
+ ... prefix = ""
134
+ ... while v != root:
135
+ ... prefix = str(T.nodes[v]["source"]) + prefix
136
+ ... v = next(T.predecessors(v)) # only one predecessor
137
+ ... recovered.append(prefix)
138
+ >>> sorted(recovered)
139
+ ['ab', 'abs', 'ad']
140
+ """
141
+
142
+ def get_children(parent, paths):
143
+ children = defaultdict(list)
144
+ # Populate dictionary with key(s) as the child/children of the root and
145
+ # value(s) as the remaining paths of the corresponding child/children
146
+ for path in paths:
147
+ # If path is empty, we add an edge to the NIL node.
148
+ if not path:
149
+ tree.add_edge(parent, NIL)
150
+ continue
151
+ child, *rest = path
152
+ # `child` may exist as the head of more than one path in `paths`.
153
+ children[child].append(rest)
154
+ return children
155
+
156
+ # Initialize the prefix tree with a root node and a nil node.
157
+ tree = nx.DiGraph()
158
+ root = 0
159
+ tree.add_node(root, source=None)
160
+ NIL = -1
161
+ tree.add_node(NIL, source="NIL")
162
+ children = get_children(root, paths)
163
+ stack = [(root, iter(children.items()))]
164
+ while stack:
165
+ parent, remaining_children = stack[-1]
166
+ try:
167
+ child, remaining_paths = next(remaining_children)
168
+ # Pop item off stack if there are no remaining children
169
+ except StopIteration:
170
+ stack.pop()
171
+ continue
172
+ # We relabel each child with an unused name.
173
+ new_name = len(tree) - 1
174
+ # The "source" node attribute stores the original node name.
175
+ tree.add_node(new_name, source=child)
176
+ tree.add_edge(parent, new_name)
177
+ children = get_children(new_name, remaining_paths)
178
+ stack.append((new_name, iter(children.items())))
179
+
180
+ return tree
181
+
182
+
183
+ @nx._dispatchable(graphs=None, returns_graph=True)
184
+ def prefix_tree_recursive(paths):
185
+ """Recursively creates a directed prefix tree from a list of paths.
186
+
187
+ The original recursive version of prefix_tree for comparison. It is
188
+ the same algorithm but the recursion is unrolled onto a stack.
189
+
190
+ Usually the paths are described as strings or lists of integers.
191
+
192
+ A "prefix tree" represents the prefix structure of the strings.
193
+ Each node represents a prefix of some string. The root represents
194
+ the empty prefix with children for the single letter prefixes which
195
+ in turn have children for each double letter prefix starting with
196
+ the single letter corresponding to the parent node, and so on.
197
+
198
+ More generally the prefixes do not need to be strings. A prefix refers
199
+ to the start of a sequence. The root has children for each one element
200
+ prefix and they have children for each two element prefix that starts
201
+ with the one element sequence of the parent, and so on.
202
+
203
+ Note that this implementation uses integer nodes with an attribute.
204
+ Each node has an attribute "source" whose value is the original element
205
+ of the path to which this node corresponds. For example, suppose `paths`
206
+ consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
207
+ this path have "source" values "c", "a" and "n".
208
+
209
+ All the descendants of a node have a common prefix in the sequence/path
210
+ associated with that node. From the returned tree, ehe prefix for each
211
+ node can be constructed by traversing the tree up to the root and
212
+ accumulating the "source" values along the way.
213
+
214
+ The root node is always `0` and has "source" attribute `None`.
215
+ The root is the only node with in-degree zero.
216
+ The nil node is always `-1` and has "source" attribute `"NIL"`.
217
+ The nil node is the only node with out-degree zero.
218
+
219
+
220
+ Parameters
221
+ ----------
222
+ paths: iterable of paths
223
+ An iterable of paths which are themselves sequences.
224
+ Matching prefixes among these sequences are identified with
225
+ nodes of the prefix tree. One leaf of the tree is associated
226
+ with each path. (Identical paths are associated with the same
227
+ leaf of the tree.)
228
+
229
+
230
+ Returns
231
+ -------
232
+ tree: DiGraph
233
+ A directed graph representing an arborescence consisting of the
234
+ prefix tree generated by `paths`. Nodes are directed "downward",
235
+ from parent to child. A special "synthetic" root node is added
236
+ to be the parent of the first node in each path. A special
237
+ "synthetic" leaf node, the "nil" node `-1`, is added to be the child
238
+ of all nodes representing the last element in a path. (The
239
+ addition of this nil node technically makes this not an
240
+ arborescence but a directed acyclic graph; removing the nil node
241
+ makes it an arborescence.)
242
+
243
+
244
+ Notes
245
+ -----
246
+ The prefix tree is also known as a *trie*.
247
+
248
+
249
+ Examples
250
+ --------
251
+ Create a prefix tree from a list of strings with common prefixes::
252
+
253
+ >>> paths = ["ab", "abs", "ad"]
254
+ >>> T = nx.prefix_tree(paths)
255
+ >>> list(T.edges)
256
+ [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]
257
+
258
+ The leaf nodes can be obtained as predecessors of the nil node.
259
+
260
+ >>> root, NIL = 0, -1
261
+ >>> list(T.predecessors(NIL))
262
+ [2, 3, 4]
263
+
264
+ To recover the original paths that generated the prefix tree,
265
+ traverse up the tree from the node `-1` to the node `0`::
266
+
267
+ >>> recovered = []
268
+ >>> for v in T.predecessors(NIL):
269
+ ... prefix = ""
270
+ ... while v != root:
271
+ ... prefix = str(T.nodes[v]["source"]) + prefix
272
+ ... v = next(T.predecessors(v)) # only one predecessor
273
+ ... recovered.append(prefix)
274
+ >>> sorted(recovered)
275
+ ['ab', 'abs', 'ad']
276
+ """
277
+
278
+ def _helper(paths, root, tree):
279
+ """Recursively create a trie from the given list of paths.
280
+
281
+ `paths` is a list of paths, each of which is itself a list of
282
+ nodes, relative to the given `root` (but not including it). This
283
+ list of paths will be interpreted as a tree-like structure, in
284
+ which two paths that share a prefix represent two branches of
285
+ the tree with the same initial segment.
286
+
287
+ `root` is the parent of the node at index 0 in each path.
288
+
289
+ `tree` is the "accumulator", the :class:`networkx.DiGraph`
290
+ representing the branching to which the new nodes and edges will
291
+ be added.
292
+
293
+ """
294
+ # For each path, remove the first node and make it a child of root.
295
+ # Any remaining paths then get processed recursively.
296
+ children = defaultdict(list)
297
+ for path in paths:
298
+ # If path is empty, we add an edge to the NIL node.
299
+ if not path:
300
+ tree.add_edge(root, NIL)
301
+ continue
302
+ child, *rest = path
303
+ # `child` may exist as the head of more than one path in `paths`.
304
+ children[child].append(rest)
305
+ # Add a node for each child, connect root, recurse to remaining paths
306
+ for child, remaining_paths in children.items():
307
+ # We relabel each child with an unused name.
308
+ new_name = len(tree) - 1
309
+ # The "source" node attribute stores the original node name.
310
+ tree.add_node(new_name, source=child)
311
+ tree.add_edge(root, new_name)
312
+ _helper(remaining_paths, new_name, tree)
313
+
314
+ # Initialize the prefix tree with a root node and a nil node.
315
+ tree = nx.DiGraph()
316
+ root = 0
317
+ tree.add_node(root, source=None)
318
+ NIL = -1
319
+ tree.add_node(NIL, source="NIL")
320
+ # Populate the tree.
321
+ _helper(paths, root, tree)
322
+ return tree
323
+
324
+
325
+ @py_random_state("seed")
326
+ @nx._dispatchable(graphs=None, returns_graph=True)
327
+ def random_labeled_tree(n, *, seed=None):
328
+ """Returns a labeled tree on `n` nodes chosen uniformly at random.
329
+
330
+ Generating uniformly distributed random Prüfer sequences and
331
+ converting them into the corresponding trees is a straightforward
332
+ method of generating uniformly distributed random labeled trees.
333
+ This function implements this method.
334
+
335
+ Parameters
336
+ ----------
337
+ n : int
338
+ The number of nodes, greater than zero.
339
+ seed : random_state
340
+ Indicator of random number generation state.
341
+ See :ref:`Randomness<randomness>`
342
+
343
+ Returns
344
+ -------
345
+ :class:`networkx.Graph`
346
+ A `networkx.Graph` with nodes in the set {0, …, *n* - 1}.
347
+
348
+ Raises
349
+ ------
350
+ NetworkXPointlessConcept
351
+ If `n` is zero (because the null graph is not a tree).
352
+
353
+ Examples
354
+ --------
355
+ >>> G = nx.random_labeled_tree(5, seed=42)
356
+ >>> nx.is_tree(G)
357
+ True
358
+ >>> G.edges
359
+ EdgeView([(0, 1), (0, 3), (0, 2), (2, 4)])
360
+
361
+ A tree with *arbitrarily directed* edges can be created by assigning
362
+ generated edges to a ``DiGraph``:
363
+
364
+ >>> DG = nx.DiGraph()
365
+ >>> DG.add_edges_from(G.edges)
366
+ >>> nx.is_tree(DG)
367
+ True
368
+ >>> DG.edges
369
+ OutEdgeView([(0, 1), (0, 3), (0, 2), (2, 4)])
370
+ """
371
+ # Cannot create a Prüfer sequence unless `n` is at least two.
372
+ if n == 0:
373
+ raise nx.NetworkXPointlessConcept("the null graph is not a tree")
374
+ if n == 1:
375
+ return nx.empty_graph(1)
376
+ return nx.from_prufer_sequence([seed.choice(range(n)) for i in range(n - 2)])
377
+
378
+
379
+ @py_random_state("seed")
380
+ @nx._dispatchable(graphs=None, returns_graph=True)
381
+ def random_labeled_rooted_tree(n, *, seed=None):
382
+ """Returns a labeled rooted tree with `n` nodes.
383
+
384
+ The returned tree is chosen uniformly at random from all labeled rooted trees.
385
+
386
+ Parameters
387
+ ----------
388
+ n : int
389
+ The number of nodes
390
+ seed : integer, random_state, or None (default)
391
+ Indicator of random number generation state.
392
+ See :ref:`Randomness<randomness>`.
393
+
394
+ Returns
395
+ -------
396
+ :class:`networkx.Graph`
397
+ A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
398
+ The root of the tree is selected uniformly from the nodes.
399
+ The "root" graph attribute identifies the root of the tree.
400
+
401
+ Notes
402
+ -----
403
+ This function returns the result of :func:`random_labeled_tree`
404
+ with a randomly selected root.
405
+
406
+ Raises
407
+ ------
408
+ NetworkXPointlessConcept
409
+ If `n` is zero (because the null graph is not a tree).
410
+ """
411
+ t = random_labeled_tree(n, seed=seed)
412
+ t.graph["root"] = seed.randint(0, n - 1)
413
+ return t
414
+
415
+
416
+ @py_random_state("seed")
417
+ @nx._dispatchable(graphs=None, returns_graph=True)
418
+ def random_labeled_rooted_forest(n, *, seed=None):
419
+ """Returns a labeled rooted forest with `n` nodes.
420
+
421
+ The returned forest is chosen uniformly at random using a
422
+ generalization of Prüfer sequences [1]_ in the form described in [2]_.
423
+
424
+ Parameters
425
+ ----------
426
+ n : int
427
+ The number of nodes.
428
+ seed : random_state
429
+ See :ref:`Randomness<randomness>`.
430
+
431
+ Returns
432
+ -------
433
+ :class:`networkx.Graph`
434
+ A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
435
+ The "roots" graph attribute is a set of integers containing the roots.
436
+
437
+ References
438
+ ----------
439
+ .. [1] Knuth, Donald E. "Another Enumeration of Trees."
440
+ Canadian Journal of Mathematics, 20 (1968): 1077-1086.
441
+ https://doi.org/10.4153/CJM-1968-104-8
442
+ .. [2] Rubey, Martin. "Counting Spanning Trees". Diplomarbeit
443
+ zur Erlangung des akademischen Grades Magister der
444
+ Naturwissenschaften an der Formal- und Naturwissenschaftlichen
445
+ Fakultät der Universität Wien. Wien, May 2000.
446
+ """
447
+
448
+ # Select the number of roots by iterating over the cumulative count of trees
449
+ # with at most k roots
450
+ def _select_k(n, seed):
451
+ r = seed.randint(0, (n + 1) ** (n - 1) - 1)
452
+ cum_sum = 0
453
+ for k in range(1, n):
454
+ cum_sum += (factorial(n - 1) * n ** (n - k)) // (
455
+ factorial(k - 1) * factorial(n - k)
456
+ )
457
+ if r < cum_sum:
458
+ return k
459
+
460
+ return n
461
+
462
+ F = nx.empty_graph(n)
463
+ if n == 0:
464
+ F.graph["roots"] = {}
465
+ return F
466
+ # Select the number of roots k
467
+ k = _select_k(n, seed)
468
+ if k == n:
469
+ F.graph["roots"] = set(range(n))
470
+ return F # Nothing to do
471
+ # Select the roots
472
+ roots = seed.sample(range(n), k)
473
+ # Nonroots
474
+ p = set(range(n)).difference(roots)
475
+ # Coding sequence
476
+ N = [seed.randint(0, n - 1) for i in range(n - k - 1)]
477
+ # Multiset of elements in N also in p
478
+ degree = Counter([x for x in N if x in p])
479
+ # Iterator over the elements of p with degree zero
480
+ iterator = iter(x for x in p if degree[x] == 0)
481
+ u = last = next(iterator)
482
+ # This loop is identical to that for Prüfer sequences,
483
+ # except that we can draw nodes only from p
484
+ for v in N:
485
+ F.add_edge(u, v)
486
+ degree[v] -= 1
487
+ if v < last and degree[v] == 0:
488
+ u = v
489
+ else:
490
+ last = u = next(iterator)
491
+
492
+ F.add_edge(u, roots[0])
493
+ F.graph["roots"] = set(roots)
494
+ return F
495
+
496
+
497
+ # The following functions support generation of unlabeled trees and forests.
498
+
499
+
500
+ def _to_nx(edges, n_nodes, root=None, roots=None):
501
+ """
502
+ Converts the (edges, n_nodes) input to a :class:`networkx.Graph`.
503
+ The (edges, n_nodes) input is a list of even length, where each pair
504
+ of consecutive integers represents an edge, and an integer `n_nodes`.
505
+ Integers in the list are elements of `range(n_nodes)`.
506
+
507
+ Parameters
508
+ ----------
509
+ edges : list of ints
510
+ The flattened list of edges of the graph.
511
+ n_nodes : int
512
+ The number of nodes of the graph.
513
+ root: int (default=None)
514
+ If not None, the "root" attribute of the graph will be set to this value.
515
+ roots: collection of ints (default=None)
516
+ If not None, he "roots" attribute of the graph will be set to this value.
517
+
518
+ Returns
519
+ -------
520
+ :class:`networkx.Graph`
521
+ The graph with `n_nodes` nodes and edges given by `edges`.
522
+ """
523
+ G = nx.empty_graph(n_nodes)
524
+ G.add_edges_from(edges)
525
+ if root is not None:
526
+ G.graph["root"] = root
527
+ if roots is not None:
528
+ G.graph["roots"] = roots
529
+ return G
530
+
531
+
532
+ def _num_rooted_trees(n, cache_trees):
533
+ """Returns the number of unlabeled rooted trees with `n` nodes.
534
+
535
+ See also https://oeis.org/A000081.
536
+
537
+ Parameters
538
+ ----------
539
+ n : int
540
+ The number of nodes
541
+ cache_trees : list of ints
542
+ The $i$-th element is the number of unlabeled rooted trees with $i$ nodes,
543
+ which is used as a cache (and is extended to length $n+1$ if needed)
544
+
545
+ Returns
546
+ -------
547
+ int
548
+ The number of unlabeled rooted trees with `n` nodes.
549
+ """
550
+ for n_i in range(len(cache_trees), n + 1):
551
+ cache_trees.append(
552
+ sum(
553
+ [
554
+ d * cache_trees[n_i - j * d] * cache_trees[d]
555
+ for d in range(1, n_i)
556
+ for j in range(1, (n_i - 1) // d + 1)
557
+ ]
558
+ )
559
+ // (n_i - 1)
560
+ )
561
+ return cache_trees[n]
562
+
563
+
564
+ def _select_jd_trees(n, cache_trees, seed):
565
+ """Returns a pair $(j,d)$ with a specific probability
566
+
567
+ Given $n$, returns a pair of positive integers $(j,d)$ with the probability
568
+ specified in formula (5) of Chapter 29 of [1]_.
569
+
570
+ Parameters
571
+ ----------
572
+ n : int
573
+ The number of nodes
574
+ cache_trees : list of ints
575
+ Cache for :func:`_num_rooted_trees`.
576
+ seed : random_state
577
+ See :ref:`Randomness<randomness>`.
578
+
579
+ Returns
580
+ -------
581
+ (int, int)
582
+ A pair of positive integers $(j,d)$ satisfying formula (5) of
583
+ Chapter 29 of [1]_.
584
+
585
+ References
586
+ ----------
587
+ .. [1] Nijenhuis, Albert, and Wilf, Herbert S.
588
+ "Combinatorial algorithms: for computers and calculators."
589
+ Academic Press, 1978.
590
+ https://doi.org/10.1016/C2013-0-11243-3
591
+ """
592
+ p = seed.randint(0, _num_rooted_trees(n, cache_trees) * (n - 1) - 1)
593
+ cumsum = 0
594
+ for d in range(n - 1, 0, -1):
595
+ for j in range(1, (n - 1) // d + 1):
596
+ cumsum += (
597
+ d
598
+ * _num_rooted_trees(n - j * d, cache_trees)
599
+ * _num_rooted_trees(d, cache_trees)
600
+ )
601
+ if p < cumsum:
602
+ return (j, d)
603
+
604
+
605
+ def _random_unlabeled_rooted_tree(n, cache_trees, seed):
606
+ """Returns an unlabeled rooted tree with `n` nodes.
607
+
608
+ Returns an unlabeled rooted tree with `n` nodes chosen uniformly
609
+ at random using the "RANRUT" algorithm from [1]_.
610
+ The tree is returned in the form: (list_of_edges, number_of_nodes)
611
+
612
+ Parameters
613
+ ----------
614
+ n : int
615
+ The number of nodes, greater than zero.
616
+ cache_trees : list ints
617
+ Cache for :func:`_num_rooted_trees`.
618
+ seed : random_state
619
+ See :ref:`Randomness<randomness>`.
620
+
621
+ Returns
622
+ -------
623
+ (list_of_edges, number_of_nodes) : list, int
624
+ A random unlabeled rooted tree with `n` nodes as a 2-tuple
625
+ ``(list_of_edges, number_of_nodes)``.
626
+ The root is node 0.
627
+
628
+ References
629
+ ----------
630
+ .. [1] Nijenhuis, Albert, and Wilf, Herbert S.
631
+ "Combinatorial algorithms: for computers and calculators."
632
+ Academic Press, 1978.
633
+ https://doi.org/10.1016/C2013-0-11243-3
634
+ """
635
+ if n == 1:
636
+ edges, n_nodes = [], 1
637
+ return edges, n_nodes
638
+ if n == 2:
639
+ edges, n_nodes = [(0, 1)], 2
640
+ return edges, n_nodes
641
+
642
+ j, d = _select_jd_trees(n, cache_trees, seed)
643
+ t1, t1_nodes = _random_unlabeled_rooted_tree(n - j * d, cache_trees, seed)
644
+ t2, t2_nodes = _random_unlabeled_rooted_tree(d, cache_trees, seed)
645
+ t12 = [(0, t2_nodes * i + t1_nodes) for i in range(j)]
646
+ t1.extend(t12)
647
+ for _ in range(j):
648
+ t1.extend((n1 + t1_nodes, n2 + t1_nodes) for n1, n2 in t2)
649
+ t1_nodes += t2_nodes
650
+
651
+ return t1, t1_nodes
652
+
653
+
654
+ @py_random_state("seed")
655
+ @nx._dispatchable(graphs=None, returns_graph=True)
656
+ def random_unlabeled_rooted_tree(n, *, number_of_trees=None, seed=None):
657
+ """Returns a number of unlabeled rooted trees uniformly at random
658
+
659
+ Returns one or more (depending on `number_of_trees`)
660
+ unlabeled rooted trees with `n` nodes drawn uniformly
661
+ at random.
662
+
663
+ Parameters
664
+ ----------
665
+ n : int
666
+ The number of nodes
667
+ number_of_trees : int or None (default)
668
+ If not None, this number of trees is generated and returned.
669
+ seed : integer, random_state, or None (default)
670
+ Indicator of random number generation state.
671
+ See :ref:`Randomness<randomness>`.
672
+
673
+ Returns
674
+ -------
675
+ :class:`networkx.Graph` or list of :class:`networkx.Graph`
676
+ A single `networkx.Graph` (or a list thereof, if `number_of_trees`
677
+ is specified) with nodes in the set {0, …, *n* - 1}.
678
+ The "root" graph attribute identifies the root of the tree.
679
+
680
+ Notes
681
+ -----
682
+ The trees are generated using the "RANRUT" algorithm from [1]_.
683
+ The algorithm needs to compute some counting functions
684
+ that are relatively expensive: in case several trees are needed,
685
+ it is advisable to use the `number_of_trees` optional argument
686
+ to reuse the counting functions.
687
+
688
+ Raises
689
+ ------
690
+ NetworkXPointlessConcept
691
+ If `n` is zero (because the null graph is not a tree).
692
+
693
+ References
694
+ ----------
695
+ .. [1] Nijenhuis, Albert, and Wilf, Herbert S.
696
+ "Combinatorial algorithms: for computers and calculators."
697
+ Academic Press, 1978.
698
+ https://doi.org/10.1016/C2013-0-11243-3
699
+ """
700
+ if n == 0:
701
+ raise nx.NetworkXPointlessConcept("the null graph is not a tree")
702
+ cache_trees = [0, 1] # initial cache of number of rooted trees
703
+ if number_of_trees is None:
704
+ return _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0)
705
+ return [
706
+ _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0)
707
+ for i in range(number_of_trees)
708
+ ]
709
+
710
+
711
+ def _num_rooted_forests(n, q, cache_forests):
712
+ """Returns the number of unlabeled rooted forests with `n` nodes, and with
713
+ no more than `q` nodes per tree. A recursive formula for this is (2) in
714
+ [1]_. This function is implemented using dynamic programming instead of
715
+ recursion.
716
+
717
+ Parameters
718
+ ----------
719
+ n : int
720
+ The number of nodes.
721
+ q : int
722
+ The maximum number of nodes for each tree of the forest.
723
+ cache_forests : list of ints
724
+ The $i$-th element is the number of unlabeled rooted forests with
725
+ $i$ nodes, and with no more than `q` nodes per tree; this is used
726
+ as a cache (and is extended to length `n` + 1 if needed).
727
+
728
+ Returns
729
+ -------
730
+ int
731
+ The number of unlabeled rooted forests with `n` nodes with no more than
732
+ `q` nodes per tree.
733
+
734
+ References
735
+ ----------
736
+ .. [1] Wilf, Herbert S. "The uniform selection of free trees."
737
+ Journal of Algorithms 2.2 (1981): 204-207.
738
+ https://doi.org/10.1016/0196-6774(81)90021-3
739
+ """
740
+ for n_i in range(len(cache_forests), n + 1):
741
+ q_i = min(n_i, q)
742
+ cache_forests.append(
743
+ sum(
744
+ [
745
+ d * cache_forests[n_i - j * d] * cache_forests[d - 1]
746
+ for d in range(1, q_i + 1)
747
+ for j in range(1, n_i // d + 1)
748
+ ]
749
+ )
750
+ // n_i
751
+ )
752
+
753
+ return cache_forests[n]
754
+
755
+
756
+ def _select_jd_forests(n, q, cache_forests, seed):
757
+ """Given `n` and `q`, returns a pair of positive integers $(j,d)$
758
+ such that $j\\leq d$, with probability satisfying (F1) of [1]_.
759
+
760
+ Parameters
761
+ ----------
762
+ n : int
763
+ The number of nodes.
764
+ q : int
765
+ The maximum number of nodes for each tree of the forest.
766
+ cache_forests : list of ints
767
+ Cache for :func:`_num_rooted_forests`.
768
+ seed : random_state
769
+ See :ref:`Randomness<randomness>`.
770
+
771
+ Returns
772
+ -------
773
+ (int, int)
774
+ A pair of positive integers $(j,d)$
775
+
776
+ References
777
+ ----------
778
+ .. [1] Wilf, Herbert S. "The uniform selection of free trees."
779
+ Journal of Algorithms 2.2 (1981): 204-207.
780
+ https://doi.org/10.1016/0196-6774(81)90021-3
781
+ """
782
+ p = seed.randint(0, _num_rooted_forests(n, q, cache_forests) * n - 1)
783
+ cumsum = 0
784
+ for d in range(q, 0, -1):
785
+ for j in range(1, n // d + 1):
786
+ cumsum += (
787
+ d
788
+ * _num_rooted_forests(n - j * d, q, cache_forests)
789
+ * _num_rooted_forests(d - 1, q, cache_forests)
790
+ )
791
+ if p < cumsum:
792
+ return (j, d)
793
+
794
+
795
+ def _random_unlabeled_rooted_forest(n, q, cache_trees, cache_forests, seed):
796
+ """Returns an unlabeled rooted forest with `n` nodes, and with no more
797
+ than `q` nodes per tree, drawn uniformly at random. It is an implementation
798
+ of the algorithm "Forest" of [1]_.
799
+
800
+ Parameters
801
+ ----------
802
+ n : int
803
+ The number of nodes.
804
+ q : int
805
+ The maximum number of nodes per tree.
806
+ cache_trees :
807
+ Cache for :func:`_num_rooted_trees`.
808
+ cache_forests :
809
+ Cache for :func:`_num_rooted_forests`.
810
+ seed : random_state
811
+ See :ref:`Randomness<randomness>`.
812
+
813
+ Returns
814
+ -------
815
+ (edges, n, r) : (list, int, list)
816
+ The forest (edges, n) and a list r of root nodes.
817
+
818
+ References
819
+ ----------
820
+ .. [1] Wilf, Herbert S. "The uniform selection of free trees."
821
+ Journal of Algorithms 2.2 (1981): 204-207.
822
+ https://doi.org/10.1016/0196-6774(81)90021-3
823
+ """
824
+ if n == 0:
825
+ return ([], 0, [])
826
+
827
+ j, d = _select_jd_forests(n, q, cache_forests, seed)
828
+ t1, t1_nodes, r1 = _random_unlabeled_rooted_forest(
829
+ n - j * d, q, cache_trees, cache_forests, seed
830
+ )
831
+ t2, t2_nodes = _random_unlabeled_rooted_tree(d, cache_trees, seed)
832
+ for _ in range(j):
833
+ r1.append(t1_nodes)
834
+ t1.extend((n1 + t1_nodes, n2 + t1_nodes) for n1, n2 in t2)
835
+ t1_nodes += t2_nodes
836
+ return t1, t1_nodes, r1
837
+
838
+
839
+ @py_random_state("seed")
840
+ @nx._dispatchable(graphs=None, returns_graph=True)
841
+ def random_unlabeled_rooted_forest(n, *, q=None, number_of_forests=None, seed=None):
842
+ """Returns a forest or list of forests selected at random.
843
+
844
+ Returns one or more (depending on `number_of_forests`)
845
+ unlabeled rooted forests with `n` nodes, and with no more than
846
+ `q` nodes per tree, drawn uniformly at random.
847
+ The "roots" graph attribute identifies the roots of the forest.
848
+
849
+ Parameters
850
+ ----------
851
+ n : int
852
+ The number of nodes
853
+ q : int or None (default)
854
+ The maximum number of nodes per tree.
855
+ number_of_forests : int or None (default)
856
+ If not None, this number of forests is generated and returned.
857
+ seed : integer, random_state, or None (default)
858
+ Indicator of random number generation state.
859
+ See :ref:`Randomness<randomness>`.
860
+
861
+ Returns
862
+ -------
863
+ :class:`networkx.Graph` or list of :class:`networkx.Graph`
864
+ A single `networkx.Graph` (or a list thereof, if `number_of_forests`
865
+ is specified) with nodes in the set {0, …, *n* - 1}.
866
+ The "roots" graph attribute is a set containing the roots
867
+ of the trees in the forest.
868
+
869
+ Notes
870
+ -----
871
+ This function implements the algorithm "Forest" of [1]_.
872
+ The algorithm needs to compute some counting functions
873
+ that are relatively expensive: in case several trees are needed,
874
+ it is advisable to use the `number_of_forests` optional argument
875
+ to reuse the counting functions.
876
+
877
+ Raises
878
+ ------
879
+ ValueError
880
+ If `n` is non-zero but `q` is zero.
881
+
882
+ References
883
+ ----------
884
+ .. [1] Wilf, Herbert S. "The uniform selection of free trees."
885
+ Journal of Algorithms 2.2 (1981): 204-207.
886
+ https://doi.org/10.1016/0196-6774(81)90021-3
887
+ """
888
+ if q is None:
889
+ q = n
890
+ if q == 0 and n != 0:
891
+ raise ValueError("q must be a positive integer if n is positive.")
892
+
893
+ cache_trees = [0, 1] # initial cache of number of rooted trees
894
+ cache_forests = [1] # initial cache of number of rooted forests
895
+
896
+ if number_of_forests is None:
897
+ g, nodes, rs = _random_unlabeled_rooted_forest(
898
+ n, q, cache_trees, cache_forests, seed
899
+ )
900
+ return _to_nx(g, nodes, roots=set(rs))
901
+
902
+ res = []
903
+ for i in range(number_of_forests):
904
+ g, nodes, rs = _random_unlabeled_rooted_forest(
905
+ n, q, cache_trees, cache_forests, seed
906
+ )
907
+ res.append(_to_nx(g, nodes, roots=set(rs)))
908
+ return res
909
+
910
+
911
+ def _num_trees(n, cache_trees):
912
+ """Returns the number of unlabeled trees with `n` nodes.
913
+
914
+ See also https://oeis.org/A000055.
915
+
916
+ Parameters
917
+ ----------
918
+ n : int
919
+ The number of nodes.
920
+ cache_trees : list of ints
921
+ Cache for :func:`_num_rooted_trees`.
922
+
923
+ Returns
924
+ -------
925
+ int
926
+ The number of unlabeled trees with `n` nodes.
927
+ """
928
+ r = _num_rooted_trees(n, cache_trees) - sum(
929
+ [
930
+ _num_rooted_trees(j, cache_trees) * _num_rooted_trees(n - j, cache_trees)
931
+ for j in range(1, n // 2 + 1)
932
+ ]
933
+ )
934
+ if n % 2 == 0:
935
+ r += comb(_num_rooted_trees(n // 2, cache_trees) + 1, 2)
936
+ return r
937
+
938
+
939
+ def _bicenter(n, cache, seed):
940
+ """Returns a bi-centroidal tree on `n` nodes drawn uniformly at random.
941
+
942
+ This function implements the algorithm Bicenter of [1]_.
943
+
944
+ Parameters
945
+ ----------
946
+ n : int
947
+ The number of nodes (must be even).
948
+ cache : list of ints.
949
+ Cache for :func:`_num_rooted_trees`.
950
+ seed : random_state
951
+ See :ref:`Randomness<randomness>`
952
+
953
+ Returns
954
+ -------
955
+ (edges, n)
956
+ The tree as a list of edges and number of nodes.
957
+
958
+ References
959
+ ----------
960
+ .. [1] Wilf, Herbert S. "The uniform selection of free trees."
961
+ Journal of Algorithms 2.2 (1981): 204-207.
962
+ https://doi.org/10.1016/0196-6774(81)90021-3
963
+ """
964
+ t, t_nodes = _random_unlabeled_rooted_tree(n // 2, cache, seed)
965
+ if seed.randint(0, _num_rooted_trees(n // 2, cache)) == 0:
966
+ t2, t2_nodes = t, t_nodes
967
+ else:
968
+ t2, t2_nodes = _random_unlabeled_rooted_tree(n // 2, cache, seed)
969
+ t.extend([(n1 + (n // 2), n2 + (n // 2)) for n1, n2 in t2])
970
+ t.append((0, n // 2))
971
+ return t, t_nodes + t2_nodes
972
+
973
+
974
+ def _random_unlabeled_tree(n, cache_trees, cache_forests, seed):
975
+ """Returns a tree on `n` nodes drawn uniformly at random.
976
+ It implements the Wilf's algorithm "Free" of [1]_.
977
+
978
+ Parameters
979
+ ----------
980
+ n : int
981
+ The number of nodes, greater than zero.
982
+ cache_trees : list of ints
983
+ Cache for :func:`_num_rooted_trees`.
984
+ cache_forests : list of ints
985
+ Cache for :func:`_num_rooted_forests`.
986
+ seed : random_state
987
+ Indicator of random number generation state.
988
+ See :ref:`Randomness<randomness>`
989
+
990
+ Returns
991
+ -------
992
+ (edges, n)
993
+ The tree as a list of edges and number of nodes.
994
+
995
+ References
996
+ ----------
997
+ .. [1] Wilf, Herbert S. "The uniform selection of free trees."
998
+ Journal of Algorithms 2.2 (1981): 204-207.
999
+ https://doi.org/10.1016/0196-6774(81)90021-3
1000
+ """
1001
+ if n % 2 == 1:
1002
+ p = 0
1003
+ else:
1004
+ p = comb(_num_rooted_trees(n // 2, cache_trees) + 1, 2)
1005
+ if seed.randint(0, _num_trees(n, cache_trees) - 1) < p:
1006
+ return _bicenter(n, cache_trees, seed)
1007
+ else:
1008
+ f, n_f, r = _random_unlabeled_rooted_forest(
1009
+ n - 1, (n - 1) // 2, cache_trees, cache_forests, seed
1010
+ )
1011
+ for i in r:
1012
+ f.append((i, n_f))
1013
+ return f, n_f + 1
1014
+
1015
+
1016
+ @py_random_state("seed")
1017
+ @nx._dispatchable(graphs=None, returns_graph=True)
1018
+ def random_unlabeled_tree(n, *, number_of_trees=None, seed=None):
1019
+ """Returns a tree or list of trees chosen randomly.
1020
+
1021
+ Returns one or more (depending on `number_of_trees`)
1022
+ unlabeled trees with `n` nodes drawn uniformly at random.
1023
+
1024
+ Parameters
1025
+ ----------
1026
+ n : int
1027
+ The number of nodes
1028
+ number_of_trees : int or None (default)
1029
+ If not None, this number of trees is generated and returned.
1030
+ seed : integer, random_state, or None (default)
1031
+ Indicator of random number generation state.
1032
+ See :ref:`Randomness<randomness>`.
1033
+
1034
+ Returns
1035
+ -------
1036
+ :class:`networkx.Graph` or list of :class:`networkx.Graph`
1037
+ A single `networkx.Graph` (or a list thereof, if
1038
+ `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}.
1039
+
1040
+ Raises
1041
+ ------
1042
+ NetworkXPointlessConcept
1043
+ If `n` is zero (because the null graph is not a tree).
1044
+
1045
+ Notes
1046
+ -----
1047
+ This function generates an unlabeled tree uniformly at random using
1048
+ Wilf's algorithm "Free" of [1]_. The algorithm needs to
1049
+ compute some counting functions that are relatively expensive:
1050
+ in case several trees are needed, it is advisable to use the
1051
+ `number_of_trees` optional argument to reuse the counting
1052
+ functions.
1053
+
1054
+ References
1055
+ ----------
1056
+ .. [1] Wilf, Herbert S. "The uniform selection of free trees."
1057
+ Journal of Algorithms 2.2 (1981): 204-207.
1058
+ https://doi.org/10.1016/0196-6774(81)90021-3
1059
+ """
1060
+ if n == 0:
1061
+ raise nx.NetworkXPointlessConcept("the null graph is not a tree")
1062
+
1063
+ cache_trees = [0, 1] # initial cache of number of rooted trees
1064
+ cache_forests = [1] # initial cache of number of rooted forests
1065
+ if number_of_trees is None:
1066
+ return _to_nx(*_random_unlabeled_tree(n, cache_trees, cache_forests, seed))
1067
+ else:
1068
+ return [
1069
+ _to_nx(*_random_unlabeled_tree(n, cache_trees, cache_forests, seed))
1070
+ for i in range(number_of_trees)
1071
+ ]
evalkit_tf446/lib/python3.10/site-packages/networkx/generators/triads.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://github.com/networkx/networkx/pull/1474
2
+ # Copyright 2011 Reya Group <http://www.reyagroup.com>
3
+ # Copyright 2011 Alex Levenson <alex@isnotinvain.com>
4
+ # Copyright 2011 Diederik van Liere <diederik.vanliere@rotman.utoronto.ca>
5
+ """Functions that generate the triad graphs, that is, the possible
6
+ digraphs on three nodes.
7
+
8
+ """
9
+
10
+ import networkx as nx
11
+ from networkx.classes import DiGraph
12
+
13
+ __all__ = ["triad_graph"]
14
+
15
+ #: Dictionary mapping triad name to list of directed edges in the
16
+ #: digraph representation of that triad (with nodes 'a', 'b', and 'c').
17
+ TRIAD_EDGES = {
18
+ "003": [],
19
+ "012": ["ab"],
20
+ "102": ["ab", "ba"],
21
+ "021D": ["ba", "bc"],
22
+ "021U": ["ab", "cb"],
23
+ "021C": ["ab", "bc"],
24
+ "111D": ["ac", "ca", "bc"],
25
+ "111U": ["ac", "ca", "cb"],
26
+ "030T": ["ab", "cb", "ac"],
27
+ "030C": ["ba", "cb", "ac"],
28
+ "201": ["ab", "ba", "ac", "ca"],
29
+ "120D": ["bc", "ba", "ac", "ca"],
30
+ "120U": ["ab", "cb", "ac", "ca"],
31
+ "120C": ["ab", "bc", "ac", "ca"],
32
+ "210": ["ab", "bc", "cb", "ac", "ca"],
33
+ "300": ["ab", "ba", "bc", "cb", "ac", "ca"],
34
+ }
35
+
36
+
37
+ @nx._dispatchable(graphs=None, returns_graph=True)
38
+ def triad_graph(triad_name):
39
+ """Returns the triad graph with the given name.
40
+
41
+ Each string in the following tuple is a valid triad name::
42
+
43
+ (
44
+ "003",
45
+ "012",
46
+ "102",
47
+ "021D",
48
+ "021U",
49
+ "021C",
50
+ "111D",
51
+ "111U",
52
+ "030T",
53
+ "030C",
54
+ "201",
55
+ "120D",
56
+ "120U",
57
+ "120C",
58
+ "210",
59
+ "300",
60
+ )
61
+
62
+ Each triad name corresponds to one of the possible valid digraph on
63
+ three nodes.
64
+
65
+ Parameters
66
+ ----------
67
+ triad_name : string
68
+ The name of a triad, as described above.
69
+
70
+ Returns
71
+ -------
72
+ :class:`~networkx.DiGraph`
73
+ The digraph on three nodes with the given name. The nodes of the
74
+ graph are the single-character strings 'a', 'b', and 'c'.
75
+
76
+ Raises
77
+ ------
78
+ ValueError
79
+ If `triad_name` is not the name of a triad.
80
+
81
+ See also
82
+ --------
83
+ triadic_census
84
+
85
+ """
86
+ if triad_name not in TRIAD_EDGES:
87
+ raise ValueError(
88
+ f'unknown triad name "{triad_name}"; use one of the triad names'
89
+ " in the TRIAD_NAMES constant"
90
+ )
91
+ G = DiGraph()
92
+ G.add_nodes_from("abc")
93
+ G.add_edges_from(TRIAD_EDGES[triad_name])
94
+ return G
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (173 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_all_random_functions.cpython-310.pyc ADDED
Binary file (7.18 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_numpy.cpython-310.pyc ADDED
Binary file (18.4 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_pandas.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_scipy.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_exceptions.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_import.cpython-310.pyc ADDED
Binary file (618 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_lazy_imports.cpython-310.pyc ADDED
Binary file (2.14 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/__pycache__/test_relabel.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_convert_numpy.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+
3
+ import pytest
4
+
5
+ np = pytest.importorskip("numpy")
6
+ npt = pytest.importorskip("numpy.testing")
7
+
8
+ import networkx as nx
9
+ from networkx.generators.classic import barbell_graph, cycle_graph, path_graph
10
+ from networkx.utils import graphs_equal
11
+
12
+
13
+ class TestConvertNumpyArray:
14
+ def setup_method(self):
15
+ self.G1 = barbell_graph(10, 3)
16
+ self.G2 = cycle_graph(10, create_using=nx.DiGraph)
17
+ self.G3 = self.create_weighted(nx.Graph())
18
+ self.G4 = self.create_weighted(nx.DiGraph())
19
+
20
+ def create_weighted(self, G):
21
+ g = cycle_graph(4)
22
+ G.add_nodes_from(g)
23
+ G.add_weighted_edges_from((u, v, 10 + u) for u, v in g.edges())
24
+ return G
25
+
26
+ def assert_equal(self, G1, G2):
27
+ assert sorted(G1.nodes()) == sorted(G2.nodes())
28
+ assert sorted(G1.edges()) == sorted(G2.edges())
29
+
30
+ def identity_conversion(self, G, A, create_using):
31
+ assert A.sum() > 0
32
+ GG = nx.from_numpy_array(A, create_using=create_using)
33
+ self.assert_equal(G, GG)
34
+ GW = nx.to_networkx_graph(A, create_using=create_using)
35
+ self.assert_equal(G, GW)
36
+ GI = nx.empty_graph(0, create_using).__class__(A)
37
+ self.assert_equal(G, GI)
38
+
39
+ def test_shape(self):
40
+ "Conversion from non-square array."
41
+ A = np.array([[1, 2, 3], [4, 5, 6]])
42
+ pytest.raises(nx.NetworkXError, nx.from_numpy_array, A)
43
+
44
+ def test_identity_graph_array(self):
45
+ "Conversion from graph to array to graph."
46
+ A = nx.to_numpy_array(self.G1)
47
+ self.identity_conversion(self.G1, A, nx.Graph())
48
+
49
+ def test_identity_digraph_array(self):
50
+ """Conversion from digraph to array to digraph."""
51
+ A = nx.to_numpy_array(self.G2)
52
+ self.identity_conversion(self.G2, A, nx.DiGraph())
53
+
54
+ def test_identity_weighted_graph_array(self):
55
+ """Conversion from weighted graph to array to weighted graph."""
56
+ A = nx.to_numpy_array(self.G3)
57
+ self.identity_conversion(self.G3, A, nx.Graph())
58
+
59
+ def test_identity_weighted_digraph_array(self):
60
+ """Conversion from weighted digraph to array to weighted digraph."""
61
+ A = nx.to_numpy_array(self.G4)
62
+ self.identity_conversion(self.G4, A, nx.DiGraph())
63
+
64
+ def test_nodelist(self):
65
+ """Conversion from graph to array to graph with nodelist."""
66
+ P4 = path_graph(4)
67
+ P3 = path_graph(3)
68
+ nodelist = list(P3)
69
+ A = nx.to_numpy_array(P4, nodelist=nodelist)
70
+ GA = nx.Graph(A)
71
+ self.assert_equal(GA, P3)
72
+
73
+ # Make nodelist ambiguous by containing duplicates.
74
+ nodelist += [nodelist[0]]
75
+ pytest.raises(nx.NetworkXError, nx.to_numpy_array, P3, nodelist=nodelist)
76
+
77
+ # Make nodelist invalid by including nonexistent nodes
78
+ nodelist = [-1, 0, 1]
79
+ with pytest.raises(
80
+ nx.NetworkXError,
81
+ match=f"Nodes {nodelist - P3.nodes} in nodelist is not in G",
82
+ ):
83
+ nx.to_numpy_array(P3, nodelist=nodelist)
84
+
85
+ def test_weight_keyword(self):
86
+ WP4 = nx.Graph()
87
+ WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
88
+ P4 = path_graph(4)
89
+ A = nx.to_numpy_array(P4)
90
+ np.testing.assert_equal(A, nx.to_numpy_array(WP4, weight=None))
91
+ np.testing.assert_equal(0.5 * A, nx.to_numpy_array(WP4))
92
+ np.testing.assert_equal(0.3 * A, nx.to_numpy_array(WP4, weight="other"))
93
+
94
+ def test_from_numpy_array_type(self):
95
+ A = np.array([[1]])
96
+ G = nx.from_numpy_array(A)
97
+ assert type(G[0][0]["weight"]) == int
98
+
99
+ A = np.array([[1]]).astype(float)
100
+ G = nx.from_numpy_array(A)
101
+ assert type(G[0][0]["weight"]) == float
102
+
103
+ A = np.array([[1]]).astype(str)
104
+ G = nx.from_numpy_array(A)
105
+ assert type(G[0][0]["weight"]) == str
106
+
107
+ A = np.array([[1]]).astype(bool)
108
+ G = nx.from_numpy_array(A)
109
+ assert type(G[0][0]["weight"]) == bool
110
+
111
+ A = np.array([[1]]).astype(complex)
112
+ G = nx.from_numpy_array(A)
113
+ assert type(G[0][0]["weight"]) == complex
114
+
115
+ A = np.array([[1]]).astype(object)
116
+ pytest.raises(TypeError, nx.from_numpy_array, A)
117
+
118
+ A = np.array([[[1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1]]])
119
+ with pytest.raises(
120
+ nx.NetworkXError, match=f"Input array must be 2D, not {A.ndim}"
121
+ ):
122
+ g = nx.from_numpy_array(A)
123
+
124
+ def test_from_numpy_array_dtype(self):
125
+ dt = [("weight", float), ("cost", int)]
126
+ A = np.array([[(1.0, 2)]], dtype=dt)
127
+ G = nx.from_numpy_array(A)
128
+ assert type(G[0][0]["weight"]) == float
129
+ assert type(G[0][0]["cost"]) == int
130
+ assert G[0][0]["cost"] == 2
131
+ assert G[0][0]["weight"] == 1.0
132
+
133
+ def test_from_numpy_array_parallel_edges(self):
134
+ """Tests that the :func:`networkx.from_numpy_array` function
135
+ interprets integer weights as the number of parallel edges when
136
+ creating a multigraph.
137
+
138
+ """
139
+ A = np.array([[1, 1], [1, 2]])
140
+ # First, with a simple graph, each integer entry in the adjacency
141
+ # matrix is interpreted as the weight of a single edge in the graph.
142
+ expected = nx.DiGraph()
143
+ edges = [(0, 0), (0, 1), (1, 0)]
144
+ expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
145
+ expected.add_edge(1, 1, weight=2)
146
+ actual = nx.from_numpy_array(A, parallel_edges=True, create_using=nx.DiGraph)
147
+ assert graphs_equal(actual, expected)
148
+ actual = nx.from_numpy_array(A, parallel_edges=False, create_using=nx.DiGraph)
149
+ assert graphs_equal(actual, expected)
150
+ # Now each integer entry in the adjacency matrix is interpreted as the
151
+ # number of parallel edges in the graph if the appropriate keyword
152
+ # argument is specified.
153
+ edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
154
+ expected = nx.MultiDiGraph()
155
+ expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
156
+ actual = nx.from_numpy_array(
157
+ A, parallel_edges=True, create_using=nx.MultiDiGraph
158
+ )
159
+ assert graphs_equal(actual, expected)
160
+ expected = nx.MultiDiGraph()
161
+ expected.add_edges_from(set(edges), weight=1)
162
+ # The sole self-loop (edge 0) on vertex 1 should have weight 2.
163
+ expected[1][1][0]["weight"] = 2
164
+ actual = nx.from_numpy_array(
165
+ A, parallel_edges=False, create_using=nx.MultiDiGraph
166
+ )
167
+ assert graphs_equal(actual, expected)
168
+
169
+ @pytest.mark.parametrize(
170
+ "dt",
171
+ (
172
+ None, # default
173
+ int, # integer dtype
174
+ np.dtype(
175
+ [("weight", "f8"), ("color", "i1")]
176
+ ), # Structured dtype with named fields
177
+ ),
178
+ )
179
+ def test_from_numpy_array_no_edge_attr(self, dt):
180
+ A = np.array([[0, 1], [1, 0]], dtype=dt)
181
+ G = nx.from_numpy_array(A, edge_attr=None)
182
+ assert "weight" not in G.edges[0, 1]
183
+ assert len(G.edges[0, 1]) == 0
184
+
185
+ def test_from_numpy_array_multiedge_no_edge_attr(self):
186
+ A = np.array([[0, 2], [2, 0]])
187
+ G = nx.from_numpy_array(A, create_using=nx.MultiDiGraph, edge_attr=None)
188
+ assert all("weight" not in e for _, e in G[0][1].items())
189
+ assert len(G[0][1][0]) == 0
190
+
191
+ def test_from_numpy_array_custom_edge_attr(self):
192
+ A = np.array([[0, 2], [3, 0]])
193
+ G = nx.from_numpy_array(A, edge_attr="cost")
194
+ assert "weight" not in G.edges[0, 1]
195
+ assert G.edges[0, 1]["cost"] == 3
196
+
197
+ def test_symmetric(self):
198
+ """Tests that a symmetric array has edges added only once to an
199
+ undirected multigraph when using :func:`networkx.from_numpy_array`.
200
+
201
+ """
202
+ A = np.array([[0, 1], [1, 0]])
203
+ G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
204
+ expected = nx.MultiGraph()
205
+ expected.add_edge(0, 1, weight=1)
206
+ assert graphs_equal(G, expected)
207
+
208
+ def test_dtype_int_graph(self):
209
+ """Test that setting dtype int actually gives an integer array.
210
+
211
+ For more information, see GitHub pull request #1363.
212
+
213
+ """
214
+ G = nx.complete_graph(3)
215
+ A = nx.to_numpy_array(G, dtype=int)
216
+ assert A.dtype == int
217
+
218
+ def test_dtype_int_multigraph(self):
219
+ """Test that setting dtype int actually gives an integer array.
220
+
221
+ For more information, see GitHub pull request #1363.
222
+
223
+ """
224
+ G = nx.MultiGraph(nx.complete_graph(3))
225
+ A = nx.to_numpy_array(G, dtype=int)
226
+ assert A.dtype == int
227
+
228
+
229
+ @pytest.fixture
230
+ def multigraph_test_graph():
231
+ G = nx.MultiGraph()
232
+ G.add_edge(1, 2, weight=7)
233
+ G.add_edge(1, 2, weight=70)
234
+ return G
235
+
236
+
237
+ @pytest.mark.parametrize(("operator", "expected"), ((sum, 77), (min, 7), (max, 70)))
238
+ def test_numpy_multigraph(multigraph_test_graph, operator, expected):
239
+ A = nx.to_numpy_array(multigraph_test_graph, multigraph_weight=operator)
240
+ assert A[1, 0] == expected
241
+
242
+
243
+ def test_to_numpy_array_multigraph_nodelist(multigraph_test_graph):
244
+ G = multigraph_test_graph
245
+ G.add_edge(0, 1, weight=3)
246
+ A = nx.to_numpy_array(G, nodelist=[1, 2])
247
+ assert A.shape == (2, 2)
248
+ assert A[1, 0] == 77
249
+
250
+
251
+ @pytest.mark.parametrize(
252
+ "G, expected",
253
+ [
254
+ (nx.Graph(), np.array([[0, 1 + 2j], [1 + 2j, 0]], dtype=complex)),
255
+ (nx.DiGraph(), np.array([[0, 1 + 2j], [0, 0]], dtype=complex)),
256
+ ],
257
+ )
258
+ def test_to_numpy_array_complex_weights(G, expected):
259
+ G.add_edge(0, 1, weight=1 + 2j)
260
+ A = nx.to_numpy_array(G, dtype=complex)
261
+ npt.assert_array_equal(A, expected)
262
+
263
+
264
+ def test_to_numpy_array_arbitrary_weights():
265
+ G = nx.DiGraph()
266
+ w = 922337203685477580102 # Out of range for int64
267
+ G.add_edge(0, 1, weight=922337203685477580102) # val not representable by int64
268
+ A = nx.to_numpy_array(G, dtype=object)
269
+ expected = np.array([[0, w], [0, 0]], dtype=object)
270
+ npt.assert_array_equal(A, expected)
271
+
272
+ # Undirected
273
+ A = nx.to_numpy_array(G.to_undirected(), dtype=object)
274
+ expected = np.array([[0, w], [w, 0]], dtype=object)
275
+ npt.assert_array_equal(A, expected)
276
+
277
+
278
+ @pytest.mark.parametrize(
279
+ "func, expected",
280
+ ((min, -1), (max, 10), (sum, 11), (np.mean, 11 / 3), (np.median, 2)),
281
+ )
282
+ def test_to_numpy_array_multiweight_reduction(func, expected):
283
+ """Test various functions for reducing multiedge weights."""
284
+ G = nx.MultiDiGraph()
285
+ weights = [-1, 2, 10.0]
286
+ for w in weights:
287
+ G.add_edge(0, 1, weight=w)
288
+ A = nx.to_numpy_array(G, multigraph_weight=func, dtype=float)
289
+ assert np.allclose(A, [[0, expected], [0, 0]])
290
+
291
+ # Undirected case
292
+ A = nx.to_numpy_array(G.to_undirected(), multigraph_weight=func, dtype=float)
293
+ assert np.allclose(A, [[0, expected], [expected, 0]])
294
+
295
+
296
+ @pytest.mark.parametrize(
297
+ ("G, expected"),
298
+ [
299
+ (nx.Graph(), [[(0, 0), (10, 5)], [(10, 5), (0, 0)]]),
300
+ (nx.DiGraph(), [[(0, 0), (10, 5)], [(0, 0), (0, 0)]]),
301
+ ],
302
+ )
303
+ def test_to_numpy_array_structured_dtype_attrs_from_fields(G, expected):
304
+ """When `dtype` is structured (i.e. has names) and `weight` is None, use
305
+ the named fields of the dtype to look up edge attributes."""
306
+ G.add_edge(0, 1, weight=10, cost=5.0)
307
+ dtype = np.dtype([("weight", int), ("cost", int)])
308
+ A = nx.to_numpy_array(G, dtype=dtype, weight=None)
309
+ expected = np.asarray(expected, dtype=dtype)
310
+ npt.assert_array_equal(A, expected)
311
+
312
+
313
+ def test_to_numpy_array_structured_dtype_single_attr_default():
314
+ G = nx.path_graph(3)
315
+ dtype = np.dtype([("weight", float)]) # A single named field
316
+ A = nx.to_numpy_array(G, dtype=dtype, weight=None)
317
+ expected = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]], dtype=float)
318
+ npt.assert_array_equal(A["weight"], expected)
319
+
320
+
321
+ @pytest.mark.parametrize(
322
+ ("field_name", "expected_attr_val"),
323
+ [
324
+ ("weight", 1),
325
+ ("cost", 3),
326
+ ],
327
+ )
328
+ def test_to_numpy_array_structured_dtype_single_attr(field_name, expected_attr_val):
329
+ G = nx.Graph()
330
+ G.add_edge(0, 1, cost=3)
331
+ dtype = np.dtype([(field_name, float)])
332
+ A = nx.to_numpy_array(G, dtype=dtype, weight=None)
333
+ expected = np.array([[0, expected_attr_val], [expected_attr_val, 0]], dtype=float)
334
+ npt.assert_array_equal(A[field_name], expected)
335
+
336
+
337
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
338
+ @pytest.mark.parametrize(
339
+ "edge",
340
+ [
341
+ (0, 1), # No edge attributes
342
+ (0, 1, {"weight": 10}), # One edge attr
343
+ (0, 1, {"weight": 5, "flow": -4}), # Multiple but not all edge attrs
344
+ (0, 1, {"weight": 2.0, "cost": 10, "flow": -45}), # All attrs
345
+ ],
346
+ )
347
+ def test_to_numpy_array_structured_dtype_multiple_fields(graph_type, edge):
348
+ G = graph_type([edge])
349
+ dtype = np.dtype([("weight", float), ("cost", float), ("flow", float)])
350
+ A = nx.to_numpy_array(G, dtype=dtype, weight=None)
351
+ for attr in dtype.names:
352
+ expected = nx.to_numpy_array(G, dtype=float, weight=attr)
353
+ npt.assert_array_equal(A[attr], expected)
354
+
355
+
356
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
357
+ def test_to_numpy_array_structured_dtype_scalar_nonedge(G):
358
+ G.add_edge(0, 1, weight=10)
359
+ dtype = np.dtype([("weight", float), ("cost", float)])
360
+ A = nx.to_numpy_array(G, dtype=dtype, weight=None, nonedge=np.nan)
361
+ for attr in dtype.names:
362
+ expected = nx.to_numpy_array(G, dtype=float, weight=attr, nonedge=np.nan)
363
+ npt.assert_array_equal(A[attr], expected)
364
+
365
+
366
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
367
+ def test_to_numpy_array_structured_dtype_nonedge_ary(G):
368
+ """Similar to the scalar case, except has a different non-edge value for
369
+ each named field."""
370
+ G.add_edge(0, 1, weight=10)
371
+ dtype = np.dtype([("weight", float), ("cost", float)])
372
+ nonedges = np.array([(0, np.inf)], dtype=dtype)
373
+ A = nx.to_numpy_array(G, dtype=dtype, weight=None, nonedge=nonedges)
374
+ for attr in dtype.names:
375
+ nonedge = nonedges[attr]
376
+ expected = nx.to_numpy_array(G, dtype=float, weight=attr, nonedge=nonedge)
377
+ npt.assert_array_equal(A[attr], expected)
378
+
379
+
380
+ def test_to_numpy_array_structured_dtype_with_weight_raises():
381
+ """Using both a structured dtype (with named fields) and specifying a `weight`
382
+ parameter is ambiguous."""
383
+ G = nx.path_graph(3)
384
+ dtype = np.dtype([("weight", int), ("cost", int)])
385
+ exception_msg = "Specifying `weight` not supported for structured dtypes"
386
+ with pytest.raises(ValueError, match=exception_msg):
387
+ nx.to_numpy_array(G, dtype=dtype) # Default is weight="weight"
388
+ with pytest.raises(ValueError, match=exception_msg):
389
+ nx.to_numpy_array(G, dtype=dtype, weight="cost")
390
+
391
+
392
+ @pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.MultiDiGraph))
393
+ def test_to_numpy_array_structured_multigraph_raises(graph_type):
394
+ G = nx.path_graph(3, create_using=graph_type)
395
+ dtype = np.dtype([("weight", int), ("cost", int)])
396
+ with pytest.raises(nx.NetworkXError, match="Structured arrays are not supported"):
397
+ nx.to_numpy_array(G, dtype=dtype, weight=None)
398
+
399
+
400
+ def test_from_numpy_array_nodelist_bad_size():
401
+ """An exception is raised when `len(nodelist) != A.shape[0]`."""
402
+ n = 5 # Number of nodes
403
+ A = np.diag(np.ones(n - 1), k=1) # Adj. matrix for P_n
404
+ expected = nx.path_graph(n)
405
+
406
+ assert graphs_equal(nx.from_numpy_array(A, edge_attr=None), expected)
407
+ nodes = list(range(n))
408
+ assert graphs_equal(
409
+ nx.from_numpy_array(A, edge_attr=None, nodelist=nodes), expected
410
+ )
411
+
412
+ # Too many node labels
413
+ nodes = list(range(n + 1))
414
+ with pytest.raises(ValueError, match="nodelist must have the same length as A"):
415
+ nx.from_numpy_array(A, nodelist=nodes)
416
+
417
+ # Too few node labels
418
+ nodes = list(range(n - 1))
419
+ with pytest.raises(ValueError, match="nodelist must have the same length as A"):
420
+ nx.from_numpy_array(A, nodelist=nodes)
421
+
422
+
423
+ @pytest.mark.parametrize(
424
+ "nodes",
425
+ (
426
+ [4, 3, 2, 1, 0],
427
+ [9, 7, 1, 2, 8],
428
+ ["a", "b", "c", "d", "e"],
429
+ [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
430
+ ["A", 2, 7, "spam", (1, 3)],
431
+ ),
432
+ )
433
+ def test_from_numpy_array_nodelist(nodes):
434
+ A = np.diag(np.ones(4), k=1)
435
+ # Without edge attributes
436
+ expected = nx.relabel_nodes(
437
+ nx.path_graph(5), mapping=dict(enumerate(nodes)), copy=True
438
+ )
439
+ G = nx.from_numpy_array(A, edge_attr=None, nodelist=nodes)
440
+ assert graphs_equal(G, expected)
441
+
442
+ # With edge attributes
443
+ nx.set_edge_attributes(expected, 1.0, name="weight")
444
+ G = nx.from_numpy_array(A, nodelist=nodes)
445
+ assert graphs_equal(G, expected)
446
+
447
+
448
+ @pytest.mark.parametrize(
449
+ "nodes",
450
+ (
451
+ [4, 3, 2, 1, 0],
452
+ [9, 7, 1, 2, 8],
453
+ ["a", "b", "c", "d", "e"],
454
+ [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
455
+ ["A", 2, 7, "spam", (1, 3)],
456
+ ),
457
+ )
458
+ def test_from_numpy_array_nodelist_directed(nodes):
459
+ A = np.diag(np.ones(4), k=1)
460
+ # Without edge attributes
461
+ H = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4)])
462
+ expected = nx.relabel_nodes(H, mapping=dict(enumerate(nodes)), copy=True)
463
+ G = nx.from_numpy_array(A, create_using=nx.DiGraph, edge_attr=None, nodelist=nodes)
464
+ assert graphs_equal(G, expected)
465
+
466
+ # With edge attributes
467
+ nx.set_edge_attributes(expected, 1.0, name="weight")
468
+ G = nx.from_numpy_array(A, create_using=nx.DiGraph, nodelist=nodes)
469
+ assert graphs_equal(G, expected)
470
+
471
+
472
+ @pytest.mark.parametrize(
473
+ "nodes",
474
+ (
475
+ [4, 3, 2, 1, 0],
476
+ [9, 7, 1, 2, 8],
477
+ ["a", "b", "c", "d", "e"],
478
+ [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
479
+ ["A", 2, 7, "spam", (1, 3)],
480
+ ),
481
+ )
482
+ def test_from_numpy_array_nodelist_multigraph(nodes):
483
+ A = np.array(
484
+ [
485
+ [0, 1, 0, 0, 0],
486
+ [1, 0, 2, 0, 0],
487
+ [0, 2, 0, 3, 0],
488
+ [0, 0, 3, 0, 4],
489
+ [0, 0, 0, 4, 0],
490
+ ]
491
+ )
492
+
493
+ H = nx.MultiGraph()
494
+ for i, edge in enumerate(((0, 1), (1, 2), (2, 3), (3, 4))):
495
+ H.add_edges_from(itertools.repeat(edge, i + 1))
496
+ expected = nx.relabel_nodes(H, mapping=dict(enumerate(nodes)), copy=True)
497
+
498
+ G = nx.from_numpy_array(
499
+ A,
500
+ parallel_edges=True,
501
+ create_using=nx.MultiGraph,
502
+ edge_attr=None,
503
+ nodelist=nodes,
504
+ )
505
+ assert graphs_equal(G, expected)
506
+
507
+
508
+ @pytest.mark.parametrize(
509
+ "nodes",
510
+ (
511
+ [4, 3, 2, 1, 0],
512
+ [9, 7, 1, 2, 8],
513
+ ["a", "b", "c", "d", "e"],
514
+ [(0, 0), (1, 1), (2, 3), (0, 2), (3, 1)],
515
+ ["A", 2, 7, "spam", (1, 3)],
516
+ ),
517
+ )
518
+ @pytest.mark.parametrize("graph", (nx.complete_graph, nx.cycle_graph, nx.wheel_graph))
519
+ def test_from_numpy_array_nodelist_rountrip(graph, nodes):
520
+ G = graph(5)
521
+ A = nx.to_numpy_array(G)
522
+ expected = nx.relabel_nodes(G, mapping=dict(enumerate(nodes)), copy=True)
523
+ H = nx.from_numpy_array(A, edge_attr=None, nodelist=nodes)
524
+ assert graphs_equal(H, expected)
525
+
526
+ # With an isolated node
527
+ G = graph(4)
528
+ G.add_node("foo")
529
+ A = nx.to_numpy_array(G)
530
+ expected = nx.relabel_nodes(G, mapping=dict(zip(G.nodes, nodes)), copy=True)
531
+ H = nx.from_numpy_array(A, edge_attr=None, nodelist=nodes)
532
+ assert graphs_equal(H, expected)
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_convert_pandas.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
5
+
6
+ np = pytest.importorskip("numpy")
7
+ pd = pytest.importorskip("pandas")
8
+
9
+
10
+ class TestConvertPandas:
11
+ def setup_method(self):
12
+ self.rng = np.random.RandomState(seed=5)
13
+ ints = self.rng.randint(1, 11, size=(3, 2))
14
+ a = ["A", "B", "C"]
15
+ b = ["D", "A", "E"]
16
+ df = pd.DataFrame(ints, columns=["weight", "cost"])
17
+ df[0] = a # Column label 0 (int)
18
+ df["b"] = b # Column label 'b' (str)
19
+ self.df = df
20
+
21
+ mdf = pd.DataFrame([[4, 16, "A", "D"]], columns=["weight", "cost", 0, "b"])
22
+ self.mdf = pd.concat([df, mdf])
23
+
24
+ def test_exceptions(self):
25
+ G = pd.DataFrame(["a"]) # adj
26
+ pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G)
27
+ G = pd.DataFrame(["a", 0.0]) # elist
28
+ pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G)
29
+ df = pd.DataFrame([[1, 1], [1, 0]], dtype=int, index=[1, 2], columns=["a", "b"])
30
+ pytest.raises(nx.NetworkXError, nx.from_pandas_adjacency, df)
31
+
32
+ def test_from_edgelist_all_attr(self):
33
+ Gtrue = nx.Graph(
34
+ [
35
+ ("E", "C", {"cost": 9, "weight": 10}),
36
+ ("B", "A", {"cost": 1, "weight": 7}),
37
+ ("A", "D", {"cost": 7, "weight": 4}),
38
+ ]
39
+ )
40
+ G = nx.from_pandas_edgelist(self.df, 0, "b", True)
41
+ assert graphs_equal(G, Gtrue)
42
+ # MultiGraph
43
+ MGtrue = nx.MultiGraph(Gtrue)
44
+ MGtrue.add_edge("A", "D", cost=16, weight=4)
45
+ MG = nx.from_pandas_edgelist(self.mdf, 0, "b", True, nx.MultiGraph())
46
+ assert graphs_equal(MG, MGtrue)
47
+
48
+ def test_from_edgelist_multi_attr(self):
49
+ Gtrue = nx.Graph(
50
+ [
51
+ ("E", "C", {"cost": 9, "weight": 10}),
52
+ ("B", "A", {"cost": 1, "weight": 7}),
53
+ ("A", "D", {"cost": 7, "weight": 4}),
54
+ ]
55
+ )
56
+ G = nx.from_pandas_edgelist(self.df, 0, "b", ["weight", "cost"])
57
+ assert graphs_equal(G, Gtrue)
58
+
59
+ def test_from_edgelist_multi_attr_incl_target(self):
60
+ Gtrue = nx.Graph(
61
+ [
62
+ ("E", "C", {0: "C", "b": "E", "weight": 10}),
63
+ ("B", "A", {0: "B", "b": "A", "weight": 7}),
64
+ ("A", "D", {0: "A", "b": "D", "weight": 4}),
65
+ ]
66
+ )
67
+ G = nx.from_pandas_edgelist(self.df, 0, "b", [0, "b", "weight"])
68
+ assert graphs_equal(G, Gtrue)
69
+
70
+ def test_from_edgelist_multidigraph_and_edge_attr(self):
71
+ # example from issue #2374
72
+ edges = [
73
+ ("X1", "X4", {"Co": "zA", "Mi": 0, "St": "X1"}),
74
+ ("X1", "X4", {"Co": "zB", "Mi": 54, "St": "X2"}),
75
+ ("X1", "X4", {"Co": "zB", "Mi": 49, "St": "X3"}),
76
+ ("X1", "X4", {"Co": "zB", "Mi": 44, "St": "X4"}),
77
+ ("Y1", "Y3", {"Co": "zC", "Mi": 0, "St": "Y1"}),
78
+ ("Y1", "Y3", {"Co": "zC", "Mi": 34, "St": "Y2"}),
79
+ ("Y1", "Y3", {"Co": "zC", "Mi": 29, "St": "X2"}),
80
+ ("Y1", "Y3", {"Co": "zC", "Mi": 24, "St": "Y3"}),
81
+ ("Z1", "Z3", {"Co": "zD", "Mi": 0, "St": "Z1"}),
82
+ ("Z1", "Z3", {"Co": "zD", "Mi": 14, "St": "X3"}),
83
+ ]
84
+ Gtrue = nx.MultiDiGraph(edges)
85
+ data = {
86
+ "O": ["X1", "X1", "X1", "X1", "Y1", "Y1", "Y1", "Y1", "Z1", "Z1"],
87
+ "D": ["X4", "X4", "X4", "X4", "Y3", "Y3", "Y3", "Y3", "Z3", "Z3"],
88
+ "St": ["X1", "X2", "X3", "X4", "Y1", "Y2", "X2", "Y3", "Z1", "X3"],
89
+ "Co": ["zA", "zB", "zB", "zB", "zC", "zC", "zC", "zC", "zD", "zD"],
90
+ "Mi": [0, 54, 49, 44, 0, 34, 29, 24, 0, 14],
91
+ }
92
+ df = pd.DataFrame.from_dict(data)
93
+ G1 = nx.from_pandas_edgelist(
94
+ df, source="O", target="D", edge_attr=True, create_using=nx.MultiDiGraph
95
+ )
96
+ G2 = nx.from_pandas_edgelist(
97
+ df,
98
+ source="O",
99
+ target="D",
100
+ edge_attr=["St", "Co", "Mi"],
101
+ create_using=nx.MultiDiGraph,
102
+ )
103
+ assert graphs_equal(G1, Gtrue)
104
+ assert graphs_equal(G2, Gtrue)
105
+
106
+ def test_from_edgelist_one_attr(self):
107
+ Gtrue = nx.Graph(
108
+ [
109
+ ("E", "C", {"weight": 10}),
110
+ ("B", "A", {"weight": 7}),
111
+ ("A", "D", {"weight": 4}),
112
+ ]
113
+ )
114
+ G = nx.from_pandas_edgelist(self.df, 0, "b", "weight")
115
+ assert graphs_equal(G, Gtrue)
116
+
117
+ def test_from_edgelist_int_attr_name(self):
118
+ # note: this also tests that edge_attr can be `source`
119
+ Gtrue = nx.Graph(
120
+ [("E", "C", {0: "C"}), ("B", "A", {0: "B"}), ("A", "D", {0: "A"})]
121
+ )
122
+ G = nx.from_pandas_edgelist(self.df, 0, "b", 0)
123
+ assert graphs_equal(G, Gtrue)
124
+
125
+ def test_from_edgelist_invalid_attr(self):
126
+ pytest.raises(
127
+ nx.NetworkXError, nx.from_pandas_edgelist, self.df, 0, "b", "misspell"
128
+ )
129
+ pytest.raises(nx.NetworkXError, nx.from_pandas_edgelist, self.df, 0, "b", 1)
130
+ # see Issue #3562
131
+ edgeframe = pd.DataFrame([[0, 1], [1, 2], [2, 0]], columns=["s", "t"])
132
+ pytest.raises(
133
+ nx.NetworkXError, nx.from_pandas_edgelist, edgeframe, "s", "t", True
134
+ )
135
+ pytest.raises(
136
+ nx.NetworkXError, nx.from_pandas_edgelist, edgeframe, "s", "t", "weight"
137
+ )
138
+ pytest.raises(
139
+ nx.NetworkXError,
140
+ nx.from_pandas_edgelist,
141
+ edgeframe,
142
+ "s",
143
+ "t",
144
+ ["weight", "size"],
145
+ )
146
+
147
+ def test_from_edgelist_no_attr(self):
148
+ Gtrue = nx.Graph([("E", "C", {}), ("B", "A", {}), ("A", "D", {})])
149
+ G = nx.from_pandas_edgelist(self.df, 0, "b")
150
+ assert graphs_equal(G, Gtrue)
151
+
152
+ def test_from_edgelist(self):
153
+ # Pandas DataFrame
154
+ G = nx.cycle_graph(10)
155
+ G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges))
156
+
157
+ edgelist = nx.to_edgelist(G)
158
+ source = [s for s, t, d in edgelist]
159
+ target = [t for s, t, d in edgelist]
160
+ weight = [d["weight"] for s, t, d in edgelist]
161
+ edges = pd.DataFrame({"source": source, "target": target, "weight": weight})
162
+
163
+ GG = nx.from_pandas_edgelist(edges, edge_attr="weight")
164
+ assert nodes_equal(G.nodes(), GG.nodes())
165
+ assert edges_equal(G.edges(), GG.edges())
166
+ GW = nx.to_networkx_graph(edges, create_using=nx.Graph)
167
+ assert nodes_equal(G.nodes(), GW.nodes())
168
+ assert edges_equal(G.edges(), GW.edges())
169
+
170
+ def test_to_edgelist_default_source_or_target_col_exists(self):
171
+ G = nx.path_graph(10)
172
+ G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges))
173
+ nx.set_edge_attributes(G, 0, name="source")
174
+ pytest.raises(nx.NetworkXError, nx.to_pandas_edgelist, G)
175
+
176
+ # drop source column to test an exception raised for the target column
177
+ for u, v, d in G.edges(data=True):
178
+ d.pop("source", None)
179
+
180
+ nx.set_edge_attributes(G, 0, name="target")
181
+ pytest.raises(nx.NetworkXError, nx.to_pandas_edgelist, G)
182
+
183
+ def test_to_edgelist_custom_source_or_target_col_exists(self):
184
+ G = nx.path_graph(10)
185
+ G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges))
186
+ nx.set_edge_attributes(G, 0, name="source_col_name")
187
+ pytest.raises(
188
+ nx.NetworkXError, nx.to_pandas_edgelist, G, source="source_col_name"
189
+ )
190
+
191
+ # drop source column to test an exception raised for the target column
192
+ for u, v, d in G.edges(data=True):
193
+ d.pop("source_col_name", None)
194
+
195
+ nx.set_edge_attributes(G, 0, name="target_col_name")
196
+ pytest.raises(
197
+ nx.NetworkXError, nx.to_pandas_edgelist, G, target="target_col_name"
198
+ )
199
+
200
+ def test_to_edgelist_edge_key_col_exists(self):
201
+ G = nx.path_graph(10, create_using=nx.MultiGraph)
202
+ G.add_weighted_edges_from((u, v, u) for u, v in list(G.edges()))
203
+ nx.set_edge_attributes(G, 0, name="edge_key_name")
204
+ pytest.raises(
205
+ nx.NetworkXError, nx.to_pandas_edgelist, G, edge_key="edge_key_name"
206
+ )
207
+
208
+ def test_from_adjacency(self):
209
+ nodelist = [1, 2]
210
+ dftrue = pd.DataFrame(
211
+ [[1, 1], [1, 0]], dtype=int, index=nodelist, columns=nodelist
212
+ )
213
+ G = nx.Graph([(1, 1), (1, 2)])
214
+ df = nx.to_pandas_adjacency(G, dtype=int)
215
+ pd.testing.assert_frame_equal(df, dftrue)
216
+
217
+ @pytest.mark.parametrize("graph", [nx.Graph, nx.MultiGraph])
218
+ def test_roundtrip(self, graph):
219
+ # edgelist
220
+ Gtrue = graph([(1, 1), (1, 2)])
221
+ df = nx.to_pandas_edgelist(Gtrue)
222
+ G = nx.from_pandas_edgelist(df, create_using=graph)
223
+ assert graphs_equal(Gtrue, G)
224
+ # adjacency
225
+ adj = {1: {1: {"weight": 1}, 2: {"weight": 1}}, 2: {1: {"weight": 1}}}
226
+ Gtrue = graph(adj)
227
+ df = nx.to_pandas_adjacency(Gtrue, dtype=int)
228
+ G = nx.from_pandas_adjacency(df, create_using=graph)
229
+ assert graphs_equal(Gtrue, G)
230
+
231
+ def test_from_adjacency_named(self):
232
+ # example from issue #3105
233
+ data = {
234
+ "A": {"A": 0, "B": 0, "C": 0},
235
+ "B": {"A": 1, "B": 0, "C": 0},
236
+ "C": {"A": 0, "B": 1, "C": 0},
237
+ }
238
+ dftrue = pd.DataFrame(data, dtype=np.intp)
239
+ df = dftrue[["A", "C", "B"]]
240
+ G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph())
241
+ df = nx.to_pandas_adjacency(G, dtype=np.intp)
242
+ pd.testing.assert_frame_equal(df, dftrue)
243
+
244
+ @pytest.mark.parametrize("edge_attr", [["attr2", "attr3"], True])
245
+ def test_edgekey_with_multigraph(self, edge_attr):
246
+ df = pd.DataFrame(
247
+ {
248
+ "source": {"A": "N1", "B": "N2", "C": "N1", "D": "N1"},
249
+ "target": {"A": "N2", "B": "N3", "C": "N1", "D": "N2"},
250
+ "attr1": {"A": "F1", "B": "F2", "C": "F3", "D": "F4"},
251
+ "attr2": {"A": 1, "B": 0, "C": 0, "D": 0},
252
+ "attr3": {"A": 0, "B": 1, "C": 0, "D": 1},
253
+ }
254
+ )
255
+ Gtrue = nx.MultiGraph(
256
+ [
257
+ ("N1", "N2", "F1", {"attr2": 1, "attr3": 0}),
258
+ ("N2", "N3", "F2", {"attr2": 0, "attr3": 1}),
259
+ ("N1", "N1", "F3", {"attr2": 0, "attr3": 0}),
260
+ ("N1", "N2", "F4", {"attr2": 0, "attr3": 1}),
261
+ ]
262
+ )
263
+ # example from issue #4065
264
+ G = nx.from_pandas_edgelist(
265
+ df,
266
+ source="source",
267
+ target="target",
268
+ edge_attr=edge_attr,
269
+ edge_key="attr1",
270
+ create_using=nx.MultiGraph(),
271
+ )
272
+ assert graphs_equal(G, Gtrue)
273
+
274
+ df_roundtrip = nx.to_pandas_edgelist(G, edge_key="attr1")
275
+ df_roundtrip = df_roundtrip.sort_values("attr1")
276
+ df_roundtrip.index = ["A", "B", "C", "D"]
277
+ pd.testing.assert_frame_equal(
278
+ df, df_roundtrip[["source", "target", "attr1", "attr2", "attr3"]]
279
+ )
280
+
281
+ def test_edgekey_with_normal_graph_no_action(self):
282
+ Gtrue = nx.Graph(
283
+ [
284
+ ("E", "C", {"cost": 9, "weight": 10}),
285
+ ("B", "A", {"cost": 1, "weight": 7}),
286
+ ("A", "D", {"cost": 7, "weight": 4}),
287
+ ]
288
+ )
289
+ G = nx.from_pandas_edgelist(self.df, 0, "b", True, edge_key="weight")
290
+ assert graphs_equal(G, Gtrue)
291
+
292
+ def test_nonexisting_edgekey_raises(self):
293
+ with pytest.raises(nx.exception.NetworkXError):
294
+ nx.from_pandas_edgelist(
295
+ self.df,
296
+ source="source",
297
+ target="target",
298
+ edge_key="Not_real",
299
+ edge_attr=True,
300
+ create_using=nx.MultiGraph(),
301
+ )
302
+
303
+ def test_multigraph_with_edgekey_no_edgeattrs(self):
304
+ Gtrue = nx.MultiGraph()
305
+ Gtrue.add_edge(0, 1, key=0)
306
+ Gtrue.add_edge(0, 1, key=3)
307
+ df = nx.to_pandas_edgelist(Gtrue, edge_key="key")
308
+ expected = pd.DataFrame({"source": [0, 0], "target": [1, 1], "key": [0, 3]})
309
+ pd.testing.assert_frame_equal(expected, df)
310
+ G = nx.from_pandas_edgelist(df, edge_key="key", create_using=nx.MultiGraph)
311
+ assert graphs_equal(Gtrue, G)
312
+
313
+
314
+ def test_to_pandas_adjacency_with_nodelist():
315
+ G = nx.complete_graph(5)
316
+ nodelist = [1, 4]
317
+ expected = pd.DataFrame(
318
+ [[0, 1], [1, 0]], dtype=int, index=nodelist, columns=nodelist
319
+ )
320
+ pd.testing.assert_frame_equal(
321
+ expected, nx.to_pandas_adjacency(G, nodelist, dtype=int)
322
+ )
323
+
324
+
325
+ def test_to_pandas_edgelist_with_nodelist():
326
+ G = nx.Graph()
327
+ G.add_edges_from([(0, 1), (1, 2), (1, 3)], weight=2.0)
328
+ G.add_edge(0, 5, weight=100)
329
+ df = nx.to_pandas_edgelist(G, nodelist=[1, 2])
330
+ assert 0 not in df["source"].to_numpy()
331
+ assert 100 not in df["weight"].to_numpy()
332
+
333
+
334
+ def test_from_pandas_adjacency_with_index_collisions():
335
+ """See gh-7407"""
336
+ df = pd.DataFrame(
337
+ [
338
+ [0, 1, 0, 0],
339
+ [0, 0, 1, 0],
340
+ [0, 0, 0, 1],
341
+ [0, 0, 0, 0],
342
+ ],
343
+ index=[1010001, 2, 1, 1010002],
344
+ columns=[1010001, 2, 1, 1010002],
345
+ )
346
+ G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph)
347
+ expected = nx.DiGraph([(1010001, 2), (2, 1), (1, 1010002)])
348
+ assert nodes_equal(G.nodes, expected.nodes)
349
+ assert edges_equal(G.edges, expected.edges)
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_convert_scipy.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ np = pytest.importorskip("numpy")
4
+ sp = pytest.importorskip("scipy")
5
+
6
+ import networkx as nx
7
+ from networkx.generators.classic import barbell_graph, cycle_graph, path_graph
8
+ from networkx.utils import graphs_equal
9
+
10
+
11
+ class TestConvertScipy:
12
+ def setup_method(self):
13
+ self.G1 = barbell_graph(10, 3)
14
+ self.G2 = cycle_graph(10, create_using=nx.DiGraph)
15
+
16
+ self.G3 = self.create_weighted(nx.Graph())
17
+ self.G4 = self.create_weighted(nx.DiGraph())
18
+
19
+ def test_exceptions(self):
20
+ class G:
21
+ format = None
22
+
23
+ pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G)
24
+
25
+ def create_weighted(self, G):
26
+ g = cycle_graph(4)
27
+ e = list(g.edges())
28
+ source = [u for u, v in e]
29
+ dest = [v for u, v in e]
30
+ weight = [s + 10 for s in source]
31
+ ex = zip(source, dest, weight)
32
+ G.add_weighted_edges_from(ex)
33
+ return G
34
+
35
+ def identity_conversion(self, G, A, create_using):
36
+ GG = nx.from_scipy_sparse_array(A, create_using=create_using)
37
+ assert nx.is_isomorphic(G, GG)
38
+
39
+ GW = nx.to_networkx_graph(A, create_using=create_using)
40
+ assert nx.is_isomorphic(G, GW)
41
+
42
+ GI = nx.empty_graph(0, create_using).__class__(A)
43
+ assert nx.is_isomorphic(G, GI)
44
+
45
+ ACSR = A.tocsr()
46
+ GI = nx.empty_graph(0, create_using).__class__(ACSR)
47
+ assert nx.is_isomorphic(G, GI)
48
+
49
+ ACOO = A.tocoo()
50
+ GI = nx.empty_graph(0, create_using).__class__(ACOO)
51
+ assert nx.is_isomorphic(G, GI)
52
+
53
+ ACSC = A.tocsc()
54
+ GI = nx.empty_graph(0, create_using).__class__(ACSC)
55
+ assert nx.is_isomorphic(G, GI)
56
+
57
+ AD = A.todense()
58
+ GI = nx.empty_graph(0, create_using).__class__(AD)
59
+ assert nx.is_isomorphic(G, GI)
60
+
61
+ AA = A.toarray()
62
+ GI = nx.empty_graph(0, create_using).__class__(AA)
63
+ assert nx.is_isomorphic(G, GI)
64
+
65
+ def test_shape(self):
66
+ "Conversion from non-square sparse array."
67
+ A = sp.sparse.lil_array([[1, 2, 3], [4, 5, 6]])
68
+ pytest.raises(nx.NetworkXError, nx.from_scipy_sparse_array, A)
69
+
70
+ def test_identity_graph_matrix(self):
71
+ "Conversion from graph to sparse matrix to graph."
72
+ A = nx.to_scipy_sparse_array(self.G1)
73
+ self.identity_conversion(self.G1, A, nx.Graph())
74
+
75
+ def test_identity_digraph_matrix(self):
76
+ "Conversion from digraph to sparse matrix to digraph."
77
+ A = nx.to_scipy_sparse_array(self.G2)
78
+ self.identity_conversion(self.G2, A, nx.DiGraph())
79
+
80
+ def test_identity_weighted_graph_matrix(self):
81
+ """Conversion from weighted graph to sparse matrix to weighted graph."""
82
+ A = nx.to_scipy_sparse_array(self.G3)
83
+ self.identity_conversion(self.G3, A, nx.Graph())
84
+
85
+ def test_identity_weighted_digraph_matrix(self):
86
+ """Conversion from weighted digraph to sparse matrix to weighted digraph."""
87
+ A = nx.to_scipy_sparse_array(self.G4)
88
+ self.identity_conversion(self.G4, A, nx.DiGraph())
89
+
90
+ def test_nodelist(self):
91
+ """Conversion from graph to sparse matrix to graph with nodelist."""
92
+ P4 = path_graph(4)
93
+ P3 = path_graph(3)
94
+ nodelist = list(P3.nodes())
95
+ A = nx.to_scipy_sparse_array(P4, nodelist=nodelist)
96
+ GA = nx.Graph(A)
97
+ assert nx.is_isomorphic(GA, P3)
98
+
99
+ pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=[])
100
+ # Test nodelist duplicates.
101
+ long_nl = nodelist + [0]
102
+ pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=long_nl)
103
+
104
+ # Test nodelist contains non-nodes
105
+ non_nl = [-1, 0, 1, 2]
106
+ pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=non_nl)
107
+
108
+ def test_weight_keyword(self):
109
+ WP4 = nx.Graph()
110
+ WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
111
+ P4 = path_graph(4)
112
+ A = nx.to_scipy_sparse_array(P4)
113
+ np.testing.assert_equal(
114
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
115
+ )
116
+ np.testing.assert_equal(
117
+ 0.5 * A.todense(), nx.to_scipy_sparse_array(WP4).todense()
118
+ )
119
+ np.testing.assert_equal(
120
+ 0.3 * A.todense(), nx.to_scipy_sparse_array(WP4, weight="other").todense()
121
+ )
122
+
123
+ def test_format_keyword(self):
124
+ WP4 = nx.Graph()
125
+ WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
126
+ P4 = path_graph(4)
127
+ A = nx.to_scipy_sparse_array(P4, format="csr")
128
+ np.testing.assert_equal(
129
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
130
+ )
131
+
132
+ A = nx.to_scipy_sparse_array(P4, format="csc")
133
+ np.testing.assert_equal(
134
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
135
+ )
136
+
137
+ A = nx.to_scipy_sparse_array(P4, format="coo")
138
+ np.testing.assert_equal(
139
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
140
+ )
141
+
142
+ A = nx.to_scipy_sparse_array(P4, format="bsr")
143
+ np.testing.assert_equal(
144
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
145
+ )
146
+
147
+ A = nx.to_scipy_sparse_array(P4, format="lil")
148
+ np.testing.assert_equal(
149
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
150
+ )
151
+
152
+ A = nx.to_scipy_sparse_array(P4, format="dia")
153
+ np.testing.assert_equal(
154
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
155
+ )
156
+
157
+ A = nx.to_scipy_sparse_array(P4, format="dok")
158
+ np.testing.assert_equal(
159
+ A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
160
+ )
161
+
162
+ def test_format_keyword_raise(self):
163
+ with pytest.raises(nx.NetworkXError):
164
+ WP4 = nx.Graph()
165
+ WP4.add_edges_from(
166
+ (n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3)
167
+ )
168
+ P4 = path_graph(4)
169
+ nx.to_scipy_sparse_array(P4, format="any_other")
170
+
171
+ def test_null_raise(self):
172
+ with pytest.raises(nx.NetworkXError):
173
+ nx.to_scipy_sparse_array(nx.Graph())
174
+
175
+ def test_empty(self):
176
+ G = nx.Graph()
177
+ G.add_node(1)
178
+ M = nx.to_scipy_sparse_array(G)
179
+ np.testing.assert_equal(M.toarray(), np.array([[0]]))
180
+
181
+ def test_ordering(self):
182
+ G = nx.DiGraph()
183
+ G.add_edge(1, 2)
184
+ G.add_edge(2, 3)
185
+ G.add_edge(3, 1)
186
+ M = nx.to_scipy_sparse_array(G, nodelist=[3, 2, 1])
187
+ np.testing.assert_equal(
188
+ M.toarray(), np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
189
+ )
190
+
191
+ def test_selfloop_graph(self):
192
+ G = nx.Graph([(1, 1)])
193
+ M = nx.to_scipy_sparse_array(G)
194
+ np.testing.assert_equal(M.toarray(), np.array([[1]]))
195
+
196
+ G.add_edges_from([(2, 3), (3, 4)])
197
+ M = nx.to_scipy_sparse_array(G, nodelist=[2, 3, 4])
198
+ np.testing.assert_equal(
199
+ M.toarray(), np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
200
+ )
201
+
202
+ def test_selfloop_digraph(self):
203
+ G = nx.DiGraph([(1, 1)])
204
+ M = nx.to_scipy_sparse_array(G)
205
+ np.testing.assert_equal(M.toarray(), np.array([[1]]))
206
+
207
+ G.add_edges_from([(2, 3), (3, 4)])
208
+ M = nx.to_scipy_sparse_array(G, nodelist=[2, 3, 4])
209
+ np.testing.assert_equal(
210
+ M.toarray(), np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
211
+ )
212
+
213
+ def test_from_scipy_sparse_array_parallel_edges(self):
214
+ """Tests that the :func:`networkx.from_scipy_sparse_array` function
215
+ interprets integer weights as the number of parallel edges when
216
+ creating a multigraph.
217
+
218
+ """
219
+ A = sp.sparse.csr_array([[1, 1], [1, 2]])
220
+ # First, with a simple graph, each integer entry in the adjacency
221
+ # matrix is interpreted as the weight of a single edge in the graph.
222
+ expected = nx.DiGraph()
223
+ edges = [(0, 0), (0, 1), (1, 0)]
224
+ expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
225
+ expected.add_edge(1, 1, weight=2)
226
+ actual = nx.from_scipy_sparse_array(
227
+ A, parallel_edges=True, create_using=nx.DiGraph
228
+ )
229
+ assert graphs_equal(actual, expected)
230
+ actual = nx.from_scipy_sparse_array(
231
+ A, parallel_edges=False, create_using=nx.DiGraph
232
+ )
233
+ assert graphs_equal(actual, expected)
234
+ # Now each integer entry in the adjacency matrix is interpreted as the
235
+ # number of parallel edges in the graph if the appropriate keyword
236
+ # argument is specified.
237
+ edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
238
+ expected = nx.MultiDiGraph()
239
+ expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
240
+ actual = nx.from_scipy_sparse_array(
241
+ A, parallel_edges=True, create_using=nx.MultiDiGraph
242
+ )
243
+ assert graphs_equal(actual, expected)
244
+ expected = nx.MultiDiGraph()
245
+ expected.add_edges_from(set(edges), weight=1)
246
+ # The sole self-loop (edge 0) on vertex 1 should have weight 2.
247
+ expected[1][1][0]["weight"] = 2
248
+ actual = nx.from_scipy_sparse_array(
249
+ A, parallel_edges=False, create_using=nx.MultiDiGraph
250
+ )
251
+ assert graphs_equal(actual, expected)
252
+
253
+ def test_symmetric(self):
254
+ """Tests that a symmetric matrix has edges added only once to an
255
+ undirected multigraph when using
256
+ :func:`networkx.from_scipy_sparse_array`.
257
+
258
+ """
259
+ A = sp.sparse.csr_array([[0, 1], [1, 0]])
260
+ G = nx.from_scipy_sparse_array(A, create_using=nx.MultiGraph)
261
+ expected = nx.MultiGraph()
262
+ expected.add_edge(0, 1, weight=1)
263
+ assert graphs_equal(G, expected)
264
+
265
+
266
+ @pytest.mark.parametrize("sparse_format", ("csr", "csc", "dok"))
267
+ def test_from_scipy_sparse_array_formats(sparse_format):
268
+ """Test all formats supported by _generate_weighted_edges."""
269
+ # trinode complete graph with non-uniform edge weights
270
+ expected = nx.Graph()
271
+ expected.add_edges_from(
272
+ [
273
+ (0, 1, {"weight": 3}),
274
+ (0, 2, {"weight": 2}),
275
+ (1, 0, {"weight": 3}),
276
+ (1, 2, {"weight": 1}),
277
+ (2, 0, {"weight": 2}),
278
+ (2, 1, {"weight": 1}),
279
+ ]
280
+ )
281
+ A = sp.sparse.coo_array([[0, 3, 2], [3, 0, 1], [2, 1, 0]]).asformat(sparse_format)
282
+ assert graphs_equal(expected, nx.from_scipy_sparse_array(A))
evalkit_tf446/lib/python3.10/site-packages/networkx/tests/test_import.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+
4
+ def test_namespace_alias():
5
+ with pytest.raises(ImportError):
6
+ from networkx import nx
7
+
8
+
9
+ def test_namespace_nesting():
10
+ with pytest.raises(ImportError):
11
+ from networkx import networkx
evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from networkx.utils.misc import *
2
+ from networkx.utils.decorators import *
3
+ from networkx.utils.random_sequence import *
4
+ from networkx.utils.union_find import *
5
+ from networkx.utils.rcm import *
6
+ from networkx.utils.heaps import *
7
+ from networkx.utils.configs import *
8
+ from networkx.utils.backends import *
evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (456 Bytes). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/backends.cpython-310.pyc ADDED
Binary file (68 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/configs.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/decorators.cpython-310.pyc ADDED
Binary file (39.5 kB). View file
 
evalkit_tf446/lib/python3.10/site-packages/networkx/utils/__pycache__/heaps.cpython-310.pyc ADDED
Binary file (8.64 kB). View file