Skip to content

PythonTTree

Maurik Holtrop edited this page Jul 5, 2021 · 5 revisions

Using TTree directly from Python

This is a relatively easy way to explore what is in a flat ntuple style ROOT file. It works very well and it is very fast for simple histograms of items that are directly available in the ntuple. When you get to more complicated histograms that require calculations to produce the numbers that you want to fill the histogram with, I highly recommend that you try to write a loop (Python Loops) or better and faster, learn about RDataFrame.

For more general details on how to use ROOT with Python, see the documentation for PyROOT:

A quick example.

import ROOT as R  # You need the basic ROOT framework.
root_file = R.TFile("pi0_455GeV_01_recon.root") 
root_file.ls()    # See what is in the root file.

Output:

TFile**		pi0_455GeV_01_recon.root	
 TFile*		pi0_455GeV_01_recon.root	
  KEY: TTree	MiniDST;10	HPS mini-DST [current cycle]
  KEY: TTree	MiniDST;9	HPS mini-DST [backup cycle]
t = root_file.Get("MiniDST")  # Get the TTree from the file.
t.Print()                     # Print a long list of all the available data in the TTree. Output not shown.
list_of_leaves = [x.GetFullName() for x in t.GetListOfLeaves()]  # A Python way to get the list of leaves (data) in the tree.
t.Draw("ecal_cluster_energy") # Create a histogram of the ECal cluster energy.
R.c1.Update()                 # This is needed in iPython to get the actual histogram drawn to the screen.

Basically, everything you can do with TTree in C++ you can also do in Python. See more in C++ TTree.

More details of using Draw are found in ROOT TTree Manual and the tutorials for trees: Tree Tutorials

Clone this wiki locally