classic.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. """Generators for some classic graphs.
  2. The typical graph builder function is called as follows:
  3. >>> G = nx.complete_graph(100)
  4. returning the complete graph on n nodes labeled 0, .., 99
  5. as a simple graph. Except for `empty_graph`, all the functions
  6. in this module return a Graph class (i.e. a simple, undirected graph).
  7. """
  8. import itertools
  9. import numbers
  10. import networkx as nx
  11. from networkx.classes import Graph
  12. from networkx.exception import NetworkXError
  13. from networkx.utils import nodes_or_number, pairwise
  14. __all__ = [
  15. "balanced_tree",
  16. "barbell_graph",
  17. "binomial_tree",
  18. "complete_graph",
  19. "complete_multipartite_graph",
  20. "circular_ladder_graph",
  21. "circulant_graph",
  22. "cycle_graph",
  23. "dorogovtsev_goltsev_mendes_graph",
  24. "empty_graph",
  25. "full_rary_tree",
  26. "ladder_graph",
  27. "lollipop_graph",
  28. "null_graph",
  29. "path_graph",
  30. "star_graph",
  31. "trivial_graph",
  32. "turan_graph",
  33. "wheel_graph",
  34. ]
  35. # -------------------------------------------------------------------
  36. # Some Classic Graphs
  37. # -------------------------------------------------------------------
  38. def _tree_edges(n, r):
  39. if n == 0:
  40. return
  41. # helper function for trees
  42. # yields edges in rooted tree at 0 with n nodes and branching ratio r
  43. nodes = iter(range(n))
  44. parents = [next(nodes)] # stack of max length r
  45. while parents:
  46. source = parents.pop(0)
  47. for i in range(r):
  48. try:
  49. target = next(nodes)
  50. parents.append(target)
  51. yield source, target
  52. except StopIteration:
  53. break
  54. def full_rary_tree(r, n, create_using=None):
  55. """Creates a full r-ary tree of `n` nodes.
  56. Sometimes called a k-ary, n-ary, or m-ary tree.
  57. "... all non-leaf nodes have exactly r children and all levels
  58. are full except for some rightmost position of the bottom level
  59. (if a leaf at the bottom level is missing, then so are all of the
  60. leaves to its right." [1]_
  61. Parameters
  62. ----------
  63. r : int
  64. branching factor of the tree
  65. n : int
  66. Number of nodes in the tree
  67. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  68. Graph type to create. If graph instance, then cleared before populated.
  69. Returns
  70. -------
  71. G : networkx Graph
  72. An r-ary tree with n nodes
  73. References
  74. ----------
  75. .. [1] An introduction to data structures and algorithms,
  76. James Andrew Storer, Birkhauser Boston 2001, (page 225).
  77. """
  78. G = empty_graph(n, create_using)
  79. G.add_edges_from(_tree_edges(n, r))
  80. return G
  81. def balanced_tree(r, h, create_using=None):
  82. """Returns the perfectly balanced `r`-ary tree of height `h`.
  83. Parameters
  84. ----------
  85. r : int
  86. Branching factor of the tree; each node will have `r`
  87. children.
  88. h : int
  89. Height of the tree.
  90. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  91. Graph type to create. If graph instance, then cleared before populated.
  92. Returns
  93. -------
  94. G : NetworkX graph
  95. A balanced `r`-ary tree of height `h`.
  96. Notes
  97. -----
  98. This is the rooted tree where all leaves are at distance `h` from
  99. the root. The root has degree `r` and all other internal nodes
  100. have degree `r + 1`.
  101. Node labels are integers, starting from zero.
  102. A balanced tree is also known as a *complete r-ary tree*.
  103. """
  104. # The number of nodes in the balanced tree is `1 + r + ... + r^h`,
  105. # which is computed by using the closed-form formula for a geometric
  106. # sum with ratio `r`. In the special case that `r` is 1, the number
  107. # of nodes is simply `h + 1` (since the tree is actually a path
  108. # graph).
  109. if r == 1:
  110. n = h + 1
  111. else:
  112. # This must be an integer if both `r` and `h` are integers. If
  113. # they are not, we force integer division anyway.
  114. n = (1 - r ** (h + 1)) // (1 - r)
  115. return full_rary_tree(r, n, create_using=create_using)
  116. def barbell_graph(m1, m2, create_using=None):
  117. """Returns the Barbell Graph: two complete graphs connected by a path.
  118. Parameters
  119. ----------
  120. m1 : int
  121. Size of the left and right barbells, must be greater than 2.
  122. m2 : int
  123. Length of the path connecting the barbells.
  124. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  125. Graph type to create. If graph instance, then cleared before populated.
  126. Only undirected Graphs are supported.
  127. Returns
  128. -------
  129. G : NetworkX graph
  130. A barbell graph.
  131. Notes
  132. -----
  133. Two identical complete graphs $K_{m1}$ form the left and right bells,
  134. and are connected by a path $P_{m2}$.
  135. The `2*m1+m2` nodes are numbered
  136. `0, ..., m1-1` for the left barbell,
  137. `m1, ..., m1+m2-1` for the path,
  138. and `m1+m2, ..., 2*m1+m2-1` for the right barbell.
  139. The 3 subgraphs are joined via the edges `(m1-1, m1)` and
  140. `(m1+m2-1, m1+m2)`. If `m2=0`, this is merely two complete
  141. graphs joined together.
  142. This graph is an extremal example in David Aldous
  143. and Jim Fill's e-text on Random Walks on Graphs.
  144. """
  145. if m1 < 2:
  146. raise NetworkXError("Invalid graph description, m1 should be >=2")
  147. if m2 < 0:
  148. raise NetworkXError("Invalid graph description, m2 should be >=0")
  149. # left barbell
  150. G = complete_graph(m1, create_using)
  151. if G.is_directed():
  152. raise NetworkXError("Directed Graph not supported")
  153. # connecting path
  154. G.add_nodes_from(range(m1, m1 + m2 - 1))
  155. if m2 > 1:
  156. G.add_edges_from(pairwise(range(m1, m1 + m2)))
  157. # right barbell
  158. G.add_edges_from(
  159. (u, v) for u in range(m1 + m2, 2 * m1 + m2) for v in range(u + 1, 2 * m1 + m2)
  160. )
  161. # connect it up
  162. G.add_edge(m1 - 1, m1)
  163. if m2 > 0:
  164. G.add_edge(m1 + m2 - 1, m1 + m2)
  165. return G
  166. def binomial_tree(n, create_using=None):
  167. """Returns the Binomial Tree of order n.
  168. The binomial tree of order 0 consists of a single node. A binomial tree of order k
  169. is defined recursively by linking two binomial trees of order k-1: the root of one is
  170. the leftmost child of the root of the other.
  171. Parameters
  172. ----------
  173. n : int
  174. Order of the binomial tree.
  175. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  176. Graph type to create. If graph instance, then cleared before populated.
  177. Returns
  178. -------
  179. G : NetworkX graph
  180. A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
  181. """
  182. G = nx.empty_graph(1, create_using)
  183. N = 1
  184. for i in range(n):
  185. # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
  186. edges = [(u + N, v + N) for (u, v) in G.edges()]
  187. G.add_edges_from(edges)
  188. G.add_edge(0, N)
  189. N *= 2
  190. return G
  191. @nodes_or_number(0)
  192. def complete_graph(n, create_using=None):
  193. """Return the complete graph `K_n` with n nodes.
  194. A complete graph on `n` nodes means that all pairs
  195. of distinct nodes have an edge connecting them.
  196. Parameters
  197. ----------
  198. n : int or iterable container of nodes
  199. If n is an integer, nodes are from range(n).
  200. If n is a container of nodes, those nodes appear in the graph.
  201. Warning: n is not checked for duplicates and if present the
  202. resulting graph may not be as desired. Make sure you have no duplicates.
  203. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  204. Graph type to create. If graph instance, then cleared before populated.
  205. Examples
  206. --------
  207. >>> G = nx.complete_graph(9)
  208. >>> len(G)
  209. 9
  210. >>> G.size()
  211. 36
  212. >>> G = nx.complete_graph(range(11, 14))
  213. >>> list(G.nodes())
  214. [11, 12, 13]
  215. >>> G = nx.complete_graph(4, nx.DiGraph())
  216. >>> G.is_directed()
  217. True
  218. """
  219. _, nodes = n
  220. G = empty_graph(nodes, create_using)
  221. if len(nodes) > 1:
  222. if G.is_directed():
  223. edges = itertools.permutations(nodes, 2)
  224. else:
  225. edges = itertools.combinations(nodes, 2)
  226. G.add_edges_from(edges)
  227. return G
  228. def circular_ladder_graph(n, create_using=None):
  229. """Returns the circular ladder graph $CL_n$ of length n.
  230. $CL_n$ consists of two concentric n-cycles in which
  231. each of the n pairs of concentric nodes are joined by an edge.
  232. Node labels are the integers 0 to n-1
  233. """
  234. G = ladder_graph(n, create_using)
  235. G.add_edge(0, n - 1)
  236. G.add_edge(n, 2 * n - 1)
  237. return G
  238. def circulant_graph(n, offsets, create_using=None):
  239. r"""Returns the circulant graph $Ci_n(x_1, x_2, ..., x_m)$ with $n$ nodes.
  240. The circulant graph $Ci_n(x_1, ..., x_m)$ consists of $n$ nodes $0, ..., n-1$
  241. such that node $i$ is connected to nodes $(i + x) \mod n$ and $(i - x) \mod n$
  242. for all $x$ in $x_1, ..., x_m$. Thus $Ci_n(1)$ is a cycle graph.
  243. Parameters
  244. ----------
  245. n : integer
  246. The number of nodes in the graph.
  247. offsets : list of integers
  248. A list of node offsets, $x_1$ up to $x_m$, as described above.
  249. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  250. Graph type to create. If graph instance, then cleared before populated.
  251. Returns
  252. -------
  253. NetworkX Graph of type create_using
  254. Examples
  255. --------
  256. Many well-known graph families are subfamilies of the circulant graphs;
  257. for example, to create the cycle graph on n points, we connect every
  258. node to nodes on either side (with offset plus or minus one). For n = 10,
  259. >>> G = nx.circulant_graph(10, [1])
  260. >>> edges = [
  261. ... (0, 9),
  262. ... (0, 1),
  263. ... (1, 2),
  264. ... (2, 3),
  265. ... (3, 4),
  266. ... (4, 5),
  267. ... (5, 6),
  268. ... (6, 7),
  269. ... (7, 8),
  270. ... (8, 9),
  271. ... ]
  272. ...
  273. >>> sorted(edges) == sorted(G.edges())
  274. True
  275. Similarly, we can create the complete graph
  276. on 5 points with the set of offsets [1, 2]:
  277. >>> G = nx.circulant_graph(5, [1, 2])
  278. >>> edges = [
  279. ... (0, 1),
  280. ... (0, 2),
  281. ... (0, 3),
  282. ... (0, 4),
  283. ... (1, 2),
  284. ... (1, 3),
  285. ... (1, 4),
  286. ... (2, 3),
  287. ... (2, 4),
  288. ... (3, 4),
  289. ... ]
  290. ...
  291. >>> sorted(edges) == sorted(G.edges())
  292. True
  293. """
  294. G = empty_graph(n, create_using)
  295. for i in range(n):
  296. for j in offsets:
  297. G.add_edge(i, (i - j) % n)
  298. G.add_edge(i, (i + j) % n)
  299. return G
  300. @nodes_or_number(0)
  301. def cycle_graph(n, create_using=None):
  302. """Returns the cycle graph $C_n$ of cyclically connected nodes.
  303. $C_n$ is a path with its two end-nodes connected.
  304. Parameters
  305. ----------
  306. n : int or iterable container of nodes
  307. If n is an integer, nodes are from `range(n)`.
  308. If n is a container of nodes, those nodes appear in the graph.
  309. Warning: n is not checked for duplicates and if present the
  310. resulting graph may not be as desired. Make sure you have no duplicates.
  311. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  312. Graph type to create. If graph instance, then cleared before populated.
  313. Notes
  314. -----
  315. If create_using is directed, the direction is in increasing order.
  316. """
  317. _, nodes = n
  318. G = empty_graph(nodes, create_using)
  319. G.add_edges_from(pairwise(nodes, cyclic=True))
  320. return G
  321. def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
  322. """Returns the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.
  323. The Dorogovtsev-Goltsev-Mendes [1]_ procedure produces a scale-free graph
  324. deterministically with the following properties for a given `n`:
  325. - Total number of nodes = ``3 * (3**n + 1) / 2``
  326. - Total number of edges = ``3 ** (n + 1)``
  327. Parameters
  328. ----------
  329. n : integer
  330. The generation number.
  331. create_using : NetworkX Graph, optional
  332. Graph type to be returned. Directed graphs and multi graphs are not
  333. supported.
  334. Returns
  335. -------
  336. G : NetworkX Graph
  337. Examples
  338. --------
  339. >>> G = nx.dorogovtsev_goltsev_mendes_graph(3)
  340. >>> G.number_of_nodes()
  341. 15
  342. >>> G.number_of_edges()
  343. 27
  344. >>> nx.is_planar(G)
  345. True
  346. References
  347. ----------
  348. .. [1] Dorogotsev S.N., Goltsev A.V., and Mendes J.F.F "Pseudofractal
  349. Scale-free Web". arXiv:cond-mat/0112143
  350. """
  351. G = empty_graph(0, create_using)
  352. if G.is_directed():
  353. raise NetworkXError("Directed Graph not supported")
  354. if G.is_multigraph():
  355. raise NetworkXError("Multigraph not supported")
  356. G.add_edge(0, 1)
  357. if n == 0:
  358. return G
  359. new_node = 2 # next node to be added
  360. for i in range(1, n + 1): # iterate over number of generations.
  361. last_generation_edges = list(G.edges())
  362. number_of_edges_in_last_generation = len(last_generation_edges)
  363. for j in range(0, number_of_edges_in_last_generation):
  364. G.add_edge(new_node, last_generation_edges[j][0])
  365. G.add_edge(new_node, last_generation_edges[j][1])
  366. new_node += 1
  367. return G
  368. @nodes_or_number(0)
  369. def empty_graph(n=0, create_using=None, default=Graph):
  370. """Returns the empty graph with n nodes and zero edges.
  371. Parameters
  372. ----------
  373. n : int or iterable container of nodes (default = 0)
  374. If n is an integer, nodes are from `range(n)`.
  375. If n is a container of nodes, those nodes appear in the graph.
  376. create_using : Graph Instance, Constructor or None
  377. Indicator of type of graph to return.
  378. If a Graph-type instance, then clear and use it.
  379. If None, use the `default` constructor.
  380. If a constructor, call it to create an empty graph.
  381. default : Graph constructor (optional, default = nx.Graph)
  382. The constructor to use if create_using is None.
  383. If None, then nx.Graph is used.
  384. This is used when passing an unknown `create_using` value
  385. through your home-grown function to `empty_graph` and
  386. you want a default constructor other than nx.Graph.
  387. Examples
  388. --------
  389. >>> G = nx.empty_graph(10)
  390. >>> G.number_of_nodes()
  391. 10
  392. >>> G.number_of_edges()
  393. 0
  394. >>> G = nx.empty_graph("ABC")
  395. >>> G.number_of_nodes()
  396. 3
  397. >>> sorted(G)
  398. ['A', 'B', 'C']
  399. Notes
  400. -----
  401. The variable create_using should be a Graph Constructor or a
  402. "graph"-like object. Constructors, e.g. `nx.Graph` or `nx.MultiGraph`
  403. will be used to create the returned graph. "graph"-like objects
  404. will be cleared (nodes and edges will be removed) and refitted as
  405. an empty "graph" with nodes specified in n. This capability
  406. is useful for specifying the class-nature of the resulting empty
  407. "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
  408. The variable create_using has three main uses:
  409. Firstly, the variable create_using can be used to create an
  410. empty digraph, multigraph, etc. For example,
  411. >>> n = 10
  412. >>> G = nx.empty_graph(n, create_using=nx.DiGraph)
  413. will create an empty digraph on n nodes.
  414. Secondly, one can pass an existing graph (digraph, multigraph,
  415. etc.) via create_using. For example, if G is an existing graph
  416. (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
  417. will empty G (i.e. delete all nodes and edges using G.clear())
  418. and then add n nodes and zero edges, and return the modified graph.
  419. Thirdly, when constructing your home-grown graph creation function
  420. you can use empty_graph to construct the graph by passing a user
  421. defined create_using to empty_graph. In this case, if you want the
  422. default constructor to be other than nx.Graph, specify `default`.
  423. >>> def mygraph(n, create_using=None):
  424. ... G = nx.empty_graph(n, create_using, nx.MultiGraph)
  425. ... G.add_edges_from([(0, 1), (0, 1)])
  426. ... return G
  427. >>> G = mygraph(3)
  428. >>> G.is_multigraph()
  429. True
  430. >>> G = mygraph(3, nx.Graph)
  431. >>> G.is_multigraph()
  432. False
  433. See also create_empty_copy(G).
  434. """
  435. if create_using is None:
  436. G = default()
  437. elif isinstance(create_using, type):
  438. G = create_using()
  439. elif not hasattr(create_using, "adj"):
  440. raise TypeError("create_using is not a valid NetworkX graph type or instance")
  441. else:
  442. # create_using is a NetworkX style Graph
  443. create_using.clear()
  444. G = create_using
  445. _, nodes = n
  446. G.add_nodes_from(nodes)
  447. return G
  448. def ladder_graph(n, create_using=None):
  449. """Returns the Ladder graph of length n.
  450. This is two paths of n nodes, with
  451. each pair connected by a single edge.
  452. Node labels are the integers 0 to 2*n - 1.
  453. """
  454. G = empty_graph(2 * n, create_using)
  455. if G.is_directed():
  456. raise NetworkXError("Directed Graph not supported")
  457. G.add_edges_from(pairwise(range(n)))
  458. G.add_edges_from(pairwise(range(n, 2 * n)))
  459. G.add_edges_from((v, v + n) for v in range(n))
  460. return G
  461. @nodes_or_number([0, 1])
  462. def lollipop_graph(m, n, create_using=None):
  463. """Returns the Lollipop Graph; `K_m` connected to `P_n`.
  464. This is the Barbell Graph without the right barbell.
  465. Parameters
  466. ----------
  467. m, n : int or iterable container of nodes (default = 0)
  468. If an integer, nodes are from `range(m)` and `range(m,m+n)`.
  469. If a container of nodes, those nodes appear in the graph.
  470. Warning: m and n are not checked for duplicates and if present the
  471. resulting graph may not be as desired. Make sure you have no duplicates.
  472. The nodes for m appear in the complete graph $K_m$ and the nodes
  473. for n appear in the path $P_n$
  474. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  475. Graph type to create. If graph instance, then cleared before populated.
  476. Notes
  477. -----
  478. The 2 subgraphs are joined via an edge (m-1, m).
  479. If n=0, this is merely a complete graph.
  480. (This graph is an extremal example in David Aldous and Jim
  481. Fill's etext on Random Walks on Graphs.)
  482. """
  483. m, m_nodes = m
  484. M = len(m_nodes)
  485. if M < 2:
  486. raise NetworkXError("Invalid description: m should indicate at least 2 nodes")
  487. n, n_nodes = n
  488. if isinstance(m, numbers.Integral) and isinstance(n, numbers.Integral):
  489. n_nodes = list(range(M, M + n))
  490. N = len(n_nodes)
  491. # the ball
  492. G = complete_graph(m_nodes, create_using)
  493. if G.is_directed():
  494. raise NetworkXError("Directed Graph not supported")
  495. # the stick
  496. G.add_nodes_from(n_nodes)
  497. if N > 1:
  498. G.add_edges_from(pairwise(n_nodes))
  499. if len(G) != M + N:
  500. raise NetworkXError("Nodes must be distinct in containers m and n")
  501. # connect ball to stick
  502. if M > 0 and N > 0:
  503. G.add_edge(m_nodes[-1], n_nodes[0])
  504. return G
  505. def null_graph(create_using=None):
  506. """Returns the Null graph with no nodes or edges.
  507. See empty_graph for the use of create_using.
  508. """
  509. G = empty_graph(0, create_using)
  510. return G
  511. @nodes_or_number(0)
  512. def path_graph(n, create_using=None):
  513. """Returns the Path graph `P_n` of linearly connected nodes.
  514. Parameters
  515. ----------
  516. n : int or iterable
  517. If an integer, nodes are 0 to n - 1.
  518. If an iterable of nodes, in the order they appear in the path.
  519. Warning: n is not checked for duplicates and if present the
  520. resulting graph may not be as desired. Make sure you have no duplicates.
  521. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  522. Graph type to create. If graph instance, then cleared before populated.
  523. """
  524. _, nodes = n
  525. G = empty_graph(nodes, create_using)
  526. G.add_edges_from(pairwise(nodes))
  527. return G
  528. @nodes_or_number(0)
  529. def star_graph(n, create_using=None):
  530. """Return the star graph
  531. The star graph consists of one center node connected to n outer nodes.
  532. Parameters
  533. ----------
  534. n : int or iterable
  535. If an integer, node labels are 0 to n with center 0.
  536. If an iterable of nodes, the center is the first.
  537. Warning: n is not checked for duplicates and if present the
  538. resulting graph may not be as desired. Make sure you have no duplicates.
  539. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  540. Graph type to create. If graph instance, then cleared before populated.
  541. Notes
  542. -----
  543. The graph has n+1 nodes for integer n.
  544. So star_graph(3) is the same as star_graph(range(4)).
  545. """
  546. n, nodes = n
  547. if isinstance(n, numbers.Integral):
  548. nodes.append(n) # there should be n+1 nodes
  549. G = empty_graph(nodes, create_using)
  550. if G.is_directed():
  551. raise NetworkXError("Directed Graph not supported")
  552. if len(nodes) > 1:
  553. hub, *spokes = nodes
  554. G.add_edges_from((hub, node) for node in spokes)
  555. return G
  556. def trivial_graph(create_using=None):
  557. """Return the Trivial graph with one node (with label 0) and no edges."""
  558. G = empty_graph(1, create_using)
  559. return G
  560. def turan_graph(n, r):
  561. r"""Return the Turan Graph
  562. The Turan Graph is a complete multipartite graph on $n$ nodes
  563. with $r$ disjoint subsets. That is, edges connect each node to
  564. every node not in its subset.
  565. Given $n$ and $r$, we create a complete multipartite graph with
  566. $r-(n \mod r)$ partitions of size $n/r$, rounded down, and
  567. $n \mod r$ partitions of size $n/r+1$, rounded down.
  568. Parameters
  569. ----------
  570. n : int
  571. The number of nodes.
  572. r : int
  573. The number of partitions.
  574. Must be less than or equal to n.
  575. Notes
  576. -----
  577. Must satisfy $1 <= r <= n$.
  578. The graph has $(r-1)(n^2)/(2r)$ edges, rounded down.
  579. """
  580. if not 1 <= r <= n:
  581. raise NetworkXError("Must satisfy 1 <= r <= n")
  582. partitions = [n // r] * (r - (n % r)) + [n // r + 1] * (n % r)
  583. G = complete_multipartite_graph(*partitions)
  584. return G
  585. @nodes_or_number(0)
  586. def wheel_graph(n, create_using=None):
  587. """Return the wheel graph
  588. The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
  589. Parameters
  590. ----------
  591. n : int or iterable
  592. If an integer, node labels are 0 to n with center 0.
  593. If an iterable of nodes, the center is the first.
  594. Warning: n is not checked for duplicates and if present the
  595. resulting graph may not be as desired. Make sure you have no duplicates.
  596. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  597. Graph type to create. If graph instance, then cleared before populated.
  598. Node labels are the integers 0 to n - 1.
  599. """
  600. _, nodes = n
  601. G = empty_graph(nodes, create_using)
  602. if G.is_directed():
  603. raise NetworkXError("Directed Graph not supported")
  604. if len(nodes) > 1:
  605. hub, *rim = nodes
  606. G.add_edges_from((hub, node) for node in rim)
  607. if len(rim) > 1:
  608. G.add_edges_from(pairwise(rim, cyclic=True))
  609. return G
  610. def complete_multipartite_graph(*subset_sizes):
  611. """Returns the complete multipartite graph with the specified subset sizes.
  612. Parameters
  613. ----------
  614. subset_sizes : tuple of integers or tuple of node iterables
  615. The arguments can either all be integer number of nodes or they
  616. can all be iterables of nodes. If integers, they represent the
  617. number of nodes in each subset of the multipartite graph.
  618. If iterables, each is used to create the nodes for that subset.
  619. The length of subset_sizes is the number of subsets.
  620. Returns
  621. -------
  622. G : NetworkX Graph
  623. Returns the complete multipartite graph with the specified subsets.
  624. For each node, the node attribute 'subset' is an integer
  625. indicating which subset contains the node.
  626. Examples
  627. --------
  628. Creating a complete tripartite graph, with subsets of one, two, and three
  629. nodes, respectively.
  630. >>> G = nx.complete_multipartite_graph(1, 2, 3)
  631. >>> [G.nodes[u]["subset"] for u in G]
  632. [0, 1, 1, 2, 2, 2]
  633. >>> list(G.edges(0))
  634. [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
  635. >>> list(G.edges(2))
  636. [(2, 0), (2, 3), (2, 4), (2, 5)]
  637. >>> list(G.edges(4))
  638. [(4, 0), (4, 1), (4, 2)]
  639. >>> G = nx.complete_multipartite_graph("a", "bc", "def")
  640. >>> [G.nodes[u]["subset"] for u in sorted(G)]
  641. [0, 1, 1, 2, 2, 2]
  642. Notes
  643. -----
  644. This function generalizes several other graph builder functions.
  645. - If no subset sizes are given, this returns the null graph.
  646. - If a single subset size `n` is given, this returns the empty graph on
  647. `n` nodes.
  648. - If two subset sizes `m` and `n` are given, this returns the complete
  649. bipartite graph on `m + n` nodes.
  650. - If subset sizes `1` and `n` are given, this returns the star graph on
  651. `n + 1` nodes.
  652. See also
  653. --------
  654. complete_bipartite_graph
  655. """
  656. # The complete multipartite graph is an undirected simple graph.
  657. G = Graph()
  658. if len(subset_sizes) == 0:
  659. return G
  660. # set up subsets of nodes
  661. try:
  662. extents = pairwise(itertools.accumulate((0,) + subset_sizes))
  663. subsets = [range(start, end) for start, end in extents]
  664. except TypeError:
  665. subsets = subset_sizes
  666. # add nodes with subset attribute
  667. # while checking that ints are not mixed with iterables
  668. try:
  669. for i, subset in enumerate(subsets):
  670. G.add_nodes_from(subset, subset=i)
  671. except TypeError as err:
  672. raise NetworkXError("Arguments must be all ints or all iterables") from err
  673. # Across subsets, all nodes should be adjacent.
  674. # We can use itertools.combinations() because undirected.
  675. for subset1, subset2 in itertools.combinations(subsets, 2):
  676. G.add_edges_from(itertools.product(subset1, subset2))
  677. return G