TTree: creating a sub-branch of a branch from scratch

Sorry, I repplied by e-mail and did not see the result on the web page.
Here is the code of my previous message.

The points to have it working properly:

  • the correction suggested to modify TBranchElement with SetID;
  • the need to add a dummy leaf to the (top) branch;
  • the need to set a buffer address to the (top) branch, otherwise the sub-branches are not filled; this address does not seem to really matter (I tried both the buffer address of the first sub-branch and the pointer to the branch itself, with the same - successful - result).
//  Needed to correct the behavior of the main branch
struct TBranchElementModifier : public TBranchElement {
   void SetID (int id) { fID = id; }
};
int main ( int argc, char *argv[] )
{
  TFile * outFile = new TFile ( "Trees/TreeFile.root", "RECREATE" );
  TTree * outTree = new TTree ( "MyTree", "MyTree" );

  Int_t buffer1[3] = { -1, -1, -1 };    // buffer for sub-branch 1
  Int_t buffer0[2] = { -1, -1 };        // buffer for sub-branch 2

  // define the top branch
  TBranch * topBranch = new TBranchElement ( );
  topBranch->SetName ( "MainBr" );
  topBranch->SetTree ( outTree );
  outTree->GetListOfBranches()->Add ( topBranch );

  // --> correction needed of branch ID
  ((TBranchElementModifier*)topBranch)->SetID(-1);

  // --> an address is required also... (most likely dummy)
  topBranch->SetAddress ( &buffer0[0] );
  //        it also works with:
  //            topBranch->SetAddress ( topBranch );

  // --> a dummy leaf must be added
  TLeaf * leaf = new TLeafElement ( topBranch, "", -1, 0 );
  topBranch->GetListOfLeaves()->Add(leaf);

  // define the sub-branches
  TBranch * subBranch1 = new TBranch ( outTree, "Sub1", &buffer1[0], "VarA1/I:VarB1/I:VarC1/I" );
  TBranch * subBranch2 = new TBranch ( outTree, "Sub2", &buffer2[0], "VarA2/I:VarB2/I" );

  topBranch->GetListOfBranches()->Add ( subBranch1 );
  topBranch->GetListOfBranches()->Add ( subBranch2 );

  //------------------------------------------------------------
  // Fill the TTree with outTree->Fill()
  //   ...
  //------------------------------------------------------------

  outTree->Write();

  outFile->Close();
  delete outFile;

  return ( 0 );
}

The TTree structure is the following:

  • BR=MainBr Nleaf=1
    • LF= (dummy)
    • BR=Sub1 Nleaf=3
      • LF=VarA1
      • LF=VarB1
      • LF=VarC1
    • BR=Sub2 Nleaf=2
      • LF=VarA2
      • LF=VarB2

Playing the same game for branches (at any level in the TTree structure) to build sub-branches of sub-branches also worked fine: I tested it by mixing several levels of sub-branches (up to 3) in the same TTree.

1 Like