Adding a branch to an existing tree

Hi. Is there a simple way of adding a branch to an existing tree (with branches)? I have a branch that has the values of oncoming particle energies, and I would like, based on those, to compute the cross section and include it in a separate branch. I realize I could just create a new tree, copy the branches from the old tree, and include a branch with cross section values…however is there a simpler way to do this?

Thanks!

You can do something like:

void upd() { TFile *f = new TFile("hs.root","update"); TTree *T = (TTree*)f->Get("ntuple"); float px,py; float pt; TBranch *bpt = T->Branch("pt",&pt,"pt/F"); T->SetBranchAddress("px",&px); T->SetBranchAddress("py",&py); Long64_t nentries = T->GetEntries(); for (Long64_t i=0;i<nentries;i++) { T->GetEntry(i); pt = TMath::Sqrt(px*px+py*py); bpt->Fill(); } T->Print(); T->Write(); delete f; }
Rene

3 Likes

Rene,

Million thanks! It worked.

With one correction, though: px and py need to be defined as Double_t.
Using float at best results in compilation error, and at worst in wrong
values.

of course you must be coherent in the declaration of the variables.

Rene

Rene, I would like to understand better what you mean by being coherent.
The original root file was produced by geant4 code, and the variable which was used in the tree->Branch("",) declaration was a G4double. Are you saying that root’s Double_t corresponds to G4double? Or is this just a general issue of using a 64bit memory for a 64bit number?

By “coherent” I meant that you must use the correct data type declaration. G4Double is “double” or “Double_t”, but not a float, Float_t

Rene

Thanks again!

Hi,

I would like to emphasize the

line in the code at the beginning. He is filling the branch not the tree, I was getting messed up results because I tried to call

tree->Fill();

:frowning:

1 Like