Adding a (constant) branch to a TTree

hi all

suppose i have a TTree in a file. this TTree has a LOT of entries and a LOT of different branches. all i want to do is to add a single float branch to it, and that branch has the same numeric value for all entries in that tree. the only way i know how to do this is (in C++):

// ---------------- BEGIN

TFile* oldfile = TFile::Open(“file.root”);
TTree* oldtree = (TTree*)oldfile->Get(“treeName”);

TFile* newFile = TFile::Open(“newfile.root”, “recreate”);
TTree* newtree = oldtree->CloneTree(0);

float xsect = 13.;
newtree->Branch(“xsect”, &xsect, “xsect/F”);

int nentries = oldtree->GetEntries();

for( unsigned i=0; i<nentries; i++ ) {
oldtree->GetEntry(i);
newtree->Fill();
}

newtree->Write();
newfile->Close();

// ---------------- END

is this the only way? because looping on all entries (and loading them all) is VERY time consuming. isn’t there a faster way to do this?

thanks a lot
f

It is slow because you are doing more than just adding a new branch, you are cloning the whole tree. Fortunately once it’s done, the branch shouldn’t take up too much space because TFiles are compressed pretty well.

A faster way would be to add the constant not as a new branch in the TTree, but rather as a TParameter stored next to the tree in the TFile. http://root.cern.ch/root/html/TParameter_double_.html

Jean-François

Google for “add branch existing tree”.

hi jean-francois

your solution unfortunately won’t work, as i plan to hadd these files later on in the analysis. and as different files might have different values of that branch (even if for a given file all entries have the same value) i want to retain the event <-> branch mapping. you see what i mean?

eg.:
file1 has 100k entries, for which xsect=13
file2 has 300k entries, for which xsect=19
if i then hadd these files i want the first 100k entries to have xsect=13 and the second 300k to have xsect=19

f