Fill TTree in pyroot loop

Dear,

I trying to fill a new tree from events using tchain:

 outfile = ROOT.TFile("Smaller.root",'recreate')
 get_var = ROOT.vector('float')(0)
 subtree = ROOT.TTree("subtree","subtree")
 subtree.Branch("var", get_var,"var/D")
 for iev in chain:
 if (a few cuts):
 get_var = iev.var
 subtree.Fill()
 subtree.Write()
 outfile.Close()

This is running but the values are all 0, is there something I’m doing wrong?

@etejedor can correct me, but I think your code should be something like that:

outfile = ROOT.TFile("Smaller.root",'recreate')
get_var = ROOT.vector('float')(0)
subtree = ROOT.TTree("subtree","subtree")
subtree.Branch("var", "vector", get_var)
for iev in chain:
if (a few cuts):
get_var.push_back(iev.var)
subtree.Fill()
subtree.Write()
outfile.Close()

Hi Bertrand,

Many thanks for your help, it works fine!
I just got an error saying:

Error in TTree::Bronch: Cannot find class:vector

which for some reason I could fix by removing “vector” :slight_smile:

Well, I was not sure about the syntax, try with

subtree.Branch("var", "std::vector<float>", get_var)

Yes this works too :slight_smile:

Once again, many thanks for your help!

1 Like

Thanks @bellenot for the answer, I just wanted to add that the TTree documentation now includes information about PyROOT (you need to look for the PyROOT box at the end of the C++ docs):

Among others, it includes documentation for the pythonization of Branch. Here you can even do subtree.Branch("var", get_var) (without the type).

1 Like