Python and ROOT Tricks: I need more range!

When you’re writing a Python program to loop over a large number of events, for instance those stored in a large ROOT TChain object [1], you may find that the standard bit of help on the web is not sufficient:

TChain aChain("NameOfTTree")
aChain.Add("/a/bunch/of/files/*.root")
for anEvent in range(aChain.GetEntries()):
    # Do a bunch of stuff with an event in a TTree

If there are too many events for the Python range() function – that is, if the integer returned by the TChain::GetEntries() method is too big for Python – you’ll get an error. Now how are you going to run over these events?

One way to handle this is to use the xrange() function instead of range(); it can handle a much larger integer and generate a much larger list of integer events:

TChain aChain("NameOfTTree")
aChain.Add("/a/bunch/of/files/*.root")
for anEvent in xrange(aChain.GetEntries()):
    # Do a bunch of stuff with an event in a TTree

[1] http://root.cern.ch/root/html/TChain.html

Python and ROOT Tricks: batch mode, please!

If you’ve tried to write a Python program that uses ROOT, you might see complaints about “not having permission to access your DISPLAY.” What is happening is that ROOT is trying to access the graphics capabilities of your shell, but for some reason it cannot. This often happens if you’ve logged into a remote computer but have either forgotten to tunnel the graphics connection from the remote machine, or you’ve otherwise somehow lost the permission to do that.

Never fear! You can still run your program; you just need ROOT to go into “batch” mode, where it doesn’t try to actively popup graphics on the screen. To do this, import ROOT as usual but then tell ROOT to run in batch mode:

import ROOT
ROOT.gROOT.SetBatch(True)

You’re good to go; now anything you do with ROOT will not require permission to access the display, and you can generate plots and save them to disk, etc.

Doing Physics with Python and ROOT – a Primer

Back in May, I organized a small workshop at SMU on how physicists can get started using Python and ROOT. Python is a programming language that lets you quickly write complex software, while ROOT is a C++-based toolkit for performing an analysis. ROOT has an interface that lets Python use its code natively, providing great flexibility to a physicist. This allows you to combine the analysis tools of ROOT with the ease-of-use and graphics capabilities of Python.

The workshop was aimed at undergraduates who are beginning research, graduate students with some programming experience, and anyone with an interest in expanding their horizons in analysis.

To view the workshop or any of its pieces (it was several hours long), check out the agenda here:

https://indico.physics.smu.edu/indico/conferenceDisplay.py?confId=0

You can play the video of the workshop using EVO Player, available here:

http://evo.caltech.edu/evoPlayer/prod/EVOPlayer.jnlp