Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/algorithms/tree/mst.py: 16%
311 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
1"""
2Algorithms for calculating min/max spanning trees/forests.
4"""
5from dataclasses import dataclass, field
6from enum import Enum
7from heapq import heappop, heappush
8from itertools import count
9from math import isnan
10from operator import itemgetter
11from queue import PriorityQueue
13import networkx as nx
14from networkx.utils import UnionFind, not_implemented_for, py_random_state
16__all__ = [
17 "minimum_spanning_edges",
18 "maximum_spanning_edges",
19 "minimum_spanning_tree",
20 "maximum_spanning_tree",
21 "random_spanning_tree",
22 "partition_spanning_tree",
23 "EdgePartition",
24 "SpanningTreeIterator",
25]
28class EdgePartition(Enum):
29 """
30 An enum to store the state of an edge partition. The enum is written to the
31 edges of a graph before being pasted to `kruskal_mst_edges`. Options are:
33 - EdgePartition.OPEN
34 - EdgePartition.INCLUDED
35 - EdgePartition.EXCLUDED
36 """
38 OPEN = 0
39 INCLUDED = 1
40 EXCLUDED = 2
43@not_implemented_for("multigraph")
44@nx._dispatch(edge_attrs="weight", preserve_edge_attrs="data")
45def boruvka_mst_edges(
46 G, minimum=True, weight="weight", keys=False, data=True, ignore_nan=False
47):
48 """Iterate over edges of a Borůvka's algorithm min/max spanning tree.
50 Parameters
51 ----------
52 G : NetworkX Graph
53 The edges of `G` must have distinct weights,
54 otherwise the edges may not form a tree.
56 minimum : bool (default: True)
57 Find the minimum (True) or maximum (False) spanning tree.
59 weight : string (default: 'weight')
60 The name of the edge attribute holding the edge weights.
62 keys : bool (default: True)
63 This argument is ignored since this function is not
64 implemented for multigraphs; it exists only for consistency
65 with the other minimum spanning tree functions.
67 data : bool (default: True)
68 Flag for whether to yield edge attribute dicts.
69 If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
70 If False, yield edges `(u, v)`.
72 ignore_nan : bool (default: False)
73 If a NaN is found as an edge weight normally an exception is raised.
74 If `ignore_nan is True` then that edge is ignored instead.
76 """
77 # Initialize a forest, assuming initially that it is the discrete
78 # partition of the nodes of the graph.
79 forest = UnionFind(G)
81 def best_edge(component):
82 """Returns the optimum (minimum or maximum) edge on the edge
83 boundary of the given set of nodes.
85 A return value of ``None`` indicates an empty boundary.
87 """
88 sign = 1 if minimum else -1
89 minwt = float("inf")
90 boundary = None
91 for e in nx.edge_boundary(G, component, data=True):
92 wt = e[-1].get(weight, 1) * sign
93 if isnan(wt):
94 if ignore_nan:
95 continue
96 msg = f"NaN found as an edge weight. Edge {e}"
97 raise ValueError(msg)
98 if wt < minwt:
99 minwt = wt
100 boundary = e
101 return boundary
103 # Determine the optimum edge in the edge boundary of each component
104 # in the forest.
105 best_edges = (best_edge(component) for component in forest.to_sets())
106 best_edges = [edge for edge in best_edges if edge is not None]
107 # If each entry was ``None``, that means the graph was disconnected,
108 # so we are done generating the forest.
109 while best_edges:
110 # Determine the optimum edge in the edge boundary of each
111 # component in the forest.
112 #
113 # This must be a sequence, not an iterator. In this list, the
114 # same edge may appear twice, in different orientations (but
115 # that's okay, since a union operation will be called on the
116 # endpoints the first time it is seen, but not the second time).
117 #
118 # Any ``None`` indicates that the edge boundary for that
119 # component was empty, so that part of the forest has been
120 # completed.
121 #
122 # TODO This can be parallelized, both in the outer loop over
123 # each component in the forest and in the computation of the
124 # minimum. (Same goes for the identical lines outside the loop.)
125 best_edges = (best_edge(component) for component in forest.to_sets())
126 best_edges = [edge for edge in best_edges if edge is not None]
127 # Join trees in the forest using the best edges, and yield that
128 # edge, since it is part of the spanning tree.
129 #
130 # TODO This loop can be parallelized, to an extent (the union
131 # operation must be atomic).
132 for u, v, d in best_edges:
133 if forest[u] != forest[v]:
134 if data:
135 yield u, v, d
136 else:
137 yield u, v
138 forest.union(u, v)
141@nx._dispatch(
142 edge_attrs={"weight": None, "partition": None}, preserve_edge_attrs="data"
143)
144def kruskal_mst_edges(
145 G, minimum, weight="weight", keys=True, data=True, ignore_nan=False, partition=None
146):
147 """
148 Iterate over edge of a Kruskal's algorithm min/max spanning tree.
150 Parameters
151 ----------
152 G : NetworkX Graph
153 The graph holding the tree of interest.
155 minimum : bool (default: True)
156 Find the minimum (True) or maximum (False) spanning tree.
158 weight : string (default: 'weight')
159 The name of the edge attribute holding the edge weights.
161 keys : bool (default: True)
162 If `G` is a multigraph, `keys` controls whether edge keys ar yielded.
163 Otherwise `keys` is ignored.
165 data : bool (default: True)
166 Flag for whether to yield edge attribute dicts.
167 If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
168 If False, yield edges `(u, v)`.
170 ignore_nan : bool (default: False)
171 If a NaN is found as an edge weight normally an exception is raised.
172 If `ignore_nan is True` then that edge is ignored instead.
174 partition : string (default: None)
175 The name of the edge attribute holding the partition data, if it exists.
176 Partition data is written to the edges using the `EdgePartition` enum.
177 If a partition exists, all included edges and none of the excluded edges
178 will appear in the final tree. Open edges may or may not be used.
180 Yields
181 ------
182 edge tuple
183 The edges as discovered by Kruskal's method. Each edge can
184 take the following forms: `(u, v)`, `(u, v, d)` or `(u, v, k, d)`
185 depending on the `key` and `data` parameters
186 """
187 subtrees = UnionFind()
188 if G.is_multigraph():
189 edges = G.edges(keys=True, data=True)
190 else:
191 edges = G.edges(data=True)
193 """
194 Sort the edges of the graph with respect to the partition data.
195 Edges are returned in the following order:
197 * Included edges
198 * Open edges from smallest to largest weight
199 * Excluded edges
200 """
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}")
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)
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)
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
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)
254@nx._dispatch(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.
258 Parameters
259 ----------
260 G : NetworkX Graph
261 The graph holding the tree of interest.
263 minimum : bool (default: True)
264 Find the minimum (True) or maximum (False) spanning tree.
266 weight : string (default: 'weight')
267 The name of the edge attribute holding the edge weights.
269 keys : bool (default: True)
270 If `G` is a multigraph, `keys` controls whether edge keys ar yielded.
271 Otherwise `keys` is ignored.
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)`.
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.
282 """
283 is_multigraph = G.is_multigraph()
284 push = heappush
285 pop = heappop
287 nodes = set(G)
288 c = count()
290 sign = 1 if minimum else -1
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 push(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 push(frontier, (wt, next(c), u, v, d))
315 while nodes and frontier:
316 if is_multigraph:
317 W, _, u, v, k, d = pop(frontier)
318 else:
319 W, _, u, v, d = pop(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 push(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 push(frontier, (new_weight, next(c), v, w, d2))
361ALGORITHMS = {
362 "boruvka": boruvka_mst_edges,
363 "borůvka": boruvka_mst_edges,
364 "kruskal": kruskal_mst_edges,
365 "prim": prim_mst_edges,
366}
369@not_implemented_for("directed")
370@nx._dispatch(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.
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.
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.
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'.
391 weight : string
392 Edge data key to use for weight (default 'weight').
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.
398 data : bool, optional
399 If True yield the edge data along with the edge.
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.
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)`
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.
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.
419 Examples
420 --------
421 >>> from networkx.algorithms import tree
423 Find minimum spanning edges by Kruskal's algorithm
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]]
432 Find minimum spanning edges by Prim's algorithm
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]]
441 Notes
442 -----
443 For Borůvka's algorithm, each edge must have a weight attribute, and
444 each edge weight must be distinct.
446 For the other algorithms, if the graph edges do not have a weight
447 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/
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
459 return algo(
460 G, minimum=True, weight=weight, keys=keys, data=data, ignore_nan=ignore_nan
461 )
464@not_implemented_for("directed")
465@nx._dispatch(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.
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.
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.
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'.
486 weight : string
487 Edge data key to use for weight (default 'weight').
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.
493 data : bool, optional
494 If True yield the edge data along with the edge.
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.
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)`
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.
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.
514 Examples
515 --------
516 >>> from networkx.algorithms import tree
518 Find maximum spanning edges by Kruskal's algorithm
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]]
527 Find maximum spanning edges by Prim's algorithm
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]]
536 Notes
537 -----
538 For Borůvka's algorithm, each edge must have a weight attribute, and
539 each edge weight must be distinct.
541 For the other algorithms, if the graph edges do not have a weight
542 attribute a default weight of 1 will be used.
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
553 return algo(
554 G, minimum=False, weight=weight, keys=keys, data=data, ignore_nan=ignore_nan
555 )
558@nx._dispatch(preserve_all_attrs=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`.
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.
568 weight : str
569 Data key to use for edge weights.
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'.
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.
580 Returns
581 -------
582 G : NetworkX Graph
583 A minimum spanning tree or forest.
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, {})]
594 Notes
595 -----
596 For Borůvka's algorithm, each edge must have a weight attribute, and
597 each edge weight must be distinct.
599 For the other algorithms, if the graph edges do not have a weight
600 attribute a default weight of 1 will be used.
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.
605 Isolated nodes with self-loops are in the tree as edgeless isolated nodes.
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
618@nx._dispatch(preserve_all_attrs=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.
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`.
628 This is used in the SpanningTreeIterator to create new partitions following
629 the algorithm of Sörensen and Janssens [1]_.
631 Parameters
632 ----------
633 G : undirected graph
634 An undirected graph.
636 minimum : bool (default: True)
637 Determines whether the returned tree is the minimum spanning tree of
638 the partition of the maximum one.
640 weight : str
641 Data key to use for edge weights.
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.
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.
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.
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
682@nx._dispatch(preserve_all_attrs=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`.
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.
692 weight : str
693 Data key to use for edge weights.
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'.
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.
705 Returns
706 -------
707 G : NetworkX Graph
708 A maximum spanning tree or forest.
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, {})]
720 Notes
721 -----
722 For Borůvka's algorithm, each edge must have a weight attribute, and
723 each edge weight must be distinct.
725 For the other algorithms, if the graph edges do not have a weight
726 attribute a default weight of 1 will be used.
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.
731 Isolated nodes with self-loops are in the tree as edgeless isolated nodes.
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
745@py_random_state(3)
746@nx._dispatch(preserve_edge_attrs=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`.
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.
760 The function uses algorithm A8 in [1]_ .
762 Parameters
763 ----------
764 G : nx.Graph
765 An undirected version of the original graph.
767 weight : string
768 The edge key for the edge attribute holding edge weight.
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.
776 seed : integer, random_state, or None (default)
777 Indicator of random number generation state.
778 See :ref:`Randomness<randomness>`.
780 Returns
781 -------
782 nx.Graph
783 A spanning tree using the distribution defined by the weight of the tree.
785 References
786 ----------
787 .. [1] V. Kulkarni, Generating random combinatorial objects, Journal of
788 Algorithms, 11 (1990), pp. 185–207
789 """
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.
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.
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
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
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`.
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 """
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)
838 # Remove all edges not in V
839 edges_to_remove = set(result.edges()).difference(V)
840 result.remove_edges_from(edges_to_remove)
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 = {}
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
864 return merged_nodes, result
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`.
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.
877 Parameters
878 ----------
879 G : NetworkX Graph
880 The graph to find the total weight of all spanning trees on.
882 weight : string
883 The key for the weight edge attribute of the graph.
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 nx.total_spanning_tree_weight(G, 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 more than two edges in the graph. Then, we can find the
901 # total weight of the spanning trees using the formula in the
902 # reference paper: take the weight of that edge and multiple it by
903 # the number of spanning trees which have to 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 total_spanning_tree_weight with weight=None
908 else:
909 total = 0
910 for u, v, w in G.edges(data=weight):
911 total += w * nx.total_spanning_tree_weight(
912 nx.contracted_edge(G, edge=(u, v), self_loops=False), None
913 )
914 return total
916 U = set()
917 st_cached_value = 0
918 V = set(G.edges())
919 shuffled_edges = list(G.edges())
920 seed.shuffle(shuffled_edges)
922 for u, v in shuffled_edges:
923 e_weight = G[u][v][weight] if weight is not None else 1
924 node_map, prepared_G = prepare_graph()
925 G_total_tree_weight = spanning_tree_total_weight(prepared_G, weight)
926 # Add the edge to U so that we can compute the total tree weight
927 # assuming we include that edge
928 # Now, if (u, v) cannot exist in G because it is fully contracted out
929 # of existence, then it by definition cannot influence G_e's Kirchhoff
930 # value. But, we also cannot pick it.
931 rep_edge = (find_node(node_map, u), find_node(node_map, v))
932 # Check to see if the 'representative edge' for the current edge is
933 # in prepared_G. If so, then we can pick it.
934 if rep_edge in prepared_G.edges:
935 prepared_G_e = nx.contracted_edge(
936 prepared_G, edge=rep_edge, self_loops=False
937 )
938 G_e_total_tree_weight = spanning_tree_total_weight(prepared_G_e, weight)
939 if multiplicative:
940 threshold = e_weight * G_e_total_tree_weight / G_total_tree_weight
941 else:
942 numerator = (
943 st_cached_value + e_weight
944 ) * nx.total_spanning_tree_weight(prepared_G_e) + G_e_total_tree_weight
945 denominator = (
946 st_cached_value * nx.total_spanning_tree_weight(prepared_G)
947 + G_total_tree_weight
948 )
949 threshold = numerator / denominator
950 else:
951 threshold = 0.0
952 z = seed.uniform(0.0, 1.0)
953 if z > threshold:
954 # Remove the edge from V since we did not pick it.
955 V.remove((u, v))
956 else:
957 # Add the edge to U since we picked it.
958 st_cached_value += e_weight
959 U.add((u, v))
960 # If we decide to keep an edge, it may complete the spanning tree.
961 if len(U) == G.number_of_nodes() - 1:
962 spanning_tree = nx.Graph()
963 spanning_tree.add_edges_from(U)
964 return spanning_tree
965 raise Exception(f"Something went wrong! Only {len(U)} edges in the spanning tree!")
968class SpanningTreeIterator:
969 """
970 Iterate over all spanning trees of a graph in either increasing or
971 decreasing cost.
973 Notes
974 -----
975 This iterator uses the partition scheme from [1]_ (included edges,
976 excluded edges and open edges) as well as a modified Kruskal's Algorithm
977 to generate minimum spanning trees which respect the partition of edges.
978 For spanning trees with the same weight, ties are broken arbitrarily.
980 References
981 ----------
982 .. [1] G.K. Janssens, K. Sörensen, An algorithm to generate all spanning
983 trees in order of increasing cost, Pesquisa Operacional, 2005-08,
984 Vol. 25 (2), p. 219-229,
985 https://www.scielo.br/j/pope/a/XHswBwRwJyrfL88dmMwYNWp/?lang=en
986 """
988 @dataclass(order=True)
989 class Partition:
990 """
991 This dataclass represents a partition and stores a dict with the edge
992 data and the weight of the minimum spanning tree of the partition dict.
993 """
995 mst_weight: float
996 partition_dict: dict = field(compare=False)
998 def __copy__(self):
999 return SpanningTreeIterator.Partition(
1000 self.mst_weight, self.partition_dict.copy()
1001 )
1003 def __init__(self, G, weight="weight", minimum=True, ignore_nan=False):
1004 """
1005 Initialize the iterator
1007 Parameters
1008 ----------
1009 G : nx.Graph
1010 The directed graph which we need to iterate trees over
1012 weight : String, default = "weight"
1013 The edge attribute used to store the weight of the edge
1015 minimum : bool, default = True
1016 Return the trees in increasing order while true and decreasing order
1017 while false.
1019 ignore_nan : bool, default = False
1020 If a NaN is found as an edge weight normally an exception is raised.
1021 If `ignore_nan is True` then that edge is ignored instead.
1022 """
1023 self.G = G.copy()
1024 self.weight = weight
1025 self.minimum = minimum
1026 self.ignore_nan = ignore_nan
1027 # Randomly create a key for an edge attribute to hold the partition data
1028 self.partition_key = (
1029 "SpanningTreeIterators super secret partition attribute name"
1030 )
1032 def __iter__(self):
1033 """
1034 Returns
1035 -------
1036 SpanningTreeIterator
1037 The iterator object for this graph
1038 """
1039 self.partition_queue = PriorityQueue()
1040 self._clear_partition(self.G)
1041 mst_weight = partition_spanning_tree(
1042 self.G, self.minimum, self.weight, self.partition_key, self.ignore_nan
1043 ).size(weight=self.weight)
1045 self.partition_queue.put(
1046 self.Partition(mst_weight if self.minimum else -mst_weight, {})
1047 )
1049 return self
1051 def __next__(self):
1052 """
1053 Returns
1054 -------
1055 (multi)Graph
1056 The spanning tree of next greatest weight, which ties broken
1057 arbitrarily.
1058 """
1059 if self.partition_queue.empty():
1060 del self.G, self.partition_queue
1061 raise StopIteration
1063 partition = self.partition_queue.get()
1064 self._write_partition(partition)
1065 next_tree = partition_spanning_tree(
1066 self.G, self.minimum, self.weight, self.partition_key, self.ignore_nan
1067 )
1068 self._partition(partition, next_tree)
1070 self._clear_partition(next_tree)
1071 return next_tree
1073 def _partition(self, partition, partition_tree):
1074 """
1075 Create new partitions based of the minimum spanning tree of the
1076 current minimum partition.
1078 Parameters
1079 ----------
1080 partition : Partition
1081 The Partition instance used to generate the current minimum spanning
1082 tree.
1083 partition_tree : nx.Graph
1084 The minimum spanning tree of the input partition.
1085 """
1086 # create two new partitions with the data from the input partition dict
1087 p1 = self.Partition(0, partition.partition_dict.copy())
1088 p2 = self.Partition(0, partition.partition_dict.copy())
1089 for e in partition_tree.edges:
1090 # determine if the edge was open or included
1091 if e not in partition.partition_dict:
1092 # This is an open edge
1093 p1.partition_dict[e] = EdgePartition.EXCLUDED
1094 p2.partition_dict[e] = EdgePartition.INCLUDED
1096 self._write_partition(p1)
1097 p1_mst = partition_spanning_tree(
1098 self.G,
1099 self.minimum,
1100 self.weight,
1101 self.partition_key,
1102 self.ignore_nan,
1103 )
1104 p1_mst_weight = p1_mst.size(weight=self.weight)
1105 if nx.is_connected(p1_mst):
1106 p1.mst_weight = p1_mst_weight if self.minimum else -p1_mst_weight
1107 self.partition_queue.put(p1.__copy__())
1108 p1.partition_dict = p2.partition_dict.copy()
1110 def _write_partition(self, partition):
1111 """
1112 Writes the desired partition into the graph to calculate the minimum
1113 spanning tree.
1115 Parameters
1116 ----------
1117 partition : Partition
1118 A Partition dataclass describing a partition on the edges of the
1119 graph.
1120 """
1121 for u, v, d in self.G.edges(data=True):
1122 if (u, v) in partition.partition_dict:
1123 d[self.partition_key] = partition.partition_dict[(u, v)]
1124 else:
1125 d[self.partition_key] = EdgePartition.OPEN
1127 def _clear_partition(self, G):
1128 """
1129 Removes partition data from the graph
1130 """
1131 for u, v, d in G.edges(data=True):
1132 if self.partition_key in d:
1133 del d[self.partition_key]