edge_augmentation.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. """
  2. Algorithms for finding k-edge-augmentations
  3. A k-edge-augmentation is a set of edges, that once added to a graph, ensures
  4. that the graph is k-edge-connected; i.e. the graph cannot be disconnected
  5. unless k or more edges are removed. Typically, the goal is to find the
  6. augmentation with minimum weight. In general, it is not guaranteed that a
  7. k-edge-augmentation exists.
  8. See Also
  9. --------
  10. :mod:`edge_kcomponents` : algorithms for finding k-edge-connected components
  11. :mod:`connectivity` : algorithms for determining edge connectivity.
  12. """
  13. import itertools as it
  14. import math
  15. from collections import defaultdict, namedtuple
  16. import networkx as nx
  17. from networkx.utils import not_implemented_for, py_random_state
  18. __all__ = ["k_edge_augmentation", "is_k_edge_connected", "is_locally_k_edge_connected"]
  19. @not_implemented_for("directed")
  20. @not_implemented_for("multigraph")
  21. def is_k_edge_connected(G, k):
  22. """Tests to see if a graph is k-edge-connected.
  23. Is it impossible to disconnect the graph by removing fewer than k edges?
  24. If so, then G is k-edge-connected.
  25. Parameters
  26. ----------
  27. G : NetworkX graph
  28. An undirected graph.
  29. k : integer
  30. edge connectivity to test for
  31. Returns
  32. -------
  33. boolean
  34. True if G is k-edge-connected.
  35. See Also
  36. --------
  37. :func:`is_locally_k_edge_connected`
  38. Examples
  39. --------
  40. >>> G = nx.barbell_graph(10, 0)
  41. >>> nx.is_k_edge_connected(G, k=1)
  42. True
  43. >>> nx.is_k_edge_connected(G, k=2)
  44. False
  45. """
  46. if k < 1:
  47. raise ValueError(f"k must be positive, not {k}")
  48. # First try to quickly determine if G is not k-edge-connected
  49. if G.number_of_nodes() < k + 1:
  50. return False
  51. elif any(d < k for n, d in G.degree()):
  52. return False
  53. else:
  54. # Otherwise perform the full check
  55. if k == 1:
  56. return nx.is_connected(G)
  57. elif k == 2:
  58. return not nx.has_bridges(G)
  59. else:
  60. return nx.edge_connectivity(G, cutoff=k) >= k
  61. @not_implemented_for("directed")
  62. @not_implemented_for("multigraph")
  63. def is_locally_k_edge_connected(G, s, t, k):
  64. """Tests to see if an edge in a graph is locally k-edge-connected.
  65. Is it impossible to disconnect s and t by removing fewer than k edges?
  66. If so, then s and t are locally k-edge-connected in G.
  67. Parameters
  68. ----------
  69. G : NetworkX graph
  70. An undirected graph.
  71. s : node
  72. Source node
  73. t : node
  74. Target node
  75. k : integer
  76. local edge connectivity for nodes s and t
  77. Returns
  78. -------
  79. boolean
  80. True if s and t are locally k-edge-connected in G.
  81. See Also
  82. --------
  83. :func:`is_k_edge_connected`
  84. Examples
  85. --------
  86. >>> from networkx.algorithms.connectivity import is_locally_k_edge_connected
  87. >>> G = nx.barbell_graph(10, 0)
  88. >>> is_locally_k_edge_connected(G, 5, 15, k=1)
  89. True
  90. >>> is_locally_k_edge_connected(G, 5, 15, k=2)
  91. False
  92. >>> is_locally_k_edge_connected(G, 1, 5, k=2)
  93. True
  94. """
  95. if k < 1:
  96. raise ValueError(f"k must be positive, not {k}")
  97. # First try to quickly determine s, t is not k-locally-edge-connected in G
  98. if G.degree(s) < k or G.degree(t) < k:
  99. return False
  100. else:
  101. # Otherwise perform the full check
  102. if k == 1:
  103. return nx.has_path(G, s, t)
  104. else:
  105. localk = nx.connectivity.local_edge_connectivity(G, s, t, cutoff=k)
  106. return localk >= k
  107. @not_implemented_for("directed")
  108. @not_implemented_for("multigraph")
  109. def k_edge_augmentation(G, k, avail=None, weight=None, partial=False):
  110. """Finds set of edges to k-edge-connect G.
  111. Adding edges from the augmentation to G make it impossible to disconnect G
  112. unless k or more edges are removed. This function uses the most efficient
  113. function available (depending on the value of k and if the problem is
  114. weighted or unweighted) to search for a minimum weight subset of available
  115. edges that k-edge-connects G. In general, finding a k-edge-augmentation is
  116. NP-hard, so solutions are not guaranteed to be minimal. Furthermore, a
  117. k-edge-augmentation may not exist.
  118. Parameters
  119. ----------
  120. G : NetworkX graph
  121. An undirected graph.
  122. k : integer
  123. Desired edge connectivity
  124. avail : dict or a set of 2 or 3 tuples
  125. The available edges that can be used in the augmentation.
  126. If unspecified, then all edges in the complement of G are available.
  127. Otherwise, each item is an available edge (with an optional weight).
  128. In the unweighted case, each item is an edge ``(u, v)``.
  129. In the weighted case, each item is a 3-tuple ``(u, v, d)`` or a dict
  130. with items ``(u, v): d``. The third item, ``d``, can be a dictionary
  131. or a real number. If ``d`` is a dictionary ``d[weight]``
  132. correspondings to the weight.
  133. weight : string
  134. key to use to find weights if ``avail`` is a set of 3-tuples where the
  135. third item in each tuple is a dictionary.
  136. partial : boolean
  137. If partial is True and no feasible k-edge-augmentation exists, then all
  138. a partial k-edge-augmentation is generated. Adding the edges in a
  139. partial augmentation to G, minimizes the number of k-edge-connected
  140. components and maximizes the edge connectivity between those
  141. components. For details, see :func:`partial_k_edge_augmentation`.
  142. Yields
  143. ------
  144. edge : tuple
  145. Edges that, once added to G, would cause G to become k-edge-connected.
  146. If partial is False, an error is raised if this is not possible.
  147. Otherwise, generated edges form a partial augmentation, which
  148. k-edge-connects any part of G where it is possible, and maximally
  149. connects the remaining parts.
  150. Raises
  151. ------
  152. NetworkXUnfeasible
  153. If partial is False and no k-edge-augmentation exists.
  154. NetworkXNotImplemented
  155. If the input graph is directed or a multigraph.
  156. ValueError:
  157. If k is less than 1
  158. Notes
  159. -----
  160. When k=1 this returns an optimal solution.
  161. When k=2 and ``avail`` is None, this returns an optimal solution.
  162. Otherwise when k=2, this returns a 2-approximation of the optimal solution.
  163. For k>3, this problem is NP-hard and this uses a randomized algorithm that
  164. produces a feasible solution, but provides no guarantees on the
  165. solution weight.
  166. Examples
  167. --------
  168. >>> # Unweighted cases
  169. >>> G = nx.path_graph((1, 2, 3, 4))
  170. >>> G.add_node(5)
  171. >>> sorted(nx.k_edge_augmentation(G, k=1))
  172. [(1, 5)]
  173. >>> sorted(nx.k_edge_augmentation(G, k=2))
  174. [(1, 5), (5, 4)]
  175. >>> sorted(nx.k_edge_augmentation(G, k=3))
  176. [(1, 4), (1, 5), (2, 5), (3, 5), (4, 5)]
  177. >>> complement = list(nx.k_edge_augmentation(G, k=5, partial=True))
  178. >>> G.add_edges_from(complement)
  179. >>> nx.edge_connectivity(G)
  180. 4
  181. >>> # Weighted cases
  182. >>> G = nx.path_graph((1, 2, 3, 4))
  183. >>> G.add_node(5)
  184. >>> # avail can be a tuple with a dict
  185. >>> avail = [(1, 5, {"weight": 11}), (2, 5, {"weight": 10})]
  186. >>> sorted(nx.k_edge_augmentation(G, k=1, avail=avail, weight="weight"))
  187. [(2, 5)]
  188. >>> # or avail can be a 3-tuple with a real number
  189. >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
  190. >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
  191. [(1, 5), (2, 5), (4, 5)]
  192. >>> # or avail can be a dict
  193. >>> avail = {(1, 5): 11, (2, 5): 10, (4, 3): 1, (4, 5): 51}
  194. >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
  195. [(1, 5), (2, 5), (4, 5)]
  196. >>> # If augmentation is infeasible, then a partial solution can be found
  197. >>> avail = {(1, 5): 11}
  198. >>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail, partial=True))
  199. [(1, 5)]
  200. """
  201. try:
  202. if k <= 0:
  203. raise ValueError(f"k must be a positive integer, not {k}")
  204. elif G.number_of_nodes() < k + 1:
  205. msg = f"impossible to {k} connect in graph with less than {k + 1} nodes"
  206. raise nx.NetworkXUnfeasible(msg)
  207. elif avail is not None and len(avail) == 0:
  208. if not nx.is_k_edge_connected(G, k):
  209. raise nx.NetworkXUnfeasible("no available edges")
  210. aug_edges = []
  211. elif k == 1:
  212. aug_edges = one_edge_augmentation(
  213. G, avail=avail, weight=weight, partial=partial
  214. )
  215. elif k == 2:
  216. aug_edges = bridge_augmentation(G, avail=avail, weight=weight)
  217. else:
  218. # raise NotImplementedError(f'not implemented for k>2. k={k}')
  219. aug_edges = greedy_k_edge_augmentation(
  220. G, k=k, avail=avail, weight=weight, seed=0
  221. )
  222. # Do eager evaluation so we can catch any exceptions
  223. # Before executing partial code.
  224. yield from list(aug_edges)
  225. except nx.NetworkXUnfeasible:
  226. if partial:
  227. # Return all available edges
  228. if avail is None:
  229. aug_edges = complement_edges(G)
  230. else:
  231. # If we can't k-edge-connect the entire graph, try to
  232. # k-edge-connect as much as possible
  233. aug_edges = partial_k_edge_augmentation(
  234. G, k=k, avail=avail, weight=weight
  235. )
  236. yield from aug_edges
  237. else:
  238. raise
  239. def partial_k_edge_augmentation(G, k, avail, weight=None):
  240. """Finds augmentation that k-edge-connects as much of the graph as possible.
  241. When a k-edge-augmentation is not possible, we can still try to find a
  242. small set of edges that partially k-edge-connects as much of the graph as
  243. possible. All possible edges are generated between remaining parts.
  244. This minimizes the number of k-edge-connected subgraphs in the resulting
  245. graph and maxmizes the edge connectivity between those subgraphs.
  246. Parameters
  247. ----------
  248. G : NetworkX graph
  249. An undirected graph.
  250. k : integer
  251. Desired edge connectivity
  252. avail : dict or a set of 2 or 3 tuples
  253. For more details, see :func:`k_edge_augmentation`.
  254. weight : string
  255. key to use to find weights if ``avail`` is a set of 3-tuples.
  256. For more details, see :func:`k_edge_augmentation`.
  257. Yields
  258. ------
  259. edge : tuple
  260. Edges in the partial augmentation of G. These edges k-edge-connect any
  261. part of G where it is possible, and maximally connects the remaining
  262. parts. In other words, all edges from avail are generated except for
  263. those within subgraphs that have already become k-edge-connected.
  264. Notes
  265. -----
  266. Construct H that augments G with all edges in avail.
  267. Find the k-edge-subgraphs of H.
  268. For each k-edge-subgraph, if the number of nodes is more than k, then find
  269. the k-edge-augmentation of that graph and add it to the solution. Then add
  270. all edges in avail between k-edge subgraphs to the solution.
  271. See Also
  272. --------
  273. :func:`k_edge_augmentation`
  274. Examples
  275. --------
  276. >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
  277. >>> G.add_node(8)
  278. >>> avail = [(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5), (1, 8)]
  279. >>> sorted(partial_k_edge_augmentation(G, k=2, avail=avail))
  280. [(1, 5), (1, 8)]
  281. """
  282. def _edges_between_disjoint(H, only1, only2):
  283. """finds edges between disjoint nodes"""
  284. only1_adj = {u: set(H.adj[u]) for u in only1}
  285. for u, neighbs in only1_adj.items():
  286. # Find the neighbors of u in only1 that are also in only2
  287. neighbs12 = neighbs.intersection(only2)
  288. for v in neighbs12:
  289. yield (u, v)
  290. avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
  291. # Find which parts of the graph can be k-edge-connected
  292. H = G.copy()
  293. H.add_edges_from(
  294. (
  295. (u, v, {"weight": w, "generator": (u, v)})
  296. for (u, v), w in zip(avail, avail_w)
  297. )
  298. )
  299. k_edge_subgraphs = list(nx.k_edge_subgraphs(H, k=k))
  300. # Generate edges to k-edge-connect internal subgraphs
  301. for nodes in k_edge_subgraphs:
  302. if len(nodes) > 1:
  303. # Get the k-edge-connected subgraph
  304. C = H.subgraph(nodes).copy()
  305. # Find the internal edges that were available
  306. sub_avail = {
  307. d["generator"]: d["weight"]
  308. for (u, v, d) in C.edges(data=True)
  309. if "generator" in d
  310. }
  311. # Remove potential augmenting edges
  312. C.remove_edges_from(sub_avail.keys())
  313. # Find a subset of these edges that makes the component
  314. # k-edge-connected and ignore the rest
  315. yield from nx.k_edge_augmentation(C, k=k, avail=sub_avail)
  316. # Generate all edges between CCs that could not be k-edge-connected
  317. for cc1, cc2 in it.combinations(k_edge_subgraphs, 2):
  318. for u, v in _edges_between_disjoint(H, cc1, cc2):
  319. d = H.get_edge_data(u, v)
  320. edge = d.get("generator", None)
  321. if edge is not None:
  322. yield edge
  323. @not_implemented_for("multigraph")
  324. @not_implemented_for("directed")
  325. def one_edge_augmentation(G, avail=None, weight=None, partial=False):
  326. """Finds minimum weight set of edges to connect G.
  327. Equivalent to :func:`k_edge_augmentation` when k=1. Adding the resulting
  328. edges to G will make it 1-edge-connected. The solution is optimal for both
  329. weighted and non-weighted variants.
  330. Parameters
  331. ----------
  332. G : NetworkX graph
  333. An undirected graph.
  334. avail : dict or a set of 2 or 3 tuples
  335. For more details, see :func:`k_edge_augmentation`.
  336. weight : string
  337. key to use to find weights if ``avail`` is a set of 3-tuples.
  338. For more details, see :func:`k_edge_augmentation`.
  339. partial : boolean
  340. If partial is True and no feasible k-edge-augmentation exists, then the
  341. augmenting edges minimize the number of connected components.
  342. Yields
  343. ------
  344. edge : tuple
  345. Edges in the one-augmentation of G
  346. Raises
  347. ------
  348. NetworkXUnfeasible
  349. If partial is False and no one-edge-augmentation exists.
  350. Notes
  351. -----
  352. Uses either :func:`unconstrained_one_edge_augmentation` or
  353. :func:`weighted_one_edge_augmentation` depending on whether ``avail`` is
  354. specified. Both algorithms are based on finding a minimum spanning tree.
  355. As such both algorithms find optimal solutions and run in linear time.
  356. See Also
  357. --------
  358. :func:`k_edge_augmentation`
  359. """
  360. if avail is None:
  361. return unconstrained_one_edge_augmentation(G)
  362. else:
  363. return weighted_one_edge_augmentation(
  364. G, avail=avail, weight=weight, partial=partial
  365. )
  366. @not_implemented_for("multigraph")
  367. @not_implemented_for("directed")
  368. def bridge_augmentation(G, avail=None, weight=None):
  369. """Finds the a set of edges that bridge connects G.
  370. Equivalent to :func:`k_edge_augmentation` when k=2, and partial=False.
  371. Adding the resulting edges to G will make it 2-edge-connected. If no
  372. constraints are specified the returned set of edges is minimum an optimal,
  373. otherwise the solution is approximated.
  374. Parameters
  375. ----------
  376. G : NetworkX graph
  377. An undirected graph.
  378. avail : dict or a set of 2 or 3 tuples
  379. For more details, see :func:`k_edge_augmentation`.
  380. weight : string
  381. key to use to find weights if ``avail`` is a set of 3-tuples.
  382. For more details, see :func:`k_edge_augmentation`.
  383. Yields
  384. ------
  385. edge : tuple
  386. Edges in the bridge-augmentation of G
  387. Raises
  388. ------
  389. NetworkXUnfeasible
  390. If no bridge-augmentation exists.
  391. Notes
  392. -----
  393. If there are no constraints the solution can be computed in linear time
  394. using :func:`unconstrained_bridge_augmentation`. Otherwise, the problem
  395. becomes NP-hard and is the solution is approximated by
  396. :func:`weighted_bridge_augmentation`.
  397. See Also
  398. --------
  399. :func:`k_edge_augmentation`
  400. """
  401. if G.number_of_nodes() < 3:
  402. raise nx.NetworkXUnfeasible("impossible to bridge connect less than 3 nodes")
  403. if avail is None:
  404. return unconstrained_bridge_augmentation(G)
  405. else:
  406. return weighted_bridge_augmentation(G, avail, weight=weight)
  407. # --- Algorithms and Helpers ---
  408. def _ordered(u, v):
  409. """Returns the nodes in an undirected edge in lower-triangular order"""
  410. return (u, v) if u < v else (v, u)
  411. def _unpack_available_edges(avail, weight=None, G=None):
  412. """Helper to separate avail into edges and corresponding weights"""
  413. if weight is None:
  414. weight = "weight"
  415. if isinstance(avail, dict):
  416. avail_uv = list(avail.keys())
  417. avail_w = list(avail.values())
  418. else:
  419. def _try_getitem(d):
  420. try:
  421. return d[weight]
  422. except TypeError:
  423. return d
  424. avail_uv = [tup[0:2] for tup in avail]
  425. avail_w = [1 if len(tup) == 2 else _try_getitem(tup[-1]) for tup in avail]
  426. if G is not None:
  427. # Edges already in the graph are filtered
  428. flags = [not G.has_edge(u, v) for u, v in avail_uv]
  429. avail_uv = list(it.compress(avail_uv, flags))
  430. avail_w = list(it.compress(avail_w, flags))
  431. return avail_uv, avail_w
  432. MetaEdge = namedtuple("MetaEdge", ("meta_uv", "uv", "w"))
  433. def _lightest_meta_edges(mapping, avail_uv, avail_w):
  434. """Maps available edges in the original graph to edges in the metagraph.
  435. Parameters
  436. ----------
  437. mapping : dict
  438. mapping produced by :func:`collapse`, that maps each node in the
  439. original graph to a node in the meta graph
  440. avail_uv : list
  441. list of edges
  442. avail_w : list
  443. list of edge weights
  444. Notes
  445. -----
  446. Each node in the metagraph is a k-edge-connected component in the original
  447. graph. We don't care about any edge within the same k-edge-connected
  448. component, so we ignore self edges. We also are only interested in the
  449. minimum weight edge bridging each k-edge-connected component so, we group
  450. the edges by meta-edge and take the lightest in each group.
  451. Examples
  452. --------
  453. >>> # Each group represents a meta-node
  454. >>> groups = ([1, 2, 3], [4, 5], [6])
  455. >>> mapping = {n: meta_n for meta_n, ns in enumerate(groups) for n in ns}
  456. >>> avail_uv = [(1, 2), (3, 6), (1, 4), (5, 2), (6, 1), (2, 6), (3, 1)]
  457. >>> avail_w = [20, 99, 20, 15, 50, 99, 20]
  458. >>> sorted(_lightest_meta_edges(mapping, avail_uv, avail_w))
  459. [MetaEdge(meta_uv=(0, 1), uv=(5, 2), w=15), MetaEdge(meta_uv=(0, 2), uv=(6, 1), w=50)]
  460. """
  461. grouped_wuv = defaultdict(list)
  462. for w, (u, v) in zip(avail_w, avail_uv):
  463. # Order the meta-edge so it can be used as a dict key
  464. meta_uv = _ordered(mapping[u], mapping[v])
  465. # Group each available edge using the meta-edge as a key
  466. grouped_wuv[meta_uv].append((w, u, v))
  467. # Now that all available edges are grouped, choose one per group
  468. for (mu, mv), choices_wuv in grouped_wuv.items():
  469. # Ignore available edges within the same meta-node
  470. if mu != mv:
  471. # Choose the lightest available edge belonging to each meta-edge
  472. w, u, v = min(choices_wuv)
  473. yield MetaEdge((mu, mv), (u, v), w)
  474. def unconstrained_one_edge_augmentation(G):
  475. """Finds the smallest set of edges to connect G.
  476. This is a variant of the unweighted MST problem.
  477. If G is not empty, a feasible solution always exists.
  478. Parameters
  479. ----------
  480. G : NetworkX graph
  481. An undirected graph.
  482. Yields
  483. ------
  484. edge : tuple
  485. Edges in the one-edge-augmentation of G
  486. See Also
  487. --------
  488. :func:`one_edge_augmentation`
  489. :func:`k_edge_augmentation`
  490. Examples
  491. --------
  492. >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
  493. >>> G.add_nodes_from([6, 7, 8])
  494. >>> sorted(unconstrained_one_edge_augmentation(G))
  495. [(1, 4), (4, 6), (6, 7), (7, 8)]
  496. """
  497. ccs1 = list(nx.connected_components(G))
  498. C = collapse(G, ccs1)
  499. # When we are not constrained, we can just make a meta graph tree.
  500. meta_nodes = list(C.nodes())
  501. # build a path in the metagraph
  502. meta_aug = list(zip(meta_nodes, meta_nodes[1:]))
  503. # map that path to the original graph
  504. inverse = defaultdict(list)
  505. for k, v in C.graph["mapping"].items():
  506. inverse[v].append(k)
  507. for mu, mv in meta_aug:
  508. yield (inverse[mu][0], inverse[mv][0])
  509. def weighted_one_edge_augmentation(G, avail, weight=None, partial=False):
  510. """Finds the minimum weight set of edges to connect G if one exists.
  511. This is a variant of the weighted MST problem.
  512. Parameters
  513. ----------
  514. G : NetworkX graph
  515. An undirected graph.
  516. avail : dict or a set of 2 or 3 tuples
  517. For more details, see :func:`k_edge_augmentation`.
  518. weight : string
  519. key to use to find weights if ``avail`` is a set of 3-tuples.
  520. For more details, see :func:`k_edge_augmentation`.
  521. partial : boolean
  522. If partial is True and no feasible k-edge-augmentation exists, then the
  523. augmenting edges minimize the number of connected components.
  524. Yields
  525. ------
  526. edge : tuple
  527. Edges in the subset of avail chosen to connect G.
  528. See Also
  529. --------
  530. :func:`one_edge_augmentation`
  531. :func:`k_edge_augmentation`
  532. Examples
  533. --------
  534. >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
  535. >>> G.add_nodes_from([6, 7, 8])
  536. >>> # any edge not in avail has an implicit weight of infinity
  537. >>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
  538. >>> sorted(weighted_one_edge_augmentation(G, avail))
  539. [(1, 5), (4, 7), (6, 1), (8, 1)]
  540. >>> # find another solution by giving large weights to edges in the
  541. >>> # previous solution (note some of the old edges must be used)
  542. >>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
  543. >>> sorted(weighted_one_edge_augmentation(G, avail))
  544. [(1, 5), (4, 7), (6, 1), (8, 2)]
  545. """
  546. avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
  547. # Collapse CCs in the original graph into nodes in a metagraph
  548. # Then find an MST of the metagraph instead of the original graph
  549. C = collapse(G, nx.connected_components(G))
  550. mapping = C.graph["mapping"]
  551. # Assign each available edge to an edge in the metagraph
  552. candidate_mapping = _lightest_meta_edges(mapping, avail_uv, avail_w)
  553. # nx.set_edge_attributes(C, name='weight', values=0)
  554. C.add_edges_from(
  555. (mu, mv, {"weight": w, "generator": uv})
  556. for (mu, mv), uv, w in candidate_mapping
  557. )
  558. # Find MST of the meta graph
  559. meta_mst = nx.minimum_spanning_tree(C)
  560. if not partial and not nx.is_connected(meta_mst):
  561. raise nx.NetworkXUnfeasible("Not possible to connect G with available edges")
  562. # Yield the edge that generated the meta-edge
  563. for mu, mv, d in meta_mst.edges(data=True):
  564. if "generator" in d:
  565. edge = d["generator"]
  566. yield edge
  567. def unconstrained_bridge_augmentation(G):
  568. """Finds an optimal 2-edge-augmentation of G using the fewest edges.
  569. This is an implementation of the algorithm detailed in [1]_.
  570. The basic idea is to construct a meta-graph of bridge-ccs, connect leaf
  571. nodes of the trees to connect the entire graph, and finally connect the
  572. leafs of the tree in dfs-preorder to bridge connect the entire graph.
  573. Parameters
  574. ----------
  575. G : NetworkX graph
  576. An undirected graph.
  577. Yields
  578. ------
  579. edge : tuple
  580. Edges in the bridge augmentation of G
  581. Notes
  582. -----
  583. Input: a graph G.
  584. First find the bridge components of G and collapse each bridge-cc into a
  585. node of a metagraph graph C, which is guaranteed to be a forest of trees.
  586. C contains p "leafs" --- nodes with exactly one incident edge.
  587. C contains q "isolated nodes" --- nodes with no incident edges.
  588. Theorem: If p + q > 1, then at least :math:`ceil(p / 2) + q` edges are
  589. needed to bridge connect C. This algorithm achieves this min number.
  590. The method first adds enough edges to make G into a tree and then pairs
  591. leafs in a simple fashion.
  592. Let n be the number of trees in C. Let v(i) be an isolated vertex in the
  593. i-th tree if one exists, otherwise it is a pair of distinct leafs nodes
  594. in the i-th tree. Alternating edges from these sets (i.e. adding edges
  595. A1 = [(v(i)[0], v(i + 1)[1]), v(i + 1)[0], v(i + 2)[1])...]) connects C
  596. into a tree T. This tree has p' = p + 2q - 2(n -1) leafs and no isolated
  597. vertices. A1 has n - 1 edges. The next step finds ceil(p' / 2) edges to
  598. biconnect any tree with p' leafs.
  599. Convert T into an arborescence T' by picking an arbitrary root node with
  600. degree >= 2 and directing all edges away from the root. Note the
  601. implementation implicitly constructs T'.
  602. The leafs of T are the nodes with no existing edges in T'.
  603. Order the leafs of T' by DFS prorder. Then break this list in half
  604. and add the zipped pairs to A2.
  605. The set A = A1 + A2 is the minimum augmentation in the metagraph.
  606. To convert this to edges in the original graph
  607. References
  608. ----------
  609. .. [1] Eswaran, Kapali P., and R. Endre Tarjan. (1975) Augmentation problems.
  610. http://epubs.siam.org/doi/abs/10.1137/0205044
  611. See Also
  612. --------
  613. :func:`bridge_augmentation`
  614. :func:`k_edge_augmentation`
  615. Examples
  616. --------
  617. >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
  618. >>> sorted(unconstrained_bridge_augmentation(G))
  619. [(1, 7)]
  620. >>> G = nx.path_graph((1, 2, 3, 2, 4, 5, 6, 7))
  621. >>> sorted(unconstrained_bridge_augmentation(G))
  622. [(1, 3), (3, 7)]
  623. >>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
  624. >>> G.add_node(4)
  625. >>> sorted(unconstrained_bridge_augmentation(G))
  626. [(1, 4), (4, 0)]
  627. """
  628. # -----
  629. # Mapping of terms from (Eswaran and Tarjan):
  630. # G = G_0 - the input graph
  631. # C = G_0' - the bridge condensation of G. (This is a forest of trees)
  632. # A1 = A_1 - the edges to connect the forest into a tree
  633. # leaf = pendant - a node with degree of 1
  634. # alpha(v) = maps the node v in G to its meta-node in C
  635. # beta(x) = maps the meta-node x in C to any node in the bridge
  636. # component of G corresponding to x.
  637. # find the 2-edge-connected components of G
  638. bridge_ccs = list(nx.connectivity.bridge_components(G))
  639. # condense G into an forest C
  640. C = collapse(G, bridge_ccs)
  641. # Choose pairs of distinct leaf nodes in each tree. If this is not
  642. # possible then make a pair using the single isolated node in the tree.
  643. vset1 = [
  644. tuple(cc) * 2 # case1: an isolated node
  645. if len(cc) == 1
  646. else sorted(cc, key=C.degree)[0:2] # case2: pair of leaf nodes
  647. for cc in nx.connected_components(C)
  648. ]
  649. if len(vset1) > 1:
  650. # Use this set to construct edges that connect C into a tree.
  651. nodes1 = [vs[0] for vs in vset1]
  652. nodes2 = [vs[1] for vs in vset1]
  653. A1 = list(zip(nodes1[1:], nodes2))
  654. else:
  655. A1 = []
  656. # Connect each tree in the forest to construct an arborescence
  657. T = C.copy()
  658. T.add_edges_from(A1)
  659. # If there are only two leaf nodes, we simply connect them.
  660. leafs = [n for n, d in T.degree() if d == 1]
  661. if len(leafs) == 1:
  662. A2 = []
  663. if len(leafs) == 2:
  664. A2 = [tuple(leafs)]
  665. else:
  666. # Choose an arbitrary non-leaf root
  667. try:
  668. root = next(n for n, d in T.degree() if d > 1)
  669. except StopIteration: # no nodes found with degree > 1
  670. return
  671. # order the leaves of C by (induced directed) preorder
  672. v2 = [n for n in nx.dfs_preorder_nodes(T, root) if T.degree(n) == 1]
  673. # connecting first half of the leafs in pre-order to the second
  674. # half will bridge connect the tree with the fewest edges.
  675. half = math.ceil(len(v2) / 2)
  676. A2 = list(zip(v2[:half], v2[-half:]))
  677. # collect the edges used to augment the original forest
  678. aug_tree_edges = A1 + A2
  679. # Construct the mapping (beta) from meta-nodes to regular nodes
  680. inverse = defaultdict(list)
  681. for k, v in C.graph["mapping"].items():
  682. inverse[v].append(k)
  683. # sort so we choose minimum degree nodes first
  684. inverse = {
  685. mu: sorted(mapped, key=lambda u: (G.degree(u), u))
  686. for mu, mapped in inverse.items()
  687. }
  688. # For each meta-edge, map back to an arbitrary pair in the original graph
  689. G2 = G.copy()
  690. for mu, mv in aug_tree_edges:
  691. # Find the first available edge that doesn't exist and return it
  692. for u, v in it.product(inverse[mu], inverse[mv]):
  693. if not G2.has_edge(u, v):
  694. G2.add_edge(u, v)
  695. yield u, v
  696. break
  697. def weighted_bridge_augmentation(G, avail, weight=None):
  698. """Finds an approximate min-weight 2-edge-augmentation of G.
  699. This is an implementation of the approximation algorithm detailed in [1]_.
  700. It chooses a set of edges from avail to add to G that renders it
  701. 2-edge-connected if such a subset exists. This is done by finding a
  702. minimum spanning arborescence of a specially constructed metagraph.
  703. Parameters
  704. ----------
  705. G : NetworkX graph
  706. An undirected graph.
  707. avail : set of 2 or 3 tuples.
  708. candidate edges (with optional weights) to choose from
  709. weight : string
  710. key to use to find weights if avail is a set of 3-tuples where the
  711. third item in each tuple is a dictionary.
  712. Yields
  713. ------
  714. edge : tuple
  715. Edges in the subset of avail chosen to bridge augment G.
  716. Notes
  717. -----
  718. Finding a weighted 2-edge-augmentation is NP-hard.
  719. Any edge not in ``avail`` is considered to have a weight of infinity.
  720. The approximation factor is 2 if ``G`` is connected and 3 if it is not.
  721. Runs in :math:`O(m + n log(n))` time
  722. References
  723. ----------
  724. .. [1] Khuller, Samir, and Ramakrishna Thurimella. (1993) Approximation
  725. algorithms for graph augmentation.
  726. http://www.sciencedirect.com/science/article/pii/S0196677483710102
  727. See Also
  728. --------
  729. :func:`bridge_augmentation`
  730. :func:`k_edge_augmentation`
  731. Examples
  732. --------
  733. >>> G = nx.path_graph((1, 2, 3, 4))
  734. >>> # When the weights are equal, (1, 4) is the best
  735. >>> avail = [(1, 4, 1), (1, 3, 1), (2, 4, 1)]
  736. >>> sorted(weighted_bridge_augmentation(G, avail))
  737. [(1, 4)]
  738. >>> # Giving (1, 4) a high weight makes the two edge solution the best.
  739. >>> avail = [(1, 4, 1000), (1, 3, 1), (2, 4, 1)]
  740. >>> sorted(weighted_bridge_augmentation(G, avail))
  741. [(1, 3), (2, 4)]
  742. >>> # ------
  743. >>> G = nx.path_graph((1, 2, 3, 4))
  744. >>> G.add_node(5)
  745. >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 1)]
  746. >>> sorted(weighted_bridge_augmentation(G, avail=avail))
  747. [(1, 5), (4, 5)]
  748. >>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
  749. >>> sorted(weighted_bridge_augmentation(G, avail=avail))
  750. [(1, 5), (2, 5), (4, 5)]
  751. """
  752. if weight is None:
  753. weight = "weight"
  754. # If input G is not connected the approximation factor increases to 3
  755. if not nx.is_connected(G):
  756. H = G.copy()
  757. connectors = list(one_edge_augmentation(H, avail=avail, weight=weight))
  758. H.add_edges_from(connectors)
  759. yield from connectors
  760. else:
  761. connectors = []
  762. H = G
  763. if len(avail) == 0:
  764. if nx.has_bridges(H):
  765. raise nx.NetworkXUnfeasible("no augmentation possible")
  766. avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=H)
  767. # Collapse input into a metagraph. Meta nodes are bridge-ccs
  768. bridge_ccs = nx.connectivity.bridge_components(H)
  769. C = collapse(H, bridge_ccs)
  770. # Use the meta graph to shrink avail to a small feasible subset
  771. mapping = C.graph["mapping"]
  772. # Choose the minimum weight feasible edge in each group
  773. meta_to_wuv = {
  774. (mu, mv): (w, uv)
  775. for (mu, mv), uv, w in _lightest_meta_edges(mapping, avail_uv, avail_w)
  776. }
  777. # Mapping of terms from (Khuller and Thurimella):
  778. # C : G_0 = (V, E^0)
  779. # This is the metagraph where each node is a 2-edge-cc in G.
  780. # The edges in C represent bridges in the original graph.
  781. # (mu, mv) : E - E^0 # they group both avail and given edges in E
  782. # T : \Gamma
  783. # D : G^D = (V, E_D)
  784. # The paper uses ancestor because children point to parents, which is
  785. # contrary to networkx standards. So, we actually need to run
  786. # nx.least_common_ancestor on the reversed Tree.
  787. # Pick an arbitrary leaf from C as the root
  788. try:
  789. root = next(n for n, d in C.degree() if d == 1)
  790. except StopIteration: # no nodes found with degree == 1
  791. return
  792. # Root C into a tree TR by directing all edges away from the root
  793. # Note in their paper T directs edges towards the root
  794. TR = nx.dfs_tree(C, root)
  795. # Add to D the directed edges of T and set their weight to zero
  796. # This indicates that it costs nothing to use edges that were given.
  797. D = nx.reverse(TR).copy()
  798. nx.set_edge_attributes(D, name="weight", values=0)
  799. # The LCA of mu and mv in T is the shared ancestor of mu and mv that is
  800. # located farthest from the root.
  801. lca_gen = nx.tree_all_pairs_lowest_common_ancestor(
  802. TR, root=root, pairs=meta_to_wuv.keys()
  803. )
  804. for (mu, mv), lca in lca_gen:
  805. w, uv = meta_to_wuv[(mu, mv)]
  806. if lca == mu:
  807. # If u is an ancestor of v in TR, then add edge u->v to D
  808. D.add_edge(lca, mv, weight=w, generator=uv)
  809. elif lca == mv:
  810. # If v is an ancestor of u in TR, then add edge v->u to D
  811. D.add_edge(lca, mu, weight=w, generator=uv)
  812. else:
  813. # If neither u nor v is a ancestor of the other in TR
  814. # let t = lca(TR, u, v) and add edges t->u and t->v
  815. # Track the original edge that GENERATED these edges.
  816. D.add_edge(lca, mu, weight=w, generator=uv)
  817. D.add_edge(lca, mv, weight=w, generator=uv)
  818. # Then compute a minimum rooted branching
  819. try:
  820. # Note the original edges must be directed towards to root for the
  821. # branching to give us a bridge-augmentation.
  822. A = _minimum_rooted_branching(D, root)
  823. except nx.NetworkXException as err:
  824. # If there is no branching then augmentation is not possible
  825. raise nx.NetworkXUnfeasible("no 2-edge-augmentation possible") from err
  826. # For each edge e, in the branching that did not belong to the directed
  827. # tree T, add the corresponding edge that **GENERATED** it (this is not
  828. # necesarilly e itself!)
  829. # ensure the third case does not generate edges twice
  830. bridge_connectors = set()
  831. for mu, mv in A.edges():
  832. data = D.get_edge_data(mu, mv)
  833. if "generator" in data:
  834. # Add the avail edge that generated the branching edge.
  835. edge = data["generator"]
  836. bridge_connectors.add(edge)
  837. yield from bridge_connectors
  838. def _minimum_rooted_branching(D, root):
  839. """Helper function to compute a minimum rooted branching (aka rooted
  840. arborescence)
  841. Before the branching can be computed, the directed graph must be rooted by
  842. removing the predecessors of root.
  843. A branching / arborescence of rooted graph G is a subgraph that contains a
  844. directed path from the root to every other vertex. It is the directed
  845. analog of the minimum spanning tree problem.
  846. References
  847. ----------
  848. [1] Khuller, Samir (2002) Advanced Algorithms Lecture 24 Notes.
  849. https://web.archive.org/web/20121030033722/https://www.cs.umd.edu/class/spring2011/cmsc651/lec07.pdf
  850. """
  851. rooted = D.copy()
  852. # root the graph by removing all predecessors to `root`.
  853. rooted.remove_edges_from([(u, root) for u in D.predecessors(root)])
  854. # Then compute the branching / arborescence.
  855. A = nx.minimum_spanning_arborescence(rooted)
  856. return A
  857. def collapse(G, grouped_nodes):
  858. """Collapses each group of nodes into a single node.
  859. This is similar to condensation, but works on undirected graphs.
  860. Parameters
  861. ----------
  862. G : NetworkX Graph
  863. grouped_nodes: list or generator
  864. Grouping of nodes to collapse. The grouping must be disjoint.
  865. If grouped_nodes are strongly_connected_components then this is
  866. equivalent to :func:`condensation`.
  867. Returns
  868. -------
  869. C : NetworkX Graph
  870. The collapsed graph C of G with respect to the node grouping. The node
  871. labels are integers corresponding to the index of the component in the
  872. list of grouped_nodes. C has a graph attribute named 'mapping' with a
  873. dictionary mapping the original nodes to the nodes in C to which they
  874. belong. Each node in C also has a node attribute 'members' with the set
  875. of original nodes in G that form the group that the node in C
  876. represents.
  877. Examples
  878. --------
  879. >>> # Collapses a graph using disjoint groups, but not necesarilly connected
  880. >>> G = nx.Graph([(1, 0), (2, 3), (3, 1), (3, 4), (4, 5), (5, 6), (5, 7)])
  881. >>> G.add_node("A")
  882. >>> grouped_nodes = [{0, 1, 2, 3}, {5, 6, 7}]
  883. >>> C = collapse(G, grouped_nodes)
  884. >>> members = nx.get_node_attributes(C, "members")
  885. >>> sorted(members.keys())
  886. [0, 1, 2, 3]
  887. >>> member_values = set(map(frozenset, members.values()))
  888. >>> assert {0, 1, 2, 3} in member_values
  889. >>> assert {4} in member_values
  890. >>> assert {5, 6, 7} in member_values
  891. >>> assert {"A"} in member_values
  892. """
  893. mapping = {}
  894. members = {}
  895. C = G.__class__()
  896. i = 0 # required if G is empty
  897. remaining = set(G.nodes())
  898. for i, group in enumerate(grouped_nodes):
  899. group = set(group)
  900. assert remaining.issuperset(
  901. group
  902. ), "grouped nodes must exist in G and be disjoint"
  903. remaining.difference_update(group)
  904. members[i] = group
  905. mapping.update((n, i) for n in group)
  906. # remaining nodes are in their own group
  907. for i, node in enumerate(remaining, start=i + 1):
  908. group = {node}
  909. members[i] = group
  910. mapping.update((n, i) for n in group)
  911. number_of_groups = i + 1
  912. C.add_nodes_from(range(number_of_groups))
  913. C.add_edges_from(
  914. (mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]
  915. )
  916. # Add a list of members (ie original nodes) to each node (ie scc) in C.
  917. nx.set_node_attributes(C, name="members", values=members)
  918. # Add mapping dict as graph attribute
  919. C.graph["mapping"] = mapping
  920. return C
  921. def complement_edges(G):
  922. """Returns only the edges in the complement of G
  923. Parameters
  924. ----------
  925. G : NetworkX Graph
  926. Yields
  927. ------
  928. edge : tuple
  929. Edges in the complement of G
  930. Examples
  931. --------
  932. >>> G = nx.path_graph((1, 2, 3, 4))
  933. >>> sorted(complement_edges(G))
  934. [(1, 3), (1, 4), (2, 4)]
  935. >>> G = nx.path_graph((1, 2, 3, 4), nx.DiGraph())
  936. >>> sorted(complement_edges(G))
  937. [(1, 3), (1, 4), (2, 1), (2, 4), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
  938. >>> G = nx.complete_graph(1000)
  939. >>> sorted(complement_edges(G))
  940. []
  941. """
  942. G_adj = G._adj # Store as a variable to eliminate attribute lookup
  943. if G.is_directed():
  944. for u, v in it.combinations(G.nodes(), 2):
  945. if v not in G_adj[u]:
  946. yield (u, v)
  947. if u not in G_adj[v]:
  948. yield (v, u)
  949. else:
  950. for u, v in it.combinations(G.nodes(), 2):
  951. if v not in G_adj[u]:
  952. yield (u, v)
  953. def _compat_shuffle(rng, input):
  954. """wrapper around rng.shuffle for python 2 compatibility reasons"""
  955. rng.shuffle(input)
  956. @py_random_state(4)
  957. @not_implemented_for("multigraph")
  958. @not_implemented_for("directed")
  959. def greedy_k_edge_augmentation(G, k, avail=None, weight=None, seed=None):
  960. """Greedy algorithm for finding a k-edge-augmentation
  961. Parameters
  962. ----------
  963. G : NetworkX graph
  964. An undirected graph.
  965. k : integer
  966. Desired edge connectivity
  967. avail : dict or a set of 2 or 3 tuples
  968. For more details, see :func:`k_edge_augmentation`.
  969. weight : string
  970. key to use to find weights if ``avail`` is a set of 3-tuples.
  971. For more details, see :func:`k_edge_augmentation`.
  972. seed : integer, random_state, or None (default)
  973. Indicator of random number generation state.
  974. See :ref:`Randomness<randomness>`.
  975. Yields
  976. ------
  977. edge : tuple
  978. Edges in the greedy augmentation of G
  979. Notes
  980. -----
  981. The algorithm is simple. Edges are incrementally added between parts of the
  982. graph that are not yet locally k-edge-connected. Then edges are from the
  983. augmenting set are pruned as long as local-edge-connectivity is not broken.
  984. This algorithm is greedy and does not provide optimality guarantees. It
  985. exists only to provide :func:`k_edge_augmentation` with the ability to
  986. generate a feasible solution for arbitrary k.
  987. See Also
  988. --------
  989. :func:`k_edge_augmentation`
  990. Examples
  991. --------
  992. >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
  993. >>> sorted(greedy_k_edge_augmentation(G, k=2))
  994. [(1, 7)]
  995. >>> sorted(greedy_k_edge_augmentation(G, k=1, avail=[]))
  996. []
  997. >>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
  998. >>> avail = {(u, v): 1 for (u, v) in complement_edges(G)}
  999. >>> # randomized pruning process can produce different solutions
  1000. >>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=2))
  1001. [(1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 6), (3, 7), (5, 7)]
  1002. >>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=3))
  1003. [(1, 3), (1, 5), (1, 6), (2, 4), (2, 6), (3, 7), (4, 7), (5, 7)]
  1004. """
  1005. # Result set
  1006. aug_edges = []
  1007. done = is_k_edge_connected(G, k)
  1008. if done:
  1009. return
  1010. if avail is None:
  1011. # all edges are available
  1012. avail_uv = list(complement_edges(G))
  1013. avail_w = [1] * len(avail_uv)
  1014. else:
  1015. # Get the unique set of unweighted edges
  1016. avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
  1017. # Greedy: order lightest edges. Use degree sum to tie-break
  1018. tiebreaker = [sum(map(G.degree, uv)) for uv in avail_uv]
  1019. avail_wduv = sorted(zip(avail_w, tiebreaker, avail_uv))
  1020. avail_uv = [uv for w, d, uv in avail_wduv]
  1021. # Incrementally add edges in until we are k-connected
  1022. H = G.copy()
  1023. for u, v in avail_uv:
  1024. done = False
  1025. if not is_locally_k_edge_connected(H, u, v, k=k):
  1026. # Only add edges in parts that are not yet locally k-edge-connected
  1027. aug_edges.append((u, v))
  1028. H.add_edge(u, v)
  1029. # Did adding this edge help?
  1030. if H.degree(u) >= k and H.degree(v) >= k:
  1031. done = is_k_edge_connected(H, k)
  1032. if done:
  1033. break
  1034. # Check for feasibility
  1035. if not done:
  1036. raise nx.NetworkXUnfeasible("not able to k-edge-connect with available edges")
  1037. # Randomized attempt to reduce the size of the solution
  1038. _compat_shuffle(seed, aug_edges)
  1039. for u, v in list(aug_edges):
  1040. # Don't remove if we know it would break connectivity
  1041. if H.degree(u) <= k or H.degree(v) <= k:
  1042. continue
  1043. H.remove_edge(u, v)
  1044. aug_edges.remove((u, v))
  1045. if not is_k_edge_connected(H, k=k):
  1046. # If removing this edge breaks feasibility, undo
  1047. H.add_edge(u, v)
  1048. aug_edges.append((u, v))
  1049. # Generate results
  1050. yield from aug_edges