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
36 from GaudiKernel.Proxy.Configurable
import Configurable, getNeededConfigurables
45 gbl.gInterpreter.Declare(
'#include "GaudiKernel/Property.h"')
46 Helper = gbl.GaudiPython.Helper
47 StringProperty = gbl.Gaudi.Property(
'std::string')
48 StringPropertyRef = gbl.Gaudi.Property(
'std::string&')
49 GaudiHandleProperty = gbl.GaudiHandleProperty
50 GaudiHandleArrayProperty = gbl.GaudiHandleArrayProperty
51 DataObject = gbl.DataObject
52 SUCCESS = gbl.StatusCode( gbl.StatusCode.SUCCESS,
True )
53 FAILURE = gbl.StatusCode( gbl.StatusCode.FAILURE,
True )
55 cppyy.gbl.gInterpreter.Declare(
''' 56 namespace GaudiPython { namespace Helpers { 57 Gaudi::Property<std::string> mkStringProperty(const std::string &name, 58 const std::string &value) { 59 return Gaudi::Property<std::string>{name, value}; 64 for l
in [ l
for l
in dir(Helper)
if re.match(
"^to.*Array$",l) ]:
65 exec
"%s = Helper.%s"%(l,l)
69 if hasattr(Helper,
"toArray"):
72 toArray =
lambda typ: getattr(Helper,
"toArray")
75 toArray =
lambda typ: getattr(Helper,
"toArray<%s>"%typ)
78 ROOT = cppyy.libPyROOT
79 makeNullPointer = cppyy.libPyROOT.MakeNullPointer
80 setOwnership = cppyy.libPyROOT.SetOwnership
83 warnings.warn(
'GaudiPython: '+ message, DeprecationWarning, stacklevel=3)
87 """ Helper class to obtain the adequate interface from a component 88 by using the Gaudi queryInterface() mechanism """ 97 if obj.queryInterface(self.type.interfaceID(), ip).isSuccess() :
100 print "ERROR: queryInterface failed for", obj,
"interface:", self.
type 102 print "ERROR: exception", e,
"caught when retrieving interface", self.
type,
"for object", obj
104 traceback.print_stack()
111 InterfaceCast.__init__(self,t)
117 """ Load a LCG dictionary using various mechanisms""" 118 if Helper.loadDynamicLib(dict) == 1 :
return 123 raise ImportError,
'Error loading dictionary library' 128 Function to retrieve a certain C++ class by name and to load dictionary if requested 132 from gaudimodule import getClass 133 # one knows that class is already loaded 134 AppMgr = getClass( 'ApplicationMgr' ) 135 # one knows where to look for class, if not loaded yet 136 MCParticle = getClass( 'MCParticle' , 'EventDict' ) 137 # one knows where to look for class, if not loaded yet 138 Vertex = getClass( 'Vertex' , ['EventDict', 'PhysEventDict'] ) 141 if hasattr( gbl , name ) :
return getattr( gbl , name )
143 if type(libs)
is not list : libs = [libs]
146 if hasattr( gbl , name ) :
return getattr( gbl , name )
152 """ holds the value and the documentation string of a property """ 157 if issubclass(
type(prop),GaudiHandleProperty) :
159 elif issubclass(
type(prop),GaudiHandleArrayProperty) :
160 self.
_value = prop.value()
163 try: self.
_value = eval( prop.toString() , {} , {} )
165 if hasattr ( prop ,
'value' ) : self.
_value = prop.value()
166 else : self.
_value = prop.toString()
168 self.
__doc__ +=
" --- Default value = " + str(self.
_value) +
" --- " 169 if prop.documentation() !=
'none':
178 "Return the underlying property itself " 187 """ Python equivalent to the C++ Property interface """ 189 if ip : self.__dict__[
'_ip'] =
InterfaceCast(gbl.IProperty)(ip)
190 else : self.__dict__[
'_ip'] =
None 191 self.__dict__[
'_svcloc'] = gbl.Gaudi.svcLocator()
192 optsvc = Helper.service(self._svcloc,
'JobOptionsSvc')
193 if optsvc : self.__dict__[
'_optsvc'] =
InterfaceCast(gbl.IJobOptionsSvc)(optsvc)
194 else : self.__dict__[
'_optsvc'] =
None 195 self.__dict__[
'_name'] = name
202 if not getattr(self,ifname) : self.retrieveInterface()
203 return getattr(getattr(self,ifname),method)(*args)
206 The method which is used for setting the property from the given value. 207 - In the case of the valid instance it sets the property through IProperty interface 208 - In the case of placeholder the property is added to JobOptionsCatalogue 210 if hasattr( value,
'toStringProperty' ):
212 value =
'%s' % value.toStringProperty()
215 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
216 raise AttributeError,
'property %s does not exist' % name
217 prop = ip.getProperty(name)
220 canSetValue = (hasattr(prop,
'value')
and 221 'const&[' not in prop.value.func_doc
and 224 canSetValue = (hasattr(prop,
'value')
and 228 if not prop.setValue(value) :
229 raise AttributeError,
'property %s could not be set from %s' % (name, value)
231 if tuple ==
type( value ) : value = str(value)
232 elif hasattr ( value ,
'toString' ) : value = value.toString()
233 elif not long ==
type( value ) : value =
'%s' % value
234 else : value =
'%d' % value
236 sc = cppyy.gbl.GaudiPython.Helper.setPropertyFromString(prop, value)
238 sc = prop.fromString(value)
240 raise AttributeError,
'property %s could not be set from %s' % (name,value)
242 if type(value) == str : value =
'"%s"' % value
243 elif type(value) == tuple : value = str(value)
244 elif hasattr( value ,
'toString' ) : value = value.toString()
245 elif type(value) == long: value =
'%d' % value
246 sp = gbl.GaudiPython.Helpers.mkStringProperty(name, str(value))
247 self._optsvc.addPropertyToCatalogue( self._name , sp ).ignore()
250 The method which returns the value for the given property 251 - In the case of the valid instance it returns the valid property value through IProperty interface 252 - In the case of placeholder the property value is retrieved from JobOptionsCatalogue 256 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
257 raise AttributeError,
'property %s does not exist' % name
258 prop = ip.getProperty(name)
259 if StringProperty ==
type( prop ) :
return prop.value()
260 elif StringPropertyRef ==
type( prop ) :
return prop.value()
261 try:
return eval( prop.toString(), {}, {} )
262 except :
return prop.value()
264 props = self._optsvc.getProperties(self._name)
266 if not p.name() == name :
continue 268 try:
return eval( p.value(), {}, {} )
269 except:
return p.value()
270 raise AttributeError,
'property %s does not exist' % name
276 props = ip.getProperties()
277 propsFrom = self._name
279 props = self._optsvc.getProperties( self._name )
280 propsFrom =
"jobOptionsSvc" 285 except (ValueError,TypeError),e:
286 raise ValueError,
"gaudimodule.iProperty.properties(): %s%s processing property %s.%s = %s" % \
287 (e.__class__.__name__, e.args, propsFrom, p.name(), p.value())
294 """ Python equivalent to IProperty interface """ 296 iProperty.__init__(self, name, isvc )
297 if isvc : self.__dict__[
'_isvc'] =
InterfaceCast(gbl.IService)(isvc)
298 else : self.__dict__[
'_isvc'] =
None 300 isvc = Helper.service(self._svcloc,self._name)
301 if isvc : iService.__init__(self, self._name, isvc)
309 if self._isvc:
return True 314 """ Python equivalent to IAlgorithm interface """ 316 iProperty.__init__(self, name, ialg )
317 if ialg : self.__dict__[
'_ialg'] =
InterfaceCast(gbl.IAlgorithm)(ialg)
318 else : self.__dict__[
'_ialg'] =
None 320 ialg = Helper.algorithm(
InterfaceCast(gbl.IAlgManager)(self._svcloc),self._name)
321 if ialg : iAlgorithm.__init__(self, self._name, ialg)
339 """ Python equivalent to IAlgTool interface (not completed yet) """ 341 iProperty.__init__(self, name, itool )
342 if itool : self.__dict__[
'_itool'] = itool
343 else : self.__dict__[
'_itool'] =
None 344 svc = Helper.service( self._svcloc,
'ToolSvc',
True )
345 self.__dict__[
'_toolsvc']=
iToolSvc(
'ToolSvc', svc)
347 itool = self._toolsvc._retrieve(self._name)
348 if itool : iAlgTool.__init__(self, self._name, itool)
353 if self._itool :
return self._itool.name()
354 else :
return self._name
359 iService.__init__(self, name, idp )
360 self.__dict__[
'_idp'] =
InterfaceCast(gbl.IDataProviderSvc)(idp)
361 self.__dict__[
'_idm'] =
InterfaceCast(gbl.IDataManagerSvc)(idp)
363 if not self._idp :
raise AttributeError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
364 return self._idp.registerObject(path,obj)
366 if not self._idp :
raise AttributeError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
367 return self._idp.unregisterObject(path)
369 if not self._idp :
return None 370 return Helper.dataobject(self._idp, path)
375 Get the existing object in TransientStore for the given location 377 - loading of object from persistency is NOT triggered 378 - 'data-on-demand' action is NOT triggered 380 >>> svc = ... ## get the service 381 >>> path = ... ## get the path in Transient Store 382 >>> data = svc.findObject ( path ) ## use the method 385 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
386 return Helper.findobject(self._idp, path)
391 Get object from Transient Store for the given location 394 - path : Location of object in Transient Store 395 - retrieve (bool) True : retrieve versus find 396 - disable on-demand (bool) False : temporary disable 'on-demand' actions 398 >>> svc = ... ## get the service 399 >>> path = ... ## get the path 401 >>> data = svc.getObject ( path , False ) ## find object in Transient Store 403 ## find object in Transient Store 404 # load form tape or use 'on-demand' action for missing objects : 405 >>> data = svc.getObject ( path , True ) 407 ## find object in Transient Store 408 # load from tape or for missing objects, disable 'on-demand'-actions 409 >>> data = svc.getObject ( path , True , True ) 412 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
413 return Helper.getobject(self._idp, path, *args )
416 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
417 return Helper.dataobject(self._idp, path)
419 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
420 return self._idp.registerObject(path,obj)
422 if not self._idp :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
423 return self._idp.unregisterObject(path)
426 ll = gbl.std.vector(
'IRegistry*')()
429 if self._idm.objectLeaves(node, ll).isSuccess() :
return ll
433 if root : node = root.registry()
435 print node.identifier()
438 def getList(self, node=None, lst=[], rootFID=None) :
442 node = root.registry()
443 rootFID = node.address().
par()
447 Helper.dataobject( self._idp, node.identifier() )
449 lst.append( node.identifier() )
450 for l
in self.
leaves(node) :
451 if l.address()
and l.address().
par() == rootFID :
460 node = root.registry()
464 Helper.dataobject( self._idp, node.identifier() )
466 lst.append( node.identifier() )
467 for l
in self.
leaves(node) :
474 if not self._idm :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
475 return self._idm.setRoot(name,obj)
477 if not self._idm :
raise IndexError(
'C++ service %s does not exist' % self.__dict__[
'_name'])
478 return self._idm.clearStore()
484 self.__dict__[
'_ihs'] =
InterfaceCast(gbl.IHistogramSvc)(ihs)
485 iDataSvc.__init__(self, name, ihs)
487 return Helper.histo1D(self._ihs, path)
489 return Helper.histo2D(self._ihs, path)
491 return Helper.histo3D(self._ihs, path)
493 return Helper.profile1D(self._ihs, path)
495 return Helper.profile2D(self._ihs, path)
498 Retrieve AIDA histogram or AIDA profile histogram by path in Histogram Transient Store 500 >>> histo = svc.retrieve ( 'path/to/my/histogram' ) 510 Book the histograms(1D,2D&3D) , see IHistogramSvc::book 512 >>> histo = svc.book( .... ) 514 return apply(self._ihs.book,args)
517 Book the profile(1D&2D) histograms, see IHistogramSvc::bookProf 519 >>> histo = svc.bookProf( .... ) 521 return apply(self._ihs.bookProf,args)
524 Retrieve the object from Histogram Transient Store (by path) 525 The reference to AIDA histogram is returned (if possible) 527 >>> histo = svc['path/to/my/histogram'] 531 return iDataSvc.__getitem__( self , path )
534 Retrieve the histogram from Histogram Transient Store (by path) 535 The reference to AIDA histogram is returned (if possible) 537 >>> histo = svc.getAsAIDA ( 'path/to/my/histogram' ) 542 Retrieve the histogram from Histogram Transient Store (by path) 543 The Underlying native ROOT object is returned (if possible) 545 >>> histo = svc.getAsROOT ( 'path/to/my/histogram' ) 547 fun = gbl.Gaudi.Utils.Aida2ROOT.aida2root
556 iDataSvc.__init__(self, name, ints)
558 return apply(self._ints.book, args)
560 """ Defines the mapping between logical names and the output file 562 defineOutput({'LUN1':'MyFile1.root', 'LUN2':'Myfile2.root'}, svc='Gaudi::RootCnvSvc') 564 import Persistency
as prs
565 helper = prs.get(typ)
566 helper.configure(
AppMgr())
567 self.
Output = [helper.formatOutput(files[lun], lun=lun)
for lun
in files]
568 if AppMgr().HistogramPersistency ==
'NONE':
569 AppMgr().HistogramPersistency =
"ROOT" 571 return iDataSvc.__getitem__( self , path )
578 iService.__init__(self, name, its)
580 sol = _gaudi.OutputLevel
582 if name.rfind(
'.') == -1 :
583 itool = Helper.tool(self._its,
'', name,
None,
False )
584 elif name[0:8] ==
'ToolSvc.' :
585 itool = Helper.tool(self._its,
'', name[8:],
None,
False )
586 elif name.count(
'.') > 1 :
587 ptool = self.
_retrieve(name[:name.rfind(
'.')])
588 itool = Helper.tool(self._its,
'', name[name.rfind(
'.')+1:], ptool,
False )
590 prop = _gaudi.property(name[:name.rfind(
'.')])
591 itool = Helper.tool(self._its,
'', name[name.rfind(
'.')+1:], prop._ip,
False )
596 def create(self, typ, name=None, parent=None, interface=None) :
597 if not name : name = typ
598 itool = Helper.tool(self._its, typ, name, parent,
True )
604 if type(itool)
is iAlgTool :
605 self._its.releaseTool(itool._itool)
610 Python-image of C++ class IJobOptionsSvc 615 self.__dict__[
'_optsvc'] =
InterfaceCast(gbl.IJobOptionsSvc)(svc)
616 return iService.__init__( self , name , svc )
619 Extract *ALL* properties of the given component 621 >>> jos = gaudi.optSvc() 622 >>> props = jos.getProperties( 'Name' ) 624 props = self._optsvc.getProperties( component )
626 if not props :
return prps
628 prop = p.name().upper()
630 value = eval( p.value() , {} , {} )
631 except: value = p.value()
632 prps [ prop ] = value
637 Get a certain property of the certain component 640 >>> extServices = jos.getProperty( 'ApplicationMgr', 'ExtSvc' ) 644 return all.get( name.upper() ,
None )
649 iService.__init__(self,
'EventSelector', Helper.service(gbl.Gaudi.svcLocator(),
'EventSelector'))
650 self.__dict__[
'g'] =
AppMgr()
651 def open(self, stream, typ = 'Gaudi::RootCnvSvc
', **kwargs): 652 import Persistency
as prs
653 helper = prs.get(typ)
654 helper.configure(self.g)
655 self.
Input = helper.formatInput(stream, **kwargs)
666 newobj = object.__new__( cls )
667 cls.
__init__(newobj, *args, **kwargs)
675 self._evtpro.release()
676 self._svcloc.release()
677 self._appmgr.release()
683 def __init__(self, outputlevel = -1, joboptions = None, selfoptions = {},
684 dllname =
None, factname =
None) :
688 self.__dict__[
'_exit_called'] =
False 690 self.__dict__[
'_gaudi_ns'] = Gaudi
692 from GaudiKernel.Proxy.Configurable
import expandvars
695 expandvars =
lambda data : data
696 if dllname
and factname:
697 self.__dict__[
'_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname,factname)
699 self.__dict__[
'_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname)
701 self.__dict__[
'_appmgr'] = gbl.Gaudi.createApplicationMgr()
702 self.__dict__[
'_svcloc'] = gbl.Gaudi.svcLocator()
703 self.__dict__[
'_algmgr'] =
InterfaceCast(gbl.IAlgManager)(self._appmgr)
704 self.__dict__[
'_evtpro'] =
InterfaceCast(gbl.IEventProcessor)(self._appmgr)
705 self.__dict__[
'_svcmgr'] =
InterfaceCast(gbl.ISvcManager)(self._appmgr)
706 self.__dict__[
'pyalgorithms'] = []
707 iService.__init__(self,
'ApplicationMgr', self._appmgr )
709 if self.
FSMState() < Gaudi.StateMachine.CONFIGURED :
715 import GaudiKernel.Proxy.Configurable
716 if hasattr(GaudiKernel.Proxy.Configurable,
"applyConfigurableUsers"):
717 GaudiKernel.Proxy.Configurable.applyConfigurableUsers()
720 selfprops = Configurable.allConfigurables.get(
'ApplicationMgr',{})
721 if selfprops : selfprops =
expandvars(selfprops.getValuedProperties())
722 for p,v
in selfprops.items() : setattr(self, p, v)
723 for p,v
in selfoptions.items() : setattr(self, p, v)
725 if outputlevel != -1 : self.
OutputLevel = outputlevel
728 ms = self.
service(
'MessageSvc')
729 if 'MessageSvc' in Configurable.allConfigurables:
730 msprops = Configurable.allConfigurables[
'MessageSvc']
731 ms = self.
service(
'MessageSvc')
732 if hasattr(msprops,
"getValuedProperties"):
733 msprops =
expandvars(msprops.getValuedProperties())
734 for p,v
in msprops.items():
736 if outputlevel != -1 : ms.OutputLevel = outputlevel
738 self.__dict__[
'_optsvc'] =
InterfaceCast(gbl.IJobOptionsSvc)(Helper.service(self._svcloc,
'JobOptionsSvc'))
740 mkStringProperty = gbl.GaudiPython.Helpers.mkStringProperty
742 c = Configurable.allConfigurables[n]
743 if n
in [
'ApplicationMgr',
'MessageSvc'] :
continue 744 for p, v
in c.getValuedProperties().items() :
747 if hasattr(Configurable,
"PropertyReference")
and type(v) == Configurable.PropertyReference:
751 if type(v) == str : v =
'"%s"' % v
752 elif type(v) == long: v =
'%d' % v
753 self._optsvc.addPropertyToCatalogue(n, mkStringProperty(p,str(v)))
754 if hasattr(Configurable,
"_configurationLocked"):
755 Configurable._configurationLocked =
True 759 atexit.register(self.
exit)
763 root_handler_installed =
False 764 for h
in atexit._exithandlers:
766 if hasattr(func,
"__module__")
and func.__module__ ==
"ROOT":
767 root_handler_installed =
True 773 if not root_handler_installed:
774 orig_register = atexit.register
775 def register(func, *targs, **kargs):
776 orig_register(func, *targs, **kargs)
777 if hasattr(func,
"__module__")
and func.__module__ ==
"ROOT":
778 orig_register(self.
exit)
781 register.__doc__ = (orig_register.__doc__ +
782 "\nNote: version hacked by GaudiPython to work " +
783 "around a problem with the ROOT exit handler")
784 atexit.register = register
786 def state(self) :
return self._isvc.FSMState()
790 svc = Helper.service( self._svcloc, name )
796 self._svcmgr.declareSvcType(svcname, svctype)
798 return Helper.service( self._svcloc, name,
True )
800 l = self._svcloc.getServices()
801 return [s.name()
for s
in l]
803 alg = Helper.algorithm( self._algmgr, name , createIf )
804 if not alg :
return iAlgorithm ( name , alg )
805 else :
return iAlgorithm ( alg.name() , alg )
807 l = self._algmgr.getAlgorithms()
808 return [a.name()
for a
in l]
817 svc = Helper.service( self._svcloc, name )
820 return self.
datasvc(
'EventDataSvc')
822 return self.
datasvc(
'DetectorDataSvc')
824 return self.
datasvc(
'FileRecordDataSvc')
827 if not hasattr(self,
'_evtsel') : self.__dict__[
'_evtsel'] =
iEventSelector()
830 svc = Helper.service( self._svcloc, name )
833 if name
not in self.ExtSvc : self.ExtSvc += [name]
835 svc = Helper.service( self._svcloc, name,
True )
839 svc = Helper.service( self._svcloc,
'ParticlePropertySvc' )
842 svc = Helper.service( self._svcloc, name,
True )
844 def optSvc (self, name='JobOptionsSvc') :
845 svc = Helper.service( self._svcloc, name,
True )
848 return self._optsvc.readOptions(file)
850 """ Add an Algorithm to the list of Top algorithms. It can be either a instance of 851 an Algorithm class or it name """ 852 if type(alg)
is str :
855 self.pyalgorithms.append(alg)
861 self.
topAlg += [alg.name()]
863 """ Set the list of Top Algorithms. 864 It can be an individual of a list of algorithms names or instances """ 865 if type(algs)
is not list : algs = [algs]
868 if type(alg)
is str : names.append(alg)
870 self.pyalgorithms.append(alg)
875 names.append(alg.name())
878 """ Remove an Algorithm to the list of Top algorithms. It can be either a instance of 879 an Algorithm class or it name """ 881 if type(alg)
is str :
884 tmp.remove(alg.name())
885 self.pyalgorithms.remove(alg)
890 Print the sequence of Algorithms. 892 def printAlgo( algName, appMgr, prefix = ' ') :
893 print prefix + algName
894 alg = appMgr.algorithm( algName.split(
"/" )[ -1 ] )
895 prop = alg.properties()
896 if prop.has_key(
"Members" ) :
897 subs = prop[
"Members" ].value()
898 for i
in subs : printAlgo( i.strip(
'"' ), appMgr, prefix +
" " )
900 prefix =
'ApplicationMgr SUCCESS ' 901 print prefix +
"****************************** Algorithm Sequence ****************************" 902 for i
in mp[
"TopAlg"].value(): printAlgo( i, self, prefix )
903 print prefix +
"******************************************************************************" 906 Simple utility to perform the configuration of Gaudi application. 907 It reads the set of input job-options files, and set few 908 additional parameters 'options' through the usage of temporary *.opts file 910 gaudi.config( files = [ '$GAUSSOPTS/Gauss.opts' , 911 '$DECFILESROOT/options/10022_010.0GeV.opts' ] , 912 options = [ 'EventSelector.PrintFreq = 5 ' ] ) 914 files = args.get(
'files',[])
918 raise RuntimeError ,
' Unable to read file "' + file +
'" ' 919 options = args.get(
'options',
None)
922 tmpfilename = tempfile.mktemp()
923 tmpfile = open( tmpfilename,
'w' )
924 tmpfile.write (
'#pragma print on \n' )
925 tmpfile.write (
'/// File "' + tmpfilename+
'" generated by GaudiPython \n\n' )
927 if type(options)
is dict :
928 tmpfile.write(
' \t ' + opt +
' = '+ options[opt]+
' ; // added by GaudiPython \n' )
930 tmpfile.write(
' \t ' + opt +
' ; // added by GaudiPython \n' )
931 tmpfile.write (
'/// End of file "' + tmpfilename+
'" generated by GaudiPython \n\n' )
935 raise RuntimeError ,
' Unable to read file "' + tmpfilename +
'" ' 936 os.remove( tmpfilename )
938 if self.
FSMState() != Gaudi.StateMachine.OFFLINE :
944 _dlls = jos.getProperty ( self.
name() ,
'DLLs' )
947 libs = [ l
for l
in _dlls
if not l
in self.DLLs ]
948 if libs : self.DLLs += libs
951 _svcs = jos.getProperty ( self.
name() ,
'ExtSvc' )
954 svcs = [ s
for s
in _svcs
if not s
in self.ExtSvc ]
955 if svcs : self.ExtSvc += svcs
958 props = jos.getProperties ( self.
name() )
961 if 'DLLS' == key
or 'EXTSVC' == key :
continue 965 return self._appmgr.configure()
967 return self._appmgr.start()
969 return self._appmgr.terminate()
971 if self.
FSMState() == Gaudi.StateMachine.CONFIGURED :
973 if sc.isFailure()
or self.ReturnCode != 0:
975 if self.
FSMState() == Gaudi.StateMachine.INITIALIZED :
977 if sc.isFailure()
or self.ReturnCode != 0:
979 return self._evtpro.executeRun(n)
981 return self._evtpro.executeEvent()
983 return self._evtpro.executeEvent()
985 if self.
FSMState() == Gaudi.StateMachine.CONFIGURED :
987 if sc.isFailure():
return sc
988 if self.
FSMState() == Gaudi.StateMachine.INITIALIZED :
990 if sc.isFailure():
return sc
992 if not hasattr(self,
'_perssvc'): self.__dict__[
'_perssvc'] = self.
service(
'EventPersistencySvc',
'IAddressCreator')
993 if not hasattr(self,
'_filecat'): self.__dict__[
'_filecat'] = self.
service(
'FileCatalog',
'Gaudi::IFileCatalog')
994 if not hasattr(self,
'_evtmgr'): self.__dict__[
'_evtmgr'] = self.
service(
'EventDataSvc',
'IDataManagerSvc')
996 if pfn.find(
'PFN:') == 0: pfn = pfn[4:]
999 if not self._filecat.existsFID(fid) : self._filecat.registerPFN(fid, pfn,
'')
1001 if type(events)
is not list : events = (events,)
1004 gadd = gbl.GenericAddress(0x02, 1, fid,
'/Event', 0, evt)
1006 self._perssvc.createAddress(gadd.svcType(),gadd.clID(),gadd.par(),gadd.ipar(),oadd)
1008 self._evtmgr.clearStore()
1009 self._evtmgr.setRoot(
'/Event',oadd)
1010 self._evtpro.executeEvent()
1013 if not self._exit_called:
1014 self.__dict__[
'_exit_called'] =
True 1015 Gaudi = self._gaudi_ns
1016 if self.
FSMState() == Gaudi.StateMachine.RUNNING:
1017 self._appmgr.stop().ignore()
1018 if self.
FSMState() == Gaudi.StateMachine.INITIALIZED:
1019 self._appmgr.finalize().ignore()
1020 if self.
FSMState() == Gaudi.StateMachine.CONFIGURED:
1021 self._appmgr.terminate()
1028 ntupleSvc = ntuplesvc
1036 tfile = gbl.TFile.Open(pfn)
1037 if not tfile :
raise 'Cannot open ROOT file ', pfn
1038 tree = tfile.Get(
'##Params')
1040 text = tree.db_string
1041 if 'NAME=FID' in text :
1042 fid = text[text.rfind(
'VALUE=')+6:-1]
1043 nevt = tfile.Get(
'_Event').GetEntries()
1049 """ Get all the properties of a component as a Python dictionary. 1050 The component is instantiated using the component library 1053 if name ==
'GaudiCoreSvc' :
1054 if Helper.loadDynamicLib(name) != 1 :
1055 raise ImportError,
'Error loading component library '+ name
1056 factorylist = gbl.FactoryTable.instance().getEntries()
1058 g =
AppMgr(outputlevel=7)
1060 g =
AppMgr(outputlevel=7)
1061 if Helper.loadDynamicLib(name) != 1 :
1062 raise ImportError,
'Error loading component library '+ name
1063 factorylist = gbl.FactoryTable.instance().getEntries()
1065 svcloc = gbl.Gaudi.svcLocator()
1066 dummysvc = gbl.Service(
'DummySvc',svcloc)
1067 for factory
in factories :
1068 if InterfaceCast(gbl.IAlgFactory)(factory) : ctype =
'Algorithm' 1069 elif InterfaceCast(gbl.ISvcFactory)(factory) : ctype =
'Service' 1070 elif InterfaceCast(gbl.IToolFactory)(factory) : ctype =
'AlgTool' 1071 elif factory.ident() ==
'ApplicationMgr' : ctype =
'ApplicationMgr' 1072 else : ctype =
'Unknown' 1073 cname = factory.ident().split()[-1]
1074 if ctype
in (
'Algorithm',
'Service',
'AlgTool',
'ApplicationMgr') :
1076 if ctype ==
'AlgTool' :
1077 obj = factory.instantiate(dummysvc)
1079 obj = factory.instantiate(svcloc)
1080 except RuntimeError, text :
1081 print 'Error instantiating', cname,
' from ', name
1085 properties[cname] = [ctype, prop.properties()]
1092 for i
in range(factories.size()) :
1093 factory = factories.front()
1094 result.append(factory)
1095 factories.pop_front()
1096 for factory
in result :
1097 factories.push_back(factory)
1102 _CallbackStreamBufBase = gbl.GaudiPython.CallbackStreamBuf
1105 _CallbackStreamBufBase.__init__(self, self)
1108 if not string :
return 0
1114 _PyAlgorithm = gbl.GaudiPython.PyAlgorithm
1117 if not name : name = self.__class__.__name__
1118 _PyAlgorithm.__init__(self, self, name)
1121 sc = self._algmgr.addAlgorithm(self)
1122 if sc.isFailure() :
raise RuntimeError,
'Unable to add Algorithm' 1124 sc = self._algmgr.removeAlgorithm(self)
1125 if sc.isFailure() :
pass 1136 import rlcompleter, readline
1137 readline.parse_and_bind(
"tab: complete")
def declSvcType(self, svcname, svctype)
def getHistoNames(self, node=None, lst=[])
def setAlgorithms(self, algs)
def printAlgsSequences(self)
def createSvc(self, name)
def histsvc(self, name='HistogramDataSvc')
def __init__(self, name, ints)
def __init__(self, name, isvc=None)
def retrieveInterface(self)
def runSelectedEvents(self, pfn, events)
def __getitem__(self, path)
def findObject(self, path)
get object from TES
decltype(auto) range(Args &&...args)
Zips multiple containers together to form a single range.
def unregisterObject(self, path)
def getClass(name, libs=[])
def retrieveProfile1D(self, path)
def getAsAIDA(self, path)
def getProperties(self, component)
def _getFIDandEvents(pfn)
def __init__(self, name, ialg=None)
def open(self, stream, typ='Gaudi::RootCnvSvc', kwargs)
def toolsvc(self, name='ToolSvc')
def __getitem__(self, path)
def __init__(self, name, ip=None)
def ROOT6WorkAroundEnabled(id=None)
def service(self, name, interface=None)
def getObject(self, path, args)
get or retrieve object, possible switch-off 'on-demand' actions
def __init__(self, callback)
def retrieveInterface(self)
def algorithm(self, name, createIf=False)
def retrieve1D(self, path)
def retrieve3D(self, path)
def __init__(self, name, svc)
constructor
def __new__(cls, args, kwargs)
def _sync(self, string=None)
def removeAlgorithm(self, alg)
def __init__(self, name, idp)
def importOptions(optsfile)
def __delitem__(self, path)
def defineOutput(self, files, typ="Gaudi::RootCnvSvc")
def addAlgorithm(self, alg)
def retrieveProfile2D(self, path)
def retrieve2D(self, path)
def __del__(self)
Custom destructor to ensure that the application is correctly finalized when exiting from python...
def getProperty(self, component, name)
def __setitem__(self, path, obj)
def retrieveInterface(self)
def __init__(self, outputlevel=-1, joboptions=None, selfoptions={}, dllname=None, factname=None)
def __init__(self, name, ihs)
def ntuplesvc(self, name='NTupleSvc')
def getAsROOT(self, path)
def dump(self, node=None)
_property
keep the original property
double fun(const std::vector< double > &x)
def __call_interface_method__(self, ifname, method, args)
def retrieveObject(self, path)
def __getitem__(self, path)
def _copyFactoriesFromList(factories)
def setRoot(self, name, obj)
def __init__(self, name=None)
constexpr void apply(const Fun &, Container &, Args...)
def registerObject(self, path, obj)
def optSvc(self, name='JobOptionsSvc')
def getComponentProperties(name)
def leaves(self, node=None)
def __getattr__(self, name)
def getList(self, node=None, lst=[], rootFID=None)
def readOptions(self, file)
def __setattr__(self, name, value)