Howto Read and Type Cast Histograms From Files

Hi all,

what is the recommended procedure to read objects from files using pyroot? I’m trying to read TH2D histograms. TFile::Get( ) returns objects of type TObject. Is there a possibility to type cast returned object to TH2D? When doing something like:

histCount = None

for objectTypeIndex in range(len(objectTypes)):

    # retrieve histograms from input file
    histCount = inputFileAtlFast.Get( 'hist_name' )

    # make a copy of the histogram
    histEff = TH2D( histCount )

python complains about the missing TH2D constructor:

Traceback (most recent call last):
File “./createEffTable.py”, line 145, in ?
createEffTable()
File “./createEffTable.py”, line 70, in createEffTable
histEff = TH2D( histCount )
TypeError: none of the 8 overloaded methods succeeded. Full details:

Any ideas?

Cheers
Jan Erik

Jan,

# make a copy of the histogram histEff = TH2D( histCount )
this is indeed a copy constructor call and does not perform a cast (unless histCount is not a TH2D and there is a constructor that takes a single argument of (a base class of) the actual type of histCount).

Generally speaking, casting is not necessary with PyROOT. There are a few boundary cases (e.g. if part of the class hierarchy is missing), but you won’t run into any of those when using ROOT classes.

To check the type of your object, print the result of type(). Like so:

[code] # retrieve histograms from input file
histCount = inputFileAtlFast.Get( ‘hist_name’ )

verify type of object (histogram) retrieved

print type( histCount )[/code]
and if histCount is indeed a TH2D, then that will be its type.

Note that in interactive mode (also in scripts, but not recommended) you can pick up objects from the file in the ROOT scope (or global, if import * is used) by just using their names, just like in CINT:

from ROOT import * f = TFile( 'myfile.root' ) histCount.Print() # works, assuming that histCount is the real name

Cheers,
Wim