00001
00002
00003
00004 """ GaudiPython.Bindings module.
00005 This module provides the basic bindings of the main Gaudi
00006 components to Python. It is itself based on the PyCintex
00007 extersion module provided by LCG/ROOT that provided
00008 dynamic bindigns of classes for which LCG dictionaires exists.
00009 """
00010
00011 __all__ = [ 'gbl','InterfaceCast', 'Interface', 'PropertyEntry',
00012 'AppMgr', 'PyAlgorithm', 'CallbackStreamBuf',
00013 'iAlgorithm', 'iDataSvc', 'iHistogramSvc','iNTupleSvc','iService', 'iAlgTool', 'Helper',
00014 'SUCCESS', 'FAILURE', 'toArray',
00015 'ROOT', 'makeNullPointer', 'makeClass', 'setOwnership',
00016 'getClass', 'loaddict', 'deprecation' ]
00017
00018 import os, sys, string, warnings, re
00019 import PyCintex
00020 import Pythonizations
00021
00022
00023 from GaudiKernel.Proxy.Configurable import Configurable, getNeededConfigurables
00024
00025
00026 gbl = PyCintex.makeNamespace('')
00027 Gaudi = gbl.Gaudi
00028
00029 _gaudi = None
00030
00031
00032
00033 Helper = gbl.GaudiPython.Helper
00034 StringProperty = gbl.SimpleProperty ('string','BoundedVerifier<string>')
00035 StringPropertyRef = gbl.SimplePropertyRef ('string','NullVerifier<string>')
00036 GaudiHandleProperty = gbl.GaudiHandleProperty
00037 GaudiHandleArrayProperty = gbl.GaudiHandleArrayProperty
00038 DataObject = gbl.DataObject
00039 SUCCESS = gbl.StatusCode( gbl.StatusCode.SUCCESS, True )
00040 FAILURE = gbl.StatusCode( gbl.StatusCode.FAILURE, True )
00041
00042 for l in [ l for l in dir(Helper) if re.match("^to.*Array$",l) ]:
00043 exec "%s = Helper.%s"%(l,l)
00044 __all__.append(l)
00045
00046
00047 if hasattr(Helper,"toArray"):
00048
00049
00050 toArray = lambda typ: getattr(Helper,"toArray")
00051 else:
00052
00053 toArray = lambda typ: getattr(Helper,"toArray<%s>"%typ)
00054
00055
00056 ROOT = PyCintex.libPyROOT
00057 makeNullPointer = PyCintex.libPyROOT.MakeNullPointer
00058 makeClass = PyCintex.libPyROOT.MakeRootClass
00059 setOwnership = PyCintex.libPyROOT.SetOwnership
00060
00061 def deprecation(message):
00062 warnings.warn('GaudiPython: '+ message, DeprecationWarning, stacklevel=3)
00063
00064
00065 class InterfaceCast(object) :
00066 """ Helper class to obtain the adequeste interface from a component
00067 by using the Gaudi queryInterface() mechanism """
00068 def __init__(self, t ) :
00069 if type(t) is str : t = PyCintex.makeClass(t)
00070 self.type = t
00071 def __call__(self, obj) :
00072 if obj :
00073 ip = PyCintex.libPyROOT.MakeNullPointer(self.type)
00074 try:
00075 if obj.queryInterface(self.type.interfaceID(), ip).isSuccess() :
00076 return ip
00077 else :
00078 print "ERROR: queryInterface failed for", obj, "interface:", self.type
00079 except Exception, e:
00080 print "ERROR: exception", e, "caught when retrieving interface", self.type, "for object", obj
00081 import traceback
00082 traceback.print_stack()
00083 return None
00084 cast = __call__
00085
00086 class Interface(InterfaceCast) :
00087 def __init__(self, t ):
00088 deprecation('Use InterfaceCast class instead')
00089 InterfaceCast.__init__(self,t)
00090 def cast(self, obj) :
00091 return self(obj)
00092
00093
00094 def loaddict(dict) :
00095 """ Load a LCG dictionary using various mechanisms"""
00096 if Helper.loadDynamicLib(dict) == 1 : return
00097 else :
00098 try:
00099 PyCintex.loadDict(dict)
00100 except:
00101 raise ImportError, 'Error loading dictionary library'
00102
00103
00104 def getClass( name , libs = [] ) :
00105 """
00106 Function to retrieve a certain C++ class by name and to load dictionary if requested
00107
00108 Usage:
00109
00110 from gaudimodule import getClass
00111 # one knows that class is already loaded
00112 AppMgr = getClass( 'ApplicationMgr' )
00113 # one knows where to look for class, if not loaded yet
00114 MCParticle = getClass( 'MCParticle' , 'EventDict' )
00115 # one knows where to look for class, if not loaded yet
00116 Vertex = getClass( 'Vertex' , ['EventDict', 'PhysEventDict'] )
00117 """
00118
00119 if hasattr( gbl , name ) : return getattr( gbl , name )
00120
00121 if type(libs) is not list : libs = [libs]
00122 for lib in libs :
00123 loaddict( lib )
00124 if hasattr( gbl , name ) : return getattr( gbl , name )
00125
00126 return None
00127
00128
00129 class PropertyEntry(object) :
00130 """ holds the value and the documentation string of a property """
00131 def __init__(self, prop) :
00132 self._type = type(prop).__name__
00133 self.__doc__ = " --- Property type is " + self.ptype()
00134
00135 if issubclass(type(prop),GaudiHandleProperty) :
00136 self._value = prop.value()
00137 elif issubclass(type(prop),GaudiHandleArrayProperty) :
00138 self._value = prop.value()
00139 else :
00140
00141 try: self._value = eval( prop.toString() , {} , {} )
00142 except: self._value = prop.value()
00143
00144 self.__doc__ += " --- Default value = " + str(self._value) + " --- "
00145 if prop.documentation() != 'none':
00146 self.__doc__ = prop.documentation() + '\\n' + self.__doc__
00147
00148 self._property = prop
00149 def value(self) :
00150 return self._value
00151 def ptype(self) :
00152 return self._type
00153 def property(self):
00154 "Return the underlying property itself "
00155 return self._property
00156 def documentation(self) :
00157 return self.__doc__
00158 def hasDoc(self):
00159 return len(self.__doc__)>0 and self.__doc__ != 'none'
00160
00161
00162 class iProperty(object) :
00163 """ Python equivalent to the C++ Property interface """
00164 def __init__(self, name, ip = None) :
00165 if ip : self.__dict__['_ip'] = InterfaceCast(gbl.IProperty)(ip)
00166 else : self.__dict__['_ip'] = None
00167 self.__dict__['_svcloc'] = gbl.Gaudi.svcLocator()
00168 optsvc = Helper.service(self._svcloc,'JobOptionsSvc')
00169 if optsvc : self.__dict__['_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(optsvc)
00170 else : self.__dict__['_optsvc'] = None
00171 self.__dict__['_name'] = name
00172 def getInterface(self) :
00173 if not self._ip : self.retrieveInterface()
00174 return self._ip
00175 def retrieveInterface(self) :
00176 pass
00177 def __call_interface_method__(self,ifname,method,*args):
00178 if not getattr(self,ifname) : self.retrieveInterface()
00179 return getattr(getattr(self,ifname),method)(*args)
00180 def __setattr__(self, name, value):
00181 """
00182 The method which is used for setting the property from the given value.
00183 - In the case of the valid instance it sets the property through IProperty interface
00184 - In the case of placeholder the property is added to JobOptionsCatalogue
00185 """
00186 if hasattr( value, 'toStringProperty' ):
00187
00188 value = '%s' % value.toStringProperty()
00189 ip = self.getInterface()
00190 if ip :
00191 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
00192 raise AttributeError, 'property %s does not exist' % name
00193 prop = ip.getProperty(name)
00194 if not type( value ) == type( prop.value() ) :
00195 if not long == type( value ) : value = '%s' % value
00196 else : value = '%d' % value
00197 if prop.fromString( value ).isFailure() :
00198 raise AttributeError, 'property %s could not be set from %s' % (name,value)
00199 else :
00200 if not prop.setValue( value ) :
00201 raise AttributeError, 'property %s could not be set from %s' % (name,value)
00202 else :
00203 if type(value) == str : value = '"%s"' % value
00204 elif type(value) == long: value = '%d' % value
00205 sp = StringProperty( name , str(value))
00206 self._optsvc.addPropertyToCatalogue( self._name , sp )
00207 def __getattr__(self, name ):
00208 """
00209 The method which returns the value for the given property
00210 - In the case of the valid instance it returns the valid property value through IProperty interface
00211 - In the case of placeholder the property value is retrieevd from JobOptionsCatalogue
00212 """
00213 ip = self.getInterface()
00214 if ip :
00215 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
00216 raise AttributeError, 'property %s does not exist' % name
00217 prop = ip.getProperty(name)
00218 if StringProperty == type( prop ) : return prop.value()
00219 elif StringPropertyRef == type( prop ) : return prop.value()
00220 try: return eval( prop.toString(), {}, {} )
00221 except : return p.value()
00222 else :
00223 props = self._optsvc.getProperties(self._name)
00224 for p in props :
00225 if not p.name() == name : continue
00226
00227 try: return eval( p.value(), {}, {} )
00228 except: return p.value()
00229 raise AttributeError, 'property %s does not exist' % name
00230 def properties(self):
00231 dct = {}
00232 props = None
00233 ip = self.getInterface()
00234 if ip :
00235 props = ip.getProperties()
00236 propsFrom = self._name
00237 else:
00238 props = self._optsvc.getProperties( self._name )
00239 propsFrom = "jobOptionsSvc"
00240 if props:
00241 for p in props :
00242 try:
00243 dct[p.name()] = PropertyEntry(p)
00244 except (ValueError,TypeError),e:
00245 raise ValueError, "gaudimodule.iProperty.properties(): %s%s processing property %s.%s = %s" % \
00246 (e.__class__.__name__, e.args, propsFrom, p.name(), p.value())
00247 return dct
00248 def name(self) :
00249 return self._name
00250
00251
00252 class iService(iProperty) :
00253 """ Python equivalent to IProperty interface """
00254 def __init__(self, name, isvc = None ) :
00255 iProperty.__init__(self, name, isvc )
00256 if isvc : self.__dict__['_isvc'] = InterfaceCast(gbl.IService)(isvc)
00257 else : self.__dict__['_isvc'] = None
00258 def retrieveInterface(self) :
00259 isvc = Helper.service(self._svcloc,self._name)
00260 if isvc : iService.__init__(self, self._name, isvc)
00261 initialize = lambda self : self.__call_interface_method__("_isvc","initialize")
00262 start = lambda self : self.__call_interface_method__("_isvc","start")
00263 stop = lambda self : self.__call_interface_method__("_isvc","stop")
00264 finalize = lambda self : self.__call_interface_method__("_isvc","finalize")
00265 reinitialize = lambda self : self.__call_interface_method__("_isvc","reinitialize")
00266 restart = lambda self : self.__call_interface_method__("_isvc","restart")
00267 def isValid(self) :
00268 if self._isvc: return True
00269 else : return False
00270
00271
00272 class iAlgorithm(iProperty) :
00273 """ Python equivalent to IAlgorithm interface """
00274 def __init__(self, name, ialg = None ) :
00275 iProperty.__init__(self, name, ialg )
00276 if ialg : self.__dict__['_ialg'] = InterfaceCast(gbl.IAlgorithm)(ialg)
00277 else : self.__dict__['_ialg'] = None
00278 def retrieveInterface(self) :
00279 ialg = Helper.algorithm(InterfaceCast(gbl.IAlgManager)(self._svcloc),self._name)
00280 if ialg : iAlgorithm.__init__(self, self._name, ialg)
00281 initialize = lambda self : self.__call_interface_method__("_ialg","initialize")
00282 start = lambda self : self.__call_interface_method__("_ialg","start")
00283 execute = lambda self : self.__call_interface_method__("_ialg","execute")
00284 stop = lambda self : self.__call_interface_method__("_ialg","stop")
00285 finalize = lambda self : self.__call_interface_method__("_ialg","finalize")
00286 reinitialize = lambda self : self.__call_interface_method__("_ialg","reinitialize")
00287 restart = lambda self : self.__call_interface_method__("_ialg","restart")
00288 sysInitialize = lambda self : self.__call_interface_method__("_ialg","sysInitialize")
00289 sysStart = lambda self : self.__call_interface_method__("_ialg","sysStart")
00290 sysExecute = lambda self : self.__call_interface_method__("_ialg","sysExecute")
00291 sysStop = lambda self : self.__call_interface_method__("_ialg","sysStop")
00292 sysFinalize = lambda self : self.__call_interface_method__("_ialg","sysFinalize")
00293 sysReinitialize = lambda self : self.__call_interface_method__("_ialg","sysReinitialize")
00294 sysRestart = lambda self : self.__call_interface_method__("_ialg","sysRestart")
00295
00296
00297 class iAlgTool(iProperty) :
00298 """ Python equivalent to IAlgTool interface (not completed yet) """
00299 def __init__(self, name, itool = None ) :
00300 iProperty.__init__(self, name, itool )
00301 if itool : self.__dict__['_itool'] = itool
00302 else : self.__dict__['_itool'] = None
00303 svc = Helper.service( self._svcloc, 'ToolSvc', True )
00304 self.__dict__['_toolsvc']= iToolSvc('ToolSvc', svc)
00305 def retrieveInterface(self) :
00306 itool = self._toolsvc._retrieve(self._name)
00307 if itool : iAlgTool.__init__(self, self._name, itool)
00308 start = lambda self : self.__call_interface_method__("_itool","start")
00309 stop = lambda self : self.__call_interface_method__("_itool","stop")
00310 type = lambda self : self.__call_interface_method__("_itool","type")
00311 def name(self) :
00312 if self._itool : return self._itool.name()
00313 else : return self._name
00314
00315
00316 class iDataSvc(iService) :
00317 def __init__(self, name, idp) :
00318 iService.__init__(self, name, idp )
00319 self.__dict__['_idp'] = InterfaceCast(gbl.IDataProviderSvc)(idp)
00320 self.__dict__['_idm'] = InterfaceCast(gbl.IDataManagerSvc)(idp)
00321 def registerObject(self, path, obj) :
00322 if not self._idp : raise AttributeError('C++ service %s does not exist' % self.__dict__['_name'])
00323 return self._idp.registerObject(path,obj)
00324 def unregisterObject(self, path) :
00325 if not self._idp : raise AttributeError('C++ service %s does not exist' % self.__dict__['_name'])
00326 return self._idp.unregisterObject(path)
00327 def retrieveObject(self, path) :
00328 if not self._idp : return None
00329 return Helper.dataobject(self._idp, path)
00330 def __getitem__(self, path) :
00331 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
00332 return Helper.dataobject(self._idp, path)
00333 def __setitem__(self, path, obj) :
00334 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
00335 return self._idp.registerObject(path,obj)
00336 def __delitem__(self, path) :
00337 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
00338 return self._idp.unregisterObject(path)
00339 def leaves(self, node=None) :
00340 if not node : node = self.retrieveObject('')
00341 ll = gbl.std.vector('IRegistry*')()
00342 if type(node) is str : obj = self.retrieveObject(node)
00343 else : obj = node
00344 if self._idm.objectLeaves(node, ll).isSuccess() : return ll
00345 def dump(self, node=None) :
00346 if not node :
00347 root = self.retrieveObject('')
00348 if root : node = root.registry()
00349 else : return
00350 print node.identifier()
00351 if node.object() :
00352 for l in self.leaves(node) : self.dump(l)
00353 def setRoot(self, name, obj):
00354 if not self._idm : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
00355 return self._idm.setRoot(name,obj)
00356 def clearStore(self):
00357 if not self._idm : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
00358 return self._idm.clearStore()
00359
00360
00361
00362 class iHistogramSvc(iDataSvc) :
00363 def __init__(self, name, ihs) :
00364 self.__dict__['_ihs'] = InterfaceCast(gbl.IHistogramSvc)(ihs)
00365 iDataSvc.__init__(self, name, ihs)
00366 def retrieve1D(self, path) :
00367 return Helper.histo1D(self._ihs, path)
00368 def retrieve2D(self, path) :
00369 return Helper.histo2D(self._ihs, path)
00370 def retrieve3D(self, path) :
00371 return Helper.histo3D(self._ihs, path)
00372 def retrieveProfile1D(self, path) :
00373 return Helper.profile1D(self._ihs, path)
00374 def retrieveProfile2D(self, path) :
00375 return Helper.profile2D(self._ihs, path)
00376 def retrieve(self,path):
00377 """
00378 Retrieve AIDA histogram or AIDA profile histogram by path in Histogram Transient Store
00379 >>> svc = ...
00380 >>> histo = svc.retrieve ( 'path/to/my/histogram' )
00381 """
00382 h = self.retrieve1D(path)
00383 if not h : h = self.retrieve2D(path)
00384 if not h : h = self.retrieve3D(path)
00385 if not h : h = self.retrieveProfile1D(path)
00386 if not h : h = self.retrieveProfile2D(path)
00387 return h
00388 def book(self, *args) :
00389 """
00390 Book the histograms(1D,2D&3D) , see IHistogramSvc::book
00391 >>> svc = ...
00392 >>> histo = svc.book( .... )
00393 """
00394 return apply(self._ihs.book,args)
00395 def bookProf(self, *args) :
00396 """
00397 Book the profile(1D&2D) histograms, see IHistogramSvc::bookProf
00398 >>> svc = ...
00399 >>> histo = svc.bookProf( .... )
00400 """
00401 return apply(self._ihs.bookProf,args)
00402 def __getitem__ ( self, path ) :
00403 """
00404 Retrieve the object from Histogram Transient Store (by path)
00405 The reference to AIDA historam is returned (if possible)
00406 >>> svc = ...
00407 >>> histo = svc['path/to/my/histogram']
00408 """
00409 h = self.retrieve ( path )
00410 if h : return h
00411 return iDataSvc.__getitem__( self , path )
00412 def getAsAIDA ( self , path ) :
00413 """
00414 Retrieve the histogram from Histogram Transient Store (by path)
00415 The reference to AIDA historam is returned (if possible)
00416 >>> svc = ...
00417 >>> histo = svc.getAsAIDA ( 'path/to/my/histogram' )
00418 """
00419 return self.__getitem__( path )
00420 def getAsROOT ( self , path ) :
00421 """
00422 Retrieve the histogram from Histogram Transient Store (by path)
00423 The Underlying native ROOT object is returned (if possible)
00424 >>> svc = ...
00425 >>> histo = svc.getAsROOT ( 'path/to/my/histogram' )
00426 """
00427 fun=gbl.Gaudi.Utils.Aida2ROOT.aida2root
00428 return fun( self.getAsAIDA( path ) )
00429
00430
00431 class iNTupleSvc(iDataSvc) :
00432 RowWiseTuple = 42
00433 ColumnWiseTuple = 43
00434 def __init__(self, name, ints) :
00435 self.__dict__['_ints'] = InterfaceCast(gbl.INTupleSvc)(ints)
00436 iDataSvc.__init__(self, name, ints)
00437 def book(self, *args) :
00438 return apply(self._ints.book, args)
00439 def defineOutput(self, files, typ='ROOT') :
00440 """ Defines dthe mapping between logical names and the output file
00441 Usage:
00442 defineOutput({'LUN1':'MyFile1.root', 'LUN2':'Myfile2.root'}, typ='ROOT')
00443 """
00444 out = []
00445 for o in files :
00446 out.append( "%s DATAFILE='%s' OPT='RECREATE' TYP='%s'" % ( o, files[o], typ ) )
00447 self.Output = out
00448 if AppMgr().HistogramPersistency == 'NONE' : AppMgr().HistogramPersistency = typ
00449 def __getitem__ ( self, path ) :
00450 return iDataSvc.__getitem__( self , path )
00451
00452
00453
00454 class iToolSvc(iService) :
00455 def __init__(self, name, its) :
00456 self.__dict__['_its'] = InterfaceCast(gbl.IToolSvc)(its)
00457 iService.__init__(self, name, its)
00458 def _retrieve(self, name, quiet=True):
00459 sol = _gaudi.OutputLevel
00460 if quiet : self.OutputLevel = 6
00461 if name.rfind('.') == -1 :
00462 itool = Helper.tool(self._its, '', name, None, False )
00463 elif name[0:8] == 'ToolSvc.' :
00464 itool = Helper.tool(self._its, '', name[8:], None, False )
00465 elif name.count('.') > 1 :
00466 ptool = self._retrieve(name[:name.rfind('.')])
00467 itool = Helper.tool(self._its, '', name[name.rfind('.')+1:], ptool, False )
00468 elif _gaudi :
00469 prop = _gaudi.property(name[:name.rfind('.')])
00470 itool = Helper.tool(self._its, '', name[name.rfind('.')+1:], prop._ip, False )
00471 if quiet : self.OutputLevel = sol
00472 return itool
00473 def retrieve(self, name):
00474 return iAlgTool(name, self._retrieve(name,quiet=False))
00475 def create(self, typ, name=None, parent=None, interface=None) :
00476 if not name : name = typ
00477 itool = Helper.tool(self._its, typ, name, parent, True )
00478 if interface :
00479 return InterfaceCast(interface)(itool)
00480 else :
00481 return iAlgTool(name,itool)
00482 def release(self, itool) :
00483 if type(itool) is iAlgTool :
00484 self._its.releaseTool(itool._itool)
00485
00486
00487 class iJobOptSvc(iService) :
00488 """
00489 Python-image of C++ class IJobOptionsSvc
00490 """
00491
00492 def __init__( self , name , svc ) :
00493 """ constructor """
00494 self.__dict__['_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(svc)
00495 return iService.__init__( self , name , svc )
00496 def getProperties( self , component ) :
00497 """
00498 Extract *ALL* properties of the given component
00499 Usage :
00500 >>> jos = gaudi.optSvc()
00501 >>> props = jos.getProperties( 'Name' )
00502 """
00503 props = self._optsvc.getProperties( component )
00504 prps = {}
00505 if not props : return prps
00506 for p in props :
00507 prop = p.name().upper()
00508 try :
00509 value = eval( p.value() , {} , {} )
00510 except: value = p.value()
00511 prps [ prop ] = value
00512
00513 return prps
00514 def getProperty ( self , component , name ) :
00515 """
00516 Get a certain property of the certain component
00517 Usage:
00518 >>> jos = ...
00519 >>> extServices = jos.getProperty( 'ApplicationMgr', 'ExtSvc' )
00520 """
00521
00522 all = self.getProperties ( component )
00523 return all.get( name.upper() , None )
00524
00525
00526 class iEventSelector(iService):
00527 def __init__(self):
00528 iService.__init__(self, 'EventSelector', Helper.service(gbl.Gaudi.svcLocator(),'EventSelector'))
00529 self.__dict__['g'] = AppMgr()
00530 def open(self, stream, typ = 'POOL_ROOT', opt = 'READ', sel = None, fun = None, collection = None ):
00531 if typ == 'ROOT' :
00532 self.g.declSvcType('RootEvtCnvSvc','DbEventCnvSvc')
00533 self.g.service('RootEvtCnvSvc').DbType = 'ROOT'
00534 self.g.createSvc('RootEvtCnvSvc')
00535 self.g.service('EventPersistencySvc').CnvServices = ['RootEvtCnvSvc']
00536 elif typ == 'POOL_ROOT':
00537 cacsvc = self.g.service('PoolDbCacheSvc')
00538 if hasattr(cacsvc, 'Dlls') : cacsvc.Dlls += ['lcg_RootStorageSvc', 'lcg_XMLCatalog']
00539 else : cacsvc.Dlls = ['lcg_RootStorageSvc', 'lcg_XMLCatalog']
00540 cacsvc.OutputLevel = 4
00541 cacsvc.DomainOpts = [ 'Domain[ROOT_All].CLASS_VERSION=2 TYP=int',
00542 'Domain[ROOT_Key].CLASS_VERSION=2 TYP=int',
00543 'Domain[ROOT_Tree].CLASS_VERSION=2 TYP=int' ]
00544 cacsvc.DatabaseOpts = ['']
00545 cacsvc.ContainerOpts = ['']
00546 self.g.createSvc('PoolDbCacheSvc')
00547 cnvSvcs = [('PoolRootEvtCnvSvc', 'POOL_ROOT'),
00548 ('PoolRootTreeEvtCnvSvc', 'POOL_ROOTTREE'),
00549 ('PoolRootKeyEvtCnvSvc', 'POOL_ROOTKEY')]
00550 for svc in cnvSvcs :
00551 self.g.declSvcType(svc[0], 'PoolDbCnvSvc')
00552 cnvsvc = self.g.service(svc[0])
00553 cnvsvc.DbType = svc[1]
00554 self.g.service('EventPersistencySvc').CnvServices = [ svc[0] for svc in cnvSvcs ]
00555 for svc in cnvSvcs :
00556 self.g.createSvc(svc[0])
00557 self.g.service('EventDataSvc').RootCLID = 1
00558 if type(stream) != list : stream = [stream]
00559 fixpart = "TYP=\'%s\' OPT=\'%s\'" % ( typ, opt )
00560 if sel : fixpart += " SEL=\'%s\'" % sel
00561 if fun : fixpart += " FUN=\'%s\'" % fun
00562 if collection : fixpart += " COLLECTION=\'%s\'" % collection
00563 cstream = ["DATAFILE=\'%s\' %s" % ( s, fixpart) for s in stream]
00564 self.Input = cstream
00565 self.reinitialize()
00566 def rewind(self):
00567
00568 self.g.service('EventLoopMgr').reinitialize()
00569
00570
00571 class AppMgr(iService) :
00572 def __new__ ( cls, *args, **kwargs ):
00573 global _gaudi
00574 if not _gaudi :
00575 newobj = object.__new__( cls, *args, **kwargs )
00576 cls.__init__(newobj, *args, **kwargs)
00577 _gaudi = newobj
00578 return _gaudi
00579 def __reset__(self):
00580 global _gaudi
00581
00582 self.exit()
00583
00584 self._evtpro.release()
00585 self._svcloc.release()
00586 self._appmgr.release()
00587
00588 gbl.Gaudi.setInstance(makeNullPointer('ISvcLocator'))
00589 gbl.Gaudi.setInstance(makeNullPointer('IAppMgrUI'))
00590
00591 _gaudi = None
00592 def __init__(self, outputlevel = -1, joboptions = None, selfoptions = {},
00593 dllname = None, factname = None) :
00594 global _gaudi
00595 if _gaudi : return
00596 try:
00597 from GaudiKernel.Proxy.Configurable import expandvars
00598 except ImportError:
00599
00600 expandvars = lambda data : data
00601 if dllname and factname:
00602 self.__dict__['_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname,factname)
00603 elif dllname:
00604 self.__dict__['_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname)
00605 else:
00606 self.__dict__['_appmgr'] = gbl.Gaudi.createApplicationMgr()
00607 self.__dict__['_svcloc'] = gbl.Gaudi.svcLocator()
00608 self.__dict__['_algmgr'] = InterfaceCast(gbl.IAlgManager)(self._appmgr)
00609 self.__dict__['_evtpro'] = InterfaceCast(gbl.IEventProcessor)(self._appmgr)
00610 self.__dict__['_svcmgr'] = InterfaceCast(gbl.ISvcManager)(self._appmgr)
00611 self.__dict__['pyalgorithms'] = []
00612 iService.__init__(self, 'ApplicationMgr', self._appmgr )
00613
00614 if self.FSMState() < Gaudi.StateMachine.CONFIGURED :
00615 self.JobOptionsType = 'NONE'
00616 if joboptions :
00617 from GaudiKernel.ProcessJobOptions import importOptions
00618 importOptions(joboptions)
00619
00620 import GaudiKernel.Proxy.Configurable
00621 if hasattr(GaudiKernel.Proxy.Configurable, "applyConfigurableUsers"):
00622 GaudiKernel.Proxy.Configurable.applyConfigurableUsers()
00623
00624 self.OutputLevel = 3
00625 selfprops = Configurable.allConfigurables.get('ApplicationMgr',{})
00626 if selfprops : selfprops = expandvars(selfprops.getValuedProperties())
00627 for p,v in selfprops.items() : setattr(self, p, v)
00628 for p,v in selfoptions.items() : setattr(self, p, v)
00629
00630 if outputlevel != -1 : self.OutputLevel = outputlevel
00631 self.configure()
00632
00633 ms = self.service('MessageSvc')
00634 if 'MessageSvc' in Configurable.allConfigurables:
00635 msprops = Configurable.allConfigurables['MessageSvc']
00636 ms = self.service('MessageSvc')
00637 if hasattr(msprops,"getValuedProperties"):
00638 msprops = expandvars(msprops.getValuedProperties())
00639 for p,v in msprops.items():
00640 setattr(ms, p, v)
00641 if outputlevel != -1 : ms.OutputLevel = outputlevel
00642
00643 self.__dict__['_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(Helper.service(self._svcloc,'JobOptionsSvc'))
00644
00645 for n in getNeededConfigurables():
00646 c = Configurable.allConfigurables[n]
00647 if n in ['ApplicationMgr','MessageSvc'] : continue
00648 for p, v in c.getValuedProperties().items() :
00649 v = expandvars(v)
00650
00651 if hasattr(Configurable,"PropertyReference") and type(v) == Configurable.PropertyReference:
00652
00653
00654 v = v.__resolve__()
00655 if type(v) == str : v = '"%s"' % v
00656 elif type(v) == long: v = '%d' % v
00657 self._optsvc.addPropertyToCatalogue(n, StringProperty(p,str(v)))
00658 if hasattr(Configurable,"_configurationLocked"):
00659 Configurable._configurationLocked = True
00660 def state(self) : return self._isvc.FSMState()
00661 def FSMState(self) : return self._isvc.FSMState()
00662 def targetFSMState(self) : return self._isvc.targetFSMState()
00663 def loaddict(self, dict) :
00664 loaddict(dict)
00665 def service(self, name, interface = None) :
00666 svc = Helper.service( self._svcloc, name )
00667 if interface :
00668 return InterfaceCast(interface)(svc)
00669 else :
00670 return iService(name, svc )
00671 def declSvcType(self, svcname, svctype ) :
00672 self._svcmgr.declareSvcType(svcname, svctype)
00673 def createSvc(self, name ) :
00674 return Helper.service( self._svcloc, name, True )
00675 def services(self) :
00676 l = self._svcloc.getServices()
00677 nl = l.__class__(l)
00678 s = []
00679 for i in range(l.size()) :
00680 s.append(nl.front().name())
00681 nl.pop_front()
00682 return s
00683 def algorithm(self, name ) :
00684 alg = Helper.algorithm( self._algmgr, name )
00685 return iAlgorithm(name, alg )
00686 def algorithms(self) :
00687 l = self._algmgr.getAlgorithms()
00688 nl = l.__class__(l)
00689 s = []
00690 for i in range(l.size()) :
00691 s.append(nl.front().name())
00692 nl.pop_front()
00693 return s
00694 def tool(self, name ) :
00695 return iAlgTool(name)
00696 def property( self , name ) :
00697 if name in self.algorithms() : return self.algorithm( name )
00698 elif name in self.services() : return self.service(name )
00699 else : return iProperty( name )
00700 def datasvc(self, name) :
00701 if self.state() == Gaudi.StateMachine.CONFIGURED : self.initialize()
00702 svc = Helper.service( self._svcloc, name )
00703 return iDataSvc(name, svc)
00704 def evtsvc(self) :
00705 return self.datasvc('EventDataSvc')
00706 def detsvc(self) :
00707 return self.datasvc('DetectorDataSvc')
00708 def evtsel(self):
00709 if self.state() == Gaudi.StateMachine.CONFIGURED : self.initialize()
00710 if not hasattr(self,'_evtsel') : self.__dict__['_evtsel'] = iEventSelector()
00711 return self._evtsel
00712 def histsvc(self, name='HistogramDataSvc') :
00713 svc = Helper.service( self._svcloc, name )
00714 return iHistogramSvc(name, svc)
00715 def ntuplesvc(self, name='NTupleSvc') :
00716 if name not in self.ExtSvc : self.ExtSvc += [name]
00717
00718 svc = Helper.service( self._svcloc, name, True )
00719 return iNTupleSvc(name, svc)
00720 def partsvc(self ) :
00721 if self.FSMState() == Gaudi.StateMachine.CONFIGURED : self.initialize()
00722 svc = Helper.service( self._svcloc, 'ParticlePropertySvc' )
00723 return InterfaceCast(gbl.IParticlePropertySvc)(svc)
00724 def toolsvc(self, name='ToolSvc') :
00725 svc = Helper.service( self._svcloc, name, True )
00726 return iToolSvc(name, svc)
00727 def optSvc (self, name='JobOptionsSvc') :
00728 svc = Helper.service( self._svcloc, name, True )
00729 return iJobOptSvc(name, svc)
00730 def readOptions(self, file) :
00731 return self._optsvc.readOptions(file)
00732 def addAlgorithm(self, alg) :
00733 """ Add an Algorithm to the list of Top algorithms. It can be either a instance of
00734 an Algorithm class or it name """
00735 if type(alg) is str :
00736 self.topAlg += [alg]
00737 else :
00738 self.pyalgorithms.append(alg)
00739 setOwnership(alg,0)
00740 if self.targetFSMState() >= Gaudi.StateMachine.INITIALIZED :
00741 alg.sysInitialize()
00742 if self.targetFSMState() == Gaudi.StateMachine.RUNNING :
00743 alg.sysStart()
00744 self.topAlg += [alg.name()]
00745 def setAlgorithms(self, algs) :
00746 """ Set the list of Top Algorithms.
00747 It can be an individual of a list of algorithms names or instances """
00748 if type(algs) is not list : algs = [algs]
00749 names = []
00750 for alg in algs :
00751 if type(alg) is str : names.append(alg)
00752 else :
00753 self.pyalgorithms.append(alg)
00754 if self.targetFSMState() >= Gaudi.StateMachine.INITIALIZED :
00755 alg.sysInitialize()
00756 if self.targetFSMState() == Gaudi.StateMachine.RUNNING :
00757 alg.sysStart()
00758 names.append(alg.name())
00759 self.topAlg = names
00760 def removeAlgorithm(self, alg) :
00761 """ Remove an Algorithm to the list of Top algorithms. It can be either a instance of
00762 an Algorithm class or it name """
00763 tmp = self.topAlg
00764 if type(alg) is str :
00765 tmp.remove(alg)
00766 else :
00767 tmp.remove(alg.name())
00768 self.pyalgorithms.remove(alg)
00769 setOwnership(alg,1)
00770 self.topAlg = tmp
00771 def config ( self, **args ):
00772 """
00773 Simple utility to perform the configuration of Gaudi application.
00774 It reads the set of input job-options files, and set few
00775 additional parameters 'options' through the usage of temporary *.opts file
00776 Usage:
00777 gaudi.config( files = [ '$GAUSSOPTS/Gauss.opts' ,
00778 '$DECFILESROOT/options/10022_010.0GeV.opts' ] ,
00779 options = [ 'EventSelector.PrintFreq = 5 ' ] )
00780 """
00781 files = args.get('files',[])
00782 for file in files :
00783 sc = self.readOptions(file)
00784 if sc.isFailure() :
00785 raise RuntimeError , ' Unable to read file "' + file +'" '
00786 options = args.get('options',None)
00787 if options :
00788 import tempfile
00789 tmpfilename = tempfile.mktemp()
00790 tmpfile = open( tmpfilename, 'w' )
00791 tmpfile.write ( '#pragma print on \n' )
00792 tmpfile.write ( '/// File "' + tmpfilename+'" generated by GaudiPython \n\n' )
00793 for opt in options :
00794 if type(options) is dict :
00795 tmpfile.write( ' \t ' + opt + ' = '+ options[opt]+ ' ; // added by GaudiPython \n' )
00796 else :
00797 tmpfile.write( ' \t ' + opt + ' ; // added by GaudiPython \n' )
00798 tmpfile.write ( '/// End of file "' + tmpfilename+'" generated by GaudiPython \n\n' )
00799 tmpfile.close()
00800 sc = self.readOptions( tmpfilename )
00801 if sc.isFailure() :
00802 raise RuntimeError , ' Unable to read file "' + tmpfilename +'" '
00803 os.remove( tmpfilename )
00804
00805 if self.FSMState() != Gaudi.StateMachine.OFFLINE :
00806
00807
00808 jos = self.optSvc()
00809
00810
00811 _dlls = jos.getProperty ( self.name() , 'DLLs' )
00812
00813 if _dlls :
00814 libs = [ l for l in _dlls if not l in self.DLLs ]
00815 if libs : self.DLLs += libs
00816
00817
00818 _svcs = jos.getProperty ( self.name() , 'ExtSvc' )
00819
00820 if _svcs :
00821 svcs = [ s for s in _svcs if not s in self.ExtSvc ]
00822 if svcs : self.ExtSvc += svcs
00823
00824
00825 props = jos.getProperties ( self.name() )
00826
00827 for key in props :
00828 if 'DLLS' == key or 'EXTSVC' == key : continue
00829 self.__setattr__( key , props[key] )
00830 return SUCCESS
00831 def configure(self) :
00832 return self._appmgr.configure()
00833 def start(self) :
00834 return self._appmgr.start()
00835 def run(self, n) :
00836 if self.FSMState() == Gaudi.StateMachine.CONFIGURED :
00837 sc = self.initialize()
00838 if sc.isFailure(): return sc
00839 if self.FSMState() == Gaudi.StateMachine.INITIALIZED :
00840 sc = self.start()
00841 if sc.isFailure(): return sc
00842 return self._evtpro.executeRun(n)
00843 def executeEvent(self) :
00844 return self._evtpro.executeEvent()
00845 def execute(self) :
00846 return self._evtpro.executeEvent()
00847 def runSelectedEvents(self, pfn, events):
00848 if self.FSMState() == Gaudi.StateMachine.CONFIGURED :
00849 sc = self.initialize()
00850 if sc.isFailure(): return sc
00851 if self.FSMState() == Gaudi.StateMachine.INITIALIZED :
00852 sc = self.start()
00853 if sc.isFailure(): return sc
00854
00855 if not hasattr(self,'_perssvc'): self.__dict__['_perssvc'] = self.service('EventPersistencySvc','IAddressCreator')
00856 if not hasattr(self,'_filecat'): self.__dict__['_filecat'] = self.service('FileCatalog','Gaudi::IFileCatalog')
00857 if not hasattr(self,'_evtmgr'): self.__dict__['_evtmgr'] = self.service('EventDataSvc','IDataManagerSvc')
00858
00859 if pfn.find('PFN:') == 0: pfn = pfn[4:]
00860 fid, maxevt = _getFIDandEvents(pfn)
00861
00862 if not self._filecat.existsFID(fid) : self._filecat.registerPFN(fid, pfn, '')
00863
00864 if type(events) is not list : events = (events,)
00865 for evt in events :
00866
00867 gadd = gbl.GenericAddress(0x202, 1, fid, '/Event', 0, evt)
00868 oadd = makeNullPointer('IOpaqueAddress')
00869 self._perssvc.createAddress(gadd.svcType(),gadd.clID(),gadd.par(),gadd.ipar(),oadd)
00870
00871 self._evtmgr.clearStore()
00872 self._evtmgr.setRoot('/Event',oadd)
00873 self._evtpro.executeEvent()
00874 def exit(self) :
00875 if self.FSMState() == Gaudi.StateMachine.RUNNING: self._appmgr.stop().ignore()
00876 if self.FSMState() == Gaudi.StateMachine.INITIALIZED: self._appmgr.finalize().ignore()
00877 return self._appmgr.terminate()
00878 evtSvc = evtsvc
00879 histSvc = histsvc
00880 ntupleSvc = ntuplesvc
00881 evtSel = evtsel
00882 detSvc = detsvc
00883 toolSvc = toolsvc
00884 partSvc = partsvc
00885
00886
00887 def _getFIDandEvents( pfn ):
00888 tfile = gbl.TFile.Open(pfn)
00889 if not tfile : raise 'Cannot open ROOT file ', pfn
00890 tree = tfile.Get('##Params')
00891 tree.GetEvent(0)
00892 text = tree.db_string
00893 if 'NAME=FID' in text :
00894 fid = text[text.rfind('VALUE=')+6:-1]
00895 nevt = tfile.Get('_Event').GetEntries()
00896 tfile.Close()
00897 return fid, nevt
00898
00899
00900 def getComponentProperties( name ):
00901 """ Get all the properties of a component as a Python dictionary.
00902 The component is instantiated using the component library
00903 """
00904 properties = {}
00905 if name == 'GaudiSvc' :
00906 if Helper.loadDynamicLib(name) != 1 :
00907 raise ImportError, 'Error loading component library '+ name
00908 factorylist = gbl.FactoryTable.instance().getEntries()
00909 factories = _copyFactoriesFromList(factorylist)
00910 g = AppMgr(outputlevel=7)
00911 else :
00912 g = AppMgr(outputlevel=7)
00913 if Helper.loadDynamicLib(name) != 1 :
00914 raise ImportError, 'Error loading component library '+ name
00915 factorylist = gbl.FactoryTable.instance().getEntries()
00916 factories = _copyFactoriesFromList(factorylist)
00917 svcloc = gbl.Gaudi.svcLocator()
00918 dummysvc = gbl.Service('DummySvc',svcloc)
00919 for factory in factories :
00920 if InterfaceCast(gbl.IAlgFactory)(factory) : ctype = 'Algorithm'
00921 elif InterfaceCast(gbl.ISvcFactory)(factory) : ctype = 'Service'
00922 elif InterfaceCast(gbl.IToolFactory)(factory) : ctype = 'AlgTool'
00923 elif factory.ident() == 'ApplicationMgr' : ctype = 'ApplicationMgr'
00924 else : ctype = 'Unknown'
00925 cname = factory.ident().split()[-1]
00926 if ctype in ('Algorithm','Service', 'AlgTool', 'ApplicationMgr') :
00927 try :
00928 if ctype == 'AlgTool' :
00929 obj = factory.instantiate(dummysvc)
00930 else :
00931 obj = factory.instantiate(svcloc)
00932 except RuntimeError, text :
00933 print 'Error instantiating', cname, ' from ', name
00934 print text
00935 continue
00936 prop = iProperty('dummy', obj)
00937 properties[cname] = [ctype, prop.properties()]
00938 try: obj.release()
00939 except: pass
00940 return properties
00941
00942 def _copyFactoriesFromList(factories) :
00943 result = []
00944 for i in range(factories.size()) :
00945 factory = factories.front()
00946 result.append(factory)
00947 factories.pop_front()
00948 for factory in result :
00949 factories.push_back(factory)
00950 return result
00951
00952
00953
00954 _CallbackStreamBufBase = gbl.GaudiPython.CallbackStreamBuf
00955 class CallbackStreamBuf (_CallbackStreamBufBase):
00956 def __init__(self, callback):
00957 _CallbackStreamBufBase.__init__(self, self)
00958 self.callback = callback
00959 def _sync(self, string = None):
00960 if not string : return 0
00961 self.callback(string)
00962 return 0
00963
00964
00965
00966 _PyAlgorithm = gbl.GaudiPython.PyAlgorithm
00967 class PyAlgorithm (_PyAlgorithm) :
00968 def __init__(self, name=None) :
00969 if not name : name = self.__class__.__name__
00970 _PyAlgorithm.__init__(self, self, name)
00971 self._svcloc = gbl.Gaudi.svcLocator()
00972 self._algmgr = InterfaceCast(gbl.IAlgManager)(self._svcloc)
00973 sc = self._algmgr.addAlgorithm(self)
00974 if sc.isFailure() : raise RuntimeError, 'Unable to add Algorithm'
00975 def __del__(self):
00976 sc = self._algmgr.removeAlgorithm(self)
00977 if sc.isFailure() : pass
00978 def initialize(self) : return 1
00979 def start(self) : return 1
00980 def execute(self) : return 1
00981 def stop(self) : return 1
00982 def finalize(self) : return 1
00983 def beginRun(self) : return 1
00984 def endRun(self) : return 1
00985
00986
00987
00988
00989 import atexit
00990 def _atexit_() :
00991 if _gaudi :
00992 state = _gaudi.FSMState()
00993 if state in [ Gaudi.StateMachine.CONFIGURED, Gaudi.StateMachine.INITIALIZED,
00994 Gaudi.StateMachine.RUNNING ]:
00995 _gaudi.exit()
00996 atexit.register( _atexit_ )
00997
00998
00999 try:
01000 import rlcompleter,readline
01001 readline.parse_and_bind("tab: complete")
01002 except:
01003 pass
01004