Looping through TTree

Hi,

I wanted to loop through the contents of a Tree in PyROOT. Its quite straight forward and I would do something like the following.

for i in range(myTree.GetEntriesFast()):
    val = myTree.myBranch

However now I want to do the same using a function which takes the branch name as the argument. The idea is to run this function inside the for loop and retrieve the current value of the variable of interest held in the branch.

def getCurrentValue(branchName):
   return myTree.branchName

for i in range(myTree.GetEntriesFast()):
    val = getCurrentValue("branchName")

But this doesn’t work since the branchname is a str() object. I have tried converting the python str() object to a ROOT.TBranch object. But doesn’t work. Does any body have more insight on how to achieve this.

Hi,

the first code snippet does not loop over the values: you’ll simply retrieve the same value over and over again. The second snippet could pass the myTree and the branch name both to the function, then do myTree.GetBranch(“branchName”) inside it.

However, what’s wrong with:for event in myTree: val = event.branchName
Cheers,
Wim

Hi Wim,

Yeah the first code snippet is wrong. I was just typing it here on the fly.

for i in range(myTree.GetEntriesFast()):
    myTree.GetEntry(i)
    val = myTree.myBranchName

# or simply as you suggested 
for event in myTree
    val = myTree.myBranchName

There is nothing wrong with this approach. But I am designing a plot script class with an execute() method. Where the execute method should be called within the loop. Inside the execute loop I would like to retrieve the value held in the branches for the current loop index.

def execute():
    getCurrentValue(branchName)

 ....

for i in range(myTree.GetEntriesFast()):
    myTree.GetEntry()
    execute()
finalize()

If I understand it correctly, If I use the GetBranch(“branchname”) method, I get the whole branch. I don’t want that, I just want the value held in the branch at the current loop index.

cheers

Rohin.

Hi Wim,

I found the solution. Its quite simple and straightforward.

def getCurrentValue(event, branchName):
     return getattr(event,branchname)

# and inside the loop
for event in self.myTree:
    getCurrentValue(event,"myBranch")

This is sufficient to solve my issue.

val  = mytree.branchName 
val  = getattr(mytree,"branchName")

are the same.

cheers

Rohin.