4 """ GaudiPython.Bindings module.
5 This module provides the basic bindings of the main Gaudi
6 components to Python. It is itself based on the ROOT cppyy
7 Python extension module.
10 __all__ = [
'gbl',
'InterfaceCast',
'Interface',
'PropertyEntry',
11 'AppMgr',
'PyAlgorithm',
'CallbackStreamBuf',
12 'iAlgorithm',
'iDataSvc',
'iHistogramSvc',
'iNTupleSvc',
'iService',
'iAlgTool',
'Helper',
13 'SUCCESS',
'FAILURE',
'toArray',
14 'ROOT',
'makeNullPointer',
'setOwnership',
15 'getClass',
'loaddict',
'deprecation' ]
17 from GaudiKernel
import ROOT6WorkAroundEnabled
19 import os, sys, string, warnings, re
24 print "# WARNING: using PyCintex as cppyy implementation"
25 import PyCintex
as cppyy
45 Helper = gbl.GaudiPython.Helper
46 StringProperty = gbl.SimpleProperty (
'string',
'BoundedVerifier<string>')
47 StringPropertyRef = gbl.SimplePropertyRef (
'string',
'NullVerifier<string>')
48 GaudiHandleProperty = gbl.GaudiHandleProperty
49 GaudiHandleArrayProperty = gbl.GaudiHandleArrayProperty
50 DataObject = gbl.DataObject
51 SUCCESS = gbl.StatusCode( gbl.StatusCode.SUCCESS,
True )
52 FAILURE = gbl.StatusCode( gbl.StatusCode.FAILURE,
True )
55 for l
in [ l
for l
in dir(Helper)
if re.match(
"^to.*Array$",l) ]:
56 exec
"%s = Helper.%s"%(l,l)
60 if hasattr(Helper,
"toArray"):
63 toArray =
lambda typ: getattr(Helper,
"toArray")
66 toArray =
lambda typ: getattr(Helper,
"toArray<%s>"%typ)
69 ROOT = cppyy.libPyROOT
70 makeNullPointer = cppyy.libPyROOT.MakeNullPointer
71 setOwnership = cppyy.libPyROOT.SetOwnership
74 warnings.warn(
'GaudiPython: '+ message, DeprecationWarning, stacklevel=3)
77 class InterfaceCast(object) :
78 """ Helper class to obtain the adequate interface from a component
79 by using the Gaudi queryInterface() mechanism """
80 def __init__(self, t ) :
84 def __call__(self, obj) :
88 if obj.queryInterface(self.type.interfaceID(), ip).isSuccess() :
91 print "ERROR: queryInterface failed for", obj,
"interface:", self.type
93 print "ERROR: exception", e,
"caught when retrieving interface", self.type,
"for object", obj
95 traceback.print_stack()
99 class Interface(InterfaceCast) :
100 def __init__(self, t ):
102 InterfaceCast.__init__(self,t)
103 def cast(self, obj) :
108 """ Load a LCG dictionary using various mechanisms"""
109 if Helper.loadDynamicLib(dict) == 1 :
return
114 raise ImportError,
'Error loading dictionary library'
119 Function to retrieve a certain C++ class by name and to load dictionary if requested
123 from gaudimodule import getClass
124 # one knows that class is already loaded
125 AppMgr = getClass( 'ApplicationMgr' )
126 # one knows where to look for class, if not loaded yet
127 MCParticle = getClass( 'MCParticle' , 'EventDict' )
128 # one knows where to look for class, if not loaded yet
129 Vertex = getClass( 'Vertex' , ['EventDict', 'PhysEventDict'] )
132 if hasattr( gbl , name ) :
return getattr( gbl , name )
134 if type(libs)
is not list : libs = [libs]
137 if hasattr( gbl , name ) :
return getattr( gbl , name )
142 class PropertyEntry(object) :
143 """ holds the value and the documentation string of a property """
144 def __init__(self, prop) :
145 self._type =
type(prop).__name__
146 self.__doc__ =
" --- Property type is " + self.ptype()
148 if issubclass(
type(prop),GaudiHandleProperty) :
149 self._value = prop.value()
150 elif issubclass(
type(prop),GaudiHandleArrayProperty) :
151 self._value = prop.value()
154 try: self._value = eval( prop.toString() , {} , {} )
156 if hasattr ( prop ,
'value' ) : self._value = prop.value()
157 else : self._value = prop.toString()
159 self.__doc__ +=
" --- Default value = " + str(self._value) +
" --- "
160 if prop.documentation() !=
'none':
161 self.__doc__ = prop.documentation() +
'\\n' + self.__doc__
163 self._property = prop
169 "Return the underlying property itself "
170 return self._property
171 def documentation(self) :
174 return len(self.__doc__)>0
and self.__doc__ !=
'none'
177 class iProperty(object) :
178 """ Python equivalent to the C++ Property interface """
179 def __init__(self, name, ip = None) :
180 if ip : self.__dict__[
'_ip'] = InterfaceCast(gbl.IProperty)(ip)
181 else : self.__dict__[
'_ip'] =
None
182 self.__dict__[
'_svcloc'] = gbl.Gaudi.svcLocator()
183 optsvc = Helper.service(self._svcloc,
'JobOptionsSvc')
184 if optsvc : self.__dict__[
'_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(optsvc)
185 else : self.__dict__[
'_optsvc'] =
None
186 self.__dict__[
'_name'] = name
187 def getInterface(self) :
188 if not self._ip : self.retrieveInterface()
190 def retrieveInterface(self) :
192 def __call_interface_method__(self,ifname,method,*args):
193 if not getattr(self,ifname) : self.retrieveInterface()
194 return getattr(getattr(self,ifname),method)(*args)
195 def __setattr__(self, name, value):
197 The method which is used for setting the property from the given value.
198 - In the case of the valid instance it sets the property through IProperty interface
199 - In the case of placeholder the property is added to JobOptionsCatalogue
201 if hasattr( value,
'toStringProperty' ):
203 value =
'%s' % value.toStringProperty()
204 ip = self.getInterface()
206 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
207 raise AttributeError,
'property %s does not exist' % name
208 prop = ip.getProperty(name)
211 canSetValue = (hasattr(prop,
'value')
and
212 'const&[' not in prop.value.func_doc
and
215 canSetValue = (hasattr(prop,
'value')
and
219 if not prop.setValue(value) :
220 raise AttributeError,
'property %s could not be set from %s' % (name, value)
222 if tuple ==
type( value ) : value = str(value)
223 elif hasattr ( value ,
'toString' ) : value = value.toString()
224 elif not long ==
type( value ) : value =
'%s' % value
225 else : value =
'%d' % value
227 sc = cppyy.gbl.GaudiPython.Helper.setPropertyFromString(prop, value)
229 sc = prop.fromString(value)
231 raise AttributeError,
'property %s could not be set from %s' % (name,value)
233 if type(value) == str : value =
'"%s"' % value
234 elif type(value) == tuple : value = str(value)
235 elif hasattr( value ,
'toString' ) : value = value.toString()
236 elif type(value) == long: value =
'%d' % value
238 self._optsvc.addPropertyToCatalogue( self._name , sp )
239 def __getattr__(self, name ):
241 The method which returns the value for the given property
242 - In the case of the valid instance it returns the valid property value through IProperty interface
243 - In the case of placeholder the property value is retrieved from JobOptionsCatalogue
245 ip = self.getInterface()
247 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
248 raise AttributeError,
'property %s does not exist' % name
249 prop = ip.getProperty(name)
250 if StringProperty ==
type( prop ) :
return prop.value()
251 elif StringPropertyRef ==
type( prop ) :
return prop.value()
252 try:
return eval( prop.toString(), {}, {} )
253 except :
return prop.value()
255 props = self._optsvc.getProperties(self._name)
257 if not p.name() == name :
continue
259 try:
return eval( p.value(), {}, {} )
260 except:
return p.value()
261 raise AttributeError,
'property %s does not exist' % name
265 ip = self.getInterface()
267 props = ip.getProperties()
268 propsFrom = self._name
270 props = self._optsvc.getProperties( self._name )
271 propsFrom =
"jobOptionsSvc"
275 dct[p.name()] = PropertyEntry(p)
276 except (ValueError,TypeError),e:
277 raise ValueError,
"gaudimodule.iProperty.properties(): %s%s processing property %s.%s = %s" % \
278 (e.__class__.__name__, e.args, propsFrom, p.name(), p.value())
284 class iService(iProperty) :
285 """ Python equivalent to IProperty interface """
286 def __init__(self, name, isvc = None ) :
287 iProperty.__init__(self, name, isvc )
288 if isvc : self.__dict__[
'_isvc'] = InterfaceCast(gbl.IService)(isvc)
289 else : self.__dict__[
'_isvc'] =
None
290 def retrieveInterface(self) :
291 isvc = Helper.service(self._svcloc,self._name)
292 if isvc : iService.__init__(self, self._name, isvc)
293 initialize =
lambda self : self.__call_interface_method__(
"_isvc",
"initialize")
294 start =
lambda self : self.__call_interface_method__(
"_isvc",
"start")
295 stop =
lambda self : self.__call_interface_method__(
"_isvc",
"stop")
296 finalize =
lambda self : self.__call_interface_method__(
"_isvc",
"finalize")
297 reinitialize =
lambda self : self.__call_interface_method__(
"_isvc",
"reinitialize")
298 restart =
lambda self : self.__call_interface_method__(
"_isvc",
"restart")
300 if self._isvc:
return True
305 """ Python equivalent to IAlgorithm interface """
306 def __init__(self, name, ialg = None ) :
307 iProperty.__init__(self, name, ialg )
308 if ialg : self.__dict__[
'_ialg'] = InterfaceCast(gbl.IAlgorithm)(ialg)
309 else : self.__dict__[
'_ialg'] =
None
310 def retrieveInterface(self) :
311 ialg = Helper.algorithm(InterfaceCast(gbl.IAlgManager)(self._svcloc),self._name)
312 if ialg : iAlgorithm.__init__(self, self._name, ialg)
313 initialize =
lambda self : self.__call_interface_method__(
"_ialg",
"initialize")
314 start =
lambda self : self.__call_interface_method__(
"_ialg",
"start")
315 execute =
lambda self : self.__call_interface_method__(
"_ialg",
"execute")
316 stop =
lambda self : self.__call_interface_method__(
"_ialg",
"stop")
317 finalize =
lambda self : self.__call_interface_method__(
"_ialg",
"finalize")
318 reinitialize =
lambda self : self.__call_interface_method__(
"_ialg",
"reinitialize")
319 restart =
lambda self : self.__call_interface_method__(
"_ialg",
"restart")
320 sysInitialize =
lambda self : self.__call_interface_method__(
"_ialg",
"sysInitialize")
321 sysStart =
lambda self : self.__call_interface_method__(
"_ialg",
"sysStart")
322 sysExecute =
lambda self : self.__call_interface_method__(
"_ialg",
"sysExecute")
323 sysStop =
lambda self : self.__call_interface_method__(
"_ialg",
"sysStop")
324 sysFinalize =
lambda self : self.__call_interface_method__(
"_ialg",
"sysFinalize")
325 sysReinitialize =
lambda self : self.__call_interface_method__(
"_ialg",
"sysReinitialize")
326 sysRestart =
lambda self : self.__call_interface_method__(
"_ialg",
"sysRestart")
330 """ Python equivalent to IAlgTool interface (not completed yet) """
331 def __init__(self, name, itool = None ) :
332 iProperty.__init__(self, name, itool )
333 if itool : self.__dict__[
'_itool'] = itool
334 else : self.__dict__[
'_itool'] =
None
335 svc = Helper.service( self._svcloc,
'ToolSvc',
True )
336 self.__dict__[
'_toolsvc']= iToolSvc(
'ToolSvc', svc)
337 def retrieveInterface(self) :
338 itool = self._toolsvc._retrieve(self._name)
339 if itool : iAlgTool.__init__(self, self._name, itool)
340 start =
lambda self : self.__call_interface_method__(
"_itool",
"start")
341 stop =
lambda self : self.__call_interface_method__(
"_itool",
"stop")
342 type =
lambda self : self.__call_interface_method__(
"_itool",
"type")
344 if self._itool :
return self._itool.name()
345 else :
return self._name
348 class iDataSvc(iService) :
349 def __init__(self, name, idp) :
350 iService.__init__(self, name, idp )
351 self.__dict__[
'_idp'] = InterfaceCast(gbl.IDataProviderSvc)(idp)
352 self.__dict__[
'_idm'] = InterfaceCast(gbl.IDataManagerSvc)(idp)
353 def registerObject(self, path, obj) :
354 if not self._idp :
raise AttributeError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
355 return self._idp.registerObject(path,obj)
356 def unregisterObject(self, path) :
357 if not self._idp :
raise AttributeError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
358 return self._idp.unregisterObject(path)
359 def retrieveObject(self, path) :
360 if not self._idp :
return None
361 return Helper.dataobject(self._idp, path)
363 def findObject(self, path) :
366 Get the existing object in TransientStore for the given location
368 - loading of object from persistency is NOT triggered
369 - 'data-on-demand' action is NOT triggered
371 >>> svc = ... ## get the service
372 >>> path = ... ## get the path in Transient Store
373 >>> data = svc.findObject ( path ) ## use the method
376 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
377 return Helper.findobject(self._idp, path)
380 def getObject ( self , path , *args ) :
382 Get object from Transient Store for the given location
385 - path : Location of object in Transient Store
386 - retrieve (bool) True : retrieve versus find
387 - disable on-demand (bool) False : temporary disable 'on-demand' actions
389 >>> svc = ... ## get the service
390 >>> path = ... ## get the path
392 >>> data = svc.getObject ( path , False ) ## find object in Transient Store
394 ## find object in Transient Store
395 # load form tape or use 'on-demand' action for missing objects :
396 >>> data = svc.getObject ( path , True )
398 ## find object in Transient Store
399 # load from tape or for missing objects, disable 'on-demand'-actions
400 >>> data = svc.getObject ( path , True , True )
403 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
404 return Helper.getobject(self._idp, path, *args )
406 def __getitem__(self, path) :
407 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
408 return Helper.dataobject(self._idp, path)
409 def __setitem__(self, path, obj) :
410 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
411 return self._idp.registerObject(path,obj)
412 def __delitem__(self, path) :
413 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
414 return self._idp.unregisterObject(path)
415 def leaves(self, node=None) :
416 if not node : node = self.retrieveObject(
'')
417 ll = gbl.std.vector(
'IRegistry*')()
418 if type(node)
is str : obj = self.retrieveObject(node)
420 if self._idm.objectLeaves(node, ll).isSuccess() :
return ll
421 def dump(self, node=None) :
423 root = self.retrieveObject(
'')
424 if root : node = root.registry()
426 print node.identifier()
428 for l
in self.leaves(node) : self.dump(l)
429 def getList(self, node=None, lst=[], rootFID=None) :
431 root = self.retrieveObject(
'')
433 node = root.registry()
434 rootFID = node.address().
par()
438 Helper.dataobject( self._idp, node.identifier() )
440 lst.append( node.identifier() )
441 for l
in self.leaves(node) :
442 if l.address()
and l.address().
par() == rootFID :
443 self.getList(l,lst,rootFID)
447 def getHistoNames( self, node=None, lst=[] ) :
449 root = self.retrieveObject(
'')
451 node = root.registry()
455 Helper.dataobject( self._idp, node.identifier() )
457 lst.append( node.identifier() )
458 for l
in self.leaves(node) :
460 self.getHistoNames(l,lst)
464 def setRoot(self, name, obj):
465 if not self._idm :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
466 return self._idm.setRoot(name,obj)
467 def clearStore(self):
468 if not self._idm :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
469 return self._idm.clearStore()
473 class iHistogramSvc(iDataSvc) :
474 def __init__(self, name, ihs) :
475 self.__dict__[
'_ihs'] = InterfaceCast(gbl.IHistogramSvc)(ihs)
476 iDataSvc.__init__(self, name, ihs)
477 def retrieve1D(self, path) :
478 return Helper.histo1D(self._ihs, path)
479 def retrieve2D(self, path) :
480 return Helper.histo2D(self._ihs, path)
481 def retrieve3D(self, path) :
482 return Helper.histo3D(self._ihs, path)
483 def retrieveProfile1D(self, path) :
484 return Helper.profile1D(self._ihs, path)
485 def retrieveProfile2D(self, path) :
486 return Helper.profile2D(self._ihs, path)
487 def retrieve(self,path):
489 Retrieve AIDA histogram or AIDA profile histogram by path in Histogram Transient Store
491 >>> histo = svc.retrieve ( 'path/to/my/histogram' )
493 h = self.retrieve1D(path)
494 if not h : h = self.retrieve2D(path)
495 if not h : h = self.retrieve3D(path)
496 if not h : h = self.retrieveProfile1D(path)
497 if not h : h = self.retrieveProfile2D(path)
499 def book(self, *args) :
501 Book the histograms(1D,2D&3D) , see IHistogramSvc::book
503 >>> histo = svc.book( .... )
505 return apply(self._ihs.book,args)
508 Book the profile(1D&2D) histograms, see IHistogramSvc::bookProf
510 >>> histo = svc.bookProf( .... )
512 return apply(self._ihs.bookProf,args)
513 def __getitem__ ( self, path ) :
515 Retrieve the object from Histogram Transient Store (by path)
516 The reference to AIDA histogram is returned (if possible)
518 >>> histo = svc['path/to/my/histogram']
520 h = self.retrieve ( path )
522 return iDataSvc.__getitem__( self , path )
525 Retrieve the histogram from Histogram Transient Store (by path)
526 The reference to AIDA histogram is returned (if possible)
528 >>> histo = svc.getAsAIDA ( 'path/to/my/histogram' )
530 return self.__getitem__( path )
533 Retrieve the histogram from Histogram Transient Store (by path)
534 The Underlying native ROOT object is returned (if possible)
536 >>> histo = svc.getAsROOT ( 'path/to/my/histogram' )
538 fun = gbl.Gaudi.Utils.Aida2ROOT.aida2root
539 return fun( self.getAsAIDA( path ) )
542 class iNTupleSvc(iDataSvc) :
545 def __init__(self, name, ints) :
546 self.__dict__[
'_ints'] = InterfaceCast(gbl.INTupleSvc)(ints)
547 iDataSvc.__init__(self, name, ints)
548 def book(self, *args) :
549 return apply(self._ints.book, args)
550 def defineOutput(self, files, typ="Gaudi::RootCnvSvc
"):
551 """ Defines the mapping between logical names and the output file
553 defineOutput({'LUN1':'MyFile1.root', 'LUN2':'Myfile2.root'}, svc='Gaudi::RootCnvSvc')
555 import Persistency
as prs
556 helper = prs.get(typ)
557 helper.configure(AppMgr())
558 self.Output = [helper.formatOutput(files[lun], lun=lun)
for lun
in files]
559 if AppMgr().HistogramPersistency ==
'NONE':
560 AppMgr().HistogramPersistency =
"ROOT"
561 def __getitem__ ( self, path ) :
562 return iDataSvc.__getitem__( self , path )
566 class iToolSvc(iService) :
567 def __init__(self, name, its) :
568 self.__dict__[
'_its'] = InterfaceCast(gbl.IToolSvc)(its)
569 iService.__init__(self, name, its)
570 def _retrieve(self, name, quiet=True):
571 sol = _gaudi.OutputLevel
572 if quiet : self.OutputLevel = 6
573 if name.rfind(
'.') == -1 :
574 itool = Helper.tool(self._its,
'', name,
None,
False )
575 elif name[0:8] ==
'ToolSvc.' :
576 itool = Helper.tool(self._its,
'', name[8:],
None,
False )
577 elif name.count(
'.') > 1 :
578 ptool = self._retrieve(name[:name.rfind(
'.')])
579 itool = Helper.tool(self._its,
'', name[name.rfind(
'.')+1:], ptool,
False )
581 prop = _gaudi.property(name[:name.rfind(
'.')])
582 itool = Helper.tool(self._its,
'', name[name.rfind(
'.')+1:], prop._ip,
False )
583 if quiet : self.OutputLevel = sol
585 def retrieve(self, name):
586 return iAlgTool(name, self._retrieve(name,quiet=
False))
587 def create(self, typ, name=None, parent=None, interface=None) :
588 if not name : name = typ
589 itool = Helper.tool(self._its, typ, name, parent,
True )
591 return InterfaceCast(interface)(itool)
594 def release(self, itool) :
595 if type(itool)
is iAlgTool :
596 self._its.releaseTool(itool._itool)
599 class iJobOptSvc(iService) :
601 Python-image of C++ class IJobOptionsSvc
604 def __init__( self , name , svc ) :
606 self.__dict__[
'_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(svc)
607 return iService.__init__( self , name , svc )
608 def getProperties( self , component ) :
610 Extract *ALL* properties of the given component
612 >>> jos = gaudi.optSvc()
613 >>> props = jos.getProperties( 'Name' )
615 props = self._optsvc.getProperties( component )
617 if not props :
return prps
619 prop = p.name().upper()
621 value = eval( p.value() , {} , {} )
622 except: value = p.value()
623 prps [ prop ] = value
628 Get a certain property of the certain component
631 >>> extServices = jos.getProperty( 'ApplicationMgr', 'ExtSvc' )
634 all = self.getProperties ( component )
635 return all.get( name.upper() ,
None )
638 class iEventSelector(iService):
640 iService.__init__(self,
'EventSelector', Helper.service(gbl.Gaudi.svcLocator(),
'EventSelector'))
641 self.__dict__[
'g'] = AppMgr()
642 def open(self, stream, typ = 'Gaudi::RootCnvSvc
', **kwargs):
643 import Persistency
as prs
644 helper = prs.get(typ)
645 helper.configure(self.g)
646 self.Input = helper.formatInput(stream, **kwargs)
650 self.g.service(
'EventLoopMgr').reinitialize()
653 class AppMgr(iService) :
654 def __new__ ( cls, *args, **kwargs ):
657 newobj = object.__new__( cls )
658 cls.__init__(newobj, *args, **kwargs)
666 self._evtpro.release()
667 self._svcloc.release()
668 self._appmgr.release()
674 def __init__(self, outputlevel = -1, joboptions = None, selfoptions = {},
675 dllname =
None, factname =
None) :
679 self.__dict__[
'_exit_called'] =
False
681 self.__dict__[
'_gaudi_ns'] = Gaudi
686 expandvars =
lambda data : data
687 if dllname
and factname:
688 self.__dict__[
'_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname,factname)
690 self.__dict__[
'_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname)
692 self.__dict__[
'_appmgr'] = gbl.Gaudi.createApplicationMgr()
693 self.__dict__[
'_svcloc'] = gbl.Gaudi.svcLocator()
694 self.__dict__[
'_algmgr'] = InterfaceCast(gbl.IAlgManager)(self._appmgr)
695 self.__dict__[
'_evtpro'] = InterfaceCast(gbl.IEventProcessor)(self._appmgr)
696 self.__dict__[
'_svcmgr'] = InterfaceCast(gbl.ISvcManager)(self._appmgr)
697 self.__dict__[
'pyalgorithms'] = []
698 iService.__init__(self,
'ApplicationMgr', self._appmgr )
700 if self.FSMState() < Gaudi.StateMachine.CONFIGURED :
701 self.JobOptionsType =
'NONE'
708 GaudiKernel.Proxy.Configurable.applyConfigurableUsers()
711 selfprops = Configurable.allConfigurables.get(
'ApplicationMgr',{})
712 if selfprops : selfprops =
expandvars(selfprops.getValuedProperties())
713 for p,v
in selfprops.items() : setattr(self, p, v)
714 for p,v
in selfoptions.items() : setattr(self, p, v)
716 if outputlevel != -1 : self.OutputLevel = outputlevel
719 ms = self.service(
'MessageSvc')
720 if 'MessageSvc' in Configurable.allConfigurables:
721 msprops = Configurable.allConfigurables[
'MessageSvc']
722 ms = self.service(
'MessageSvc')
723 if hasattr(msprops,
"getValuedProperties"):
724 msprops =
expandvars(msprops.getValuedProperties())
725 for p,v
in msprops.items():
727 if outputlevel != -1 : ms.OutputLevel = outputlevel
729 self.__dict__[
'_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(Helper.service(self._svcloc,
'JobOptionsSvc'))
732 c = Configurable.allConfigurables[n]
733 if n
in [
'ApplicationMgr',
'MessageSvc'] :
continue
734 for p, v
in c.getValuedProperties().items() :
737 if hasattr(Configurable,
"PropertyReference")
and type(v) == Configurable.PropertyReference:
741 if type(v) == str : v =
'"%s"' % v
742 elif type(v) == long: v =
'%d' % v
744 if hasattr(Configurable,
"_configurationLocked"):
745 Configurable._configurationLocked =
True
749 atexit.register(self.exit)
753 root_handler_installed =
False
754 for h
in atexit._exithandlers:
756 if hasattr(func,
"__module__")
and func.__module__ ==
"ROOT":
757 root_handler_installed =
True
763 if not root_handler_installed:
764 orig_register = atexit.register
765 def register(func, *targs, **kargs):
766 orig_register(func, *targs, **kargs)
767 if hasattr(func,
"__module__")
and func.__module__ ==
"ROOT":
768 orig_register(self.exit)
771 register.__doc__ = (orig_register.__doc__ +
772 "\nNote: version hacked by GaudiPython to work " +
773 "around a problem with the ROOT exit handler")
774 atexit.register = register
776 def state(self) :
return self._isvc.FSMState()
777 def FSMState(self) :
return self._isvc.FSMState()
778 def targetFSMState(self) :
return self._isvc.targetFSMState()
779 def service(self, name, interface = None) :
780 svc = Helper.service( self._svcloc, name )
782 return InterfaceCast(interface)(svc)
784 return iService(name, svc )
785 def declSvcType(self, svcname, svctype ) :
786 self._svcmgr.declareSvcType(svcname, svctype)
787 def createSvc(self, name ) :
788 return Helper.service( self._svcloc, name,
True )
790 l = self._svcloc.getServices()
791 return [s.name()
for s
in l]
792 def algorithm(self, name , createIf = False ) :
793 alg = Helper.algorithm( self._algmgr, name , createIf )
794 if not alg :
return iAlgorithm ( name , alg )
795 else :
return iAlgorithm ( alg.name() , alg )
796 def algorithms(self) :
797 l = self._algmgr.getAlgorithms()
798 return [a.name()
for a
in l]
799 def tool(self, name ) :
801 def property( self , name ) :
802 if name
in self.algorithms() :
return self.algorithm( name )
803 elif name
in self.services() :
return self.service(name )
804 else :
return iProperty( name )
805 def datasvc(self, name) :
806 if self.state() == Gaudi.StateMachine.CONFIGURED : self.initialize()
807 svc = Helper.service( self._svcloc, name )
808 return iDataSvc(name, svc)
810 return self.datasvc(
'EventDataSvc')
812 return self.datasvc(
'DetectorDataSvc')
813 def filerecordsvc(self) :
814 return self.datasvc(
'FileRecordDataSvc')
816 if self.state() == Gaudi.StateMachine.CONFIGURED : self.initialize()
817 if not hasattr(self,
'_evtsel') : self.__dict__[
'_evtsel'] = iEventSelector()
819 def histsvc(self, name='HistogramDataSvc') :
820 svc = Helper.service( self._svcloc, name )
821 return iHistogramSvc(name, svc)
822 def ntuplesvc(self, name='NTupleSvc') :
823 if name
not in self.ExtSvc : self.ExtSvc += [name]
825 svc = Helper.service( self._svcloc, name,
True )
826 return iNTupleSvc(name, svc)
828 if self.FSMState() == Gaudi.StateMachine.CONFIGURED : self.initialize()
829 svc = Helper.service( self._svcloc,
'ParticlePropertySvc' )
830 return InterfaceCast(gbl.IParticlePropertySvc)(svc)
831 def toolsvc(self, name='ToolSvc') :
832 svc = Helper.service( self._svcloc, name,
True )
833 return iToolSvc(name, svc)
834 def optSvc (self, name='JobOptionsSvc') :
835 svc = Helper.service( self._svcloc, name,
True )
836 return iJobOptSvc(name, svc)
837 def readOptions(self, file) :
838 return self._optsvc.readOptions(file)
839 def addAlgorithm(self, alg) :
840 """ Add an Algorithm to the list of Top algorithms. It can be either a instance of
841 an Algorithm class or it name """
842 if type(alg)
is str :
845 self.pyalgorithms.append(alg)
847 if self.targetFSMState() >= Gaudi.StateMachine.INITIALIZED :
849 if self.targetFSMState() == Gaudi.StateMachine.RUNNING :
851 self.topAlg += [alg.name()]
852 def setAlgorithms(self, algs) :
853 """ Set the list of Top Algorithms.
854 It can be an individual of a list of algorithms names or instances """
855 if type(algs)
is not list : algs = [algs]
858 if type(alg)
is str : names.append(alg)
860 self.pyalgorithms.append(alg)
861 if self.targetFSMState() >= Gaudi.StateMachine.INITIALIZED :
863 if self.targetFSMState() == Gaudi.StateMachine.RUNNING :
865 names.append(alg.name())
867 def removeAlgorithm(self, alg) :
868 """ Remove an Algorithm to the list of Top algorithms. It can be either a instance of
869 an Algorithm class or it name """
871 if type(alg)
is str :
874 tmp.remove(alg.name())
875 self.pyalgorithms.remove(alg)
878 def printAlgsSequences(self):
880 Print the sequence of Algorithms.
882 def printAlgo( algName, appMgr, prefix = ' ') :
883 print prefix + algName
884 alg = appMgr.algorithm( algName.split(
"/" )[ -1 ] )
885 prop = alg.properties()
886 if prop.has_key(
"Members" ) :
887 subs = prop[
"Members" ].
value()
888 for i
in subs : printAlgo( i.strip(
'"' ), appMgr, prefix +
" " )
889 mp = self.properties()
890 prefix =
'ApplicationMgr SUCCESS '
891 print prefix +
"****************************** Algorithm Sequence ****************************"
892 for i
in mp[
"TopAlg"].
value(): printAlgo( i, self, prefix )
893 print prefix +
"******************************************************************************"
894 def config ( self, **args ):
896 Simple utility to perform the configuration of Gaudi application.
897 It reads the set of input job-options files, and set few
898 additional parameters 'options' through the usage of temporary *.opts file
900 gaudi.config( files = [ '$GAUSSOPTS/Gauss.opts' ,
901 '$DECFILESROOT/options/10022_010.0GeV.opts' ] ,
902 options = [ 'EventSelector.PrintFreq = 5 ' ] )
904 files = args.get(
'files',[])
906 sc = self.readOptions(file)
908 raise RuntimeError ,
' Unable to read file "' + file +
'" '
909 options = args.get(
'options',
None)
912 tmpfilename = tempfile.mktemp()
913 tmpfile = open( tmpfilename,
'w' )
914 tmpfile.write (
'#pragma print on \n' )
915 tmpfile.write (
'/// File "' + tmpfilename+
'" generated by GaudiPython \n\n' )
917 if type(options)
is dict :
918 tmpfile.write(
' \t ' + opt +
' = '+ options[opt]+
' ; // added by GaudiPython \n' )
920 tmpfile.write(
' \t ' + opt +
' ; // added by GaudiPython \n' )
921 tmpfile.write (
'/// End of file "' + tmpfilename+
'" generated by GaudiPython \n\n' )
923 sc = self.readOptions( tmpfilename )
925 raise RuntimeError ,
' Unable to read file "' + tmpfilename +
'" '
926 os.remove( tmpfilename )
928 if self.FSMState() != Gaudi.StateMachine.OFFLINE :
934 _dlls = jos.getProperty ( self.name() ,
'DLLs' )
937 libs = [ l
for l
in _dlls
if not l
in self.DLLs ]
938 if libs : self.DLLs += libs
941 _svcs = jos.getProperty ( self.name() ,
'ExtSvc' )
944 svcs = [ s
for s
in _svcs
if not s
in self.ExtSvc ]
945 if svcs : self.ExtSvc += svcs
948 props = jos.getProperties ( self.name() )
951 if 'DLLS' == key
or 'EXTSVC' == key :
continue
952 self.__setattr__( key , props[key] )
954 def configure(self) :
955 return self._appmgr.configure()
957 return self._appmgr.start()
959 return self._appmgr.terminate()
961 if self.FSMState() == Gaudi.StateMachine.CONFIGURED :
962 sc = self.initialize()
963 if sc.isFailure()
or self.ReturnCode != 0:
965 if self.FSMState() == Gaudi.StateMachine.INITIALIZED :
967 if sc.isFailure()
or self.ReturnCode != 0:
969 return self._evtpro.executeRun(n)
970 def executeEvent(self) :
971 return self._evtpro.executeEvent()
973 return self._evtpro.executeEvent()
974 def runSelectedEvents(self, pfn, events):
975 if self.FSMState() == Gaudi.StateMachine.CONFIGURED :
976 sc = self.initialize()
977 if sc.isFailure():
return sc
978 if self.FSMState() == Gaudi.StateMachine.INITIALIZED :
980 if sc.isFailure():
return sc
982 if not hasattr(self,
'_perssvc'): self.__dict__[
'_perssvc'] = self.service(
'EventPersistencySvc',
'IAddressCreator')
983 if not hasattr(self,
'_filecat'): self.__dict__[
'_filecat'] = self.service(
'FileCatalog',
'Gaudi::IFileCatalog')
984 if not hasattr(self,
'_evtmgr'): self.__dict__[
'_evtmgr'] = self.service(
'EventDataSvc',
'IDataManagerSvc')
986 if pfn.find(
'PFN:') == 0: pfn = pfn[4:]
989 if not self._filecat.existsFID(fid) : self._filecat.registerPFN(fid, pfn,
'')
991 if type(events)
is not list : events = (events,)
994 gadd = gbl.GenericAddress(0x02, 1, fid,
'/Event', 0, evt)
996 self._perssvc.createAddress(gadd.svcType(),gadd.clID(),gadd.par(),gadd.ipar(),oadd)
998 self._evtmgr.clearStore()
999 self._evtmgr.setRoot(
'/Event',oadd)
1000 self._evtpro.executeEvent()
1003 if not self._exit_called:
1004 self.__dict__[
'_exit_called'] =
True
1005 Gaudi = self._gaudi_ns
1006 if self.FSMState() == Gaudi.StateMachine.RUNNING:
1007 self._appmgr.stop().ignore()
1008 if self.FSMState() == Gaudi.StateMachine.INITIALIZED:
1009 self._appmgr.finalize().ignore()
1010 if self.FSMState() == Gaudi.StateMachine.CONFIGURED:
1011 self._appmgr.terminate()
1018 ntupleSvc = ntuplesvc
1026 tfile = gbl.TFile.Open(pfn)
1027 if not tfile :
raise 'Cannot open ROOT file ', pfn
1028 tree = tfile.Get(
'##Params')
1030 text = tree.db_string
1031 if 'NAME=FID' in text :
1032 fid = text[text.rfind(
'VALUE=')+6:-1]
1033 nevt = tfile.Get(
'_Event').GetEntries()
1039 """ Get all the properties of a component as a Python dictionary.
1040 The component is instantiated using the component library
1043 if name ==
'GaudiCoreSvc' :
1044 if Helper.loadDynamicLib(name) != 1 :
1045 raise ImportError,
'Error loading component library '+ name
1046 factorylist = gbl.FactoryTable.instance().getEntries()
1048 g = AppMgr(outputlevel=7)
1050 g = AppMgr(outputlevel=7)
1051 if Helper.loadDynamicLib(name) != 1 :
1052 raise ImportError,
'Error loading component library '+ name
1053 factorylist = gbl.FactoryTable.instance().getEntries()
1055 svcloc = gbl.Gaudi.svcLocator()
1056 dummysvc = gbl.Service(
'DummySvc',svcloc)
1057 for factory
in factories :
1058 if InterfaceCast(gbl.IAlgFactory)(factory) : ctype =
'Algorithm'
1059 elif InterfaceCast(gbl.ISvcFactory)(factory) : ctype =
'Service'
1060 elif InterfaceCast(gbl.IToolFactory)(factory) : ctype =
'AlgTool'
1061 elif factory.ident() ==
'ApplicationMgr' : ctype =
'ApplicationMgr'
1062 else : ctype =
'Unknown'
1063 cname = factory.ident().split()[-1]
1064 if ctype
in (
'Algorithm',
'Service',
'AlgTool',
'ApplicationMgr') :
1066 if ctype ==
'AlgTool' :
1067 obj = factory.instantiate(dummysvc)
1069 obj = factory.instantiate(svcloc)
1070 except RuntimeError, text :
1071 print 'Error instantiating', cname,
' from ', name
1074 prop = iProperty(
'dummy', obj)
1075 properties[cname] = [ctype, prop.properties()]
1082 for i
in range(factories.size()) :
1083 factory = factories.front()
1084 result.append(factory)
1085 factories.pop_front()
1086 for factory
in result :
1087 factories.push_back(factory)
1092 _CallbackStreamBufBase = gbl.GaudiPython.CallbackStreamBuf
1094 def __init__(self, callback):
1095 _CallbackStreamBufBase.__init__(self, self)
1096 self.callback = callback
1097 def _sync(self, string = None):
1098 if not string :
return 0
1099 self.callback(string)
1104 _PyAlgorithm = gbl.GaudiPython.PyAlgorithm
1106 def __init__(self, name=None) :
1107 if not name : name = self.__class__.__name__
1108 _PyAlgorithm.__init__(self, self, name)
1109 self._svcloc = gbl.Gaudi.svcLocator()
1110 self._algmgr = InterfaceCast(gbl.IAlgManager)(self._svcloc)
1111 sc = self._algmgr.addAlgorithm(self)
1112 if sc.isFailure() :
raise RuntimeError,
'Unable to add Algorithm'
1114 sc = self._algmgr.removeAlgorithm(self)
1115 if sc.isFailure() :
pass
1117 def start(self) :
return 1
1119 def stop(self) :
return 1
1120 def finalize(self) :
return 1
1121 def beginRun(self) :
return 1
1122 def endRun(self) :
return 1
1126 import rlcompleter, readline
1127 readline.parse_and_bind(
"tab: complete")
def bookProf(args, kwargs)
The trivial function to book 1D&2D profile histograms:
def getAsROOT(path, kwargs)
The most trivial function to retrieve the histogram from Histogram Transient Store.
def ROOT6WorkAroundEnabled
const char *PyHelper() getProperty(IInterface *p, char *name)
def _copyFactoriesFromList(factories)
def getComponentProperties(name)
NamedRange_< CONTAINER > range(const CONTAINER &cnt, std::string name)
simple function to create the named range form arbitrary container
def getAsAIDA(path, kwargs)
The most trivial function to retrieve the histogram from Histogram Transient Store.
def importOptions(optsfile)
iAlgorithm
The basic module.
double fun(const std::vector< double > &x)
GAUDI_API AIDA::IHistogram1D * book(IHistogramSvc *svc, const std::string &path, const Gaudi::Histo1DDef &hist)
helper function to book 1D-histogram
def getNeededConfigurables()
def _getFIDandEvents(pfn)