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