Reading values from TLeaf containing vector<double> type data in PyROOT

Hello everyone

I have a .root file that contains the structure as: TDirectory -> TTree -> TBranch -> TLeaf. Few TBranches contain only one TLeaf which contains data of type vector. I want to read the data using PyROOT. I have been able to access each leaf from this file structure. But, I am unable to read the vector data contained in the leaf. Can anyone guide or point me to some tutorial or code snippet from where I can get a solution to this?

Best regards

Hi,
From Python something like:

vector = file_name.tree_name.branch_name 

should work if the branch with name branch_name contains the vector

Lorenzo

Thanks for the response. Will try that and update…

Hello

I tried what you had suggested but it doesn’t work as the .root file also contains a directory. When I do:
dir = file_name.directory_name
this works and I can see that dir is assigned the pointer to the directory. But it doesn’t work when I do:
tree = file_name.directory_name.tree_name
It throws an error:
AttributeError: 'TDirectoryFile' object has no attribute 'tree'

Shubham

Hi,
Please try:

file = TFile.Open("file_name.root")
tree = file.Get("dir_name/tree_name")
for event in tree:
   v = tree.branch_name
   ...

Hello

This I think iterates through the vector and returns the pointer to the vector as many times as the size of the vector.

<ROOT.vector<double> object at 0x5b5ef70>
<ROOT.vector<double> object at 0x5b5ef70>
<ROOT.vector<double> object at 0x5b5ef70>
<ROOT.vector<double> object at 0x5b5ef70>
<ROOT.vector<double> object at 0x5b5ef70>
.
.
.
. 

So, I think this will work but I am unable to dereference the pointer and get the values.

This iterates over the entries of the tree and gets the vector branch value for every entry of the tree. When you are processing a particular entry of the tree, you can iterate over the values of the current vector or access particular positions of it:

file = TFile.Open("file_name.root")
tree = file.Get("dir_name/tree_name")
for event in tree:
   v = tree.branch_name
   for elem in v:
       print(elem)
   print(v[0])
1 Like

Hello

This worked. Thanks a lot. :slight_smile:

Best regards
Shubham

Hi

Just asking out of curiosity, is it possible to access the vector by passing a string to some function (like we did to get the tree in the previous line), instead of doing tree.branch_name? I mean something like:
v = tree.someGetFunction("branch_name")

Hi,
Yes, you can do getattr(tree, 'branch_name').
Cheers,
Enric

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