semiconnected.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. def is_semiconnected(G, topo_order=None):
  7. """Returns True if the graph is semiconnected, False otherwise.
  8. A graph is semiconnected if, and only if, for any pair of nodes, either one
  9. is reachable from the other, or they are mutually reachable.
  10. Parameters
  11. ----------
  12. G : NetworkX graph
  13. A directed graph.
  14. topo_order: list or tuple, optional
  15. A topological order for G (if None, the function will compute one)
  16. Returns
  17. -------
  18. semiconnected : bool
  19. True if the graph is semiconnected, False otherwise.
  20. Raises
  21. ------
  22. NetworkXNotImplemented
  23. If the input graph is undirected.
  24. NetworkXPointlessConcept
  25. If the graph is empty.
  26. Examples
  27. --------
  28. >>> G = nx.path_graph(4, create_using=nx.DiGraph())
  29. >>> print(nx.is_semiconnected(G))
  30. True
  31. >>> G = nx.DiGraph([(1, 2), (3, 2)])
  32. >>> print(nx.is_semiconnected(G))
  33. False
  34. See Also
  35. --------
  36. is_strongly_connected
  37. is_weakly_connected
  38. is_connected
  39. is_biconnected
  40. """
  41. if len(G) == 0:
  42. raise nx.NetworkXPointlessConcept(
  43. "Connectivity is undefined for the null graph."
  44. )
  45. if not nx.is_weakly_connected(G):
  46. return False
  47. G = nx.condensation(G)
  48. if topo_order is None:
  49. topo_order = nx.topological_sort(G)
  50. return all(G.has_edge(u, v) for u, v in pairwise(topo_order))