Example #1
0
def Create_Legend(x1,
                  y1,
                  x2,
                  y2,
                  font=42,
                  text_size=0.045,
                  fill=0,
                  border_size=1,
                  entry_sep=0,
                  margin=0.3,
                  show_stats=False,
                  ncols=1):

    leg = TLegend(x1, y1, x2, y2)
    leg.SetTextFont(font)
    leg.SetTextSize(text_size)
    leg.SetFillColor(fill)
    leg.SetBorderSize(border_size)
    leg.SetEntrySeparation(entry_sep)
    leg.SetMargin(margin)
    leg.SetNColumns(ncols)

    if show_stats:
        leg.SetNColumns(2)

        ## Creating headers for the legend
        leg.AddEntry(0, "", "")
        # leg.AddEntry( 0, "#bf{Mean}", "")
        leg.AddEntry(0, "#bf{RMSE}", "")

    return leg
Example #2
0
def phicomparison(rbef,raft,wheel,station,name,title):
  hb = barrelSectorAvg( rbef, wheel, station, name+"_bef", title )
  ha = barrelSectorAvg( raft, wheel, station, name+"_aft", title )
  hsettings(ha); ha.SetLineColor(kBlue); ha.SetLineWidth(3)
  hsettings(hb); hb.SetLineColor(kRed);  hb.SetLineWidth(3)
  
  acan = TCanvas("can","",1200,700)
  leg = TLegend(0.645,0.68,0.845,0.88) 
  leg.SetFillStyle( 0 )
  leg.SetBorderSize(0)
  leg.SetMargin( 0.1 )

  maxx = hb.GetMaximum()
  if maxx < ha.GetMaximum():
    maxx = ha.GetMaximum()

  ha.SetMaximum(1.1*maxx)
  hb.SetMaximum(1.1*maxx)

  leg.AddEntry(ha, "after  TS2", "l")
  leg.AddEntry(hb, "before TS2", "l")
  ha.Draw("same hist")
  hb.Draw("same hist")
  leg.Draw("same")
  acan.SaveAs(name+".png")
  acan.Clear()

  return {"before":hb,"after":ha}
 def plotHists(hists,xtitle,plotname,header,ctexts=[ ],otext="",logy=False,y1=0.70):
     colors = [ kBlue, kRed, kGreen+2, kOrange, kMagenta+1 ]
     canvas   = TCanvas('canvas','canvas',100,100,800,700)
     canvas.SetMargin(0.12,0.03,0.14,0.06 if otext else 0.03)
     textsize = 0.040
     height   = 1.28*(len(hists)+1)*textsize
     y1
     legend   = TLegend(0.65,y1,0.88,y1-height)
     legend.SetTextSize(textsize)
     legend.SetBorderSize(0)
     legend.SetFillStyle(0)
     legend.SetFillColor(0)
     legend.SetTextFont(62)
     legend.SetHeader(header)
     legend.SetTextFont(42)
     legend.SetMargin(0.2)
     latex = TLatex()
     latex.SetTextAlign(13)
     latex.SetTextFont(42)
     latex.SetNDC(True)
     frame = hists[0]
     frame.GetXaxis().SetTitle(xtitle)
     frame.GetYaxis().SetTitle("Fraction [%]")
     frame.GetXaxis().SetLabelSize(0.074)
     frame.GetYaxis().SetLabelSize(0.046)
     frame.GetXaxis().SetTitleSize(0.048)
     frame.GetYaxis().SetTitleSize(0.052)
     frame.GetXaxis().SetTitleOffset(1.38)
     frame.GetYaxis().SetTitleOffset(1.12)
     frame.GetXaxis().SetLabelOffset(0.009)
     frame.SetMaximum(1.25*max(h.GetMaximum() for h in hists))
     if logy:
       canvas.SetLogy()
       frame.SetMinimum(1e-3)
     else:
       frame.SetMinimum(0)
     for i, hist in enumerate(hists):
       hist.Draw('HISTE0E1SAME')
       hist.SetLineWidth(2)
       hist.SetLineColor(colors[i%len(colors)])
       legend.AddEntry(hist,hist.GetTitle(),'le')
     legend.Draw()
     for i, text in enumerate(ctexts):
       textsize = 0.024 #if i>0 else 0.044
       latex.SetTextSize(textsize)
       latex.DrawLatex(0.14,0.98-canvas.GetTopMargin()-1.7*i*textsize,text)
     if otext:
       latex.SetTextSize(0.05)
       latex.SetTextAlign(31)
       latex.DrawLatex(1.-canvas.GetRightMargin(),1.-0.84*canvas.GetTopMargin(),otext)
     canvas.SaveAs(plotname+".png")
     canvas.SaveAs(plotname+".pdf")
     canvas.Close()
     for hist in hists:
       gDirectory.Delete(hist.GetName())
Example #4
0
def getLegend():
    legend = TLegend(0.55010112, 0.7183362, 0.70202143, 0.919833)
    legend.SetTextSize(0.032)
    legend.SetLineColor(0)
    legend.SetShadowColor(0)
    legend.SetLineStyle(1)
    legend.SetLineWidth(1)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetMargin(0.35)
    return legend
Example #5
0
def getLegend(x1=0.70010112,y1=0.123362,x2=0.90202143,y2=0.279833):
  legend = TLegend(x1,y1,x2,y2)
  legend.SetTextSize(0.032)
  legend.SetLineColor(0)
  legend.SetShadowColor(0)
  legend.SetLineStyle(1)
  legend.SetLineWidth(1)
  legend.SetFillColor(0)
  legend.SetFillStyle(0)
  legend.SetMargin(0.35)
  return legend
Example #6
0
def setup_canvas(hist_name):
    canvas = TCanvas(hist_name, hist_name, 0, 0, 800, 800)
    canvas.SetMargin(0.13, 0.05, 0.12, 0.05)
    canvas.SetTicks(1, 1)

    leg = TLegend(0.3, 0.15, 0.75, 0.4)
    leg.SetNColumns(3)
    leg.SetBorderSize(0)
    leg.SetTextSize(0.03)
    leg.SetTextFont(42)
    leg.SetMargin(0.2)
    leg.SetHeader("Train setup: #it{N}_{ev}^{training}, #it{n}_{#it{#varphi}}" +\
                  " #times #it{n}_{#it{r}} #times #it{n}_{#it{z}}", "C")

    return canvas, leg
Example #7
0
def make_legend(x1=.65,
                y2=.88,
                nentries=2,
                scale=1,
                name='l',
                y1=None,
                margin=.25,
                x2=None):
    x2 = .95 if x2 is None else x2
    y1 = y2 - nentries * .05 * scale if y1 is None else y1
    l = TLegend(x1, y1, x2, y2)
    l.SetName(name)
    l.SetTextFont(42)
    l.SetTextSize(0.03 * scale)
    l.SetMargin(margin)
    return l
Example #8
0
def checklegend(samples,tag=""):
  """Check legend entries: colors, titles, ..."""
  # https://root.cern.ch/doc/master/classTLegend.html
  LOG.header("checklegend"+tag.replace(' ',''))
  output = ensuredir('plots')
  fname  = "%s/testStyle_legend%s"%(output,tag)
  #height = 0.05*(len(samples))
  xdim   = 550
  ydim   = 50*(len(samples)+2)
  #width  = 0.4
  #x1, y1 = 0.1, 0.9
  print ">>> Canvas: %sx%s (nsamples=%d)"%(xdim,ydim,len(samples))
  canvas = TCanvas('canvas','canvas',xdim,ydim)
  #legend = TLegend(x1,y1,x1+width,y1-height)
  legend = TLegend(0,0,1,1)
  legend.SetBorderSize(0)
  legend.SetMargin(0.12)
  #legend.SetTextSize(tsize)
  #legend.SetNColumns(ncols)
  #legend.SetColumnSeparation(colsep)
  #legend.SetHeader("HTT style",'C')
  legend.SetTextFont(42) # bold for title
  hists = [ ]
  for sample in samples:
    color = STYLE.getcolor(sample,verb=2)
    title = STYLE.gettitle(sample,latex=True,verb=2)
    style = 'ep' if 'Data' in sample else 'f'
    hist  = TH1F(sample,title,1,0,1)
    hist.SetFillColor(color)
    #hist.SetLineColor(kBlack)
    hist.SetLineWidth(2)
    hist.SetMarkerColor(kBlack)
    #hist.SetMarkerStyle(1)
    legend.AddEntry(hist,title,style)
    if 'Data' in sample: hist.Draw('E1')
    hists.append(hist)
  legend.Draw()
  canvas.SaveAs(fname+".png")
  canvas.SaveAs(fname+".pdf")
  canvas.Close()
Example #9
0
def DrawText(can,text='text',x1=None,y1=None,x2=None,y2=None,angle=0,align='',textsize=18,totalentries=1) :

    if x1 == None : x1 = 0.2
    if x2 == None : x2 = 0.5

    if can.GetPrimitive('pad_top') :
        if y1 == None : y1 = 0.73
        if y2 == None : y2 = 0.93
    else :
        if y1 == None : y1 = 0.78
        if y2 == None : y2 = 0.94

    can.cd()
    if can.GetPrimitive('pad_top') :
        can.GetPrimitive('pad_top').cd()
    from ROOT import TLegend
    leg = TLegend(x1,y1,x2,y2)
    leg.SetMargin(0)
    leg.SetName(can.GetName()+'_text')
    tobject_collector.append(leg)
    leg.SetTextSize(textsize)
    leg.SetTextFont(43)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    if type(text) == type('') :
        text = [text]
    total = 0
    for i in text :
        leg.AddEntry(0,i,'')
        total += 1
    while (total < totalentries) :
        leg.AddEntry(0,'','')
        total += 1
    leg.Draw()
    can.Modified()
    #can.Update()
    return
Example #10
0
     if (i > 0):
         binwidths.append(bins[i] - bins[i - 1])
     else:
         binwidths.append(30.0)
 #print binwidths
 normCMS = normalizeGraph(unnormCMS, binwidths)
 normCMS.SetMarkerStyle(kFullCircle)
 normCMS.SetMarkerSize(1.4)
 normCMS.SetMarkerColor(kBlue + 2)
 normCMS.SetLineColor(kBlue + 2)
 normCMS.Draw('apz')
 normCMS.SetMaximum(0.3)
 leg = TLegend(0.4, 1. - gPad.GetTopMargin() - 0.03 - 0.18,
               1. - gPad.GetRightMargin() - 0.02,
               1. - gPad.GetTopMargin() - 0.03, '', 'NDC')
 leg.SetMargin(0.15)
 #leg.Dump()
 leg.SetFillStyle(0)
 leg.SetBorderSize(0)
 leg.AddEntry(normCMS, 'CMS, |y|<2, #sqrt{s}=7 TeV', 'pe')
 if (D0):
     D0.Draw('pz')
     leg.AddEntry(D0, 'D#oslash, |y|<1.8, #sqrt{s}=1.96 TeV', 'pe')
 else:
     leg.SetY1(1. - gPad.GetTopMargin() - 0.03 - 0.12)
 if (CDF):
     CDF.Draw('pz')
     leg.AddEntry(CDF, 'CDF, |y|<0.4, #sqrt{s}=1.8 TeV', 'pe')
 #leg.Dump()
 leg.Draw('same')
 l.DrawLatex(1.0 - gPad.GetRightMargin() - 0.04,
Example #11
0
def main():  
  rpcrateB = RPCRates('316111',"m")
  rpcrateA = RPCRates('323726',"m")
  rpcrateA.rates_ = load_json("ratesAt1p5After.json")
  rpcrateB.rates_ = load_json("ratesAt1p5before.json")

  hREP4A = rollavg( rpcrateA.rates_, "hREP4A", "RE+4/R3", "RE+4_R3_" )
  hREM4A = rollavg( rpcrateA.rates_, "hREM4A", "RE-4/R3", "RE-4_R3_" )

  hREP4B = rollavg( rpcrateB.rates_, "hREP4B", "RE+4/R3", "RE+4_R3_" )
  hREM4B = rollavg( rpcrateB.rates_, "hREM4B", "RE-4/R3", "RE-4_R3_" )

  hsettings(hREP4A); hREP4A.SetLineColor(kBlue)
  hsettings(hREM4A); hREM4A.SetLineColor(kBlue)
  hsettings(hREP4B); hREP4B.SetLineColor(kRed)
  hsettings(hREM4B); hREM4B.SetLineColor(kRed)

  acan = TCanvas("can","",1200,700)

  leg = TLegend(0.645,0.68,0.845,0.88) 
  leg.SetFillStyle( 0 )
  leg.SetBorderSize(0)
  leg.SetMargin( 0.1 )
  
  #leg.AddEntry(hREP4B, "before TS2", "l")
  #leg.AddEntry(hREP4A, "after  TS2", "l")
  #hREP4B.Draw("same hist")
  #hREP4A.Draw("same hist")
  #leg.Draw("same")
  #acan.SaveAs("compREP4.png")
  #acan.Clear()
  #return

  #leg.AddEntry(hREM4B, "before TS2", "l")
  #leg.AddEntry(hREM4A, "after  TS2", "l")
  #hREM4B.Draw("same hist")
  #hREM4A.Draw("same hist")
  #leg.Draw("same")
  #acan.Update()
  #acan.SaveAs("compREM4.png")
  #acan.Clear()
  #return

  hREP4A.Divide(hREP4B)
  hREM4A.Divide(hREM4B)
  hREP4A.SetLineColor(kBlue); hREP4A.SetLineWidth(3)
  hREM4A.SetLineColor(kRed);  hREM4A.SetLineWidth(3)
  hREP4A.GetYaxis().SetTitle("rate ratio")
  hREM4A.GetYaxis().SetTitle("rate ratio")
  hREP4A.SetMaximum(1.5)
  hREM4A.SetMaximum(1.5)
  #leg.AddEntry(hREP4A, "RE+4", "l")
  #leg.AddEntry(hREM4A, "RE-4", "l")
  #hREP4A.Draw("same hist")
  #hREM4A.Draw("same hist")
  #leg.Draw("same")
  #acan.SaveAs("ratiosRE4.png")
  #acan.Clear()
  #return

  mapcreator = RPCMapCreator()  
  histsB = mapcreator.create2Dhistograms( rpcrateB.rates_, 'RPC', "run316111")
  histsA = mapcreator.create2Dhistograms( rpcrateA.rates_, 'RPC', "run323726")
  #prep4_b = histsB["RE+4"].ProjectionX ("rep4b_pfx"); prep4_a = histsA["RE+4"].ProjectionX ("rep4a_pfx")
  #prem4_b = histsB["RE-4"].ProjectionX ("rem4b_pfx"); prem4_a = histsA["RE-4"].ProjectionX ("rem4a_pfx")
  #prep4_b = histsB["RE+4"].ProfileX ("rep4b_pfx"); prep4_a = histsA["RE+4"].ProfileX ("rep4a_pfx")
  #prem4_b = histsB["RE-4"].ProfileX ("rem4b_pfx"); prem4_a = histsA["RE-4"].ProfileX ("rem4a_pfx")
  rep4B = histsB["RE+4"]; rep4A = histsA["RE+4"]
  rem4B = histsB["RE-4"]; rem4A = histsA["RE-4"]

  #prep4_b.SetLineColor(kBlue)
  #prep4_a.SetLineColor(kRed)
  #prem4_b.SetLineColor(kBlue)
  #prem4_a.SetLineColor(kRed)
  #acan.cd()
  rep4A.Divide(rep4B)
  rep4A.SetMaximum(1.1)
  rep4A.SetMinimum(0.9)
  rep4A.Draw("text89 colz")
  acan.SaveAs("ratios2DREP4.png")
Example #12
0
def savePlots(title,
              saveName,
              listFromats,
              plot,
              Histos,
              keyHisto,
              listLegend,
              options,
              ratios=None,
              legendName=""):
    #create canvas
    c = {}
    pads = {}
    if options.doRatio:
        c[keyHisto] = TCanvas(saveName, keyHisto + plot.title, 700,
                              700 + 24 * len(listFlavors))
        pads["hist"] = TPad("hist", saveName + plot.title, 0,
                            0.11 * len(listFlavors), 1.0, 1.0)
    else:
        c[keyHisto] = TCanvas(keyHisto, saveName + plot.title, 700, 700)
        pads["hist"] = TPad("hist", saveName + plot.title, 0, 0., 1.0, 1.0)
    pads["hist"].Draw()
    if ratios:
        for r in range(0, len(ratios)):
            pads["ratio_" + str(r)] = TPad("ratio_" + str(r),
                                           saveName + plot.title + str(r), 0,
                                           0.11 * r, 1.0, 0.11 * (r + 1))
            pads["ratio_" + str(r)].Draw()
    pads["hist"].cd()
    #canvas style
    if plot.logY: pads["hist"].SetLogy()
    if plot.grid: pads["hist"].SetGrid()
    #legend
    leg = TLegend(0.6, 0.4, 0.8, 0.6)
    leg.SetMargin(0.12)
    leg.SetTextSize(0.035)
    leg.SetFillColor(10)
    leg.SetBorderSize(0)
    #draw histos
    first = True
    option = drawOption
    optionSame = drawOption + "same"
    if plot.doPerformance:
        option = "AP"
        optionSame = "sameP"
    for i in range(0, len(Histos)):
        if Histos[i] is None: continue
        if first:
            if not plot.doPerformance:
                Histos[i].GetPainter().PaintStat(ROOT.gStyle.GetOptStat(), 0)
            Histos[i].SetTitle(title)
            Histos[i].Draw(option)
            first = False
        else:
            Histos[i].Draw(optionSame)
        #Fill legend
        if plot.legend and len(Histos) % len(listLegend) == 0:
            r = len(Histos) / len(listLegend)
            index = i - r * len(listLegend)
            while (index < 0):
                index += len(listLegend)
            legName = legendName.replace("KEY", listLegend[index])
            if i < len(listLegend):
                legName = legName.replace("isVAL", options.ValRel)
            else:
                legName = legName.replace("isVAL", options.RefRel)
            if drawOption == "HIST":
                leg.AddEntry(Histos[i], legName, "L")
            else:
                leg.AddEntry(Histos[i], legName, "P")
    #Draw legend
    if plot.legend and options.drawLegend: leg.Draw("same")
    tex = None
    if options.printBanner:
        print(type(options.printBanner))
        tex = TLatex(0.55, 0.75, options.Banner)
        tex.SetNDC()
        tex.SetTextSize(0.05)
        tex.Draw()
    #save canvas
    if ratios:
        for r in range(0, len(ratios)):
            pads["ratio_" + str(r)].cd()
            if ratios[r] is None: continue
            pads["ratio_" + str(r)].SetGrid()
            ratios[r].GetYaxis().SetTitle(listLegend[r] + "-jets")
            ratios[r].GetYaxis().SetTitleSize(0.15)
            ratios[r].GetYaxis().SetTitleOffset(0.2)
            ratios[r].GetYaxis().SetNdivisions(3, 3, 2)
            ratios[r].Draw("")
            unity.Draw("same")
    for format in listFromats:
        save = saveName + "." + format
        c[keyHisto].Print(save)
    return [c, leg, tex, pads]
Example #13
0
class DataMCPlot(object):
    '''Handles a Data vs MC plot.

    Features a list of histograms (some of them being stacked),
    and several Drawing functions.
    '''
    _f_keeper = {}
    _t_keeper = {}

    def __init__(self, name):
        self.histosDict = {}
        self.histos = []
        self.supportHist = None
        self.name = name
        self.stack = None
        self.legendOn = True
        self.legend = None
        #        self.legendBorders = 0.20, 0.46, 0.44, 0.89
        #        self.legendPos = 'left'
        self.legendBorders = 0.20, 0.78, 0.80, 0.88
        self.legendPos = 'top'
        # self.lastDraw = None
        # self.lastDrawArgs = None
        self.nostack = None
        self.blindminx = None
        self.blindmaxx = None
        self.groups = {}
        self.axisWasSet = False
        self.histPref = histPref

    def __contains__(self, name):
        return name in self.histosDict

    def __getitem__(self, name):
        return self.histosDict[name]

    def readTree(self,
                 file_name,
                 tree_name='tree',
                 verbose=False,
                 friend_func=None):
        '''Cache files/trees'''
        if file_name in self.__class__._t_keeper:
            ttree = self.__class__._t_keeper[file_name]
            if verbose:
                print 'got cached tree', ttree
        else:
            tfile = self.__class__._f_keeper[file_name] = TFile.Open(file_name)
            ttree = self.__class__._t_keeper[file_name] = tfile.Get(tree_name)
            if verbose:
                print 'read tree', ttree, 'from file', file_name

        if friend_func:
            file_name = friend_func(file_name)
            friend_tree = self.readTree(file_name, tree_name, verbose)
            ttree.AddFriend(friend_tree)

        gROOT.cd()

        return ttree

    def Blind(self, minx, maxx, blindStack):
        self.blindminx = minx
        self.blindmaxx = maxx
        if self.stack and blindStack:
            self.stack.Blind(minx, maxx)
        if self.nostack:
            for hist in self.nostack:
                if hist.style.drawAsData:
                    hist.Blind(minx, maxx)

    def AddHistogram(self, name, histo, layer=0, legendLine=None, stack=True):
        '''Add a ROOT histogram, with a given name.

        Histograms will be drawn by increasing layer.'''
        tmp = Histogram(name, histo, layer, legendLine, stack=stack)
        self.histos.append(tmp)
        self.histosDict[name] = tmp
        return tmp

    def Group(self,
              groupName,
              namesToGroup,
              layer=None,
              style=None,
              silent=False):
        '''Group all histos with names in namesToGroup into a single
        histo with name groupName. All histogram properties are taken
        from the first histogram in namesToGroup.
        See UnGroup as well
        '''
        groupHist = None
        realNames = []
        actualNamesInGroup = []
        for name in namesToGroup:
            hist = self.histosDict.get(name, None)
            if hist is None:
                if not silent:
                    print 'warning, no histo with name', name
                continue
            if groupHist is None:
                groupHist = hist.Clone(groupName)
                self.histos.append(groupHist)
                self.histosDict[groupName] = groupHist
            else:
                groupHist.Add(hist)
            actualNamesInGroup.append(name)
            realNames.append(hist.realName)
            hist.on = False
        if groupHist:
            self.groups[groupName] = actualNamesInGroup
            groupHist.realName = ','.join(realNames)
            if style is not None:
                groupHist.SetStyle(style)
            self._ApplyPrefs()

    def UnGroup(self, groupName):
        '''Ungroup groupName, recover the histograms in the group'''
        group = self.groups.get(groupName, None)
        if group is None:
            print groupName, 'is not a group in this plot.'
            return
        for name in group:
            self.histosDict[name].on = True
        self.histosDict[groupName].on = False

    def Replace(self, name, pyhist):
        '''Not very elegant... should have a clone function in Histogram...'''
        oldh = self.histosDict.get(name, None)
        if oldh is None:
            print 'histogram', name, 'does not exist, cannot replace it.'
            return

        pythist = copy.deepcopy(pyhist)
        pythist.layer = oldh.layer
        pythist.stack = oldh.stack
        pythist.name = oldh.name
        pythist.legendLine = oldh.legendLine
        pythist.SetStyle(oldh.style)
        pythist.weighted.SetFillStyle(oldh.weighted.GetFillStyle())

        index = self.histos.index(oldh)
        self.histosDict[name] = pythist
        self.histos[index] = pythist

    def _SortedHistograms(self, reverse=False):
        '''Returns the histogram dictionary, sorted by increasing layer,
        excluding histograms which are not "on".

        This function is used in all the Draw functions.'''
        byLayer = sorted(self.histos, key=attrgetter('layer'))
        byLayerOn = [hist for hist in byLayer if (hist.on is True)]
        if reverse:
            byLayerOn.reverse()
        return byLayerOn

    def Hist(self, histName):
        '''Returns a histogram.

        Print the DataMCPlot object to see which histograms are available.'''
        return self.histosDict[histName]

    def DrawNormalized(self, opt=''):
        '''All histograms are drawn as PDFs, even the stacked ones'''
        same = ''
        for hist in self._SortedHistograms():
            hist.obj.DrawNormalized(same + opt)
            if same == '':
                same = 'same'
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalized'
        # self.lastDrawArgs = [ opt ]

    def Draw(self, opt=''):
        '''All histograms are drawn.'''
        same = ''
        self.supportHist = None
        for hist in self._SortedHistograms():
            if self.supportHist is None:
                self.supportHist = hist
            hist.Draw(same + opt)
            if same == '':
                same = 'same'
#        set_trace()
        yaxis = self.supportHist.GetYaxis()
        yaxis.SetRangeUser(0.01, 1.5 * ymax(self._SortedHistograms()))
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'Draw'
        # self.lastDrawArgs = [ opt ]

    def CreateLegend(self, ratio=False, print_norm=False):
        if self.legend is None:
            self.legend = TLegend(*self.legendBorders)
            self.legend.SetFillColor(0)
            self.legend.SetFillStyle(0)
            self.legend.SetLineColor(0)
            self.legend.SetLineWidth(1)
            self.legend.SetNColumns(5)  # number of comps / 2 (or 3) + 1
            self.legend.SetEntrySeparation(0.2)
            self.legend.SetColumnSeparation(0.2)
            self.legend.SetBorderSize(0)
            self.legend.SetMargin(0.25)
        else:
            self.legend.Clear()
        hists = self._SortedHistograms(reverse=True)
        if ratio:
            hists = hists[:-1]  # removing the last histo.
        for index, hist in enumerate(hists):
            if print_norm:
                if not hist.legendLine:
                    hist.legendLine = hist.name
                hist.legendLine += ' ({norm:.1f})'.format(norm=hist.Yield())
            hist.AddEntry(self.legend)

    def DrawLegend(self, ratio=False, print_norm=False):
        '''Draw the legend.'''
        if self.legendOn:
            self.CreateLegend(ratio=ratio, print_norm=print_norm)
            self.legend.Draw('same')

    def DrawRatio(self, opt=''):
        '''Draw ratios : h_i / h_0.

        h_0 is the histogram with the smallest layer, and h_i, i>0 are the other histograms.
        if the DataMCPlot object contains N histograms, N-1 ratio plots will be drawn.
        To take another histogram as the denominator, change the layer of this histogram by doing:
        dataMCPlot.Hist("histName").layer = -99 '''
        same = ''
        denom = None
        self.ratios = []
        for hist in self._SortedHistograms():
            if denom == None:
                denom = hist
                continue
            ratio = copy.deepcopy(hist)
            ratio.obj.Divide(denom.obj)
            ratio.obj.Draw(same)
            self.ratios.append(ratio)
            if same == '':
                same = 'same'
        self.DrawLegend(ratio=True)
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawRatio'
        # self.lastDrawArgs = [ opt ]

    def DrawDataOverMCMinus1(self, ymin=-0.5, ymax=0.5):
        stackedHists = []
        dataHist = None
        for hist in self._SortedHistograms():
            if hist.stack is False:
                dataHist = hist
                continue
            stackedHists.append(hist)
        self._BuildStack(stackedHists, ytitle='Data/MC')
        mcHist = self.BGHist()
        if dataHist == None:
            dataHist = mcHist  # this was added to avoid crashes for SR plots (without data)
        self.dataOverMCHist = copy.deepcopy(dataHist)
        # self.dataOverMCHist.Add(mcHist, -1)
        self.dataOverMCHist.Divide(mcHist)
        self.dataOverMCHist.Draw()
        yaxis = self.dataOverMCHist.GetYaxis()
        yaxis.SetRangeUser(ymin + 1., ymax + 1.)
        yaxis.SetTitle('Data/MC')
        yaxis.SetNdivisions(5)
        fraclines = 0.2
        if ymax <= 0.2 or ymin >= -0.2:
            fraclines = 0.1
        self.DrawRatioLines(self.dataOverMCHist, fraclines, 1.)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawRatioStack(self,
                       opt='',
                       xmin=None,
                       xmax=None,
                       ymin=None,
                       ymax=None):
        '''Draw ratios.

        The stack is considered as a single histogram.'''
        denom = None
        # import pdb; pdb.set_trace()
        histForRatios = []
        denom = None
        for hist in self._SortedHistograms():
            if hist.stack is False:
                # if several unstacked histograms, the highest layer is used
                denom = hist
                continue
            histForRatios.append(hist)
        self._BuildStack(histForRatios, ytitle='MC/Data')
        self.stack.Divide(denom.obj)
        if self.blindminx and self.blindmaxx:
            self.stack.Blind(self.blindminx, self.blindmaxx)
        self.stack.Draw(opt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)
        self.ratios = []
        for hist in self.nostack:
            if hist is denom:
                continue
            ratio = copy.deepcopy(hist)
            ratio.obj.Divide(denom.obj)
            ratio.obj.Draw('same')
            self.ratios.append(ratio)
        self.DrawLegend(ratio=True)
        self.DrawRatioLines(denom, 0.2, 1)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawNormalizedRatioStack(self,
                                 opt='',
                                 xmin=None,
                                 xmax=None,
                                 ymin=None,
                                 ymax=None):
        '''Draw ratios.

        The stack is considered as a single histogram.
        All histograms are normalized before computing the ratio'''
        denom = None
        histForRatios = []
        for hist in self._SortedHistograms():
            # taking the first histogram (lowest layer)
            # as the denominator histogram.
            if denom == None:
                denom = copy.deepcopy(hist)
                continue
            # other histograms will be divided by the denominator
            histForRatios.append(hist)
        self._BuildStack(histForRatios, ytitle='MC p.d.f. / Data p.d.f.')
        self.stack.Normalize()
        denom.Normalize()
        self.stack.Divide(denom.weighted)
        self.stack.Draw(opt, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)
        self.ratios = []
        for hist in self.nostack:
            # print 'nostack ', hist
            ratio = copy.deepcopy(hist)
            ratio.Normalize()
            ratio.obj.Divide(denom.weighted)
            ratio.obj.Draw('same')
            self.ratios.append(ratio)
        self.DrawLegend(ratio=True)
        self.DrawRatioLines(denom, 0.2, 1)
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalizedRatioStack'
        # self.lastDrawArgs = [ opt ]

    def DrawRatioLines(self, hist, frac=0.2, y0=1.):
        '''Draw a line at y = 1, at 1+frac, and at 1-frac.

        hist is used to get the x axis range.'''
        xmin = hist.obj.GetXaxis().GetXmin()
        xmax = hist.obj.GetXaxis().GetXmax()
        line = TLine()
        line.DrawLine(xmin, y0, xmax, y0)
        line.SetLineStyle(2)
        line.DrawLine(xmin, y0 + frac, xmax, y0 + frac)
        line.DrawLine(xmin, y0 - frac, xmax, y0 - frac)

    def GetStack(self):
        '''Returns stack; builds stack if not there yet'''
        if not self.stack:
            self._BuildStack(self._SortedHistograms(), ytitle='Events')
        return self.stack

    def BGHist(self):
        return self.GetStack().totalHist

    def SignalHists(self):
        return [h for h in self.nostack if not h.style.drawAsData]

    def DrawStack(self,
                  opt='',
                  xmin=None,
                  xmax=None,
                  ymin=None,
                  ymax=None,
                  print_norm=False,
                  scale_signal=''):
        '''Draw all histograms, some of them in a stack.

        if Histogram.stack is True, the histogram is put in the stack.
        scale_signal: mc_int -> scale to stack integral'''
        self._BuildStack(self._SortedHistograms(), ytitle='Events')
        same = 'same'
        if len(self.nostack) == 0:
            same = ''
        self.supportHist = None
        for hist in self.nostack:
            if hist.style.drawAsData:
                hist.Draw('SAME' if self.supportHist else '')
            else:
                if scale_signal == 'mc_int':
                    hist.Scale(hist.Yield(weighted=True) / self.stack.integral)
                hist.Draw('SAME HIST' if self.supportHist else 'HIST')
            if not self.supportHist:
                self.supportHist = hist
        self.stack.Draw(opt + same, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)
        if self.supportHist is None:
            self.supportHist = self.BGHist()
        if not self.axisWasSet:
            mxsup = self.supportHist.weighted.GetBinContent(
                self.supportHist.weighted.GetMaximumBin())
            mxstack = self.BGHist().weighted.GetBinContent(
                self.BGHist().weighted.GetMaximumBin())
            mx = max(mxsup, mxstack)
            if ymin is None:
                ymin = 0.01
            if ymax is None:
                ymax = mx * 2
                centrality = self.supportHist.weighted.GetRMS() / (
                    self.supportHist.weighted.GetXaxis().GetXmax() -
                    self.supportHist.weighted.GetXaxis().GetXmin())
                if centrality > 0.15:
                    ymax = mx * 2.2

            self.supportHist.GetYaxis().SetRangeUser(ymin, ymax)
            self.axisWasSet = True
        for hist in self.nostack:
            if self.blindminx and hist.style.drawAsData:
                hist.Blind(self.blindminx, self.blindmaxx)
            if hist.style.drawAsData:
                hist.Draw('SAME')
            else:
                hist.Draw('SAME HIST')

        if self.supportHist.weighted.GetMaximumBin(
        ) < self.supportHist.weighted.GetNbinsX() / 2:
            #            self.legendBorders = 0.62, 0.46, 0.88, 0.89
            self.legendBorders = 0.20, 0.78, 0.80, 0.88
            #            self.legendPos = 'right'
            self.legendPos = 'top'

        self.DrawLegend(print_norm=print_norm)
        if TPad.Pad():
            TPad.Pad().Update()


#        set_trace()

    def DrawNormalizedStack(self,
                            opt='',
                            xmin=None,
                            xmax=None,
                            ymin=0.001,
                            ymax=None):
        '''Draw all histograms, some of them in a stack.

        if Histogram.stack is True, the histogram is put in the stack.
        all histograms out of the stack, and the stack itself, are shown as PDFs.'''
        self._BuildStack(self._SortedHistograms(), ytitle='p.d.f.')
        self.stack.DrawNormalized(opt,
                                  xmin=xmin,
                                  xmax=xmax,
                                  ymin=ymin,
                                  ymax=ymax)
        for hist in self.nostack:
            hist.obj.DrawNormalized('same')
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalizedStack'
        # self.lastDrawArgs = [ opt ]

    def Rebin(self, factor):
        '''Rebin, and redraw.'''
        # the dispatching technique is not too pretty,
        # but keeping a self.lastDraw function initialized to one of the Draw functions
        # when calling it creates a problem in deepcopy.
        for hist in self.histos:
            hist.Rebin(factor)
        self.axisWasSet = False

    def NormalizeToBinWidth(self):
        '''Normalize each Histograms bin to the bin width.'''
        for hist in self.histos:
            hist.NormalizeToBinWidth()

    def WriteDataCard(self,
                      filename=None,
                      verbose=True,
                      mode='RECREATE',
                      dir=None,
                      postfix=''):
        '''Export current plot to datacard'''
        if not filename:
            filename = self.name + '.root'

        outf = TFile(filename, mode)
        if dir and outf.Get(dir):
            print 'Directory', dir, 'already present in output file'
            if any(
                    outf.Get(dir + '/' + hist.name + postfix)
                    for hist in self._SortedHistograms()):
                print 'Recreating file because histograms already present'
                outf = TFile(filename, 'RECREATE')
        if dir:
            outf_dir = outf.Get(dir)
            if not outf_dir:
                outf_dir = outf.mkdir(dir)
            outf_dir.cd()

        for hist in self._SortedHistograms():
            'Writing', hist, 'as', hist.name
            hist.weighted.Write(hist.name + postfix)
        outf.Write()

    def _BuildStack(self, hists, ytitle=None):
        '''build a stack from a list of Histograms.

        The histograms for which Histogram.stack is False are put in self.nostack'''
        self.stack = None
        self.stack = Stack(self.name + '_stack', ytitle=ytitle)
        self.nostack = []
        for hist in hists:
            if hist.stack:
                self.stack.Add(hist)
            else:
                self.nostack.append(hist)

    def _GetHistPref(self, name):
        '''Return the preference dictionary for a given component'''
        thePref = None
        for prefpat, pref in self.histPref.iteritems():
            if fnmatch.fnmatch(name, prefpat):
                if thePref is not None:
                    print 'several matching preferences for', name
                thePref = pref
        if thePref is None:
            print 'cannot find preference for hist', name
            thePref = {'style': Style(), 'layer': 999, 'legend': name}
        return thePref

    def _ApplyPrefs(self):
        for hist in self.histos:
            pref = self._GetHistPref(hist.name)
            hist.layer = pref['layer']
            hist.SetStyle(pref['style'])
            hist.legendLine = pref['legend']

    def __str__(self):
        if self.stack is None:
            self._BuildStack(self._SortedHistograms(), ytitle='Events')
        tmp = [' '.join(['DataMCPlot: ', self.name])]
        tmp.append('Histograms:')
        for hist in self._SortedHistograms(reverse=True):
            tmp.append(' '.join(['\t', str(hist)]))
        tmp.append(
            'Stack yield = {integ:7.1f}'.format(integ=self.stack.integral))
        return '\n'.join(tmp)
Example #14
0
def make_time_rod_evo(error_dict, rod_dict, results, doLock):
 
    c2 = TCanvas( 'c2', 'c2', 1000, 600)
    leg = TLegend(0.18,0.85,0.45,0.55)
    leg.SetLineColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
     
    R15 = TLine(431,0,431,60)
    R15.SetLineColorAlpha(kPink+10,0.4)
    R15.SetLineWidth(4)

    R16 = TLine(1820,0,1820,60)
    R16.SetLineColorAlpha(kMagenta+10,0.4)
    R16.SetLineWidth(4)

    R17 = TLine(3376,0,3376,60)
    R17.SetLineColorAlpha(kGreen-3,0.4)
    R17.SetLineWidth(4)


    TS1 = TLine(431,0,432,60)
    TS1.SetLineColorAlpha(kPink+10,0.5)
    TS1.SetLineWidth(5)

    TS2 = TLine(1415,0,1415,60)
    TS2.SetLineColorAlpha(kMagenta+3,0.5)
    TS2.SetLineWidth(5)

    leg2 = TLegend(0.18,0.45,0.35,0.55)
    leg2.SetLineColor(0)
    leg2.SetFillStyle(0)
    leg2.SetShadowColor(0)
    leg2.SetBorderSize(0)
    gStyle.SetLegendTextSize(0.030)

    leg2.AddEntry(R15, "End of 2015", 'lf')
    leg2.AddEntry(R16, "End of 2016", 'lf')
    leg2.AddEntry(R17, "End of 2017", 'lf')
    #leg2.AddEntry(TS2, "TS2", 'lf')


    for key,val in rod_dict.items(): 
        TS1.SetY2(val*0.5)
        TS2.SetY2(val+1)

        R15.SetY2(val*0.3)
        R16.SetY2(val*0.5)
        R17.SetY2(val*0.8)

        times = {}
        times.clear()
        for e in error_bits:
            times['0x'+e] = [0] 
        for error in results:
            pos_rod  = error.text.find("ROD") + 4
            pos_lock = error.text.find("Lock") + 15
            pos_buff = error.text.find("buffer") + 17

            if error.msgID == 'TRT::ROD05Module':
                rod  = '0x'+str(error.text[pos_rod:pos_rod+6])
            else:
                rod  = str(error.text[pos_rod:pos_rod+8])

            lock = str(error.text[pos_lock:pos_lock+3])
            buff = str(error.text[pos_buff:pos_buff+3])

            if key == rod and doLock and lock != '0xf':
                times[lock].append(error.sb_total_time)


        leg.Clear()
        mg = TMultiGraph()

        for e in error_bits:
            errs = []
            for i,x in enumerate(times['0x'+e]):
                errs.append(i+0.0)
            errs.append(errs[-1])
            #times['0x'+e].append(1800.0)
            times['0x'+e].append(results[-1].sb_total_time)
            gr = TGraph(len(times['0x'+e]), array(times['0x'+e]), array(errs))
            gr.SetMarkerSize(0.7)
            if bin(int('0x'+e, 16))[2:].zfill(4) == '0111':
                leg.AddEntry(gr,'GOL 3',"lp");
            elif bin(int('0x'+e, 16))[2:].zfill(4) == '1011':
                leg.AddEntry(gr,'GOL 2',"lp");
            elif bin(int('0x'+e, 16))[2:].zfill(4) == '1101':
                leg.AddEntry(gr,'GOL 1',"lp");
            elif bin(int('0x'+e, 16))[2:].zfill(4) == '1110':
                leg.AddEntry(gr,'GOL 0',"lp");
            else:
                leg.AddEntry(gr,bin(int('0x'+e, 16))[2:].zfill(4),"lp");
            mg.Add(gr,"pl");

        mg.SetTitle("; Hours of stable beams; # of rocketio io lock errors");
        mg.Draw("PMC PLC a");
        R15.Draw()
        R16.Draw()
        R17.Draw()
        #TS1.Draw()
        #TS2.Draw()
        
        AtlasStyle.ATLAS_LABEL(0.19,.88, 1, "Internal")
        leg.Draw()
        leg2.Draw()
        AtlasStyle.myText(0.4, 0.88, kBlack, "ROD: " + key)
        
        
        leg.SetMargin(0.5)
        gPad.Modified()
        mg.GetXaxis().SetLimits(0,results[-1].sb_total_time)
        mg.SetMinimum(0.)
        mg.SetMaximum(val+1)
        c2.Update()
        c2.Print("plots/time_"+key+".pdf")
        c2.Clear()
Example #15
0
label = ROOT.TLatex()
label.SetNDC()
label.SetTextSize(0.04)
label.SetTextFont(42)
#label.DrawLatex(0.575, 0.645, "#sqrt{s} = 13 TeV, 70fb^{-1}")
label.DrawLatex(text_x, 0.785, "#sqrt{s} = 13 TeV, %sfb^{-1}" % str(fb))

label = ROOT.TLatex()
label.SetNDC()
label.SetTextSize(0.04)
label.SetTextFont(42)
#label.DrawLatex(0.575, 0.645, "#sqrt{s} = 13 TeV, 70fb^{-1}")
label.DrawLatex(text_x, 0.73, "|y*| < %s" % str(rapidity))

legend = TLegend(0.125, 0.125, 0.6, 0.3)
legend.SetMargin(0.15)
legend.SetBorderSize(0)
legend.SetFillStyle(0)
legend.AddEntry(theory_line, particle_symbol, "l")
legend.AddEntry(data_line, "Observed 95% CL upper limit", "lp")
legend.AddEntry(brazil_line, "Expected 95% CL upper limit", "l")
legend.AddEntry(brazil_yellow, "Expected #pm1#sigma and #pm2#sigma")
legend.Draw()

canvas.SaveAs(op.join(args.output_dir, "brazil-{0}.png".format(job_id)))
canvas.SaveAs(op.join(args.output_dir, "brazil-{0}.pdf".format(job_id)))

with open(op.join(args.output_dir, "limits.txt"), "w") as limit_file:
    limit_file.write("Observed mass limit: {0} GeV\n".format(x_intersect))
    limit_file.write(
        "Observed cross section limit: {0} pb\n".format(y_intersect))
Example #16
0
        projectBin = -1 #all
        if thesuper[ikey].projection == "x": projectAxis = "x"
        if thesuper[ikey].projection == "y": projectAxis = "y"
        if thesuper[ikey].bin != None: projectBin = thesuper[ikey].bin
        profileAxis = "no"
        if thesuper[ikey].profile == "x": profileAxis = "x"
        if thesuper[ikey].profile == "y": profileAxis = "y"
        doFill = False
        if thesuper[ikey].Fill == "true": doFill = True
        if verbose : print("fill option:"+ doFill)
        #create canvas
        cv[thesuper[ikey].name] = TCanvas(thesuper[ikey].name,thesuper[ikey].title,700,700)
        #legend
        aleg = TLegend(0.6,0.4,0.8,0.6)
        SetOwnership( aleg, 0 ) 
        aleg.SetMargin(0.12)
        aleg.SetTextSize(0.035)
        aleg.SetFillColor(10)
        aleg.SetBorderSize(0)

        isFirst = 1
        ii = 0

        stacklist[thesuper[ikey].name] = THStack("astack"+thesuper[ikey].name,thesuper[ikey].title)
        astack = stacklist[thesuper[ikey].name]
        for ihname in listname:

            for jkey in thedata:
                tmpkeys = thedata[jkey].histos.keys()

                for tmpname in tmpkeys:
Example #17
0
def MakeLegend(can,
               x1=.8,
               y1=.8,
               x2=.9,
               y2=.9,
               textsize=18,
               ncolumns=1,
               totalentries=0,
               option='f',
               skip=[]):
    from ROOT import TLegend, TH1, gStyle, TGraph
    if can.GetPrimitive('pad_top'):
        MakeLegend(can.GetPrimitive('pad_top'),
                   x1,
                   y1,
                   x2,
                   y2,
                   textsize,
                   ncolumns,
                   totalentries,
                   skip=skip)
        return
    if CanvasEmpty(can):
        print 'Error: trying to make legend from canvas with 0 plots. Will do nothing.'
        return
    #
    # if a previous version exists from this function, delete it
    #
    if can.GetPrimitive('legend'):
        can.GetPrimitive('legend').Delete()
    leg = TLegend(x1, y1, x2, y2)
    leg.SetName('legend')
    tobject_collector.append(leg)
    leg.SetTextFont(43)
    leg.SetTextSize(textsize)
    leg.SetTextFont(43)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetNColumns(ncolumns)
    #
    # Add by TH1 GetTitle()
    #
    the_primitives = can.GetListOfPrimitives()
    if can.GetPrimitive('pad_top'):
        the_primitives = can.GetPrimitive('pad_top').GetListOfPrimitives()
    if can.GetPrimitive('stack'):
        the_stack = list(reversed(list(can.GetPrimitive('stack').GetHists())))
        the_primitives = the_stack + list(the_primitives)

    if type(option) == type(''):
        option = [option] * 100

    total = 0
    for i in the_primitives:
        if i.GetName() == 'stack': continue
        drawopt = i.GetDrawOption()
        if issubclass(type(i), TH1) or issubclass(type(i), TGraph):
            if i.GetTitle() in skip:
                continue
            leg.AddEntry(i, i.GetTitle(), option[total])  # plef
            total += 1

    #
    # Add empty entries to ensure a standard layout
    #
    for i in range(100):
        if totalentries == 0: break
        if total >= totalentries: break
        leg.AddEntry(None, '', '')
        total += 1

    # recipe for making roughly square boxes
    h = leg.GetY2() - leg.GetY1()
    w = leg.GetX2() - leg.GetX1()
    leg.SetMargin(leg.GetNColumns() * h / float(leg.GetNRows() * w))
    can.cd()
    if can.GetPrimitive('pad_top'):
        can.GetPrimitive('pad_top').cd()
    leg.Draw()
    can.Modified()
    can.Update()
    return
Example #18
0
def binFile(rerror, filename, xtitle, backgrounds):
    warnings.simplefilter("ignore")
    file = TFile(filename)
    keys = file.GetListOfKeys()

    print 'input file:', filename
    print 'background:', backgrounds
    h_bkg = {}
    h_data = {}

    resultfile = filename.split('.')[0] + '_rebinned.root'

    # load all the background and data histograms
    for key in keys:
        key = key.GetName()
        info = hinfo(key)
        if not info.systematic:
            if info.process in backgrounds:
                if info.channel in h_bkg:
                    print 'merging', info.channel
                    h_bkg[info.channel] = merge(h_bkg[info.channel],
                                                file.Get(key).Clone())
                else:
                    print 'adding', info.channel
                    h_bkg[info.channel] = file.Get(key).Clone()
            elif info.process == 'data' or info.process == 'DATA':
                if info.channel in h_data:
                    h_data[info.channel] = merge(h_data[info.channel],
                                                 file.Get(key).Clone())
                else:
                    h_data[info.channel] = file.Get(key).Clone()

    canvas = TCanvas()
    canvas.SetLogy()

    #keys = file.GetListOfKeys()
    output = TFile(resultfile, 'RECREATE')
    #print h_bkg[1]
    # print all the histograms for all the channels
    for key in h_bkg:
        binning = array.array('d', computeBinning(h_bkg[key], rerror))
        #print binning
        h_bkg[key] = h_bkg[key].Rebin(
            len(binning) - 1, h_bkg[key].GetName(), binning)

        h_bkg[key].SetLineColor(ROOT.kGray + 1)
        h_bkg[key].SetFillColor(ROOT.kGray + 1)

        maxs = h_bkg[key].GetMaximum()

        if len(h_data) > 0:
            h_data[key] = h_data[key].Rebin(
                len(binning) - 1, h_data[key].GetName(), binning)
            h_data[key].SetLineColor(ROOT.kBlack)
            h_data[key].SetMarkerStyle(20)
            maxs = [h_data[key].GetMaximum(), h_bkg[key].GetMaximum()]

        pad = canvas.cd(1)
        pad.SetLeftMargin(0.15)
        pad.SetBottomMargin(0.15)

        min = h_bkg[key].GetBinContent(h_bkg[key].GetMinimumBin())

        if len(h_data) > 0:
            h_data[key].GetYaxis().SetRangeUser(0.5 * min, max(maxs) * 1.8)

            h_data[key].GetYaxis().SetLabelSize(0.05)
            h_data[key].GetYaxis().SetTitleSize(0.05)
            h_data[key].GetYaxis().SetTitle('event yield')
            h_data[key].GetXaxis().SetLabelSize(0.05)
            h_data[key].GetXaxis().SetTitleSize(0.05)
            h_data[key].GetXaxis().SetTitle(xtitle)

            h_data[key].Draw('e')

        h_bkg[key].Draw('samehist')

        if len(h_data) > 0:
            h_data[key].Draw('samee')

        legend = TLegend(.67, .78, .89, .88)
        legend.SetMargin(0.12)
        legend.SetTextSize(0.03)
        legend.SetFillColor(10)
        legend.SetBorderSize(0)
        legend.AddEntry(h_bkg[key], "Background", "f")
        if len(h_data) > 0: legend.AddEntry(h_data[key], "CMS Data 2016", "lp")
        legend.Draw()

        labelcms = TLegend(.15, .91, 1, .96)
        labelcms.SetTextSize(0.04)
        labelcms.SetMargin(0.12)
        labelcms.SetFillColor(10)
        labelcms.SetBorderSize(0)
        labelcms.SetHeader('CMS Preliminary #sqrt{s} = 13 TeV')
        labelcms.Draw()

        labellumi = TLegend(.73, .91, 1, .96)
        labellumi.SetTextSize(0.04)
        labellumi.SetMargin(0.12)
        labellumi.SetFillColor(10)
        labellumi.SetBorderSize(0)
        labellumi.SetHeader('L = 35.8 fb^{-1}')
        labellumi.Draw()

        labellumi2 = TLegend(.67, .70, .89, .75)
        labellumi2.SetTextSize(0.03)
        labellumi2.SetMargin(0.12)
        labellumi2.SetFillColor(10)
        labellumi2.SetBorderSize(0)
        labellumi2.SetHeader(key)
        labellumi2.Draw()

        canvas.SaveAs('h_' + filename.split('.')[0] + '_' + key + '.pdf')

        for hkey in keys:
            hkey = hkey.GetName()
            info = hinfo(hkey)

            if info.channel == key:
                #print hkey
                #print info.channel,key
                #print hkey
                histogram = file.Get(hkey).Clone()

                # Hack to fix the data lowercase names
                #if info.systematic == 'pdf':
                #    continue

                #if (info.systematic == 'scale' or info.systematic == 'matching') and 'light' in info.process and '1btag' in info.channel:
                #    print "Excluding : ", info.systematic, info.process, info.channel
                #    continue
                if 'data' in info.process:
                    histogram.SetName(histogram.GetName().replace(
                        'data', 'DATA'))

                if info.systematic:
                    if ('ttjets' in info.process.lower()
                            or 'ttbar' in info.process.lower()
                        ) and 'scale' in info.systematic:
                        orig = histogram.GetName()
                        histogram.SetName(histogram.GetName().replace(
                            'scaleWeight', 'scale_ttbar'))
                        if debug:
                            print "Renaming: %s to %s" % (orig,
                                                          histogram.GetName())
                    elif ('wjets' in info.process.lower()
                          or 'zjets' in info.process.lower()
                          ) and 'scale' in info.systematic:
                        orig = histogram.GetName()
                        histogram.SetName(histogram.GetName().replace(
                            'scaleWeight', 'scale_vjets'))
                        if debug:
                            print "Renaming: %s to %s" % (orig,
                                                          histogram.GetName())
                    elif 'singlet' in info.process.lower(
                    ) and 'scale' in info.systematic:
                        orig = histogram.GetName()
                        histogram.SetName(histogram.GetName().replace(
                            'scaleWeight', 'scale_singletop'))
                        if debug:
                            print "Renaming: %s to %s" % (orig,
                                                          histogram.GetName())
                    elif ('bpb' in info.process.lower()
                          or 'bpt' in info.process.lower()
                          ) and 'scale' in info.systematic:
                        orig = histogram.GetName()
                        histogram.SetName(histogram.GetName().replace(
                            'scaleWeight', 'scale_bp'))
                        if debug:
                            print "Renaming: %s to %s" % (orig,
                                                          histogram.GetName())
                    elif 'qcd' in info.process.lower(
                    ) and 'scale' in info.systematic:
                        if debug: print "ignoring QCD scale uncertainties"
                        continue

                #following not used at the moment!
                if ('wlight' in info.process or 'zlight'
                        in info.process) and info.systematic == 'matching':
                    orig = histogram.GetName()
                    histogram.SetName(histogram.GetName().replace(
                        'matching', 'matching_vjets'))
                    print "Renaming: %s to %s" % (orig, histogram.GetName())

                if 'mcregion' in hkey:
                    print key
                    channel = info.channel.replace('Mu', '')
                    channel = channel.replace('Ele', '')
                    histogram.SetName(histogram.GetName().replace(
                        'mcregion', 'mcregion_' + channel))

#Rename the hists to make it easier for theta to find the mass
                if 'X53' in info.process:
                    histogram.SetName(histogram.GetName().replace('X53', 'X'))

                #norm signal, just pure shape
                if ('Bprime' in info.process
                        or 'X53' in info.process) and info.systematic:
                    for h_hkey in keys:
                        h_hkey = h_hkey.GetName()
                        h_info = hinfo(h_hkey)
                        if not h_info.systematic and info.process == h_info.process and h_info.channel == info.channel:
                            h_norm = file.Get(hkey).Clone()
                            events_unc = 0
                            events_nom = 0
                            for i in xrange(1, histogram.GetNbinsX() + 1):
                                events_nom += h_norm.GetBinContent(i)
                                events_unc += histogram.GetBinContent(i)
                            #print 'Going to normalize to the same value', h_info.process,h_info.channel,info.systematic,'factor',events_nom/events_unc
                            #histogram.Scale(events_nom/events_unc)

                #print 'rebinning',hkey
                histogram = histogram.Rebin(
                    len(binning) - 1, histogram.GetName(), binning)
                for i in xrange(1, histogram.GetNbinsX() + 1):
                    if histogram.GetBinContent(i) <= 0.:
                        histogram.SetBinContent(i, 0.0001)

                output.cd()
                histogram.Sumw2()
                histogram.Write()
    return resultfile
Example #19
0
 def plotMatches(tree, basebranch, trigger, WPs, plotname, header, ctexts):
     gStyle.SetOptTitle(True)
     hists = []
     for i, wp in enumerate(WPs, 1):
         ###canvas    = TCanvas('canvas','canvas',100,100,800,600)
         branch = basebranch + ("" if 'all' in wp else '_' + wp)
         histname = "%s_%s" % (trigger, branch)
         histtitle = "all (slimmed)" if wp == 'all' else wp  #"%s, %s"%(trigger,wp)
         hist = TH1F(histname, histtitle, 8, -2, 6)
         hist.GetXaxis().SetTitle(branch)
         hist.GetYaxis().SetTitle("Fraction")
         for ibin in xrange(1, hist.GetXaxis().GetNbins() + 1):
             xbin = hist.GetBinLowEdge(ibin)
             if xbin == -2:
                 hist.GetXaxis().SetBinLabel(ibin, "HLT not fired")
             elif xbin == -1:
                 hist.GetXaxis().SetBinLabel(ibin, "No trig. obj.")
             elif xbin == 0:
                 hist.GetXaxis().SetBinLabel(ibin, "No match")
             elif xbin == 1:
                 hist.GetXaxis().SetBinLabel(ibin, "1 match")
             else:
                 hist.GetXaxis().SetBinLabel(ibin, "%d matches" % xbin)
         hist.GetXaxis().SetLabelSize(0.074)
         hist.GetYaxis().SetLabelSize(0.046)
         hist.GetXaxis().SetTitleSize(0.046)
         hist.GetYaxis().SetTitleSize(0.052)
         hist.GetXaxis().SetTitleOffset(2.14)
         hist.GetYaxis().SetTitleOffset(0.98)
         hist.GetXaxis().SetLabelOffset(0.009)
         if len(branch) > 60:
             hist.GetXaxis().CenterTitle(True)
             hist.GetXaxis().SetTitleOffset(2.65)
             hist.GetXaxis().SetTitleSize(0.038)
         elif len(branch) > 40:
             hist.GetXaxis().CenterTitle(True)
             hist.GetXaxis().SetTitleOffset(2.16)
             hist.GetXaxis().SetTitleSize(0.044)
         hist.SetLineWidth(2)
         hist.SetLineColor(i)
         out = tree.Draw("%s >> %s" % (branch, histname),
                         "trigger_%s" % trigger, 'gOff')
         if hist.Integral() > 0:
             hist.Scale(1. / hist.Integral())
         else:
             print "Warning! Histogram '%s' is empty!" % hist.GetName()
         ###hist.Draw('HISTE')
         ###canvas.SaveAs(histname+".png")
         ###canvas.SaveAs(histname+".pdf")
         ###canvas.Close()
         hists.append(hist)
     gStyle.SetOptTitle(False)
     canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 600)
     canvas.SetMargin(0.10, 0.09, 0.18, 0.03)
     textsize = 0.040
     height = 1.28 * (len(hists) + 1) * textsize
     legend = TLegend(0.63, 0.70, 0.88, 0.70 - height)
     legend.SetTextSize(textsize)
     legend.SetBorderSize(0)
     legend.SetFillStyle(0)
     legend.SetFillColor(0)
     legend.SetTextFont(62)
     legend.SetHeader(header)
     legend.SetTextFont(42)
     legend.SetMargin(0.2)
     latex = TLatex()
     latex.SetTextAlign(13)
     latex.SetTextFont(42)
     latex.SetNDC(True)
     hists[0].SetMaximum(1.25 * max(h.GetMaximum() for h in hists))
     for hist in hists:
         hist.Draw('HISTSAME')
         legend.AddEntry(hist, hist.GetTitle().capitalize(), 'l')
     legend.Draw()
     for i, text in enumerate(ctexts):
         textsize = 0.031 if i > 0 else 0.044
         latex.SetTextSize(textsize)
         latex.DrawLatex(0.14, 0.95 - 1.7 * i * textsize, text)
     canvas.SaveAs(plotname + ".png")
     canvas.SaveAs(plotname + ".pdf")
     canvas.Close()
     for hist in hists:
         gDirectory.Delete(hist.GetName())
Example #20
0
    graph_exclusion_exp_.Draw("AL")
    graph_exclusion_exp_pm1sig_.Draw("Fsame")
    graph_exclusion_exp_p1sig_.Draw("Lsame")
    graph_exclusion_exp_m1sig_.Draw("Lsame")
    if drawObs:
        graph_exclusion_obs_.Draw("Lsames")

    graph_exclusion_atlas_8TeV_2g.Draw("Lsames")
    graph_exclusion_cms_7TeV_1g.Draw("Lsames")
    #graph_exclusion_cms_8TeV_1g.Draw("Fsames")
    #graph_exclusion_cms_8TeV_2g.Draw("Fsames")

    ####legend
    leg_2d_exclusion_ = TLegend(0.21, 0.70, 0.6, 0.92)
    leg_2d_exclusion_.SetMargin(0.5)
    leg_2d_exclusion_.SetBorderSize(0)
    leg_2d_exclusion_.SetTextSize(0.03)
    leg_2d_exclusion_.SetTextFont(42)
    #leg_2d_exclusion_.SetLineColor(1)
    #leg_2d_exclusion_.SetLineStyle(1)
    #leg_2d_exclusion_.SetLineWidth(1)
    leg_2d_exclusion_.SetFillColor(0)
    leg_2d_exclusion_.SetFillStyle(1001)

    leg_2d_exclusion_.SetHeader(" GMSB SPS8")
    leg_2d_exclusion_.AddEntry(
        graph_exclusion_exp_,
        "CMS expected (#pm 1 #sigma) " + label_this_withoutY, "LF")
    if drawObs:
        leg_2d_exclusion_.AddEntry(graph_exclusion_obs_,
Example #21
0
def make_plot_all_rods(error_dict, rod_dict, name):
    

    leg = TLegend(0,0,0,0)
    if 'lock' in name:
        leg = TLegend(0.18,0.85,0.50,0.55)
    else:
        leg = TLegend(0.18,0.85,0.40,0.55)
    leg.SetLineColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(3)
    gStyle.SetLegendTextSize(0.045)

   
    v_hists = []
    #for e,c in zip(error_bits, error_colors):
    for e in error_bits:
        h = TH1F('h'+e,'h'+e, len(rod_dict), 0, len(rod_dict))
        h.SetFillStyle(1001)
        h.SetLineWidth(0)
        v_hists.append(h)
        v_hists[-1].SetDirectory(0)
        if bin(int('0x'+e, 16))[2:].zfill(4) == '0111':
            leg.AddEntry(v_hists[-1],'GOL 3',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1011':
            leg.AddEntry(v_hists[-1],'GOL 2',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1101':
            leg.AddEntry(v_hists[-1],'GOL 1',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1110':
            leg.AddEntry(v_hists[-1],'GOL 0',"f");
        else:
            leg.AddEntry(v_hists[-1],bin(int('0x'+e, 16))[2:].zfill(4),"f");
    h = leg.GetY2()-leg.GetY1();
    w = leg.GetX2()-leg.GetX1()*.6;
    leg.SetMargin(leg.GetNColumns()*h/(leg.GetNRows()*w))
    

    for key,val in error_dict.items():
        idx_rod = 0
        for i, key2 in enumerate(rod_dict):
            if key2 == key[:8]:
                idx_rod = i
        v_hists[int(key[11:12], 16)].Fill(idx_rod, val)
  
    stack  = THStack("stack","stack")
    for hist in v_hists:
        stack.Add(hist)

    if 'buff' in name:
        c1 = TCanvas( 'c1', 'c1', 2000, 500)
    else:
        c1 = TCanvas( 'c1', 'c1', 1000, 500)


    h1 = TH1F('h_1','h_1', len(rod_dict), 0, len(rod_dict))
    for i, key in enumerate(rod_dict):
        h1.GetXaxis().SetBinLabel(i+1,key)
        h1.SetBinContent(i+1,rod_dict[key])

 
    h1.GetXaxis().LabelsOption("v")
    h1.GetXaxis().SetTitle("ROD")
    h1.GetXaxis().SetTitleOffset(2.2)
    h1.GetYaxis().SetTitle("# of rocketio errors")
    h1.SetLineColor(kRed)
    h1.SetLineWidth(1)

    leg.AddEntry(h1,'total',"l");
    
    c1.SetBottomMargin(0.23)  
    h1.GetXaxis().SetTitle("ROD")
    h1.Draw("HIST")
    stack.Draw("PFC PLC SAME HIST")
    h1.Draw("SAMEHIST")
    AtlasStyle.ATLAS_LABEL(0.19,.88, 1, "Internal")
    leg.Draw()
    c1.Update()
    c1.Print("plots/"+name +".pdf")
    c1.Clear()
Example #22
0
def main():
  ratesA_ = load_json("ratesAt1p5after.json")
  ratesB_ = load_json("ratesAt1p5before.json")

  wp2 = phicomparison(ratesB_,ratesA_,"W+2","RB4","compWP2RB4","W+2/RB4")
  wp1 = phicomparison(ratesB_,ratesA_,"W+1","RB4","compWP1RB4","W+1/RB4")
  wp0 = phicomparison(ratesB_,ratesA_,"W+0","RB4","compWP0RB4","W+0/RB4")
  wm1 = phicomparison(ratesB_,ratesA_,"W-1","RB4","compWM1RB4","W-1/RB4")
  wm2 = phicomparison(ratesB_,ratesA_,"W-2","RB4","compWM2RB4","W-2/RB4")
  
  rem4 = diskphicomparison(ratesB_,ratesA_,"RE-4","R3","compREM4R3","RE-4/R3")
  rem3 = diskphicomparison(ratesB_,ratesA_,"RE-3","R3","compREM3R3","RE-3/R3")
  rem2 = diskphicomparison(ratesB_,ratesA_,"RE-2","R3","compREM2R3","RE-2/R3")
  rem1 = diskphicomparison(ratesB_,ratesA_,"RE-1","R3","compREM1R3","RE-1/R3")
  rep1 = diskphicomparison(ratesB_,ratesA_,"RE+1","R3","compREP1R3","RE+1/R3")
  rep2 = diskphicomparison(ratesB_,ratesA_,"RE+2","R3","compREP2R3","RE+2/R3")
  rep3 = diskphicomparison(ratesB_,ratesA_,"RE+3","R3","compREP3R3","RE+3/R3")
  rep4 = diskphicomparison(ratesB_,ratesA_,"RE+4","R3","compREP4R3","RE+4/R3")

  wp2["before"].SetLineColor(kRed+2);  wp2["after"].SetLineColor(kRed+2)
  wp1["before"].SetLineColor(kBlue+2); wp1["after"].SetLineColor(kBlue+2)
  wp0["before"].SetLineColor(kBlack);  wp0["after"].SetLineColor(kBlack)
  wm1["before"].SetLineColor(kGreen+2); wm1["after"].SetLineColor(kGreen+2)
  wm1["before"].SetLineStyle(9);       wm1["after"].SetLineStyle(9)
  wm2["before"].SetLineColor(kMagenta+2);  wm2["after"].SetLineColor(kMagenta+2)
  wm2["before"].SetLineStyle(9);       wm2["after"].SetLineStyle(9)
  
  acan = TCanvas("can","",1200,700)
  acan.Divide(2,1)
  #wp2["after"].Divide(wp2["before"])
  #wp1["after"].Divide(wp1["before"])
  #wp0["after"].Divide(wp0["before"])
  #wm1["after"].Divide(wm1["before"])
  #wm2["after"].Divide(wm2["before"])
  #wp2["after"].SetMaximum(2.5)
  #wp1["after"].SetMaximum(2.5)
  #wp0["after"].SetMaximum(2.5)
  #wm1["after"].SetMaximum(2.5)
  #wm2["after"].SetMaximum(2.5)

  #wp2["after"].SetBarWidth(0.18); wp2["after"].SetBarOffset(0.0); wp2["after"].SetFillColor(kRed+2);
  #h1 = wp2["after"].DrawCopy("bar2");
  #wp1["after"].SetBarWidth(0.18); wp1["after"].SetBarOffset(0.20); wp1["after"].SetFillColor(kBlue+2);
  #h2 = wp1["after"].DrawCopy("bar2 same");
  #wp0["after"].SetBarWidth(0.18); wp0["after"].SetBarOffset(0.40); wp0["after"].SetFillColor(kBlack);
  #h3 = wp0["after"].DrawCopy("bar2 same");
  #wm1["after"].SetBarWidth(0.18); wm1["after"].SetBarOffset(0.60); wm1["after"].SetFillColor(kGreen+2);
  #h4 = wm1["after"].DrawCopy("bar2 same");
  #wp2["after"].SetBarWidth(0.18); wp2["after"].SetBarOffset(0.80); wp2["after"].SetFillColor(kMagenta+2);
  #h5 = wp2["after"].DrawCopy("bar2 same");
  
  acan.cd(1)
  wp2["after"].SetTitle("RB4")
  wp2["after"].Draw("same hist")
  wp1["after"].Draw("same hist")
  wp0["after"].Draw("same hist")
  wm1["after"].Draw("same hist")
  wm2["after"].Draw("same hist")
  
  acan.cd(2)
  wp2["before"].SetTitle("RB4")
  wp2["before"].Draw("same hist")
  wp1["before"].Draw("same hist")
  wp0["before"].Draw("same hist")
  wm1["before"].Draw("same hist")
  wm2["before"].Draw("same hist")

  leg = TLegend(0.345,0.68,0.845,0.88) 
  leg.SetFillStyle( 0 )
  leg.SetBorderSize(0)
  leg.SetMargin( 0.1 )
  leg.AddEntry(wp2["after"], "W+2", "l")
  leg.AddEntry(wp1["after"], "W+1", "l")
  leg.AddEntry(wp0["after"], "W+0", "l")
  leg.AddEntry(wm1["after"], "W-1", "l")
  leg.AddEntry(wm2["after"], "W-2", "l")
  leg.Draw("same")
  
  acan.SaveAs("allwheels.png")
  acan.Clear()

  acan.Divide(2,1)
  acan.cd(1)
  rem4["after"].SetTitle("R3")
  rem4["after"].Draw("same hist")
  rem3["after"].Draw("same hist")
  rem2["after"].Draw("same hist")
  rem1["after"].Draw("same hist")
  
  acan.cd(2)
  rem4["before"].SetTitle("R3")
  rem4["before"].Draw("same hist")
  rem3["before"].Draw("same hist")
  rem2["before"].Draw("same hist")
  rem1["before"].Draw("same hist")

  leg = TLegend(0.345,0.68,0.845,0.88) 
  leg.SetFillStyle( 0 )
  leg.SetBorderSize(0)
  leg.SetMargin( 0.1 )
  leg.AddEntry(rem4["after"], "RE-4", "l")
  leg.AddEntry(rem3["after"], "RE-3", "l")
  leg.AddEntry(rem2["after"], "RE-2", "l")
  leg.AddEntry(rem1["after"], "RE-1", "l")
  leg.Draw("same")
  
  acan.SaveAs("alldisks.png")
  acan.Clear()



  return
Example #23
0
def printmultigraph(grs, sortk, plotoptions, outn, title, year, doext,
                    ploterror, ymax):
    import CMS_lumi, tdrstyle
    import array
    #set the tdr style
    tdrstyle.setTDRStyle()

    #change the CMS_lumi variables (see CMS_lumi.py)
    CMS_lumi.writeExtraText = 1
    CMS_lumi.extraText = "Preliminary"
    if year == 2018:
        CMS_lumi.extraText2 = "2018 pp data"
    if year == 2017:
        CMS_lumi.extraText2 = "2017 pp data"
    if year == 2016:
        CMS_lumi.extraText2 = "2016 pp data"
    CMS_lumi.lumi_sqrtS = "13 TeV"  # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)
    CMS_lumi.writeTitle = 1
    CMS_lumi.textTitle = title

    iPos = 11
    if (iPos == 0): CMS_lumi.relPosX = 0.12

    H_ref = 600
    W_ref = 800
    W = W_ref
    H = H_ref

    iPeriod = 0
    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.12 * W_ref
    R = 0.04 * W_ref

    c = TCanvas("c", "c", 50, 50, W, H)
    #gStyle.SetOptStat(0)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    #canvassettings(c)

    mg = TMultiGraph()
    #mg  = grs['main']
    mg.SetTitle(title)
    #gStyle.SetTitleAlign(33)
    #gStyle.SetTitleX(0.99)
    leg = TLegend(
        0.345, 0.68, 0.645, 0.88
    )  #TLegend(1. - c.GetRightMargin() - 0.8, 1. - c.GetTopMargin() - 0.40,1. - c.GetRightMargin()- 0.60, 1. - c.GetTopMargin() -0.02)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetMargin(0.1)
    #ymax = 0;
    ratesFromFit = {}
    evVal = 15000
    if doext:
        evVal = 50000

    #f=TFile.Open(outn+".root","RECREATE")


#  for name,value in plotoptions.iteritems():
    for name in sortk:
        if name != 'main': continue
        value = plotoptions[name]
        #print grs
        gr = grs[name]
        #print gr
        gr.SetName(title)
        #extrate = fitGraph(gr,evVal)
        #ratesFromFit[name] = extrate
        if doext:
            #print name, extrate[0], extrate[1]
            NN = gr.GetN()
            gr.Set(NN + 1)
            gr.SetPoint(NN + 1, 50000.0, extrate["rate"][0])
            yErr = extrate["rate"][1]
            if not ploterror:
                yErr = 0.0
            gr.SetPointError(NN + 1, 0.0, yErr)
        gr.SetMarkerColor(value['color'])
        gr.SetMarkerStyle(value['markst'])
        gr.SetLineColor(value['color'])
        gr.SetMarkerSize(1.15)  #1.05
        gr.SetMinimum(0.1)
        #gr.Write()
        mg.Add(gr)
        text = title  #name #+plotoptions[name]['leg']
        leg.AddEntry(gr, text, "p")
        continue

    mg.SetName(outn)
    mg.SetMinimum(0.1)
    mg.SetMaximum(ymax)  #1.6*ymax
    mg.Draw("AP")
    mg.GetXaxis().SetRangeUser(2000, 20000)
    c.Update()
    graphAxis(mg)

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)
    c.cd()
    c.Update()
    frame = c.GetFrame()
    frame.Draw()

    leg.Draw()
    c.SaveAs(outn + ".png")
    #c.SaveAs(outn+".C")
    del c

    return ratesFromFit
Example #24
0
def binFile(rerror, filename, xtitle, backgrounds):

    file = TFile(filename)
    keys = file.GetListOfKeys()

    h_bkg = {}
    h_data = {}

    # load all the background and data histograms
    for key in keys:
        key = key.GetName()
        print key
        info = hinfo(key)
        if not info.systematic:
            if info.process in backgrounds:
                if info.channel in h_bkg:
                    h_bkg[info.channel] = merge(h_bkg[info.channel], file.Get(key).Clone())
                else:
                    h_bkg[info.channel] = file.Get(key).Clone()
            elif info.process == 'data' or info.process == 'DATA':
                if info.channel in h_data:
                    h_data[info.channel] = merge(h_data[info.channel], file.Get(key).Clone())
                else:
                    h_data[info.channel] = file.Get(key).Clone()

    canvas = TCanvas()
    canvas.SetLogy()

    keys = file.GetListOfKeys()

    output = TFile(filename.split('.')[0]+'_rebinned.root', 'RECREATE')

    # print all the histograms for all the channels
    for key in h_bkg:

        binning = array.array('d', computeBinning(h_bkg[key], rerror))
        h_bkg[key] = h_bkg[key].Rebin(len(binning)-1, h_bkg[key].GetName(), binning)
        h_data[key] = h_data[key].Rebin(len(binning)-1, h_data[key].GetName(), binning)

        h_bkg[key].SetLineColor(ROOT.kGray+1)
        h_bkg[key].SetFillColor(ROOT.kGray+1)
        h_data[key].SetLineColor(ROOT.kBlack)
        h_data[key].SetMarkerStyle(20)

        pad = canvas.cd(1)
        pad.SetLeftMargin(0.15)
        pad.SetBottomMargin(0.15)

        maxs = [h_data[key].GetMaximum(), h_bkg[key].GetMaximum()]
        min = h_bkg[key].GetBinContent(h_bkg[key].GetMinimumBin())

        h_data[key].GetYaxis().SetRangeUser(0.5*min,max(maxs)*1.8)

        h_data[key].GetYaxis().SetLabelSize(0.05)
        h_data[key].GetYaxis().SetTitleSize(0.05)
        h_data[key].GetYaxis().SetTitle('event yield')
        h_data[key].GetXaxis().SetLabelSize(0.05)
        h_data[key].GetXaxis().SetTitleSize(0.05)
        h_data[key].GetXaxis().SetTitle(xtitle)

        h_data[key].Draw('e')
        h_bkg[key].Draw('samehist')
        h_data[key].Draw('samee')

        legend = TLegend(.67, .78, .89, .88)
        legend.SetMargin(0.12);
        legend.SetTextSize(0.03);
        legend.SetFillColor(10);
        legend.SetBorderSize(0);
        legend.AddEntry(h_bkg[key], "Background", "f")
        legend.AddEntry(h_data[key], "CMS Data 2015", "lp")
        legend.Draw()

        labelcms = TLegend(.15, .91, 1, .96)
        labelcms.SetTextSize(0.04)
        labelcms.SetMargin(0.12);
        labelcms.SetFillColor(10);
        labelcms.SetBorderSize(0);
        labelcms.SetHeader('CMS Preliminary #sqrt{s} = 13 TeV')
        labelcms.Draw()

        labellumi = TLegend(.73, .91, 1, .96)
        labellumi.SetTextSize(0.04)
        labellumi.SetMargin(0.12);
        labellumi.SetFillColor(10);
        labellumi.SetBorderSize(0);
        labellumi.SetHeader('L = 2.4 fb^{-1}')
        labellumi.Draw()

        labellumi2 = TLegend(.67, .70, .89, .75)
        labellumi2.SetTextSize(0.03)
        labellumi2.SetMargin(0.12);
        labellumi2.SetFillColor(10);
        labellumi2.SetBorderSize(0);
        labellumi2.SetHeader(key)
        labellumi2.Draw()

        canvas.SaveAs('h_'+filename.split('.')[0]+'_'+key+'.pdf')

        for hkey in keys:
            hkey = hkey.GetName()
            info = hinfo(hkey)
            if info.channel == key:
                histogram = file.Get(hkey).Clone()
                # Hack to fix the data lowercase names
                #if info.systematic == 'pdf':
                #    continue
                if (info.systematic == 'scale' or info.systematic == 'matching') and 'light' in info.process and '1btag' in info.channel:
                    print "Excluding : ", info.systematic, info.process, info.channel
                    continue
                if 'data' in info.process:
                    histogram.SetName(histogram.GetName().replace('data','DATA'))
                if 'ttbar' in info.process and info.systematic == 'scale':
                    orig = histogram.GetName()
                    histogram.SetName(histogram.GetName().replace('scale','scale_ttbar'))
                    print "Renaming: %s to %s" % (orig, histogram.GetName())
                if ('wlight' in info.process or 'zlight' in info.process) and info.systematic == 'scale':
                    orig = histogram.GetName()
                    histogram.SetName(histogram.GetName().replace('scale','scale_vjets'))
                    print "Renaming: %s to %s" % (orig, histogram.GetName())
                if ('wlight' in info.process or 'zlight' in info.process) and info.systematic == 'matching':
                    orig = histogram.GetName()
                    histogram.SetName(histogram.GetName().replace('matching','matching_vjets'))
                    print "Renaming: %s to %s" % (orig, histogram.GetName())
                if info.process.startswith('zp') or info.process.startswith('rsg'):
                    print "Scaling signal sample %s by x0.1" % histogram.GetName()
                    histogram.Scale(0.1)
                histogram = histogram.Rebin(len(binning)-1, histogram.GetName(), binning)
                output.cd()
                histogram.Write()
Example #25
0
    def drawlegend(self, position=None, **kwargs):
        """Create and draw legend.
    Legend position can be controlled in several ways
      drawlegend(position)
      drawlegend(position=position)
    where position is a string which can contain the horizontal position, e.g.
      'left', 'center', 'right', 'L', 'C', 'R', 'x=0.3', ...
    where 'x' is the position (between 0 an 1) of the left side in the frame.
    The position string can also contain the vertical position as e.g.
      'top', 'middle', 'bottom', 'T', 'M', 'B', 'y=0.3', ...
    where 'y' is the position (between 0 an 1) of the top side in the frame.
    Instead of the strings, the exact legend coordinates can be controlled with
    the keywords x1, x2, y1 and y2, or, x1, y1, width and height:
      drawlegend(x1=0.2,width=0.4)
      drawlegend(x1=0.2,width=0.4,y1=0.9,height=0.4)
      drawlegend(x1=0.2,x2=0.6,y1=0.9,y2=0.4)
    These floats are normalized to the axis frame, ignoring the canvas margins:
    x=0 is the left, x=1 is the right, y=0 is the bottom and y=1 is the top side.
    Values less than 0, or larger than 1, will put the legend outside the frame.
    """
        #if not ratio:
        #  tsize *= 0.80
        #  signaltsize *= 0.80
        verbosity = LOG.getverbosity(self, kwargs)
        hists = self.hists
        errstyle = 'lep' if gStyle.GetErrorX() else 'ep'
        entries = kwargs.get('entries', [])
        bands = kwargs.get('band', [self.errband])  # error bands
        bands = ensurelist(bands, nonzero=True)
        bandentries = kwargs.get('bandentries', [])
        title = kwargs.get('header', None)
        title = kwargs.get('title', title)  # legend header/title
        latex = kwargs.get('latex',
                           True)  # automatically format strings as LaTeX
        style = kwargs.get('style', None)
        style0 = kwargs.get('style0', None)  # style of first histogram
        errstyle = kwargs.get('errstyle', errstyle)  # style for an error point
        styles = kwargs.get('styles', [])
        position = kwargs.get('pos', position)  # legend position
        position = kwargs.get('position', position) or self.position
        option = kwargs.get('option', '')
        border = kwargs.get('border', False)
        transparent = kwargs.get('transparent', True)
        x1_user = kwargs.get('x1', None)  # legend left side
        x2_user = kwargs.get('x2', None)  # legend right side
        y1_user = kwargs.get('y1', None)  # legend top side
        y2_user = kwargs.get('y2', None)  # legend bottom side
        width = kwargs.get('width', -1)  # legend width
        height = kwargs.get('height', -1)  # legend height
        tsize = kwargs.get('tsize', _lsize)  # text size
        twidth = kwargs.get('twidth',
                            None) or 1  # scalefactor for legend width
        theight = kwargs.get('theight',
                             None) or 1  # scalefactor for legend height
        texts = kwargs.get('text', [])  # extra text below legend
        ncols = kwargs.get('ncols',
                           self.ncols) or 1  # number of legend columns
        colsep = kwargs.get('colsep',
                            0.06)  # seperation between legend columns
        bold = kwargs.get('bold', True)  # bold legend header
        panel = kwargs.get('panel', 1)  # panel (top=1, bottom=2)
        texts = ensurelist(texts, nonzero=True)
        entries = ensurelist(entries, nonzero=False)
        bandentries = ensurelist(bandentries, nonzero=True)
        headerfont = 62 if bold else 42

        # CHECK
        LOG.insist(self.canvas, "Canvas does not exist!")
        self.canvas.cd(panel)
        scale = 485. / min(gPad.GetWh() * gPad.GetHNDC(),
                           gPad.GetWw() * gPad.GetWNDC())
        tsize *= scale  # text size

        # ENTRIES
        #if len(bandentries)==len(bands) and len(entries)>len(hists):
        #  for band, bandtitle in zip(band,bandentries):
        #    entries.insert(hists.index(band),bandtitle)
        while len(entries) < len(hists):
            entries.append(hists[len(entries)].GetTitle())
        while len(bandentries) < len(bands):
            bandentries.append(bands[len(bandentries)].GetTitle())
        hists = hists + bands
        entries = entries + bandentries
        if latex:
            title = maketitle(title)
            entries = [maketitle(e) for e in entries]
            texts = [maketitle(t) for t in texts]
        maxlen = estimatelen([title] + entries + texts)

        # STYLES
        if style0:
            styles[0] = style0
        while len(styles) < len(hists):
            hist = hists[len(styles)]
            if hist in bands:
                styles.append('f')
            elif style != None:
                styles.append(style)
            elif hasattr(hist, 'GetFillStyle') and hist.GetFillStyle() > 0:
                styles.append('f')
            elif 'E0' in hist.GetOption() or 'E1' in hist.GetOption():
                styles.append(errstyle)
            else:
                styles.append('lp')

        # NUMBER of LINES
        nlines = sum([1 + e.count('\n') for e in entries])
        #else:       nlines += 0.80
        if texts: nlines += sum([1 + t.count('\n') for t in texts])
        if ncols > 1: nlines /= float(ncols)
        if title: nlines += 1 + title.count('\n')

        # DIMENSIONS
        if width < 0:
            width = twidth * max(0.22, min(0.60, 0.036 + 0.016 * maxlen))
        if height < 0: height = theight * 1.34 * tsize * nlines
        if ncols > 1: width *= ncols / (1 - colsep)
        x2 = 0.90
        x1 = x2 - width
        y1 = 0.92
        y2 = y1 - height

        # POSITION
        if position == None:
            position = ""
        position = position.replace('left', 'L').replace(
            'center', 'C').replace('right', 'R').replace(  #.lower()
                'top', 'T').replace('middle', 'M').replace('bottom', 'B')
        if not any(c in position for c in 'TMBy'):  # set default vertical
            position += 'T'
        if not any(c in position for c in 'LCRx'):  # set default horizontal
            position += 'RR' if ncols > 1 else 'R'  # if title else 'L'

        if 'C' in position:
            if 'R' in position: center = 0.57
            elif 'L' in position: center = 0.43
            else: center = 0.50
            x1 = center - width / 2
            x2 = center + width / 2
        elif 'LL' in position:
            x1 = 0.03
            x2 = x1 + width
        elif 'L' in position:
            x1 = 0.08
            x2 = x1 + width
        elif 'RR' in position:
            x2 = 0.97
            x1 = x2 - width
        elif 'R' in position:
            x2 = 0.92
            x1 = x2 - width
        elif 'x=' in position:
            x1 = float(re.findall(r"x=(\d\.\d+)", position)[0])
            x2 = x1 + width
        if 'M' in position:
            if 'T' in position: middle = 0.57
            elif 'B' in position: middle = 0.43
            else: middle = 0.50
            y1 = middle - height / 2
            y2 = middle + height / 2
        elif 'TT' in position:
            y2 = 0.97
            y1 = y2 - height
        elif 'T' in position:
            y2 = 0.92
            y1 = y2 - height
        elif 'BB' in position:
            y1 = 0.03
            y2 = y1 + height
        elif 'B' in position:
            y1 = 0.08
            y2 = y1 + height
        elif 'y=' in position:
            y2 = float(re.findall(r"y=(\d\.\d+)", position)[0])
            y1 = y2 - height
        if x1_user != None:
            x1 = x1_user
            x2 = x1 + width if x2_user == None else x2_user
        if y1_user != None:
            y1 = y1_user
            y2 = y1 - height if y2_user == None else y2_user
        L, R = gPad.GetLeftMargin(), gPad.GetRightMargin()
        T, B = gPad.GetTopMargin(), gPad.GetBottomMargin()
        X1, X2 = L + (1 - L - R) * x1, L + (
            1 - L - R) * x2  # convert frame to canvas coordinates
        Y1, Y2 = B + (1 - T - B) * y1, B + (
            1 - T - B) * y2  # convert frame to canvas coordinates
        legend = TLegend(X1, Y1, X2, Y2)
        LOG.verb(
            "Plot.drawlegend: position=%r, height=%.3f, width=%.3f, (x1,y1,x2,y2)=(%.2f,%.2f,%.2f,%.2f), (X1,Y1,X2,Y2)=(%.2f,%.2f,%.2f,%.2f)"
            % (position, height, width, x1, y1, x2, y2, X1, Y1, X2, Y2),
            verbosity, 1)

        # MARGIN
        if ncols >= 2:
            margin = 0.090 / width
        else:
            margin = 0.044 / width
        legend.SetMargin(margin)

        # STYLE
        if transparent: legend.SetFillStyle(0)  # 0 = transparent
        else: legend.SetFillColor(0)
        legend.SetBorderSize(border)
        legend.SetTextSize(tsize)
        legend.SetTextFont(headerfont)  # bold for title
        if ncols > 1:
            legend.SetNColumns(ncols)
            legend.SetColumnSeparation(colsep)

        # HEADER
        if title:
            legend.SetHeader(title)
        legend.SetTextFont(42)  # no bold for entries

        # ENTRIES
        if hists:
            for hist1, entry1, style1 in columnize(zip(hists, entries, styles),
                                                   ncols):
                for entry in entry1.split('\n'):
                    legend.AddEntry(hist1, entry, style1)
                    hist1, style1 = 0, ''
        for line in texts:
            legend.AddEntry(0, line, '')

        if verbosity >= 2:
            print ">>> Plot.drawlegend: title=%r, texts=%s, latex=%s" % (
                title, texts, latex)
            print ">>> Plot.drawlegend: hists=%s" % (hists)
            print ">>> Plot.drawlegend: entries=%s" % (entries)
            print ">>> Plot.drawlegend: styles=%s" % (styles)
            print ">>> Plot.drawlegend: nlines=%s, len(hists)=%s, len(texts)=%s, ncols=%s, margin=%s" % (
                nlines, len(hists), len(texts), ncols, margin)

        legend.Draw(option)
        self.legends.append(legend)
        return legend
Example #26
0
def cutflow(Region='SignalRegion',
            removeEvents=False,
            logY=True,
            normalise=True,
            singlePlots=False,
            drawOptions='HIST',
            weightedORraw='weighted'):
    # removeEvents=True
    PreSelectionName = 'PreSelection'
    # Region='HIGHSidebandRegion'
    PlotBGStack = False
    StackBG = False
    # singlePlots=False
    # normalise=True
    # logY=True
    # drawOptions='HIST TEXT90'

    channel = 'ZZ'

    channelTex = {
        'WPWP': 'W^{+}W^{+}',
        'WPWM': 'W^{+}W^{-}',
        'WMWM': 'W^{-}W^{-}',
        'WPZ': 'W^{+}Z',
        'WMZ': 'W^{-}Z',
        'ZZ': 'ZZ'
    }
    plotstyle = [(1, 1), (1, 2), (2, 1), (2, 2), (4, 1), (4, 2)]

    PreSelectionCuts = [
        ('nocuts', 'All'),
        ('common', 'CommonModules'),
        # ('corrections','JetCorrections'),
        # ('cleaner','JetCleaner'),
        ('AK4pfidfilter', 'AK4 PFID-Filter'),
        ('AK8pfidfilter', 'AK8 PFID-Filter'),
        ('AK8N2sel', 'N_{AK8} #geq 2'),
        ('invMAk8sel', 'M_{jj-AK8} > 1050 GeV'),
        ('detaAk8sel', '|#Delta#eta_{jj-AK8}|<1.3')
    ]

    SelectionCuts = [  #('preselection','PreSelection-check'),
        ('softdropAK8sel', '65 GeV <M_{SD}< 105 GeV'),
        ('tau21sel', '0 #leq #tau_{2}/#tau_{1}<0.35'),
        ('deltaR48', '#Delta R(AK4,leading AK8) > 1.3'),
        # ('VVRegion','VVRegion'),
        ('AK4N2sel', 'N_{AK4} #geq 2'),
        ('OpSignsel', '#eta_{1-AK4} #eta_{2-AK4} < 0'),
        ('detaAk4sel', '|#Delta#eta_{jj-AK4}| > 3.0'),
        ('invMAk4sel_1p0', 'M_{jj-AK4} > 1.0 TeV')
    ]

    Cuts = PreSelectionCuts + SelectionCuts
    # Cuts=SelectionCuts

    QCDColor = rt.kAzure + 7
    WJetsColor = rt.kRed - 4
    ZJetsColor = rt.kOrange - 2
    path = '/nfs/dust/cms/user/albrechs/UHH2_Output/'

    datasets = [  #(filename, Name for Legend, Linestyle, Color)
        ('MC.MC_aQGC_%sjj_hadronic.root' % channel, channelTex[channel], 1, 28
         )  #,
        # ('MC.MC_QCD.root','QCD',1,QCDColor),
        # ('MC.MC_WJetsToQQ_HT600ToInf.root','W+JetsToQQ',1,WJetsColor),
        # ('MC.MC_ZJetsToQQ_HT600ToInf.root','Z+JetsToQQ',1,ZJetsColor),
        # ('Data.DATA.root','Data',1,1)
    ]

    gROOT.ProcessLine("gErrorIgnoreLevel = 2001;")
    PreSelectionFiles = []
    SelectionFiles = []

    if removeEvents:
        PreSelectionName = PreSelectionName + 'RmEvent'
        Region = Region + 'RmEvent'

    for dataset in datasets:
        PreSelectionFiles.append(
            TFile(path + PreSelectionName +
                  "/uhh2.AnalysisModuleRunner.%s" % dataset[0]))
        # SelectionFiles.append(TFile(path+Region+'/backup/'+"/uhh2.AnalysisModuleRunner.%s"%dataset[0]))
        SelectionFiles.append(
            TFile(path + Region +
                  "/uhh2.AnalysisModuleRunner.%s" % dataset[0]))
    gROOT.ProcessLine("gErrorIgnoreLevel = 0;")

    yTitle = 'NEvents_%s' % weightedORraw
    if (normalise):
        yTitle = yTitle + '/N_%s' % Cuts[0][1]

    canv = TCanvas('cutflow_canvas', 'cutflow_canvas', 1000, 500)
    if (not singlePlots):
        legend = TLegend(0.7, 0.7, 0.9, 0.95)
        legend.SetFillStyle(0)
        legend.SetTextSize(0.02)
        legend.SetMargin(0.4)

    NCuts = len(Cuts)
    # NMETFilter=0
    # if 'common' in Cuts[:][0]:
    #     NMETFilter=PreSelectionFiles[0].Get('cf_metfilters').GetNbinsX()
    #     for i in range(1,PreSelectionFiles[0].Get('cf_metfilters').GetNbinsX()):
    #         Cuts.insert(Cuts.index(('common','CommonModules')),(PreSelectionFiles[0].Get('cf_metfilters').GetXaxis().GetBinLabel(i),PreSelectionFiles[0].Get('cf_metfilters').GetXaxis().GetBinLabel(i)))
    #     NCuts=NCuts+NMETFilter
    print('Plotting Cutflow of', NCuts, 'Cuts.')
    # for dataset in datasets:
    BGStack = THStack('MCBackground', 'MCBackground')

    TotalMinimum = 10**10
    NBG = 0
    for l in range(len(datasets)):
        print('checking', datasets[l][1])
        if normalise:
            if ((len(Cuts) == len(PreSelectionCuts)) or
                (len(Cuts) == (len(PreSelectionCuts) + len(SelectionCuts)))):
                Norm = PreSelectionFiles[l].Get(Cuts[0][0] + '/NEvents_%s' %
                                                weightedORraw).GetBinContent(1)
            else:
                Norm = SelectionFiles[l].Get(Cuts[0][0] + '/NEvents_%s' %
                                             weightedORraw).GetBinContent(1)
        else:
            Norm = 1
        if (len(Cuts) > len(PreSelectionCuts)):
            CurrentMinimum = SelectionFiles[l].Get(
                SelectionCuts[-1][0] +
                '/NEvents_%s' % weightedORraw).GetBinContent(1) / Norm
        else:
            CurrentMinimum = PreSelectionFiles[l].Get(
                PreSelectionCuts[-1][0] +
                '/NEvents_%s' % weightedORraw).GetBinContent(1) / Norm
        print(CurrentMinimum, TotalMinimum)

        if (CurrentMinimum < TotalMinimum):
            print('setting ', datasets[l][1], 'as new minimum')
            TotalMinimum = CurrentMinimum
        if (datasets[l][1] == 'QCD' or datasets[l][1] == 'W+JetsToQQ'
                or datasets[l][1] == 'Z+JetsToQQ'):
            # NBG= NBG + PreSelectionFiles[l].Get(Cuts[0][0]+'/NEvents_%s'%weightedORraw).GetBinContent(1)
            NBG = NBG + Norm
    cutflows = []
    for i in range(len(datasets)):
        if (singlePlots):
            legend = TLegend(0.75, 0.6, 1, 0.9)
            legend.SetFillStyle(0)
            legend.SetTextSize(0.02)
            legend.SetMargin(0.4)

        print('Drawing', datasets[i][1])
        currentCutflow = TH1F(datasets[i][1], datasets[i][1], NCuts, 0, NCuts)
        cutflows.append(currentCutflow)
        #filling the current cutflow (with NEvents_weighted or NEvents_raw)
        if (normalise):
            if (StackBG and
                (datasets[i][1] == 'QCD' or datasets[i][1] == 'W+JetsToQQ'
                 or datasets[i][1] == 'Z+JetsToQQ')):
                NAll = NBG
            else:
                if ((len(Cuts) == len(PreSelectionCuts))
                        or (len(Cuts)
                            == (len(PreSelectionCuts) + len(SelectionCuts)))):
                    NAll = PreSelectionFiles[i].Get(
                        PreSelectionCuts[0][0] +
                        '/NEvents_%s' % weightedORraw).GetBinContent(1)
                else:
                    NAll = SelectionFiles[i].Get(
                        SelectionCuts[0][0] +
                        '/NEvents_%s' % weightedORraw).GetBinContent(1)

        else:
            NAll = 1
        for j in range(NCuts):
            cut = Cuts[j]
            if ((len(Cuts) == len(PreSelectionCuts)) or
                (len(Cuts) == (len(PreSelectionCuts) + len(SelectionCuts)))
                    and j < len(PreSelectionCuts)):
                NEvents = PreSelectionFiles[i].Get(
                    cut[0] + '/NEvents_%s' % weightedORraw).GetBinContent(1)
            else:
                NEvents = SelectionFiles[i].Get(cut[0] + '/NEvents_%s' %
                                                weightedORraw).GetBinContent(1)
                # NEvents=NAll
            currentCutflow.GetXaxis().SetBinLabel(j + 1, cut[1])
            currentCutflow.Fill(j + 0.5, NEvents / NAll)
        #cosmectics for and draw current cutflow
        currentCutflow.SetLineColor(datasets[i][3])
        currentCutflow.SetMarkerSize(1.4)
        currentCutflow.GetYaxis().SetTitle(yTitle)
        HistMax = currentCutflow.GetMaximum()
        if (logY):
            if (singlePlots):
                MAX = float(10**(magnitude(HistMax) + 3))
                MIN = float(10**(magnitude(currentCutflow.GetMinimum()) - 1))
            else:
                MAX = float(10**(magnitude(HistMax) + 2))
                MIN = float(10**(magnitude(TotalMinimum) - 1))

            MIN += float(10**(magnitude(MIN)))
        else:
            MAX = 1.1 * HistMax
            MIN = 0.
        currentCutflow.GetYaxis().SetRangeUser(MIN, MAX)
        print('RangeUser=(', MIN, ',', MAX, ')')
        print('drawOptions:', drawOptions)
        if (datasets[i][1] == 'Data'):
            # legend.AddEntry(currentCutflow,datasets[i][1],'lep')
            # currentCutflow.SetMarkerStyle(8)
            # currentCutflow.Draw(drawOptions+'HP')
            legend.AddEntry(currentCutflow, datasets[i][1], 'l')
            currentCutflow.Draw(drawOptions)
            if (not singlePlots and ('SAME' not in drawOptions)):
                drawOptions = drawOptions + 'SAME'
        elif (StackBG
              and (datasets[i][1] == 'QCD' or datasets[i][1] == 'W+JetsToQQ'
                   or datasets[i][1] == 'Z+JetsToQQ')):
            legend.AddEntry(currentCutflow, datasets[i][1], 'f')
            currentCutflow.SetFillColor(datasets[i][3])
            BGStack.Add(currentCutflow, drawOptions)
            # currentCutflow.Draw(drawOptions)
            PlotBGStack = True
        else:
            legend.AddEntry(currentCutflow, datasets[i][1], 'l')
            currentCutflow.Draw(drawOptions)
            if (not singlePlots and ('SAME' not in drawOptions)):
                drawOptions = drawOptions + 'SAME'

        if (singlePlots):
            legend.Draw()
            if (logY):
                canv.SetLogy()
            # canv.SetGrid()
            canv.SetTicks()
            gPad.RedrawAxis()
            canv.Print('cutflows/' + Region + '_cutflow_%s_%s.eps' %
                       (datasets[i][1], weightedORraw))
    if (not singlePlots):
        if (PlotBGStack):
            BGStack.Draw(drawOptions)
        legend.Draw()
        if (logY):
            canv.SetLogy()
        # canv.SetGrid()
        canv.SetTicks()
        gPad.RedrawAxis()
        canv.Print('cutflows/' + Region + '_cutflow_%s.eps' % weightedORraw)
Example #27
0
def plotter(plotdir,
            plot,
            xTitle,
            logY,
            channels=['VV'],
            includeData=False,
            scaleSignal=0,
            UserRange=[None, None, None, None],
            initPath=''):

    # channelTex={'WPWP':'W^{+}W^{+}', 'WPWM':'W^{+}W^{-}','WMWM':'W^{-}W^{-}','WPZ':'W^{+}Z','WMZ':'W^{-}Z','ZZ':'ZZ'}
    channelTex = {'ZZ': 'ZZ'}
    # plotstyle=[(1,1),(1,2),(2,1),(2,2),(4,1),(4,2)]
    plotstyle = [(1, 1)]
    #             0              1                       2                        3             4              5             6
    # Backgrounds=['QCD',     'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf',     'TT',         'WW',          'WZ',         'ZZ']
    # BGColors=   [rt.kAzure+7,   rt.kRed-4,              rt.kOrange-2,            rt.kGreen+2,  rt.kOrange+7,  rt.kBlue+1,   rt.kMagenta+2]
    # BGTeX=      ['QCD',        'W+JetsToQQ',           'Z+JetsToQQ',             'TTbar'],      'WW',          'WZ',         'ZZ']
    #stackOrder= [4,5,6,2,1,3,0]
    Backgrounds = [
        'QCD'
    ]  # 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'ZZ']  'TT',         'WW',          'WZ',         'ZZ']
    BGColors = [
        rt.kAzure + 7
    ]  #,              rt.kOrange-2,            rt.kGreen+2],  rt.kOrange+7,  rt.kBlue+1,   rt.kMagenta+2]
    BGTeX = ['QCD']  #

    stackOrder = [0]

    PreSelection = [
        'nocuts', 'common', 'corrections', 'cleaner', 'softdropmassCorr',
        'AK4pfidfilter', 'AK8pfidfilter', 'invMAk8sel', 'detaAk8sel',
        'AK8N2sel'
    ]
    Selection = [
        'preselection', 'softdropAK8sel', 'tau21sel', 'deltaR48', 'VVRegion',
        'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0', 'Kin_AK8'
    ]

    cutnames = [
        'cleaner', 'AK8N2sel', 'invMAk8sel', 'detaAk8sel', 'softdropAK8sel',
        'tau21sel', 'AK4cleaner', 'AK4N2sel', 'OpSignsel', 'detaAk4sel',
        'invMAk4sel_1p0'
    ]

    cuts = {
        'cleaner':
        '#splitline{p_{T-AK8} > 200 GeV, |#eta_{AK8}| < 2.5}{p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0}',
        'AK8N2sel': 'N_{AK8} #geq 2',
        'invMAk8sel': 'M_{jj-AK8} > 1050 GeV',
        'detaAk8sel': '|#Delta#eta_{jj-AK8}|<1.3',
        'softdropAK8sel': '65 GeV <M_{SD}< 105 GeV',
        'tau21sel': '0 #leq #tau_{2}/#tau_{1}<0.45',
        # 'AK4cleaner':'p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0',
        'AK4cleaner': '',
        'AK4N2sel': 'N_{AK4} #geq 2',
        'OpSignsel': '#eta_{1-AK4} #eta_{2-AK4} < 0',
        'detaAk4sel': '|#Delta#eta_{jj-AK4}| > 3.0',
        'invMAk4sel_1p0': 'M_{jj-AK4} > 1.0 TeV'
    }

    VV = ('VV' in channels)
    seperate = (not VV)
    if VV:
        #channels=["WPWP","WPWM","WMWM","WPZ","WMZ","ZZ"]
        channels = ["ZZ"]

    plottitle = plotdir + '_' + plot

    lumi = 36.814
    xLabelSize = 18.
    yLabelSize = 18.
    xTitleSize = 20.
    yTitleSize = 22.
    xTitleOffset = 4.
    yTitleOffset = 1.3

    printout = False
    Portrait = True
    cutname = False
    ratio = includeData

    if ('highbin' in plot):
        binning = 'dijetbinning'
    else:
        binning = 'default'

    if (Portrait):
        canvX = 600
        canvY = 600
    else:
        canvX = 900
        canvY = 675

    if (plotdir in PreSelection):
        region = 'PreSelection'
        initPath = ''
        referenceHistPath = 'detaAk8sel/N_pv'
        if (PreSelection.index(plotdir) < 4 and ('softdrop' in plot)):
            return 'SofdropMass not filled yet!'
    else:
        region = 'SignalRegion'
        referenceHistPath = 'tau21sel/N_pv'
    referenceHistPath = plotdir + '/' + plot

    if (initPath == ''):
        path = '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/%s' % region
    else:
        path = initPath
    outputPath = path.replace(
        '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/SignalRegion',
        'plots/')
    if (plotdir in PreSelection):
        CutNumber = PreSelection.index(plotdir)
    else:
        CutNumber = Selection.index(plotdir)
    outputPath = outputPath + '/%02i_%s' % (CutNumber, plotdir) + '/'
    if (printout):
        print('InputPath:', path)
        print('OutputPath:', outputPath)
    #check if OutputPath exists - and if not create it!
    if not os.path.exists(outputPath):
        os.makedirs(outputPath)
    # path='/home/albrec/Master/signal/'
    scaleVV = (scaleSignal != 0)
    VVScale = scaleSignal

    if (UserRange[2] == None or UserRange[3] == None):
        YRangeUser = False
        Ymin = UserRange[2]
        Ymax = UserRange[3]
    else:
        YRangeUser = True
        Ymin = UserRange[2]
        Ymax = UserRange[3]

    if (UserRange[0] == None or UserRange[1] == None):
        XRangeUser = False
        Xmin = UserRange[0]
        Xmax = UserRange[1]
    else:
        XRangeUser = True
        Xmin = UserRange[0]
        Xmax = UserRange[1]

    # YRangeUser=False
    # Ymin=0.11
    # Ymax=9*10**3

    # XRangeUser=False
    # Xmin=0
    # Xmax=6000.

    gROOT.ProcessLine("gErrorIgnoreLevel = 2001;")
    SFiles = []
    for i in range(len(channels)):
        SFiles.append(
            TFile(
                path +
                "/uhh2.AnalysisModuleRunner.MC.MC_aQGC_%sjj_hadronic_2016v3.root"
                % channels[i]))
#uhh2.AnalysisModuleRunner.MC.MC_aQGC_ZZjj_hadronic_2016v3.root
##Open Files to get BackgroundHist:
    BFiles = []
    for i in range(len(Backgrounds)):
        BFiles.append(
            TFile(path +
                  "/uhh2.AnalysisModuleRunner.MC.MC_%s.root" % Backgrounds[i]))

    #Open File to get DataHist:

# DataFile = TFile(path+"/uhh2.AnalysisModuleRunner.Data.DATA.root")

#gROOT.ProcessLine( "gErrorIgnoreLevel = 0;")

    if (includeData == True):
        #calculate QCDscale with Integrals from the following Histogram:
        # referenceHistPath = 'tau21sel/N_AK4'
        # referenceHistPath = 'detaAk8sel/N_pv'
        # referenceHistPath = 'tau21sel/met_pt_over_sumptAK8_2'
        QCDscale = float(DataFile.Get(referenceHistPath).Integral())
        QCDNorm = 1
        for i in range(len(BFiles)):
            if ('QCD' in BFiles[i].GetName()):
                QCDNorm = float(BFiles[i].Get(referenceHistPath).Integral())
            else:
                QCDscale -= float(BFiles[i].Get(referenceHistPath).Integral())
        QCDscale /= QCDNorm
    else:
        QCDscale = 1.0
    if (printout):
        print('using QCDscale:', QCDscale)

    SHists = []
    for i in range(len(channels)):
        SHists.append(SFiles[i].Get(plotdir + '/' + plot))

    BHists = []
    for i in range(len(BFiles)):
        BHists.append(BFiles[i].Get(plotdir + '/' + plot))
        if ('QCD' in BFiles[i].GetName()):
            BHists[-1].Scale(QCDscale)

    #if(includeData):
    #    DataHist=DataFile.Get(plotdir+'/'+plot)

    if (binning == 'dijetbinning'):
        fitbinning = array('d')
        binwidth = 200
        NBins = (14000 / binwidth) - ((1040 / binwidth) + 1)
        NBins = int(NBins)
        for i in range(NBins + 1):
            fitbinning.append(1050 + i * binwidth)

        for i in range(len(channels)):
            SHists[i] = SHists[i].Rebin(NBins, "new binning", fitbinning)
        for i in range(len(Backgrounds)):
            BHists[i] = BHists[i].Rebin(NBins, "new binning", fitbinning)

        if (includeData):
            DataHist = DataHist.Rebin(NBins, "new binning", fitbinning)

    canv = TCanvas(plottitle, plottitle, canvX, canvY)

    yplot = 0.7
    yratio = 0.3
    ymax = 1.0
    xmax = 1.0
    xmin = 0.0
    if (ratio):
        plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot, xmax, ymax)
        ratiopad = TPad("ratiopad", "Ratio", xmin, ymax - yplot - yratio, xmax,
                        ymax - yplot)
    else:
        plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot - yratio, xmax,
                       ymax)

    plotpad.SetTopMargin(0.08)
    plotpad.SetLeftMargin(0.1)
    plotpad.SetRightMargin(0.05)
    plotpad.SetTicks()
    plotpad.Draw()

    if (ratio):
        plotpad.SetBottomMargin(0.016)
        ratiopad.SetTopMargin(0.016)
        ratiopad.SetBottomMargin(0.35)
        ratiopad.SetLeftMargin(0.1)
        ratiopad.SetRightMargin(0.05)
        ratiopad.SetTicks()
        ratiopad.Draw()
    else:
        plotpad.SetBottomMargin(0.1)

    if (logY):
        plotpad.SetLogy()
        canv.SetLogy()
    if ('-logX' in xTitle):
        plotpad.SetLogx()
        if (ratio):
            ratiopad.SetLogx()
        canv.SetLogx()

    drawOptions = "HE"

    stack = THStack(plottitle, plottitle)

    BHist = THStack(plottitle, plottitle)

    # for i in range(len(Backgrounds)):
    for i in stackOrder:
        # BHists[i].SetFillColor(BGColors[i])
        BHists[i].SetLineColor(BGColors[i])
        BHist.Add(BHists[i], 'Hist')

    BHist.SetTitle(plottitle)

    BHistErr = BHists[0].Clone()
    for i in range(1, len(Backgrounds)):
        BHistErr.Add(BHists[i])

    BHistErr.SetFillStyle(3204)
    BHistErr.SetFillColor(rt.kGray + 2)
    BHistErr.SetLineColor(1)

    BGMax = BHist.GetMaximum()
    SIGMax = 0
    #if(VV):       #new
    #    SIGMax=VVsum.GetMaximum()
    #else:
    for i in range(len(channels)):
        tmpmax = SHists[i].GetMaximum()
        if (tmpmax > SIGMax):
            SIGMax = tmpmax
    if (scaleVV):
        SIGMax = SIGMax * VVScale
    if (logY):
        MAX = 0.9 * float(10**(magnitude(max(BGMax, SIGMax)) + 1))
        MIN = float(10**(magnitude(max(BGMax, SIGMax)) - 5))
        MIN += float(10**(magnitude(MIN)))
        legendMIN = math.log(max(BGMax, SIGMax)) / math.log(MAX)
    else:
        MAX = (1.0 / 0.8) * max(BGMax, SIGMax)
        legendMIN = 0.7
        MIN = 0.
    legendMIN = (legendMIN * 0.7) + 0.3 - 0.016

    legend = TLegend(0.5, 0.75, 0.85, 0.89)
    legend.SetFillStyle(0)
    legend.SetTextSize(0.02)
    legend.SetMargin(0.4)
    legend.SetNColumns(2)
    legend.SetColumnSeparation(0.3)

    if (includeData):
        DataHist.SetMarkerStyle(8)
        DataHist.SetLineColor(1)
        DataHist.SetTitle(plottitle)

    if VV:
        for i in range(len(channels)):
            if (i == 0):
                VVsum = SHists[i].Clone()
            else:
                VVsum.Add(SHists[i])
        legentry = 'VVjj'
        if (scaleVV):
            VVsum.Scale(VVScale)
            legentry += ' *%0.f' % VVScale
        VVsum.SetLineColor(1)
        VVsum.SetLineStyle(plotstyle[0][1])
        VVsum.SetLineWidth(2)
        legend.AddEntry(VVsum, legentry)
    else:
        for i in range(len(channels)):
            SHists[i].SetLineColor(plotstyle[i][0])
            SHists[i].SetLineStyle(plotstyle[i][1])
            SHists[i].SetLineWidth(2)
            legentry = "%sjj" % channelTex[channels[i]]
            if (scaleVV):
                SHists[i].Scale(VVScale)
                legentry += ' *%.2E' % VVScale
            legend.AddEntry(SHists[i], legentry)

    for i in stackOrder:
        legend.AddEntry(BHists[i], BGTeX[i], "f")
    legend.AddEntry(BHistErr, "stat. Uncertainty", "f")

    if (includeData):
        legend.AddEntry(DataHist, "Data", "lep")

    canv.SetTitle(plottitle)

    BHistErr.GetYaxis().SetTitle('Events')
    BHistErr.GetYaxis().SetRangeUser(MIN, MAX)
    BHistErr.GetYaxis().SetTitleFont(43)
    BHistErr.GetYaxis().SetTitleSize(yTitleSize)
    BHistErr.GetYaxis().SetTitleOffset(yTitleOffset)
    BHistErr.GetYaxis().SetLabelFont(43)
    BHistErr.GetYaxis().SetLabelSize(yLabelSize)
    if (ratio):
        BHistErr.GetXaxis().SetTitleSize(0.0)
        BHistErr.GetXaxis().SetLabelSize(0.0)
    else:
        BHistErr.GetXaxis().SetTitle(xTitle)
        BHistErr.GetXaxis().SetTitleFont(43)
        BHistErr.GetXaxis().SetTitleSize(xTitleSize)
        # BHistErr.GetXaxis().SetTitleOffset(xTitleOffset)
        BHistErr.GetXaxis().SetTitleOffset(1.2)
        BHistErr.GetXaxis().SetLabelFont(43)
        BHistErr.GetXaxis().SetLabelSize(xLabelSize)
        # BHistErr.GetXaxis().SetTickLength(0.08)
        # BHistErr.GetXaxis().SetNdivisions(506)

    if (YRangeUser):
        BHistErr.GetYaxis().SetRangeUser(Ymin, Ymax)
    if (XRangeUser):
        BHistErr.GetXaxis().SetRangeUser(Xmin, Xmax)

    plotpad.cd()

    BHistErr.Draw("E2")
    BHist.Draw("HistSAME")
    BHistErr.Draw("E2SAME")

    if (VV):
        VVsum.Draw("SAME" + drawOptions)
    elif ('-noSig' not in xTitle):
        for i in range(len(channels)):
            SHists[i].Draw("SAME" + drawOptions)

    if (includeData):
        DataHist.Draw("APE1SAME")

    plotpad.RedrawAxis()
    if (ratio):
        ratiopad.cd()

        if (includeData):
            ratioHist = DataHist.Clone()
        else:
            ratioHist = BHistErr.Clone()
        ratioHist.SetLineColor(rt.kBlack)
        # ratioHist.Sumw2()
        ratioHist.SetStats(0)
        ratioHist.Divide(BHistErr)
        ratioHist.SetMarkerStyle(21)
        ratioHist.SetMarkerSize(0.7)

        #Yaxis
        ratioHist.GetYaxis().SetRangeUser(0.3, 1.7)
        ratioHist.GetYaxis().SetTitle("Data/BG")
        ratioHist.GetYaxis().CenterTitle()
        ratioHist.GetYaxis().SetTitleFont(43)
        ratioHist.GetYaxis().SetTitleSize(yTitleSize)
        ratioHist.GetYaxis().SetTitleOffset(yTitleOffset)
        ratioHist.GetYaxis().SetLabelFont(43)
        ratioHist.GetYaxis().SetLabelSize(yLabelSize)
        ratioHist.GetYaxis().SetNdivisions(506)
        #Xaxis
        ratioHist.GetXaxis().SetTitle(xTitle)
        ratioHist.GetXaxis().SetTitleFont(43)
        ratioHist.GetXaxis().SetTitleSize(xTitleSize)
        ratioHist.GetXaxis().SetTitleOffset(xTitleOffset)
        ratioHist.GetXaxis().SetLabelFont(43)
        ratioHist.GetXaxis().SetLabelSize(xLabelSize)
        ratioHist.GetXaxis().SetTickLength(0.08)
        ratioHist.GetXaxis().SetNdivisions(506)

        # if(YRangeUser):
        #     ratioHist.GetYaxis().SetRangeUser(Ymin,Ymax)
        if (XRangeUser):
            ratioHist.GetXaxis().SetRangeUser(Xmin, Xmax)
            ratioXMin = Xmin
            ratioXMax = Xmax
        else:
            ratioXMin = ratioHist.GetXaxis().GetXmin()
            ratioXMax = ratioHist.GetXaxis().GetXmax()
        ratioHist.Draw("ep")

        zeropercent = TLine(ratioXMin, 1, ratioXMax, 1)
        zeropercent.Draw()
        plus10percent = TLine(ratioXMin, 1.1, ratioXMax, 1.1)
        plus10percent.SetLineStyle(rt.kDashed)
        plus10percent.Draw()
        minus10percent = TLine(ratioXMin, 0.9, ratioXMax, 0.9)
        minus10percent.SetLineStyle(rt.kDashed)
        minus10percent.Draw()

    canv.cd()
    gPad.RedrawAxis()
    legend.Draw()

    latex = TLatex()
    latex.SetNDC(kTRUE)
    latex.SetTextSize(20)
    latex.DrawLatex(0.69, 0.953, "%.2f fb^{-1} (13 TeV)" % lumi)
    latex.DrawLatex(0.1, 0.953, "private work")

    lastcut = 'nocuts'
    for cut in cutnames:
        if cut in plotdir:
            lastcut = cut

    if (not (lastcut == 'nocuts') and cutname):
        # latex.SetTextSize(0.03)
        latex.SetTextSize(15)
        for l in range(cutnames.index(lastcut) + 1):
            latex.DrawLatex(0.12, 0.8 - l * 0.04, cuts[cutnames[l]])

    canv.Update()
    canv.Print(outputPath + '/%s_%s.pdf' % (plotdir, plot))
    #prevents memory leak in Canvas Creation/Deletion
    #see: https://root.cern.ch/root/roottalk/roottalk04/2484.html
    gSystem.ProcessEvents()
    if (ratio):
        del ratiopad
    del plotpad, canv
    # gc.collect()
    return 'done!'
Example #28
0
def drawHistsWithRatio(hists, name, **kwargs):
    """Draw histograms with ratios."""

    title = kwargs.get('title', "")
    xtitle = kwargs.get('xtitle', "")
    ytitle = kwargs.get('ytitle', "")
    rtitle = kwargs.get('rtitle', "Ratio")
    xmin = kwargs.get('xmin', hists[0].GetXaxis().GetXmin())
    xmax = kwargs.get('xmax', hists[0].GetXaxis().GetXmax())
    ymin = kwargs.get('ymin', None)
    ymax = kwargs.get('ymax', None)
    rmin = kwargs.get('rmin', 0.45)
    rmax = kwargs.get('rmax', 1.55)
    logx = kwargs.get('logx', False)
    logy = kwargs.get('logy', False)
    denom = kwargs.get('denom', 1) - 1  # denominator for ratio
    textsize = kwargs.get('textsize', 0.045)
    texts = kwargs.get('text', [])
    #textheight = kwargs.get('textheight',   1.09                 )
    #ctext      = kwargs.get('ctext',        [ ]                  ) # corner text
    #cposition  = kwargs.get('cposition',    'topleft'            ).lower() # cornertext
    #ctextsize  = kwargs.get('ctextsize',    1.4*legendtextsize   )
    colors = kwargs.get('colors', linecolors)
    if not isinstance(texts, list) or isinstance(texts, tuple):
        texts = [texts]
    if ymax == None:
        ymax = 1.12 * max(h.GetMaximum() for h in hists)

    # MAIN plot
    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 800)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.Divide(2)
    canvas.SetMargin(0.0, 0.0, 0.0, 0.0)
    canvas.cd(1)
    gPad.SetPad('pad1', 'pad1', 0, 0.33, 1, 1)
    gPad.SetMargin(0.12, 0.04, 0.02, 0.08)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetTickx(0)
    gPad.SetTicky(0)
    gPad.SetGrid()
    gPad.Draw()
    canvas.cd(2)
    gPad.SetPad('pad2', 'pad2', 0, 0, 1, 0.33)
    gPad.SetMargin(0.12, 0.04, 0.30, 0.03)
    gPad.SetFillColor(0)
    gPad.SetFillStyle(4000)
    gPad.SetFrameFillStyle(0)
    gPad.SetBorderMode(0)
    gPad.Draw()

    # MAIN plot
    canvas.cd(1)
    for i, hist in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.Draw('HIST SAME')
    frame = hists[0]
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0)
    frame.GetXaxis().SetLabelSize(0)
    frame.GetYaxis().SetLabelSize(0.052)
    frame.GetXaxis().SetLabelOffset(0.010)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    if logy:
        gPad.Update()
        gPad.SetLogy()
    if ymin: frame.SetMinimum(ymin)
    if ymax: frame.SetMaximum(ymax)

    width = 0.25
    height = 1.1 * textsize * len([l for l in texts + hists if l])
    x1, y1 = 0.65, 0.88
    x2, y2 = x1 + width, y1 - height
    legend = TLegend(x1, y1, x2, y2)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetMargin(0.05 / width)
    if title:
        legend.SetTextFont(62)
        legend.SetHeader(title)
    legend.SetTextFont(42)
    for hist in hists:
        legend.AddEntry(hist, hist.GetTitle(), 'l')
    for text in texts:
        legend.AddEntry(0, text, '')
    legend.Draw()

    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame.Draw('AXIS SAME')
    CMS_style.CMS_lumi(gPad, 13, 0)

    # RATIO plot
    canvas.cd(2)
    ratios = []
    for i, hist in enumerate(hists):
        if i == denom: continue
        ratio = hist.Clone(hist.GetName() + "_ratio")
        ratio.Divide(hists[denom])
        ratio.Draw('HIST SAME')
        ratios.append(ratio)
    frame_ratio = ratios[0]
    frame_ratio.GetYaxis().SetRangeUser(rmin, rmax)
    frame_ratio.GetYaxis().CenterTitle()
    frame_ratio.GetYaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetLabelSize(0.12)
    frame_ratio.GetYaxis().SetLabelSize(0.11)
    frame_ratio.GetXaxis().SetLabelOffset(0.012)
    frame_ratio.GetXaxis().SetTitleOffset(1.02)
    frame_ratio.GetYaxis().SetTitleOffset(0.48)
    frame_ratio.GetXaxis().SetNdivisions(508)
    frame_ratio.GetYaxis().CenterTitle(True)
    frame_ratio.GetYaxis().SetTitle(rtitle)
    frame_ratio.GetXaxis().SetTitle(xtitle)
    frame_ratio.GetYaxis().SetNdivisions(505)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    line = TLine(xmin, 1., xmax, 1.)
    line.SetLineColor(hists[denom].GetLineColor())
    line.SetLineWidth(hists[denom].GetLineWidth())
    line.SetLineStyle(1)
    line.Draw('SAME')
    gPad.SetTicks(1, 1)
    gPad.Update()
    gPad.SetGrid()
    gPad.Modified()
    frame_ratio.Draw('SAME AXIS')

    canvas.SaveAs(name + ".png")
    canvas.SaveAs(name + ".pdf")
    canvas.Close()
Example #29
0
xstart = 0.4
ystart = 0.75

latex = TLatex()
latex.SetNDC()
latex.SetTextAlign(12)
latex.SetTextSize(textsize)
latex.DrawLatex(xstart, 0.85, "CMS Preliminary")
latex.DrawLatex(xstart, 0.80, "4.96 fb^{-1}, #sqrt{s}=7TeV")

legend = TLegend(xstart, ystart - 7.7 * textsize, xstart + width, ystart)
legend.SetFillColor(0)
legend.SetTextSize(textsize)
legend.SetColumnSeparation(0.0)
legend.SetEntrySeparation(0.1)
legend.SetMargin(0.2)

# Add data to legend
if nj == "2":
    legend.AddEntry(rooplot.findObject("h_dataset"), "2-jet Data", "p")
elif nj == "3":
    legend.AddEntry(rooplot.findObject("h_dataset"), "3-jet Data", "p")
elif nj == "4":
    legend.AddEntry(rooplot.findObject("h_dataset"), "#geq4-jet Data", "p")
elif nj == "23":
    legend.AddEntry(rooplot.findObject("h_dataset"), "2+3-jet Data", "p")

# Add functions to legend
for func in ["f1", "f2", "f3"]:
    legend.AddEntry(pdfs[func, "obj"], fitFuncs[func, "name"], "l")
Example #30
0
def hvt(benchmark=['B3', 'A1']):

    hxs = {}
    hw = {}
    gxs = {}
    gw = {}
    mg = TMultiGraph()

    for m in massPoints:

        hxs[m] = TH2F("hxs_M%d" % m, ";;", 50, -0.04, 3.96, 100, 0., 2.)
        hw[m] = TH2F("hw_M%d" % m, ";;", 50, -0.04, 3.96, 50, 0., 2.)

    for m in massPoints:
        file = TFile.Open("HVT/scanHVT_M%s.root" % m, "READ")
        tree = file.Get("tree")
        for entry in range(
                tree.GetEntries()):  # Fill mass points only if NOT excluded
            tree.GetEntry(entry)
            gH, gF = tree.gv * tree.ch, tree.g * tree.g * tree.cq / tree.gv
            XsBr = tree.CX0 * tree.BRbb * 1000.  # in fb
            if XsBr < observed[m]: hxs[m].Fill(gH, gF)
            if tree.total_widthV0 / float(m) < width: hw[m].Fill(gH, gF)

        for b in range(hxs[m].GetNbinsX() * hxs[m].GetNbinsY()):
            hxs[m].SetBinContent(b, 1. if hxs[m].GetBinContent(b) > 0. else 0.)
            hw[m].SetBinContent(b, 1. if hw[m].GetBinContent(b) > 0. else 0.)

        #hxs[m].Smooth(20)
        #hw[m].Smooth(20)

        gxs[m] = getCurve(hxs[m])
        for i, g in enumerate(gxs[m]):
            g.SetLineColor(massColors[m])
            g.SetFillColor(massColors[m])
            g.SetFillStyle(massFill[m])  #(3345 if i>1 else 3354)
            g.SetLineWidth(503 * (1 if i < 2 else -1))
            mg.Add(g)

        #if m==3000:
        if m == massPoints[-1]:
            gw[m] = getCurve(hw[m])
            for i, g in enumerate(gw[m]):
                g.SetPoint(0, 0., g.GetY()[0])
                g.SetLineWidth(501 * (1 if i < 2 else -1))
                g.SetLineColor(920 + 2)
                g.SetFillColor(920 + 1)
                g.SetFillStyle(3003)
                mg.Add(g)

    if options.root:
        outFile = TFile("plotsLimit/Model.root", "RECREATE")
        outFile.cd()
        for m in massPoints:
            mg[m].Write("X_M%d" % m)
        mgW.Write("width")
        outFile.Close()
        print "Saved histogram in file plotsLimit/Model.root, exiting..."
        exit()

    ### plot ###

    c1 = TCanvas("c1", "HVT Exclusion Limits", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    mg.Draw("AC")
    #mg.GetXaxis().SetTitle("g_{V} c_{H}")
    mg.GetXaxis().SetTitle("Higgs and vector boson coupling g_{H}")
    mg.GetXaxis().SetRangeUser(-3., 3.)
    mg.GetXaxis().SetLabelSize(0.045)
    mg.GetXaxis().SetTitleSize(0.045)
    mg.GetXaxis().SetTitleOffset(1.)
    #mg.GetYaxis().SetTitle("g^{2} c_{F} / g_{V}")
    mg.GetYaxis().SetTitle("Fermion coupling g_{F}")
    mg.GetYaxis().SetLabelSize(0.045)
    mg.GetYaxis().SetTitleSize(0.045)
    mg.GetYaxis().SetTitleOffset(1.)
    mg.GetYaxis().SetRangeUser(-1.2, 1.2)
    mg.GetYaxis().SetNdivisions(505)
    #    hxs[3500].Draw("CONTZ")

    drawCMS(LUMI, "Preliminary", False)
    #    drawAnalysis("XVH"+category, False)
    #    latex = TLatex()
    #    latex.SetNDC()
    #    latex.SetTextFont(62)
    #    latex.SetTextSize(0.06)
    #    latex.DrawLatex(0.10, 0.925, "CMS")

    # model B
    g_model = {}
    for i, b in enumerate(benchmark):
        g_model[i] = TGraph(1)
        g_model[i].SetTitle(models_name[b])
        g_model[i].SetPoint(0, models_point[b][0], models_point[b][1])
        g_model[i].SetMarkerStyle(models_style[b])
        g_model[i].SetMarkerColor(models_color[b])
        g_model[i].SetMarkerSize(1.5)
        g_model[i].Draw("PSAME")

    # text
    latex = TLatex()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    latex.SetTextColor(630)
    #    for b in benchmark: latex.DrawLatex(models_point[b][0]+0.02, models_point[b][1]+0.02, models_name[b])
    latex.SetTextColor(920 + 2)
    latex.DrawLatex(-2.8, -0.875,
                    "#frac{#Gamma_{Z'}}{m_{Z'}} > %.0f%%" % (width * 100, ))

    #leg = TLegend(0.68, 0.60, 0.95, 0.94)
    leg = TLegend(0.68, 0.34, 0.95, 0.66)
    leg.SetBorderSize(1)
    leg.SetFillStyle(1001)
    leg.SetFillColor(0)
    for m in massPoints:
        leg.AddEntry(gxs[m][0], "m_{Z'} = %.1f TeV" % (m / 1000.), "fl")
    for i, b in enumerate(benchmark):
        leg.AddEntry(g_model[i], g_model[i].GetTitle(), "P")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * 0.050)
    leg.SetMargin(0.35)
    leg.Draw()

    gxs_ = gxs[massPoints[0]][0].Clone("gxs_")
    gxs_.SetLineColor(1)
    #    gxs_.SetFillColor(1)

    latex.SetNDC()
    latex.SetTextColor(1)
    latex.SetTextSize(0.04)
    latex.SetTextFont(52)
    latex.DrawLatex(0.15, 0.95, "q#bar{q} #rightarrow Z' #rightarrow b#bar{b}")

    c1.Print("plots/model/HVT.png")
    c1.Print("plots/model/HVT.pdf")
    c1.Print("plots/model/HVT.root")
    c1.Print("plots/model/HVT.C")

    #g = 0.646879, cH = 0.976246, cF = 1.02433
    print "model B = [", 3 * 0.976246, ",", 0.646879 * 0.646879 * 1.02433 / 3, "]"

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")