Exemplo n.º 1
0
def set_text_attributes(obj, **kwargs):
    """Set text attributes for the object
    >>> set_text_attribute ( obj , marker_color = 5 , markerStyle = 6 , ... ) 
    """

    key_transform = lambda k: k.lower().replace('_', '').replace('text', '')
    keys = cidict(transform=key_transform)
    keys.update(kwargs)

    if hasattr(obj, 'SetTextAlign'):
        l = keys.get('align', None)
        if not l is None: obj.SetTextAlign(l)

    if hasattr(obj, 'SetTextAngle'):
        l = keys.get('angle', None)
        if not l is None: obj.SetTextAngle(l)

    if hasattr(obj, 'SetTextFont'):
        l = keys.get('font', None)
        if not l is None: obj.SetTextFont(l)

    if hasattr(obj, 'SetTextSize'):
        l = keys.get('size', None)
        if not l is None: obj.SetTextSize(l)

    if hasattr(obj, 'SetTextColor'):
        l = keys.get('color', None)
        if not l is None: obj.SetTextColor(l)

    if hasattr(obj, 'SetTextColorAlpha') and hasattr(obj, 'GetTextColor'):
        l = keys.get('color_alpha', None)
        if not l is None: obj.SetTextColorAlpha(object.GetTextColor(), l)
Exemplo n.º 2
0
def error_band2(value, epos, eneg, min_value, max_value, **kwargs):
    """Helper function to prepare drawing the error band(s)
    >>> objects = error_band ( 1 , 0.2 , (-0.1,0.4) , (0.1,-0.3) , min_value = 0 , max_value = 10 , transpose = False )
    >>> for o in objects  : o.draw()
    """
    config = cidict(transform=cidict_fun)
    config.update(kwargs)

    transpose = config.get('transpose', False)
    transparent = config.get('transparent', -1)

    if max_value < min_value:
        min_value, max_value = max_value, min_value

    boxes = []

    ## fill color
    fcolor = config.get('fill_color', ROOT.kOrange)

    from itertools import count
    for fc, ep, en in zip(count(fcolor, -1), reversed(epos), reversed(eneg)):

        if not transpose:
            box1 = ROOT.TBox(value - en, min_value, value + ep, max_value)
            box2 = ROOT.TBox(value - en, min_value, value + ep, max_value)
        else:
            box1 = ROOT.TBox(min_value, value - en, max_value, value + ep)
            box2 = ROOT.TBox(min_value, value - en, max_value, value + ep)

        box1.set_fill_attributes(**config)
        box2.set_fill_attributes(**config)

        ## adjust fill color for transparency

        if 0 <= transparent <= 1: box1.SetFillColorAlpha(fc, transparent)
        else: box1.SetFillColor(fc)

        box2.SetLineColor(fc - 1)
        box2.SetFillStyle(0)

        boxes.append(box1)
        boxes.append(box2)

    ##  mean value
    if not transpose: line = ROOT.TLine(value, min_value, value, max_value)
    else: line = ROOT.TLine(min_value, value, max_value, value)

    line.set_line_attributes(**config)
    line.SetLineWidth(config.get('average_width', 3))

    boxes.append(line)

    return tuple(boxes)
Exemplo n.º 3
0
    def __init__(self, color=ROOT.kRed, style=1001, **kwargs):

        from ostap.utils.cidict import cidict
        kw = cidict(transform=lambda k: k.lower().replace('_', ''), **kwargs)

        fillcolor = kw.pop('fill_color', color)
        fillstyle = kw.pop('fill_style', style)

        linecolor = kw.pop('line_color', None)  ## ignore
        linestyle = kw.pop('line_style', None)  ## ignore
        linewidth = kw.pop('line_width', None)  ## ignore

        Style.__init__(self, fillcolor=fillcolor, fillstyle=fillstyle, **kw)
Exemplo n.º 4
0
def set_fill_attributes(obj, **kwargs):
    """Set fill attributes for the object
    >>> set_fill_attribute ( obj , fill_color = 5 , FillStyle = 6 , ... ) 
    """

    key_transform = lambda k: k.lower().replace('_', '').replace(
        'fill', '').replace('area', '')
    keys = cidict(transform=key_transform)
    keys.update(kwargs)

    if hasattr(obj, 'SetFillStyle'):
        l = keys.get('style', None)
        if not l is None: obj.SetFillStyle(l)

    if hasattr(obj, 'SetFillColor'):
        l = keys.get('color', None)
        if not l is None: obj.SetFillColor(l)

    if hasattr(obj, 'SetFillColorAlpha') and hasattr(obj, 'GetFillColor'):
        l = keys.get('color_alpha', None)
        if not l is None: obj.SetFillColorAlpha(object.GetFillColor(), l)
Exemplo n.º 5
0
def set_marker_attributes(obj, **kwargs):
    """Set marker attributes for the object
    >>> set_marker_attribute ( obj , marker_color = 5 , markerStyle = 6 , ... ) 
    """

    key_transform = lambda k: k.lower().replace('_', '').replace('marker', '')
    keys = cidict(transform=key_transform)
    keys.update(kwargs)

    if hasattr(obj, 'SetMarkerStyle'):
        l = keys.get('style', None)
        if not l is None: obj.SetMarkerStyle(l)

    if hasattr(obj, 'SetMarkerColor'):
        l = keys.get('color', None)
        if not l is None: obj.SetMarkerColor(l)

    if hasattr(obj, 'SetMarkerSize'):
        l = keys.get('size', None)
        if not l is None: obj.SetMarkerSize(l)

    if hasattr(obj, 'SetMarkerColorAlpha') and hasattr(obj, 'GetMarkerColor'):
        l = keys.get('color_alpha', None)
        if not l is None: obj.SetMarkerColorAlpha(object.GetMarkerColor(), l)
Exemplo n.º 6
0
def set_line_attributes(obj, **kwargs):
    """Set line attributes for the object
    >>> set_line_attribute ( obj , line_color = 5 , LineStyle = 6 , ... ) 
    """

    key_transform = lambda k: k.lower().replace('_', '').replace('line', '')
    keys = cidict(transform=key_transform)
    keys.update(kwargs)

    if hasattr(obj, 'SetLineStyle'):
        l = keys.get('style', None)
        if not l is None: obj.SetLineStyle(l)

    if hasattr(obj, 'SetLineWidth'):
        l = keys.get('line_width', None)
        if not l is None: obj.SetLineWidth(l)

    if hasattr(obj, 'SetLineColor'):
        l = keys.get('color', None)
        if not l is None: obj.SetLineColor(l)

    if hasattr(obj, 'SetLineColorAlpha') and hasattr(obj, 'GetLineColor'):
        l = keys.get('color_alpha', None)
        if not l is None: obj.SetLineColorAlpha(object.GetLineColor(), l)
Exemplo n.º 7
0
 def __init__(self, **config):
     self.__config = cidict(transform=cidict_fun)
     self.__config.update(config)
Exemplo n.º 8
0
    def __process_func ( self , task , chunks  , **kwargs ) :
        """Helper internal method for parallel processiing of
        the plain function with chunks of data
        """
        from ostap.utils.cidict import cidict
        my_args = cidict( kwargs )
        
        from timeit import default_timer as _timer
        start = _timer()
        
        init      = my_args.pop ( 'init'      , None )
        merger    = my_args.pop ( 'merger'    , None )
        collector = my_args.pop ( 'collector' , None )
        
        ## mergers for statistics & results
        if   not merger and not collector :
            logger.warning ( "Neither ``merger'' nor ``collector'' are specified for merging!")
        elif     merger and     collector :
            logger.warning ( "Both    ``merger'' and ``collector'' are specified for merging!")
            
        ## mergers for statistics 
        merged_stat    = StatMerger ()
        merged_stat_pp = StatMerger ()

        ## start index for the jobs 
        index = 0

        ## initialize the results 
        results = init

        from ostap.utils.progress_bar import ProgressBar
        ## total number of jobs  
        njobs = sum  ( len ( c ) for c in chunks )
        with ProgressBar ( max_value = njobs , silent = self.silent ) as bar :
            
            while chunks :

                chunk = chunks.pop ( 0 ) 
                
                jobs_args = zip ( repeat ( task ) , count ( index ) , chunk )

                ## call for the actual jobs handling method 
                for jobid , result , stat in self.iexecute ( func_executor    ,
                                                             jobs_args        ,
                                                             progress = False ) :
                    
                    merged_stat += stat
                    
                    ## merge results if merger or collector are provided 
                    if   merger    : results = merger    ( results , result ) 
                    elif collector : results = collector ( results , result , jobid )
                    
                    bar += 1 

                index           += len ( chunk )
                
                pp_stat = self.get_pp_stat() 
                if pp_stat : merged_stat_pp  += pp_stat 

        ## print statistics 
        self.print_statistics ( merged_stat_pp , merged_stat , _timer() - start )
        ##
        return results 
Exemplo n.º 9
0
    def _TO_draw_(obj, option='', *args, **kwargs):
        """ (silent) Draw of ROOT object, optionally setting the drawing attributes when applicable:
        
        - LineColor
        - LineStyle
        - LineWidth
        - MarkerColor
        - MarkerStyle
        - MarkerSize
        - FillColor
        - FillStyle
        - Min/Minimal
        - Max/Maximal

        - see ROOT.TAttLine, ROOT.TAttMarker and ROOT.TAttFill

        (case-insensitive and underscore-blind)
        
        >>> obj
        >>> obj.draw ()  ##
        >>> obj.draw ( linecolor   = 2 ) 
        >>> obj.draw ( LineColor   = 2 , fill_style = 1003 ) 
        >>> obj.draw ( markerStyle = 22  )

        >>> obj.draw ( minimal     = -1  )
        >>> obj.draw ( max         = 100 )

        """

        from ostap.utils.cidict import cidict
        kw = cidict(transform=lambda k: k.lower().replace('_', ''), **kwargs)

        ## Line

        if 'LineColor' in kw and hasattr(obj, 'SetLineColor'):
            obj.SetLineColor(kw.pop('LineColor'))
        if 'LineStyle' in kw and hasattr(obj, 'SetLineStyle'):
            obj.SetLineStyle(kw.pop('LineStyle'))
        if 'LineWidth' in kw and hasattr(obj, 'SetLineWidth'):
            obj.SetLineWidth(kw.pop('LineWidth'))

        ## Marker

        if 'MarkerColor' in kw and hasattr(obj, 'SetMarkerColor'):
            obj.SetMarkerColor(kw.pop('MarkerColor'))
        if 'MarkerStyle' in kw and hasattr(obj, 'SetMarkerStyle'):
            obj.SetMarkerStyle(kw.pop('MarkerStyle'))
        if 'MarkerSize' in kw and hasattr(obj, 'SetMarkerSize'):
            obj.SetMarkerSize(kw.pop('MarkerSize'))

        ## Area

        if 'FillColor' in kw and hasattr(obj, 'SetFillColor'):
            obj.SetFillColor(kw.pop('FillColor'))
        if 'FillStyle' in kw and hasattr(obj, 'SetFillStyle'):
            obj.SetFillStyle(kw.pop('FillStyle'))

        ## Min/max values

        if 'Minimum' in kw and hasattr(obj, 'SetMinimum'):
            obj.SetMinimum(kw.pop('Minimum'))
        elif 'Min' in kw and hasattr(obj, 'SetMinimum'):
            obj.SetMinimum(kw.pop('Min'))
        if 'Maximum' in kw and hasattr(obj, 'SetMaximum'):
            obj.SetMaximum(kw.pop('Maximum'))
        elif 'Max' in kw and hasattr(obj, 'SetMaximum'):
            obj.SetMaximum(kw.pop('Max'))

        if kw: logger.warning('draw: unknown attributes: %s' % kw.keys())

        from ostap.logger.utils import rootWarning, rooSilent
        with rootWarning(), rooSilent(2):
            result = obj.Draw(option, *args)

        pad = ROOT.gROOT.GetSelectedPad()
        if pad and not ROOT.gPad:
            c = pad.GetCanvas()
            if c: c.Update()
        elif ROOT.gPad:
            c = ROOT.gPad
            if c: c.Update()

        return result
Exemplo n.º 10
0
def set_pad(pad, **config):
    """Change main parametes of `TAttPad`"""

    conf = cidict(transform=cidict_fun)
    conf.update(config)

    changed = {}

    if 'frame_border_mode' in conf:
        changed['frame_border_mode'] = pad.GetFrameBorderMode()
        pad.SetFrameBorderMode(conf.pop('frame_border_mode'))

    if 'frame_border_size' in conf:
        changed['frame_border_size'] = pad.GetFrameBorderSize()
        pad.SetFrameBorderSize(conf.pop('frame_border_size'))

    if 'frame_fill_color' in conf:
        changed['frame_fill_color'] = pad.GetFrameFillColor()
        pad.SetFrameFillColor(conf.pop('frame_fill_color'))

    if 'frame_fill_style' in conf:
        changed['frame_fill_style'] = pad.GetFrameFillStyle()
        pad.SetFrameFillStyle(conf.pop('frame_fill_style'))

    if 'frame_line_color' in conf:
        changed['frame_line_color'] = pad.GetFrameLineColor()
        pad.SetFrameLineColor(conf.pop('frame_line_color'))

    if 'frame_line_style' in conf:
        changed['frame_line_style'] = pad.GetFrameLineStyle()
        pad.SetFrameLineStyle(conf.pop('frame_line_style'))

    if 'frame_line_width' in conf:
        changed['frame_line_width'] = pad.GetFrameLineWidth()
        pad.SetFrameLineWidth(conf.pop('frame_line_width'))

    if 'a_file' in conf:
        changed['a_file'] = pad.GetAfile()
        pad.SetAfile(conf.pop('a_file'))

    if 'a_stat' in conf:
        changed['a_stat'] = pad.GetAstat()
        pad.SetAstat(conf.pop('a_stat'))

    if 'x_file' in conf:
        changed['x_file'] = pad.GetXfile()
        pad.SetXfile(conf.pop('x_file'))

    if 'x_stat' in conf:
        changed['x_stat'] = pad.GetXstat()
        pad.SetXstat(conf.pop('x_stat'))

    if 'y_file' in conf:
        changed['y_file'] = pad.GetYfile()
        pad.SetYfile(conf.pop('y_file'))

    if 'y_stat' in conf:
        changed['y_stat'] = pad.GetYstat()
        pad.SetYstat(conf.pop('y_stat'))

    if 'top_margin' in conf or 'margin_top' in conf:
        changed['margin_top'] = pad.GetTopMargin()
        if 'top_margin' in conf: pad.SetTopMargin(conf.pop('top_margin'))
        else: pad.SetTopMargin(conf.pop('margin_top'))

    if 'bottom_margin' in conf or 'margin_bottom' in conf:
        changed['margin_bottom'] = pad.GetBottomMargin()
        if 'bottom_margin' in con:
            pad.SetBottomMargin(conf.pop('bottom_margin'))
        else:
            pad.SetBottomMargin(conf.pop('margin_bottom'))

    if 'left_margin' in conf or 'margin_left' in conf:
        changed['margin_left'] = pad.GetLeftMargin()
        if 'left_margin' in conf: pad.SetLeftMargin(conf.pop('left_margin'))
        else: pad.SetLeftMargin(conf.pop('margin_left'))

    if 'right_margin' in conf or 'margin_right' in conf:
        changed['margin_right'] = pad.GetRightMargin()
        if 'right_margin' in conf: pad.SetRightMargin(conf.pop('right_margin'))
        else: pad.SetRightMargin(conf.pop('margin_right'))

    if conf:
        logger.warning("set_pad: unprocessed items: %s" % conf)

    return changed
Exemplo n.º 11
0
    def __init__(self, *args, **kwargs):

        from ostap.utils.cidict import cidict
        kw = cidict(transform=lambda k: k.lower().replace('_', ''), **kwargs)

        linecolor = kw.pop('linecolor', ROOT.kBlack)
        linestyle = kw.pop('linestyle', 1)
        linewidth = kw.pop('linewidth', 1)
        fillcolor = kw.pop('fillcolor', None)
        fillstyle = kw.pop('fillstyle', None)
        transparency = kw.pop('transparency', 0.35)

        if kw: logger.warning("Style: Unknown arguments: %s" % kw.keys())

        options = []

        self.__linecolor = None
        self.__linestyle = None
        self.__linewidth = None
        self.__fillcolor = None
        self.__fillstyle = None

        for i, a in enumerate(args):

            if isinstance(a, ROOT.RooCmdArg):

                if 'LineColor' == a.GetName(): linecolor = a
                elif 'LineStyle' == a.GetName(): linestyle = a
                elif 'FillColor' == a.GetName(): fillcolor = a
                elif 'FillStyle' == a.GetName(): fillstyle = a
                else: logger.warning('Style:Unknown argument: %s ' % a)

            elif i == 0 and isinstance(a, ROOT.TColor): linecolor = a
            elif i == 0 and isinstance(a, int) and 0 <= a: linecolor = a
            elif i == 1 and isinstance(a, int) and 0 <= a: linestyle = a
            elif i == 2 and isinstance(a, int) and 0 <= a: linewidth = a
            elif i == 3 and isinstance(a, ROOT.TColor): fillcolor = a
            elif i == 3 and isinstance(a, int) and 0 <= a: fillcolor = a
            elif i == 4 and isinstance(a, int) and 0 <= a: fillstyle = a
            elif i == 5 and isinstance(a, float) and 0 < a < 1:
                transparency = a
            else:
                logger.warning('Style:Unknown argument #%d : %s/%s ' %
                               (i, a, type(a)))

        if isinstance(linecolor, ROOT.TColor):
            linecolor = linecolor.GetNumber()
        if isinstance(fillcolor, ROOT.TColor):
            fillcolor = fillcolor.GetNumber()

        if isinstance(linecolor, integer_types) and 0 < linecolor:
            self.__linecolor = linecolor
            options.append(ROOT.RooFit.LineColor(linecolor))
        elif isinstance(linecolor,
                        ROOT.RooCmdArg) and 'LineColor' == linecolor.GetName():
            self.__linecolor = linecolor.getInt(0)
            options.append(linecolor)

        if isinstance(linestyle, integer_types) and 0 < linestyle:
            self.__linestyle = linestyle
            options.append(ROOT.RooFit.LineStyle(linestyle))
        elif isinstance(linestyle,
                        ROOT.RooCmdArg) and 'LineStyle' == linestyle.GetName():
            self.__linestyle = linestyle.getInt(0)
            options.append(linestyle)

        if isinstance(linewidth, integer_types) and 0 < linewidth:
            self.__linewidth = linewidth
            options.append(ROOT.RooFit.LineWidth(linewidth))
        elif isinstance(linewidth,
                        ROOT.RooCmdArg) and 'LineWidth' == linewidth.GetName():
            self.__linewidth = linewidth.getInt(0)
            options.append(linewidth)

        _fillopt = False
        if isinstance(fillcolor, integer_types) and 0 < fillcolor:
            self.__fillcolor = fillcolor
            cc = ROOT.gROOT.GetColor(fillcolor)
            if cc and 1.0 == cc.GetAlpha():
                ## add tranparency
                fillcolor = ROOT.TColor.GetColorTransparent(
                    fillcolor, transparency)
            options.append(ROOT.RooFit.FillColor(fillcolor))
            _fillopt = True
        elif isinstance(fillcolor,
                        ROOT.RooCmdArg) and 'FillColor' == fillcolor.GetName():
            self.__fillcolor = fillcolor.getInt(0)
            options.append(fillcolor)
            _fillopt = True

        if isinstance(fillstyle, integer_types) and 0 < fillstyle:
            self.__fillstyle = fillstyle
            options.append(ROOT.RooFit.FillStyle(fillstyle))
            _fillopt = True
        elif isinstance(fillstyle,
                        ROOT.RooCmdArg) and 'FillStyle' == fillstyle.GetName():
            self.__fillstyle = fillstyle.getInt(0)
            options.append(fillstyle)
            _fillopt = True

        if _fillopt:
            options.append(ROOT.RooFit.VLines())
            options.append(ROOT.RooFit.DrawOption("FL"))

        self.__options = tuple(options)
Exemplo n.º 12
0
    def __init__(self,
                 ncpus='autodetect',
                 ppservers=(),
                 silent=False,
                 progress=True,
                 **kwargs):

        if not (isinstance(ncpus, int) and 0 <= ncpus):
            from pathos.helpers import cpu_count
            ncpus = cpu_count()

        ## initialize the base class
        TaskManager.__init__(self,
                             ncpus=ncpus,
                             silent=silent,
                             progress=progress)

        from ostap.utils.cidict import cidict
        kwa = cidict(**kwargs)

        self.__ppservers = ()
        self.__locals = ()
        self.__pool = ()

        import socket
        local_host = socket.getfqdn().lower()

        from ostap.core.ostap_types import string_types
        if isinstance ( ppservers , string_types ) and \
               ppservers.lower() in ( 'config' , 'auto' , '*' ) :
            from ostap.parallel.utils import get_ppservers
            ppservers = get_ppservers(local_host)

        ## use Paralell python if ppservers are specified or explicit flag
        if ppservers or kwa.pop('PP', False) or kwa.pop('Parallel', False):

            ## remove duplicates (if any) - do not sort!
            pps = []
            for p in ppservers:
                if p not in pps:
                    pps.append(p)
            ppservers = tuple(pps)

            ## check local ports
            local_ports = []
            remotes = []

            for p in ppservers:
                port = get_local_port(p)
                if port: local_ports.append("localhost:%d" % port)
                else: remotes.append(p)

            ## check alive remote hosts
            from ostap.parallel.utils import good_pings
            alive = good_pings(*remotes)
            if len(alive) != len(remotes):
                dead = list(set(remotes) - set(alive))
                logger.warning("Dead remote hosts: %s" % dead)
            remotes = alive

            environment = kwa.pop('environment', '')
            script = kwa.pop('script', None)
            profile = kwa.pop('profile', None)
            secret = kwa.pop('secret', None)
            timeout = kwa.pop('timeout', 7200)

            if script:
                assert os.path.exists ( script ) and os.path.isfile ( script ) ,\
                       'WorkManager: no script %s is found' % script

            if secret is None:
                from ostap.utils.utils import gen_password
                secret = gen_password(16)

            from ostap.parallel.pptunnel import ppServer, show_tunnels
            ppsrvs = [
                ppServer(remote,
                         environment=environment,
                         script=script,
                         profile=profile,
                         secret=secret,
                         timeout=timeout,
                         silent=self.silent) for remote in remotes
            ]

            ppbad = [p for p in ppsrvs if not p.pid]
            ppgood = [p for p in ppsrvs if p.pid]

            self.__ppservers = tuple(ppgood)

            if ppbad:
                rs = [p.remote_host for p in ppbad]
                logger.warning('Failed to start remote ppservers at %s' % rs)

            ## if remote servers are available, reduce a bit the load for local server
            ## if ncpus == 'autodetect' or ncpus == 'auto' :
            ##    self.ncpus = max  ( 0 , self.ncpus - 2 )

            ## some trick to setup the password.
            ## unfortunately ParallelPool interface does not allow it :-(
            if secret:
                import pathos.parallel as PP
                _ds = PP.pp.Server.default_secret
                PP.pp.Server.default_secret = secret

            ## add remote connections to the list of local ports
            for p in self.ppservers:
                local_ports.append(p.local)
            self.__locals = tuple(local_ports)

            from pathos.pools import ParallelPool
            self.__pool = ParallelPool(ncpus=self.ncpus, servers=self.locals)

            ## end of the trick
            PP.pp.Server.default_secret = _ds
            if not self.silent and self.ppservers: show_tunnels(self.ppservers)

        else:

            ## from pathos.multiprocessing import ProcessPool
            from pathos.pools import ProcessPool
            self.__pool = ProcessPool(self.ncpus)

        ps = '%s' % self.pool
        ps = ps.replace('<pool ',
                        '').replace('>', '').replace('servers', 'remotes')
        for p in self.ppservers:
            ps = ps.replace(p.local, p.remote)
        if not self.silent: logger.info('WorkManager is %s' % ps)
Exemplo n.º 13
0
    def _TO_draw_ ( obj , option = '', *args , **kwargs ) :
        """ (silent) Draw of ROOT object, optionally setting the drawing attributes when applicable:
        
        - LineColor
        - LineStyle
        - LineWidth
        - MarkerColor
        - MarkerStyle
        - MarkerSize
        - FillColor
        - FillStyle
        - Min/Minimal
        - Max/Maximal

        - see ROOT.TAttLine, ROOT.TAttMarker and ROOT.TAttFill

        (case-insensitive and underscore-blind)
        
        >>> obj
        >>> obj.draw ()  ##
        >>> obj.draw ( linecolor   = 2 ) 
        >>> obj.draw ( LineColor   = 2 , fill_style = 1003 ) 
        >>> obj.draw ( markerStyle = 22  )

        >>> obj.draw ( minimal     = -1  )
        >>> obj.draw ( max         = 100 )

        """
        
        from ostap.utils.cidict import cidict
        kw = cidict ( transform = cidict_fun , **kwargs )
        
        ## Line
        
        if 'LineColor'  in kw and hasattr ( obj , 'SetLineColor' ) :
            obj.SetLineColor   ( kw.pop('LineColor' ) )
        if 'LineStyle'  in kw and hasattr ( obj , 'SetLineStyle' ) :
            obj.SetLineStyle   ( kw.pop('LineStyle' ) )
        if 'LineWidth'  in kw and hasattr ( obj , 'SetLineWidth' ) :
            obj.SetLineWidth   ( kw.pop('LineWidth' ) )

        ## Marker
            
        if 'MarkerColor' in kw and hasattr ( obj , 'SetMarkerColor' ) :
            obj.SetMarkerColor ( kw.pop('MarkerColor' ) )
        if 'MarkerStyle' in kw and hasattr ( obj , 'SetMarkerStyle' ) :
            obj.SetMarkerStyle ( kw.pop('MarkerStyle' ) )
        if 'MarkerSize'  in kw and hasattr ( obj , 'SetMarkerSize'  ) :
            obj.SetMarkerSize  ( kw.pop('MarkerSize'  ) )

        ## Area
            
        if 'FillColor'   in kw and hasattr ( obj , 'SetFillColor' ) :
            obj.SetFillColor   ( kw.pop('FillColor' ) )
        if 'FillStyle'   in kw and hasattr ( obj , 'SetFillStyle' ) :
            obj.SetFillStyle   ( kw.pop('FillStyle' ) )

        ## Min/max values  
            
        if   'Minimum'     in kw and hasattr ( obj , 'SetMinimum' ) :
            obj.SetMinimum     ( kw.pop ( 'Minimum' ) )
        elif 'Min'         in kw and hasattr ( obj , 'SetMinimum' ) :
            obj.SetMinimum     ( kw.pop ( 'Min'     ) )
        if   'Maximum'     in kw and hasattr ( obj , 'SetMaximum' ) :
            obj.SetMaximum     ( kw.pop ( 'Maximum' ) )
        elif 'Max'         in kw and hasattr ( obj , 'SetMaximum' ) :
            obj.SetMaximum     ( kw.pop ( 'Max'     ) )


        if 'LabelSize' in kw or 'LabelFont' in kw or 'LabelScale' in kw  :

            axis = [] 
            if hasattr ( obj , 'GetXaxis'     ) :
                xa = obj.GetXaxis()
                if xa : axis.append ( xa )
            if hasattr ( obj , 'GetYaxis'     ) :
                ya = obj.GetYaxis()
                if ya : axis.append ( ya ) 
            if hasattr ( obj , 'GetZaxis'     ) :
                za = obj.GetZaxis()
                if za : axis.append ( za ) 

            if axis and 'LabelSize' in kw :
                ls = kw.pop ( 'LabelSize' ) 
                for a in axis : a.SetLabelSize ( ls ) 

            if axis and 'LabelFont' in kw :
                lf = kw.pop ( 'LabelFont' ) 
                for a in axis : a.SetLabelFont ( lf )                

            if axis and 'LabelScale' in kw :
                ls = kw.pop ( 'LabelScale' ) 
                for a in axis : a.SetLabelSize  ( ls * a.GetLabelSize () ) 

        if 'XaxisLabelOffset' in kw and hasattr ( obj , 'GetXaxis' ) :
            xa = obj.GetXaxis() 
            if xa : xa.SetLabelOffset ( kw.pop  ( 'XaxisLabelOffset' ) ) 

        if 'YaxisLabelOffset' in kw and hasattr ( obj , 'GetYaxis' ) :
            ya = obj.GetYaxis() 
            if ya : ya.SetLabelOffset ( kw.pop  ( 'YaxisLabelOffset' ) ) 
                                        
        if 'ZaxisLabelOffset' in kw and hasattr ( obj , 'GetZaxis' ) :
            za = obj.GetZaxis() 
            if za : za.SetLabelOffset ( kw.pop  ( 'ZaxisLabelOffset' ) ) 
                                        
                
        if kw : logger.warning('draw: unknown attributes: %s' % kw.keys() )
            
        from ostap.logger.utils import  rootWarning,   rooSilent 
        with rootWarning() , rooSilent ( 2 )  :
            result = obj.Draw( option , *args )
            
        groot = ROOT.ROOT.GetROOT ()
        pad   = groot.GetSelectedPad()
        if   pad and not ROOT.gPad :
            c = pad.GetCanvas()
            if c : c.Update()
        elif ROOT.gPad :
            c = ROOT.gPad
            if c : c.Update()
            
        return result 
Exemplo n.º 14
0
def set_style(style, config):
    """Set the style from the configurtaion dictionary
    >>> config = ...
    >>> style  = ...
    >>> set_style ( style , config )
    >>> style.set ( config ) ## ditto 
    """

    conf = cidict(transform=cidict_fun)
    conf.update(config)

    changed = {}

    for attr in style_setters[0]:

        if not attr in config: continue

        try:

            value = float(conf.pop(attr))
            setter = getattr(style, 'Set' + attr)

            old_value = None
            try:
                if attr in style_getters:
                    getter = getattr(style, 'Get' + attr)
                    old_value = getter()
            except:
                pass

            setter(value)

            if not old_value is None:
                changed[attr] = old_value

            logger.debug("Set (float) attribute %s/%s/%s " %
                         (attr, config[attr], value))
        except:
            logger.warning("Can't set (float) attribute %s/%s, skip " %
                           (attr, config[attr]))
            pass

    for attr in style_setters[1]:

        if not attr in config: continue

        try:
            value = int(conf.pop(attr))
            setter = getattr(style, 'Set' + attr)

            old_value = None
            try:
                if attr in style_getters:
                    getter = getattr(style, 'Get' + attr)
                    old_value = getter()
            except:
                pass

            setter(value)

            if not old_value is None:
                changed[attr] = old_value

            logger.debug("Set (int)   attribute %s/%s/%s " %
                         (attr, config[attr], value))
        except:
            logger.warning("Can't set (int)   attribute %s/%s, skip " %
                           (attr, config[attr]))
            pass

    for attr in style_setters[2]:

        if not attr in config: continue

        try:

            value = conf.pop(attr)
            setter = getattr(style, 'Set' + attr)

            old_value = None
            try:
                if attr in style_getters:
                    getter = getattr(style, 'Get' + attr)
                    old_value = getter()
            except:
                pass

            setter(value)

            if not old_value is None:
                changed[attr] = old_value

            logger.debug("Set (str)   attribute %s/%s/%s " %
                         (attr, config[attr], value))
        except:
            logger.warning("Can't set (str)   attribute %s/%s, skip " %
                           (attr, config[attr]))
            pass

    ## half-special attributes
    for attr in ('AxisColor', 'TickLength', 'Ndivisions', 'LabelColor',
                 'LabelFont', 'LabelOffset', 'LabelSize', 'TitleColor',
                 'TitleFont', 'TitleOffset', 'TitleSize'):

        if attr in conf:

            x_attr = '%s_X' % attr
            y_attr = '%s_Y' % attr
            z_attr = '%s_Z' % attr

            if ( not x_attr in conf ) and \
               ( not y_attr in cong ) and \
               ( not z_attr in conf ) :

                value = conf.pop(attr)
                conf[x_attr] = value
                conf[y_attr] = value
                conf[z_attr] = value

    ## special attributes
    for axis in ('X', 'Y', 'Z'):

        key = 'AxisColor_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetAxisColor(axis)
                style.SetAxisColor(int(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'TickLength_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetTickLength(axis)
                style.SetTickLength(float(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'Ndivisions_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetNdivisions(axis)
                style.SetNdivisions(int(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'LabelColor_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetLabelColor(axis)
                style.SetLabelColor(int(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'LabelFont_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetLabelFont(axis)
                style.SetLabelFont(int(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'LabelOffset_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetLabelOffset(axis)
                style.SetLabelOffset(float(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'LabelSize_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetLabelSize(axis)
                style.SetLabelSize(float(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'TitleColor_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetTitleColor(axis)
                style.SetTitleColor(int(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'TitleFont_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetTitleFont(axis)
                style.SetTitleFont(int(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'TitleOffset_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetTitleOffset(axis)
                style.SetTitleOffset(float(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

        key = 'TitleSize_%s' % axis
        try:
            if key in conf:
                changed[key] = style.GetTitleSize(axis)
                style.SetTitleSize(float(conf.pop(key)), axis)
        except:
            logger.warning("Can't set attribute %s" % key)

    ## very special attribute
    if 'PaperSize_X' in conf and 'PaperSize_Y' in conf:
        key = 'PaperSize/1'
        try:
            x = ctypes.c_float()
            y = ctypes.c_float()
            style.GetPaperSize(x, y)
            changed['PaperSize_X'] = x.value
            changed['PaperSize_Y'] = y.value
            style.SetPaperSize(float(conf.pop('PaperSize_X')),
                               float(conf.pop('PaperSize_Y')))
        except:
            logger.warning("Can't set attribute %s" % key)

    elif 'PaperSize' in conf:
        key = 'PaperSize/2'
        try:
            x = ctypes.c_float()
            y = ctypes.c_float()
            style.GetPaperSize(x, y)
            changed['PaperSize_X'] = x.value
            changed['PaperSize_Y'] = y.value
            style.SetPaperSize(int(conf.pop('PaperSize')))
        except:
            logger.warning("Can't set attribute %s" % key)

    ## one more very special attribute
    for i in range(31):
        k = 'LineStyleString_%s' % i
        if k in conf:
            changed[key] = style.GetLineStyleString(i)
            style.SetLineStyleString(i, conf.pop(k).strip())

    if 'palette' in conf:
        style.SetPalette(conf.pop('palette'))

    if conf:
        logger.warning("set_style: unprocessed parameters: %s" %
                       list(conf.keys()))

    return changed