spectral.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """
  2. Spectral bipartivity measure.
  3. """
  4. import networkx as nx
  5. __all__ = ["spectral_bipartivity"]
  6. def spectral_bipartivity(G, nodes=None, weight="weight"):
  7. """Returns the spectral bipartivity.
  8. Parameters
  9. ----------
  10. G : NetworkX graph
  11. nodes : list or container optional(default is all nodes)
  12. Nodes to return value of spectral bipartivity contribution.
  13. weight : string or None optional (default = 'weight')
  14. Edge data key to use for edge weights. If None, weights set to 1.
  15. Returns
  16. -------
  17. sb : float or dict
  18. A single number if the keyword nodes is not specified, or
  19. a dictionary keyed by node with the spectral bipartivity contribution
  20. of that node as the value.
  21. Examples
  22. --------
  23. >>> from networkx.algorithms import bipartite
  24. >>> G = nx.path_graph(4)
  25. >>> bipartite.spectral_bipartivity(G)
  26. 1.0
  27. Notes
  28. -----
  29. This implementation uses Numpy (dense) matrices which are not efficient
  30. for storing large sparse graphs.
  31. See Also
  32. --------
  33. color
  34. References
  35. ----------
  36. .. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of
  37. bipartivity in complex networks", PhysRev E 72, 046105 (2005)
  38. """
  39. import scipy as sp
  40. import scipy.linalg # call as sp.linalg
  41. nodelist = list(G) # ordering of nodes in matrix
  42. A = nx.to_numpy_array(G, nodelist, weight=weight)
  43. expA = sp.linalg.expm(A)
  44. expmA = sp.linalg.expm(-A)
  45. coshA = 0.5 * (expA + expmA)
  46. if nodes is None:
  47. # return single number for entire graph
  48. return coshA.diagonal().sum() / expA.diagonal().sum()
  49. else:
  50. # contribution for individual nodes
  51. index = dict(zip(nodelist, range(len(nodelist))))
  52. sb = {}
  53. for n in nodes:
  54. i = index[n]
  55. sb[n] = coshA[i, i] / expA[i, i]
  56. return sb