spectral.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. Spectral bipartivity measure.
  3. """
  4. import networkx as nx
  5. __all__ = ["spectral_bipartivity"]
  6. @nx._dispatchable(edge_attrs="weight")
  7. def spectral_bipartivity(G, nodes=None, weight="weight"):
  8. """Returns the spectral bipartivity.
  9. Parameters
  10. ----------
  11. G : NetworkX graph
  12. nodes : list or container optional(default is all nodes)
  13. Nodes to return value of spectral bipartivity contribution.
  14. weight : string or None optional (default = 'weight')
  15. Edge data key to use for edge weights. If None, weights set to 1.
  16. Returns
  17. -------
  18. sb : float or dict
  19. A single number if the keyword nodes is not specified, or
  20. a dictionary keyed by node with the spectral bipartivity contribution
  21. of that node as the value.
  22. Examples
  23. --------
  24. >>> from networkx.algorithms import bipartite
  25. >>> G = nx.path_graph(4)
  26. >>> bipartite.spectral_bipartivity(G)
  27. 1.0
  28. Notes
  29. -----
  30. This implementation uses Numpy (dense) matrices which are not efficient
  31. for storing large sparse graphs.
  32. See Also
  33. --------
  34. color
  35. References
  36. ----------
  37. .. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of
  38. bipartivity in complex networks", PhysRev E 72, 046105 (2005)
  39. """
  40. import scipy as sp
  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 float(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.item(i, i) / expA.item(i, i)
  56. return sb