semiconnected.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """Semiconnectedness."""
  2. import networkx as nx
  3. from networkx.utils import not_implemented_for, pairwise
  4. __all__ = ["is_semiconnected"]
  5. @not_implemented_for("undirected")
  6. @nx._dispatchable
  7. def is_semiconnected(G):
  8. r"""Returns True if the graph is semiconnected, False otherwise.
  9. A graph is semiconnected if and only if for any pair of nodes, either one
  10. is reachable from the other, or they are mutually reachable.
  11. This function uses a theorem that states that a DAG is semiconnected
  12. if for any topological sort, for node $v_n$ in that sort, there is an
  13. edge $(v_i, v_{i+1})$. That allows us to check if a non-DAG `G` is
  14. semiconnected by condensing the graph: i.e. constructing a new graph `H`
  15. with nodes being the strongly connected components of `G`, and edges
  16. (scc_1, scc_2) if there is a edge $(v_1, v_2)$ in `G` for some
  17. $v_1 \in scc_1$ and $v_2 \in scc_2$. That results in a DAG, so we compute
  18. the topological sort of `H` and check if for every $n$ there is an edge
  19. $(scc_n, scc_{n+1})$.
  20. Parameters
  21. ----------
  22. G : NetworkX graph
  23. A directed graph.
  24. Returns
  25. -------
  26. semiconnected : bool
  27. True if the graph is semiconnected, False otherwise.
  28. Raises
  29. ------
  30. NetworkXNotImplemented
  31. If the input graph is undirected.
  32. NetworkXPointlessConcept
  33. If the graph is empty.
  34. Examples
  35. --------
  36. >>> G = nx.path_graph(4, create_using=nx.DiGraph())
  37. >>> print(nx.is_semiconnected(G))
  38. True
  39. >>> G = nx.DiGraph([(1, 2), (3, 2)])
  40. >>> print(nx.is_semiconnected(G))
  41. False
  42. See Also
  43. --------
  44. is_strongly_connected
  45. is_weakly_connected
  46. is_connected
  47. is_biconnected
  48. """
  49. if len(G) == 0:
  50. raise nx.NetworkXPointlessConcept(
  51. "Connectivity is undefined for the null graph."
  52. )
  53. if not nx.is_weakly_connected(G):
  54. return False
  55. H = nx.condensation(G)
  56. return all(H.has_edge(u, v) for u, v in pairwise(nx.topological_sort(H)))