histogram.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """
  2. histogram.py
  3. The functions in this module use a representation of a histogram that is a
  4. tuple containing an arr of N bin values, an array of N bin errors(symmetric)
  5. and an array of N+1 bin edges(N lower edges + 1 upper edge).
  6. For 2d histograms, It is similar, but the arrays are two dimensional and
  7. there are separate arrays for x-edges and y-edges.
  8. """
  9. import numpy as np
  10. from scipy.optimize import curve_fit
  11. def hist(th1, rescale_x=1.0, rescale_y=1.0):
  12. nbins = th1.GetNbinsX()
  13. edges = np.zeros(nbins+1, np.float32)
  14. values = np.zeros(nbins, np.float32)
  15. errors = np.zeros(nbins, np.float32)
  16. for i in range(nbins):
  17. edges[i] = th1.GetXaxis().GetBinLowEdge(i+1)
  18. values[i] = th1.GetBinContent(i+1)
  19. errors[i] = th1.GetBinError(i+1)
  20. edges[nbins] = th1.GetXaxis().GetBinUpEdge(nbins)
  21. edges *= rescale_x
  22. values *= rescale_y
  23. errors *= rescale_y
  24. return values, errors, edges
  25. def hist_bin_centers(h):
  26. _, _, edges = h
  27. return (edges[:-1] + edges[1:])/2.0
  28. def hist_slice(h, range_):
  29. values, errors, edges = h
  30. lim_low, lim_high = range_
  31. slice_ = np.logical_and(edges[:-1] > lim_low, edges[1:] < lim_high)
  32. last = len(slice_) - np.argmax(slice_[::-1])
  33. return (values[slice_],
  34. errors[slice_],
  35. np.concatenate([edges[:-1][slice_], [edges[last]]]))
  36. def hist_add(*hs):
  37. if len(hs) == 0:
  38. return np.zeros(0)
  39. vals, errs, edges = zip(*hs)
  40. return np.sum(vals, axis=0), np.sqrt(np.sum([err*err for err in errs], axis=0)), edges[0]
  41. def hist_integral(h, times_bin_width=True):
  42. values, errors, edges = h
  43. if times_bin_width:
  44. bin_widths = [abs(x2 - x1) for x1, x2 in zip(edges[:-1], edges[1:])]
  45. return sum(val*width for val, width in zip(values, bin_widths))
  46. else:
  47. return sum(values)
  48. def hist_scale(h, scale):
  49. values, errors, edges = h
  50. return values*scale, errors*scale, edges
  51. def hist_norm(h, norm=1):
  52. scale = norm/np.sum(h[0])
  53. return hist_scale(h, scale)
  54. def hist_mean(h):
  55. xs = hist_bin_centers(h)
  56. ys, _, _ = h
  57. return sum(x*y for x, y in zip(xs, ys)) / sum(ys)
  58. def hist_var(h):
  59. xs = hist_bin_centers(h)
  60. ys, _, _ = h
  61. mean = sum(x*y for x, y in zip(xs, ys)) / sum(ys)
  62. mean2 = sum((x**2)*y for x, y in zip(xs, ys)) / sum(ys)
  63. return mean2 - mean**2
  64. def hist_std(h):
  65. return np.sqrt(hist_var(h))
  66. def hist_stats(h):
  67. return {'int': hist_integral(h),
  68. 'sum': hist_integral(h, False),
  69. 'mean': hist_mean(h),
  70. 'var': hist_var(h),
  71. 'std': hist_std(h)}
  72. # def hist_slice2d(h, range_):
  73. # values, errors, xs, ys = h
  74. # last = len(slice_) - np.argmax(slice_[::-1])
  75. # (xlim_low, xlim_high), (ylim_low, ylim_high) = range_
  76. # slice_ = np.logical_and(xs[:-1, :-1] > xlim_low, xs[1:, 1:] < xlim_high,
  77. # ys[:-1, :-1] > ylim_low, ys[1:, 1:] < ylim_high)
  78. # last = len(slice_) - np.argmax(slice_[::-1])
  79. # return (values[slice_],
  80. # errors[slice_],
  81. # np.concatenate([edges[:-1][slice_], [edges[last]]]))
  82. def hist_fit(h, f, p0=None):
  83. values, errors, edges = h
  84. xs = hist_bin_centers(h)
  85. # popt, pcov = curve_fit(f, xs, values, p0=p0, sigma=errors)
  86. popt, pcov = curve_fit(f, xs, values, p0=p0)
  87. return popt, pcov
  88. def hist_rebin(h, range_, nbins):
  89. raise NotImplementedError()
  90. def hist2d(th2, rescale_x=1.0, rescale_y=1.0, rescale_z=1.0):
  91. """ Converts TH2 object to something amenable to
  92. plotting w/ matplotlab's pcolormesh.
  93. """
  94. nbins_x = th2.GetNbinsX()
  95. nbins_y = th2.GetNbinsY()
  96. xs = np.zeros((nbins_y+1, nbins_x+1), np.float32)
  97. ys = np.zeros((nbins_y+1, nbins_x+1), np.float32)
  98. values = np.zeros((nbins_y, nbins_x), np.float32)
  99. errors = np.zeros((nbins_y, nbins_x), np.float32)
  100. for i in range(nbins_x):
  101. for j in range(nbins_y):
  102. xs[j][i] = th2.GetXaxis().GetBinLowEdge(i+1)
  103. ys[j][i] = th2.GetYaxis().GetBinLowEdge(j+1)
  104. values[j][i] = th2.GetBinContent(i+1, j+1)
  105. errors[j][i] = th2.GetBinError(i+1, j+1)
  106. xs[nbins_y][i] = th2.GetXaxis().GetBinUpEdge(i)
  107. ys[nbins_y][i] = th2.GetYaxis().GetBinUpEdge(nbins_y)
  108. for j in range(nbins_y+1):
  109. xs[j][nbins_x] = th2.GetXaxis().GetBinUpEdge(nbins_x)
  110. ys[j][nbins_x] = th2.GetYaxis().GetBinUpEdge(j)
  111. xs *= rescale_x
  112. ys *= rescale_y
  113. values *= rescale_z
  114. errors *= rescale_z
  115. return values, errors, xs, ys
  116. def hist2d_norm(h, norm=1, axis=None):
  117. """
  118. :param h:
  119. :param norm: value to normalize the sum of axis to
  120. :param axis: which axis to normalize None is the sum over all bins, 0 is columns, 1 is rows.
  121. :return: The normalized histogram
  122. """
  123. values, errors, xs, ys = h
  124. with np.errstate(divide='ignore'):
  125. scale_values = norm / np.sum(values, axis=axis)
  126. scale_values[scale_values == np.inf] = 1
  127. scale_values[scale_values == -np.inf] = 1
  128. if axis == 1:
  129. scale_values.shape = (scale_values.shape[0], 1)
  130. values = values * scale_values
  131. errors = errors * scale_values
  132. return values, errors, xs.copy(), ys.copy()