Skip to content

Instantly share code, notes, and snippets.

@jpata
Created May 11, 2020 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpata/ca75021ecf753daec1f503e392be430f to your computer and use it in GitHub Desktop.
Save jpata/ca75021ecf753daec1f503e392be430f to your computer and use it in GitHub Desktop.
ROOT histogram bins
import ROOT
from test_uproot import vals
if __name__ == "__main__":
h = ROOT.TH1D("h", "h", 10, 0, 1)
for v in vals:
h.Fill(v)
print("h1")
for b in range(h.GetNbinsX()+2):
print("bin={} content={:.2f} error={:.2f} low={}".format(
b, h.GetBinContent(b), h.GetBinError(b), h.GetBinLowEdge(b)
))
fi = ROOT.TFile.Open("out_uproot.root")
h2 = fi.Get("h")
print("h2")
for b in range(h2.GetNbinsX()+2):
print("bin={} content={:.2f} error={:.2f} low={}".format(
b, h2.GetBinContent(b), h2.GetBinError(b), h2.GetBinLowEdge(b)
))
import numpy as np
from uproot_methods.classes.TH1 import from_numpy
import uproot
from hepaccelerate.backend_cpu import fill_histogram
#data array to put into histogram
vals = [-0.1, 0, 0.2, 0.9, 1.0, 1.1]
def to_th1(hdict, name):
content = np.array(hdict["contents"])
content_w2 = np.array(hdict["contents_w2"])
edges = np.array(hdict["edges"])
#remove inf/nan just in case
content[np.isinf(content)] = 0
content_w2[np.isinf(content_w2)] = 0
content[np.isnan(content)] = 0
content_w2[np.isnan(content_w2)] = 0
#update the error bars
centers = (edges[:-1] + edges[1:]) / 2.0
th1 = from_numpy((content, edges))
th1._fName = name
#note, fix needed here
th1._fSumw2[1:-1] = np.array(hdict["contents_w2"])
th1._fTsumw2 = np.array(hdict["contents_w2"]).sum()
th1._fTsumwx2 = np.array(hdict["contents_w2"] * centers).sum()
return th1
if __name__ == "__main__":
#explicitly include overflow as a bin 1.1
bins = np.array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1], np.float32)
out_w = np.zeros((len(bins) - 1), np.float32)
out_w2 = np.zeros((len(bins) - 1), np.float32)
fill_histogram(np.array(vals, np.float32), np.ones_like(vals, dtype=np.float32), bins, out_w, out_w2)
h2 = to_th1({
"contents": out_w,
"contents_w2": out_w2,
"edges": bins
}, name="h2")
fi = uproot.recreate("out_uproot.root")
fi["h"] = h2
fi.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment