mst.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. """
  2. Algorithms for calculating min/max spanning trees/forests.
  3. """
  4. from dataclasses import dataclass, field
  5. from enum import Enum
  6. from heapq import heappop, heappush
  7. from itertools import count
  8. from math import isnan
  9. from operator import itemgetter
  10. from queue import PriorityQueue
  11. import networkx as nx
  12. from networkx.utils import UnionFind, not_implemented_for, py_random_state
  13. __all__ = [
  14. "minimum_spanning_edges",
  15. "maximum_spanning_edges",
  16. "minimum_spanning_tree",
  17. "maximum_spanning_tree",
  18. "number_of_spanning_trees",
  19. "random_spanning_tree",
  20. "partition_spanning_tree",
  21. "EdgePartition",
  22. "SpanningTreeIterator",
  23. ]
  24. class EdgePartition(Enum):
  25. """
  26. An enum to store the state of an edge partition. The enum is written to the
  27. edges of a graph before being pasted to `kruskal_mst_edges`. Options are:
  28. - EdgePartition.OPEN
  29. - EdgePartition.INCLUDED
  30. - EdgePartition.EXCLUDED
  31. """
  32. OPEN = 0
  33. INCLUDED = 1
  34. EXCLUDED = 2
  35. @not_implemented_for("multigraph")
  36. @nx._dispatchable(edge_attrs="weight", preserve_edge_attrs="data")
  37. def boruvka_mst_edges(
  38. G, minimum=True, weight="weight", keys=False, data=True, ignore_nan=False
  39. ):
  40. """Iterate over edges of a Borůvka's algorithm min/max spanning tree.
  41. Parameters
  42. ----------
  43. G : NetworkX Graph
  44. The edges of `G` must have distinct weights,
  45. otherwise the edges may not form a tree.
  46. minimum : bool (default: True)
  47. Find the minimum (True) or maximum (False) spanning tree.
  48. weight : string (default: 'weight')
  49. The name of the edge attribute holding the edge weights.
  50. keys : bool (default: True)
  51. This argument is ignored since this function is not
  52. implemented for multigraphs; it exists only for consistency
  53. with the other minimum spanning tree functions.
  54. data : bool (default: True)
  55. Flag for whether to yield edge attribute dicts.
  56. If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
  57. If False, yield edges `(u, v)`.
  58. ignore_nan : bool (default: False)
  59. If a NaN is found as an edge weight normally an exception is raised.
  60. If `ignore_nan is True` then that edge is ignored instead.
  61. """
  62. # Initialize a forest, assuming initially that it is the discrete
  63. # partition of the nodes of the graph.
  64. forest = UnionFind(G)
  65. def best_edge(component):
  66. """Returns the optimum (minimum or maximum) edge on the edge
  67. boundary of the given set of nodes.
  68. A return value of ``None`` indicates an empty boundary.
  69. """
  70. sign = 1 if minimum else -1
  71. minwt = float("inf")
  72. boundary = None
  73. for e in nx.edge_boundary(G, component, data=True):
  74. wt = e[-1].get(weight, 1) * sign
  75. if isnan(wt):
  76. if ignore_nan:
  77. continue
  78. msg = f"NaN found as an edge weight. Edge {e}"
  79. raise ValueError(msg)
  80. if wt < minwt:
  81. minwt = wt
  82. boundary = e
  83. return boundary
  84. # Determine the optimum edge in the edge boundary of each component
  85. # in the forest.
  86. best_edges = (best_edge(component) for component in forest.to_sets())
  87. best_edges = [edge for edge in best_edges if edge is not None]
  88. # If each entry was ``None``, that means the graph was disconnected,
  89. # so we are done generating the forest.
  90. while best_edges:
  91. # Determine the optimum edge in the edge boundary of each
  92. # component in the forest.
  93. #
  94. # This must be a sequence, not an iterator. In this list, the
  95. # same edge may appear twice, in different orientations (but
  96. # that's okay, since a union operation will be called on the
  97. # endpoints the first time it is seen, but not the second time).
  98. #
  99. # Any ``None`` indicates that the edge boundary for that
  100. # component was empty, so that part of the forest has been
  101. # completed.
  102. #
  103. # TODO This can be parallelized, both in the outer loop over
  104. # each component in the forest and in the computation of the
  105. # minimum. (Same goes for the identical lines outside the loop.)
  106. best_edges = (best_edge(component) for component in forest.to_sets())
  107. best_edges = [edge for edge in best_edges if edge is not None]
  108. # Join trees in the forest using the best edges, and yield that
  109. # edge, since it is part of the spanning tree.
  110. #
  111. # TODO This loop can be parallelized, to an extent (the union
  112. # operation must be atomic).
  113. for u, v, d in best_edges:
  114. if forest[u] != forest[v]:
  115. if data:
  116. yield u, v, d
  117. else:
  118. yield u, v
  119. forest.union(u, v)
  120. @nx._dispatchable(
  121. edge_attrs={"weight": None, "partition": None}, preserve_edge_attrs="data"
  122. )
  123. def kruskal_mst_edges(
  124. G, minimum, weight="weight", keys=True, data=True, ignore_nan=False, partition=None
  125. ):
  126. """
  127. Iterate over edge of a Kruskal's algorithm min/max spanning tree.
  128. Parameters
  129. ----------
  130. G : NetworkX Graph
  131. The graph holding the tree of interest.
  132. minimum : bool (default: True)
  133. Find the minimum (True) or maximum (False) spanning tree.
  134. weight : string (default: 'weight')
  135. The name of the edge attribute holding the edge weights.
  136. keys : bool (default: True)
  137. If `G` is a multigraph, `keys` controls whether edge keys ar yielded.
  138. Otherwise `keys` is ignored.
  139. data : bool (default: True)
  140. Flag for whether to yield edge attribute dicts.
  141. If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
  142. If False, yield edges `(u, v)`.
  143. ignore_nan : bool (default: False)
  144. If a NaN is found as an edge weight normally an exception is raised.
  145. If `ignore_nan is True` then that edge is ignored instead.
  146. partition : string (default: None)
  147. The name of the edge attribute holding the partition data, if it exists.
  148. Partition data is written to the edges using the `EdgePartition` enum.
  149. If a partition exists, all included edges and none of the excluded edges
  150. will appear in the final tree. Open edges may or may not be used.
  151. Yields
  152. ------
  153. edge tuple
  154. The edges as discovered by Kruskal's method. Each edge can
  155. take the following forms: `(u, v)`, `(u, v, d)` or `(u, v, k, d)`
  156. depending on the `key` and `data` parameters
  157. """
  158. subtrees = UnionFind()
  159. if G.is_multigraph():
  160. edges = G.edges(keys=True, data=True)
  161. else:
  162. edges = G.edges(data=True)
  163. # Sort the edges of the graph with respect to the partition data.
  164. # Edges are returned in the following order:
  165. # * Included edges
  166. # * Open edges from smallest to largest weight
  167. # * Excluded edges
  168. included_edges = []
  169. open_edges = []
  170. for e in edges:
  171. d = e[-1]
  172. wt = d.get(weight, 1)
  173. if isnan(wt):
  174. if ignore_nan:
  175. continue
  176. raise ValueError(f"NaN found as an edge weight. Edge {e}")
  177. edge = (wt,) + e
  178. if d.get(partition) == EdgePartition.INCLUDED:
  179. included_edges.append(edge)
  180. elif d.get(partition) == EdgePartition.EXCLUDED:
  181. continue
  182. else:
  183. open_edges.append(edge)
  184. if minimum:
  185. sorted_open_edges = sorted(open_edges, key=itemgetter(0))
  186. else:
  187. sorted_open_edges = sorted(open_edges, key=itemgetter(0), reverse=True)
  188. # Condense the lists into one
  189. included_edges.extend(sorted_open_edges)
  190. sorted_edges = included_edges
  191. del open_edges, sorted_open_edges, included_edges
  192. # Multigraphs need to handle edge keys in addition to edge data.
  193. if G.is_multigraph():
  194. for wt, u, v, k, d in sorted_edges:
  195. if subtrees[u] != subtrees[v]:
  196. if keys:
  197. if data:
  198. yield u, v, k, d
  199. else:
  200. yield u, v, k
  201. else:
  202. if data:
  203. yield u, v, d
  204. else:
  205. yield u, v
  206. subtrees.union(u, v)
  207. else:
  208. for wt, u, v, d in sorted_edges:
  209. if subtrees[u] != subtrees[v]:
  210. if data:
  211. yield u, v, d
  212. else:
  213. yield u, v
  214. subtrees.union(u, v)
  215. @nx._dispatchable(edge_attrs="weight", preserve_edge_attrs="data")
  216. def prim_mst_edges(G, minimum, weight="weight", keys=True, data=True, ignore_nan=False):
  217. """Iterate over edges of Prim's algorithm min/max spanning tree.
  218. Parameters
  219. ----------
  220. G : NetworkX Graph
  221. The graph holding the tree of interest.
  222. minimum : bool (default: True)
  223. Find the minimum (True) or maximum (False) spanning tree.
  224. weight : string (default: 'weight')
  225. The name of the edge attribute holding the edge weights.
  226. keys : bool (default: True)
  227. If `G` is a multigraph, `keys` controls whether edge keys ar yielded.
  228. Otherwise `keys` is ignored.
  229. data : bool (default: True)
  230. Flag for whether to yield edge attribute dicts.
  231. If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
  232. If False, yield edges `(u, v)`.
  233. ignore_nan : bool (default: False)
  234. If a NaN is found as an edge weight normally an exception is raised.
  235. If `ignore_nan is True` then that edge is ignored instead.
  236. """
  237. is_multigraph = G.is_multigraph()
  238. nodes = set(G)
  239. c = count()
  240. sign = 1 if minimum else -1
  241. while nodes:
  242. u = nodes.pop()
  243. frontier = []
  244. visited = {u}
  245. if is_multigraph:
  246. for v, keydict in G.adj[u].items():
  247. for k, d in keydict.items():
  248. wt = d.get(weight, 1) * sign
  249. if isnan(wt):
  250. if ignore_nan:
  251. continue
  252. msg = f"NaN found as an edge weight. Edge {(u, v, k, d)}"
  253. raise ValueError(msg)
  254. heappush(frontier, (wt, next(c), u, v, k, d))
  255. else:
  256. for v, d in G.adj[u].items():
  257. wt = d.get(weight, 1) * sign
  258. if isnan(wt):
  259. if ignore_nan:
  260. continue
  261. msg = f"NaN found as an edge weight. Edge {(u, v, d)}"
  262. raise ValueError(msg)
  263. heappush(frontier, (wt, next(c), u, v, d))
  264. while nodes and frontier:
  265. if is_multigraph:
  266. W, _, u, v, k, d = heappop(frontier)
  267. else:
  268. W, _, u, v, d = heappop(frontier)
  269. if v in visited or v not in nodes:
  270. continue
  271. # Multigraphs need to handle edge keys in addition to edge data.
  272. if is_multigraph and keys:
  273. if data:
  274. yield u, v, k, d
  275. else:
  276. yield u, v, k
  277. else:
  278. if data:
  279. yield u, v, d
  280. else:
  281. yield u, v
  282. # update frontier
  283. visited.add(v)
  284. nodes.discard(v)
  285. if is_multigraph:
  286. for w, keydict in G.adj[v].items():
  287. if w in visited:
  288. continue
  289. for k2, d2 in keydict.items():
  290. new_weight = d2.get(weight, 1) * sign
  291. if isnan(new_weight):
  292. if ignore_nan:
  293. continue
  294. msg = f"NaN found as an edge weight. Edge {(v, w, k2, d2)}"
  295. raise ValueError(msg)
  296. heappush(frontier, (new_weight, next(c), v, w, k2, d2))
  297. else:
  298. for w, d2 in G.adj[v].items():
  299. if w in visited:
  300. continue
  301. new_weight = d2.get(weight, 1) * sign
  302. if isnan(new_weight):
  303. if ignore_nan:
  304. continue
  305. msg = f"NaN found as an edge weight. Edge {(v, w, d2)}"
  306. raise ValueError(msg)
  307. heappush(frontier, (new_weight, next(c), v, w, d2))
  308. ALGORITHMS = {
  309. "boruvka": boruvka_mst_edges,
  310. "borůvka": boruvka_mst_edges,
  311. "kruskal": kruskal_mst_edges,
  312. "prim": prim_mst_edges,
  313. }
  314. @not_implemented_for("directed")
  315. @nx._dispatchable(edge_attrs="weight", preserve_edge_attrs="data")
  316. def minimum_spanning_edges(
  317. G, algorithm="kruskal", weight="weight", keys=True, data=True, ignore_nan=False
  318. ):
  319. """Generate edges in a minimum spanning forest of an undirected
  320. weighted graph.
  321. A minimum spanning tree is a subgraph of the graph (a tree)
  322. with the minimum sum of edge weights. A spanning forest is a
  323. union of the spanning trees for each connected component of the graph.
  324. Parameters
  325. ----------
  326. G : undirected Graph
  327. An undirected graph. If `G` is connected, then the algorithm finds a
  328. spanning tree. Otherwise, a spanning forest is found.
  329. algorithm : string
  330. The algorithm to use when finding a minimum spanning tree. Valid
  331. choices are 'kruskal', 'prim', or 'boruvka'. The default is 'kruskal'.
  332. weight : string
  333. Edge data key to use for weight (default 'weight').
  334. keys : bool
  335. Whether to yield edge key in multigraphs in addition to the edge.
  336. If `G` is not a multigraph, this is ignored.
  337. data : bool, optional
  338. If True yield the edge data along with the edge.
  339. ignore_nan : bool (default: False)
  340. If a NaN is found as an edge weight normally an exception is raised.
  341. If `ignore_nan is True` then that edge is ignored instead.
  342. Returns
  343. -------
  344. edges : iterator
  345. An iterator over edges in a maximum spanning tree of `G`.
  346. Edges connecting nodes `u` and `v` are represented as tuples:
  347. `(u, v, k, d)` or `(u, v, k)` or `(u, v, d)` or `(u, v)`
  348. If `G` is a multigraph, `keys` indicates whether the edge key `k` will
  349. be reported in the third position in the edge tuple. `data` indicates
  350. whether the edge datadict `d` will appear at the end of the edge tuple.
  351. If `G` is not a multigraph, the tuples are `(u, v, d)` if `data` is True
  352. or `(u, v)` if `data` is False.
  353. Examples
  354. --------
  355. >>> from networkx.algorithms import tree
  356. Find minimum spanning edges by Kruskal's algorithm
  357. >>> G = nx.cycle_graph(4)
  358. >>> G.add_edge(0, 3, weight=2)
  359. >>> mst = tree.minimum_spanning_edges(G, algorithm="kruskal", data=False)
  360. >>> edgelist = list(mst)
  361. >>> sorted(sorted(e) for e in edgelist)
  362. [[0, 1], [1, 2], [2, 3]]
  363. Find minimum spanning edges by Prim's algorithm
  364. >>> G = nx.cycle_graph(4)
  365. >>> G.add_edge(0, 3, weight=2)
  366. >>> mst = tree.minimum_spanning_edges(G, algorithm="prim", data=False)
  367. >>> edgelist = list(mst)
  368. >>> sorted(sorted(e) for e in edgelist)
  369. [[0, 1], [1, 2], [2, 3]]
  370. Notes
  371. -----
  372. For Borůvka's algorithm, each edge must have a weight attribute, and
  373. each edge weight must be distinct.
  374. For the other algorithms, if the graph edges do not have a weight
  375. attribute a default weight of 1 will be used.
  376. Modified code from David Eppstein, April 2006
  377. http://www.ics.uci.edu/~eppstein/PADS/
  378. """
  379. try:
  380. algo = ALGORITHMS[algorithm]
  381. except KeyError as err:
  382. msg = f"{algorithm} is not a valid choice for an algorithm."
  383. raise ValueError(msg) from err
  384. return algo(
  385. G, minimum=True, weight=weight, keys=keys, data=data, ignore_nan=ignore_nan
  386. )
  387. @not_implemented_for("directed")
  388. @nx._dispatchable(edge_attrs="weight", preserve_edge_attrs="data")
  389. def maximum_spanning_edges(
  390. G, algorithm="kruskal", weight="weight", keys=True, data=True, ignore_nan=False
  391. ):
  392. """Generate edges in a maximum spanning forest of an undirected
  393. weighted graph.
  394. A maximum spanning tree is a subgraph of the graph (a tree)
  395. with the maximum possible sum of edge weights. A spanning forest is a
  396. union of the spanning trees for each connected component of the graph.
  397. Parameters
  398. ----------
  399. G : undirected Graph
  400. An undirected graph. If `G` is connected, then the algorithm finds a
  401. spanning tree. Otherwise, a spanning forest is found.
  402. algorithm : string
  403. The algorithm to use when finding a maximum spanning tree. Valid
  404. choices are 'kruskal', 'prim', or 'boruvka'. The default is 'kruskal'.
  405. weight : string
  406. Edge data key to use for weight (default 'weight').
  407. keys : bool
  408. Whether to yield edge key in multigraphs in addition to the edge.
  409. If `G` is not a multigraph, this is ignored.
  410. data : bool, optional
  411. If True yield the edge data along with the edge.
  412. ignore_nan : bool (default: False)
  413. If a NaN is found as an edge weight normally an exception is raised.
  414. If `ignore_nan is True` then that edge is ignored instead.
  415. Returns
  416. -------
  417. edges : iterator
  418. An iterator over edges in a maximum spanning tree of `G`.
  419. Edges connecting nodes `u` and `v` are represented as tuples:
  420. `(u, v, k, d)` or `(u, v, k)` or `(u, v, d)` or `(u, v)`
  421. If `G` is a multigraph, `keys` indicates whether the edge key `k` will
  422. be reported in the third position in the edge tuple. `data` indicates
  423. whether the edge datadict `d` will appear at the end of the edge tuple.
  424. If `G` is not a multigraph, the tuples are `(u, v, d)` if `data` is True
  425. or `(u, v)` if `data` is False.
  426. Examples
  427. --------
  428. >>> from networkx.algorithms import tree
  429. Find maximum spanning edges by Kruskal's algorithm
  430. >>> G = nx.cycle_graph(4)
  431. >>> G.add_edge(0, 3, weight=2)
  432. >>> mst = tree.maximum_spanning_edges(G, algorithm="kruskal", data=False)
  433. >>> edgelist = list(mst)
  434. >>> sorted(sorted(e) for e in edgelist)
  435. [[0, 1], [0, 3], [1, 2]]
  436. Find maximum spanning edges by Prim's algorithm
  437. >>> G = nx.cycle_graph(4)
  438. >>> G.add_edge(0, 3, weight=2) # assign weight 2 to edge 0-3
  439. >>> mst = tree.maximum_spanning_edges(G, algorithm="prim", data=False)
  440. >>> edgelist = list(mst)
  441. >>> sorted(sorted(e) for e in edgelist)
  442. [[0, 1], [0, 3], [2, 3]]
  443. Notes
  444. -----
  445. For Borůvka's algorithm, each edge must have a weight attribute, and
  446. each edge weight must be distinct.
  447. For the other algorithms, if the graph edges do not have a weight
  448. attribute a default weight of 1 will be used.
  449. Modified code from David Eppstein, April 2006
  450. http://www.ics.uci.edu/~eppstein/PADS/
  451. """
  452. try:
  453. algo = ALGORITHMS[algorithm]
  454. except KeyError as err:
  455. msg = f"{algorithm} is not a valid choice for an algorithm."
  456. raise ValueError(msg) from err
  457. return algo(
  458. G, minimum=False, weight=weight, keys=keys, data=data, ignore_nan=ignore_nan
  459. )
  460. @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
  461. def minimum_spanning_tree(G, weight="weight", algorithm="kruskal", ignore_nan=False):
  462. """Returns a minimum spanning tree or forest on an undirected graph `G`.
  463. Parameters
  464. ----------
  465. G : undirected graph
  466. An undirected graph. If `G` is connected, then the algorithm finds a
  467. spanning tree. Otherwise, a spanning forest is found.
  468. weight : str
  469. Data key to use for edge weights.
  470. algorithm : string
  471. The algorithm to use when finding a minimum spanning tree. Valid
  472. choices are 'kruskal', 'prim', or 'boruvka'. The default is
  473. 'kruskal'.
  474. ignore_nan : bool (default: False)
  475. If a NaN is found as an edge weight normally an exception is raised.
  476. If `ignore_nan is True` then that edge is ignored instead.
  477. Returns
  478. -------
  479. G : NetworkX Graph
  480. A minimum spanning tree or forest.
  481. Examples
  482. --------
  483. >>> G = nx.cycle_graph(4)
  484. >>> G.add_edge(0, 3, weight=2)
  485. >>> T = nx.minimum_spanning_tree(G)
  486. >>> sorted(T.edges(data=True))
  487. [(0, 1, {}), (1, 2, {}), (2, 3, {})]
  488. Notes
  489. -----
  490. For Borůvka's algorithm, each edge must have a weight attribute, and
  491. each edge weight must be distinct.
  492. For the other algorithms, if the graph edges do not have a weight
  493. attribute a default weight of 1 will be used.
  494. There may be more than one tree with the same minimum or maximum weight.
  495. See :mod:`networkx.tree.recognition` for more detailed definitions.
  496. Isolated nodes with self-loops are in the tree as edgeless isolated nodes.
  497. """
  498. edges = minimum_spanning_edges(
  499. G, algorithm, weight, keys=True, data=True, ignore_nan=ignore_nan
  500. )
  501. T = G.__class__() # Same graph class as G
  502. T.graph.update(G.graph)
  503. T.add_nodes_from(G.nodes.items())
  504. T.add_edges_from(edges)
  505. return T
  506. @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
  507. def partition_spanning_tree(
  508. G, minimum=True, weight="weight", partition="partition", ignore_nan=False
  509. ):
  510. """
  511. Find a spanning tree while respecting a partition of edges.
  512. Edges can be flagged as either `INCLUDED` which are required to be in the
  513. returned tree, `EXCLUDED`, which cannot be in the returned tree and `OPEN`.
  514. This is used in the SpanningTreeIterator to create new partitions following
  515. the algorithm of Sörensen and Janssens [1]_.
  516. Parameters
  517. ----------
  518. G : undirected graph
  519. An undirected graph.
  520. minimum : bool (default: True)
  521. Determines whether the returned tree is the minimum spanning tree of
  522. the partition of the maximum one.
  523. weight : str
  524. Data key to use for edge weights.
  525. partition : str
  526. The key for the edge attribute containing the partition
  527. data on the graph. Edges can be included, excluded or open using the
  528. `EdgePartition` enum.
  529. ignore_nan : bool (default: False)
  530. If a NaN is found as an edge weight normally an exception is raised.
  531. If `ignore_nan is True` then that edge is ignored instead.
  532. Returns
  533. -------
  534. G : NetworkX Graph
  535. A minimum spanning tree using all of the included edges in the graph and
  536. none of the excluded edges.
  537. References
  538. ----------
  539. .. [1] G.K. Janssens, K. Sörensen, An algorithm to generate all spanning
  540. trees in order of increasing cost, Pesquisa Operacional, 2005-08,
  541. Vol. 25 (2), p. 219-229,
  542. https://www.scielo.br/j/pope/a/XHswBwRwJyrfL88dmMwYNWp/?lang=en
  543. """
  544. edges = kruskal_mst_edges(
  545. G,
  546. minimum,
  547. weight,
  548. keys=True,
  549. data=True,
  550. ignore_nan=ignore_nan,
  551. partition=partition,
  552. )
  553. T = G.__class__() # Same graph class as G
  554. T.graph.update(G.graph)
  555. T.add_nodes_from(G.nodes.items())
  556. T.add_edges_from(edges)
  557. return T
  558. @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
  559. def maximum_spanning_tree(G, weight="weight", algorithm="kruskal", ignore_nan=False):
  560. """Returns a maximum spanning tree or forest on an undirected graph `G`.
  561. Parameters
  562. ----------
  563. G : undirected graph
  564. An undirected graph. If `G` is connected, then the algorithm finds a
  565. spanning tree. Otherwise, a spanning forest is found.
  566. weight : str
  567. Data key to use for edge weights.
  568. algorithm : string
  569. The algorithm to use when finding a maximum spanning tree. Valid
  570. choices are 'kruskal', 'prim', or 'boruvka'. The default is
  571. 'kruskal'.
  572. ignore_nan : bool (default: False)
  573. If a NaN is found as an edge weight normally an exception is raised.
  574. If `ignore_nan is True` then that edge is ignored instead.
  575. Returns
  576. -------
  577. G : NetworkX Graph
  578. A maximum spanning tree or forest.
  579. Examples
  580. --------
  581. >>> G = nx.cycle_graph(4)
  582. >>> G.add_edge(0, 3, weight=2)
  583. >>> T = nx.maximum_spanning_tree(G)
  584. >>> sorted(T.edges(data=True))
  585. [(0, 1, {}), (0, 3, {'weight': 2}), (1, 2, {})]
  586. Notes
  587. -----
  588. For Borůvka's algorithm, each edge must have a weight attribute, and
  589. each edge weight must be distinct.
  590. For the other algorithms, if the graph edges do not have a weight
  591. attribute a default weight of 1 will be used.
  592. There may be more than one tree with the same minimum or maximum weight.
  593. See :mod:`networkx.tree.recognition` for more detailed definitions.
  594. Isolated nodes with self-loops are in the tree as edgeless isolated nodes.
  595. """
  596. edges = maximum_spanning_edges(
  597. G, algorithm, weight, keys=True, data=True, ignore_nan=ignore_nan
  598. )
  599. edges = list(edges)
  600. T = G.__class__() # Same graph class as G
  601. T.graph.update(G.graph)
  602. T.add_nodes_from(G.nodes.items())
  603. T.add_edges_from(edges)
  604. return T
  605. @py_random_state(3)
  606. @nx._dispatchable(preserve_edge_attrs=True, returns_graph=True)
  607. def random_spanning_tree(G, weight=None, *, multiplicative=True, seed=None):
  608. """
  609. Sample a random spanning tree using the edges weights of `G`.
  610. This function supports two different methods for determining the
  611. probability of the graph. If ``multiplicative=True``, the probability
  612. is based on the product of edge weights, and if ``multiplicative=False``
  613. it is based on the sum of the edge weight. However, since it is
  614. easier to determine the total weight of all spanning trees for the
  615. multiplicative version, that is significantly faster and should be used if
  616. possible. Additionally, setting `weight` to `None` will cause a spanning tree
  617. to be selected with uniform probability.
  618. The function uses algorithm A8 in [1]_ .
  619. Parameters
  620. ----------
  621. G : nx.Graph
  622. An undirected version of the original graph.
  623. weight : string
  624. The edge key for the edge attribute holding edge weight.
  625. multiplicative : bool, default=True
  626. If `True`, the probability of each tree is the product of its edge weight
  627. over the sum of the product of all the spanning trees in the graph. If
  628. `False`, the probability is the sum of its edge weight over the sum of
  629. the sum of weights for all spanning trees in the graph.
  630. seed : integer, random_state, or None (default)
  631. Indicator of random number generation state.
  632. See :ref:`Randomness<randomness>`.
  633. Returns
  634. -------
  635. nx.Graph
  636. A spanning tree using the distribution defined by the weight of the tree.
  637. References
  638. ----------
  639. .. [1] V. Kulkarni, Generating random combinatorial objects, Journal of
  640. Algorithms, 11 (1990), pp. 185–207
  641. """
  642. def find_node(merged_nodes, node):
  643. """
  644. We can think of clusters of contracted nodes as having one
  645. representative in the graph. Each node which is not in merged_nodes
  646. is still its own representative. Since a representative can be later
  647. contracted, we need to recursively search though the dict to find
  648. the final representative, but once we know it we can use path
  649. compression to speed up the access of the representative for next time.
  650. This cannot be replaced by the standard NetworkX union_find since that
  651. data structure will merge nodes with less representing nodes into the
  652. one with more representing nodes but this function requires we merge
  653. them using the order that contract_edges contracts using.
  654. Parameters
  655. ----------
  656. merged_nodes : dict
  657. The dict storing the mapping from node to representative
  658. node
  659. The node whose representative we seek
  660. Returns
  661. -------
  662. The representative of the `node`
  663. """
  664. if node not in merged_nodes:
  665. return node
  666. else:
  667. rep = find_node(merged_nodes, merged_nodes[node])
  668. merged_nodes[node] = rep
  669. return rep
  670. def prepare_graph():
  671. """
  672. For the graph `G`, remove all edges not in the set `V` and then
  673. contract all edges in the set `U`.
  674. Returns
  675. -------
  676. A copy of `G` which has had all edges not in `V` removed and all edges
  677. in `U` contracted.
  678. """
  679. # The result is a MultiGraph version of G so that parallel edges are
  680. # allowed during edge contraction
  681. result = nx.MultiGraph(incoming_graph_data=G)
  682. # Remove all edges not in V
  683. edges_to_remove = set(result.edges()).difference(V)
  684. result.remove_edges_from(edges_to_remove)
  685. # Contract all edges in U
  686. #
  687. # Imagine that you have two edges to contract and they share an
  688. # endpoint like this:
  689. # [0] ----- [1] ----- [2]
  690. # If we contract (0, 1) first, the contraction function will always
  691. # delete the second node it is passed so the resulting graph would be
  692. # [0] ----- [2]
  693. # and edge (1, 2) no longer exists but (0, 2) would need to be contracted
  694. # in its place now. That is why I use the below dict as a merge-find
  695. # data structure with path compression to track how the nodes are merged.
  696. merged_nodes = {}
  697. for u, v in U:
  698. u_rep = find_node(merged_nodes, u)
  699. v_rep = find_node(merged_nodes, v)
  700. # We cannot contract a node with itself
  701. if u_rep == v_rep:
  702. continue
  703. nx.contracted_nodes(result, u_rep, v_rep, self_loops=False, copy=False)
  704. merged_nodes[v_rep] = u_rep
  705. return merged_nodes, result
  706. def spanning_tree_total_weight(G, weight):
  707. """
  708. Find the sum of weights of the spanning trees of `G` using the
  709. appropriate `method`.
  710. This is easy if the chosen method is 'multiplicative', since we can
  711. use Kirchhoff's Tree Matrix Theorem directly. However, with the
  712. 'additive' method, this process is slightly more complex and less
  713. computationally efficient as we have to find the number of spanning
  714. trees which contain each possible edge in the graph.
  715. Parameters
  716. ----------
  717. G : NetworkX Graph
  718. The graph to find the total weight of all spanning trees on.
  719. weight : string
  720. The key for the weight edge attribute of the graph.
  721. Returns
  722. -------
  723. float
  724. The sum of either the multiplicative or additive weight for all
  725. spanning trees in the graph.
  726. """
  727. if multiplicative:
  728. return number_of_spanning_trees(G, weight=weight)
  729. else:
  730. # There are two cases for the total spanning tree additive weight.
  731. # 1. There is one edge in the graph. Then the only spanning tree is
  732. # that edge itself, which will have a total weight of that edge
  733. # itself.
  734. if G.number_of_edges() == 1:
  735. return G.edges(data=weight).__iter__().__next__()[2]
  736. # 2. There are no edges or two or more edges in the graph. Then, we find the
  737. # total weight of the spanning trees using the formula in the
  738. # reference paper: take the weight of each edge and multiply it by
  739. # the number of spanning trees which include that edge. This
  740. # can be accomplished by contracting the edge and finding the
  741. # multiplicative total spanning tree weight if the weight of each edge
  742. # is assumed to be 1, which is conveniently built into networkx already,
  743. # by calling number_of_spanning_trees with weight=None.
  744. # Note that with no edges the returned value is just zero.
  745. else:
  746. total = 0
  747. for u, v, w in G.edges(data=weight):
  748. total += w * nx.number_of_spanning_trees(
  749. nx.contracted_edge(G, edge=(u, v), self_loops=False),
  750. weight=None,
  751. )
  752. return total
  753. if G.number_of_nodes() < 2:
  754. # no edges in the spanning tree
  755. return nx.empty_graph(G.nodes)
  756. U = set()
  757. st_cached_value = 0
  758. V = set(G.edges())
  759. shuffled_edges = list(G.edges())
  760. seed.shuffle(shuffled_edges)
  761. for u, v in shuffled_edges:
  762. e_weight = G[u][v][weight] if weight is not None else 1
  763. node_map, prepared_G = prepare_graph()
  764. G_total_tree_weight = spanning_tree_total_weight(prepared_G, weight)
  765. # Add the edge to U so that we can compute the total tree weight
  766. # assuming we include that edge
  767. # Now, if (u, v) cannot exist in G because it is fully contracted out
  768. # of existence, then it by definition cannot influence G_e's Kirchhoff
  769. # value. But, we also cannot pick it.
  770. rep_edge = (find_node(node_map, u), find_node(node_map, v))
  771. # Check to see if the 'representative edge' for the current edge is
  772. # in prepared_G. If so, then we can pick it.
  773. if rep_edge in prepared_G.edges:
  774. prepared_G_e = nx.contracted_edge(
  775. prepared_G, edge=rep_edge, self_loops=False
  776. )
  777. G_e_total_tree_weight = spanning_tree_total_weight(prepared_G_e, weight)
  778. if multiplicative:
  779. threshold = e_weight * G_e_total_tree_weight / G_total_tree_weight
  780. else:
  781. numerator = (st_cached_value + e_weight) * nx.number_of_spanning_trees(
  782. prepared_G_e
  783. ) + G_e_total_tree_weight
  784. denominator = (
  785. st_cached_value * nx.number_of_spanning_trees(prepared_G)
  786. + G_total_tree_weight
  787. )
  788. threshold = numerator / denominator
  789. else:
  790. threshold = 0.0
  791. z = seed.uniform(0.0, 1.0)
  792. if z > threshold:
  793. # Remove the edge from V since we did not pick it.
  794. V.remove((u, v))
  795. else:
  796. # Add the edge to U since we picked it.
  797. st_cached_value += e_weight
  798. U.add((u, v))
  799. # If we decide to keep an edge, it may complete the spanning tree.
  800. if len(U) == G.number_of_nodes() - 1:
  801. spanning_tree = nx.Graph()
  802. spanning_tree.add_edges_from(U)
  803. return spanning_tree
  804. raise Exception(f"Something went wrong! Only {len(U)} edges in the spanning tree!")
  805. class SpanningTreeIterator:
  806. """
  807. Iterate over all spanning trees of a graph in either increasing or
  808. decreasing cost.
  809. Notes
  810. -----
  811. This iterator uses the partition scheme from [1]_ (included edges,
  812. excluded edges and open edges) as well as a modified Kruskal's Algorithm
  813. to generate minimum spanning trees which respect the partition of edges.
  814. For spanning trees with the same weight, ties are broken arbitrarily.
  815. References
  816. ----------
  817. .. [1] G.K. Janssens, K. Sörensen, An algorithm to generate all spanning
  818. trees in order of increasing cost, Pesquisa Operacional, 2005-08,
  819. Vol. 25 (2), p. 219-229,
  820. https://www.scielo.br/j/pope/a/XHswBwRwJyrfL88dmMwYNWp/?lang=en
  821. """
  822. @dataclass(order=True)
  823. class Partition:
  824. """
  825. This dataclass represents a partition and stores a dict with the edge
  826. data and the weight of the minimum spanning tree of the partition dict.
  827. """
  828. mst_weight: float
  829. partition_dict: dict = field(compare=False)
  830. def __copy__(self):
  831. return SpanningTreeIterator.Partition(
  832. self.mst_weight, self.partition_dict.copy()
  833. )
  834. def __init__(self, G, weight="weight", minimum=True, ignore_nan=False):
  835. """
  836. Initialize the iterator
  837. Parameters
  838. ----------
  839. G : nx.Graph
  840. The directed graph which we need to iterate trees over
  841. weight : String, default = "weight"
  842. The edge attribute used to store the weight of the edge
  843. minimum : bool, default = True
  844. Return the trees in increasing order while true and decreasing order
  845. while false.
  846. ignore_nan : bool, default = False
  847. If a NaN is found as an edge weight normally an exception is raised.
  848. If `ignore_nan is True` then that edge is ignored instead.
  849. """
  850. self.G = G.copy()
  851. self.G.__networkx_cache__ = None # Disable caching
  852. self.weight = weight
  853. self.minimum = minimum
  854. self.ignore_nan = ignore_nan
  855. # Randomly create a key for an edge attribute to hold the partition data
  856. self.partition_key = (
  857. "SpanningTreeIterators super secret partition attribute name"
  858. )
  859. def __iter__(self):
  860. """
  861. Returns
  862. -------
  863. SpanningTreeIterator
  864. The iterator object for this graph
  865. """
  866. self.partition_queue = PriorityQueue()
  867. self._clear_partition(self.G)
  868. mst_weight = partition_spanning_tree(
  869. self.G, self.minimum, self.weight, self.partition_key, self.ignore_nan
  870. ).size(weight=self.weight)
  871. self.partition_queue.put(
  872. self.Partition(mst_weight if self.minimum else -mst_weight, {})
  873. )
  874. return self
  875. def __next__(self):
  876. """
  877. Returns
  878. -------
  879. (multi)Graph
  880. The spanning tree of next greatest weight, which ties broken
  881. arbitrarily.
  882. """
  883. if self.partition_queue.empty():
  884. del self.G, self.partition_queue
  885. raise StopIteration
  886. partition = self.partition_queue.get()
  887. self._write_partition(partition)
  888. next_tree = partition_spanning_tree(
  889. self.G, self.minimum, self.weight, self.partition_key, self.ignore_nan
  890. )
  891. self._partition(partition, next_tree)
  892. self._clear_partition(next_tree)
  893. return next_tree
  894. def _partition(self, partition, partition_tree):
  895. """
  896. Create new partitions based of the minimum spanning tree of the
  897. current minimum partition.
  898. Parameters
  899. ----------
  900. partition : Partition
  901. The Partition instance used to generate the current minimum spanning
  902. tree.
  903. partition_tree : nx.Graph
  904. The minimum spanning tree of the input partition.
  905. """
  906. # create two new partitions with the data from the input partition dict
  907. p1 = self.Partition(0, partition.partition_dict.copy())
  908. p2 = self.Partition(0, partition.partition_dict.copy())
  909. for e in partition_tree.edges:
  910. # determine if the edge was open or included
  911. if e not in partition.partition_dict:
  912. # This is an open edge
  913. p1.partition_dict[e] = EdgePartition.EXCLUDED
  914. p2.partition_dict[e] = EdgePartition.INCLUDED
  915. self._write_partition(p1)
  916. p1_mst = partition_spanning_tree(
  917. self.G,
  918. self.minimum,
  919. self.weight,
  920. self.partition_key,
  921. self.ignore_nan,
  922. )
  923. p1_mst_weight = p1_mst.size(weight=self.weight)
  924. if nx.is_connected(p1_mst):
  925. p1.mst_weight = p1_mst_weight if self.minimum else -p1_mst_weight
  926. self.partition_queue.put(p1.__copy__())
  927. p1.partition_dict = p2.partition_dict.copy()
  928. def _write_partition(self, partition):
  929. """
  930. Writes the desired partition into the graph to calculate the minimum
  931. spanning tree.
  932. Parameters
  933. ----------
  934. partition : Partition
  935. A Partition dataclass describing a partition on the edges of the
  936. graph.
  937. """
  938. partition_dict = partition.partition_dict
  939. partition_key = self.partition_key
  940. G = self.G
  941. edges = (
  942. G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
  943. )
  944. for *e, d in edges:
  945. d[partition_key] = partition_dict.get(tuple(e), EdgePartition.OPEN)
  946. def _clear_partition(self, G):
  947. """
  948. Removes partition data from the graph
  949. """
  950. partition_key = self.partition_key
  951. edges = (
  952. G.edges(keys=True, data=True) if G.is_multigraph() else G.edges(data=True)
  953. )
  954. for *e, d in edges:
  955. if partition_key in d:
  956. del d[partition_key]
  957. @nx._dispatchable(edge_attrs="weight")
  958. def number_of_spanning_trees(G, *, root=None, weight=None):
  959. """Returns the number of spanning trees in `G`.
  960. A spanning tree for an undirected graph is a tree that connects
  961. all nodes in the graph. For a directed graph, the analog of a
  962. spanning tree is called a (spanning) arborescence. The arborescence
  963. includes a unique directed path from the `root` node to each other node.
  964. The graph must be weakly connected, and the root must be a node
  965. that includes all nodes as successors [3]_. Note that to avoid
  966. discussing sink-roots and reverse-arborescences, we have reversed
  967. the edge orientation from [3]_ and use the in-degree laplacian.
  968. This function (when `weight` is `None`) returns the number of
  969. spanning trees for an undirected graph and the number of
  970. arborescences from a single root node for a directed graph.
  971. When `weight` is the name of an edge attribute which holds the
  972. weight value of each edge, the function returns the sum over
  973. all trees of the multiplicative weight of each tree. That is,
  974. the weight of the tree is the product of its edge weights.
  975. Kirchoff's Tree Matrix Theorem states that any cofactor of the
  976. Laplacian matrix of a graph is the number of spanning trees in the
  977. graph. (Here we use cofactors for a diagonal entry so that the
  978. cofactor becomes the determinant of the matrix with one row
  979. and its matching column removed.) For a weighted Laplacian matrix,
  980. the cofactor is the sum across all spanning trees of the
  981. multiplicative weight of each tree. That is, the weight of each
  982. tree is the product of its edge weights. The theorem is also
  983. known as Kirchhoff's theorem [1]_ and the Matrix-Tree theorem [2]_.
  984. For directed graphs, a similar theorem (Tutte's Theorem) holds with
  985. the cofactor chosen to be the one with row and column removed that
  986. correspond to the root. The cofactor is the number of arborescences
  987. with the specified node as root. And the weighted version gives the
  988. sum of the arborescence weights with root `root`. The arborescence
  989. weight is the product of its edge weights.
  990. Parameters
  991. ----------
  992. G : NetworkX graph
  993. root : node
  994. A node in the directed graph `G` that has all nodes as descendants.
  995. (This is ignored for undirected graphs.)
  996. weight : string or None, optional (default=None)
  997. The name of the edge attribute holding the edge weight.
  998. If `None`, then each edge is assumed to have a weight of 1.
  999. Returns
  1000. -------
  1001. Number
  1002. Undirected graphs:
  1003. The number of spanning trees of the graph `G`.
  1004. Or the sum of all spanning tree weights of the graph `G`
  1005. where the weight of a tree is the product of its edge weights.
  1006. Directed graphs:
  1007. The number of arborescences of `G` rooted at node `root`.
  1008. Or the sum of all arborescence weights of the graph `G` with
  1009. specified root where the weight of an arborescence is the product
  1010. of its edge weights.
  1011. Raises
  1012. ------
  1013. NetworkXPointlessConcept
  1014. If `G` does not contain any nodes.
  1015. NetworkXError
  1016. If the graph `G` is directed and the root node
  1017. is not specified or is not in G.
  1018. Examples
  1019. --------
  1020. >>> G = nx.complete_graph(5)
  1021. >>> round(nx.number_of_spanning_trees(G))
  1022. 125
  1023. >>> G = nx.Graph()
  1024. >>> G.add_edge(1, 2, weight=2)
  1025. >>> G.add_edge(1, 3, weight=1)
  1026. >>> G.add_edge(2, 3, weight=1)
  1027. >>> round(nx.number_of_spanning_trees(G, weight="weight"))
  1028. 5
  1029. Notes
  1030. -----
  1031. Self-loops are excluded. Multi-edges are contracted in one edge
  1032. equal to the sum of the weights.
  1033. References
  1034. ----------
  1035. .. [1] Wikipedia
  1036. "Kirchhoff's theorem."
  1037. https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem
  1038. .. [2] Kirchhoff, G. R.
  1039. Über die Auflösung der Gleichungen, auf welche man
  1040. bei der Untersuchung der linearen Vertheilung
  1041. Galvanischer Ströme geführt wird
  1042. Annalen der Physik und Chemie, vol. 72, pp. 497-508, 1847.
  1043. .. [3] Margoliash, J.
  1044. "Matrix-Tree Theorem for Directed Graphs"
  1045. https://www.math.uchicago.edu/~may/VIGRE/VIGRE2010/REUPapers/Margoliash.pdf
  1046. """
  1047. import numpy as np
  1048. if len(G) == 0:
  1049. raise nx.NetworkXPointlessConcept("Graph G must contain at least one node.")
  1050. # undirected G
  1051. if not nx.is_directed(G):
  1052. if not nx.is_connected(G):
  1053. return 0
  1054. G_laplacian = nx.laplacian_matrix(G, weight=weight).toarray()
  1055. return float(np.linalg.det(G_laplacian[1:, 1:]))
  1056. # directed G
  1057. if root is None:
  1058. raise nx.NetworkXError("Input `root` must be provided when G is directed")
  1059. if root not in G:
  1060. raise nx.NetworkXError("The node root is not in the graph G.")
  1061. if not nx.is_weakly_connected(G):
  1062. return 0
  1063. # Compute directed Laplacian matrix
  1064. nodelist = [root] + [n for n in G if n != root]
  1065. A = nx.adjacency_matrix(G, nodelist=nodelist, weight=weight)
  1066. D = np.diag(A.sum(axis=0))
  1067. G_laplacian = D - A
  1068. # Compute number of spanning trees
  1069. return float(np.linalg.det(G_laplacian[1:, 1:]))