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