class std: stlclasses = ( 'complex', 'exception', 'pair', \ 'deque', 'list', 'queue', 'stack', 'vector', 'map', 'multimap', 'set', 'multiset' ) for name in stlclasses: exec '%(name)s = Template( "std::%(name)s" )' % {'name': name} string = _root.MakeRootClass('string')
class std(object): __metaclass__ = _stdmeta stlclasses = ( 'complex', 'pair', \ 'deque', 'list', 'queue', 'stack', 'vector', 'map', 'multimap', 'set', 'multiset' ) for name in stlclasses: locals()[name] = Template("std::%s" % name) string = _root.MakeRootClass('string')
class std(object): __metaclass__ = _stdmeta stlclasses = ( 'complex', 'pair', \ 'deque', 'list', 'queue', 'stack', 'vector', 'map', 'multimap', 'set', 'multiset' ) for name in stlclasses: locals()[name] = Template('std::%s' % name) _backend.gROOT.ProcessLine("#include <iostream>") string = _backend.MakeRootClass('string')
def __finalSetup(self): # prevent this method from being re-entered through the gROOT wrapper self.__dict__['gROOT'] = _root.gROOT # switch to running gettattr/setattr self.__class__.__getattr__ = self.__class__.__getattr2 del self.__class__.__getattr2 self.__class__.__setattr__ = self.__class__.__setattr2 del self.__class__.__setattr2 # normally, you'll want a ROOT application; don't init any further if # one pre-exists from some C++ code somewhere hasargv = hasattr(sys, 'argv') if hasargv and PyConfig.IgnoreCommandLineOptions: argv = sys.argv sys.argv = [] appc = _root.MakeRootClass('PyROOT::TPyROOTApplication') if appc.CreatePyROOTApplication(): appc.InitROOTGlobals() appc.InitCINTMessageCallback() appc.InitROOTMessageCallback() if hasargv and PyConfig.IgnoreCommandLineOptions: sys.argv = argv # must be called after gApplication creation: if '__IPYTHON__' in __builtins__: # IPython's FakeModule hack otherwise prevents usage of python from CINT _root.gROOT.ProcessLine('TPython::Exec( "" )') sys.modules['__main__'].__builtins__ = __builtins__ # custom logon file (must be after creation of ROOT globals) if hasargv and not '-n' in sys.argv: rootlogon = os.path.expanduser('~/.rootlogon.py') if os.path.exists(rootlogon): # could also have used execfile, but import is likely to give fewer surprises import imp imp.load_module('rootlogon', open(rootlogon, 'r'), rootlogon, ('.py', 'r', 1)) del imp else: # if the .py version of rootlogon exists, the .C is ignored (the user can # load the .C from the .py, if so desired) # system logon, user logon, and local logon (skip Rint.Logon) name = '.rootlogon.C' logons = [ os.path.join(str(self.gRootDir), 'etc', 'system' + name), os.path.expanduser(os.path.join('~', name)) ] if logons[-1] != os.path.join(os.getcwd(), name): logons.append(name) for rootlogon in logons: if os.path.exists(rootlogon): appc.ExecuteFile(rootlogon) del rootlogon, logons # root thread, if needed, to prevent GUIs from starving, as needed if self.PyConfig.StartGuiThread and \ not ( self.keeppolling or _root.gROOT.IsBatch() ): import threading self.__dict__['keeppolling'] = 1 self.__dict__[ 'PyGUIThread' ] = \ threading.Thread( None, _processRootEvents, None, ( self, ) ) def _finishSchedule(ROOT=self): import threading if threading.currentThread() != self.PyGUIThread: while self.PyConfig.GUIThreadScheduleOnce: self.PyGUIThread.join(0.1) self.PyGUIThread.finishSchedule = _finishSchedule self.PyGUIThread.setDaemon(1) self.PyGUIThread.start() # store already available ROOT objects to prevent spurious lookups for name in self.module.__pseudo__all__ + _memPolicyAPI + _sigPolicyAPI: self.__dict__[name] = getattr(_root, name) for name in std.stlclasses: setattr(_root, name, getattr(std, name)) # set the display hook sys.displayhook = _displayhook
def __init__(self, klass, func): c = _root.MakeRootClass(klass) self.func = getattr(c, func)
def __getattr__(cls, attr): # for non-templated classes in std klass = _root.MakeRootClass(attr, cls) setattr(cls, attr, klass) return klass
_root.gPad = _ExpandMacroFunction("TVirtualPad", "Pad") _root.gVirtualX = _ExpandMacroFunction("TVirtualX", "Instance") _root.gDirectory = _ExpandMacroFunction("TDirectory", "CurrentDirectory") _root.gFile = _ExpandMacroFunction("TFile", "CurrentFile") _root.gInterpreter = _ExpandMacroFunction("TInterpreter", "Instance") ### special case pythonization -------------------------------------------------- def _TTree__iter__(self): i = 0 while self.GetEntry(i): yield self # TODO: not sure how to do this w/ C-API ... i += 1 _root.MakeRootClass("TTree").__iter__ = _TTree__iter__ ### RINT command emulation ------------------------------------------------------ def _excepthook(exctype, value, traceb): # catch syntax errors only (they contain the full line) if isinstance(value, SyntaxError) and value.text: cmd, arg = split(value.text[:-1]) # mimic ROOT/CINT commands if cmd == '.q': sys.exit(0) elif cmd == '.?' or cmd == '.help': sys.stdout.write("""PyROOT emulation of CINT commands. All emulated commands must be preceded by a . (dot). ===========================================================================
def makeClass(name): return _backend.MakeRootClass(name)
ROOT.gSystem.Load("libDelphes") ##################################################### ### Definition of the string conversion methods ### ##################################################### def _Event__str__(self): theString = "Event number %i\n" % self.Number theString += "Read in %f and processed in %f.\n" % (self.ReadTime, self.ProcTime) return theString if hasattr(_root, "MakeRootClass"): _root.MakeRootClass("Event").__str__ = _Event__str__ else: _root.CreateScopeProxy("Event").__str__ = _Event__str__ def _LHCOEvent__str__(self): theString = "Trigger word: %b\n" % self.Trigger return theString if hasattr(_root, "MakeRootClass"): _root.MakeRootClass("LHCOEvent").__str__ = _LHCOEvent__str__ else: _root.CreateScopeProxy("LHCOEvent").__str__ = _LHCOEvent__str__
def makeClass(name): return libPyROOT.MakeRootClass(name)
needsGlobal = ( 0 <= string.find( sys.platform, 'linux' ) ) or\ ( 0 <= string.find( sys.platform, 'sunos' ) ) if needsGlobal: # change dl flags to load dictionaries from pre-linked .so's dlflags = sys.getdlopenflags() sys.setdlopenflags(0x100 | 0x2) # RTLD_GLOBAL | RTLD_NOW import libPyROOT # reset dl flags if needed if needsGlobal: sys.setdlopenflags(dlflags) del needsGlobal libPyROOT.SetMemoryPolicy(libPyROOT.kMemoryStrict) libPyROOT.MakeRootClass('PyROOT::TPyROOTApplication').InitCINTMessageCallback() #--- Enable Autoloading ignoring possible error for the time being try: libPyROOT.gInterpreter.EnableAutoLoading() except: pass #--- Load CINT dictionaries for STL classes first before other "Reflex" dictionaries # are loaded. The Reflex once are protected against the class being there #libPyROOT.gROOT.ProcessLine('int sav = gErrorIgnoreLevel; gErrorIgnoreLevel = 2001;') #for c in ('vector', 'list', 'set', 'deque') : # if libPyROOT.gSystem.Load('lib%sDict' % c ) == -1 : # warnings.warn('CINT dictionary for STL class %s could not be loaded' % c ) #libPyROOT.gROOT.ProcessLine('gErrorIgnoreLevel = sav;')
def __getattr__( cls, name ): # for non-templated classes in std klass = _backend.MakeRootClass( name, cls ) setattr( cls, name, klass ) return klass
def __finalSetup( self ): # prevent this method from being re-entered through the gROOT wrapper self.__dict__[ 'gROOT' ] = _root.gROOT # switch to running gettattr/setattr self.__class__.__getattr__ = self.__class__.__getattr2 del self.__class__.__getattr2 self.__class__.__setattr__ = self.__class__.__setattr2 del self.__class__.__setattr2 # normally, you'll want a ROOT application; don't init any further if # one pre-exists from some C++ code somewhere hasargv = hasattr( sys, 'argv' ) if hasargv and PyConfig.IgnoreCommandLineOptions: argv = sys.argv sys.argv = [] appc = _root.MakeRootClass( 'PyROOT::TPyROOTApplication' ) if appc.CreatePyROOTApplication(): appc.InitROOTGlobals() # TODO Cling equivalent needed: appc.InitCINTMessageCallback(); appc.InitROOTMessageCallback(); if hasargv and PyConfig.IgnoreCommandLineOptions: sys.argv = argv # must be called after gApplication creation: if '__IPYTHON__' in __builtins__: # IPython's FakeModule hack otherwise prevents usage of python from Cling (TODO: verify necessity) _root.gROOT.ProcessLine( 'TPython::Exec( "" );' ) sys.modules[ '__main__' ].__builtins__ = __builtins__ # special case for cout (backwards compatibility) if hasattr( std, '__1' ): self.__dict__[ 'cout' ] = getattr( std, '__1' ).cout # custom logon file (must be after creation of ROOT globals) if hasargv and not '-n' in sys.argv: rootlogon = os.path.expanduser( '~/.rootlogon.py' ) if os.path.exists( rootlogon ): # could also have used execfile, but import is likely to give fewer surprises import imp imp.load_module( 'rootlogon', open( rootlogon, 'r' ), rootlogon, ('.py','r',1) ) del imp else: # if the .py version of rootlogon exists, the .C is ignored (the user can # load the .C from the .py, if so desired) # system logon, user logon, and local logon (skip Rint.Logon) name = '.rootlogon.C' logons = [ os.path.join( str(self.gRootDir), 'etc', 'system' + name ), os.path.expanduser( os.path.join( '~', name ) ) ] if logons[-1] != os.path.join( os.getcwd(), name ): logons.append( name ) for rootlogon in logons: if os.path.exists( rootlogon ): appc.ExecuteFile( rootlogon ) del rootlogon, logons # use either the input hook or thread to send events to GUIs if self.PyConfig.StartGuiThread and \ not ( self.keeppolling or _root.gROOT.IsBatch() ): if self.PyConfig.StartGuiThread == 'inputhook' or\ _root.gSystem.InheritsFrom( 'TMacOSXSystem' ): # new, PyOS_InputHook based mechanism if PyConfig.GUIThreadScheduleOnce: for guicall in PyConfig.GUIThreadScheduleOnce: guicall() PyConfig.GUIThreadScheduleOnce = [] _root.InstallGUIEventInputHook() else: # original, threading based approach import threading self.__dict__[ 'keeppolling' ] = 1 self.__dict__[ 'PyGUIThread' ] = \ threading.Thread( None, _processRootEvents, None, ( self, ) ) def _finishSchedule( ROOT = self ): import threading if threading.currentThread() != self.PyGUIThread: while self.PyConfig.GUIThreadScheduleOnce: self.PyGUIThread.join( 0.1 ) self.PyGUIThread.finishSchedule = _finishSchedule self.PyGUIThread.setDaemon( 1 ) self.PyGUIThread.start() # store already available ROOT objects to prevent spurious lookups for name in self.module.__pseudo__all__ + _memPolicyAPI + _sigPolicyAPI: self.__dict__[ name ] = getattr( _root, name ) # the macro NULL is not available from Cling globals, but might be useful setattr( _root, 'NULL', 0 ) for name in std.stlclasses: setattr( _root, name, getattr( std, name ) ) # set the display hook sys.displayhook = _displayhook
# GenEventInfoProduct def _GenEventInfoProduct__str__(self): theString = " alphaQCD=%f; alphaQED=%f" % (self.alphaQCD(), self.alphaQED()) theString += " qScale=%f\n" % self.qScale() theString += " signalProcessID: %d\n" % self.signalProcessID() theString += " MC weight: %d\n" % self.weight() for w in range(self.weights().size()): theString += " MC weight from list: %f\n" % self.weights()[w] return theString ROOT.GenEventInfoProduct.__str__ = MethodType(_GenEventInfoProduct__str__, None, ROOT.GenEventInfoProduct) ##################################################### ### Definition of additional ROOT methods ### ##################################################### def _lorentzVector__str__(self): theString = "(pt, eta, phi) = (%f,%f,%f)\n" % (self.Pt(), self.Eta(), self.Phi()) theString += "mass = %f, p = %f, mt = %f\n" % (self.M(), self.P(), self.Mt()) return theString _root.MakeRootClass("TLorentzVector").__str__ = _lorentzVector__str__