Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/networkx/algorithms/components/semiconnected.py: 54%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

13 statements  

1"""Semiconnectedness.""" 

2 

3import networkx as nx 

4from networkx.utils import not_implemented_for, pairwise 

5 

6__all__ = ["is_semiconnected"] 

7 

8 

9@not_implemented_for("undirected") 

10@nx._dispatchable 

11def is_semiconnected(G): 

12 r"""Returns True if the graph is semiconnected, False otherwise. 

13 

14 A graph is semiconnected if and only if for any pair of nodes, either one 

15 is reachable from the other, or they are mutually reachable. 

16 

17 This function uses a theorem that states that a DAG is semiconnected 

18 if for any topological sort, for node $v_n$ in that sort, there is an 

19 edge $(v_i, v_{i+1})$. That allows us to check if a non-DAG `G` is 

20 semiconnected by condensing the graph: i.e. constructing a new graph `H` 

21 with nodes being the strongly connected components of `G`, and edges 

22 (scc_1, scc_2) if there is a edge $(v_1, v_2)$ in `G` for some 

23 $v_1 \in scc_1$ and $v_2 \in scc_2$. That results in a DAG, so we compute 

24 the topological sort of `H` and check if for every $n$ there is an edge 

25 $(scc_n, scc_{n+1})$. 

26 

27 Parameters 

28 ---------- 

29 G : NetworkX graph 

30 A directed graph. 

31 

32 Returns 

33 ------- 

34 semiconnected : bool 

35 True if the graph is semiconnected, False otherwise. 

36 

37 Raises 

38 ------ 

39 NetworkXNotImplemented 

40 If the input graph is undirected. 

41 

42 NetworkXPointlessConcept 

43 If the graph is empty. 

44 

45 Examples 

46 -------- 

47 >>> G = nx.path_graph(4, create_using=nx.DiGraph()) 

48 >>> print(nx.is_semiconnected(G)) 

49 True 

50 >>> G = nx.DiGraph([(1, 2), (3, 2)]) 

51 >>> print(nx.is_semiconnected(G)) 

52 False 

53 

54 See Also 

55 -------- 

56 is_strongly_connected 

57 is_weakly_connected 

58 is_connected 

59 is_biconnected 

60 """ 

61 if len(G) == 0: 

62 raise nx.NetworkXPointlessConcept( 

63 "Connectivity is undefined for the null graph." 

64 ) 

65 

66 if not nx.is_weakly_connected(G): 

67 return False 

68 

69 H = nx.condensation(G) 

70 

71 return all(H.has_edge(u, v) for u, v in pairwise(nx.topological_sort(H)))