Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve histogram from stack via RootFileReader.retrieve_object #261

Merged
merged 5 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion hepdata_lib/root_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ def retrieve_object(self, path_to_object):
try:
obj = self.tfile.Get(parts[0])
for part in parts[1:]:
obj = obj.GetPrimitive(part)
if isinstance(obj,r.THStack): # pylint: disable=no-member
obj = obj.GetHists().FindObject(part)
else:
obj = obj.GetPrimitive(part)

assert obj

Expand Down
38 changes: 38 additions & 0 deletions tests/test_rootfilereader.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

@pytest.mark.needs_root
class TestRootFileReader(TestCase):
# pylint: disable=R0904
"""Test the RootFileReader class."""

def test_tfile_setter(self):
Expand Down Expand Up @@ -784,6 +785,43 @@ def test_retrieve_object_canvas(self):
# Clean up
self.doCleanups()

def test_retrieve_object_stack(self):
'''Check that retrieve_object correctly reads from stack in canvas.'''
# Disable graphical output
ROOT.gROOT.SetBatch(ROOT.kTRUE) # pylint: disable=no-member

# Create test histogram, plot on canvas, save to file
tfile = make_tmp_root_file(testcase=self)
histogram = ROOT.TH1D("testhist", "testhist", 10, 0, 1) # pylint: disable=no-member
stack = ROOT.THStack("teststack","teststack") # pylint: disable=no-member
stack.Add(histogram)
path_to_file = tfile.GetName()

canvas = ROOT.TCanvas() # pylint: disable=no-member
stack.Draw("HIST")
canvas.Write("canvas")

reference = histogram.Clone("reference")
reference.SetDirectory(0)
if tfile:
tfile.Close()

# Read it back
reader = RootFileReader(path_to_file)
try:
readback = reader.retrieve_object("canvas/teststack/testhist")
except OSError:
print("RootFileReader.retrieve_object raised unexpected IOError!")
self.fail()

self.assertTrue(readback)
self.assertTrue(
histogram_compare_1d(reference, readback)
)

# Clean up
self.doCleanups()

def test_retrieve_object_canvas_tpad(self):
'''Check that retrieve_object correctly reads from canvas.'''
# Disable graphical output
Expand Down
Loading