PyROOT

  • pyROOT provides bindings for the classes in the root libraries
  • it allows you to replace CINT with its interpreted c++ with (i)python

Installation

  • compile ROOT with python support
  • make sure that $ROOTSYS/lib is in your PYTHONPATH and LD_LIBRARY_PATH variables

Example 1 - TBrowser

In [2]: import ROOT

In [3]: tb = ROOT.TBrowser()

Example 2 - Opening TFiles

In [4]: f = ROOT.TFile("examples/tree.root")

In [5]: f.ls()
TFile**     examples/tree.root
 TFile*     examples/tree.root
  KEY: TTree    aTree;1 tree title

In [6]: t = f.Get("aTree")

In [7]: t.Print()
******************************************************************************
*Tree    :aTree     : tree title                                             *
*Entries :  1000000 : Total =        24071514 bytes  File  Size =   19821249 *
*        :          : Tree compression factor =   1,21                       *
******************************************************************************
*Br    0 :normal    : normal/D                                               *
*Entries :  1000000 : Total  Size=    8023900 bytes  File Size  =    7227246 *
*Baskets :      251 : Basket Size=      32000 bytes  Compression=   1,11     *
*............................................................................*
*Br    1 :uniform   : uniform/D                                              *
*Entries :  1000000 : Total  Size=    8024155 bytes  File Size  =    5452842 *
*Baskets :      251 : Basket Size=      32000 bytes  Compression=   1,47     *
*............................................................................*
*Br    2 :var       : var/D                                                  *
*Entries :  1000000 : Total  Size=    8023135 bytes  File Size  =    7134158 *
*Baskets :      251 : Basket Size=      32000 bytes  Compression=   1,12     *
*............................................................................*

In [8]: t.<Tab>
Display all 326 possibilities? (y or n)
t.AbstractMethod                  t.GetEntryList                    t.InvertBit                       t.SaveFillAttributes
t.AddFriend                       t.GetEntryNumber                  t.IsA                             t.SaveLineAttributes
t.AddTotBytes                     t.GetEntryNumberWithBestIndex     t.IsEqual                         t.SaveMarkerAttributes
t.AddZipBytes                     t.GetEntryNumberWithIndex         t.IsFolder                        t.SavePrimitive
t.AppendPad                       t.GetEntryWithIndex               t.IsOnHeap                        t.Scan
t.__assign__                      t.GetEstimate                     t.IsSortable                      t.SetAlias
t.AutoSave                        t.GetEvent                        t.IsTransparent                   t.__setattr__
t.Branch                          t.GetEventList                    t.IsZombie                        t.SetAutoSave
t.BranchOld                       t.GetFileNumber                   t.__iter__                        t.SetBasketSize
t.BranchRef                       t.GetFillColor                    t.kBitMask                        t.SetBit
t.Bronch                          t.GetFillStyle                    t.kCanDelete                      t.SetBranchAddress
t.Browse                          t.GetFriend                       t.kCannotPick                     t.SetBranchStatus
t.BuildIndex                      t.GetFriendAlias                  t.kCircular                       t.SetBranchStyle
t.BuildStreamerInfo               t.GetHistogram                    t.kFindBranch                     t.SetCacheSize
t.ChangeFile                      t.GetIconName                     t.kFindLeaf                       t.SetChainOffset
t.__class__                       t.GetIndex                        t.kForceRead                      t.SetCircular
t.Class                           t.GetIndexValues                  t.kGetAlias                       t.SetDebug
t.ClassName                       t.GetIteratorOnAllLeaves          t.kGetBranch                      t.SetDirectory
t.Class_Name                      t.GetLeaf                         t.kGetEntry                       t.SetDrawOption
t.Class_Version                   t.GetLineColor                    t.kGetEntryWithIndex              t.SetDtorOnly
t.Clear                           t.GetLineStyle                    t.kGetFriend                      t.SetEntries
t.Clone                           t.GetLineWidth                    t.kGetFriendAlias                 t.SetEntryList
t.CloneTree                       t.GetListOfAliases                t.kGetLeaf                        t.SetEstimate
t.__cmp__                         t.GetListOfBranches               t.kHasUUID                        t.SetEventList
t.Compare                         t.GetListOfClones                 t.kInvalidObject                  t.SetFileNumber
t.__contains__                    t.GetListOfFriends                t.kIsOnHeap                       t.SetFillAttributes
t.Copy                            t.GetListOfLeaves                 t.kIsReferenced                   t.SetFillColor
t.CopyAddresses                   t.GetMakeClass                    t.kLoadTree                       t.SetFillStyle
t.CopyEntries                     t.GetMarkerColor                  t.kMustCleanup                    t.SetLineAttributes
t.CopyTree                        t.GetMarkerSize                   t.kNoContextMenu                  t.SetLineColor
t.CreateBasket                    t.GetMarkerStyle                  t.kNotDeleted                     t.SetLineStyle
t.Debug                           t.GetMaxEntryLoop                 t.kObjInCanvas                    t.SetLineWidth
t.DeclFileLine                    t.GetMaximum                      t.kOverwrite                      t.SetMakeClass
t.DeclFileName                    t.GetMaxTreeSize                  t.kPrint                          t.SetMarkerAttributes
t.__delattr__                     t.GetMaxVirtualSize               t.kRemoveFriend                   t.SetMarkerColor
t.Delete                          t.GetMinimum                      t.kSetBranchStatus                t.SetMarkerSize
t.__dict__                        t.GetName                         t.kSingleKey                      t.SetMarkerStyle
t.Dictionary                      t.GetNbranches                    t.kWriteDelete                    t.SetMaxEntryLoop
t.DirectoryAutoAdd                t.GetNotify                       t.kZombie                         t.SetMaxTreeSize
t.DistancetoLine                  t.GetObjectInfo                   t.__le__                          t.SetMaxVirtualSize
t.DistancetoPrimitive             t.GetObjectStat                   t.LoadBaskets                     t.SetName

Example III - simple graphs

import ROOT
import numpy as n

x = n.linspace(0, 4*n.pi,101)
y = n.cos(x)

g = ROOT.TGraph(len(x), x,y)
g.SetTitle("cosine in x=[%.1f, %.1f]" % (x[0], x[-1]))
g.GetXaxis().SetTitle("x")
g.GetYaxis().SetTitle("y")
g.Draw("AL")
_images/graph.png

Example IV - writing trees

in C++:

{
    TFile* f = new TFile("tree.root", "recreate");
    TTree* t = new TTree("aTree", "tree title");

    double n;
    double u;
    double x;

    t->Branch("normal", &n, "normal/D");
    t->Branch("uniform", &u, "uniform/D");
    t->Branch("var", &x, "var/D");

    for (int i=0; i < 1000000; ++i) {
        n = gRandom->Gaus();
        u = gRandom->Uniform();
        x = 2*u + 3 + n;
        t->Fill();
    }

    f->Write();
    f->Close();
}

in python:

#!/usr/bin/env python

import ROOT
import numpy as n

print "Writing a tree"

f = ROOT.TFile("tree.root", "recreate")
t = ROOT.TTree("name_of_tree", "tree title")


# create 1 dimensional float arrays (python's float datatype corresponds to c++ doubles)
# as fill variables
n = n.zeros(1, dtype=float)
u = n.zeros(1, dtype=float)

# create the branches and assign the fill-variables to them
t.Branch('normal', n, 'normal/D')
t.Branch('uniform', u, 'uniform/D')

# create some random numbers, fill them into the fill varibles and call Fill()
for i in xrange(100000):
	n[0] = ROOT.gRandom.Gaus()
	u[0] = ROOT.gRandom.Uniform()
	t.Fill()

# write the tree into the output file and close the file
f.Write()
f.Close()

Examples V - Drawing

In [1]: import ROOT

In [2]: f = ROOT.TFile("examples/tree.root")

In [3]: t = f.Get("aTree")

In [4]: t.Draw("uniform")
_images/tree.png

Example VI - ProcessLine

#!/usr/bin/env python
from ROOT import TTree, TFile, AddressOf, gROOT

# Make a tree
f = TFile('myTest.root','RECREATE')
t = TTree('MyTree','My test tree')

# Create a struct
gROOT.ProcessLine(\
  "struct MyStruct{\
    Int_t someInt;\
    Double_t someDouble;\
  };")

from ROOT import MyStruct

# Create branches in the tree
s = MyStruct()
t.Branch('rootInt',AddressOf(s,'someInt'),'someInt/I')
t.Branch('rootDouble',AddressOf(s,'someDouble'),'someDouble/D')

# Fill tree
for i in range(100):
  s.someInt = i
  s.someDouble = i
  t.Fill()

f.Write()
f.Close()