def _py_init_ClassIDSvc(): import cppyy # IClassIDSvc bindings from dictionary _load_dict("libAthenaPythonDict") # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # noqa: F841 # load the AthenaInternal::getClid helper method cppyy.makeNamespace('AthenaInternal') # Really make sure that dictionaries are loaded. # Needed this with 20.7.X-VAL. cppyy.gbl.AthenaInternal.ROOT6_AthenaPython_WorkAround_Dummy # retrieve the IClassIDSvc class global IClassIDSvc IClassIDSvc = cppyy.gbl.IClassIDSvc _missing_clids = { 'DataHistory': 83814411, 83814411: 'DataHistory', } # re-use the python-based clid generator # (faster than calling back into C++ via Reflex bindings) from CLIDComps.clidGenerator import clidGenerator IClassIDSvc._clidgen = clidGenerator(db=None) # add pythonized methods @memoize def _clid(self, name): # handle special cases where CLID has been registered with a typedef try: name = _clid_typename_aliases[name] except KeyError: pass try: return _missing_clids[name] except KeyError: pass return self._clidgen.getClidFromName(name) IClassIDSvc.clid = _clid del _clid @memoize def _typename(self, clid): # handle special cases of missing clids try: return _missing_clids[clid] except KeyError: pass return self._clidgen.getNameFromClid(clid) IClassIDSvc.typename = _typename del _typename return IClassIDSvc
def _py_init_ThinningSvc(): import cppyy # IThinningSvc bindings from dictionary _load_dict("libAthenaPythonDict") # we also need StoreGate bindings to be initialized sgbindings = _py_init_StoreGateSvc() # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # make sure AthenaInternal namespace has been created gbl.AthenaInternal = cppyy.makeNamespace('AthenaInternal') #global py_thinning py_thinning = cppyy.gbl.AthenaInternal.thinContainer #global py_thinning_idx py_thinning_idx = cppyy.gbl.AthenaInternal.thinIdxContainer # retrieve the IThinningSvc class #global IThinningSvc IThinningSvc = cppyy.gbl.IThinningSvc try: IThinningSvc.RemovedIdx = cppyy.gbl.AthenaInternal.thinRemovedIdx() except TypeError: pass # add specialized filter method from operator import isCallable from string import lower def filter(self, container, selection, op='and'): if isCallable(selection): selection = map(selection, container) if lower(op) == 'and': op = 0 # IThinningSvc.Operator.And elif lower(op) == 'or': op = 1 # IThinningSvc.Operator.Or else: op = 0 # IThinningSvc default return py_thinning(self, container, selection, op) IThinningSvc.filter = filter # add specialized index method def index(self, container, idx): return py_thinning_idx(self, container, idx) IThinningSvc.index = index return IThinningSvc
def gen_typeregistry_dso(oname=_dflt_typereg_fname): '''inspect all the accessible reflex types and get their rootmap-naming. also associate the clid if available. ''' import CLIDComps.clidGenerator as _c cliddb = _c.clidGenerator(db=None) del _c import PyUtils.path as _p oname = _p.path(oname) del _p import PyUtils.Logging as _L msg = _L.logging.getLogger('typereg-dso') msg.setLevel(_L.logging.INFO) #msg.setLevel(_L.logging.VERBOSE) #MN del _L msg.info("installing registry in [%s]...", oname) # FIXME: should use the Cxx one... #reg = DsoDb() reg = PyDsoDb() cls_names = reg.db.keys() import cppyy _load_lib = cppyy.loadDict # if int(cppyy.get_version().split('.')[0]) < 6: if hasattr(cppyy, 'hasCintex'): # load reflex for ROOT ver<6 msg.debug("::: loading reflex") _load_lib('libReflexRflx.so') rflx = cppyy.makeNamespace('Reflex') if not rflx: rflx = cppyy.makeNamespace('ROOT::Reflex') rflx = rflx.Type assert (rflx) def _load_dict(libname, retry=10): msg.debug("::: loading [%s]...", libname) try: return _load_lib(libname) except ( Exception, SystemError, ), err: msg.warning("**error** %s", err) return
def _py_init_IIncidentSvc(): import cppyy # IIncidentSvc bindings from dictionary _load_dict("libGaudiKernelDict") # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # noqa: F841 # retrieve the IIncidentSvc class global IIncidentSvc IIncidentSvc = cppyy.gbl.IIncidentSvc IIncidentSvc._cpp_addListener = IIncidentSvc.addListener def addListener(self, *args): listener = args[0] if hasattr(listener, '_cppHandle'): args = (getattr(listener, '_cppHandle'), ) + args[1:] return self._cpp_addListener(*args) addListener.__doc__ = IIncidentSvc._cpp_addListener.__doc__ IIncidentSvc.addListener = addListener del addListener IIncidentSvc._cpp_removeListener = IIncidentSvc.removeListener def removeListener(self, *args): listener = args[0] if hasattr(listener, '_cppHandle'): args = (getattr(listener, '_cppHandle'), ) + args[1:] return self._cpp_removeListener(*args) removeListener.__doc__ = IIncidentSvc._cpp_removeListener.__doc__ IIncidentSvc.removeListener = removeListener del removeListener return IIncidentSvc
def _py_init_EventType(): import cppyy # EventStreamInfo bindings from dictionary _load_dict( "libEventInfoDict" ) # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # retrieve the EventType class cls = cppyy.gbl.EventType cls.bit_mask_typecodes = [ ('IS_DATA','IS_SIMULATION'), #0 ('IS_ATLAS', 'IS_TESTBEAM'), #1 ('IS_PHYSICS','IS_CALIBRATION'),#2 ] # retrieve the PyEventType class py_cls = cppyy.gbl.PyEventType def raw_bit_mask(self): self._raw_bit_mask = py_cls.bit_mask(self) return self._raw_bit_mask cls.raw_bit_mask = property(raw_bit_mask) def bit_mask(self): def decode_bitmask(idx): if len(self.raw_bit_mask) <= idx: return self.bit_mask_typecodes[idx][0] isa_idx = self.raw_bit_mask[idx] return self.bit_mask_typecodes[idx][isa_idx] bm = map(decode_bitmask, xrange(len(self.bit_mask_typecodes))) return tuple(bm) cls.bit_mask = property(bit_mask) return cls
def _py_init_EventStreamInfo(): import cppyy # EventStreamInfo bindings from dictionary _load_dict( "libEventInfoDict" ) # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # retrieve the EventStreamInfo class ESI = cppyy.gbl.EventStreamInfo # retrieve the PyEventStreamInfo helper class PyESI= cppyy.gbl.PyEventStreamInfo def run_numbers(self): self._run_numbers = PyESI.runNumbers(self) return list(self._run_numbers) def evt_types(self): self._evt_types = PyESI.eventTypes(self) return list(self._evt_types) def item_list(self): self._item_list = PyESI.itemList(self) return list(tuple(i) for i in self._item_list) def lumi_blocks(self): self._lumi_blocks = PyESI.lumiBlockNumbers(self) return list(self._lumi_blocks) def processing_tags(self): self._processing_tags = PyESI.processingTags(self) return list(self._processing_tags) for fct in ('run_numbers', 'evt_types', 'item_list', 'lumi_blocks', 'processing_tags'): setattr(ESI, fct, locals()[fct]) return ESI
def _py_init_EventType(): import cppyy # EventStreamInfo bindings from dictionary _load_dict("libEventInfoDict") # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # noqa: F841 # retrieve the EventType class cls = cppyy.gbl.EventType cls.bit_mask_typecodes = [ ('IS_DATA', 'IS_SIMULATION'), #0 ('IS_ATLAS', 'IS_TESTBEAM'), #1 ('IS_PHYSICS', 'IS_CALIBRATION'), #2 ] # retrieve the PyEventType class py_cls = cppyy.gbl.PyEventType def raw_bit_mask(self): self._raw_bit_mask = py_cls.bit_mask(self) return self._raw_bit_mask cls.raw_bit_mask = property(raw_bit_mask) def bit_mask(self): def decode_bitmask(idx): if len(self.raw_bit_mask) <= idx: return self.bit_mask_typecodes[idx][0] isa_idx = self.raw_bit_mask[idx] return self.bit_mask_typecodes[idx][isa_idx] bm = map(decode_bitmask, range(len(self.bit_mask_typecodes))) return tuple(bm) cls.bit_mask = property(bit_mask) return cls
def _py_init_IIncidentSvc(): import cppyy # IIncidentSvc bindings from dictionary _load_dict( "libGaudiKernelDict" ) # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # retrieve the IIncidentSvc class global IIncidentSvc IIncidentSvc = cppyy.gbl.IIncidentSvc IIncidentSvc._cpp_addListener = IIncidentSvc.addListener def addListener (self, *args): listener = args[0] if hasattr (listener, '_cppHandle'): args = (getattr (listener, '_cppHandle'),) + args[1:] return self._cpp_addListener (*args) addListener.__doc__ = IIncidentSvc._cpp_addListener.__doc__ IIncidentSvc.addListener = addListener del addListener IIncidentSvc._cpp_removeListener = IIncidentSvc.removeListener def removeListener (self, *args): listener = args[0] if hasattr (listener, '_cppHandle'): args = (getattr (listener, '_cppHandle'),) + args[1:] return self._cpp_removeListener (*args) removeListener.__doc__ = IIncidentSvc._cpp_removeListener.__doc__ IIncidentSvc.removeListener = removeListener del removeListener return IIncidentSvc
def have_cppyy(): import sys, platform try: import cppyy as Dict if platform.system() == 'Linux': Dict.loadDictionary('libOnlineKernelDict') else: Dict.loadDictionary('OnlineKernelDict.dll') CPP = Dict.makeNamespace('CPP') gbl = Dict.gbl std = gbl.std Interactor = CPP.PyInteractor Event = CPP.Event BaseSensor = CPP.Sensor IocSensor = CPP.IocSensor TimeSensor = CPP.TimeSensor Sensor = gbl.UpiSensor UpiSensor = gbl.UpiSensor return True except Exception, X: print 'OnlineKernel: Failed to use cppyy - you need to live without. [%s]' % ( str(X), ) return None
def __init__(self): # import cintex # import PyCintex; PyCintex.Cintex.Enable() import cppyy # import root import PyUtils.RootUtils as ru ROOT = ru.import_root() self._cxx = ROOT.Ath.DsoDb.instance() # if int(cppyy.get_version().split('.')[0]) < 6: if hasattr(cppyy, 'hasCintex'): # load reflex for ROOT ver<6 _load_dict = cppyy.loadDict _load_dict('ReflexRflx') self._rflx = cppyy.makeNamespace('Reflex') if not self._rflx: self._rflx = cppyy.makeNamespace('ROOT::Reflex') return
def __init__(self, name_simu="", useISF=False): """ Default simulation engine object initialization. Only one instance per simulation job. """ if G4AtlasEngine._NumInstances > 0: msg = 'There is already an instance of the G4AtlasEngine class -- try to use it!' G4AtlasEngine.log.error('G4AtlasEngine: ' + msg) raise RuntimeError( 'PyG4Atlas: G4AtlasEngine: __init__(): Attempted multiple instantiation' ) ## Init dictionaries and lists # TODO: Clean up this whole ugly "Dict*" mess G4AtlasEngine.Dict = dict() G4AtlasEngine.Dict_DetConfig = dict() G4AtlasEngine.Dict_Materials = dict() G4AtlasEngine.Dict_SpecialConfiguration = dict() ## Web doc links G4AtlasEngine.Dict_WebLinks = { 'maindoc': 'https://twiki.cern.ch/twiki/bin/view/Atlas/G4AtlasApps', 'recipes': 'https://twiki.cern.ch/twiki/bin/view/Atlas/RecipesG4AtlasApps' } G4AtlasEngine.List_Elements = [] G4AtlasEngine.List_LoadedDict = [] G4AtlasEngine.List_LoadedLib = [] G4AtlasEngine.List_LoadedXML = [] ## Simulation name and number of instances control G4AtlasEngine.Name = name_simu G4AtlasEngine._NumInstances += 1 ## Counter to track the number of callback functions that have been executed G4AtlasEngine._callback_counter = 0 ## Logging service G4AtlasEngine.log = Logging.logging.getLogger('G4AtlasApps') from AthenaCommon.AppMgr import ServiceMgr as svcMgr G4AtlasEngine.log.setLevel(10 * (svcMgr.MessageSvc.OutputLevel - 1)) # The profiler will work if log level = debug G4AtlasEngine._app_profiler = _app_profiler(G4AtlasEngine.log.level) # pylcgdict default dictionaries self.load_Dict('AtlasSealCLHEPDict') self.load_Dict('G4AtlasControlDict') G4AtlasEngine.gbl = cppyy.makeNamespace("") G4AtlasEngine._ctrl = G4AtlasEngine.gbl.SimControl() self.init_status = 0 self.useISF = useISF G4AtlasEngine._InitList = list() G4AtlasEngine.log.info('G4AtlasEngine: starting engine')
def _py_init_ThinningSvc(): import cppyy # IThinningSvc bindings from dictionary _load_dict( "libAthenaPythonDict" ) # we also need StoreGate bindings to be initialized sgbindings = _py_init_StoreGateSvc() # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # make sure AthenaInternal namespace has been created gbl.AthenaInternal = cppyy.makeNamespace('AthenaInternal') #global py_thinning py_thinning = cppyy.gbl.AthenaInternal.thinContainer #global py_thinning_idx py_thinning_idx = cppyy.gbl.AthenaInternal.thinIdxContainer # retrieve the IThinningSvc class #global IThinningSvc IThinningSvc = cppyy.gbl.IThinningSvc try: IThinningSvc.RemovedIdx = cppyy.gbl.AthenaInternal.thinRemovedIdx() except TypeError: pass # add specialized filter method from operator import isCallable from string import lower def filter( self, container, selection, op = 'and' ): if isCallable(selection): selection = map( selection, container ) if lower(op) == 'and' : op = 0 # IThinningSvc.Operator.And elif lower(op) == 'or' : op = 1 # IThinningSvc.Operator.Or else : op = 0 # IThinningSvc default return py_thinning( self, container, selection, op ) IThinningSvc.filter = filter # add specialized index method def index( self, container, idx ): return py_thinning_idx( self, container, idx ) IThinningSvc.index = index return IThinningSvc
def _py_init_ClassIDSvc(): import cppyy # IClassIDSvc bindings from dictionary _load_dict("libAthenaPythonDict") # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # load the AthenaInternal::getClid helper method cppyy.makeNamespace('AthenaInternal') # Really make sure that dictionaries are loaded. # Needed this with 20.7.X-VAL. cppyy.gbl.AthenaInternal.ROOT6_AthenaPython_WorkAround_Dummy _getClid = cppyy.gbl.AthenaInternal.getClid # retrieve the IClassIDSvc class global IClassIDSvc IClassIDSvc = cppyy.gbl.IClassIDSvc _missing_clids = { 'DataHistory': 83814411L, 83814411L: 'DataHistory', }
def _py_init_ClassIDSvc(): import cppyy # IClassIDSvc bindings from dictionary _load_dict( "libAthenaPythonDict" ) # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # load the AthenaInternal::getClid helper method cppyy.makeNamespace('AthenaInternal') # Really make sure that dictionaries are loaded. # Needed this with 20.7.X-VAL. cppyy.gbl.AthenaInternal.ROOT6_AthenaPython_WorkAround_Dummy _getClid = cppyy.gbl.AthenaInternal.getClid # retrieve the IClassIDSvc class global IClassIDSvc IClassIDSvc = cppyy.gbl.IClassIDSvc _missing_clids = { 'DataHistory' : 83814411L, 83814411L : 'DataHistory', }
def _py_init_EventStreamInfo(): import cppyy # EventStreamInfo bindings from dictionary _load_dict("libEventInfoDict") # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # retrieve the EventStreamInfo class ESI = cppyy.gbl.EventStreamInfo # retrieve the PyEventStreamInfo helper class PyESI = cppyy.gbl.PyEventStreamInfo def run_numbers(self): self._run_numbers = PyESI.runNumbers(self) return list(self._run_numbers) def evt_types(self): self._evt_types = PyESI.eventTypes(self) return list(self._evt_types) def item_list(self): self._item_list = PyESI.itemList(self) return list(tuple(i) for i in self._item_list) def lumi_blocks(self): self._lumi_blocks = PyESI.lumiBlockNumbers(self) return list(self._lumi_blocks) def processing_tags(self): self._processing_tags = PyESI.processingTags(self) return list(self._processing_tags) for fct in ('run_numbers', 'evt_types', 'item_list', 'lumi_blocks', 'processing_tags'): setattr(ESI, fct, locals()[fct]) return ESI
def _setup(): import cppyy # StoreGate bindings from dictionary cppyy.loadDictionary("libAthenaPythonDict") # for clidsvc cppyy.loadDictionary("libStoreGateBindingsDict") # for storegatesvc cppyy.loadDictionary("libStoreGateBindings" ) # not linked from libStoreGateBindingsDict in ROOT6 # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') _ath = cppyy.makeNamespace('AthenaInternal') # ROOT6 workaround, kick the loading of headers _ath.ROOT6_AthenaPython_WorkAround_Dummy _ath.ROOT6_StoreGateBindings_WorkAround_Dummy # end workaround global py_retrieve py_retrieve = cppyy.gbl.AthenaInternal.retrieveObjectFromStore global py_record py_record = cppyy.gbl.AthenaInternal.recordObjectToStore global py_sg_contains py_sg_contains = cppyy.gbl.AthenaInternal.py_sg_contains global py_sg_getitem py_sg_getitem = cppyy.gbl.AthenaInternal.py_sg_getitem # retrieve the StoreGateSvc class global StoreGate, StoreGateSvc StoreGateSvc = cppyy.gbl.StoreGateSvc StoreGate = cppyy.gbl.StoreGate # add specialized retrieve method def retrieve(self, klass, key=None): ret = py_retrieve(self, klass, key) if ret and hasattr(ret, 'setStore') and not ret.hasStore(): if not hasattr(ret, 'trackIndices') or ret.trackIndices(): if py_sg_contains(self, 'SG::IConstAuxStore', key + 'Aux.'): aux = py_retrieve(self, 'SG::IConstAuxStore', key + 'Aux.') ret.setStore(aux) return ret StoreGateSvc.retrieve = retrieve # add specialized record method def record(self, obj, key, allowMods=True, resetOnly=True, noHist=False): return py_record(self, obj, key, allowMods, resetOnly, noHist) StoreGateSvc.record = record # add specialized contains method def contains(self, klass_or_clid, key): print "---- StoreGateSvc.contains() ", klass_or_clid, key if isinstance(klass_or_clid, str): try: clid = int(klass_or_clid) klass = self._pyclidsvc.typename(clid) except ValueError: klass = str(klass_or_clid) pass elif isinstance(klass_or_clid, (int, long)): klass = self._pyclidsvc.typename(klass_or_clid) elif isinstance(klass_or_clid, type): klass = klass_or_clid.__name__ else: raise TypeError( 'argument 2 must be a typename, a clid or a type (got %r)' % type(klass_or_clid)) return py_sg_contains(self, klass, key) StoreGateSvc.contains = contains # dict-pythonization of storegate: __setitem__ def __setitem__(self, key, obj): return py_record(self, obj, key, True, True, False) StoreGateSvc.__setitem__ = __setitem__ # dict-pythonization of storegate: __getitem__ def __getitem__(self, key): try: ret = py_sg_getitem(self, key) except LookupError, err: raise KeyError(str(err)) if ret and hasattr(ret, 'setStore') and not ret.hasStore(): if not hasattr(ret, 'trackIndices') or ret.trackIndices(): if py_sg_contains(self, 'SG::IConstAuxStore', key + 'Aux.'): aux = py_retrieve(self, 'SG::IConstAuxStore', key + 'Aux.') ret.setStore(aux) return ret
def _py_init_THistSvc(): import cppyy # ITHistSvc bindings from dictionary _load_dict( "libGaudiKernelDict" ) # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # retrieve the ITHistSvc class global ITHistSvc ITHistSvc = cppyy.gbl.ITHistSvc from weakref import WeakValueDictionary # per-object cache of ROOT objects #ITHistSvc._py_cache = WeakValueDictionary() #ITHistSvc._py_cache = dict() ROOT = _import_ROOT() @property def _py_cache(self): try: return self.__py_cache except AttributeError: self.__py_cache = dict() return self.__py_cache ITHistSvc._py_cache = _py_cache # save original regXYZ methods: we'll use some modified ones # to improve look-up time from python for n in ('Hist', 'Graph', 'Tree'): code = "ITHistSvc._cpp_reg%s = ITHistSvc.reg%s" % (n,n) exec code in globals(),locals() def book(self, oid, obj=None, *args, **kw): """book a histogram, profile or tree @param oid is the unique object identifier even across streams, ie: 'stream'+'id' @param obj either an already full-fledge constructed ROOT object or None (then `*args` or `**kw` need to be correctly setup) @param *args list of arguments to give to the constructor of the ROOT object one wants to book @param **kw a dictionary containing a key 'args' being the list of arguments to the constructor of the ROOT objects one wants to book examples: >>> th.book('/temp/1d/h1', 'TH1D', args=('h1','h1',100,0.,100.)) >>> th.book('/temp/1d/h2', ROOT.TH1D, args=('h2','h2',100,0.,100.)) >>> th.book('/temp/1d/h3', ROOT.TH1D, 'h3','h3',100,0.,100.) >>> th.book('/temp/1d/h4', ROOT.TH1D('h4','h4',100,0.,100.)) >>> th.book('/temp/1d/h5', obj=ROOT.TH1D('h5','h5',100,0.,100.)) >>> th.book('/temp/1d/h6', klass='TH1D', args=('h6','h6',100,0.,100.)) >>> th.book('/temp/tree/t1', ROOT.TTree('t1','t1')) >>> th.book('/temp/tree/t2', obj=ROOT.TTree('t2','t2')) >>> th.book('/temp/tree/t3', klass='TTree', args=('t3','t3')) """ _err = "please provide _either_ an already constructed ROOT object or"\ "a class name/class type (with appropriate arguments)" klass = kw.get('klass', None) assert not (obj is None and klass is None), _err assert not (obj is not None and klass is not None), _err if isinstance(obj, (str,type)): klass=obj obj=None if obj: if isinstance(obj, ROOT.TH1): # capture all of TH1x,TH2x,TH3x,TProfileXY meth = '_cpp_regHist' elif isinstance(obj, (ROOT.TGraph,)): meth = '_cpp_regGraph' elif isinstance(obj, (ROOT.TTree,)): meth = '_cpp_regTree' else: raise TypeError("invalid type '%r'"%type(obj)) if getattr(self,meth)(oid, obj).isSuccess(): self._py_cache[oid]=obj return obj raise RuntimeError('could not book object [%r]'%obj) if klass: if isinstance(klass, str): klass = getattr(ROOT, klass) if args: return self.book(oid, obj=klass(*args)) if kw and kw.has_key('args'): return self.book(oid, obj=klass(*kw['args'])) err = "invalid arguments: either provide a valid `*args` or "\ "a `**kw` containing a 'args' key" raise RuntimeError(err) raise RuntimeError("unforseen case: oid='%r' obj='%r' args='%r' "\ "kw='%r'"%(oid,obj,args,kw)) ITHistSvc.book = book def get(self, oid, klass=None): """retrieve an already booked ROOT object. If the object was booked on the C++ side, try to use the `klass` hint (the usual string or type) to find the object in the correct 'folder' (histograms, graphs or trees). If `klass` is None, then go through all the folders iteratively (slow) """ try: return self._py_cache[oid] except KeyError: pass def _get_helper(klass, hsvc, meth, oid, update_cache=True): import cppyy makeNullPtr = cppyy.libPyROOT.MakeNullPointer o = makeNullPtr(klass) if meth(oid, o).isSuccess(): if update_cache: hsvc._py_cache[oid] = o return o return if klass: if isinstance(klass, str): klass = getattr(ROOT, klass) if issubclass(klass, (ROOT.TH1,)): return _get_helper(klass, self, self.getHist, oid) if issubclass(klass, (ROOT.TGraph,)): return _get_helper(klass, self, self.getGraph, oid) if issubclass(klass, (ROOT.TTree,)): return _get_helper(klass, self, self.getTree, oid) raise RuntimeError('unsupported type [%r]'%klass) # as we are sentenced to crawl through all these std::vector<str> # we might as well update our local cache... # first update histos oids = [n for n in self.getHists() if not n in self._py_cache.keys()] for name in oids: obj = _get_helper(ROOT.TH1, self, self.getHist, name, update_cache=False) if obj: # now try with real class klass = getattr(ROOT, obj.ClassName()) obj = _get_helper(klass, self, self.getHist, name) # then graphs ## FIXME: no 'ITHistSvc::getGraphs' method !! ## https://savannah.cern.ch/bugs/index.php?36379 ## oids = [n for n in self.getGraphs() if not n in self._py_cache.keys()] ## for name in oids: ## _get_helper(ROOT.TGraph, self, self.getGraph, name) # finally try ttrees oids = [n for n in self.getTrees() if not n in self._py_cache.keys()] for name in oids: _get_helper(ROOT.TTree, self, self.getTree, name) ## all done, crossing fingers return self._py_cache[oid] ITHistSvc.get = get del get def getitem(self, oid): return self.get(oid) ITHistSvc.__getitem__ = getitem del getitem def delitem(self, oid): if isinstance(oid, str): obj=self.get(oid) del self._py_cache[oid] assert self.deReg(oid).isSuccess(), \ "could not remove object [%r]"%oid return ITHistSvc.__delitem__ = delitem def setitem(self, k, v): return self.book(k, obj=v) ITHistSvc.__setitem__ = setitem del setitem ## ties some loose ends for n in ('Hist', 'Graph', 'Tree'): code = """\ def reg%s(self, oid, oid_type=None): if not (oid_type is None): return self.book(oid,obj=oid_type) if ITHistSvc._cpp_reg%s(self,oid).isSuccess(): # update py_cache return self.get(oid) err = ''.join(['invalid arguments oid=',repr(oid),' oid_type=', repr(oid_type)]) raise ValueError(err) ITHistSvc.reg%s = reg%s del reg%s""" % (n,n,n,n,n) exec code in globals(),locals() pass def load(self, oid, oid_type): """Helper method to load a given object `oid' from a stream, knowing its type. `oid_type' is a string whose value is either: - 'hist', to load any THx and TProfiles - 'tree', to load TTrees - 'graph', to load TGraph and TGraphErrors """ _allowed_values = ('hist','tree','graph') if not oid_type in _allowed_values: raise ValueError( 'oid_type (=%r) MUST be one of %r'%(oid_type, _allowed_values) ) return getattr(self, 'reg%s'%oid_type.capitalize())(oid) ITHistSvc.load = load del load ## -- ## 'dict-onization' of ITHistSvc for n in ('__contains__', '__iter__', '__len__', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'values'): code = """\ def %s(self, *args, **kw): return self._py_cache.%s(*args,**kw) ITHistSvc.%s = %s del %s""" % (n,n,n,n,n) exec code in globals(),locals() def pop(self, k): obj = self.get(k) assert self.deReg(obj).isSuccess(), \ "could not remove object [%r]"%k return obj ITHistSvc.pop = pop del pop def popitem(self): k = self.iterkeys().next() return (k, self.pop(k)) ITHistSvc.popitem = popitem del popitem ## ------------------------------ ## try to install ttree access enhancement try: from RootUtils.PyROOTFixes import enable_tree_speedups enable_tree_speedups() except ImportError: pass ## FIXME: would be nice... but somehow interferes with _py_cache property ## ## allow the use of the pythonized properties interface ## def __getattr__( self, attr ): ## try: from GaudiPython.Bindings import iProperty ## except ImportError: from gaudimodule import iProperty ## return getattr( iProperty('THistSvc', self), attr ) ## def __setattr__( self, attr, value ): ## try: from GaudiPython.Bindings import iProperty ## except ImportError: from gaudimodule import iProperty ## return setattr( iProperty('THistSvc', self), attr, value ) ## ITHistSvc.__getattr__ = __getattr__ ## ITHistSvc.__setattr__ = __setattr__ return ITHistSvc
def _py_init_THistSvc(): import cppyy # ITHistSvc bindings from dictionary _load_dict("libGaudiKernelDict") # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # retrieve the ITHistSvc class global ITHistSvc ITHistSvc = cppyy.gbl.ITHistSvc ROOT = _import_ROOT() @property def _py_cache(self): try: return self.__py_cache except AttributeError: self.__py_cache = dict() return self.__py_cache ITHistSvc._py_cache = _py_cache # save original regXYZ methods: we'll use some modified ones # to improve look-up time from python for n in ('Hist', 'Graph', 'Tree'): code = "ITHistSvc._cpp_reg%s = ITHistSvc.reg%s" % (n, n) exec(code, globals(), locals()) def book(self, oid, obj=None, *args, **kw): """book a histogram, profile or tree @param oid is the unique object identifier even across streams, ie: 'stream'+'id' @param obj either an already full-fledge constructed ROOT object or None (then `*args` or `**kw` need to be correctly setup) @param *args list of arguments to give to the constructor of the ROOT object one wants to book @param **kw a dictionary containing a key 'args' being the list of arguments to the constructor of the ROOT objects one wants to book examples: >>> th.book('/temp/1d/h1', 'TH1D', args=('h1','h1',100,0.,100.)) >>> th.book('/temp/1d/h2', ROOT.TH1D, args=('h2','h2',100,0.,100.)) >>> th.book('/temp/1d/h3', ROOT.TH1D, 'h3','h3',100,0.,100.) >>> th.book('/temp/1d/h4', ROOT.TH1D('h4','h4',100,0.,100.)) >>> th.book('/temp/1d/h5', obj=ROOT.TH1D('h5','h5',100,0.,100.)) >>> th.book('/temp/1d/h6', klass='TH1D', args=('h6','h6',100,0.,100.)) >>> th.book('/temp/tree/t1', ROOT.TTree('t1','t1')) >>> th.book('/temp/tree/t2', obj=ROOT.TTree('t2','t2')) >>> th.book('/temp/tree/t3', klass='TTree', args=('t3','t3')) """ _err = "please provide _either_ an already constructed ROOT object or"\ "a class name/class type (with appropriate arguments)" klass = kw.get('klass', None) assert not (obj is None and klass is None), _err assert not (obj is not None and klass is not None), _err if isinstance(obj, (str, type)): klass = obj obj = None if obj: if isinstance(obj, ROOT.TH1): # capture all of TH1x,TH2x,TH3x,TProfileXY meth = '_cpp_regHist' elif isinstance(obj, (ROOT.TGraph, )): meth = '_cpp_regGraph' elif isinstance(obj, (ROOT.TTree, )): meth = '_cpp_regTree' else: raise TypeError("invalid type '%r'" % type(obj)) if getattr(self, meth)(oid, obj).isSuccess(): self._py_cache[oid] = obj return obj raise RuntimeError('could not book object [%r]' % obj) if klass: if isinstance(klass, str): klass = getattr(ROOT, klass) if args: return self.book(oid, obj=klass(*args)) if kw and 'args' in kw: return self.book(oid, obj=klass(*kw['args'])) err = "invalid arguments: either provide a valid `*args` or "\ "a `**kw` containing a 'args' key" raise RuntimeError(err) raise RuntimeError("unforseen case: oid='%r' obj='%r' args='%r' " "kw='%r'" % (oid, obj, args, kw)) ITHistSvc.book = book def get(self, oid, klass=None): """retrieve an already booked ROOT object. If the object was booked on the C++ side, try to use the `klass` hint (the usual string or type) to find the object in the correct 'folder' (histograms, graphs or trees). If `klass` is None, then go through all the folders iteratively (slow) """ try: return self._py_cache[oid] except KeyError: pass def _get_helper(klass, hsvc, meth, oid, update_cache=True): import cppyy makeNullPtr = cppyy.libPyROOT.MakeNullPointer o = makeNullPtr(klass) if meth(oid, o).isSuccess(): if update_cache: hsvc._py_cache[oid] = o return o return if klass: if isinstance(klass, str): klass = getattr(ROOT, klass) if issubclass(klass, (ROOT.TH1, )): return _get_helper(klass, self, self.getHist, oid) if issubclass(klass, (ROOT.TGraph, )): return _get_helper(klass, self, self.getGraph, oid) if issubclass(klass, (ROOT.TTree, )): return _get_helper(klass, self, self.getTree, oid) raise RuntimeError('unsupported type [%r]' % klass) # as we are sentenced to crawl through all these std::vector<str> # we might as well update our local cache... # first update histos oids = [n for n in self.getHists() if n not in self._py_cache.keys()] for name in oids: obj = _get_helper(ROOT.TH1, self, self.getHist, name, update_cache=False) if obj: # now try with real class klass = getattr(ROOT, obj.ClassName()) obj = _get_helper(klass, self, self.getHist, name) # then graphs ## FIXME: no 'ITHistSvc::getGraphs' method !! ## https://savannah.cern.ch/bugs/index.php?36379 ## oids = [n for n in self.getGraphs() if not n in self._py_cache.keys()] ## for name in oids: ## _get_helper(ROOT.TGraph, self, self.getGraph, name) # finally try ttrees oids = [n for n in self.getTrees() if n not in self._py_cache.keys()] for name in oids: _get_helper(ROOT.TTree, self, self.getTree, name) ## all done, crossing fingers return self._py_cache[oid] ITHistSvc.get = get del get def getitem(self, oid): return self.get(oid) ITHistSvc.__getitem__ = getitem del getitem def delitem(self, oid): if isinstance(oid, str): self.get(oid) del self._py_cache[oid] assert self.deReg(oid).isSuccess(), \ "could not remove object [%r]"%oid return ITHistSvc.__delitem__ = delitem def setitem(self, k, v): return self.book(k, obj=v) ITHistSvc.__setitem__ = setitem del setitem ## ties some loose ends for n in ('Hist', 'Graph', 'Tree'): code = """\ def reg%s(self, oid, oid_type=None): if not (oid_type is None): return self.book(oid,obj=oid_type) if ITHistSvc._cpp_reg%s(self,oid).isSuccess(): # update py_cache return self.get(oid) err = ''.join(['invalid arguments oid=',repr(oid),' oid_type=', repr(oid_type)]) raise ValueError(err) ITHistSvc.reg%s = reg%s del reg%s""" % (n, n, n, n, n) exec(code, globals(), locals()) pass def load(self, oid, oid_type): """Helper method to load a given object `oid' from a stream, knowing its type. `oid_type' is a string whose value is either: - 'hist', to load any THx and TProfiles - 'tree', to load TTrees - 'graph', to load TGraph and TGraphErrors """ _allowed_values = ('hist', 'tree', 'graph') if oid_type not in _allowed_values: raise ValueError('oid_type (=%r) MUST be one of %r' % (oid_type, _allowed_values)) return getattr(self, 'reg%s' % oid_type.capitalize())(oid) ITHistSvc.load = load del load ## -- ## 'dict-onization' of ITHistSvc for n in ('__contains__', '__iter__', '__len__', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'values'): code = """\ def %s(self, *args, **kw): return self._py_cache.%s(*args,**kw) ITHistSvc.%s = %s del %s""" % (n, n, n, n, n) exec(code, globals(), locals()) def pop(self, k): obj = self.get(k) assert self.deReg(obj).isSuccess(), \ "could not remove object [%r]"%k return obj ITHistSvc.pop = pop del pop def popitem(self): k = self.iterkeys().next() return (k, self.pop(k)) ITHistSvc.popitem = popitem del popitem ## ------------------------------ ## FIXME: would be nice... but somehow interferes with _py_cache property ## ## allow the use of the pythonized properties interface ## def __getattr__( self, attr ): ## try: from GaudiPython.Bindings import iProperty ## except ImportError: from gaudimodule import iProperty ## return getattr( iProperty('THistSvc', self), attr ) ## def __setattr__( self, attr, value ): ## try: from GaudiPython.Bindings import iProperty ## except ImportError: from gaudimodule import iProperty ## return setattr( iProperty('THistSvc', self), attr, value ) ## ITHistSvc.__getattr__ = __getattr__ ## ITHistSvc.__setattr__ = __setattr__ return ITHistSvc
# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration # @author: Sebastien Binet <*****@*****.**> # @date: April 2007 # # __version__ = "$Revision: 1.8 $" __author__ = "Sebastien Binet <*****@*****.**>" __all__ = [ 'CpuHdr', 'IoHdr', 'MemHdr', 'PersHdr', 'CpuData', 'IoData', 'MemData', #'PersData', ] import cppyy cppyy.loadDictionary( 'libPerfMonEventDict' ) PerfMon = cppyy.makeNamespace( 'PerfMon' ) CpuHdr = PerfMon.CpuHdr IoHdr = PerfMon.IoHdr MemHdr = PerfMon.MemHdr PersHdr = PerfMon.PersHdr CpuData = PerfMon.CpuData IoData = PerfMon.IoData MemData = PerfMon.MemData #PersData = PerfMon.PersData
#!/usr/bin/env python # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration #### This is the dbgHLTResult class for the Debug Stream event analysis from __future__ import print_function from PyUtils import RootUtils ROOT = RootUtils.import_root() from ROOT import std import cppyy from CLIDComps.clidGenerator import clidGenerator clidg = clidGenerator("") cppyy.makeNamespace('HLT') ActualHLTResult = cppyy.makeClass('HLT::HLTResult') stringSerializer = cppyy.makeClass('StringSerializer')() class hltResult(ActualHLTResult): def __init__(self): super(hltResult, self).__init__() self.as_int_v = std.vector('unsigned int')() def load(self, rob): self.nav_payload = [] data = list(rob.rod_data()) self.as_int_v.clear()
def _setup(): import cppyy # StoreGate bindings from dictionary cppyy.loadDictionary( "libAthenaPythonDict" ) # for clidsvc cppyy.loadDictionary( "libStoreGateBindingsDict" ) # for storegatesvc cppyy.loadDictionary( "libStoreGateBindings" ) # not linked from libStoreGateBindingsDict in ROOT6 # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') _ath= cppyy.makeNamespace('AthenaInternal') # ROOT6 workaround, kick the loading of headers _ath.ROOT6_AthenaPython_WorkAround_Dummy _ath.ROOT6_StoreGateBindings_WorkAround_Dummy # end workaround global py_retrieve py_retrieve = cppyy.gbl.AthenaInternal.retrieveObjectFromStore global py_record py_record = cppyy.gbl.AthenaInternal.recordObjectToStore global py_sg_contains py_sg_contains = cppyy.gbl.AthenaInternal.py_sg_contains global py_sg_getitem py_sg_getitem = cppyy.gbl.AthenaInternal.py_sg_getitem # retrieve the StoreGateSvc class global StoreGate, StoreGateSvc StoreGateSvc = cppyy.gbl.StoreGateSvc StoreGate = cppyy.gbl.StoreGate # add specialized retrieve method def retrieve( self, klass, key = None ): ret = py_retrieve( self, klass, key ) if ret and hasattr(ret,'setStore') and not ret.hasStore(): if not hasattr(ret,'trackIndices') or ret.trackIndices(): if py_sg_contains (self, 'SG::IConstAuxStore', key + 'Aux.'): aux = py_retrieve (self, 'SG::IConstAuxStore', key + 'Aux.') ret.setStore (aux) return ret StoreGateSvc.retrieve = retrieve # add specialized record method def record( self, obj, key, allowMods=True, resetOnly=True, noHist=False ): return py_record( self, obj, key, allowMods, resetOnly, noHist ) StoreGateSvc.record = record # add specialized contains method def contains( self, klass_or_clid, key ): print "---- StoreGateSvc.contains() ", klass_or_clid, key if isinstance(klass_or_clid, str): try: clid = int(klass_or_clid) klass = self._pyclidsvc.typename(clid) except ValueError: klass = str(klass_or_clid) pass elif isinstance(klass_or_clid, (int, long)): klass = self._pyclidsvc.typename(klass_or_clid) elif isinstance(klass_or_clid, type): klass = klass_or_clid.__name__ else: raise TypeError( 'argument 2 must be a typename, a clid or a type (got %r)' % type(klass_or_clid)) return py_sg_contains( self, klass, key ) StoreGateSvc.contains = contains # dict-pythonization of storegate: __setitem__ def __setitem__ (self, key, obj): return py_record( self, obj, key, True, True, False ) StoreGateSvc.__setitem__ = __setitem__ # dict-pythonization of storegate: __getitem__ def __getitem__ (self, key): try: ret = py_sg_getitem(self, key) except LookupError,err: raise KeyError(str(err)) if ret and hasattr(ret,'setStore') and not ret.hasStore(): if not hasattr(ret,'trackIndices') or ret.trackIndices(): if py_sg_contains (self, 'SG::IConstAuxStore', key + 'Aux.'): aux = py_retrieve (self, 'SG::IConstAuxStore', key + 'Aux.') ret.setStore (aux) return ret
def execute(self): self.msg.info('running execute...') self.msg.info('dumping [%s] content', self.sg.name()) self.msg.info(self.sg.dump()) listOfFolders = [ "/LAR/BadChannels/BadChannels", "/LAR/BadChannels/MissingFEBs" ] iSelectedFolder = LArBadChannelBrowserTools.ChooseOptionFromList( "Folder list : ", "", "", listOfFolders, +1, False, {}) if iSelectedFolder == 1: self.dbFolderName = "/LAR/BadChannels/BadChannels" self.folderId = BAD_CHANNEL else: self.dbFolderName = "/LAR/BadChannels/MissingFEBs" self.folderId = MISSING_FEB # ----------------------------------------------------------- # Browse database a first time to catch tags name and IOV listOfTags, dictIOV, self.iNbCoolChannel = self.GetTagsAndIOVFromDatabase( self.dbFolderName) # ----------------------------------------------------------- # Create an objec instance for all interfaced python classes LArBadChannelDBTools = cppyy.makeNamespace('LArBadChannelDBTools') self.nspace_LArBadChannelDBTools = LArBadChannelDBTools() self.class_LArBadChannel = cppyy.makeClass('LArBadChannel') self.class_HWIdentifier = cppyy.makeClass('HWIdentifier') self.class_LArBadChanBitPacking = cppyy.makeClass( "LArBadChanBitPacking") if self.folderId == BAD_CHANNEL: self.dbBrowserBadChan = LArDBFolderBrowser_BadChan.LArDBFolderBrowser_BadChan( self.nspace_LArBadChannelDBTools, self.class_LArBadChanBitPacking, self.class_LArBadChannel, self.class_HWIdentifier, self.onlineID, self.larCablingSvc, self.msg) elif self.folderId == MISSING_FEB: self.dbBrowserMissingFeb = LArDBFolderBrowser_MissingFEBs.LArDBFolderBrowser_MissingFEBs( self.nspace_LArBadChannelDBTools, self.class_LArBadChanBitPacking, self.class_LArBadChannel, self.class_HWIdentifier, self.onlineID, self.larCablingSvc, ) # ----------------------------------------------------------- # Select the tag iSelectedTag = LArBadChannelBrowserTools.ChooseOptionFromList( "Tag list : ", "", "", listOfTags, +1, False, {}) if iSelectedTag < 1: return self.selectedTag = listOfTags[iSelectedTag - 1] # ----------------------------------------------------------- # Construct IOV list based on selected tag self.tagIOVDict = {} for iChannel in range(0, self.iNbCoolChannel): self.tagIOVDict[iChannel] = dictIOV[ self.selectedTag][iChannel][-1][0] # ----------------------------------------------------------- # Show database content self.channelNameDict = self.ReadObjectsFromDatabase( self.dbFolderName, self.selectedTag, self.tagIOVDict) if self.folderId == BAD_CHANNEL: self.dbBrowserBadChan.BadChan_SetChannelNameDict( self.channelNameDict) # sMessage="IOV : "+str(self.tagIOVDict)+" / channel : "+str(self.channelNameDict) # LArBadChannelBrowserTools.TypeEnterToContinue(sMessage) # ------------------------------------------------------------------------------------- # # LOOP OVER COOL CHANNEL MODIFICATIONS # # ------------------------------------------------------------------------------------- bEndOfCoolChannelModification = False while not bEndOfCoolChannelModification: # ----------------------------------------------------------- # MISSING_FEB : go to correction menu if self.folderId == MISSING_FEB: # coolChan = 0 self.dbBrowserMissingFeb.MissingFeb_DisplayMissingFeb(coolChan) endOfModif = self.dbBrowserMissingFeb.MissingFeb_ModifyMissingFeb( coolChan) if endOfModif == 'q': sDBName = os.environ["PWD"] + "/MissingFebUpdate.db" if os.path.isfile(sDBName): os.remove(sDBName) dbstring = "sqlite://;schema=" + sDBName + ";dbname=BADCHAN" self.dbBrowserMissingFeb.MissingFeb_SaveMissingFebCorrectionsToDatabase( dbstring, self.dbSvc, self.dbFolderName, self.selectedTag) self.dbBrowserMissingFeb.MissingFeb_CheckSavedDatabaseContent( dbstring, self.dbSvc, self.dbFolderName, self.selectedTag) return # ----------------------------------------------------------- # Select Cool channel sCoolChannelMenuDict = [("s", "(summary)"), ("a", "(abort)"), ("q", "(save and quit)")] listCoolChannel = [] for i in range(0, self.iNbCoolChannel): listCoolChannel.append(self.channelNameDict[i] + " (IOV " + str(self.tagIOVDict[i]) + ")") repCoolChan = LArBadChannelBrowserTools.ChooseOptionFromList( "Cool channel list : ", "", "", listCoolChannel, 0, False, sCoolChannelMenuDict) if repCoolChan == "a": iAbortConfirmation = LArBadChannelBrowserTools.YesNoQuestion( "Are you sure you want to quit ? ") if iAbortConfirmation == 1: return elif repCoolChan == "q": print(" SAUVEGARDE FINALE") if self.folderId == BAD_CHANNEL: sDBName = os.environ["PWD"] + "/BadChannelUpdate.db" if os.path.isfile(sDBName): os.remove(sDBName) dbstring = "sqlite://;schema=" + sDBName + ";dbname=BADCHAN" self.dbBrowserBadChan.BadChan_SaveBadChannelCorrectionsToDatabase( dbstring, self.dbSvc, self.dbFolderName, self.selectedTag) self.dbBrowserBadChan.BadChan_CheckSavedDatabaseContent( dbstring, self.dbSvc, self.dbFolderName, self.selectedTag) bEndOfCoolChannelModification = True elif repCoolChan == "s": for i in range(0, self.iNbCoolChannel): self.dbBrowserBadChan.BadChan_ShowBadChannelCorrectionsSummary( i) else: # ----------------------------------------------------------- # Display selected Cool channel coolChan = int(repCoolChan) if self.folderId == BAD_CHANNEL: self.dbBrowserBadChan.BadChan_DisplayBadChanEntry(coolChan) self.dbBrowserBadChan.BadChan_ModifyLarBadChannel(coolChan)
# # # $Revision$ # Last modification $Date$ # by $Author$ # ============================================================================= """ Module with decoration of histo&text objects for efficient use in python """ # ============================================================================= __version__ = "$Revision$" __author__ = "Vanya BELYAEV [email protected]" __date__ = "2011-06-07" __all__ = () # ============================================================================= import ROOT, cppyy ## attention here!! cpp = cppyy.makeNamespace('') VE = cpp.Gaudi.Math.ValueWithError # # ============================================================================= # logging # ============================================================================= from Ostap.Logger import getLogger if '__main__' == __name__: logger = getLogger('Ostap.HTextDeco') else: logger = getLogger(__name__) # ============================================================================= logger.debug('Some useful decorations for Histo&Text objects') # ============================================================================= ## further decoration try: import GaudiPython.HistoUtils logger.debug('Histogram utilities from GaudiPython.HistoUtils')
def _setup(): import cppyy # StoreGate bindings from dictionary cppyy.loadDictionary("libAthenaPythonDict") # for clidsvc cppyy.loadDictionary("libStoreGateBindingsDict") # for storegatesvc cppyy.loadDictionary("libStoreGateBindings" ) # not linked from libStoreGateBindingsDict in ROOT6 # make sure the global C++ namespace has been created gbl = cppyy.makeNamespace('') # noqa: F841 _ath = cppyy.makeNamespace('AthenaInternal') # ROOT6 workaround, kick the loading of headers _ath.ROOT6_AthenaPython_WorkAround_Dummy _ath.ROOT6_StoreGateBindings_WorkAround_Dummy # end workaround global py_retrieve py_retrieve = cppyy.gbl.AthenaInternal.retrieveObjectFromStore global py_record py_record = cppyy.gbl.AthenaInternal.recordObjectToStore global py_sg_contains py_sg_contains = cppyy.gbl.AthenaInternal.py_sg_contains global py_sg_getitem py_sg_getitem = cppyy.gbl.AthenaInternal.py_sg_getitem # retrieve the StoreGateSvc class global StoreGate, StoreGateSvc StoreGateSvc = cppyy.gbl.StoreGateSvc StoreGate = cppyy.gbl.StoreGate # add specialized retrieve method def retrieve(self, klass, key=None): ret = py_retrieve(self, klass, key) if ret and hasattr(ret, 'setStore') and not ret.hasStore(): if not hasattr(ret, 'trackIndices') or ret.trackIndices(): if py_sg_contains(self, 'SG::IConstAuxStore', key + 'Aux.'): aux = py_retrieve(self, 'SG::IConstAuxStore', key + 'Aux.') ret.setStore(aux) return ret StoreGateSvc.retrieve = retrieve # add specialized record method def record(self, obj, key, allowMods=True, resetOnly=True, noHist=False): return py_record(self, obj, key, allowMods, resetOnly, noHist) StoreGateSvc.record = record # add specialized contains method def contains(self, klass_or_clid, key): print("---- StoreGateSvc.contains() ", klass_or_clid, key) from builtins import int if isinstance(klass_or_clid, str): try: clid = int(klass_or_clid) klass = self._pyclidsvc.typename(clid) except ValueError: klass = str(klass_or_clid) pass elif isinstance(klass_or_clid, int): klass = self._pyclidsvc.typename(klass_or_clid) elif isinstance(klass_or_clid, type): klass = klass_or_clid.__name__ else: raise TypeError( 'argument 2 must be a typename, a clid or a type (got %r)' % type(klass_or_clid)) return py_sg_contains(self, klass, key) StoreGateSvc.contains = contains # dict-pythonization of storegate: __setitem__ def __setitem__(self, key, obj): return py_record(self, obj, key, True, True, False) StoreGateSvc.__setitem__ = __setitem__ # dict-pythonization of storegate: __getitem__ def __getitem__(self, key): try: ret = py_sg_getitem(self, key.encode()) except LookupError as err: raise KeyError(str(err)) if ret and hasattr(ret, 'setStore') and not ret.hasStore(): if not hasattr(ret, 'trackIndices') or ret.trackIndices(): if py_sg_contains(self, 'SG::IConstAuxStore', key + 'Aux.'): aux = py_retrieve(self, 'SG::IConstAuxStore', key + 'Aux.') ret.setStore(aux) return ret StoreGateSvc.__getitem__ = __getitem__ # dict-pythonization of storegate: __len__ def __len__(self): return len(self.keys()) StoreGateSvc.__len__ = __len__ # make dump print, rather than return string def dump(self, fd=None): if fd is None: import sys fd = sys.stdout print(self.__class__._dump(self), file=fd) StoreGateSvc._dump = StoreGateSvc.dump StoreGateSvc.dump = dump # allow the use of the pythonized properties interface def __getattr__(self, attr): try: from GaudiPython.Bindings import iProperty except ImportError: from gaudimodule import iProperty return getattr(iProperty("StoreGateSvc", self), attr) def __setattr__(self, attr, value): try: from GaudiPython.Bindings import iProperty except ImportError: from gaudimodule import iProperty return setattr(iProperty("StoreGateSvc", self), attr, value) StoreGateSvc.__getattr__ = __getattr__ StoreGateSvc.__setattr__ = __setattr__ import AthenaPython.PyAthena as PyAthena StoreGateSvc._pyclidsvc = PyAthena.py_svc('ClassIDSvc') def keys(self, clid=None, allKeys=False): """return the list of keys for a given CLID (int, type or class_name) if clid is None, it will return the list of all keys. When 'allKeys' is True it will also return the key aliases. """ if isinstance(clid, str): clid = self._pyclidsvc.clid(clid) if isinstance(clid, type): clid = self._pyclidsvc.clid(clid.__name__) if clid is None: return [p.name() for p in self.proxies()] return list(self._cpp_keys(clid, allKeys)) StoreGateSvc._cpp_keys = StoreGateSvc.keys StoreGateSvc.keys = keys return