Beispiel #1
0
    def test01_size_mapping(self):
        """Use composites to map GetSize() onto buffer returns"""

        import cppyy

        exp_pyroot = self.exp_pyroot

        def set_size(self, buf):
            if exp_pyroot:
                buf.reshape((self.GetN(), ))
            else:
                buf.SetSize(self.GetN())
            return buf

        if exp_pyroot:
            cppyy.py.add_pythonization(
                cppyy.py.compose_method("pythonizables::MyBufferReturner$",
                                        "Get[XY]$", set_size))
        else:
            cppyy.add_pythonization(
                cppyy.compose_method("pythonizables::MyBufferReturner$",
                                     "Get[XY]$", set_size))

        bsize, xval, yval = 3, 2, 5
        m = cppyy.gbl.pythonizables.MyBufferReturner(bsize, xval, yval)

        x = m.GetX()
        assert len(x) == bsize
        assert list(x) == list(map(lambda x: x * xval, range(bsize)))

        y = m.GetY()
        assert len(y) == bsize
        assert list(y) == list(map(lambda x: x * yval, range(bsize)))
    def test01_size_mapping(self):
        """Use composites to map GetSize() onto buffer returns"""

        import cppyy

        def set_size(self, buf):
            buf.SetSize(self.GetN())
            return buf

        cppyy.add_pythonization(
            cppyy.compose_method('MyBufferReturner$', 'Get[XY]$', set_size))

        m = cppyy.gbl.MyBufferReturner
    def test01_size_mapping(self):
        """Use composites to map GetSize() onto buffer returns"""

        import cppyy

        def set_size(self, buf):
            buf.SetSize(self.GetN())
            return buf

        cppyy.add_pythonization(
            cppyy.compose_method("pythonizables::MyBufferReturner$", "Get[XY]$", set_size))

        bsize, xval, yval = 3, 2, 5
        m = cppyy.gbl.pythonizables.MyBufferReturner(bsize, xval, yval)

        x = m.GetX()
        assert len(x) == bsize
        assert list(x) == map(lambda x: x*xval, range(bsize))

        y = m.GetY()
        assert len(y) == bsize
        assert list(y) == map(lambda x: x*yval, range(bsize))
Beispiel #4
0
    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.CreateScopeProxy('PyROOT::TPyROOTApplication')
        if (not _builtin_cppyy
                and appc.CreatePyROOTApplication()) or _builtin_cppyy:
            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 _is_ipython:
            # 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(cppyy.gbl.std, '__1'):
            attr_1 = getattr(cppyy.gbl.std, '__1')
            if hasattr(attr_1, 'cout'):
                self.__dict__['cout'] = attr_1.cout

    # python side pythonizations (should live in their own file, if we get many)

        def set_size(self, buf):
            buf.SetSize(self.GetN())
            return buf

    # TODO: add pythonization API to pypy-c

        if not PYPY_CPPYY_COMPATIBILITY_FIXME:
            cppyy.add_pythonization(
                cppyy.compose_method("^TGraph(2D)?$|^TGraph.*Errors$",
                                     "GetE?[XYZ]$", set_size))
            gRootDir = self.gRootDir
        else:
            gRootDir = _root.gRootDir

    # custom logon file (must be after creation of ROOT globals)
        if hasargv and not '-n' in sys.argv and not PyConfig.DisableRootLogon:
            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.TROOT.GetEtcDir()), '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 _is_ipython and 'IPython' in sys.modules and sys.modules[
                    'IPython'].version_info[0] >= 5:
                from IPython.terminal import pt_inputhooks

                def _inputhook(context):
                    while not context.input_is_ready():
                        _root.gSystem.ProcessEvents()

                pt_inputhooks.register('ROOT', _inputhook)
                get_ipython().run_line_magic('gui', 'ROOT')
            elif 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)

        # TODO: is the following still necessary? Note: dupe of classes in cppyy.py
        for name in ('complex', 'pair', 'deque', 'list', 'queue', 'stack',
                     'vector', 'map', 'multimap', 'set', 'multiset'):
            setattr(_root, name, getattr(cppyy.gbl.std, name))

    # set the display hook
        sys.displayhook = _displayhook

        # manually load libMathCore, for example to obtain gRandom
        # This can be removed once autoloading on selected variables is available
        _root.gSystem.Load("libMathCore")
Beispiel #5
0
   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.CreateScopeProxy( 'PyROOT::TPyROOTApplication' )
      if (not _builtin_cppyy and appc.CreatePyROOTApplication()) or _builtin_cppyy:
            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 _is_ipython:
       # 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( cppyy.gbl.std, '__1' ):
         attr_1 = getattr( cppyy.gbl.std, '__1' )
         if hasattr( attr_1, 'cout' ):
            self.__dict__[ 'cout' ] = attr_1.cout

    # python side pythonizations (should live in their own file, if we get many)
      def set_size(self, buf):
         buf.SetSize(self.GetN())
         return buf

    # TODO: add pythonization API to pypy-c
      if not PYPY_CPPYY_COMPATIBILITY_FIXME:
         cppyy.add_pythonization(
            cppyy.compose_method("^TGraph(2D)?$|^TGraph.*Errors$", "GetE?[XYZ]$", set_size))
         gRootDir = self.gRootDir
      else:
         gRootDir = _root.gRootDir

    # custom logon file (must be after creation of ROOT globals)
      if hasargv and not '-n' in sys.argv and not PyConfig.DisableRootLogon:
         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.TROOT.GetEtcDir()), '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 _is_ipython and 'IPython' in sys.modules and sys.modules['IPython'].version_info[0] >= 5 :
            from IPython.terminal import pt_inputhooks
            import time
            def _inputhook(context):
               while not context.input_is_ready():
                  _root.gSystem.ProcessEvents()  
                  time.sleep( 0.01 )
            pt_inputhooks.register('ROOT',_inputhook)
            if get_ipython() : get_ipython().run_line_magic('gui', 'ROOT')
         elif 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 )

    # TODO: is the following still necessary? Note: dupe of classes in cppyy.py
      for name in ( 'complex', 'pair', 'deque', 'list', 'queue', 'stack',
            'vector', 'map', 'multimap', 'set', 'multiset' ):
         setattr( _root, name, getattr( cppyy.gbl.std, name ) )

    # set the display hook
      sys.displayhook = _displayhook

    # manually load libMathCore, for example to obtain gRandom
    # This can be removed once autoloading on selected variables is available
      _root.gSystem.Load( "libMathCore" )
Beispiel #6
0
   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.CreateScopeProxy( '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( cppyy.gbl.std, '__1' ):
         attr_1 = getattr( cppyy.gbl.std, '__1' )
         if hasattr( attr_1, 'cout' ):
            self.__dict__[ 'cout' ] = attr_1.cout

    # python side pythonizations (should live in their own file, if we get many)
      def set_size(self, buf):
         buf.SetSize(self.GetN())
         return buf

      cppyy.add_pythonization(
         cppyy.compose_method("^TGraph(2D)?$|^TGraph.*Errors$", "GetE?[XYZ]$", set_size))

    # custom logon file (must be after creation of ROOT globals)
      if hasargv and not '-n' in sys.argv and not PyConfig.DisableRootLogon:
         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 cppyy.gbl.std.stlclasses:
         setattr( _root, name, getattr( cppyy.gbl.std, name ) )

    # set the display hook
      sys.displayhook = _displayhook