I have simple code to write new branches to an existing TTree, but the resulting root file seems to contain two copies of the same ttree. Can anyone see why in the code below?
The problem I’m trying to solve is that I have an existing TTree that contains a few arrays of known length. I’m writing a function to loop through all entries in the TTree, and then loop over all elements in the array to find elements that pass certain cuts and place those in a new branch.
I’m still thinking how I can simplify the code below, or if it could be made faster.
[code]from ROOT import TFile, TTree # Import any ROOT class you want
from array import array # used to make Float_t array ROOT wants
ttreeName = “NTuples/Analysis” # TTree name in all files
listOfFiles = [“testing.root”]
for fileName in listOfFiles:
file = TFile(fileName, “update”) # Open TFile
print “Error opening %s, exiting…” % fileName
print “Opened %s, looking for %s…” % (fileName, ttreeName)
ttree = TTree() # Create empty TTree, and try: # try to get TTree from file. file.GetObject(ttreeName, ttree) except: print "Error: %s not found in %s, exiting..." % (ttreeName, fileName) sys.exit(0) print "found." # Add those variables into the TTree print "Adding new branches:\n ", listOfNewBranches =  newJetPt = array( 'f',  ) listOfNewBranches.append( ttree.Branch("passjetPt", newJetPt, "passjetPt/F") ) newJetEta = array( 'f',  ) listOfNewBranches.append( ttree.Branch("passjetEta", newJetEta, "passjetEta/F") ) newJetPhi = array( 'f',  ) listOfNewBranches.append( ttree.Branch("passjetPhi", newJetPhi, "passjetPhi/F") ) newJetEmEnergyFraction = array( 'f',  ) listOfNewBranches.append( ttree.Branch("passjetEmEnergyFraction", newJetEmEnergyFraction, "passjetEmEnergyFraction/F") ) newJetFHPD = array( 'f',  ) listOfNewBranches.append( ttree.Branch("passjetFHPD", newJetFHPD, "passjetFHPD/F") ) # Loop over all the entries numOfEvents = ttree.GetEntries() for n in xrange(numOfEvents): newJetPt = 0.0 newJetEta = 0.0 newJetPhi = 0.0 newJetEmEnergyFraction = 0.0 newJetFHPD = 0.0 ttree.GetEntry(n) for i in 0,1,2,3: # Loop over the top 3 jets until we find one passing cuts if ttree.jetPt[i] < 5.0: break if (ttree.emEnergyFraction[i]>0.01) and (ttree.fHPD[i]<0.98): # Found a jet that passes cuts newJetPt = ttree.jetPt[i] newJetEta = ttree.jetEta[i] newJetPhi = ttree.jetPhi[i] newJetEmEnergyFraction = ttree.emEnergyFraction[i] newJetFHPD = ttree.fHPD[i] break # Fill new branches for newBranch in sorted(listOfNewBranches): newBranch.Fill() file.Write() file.Close()[/code]