euler.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. """
  2. Eulerian circuits and graphs.
  3. """
  4. from itertools import combinations
  5. import networkx as nx
  6. from ..utils import arbitrary_element, not_implemented_for
  7. __all__ = [
  8. "is_eulerian",
  9. "eulerian_circuit",
  10. "eulerize",
  11. "is_semieulerian",
  12. "has_eulerian_path",
  13. "eulerian_path",
  14. ]
  15. def is_eulerian(G):
  16. """Returns True if and only if `G` is Eulerian.
  17. A graph is *Eulerian* if it has an Eulerian circuit. An *Eulerian
  18. circuit* is a closed walk that includes each edge of a graph exactly
  19. once.
  20. Graphs with isolated vertices (i.e. vertices with zero degree) are not
  21. considered to have Eulerian circuits. Therefore, if the graph is not
  22. connected (or not strongly connected, for directed graphs), this function
  23. returns False.
  24. Parameters
  25. ----------
  26. G : NetworkX graph
  27. A graph, either directed or undirected.
  28. Examples
  29. --------
  30. >>> nx.is_eulerian(nx.DiGraph({0: [3], 1: [2], 2: [3], 3: [0, 1]}))
  31. True
  32. >>> nx.is_eulerian(nx.complete_graph(5))
  33. True
  34. >>> nx.is_eulerian(nx.petersen_graph())
  35. False
  36. If you prefer to allow graphs with isolated vertices to have Eulerian circuits,
  37. you can first remove such vertices and then call `is_eulerian` as below example shows.
  38. >>> G = nx.Graph([(0, 1), (1, 2), (0, 2)])
  39. >>> G.add_node(3)
  40. >>> nx.is_eulerian(G)
  41. False
  42. >>> G.remove_nodes_from(list(nx.isolates(G)))
  43. >>> nx.is_eulerian(G)
  44. True
  45. """
  46. if G.is_directed():
  47. # Every node must have equal in degree and out degree and the
  48. # graph must be strongly connected
  49. return all(
  50. G.in_degree(n) == G.out_degree(n) for n in G
  51. ) and nx.is_strongly_connected(G)
  52. # An undirected Eulerian graph has no vertices of odd degree and
  53. # must be connected.
  54. return all(d % 2 == 0 for v, d in G.degree()) and nx.is_connected(G)
  55. def is_semieulerian(G):
  56. """Return True iff `G` is semi-Eulerian.
  57. G is semi-Eulerian if it has an Eulerian path but no Eulerian circuit.
  58. See Also
  59. --------
  60. has_eulerian_path
  61. is_eulerian
  62. """
  63. return has_eulerian_path(G) and not is_eulerian(G)
  64. def _find_path_start(G):
  65. """Return a suitable starting vertex for an Eulerian path.
  66. If no path exists, return None.
  67. """
  68. if not has_eulerian_path(G):
  69. return None
  70. if is_eulerian(G):
  71. return arbitrary_element(G)
  72. if G.is_directed():
  73. v1, v2 = (v for v in G if G.in_degree(v) != G.out_degree(v))
  74. # Determines which is the 'start' node (as opposed to the 'end')
  75. if G.out_degree(v1) > G.in_degree(v1):
  76. return v1
  77. else:
  78. return v2
  79. else:
  80. # In an undirected graph randomly choose one of the possibilities
  81. start = [v for v in G if G.degree(v) % 2 != 0][0]
  82. return start
  83. def _simplegraph_eulerian_circuit(G, source):
  84. if G.is_directed():
  85. degree = G.out_degree
  86. edges = G.out_edges
  87. else:
  88. degree = G.degree
  89. edges = G.edges
  90. vertex_stack = [source]
  91. last_vertex = None
  92. while vertex_stack:
  93. current_vertex = vertex_stack[-1]
  94. if degree(current_vertex) == 0:
  95. if last_vertex is not None:
  96. yield (last_vertex, current_vertex)
  97. last_vertex = current_vertex
  98. vertex_stack.pop()
  99. else:
  100. _, next_vertex = arbitrary_element(edges(current_vertex))
  101. vertex_stack.append(next_vertex)
  102. G.remove_edge(current_vertex, next_vertex)
  103. def _multigraph_eulerian_circuit(G, source):
  104. if G.is_directed():
  105. degree = G.out_degree
  106. edges = G.out_edges
  107. else:
  108. degree = G.degree
  109. edges = G.edges
  110. vertex_stack = [(source, None)]
  111. last_vertex = None
  112. last_key = None
  113. while vertex_stack:
  114. current_vertex, current_key = vertex_stack[-1]
  115. if degree(current_vertex) == 0:
  116. if last_vertex is not None:
  117. yield (last_vertex, current_vertex, last_key)
  118. last_vertex, last_key = current_vertex, current_key
  119. vertex_stack.pop()
  120. else:
  121. triple = arbitrary_element(edges(current_vertex, keys=True))
  122. _, next_vertex, next_key = triple
  123. vertex_stack.append((next_vertex, next_key))
  124. G.remove_edge(current_vertex, next_vertex, next_key)
  125. def eulerian_circuit(G, source=None, keys=False):
  126. """Returns an iterator over the edges of an Eulerian circuit in `G`.
  127. An *Eulerian circuit* is a closed walk that includes each edge of a
  128. graph exactly once.
  129. Parameters
  130. ----------
  131. G : NetworkX graph
  132. A graph, either directed or undirected.
  133. source : node, optional
  134. Starting node for circuit.
  135. keys : bool
  136. If False, edges generated by this function will be of the form
  137. ``(u, v)``. Otherwise, edges will be of the form ``(u, v, k)``.
  138. This option is ignored unless `G` is a multigraph.
  139. Returns
  140. -------
  141. edges : iterator
  142. An iterator over edges in the Eulerian circuit.
  143. Raises
  144. ------
  145. NetworkXError
  146. If the graph is not Eulerian.
  147. See Also
  148. --------
  149. is_eulerian
  150. Notes
  151. -----
  152. This is a linear time implementation of an algorithm adapted from [1]_.
  153. For general information about Euler tours, see [2]_.
  154. References
  155. ----------
  156. .. [1] J. Edmonds, E. L. Johnson.
  157. Matching, Euler tours and the Chinese postman.
  158. Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
  159. .. [2] https://en.wikipedia.org/wiki/Eulerian_path
  160. Examples
  161. --------
  162. To get an Eulerian circuit in an undirected graph::
  163. >>> G = nx.complete_graph(3)
  164. >>> list(nx.eulerian_circuit(G))
  165. [(0, 2), (2, 1), (1, 0)]
  166. >>> list(nx.eulerian_circuit(G, source=1))
  167. [(1, 2), (2, 0), (0, 1)]
  168. To get the sequence of vertices in an Eulerian circuit::
  169. >>> [u for u, v in nx.eulerian_circuit(G)]
  170. [0, 2, 1]
  171. """
  172. if not is_eulerian(G):
  173. raise nx.NetworkXError("G is not Eulerian.")
  174. if G.is_directed():
  175. G = G.reverse()
  176. else:
  177. G = G.copy()
  178. if source is None:
  179. source = arbitrary_element(G)
  180. if G.is_multigraph():
  181. for u, v, k in _multigraph_eulerian_circuit(G, source):
  182. if keys:
  183. yield u, v, k
  184. else:
  185. yield u, v
  186. else:
  187. yield from _simplegraph_eulerian_circuit(G, source)
  188. def has_eulerian_path(G, source=None):
  189. """Return True iff `G` has an Eulerian path.
  190. An Eulerian path is a path in a graph which uses each edge of a graph
  191. exactly once. If `source` is specified, then this function checks
  192. whether an Eulerian path that starts at node `source` exists.
  193. A directed graph has an Eulerian path iff:
  194. - at most one vertex has out_degree - in_degree = 1,
  195. - at most one vertex has in_degree - out_degree = 1,
  196. - every other vertex has equal in_degree and out_degree,
  197. - and all of its vertices belong to a single connected
  198. component of the underlying undirected graph.
  199. If `source` is not None, an Eulerian path starting at `source` exists if no
  200. other node has out_degree - in_degree = 1. This is equivalent to either
  201. there exists an Eulerian circuit or `source` has out_degree - in_degree = 1
  202. and the conditions above hold.
  203. An undirected graph has an Eulerian path iff:
  204. - exactly zero or two vertices have odd degree,
  205. - and all of its vertices belong to a single connected component.
  206. If `source` is not None, an Eulerian path starting at `source` exists if
  207. either there exists an Eulerian circuit or `source` has an odd degree and the
  208. conditions above hold.
  209. Graphs with isolated vertices (i.e. vertices with zero degree) are not considered
  210. to have an Eulerian path. Therefore, if the graph is not connected (or not strongly
  211. connected, for directed graphs), this function returns False.
  212. Parameters
  213. ----------
  214. G : NetworkX Graph
  215. The graph to find an euler path in.
  216. source : node, optional
  217. Starting node for path.
  218. Returns
  219. -------
  220. Bool : True if G has an Eulerian path.
  221. Examples
  222. --------
  223. If you prefer to allow graphs with isolated vertices to have Eulerian path,
  224. you can first remove such vertices and then call `has_eulerian_path` as below example shows.
  225. >>> G = nx.Graph([(0, 1), (1, 2), (0, 2)])
  226. >>> G.add_node(3)
  227. >>> nx.has_eulerian_path(G)
  228. False
  229. >>> G.remove_nodes_from(list(nx.isolates(G)))
  230. >>> nx.has_eulerian_path(G)
  231. True
  232. See Also
  233. --------
  234. is_eulerian
  235. eulerian_path
  236. """
  237. if nx.is_eulerian(G):
  238. return True
  239. if G.is_directed():
  240. ins = G.in_degree
  241. outs = G.out_degree
  242. # Since we know it is not eulerian, outs - ins must be 1 for source
  243. if source is not None and outs[source] - ins[source] != 1:
  244. return False
  245. unbalanced_ins = 0
  246. unbalanced_outs = 0
  247. for v in G:
  248. if ins[v] - outs[v] == 1:
  249. unbalanced_ins += 1
  250. elif outs[v] - ins[v] == 1:
  251. unbalanced_outs += 1
  252. elif ins[v] != outs[v]:
  253. return False
  254. return (
  255. unbalanced_ins <= 1 and unbalanced_outs <= 1 and nx.is_weakly_connected(G)
  256. )
  257. else:
  258. # We know it is not eulerian, so degree of source must be odd.
  259. if source is not None and G.degree[source] % 2 != 1:
  260. return False
  261. # Sum is 2 since we know it is not eulerian (which implies sum is 0)
  262. return sum(d % 2 == 1 for v, d in G.degree()) == 2 and nx.is_connected(G)
  263. def eulerian_path(G, source=None, keys=False):
  264. """Return an iterator over the edges of an Eulerian path in `G`.
  265. Parameters
  266. ----------
  267. G : NetworkX Graph
  268. The graph in which to look for an eulerian path.
  269. source : node or None (default: None)
  270. The node at which to start the search. None means search over all
  271. starting nodes.
  272. keys : Bool (default: False)
  273. Indicates whether to yield edge 3-tuples (u, v, edge_key).
  274. The default yields edge 2-tuples
  275. Yields
  276. ------
  277. Edge tuples along the eulerian path.
  278. Warning: If `source` provided is not the start node of an Euler path
  279. will raise error even if an Euler Path exists.
  280. """
  281. if not has_eulerian_path(G, source):
  282. raise nx.NetworkXError("Graph has no Eulerian paths.")
  283. if G.is_directed():
  284. G = G.reverse()
  285. if source is None or nx.is_eulerian(G) is False:
  286. source = _find_path_start(G)
  287. if G.is_multigraph():
  288. for u, v, k in _multigraph_eulerian_circuit(G, source):
  289. if keys:
  290. yield u, v, k
  291. else:
  292. yield u, v
  293. else:
  294. yield from _simplegraph_eulerian_circuit(G, source)
  295. else:
  296. G = G.copy()
  297. if source is None:
  298. source = _find_path_start(G)
  299. if G.is_multigraph():
  300. if keys:
  301. yield from reversed(
  302. [(v, u, k) for u, v, k in _multigraph_eulerian_circuit(G, source)]
  303. )
  304. else:
  305. yield from reversed(
  306. [(v, u) for u, v, k in _multigraph_eulerian_circuit(G, source)]
  307. )
  308. else:
  309. yield from reversed(
  310. [(v, u) for u, v in _simplegraph_eulerian_circuit(G, source)]
  311. )
  312. @not_implemented_for("directed")
  313. def eulerize(G):
  314. """Transforms a graph into an Eulerian graph.
  315. If `G` is Eulerian the result is `G` as a MultiGraph, otherwise the result is a smallest
  316. (in terms of the number of edges) multigraph whose underlying simple graph is `G`.
  317. Parameters
  318. ----------
  319. G : NetworkX graph
  320. An undirected graph
  321. Returns
  322. -------
  323. G : NetworkX multigraph
  324. Raises
  325. ------
  326. NetworkXError
  327. If the graph is not connected.
  328. See Also
  329. --------
  330. is_eulerian
  331. eulerian_circuit
  332. References
  333. ----------
  334. .. [1] J. Edmonds, E. L. Johnson.
  335. Matching, Euler tours and the Chinese postman.
  336. Mathematical programming, Volume 5, Issue 1 (1973), 111-114.
  337. .. [2] https://en.wikipedia.org/wiki/Eulerian_path
  338. .. [3] http://web.math.princeton.edu/math_alive/5/Notes1.pdf
  339. Examples
  340. --------
  341. >>> G = nx.complete_graph(10)
  342. >>> H = nx.eulerize(G)
  343. >>> nx.is_eulerian(H)
  344. True
  345. """
  346. if G.order() == 0:
  347. raise nx.NetworkXPointlessConcept("Cannot Eulerize null graph")
  348. if not nx.is_connected(G):
  349. raise nx.NetworkXError("G is not connected")
  350. odd_degree_nodes = [n for n, d in G.degree() if d % 2 == 1]
  351. G = nx.MultiGraph(G)
  352. if len(odd_degree_nodes) == 0:
  353. return G
  354. # get all shortest paths between vertices of odd degree
  355. odd_deg_pairs_paths = [
  356. (m, {n: nx.shortest_path(G, source=m, target=n)})
  357. for m, n in combinations(odd_degree_nodes, 2)
  358. ]
  359. # use the number of vertices in a graph + 1 as an upper bound on
  360. # the maximum length of a path in G
  361. upper_bound_on_max_path_length = len(G) + 1
  362. # use "len(G) + 1 - len(P)",
  363. # where P is a shortest path between vertices n and m,
  364. # as edge-weights in a new graph
  365. # store the paths in the graph for easy indexing later
  366. Gp = nx.Graph()
  367. for n, Ps in odd_deg_pairs_paths:
  368. for m, P in Ps.items():
  369. if n != m:
  370. Gp.add_edge(
  371. m, n, weight=upper_bound_on_max_path_length - len(P), path=P
  372. )
  373. # find the minimum weight matching of edges in the weighted graph
  374. best_matching = nx.Graph(list(nx.max_weight_matching(Gp)))
  375. # duplicate each edge along each path in the set of paths in Gp
  376. for m, n in best_matching.edges():
  377. path = Gp[m][n]["path"]
  378. G.add_edges_from(nx.utils.pairwise(path))
  379. return G