25.4. D. Common TTree Commands
Table of Contents
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:
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:
TTree *t = (TTree*)f->Get("treeName");If you are not sure of the tree name, use the ROOT browser:
TBrowser *b = new TBrowser();
or list keys and look for type TTree:
f->GetListOfKeys()->Print();Checking basic information:
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 branchesInspecting 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:
t->Print(); // full summary
t->Print("toponly"); // only top-level branchesShowing a single entry:
t->Show(0); // show entry 0
t->Show(10); // show entry 10Scanning values of branches:
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 > 10Limiting the number of scanned entries:
t->Scan("E:pt", "", "", 20); // first 20 entriesGetting lists of branches and leaves:
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:
TTree *t = new TTree("t", "example tree");Creating branches for simple variables:
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):
Double_t x;
t->Branch("x", &x); // ROOT infers type, simple but less explicit
Branches with object types (for example std::vector):
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:
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:
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:
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:
t->Draw("E"); // 1D histogram of E with default binningSetting custom binning and range:
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:
TH1F *hE = new TH1F("hE", "Energy", 50, 0, 100);
t->Draw("E >> hE"); // fill existing hEDrawing with a selection cut:
t->Draw("E", "nHits > 5"); // only events with nHits > 5
t->Draw("E", "E > 10 && E < 80"); // compound logical conditions2D histograms from TTrees:
t->Draw("py:px"); // py vs px, default bins
t->Draw("py:px >> h2(50, -5, 5, 50, -5, 5)");Drawing expressions:
t->Draw("sqrt(px*px + py*py)"); // transverse momentum
t->Draw("E / nHits", "nHits > 0");Specifying drawing options:
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:
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:
t->Draw("E >> hE(50,0,100)", "run==1");
t->Draw("E >>+hE", "run==2"); // add events from run==2 to hESetting 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:
Float_t E;
Int_t nHits;
t->SetBranchAddress("E", &E);
t->SetBranchAddress("nHits", &nHits);Reading entries in a loop:
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:
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:
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:
t->GetEntries(); // total entries
t->GetTotBytes(); // total bytes read
t->GetZipBytes(); // compressed bytes on diskRetrieving branch objects:
TBranch *bE = t->GetBranch("E");
TBranch *bNHits = t->GetBranch("nHits");
bE->Print();Estimating event size:
Double_t approxSize = t->GetEntry(0); // bytes read for this entry
Printing timer and statistics for TTree::Draw:
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:
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:
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:
TChain *ch = new TChain("treeName");
ch->Add("data_run1.root");
ch->Add("data_run2.root");
ch->Add("data_run*.root"); // wildcard patternUsing a chain like a tree:
ch->Draw("E"); // same interface as TTree
ch->Scan("E:nHits");Setting branch addresses for a chain:
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:
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:
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:
t1->Draw("E:extraVar"); // extraVar from friend tree
t1->Draw("E", "extraVar > 0.5");Creating simple on-the-fly aliases:
t->SetAlias("pt", "sqrt(px*px + py*py)");
t->Draw("pt");
t->Scan("pt:E");Listing aliases:
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:
TFile *fout = new TFile("result.root", "RECREATE");
t->Write(); // writes tree into result.root
fout->Close();Writing multiple objects:
TFile *fout = new TFile("result.root", "RECREATE");
t->Write();
hE->Write();
h2->Write();
fout->Close();Writing into subdirectories:
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.
| Task | Command / Pattern |
|---|---|
| Open file | TFile *f = TFile::Open("file.root"); |
| Get tree from file | TTree t = (TTree)f->Get("T"); |
| Print structure | t->Print(); |
| Show entry | t->Show(0); |
| List branches | t->GetListOfBranches()->Print(); |
| Quick view of data | t->Scan("E:pt"); |
| Simple draw | t->Draw("E"); |
| Draw with cut | t->Draw("E", "pt>1.0"); |
| Draw 2D | t->Draw("y:x"); |
| Create histogram from tree | t->Draw("E >> h(100,0,200)"); |
| Create tree | TTree *t = new TTree("t","title"); |
| Create branch | t->Branch("E", &E, "E/F"); |
| Fill tree | t->Fill(); |
| Write tree | t->Write(); |
| Set branch address | t->SetBranchAddress("E", &E); |
| Loop over entries | for (i=0; i<t->GetEntries(); ++i) t->GetEntry(i); |
| Disable branches | t->SetBranchStatus("*",0); |
| Enable single branch | t->SetBranchStatus("E",1); |
| Build chain | TChain ch = new TChain("T"); ch->Add(".root"); |
| Add friend | t->AddFriend("friendTree","friend.root"); |
| Set alias | t->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
KAHIBARO