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