utils.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import io
  2. import sys
  3. import itertools as it
  4. import ROOT
  5. class OutputCapture:
  6. def __init__(self):
  7. self.my_stdout = io.StringIO()
  8. self.my_stderr = io.StringIO()
  9. def get_stdout(self):
  10. self.my_stdout.seek(0)
  11. return self.my_stdout.read()
  12. def get_stderr(self):
  13. self.my_stderr.seek(0)
  14. return self.my_stderr.read()
  15. def __enter__(self):
  16. self.stdout = sys.stdout
  17. self.stderr = sys.stderr
  18. sys.stdout = self.my_stdout
  19. sys.stderr = self.my_stderr
  20. def __exit__(self, *args):
  21. sys.stdout = self.stdout
  22. sys.stderr = self.stderr
  23. self.stdout = None
  24. self.stderr = None
  25. def bin_range(n, end=None):
  26. if end is None:
  27. return range(1, n+1)
  28. else:
  29. return range(n+1, end+1)
  30. def normalize_columns(hist2d):
  31. normHist = ROOT.TH2D(hist2d)
  32. cols, rows = hist2d.GetNbinsX(), hist2d.GetNbinsY()
  33. for col in bin_range(cols):
  34. sum_ = 0;
  35. for row in bin_range(rows):
  36. sum_ += hist2d.GetBinContent(col, row)
  37. if sum_ == 0:
  38. continue
  39. for row in bin_range(rows):
  40. norm = hist2d.GetBinContent(col, row) / sum_
  41. normHist.SetBinContent(col, row, norm)
  42. return normHist
  43. def stack_hist(hists, labels=None, id_="stack", title="", enable_fill=False, normalize_to=0):
  44. """hists should be a list of TH1D objects
  45. returns a new stacked histogram
  46. """
  47. colors = it.cycle([ROOT.kRed,ROOT.kBlue, ROOT.kGreen])
  48. stack = ROOT.THStack(id_, title)
  49. if labels is None:
  50. labels = [hist.GetName() for hist in hists]
  51. for i, (hist, label, color) in enumerate(zip(hists, labels, colors)):
  52. hist_copy = hist
  53. hist_copy = hist.Clone(str(i)+"_clone")
  54. hist_copy.SetTitle(label)
  55. hist_copy.SetStats(False)
  56. if enable_fill:
  57. hist_copy.SetFillColorAlpha(color, 0.75)
  58. hist_copy.SetLineColorAlpha(color, 0.75)
  59. if normalize_to:
  60. integral = hist_copy.Integral()
  61. hist_copy.Scale(normalize_to/integral, "nosw2")
  62. hist_copy.SetStats(False)
  63. stack.Add(hist_copy)
  64. return stack