Problem with setattr and saving values in TBranch with pyROOT

Hello

I am trying to fill several branches by doing something

setattr(self, "{0:s}Cor_T1_pt{1:s}{2:s}".format(mfl, ss, dr), [pmet[2]])

and that works fine while looping/filling the tree, because I can see proper values when printing on the fly

 print  "{0:s}Cor_T1_pt{1:s}{2:s}".format(mfl, ss, dr), getattr(self,"{0:s}Cor_T1_pt{1:s}{2:s}".format(mfl, ss, dr) ), pmet[2]
...
METCor_T1_ptJESUp [68.84608395743106] 68.8460839574
METCor_T1_ptJESDown [68.84608395743106] 68.8460839574

However, when I open and do an Events->Scan("METCor_T1_ptJESUp") the branch is filled with zeroes…What am I missing?

Thanks

Maybe @etejedor can help

Hello,

In order to fill a new branch of a TTree, you need to:

  1. Create the branch via TTree::Branch, where you specify from which address the branch should be filled.
  2. Go in a loop where you modify the content pointed by the aforementioned address, and then call TTree::Fill.

This is an example: ROOT: tutorials/tree/tree0.C File Reference

In the TTree documentation (ROOT: TTree Class Reference) you can find information on how to use TTree::Branch for Python (look for the PyROOT box after the C++ docs).

You could also consider learning how to use RDataFrame:

https://root.cern/doc/master/classROOT_1_1RDataFrame.html

to create new branches of a tree and snapshot them into a new file.

hello

Yes, I properly create the branches, and I of course do the TTree:Fill at the end, I just did not include those in my snippet to save some space/time. Also, the branch is filled properly, if I assign directly the value, but still as I said, not when I use the setattr(). I will invest some time on the RDataFrame anyway, thanks!

Hello,

I’m not sure why you do the setattr on self, is self the tree? Please note that setattr does not set the value of a branch, it just injects an attribute in a Python object but that won’t be taken into account by TTree::Fill, which fills with the address specified by TTree::Branch.

oh, I see, this would explain it then. So, what is the proper way of still using setattr() and also force the branch to be filled with the value I pass ? What I find strange anyway, is that when I print the value of the branch on the screen, it shows up correcty, but then, as I said, the branch while browsing the .root is not correct.

Hello,

setattr can’t be used to fill the branch, the branch is filled with a combination of TTree::Branch and Fill. You see the value while looping because you just injected it in the Python object, it’s there as an attribute, but it won’t have any effect for what concerns writing to the file.

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