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