dag.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. """Algorithms for directed acyclic graphs (DAGs).
  2. Note that most of these functions are only guaranteed to work for DAGs.
  3. In general, these functions do not check for acyclic-ness, so it is up
  4. to the user to check for that.
  5. """
  6. import heapq
  7. from collections import deque
  8. from functools import partial
  9. from itertools import chain, combinations, product, starmap
  10. from math import gcd
  11. import networkx as nx
  12. from networkx.utils import arbitrary_element, not_implemented_for, pairwise
  13. __all__ = [
  14. "descendants",
  15. "ancestors",
  16. "topological_sort",
  17. "lexicographical_topological_sort",
  18. "all_topological_sorts",
  19. "topological_generations",
  20. "is_directed_acyclic_graph",
  21. "is_aperiodic",
  22. "transitive_closure",
  23. "transitive_closure_dag",
  24. "transitive_reduction",
  25. "antichains",
  26. "dag_longest_path",
  27. "dag_longest_path_length",
  28. "dag_to_branching",
  29. ]
  30. chaini = chain.from_iterable
  31. @nx._dispatchable
  32. def descendants(G, source):
  33. """Returns all nodes reachable from `source` in `G`.
  34. Parameters
  35. ----------
  36. G : NetworkX Graph
  37. source : node in `G`
  38. Returns
  39. -------
  40. set()
  41. The descendants of `source` in `G`
  42. Raises
  43. ------
  44. NetworkXError
  45. If node `source` is not in `G`.
  46. Examples
  47. --------
  48. >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
  49. >>> sorted(nx.descendants(DG, 2))
  50. [3, 4]
  51. The `source` node is not a descendant of itself, but can be included manually:
  52. >>> sorted(nx.descendants(DG, 2) | {2})
  53. [2, 3, 4]
  54. See also
  55. --------
  56. ancestors
  57. """
  58. return {child for parent, child in nx.bfs_edges(G, source)}
  59. @nx._dispatchable
  60. def ancestors(G, source):
  61. """Returns all nodes having a path to `source` in `G`.
  62. Parameters
  63. ----------
  64. G : NetworkX Graph
  65. source : node in `G`
  66. Returns
  67. -------
  68. set()
  69. The ancestors of `source` in `G`
  70. Raises
  71. ------
  72. NetworkXError
  73. If node `source` is not in `G`.
  74. Examples
  75. --------
  76. >>> DG = nx.path_graph(5, create_using=nx.DiGraph)
  77. >>> sorted(nx.ancestors(DG, 2))
  78. [0, 1]
  79. The `source` node is not an ancestor of itself, but can be included manually:
  80. >>> sorted(nx.ancestors(DG, 2) | {2})
  81. [0, 1, 2]
  82. See also
  83. --------
  84. descendants
  85. """
  86. return {child for parent, child in nx.bfs_edges(G, source, reverse=True)}
  87. @nx._dispatchable
  88. def has_cycle(G):
  89. """Decides whether the directed graph has a cycle."""
  90. try:
  91. # Feed the entire iterator into a zero-length deque.
  92. deque(topological_sort(G), maxlen=0)
  93. except nx.NetworkXUnfeasible:
  94. return True
  95. else:
  96. return False
  97. @nx._dispatchable
  98. def is_directed_acyclic_graph(G):
  99. """Returns True if the graph `G` is a directed acyclic graph (DAG) or
  100. False if not.
  101. Parameters
  102. ----------
  103. G : NetworkX graph
  104. Returns
  105. -------
  106. bool
  107. True if `G` is a DAG, False otherwise
  108. Examples
  109. --------
  110. Undirected graph::
  111. >>> G = nx.Graph([(1, 2), (2, 3)])
  112. >>> nx.is_directed_acyclic_graph(G)
  113. False
  114. Directed graph with cycle::
  115. >>> G = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
  116. >>> nx.is_directed_acyclic_graph(G)
  117. False
  118. Directed acyclic graph::
  119. >>> G = nx.DiGraph([(1, 2), (2, 3)])
  120. >>> nx.is_directed_acyclic_graph(G)
  121. True
  122. See also
  123. --------
  124. topological_sort
  125. """
  126. return G.is_directed() and not has_cycle(G)
  127. @nx._dispatchable
  128. def topological_generations(G):
  129. """Stratifies a DAG into generations.
  130. A topological generation is node collection in which ancestors of a node in each
  131. generation are guaranteed to be in a previous generation, and any descendants of
  132. a node are guaranteed to be in a following generation. Nodes are guaranteed to
  133. be in the earliest possible generation that they can belong to.
  134. Parameters
  135. ----------
  136. G : NetworkX digraph
  137. A directed acyclic graph (DAG)
  138. Yields
  139. ------
  140. sets of nodes
  141. Yields sets of nodes representing each generation.
  142. Raises
  143. ------
  144. NetworkXError
  145. Generations are defined for directed graphs only. If the graph
  146. `G` is undirected, a :exc:`NetworkXError` is raised.
  147. NetworkXUnfeasible
  148. If `G` is not a directed acyclic graph (DAG) no topological generations
  149. exist and a :exc:`NetworkXUnfeasible` exception is raised. This can also
  150. be raised if `G` is changed while the returned iterator is being processed
  151. RuntimeError
  152. If `G` is changed while the returned iterator is being processed.
  153. Examples
  154. --------
  155. >>> DG = nx.DiGraph([(2, 1), (3, 1)])
  156. >>> [sorted(generation) for generation in nx.topological_generations(DG)]
  157. [[2, 3], [1]]
  158. Notes
  159. -----
  160. The generation in which a node resides can also be determined by taking the
  161. max-path-distance from the node to the farthest leaf node. That value can
  162. be obtained with this function using `enumerate(topological_generations(G))`.
  163. See also
  164. --------
  165. topological_sort
  166. """
  167. if not G.is_directed():
  168. raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
  169. multigraph = G.is_multigraph()
  170. indegree_map = {v: d for v, d in G.in_degree() if d > 0}
  171. zero_indegree = [v for v, d in G.in_degree() if d == 0]
  172. while zero_indegree:
  173. this_generation = zero_indegree
  174. zero_indegree = []
  175. for node in this_generation:
  176. if node not in G:
  177. raise RuntimeError("Graph changed during iteration")
  178. for child in G.neighbors(node):
  179. try:
  180. indegree_map[child] -= len(G[node][child]) if multigraph else 1
  181. except KeyError as err:
  182. raise RuntimeError("Graph changed during iteration") from err
  183. if indegree_map[child] == 0:
  184. zero_indegree.append(child)
  185. del indegree_map[child]
  186. yield this_generation
  187. if indegree_map:
  188. raise nx.NetworkXUnfeasible(
  189. "Graph contains a cycle or graph changed during iteration"
  190. )
  191. @nx._dispatchable
  192. def topological_sort(G):
  193. """Returns a generator of nodes in topologically sorted order.
  194. A topological sort is a nonunique permutation of the nodes of a
  195. directed graph such that an edge from u to v implies that u
  196. appears before v in the topological sort order. This ordering is
  197. valid only if the graph has no directed cycles.
  198. Parameters
  199. ----------
  200. G : NetworkX digraph
  201. A directed acyclic graph (DAG)
  202. Yields
  203. ------
  204. nodes
  205. Yields the nodes in topological sorted order.
  206. Raises
  207. ------
  208. NetworkXError
  209. Topological sort is defined for directed graphs only. If the graph `G`
  210. is undirected, a :exc:`NetworkXError` is raised.
  211. NetworkXUnfeasible
  212. If `G` is not a directed acyclic graph (DAG) no topological sort exists
  213. and a :exc:`NetworkXUnfeasible` exception is raised. This can also be
  214. raised if `G` is changed while the returned iterator is being processed
  215. RuntimeError
  216. If `G` is changed while the returned iterator is being processed.
  217. Examples
  218. --------
  219. To get the reverse order of the topological sort:
  220. >>> DG = nx.DiGraph([(1, 2), (2, 3)])
  221. >>> list(reversed(list(nx.topological_sort(DG))))
  222. [3, 2, 1]
  223. If your DiGraph naturally has the edges representing tasks/inputs
  224. and nodes representing people/processes that initiate tasks, then
  225. topological_sort is not quite what you need. You will have to change
  226. the tasks to nodes with dependence reflected by edges. The result is
  227. a kind of topological sort of the edges. This can be done
  228. with :func:`networkx.line_graph` as follows:
  229. >>> list(nx.topological_sort(nx.line_graph(DG)))
  230. [(1, 2), (2, 3)]
  231. Notes
  232. -----
  233. This algorithm is based on a description and proof in
  234. "Introduction to Algorithms: A Creative Approach" [1]_ .
  235. See also
  236. --------
  237. is_directed_acyclic_graph, lexicographical_topological_sort
  238. References
  239. ----------
  240. .. [1] Manber, U. (1989).
  241. *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
  242. """
  243. for generation in nx.topological_generations(G):
  244. yield from generation
  245. @nx._dispatchable
  246. def lexicographical_topological_sort(G, key=None):
  247. """Generate the nodes in the unique lexicographical topological sort order.
  248. Generates a unique ordering of nodes by first sorting topologically (for which there are often
  249. multiple valid orderings) and then additionally by sorting lexicographically.
  250. A topological sort arranges the nodes of a directed graph so that the
  251. upstream node of each directed edge precedes the downstream node.
  252. It is always possible to find a solution for directed graphs that have no cycles.
  253. There may be more than one valid solution.
  254. Lexicographical sorting is just sorting alphabetically. It is used here to break ties in the
  255. topological sort and to determine a single, unique ordering. This can be useful in comparing
  256. sort results.
  257. The lexicographical order can be customized by providing a function to the `key=` parameter.
  258. The definition of the key function is the same as used in python's built-in `sort()`.
  259. The function takes a single argument and returns a key to use for sorting purposes.
  260. Lexicographical sorting can fail if the node names are un-sortable. See the example below.
  261. The solution is to provide a function to the `key=` argument that returns sortable keys.
  262. Parameters
  263. ----------
  264. G : NetworkX digraph
  265. A directed acyclic graph (DAG)
  266. key : function, optional
  267. A function of one argument that converts a node name to a comparison key.
  268. It defines and resolves ambiguities in the sort order. Defaults to the identity function.
  269. Yields
  270. ------
  271. nodes
  272. Yields the nodes of G in lexicographical topological sort order.
  273. Raises
  274. ------
  275. NetworkXError
  276. Topological sort is defined for directed graphs only. If the graph `G`
  277. is undirected, a :exc:`NetworkXError` is raised.
  278. NetworkXUnfeasible
  279. If `G` is not a directed acyclic graph (DAG) no topological sort exists
  280. and a :exc:`NetworkXUnfeasible` exception is raised. This can also be
  281. raised if `G` is changed while the returned iterator is being processed
  282. RuntimeError
  283. If `G` is changed while the returned iterator is being processed.
  284. TypeError
  285. Results from un-sortable node names.
  286. Consider using `key=` parameter to resolve ambiguities in the sort order.
  287. Examples
  288. --------
  289. >>> DG = nx.DiGraph([(2, 1), (2, 5), (1, 3), (1, 4), (5, 4)])
  290. >>> list(nx.lexicographical_topological_sort(DG))
  291. [2, 1, 3, 5, 4]
  292. >>> list(nx.lexicographical_topological_sort(DG, key=lambda x: -x))
  293. [2, 5, 1, 4, 3]
  294. The sort will fail for any graph with integer and string nodes. Comparison of integer to strings
  295. is not defined in python. Is 3 greater or less than 'red'?
  296. >>> DG = nx.DiGraph([(1, "red"), (3, "red"), (1, "green"), (2, "blue")])
  297. >>> list(nx.lexicographical_topological_sort(DG))
  298. Traceback (most recent call last):
  299. ...
  300. TypeError: '<' not supported between instances of 'str' and 'int'
  301. ...
  302. Incomparable nodes can be resolved using a `key` function. This example function
  303. allows comparison of integers and strings by returning a tuple where the first
  304. element is True for `str`, False otherwise. The second element is the node name.
  305. This groups the strings and integers separately so they can be compared only among themselves.
  306. >>> key = lambda node: (isinstance(node, str), node)
  307. >>> list(nx.lexicographical_topological_sort(DG, key=key))
  308. [1, 2, 3, 'blue', 'green', 'red']
  309. Notes
  310. -----
  311. This algorithm is based on a description and proof in
  312. "Introduction to Algorithms: A Creative Approach" [1]_ .
  313. See also
  314. --------
  315. topological_sort
  316. References
  317. ----------
  318. .. [1] Manber, U. (1989).
  319. *Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
  320. """
  321. if not G.is_directed():
  322. msg = "Topological sort not defined on undirected graphs."
  323. raise nx.NetworkXError(msg)
  324. if key is None:
  325. def key(node):
  326. return node
  327. nodeid_map = {n: i for i, n in enumerate(G)}
  328. def create_tuple(node):
  329. return key(node), nodeid_map[node], node
  330. indegree_map = {v: d for v, d in G.in_degree() if d > 0}
  331. # These nodes have zero indegree and ready to be returned.
  332. zero_indegree = [create_tuple(v) for v, d in G.in_degree() if d == 0]
  333. heapq.heapify(zero_indegree)
  334. while zero_indegree:
  335. _, _, node = heapq.heappop(zero_indegree)
  336. if node not in G:
  337. raise RuntimeError("Graph changed during iteration")
  338. for _, child in G.edges(node):
  339. try:
  340. indegree_map[child] -= 1
  341. except KeyError as err:
  342. raise RuntimeError("Graph changed during iteration") from err
  343. if indegree_map[child] == 0:
  344. try:
  345. heapq.heappush(zero_indegree, create_tuple(child))
  346. except TypeError as err:
  347. raise TypeError(
  348. f"{err}\nConsider using `key=` parameter to resolve ambiguities in the sort order."
  349. )
  350. del indegree_map[child]
  351. yield node
  352. if indegree_map:
  353. msg = "Graph contains a cycle or graph changed during iteration"
  354. raise nx.NetworkXUnfeasible(msg)
  355. @not_implemented_for("undirected")
  356. @nx._dispatchable
  357. def all_topological_sorts(G):
  358. """Returns a generator of _all_ topological sorts of the directed graph G.
  359. A topological sort is a nonunique permutation of the nodes such that an
  360. edge from u to v implies that u appears before v in the topological sort
  361. order.
  362. Parameters
  363. ----------
  364. G : NetworkX DiGraph
  365. A directed graph
  366. Yields
  367. ------
  368. topological_sort_order : list
  369. a list of nodes in `G`, representing one of the topological sort orders
  370. Raises
  371. ------
  372. NetworkXNotImplemented
  373. If `G` is not directed
  374. NetworkXUnfeasible
  375. If `G` is not acyclic
  376. Examples
  377. --------
  378. To enumerate all topological sorts of directed graph:
  379. >>> DG = nx.DiGraph([(1, 2), (2, 3), (2, 4)])
  380. >>> list(nx.all_topological_sorts(DG))
  381. [[1, 2, 4, 3], [1, 2, 3, 4]]
  382. Notes
  383. -----
  384. Implements an iterative version of the algorithm given in [1].
  385. References
  386. ----------
  387. .. [1] Knuth, Donald E., Szwarcfiter, Jayme L. (1974).
  388. "A Structured Program to Generate All Topological Sorting Arrangements"
  389. Information Processing Letters, Volume 2, Issue 6, 1974, Pages 153-157,
  390. ISSN 0020-0190,
  391. https://doi.org/10.1016/0020-0190(74)90001-5.
  392. Elsevier (North-Holland), Amsterdam
  393. """
  394. if not G.is_directed():
  395. raise nx.NetworkXError("Topological sort not defined on undirected graphs.")
  396. # the names of count and D are chosen to match the global variables in [1]
  397. # number of edges originating in a vertex v
  398. count = dict(G.in_degree())
  399. # vertices with indegree 0
  400. D = deque([v for v, d in G.in_degree() if d == 0])
  401. # stack of first value chosen at a position k in the topological sort
  402. bases = []
  403. current_sort = []
  404. # do-while construct
  405. while True:
  406. assert all(count[v] == 0 for v in D)
  407. if len(current_sort) == len(G):
  408. yield list(current_sort)
  409. # clean-up stack
  410. while len(current_sort) > 0:
  411. assert len(bases) == len(current_sort)
  412. q = current_sort.pop()
  413. # "restores" all edges (q, x)
  414. # NOTE: it is important to iterate over edges instead
  415. # of successors, so count is updated correctly in multigraphs
  416. for _, j in G.out_edges(q):
  417. count[j] += 1
  418. assert count[j] >= 0
  419. # remove entries from D
  420. while len(D) > 0 and count[D[-1]] > 0:
  421. D.pop()
  422. # corresponds to a circular shift of the values in D
  423. # if the first value chosen (the base) is in the first
  424. # position of D again, we are done and need to consider the
  425. # previous condition
  426. D.appendleft(q)
  427. if D[-1] == bases[-1]:
  428. # all possible values have been chosen at current position
  429. # remove corresponding marker
  430. bases.pop()
  431. else:
  432. # there are still elements that have not been fixed
  433. # at the current position in the topological sort
  434. # stop removing elements, escape inner loop
  435. break
  436. else:
  437. if len(D) == 0:
  438. raise nx.NetworkXUnfeasible("Graph contains a cycle.")
  439. # choose next node
  440. q = D.pop()
  441. # "erase" all edges (q, x)
  442. # NOTE: it is important to iterate over edges instead
  443. # of successors, so count is updated correctly in multigraphs
  444. for _, j in G.out_edges(q):
  445. count[j] -= 1
  446. assert count[j] >= 0
  447. if count[j] == 0:
  448. D.append(j)
  449. current_sort.append(q)
  450. # base for current position might _not_ be fixed yet
  451. if len(bases) < len(current_sort):
  452. bases.append(q)
  453. if len(bases) == 0:
  454. break
  455. @nx._dispatchable
  456. def is_aperiodic(G):
  457. """Returns True if `G` is aperiodic.
  458. A strongly connected directed graph is aperiodic if there is no integer ``k > 1``
  459. that divides the length of every cycle in the graph.
  460. This function requires the graph `G` to be strongly connected and will raise
  461. an error if it's not. For graphs that are not strongly connected, you should
  462. first identify their strongly connected components
  463. (using :func:`~networkx.algorithms.components.strongly_connected_components`)
  464. or attracting components
  465. (using :func:`~networkx.algorithms.components.attracting_components`),
  466. and then apply this function to those individual components.
  467. Parameters
  468. ----------
  469. G : NetworkX DiGraph
  470. A directed graph
  471. Returns
  472. -------
  473. bool
  474. True if the graph is aperiodic False otherwise
  475. Raises
  476. ------
  477. NetworkXError
  478. If `G` is not directed
  479. NetworkXError
  480. If `G` is not strongly connected
  481. NetworkXPointlessConcept
  482. If `G` has no nodes
  483. Examples
  484. --------
  485. A graph consisting of one cycle, the length of which is 2. Therefore ``k = 2``
  486. divides the length of every cycle in the graph and thus the graph
  487. is *not aperiodic*::
  488. >>> DG = nx.DiGraph([(1, 2), (2, 1)])
  489. >>> nx.is_aperiodic(DG)
  490. False
  491. A graph consisting of two cycles: one of length 2 and the other of length 3.
  492. The cycle lengths are coprime, so there is no single value of k where ``k > 1``
  493. that divides each cycle length and therefore the graph is *aperiodic*::
  494. >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1), (1, 4), (4, 1)])
  495. >>> nx.is_aperiodic(DG)
  496. True
  497. A graph created from cycles of the same length can still be aperiodic since
  498. the cycles can overlap and form new cycles of different lengths. For example,
  499. the following graph contains a cycle ``[4, 2, 3, 1]`` of length 4, which is coprime
  500. with the explicitly added cycles of length 3, so the graph is aperiodic::
  501. >>> DG = nx.DiGraph()
  502. >>> nx.add_cycle(DG, [1, 2, 3])
  503. >>> nx.add_cycle(DG, [2, 1, 4])
  504. >>> nx.is_aperiodic(DG)
  505. True
  506. A single-node graph's aperiodicity depends on whether it has a self-loop:
  507. it is aperiodic if a self-loop exists, and periodic otherwise::
  508. >>> G = nx.DiGraph()
  509. >>> G.add_node(1)
  510. >>> nx.is_aperiodic(G)
  511. False
  512. >>> G.add_edge(1, 1)
  513. >>> nx.is_aperiodic(G)
  514. True
  515. A Markov chain can be modeled as a directed graph, with nodes representing
  516. states and edges representing transitions with non-zero probability.
  517. Aperiodicity is typically considered for irreducible Markov chains,
  518. which are those that are *strongly connected* as graphs.
  519. The following Markov chain is irreducible and aperiodic, and thus
  520. ergodic. It is guaranteed to have a unique stationary distribution::
  521. >>> G = nx.DiGraph()
  522. >>> nx.add_cycle(G, [1, 2, 3, 4])
  523. >>> G.add_edge(1, 3)
  524. >>> nx.is_aperiodic(G)
  525. True
  526. Reducible Markov chains can sometimes have a unique stationary distribution.
  527. This occurs if the chain has exactly one closed communicating class and
  528. that class itself is aperiodic (see [1]_). You can use
  529. :func:`~networkx.algorithms.components.attracting_components`
  530. to find these closed communicating classes::
  531. >>> G = nx.DiGraph([(1, 3), (2, 3)])
  532. >>> nx.add_cycle(G, [3, 4, 5, 6])
  533. >>> nx.add_cycle(G, [3, 5, 6])
  534. >>> communicating_classes = list(nx.strongly_connected_components(G))
  535. >>> len(communicating_classes)
  536. 3
  537. >>> closed_communicating_classes = list(nx.attracting_components(G))
  538. >>> len(closed_communicating_classes)
  539. 1
  540. >>> nx.is_aperiodic(G.subgraph(closed_communicating_classes[0]))
  541. True
  542. Notes
  543. -----
  544. This uses the method outlined in [1]_, which runs in $O(m)$ time
  545. given $m$ edges in `G`.
  546. References
  547. ----------
  548. .. [1] Jarvis, J. P.; Shier, D. R. (1996),
  549. "Graph-theoretic analysis of finite Markov chains,"
  550. in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling:
  551. A Multidisciplinary Approach, CRC Press.
  552. """
  553. if not G.is_directed():
  554. raise nx.NetworkXError("is_aperiodic not defined for undirected graphs")
  555. if len(G) == 0:
  556. raise nx.NetworkXPointlessConcept("Graph has no nodes.")
  557. if not nx.is_strongly_connected(G):
  558. raise nx.NetworkXError("Graph is not strongly connected.")
  559. s = arbitrary_element(G)
  560. levels = {s: 0}
  561. this_level = [s]
  562. g = 0
  563. lev = 1
  564. while this_level:
  565. next_level = []
  566. for u in this_level:
  567. for v in G[u]:
  568. if v in levels: # Non-Tree Edge
  569. g = gcd(g, levels[u] - levels[v] + 1)
  570. else: # Tree Edge
  571. next_level.append(v)
  572. levels[v] = lev
  573. this_level = next_level
  574. lev += 1
  575. return g == 1
  576. @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
  577. def transitive_closure(G, reflexive=False):
  578. """Returns transitive closure of a graph
  579. The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
  580. for all v, w in V there is an edge (v, w) in E+ if and only if there
  581. is a path from v to w in G.
  582. Handling of paths from v to v has some flexibility within this definition.
  583. A reflexive transitive closure creates a self-loop for the path
  584. from v to v of length 0. The usual transitive closure creates a
  585. self-loop only if a cycle exists (a path from v to v with length > 0).
  586. We also allow an option for no self-loops.
  587. Parameters
  588. ----------
  589. G : NetworkX Graph
  590. A directed/undirected graph/multigraph.
  591. reflexive : Bool or None, optional (default: False)
  592. Determines when cycles create self-loops in the Transitive Closure.
  593. If True, trivial cycles (length 0) create self-loops. The result
  594. is a reflexive transitive closure of G.
  595. If False (the default) non-trivial cycles create self-loops.
  596. If None, self-loops are not created.
  597. Returns
  598. -------
  599. NetworkX graph
  600. The transitive closure of `G`
  601. Raises
  602. ------
  603. NetworkXError
  604. If `reflexive` not in `{None, True, False}`
  605. Examples
  606. --------
  607. The treatment of trivial (i.e. length 0) cycles is controlled by the
  608. `reflexive` parameter.
  609. Trivial (i.e. length 0) cycles do not create self-loops when
  610. ``reflexive=False`` (the default)::
  611. >>> DG = nx.DiGraph([(1, 2), (2, 3)])
  612. >>> TC = nx.transitive_closure(DG, reflexive=False)
  613. >>> TC.edges()
  614. OutEdgeView([(1, 2), (1, 3), (2, 3)])
  615. However, nontrivial (i.e. length greater than 0) cycles create self-loops
  616. when ``reflexive=False`` (the default)::
  617. >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
  618. >>> TC = nx.transitive_closure(DG, reflexive=False)
  619. >>> TC.edges()
  620. OutEdgeView([(1, 2), (1, 3), (1, 1), (2, 3), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)])
  621. Trivial cycles (length 0) create self-loops when ``reflexive=True``::
  622. >>> DG = nx.DiGraph([(1, 2), (2, 3)])
  623. >>> TC = nx.transitive_closure(DG, reflexive=True)
  624. >>> TC.edges()
  625. OutEdgeView([(1, 2), (1, 1), (1, 3), (2, 3), (2, 2), (3, 3)])
  626. And the third option is not to create self-loops at all when ``reflexive=None``::
  627. >>> DG = nx.DiGraph([(1, 2), (2, 3), (3, 1)])
  628. >>> TC = nx.transitive_closure(DG, reflexive=None)
  629. >>> TC.edges()
  630. OutEdgeView([(1, 2), (1, 3), (2, 3), (2, 1), (3, 1), (3, 2)])
  631. References
  632. ----------
  633. .. [1] https://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py
  634. """
  635. TC = G.copy()
  636. if reflexive not in {None, True, False}:
  637. raise nx.NetworkXError("Incorrect value for the parameter `reflexive`")
  638. for v in G:
  639. if reflexive is None:
  640. TC.add_edges_from((v, u) for u in nx.descendants(G, v) if u not in TC[v])
  641. elif reflexive is True:
  642. TC.add_edges_from(
  643. (v, u) for u in nx.descendants(G, v) | {v} if u not in TC[v]
  644. )
  645. elif reflexive is False:
  646. TC.add_edges_from((v, e[1]) for e in nx.edge_bfs(G, v) if e[1] not in TC[v])
  647. return TC
  648. @not_implemented_for("undirected")
  649. @nx._dispatchable(preserve_all_attrs=True, returns_graph=True)
  650. def transitive_closure_dag(G, topo_order=None):
  651. """Returns the transitive closure of a directed acyclic graph.
  652. This function is faster than the function `transitive_closure`, but fails
  653. if the graph has a cycle.
  654. The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
  655. for all v, w in V there is an edge (v, w) in E+ if and only if there
  656. is a non-null path from v to w in G.
  657. Parameters
  658. ----------
  659. G : NetworkX DiGraph
  660. A directed acyclic graph (DAG)
  661. topo_order: list or tuple, optional
  662. A topological order for G (if None, the function will compute one)
  663. Returns
  664. -------
  665. NetworkX DiGraph
  666. The transitive closure of `G`
  667. Raises
  668. ------
  669. NetworkXNotImplemented
  670. If `G` is not directed
  671. NetworkXUnfeasible
  672. If `G` has a cycle
  673. Examples
  674. --------
  675. >>> DG = nx.DiGraph([(1, 2), (2, 3)])
  676. >>> TC = nx.transitive_closure_dag(DG)
  677. >>> TC.edges()
  678. OutEdgeView([(1, 2), (1, 3), (2, 3)])
  679. Notes
  680. -----
  681. This algorithm is probably simple enough to be well-known but I didn't find
  682. a mention in the literature.
  683. """
  684. if topo_order is None:
  685. topo_order = list(topological_sort(G))
  686. TC = G.copy()
  687. # idea: traverse vertices following a reverse topological order, connecting
  688. # each vertex to its descendants at distance 2 as we go
  689. for v in reversed(topo_order):
  690. TC.add_edges_from((v, u) for u in nx.descendants_at_distance(TC, v, 2))
  691. return TC
  692. @not_implemented_for("undirected")
  693. @nx._dispatchable(returns_graph=True)
  694. def transitive_reduction(G):
  695. """Returns transitive reduction of a directed graph
  696. The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that
  697. for all v,w in V there is an edge (v,w) in E- if and only if (v,w) is
  698. in E and there is no path from v to w in G with length greater than 1.
  699. Parameters
  700. ----------
  701. G : NetworkX DiGraph
  702. A directed acyclic graph (DAG)
  703. Returns
  704. -------
  705. NetworkX DiGraph
  706. The transitive reduction of `G`
  707. Raises
  708. ------
  709. NetworkXError
  710. If `G` is not a directed acyclic graph (DAG) transitive reduction is
  711. not uniquely defined and a :exc:`NetworkXError` exception is raised.
  712. Examples
  713. --------
  714. To perform transitive reduction on a DiGraph:
  715. >>> DG = nx.DiGraph([(1, 2), (2, 3), (1, 3)])
  716. >>> TR = nx.transitive_reduction(DG)
  717. >>> list(TR.edges)
  718. [(1, 2), (2, 3)]
  719. To avoid unnecessary data copies, this implementation does not return a
  720. DiGraph with node/edge data.
  721. To perform transitive reduction on a DiGraph and transfer node/edge data:
  722. >>> DG = nx.DiGraph()
  723. >>> DG.add_edges_from([(1, 2), (2, 3), (1, 3)], color="red")
  724. >>> TR = nx.transitive_reduction(DG)
  725. >>> TR.add_nodes_from(DG.nodes(data=True))
  726. >>> TR.add_edges_from((u, v, DG.edges[u, v]) for u, v in TR.edges)
  727. >>> list(TR.edges(data=True))
  728. [(1, 2, {'color': 'red'}), (2, 3, {'color': 'red'})]
  729. References
  730. ----------
  731. https://en.wikipedia.org/wiki/Transitive_reduction
  732. """
  733. if not is_directed_acyclic_graph(G):
  734. msg = "Directed Acyclic Graph required for transitive_reduction"
  735. raise nx.NetworkXError(msg)
  736. TR = nx.DiGraph()
  737. TR.add_nodes_from(G.nodes())
  738. descendants = {}
  739. # count before removing set stored in descendants
  740. check_count = dict(G.in_degree)
  741. for u in G:
  742. u_nbrs = set(G[u])
  743. for v in G[u]:
  744. if v in u_nbrs:
  745. if v not in descendants:
  746. descendants[v] = {y for x, y in nx.dfs_edges(G, v)}
  747. u_nbrs -= descendants[v]
  748. check_count[v] -= 1
  749. if check_count[v] == 0:
  750. del descendants[v]
  751. TR.add_edges_from((u, v) for v in u_nbrs)
  752. return TR
  753. @not_implemented_for("undirected")
  754. @nx._dispatchable
  755. def antichains(G, topo_order=None):
  756. """Generates antichains from a directed acyclic graph (DAG).
  757. An antichain is a subset of a partially ordered set such that any
  758. two elements in the subset are incomparable.
  759. Parameters
  760. ----------
  761. G : NetworkX DiGraph
  762. A directed acyclic graph (DAG)
  763. topo_order: list or tuple, optional
  764. A topological order for G (if None, the function will compute one)
  765. Yields
  766. ------
  767. antichain : list
  768. a list of nodes in `G` representing an antichain
  769. Raises
  770. ------
  771. NetworkXNotImplemented
  772. If `G` is not directed
  773. NetworkXUnfeasible
  774. If `G` contains a cycle
  775. Examples
  776. --------
  777. >>> DG = nx.DiGraph([(1, 2), (1, 3)])
  778. >>> list(nx.antichains(DG))
  779. [[], [3], [2], [2, 3], [1]]
  780. Notes
  781. -----
  782. This function was originally developed by Peter Jipsen and Franco Saliola
  783. for the SAGE project. It's included in NetworkX with permission from the
  784. authors. Original SAGE code at:
  785. https://github.com/sagemath/sage/blob/master/src/sage/combinat/posets/hasse_diagram.py
  786. References
  787. ----------
  788. .. [1] Free Lattices, by R. Freese, J. Jezek and J. B. Nation,
  789. AMS, Vol 42, 1995, p. 226.
  790. """
  791. if topo_order is None:
  792. topo_order = list(nx.topological_sort(G))
  793. TC = nx.transitive_closure_dag(G, topo_order)
  794. antichains_stacks = [([], list(reversed(topo_order)))]
  795. while antichains_stacks:
  796. (antichain, stack) = antichains_stacks.pop()
  797. # Invariant:
  798. # - the elements of antichain are independent
  799. # - the elements of stack are independent from those of antichain
  800. yield antichain
  801. while stack:
  802. x = stack.pop()
  803. new_antichain = antichain + [x]
  804. new_stack = [t for t in stack if not ((t in TC[x]) or (x in TC[t]))]
  805. antichains_stacks.append((new_antichain, new_stack))
  806. @not_implemented_for("undirected")
  807. @nx._dispatchable(edge_attrs={"weight": "default_weight"})
  808. def dag_longest_path(G, weight="weight", default_weight=1, topo_order=None):
  809. """Returns the longest path in a directed acyclic graph (DAG).
  810. If `G` has edges with `weight` attribute the edge data are used as
  811. weight values.
  812. Parameters
  813. ----------
  814. G : NetworkX DiGraph
  815. A directed acyclic graph (DAG)
  816. weight : str, optional
  817. Edge data key to use for weight
  818. default_weight : int, optional
  819. The weight of edges that do not have a weight attribute
  820. topo_order: list or tuple, optional
  821. A topological order for `G` (if None, the function will compute one)
  822. Returns
  823. -------
  824. list
  825. Longest path
  826. Raises
  827. ------
  828. NetworkXNotImplemented
  829. If `G` is not directed
  830. Examples
  831. --------
  832. >>> DG = nx.DiGraph(
  833. ... [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
  834. ... )
  835. >>> list(nx.all_simple_paths(DG, 0, 2))
  836. [[0, 1, 2], [0, 2]]
  837. >>> nx.dag_longest_path(DG)
  838. [0, 1, 2]
  839. >>> nx.dag_longest_path(DG, weight="cost")
  840. [0, 2]
  841. In the case where multiple valid topological orderings exist, `topo_order`
  842. can be used to specify a specific ordering:
  843. >>> DG = nx.DiGraph([(0, 1), (0, 2)])
  844. >>> sorted(nx.all_topological_sorts(DG)) # Valid topological orderings
  845. [[0, 1, 2], [0, 2, 1]]
  846. >>> nx.dag_longest_path(DG, topo_order=[0, 1, 2])
  847. [0, 1]
  848. >>> nx.dag_longest_path(DG, topo_order=[0, 2, 1])
  849. [0, 2]
  850. See also
  851. --------
  852. dag_longest_path_length
  853. """
  854. if not G:
  855. return []
  856. if topo_order is None:
  857. topo_order = nx.topological_sort(G)
  858. dist = {} # stores {v : (length, u)}
  859. for v in topo_order:
  860. us = [
  861. (
  862. dist[u][0]
  863. + (
  864. max(data.values(), key=lambda x: x.get(weight, default_weight))
  865. if G.is_multigraph()
  866. else data
  867. ).get(weight, default_weight),
  868. u,
  869. )
  870. for u, data in G.pred[v].items()
  871. ]
  872. # Use the best predecessor if there is one and its distance is
  873. # non-negative, otherwise terminate.
  874. maxu = max(us, key=lambda x: x[0]) if us else (0, v)
  875. dist[v] = maxu if maxu[0] >= 0 else (0, v)
  876. u = None
  877. v = max(dist, key=lambda x: dist[x][0])
  878. path = []
  879. while u != v:
  880. path.append(v)
  881. u = v
  882. v = dist[v][1]
  883. path.reverse()
  884. return path
  885. @not_implemented_for("undirected")
  886. @nx._dispatchable(edge_attrs={"weight": "default_weight"})
  887. def dag_longest_path_length(G, weight="weight", default_weight=1):
  888. """Returns the longest path length in a DAG
  889. Parameters
  890. ----------
  891. G : NetworkX DiGraph
  892. A directed acyclic graph (DAG)
  893. weight : string, optional
  894. Edge data key to use for weight
  895. default_weight : int, optional
  896. The weight of edges that do not have a weight attribute
  897. Returns
  898. -------
  899. int
  900. Longest path length
  901. Raises
  902. ------
  903. NetworkXNotImplemented
  904. If `G` is not directed
  905. Examples
  906. --------
  907. >>> DG = nx.DiGraph(
  908. ... [(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]
  909. ... )
  910. >>> list(nx.all_simple_paths(DG, 0, 2))
  911. [[0, 1, 2], [0, 2]]
  912. >>> nx.dag_longest_path_length(DG)
  913. 2
  914. >>> nx.dag_longest_path_length(DG, weight="cost")
  915. 42
  916. See also
  917. --------
  918. dag_longest_path
  919. """
  920. path = nx.dag_longest_path(G, weight, default_weight)
  921. path_length = 0
  922. if G.is_multigraph():
  923. for u, v in pairwise(path):
  924. i = max(G[u][v], key=lambda x: G[u][v][x].get(weight, default_weight))
  925. path_length += G[u][v][i].get(weight, default_weight)
  926. else:
  927. for u, v in pairwise(path):
  928. path_length += G[u][v].get(weight, default_weight)
  929. return path_length
  930. @nx._dispatchable
  931. def root_to_leaf_paths(G):
  932. """Yields root-to-leaf paths in a directed acyclic graph.
  933. `G` must be a directed acyclic graph. If not, the behavior of this
  934. function is undefined. A "root" in this graph is a node of in-degree
  935. zero and a "leaf" a node of out-degree zero.
  936. When invoked, this function iterates over each path from any root to
  937. any leaf. A path is a list of nodes.
  938. """
  939. roots = (v for v, d in G.in_degree() if d == 0)
  940. leaves = (v for v, d in G.out_degree() if d == 0)
  941. all_paths = partial(nx.all_simple_paths, G)
  942. # TODO In Python 3, this would be better as `yield from ...`.
  943. return chaini(starmap(all_paths, product(roots, leaves)))
  944. @not_implemented_for("multigraph")
  945. @not_implemented_for("undirected")
  946. @nx._dispatchable(returns_graph=True)
  947. def dag_to_branching(G):
  948. """Returns a branching representing all (overlapping) paths from
  949. root nodes to leaf nodes in the given directed acyclic graph.
  950. As described in :mod:`networkx.algorithms.tree.recognition`, a
  951. *branching* is a directed forest in which each node has at most one
  952. parent. In other words, a branching is a disjoint union of
  953. *arborescences*. For this function, each node of in-degree zero in
  954. `G` becomes a root of one of the arborescences, and there will be
  955. one leaf node for each distinct path from that root to a leaf node
  956. in `G`.
  957. Each node `v` in `G` with *k* parents becomes *k* distinct nodes in
  958. the returned branching, one for each parent, and the sub-DAG rooted
  959. at `v` is duplicated for each copy. The algorithm then recurses on
  960. the children of each copy of `v`.
  961. Parameters
  962. ----------
  963. G : NetworkX graph
  964. A directed acyclic graph.
  965. Returns
  966. -------
  967. DiGraph
  968. The branching in which there is a bijection between root-to-leaf
  969. paths in `G` (in which multiple paths may share the same leaf)
  970. and root-to-leaf paths in the branching (in which there is a
  971. unique path from a root to a leaf).
  972. Each node has an attribute 'source' whose value is the original
  973. node to which this node corresponds. No other graph, node, or
  974. edge attributes are copied into this new graph.
  975. Raises
  976. ------
  977. NetworkXNotImplemented
  978. If `G` is not directed, or if `G` is a multigraph.
  979. HasACycle
  980. If `G` is not acyclic.
  981. Examples
  982. --------
  983. To examine which nodes in the returned branching were produced by
  984. which original node in the directed acyclic graph, we can collect
  985. the mapping from source node to new nodes into a dictionary. For
  986. example, consider the directed diamond graph::
  987. >>> from collections import defaultdict
  988. >>> from operator import itemgetter
  989. >>>
  990. >>> G = nx.DiGraph(nx.utils.pairwise("abd"))
  991. >>> G.add_edges_from(nx.utils.pairwise("acd"))
  992. >>> B = nx.dag_to_branching(G)
  993. >>>
  994. >>> sources = defaultdict(set)
  995. >>> for v, source in B.nodes(data="source"):
  996. ... sources[source].add(v)
  997. >>> len(sources["a"])
  998. 1
  999. >>> len(sources["d"])
  1000. 2
  1001. To copy node attributes from the original graph to the new graph,
  1002. you can use a dictionary like the one constructed in the above
  1003. example::
  1004. >>> for source, nodes in sources.items():
  1005. ... for v in nodes:
  1006. ... B.nodes[v].update(G.nodes[source])
  1007. Notes
  1008. -----
  1009. This function is not idempotent in the sense that the node labels in
  1010. the returned branching may be uniquely generated each time the
  1011. function is invoked. In fact, the node labels may not be integers;
  1012. in order to relabel the nodes to be more readable, you can use the
  1013. :func:`networkx.convert_node_labels_to_integers` function.
  1014. The current implementation of this function uses
  1015. :func:`networkx.prefix_tree`, so it is subject to the limitations of
  1016. that function.
  1017. """
  1018. if has_cycle(G):
  1019. msg = "dag_to_branching is only defined for acyclic graphs"
  1020. raise nx.HasACycle(msg)
  1021. paths = root_to_leaf_paths(G)
  1022. B = nx.prefix_tree(paths)
  1023. # Remove the synthetic `root`(0) and `NIL`(-1) nodes from the tree
  1024. B.remove_node(0)
  1025. B.remove_node(-1)
  1026. return B
  1027. @not_implemented_for("undirected")
  1028. @nx._dispatchable
  1029. def v_structures(G):
  1030. """Yields 3-node tuples that represent the v-structures in `G`.
  1031. Colliders are triples in the directed acyclic graph (DAG) where two parent nodes
  1032. point to the same child node. V-structures are colliders where the two parent
  1033. nodes are not adjacent. In a causal graph setting, the parents do not directly
  1034. depend on each other, but conditioning on the child node provides an association.
  1035. Parameters
  1036. ----------
  1037. G : graph
  1038. A networkx `~networkx.DiGraph`.
  1039. Yields
  1040. ------
  1041. A 3-tuple representation of a v-structure
  1042. Each v-structure is a 3-tuple with the parent, collider, and other parent.
  1043. Raises
  1044. ------
  1045. NetworkXNotImplemented
  1046. If `G` is an undirected graph.
  1047. Examples
  1048. --------
  1049. >>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
  1050. >>> nx.is_directed_acyclic_graph(G)
  1051. True
  1052. >>> list(nx.dag.v_structures(G))
  1053. [(0, 4, 2), (0, 5, 1), (4, 5, 1)]
  1054. See Also
  1055. --------
  1056. colliders
  1057. Notes
  1058. -----
  1059. This function was written to be used on DAGs, however it works on cyclic graphs
  1060. too. Since colliders are referred to in the cyclic causal graph literature
  1061. [2]_ we allow cyclic graphs in this function. It is suggested that you test if
  1062. your input graph is acyclic as in the example if you want that property.
  1063. References
  1064. ----------
  1065. .. [1] `Pearl's PRIMER <https://bayes.cs.ucla.edu/PRIMER/primer-ch2.pdf>`_
  1066. Ch-2 page 50: v-structures def.
  1067. .. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
  1068. "Discovering cyclic causal models with latent variables:
  1069. a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
  1070. Conference on Uncertainty in Artificial Intelligence, pg 301–310,
  1071. `doi:10.5555/3023638.3023669 <https://dl.acm.org/doi/10.5555/3023638.3023669>`_
  1072. """
  1073. for p1, c, p2 in colliders(G):
  1074. if not (G.has_edge(p1, p2) or G.has_edge(p2, p1)):
  1075. yield (p1, c, p2)
  1076. @not_implemented_for("undirected")
  1077. @nx._dispatchable
  1078. def colliders(G):
  1079. """Yields 3-node tuples that represent the colliders in `G`.
  1080. In a Directed Acyclic Graph (DAG), if you have three nodes A, B, and C, and
  1081. there are edges from A to C and from B to C, then C is a collider [1]_ . In
  1082. a causal graph setting, this means that both events A and B are "causing" C,
  1083. and conditioning on C provide an association between A and B even if
  1084. no direct causal relationship exists between A and B.
  1085. Parameters
  1086. ----------
  1087. G : graph
  1088. A networkx `~networkx.DiGraph`.
  1089. Yields
  1090. ------
  1091. A 3-tuple representation of a collider
  1092. Each collider is a 3-tuple with the parent, collider, and other parent.
  1093. Raises
  1094. ------
  1095. NetworkXNotImplemented
  1096. If `G` is an undirected graph.
  1097. Examples
  1098. --------
  1099. >>> G = nx.DiGraph([(1, 2), (0, 4), (3, 1), (2, 4), (0, 5), (4, 5), (1, 5)])
  1100. >>> nx.is_directed_acyclic_graph(G)
  1101. True
  1102. >>> list(nx.dag.colliders(G))
  1103. [(0, 4, 2), (0, 5, 4), (0, 5, 1), (4, 5, 1)]
  1104. See Also
  1105. --------
  1106. v_structures
  1107. Notes
  1108. -----
  1109. This function was written to be used on DAGs, however it works on cyclic graphs
  1110. too. Since colliders are referred to in the cyclic causal graph literature
  1111. [2]_ we allow cyclic graphs in this function. It is suggested that you test if
  1112. your input graph is acyclic as in the example if you want that property.
  1113. References
  1114. ----------
  1115. .. [1] `Wikipedia: Collider in causal graphs <https://en.wikipedia.org/wiki/Collider_(statistics)>`_
  1116. .. [2] A Hyttinen, P.O. Hoyer, F. Eberhardt, M J ̈arvisalo, (2013)
  1117. "Discovering cyclic causal models with latent variables:
  1118. a general SAT-based procedure", UAI'13: Proceedings of the Twenty-Ninth
  1119. Conference on Uncertainty in Artificial Intelligence, pg 301–310,
  1120. `doi:10.5555/3023638.3023669 <https://dl.acm.org/doi/10.5555/3023638.3023669>`_
  1121. """
  1122. for node in G.nodes:
  1123. for p1, p2 in combinations(G.predecessors(node), 2):
  1124. yield (p1, node, p2)