Hello all,
I am trying to clone a histogram in PyROOT.
The histogram to be cloned is part of a user class that only has function scope. I thought by cloning and returning a new histogram, it wouldn’t disappear when the object that contained the original histogram disappeared. This, unfortunately, doesn’t seem to be the case.
I can manually create and fill and new TH1F histogram, but I was wondering if there was a better way.
Methods tried:
- Clone method: newh = oldhist.Clone(“newhist”)
- Copy constructor: newh = ROOT.TH1F( oldhist )
- Python copy module: newh = copy.deepcopy( oldh )
The full code is attached at the end of this message.
Thank you,
Sean
[code]
#!/usr/bin/env python
"""
Normalize a root histogram and save the normalized histogram to disk.
Sean McDaniel - mcdaniel@nscl.msu.edu
Created: 20 Oct 2008
Last updated: 24 Nov 2008
"""
import sys
import os
import getopt
Cern ROOT bindings
import ROOT
User
from loadrootfile import SingleHistogram
def normalize(fname, area_norm):
"""Normalize passed file. Normalization can either be to bin contents or area
depending on the passed parameters.
"""
print "Processing file: ", os.path.split(fname)[1]
# Normalize histogram to unit area
h = SingleHistogram(fname)
print h.histogram
hscaled = h.histogram.Clone("hscaled")
integral = hscaled.Integral()
# Normalize by area (rather than bin content) if the option is passed
if area_norm:
integral *= hscaled.GetBinWidth(0)
scale = 1/integral
print "Total area: ", integral
hscaled.Scale(scale)
return hscaled
def write(fname, histogram):
""“Write the new histogram to disk”""
base, ext = os.path.splitext(fname)
outfname = base + "_norm.root"
fout = ROOT.TFile(outfname,“NEW”)
histogram.Write()
fout.Close()
def main():
""“Execute program”""
# Parse command line options
try:
opts, args = getopt.getopt(sys.argv[1:],“ahd”,[“help”])
except getopt.error, msg:
print msg
print "for help use --help"
sys.exit(2)
# Set defaults
area_norm = False
display_hist = False
# Parse options
for o,a in opts:
if o in ("-h", "--help"):
print __doc__
sys.exit(0)
if o == "-a":
area_norm = True
if o == "-d":
display_hist = True
# Setup canvas is the option is passed
if display_hist:
canvas = ROOT.TCanvas("canvas","superposition",800,600)
# Process all files
for f in args:
histogram = normalize(f, area_norm)
print histogram
histogram.Draw()
raw_input()
if display_hist:
histogram.Draw()
raw_input("Enter to continue...")
write(f, histogram)
if name==“main”:
main()
print “Finished…”
[/code][/code]