KAHIBARO
Discord Login Register

25.4. D. Common TTree Commands

Overview

This appendix collects commonly used TTree commands and idioms so you do not have to search through the whole course. The focus is on practical, short snippets that you will use frequently when working with TTrees in interactive ROOT sessions or in macros.

Where relevant, examples assume you have a TTree* t already available, either read from a file or created in your analysis.

Use this appendix as a quick reference, not as a full tutorial. Detailed explanations of concepts appear in the main TTree chapters.

Opening Files and Accessing TTrees

A typical first step is to open a ROOT file and get a pointer to a TTree.

Opening a file and listing its contents:

cpp
TFile *f = TFile::Open("data.root");   // or new TFile("data.root", "READ");
f->ls();                               // list objects in the file

Getting a TTree from a file:

cpp
TTree *t = (TTree*)f->Get("treeName");

If you are not sure of the tree name, use the ROOT browser:

cpp
TBrowser *b = new TBrowser();

or list keys and look for type TTree:

cpp
f->GetListOfKeys()->Print();

Checking basic information:

cpp
t->Print();          // structure and some stats
t->GetName();        // tree name
t->GetTitle();       // tree title
t->GetEntries();     // total number of entries (Long64_t)
t->GetNbranches();   // number of branches

Inspecting Structure and Content

When you first encounter a tree, you will usually want to see its branches and some example values.

Printing the TTree structure:

cpp
t->Print();          // full summary
t->Print("toponly"); // only top-level branches

Showing a single entry:

cpp
t->Show(0);          // show entry 0
t->Show(10);         // show entry 10

Scanning values of branches:

cpp
t->Scan();                // scan all branches for all entries
t->Scan("E:px:py");       // scan specific branches
t->Scan("E:pt", "E>10");  // only entries with E > 10

Limiting the number of scanned entries:

cpp
t->Scan("E:pt", "", "", 20);   // first 20 entries

Getting lists of branches and leaves:

cpp
t->GetListOfBranches()->Print();
t->GetListOfLeaves()->Print();

Creating TTrees and Branches

For quick tests, you can create a tree directly in an interactive session or macro.

Creating an empty tree:

cpp
TTree *t = new TTree("t", "example tree");

Creating branches for simple variables:

cpp
Float_t E;
Int_t   nHits;
t->Branch("E", &E, "E/F");          // /F for float
t->Branch("nHits", &nHits, "nHits/I"); // /I for int

Using automatic leaf lists with t->Branch(name, address):

cpp
Double_t x;
t->Branch("x", &x); // ROOT infers type, simple but less explicit

Branches with object types (for example std::vector):

cpp
std::vector<float> *px = new std::vector<float>;
t->Branch("px", &px);

For std::vector branches in compiled code, you must include the proper headers and have a dictionary available. See the advanced TTree and vector storage chapters for details.

Filling TTrees

After branches are created, you fill entries inside an event loop.

Simple filling loop:

cpp
for (Int_t i = 0; i < 1000; ++i) {
  E     = gRandom->Gaus(50, 10);
  nHits = (Int_t)gRandom->Poisson(5);
  t->Fill();
}

For vector branches, you typically clear and fill the vector each event:

cpp
for (Int_t evt = 0; evt < 100; ++evt) {
  px->clear();
  Int_t n = gRandom->Poisson(3);
  for (Int_t i = 0; i < n; ++i) {
    px->push_back(gRandom->Gaus(0, 1));
  }
  t->Fill();
}

Writing the tree to a file:

cpp
TFile *fout = new TFile("out.root", "RECREATE");
t->Write();
fout->Close();

Drawing from TTrees

One of the most convenient features of TTrees is the TTree::Draw function.

Basic histogram from a single variable:

cpp
t->Draw("E");           // 1D histogram of E with default binning

Setting custom binning and range:

cpp
t->Draw("E >> h1(100, 0, 200)");   // 100 bins from 0 to 200
TH1F *h1 = (TH1F*)gDirectory->Get("h1");

Storing output in an existing histogram:

cpp
TH1F *hE = new TH1F("hE", "Energy", 50, 0, 100);
t->Draw("E >> hE");                // fill existing hE

Drawing with a selection cut:

cpp
t->Draw("E", "nHits > 5");         // only events with nHits > 5
t->Draw("E", "E > 10 && E < 80");  // compound logical conditions

2D histograms from TTrees:

cpp
t->Draw("py:px");                   // py vs px, default bins
t->Draw("py:px >> h2(50, -5, 5, 50, -5, 5)");

Drawing expressions:

cpp
t->Draw("sqrt(px*px + py*py)");    // transverse momentum
t->Draw("E / nHits", "nHits > 0");

Specifying drawing options:

cpp
t->Draw("E", "", "hist");    // histogram option
t->Draw("E", "", "same");    // draw on same pad
t->Draw("py:px", "", "colz");// 2D color plot

Storing the result histogram created by Draw:

cpp
t->Draw("E >> htemp(50, 0, 100)");
TH1 *htemp = (TH1*)gDirectory->Get("htemp");

TTree::Draw creates histograms in the current directory. If you call it repeatedly with the same name without the >>+ option, the histogram is replaced. Use >>+hname to add to an existing histogram.

Example of adding to an existing histogram:

cpp
t->Draw("E >> hE(50,0,100)", "run==1");
t->Draw("E >>+hE", "run==2");   // add events from run==2 to hE

Setting Branch Addresses and Manual Reading

For more complex analyses, you often loop over tree entries yourself instead of using TTree::Draw.

Connecting branch addresses to variables:

cpp
Float_t E;
Int_t   nHits;
t->SetBranchAddress("E", &E);
t->SetBranchAddress("nHits", &nHits);

Reading entries in a loop:

cpp
Long64_t nentries = t->GetEntries();
for (Long64_t i = 0; i < nentries; ++i) {
  t->GetEntry(i);
  // now E and nHits hold values for entry i
}

Partial reading of branches to speed up access:

cpp
t->SetBranchStatus("*", 0);     // disable all branches
t->SetBranchStatus("E", 1);     // enable only E
t->SetBranchStatus("nHits", 1); // and nHits

GetEntry only loads active branches.

Using GetEntry in combination with selection logic:

cpp
for (Long64_t i = 0; i < t->GetEntries(); ++i) {
  t->GetEntry(i);
  if (E < 20) continue;
  // further analysis for selected events
}

Tree Information and Statistics

There are several helper functions to access metadata and simple statistics.

Getting number of entries, bytes, and approximate size:

cpp
t->GetEntries();         // total entries
t->GetTotBytes();        // total bytes read
t->GetZipBytes();        // compressed bytes on disk

Retrieving branch objects:

cpp
TBranch *bE     = t->GetBranch("E");
TBranch *bNHits = t->GetBranch("nHits");
bE->Print();

Estimating event size:

cpp
Double_t approxSize = t->GetEntry(0); // bytes read for this entry

Printing timer and statistics for TTree::Draw:

cpp
t->SetEstimate(1000000);          // hint for large scans
t->Scan("E:nHits");

Creating Histograms from TTrees in Macros

A common pattern in analysis macros is to create histograms and fill them from a TTree loop.

Example: histogram from manual loop:

cpp
TH1F *hE = new TH1F("hE", "Energy", 100, 0, 200);
Float_t E;
t->SetBranchAddress("E", &E);
Long64_t nentries = t->GetEntries();
for (Long64_t i = 0; i < nentries; ++i) {
  t->GetEntry(i);
  if (E < 10) continue;
  hE->Fill(E);
}

Example: 2D histogram from two branches:

cpp
TH2F *h2 = new TH2F("h2", "py vs px", 50, -5, 5, 50, -5, 5);
Float_t px, py;
t->SetBranchAddress("px", &px);
t->SetBranchAddress("py", &py);
for (Long64_t i = 0; i < t->GetEntries(); ++i) {
  t->GetEntry(i);
  h2->Fill(px, py);
}

TChain Basics

TChain lets you treat many TTrees from different files as a single logical tree.

Creating and filling a chain:

cpp
TChain *ch = new TChain("treeName");
ch->Add("data_run1.root");
ch->Add("data_run2.root");
ch->Add("data_run*.root");   // wildcard pattern

Using a chain like a tree:

cpp
ch->Draw("E");               // same interface as TTree
ch->Scan("E:nHits");

Setting branch addresses for a chain:

cpp
Float_t E;
ch->SetBranchAddress("E", &E);
for (Long64_t i = 0; i < ch->GetEntries(); ++i) {
  ch->GetEntry(i);
  // analysis code
}

Checking which file a given entry belongs to:

cpp
TFile *currentFile = ch->GetCurrentFile();
currentFile->GetName();

Friends and Derived Variables

Friend trees let you combine information from multiple TTrees that share the same entry numbering or event structure.

Adding a friend tree:

cpp
TFile *f1 = TFile::Open("data.root");
TTree *t1 = (TTree*)f1->Get("t1");
TFile *f2 = TFile::Open("extra.root");
TTree *t2 = (TTree*)f2->Get("t2");
t1->AddFriend(t2);   // t2 becomes a friend of t1

Now you can refer to branches from both trees in Draw:

cpp
t1->Draw("E:extraVar");              // extraVar from friend tree
t1->Draw("E", "extraVar > 0.5");

Creating simple on-the-fly aliases:

cpp
t->SetAlias("pt", "sqrt(px*px + py*py)");
t->Draw("pt");
t->Scan("pt:E");

Listing aliases:

cpp
t->GetListOfAliases()->Print();

File Writing and Closing

At the end of an analysis that creates or modifies TTrees you usually write objects and close files.

Creating a file and writing a tree:

cpp
TFile *fout = new TFile("result.root", "RECREATE");
t->Write();           // writes tree into result.root
fout->Close();

Writing multiple objects:

cpp
TFile *fout = new TFile("result.root", "RECREATE");
t->Write();
hE->Write();
h2->Write();
fout->Close();

Writing into subdirectories:

cpp
TFile *fout = new TFile("result.root", "RECREATE");
TDirectory *dir = fout->mkdir("trees");
dir->cd();
t->Write();
fout->cd();
hE->Write();
fout->Close();

Always close files with Close() in macros and long sessions. In interactive, short ROOT sessions it is easy to forget, but forgetting in larger workflows can lead to incomplete files.

Quick Reference Table

The following table summarizes some of the most common TTree commands by task.

TaskCommand / Pattern
Open fileTFile *f = TFile::Open("file.root");
Get tree from fileTTree t = (TTree)f->Get("T");
Print structuret->Print();
Show entryt->Show(0);
List branchest->GetListOfBranches()->Print();
Quick view of datat->Scan("E:pt");
Simple drawt->Draw("E");
Draw with cutt->Draw("E", "pt>1.0");
Draw 2Dt->Draw("y:x");
Create histogram from treet->Draw("E >> h(100,0,200)");
Create treeTTree *t = new TTree("t","title");
Create brancht->Branch("E", &E, "E/F");
Fill treet->Fill();
Write treet->Write();
Set branch addresst->SetBranchAddress("E", &E);
Loop over entriesfor (i=0; i<t->GetEntries(); ++i) t->GetEntry(i);
Disable branchest->SetBranchStatus("*",0);
Enable single brancht->SetBranchStatus("E",1);
Build chainTChain ch = new TChain("T"); ch->Add(".root");
Add friendt->AddFriend("friendTree","friend.root");
Set aliast->SetAlias("pt","sqrt(pxpx+pypy)");

Use this appendix whenever you need a quick reminder of the exact function names and simple usage patterns for TTrees in ROOT.

Views: 10

Comments

Please login to add a comment.

Don't have an account? Register now!