Пример #1
0
def plotsamples(datasample, expsamples, tag=""):
    """Test Sample.gethist method and plot data/MC comparison."""
    LOG.header("plotsamples")

    # SETTING
    outdir = ensuredir("plots")
    fname = "%s/testSamples_$VAR%s.png" % (outdir, tag)

    # MAKE 1D HISTS
    for selection, weight in selections:
        histdict = {}
        for sample in [datasample] + expsamples:
            hists = sample.gethist(variables, selection)
            histdict[sample] = hists
            print ">>> %r: %s" % (sample.name,
                                  [repr(h.GetName()) for h in hists])

        # PLOT
        for i, variable in enumerate(variables):
            #LOG.header(variable)
            datahist = histdict[datasample][i]
            exphists = [histdict[s][i] for s in expsamples]
            plot = Stack(variable, datahist, exphists)
            plot.draw(ratio=True)
            plot.drawlegend(position=position)
            plot.drawtext(text)
            plot.saveas(fname)
            plot.close()
Пример #2
0
def plotstack(xname,xtitle,datahist,exphists,ratio=False,logy=False):
  """Plot Stack objects for a given data hisogram and list of MC histograms."""
  
  # SETTING
  outdir   = ensuredir("plots")
  fname    = "%s/testStack_%s"%(outdir,xname)
  if ratio:
    fname += "_ratio"
  if logy:
    fname += "_logy"
  rrange   = 0.5
  text     = "#mu#tau_{h} baseline"
  grid     = True and False
  position = 'topright' if logy else 'right'
  
  # PLOT
  LOG.header(fname)
  plot = Stack(xtitle,datahist,exphists)
  plot.draw(ratio=ratio,logy=logy,ratiorange=rrange,grid=grid)
  plot.drawlegend(position=position)
  plot.drawtext(text)
  plot.saveas(fname+".png")
  plot.saveas(fname+".pdf")
  #plot.saveas(fname+".C")
  #plot.saveas(fname+".png",fname+".C")
  #plot.saveas(fname,ext=['png','pdf'])
  plot.close()
  print
Пример #3
0
def stackinputs(file, variable, processes, **kwargs):
    """Stack histograms from ROOT file.
       file:       TFile or TDirectory object
       variable:  Variables object
       processes: list of strings (name of processes)
     e.g.
       stackinputs(file,variable,['ZTT','TTT','W','QCD','data_obs'])
  """
    text = kwargs.get('text', None)
    tag = kwargs.get('tag', "")
    groups = kwargs.get('group', [])  # e.g. [(['^TT','ST'],'Top')]
    dname = kwargs.get('dname', None)  # directory ('bin') name
    pname = kwargs.get('save', "stack$TAG.png")  # save as image file
    wname = kwargs.get('write', "stack$TAG")  # write to file
    style = kwargs.get('style', False)  # write style to file

    exphists = []
    datahist = None
    tdir = ensureTDirectory(file, dname, cd=True) if dname else file
    if style:
        gStyle.Write(
            'style',
            TH1.kOverwrite)  # write current TStyle object to reproduce plots
    for process in processes:
        hname = process
        hist = gethist(tdir, process, fatal=False, warn=False)
        if not hist:
            LOG.warning(
                "stackinputs: Could not find %r in %s. Skipping stacked plot..."
                % (process, tdir.GetPath()))
            return
        hist.SetDirectory(0)
        hist.SetLineColor(kBlack)
        hist.SetFillStyle(1001)  # assume fill color is already correct
        if process == 'data_obs':
            datahist = hist
        else:
            exphists.append(hist)
    for group in groups:
        grouphists(exphists, *group, replace=True, regex=True, verb=0)
    stack = Stack(variable, datahist, exphists)
    stack.draw()
    stack.drawlegend(ncols=2, twidth=0.9)
    if text:
        stack.drawtext(text)
    if pname:
        pname = repkey(pname, TAG=tag)
        stack.saveas(pname, ext=['png'])
    if wname:
        wname = repkey(wname, TAG=tag)
        stack.canvas.Write(wname, TH1.kOverwrite)
    stack.close()
Пример #4
0
def drawpostfit(fname, bin, procs, **kwargs):
    """Plot pre- and post-fit plots PostFitShapesFromWorkspace."""
    print '>>>\n>>> drawpostfit("%s","%s")' % (fname, bin)
    outdir = kwargs.get('outdir', "")
    pname = kwargs.get('pname',
                       "$FIT.png")  # replace $FIT = 'prefit', 'postfit'
    ratio = kwargs.get('ratio', True)
    tag = kwargs.get('tag', "")
    xtitle = kwargs.get('xtitle', None)
    title = kwargs.get('title', None)
    text = kwargs.get('text', "")
    tsize = kwargs.get('tsize', 0.050)
    xmin = kwargs.get('xmin', None)
    xmax = kwargs.get('xmax', None)
    ymargin = kwargs.get('ymargin', 1.22)
    groups = kwargs.get('group', [])
    position = kwargs.get('pos', None)  # legend position
    ncol = kwargs.get('ncol', None)  # legend columns
    square = kwargs.get('square', False)
    era = kwargs.get('era', "")
    exts = kwargs.get('exts', ['pdf', 'png'])  # figure extension
    ymax = None
    fits = ['prefit', 'postfit']
    file = ensureTFile(fname, 'READ')
    if outdir:
        ensuredir(outdir)
    if era:
        setera(era)

    # DRAW PRE-/POST-FIT
    for fit in fits:
        fitdirname = "%s_%s" % (bin, fit)
        dir = file.Get(fitdirname)
        if not dir:
            LOG.warning('drawpostfit: Did not find dir "%s"' % (fitdirname),
                        pre="   ")
            return
        obshist = None
        exphists = []

        # GET HIST
        for proc in procs:  #reversed(samples):
            hname = "%s/%s" % (fitdirname, proc)
            hist = file.Get(hname)
            if not hist:
                LOG.warning(
                    'drawpostfit: Could not find "%s" template in directory "%s_%s"'
                    % (proc, bin, fit),
                    pre="   ")
                continue
            if 'data_obs' in proc:
                obshist = hist
                hist.SetLineColor(1)
                ymax = hist.GetMaximum() * ymargin
            else:
                exphists.append(hist)
            if proc in STYLE.sample_titles:
                hist.SetTitle(STYLE.sample_titles[proc])
            if proc in STYLE.sample_colors:
                hist.SetFillStyle(1001)
                hist.SetFillColor(STYLE.sample_colors[proc])
        if len(exphists) == 0:
            LOG.warning(
                'drawpostfit: Could not find any templates in directory "%s"' %
                (bin),
                pre="   ")
            continue
        if not obshist:
            LOG.warning(
                'drawpostfit: Could not find a data template in directory "%s"'
                % (bin),
                pre="   ")
            continue
        for groupargs in groups:
            grouphists(exphists, *groupargs, replace=True)

        # PLOT
        xtitle = (xtitle or exphists[0].GetXaxis().GetTitle()
                  )  #.replace('[GeV]','(GeV)')
        xmax = xmax or exphists[0].GetXaxis().GetXmax()
        xmin = xmin or exphists[0].GetXaxis().GetXmin()
        errtitle = "Pre-fit stat. + syst. unc." if fit == 'prefit' else "Post-fit unc."
        pname_ = repkey(pname, FIT=fit, ERA=era)
        rmin, rmax = (0.28, 1.52)
        plot = Stack(xtitle, obshist, exphists)
        plot.draw(xmin=xmin,
                  xmax=xmax,
                  ymax=ymax,
                  square=square,
                  ratio=ratio,
                  rmin=rmin,
                  rmax=rmax,
                  staterror=True,
                  errtitle=errtitle)
        plot.drawlegend(position, tsize=tsize, text=text, ncol=ncol)
        if title:
            plot.drawtext(title, bold=False)
        plot.saveas(pname_, outdir=outdir, ext=exts)
        plot.close()

    file.Close()