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