How To Use PyROOT

Overview

PyROOT is a Python extension module that allows the user to interact with any ROOT class. This is done generically using the ROOT dictionary. There is no need to generate any Python wrapper code to include new ROOT classes.

Setting up your environment

You need to setup your environment for ROOT, Boost and Python. This is achieved automatically and consistently if using a configuration management tool like SCRAM. In addition, the user needs to setup the PYTHONPATH environment to locate the PyROOT extension module and the module ROOT.py. Alternatively the examples/demo.py contains the pyhton command to achive it from the script itself.

Running an example

To run the demo examples you can type the following command. Note that the -i is there to avoid the script to terminate before you have a chance to interact with the demo ROOT menu.

> python2.2 -i demo.py

hsimple.py example

Here is a fragment of the hsimple.py example. This is equivalent to the hsimple.C example of ROOT

from ROOT import *

# Create a new canvas.
c1 = TCanvas('c1','Dynamic Filling Example',200,10,700,500);
c1.SetFillColor(42)
c1.GetFrame().SetFillColor(21)
c1.GetFrame().SetBorderSize(6)
c1.GetFrame().SetBorderMode(-1)

# Create a new ROOT binary machine independent file.
# Note that this file may contain any kind of ROOT objects, histograms,
# pictures, graphics objects, detector geometries, tracks, events, etc..
# This file is now becoming the current directory.

hfile = gROOT.FindObject('hsimple.root')
if hfile : hfile.Close()
hfile = TFile('hsimple.root','RECREATE','Demo ROOT file with histograms')

# Create some histograms, a profile histogram and an ntuple
hpx = TH1F('hpx','This is the px distribution',100,-4,4)
hpxpy = TH2F('hpxpy','py vs px',40,-4,4,40,-4,4)
hprof = TProfile('hprof','Profile of pz versus px',100,-4,4,0,20)
ntuple = TNtuple('ntuple','Demo ntuple','px:py:pz:random:i')

# Set canvas/frame attributes (save old attributes)
hpx.SetFillColor(48)

gBenchmark.Start('hsimple')

# Fill histograms randomly
gRandom.SetSeed()
kUPDATE = 1000
for i in xrange(25000) :
px = gRandom.Gaus()
py = gRandom.Gaus()
pz = px*px + py*py
random = gRandom.Rndm(1)
hpx.Fill(px)
hpxpy.Fill(px,py)
hprof.Fill(px,pz)
ntuple.Fill(px,py,pz,random,i)
if i and i%kUPDATE == 0 :
if i == kUPDATE : hpx.Draw()
c1.Modified()
c1.Update()
if gSystem.ProcessEvents() : break

gBenchmark.Show('hsimple')

# Save all objects in this file
hpx.SetFillColor(0)
hfile.Write()
hpx.SetFillColor(48)
c1.Modified()