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