Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/algorithms/bipartite/spectral.py: 22%

18 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-10-20 07:00 +0000

1""" 

2Spectral bipartivity measure. 

3""" 

4import networkx as nx 

5 

6__all__ = ["spectral_bipartivity"] 

7 

8 

9@nx._dispatch(edge_attrs="weight") 

10def spectral_bipartivity(G, nodes=None, weight="weight"): 

11 """Returns the spectral bipartivity. 

12 

13 Parameters 

14 ---------- 

15 G : NetworkX graph 

16 

17 nodes : list or container optional(default is all nodes) 

18 Nodes to return value of spectral bipartivity contribution. 

19 

20 weight : string or None optional (default = 'weight') 

21 Edge data key to use for edge weights. If None, weights set to 1. 

22 

23 Returns 

24 ------- 

25 sb : float or dict 

26 A single number if the keyword nodes is not specified, or 

27 a dictionary keyed by node with the spectral bipartivity contribution 

28 of that node as the value. 

29 

30 Examples 

31 -------- 

32 >>> from networkx.algorithms import bipartite 

33 >>> G = nx.path_graph(4) 

34 >>> bipartite.spectral_bipartivity(G) 

35 1.0 

36 

37 Notes 

38 ----- 

39 This implementation uses Numpy (dense) matrices which are not efficient 

40 for storing large sparse graphs. 

41 

42 See Also 

43 -------- 

44 color 

45 

46 References 

47 ---------- 

48 .. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of 

49 bipartivity in complex networks", PhysRev E 72, 046105 (2005) 

50 """ 

51 import scipy as sp 

52 

53 nodelist = list(G) # ordering of nodes in matrix 

54 A = nx.to_numpy_array(G, nodelist, weight=weight) 

55 expA = sp.linalg.expm(A) 

56 expmA = sp.linalg.expm(-A) 

57 coshA = 0.5 * (expA + expmA) 

58 if nodes is None: 

59 # return single number for entire graph 

60 return coshA.diagonal().sum() / expA.diagonal().sum() 

61 else: 

62 # contribution for individual nodes 

63 index = dict(zip(nodelist, range(len(nodelist)))) 

64 sb = {} 

65 for n in nodes: 

66 i = index[n] 

67 sb[n] = coshA[i, i] / expA[i, i] 

68 return sb