PyROOT: Adding a branch to a tree

My goal is to add a branch with new varibles to an existing tree and save the tree out into a new file. The new files are created with the proper tree structure and the proper values in the new leaves. The problem is that I can’t talk ROOT into saving out the values for the other leaves.

Any ideas on what I’m doing wrong?

[code]def addLeaves(tree):

cField = 0.0
events = tree.GetEntries()

leaves = "cCut/D:MUpt0/D"

leafValues = array.array("d", [0.0,0.0])
newBranch = tree.Branch( "new_vars" , leafValues, leaves )
for i in range(events):
	#returnValue = tree.GetEntry(i, 1) #1 get all branches, 0 only active branches
	tree.GetEntry(i)

	mMet = tree.GetLeaf( "mMet" ).GetValue()
	dPhi = tree.GetLeaf("m1metDphi").GetValue()

	pt0 =  tree.GetBranch("MUpt").GetEntry(0)

	leafValues[0] = (mMet/100.0 - 1.0)**2.0 + (dPhi/math.pi - 0.5)**2.0
	leafValues[1] =  pt0

	newBranch.Fill()
	tree.Fill()
	if i % 3000 == 0:
		print "%s of %s: %s" % (i,events,leafValues)

tree.Write()
print "Saved tree with %s events . . ." % ( events )
#end of AddLeaves()[/code]

We do not recommend adding branches to existing TTree (this is possible but is an advanced feature :slight_smile: ).
Instead you should either create a new TTree and make it a friend of the existing one or you should Clone the original tree.
The following (untested) modification of your code might work.

[code]def addLeaves(tree):

cField = 0.0
events = tree.GetEntries()

leaves = “cCut/D:MUpt0/D”

leafValues = array.array(“d”, [0.0,0.0])

newfile = new TFile(“newfilename.root”,“RECREATE”)
newtree = tree.CloneTree(0)

newBranch = newtree.Branch( “new_vars” , leafValues, leaves )
for i in range(events):
#returnValue = tree.GetEntry(i, 1) #1 get all branches, 0 only active branches
tree.GetEntry(i)

  mMet = tree.GetLeaf( "mMet" ).GetValue()
  dPhi = tree.GetLeaf("m1metDphi").GetValue()

  pt0 =  tree.GetBranch("MUpt").GetEntry(0)

  leafValues[0] = (mMet/100.0 - 1.0)**2.0 + (dPhi/math.pi - 0.5)**2.0
  leafValues[1] =  pt0

  newtree.Fill()

  if i % 3000 == 0:
     print "%s of %s: %s" % (i,events,leafValues)

newtree.Write()
print “Saved tree with %s events . . .” % ( events )
#end of AddLeaves()[/code]

Thank much. I think I understand your solution. Now I need to develop the confidence that the values in the new tree will stay in synch with the values of the old tree.