コード例 #1
0
def compareDataMCProfiles(datahists,mchist,era="",minbiases=0.0,tag="",rmin=0.6,rmax=1.4,delete=False):
  """Compare data/MC profiles."""
  print ">>> compareDataMCProfiles()"
  mctitle = "MC average"
  outdir  = ensuredir("plots")
  if islist(datahists): # multiple datahists
    if all(islist(x) for x in datahists): # datahists = [(minbias1,datahist1),...]
      minbiases = [m for m,h in datahists]
      datahists = [h for m,h in datahists]
  else: # is single datahist histogram
    minbiases = [minbiases]
    datahists = [datahists]
  hists  = datahists+[mchist]
  styles = [kSolid]*len(datahists)+[kDashed]
  colors = [kBlack]+linecolors if len(datahists)==1 else linecolors[:len(datahists)]+[kBlack]
  if 'pmx' in tag:
    width  = 0.36
    position = 'TCR'
  else:
    width  = 0.39
    position = 'TR'
  if era and isinstance(era,str) and any(s in era for s in ["Run","VFP"]):
    width =  max(width,0.26+(len(era)-5)*0.018)
    position = 'TCR'
  if tag and tag[0]!='_':
    tag = '_'+tag
  if 'pmx' in tag:
    mctitle += " (%s pre-mixing)"%("old" if "old" in tag else "new")
  if len(minbiases)==1 and minbiases[0]>0:
    tag = "_"+str(minbiases[0]).replace('.','p')
  
  for datahist, minbias in zip(datahists,minbiases):
    title = "Data"
    if era:
      title += " %s"%(era)
    if minbias>0:
      title += ", %.1f pb"%(minbias)
    if 'VFP' in era:
      title = title.replace("_"," ").replace("VFP","-VFP")
    datahist.SetTitle(title)
    datahist.Scale(1./datahist.Integral())
  mchist.SetTitle(mctitle)
  mchist.Scale(1./mchist.Integral())
  
  xtitle = "Number of interactions"
  pname  = "%s/pileup_Data-MC_%s%s"%(outdir,era,tag)
  plot   = Plot(hists,ratio=True)
  plot.draw(xtitle=xtitle,ytitle="A.U.",rtitle="Data / MC",
            textsize=0.045,rmin=rmin,rmax=rmax,denom=-1,colors=colors,styles=styles)
  plot.drawlegend(position,width=width)
  plot.saveas(pname+".png")
  plot.saveas(pname+".pdf")
  plot.close(keep=True)
  if delete:
    deletehist(datahists) # clean memory
コード例 #2
0
def unwrap_MergedSamples_args(*args, **kwargs):
    """
  Help function to unwrap arguments for MergedSamples initialization:
    - MergedSample(str name)
    - MergedSample(str name, str title)
    - MergedSample(str name, list samples)
    - MergedSample(str name, str title, list samples)
  where samples is a list of Sample objects.
  Returns a sample name, title and a list of Sample objects:
    (str name, str, title, list samples)
  """
    strings = []
    name = "noname"
    title = "No title"
    samples = []
    #args    = unwraplistargs(args)
    for arg in args:
        if isinstance(arg, str):
            strings.append(arg)
        elif isinstance(arg, Sample):
            samples.append(arg)
        elif islist(arg) and all(isinstance(s, Sample) for s in arg):
            for sample in arg:
                samples.append(sample)
    if len(strings) == 1:
        name, title = strings[0], strings[0]
    elif len(strings) > 1:
        name, title = strings[:2]
    elif len(samples) > 1:
        name, title = '-'.join([s.name for s in samples
                                ]), ', '.join([s.title for s in samples])
    LOG.verb("unwrap_MergedSamples_args: name=%r, title=%r, samples=%s" %
             (name, title, samples),
             level=3)
    return name, title, samples
コード例 #3
0
 def setlinestyle(self, hists, **kwargs):
     """Set the line style for a list of histograms."""
     verbosity = LOG.getverbosity(self, kwargs)
     pair = kwargs.get('pair', False)
     triple = kwargs.get('triple', False)
     colors = kwargs.get('color', None)
     colors = kwargs.get('colors', colors) or self.lcolors
     style = kwargs.get('style', True)
     styles = style if islist(style) else None
     styles = kwargs.get('styles', styles) or self.lstyles
     width = kwargs.get('width', 2)
     offset = kwargs.get('offset', 0)
     mstyle = kwargs.get('mstyle', None)
     styles = ensurelist(styles)
     LOG.verb(
         "Plot.setlinestyle: width=%s, colors=%s, styles=%s" %
         (width, colors, styles), verbosity, 2)
     if mstyle == None:
         mstyle = triple or pair
     for i, hist in enumerate(hists):
         hist.SetFillStyle(0)
         if triple:
             hist.SetLineColor(colors[(i // 3) % len(colors)])
             hist.SetLineStyle(styles[i % 3])
             hist.SetMarkerSize(0.6)
             hist.SetMarkerColor(hist.GetLineColor() + 1)
         elif pair:
             hist.SetLineColor(colors[(i // 2) % len(colors)])
             hist.SetLineStyle(styles[i % 2])
             hist.SetMarkerColor(hist.GetLineColor() + 1)
             if i % 2 == 1: hist.SetMarkerSize(0.6)
             else: hist.SetMarkerSize(0.0)
         else:
             hist.SetLineColor(colors[i % len(colors)])
             hist.SetMarkerSize(0.6)
             hist.SetMarkerColor(hist.GetLineColor() + 1)
             if style:
                 if isinstance(style, bool):
                     hist.SetLineStyle(styles[i % len(styles)])
                 else:
                     hist.SetLineStyle(style)
         hist.SetLineWidth(width)
         if triple and i % 3 == 2:
             hist.SetOption('E1')
             #hist.SetLineWidth(0)
             hist.SetLineStyle(kSolid)
             hist.SetLineColor(hist.GetMarkerColor())
         elif not mstyle:
             hist.SetMarkerSize(0)
コード例 #4
0
def unwrap_gethist_args(*args, **kwargs):
    """
  Help function to unwrap argument list that contain variable(s) and selection:
    gethist(str xvar, int nxbins, float xmin, float xmax, str cuts="")
    gethist(str xvar, list xbins, str cuts="")
    gethist(Variable xvar, str cuts="")
    gethist(list varlist, str cuts="")
  where varlist is a list of Variables objects, or a list of tuples defining a variable:
    - [(str xvar, int nxbins, float xmin, float xmax), ... ]
    - [(str xvar, list xbins), ... ]
  Returns a list of Variable objects, a Selection object, and a boolean to flag a single
  instead of a list of variables was given:
    - (list vars, str cut, bool single)
  For testing, see test/testUnwrapping.py.
  """
    vars = None  # list of Variable objects
    sel = None  # selection (string or Selection object)
    single = False  # only one Variable passed
    if len(args) >= 1:
        if isinstance(args[-1], Selection):
            sel = args[-1]
            vargs = args[:-1]
        elif isinstance(args[-1], str):
            sel = Selection(args[-1])
            vargs = args[:-1]
        else:
            sel = Selection()  # no selection given
            vargs = args
    if len(vargs) == 1:
        vars = vargs[0]
        if isinstance(vars, Variable):
            vars = [vars]
            single = True
        elif islist(vargs[0]):
            vars = [ensurevar(v) for v in vargs[0]]
    elif len(vargs) in [2, 4]:
        vars = [Variable(*vargs)]
        single = True
    if vars == None or sel == None:
        LOG.throw(
            IOError,
            'unwrap_gethist_args: Could not unwrap arguments %s, len(args)=%d, vars=%s, sel=%s.'
            % (args, len(args), vars, sel.selection))
    LOG.verb("unwrap_gethist_args: vars=%s, sel=%r, single=%r" %
             (vars, sel.selection, single),
             level=4)
    return vars, sel, single
コード例 #5
0
def unwrap_gethist_args(*args, **kwargs):
    """
  Help function to unwrap argument list that contain variable(s) and selection:
    - gethist(str xvar, int nxbins, float xmin, float xmax, str cuts)
    - gethist(str xvar, list xbins, str cuts)
    - gethist(Variable xvar, str cuts)
    - gethist(list varlist, str cuts)
  where varlist is a list of Variables objects, or a list of tuples defining a variable:
    - [(str xvar, int nxbins, float xmin, float xmax), ... ]
    - [(str xvar, list xbins), ... ]
  Returns a list of Variable objects, a selection string, and a boolean to flag a single
  instead of a list of variables was given:
    (list vars, str cut, bool single)
  For testing, see test/testUnwrapping.py.
  """
    vars = None  # list of Variable objects
    sel = None  # selection (string)
    single = False  # only one Variable passed
    if len(args) == 2:
        vars = args[0]
        sel = args[1]
        if isinstance(vars, Variable):
            vars = [vars]
            single = True
        elif islist(args[0]):
            vars = [ensurevar(v) for v in args[0]]
    elif len(args) in [3, 5]:
        vars = [Variable(*args[:len(args) - 1])]
        sel = args[-1]
        single = True
    if vars == None or sel == None:
        LOG.throw(
            IOError,
            'unwrap_gethist_args: Could not unwrap arguments %s, len(args)=%d, vars=%s, sel=%s.'
            % (args, len(args), vars, sel))
    LOG.verb("unwrap_gethist_args: vars=%s, sel=%r, single=%r" %
             (vars, sel, single),
             level=3)
    return vars, sel, single
コード例 #6
0
 def __init__(self, *args, **kwargs):
     """
 Initialize with list of histograms:
   Plot(hists)
 or with a variable (string or Variable object) as well:
   Plot(variable,hists)
 """
     variable = None
     hists = None
     self.verbosity = LOG.getverbosity(kwargs)
     if len(args) == 1 and islist(args[0]):
         hists = args[0]  # list of histograms
     elif len(args) == 2:
         variable = args[0]  # string or Variable
         hists = args[1]  # list of histograms
     else:
         LOG.throw(IOError, "Plot: Wrong input %s" % (args))
     if kwargs.get('clone', False):
         hists = [h.Clone(h.GetName() + "_plot") for h in hists]
     self.hists = hists
     frame = kwargs.get('frame', self.hists[0])
     if isinstance(variable, Variable):
         self.variable = variable
         self.name = kwargs.get('name', variable.filename)
         self.xtitle = kwargs.get('xtitle', variable.title)
         self.xmin = kwargs.get('xmin', variable.xmin)
         self.xmax = kwargs.get('xmax', variable.xmax)
         self.ymin = kwargs.get('ymin', variable.ymin)
         self.ymax = kwargs.get('ymax', variable.ymax)
         self.rmin = kwargs.get('rmin', variable.rmin)
         self.rmax = kwargs.get('rmax', variable.rmax)
         self.ratiorange = kwargs.get('rrange', variable.ratiorange)
         self.binlabels = kwargs.get('binlabels', variable.binlabels)
         self.logx = kwargs.get('logx', variable.logx)
         self.logy = kwargs.get('logy', variable.logy)
         self.ymargin = kwargs.get('ymargin', variable.ymargin)
         self.logyrange = kwargs.get('logyrange', variable.logyrange)
         self.position = kwargs.get('position', variable.position)
         self.ncols = kwargs.get('ncols', variable.ncols)
         self.latex = kwargs.get('latex',
                                 False)  # already done by Variable.__init__
         self.dividebins = kwargs.get(
             'dividebins', variable.dividebins
         )  # divide each histogram bins by it bin size
     else:
         self.variable = variable or frame.GetXaxis().GetTitle()
         self.name = kwargs.get('name', None)
         self.xtitle = kwargs.get('xtitle', self.variable)
         self.xmin = kwargs.get('xmin', frame.GetXaxis().GetXmin())
         self.xmax = kwargs.get('xmax', frame.GetXaxis().GetXmax())
         self.ymin = kwargs.get('ymin', None)
         self.ymax = kwargs.get('ymax', None)
         self.rmin = kwargs.get('rmin', None)
         self.rmax = kwargs.get('rmax', None)
         self.ratiorange = kwargs.get('rrange', None)
         self.binlabels = kwargs.get('binlabels', None)
         self.logx = kwargs.get('logx', False)
         self.logy = kwargs.get('logy', False)
         self.ymargin = kwargs.get('ymargin', None)
         self.logyrange = kwargs.get('logyrange', None)
         self.position = kwargs.get('position', "")
         self.ncols = kwargs.get('ncols', None)
         self.latex = kwargs.get('latex', True)
         self.dividebins = kwargs.get('dividebins',
                                      frame.GetXaxis().IsVariableBinSize())
     self.ytitle = kwargs.get('ytitle', frame.GetYaxis().GetTitle() or None)
     self.name = self.name or (self.hists[0].GetName()
                               if self.hists else "noname")
     self.title = kwargs.get('title', None)
     self.errband = None
     self.ratio = kwargs.get('ratio', False)
     self.append = kwargs.get('append', "")
     self.norm = kwargs.get('norm', False)
     self.lcolors = kwargs.get('lcolors', _lcolors)
     self.fcolors = kwargs.get('fcolors', _fcolors)
     self.lstyles = kwargs.get('lstyles', _lstyles)
     self.canvas = None
     self.frame = frame
     self.legends = []
     self.texts = []  # to save TLatex objects made by drawtext
     self.garbage = []
コード例 #7
0
def unwrap_gethist2D_args(*args, **kwargs):
    """
  Help function to unwrap argument list that contain variable pair(s) and selection:
    gethist2D(str xvar, int nxbins, float xmin, float xmax, str yvar, int nybins, float ymin, float ymax, str cuts="")
    gethist2D(str xvar, list xbins, str yvar, list ybins, str cuts="")
    gethist2D(str xvar, int nxbins, float xmin, float xmax, str yvar, list ybins, str cuts="")
    gethist2D(str xvar, list xbins, str yvar, int nybins, float ymin, float ymax, str cuts="")
    gethist2D(Variable xvar, Variable yvar, str cuts="")
    gethist2D(tuple xvar, tuple yvar, str cuts="")
    gethist2D(list xvarlist, list yvarlist, str cuts="")
    gethist2D(list varlist, str cuts="")
    gethist2D(tuple varpair, str cuts="")
  where the tuples xvar and yvar can be of the form
    – (str xvar, int nxbins, float xmin, float xmax)
    – (str xvar, list xbins)
  and the [xy]varlist is a list of Variables object pairs,
    - [(Variable xvar,Variable yvar), ... ]
  or a list of tuples defining a variable:
    - [(str xvar, int nxbins, float xmin, float xmax, str yvar, int nybins, float ymin, float ymax), ...]
    - [(str xvar, list xbins), ...]
  and varpair is tuple of a single pair of Variable objects:
    - (Variable xvar,Variable yvar)
  Returns a list of Variable pairs, a Selection object, and a boolean to flag a single
  instead of a list of variables was given:
    (list varpairs, str cut, bool single)
  For testing, see test/testUnwrapping.py.
  """
    verbosity = LOG.getverbosity(kwargs)
    vars = None  # list of Variable objects
    sel = None  # selection (string or Selection object)
    single = False  # only one Variable passed
    if len(args) >= 1:
        if isinstance(args[-1], Selection):
            sel = args[-1]
            vargs = args[:-1]
        elif isinstance(args[-1], str):
            sel = Selection(args[-1])
            vargs = args[:-1]
        else:
            sel = Selection()  # no selection given
            vargs = args
    if len(vargs) == 1:
        vars = vargs[0]
        single = len(vars) == 2 and islist(vars) and all(
            isinstance(v, Variable) for v in vars)
        if single:
            vars = [vars]
    elif len(vargs) == 2:
        xvars, yvars = vargs
        if isinstance(xvars, Variable) and isinstance(yvars, Variable):
            vars = [(xvars, yvars)]
            single = True
        elif all(isinstance(v, Variable)
                 for v in xvars + yvars):  # assume list
            vars = zip(xvars, yvars)
        elif len(xvars) in [2, 4] and len(yvars) in [2, 4] and isinstance(
                xvars[0], str) and isinstance(yvars[0], str):
            vars = [Variable(*xvars), Variable(*yvars)]
            single = True
        elif islist(xvars) and islist(yvars) and all(
                islist(x) for x in xvars) and all(islist(y) for y in yvars):
            vars = [(Variable(*x), Variable(*y)) for x, y in zip(xvars, yvars)]
    elif len(vargs) == 4:
        vars = [(Variable(*vargs[0:2]), Variable(*vargs[2:4]))]
        single = True
    elif len(vargs) == 6:
        if isinstance(vargs[2], str):
            vars = [(Variable(*vargs[0:2]), Variable(*vargs[2:6]))]
            single = True
        elif isinstance(vargs[4], str):
            vars = [(Variable(*vargs[0:4]), Variable(*vargs[4:6]))]
            single = True
    elif len(vargs) == 8:
        vars = [(Variable(*vargs[0:4]), Variable(*vargs[4:8]))]
        single = True
    if vars == None or sel == None:
        LOG.throw(
            IOError,
            'unwrap_gethist2D_args: Could not unwrap arguments %s, len(args)=%d, vars=%s, sel=%s.'
            % (args, len(args), vars, sel))
    elif isinstance(sel, str):
        sel = Selection(str)
    LOG.verb("unwrap_gethist2D_args: args=%r" % (args, ), verbosity, 3)
    LOG.verb(
        "unwrap_gethist2D_args: vars=%s, sel=%r, single=%r" %
        (vars, sel.selection, single), verbosity, 4)
    return vars, sel, single
コード例 #8
0
def unwrap_gethist2D_args(*args, **kwargs):
    """
  Help function to unwrap argument list that contain variable pair(s) and selection:
    - gethist2D(str xvar, int nxbins, float xmin, float xmax, str yvar, int nybins, float ymin, float ymax, str cuts)
    - gethist2D(str xvar, list xbins, str yvar, list ybins, str cuts)
    - gethist2D(Variable xvar, Variable yvar, str cuts)
    - gethist2D(tuple xvar, tuple yvar, str cuts)
    - gethist2D(list xvarlist, list yvarlist, str cuts)
    - gethist2D(list varlist, str cuts)
    - gethist2D(tuple varpair, str cuts)
  where the tuples xvar and yvar can be
    – (str xvar, int nxbins, float xmin, float xmax)
    – (str xvar, list xbins)
  and the [xy]varlist is a list of Variables object pairs,
    - [(Variable xvar,Variable yvar), ... ]
  or a list of tuples defining a variable:
    - [(str xvar, int nxbins, float xmin, float xmax, str yvar, int nybins, float ymin, float ymax), ...]
    - [(str xvar, list xbins), ...]
  and varpair is tuple of a single pair of Variable objects:
    - (Variable xvar,Variable yvar)
  Returns a list of Variable pairs, a selection string, and a boolean to flag a single
  instead of a list of variables was given:
    (list varpairs, str cut, bool single)
  For testing, see test/testUnwrapping.py.
  """
    vars = None  # list of Variable objects
    sel = None  # selection (string)
    single = False  # only one pair of Variable objects passed
    if len(args) == 2:
        vars, sel = args
        single = len(vars) == 2 and islist(vars) and all(
            isinstance(v, Variable) for v in vars)
        if single:
            vars = [vars]
    elif len(args) == 3:
        xvars, yvars, sel = args
        if isinstance(xvars, Variable) and isinstance(yvars, Variable):
            vars = [(xvars, yvars)]
            single = True
        elif all(isinstance(v, Variable)
                 for v in xvars + yvars):  # assume list
            vars = zip(xvars, yvars)
        elif len(xvars) in [2, 4] and len(yvars) in [2, 4] and isinstance(
                xvars[0], str) and isinstance(yvars[0], str):
            vars = [Variable(*xvars), Variable(*yvars)]
            single = True
        elif islist(xvars) and islist(yvars) and all(
                islist(x) for x in xvars) and all(islist(y) for y in yvars):
            vars = [(Variable(*x), Variable(*y)) for x, y in zip(xvars, yvars)]
    elif len(args) == 5:
        vars = [(Variable(*args[0:2]), Variable(*args[2:4]))]
        sel = args[-1]
        single = True
    elif len(args) == 9:
        vars = [(Variable(*args[0:4]), Variable(*args[4:8]))]
        sel = args[-1]
        single = True
    if vars == None or sel == None:
        LOG.throw(
            IOError,
            'unwrap_gethist2D_args: Could not unwrap arguments %s, len(args)=%d, vars=%s, sel=%s.'
            % (args, len(args), vars, sel))
    LOG.verb("unwrap_gethist2D_args: vars=%s, sel=%r, single=%r" %
             (vars, sel, single),
             level=3)
    return vars, sel, single