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