| # Gaudi Framework, version v25r0 |

Home |  | Generated: Mon Feb 17 2014

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Bindings.py
Go to the documentation of this file.
1 # File: GaudiPython/Bindings.py
2 # Author: Pere Mato (pere.mato@cern.ch)
3
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.
8 """
9
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', 'makeClass', 'setOwnership',
15 'getClass', 'loaddict', 'deprecation' ]
16
17 from GaudiKernel import ROOT6WorkAroundEnabled
18
19 import os, sys, string, warnings, re
20 try:
21 import cppyy
22 except ImportError:
23 # FIXME: backward compatibility
24 print "# WARNING: using PyCintex as cppyy implementation"
25 import PyCintex as cppyy
26
27 if ROOT6WorkAroundEnabled('ROOT-5478'):
28 # Trigger the loading of GaudiKernelDict
29 cppyy.gbl.DataObject
30 # Trigger the loading of GaudiPythonDict
31 cppyy.gbl.Chrono
32
33 import Pythonizations
34 # Import Configurable from AthenaCommon or GaudiKernel if the first is not
35 # available.
36 from GaudiKernel.Proxy.Configurable import Configurable, getNeededConfigurables
37
38 #namespaces
39 gbl = cppyy.gbl
40 Gaudi = gbl.Gaudi
41
42 _gaudi = None
43
44 #----Useful shortcuts for classes -------------------------------------------------------
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 )
53
54 # toIntArray, toShortArray, etc.
55 for l in [ l for l in dir(Helper) if re.match("^to.*Array$",l) ]:
56 exec "%s = Helper.%s"%(l,l)
57 __all__.append(l)
58
59 # FIXME: (MCl) Hack to handle ROOT 5.18 and ROOT >= 5.20
60 if hasattr(Helper,"toArray"):
61 # This is not backward compatible, but allows to use the same signature
62 # with all the versions of ROOT.
63 toArray = lambda typ: getattr(Helper,"toArray")
64 else:
65 # forward to the actual implementation of GaudiPython::Helper::toArray<T>
66 toArray = lambda typ: getattr(Helper,"toArray<%s>"%typ)
67
68 #----Convenient accessors to PyROOT functionality ---------------------------------------
69 ROOT = cppyy.libPyROOT
70 makeNullPointer = cppyy.libPyROOT.MakeNullPointer
71 makeClass = cppyy.libPyROOT.MakeRootClass
72 setOwnership = cppyy.libPyROOT.SetOwnership
73
74 def deprecation(message):
75 warnings.warn('GaudiPython: '+ message, DeprecationWarning, stacklevel=3)
76
77 #----InterfaceCast class ----------------------------------------------------------------
78 class InterfaceCast(object) :
79 """ Helper class to obtain the adequate interface from a component
80 by using the Gaudi queryInterface() mechanism """
81 def __init__(self, t ) :
82 if type(t) is str:
83 t = getattr(gbl, t)
84 self.type = t
85 def __call__(self, obj) :
86 if obj :
87 ip = makeNullPointer(self.type)
88 try:
89 if obj.queryInterface(self.type.interfaceID(), ip).isSuccess() :
90 return ip
91 else :
92 print "ERROR: queryInterface failed for", obj, "interface:", self.type
93 except Exception, e:
94 print "ERROR: exception", e, "caught when retrieving interface", self.type, "for object", obj
95 import traceback
96 traceback.print_stack()
97 return None
98 cast = __call__
99 #---Interface class (for backward compatibility)-----------------------------------------
100 class Interface(InterfaceCast) :
101 def __init__(self, t ):
102 deprecation('Use InterfaceCast class instead')
103 InterfaceCast.__init__(self,t)
104 def cast(self, obj) :
105 return self(obj)
106
107 #----load dictionary function using Gaudi function---------------------------------------
108 def loaddict(dict) :
109 """ Load a LCG dictionary using various mechanisms"""
110 if Helper.loadDynamicLib(dict) == 1 : return
111 else :
112 try:
113 cppyy.loadDict(dict)
114 except:
115 raise ImportError, 'Error loading dictionary library'
116
117 #---get a class (by loading modules if needed)--------------------------------------------
118 def getClass( name , libs = [] ) :
119 """
120 Function to retrieve a certain C++ class by name and to load dictionary if requested
121
122 Usage:
123
124 from gaudimodule import getClass
125 # one knows that class is already loaded
126 AppMgr = getClass( 'ApplicationMgr' )
127 # one knows where to look for class, if not loaded yet
128 MCParticle = getClass( 'MCParticle' , 'EventDict' )
129 # one knows where to look for class, if not loaded yet
130 Vertex = getClass( 'Vertex' , ['EventDict', 'PhysEventDict'] )
131 """
132 # see if class is already loaded
133 if hasattr( gbl , name ) : return getattr( gbl , name )
134 # try to load dictionaries and look for the required class
135 if type(libs) is not list : libs = [libs]
136 for lib in libs :
137 loaddict( lib )
138 if hasattr( gbl , name ) : return getattr( gbl , name )
139 # return None ( or raise exception? I do not know... )
140 return None
141
142 #----PropertyEntry class---------------------------------------------------------------------
143 class PropertyEntry(object) :
144 """ holds the value and the documentation string of a property """
145 def __init__(self, prop) :
146 self._type = type(prop).__name__
147 self.__doc__ = " --- Property type is " + self.ptype()
148
149 if issubclass(type(prop),GaudiHandleProperty) :
150 self._value = prop.value() # do nothing for ATLAS' handles
151 elif issubclass(type(prop),GaudiHandleArrayProperty) :
152 self._value = prop.value() # do nothing for ATLAS' handles
153 else :
154 # for all other types try to extract the native python type
155 try: self._value = eval( prop.toString() , {} , {} )
156 except:
157 if hasattr ( prop , 'value' ) : self._value = prop.value()
158 else : self._value = prop.toString()
159
160 self.__doc__ += " --- Default value = " + str(self._value) + " --- "
161 if prop.documentation() != 'none':
162 self.__doc__ = prop.documentation() + '\\n' + self.__doc__
163 ## keep the original property
164 self._property = prop # property itself
165 def value(self) :
166 return self._value
167 def ptype(self) :
168 return self._type
169 def property(self):
170 "Return the underlying property itself "
171 return self._property
172 def documentation(self) :
173 return self.__doc__
174 def hasDoc(self):
175 return len(self.__doc__)>0 and self.__doc__ != 'none'
176
177 #----iProperty class---------------------------------------------------------------------
178 class iProperty(object) :
179 """ Python equivalent to the C++ Property interface """
180 def __init__(self, name, ip = None) :
181 if ip : self.__dict__['_ip'] = InterfaceCast(gbl.IProperty)(ip)
182 else : self.__dict__['_ip'] = None
183 self.__dict__['_svcloc'] = gbl.Gaudi.svcLocator()
184 optsvc = Helper.service(self._svcloc,'JobOptionsSvc')
185 if optsvc : self.__dict__['_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(optsvc)
186 else : self.__dict__['_optsvc'] = None
187 self.__dict__['_name'] = name
188 def getInterface(self) :
189 if not self._ip : self.retrieveInterface()
190 return self._ip
191 def retrieveInterface(self) :
192 pass
193 def __call_interface_method__(self,ifname,method,*args):
194 if not getattr(self,ifname) : self.retrieveInterface()
195 return getattr(getattr(self,ifname),method)(*args)
196 def __setattr__(self, name, value):
197 """
198 The method which is used for setting the property from the given value.
199 - In the case of the valid instance it sets the property through IProperty interface
200 - In the case of placeholder the property is added to JobOptionsCatalogue
201 """
202 if hasattr( value, 'toStringProperty' ):
203 # user defined behaviour
204 value = '%s' % value.toStringProperty()
205 ip = self.getInterface()
206 if ip :
207 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
208 raise AttributeError, 'property %s does not exist' % name
209 prop = ip.getProperty(name)
210
211 if ROOT6WorkAroundEnabled('ROOT-6032'):
212 canSetValue = (hasattr(prop, 'value') and
213 'const(&)[' not in prop.value.func_doc and
214 type(value) == type(prop.value()))
215 else:
216 canSetValue = (hasattr(prop, 'value') and
217 type(value) == type(prop.value()))
218
219 if canSetValue:
220 if not prop.setValue(value) :
221 raise AttributeError, 'property %s could not be set from %s' % (name, value)
222 else:
223 if tuple == type( value ) : value = str(value)
224 elif hasattr ( value , 'toString' ) : value = value.toString()
225 elif not long == type( value ) : value = '%s' % value
226 else : value = '%d' % value
227 if ROOT6WorkAroundEnabled('ROOT-6028'):
228 sc = cppyy.gbl.GaudiPython.Helper.setPropertyFromString(prop, value)
229 else:
230 sc = prop.fromString(value)
231 if sc.isFailure() :
232 raise AttributeError, 'property %s could not be set from %s' % (name,value)
233 else :
234 if type(value) == str : value = '"%s"' % value # need double quotes
235 elif type(value) == tuple : value = str(value)
236 elif hasattr( value , 'toString' ) : value = value.toString()
237 elif type(value) == long: value = '%d' % value # prevent pending 'L'
238 sp = StringProperty( name , str(value))
239 self._optsvc.addPropertyToCatalogue( self._name , sp )
240 def __getattr__(self, name ):
241 """
242 The method which returns the value for the given property
243 - In the case of the valid instance it returns the valid property value through IProperty interface
244 - In the case of placeholder the property value is retrieved from JobOptionsCatalogue
245 """
246 ip = self.getInterface()
247 if ip :
248 if not gbl.Gaudi.Utils.hasProperty ( ip , name ) :
249 raise AttributeError, 'property %s does not exist' % name
250 prop = ip.getProperty(name)
251 if StringProperty == type( prop ) : return prop.value()
252 elif StringPropertyRef == type( prop ) : return prop.value()
253 try: return eval( prop.toString(), {}, {} )
254 except : return prop.value()
255 else :
256 props = self._optsvc.getProperties(self._name)
257 for p in props :
258 if not p.name() == name : continue
259 # from JobOptionsSvc we always have only strings
260 try: return eval( p.value(), {}, {} )
261 except: return p.value()
262 raise AttributeError, 'property %s does not exist' % name
263 def properties(self):
264 dct = {}
265 props = None
266 ip = self.getInterface()
267 if ip :
268 props = ip.getProperties()
269 propsFrom = self._name # "interface"
270 else:
271 props = self._optsvc.getProperties( self._name )
272 propsFrom = "jobOptionsSvc"
273 if props:
274 for p in props :
275 try:
276 dct[p.name()] = PropertyEntry(p)
277 except (ValueError,TypeError),e:
278 raise ValueError, "gaudimodule.iProperty.properties(): %s%s processing property %s.%s = %s" % \
279 (e.__class__.__name__, e.args, propsFrom, p.name(), p.value())
280 return dct
281 def name(self) :
282 return self._name
283
284 #----iService class---------------------------------------------------------------------
285 class iService(iProperty) :
286 """ Python equivalent to IProperty interface """
287 def __init__(self, name, isvc = None ) :
288 iProperty.__init__(self, name, isvc )
289 if isvc : self.__dict__['_isvc'] = InterfaceCast(gbl.IService)(isvc)
290 else : self.__dict__['_isvc'] = None
291 def retrieveInterface(self) :
292 isvc = Helper.service(self._svcloc,self._name)
293 if isvc : iService.__init__(self, self._name, isvc)
294 initialize = lambda self : self.__call_interface_method__("_isvc","initialize")
295 start = lambda self : self.__call_interface_method__("_isvc","start")
296 stop = lambda self : self.__call_interface_method__("_isvc","stop")
297 finalize = lambda self : self.__call_interface_method__("_isvc","finalize")
298 reinitialize = lambda self : self.__call_interface_method__("_isvc","reinitialize")
299 restart = lambda self : self.__call_interface_method__("_isvc","restart")
300 def isValid(self) :
301 if self._isvc: return True
302 else : return False
303
304 #----iAlgorithm class---------------------------------------------------------------------
305 class iAlgorithm(iProperty) :
306 """ Python equivalent to IAlgorithm interface """
307 def __init__(self, name, ialg = None ) :
308 iProperty.__init__(self, name, ialg )
309 if ialg : self.__dict__['_ialg'] = InterfaceCast(gbl.IAlgorithm)(ialg)
310 else : self.__dict__['_ialg'] = None
311 def retrieveInterface(self) :
312 ialg = Helper.algorithm(InterfaceCast(gbl.IAlgManager)(self._svcloc),self._name)
313 if ialg : iAlgorithm.__init__(self, self._name, ialg)
314 initialize = lambda self : self.__call_interface_method__("_ialg","initialize")
315 start = lambda self : self.__call_interface_method__("_ialg","start")
316 execute = lambda self : self.__call_interface_method__("_ialg","execute")
317 stop = lambda self : self.__call_interface_method__("_ialg","stop")
318 finalize = lambda self : self.__call_interface_method__("_ialg","finalize")
319 reinitialize = lambda self : self.__call_interface_method__("_ialg","reinitialize")
320 restart = lambda self : self.__call_interface_method__("_ialg","restart")
321 sysInitialize = lambda self : self.__call_interface_method__("_ialg","sysInitialize")
322 sysStart = lambda self : self.__call_interface_method__("_ialg","sysStart")
323 sysExecute = lambda self : self.__call_interface_method__("_ialg","sysExecute")
324 sysStop = lambda self : self.__call_interface_method__("_ialg","sysStop")
325 sysFinalize = lambda self : self.__call_interface_method__("_ialg","sysFinalize")
326 sysReinitialize = lambda self : self.__call_interface_method__("_ialg","sysReinitialize")
327 sysRestart = lambda self : self.__call_interface_method__("_ialg","sysRestart")
328
329 #----iAlgTool class---------------------------------------------------------------------
330 class iAlgTool(iProperty) :
331 """ Python equivalent to IAlgTool interface (not completed yet) """
332 def __init__(self, name, itool = None ) :
333 iProperty.__init__(self, name, itool )
334 if itool : self.__dict__['_itool'] = itool
335 else : self.__dict__['_itool'] = None
336 svc = Helper.service( self._svcloc, 'ToolSvc', True )
337 self.__dict__['_toolsvc']= iToolSvc('ToolSvc', svc)
338 def retrieveInterface(self) :
339 itool = self._toolsvc._retrieve(self._name)
340 if itool : iAlgTool.__init__(self, self._name, itool)
341 start = lambda self : self.__call_interface_method__("_itool","start")
342 stop = lambda self : self.__call_interface_method__("_itool","stop")
343 type = lambda self : self.__call_interface_method__("_itool","type")
344 def name(self) :
345 if self._itool : return self._itool.name()
346 else : return self._name
347
348 #----iDataSvc class---------------------------------------------------------------------
349 class iDataSvc(iService) :
350 def __init__(self, name, idp) :
351 iService.__init__(self, name, idp )
352 self.__dict__['_idp'] = InterfaceCast(gbl.IDataProviderSvc)(idp)
353 self.__dict__['_idm'] = InterfaceCast(gbl.IDataManagerSvc)(idp)
354 def registerObject(self, path, obj) :
355 if not self._idp : raise AttributeError('C++ service %s does not exist' % self.__dict__['_name'])
356 return self._idp.registerObject(path,obj)
357 def unregisterObject(self, path) :
358 if not self._idp : raise AttributeError('C++ service %s does not exist' % self.__dict__['_name'])
359 return self._idp.unregisterObject(path)
360 def retrieveObject(self, path) :
361 if not self._idp : return None
362 return Helper.dataobject(self._idp, path)
363 ## get object from TES
364 def findObject(self, path) :
365 """
366
367 Get the existing object in TransientStore for the given location
368
369 - loading of object from persistency is NOT triggered
370 - 'data-on-demand' action is NOT triggered
371
372 >>> svc = ... ## get the service
373 >>> path = ... ## get the path in Transient Store
374 >>> data = svc.findObject ( path ) ## use the method
375
376 """
377 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
378 return Helper.findobject(self._idp, path)
379
380 ## get or retrieve object, possible switch-off 'on-demand' actions
381 def getObject ( self , path , *args ) :
382 """
383 Get object from Transient Store for the given location
384
385 arguments :
386 - path : Location of object in Transient Store
387 - retrieve (bool) True : retrieve versus find
388 - disable on-demand (bool) False : temporary disable 'on-demand' actions
389
390 >>> svc = ... ## get the service
391 >>> path = ... ## get the path
392
393 >>> data = svc.getObject ( path , False ) ## find object in Transient Store
394
395 ## find object in Transient Store
396 # load form tape or use 'on-demand' action for missing objects :
397 >>> data = svc.getObject ( path , True )
398
399 ## find object in Transient Store
400 # load from tape or for missing objects, disable 'on-demand'-actions
401 >>> data = svc.getObject ( path , True , True )
402
403 """
404 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
405 return Helper.getobject(self._idp, path, *args )
406
407 def __getitem__(self, path) :
408 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
409 return Helper.dataobject(self._idp, path)
410 def __setitem__(self, path, obj) :
411 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
412 return self._idp.registerObject(path,obj)
413 def __delitem__(self, path) :
414 if not self._idp : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
415 return self._idp.unregisterObject(path)
416 def leaves(self, node=None) :
417 if not node : node = self.retrieveObject('')
418 ll = gbl.std.vector('IRegistry*')()
419 if type(node) is str : obj = self.retrieveObject(node)
420 else : obj = node
421 if self._idm.objectLeaves(node, ll).isSuccess() : return ll
422 def dump(self, node=None) :
423 if not node :
424 root = self.retrieveObject('')
425 if root : node = root.registry()
426 else : return
427 print node.identifier()
428 if node.object() :
429 for l in self.leaves(node) : self.dump(l)
430 def getList(self, node=None, lst=[], rootFID=None) :
431 if not node :
432 root = self.retrieveObject('')
433 if root :
434 node = root.registry()
435 rootFID = node.address().par()
436 lst = []
437 else :
438 return
439 Helper.dataobject( self._idp, node.identifier() )
440 if node.object() :
441 lst.append( node.identifier() )
442 for l in self.leaves(node) :
443 if l.address() and l.address().par() == rootFID :
444 self.getList(l,lst,rootFID)
445 else :
446 continue
447 return lst
448 def getHistoNames( self, node=None, lst=[] ) :
449 if not node :
450 root = self.retrieveObject('')
451 if root :
452 node = root.registry()
453 # rootFID = node.address().par()
454 lst = []
455 else : return
456 Helper.dataobject( self._idp, node.identifier() )
457 if node.object() :
458 lst.append( node.identifier() )
459 for l in self.leaves(node) :
460 if l.name() : # and l.address().par() == rootFID :
461 self.getHistoNames(l,lst)
462 else :
463 continue
464 return lst
465 def setRoot(self, name, obj):
466 if not self._idm : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
467 return self._idm.setRoot(name,obj)
468 def clearStore(self):
469 if not self._idm : raise IndexError('C++ service %s does not exist' % self.__dict__['_name'])
470 return self._idm.clearStore()
471
472
473 #----iHistogramSvc class---------------------------------------------------------------------
474 class iHistogramSvc(iDataSvc) :
475 def __init__(self, name, ihs) :
476 self.__dict__['_ihs'] = InterfaceCast(gbl.IHistogramSvc)(ihs)
477 iDataSvc.__init__(self, name, ihs)
478 def retrieve1D(self, path) :
479 return Helper.histo1D(self._ihs, path)
480 def retrieve2D(self, path) :
481 return Helper.histo2D(self._ihs, path)
482 def retrieve3D(self, path) :
483 return Helper.histo3D(self._ihs, path)
484 def retrieveProfile1D(self, path) :
485 return Helper.profile1D(self._ihs, path)
486 def retrieveProfile2D(self, path) :
487 return Helper.profile2D(self._ihs, path)
488 def retrieve(self,path):
489 """
490 Retrieve AIDA histogram or AIDA profile histogram by path in Histogram Transient Store
491 >>> svc = ...
492 >>> histo = svc.retrieve ( 'path/to/my/histogram' )
493 """
494 h = self.retrieve1D(path)
495 if not h : h = self.retrieve2D(path)
496 if not h : h = self.retrieve3D(path)
497 if not h : h = self.retrieveProfile1D(path)
498 if not h : h = self.retrieveProfile2D(path)
499 return h
500 def book(self, *args) :
501 """
502 Book the histograms(1D,2D&3D) , see IHistogramSvc::book
503 >>> svc = ...
504 >>> histo = svc.book( .... )
505 """
506 return apply(self._ihs.book,args)
507 def bookProf(self, *args) :
508 """
509 Book the profile(1D&2D) histograms, see IHistogramSvc::bookProf
510 >>> svc = ...
511 >>> histo = svc.bookProf( .... )
512 """
513 return apply(self._ihs.bookProf,args)
514 def __getitem__ ( self, path ) :
515 """
516 Retrieve the object from Histogram Transient Store (by path)
517 The reference to AIDA histogram is returned (if possible)
518 >>> svc = ...
519 >>> histo = svc['path/to/my/histogram']
520 """
521 h = self.retrieve ( path )
522 if h : return h
523 return iDataSvc.__getitem__( self , path )
524 def getAsAIDA ( self , path ) :
525 """
526 Retrieve the histogram from Histogram Transient Store (by path)
527 The reference to AIDA histogram is returned (if possible)
528 >>> svc = ...
529 >>> histo = svc.getAsAIDA ( 'path/to/my/histogram' )
530 """
531 return self.__getitem__( path )
532 def getAsROOT ( self , path ) :
533 """
534 Retrieve the histogram from Histogram Transient Store (by path)
535 The Underlying native ROOT object is returned (if possible)
536 >>> svc = ...
537 >>> histo = svc.getAsROOT ( 'path/to/my/histogram' )
538 """
539 fun = gbl.Gaudi.Utils.Aida2ROOT.aida2root
540 return fun( self.getAsAIDA( path ) )
541
542 #----iNTupleSvc class---------------------------------------------------------------------
543 class iNTupleSvc(iDataSvc) :
544 RowWiseTuple = 42
545 ColumnWiseTuple = 43
546 def __init__(self, name, ints) :
547 self.__dict__['_ints'] = InterfaceCast(gbl.INTupleSvc)(ints)
548 iDataSvc.__init__(self, name, ints)
549 def book(self, *args) :
550 return apply(self._ints.book, args)
551 def defineOutput(self, files, typ="Gaudi::RootCnvSvc"):
552 """ Defines the mapping between logical names and the output file
553 Usage:
554 defineOutput({'LUN1':'MyFile1.root', 'LUN2':'Myfile2.root'}, svc='Gaudi::RootCnvSvc')
555 """
556 import Persistency as prs
557 helper = prs.get(typ)
558 helper.configure(AppMgr())
559 self.Output = [helper.formatOutput(files[lun], lun=lun) for lun in files]
560 if AppMgr().HistogramPersistency == 'NONE':
561 AppMgr().HistogramPersistency = "ROOT"
562 def __getitem__ ( self, path ) :
563 return iDataSvc.__getitem__( self , path )
564
565
566 #----iToolSvc class---------------------------------------------------------------------
567 class iToolSvc(iService) :
568 def __init__(self, name, its) :
569 self.__dict__['_its'] = InterfaceCast(gbl.IToolSvc)(its)
570 iService.__init__(self, name, its)
571 def _retrieve(self, name, quiet=True):
572 sol = _gaudi.OutputLevel
573 if quiet : self.OutputLevel = 6
574 if name.rfind('.') == -1 :
575 itool = Helper.tool(self._its, '', name, None, False )
576 elif name[0:8] == 'ToolSvc.' :
577 itool = Helper.tool(self._its, '', name[8:], None, False )
578 elif name.count('.') > 1 :
579 ptool = self._retrieve(name[:name.rfind('.')])
580 itool = Helper.tool(self._its, '', name[name.rfind('.')+1:], ptool, False )
581 elif _gaudi :
582 prop = _gaudi.property(name[:name.rfind('.')])
583 itool = Helper.tool(self._its, '', name[name.rfind('.')+1:], prop._ip, False )
584 if quiet : self.OutputLevel = sol
585 return itool
586 def retrieve(self, name):
587 return iAlgTool(name, self._retrieve(name,quiet=False))
588 def create(self, typ, name=None, parent=None, interface=None) :
589 if not name : name = typ
590 itool = Helper.tool(self._its, typ, name, parent, True )
591 if interface :
592 return InterfaceCast(interface)(itool)
593 else :
594 return iAlgTool(name,itool)
595 def release(self, itool) :
596 if type(itool) is iAlgTool :
597 self._its.releaseTool(itool._itool)
598
599 #----iJopOptSvc class-------------------------------------------------------------------
600 class iJobOptSvc(iService) :
601 """
602 Python-image of C++ class IJobOptionsSvc
603 """
604 ## constructor
605 def __init__( self , name , svc ) :
606 """ constructor """
607 self.__dict__['_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(svc)
608 return iService.__init__( self , name , svc )
609 def getProperties( self , component ) :
610 """
611 Extract *ALL* properties of the given component
612 Usage :
613 >>> jos = gaudi.optSvc()
614 >>> props = jos.getProperties( 'Name' )
615 """
616 props = self._optsvc.getProperties( component )
617 prps = {}
618 if not props : return prps # RETURN
619 for p in props :
620 prop = p.name().upper()
621 try :
622 value = eval( p.value() , {} , {} )
623 except: value = p.value()
624 prps [ prop ] = value
625
626 return prps # RETURN
627 def getProperty ( self , component , name ) :
628 """
629 Get a certain property of the certain component
630 Usage:
631 >>> jos = ...
632 >>> extServices = jos.getProperty( 'ApplicationMgr', 'ExtSvc' )
633 """
634 ## get all properties of the component
635 all = self.getProperties ( component )
636 return all.get( name.upper() , None ) # RETURN
637
638 #----iEventSelector class------------------------------------------------------------------
639 class iEventSelector(iService):
640 def __init__(self):
641 iService.__init__(self, 'EventSelector', Helper.service(gbl.Gaudi.svcLocator(),'EventSelector'))
642 self.__dict__['g'] = AppMgr()
643 def open(self, stream, typ = 'Gaudi::RootCnvSvc', **kwargs):
644 import Persistency as prs
645 helper = prs.get(typ)
646 helper.configure(self.g)
647 self.Input = helper.formatInput(stream, **kwargs)
648 self.reinitialize()
649 def rewind(self):
650 # It is not possible to reinitialize EventSelector only
651 self.g.service('EventLoopMgr').reinitialize()
652
653 #----AppMgr class---------------------------------------------------------------------
654 class AppMgr(iService) :
655 def __new__ ( cls, *args, **kwargs ):
656 global _gaudi
657 if not _gaudi :
658 newobj = object.__new__( cls )
659 cls.__init__(newobj, *args, **kwargs)
660 _gaudi = newobj
661 return _gaudi
662 def __reset__(self):
663 global _gaudi
664 # Stop, Finalize and Terminate the current AppMgr
665 self.exit()
666 # release interfaces
667 self._evtpro.release()
668 self._svcloc.release()
669 self._appmgr.release()
670 # Reset the C++ globals
671 gbl.Gaudi.setInstance(makeNullPointer('ISvcLocator'))
672 gbl.Gaudi.setInstance(makeNullPointer('IAppMgrUI'))
673 # Reset the Python global
674 _gaudi = None
675 def __init__(self, outputlevel = -1, joboptions = None, selfoptions = {},
676 dllname = None, factname = None) :
677 global _gaudi
678 if _gaudi : return
679 # Protection against multiple calls to exit() if the finalization fails
680 self.__dict__['_exit_called'] = False
681 # keep the Gaudi namespace around (so it is still available during atexit shutdown)...
682 self.__dict__['_gaudi_ns'] = Gaudi
683 try:
684 from GaudiKernel.Proxy.Configurable import expandvars
685 except ImportError:
686 # pass-through implementation if expandvars is not defined (AthenaCommon)
687 expandvars = lambda data : data
688 if dllname and factname:
689 self.__dict__['_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname,factname)
690 elif dllname:
691 self.__dict__['_appmgr'] = gbl.Gaudi.createApplicationMgr(dllname)
692 else:
693 self.__dict__['_appmgr'] = gbl.Gaudi.createApplicationMgr()
694 self.__dict__['_svcloc'] = gbl.Gaudi.svcLocator()
695 self.__dict__['_algmgr'] = InterfaceCast(gbl.IAlgManager)(self._appmgr)
696 self.__dict__['_evtpro'] = InterfaceCast(gbl.IEventProcessor)(self._appmgr)
697 self.__dict__['_svcmgr'] = InterfaceCast(gbl.ISvcManager)(self._appmgr)
698 self.__dict__['pyalgorithms'] = []
699 iService.__init__(self, 'ApplicationMgr', self._appmgr )
700 #------python specific initialization-------------------------------------
701 if self.FSMState() < Gaudi.StateMachine.CONFIGURED : # Not yet configured
702 self.JobOptionsType = 'NONE'
703 if joboptions :
704 from GaudiKernel.ProcessJobOptions import importOptions
705 importOptions(joboptions)
706 # Ensure that the ConfigurableUser instances have been applied
707 import GaudiKernel.Proxy.Configurable
708 if hasattr(GaudiKernel.Proxy.Configurable, "applyConfigurableUsers"):
709 GaudiKernel.Proxy.Configurable.applyConfigurableUsers()
710 # This is the default and could be overridden with "selfopts"
711 self.OutputLevel = 3
712 selfprops = Configurable.allConfigurables.get('ApplicationMgr',{})
713 if selfprops : selfprops = expandvars(selfprops.getValuedProperties())
714 for p,v in selfprops.items() : setattr(self, p, v)
715 for p,v in selfoptions.items() : setattr(self, p, v)
716 # Override job options
717 if outputlevel != -1 : self.OutputLevel = outputlevel
718 self.configure()
719 #---MessageSvc------------------------------------------------------------
720 ms = self.service('MessageSvc')
721 if 'MessageSvc' in Configurable.allConfigurables:
722 msprops = Configurable.allConfigurables['MessageSvc']
723 ms = self.service('MessageSvc')
724 if hasattr(msprops,"getValuedProperties"):
725 msprops = expandvars(msprops.getValuedProperties())
726 for p,v in msprops.items():
727 setattr(ms, p, v)
728 if outputlevel != -1 : ms.OutputLevel = outputlevel
729 #---JobOptions------------------------------------------------------------
730 self.__dict__['_optsvc'] = InterfaceCast(gbl.IJobOptionsSvc)(Helper.service(self._svcloc,'JobOptionsSvc'))
731 #------Configurables initialization (part2)-------------------------------
732 for n in getNeededConfigurables():
733 c = Configurable.allConfigurables[n]
734 if n in ['ApplicationMgr','MessageSvc'] : continue # These are already done---
735 for p, v in c.getValuedProperties().items() :
736 v = expandvars(v)
737 # Note: AthenaCommon.Configurable does not have Configurable.PropertyReference
738 if hasattr(Configurable,"PropertyReference") and type(v) == Configurable.PropertyReference:
739 # this is done in "getFullName", but the exception is ignored,
740 # so we do it again to get it
741 v = v.__resolve__()
742 if type(v) == str : v = '"%s"' % v # need double quotes
743 elif type(v) == long: v = '%d' % v # prevent pending 'L'
744 self._optsvc.addPropertyToCatalogue(n, StringProperty(p,str(v)))
745 if hasattr(Configurable,"_configurationLocked"):
746 Configurable._configurationLocked = True
747
748 # Ensure that the exit method is called when exiting from Python
749 import atexit
750 atexit.register(self.exit)
751
752 #---Hack to avoid bad interactions with the ROOT exit handler
753 # Look for an exit handler installed by ROOT
754 root_handler_installed = False
755 for h in atexit._exithandlers:
756 func = h[0]
757 if hasattr(func, "__module__") and func.__module__ == "ROOT":
758 root_handler_installed = True
759 break
760
761 # If the handler is not yet installed, let's install our private version
762 # that detects that the ROOT exit handler is installed and add our own
763 # after it to ensure it is called before.
764 if not root_handler_installed:
765 orig_register = atexit.register
766 def register(func, *targs, **kargs):
767 orig_register(func, *targs, **kargs)
768 if hasattr(func, "__module__") and func.__module__ == "ROOT":
769 orig_register(self.exit)
770 # we do not need to remove out handler from the list because
771 # it can be safely called more than once
772 register.__doc__ = (orig_register.__doc__ +
773 "\nNote: version hacked by GaudiPython to work " +
774 "around a problem with the ROOT exit handler")
775 atexit.register = register
776
777 def state(self) : return self._isvc.FSMState()
778 def FSMState(self) : return self._isvc.FSMState()
779 def targetFSMState(self) : return self._isvc.targetFSMState()
780 def service(self, name, interface = None) :
781 svc = Helper.service( self._svcloc, name )
782 if interface :
783 return InterfaceCast(interface)(svc)
784 else :
785 return iService(name, svc )
786 def declSvcType(self, svcname, svctype ) :
787 self._svcmgr.declareSvcType(svcname, svctype)
788 def createSvc(self, name ) :
789 return Helper.service( self._svcloc, name, True )
790 def services(self) :
791 l = self._svcloc.getServices()
792 nl = l.__class__(l) # get a copy
793 s = []
794 for i in range(l.size()) :
795 s.append(nl.front().name())
796 nl.pop_front()
797 return s
798 def algorithm(self, name , createIf = False ) :
799 alg = Helper.algorithm( self._algmgr, name , createIf )
800 if not alg : return iAlgorithm ( name , alg )
801 else : return iAlgorithm ( alg.name() , alg )
802 def algorithms(self) :
803 l = self._algmgr.getAlgorithms()
804 nl = l.__class__(l) # get a copy
805 s = []
806 for i in range(l.size()) :
807 s.append(nl.front().name())
808 nl.pop_front()
809 return s
810 def tool(self, name ) :
811 return iAlgTool(name)
812 def property( self , name ) :
813 if name in self.algorithms() : return self.algorithm( name )
814 elif name in self.services() : return self.service(name )
815 else : return iProperty( name )
816 def datasvc(self, name) :
817 if self.state() == Gaudi.StateMachine.CONFIGURED : self.initialize()
818 svc = Helper.service( self._svcloc, name )
819 return iDataSvc(name, svc)
820 def evtsvc(self) :
821 return self.datasvc('EventDataSvc')
822 def detsvc(self) :
823 return self.datasvc('DetectorDataSvc')
824 def filerecordsvc(self) :
825 return self.datasvc('FileRecordDataSvc')
826 def evtsel(self):
827 if self.state() == Gaudi.StateMachine.CONFIGURED : self.initialize()
828 if not hasattr(self,'_evtsel') : self.__dict__['_evtsel'] = iEventSelector()
829 return self._evtsel
830 def histsvc(self, name='HistogramDataSvc') :
831 svc = Helper.service( self._svcloc, name )
832 return iHistogramSvc(name, svc)
833 def ntuplesvc(self, name='NTupleSvc') :
834 if name not in self.ExtSvc : self.ExtSvc += [name]
835 # if self.HistogramPersistency == 'NONE' : self.HistogramPersistency = 'ROOT'
836 svc = Helper.service( self._svcloc, name, True )
837 return iNTupleSvc(name, svc)
838 def partsvc(self ) :
839 if self.FSMState() == Gaudi.StateMachine.CONFIGURED : self.initialize()
840 svc = Helper.service( self._svcloc, 'ParticlePropertySvc' )
841 return InterfaceCast(gbl.IParticlePropertySvc)(svc)
842 def toolsvc(self, name='ToolSvc') :
843 svc = Helper.service( self._svcloc, name, True )
844 return iToolSvc(name, svc)
845 def optSvc (self, name='JobOptionsSvc') :
846 svc = Helper.service( self._svcloc, name, True )
847 return iJobOptSvc(name, svc)
848 def readOptions(self, file) :
849 return self._optsvc.readOptions(file)
850 def addAlgorithm(self, alg) :
851 """ Add an Algorithm to the list of Top algorithms. It can be either a instance of
852 an Algorithm class or it name """
853 if type(alg) is str :
854 self.topAlg += [alg]
855 else :
856 self.pyalgorithms.append(alg)
857 setOwnership(alg,0)
858 if self.targetFSMState() >= Gaudi.StateMachine.INITIALIZED :
859 alg.sysInitialize()
860 if self.targetFSMState() == Gaudi.StateMachine.RUNNING :
861 alg.sysStart()
862 self.topAlg += [alg.name()]
863 def setAlgorithms(self, algs) :
864 """ Set the list of Top Algorithms.
865 It can be an individual of a list of algorithms names or instances """
866 if type(algs) is not list : algs = [algs]
867 names = []
868 for alg in algs :
869 if type(alg) is str : names.append(alg)
870 else :
871 self.pyalgorithms.append(alg)
872 if self.targetFSMState() >= Gaudi.StateMachine.INITIALIZED :
873 alg.sysInitialize()
874 if self.targetFSMState() == Gaudi.StateMachine.RUNNING :
875 alg.sysStart()
876 names.append(alg.name())
877 self.topAlg = names
878 def removeAlgorithm(self, alg) :
879 """ Remove an Algorithm to the list of Top algorithms. It can be either a instance of
880 an Algorithm class or it name """
881 tmp = self.topAlg
882 if type(alg) is str :
883 tmp.remove(alg)
884 else :
885 tmp.remove(alg.name())
886 self.pyalgorithms.remove(alg)
887 setOwnership(alg,1)
888 self.topAlg = tmp
889 def config ( self, **args ):
890 """
891 Simple utility to perform the configuration of Gaudi application.
892 It reads the set of input job-options files, and set few
893 additional parameters 'options' through the usage of temporary *.opts file
894 Usage:
895 gaudi.config( files = [ '$GAUSSOPTS/Gauss.opts' ,
896 '$DECFILESROOT/options/10022_010.0GeV.opts' ] ,
897 options = [ 'EventSelector.PrintFreq = 5 ' ] )
898 """
899 files = args.get('files',[])
900 for file in files :
901 sc = self.readOptions(file)
902 if sc.isFailure() :
903 raise RuntimeError , ' Unable to read file "' + file +'" '
904 options = args.get('options',None)
905 if options :
906 import tempfile
907 tmpfilename = tempfile.mktemp()
908 tmpfile = open( tmpfilename, 'w' )
909 tmpfile.write ( '#pragma print on \n' )
910 tmpfile.write ( '/// File "' + tmpfilename+'" generated by GaudiPython \n\n' )
911 for opt in options :
912 if type(options) is dict :
913 tmpfile.write( ' \t ' + opt + ' = '+ options[opt]+ ' ; // added by GaudiPython \n' )
914 else :
915 tmpfile.write( ' \t ' + opt + ' ; // added by GaudiPython \n' )
916 tmpfile.write ( '/// End of file "' + tmpfilename+'" generated by GaudiPython \n\n' )
917 tmpfile.close()
918 sc = self.readOptions( tmpfilename )
919 if sc.isFailure() :
920 raise RuntimeError , ' Unable to read file "' + tmpfilename +'" '
921 os.remove( tmpfilename )
922 # We need to make sure that the options are taken by the ApplicationMgr
923 if self.FSMState() != Gaudi.StateMachine.OFFLINE : # The state is already configured, so we need to do something....
924
925 ## get job-options-service, @see class iJobOptSvc
926 jos = self.optSvc()
927
928 ## list of all libraries
929 _dlls = jos.getProperty ( self.name() , 'DLLs' )
930 ## take care about libraries : APPEND if not done yet
931 if _dlls :
932 libs = [ l for l in _dlls if not l in self.DLLs ]
933 if libs : self.DLLs += libs
934
935 ## all external services
936 _svcs = jos.getProperty ( self.name() , 'ExtSvc' )
937 ## take care about services : APPEND if not done yet
938 if _svcs :
939 svcs = [ s for s in _svcs if not s in self.ExtSvc ]
940 if svcs : self.ExtSvc += svcs
941
942 ## get all properties
943 props = jos.getProperties ( self.name() )
944 ## finally treat all other properties (presumably scalar properties)
945 for key in props :
946 if 'DLLS' == key or 'EXTSVC' == key : continue
947 self.__setattr__( key , props[key] )
948 return SUCCESS # RETURN
949 def configure(self) :
950 return self._appmgr.configure()
951 def start(self) :
952 return self._appmgr.start()
953 def run(self, n) :
954 if self.FSMState() == Gaudi.StateMachine.CONFIGURED :
955 sc = self.initialize()
956 if sc.isFailure() or self.ReturnCode != 0:
957 return sc
958 if self.FSMState() == Gaudi.StateMachine.INITIALIZED :
959 sc = self.start()
960 if sc.isFailure() or self.ReturnCode != 0:
961 return sc
962 return self._evtpro.executeRun(n)
963 def executeEvent(self) :
964 return self._evtpro.executeEvent()
965 def execute(self) :
966 return self._evtpro.executeEvent()
967 def runSelectedEvents(self, pfn, events):
968 if self.FSMState() == Gaudi.StateMachine.CONFIGURED :
969 sc = self.initialize()
970 if sc.isFailure(): return sc
971 if self.FSMState() == Gaudi.StateMachine.INITIALIZED :
972 sc = self.start()
973 if sc.isFailure(): return sc
974 #--- Access a number of services ----
975 if not hasattr(self,'_perssvc'): self.__dict__['_perssvc'] = self.service('EventPersistencySvc','IAddressCreator')
976 if not hasattr(self,'_filecat'): self.__dict__['_filecat'] = self.service('FileCatalog','Gaudi::IFileCatalog')
977 if not hasattr(self,'_evtmgr'): self.__dict__['_evtmgr'] = self.service('EventDataSvc','IDataManagerSvc')
978 #--- Get FID from PFN and number of events in file
979 if pfn.find('PFN:') == 0: pfn = pfn[4:]
980 fid, maxevt = _getFIDandEvents(pfn)
981 #--- Add FID into catalog if needed ---
982 if not self._filecat.existsFID(fid) : self._filecat.registerPFN(fid, pfn, '')
983 #--- Loop over events
984 if type(events) is not list : events = (events,)
985 for evt in events :
986 #--- Create POOL Address from Generic Address
987 gadd = gbl.GenericAddress(0x02, 1, fid, '/Event', 0, evt)
988 oadd = makeNullPointer('IOpaqueAddress')
989 self._perssvc.createAddress(gadd.svcType(),gadd.clID(),gadd.par(),gadd.ipar(),oadd)
990 #--- Clear TES, set root and run all algorithms
991 self._evtmgr.clearStore()
992 self._evtmgr.setRoot('/Event',oadd)
993 self._evtpro.executeEvent()
994 def exit(self):
995 # Protection against multiple calls to exit() if the finalization fails
996 if not self._exit_called:
997 self.__dict__['_exit_called'] = True
998 Gaudi = self._gaudi_ns
999 if self.FSMState() == Gaudi.StateMachine.RUNNING:
1000 self._appmgr.stop().ignore()
1001 if self.FSMState() == Gaudi.StateMachine.INITIALIZED:
1002 self._appmgr.finalize().ignore()
1003 if self.FSMState() == Gaudi.StateMachine.CONFIGURED:
1004 self._appmgr.terminate()
1005 return SUCCESS
1006 ## Custom destructor to ensure that the application is correctly finalized when exiting from python.
1007 def __del__(self):
1008 self.exit()
1009 evtSvc = evtsvc
1010 histSvc = histsvc
1011 ntupleSvc = ntuplesvc
1012 evtSel = evtsel
1013 detSvc = detsvc
1014 toolSvc = toolsvc
1015 partSvc = partsvc
1016
1017 #--------------------------------------------------------------------------------------
1018 def _getFIDandEvents( pfn ):
1019 tfile = gbl.TFile.Open(pfn)
1020 if not tfile : raise 'Cannot open ROOT file ', pfn
1021 tree = tfile.Get('##Params')
1022 tree.GetEvent(0)
1023 text = tree.db_string
1024 if 'NAME=FID' in text :
1025 fid = text[text.rfind('VALUE=')+6:-1]
1026 nevt = tfile.Get('_Event').GetEntries()
1027 tfile.Close()
1028 return fid, nevt
1029
1030 #--------------------------------------------------------------------------------------
1031 def getComponentProperties( name ):
1032 """ Get all the properties of a component as a Python dictionary.
1033 The component is instantiated using the component library
1034 """
1035 properties = {}
1036 if name == 'GaudiCoreSvc' :
1037 if Helper.loadDynamicLib(name) != 1 :
1038 raise ImportError, 'Error loading component library '+ name
1039 factorylist = gbl.FactoryTable.instance().getEntries()
1040 factories = _copyFactoriesFromList(factorylist)
1041 g = AppMgr(outputlevel=7)
1042 else :
1043 g = AppMgr(outputlevel=7)
1044 if Helper.loadDynamicLib(name) != 1 :
1045 raise ImportError, 'Error loading component library '+ name
1046 factorylist = gbl.FactoryTable.instance().getEntries()
1047 factories = _copyFactoriesFromList(factorylist)
1048 svcloc = gbl.Gaudi.svcLocator()
1049 dummysvc = gbl.Service('DummySvc',svcloc)
1050 for factory in factories :
1051 if InterfaceCast(gbl.IAlgFactory)(factory) : ctype = 'Algorithm'
1052 elif InterfaceCast(gbl.ISvcFactory)(factory) : ctype = 'Service'
1053 elif InterfaceCast(gbl.IToolFactory)(factory) : ctype = 'AlgTool'
1054 elif factory.ident() == 'ApplicationMgr' : ctype = 'ApplicationMgr'
1055 else : ctype = 'Unknown'
1056 cname = factory.ident().split()[-1]
1057 if ctype in ('Algorithm','Service', 'AlgTool', 'ApplicationMgr') :
1058 try :
1059 if ctype == 'AlgTool' :
1060 obj = factory.instantiate(dummysvc)
1061 else :
1062 obj = factory.instantiate(svcloc)
1063 except RuntimeError, text :
1064 print 'Error instantiating', cname, ' from ', name
1065 print text
1066 continue
1067 prop = iProperty('dummy', obj)
1068 properties[cname] = [ctype, prop.properties()]
1069 try: obj.release()
1070 except: pass
1071 return properties
1072
1073 def _copyFactoriesFromList(factories) :
1074 result = []
1075 for i in range(factories.size()) :
1076 factory = factories.front()
1077 result.append(factory)
1078 factories.pop_front()
1079 for factory in result :
1080 factories.push_back(factory)
1081 return result
1082
1083 #----CallbackStreamBuf----------------------------------------------------------------
1084 # Used for redirecting C++ messages to python
1085 _CallbackStreamBufBase = gbl.GaudiPython.CallbackStreamBuf
1086 class CallbackStreamBuf (_CallbackStreamBufBase):
1087 def __init__(self, callback):
1088 _CallbackStreamBufBase.__init__(self, self)
1089 self.callback = callback
1090 def _sync(self, string = None):
1091 if not string : return 0
1092 self.callback(string)
1093 return 0
1094
1095 #----PyAlgorithm----------------------------------------------------------------------
1096 # Used to implement Algorithms in Python
1097 _PyAlgorithm = gbl.GaudiPython.PyAlgorithm
1098 class PyAlgorithm (_PyAlgorithm) :
1099 def __init__(self, name=None) :
1100 if not name : name = self.__class__.__name__
1101 _PyAlgorithm.__init__(self, self, name)
1102 self._svcloc = gbl.Gaudi.svcLocator()
1103 self._algmgr = InterfaceCast(gbl.IAlgManager)(self._svcloc)
1104 sc = self._algmgr.addAlgorithm(self)
1105 if sc.isFailure() : raise RuntimeError, 'Unable to add Algorithm'
1106 def __del__(self):
1107 sc = self._algmgr.removeAlgorithm(self)
1108 if sc.isFailure() : pass
1109 def initialize(self) : return 1
1110 def start(self) : return 1
1111 def execute(self) : return 1
1112 def stop(self) : return 1
1113 def finalize(self) : return 1
1114 def beginRun(self) : return 1
1115 def endRun(self) : return 1
1116
1117 #----Enable tab completion------------------------------------------------------------
1118 try:
1119 import rlcompleter, readline
1120 readline.parse_and_bind("tab: complete")
1121 except:
1122 pass