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