Well, it's a bit tricky to reproduce, because it is a conversion script from
the ROOT file format to pytables.
I'll try to reproduce it without the ROOT dependency.
For now, maybe the script itself can be of help.

convertChain.py reads a ROOT file and attempts to map the pytables structure
in CommonBaryonTuple.py

Cheers,
   Jan

PS: The problem could also be related to my installation of pytables-1.4, so
I'll try that one again, too...
#!/usr/bin/env python2.4
from RootPython.Samples import RooTuple
from ROOT import SigmaPbarGammaEvent, CommonBaryonEvent
from ROOT import TVector3, TLorentzVector
from optparse import OptionParser
from tables import *
from numpy import array
import psyco
psyco.full()


def vector3_to_array(vector):
    return array([vector.x(), vector.y(), vector.z()])


def vector4_to_array(vector):
    return array([vector.T(), vector.X(), vector.Y(), vector.Z()])


def convertEventHeader(table, chain, event):
    row = table.row
    nEntries = chain.GetEntries()
    print 'starting to convert file (%d Events)' % nEntries,
    header = event.eventHeader
    for iEv in xrange(nEntries):
	if iEv % 500 == 0:
	    print '.',
	chain.GetEntry(iEv)
	row['eventCMS'] = vector4_to_array(header.eventCMS)
	row['r2'] = header.r2
	row['event_id'] = iEv
        row['upperID'] = header.upperID
        row['lowerID'] = header.lowerID
	row.append()
    table.attrs.nevents = chain.GetEntries()
    table.flush()


def fillProperty(row, columnName, itemName, candidate):
    if isinstance(itemName, tuple):
        columnName += itemName[0] + '/'
        daughter = candidate.__getattribute__(itemName[0])
        for name in itemName[1]:
            fillProperty(row, columnName, name, daughter)
    elif isinstance(itemName, str):
        columnName += itemName
        if itemName in ('event_id', 'upperID', 'lowerID'):
            return
        data = candidate.__getattribute__(itemName)
        if isinstance(data, TVector3):
	    row[columnName] = vector3_to_array(data)
	elif isinstance(data, TLorentzVector):
	    row[columnName] = vector4_to_array(data)
	else:
            row[columnName] = data
    else:
        print "Unknown column type %s. This is bad !" % itemName


def convertB_Candidates(table, chain, event):
    row = table.row
    nEntries = chain.GetEntries()
    print 'starting to convert file (%d Events)' % nEntries,
    for iEv in xrange(nEntries):
	if iEv % 500 == 0:
	    print '.',
	chain.GetEntry(iEv)
	bList = event.bList
        upperID = event.eventHeader.upperID
        lowerID = event.eventHeader.lowerID
	for B in bList:
	    # just fill the Tuple with everything
	    # hopefully the attribute names are the same.
	    for item in table.colnames:
                fillProperty(row, '', item, B)
	    row['event_id'] = iEv
            row['upperID'] = upperID
            row['lowerID'] = lowerID
	    row.append()
    # this isn't really the correct number
    table.attrs.nevents = chain.GetEntries()
    table.flush()
    print 'done'


def processSigmaSample(sample, candidate_class, event_class, baseDir='/data1/BaryonicPenguins/Analysis-32/RooTuples/SigmaTuples'):
    s = RooTuple(sample, baseDir, SigmaPbarGammaEvent, 'SigmaPbarGammaAnalysis')
    f = openFile('/u/br/jstrube/work/Tuples/%s_SigmaTuples.h5' % sample, 'w')
    group = f.createGroup(f.root, 'events')
    # be careful with the expected events. The number of B is not the number of events
    # trick ROOT into telling us -- it's a hack but the best we can do here
    s.chain.Draw('bList.mES >> dummy')
    number_of_B = s.chain.GetSelectedRows()
    print 'number of B:', number_of_B, 'total events:', s.chain.GetEntries()
    candidates = f.createTable(group, 'B_candidates', candidate_class, 'reconstructed B candidates', filters=Filters(complevel=9, complib='lzo'), expectedrows=number_of_B)
    events = f.createTable(group, 'eventHeader', event_class, 'event information', filters=Filters(complevel=9, complib='lzo'), expectedrows=s.chain.GetEntries())
    candidates.attrs.reconstruction = '%s_Sigma' % sample
    convertB_Candidates(candidates, s.chain, s.event)
    convertEventHeader(events, s.chain, s.event)
    f.close()


def processLambdaSample(sample, candidate_class, event_class, baseDir='/data1/BaryonicPenguins/Analysis-32/RooTuples/LambdaTuples'):
    s = RooTuple(sample, baseDir, CommonBaryonEvent, 'CommonBaryonAnalysis')
    f = openFile('/u/br/jstrube/work/Tuples/%s_LambdaTuples.h5' % sample, 'w')
    group = f.createGroup(f.root, 'events')
    # be careful with the expected events. The number of B is not the number of events
    # trick ROOT into telling us -- it's a hack but the best we can do here
    s.chain.Draw('bList.mES >> dummy')
    number_of_B = s.chain.GetSelectedRows()
    print 'number of B:', number_of_B, 'total events:', s.chain.GetEntries()
    candidates = f.createTable(group, 'B_candidates', candidate_class, 'reconstructed B candidates', filters=Filters(complevel=9, complib='lzo'), expectedrows=number_of_B)
    candidates.attrs.reconstruction = '%s_Lambda' % sample
    events = f.createTable(group, 'eventHeader', event_class, 'event information', filters=Filters(complevel=9, complib='lzo'), expectedrows=s.chain.GetEntries())
    convertB_Candidates(candidates, s.chain, s.event)
    convertEventHeader(events, s.chain, s.event)
    f.close()


if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-b', action='store_true', help='batch mode, passed on to ROOT')
    parser.add_option('--sample', help='Select the id for the input sample')
    parser.add_option('--mode', help='Select Lambda or Sigma0 reconstruction. Allowed values are "Lambda" and "Sigma0"')
    parser.add_option('--directory', help='Base Directory for the files in the chain')
    options, args = parser.parse_args()

    if options.mode == 'Lambda':
        modulename = 'TablePython.CommonBaryonTuple'
        processor = processLambdaSample
    elif options.mode == 'Sigma0':
        modulename = 'TablePython.SigmaPbarGammaTuple'
        processor = processSigmaSample
    else:
	parser.print_help()
	parser.error('This is not a valid reconstruction mode. Aborting.')

    tupleModule = __import__(modulename, globals(), locals(), ['B_Candidate'])
    B_Candidate = vars(tupleModule)['B_Candidate']
    Event = vars(tupleModule)['Event']
    processor(options.sample, B_Candidate, Event, options.directory)


from tables import *
# note: inheritance from IsDescription does not copy columns
# this is a bug in pytables

class Event(IsDescription):
    _v_flavor = "numpy"
    event_id     = UInt32Col(pos=0, indexed=True)
    upperID      = UInt32Col(pos=1, indexed=True)
    lowerID      = UInt32Col(pos=2, indexed=True)
#    decayString  = StringCol(500)
    r2		 = Float32Col(pos=3)
    eventCMS	 = Float32Col(shape=4, pos=4)

class Baryon1(IsDescription):
    _v_flavor = "numpy"
    isTruthMatched   = UInt8Col()
    uid		     = UInt32Col()
    mass	     = Float32Col()
    chi2	     = Float32Col()
    nDOF	     = Int32Col()
    decayLength      = Float32Col()
    decayLengthError = Float32Col()
    decayVector      = Float32Col(shape=3)

class Baryon2(IsDescription):
    _v_flavor = "numpy"
    isTruthMatched   = UInt8Col()
    uid		     = UInt32Col()
    pidMask	     = Int32Col()
    pidStatus	     = Int32Col()
    pidWeight	     = Float32Col()
    pidError	     = Float32Col()

class Gamma(IsDescription):
    _v_flavor = "numpy"
    isTruthMatched   = UInt8Col()
    uid = UInt32Col()
    momentum    = Float32Col(shape=3)
    minNeutralDistance = Float32Col()
    minTrackDistance = Float32Col()
    minTrackDTheta = Float32Col()
    bestEtaMass	= Float32Col()
    bestPi0Mass	= Float32Col()
    cmsEnergy	= Float32Col()
    labEnergy	= Float32Col()

# Particle description
class B_Candidate(IsDescription):
    _v_flavor = "numpy"
    event_id    = UInt32Col(indexed=True) # event id (indexed)
    upperID     = UInt32Col(indexed=True)
    lowerID     = UInt32Col(indexed=True)
    isTruthMatched = UInt8Col()
    momentum    = Float32Col(shape=3)    # momentum of the particle
    mass        = Float32Col()             # mass of the particle
    uid		= UInt32Col()
    charge	= Int8Col()
    chi2	= Float32Col()
    nDOF	= Int32Col()
    legendreRatio = Float32Col()
    decayLength = Float32Col()
    decayLengthError = Float32Col()
    decayVector = Float32Col(shape=3)
    btaB_Status = Int32Col()
    mES		= Float32Col()
    mMiss	= Float32Col()
    deltaE	= Float32Col()
    Gamma       = Gamma()
    Baryon1	= Baryon1()
    Baryon2	= Baryon2()

-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys - and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV
_______________________________________________
Pytables-users mailing list
Pytables-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/pytables-users

Reply via email to