20.4. Friends
Table of Contents
TTree friends
In many analyses you do not have a single self contained TTree. Instead, information about the same physical events is split across several trees, often in different files. ROOT “friends” provide a way to virtually merge such trees, so you can use all variables together without physically copying or restructuring the data.
A TTree friend is another TTree that ROOT associates entry by entry with a given “master” tree. Once the friendship is established, branches from the friend tree appear as if they were extra branches of the main tree. You can then use them transparently in TTree::Draw, in traditional event loops, and in RDataFrame.
The basic idea is simple. You start with a main TTree, for example:
TTree *t = (TTree*)file->Get("Events");and a second tree that you want to attach as a friend:
TTree *tf = (TTree*)file2->Get("Calib");You then declare the friendship:
t->AddFriend(tf);From that point on, when you run
t->Draw("energy:calib_factor");
ROOT will read the energy branch from the main tree t and the calib_factor branch from the friend tree tf, pairing entries by index (entry 0 with entry 0, entry 1 with entry 1, and so on).
A TTree friend is not a copy or merge of data. It is only a logical link. The underlying trees and files must remain accessible while you use the friendship, and entry pairing must be consistent with how your data were produced.
You can add a friend by passing a tree pointer, or by passing file and tree names as strings. The latter is useful when the friend lives in another file:
t->AddFriend("Calib", "calibration.root");
Here "Calib" is the tree name, and "calibration.root" is the file that contains it. ROOT will open the file when needed.
It is possible to have more than one friend. You can call AddFriend several times, and the main tree t will see all branches from all friends as if they were its own. If branch names clash, you can qualify them with the tree name, for example Calib.calib_factor to pick the correct one.
Using friends with TTree::Draw and similar high level functions is very natural. After the friendship is defined, you simply reference the friend branches by name in the draw expression or in the selection string:
t->Draw("energy*Calib.calib_factor", "qualityFlag && Trig.pass");
Here Calib and Trig could be two different friend trees, each providing a set of branches.
For more explicit processing in a C++ loop, the mechanism is the same. You set branch addresses on the main tree, including branches that actually belong to friends. Once the friendship exists, ROOT takes care of reading the right tree and entry for every event. You only call GetEntry on the main tree:
float energy, calib_factor;
t->SetBranchAddress("energy", &energy);
t->SetBranchAddress("calib_factor", &calib_factor); // from friend
for (Long64_t i = 0; i < t->GetEntries(); ++i) {
t->GetEntry(i); // also reads friend entry i
float energy_calibrated = energy * calib_factor;
// analysis code
}All the complexity of moving across multiple files and TTrees is hidden behind the friendship relation.
Important rule: when trees are friends, you must always drive the event loop with the main tree. Do not call GetEntry on the friend trees yourself, or you will break the synchronization that ROOT maintains.
Combining related datasets
Friends are especially useful to combine related datasets that were produced at different stages, by different people, or with different event content. The key is that all trees share a common way to identify corresponding entries.
The simplest and most common scenario is one to one alignment by entry index. This is typically the case when a downstream processing step reads a source TTree and writes a new TTree in the same order, one output entry per input entry. If you have
TTree *tReco = (TTree*)fReco->Get("Events");
TTree *tCalib = (TTree*)fCalib->Get("Events");
tReco->AddFriend(tCalib);
then entry i in tReco corresponds to entry i in tCalib. When you draw or loop over tReco, you can use reconstruction level variables and calibration constants together without any explicit joining logic.
In many workflows you maintain a “slimmed” or “derived” tree that contains only high level variables, and you keep the original tree with detailed detector level quantities. Instead of duplicating all variables into the derived tree, you can keep them in separate trees and connect them with friends. This saves space in files and makes it easy to regenerate or replace one part of the dataset without touching the other.
Sometimes trees are not aligned by simple entry index, for example when you have applied event selection and removed some entries in one of the trees. In such cases you need an explicit event identifier, such as a run number and event number pair, or any unique ID stored as branches in both trees. ROOT supports friend relationships based on variable lookup instead of raw entry index. You do this by defining an index on the trees:
tMain->BuildIndex("run", "event");
tFriend->BuildIndex("run", "event");
tMain->AddFriend(tFriend);
With this setup, when ROOT reads entry i from tMain, it uses run and event to find the matching entry in the friend tree. This allows you to combine datasets that were produced independently, as long as they share a consistent event identifier.
When combining datasets with friends, ensure that:
- There is a well defined mapping between entries, either by index or by explicit IDs.
- The mapping is consistent across the full range of entries.
- You do not overwrite or modify branches in a way that breaks the assumed mapping.
If these conditions fail, you will silently combine mismatched events and obtain incorrect physics results.
In practice, you often work with several friends at once. For example, a main physics tree might have friends providing trigger decisions, detector calibrations, pileup information, and machine learning scores. You can attach them all:
t->AddFriend("Trig", "triggers.root");
t->AddFriend("Calib", "calibration.root");
t->AddFriend("ML", "ml_scores.root");Then in a single analysis step you can cut on trigger decisions, apply calibrations, and read classifier outputs:
t->Draw("ML.score",
"Trig.pass && energy*Calib.factor > 1.0");Although the data are physically stored in multiple ROOT files, the analysis code sees a single logical dataset.
RDataFrame also supports friends. If t already has friends attached, constructing a dataframe from it gives you transparent access to all branches:
ROOT::RDataFrame df(*t);
auto h = df.Filter("Trig.pass")
.Define("Ecalib", "energy*Calib.factor")
.Histo1D("Ecalib");This approach keeps individual production steps modular and still allows you to combine everything into a coherent analysis view.
A useful pattern is to use one TTree per logical layer of processing, save each layer in its own file, and then connect them with friends when doing the final analysis. This keeps files smaller and more manageable, and if you need to redo a calibration or recompute a set of derived variables, you only regenerate the corresponding friend file, not the full dataset.
When working with large datasets you should also be aware of performance. Each friend may live in a separate file, so reading an event may require several I/O operations. It is usually better to keep related friend trees in as few files as practical and to avoid unnecessary friends that you do not use in your final analysis selections or histograms.
Finally, remember that friendships are not permanent modifications to the data. You create them at analysis time in your code or in an interactive ROOT session. This makes them a flexible tool to combine related datasets exactly as needed for a given analysis, without changing the underlying ROOT files.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Introduction to ROOT
- ☰ 1.1. What Is ROOT?
- ☰ 1.2. Installing ROOT
- ☰ 1.3. Starting ROOT
- ☰ 1.4. Your First ROOT Session
-
- ☰ 2. C++ Basics for ROOT
- ☰ 2.1. Why ROOT Uses C++
- ☰ 2.2. Variables and Data Types
- ☰ 2.3. Operators
- ☰ 2.4. Conditional Statements
- ☰ 2.5. Loops
- ☰ 2.6. Functions
- ☰ 2.7. Arrays and Vectors
-
- ☰ 3. ROOT Macros
- ☰ 3.1. What Is a ROOT Macro?
- ☰ 3.2. Running ROOT Macros
- ☰ 3.3. Functions Inside ROOT Macros
- ☰ 3.4. Compiling ROOT Macros
- ☰ 3.5. Organizing a ROOT Project
-
- ☰ 4. ROOT Objects and the ROOT Object Model
- ☰ 4.1. Introduction to ROOT Classes
- ☰ 4.2. Object Names and Titles
- ☰ 4.3. ROOT Collections
- ☰ 4.4. Inspecting ROOT Objects
-
- ☰ 5. Histograms
- ☰ 5.1. Introduction to Histograms
- ☰ 5.2. Creating a 1D Histogram
- ☰ 5.3. Filling Histograms
- ☰ 5.4. Drawing Histograms
- ☰ 5.5. Histogram Properties
- ☰ 5.6. Accessing Histogram Bins
- ☰ 5.7. Histogram Errors
- ☰ 5.8. Normalizing Histograms
- ☰ 5.9. Combining Histograms
-
- ☰ 6. Two-Dimensional Histograms
- ☰ 6.1. Creating 2D Histograms
- ☰ 6.2. Filling 2D Histograms
- ☰ 6.3. Drawing 2D Histograms
- ☰ 6.4. Projections
- ☰ 6.5. Profiles
-
- ☰ 7. Graphs
- ☰ 7.1. Introduction to TGraph
- ☰ 7.2. Creating a TGraph
- ☰ 7.3. Graph Styling
- ☰ 7.4. TGraphErrors
- ☰ 7.5. TGraphAsymmErrors
- ☰ 7.6. MultiGraph
-
- ☰ 8. Canvases and Plotting
- ☰ 8.1. TCanvas
- ☰ 8.2. Dividing a Canvas
- ☰ 8.3. Drawing Multiple Objects
- ☰ 8.4. Legends
- ☰ 8.5. Text and Annotations
- ☰ 8.6. Logarithmic Axes
- ☰ 8.7. Saving Plots
-
- ☰ 9. Styling ROOT Plots
- ☰ 9.1. ROOT Plot Styles
- ☰ 9.2. Axis Configuration
- ☰ 9.3. Line Styles
- ☰ 9.4. Marker Styles
- ☰ 9.5. Publication-Quality Figures
-
- ☰ 10. Mathematical Functions
- ☰ 10.1. Introduction to TF1
- ☰ 10.2. Built-in Functions
- ☰ 10.3. Custom Functions
- ☰ 10.4. Evaluating Functions
- ☰ 10.5. Function Integrals
-
- ☰ 11. Curve Fitting
- ☰ 11.1. Introduction to Fitting
- ☰ 11.2. Gaussian Fits
- ☰ 11.3. Polynomial Fits
- ☰ 11.4. Custom Fit Functions
- ☰ 11.5. Fit Parameters
- ☰ 11.6. Goodness of Fit
- ☰ 11.7. Fit Residuals
- ☰ 11.8. Fitting Graphs
-
- ☰ 12. ROOT Files
- ☰ 12.1. Introduction to ROOT Files
- ☰ 12.2. Creating ROOT Files
- ☰ 12.3. Writing Objects
- ☰ 12.4. Reading ROOT Files
- ☰ 12.5. Exploring ROOT Files
- ☰ 12.6. Directories Inside ROOT Files
-
- ☰ 13. TTrees
- ☰ 13.1. Introduction to TTrees
- ☰ 13.2. Creating a TTree
- ☰ 13.3. Filling a TTree
- ☰ 13.4. Writing a TTree to a File
- ☰ 13.5. Reading a TTree
- ☰ 13.6. Inspecting TTrees
- ☰ 13.7. Drawing Data from TTrees
- ☰ 13.8. Applying Selection Cuts
- ☰ 13.9. Branch Addresses
-
- ☰ 14. Event-Based Data Analysis
- ☰ 14.1. Understanding Event Data
- ☰ 14.2. Event Loops
- ☰ 14.3. Event Selection
- ☰ 14.4. Derived Quantities
- ☰ 14.5. Analysis Workflow
-
- ☰ 15. Working with Real Experimental Data
- ☰ 15.1. Importing Text Data
- ☰ 15.2. Converting Data to ROOT
- ☰ 15.3. Data Cleaning
- ☰ 15.4. Data Calibration
- ☰ 15.5. Signal and Background
-
- ☰ 16. Random Numbers and Simulations
- ☰ 16.1. Random Number Generation
- ☰ 16.2. Common Distributions
- ☰ 16.3. Simple Monte Carlo Simulation
- ☰ 16.4. Detector Resolution Simulation
- ☰ 16.5. Efficiency Simulation
-
- ☰ 17. Statistical Analysis with ROOT
- ☰ 17.1. Basic Statistics
- ☰ 17.2. Probability Distributions
- ☰ 17.3. Statistical Uncertainties
- ☰ 17.4. Chi-Square Tests
- ☰ 17.5. Confidence Intervals
-
- ☰ 18. Modern ROOT with RDataFrame
- ☰ 18.1. Introduction to RDataFrame
- ☰ 18.2. Loading Data
- ☰ 18.3. Filtering Data
- ☰ 18.4. Defining New Columns
- ☰ 18.5. Creating Histograms
- ☰ 18.6. Statistical Operations
- ☰ 18.7. Saving Results
- ☰ 18.8. Multithreading
-
- ☰ 19. ROOT and Python
- ☰ 19.1. Introduction to PyROOT
- ☰ 19.2. ROOT Objects in Python
- ☰ 19.3. Reading ROOT Files with Python
- ☰ 19.4. PyROOT and NumPy
- ☰ 19.5. PyROOT and Matplotlib
- ☰ 19.6. Choosing Between C++ and Python
-
- ☰ 20. Advanced TTree Techniques
- ☰ 20.1. Trees with Multiple Branches
- ☰ 20.2. Storing std::vector Objects
- ☰ 20.3. TChain
- ☰ 20.4. Friends
- ☰ 20.5. Efficient TTree Analysis
-
- ☰ 21. ROOT for Particle and Nuclear Physics
- ☰ 21.1. Four-Vectors
- ☰ 21.2. Particle Kinematics
- ☰ 21.3. Invariant Mass
- ☰ 21.4. Angular Distributions
- ☰ 21.5. Detector Spectra
-
- ☰ 22. Debugging and Common ROOT Problems
- ☰ 22.1. ROOT Object Ownership
- ☰ 22.2. Null Pointers
- ☰ 22.3. Segmentation Faults
- ☰ 22.4. Missing Histograms
- ☰ 22.5. ROOT File Problems
- ☰ 22.6. TTree Branch Problems
- ☰ 22.7. Histogram Range Problems
- ☰ 22.8. Fit Failures
- ☰ 22.9. Debugging ROOT Macros
-
- ☰ 23. Writing Better ROOT Analysis Code
- ☰ 23.1. Separating Analysis and Plotting
- ☰ 23.2. Using Functions
- ☰ 23.3. Using Header Files
- ☰ 23.4. Naming Conventions
- ☰ 23.5. Avoiding Hard-Coded Values
- ☰ 23.6. Configuration Parameters
- ☰ 23.7. Reproducible Analysis
- ☰ 23.8. Version Control with Git
-
- ☰ 24. Final Project
- ☰ 24.1. Project Overview
- ☰ 24.2. Analyze a complete scientific dataset using ROOT.
- ☰ 24.3. Import the Data
- ☰ 24.4. Explore the Dataset
- ☰ 24.5. Apply Data Selection
- ☰ 24.6. Create Histograms
- ☰ 24.7. Fit the Data
- ☰ 24.8. Calculate Physical Quantities
- ☰ 24.9. Estimate Statistical Uncertainties
- ☰ 24.10. Create Publication-Quality Figures
- ☰ 24.11. Save the Analysis Results
- ☰ 24.12. Write a Short Analysis Report
-
- ☰ 25. Appendices
- ☰ 25.1. A. ROOT Command Cheat Sheet
- ☰ 25.2. B. ROOT Histogram Classes
- ☰ 25.3. C. ROOT Graph Classes
- ☰ 25.4. D. Common TTree Commands
- ☰ 25.5. E. Common Drawing Options
- ☰ 25.6. F. Common Fit Functions
- ☰ 25.7. G. ROOT C++ Cheat Sheet
- ☰ 25.8. H. PyROOT Cheat Sheet
- ☰ 25.9. I. Common ROOT Errors and Solutions
- ☰ 25.10. J. Recommended ROOT Analysis Workflow
-
Comments
Please login to add a comment.
Don't have an account? Register now!