GraphStat.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. altgraph.GraphStat - Functions providing various graph statistics
  3. =================================================================
  4. """
  5. def degree_dist(graph, limits=(0, 0), bin_num=10, mode="out"):
  6. """
  7. Computes the degree distribution for a graph.
  8. Returns a list of tuples where the first element of the tuple is the
  9. center of the bin representing a range of degrees and the second element
  10. of the tuple are the number of nodes with the degree falling in the range.
  11. Example::
  12. ....
  13. """
  14. deg = []
  15. if mode == "inc":
  16. get_deg = graph.inc_degree
  17. else:
  18. get_deg = graph.out_degree
  19. for node in graph:
  20. deg.append(get_deg(node))
  21. if not deg:
  22. return []
  23. results = _binning(values=deg, limits=limits, bin_num=bin_num)
  24. return results
  25. _EPS = 1.0 / (2.0 ** 32)
  26. def _binning(values, limits=(0, 0), bin_num=10):
  27. """
  28. Bins data that falls between certain limits, if the limits are (0, 0) the
  29. minimum and maximum values are used.
  30. Returns a list of tuples where the first element of the tuple is the
  31. center of the bin and the second element of the tuple are the counts.
  32. """
  33. if limits == (0, 0):
  34. min_val, max_val = min(values) - _EPS, max(values) + _EPS
  35. else:
  36. min_val, max_val = limits
  37. # get bin size
  38. bin_size = (max_val - min_val) / float(bin_num)
  39. bins = [0] * (bin_num)
  40. # will ignore these outliers for now
  41. for value in values:
  42. try:
  43. if (value - min_val) >= 0:
  44. index = int((value - min_val) / float(bin_size))
  45. bins[index] += 1
  46. except IndexError:
  47. pass
  48. # make it ready for an x,y plot
  49. result = []
  50. center = (bin_size / 2) + min_val
  51. for i, y in enumerate(bins):
  52. x = center + bin_size * i
  53. result.append((x, y))
  54. return result