THStack and PyROOT problem

Hi,

I have a problem with THStack in PyROOT.

I have various root file containing a same histo (same name) and if I add histo to a THStack in a loop…only the last histo is stored in the stack.

For example:

If I do the following everything works fine:

from ROOT import TH1F, TFile, TCanvas, THStack

flist = [ 'file1.root', 'file2.root' ]
file2 = TFile( flist[1] )
file1 = TFile( flist[0] )

ths1 = THStack ("test1","test1")

h1 = file1.Get("Meff_NoLepton")
ths1.Add(h1)
h1 = file2.Get("Meff_NoLepton")
h1.SetFillColor(4)
ths1.Add(h1)

ths1.ls()

c1 = TCanvas('c1','test',10,10,800,600)
c1.Divide(2,1)
c1.cd(1)
ths1.Draw("nostack")

With the code above I get two histo on the same plot, as expected. And in the output of ths1.ls() I see two objects in memory:

THStack Name= test1 Title= test1 Option=
 OBJ: TH1F      Meff_NoLepton   Meff 0-lepton channel : 0 at: 0xabdcdb8
 OBJ: TH1F      Meff_NoLepton   Meff 0-lepton channel : 0 at: 0xac04560

But when I use a loop as in the following…

flist = [ 'file1.root', 'file2.root' ]

ths2 = THStack ("test2","test2")

for j in flist:
    f1 = TFile(j)
    h1 = f1.Get("Meff_NoLepton")
    ths2.Add(h1)

ths2.ls()

c1.cd(2)
ths2.Draw("nostack")

…I get a plot with only one histo: the histo from the last loaded file.
And from ths2.ls() I can see only one object in memory:

THStack Name= test2 Title= test2 Option=
 OBJ: TH1F      Meff_NoLepton   Meff 0-lepton channel : 0 at: 0xa0d83f0

Sure I miss something very stupid… :stuck_out_tongue:
Any idea of what? May you help me?

Thanks a lot!! :slight_smile:

Ric.

P.S. I also tried with Clone(), but it did not happen.

Ric,

‘f1’ is local to the loop, and since you call the TFile constructor, python owns is. Thus, in each iteration, the previous TFile is destroyed (closed) and it takes the histos with it. Cloning does not work, b/c the new histo is created in the current directory, which is the file you just opened.

Either keep the directories open by keeping a reference to each TFile, or do gROOT.cd() to switch to the top directory before cloning.

HTH,
Wim

P.S. I haven’t actually tested the above statement; I’ll be offline for a week and am in a bit of a hurry.

Thanks a lot Wim!

As you suggested I changed directory with gROOT.cd() before cloning the histo, and now everything works.

from ROOT import gROOT
for j in flist:
    f1 = TFile(j)
    h1 = f1.Get("Meff_NoLepton")
    gROOT.cd()
    hnew = h1.Clone()
    ths2.Add(hnew) 

Thanks a lot again! :slight_smile:

Ric.