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