New TTree has 0 entries

I would like to create a new TTree based on information in an existing TTree. (I plan to add it as a friend later.) However, the created TTree ends up with 0 entries:

In [1]: import ROOT

In [2]: infile = ROOT.TFile.Open('../DVnTuples.root')

In [3]: intree = infile.Get('X2LcpLcpTree/DecayTree')

In [4]: outfile = ROOT.TFile.Open('../test.root', 'update')

In [5]: outtree = ROOT.TTree('testtree', 'testing testing 123')

In [6]: from array import array

In [7]: mytest = array('f', [0])

In [8]: mybranch = outtree.Branch('mytest', mytest, 'mytest/F')

In [9]: for ientry in xrange(intree.GetEntries()):
   ...:     intree.GetEntry(ientry)
   ...:     mytest[0] = intree.X_ENDVERTEX_X
   ...:     mybranch.Fill()
   ...:     

In [10]: outfile.cd()
Out[10]: True

In [11]: outtree.Write('', ROOT.TObject.kOverwrite)
Out[11]: 388

In [12]: outtree.GetEntries()
Out[12]: 0L

What am I doing wrong? I suspect it has something to do with telling outtree what entry it should be on, but this is the method shown in the tutorials…


ROOT Version: 6.17/01
Platform: macOS
Compiler: Not Provided


I (re)discovered the solution. If the TTree is newly created, one must call TTree::Fill()TBranch::Fill() will not properly fill the branches. However, calling TTree::Fill() on a tree that already exists results in new entries being created and 0s being filled for existing branches–in this case, one must call TBranch::Fill().

Therefore, it is necessary to know whether the TTree has been newly created and only call TTree::Fill() in that case. One must also be careful not to call TBranch::Fill() in this case–doing so will result in each value being filled twice (that is, entries 0 & 1 will have the entry 0 value, entries 2 & 3 will have the entry 1 value, and so on). The resulting tree is then truncated so it ends up with the proper number of entries.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.