Exemple #1
0
def fit(hhh):
    hh = hhh.Clone("h" + hhh.GetName())
    nbins = hh.GetNbinsX()
    for i in range(1, nbins):
        ### FIXME : 288 is hard-coded pedestal
        val = hh.GetBinContent(i)
        hh.SetBinContent(i, val)
        hh.SetBinError(i, 0.01 * (val + 288.))
    func = TF1("langaus", langaufun, 0, 60, 4)
    func.SetParameter(0, .5)
    func.SetParameter(1, 17)  ## most probable value
    func.SetParameter(2, 170)  ## normalization (area)
    func.SetParameter(3, 2)  ## width of gaussian
    ## the way I set up the histogram the peak is usually
    ## around bin 15-17. We get some of the pre-pulse
    ## but avoid the undershoot by cutting off pretty early
    func.SetRange(10, 27)
    hh.Fit("langaus", "R")
    peaktime = func.GetParameter(1)
    peak = func.Eval(peaktime)
    hh.Write()
    ## if you comment out these next two lines it'll probably go faster
    gPad.Modified()
    gPad.Update()
    return peak
Exemple #2
0
def plotPerLumiSection(options):
    """Save profile histograms per lumisection to PDF files"""
    name = options['name'] + '_perLS'
    f = openRootFileR(name)
    histname = plotName(options['title'] + '_perLS', timestamp=False)
    filename = plotName(options['title'] + '_perLS', timestamp=True)
    filepath = plotPath(options['title'] + '_perLS', timestamp=True)
    print '<<< Save plot:', filepath
    hist = f.Get(histname)
    canvas = TCanvas()
    canvas.SetLogy(options['logy'])
    gStyle.SetOptStat(options['optstat'])
    hist.Draw()
    gPad.Update()
    hist.GetXaxis().SetTitle('Lumisection')
    hist.GetYaxis().SetTitle(options['ytitle'])
    hist.GetYaxis().SetTitleOffset(1.2)
    for axis in [hist.GetXaxis(), hist.GetYaxis()]:
        axis.SetTitleFont(133)
        axis.SetTitleSize(16)
        axis.SetLabelFont(133)
        axis.SetLabelSize(12)
        axis.CenterTitle()
    drawSignature(filename)
    gPad.Modified()
    gPad.Update()
    #canvas.Print(filepath)
    #canvas.Close()
    #closeRootFile(f, name)
    return [canvas, hist, f]
Exemple #3
0
def SaveHisto2D(histin, tokens, data=False):
    proc = 'DY' if not data else 'DATA'
    histname = histin.GetName()
    cam = TCanvas(histname, histname, 2000, 2000)
    cam.SetTopMargin(0.1)
    cam.SetBottomMargin(0.15)
    cam.SetLeftMargin(0.215)
    cam.SetRightMargin(0.15)

    cam.cd().SetLogz()
    histin.Draw("colztextE")
    histin.SetTitle(histname)

    #needed to move the axis a bit
    z_begin = 0.875
    palette = histin.GetListOfFunctions().FindObject("palette")
    palette.SetX1NDC(z_begin)
    palette.SetX2NDC(z_begin + 0.05)
    histin.GetZaxis().SetTitle('N_SS/N_OS')
    gPad.Modified()
    gPad.Update()

    cam.SaveAs('plots/%s/Ratio_%s_%s.png' % (tokens, tokens, proc))
    cam.SaveAs('plots/%s/Ratio_%s_%s.pdf' % (tokens, tokens, proc))
    #cam.SaveAs('plots/%s/Ratio_%s_DY.C' %(histname.split('_')[-1],histname))
    return
Exemple #4
0
  def plotGraph(self, x='vv', y='acc'): 
    '''
    Plot a graph with specified quantities on x and y axes , and saves the graph
    '''

    if (x not in self.quantities.keys()) or (y not in self.quantities.keys()):
      raise RuntimeError('selected quantities not available, available quantities are: \n{}'.format(self.quantities.keys()))

    xq = self.quantities[x]
    yq = self.quantities[y]

    #graph = TGraphAsymmErrors()
    #graph = TGraph()
    graph = TGraphErrors()
    for i,s in enumerate(self.samples):
      graph.SetPoint(i,getattr(s, xq.name), getattr(s, yq.name) )
      #if xq.err: 
      #  graph.SetPointEXhigh(i, getattr(s, xq.name+'_errup'))   # errup errdn
      #  graph.SetPointEXlow (i, getattr(s, xq.name+'_errdn'))
      if yq.err: 
        graph.SetPointError(i, 0, getattr(s, yq.name+'_errup'))
      #  graph.SetPointEYhigh(i, getattr(s, yq.name+'_errup'))  
      #  graph.SetPointEYlow (i, getattr(s, yq.name+'_errdn'))

    c = TCanvas()
    graph.SetLineWidth(2)
    graph.SetMarkerStyle(22)
    graph.SetTitle(';{x};{y}'.format(y=yq.title,x=xq.title))
    graph.Draw('APLE')

    if yq.forceRange:
      graph.SetMinimum(yq.Range[0])
      graph.SetMaximum(yq.Range[1])

    gPad.Modified()
    gPad.Update()
    if yq.name=='expNevts':
      line = TLine(gPad.GetUxmin(),3,gPad.GetUxmax(),3)
      line.SetLineColor(ROOT.kBlue)
      line.Draw('same')
      #graph.SetMinimum(0.01)
      #graph.SetMaximum(1E06)

    if xq.log: c.SetLogx()
    if yq.log: c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    c.SaveAs('./plots/{}{}/{}_{}VS{}.pdf'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.C'.format(self.label,suffix,self.name,yq.name,xq.name))
    c.SaveAs('./plots/{}{}/{}_{}VS{}.png'.format(self.label,suffix,self.name,yq.name,xq.name))

    self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph
    # add the graph container for memory?
    graph_saver.append(graph)
Exemple #5
0
 def draw_data(self):
     self.mframe = self.xvar.frame()
     self.data.plotOn(self.mframe)
     self.underlying_model.plotOn(self.mframe)
     for icomp, compname in enumerate(self.pdfs):
         self.underlying_model.plotOn(self.mframe,
                                      RooFit.Components(compname),
                                      RooFit.LineColor(icomp + 1))
     self.mframe.Draw()
     gPad.Modified()
     gPad.Update()
def ReadOneFile(PairsDat, alpha, h2d):

    hist_px = TH1F("px", "; p_{x} [MeV]; Entries", 120, -20, 100)
    hist_py = TH1F("py", "; p_{y} [MeV]; Entries", 200, -10, 10)
    hist_pz = TH1F("pz", "; p_{z} [MeV]; Entries", 200, -1000, 1000)

    with open(PairsDat, "r") as fp:
        lines = fp.readlines()
        for line in lines:
            if len(line.split()) < 2:
                continue
            pdgCode = float(line.split()[1])
            sign = np.sign(pdgCode)
            e = 1  #float(line.split()[9])
            charge = -sign
            px = float(line.split()[6]) * e
            py = float(line.split()[7]) * e
            pz = float(line.split()[8]) * e
            hist_px.Fill(px * 1000)
            hist_py.Fill(py * 1000)
            hist_pz.Fill(pz * 1000)

    canvx = TCanvas("px", "px")
    hist_px.Draw()
    gPad.SetLogy()
    gPad.Update()
    gPad.Modified()

    canvy = TCanvas("py", "py")
    hist_py.Draw()
    gPad.SetLogy()
    gPad.Update()
    gPad.Modified()

    canvz = TCanvas("pz", "pz")
    hist_pz.Draw()
    gPad.SetLogy()
    gPad.Update()
    gPad.Modified()

    bla = raw_input()
def lumiVsRunHisto(histograms,
                   tree,
                   minRun=165000,
                   maxRun=168000,
                   minLum=0,
                   maxLum=3000):
    nbinsLum = maxLum - minLum
    nbinsRun = maxRun - minRun
    histograms.hlumVSrun = TH2F('hlumVSrun', ';Run number;Lumi number',
                                nbinsRun, minRun, maxRun, nbinsLum, minLum,
                                maxLum)
    tree.Draw('lumi:run>>' + histograms.hlumVSrun.GetName(), '', 'col')
    gPad.Modified()
    gPad.Update()
Exemple #8
0
def drawTH2DColMap(h, c):
    """
    Drawing a TH2D as color map requires some tweaking for a (more or less) nice result
    Most importantly the color axis has to be moved to the left for readable axis labels
    """
    from ROOT import gPad, TPaletteAxis
    c.SetRightMargin(0.175)  # make some space for color axis
    c.cd()
    h.Draw("colz")
    c.Update()  # draw first, since the TPaletteAxis won't be available else
    p = h.GetListOfFunctions().FindObject("palette")
    p.SetX1NDC(0.84)  # move to the right
    p.SetX2NDC(0.89)
    gPad.Modified()
    gPad.Update()
Exemple #9
0
def plotPerTimeStamp(options):
    """Save profile histograms per timestamp to PDF files"""
    name = options['name'] + '_' + options['scan'] + '_perTime'
    if options['extra']:
        name += '_' + options['extra']
    f = openRootFileR(options['name'] + '_perTime')
    histname = plotName(name, timestamp=False)
    filename = plotName(name, timestamp=True)
    filepath = plotPath(name, timestamp=True)
    print '<<< Save plot:', filepath
    hist = f.Get(histname)
    hist.SetErrorOption(options['error'])
    if options['big']:
        canvas = TCanvas('c', '', 8000, 1200)
    else:
        canvas = TCanvas('c', '', 1400, 500)
    canvas.SetLogy(options['logy'])
    gStyle.SetOptStat(options['optstat'])
    hist.Draw()
    gPad.Update()
    hist.GetXaxis().SetTimeDisplay(1)
    hist.GetXaxis().SetTimeFormat('#splitline{%d.%m.%y}{%H:%M:%S}%F1969-12-31' \
                                  +' 22:00:00')
    hist.GetXaxis().SetLabelOffset(0.03)
    hist.GetXaxis().SetTitle('')
    if 'xmin' in options and 'xmax' in options:
        hist.GetXaxis().SetRangeUser(options['xmin'], options['xmax'])
    hist.GetYaxis().SetTitle(options['ytitle'])
    hist.GetYaxis().SetTitleOffset(1.2)
    for axis in [hist.GetXaxis(), hist.GetYaxis()]:
        axis.SetTitleFont(133)
        axis.SetTitleSize(16)
        axis.SetLabelFont(133)
        axis.SetLabelSize(12)
        axis.CenterTitle()
        if options['big']:
            axis.SetTickLength(0.01)
    if options['big']:
        hist.GetYaxis().SetTitleOffset(0.25)
    drawSignature(filename)
    gPad.Modified()
    gPad.Update()
    if options['retrn']:
        return [canvas, hist, f]
    else:
        canvas.Print(filepath)
        canvas.Close()
        closeRootFile(f, options['name'] + '_perTime')
Exemple #10
0
 def draw(self, var, cut):
     same = ''
     hists = []
     for comp in self.comps.values():
         comp.tree.Draw(var, cut, 'histnorm'+same)
         hist = comp.tree.GetHistogram()
         hists.append(hist)
         if hasattr(comp, 'style'):
             comp.style.formatHisto(hist)
         if same == '':
             var = var.split('>>')[0]
             same = 'same'
     maxy = max(h.GetMaximum() for h in hists)
     hists[0].GetYaxis().SetRangeUser(0, maxy*1.1)
     gPad.Modified()
     gPad.Update()
def analyzeRuns(histograms):
    histo = histograms.hlumVSrun
    px = histo.ProjectionX()
    lumis = []
    for bin in range(1, histo.GetNbinsX()):
        if px.GetBinContent(bin) == 0:
            continue
        run = px.GetBinLowEdge(bin)
        histograms.runHisto = histo.ProjectionY("", bin, bin, "")
        histograms.runHisto.SetTitle('run %d' % run)
        histograms.runHisto.Draw()
        gPad.Modified()
        gPad.Update()
        tmp = lumisProcessed(histograms.runHisto, run)
        lumis.extend(tmp)
    pprint.pprint(lumis)
def drawdiff(h, opt="", useabs=True):
    hd = draw(h[0], opt=opt, copy=" Difference")
    if useabs:
        if "TH2" in h[0].ClassName():
            for i in range(0, h[0].GetNbinsX()):
                for j in range(0, h[0].GetNbinsY()):
                    hd.SetBinContent(
                        i + 1,
                        j + 1,
                        abs(
                            h[0].GetBinContent(i + 1, j + 1)
                            - h[1].GetBinContent(i + 1, j + 1)
                        ),
                    )
    else:
        hd.Add(h[1], -1)
    gPad.Modified()
    gPad.Update()
Exemple #13
0
def plotPerBxStep(options):
    """Save histograms (per BX and step) to PDF files"""
    name = options['scan'] + '_' + options['name'] + options['extra']
    if 'method' in options:
        name += '_' + options['method']
    f = openRootFileR(name)
    for bx in options['crossings']:
        for step in range(len(O['nominalPos'][options['scan']])):
            histname = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=False)
            filename = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=True)
            filepath = plotPath(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=True)
            print '<<< Save plot:', filepath
            hist = f.Get(histname)
            canvas = TCanvas()
            canvas.SetLogx(options['logx'])
            canvas.SetLogy(options['logy'])
            gStyle.SetOptStat(options['optstat'])
            gStyle.SetOptFit(options['optfit'])
            hist.Draw()
            gPad.Update()
            hist.GetXaxis().SetTitle(options['xtitle'])
            hist.GetXaxis().SetRangeUser(options['xmin'], options['xmax'])
            hist.GetYaxis().SetTitle(options['ytitle'])
            hist.GetYaxis().SetTitleOffset(1.2)
            for axis in [hist.GetXaxis(), hist.GetYaxis()]:
                axis.SetTitleFont(133)
                axis.SetTitleSize(16)
                axis.SetLabelFont(133)
                axis.SetLabelSize(12)
                axis.CenterTitle()
            stats = hist.FindObject('stats')
            stats.SetTextFont(133)
            stats.SetTextSize(16)
            drawSignature(filename)
            gPad.Modified()
            gPad.Update()
            if 'custom' in options:
                extragraphs = options['custom'](hist)
            canvas.Print(filepath)
            canvas.Close()
    closeRootFile(f, name)
def printCanvas(histogram, title):
    "to print histogram for debugging"
    can = TCanvas()
    histogram.Draw("colz")
    gStyle.SetOptStat("")
    histogram.SetTitle("")
    histogram.GetXaxis().SetTitle("pixel number")
    histogram.GetYaxis().SetTitle("pixel number")
    histogram.GetZaxis().SetTitle("measured energy in cells")
    gPad.Update()
    palette = histogram.GetListOfFunctions().FindObject("palette")
    can.SetRightMargin(0.2)
    palette.SetX1NDC(0.8)
    palette.SetX2NDC(0.815)
    palette.SetY1NDC(0.1)
    palette.SetY2NDC(0.9)
    gPad.Modified()
    gPad.Update()
    can.Print(title + ".png")
def printCanvas(histogram,title,theRange,maximum):
    can=TCanvas()
    histogram.Draw("colz")
    gStyle.SetOptStat("")
    histogram.SetTitle("")
    histogram.GetXaxis().SetTitle("pixel number")
    histogram.GetYaxis().SetTitle("pixel number")
    histogram.GetZaxis().SetTitle("measured energy in cells")
    histogram.GetXaxis().SetRangeUser(theRange[0]-20,theRange[1]+20)
    histogram.GetYaxis().SetRangeUser(theRange[2]-20,theRange[3]+20)
    histogram.GetZaxis().SetRangeUser(0,maximum)
    gPad.Update()
    palette=histogram.GetListOfFunctions().FindObject("palette")
    can.SetRightMargin(0.2)
    palette.SetX1NDC(0.8)
    palette.SetX2NDC(0.815)
    palette.SetY1NDC(0.1)
    palette.SetY2NDC(0.9)
    gPad.Modified()
    gPad.Update()
    
    print ("title",title)
    can.Print("test/"+str(title)+".png")
Exemple #16
0
def TwoFileSAME3VsLumi(F1graph1, F1graph2, F1graph3, F2graph1, F2graph2, F2graph3, title, type, DoInclusive):
    canvas = makeCMSCanvas(str(random.random()),"canvas",900,700)
    canvas.cd()
    F1graph1.SetMarkerColor(kBlack)#electrons
    F1graph2.SetMarkerColor(kBlue)#electrons
    F1graph3.SetMarkerColor(kRed)#muons
    F2graph1.SetMarkerColor(kBlack)#electrons
    F2graph2.SetMarkerColor(kBlue)#electrons
    F2graph3.SetMarkerColor(kRed)#muons
    F2graph1.SetMarkerStyle(kOpenStar)#inclusive
    F2graph2.SetMarkerStyle(kOpenStar)#electrons
    F2graph3.SetMarkerStyle(kOpenStar)#muons
    multigraph = TMultiGraph()
    if(DoInclusive or type == "ZmassBARELL" or type == "ZwidthBARELL" or type == "ZmultBARELL"):
        multigraph.Add(F1graph1,"AP")
        multigraph.Add(F2graph1,"AP")
    multigraph.Add(F1graph2,"AP")
    multigraph.Add(F1graph3,"AP")
    multigraph.Add(F2graph2,"AP")
    multigraph.Add(F2graph3,"AP")
    multigraph.Draw("AP")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetXaxis().SetLimits(0.,40.)
    multigraph.GetYaxis().SetTitleOffset(1.4)
    gPad.Modified()

    if(type == "Zmass" or type == "ZmassBARELL"):
        multigraph.SetMaximum(1.008*gPad.GetUymax())
        multigraph.GetYaxis().SetTitle("M_{l^{+}l^{-}} [GeV]")
    elif(type == "Zwidth" or type == "ZwidthBARELL"):
        multigraph.SetMaximum(1.1*gPad.GetUymax())
        multigraph.GetYaxis().SetTitle("#Gamma [GeV]")
    elif(type == "Zmult" or type == "ZmultBARELL"):
        multigraph.SetMaximum(1.2*gPad.GetUymax())
        multigraph.GetYaxis().SetTitle("#Z")
    elif(type == "SIP"):
        multigraph.GetYaxis().SetTitle("SIP")
        multigraph.SetMaximum(1.1*gPad.GetUymax())
    printLumiPrelOut(canvas)
    canvas.Update()
    down = gPad.GetUymin()
    up = gPad.GetUymax()
    MC_muMass = 90.92
    MC_eleMass = 90.63
    Data_muMass = 90.95
    Data_eleMass = 90.68
    lineB = TLine(5.57,down,5.57, up)
    lineB.SetLineColor(kBlack)
    lineB.SetLineStyle(2)
    lineB.Draw()
    lineC = TLine(8.58,down,8.58,up)
    lineC.SetLineColor(kBlack)
    lineC.SetLineStyle(2)
    lineC.Draw()
    lineD = TLine(12.9,down,12.9,up)
    lineD.SetLineColor(kBlack)
    lineD.SetLineStyle(2)
    lineD.Draw()
    lineE = TLine(16.57,down,16.57,up)
    lineE.SetLineColor(kBlack)
    lineE.SetLineStyle(2)
    lineE.Draw()
    lineF = TLine(19.7,down,19.7,up)
    lineF.SetLineColor(kBlack)
    lineF.SetLineStyle(2)
    lineF.Draw()
    lineG = TLine(26.9,down,26.9,up)
    lineG.SetLineColor(kBlack)
    lineG.SetLineStyle(2)
    lineG.Draw()
    if(type == "Zmass"):
        lineMC_ele = TLine(0.,MC_eleMass,40., MC_eleMass)
        lineMC_ele.SetLineColor(kBlue)
        lineMC_ele.SetLineStyle(1)
        lineMC_ele.Draw()
        lineMC_mu = TLine(0.,MC_muMass,40., MC_muMass)
        lineMC_mu.SetLineColor(kRed)
        lineMC_mu.SetLineStyle(1)
        lineMC_mu.Draw()
        lineData_ele = TLine(0.,Data_eleMass,40., Data_eleMass)
        lineData_ele.SetLineColor(kBlue)
        lineData_ele.SetLineStyle(2)
        lineData_ele.Draw()
        lineData_mu = TLine(0.,Data_muMass,40., Data_muMass)
        lineData_mu.SetLineColor(kRed)
        lineData_mu.SetLineStyle(2)
        lineData_mu.Draw()
    legend = TLegend(0.80,0.75,0.965,0.93)
    if(type == "Zmass" or type == "Zwidth" or type == "Zmult"):
        legend.AddEntry(F1graph2,"e^{+}e^{-}","P")
        legend.AddEntry(F1graph3,"#mu^{+}#mu^{-}","P")
        legend.AddEntry(F2graph2,"e^{+}e^{-} ICHEP","P")
        legend.AddEntry(F2graph3,"#mu^{+}#mu^{-} ICHEP","P")
    else:
        legend.AddEntry(F1graph1,"EBEB","P")
        legend.AddEntry(F2graph1,"EBEB ICHEP","P")
        legend.AddEntry(F1graph2,"EBEE","P")
        legend.AddEntry(F1graph3,"EEEE","P")
        legend.AddEntry(F2graph2,"EBEE ICHEP","P")
        legend.AddEntry(F2graph3,"EEEE ICHEP","P")
    legend.SetTextFont(32)
    legend.Draw()
    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return;
Exemple #17
0
ref_pts = array('d', [0.0, 1.0])
ref = ROOT.TGraph(2, ref_pts, ref_pts)  # draw a diagonal line for reference
ref.SetLineColor(ROOT.kBlack)
ref.SetLineWidth(1)

x = 0.35
y = 0.65
latex_ = TLatex(x, y, "")

c1 = TCanvas("c1", "c1")
c1.cd()
roc_baseline.Add(ref)

roc_baseline.Draw('ACP')
roc_baseline.SetTitle("ROC Curve for BDT Evaluation")
roc_baseline.GetXaxis().SetTitle("Signal Efficiency")
roc_baseline.GetYaxis().SetTitle("Background Efficiency")
leg_baseline.Draw("same")
latex_.Draw("same")

gPad.Modified()
roc_baseline.GetXaxis().SetLimits(0.0, 1.0)
roc_baseline.SetMinimum(0.0)
roc_baseline.SetMaximum(1.0)

c1.Update()
c1.SaveAs(dir_ + "/dist/EVERYTHING/ROC_new_vars_comp_" + str(i) + ".pdf")
c1.SaveAs(dir_ + "/dist/EVERYTHING/ROC_new_vars_comp_" + str(i) + ".png")

raw_input("<<<waiting")
Exemple #18
0
def mistagSFtopEMu(year_, ana_):
    if year_ == 2017:
        dir = "monohbb.v06.00.05.2017_NCU/withSingleTop/" + ana_ + "/"
    if year_ == 2018:
        dir = "monohbb.v06.00.05.2018_NCU/withSingleTop/" + ana_ + "/"

    print "Top Electron Region"
    print " "

    openfile1 = TFile(dir + "TopE.root")  #

    topmatchTopE = openfile1.Get("h_TopMatch")
    WmatchTopE = openfile1.Get("h_Wmatch")
    unmatchTopE = openfile1.Get("h_unmatch")
    wjetsTopE = openfile1.Get("h_sumWJets")
    dibosonTopE = openfile1.Get("h_sumDiboson")
    unsubtractedDataTopE = openfile1.Get("h_Data")

    failMCsubtractTopE = openfile1.Get("h_ttFailed")
    passMCsubtractTopE = openfile1.Get("h_ttPassed")
    subtractedDataTopE = openfile1.Get("SubtractedData")

    datafailTopE = openfile1.Get("SubtractedDataFailed")
    datapassTopE = openfile1.Get("SubtractedDataPassed")  #
    totaldataTopE = openfile1.Get("h_totaldata")
    totalMCtopE = openfile1.Get("h_tt")

    passedTopEdataBfrSubtract = openfile1.Get("h_Data_Passed")
    wjetsTopEpassed = openfile1.Get("h_sumWJetsPassed")
    dibosonTopEpassed = openfile1.Get("h_sumDibosonPassed")

    failedTopEdataBfrSubtract = openfile1.Get("h_Data_Failed")
    wjetsTopEfailed = openfile1.Get("h_sumWJetsFailed")
    dibosonTopEfailed = openfile1.Get("h_sumDibosonFailed")

    stTopE = openfile1.Get("h_sumST")
    stTopEpassed = openfile1.Get("h_sumSTPassed")
    stTopEfailed = openfile1.Get("h_sumSTFailed")

    print "Top Muon Region"
    print " "

    openfile2 = TFile(dir + "TopMu.root")  #

    topmatchTopMu = openfile2.Get("h_TopMatch")
    WmatchTopMu = openfile2.Get("h_Wmatch")
    unmatchTopMu = openfile2.Get("h_unmatch")
    wjetsTopMu = openfile2.Get("h_sumWJets")
    dibosonTopMu = openfile2.Get("h_sumDiboson")
    unsubtractedDataTopMu = openfile2.Get("h_Data")

    failMCsubtractTopMu = openfile2.Get("h_ttFailed")
    passMCsubtractTopMu = openfile2.Get("h_ttPassed")
    subtractedDataTopMu = openfile2.Get("SubtractedData")

    datafailTopMu = openfile2.Get("SubtractedDataFailed")
    datapassTopMu = openfile2.Get("SubtractedDataPassed")  #
    totaldataTopMu = openfile2.Get("h_totaldata")
    totalMCtopMu = openfile2.Get("h_tt")

    passedTopMudataBfrSubtract = openfile2.Get("h_Data_Passed")
    wjetsTopMupassed = openfile2.Get("h_sumWJetsPassed")
    dibosonTopMupassed = openfile2.Get("h_sumDibosonPassed")

    failedTopMudataBfrSubtract = openfile2.Get("h_Data_Failed")
    wjetsTopMufailed = openfile2.Get("h_sumWJetsFailed")
    dibosonTopMufailed = openfile2.Get("h_sumDibosonFailed")

    stTopMu = openfile2.Get("h_sumST")
    stTopMupassed = openfile2.Get("h_sumSTPassed")
    stTopMufailed = openfile2.Get("h_sumSTFailed")

    print "get histograms from root files: done"
    print " "

    SubtractedDataPassedTopE = datapassTopE.Clone("SubtractedDataPassedTopE")
    SubtractedDataPassedTopMu = datapassTopMu.Clone(
        "SubtractedDataPassedTopMu")

    #merge histogram"
    print "merge histograms"
    print " "

    topmatchMerge = topmatchTopE + topmatchTopMu
    WmatchMerge = WmatchTopE + WmatchTopMu
    unmatchMerge = unmatchTopE + unmatchTopMu
    wjetsMerge = wjetsTopE + wjetsTopMu
    stMerge = stTopE + stTopMu
    dibosonMerge = dibosonTopE + dibosonTopMu
    unsubtractedDataMerge = unsubtractedDataTopE + unsubtractedDataTopMu

    failMCsubtractMerge = failMCsubtractTopE.Clone("failMCsubtractMerge")
    failMCsubtractMerge = failMCsubtractMerge + failMCsubtractTopMu
    passMCsubtractMerge = passMCsubtractTopE.Clone("passMCsubtractMerge")
    passMCsubtractMerge = passMCsubtractMerge + passMCsubtractTopMu
    subtractedDataMerge = subtractedDataTopE + subtractedDataTopMu

    ttData_fraction = arr.array('d')
    ttData_error = arr.array('d')

    totaldataMerge = totaldataTopE + totaldataTopMu
    totaldata = totaldataMerge.Integral()
    totaldataMerge.Rebin(14)

    datafailMerge = datafailTopE + datafailTopMu
    faildata = datafailMerge.Integral()
    datafailMerge.Rebin(14)
    datafailMerge.Sumw2()
    datafailMerge.Divide(totaldataMerge)
    frac_ttData_fail = datafailMerge.Integral()
    ttData_fraction.append(frac_ttData_fail)
    ttData_error.append(datafailMerge.GetBinError(1))

    datapassMerge = datapassTopE + datapassTopMu
    passdata = datapassMerge.Integral()
    datapassMerge.Rebin(14)
    datapassMerge.Sumw2()
    datapassMerge.Divide(totaldataMerge)
    frac_ttData_pass = datapassMerge.Integral()
    ttData_fraction.append(frac_ttData_pass)
    ttData_error.append(datapassMerge.GetBinError(1))

    ttMC_fraction = arr.array('d')
    ttMC_error = arr.array('d')

    totalMCmerge = totalMCtopE + totalMCtopMu
    totalMCmerge.Rebin(14)

    MCfailTopE = failMCsubtractTopE.Clone("MCfailTopE")
    MCfailTopMu = failMCsubtractTopMu.Clone("MCfailTopMu")
    MCfailMerge = MCfailTopE + MCfailTopMu
    MCfailMerge.Rebin(14)
    MCfailMerge.Sumw2()
    MCfailMerge.Divide(totalMCmerge)
    frac_Failed_fin = MCfailMerge.Integral()
    ttMC_fraction.append(frac_Failed_fin)
    ttMC_error.append(MCfailMerge.GetBinError(1))

    MCpassTopE = passMCsubtractTopE.Clone("MCpassTopE")
    MCpassTopMu = passMCsubtractTopMu.Clone("MCpassTopMu")
    MCpassMerge = MCpassTopE + MCpassTopMu
    MCpassMerge.Rebin(14)
    MCpassMerge.Sumw2()
    MCpassMerge.Divide(totalMCmerge)
    frac_Passed_fin = MCpassMerge.Integral()
    ttMC_fraction.append(frac_Passed_fin)
    ttMC_error.append(MCpassMerge.GetBinError(1))

    #print "\nttMC_fraction:", ttMC_fraction
    #print "ttMC_error:", ttMC_error

    sfMerge = datapassMerge.Clone("sfMerge")
    sfMerge.Sumw2()
    sfMerge.Divide(MCpassMerge)

    stacklist = []
    stacklist.append(dibosonMerge)
    stacklist.append(stMerge)
    stacklist.append(wjetsMerge)
    stacklist.append(unmatchMerge)
    stacklist.append(WmatchMerge)
    stacklist.append(topmatchMerge)

    print "merge histograms: done"
    print " "

    print "draw histograms"
    print " "
    #----------------------- canvas 1 -----------------------#

    c1 = TCanvas("c1", "", 800, 900)  #width-height
    c1.SetTopMargin(0.4)
    c1.SetBottomMargin(0.05)
    c1.SetRightMargin(0.1)
    c1.SetLeftMargin(0.15)
    gStyle.SetOptStat(0)

    binvalues1 = []
    for i in range(14):
        binvalue = unsubtractedDataMerge.GetBinContent(i)
        binvalues1.append(binvalue)
    totalmax = max(binvalues1) + 100

    padMain = TPad("padMain", "", 0.0, 0.25, 1.0, 0.97)
    padMain.SetTopMargin(0.4)
    padMain.SetRightMargin(0.05)
    padMain.SetLeftMargin(0.17)
    padMain.SetBottomMargin(0.03)
    padMain.SetTopMargin(0.1)

    padRatio = TPad("padRatio", "", 0.0, 0.0, 1.0, 0.25)
    padRatio.SetRightMargin(0.05)
    padRatio.SetLeftMargin(0.17)
    padRatio.SetTopMargin(0.05)
    padRatio.SetBottomMargin(0.3)
    padMain.Draw()
    padRatio.Draw()

    padMain.cd()

    gPad.GetUymax()
    leg1 = myLegend(coordinate=[0.45, 0.57, 0.65, 0.6])

    unsubtractedDataMerge.SetMaximum(totalmax)
    unsubtractedDataMerge.SetLineColor(1)
    unsubtractedDataMerge.SetMarkerStyle(20)
    unsubtractedDataMerge.SetMarkerSize(1.5)
    unsubtractedDataMerge.GetXaxis().SetLabelSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitleSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitle("DDB")
    unsubtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg1.AddEntry(unsubtractedDataMerge, "Data", "lep")
    unsubtractedDataMerge.Draw("e1")

    stackhisto = myStack(colorlist_=[627, 800, 854, 813, 822, 821],
                         backgroundlist_=stacklist,
                         legendname_=[
                             "Diboson", "Single Top", "W+Jets",
                             "Top (unmtch.)", "Top (W-mtch.)", "Top (mtch.)"
                         ])
    stackhisto[0].Draw("histsame")
    unsubtractedDataMerge.Draw("e1same")
    stackhisto[1].Draw()
    leg1.Draw()

    lt = TLatex()
    lt.DrawLatexNDC(0.23, 0.85,
                    "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    if ana_ == "Inclusive":
        lt.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt.DrawLatexNDC(0.17, 0.92,
                            "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt.DrawLatexNDC(0.71, 0.92,
                        "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    padRatio.cd()

    gPad.GetUymax()

    h_totalBkg = topmatchMerge.Clone("h_totalBkg")
    h_totalBkg = h_totalBkg + WmatchMerge + unmatchMerge + wjetsMerge + dibosonMerge
    ratio = dataPredRatio(data_=unsubtractedDataMerge, totalBkg_=h_totalBkg)
    ratio.SetLineColor(1)
    ratio.SetLineWidth(3)
    ratio.SetMarkerSize(1.5)
    ratio.GetXaxis().SetLabelSize(0.13)
    ratio.GetXaxis().SetTitleOffset(1)
    ratio.GetXaxis().SetTitleSize(0.13)
    ratio.GetXaxis().SetTickLength(0.1)
    ratio.GetYaxis().SetLabelSize(0.12)
    ratio.GetYaxis().SetTitleOffset(0.5)
    ratio.GetYaxis().SetTitleSize(0.13)
    ratio.GetYaxis().SetNdivisions(405)
    ratio.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}")
    ratio.GetXaxis().SetTitle("DDB")
    ratio.Draw("e1")

    c1.SaveAs(dir + "Merge_all.pdf")  #

    #----------------------- canvas 2 -----------------------#

    c2 = myCanvas(c="c2")
    gPad.GetUymax()
    leg2 = myLegend()

    binvalues2 = []
    for i in range(14):
        binvalue = subtractedDataMerge.GetBinContent(i)
        binvalues2.append(binvalue)
    ttmax = max(binvalues2) + 50

    failMCsubtractMerge.SetMaximum(ttmax)
    failMCsubtractMerge.SetFillColor(821)
    failMCsubtractMerge.SetLineColor(821)  #922
    failMCsubtractMerge.GetXaxis().SetTitle("DDB")
    failMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(failMCsubtractMerge, "t#bar{t}", "f")

    passMCsubtractMerge.SetFillColor(622)
    passMCsubtractMerge.SetLineColor(622)
    #passMCsubtractMerge.GetXaxis().SetTitle("DDB")
    #passMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(passMCsubtractMerge, "t#bar{t} mistag", "f")

    subtractedDataMerge.SetLineColor(1)
    subtractedDataMerge.SetMarkerStyle(20)
    subtractedDataMerge.SetMarkerSize(1.5)
    #subtractedDataMerge.GetXaxis().SetTitle("DDB")
    #subtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(subtractedDataMerge, "Subtracted Data", "lep")

    failMCsubtractMerge.Draw("hist")
    passMCsubtractMerge.Draw("histsame")
    subtractedDataMerge.Draw("e1same")
    leg2.Draw()

    lt2 = TLatex()
    if ana_ == "Inclusive":
        lt2.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt2.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt2.DrawLatexNDC(0.23, 0.85,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt2.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt2.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt2.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt2.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    c2.SaveAs(dir + "Merged_subtrac.pdf")  #

    #----------------------- canvas 3 -----------------------#

    c3 = myCanvas(c="c3", size=[700, 900])

    pad1 = TPad("pad1", "", 0.01, 0.25, 0.93, 1.0)
    pad1.SetTopMargin(0.1)
    pad1.SetRightMargin(0.05)
    pad1.SetLeftMargin(0.17)
    pad1.SetBottomMargin(0.05)

    pad2 = TPad("pad2", "", 0.0, 0.0, 0.375, 0.24)
    pad2.SetTopMargin(0.0)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.0)
    pad2.SetBottomMargin(0.0)

    pad3 = TPad("pad3", "", 0.38, 0.025, 0.94, 0.25)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.45)
    pad2.SetBottomMargin(0.2)

    pad1.Draw()
    pad2.Draw()
    pad3.Draw()

    #* Pad 1 *#
    pad1.cd()
    leg3 = myLegend(coordinate=[0.65, 0.4, 0.75, 0.5])

    xaxisname = arr.array('d', [1, 2])
    zero1 = np.zeros(2)

    gPad.Modified()
    gPad.SetGridy()

    gr1 = TGraphErrors(2, xaxisname, ttMC_fraction, zero1, ttMC_error)
    gr1.SetTitle("t#bar{t}")
    gr1.SetLineColor(870)
    gr1.SetLineWidth(3)
    gr1.SetMarkerStyle(20)
    gr1.SetMarkerColor(870)
    leg3.AddEntry(gr1, "t#bar{t}", "lep")

    gr2 = TGraphErrors(2, xaxisname, ttData_fraction, zero1, ttData_error)
    gr2.SetTitle("t#bar{t} Data")
    gr2.SetLineColor(1)
    gr2.SetLineWidth(2)
    gr2.SetMarkerStyle(20)
    gr2.SetMarkerColor(1)
    leg3.AddEntry(gr2, "t#bar{t} Data", "lep")

    mg = TMultiGraph("mg", "")
    mg.Add(gr1)
    mg.Add(gr2)
    mg.GetHistogram().SetMaximum(1.5)
    mg.GetHistogram().SetMinimum(0)
    mg.GetYaxis().SetTitle("Fraction")
    mg.GetXaxis().SetLimits(0, 3)
    mg.GetXaxis().SetTickLength(0.03)
    mg.GetXaxis().SetNdivisions(103)
    mg.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Fail")
    mg.GetXaxis().ChangeLabel(1, -1, 0)
    mg.GetXaxis().ChangeLabel(-1, -1, 0)
    mg.GetXaxis().ChangeLabel(3, -1, -1, -1, -1, -1, "Pass")
    mg.Draw("AP")
    leg3.Draw()

    lt3 = TLatex()
    if ana_ == "Inclusive":
        lt3.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt3.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt3.DrawLatexNDC(0.19, 0.855,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt3.DrawLatexNDC(0.19, 0.805, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt3.DrawLatexNDC(0.19, 0.755, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt3.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt3.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")
    lt3.Draw()

    pad1.Update()

    #* Pad 2 *#
    pad2.cd()

    MCpassMerge.SetFillColor(0)
    MCpassMerge.SetLineColor(870)
    MCpassMerge.SetLineWidth(3)
    MCpassMerge.SetMarkerColor(870)
    MCpassMerge.SetMarkerStyle(20)
    MCpassMerge.GetYaxis().SetTitle("Fraction")
    MCpassMerge.GetYaxis().SetTitleSize(0.09)
    MCpassMerge.GetYaxis().SetLabelSize(0.1)
    MCpassMerge.GetYaxis().SetNdivisions(404)
    MCpassMerge.SetMaximum(0.3)
    MCpassMerge.SetMinimum(0.0)
    MCpassMerge.GetXaxis().SetTitle("")
    MCpassMerge.GetXaxis().SetLabelOffset(0.02)
    MCpassMerge.GetXaxis().SetLabelSize(0.09)
    MCpassMerge.GetXaxis().SetNdivisions(104)
    MCpassMerge.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Pass")
    MCpassMerge.GetXaxis().ChangeLabel(1, -1, 0)
    MCpassMerge.GetXaxis().ChangeLabel(-1, -1, 0)

    datapassMerge.SetFillColor(0)
    datapassMerge.SetLineColor(1)
    datapassMerge.SetLineWidth(2)
    datapassMerge.SetMarkerColor(1)
    datapassMerge.SetMarkerStyle(20)

    MCpassMerge.Draw("e1")
    datapassMerge.Draw("e1histsame")

    #* Pad 3 *#
    pad3.cd()

    SF = sfMerge.Integral()
    print "******"
    print "mistag SF:", SF

    SFfinal = round(SF, 3)
    SFtext = "SF = " + str(SFfinal)

    mistagSFmax = SF + 0.2
    mistagSFmin = SF - 0.2

    sfMerge.SetLineColor(797)
    sfMerge.SetMarkerColor(797)
    sfMerge.SetLineWidth(3)
    sfMerge.SetMaximum(mistagSFmax)
    sfMerge.SetMinimum(mistagSFmin)
    sfMerge.GetXaxis().SetTitle(" ")
    sfMerge.GetXaxis().SetLabelOffset(999)
    sfMerge.GetXaxis().SetLabelSize(0)
    sfMerge.GetXaxis().SetTickLength(0)
    sfMerge.GetYaxis().SetLabelSize(0.1)
    sfMerge.GetYaxis().SetNdivisions(404)
    sfMerge.GetYaxis().SetTitle(" ")

    sfMerge.Draw("e1hist")

    pt = TPaveText(0.21, 0.72, 0.31, 0.8, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.1)
    pt.AddText(SFtext)
    pt.Draw()

    c3.SaveAs(dir + "Merge_SF.pdf")  #

    passedBfrSubtactDataMerge = (passedTopEdataBfrSubtract +
                                 passedTopMudataBfrSubtract).Integral()
    failedBfrSubtractDataMerge = (failedTopEdataBfrSubtract +
                                  failedTopMudataBfrSubtract).Integral()

    passbackground = (wjetsTopEpassed + wjetsTopMupassed + dibosonTopEpassed +
                      dibosonTopMupassed + stTopEpassed +
                      stTopMupassed).Integral()
    failbackground = (wjetsTopEfailed + wjetsTopMufailed + dibosonTopEfailed +
                      dibosonTopMufailed + stTopEfailed +
                      stTopMufailed).Integral()
    totalbackground = (wjetsMerge + dibosonMerge + stMerge).Integral()

    #get the statistical uncertainty#

    dx = ttData_error[1]
    print "data efficiency error", dx

    dy = ttMC_error[1]
    print "MC efficiency error", dy

    x = datapassMerge.Integral()
    y = MCpassMerge.Integral()

    statUnc = TMath.Sqrt(((dx**2) / (y**2)) + ((x**2) * (dy**2) / (y**4)))
    #print "statistical Uncertainty in Top (e+muon) CR", statUnc
    #print " "
    print "relative statistical Uncertainty in Top (e+muon) CR", statUnc / SF * 100, " %"
    print " "

    print "DDB Mistag SF and stat: ", round(SF, 3), " +- ", round(statUnc,
                                                                  3), " (stat)"
    #print "theoretical statistical uncertainty of data efficiency", TMath.Sqrt((x*(1-x))/(subtractedDataMerge.Integral()))
    #print "theoretical statistical uncertainty of MC efficiency", TMath.Sqrt((y*(1-y))/(totalMCmerge.Integral()))
    #print " "

    header = ["Process", "Number of Events", "Top (e+muon)"]
    row1 = [
        " ", "DDB mistag SF",
        str(SFfinal) + " +- " + str(round(statUnc, 3)) + " (stat)"
    ]
    row2 = ["tt MC", "Pass (not normalized)", ""]
    row3 = [
        " ", "Pass (normalized)",
        str(round(passMCsubtractMerge.Integral(), 2))
    ]
    row4 = [" ", "Fail (not normalized)", ""]
    row5 = [
        " ", "Fail (normalized)",
        str(round(failMCsubtractMerge.Integral(), 2))
    ]
    row6 = [" ", "Total (not normalized)", ""]
    row7 = [" ", "Total (normalized)", str(round(totalMCmerge.Integral(), 2))]

    inforMC = [row2, row3, row4, row5, row6, row7]

    row8 = [
        "tt DATA", "Pass (before subtraction)",
        str(round(passedBfrSubtactDataMerge, 2))
    ]
    row9 = [" ", "Pass (after subtraction)", str(round(passdata, 2))]
    row10 = [
        " ", "Fail (before subtraction)",
        str(round(failedBfrSubtractDataMerge, 2))
    ]
    row11 = [" ", "Fail (after subtraction)", str(round(faildata, 2))]
    row12 = [
        " ", "Total (before subtraction)",
        str(round(unsubtractedDataMerge.Integral(), 2))
    ]
    row13 = [" ", "Total (after subtraction)", str(round(totaldata, 2))]

    inforDATA = [row8, row9, row10, row11, row12, row13]

    row14 = ["Background", "Pass (normalized)", str(round(passbackground, 2))]
    row15 = [" ", "Fail (normalized)", str(round(failbackground, 2))]
    row16 = [" ", "Total (normalized)", str(round(totalbackground, 2))]

    inforBKG = [row14, row15, row16]

    DDB_mistagSF.makeTable(header, row1, inforMC, inforDATA, inforBKG)
Exemple #19
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()
Exemple #20
0
def plotPostFitValues(channel,var,DM,year,*parameters,**kwargs):
    """Draw post-fit values for parameter using MultiDimFit and FitDiagnostics output."""
    if DM=='DM0' and 'm_2' in var: return
    print green("\n>>> plotPostFitValues %s, %s"%(DM, var))
    if len(parameters)==1 and isinstance(parameters[0],list): parameters = parameters[0]
    
    parameters  = [p.replace('$CAT',DM).replace('$CHANNEL',channel) for p in list(parameters)]
    title       = kwargs.get('title',     ""    )
    name        = kwargs.get('name',      ""    )
    indir       = kwargs.get('indir',     "output_%d"%year  )
    outdir      = kwargs.get('outdir',    "postfit_%d"%year )
    tag         = kwargs.get('tag',       ""    )
    plotlabel   = kwargs.get('plotlabel', ""    )
    compareFD   = kwargs.get('compareFD', False ) and N==1
    era         = "%d-13TeV"%year
    isBBB       = any("_bin_" in p for p in parameters)
    filename    = '%s/higgsCombine.%s_%s-%s%s-%s.MultiDimFit.mH90.root'%(indir,channel,var,DM,tag,era)
    filenamesFD = '%s/fitDiagnostics.%s_%s-%s%s-%s_TES*p*.root'%(indir,channel,var,DM,tag,era)
    ensureDirectory(outdir)
    if not name:
      name = formatParameter(parameters[0]).replace('_'+DM,'')
    if len(parameters)>1:
      name = "comparison_%s"%(name) #re.sub(r"bin_\d+","bin",name)
    canvasname = "%s/postfit-%s_%s_%s%s%s"%(outdir,name,var,DM,tag,plotlabel)
    print '>>>   file "%s"'%(filename)
    
    
    graphs      = [ ]
    graphsFD    = [ ]
    tvals       = [ ]
    pvals       = [ -2.2, +2.2 ]
    tes         = measureTES(filename)
    for parameter in parameters[:]:
      graph = getTGraphOfParameter(filename,'tes',parameter,xvals=tvals,yvals=pvals)
      if graph:
        graphs.append(graph)
      else:
        parameters.remove(parameter)
      if compareFD:
        graphFD = getTGraphOfParameter_FD(filenamesFD,parameter,xvals=tvals,yvals=pvals)
        if graphFD: graphsFD.append(graphFD)
    if len(parameters)!=len(graphs):
      warning("plotPostFitValues: len(parameters) = %d != %d = len(graphs)"%(len(parameters),len(graphs)))
      exit(1)
    N           = len(parameters)
    compareFD   = compareFD and len(graphsFD)>0
    parameters  = [formatParameter(p).replace('_'+DM,'') for p in parameters]
    graphsleg   = columnize(graphs,3)     if N>6 else columnize(graphs,2)     if N>3 else graphs # reordered for two columns
    paramsleg   = columnize(parameters,3) if N>6 else columnize(parameters,2) if N>3 else parameters # reordered for two columns
    
    xtitle  = 'tau energy scale'
    ytitle  = "%s post-fit value"%(parameters[0] if N==1 else "MultiDimFit")
    xmin, xmax = min(tvals), max(tvals)
    ymin, ymax = min(pvals), max(pvals)
    colors  = [ kBlack, kBlue, kRed, kGreen, kMagenta, kOrange, kTeal, kAzure+2, kYellow-3 ]
    
    canvas = TCanvas("canvas","canvas",100,100,800,650)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(  0.07 ); canvas.SetBottomMargin( 0.13 )
    canvas.SetLeftMargin( 0.11 ); canvas.SetRightMargin(  0.05 )
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    canvas.cd()
    
    maxmargin = 0.18*abs(ymax-ymin)
    minmargin = 0.20*abs(ymax-ymin) #(0.20 if N<5 else 0.10*ceil(N/2))
    ymin   = 0.0 if ymin>=0 else ymin-minmargin
    ymax   = ymax + minmargin
    
    textsize   = 0.045 if N==1 else 0.036
    lineheight = 0.055 if N==1 else 0.045
    x1, width  = 0.42, 0.25
    y1, height = 0.15, lineheight*(ceil(N/3.) if N>6 else ceil(N/2.) if N>3 else N)
    if title:     height += lineheight
    if compareFD: height += lineheight
    if   N>6:
      if isBBB: width = 0.62; x1 = 0.25
      else:     width = 0.70; x1 = 0.20
    elif N>3:   width = 0.52; x1 = 0.36
    legend = TLegend(x1,y1,x1+width,y1+height)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    if title:
      legend.SetTextFont(62)
      legend.SetHeader(title) 
    legend.SetTextFont(42)
    if N>6:
      legend.SetNColumns(3)
      legend.SetColumnSeparation(0.02)
    elif N>3:
      legend.SetNColumns(2)
      legend.SetColumnSeparation(0.03)
    
    frame = canvas.DrawFrame(xmin,ymin,xmax,ymax)
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetLabelSize(0.050)
    frame.GetYaxis().SetLabelSize(0.050)
    frame.GetXaxis().SetLabelOffset(0.01)
    frame.GetYaxis().SetLabelOffset(0.01)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(0.84)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    
    for i, (parameter,graph) in enumerate(zip(parameters,graphs)):
      graph.SetLineColor(colors[i%len(colors)])
      graph.SetLineWidth(2)
      graph.SetLineStyle(1)
      graph.Draw('LSAME')
    
    for parameter,graph in zip(paramsleg,graphsleg):
      if N==1:
        legend.AddEntry(graph, "MultiDimFit", 'l')
      else:
        legend.AddEntry(graph, parameter, 'l')
    
    line = TLine(tes, ymin, tes, ymax)
    #line.SetLineWidth(1)
    line.SetLineStyle(7)
    line.Draw('SAME')
    latex = TLatex()
    latex.SetTextSize(0.045)
    latex.SetTextAlign(13)
    latex.SetTextFont(42)
    latex.DrawLatex(tes+0.02*(xmax-xmin),ymax-0.04*(ymax-ymin),"tes = %.3f"%tes)
    
    if compareFD:
      graphFD.SetLineColor(kBlue)
      graphFD.SetLineWidth(2)
      graphFD.SetLineStyle(2)
      graphFD.Draw('LSAME')
      legend.AddEntry(graphFD, "FitDiagnostics", 'l')
    
    legend.Draw()
    
    CMS_lumi.relPosX = 0.12
    CMS_lumi.CMS_lumi(canvas,13,0)
    gPad.SetTicks(1,1)
    gPad.Modified()
    frame.Draw('SAMEAXIS')
    
    canvas.SaveAs(canvasname+".png")
    if args.pdf: canvas.SaveAs(canvasname+".pdf")
    canvas.Close()
Exemple #21
0
def plotCorrelation(channel,var,DM,year,*parameters,**kwargs):
    """Calculate and plot correlation between parameters."""
    if DM=='DM0' and 'm_2' in var: return
    print green("\n>>> plotCorrelation %s, %s"%(DM, var))
    if len(parameters)==1 and isinstance(parameters[0],list): parameters = parameters[0]
    parameters  = [p.replace('$CAT',DM).replace('$CHANNEL',channel) for p in list(parameters)]
    
    title       = kwargs.get('title',     ""                )
    name        = kwargs.get('name',      ""                )
    indir       = kwargs.get('indir',     "output_%d"%year  )
    outdir      = kwargs.get('outdir',    "postfit_%d"%year )
    tag         = kwargs.get('tag',       ""                )
    plotlabel   = kwargs.get('plotlabel', ""                )
    order       = kwargs.get('order',     False             )
    era         = "%d-13TeV"%year
    filename    = '%s/higgsCombine.%s_%s-%s%s-%s.MultiDimFit.mH90.root'%(indir,channel,var,DM,tag,era)
    ensureDirectory(outdir)
    print '>>>   file "%s"'%(filename)
    
    # HISTOGRAM
    parlist = getParameters(filename,parameters)
    if order:
      parlist.sort(key=lambda x: -x.sigma)
    N       = len(parlist)     
    hist    = TH2F("corr","corr",N,0,N,N,0,N)
    
    for i in xrange(N): # diagonal
      hist.SetBinContent(i+1,N-i,1.0)
      hist.GetXaxis().SetBinLabel(1+i,parlist[i].title)
      hist.GetYaxis().SetBinLabel(N-i,parlist[i].title)
    for xi, yi in combinations(range(N),2): # off-diagonal
      r = parlist[xi].corr(parlist[yi])
      hist.SetBinContent(1+xi,N-yi,r)
      hist.SetBinContent(1+yi,N-xi,r)
      #print "%20s - %20s: %5.3f"%(par1,par2,r)
      #hist.Fill(par1.title,par2.title,r)
      #hist.Fill(par2.title,par1.title,r)
    
    # SCALE
    canvasH  = 160+64*max(10,N)
    canvasW  = 300+70*max(10,N)
    scaleH   =  800./canvasH
    scaleW   = 1000./canvasW
    scaleF   = 640./(canvasH-160)
    tmargin  = 0.06
    bmargin  = 0.14
    lmargin  = 0.22
    rmargin  = 0.12
    
    canvas = TCanvas('canvas','canvas',100,100,canvasW,canvasH)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(  tmargin ); canvas.SetBottomMargin( bmargin )
    canvas.SetLeftMargin( lmargin ); canvas.SetRightMargin( rmargin )
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    canvas.cd()
    
    frame = hist
    frame.GetXaxis().SetLabelSize(0.054*scaleF)
    frame.GetYaxis().SetLabelSize(0.072*scaleF)
    frame.GetZaxis().SetLabelSize(0.034)
    frame.GetXaxis().SetLabelOffset(0.005)
    frame.GetYaxis().SetLabelOffset(0.003)
    frame.GetXaxis().SetNdivisions(508)
    #gStyle.SetPalette(kBlackBody)
    #frame.SetContour(3);
    gStyle.SetPaintTextFormat(".2f")
    frame.SetMarkerSize(1.5*scaleF)
    #frame.SetMarkerColor(kRed)
    
    hist.Draw('COLZ TEXT')
    
    # TEXT
    if title:
      latex = TLatex()
      latex.SetTextSize(0.045)
      latex.SetTextAlign(33)
      latex.SetTextFont(42)
      latex.DrawLatexNDC(0.96*lmargin,0.80*bmargin,title)
    
    CMS_lumi.relPosX = 0.14
    CMS_lumi.CMS_lumi(canvas,13,0)
    gPad.SetTicks(1,1)
    gPad.Modified()
    frame.Draw('SAMEAXIS')
    
    canvasname = "%s/postfit-correlation_%s_%s%s%s"%(outdir,var,DM,tag,plotlabel)
    canvas.SaveAs(canvasname+".png")
    if args.pdf: canvas.SaveAs(canvasname+".pdf")
    canvas.Close()
Exemple #22
0
def TwoFileSAME2VsLumi(F1graph1, F1graph2, F2graph1, F2graph2, title, type):
    canvas = makeCMSCanvas(str(random.random()),"canvas",900,700)
    canvas.cd()
    F1graph1.SetMarkerColor(kBlue)#electrons
    F1graph2.SetMarkerColor(kRed)#muons
    F2graph1.SetMarkerColor(kBlue)#electrons
    F2graph2.SetMarkerColor(kRed)#muons
    F2graph1.SetMarkerStyle(kOpenStar)
    F2graph2.SetMarkerStyle(kOpenStar)
    multigraph = TMultiGraph()
    multigraph.Add(F1graph1,"AP")
    multigraph.Add(F1graph2,"AP")
    multigraph.Add(F2graph1,"AP")
    multigraph.Add(F2graph2,"AP")
    multigraph.Draw("AP")
    multigraph.GetXaxis().SetLimits(0.,40.)
    #TGaxis.SetMaxDigits(2)
    #TGaxis.SetExponentOffset(-0.06, 0.02, "y")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetYaxis().SetTitleOffset(1.4)
    if(type == "ISO"):
        multigraph.GetYaxis().SetTitle("Isolation")
        gPad.Modified()
        multigraph.SetMinimum(0.5*gPad.GetUymin())
        multigraph.SetMaximum(1.5*gPad.GetUymax())
    elif(type == "SIP"):
        multigraph.GetYaxis().SetTitle("SIP")
    printLumiPrelOut(canvas)
    canvas.Update()
    down = gPad.GetUymin()
    up = gPad.GetUymax()
    lineB = TLine(5.57,down,5.57, up)
    lineB.SetLineColor(kBlack)
    lineB.SetLineStyle(2)
    lineB.Draw()
    lineC = TLine(8.58,down,8.58,up)
    lineC.SetLineColor(kBlack)
    lineC.SetLineStyle(2)
    lineC.Draw()
    lineD = TLine(12.9,down,12.9,up)
    lineD.SetLineColor(kBlack)
    lineD.SetLineStyle(2)
    lineD.Draw()
    lineE = TLine(16.57,down,16.57,up)
    lineE.SetLineColor(kBlack)
    lineE.SetLineStyle(2)
    lineE.Draw()
    lineF = TLine(19.7,down,19.7,up)
    lineF.SetLineColor(kBlack)
    lineF.SetLineStyle(2)
    lineF.Draw()
    lineG = TLine(26.9,down,26.9,up)
    lineG.SetLineColor(kBlack)
    lineG.SetLineStyle(2)
    lineG.Draw()
    legend = TLegend(0.80,0.75,0.965,0.93)
    legend.AddEntry(F1graph1,"e^{+}e^{-}","P")
    legend.AddEntry(F1graph2,"#mu^{+}#mu^{-}","P")
    legend.AddEntry(F2graph1,"e^{+}e^{-} ICHEP","P")
    legend.AddEntry(F2graph2,"#mu^{+}#mu^{-} ICHEP","P")
    legend.SetTextFont(32)
    legend.Draw()

    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return;
Exemple #23
0
def main():
    parser = ArgumentParser(description='Scan over ROOT files to find the '+ \
                            'lumisections belonging to a specific run.')
    parser.add_argument('-b', action='store_true', help='enable batch mode')
    parser.add_argument('--dataset', required=True, choices=['PromptReco2015', \
                        'ReRecoOct2015', 'ReRecoDec2015', 'PromptReco2016', \
                        '2015ReRecoJan2017', '2016ReRecoJan2017'], \
                        help='specify data-taking period and reconstruction')
    parser.add_argument('-n', nargs=1, default=1, type=int, help='Specify '+ \
                        'the number of ZeroBias datasets to be included')
    parser.add_argument('-run', nargs=1, required=True, type=int, \
                        help='Specify the run number for the selection of '+ \
                        'the lumisections')
    parser.add_argument('-range', nargs=2, type=int, help='Specify a range '+ \
                        'in lumisections for the histogram')
    parser.add_argument('-X', dest='coords', action='append_const', \
                        const='vtx_x', help='look for vtx_x')
    parser.add_argument('-Y', dest='coords', action='append_const', \
                        const='vtx_y', help='look for vtx_y')
    parser.add_argument('-noscan', action='store_const', const=True, \
                        default=False, help='don\'t repeat the scan of the '+ \
                        'ROOT files, just do the plotting')
    parser.add_argument('-title', nargs=1, help='Specify a title for the '+ \
                        'histogram')
    args = parser.parse_args()

    from importlib import import_module
    from lsctools import config
    from lsctools.config import options as O, EOSPATH as eos
    from lsctools.tools import openRootFileU, closeRootFile, writeFiles, \
                               plotName, plotTitle, loadFiles, plotPath, \
                               drawSignature
    from lsctools.prepare import loopOverRootFiles
    from ROOT import TChain, TObject, TProfile, TCanvas, gStyle, gPad
    getattr(config, 'PCC' + args.dataset)()
    O['fulltrees'] = O['fulltrees'][:args.n]
    run = args.run[0]
    files = []
    if args.noscan:
        files = loadFiles('fulltrees_' + str(run))
    else:

        def action(tree, filename):
            condition = 'run == ' + str(run)
            if tree.GetEntries(condition) > 0:
                files.append(filename)
                print '<<< Found file:', filename

        loopOverRootFiles(action, 'fulltrees')
        writeFiles(files, 'fulltrees_' + str(run))
    chain = TChain(O['treename']['fulltrees'])
    for filename in files:
        chain.Add(eos + filename)
    name = 'vtxPos_perLS'
    title1 = 'run' + str(run) + '_perLS'
    title2 = 'Run ' + str(run)
    if (args.title):
        title2 = args.title[0] + ' (' + title2 + ')'
    f = openRootFileU(name)
    if args.range:
        mini = args.range[0]
        maxi = args.range[1]
        title1 += '_from' + str(mini) + 'to' + str(maxi)
    else:
        print '<<< Get minimum lumisection'
        mini = int(chain.GetMinimum('LS'))
        print '<<< Get maximum lumisection'
        maxi = int(chain.GetMaximum('LS'))
    for coord in args.coords:
        print '<<< Analyze coordinate', coord
        histname = plotName(coord + '_' + title1, timestamp=False)
        histtitl = plotTitle('- ' + title2)
        histfile = plotName(coord + '_' + title1)
        histpath = plotPath(coord + '_' + title1)
        hist = TProfile(histname, histtitl, maxi - mini + 1, mini - 0.5,
                        maxi + 0.5)
        chain.Draw(coord + '*1e4:LS>>' + histname, 'run == ' + str(run),
                   'goff')
        hist.Write('', TObject.kOverwrite)
        print '<<< Save plot:', histpath
        canvas = TCanvas()
        gStyle.SetOptStat(0)
        hist.Draw()
        hist.GetXaxis().SetTitle('LS')
        hist.GetYaxis().SetTitle(coord + ' [#mum]')
        hist.GetYaxis().SetTitleOffset(1.2)
        for axis in [hist.GetXaxis(), hist.GetYaxis()]:
            axis.SetTitleFont(133)
            axis.SetTitleSize(16)
            axis.SetLabelFont(133)
            axis.SetLabelSize(12)
            axis.CenterTitle()
        drawSignature(histfile)
        gPad.Modified()
        gPad.Update()
        canvas.Print(histpath)
        canvas.Close()
    closeRootFile(f, name)
def doPlots(f, f_sim, name):
    plots = []
    cwm = plot()
    cwm.name = "chargeWeightedMean"
    cwm.lowerBoundary = 0
    cwm.upperBoundary = 90
    cwm.nBins = 180
    cwm.xAxisLabel = "Charge weighted mean"
    cwm.yAxisLabel = "Events / " + cwm.binWidth()
    #plots.append(cwm)

    hwm = plot()
    hwm.name = "hitWeightedMean"
    hwm.lowerBoundary = 0
    hwm.upperBoundary = 90
    hwm.nBins = 180
    hwm.xAxisLabel = "Hit weighted mean"
    hwm.yAxisLabel = "Events / " + hwm.binWidth()
    #plots.append(hwm)

    sc = plot()
    sc.name = "sumCharge"
    sc.lowerBoundary = 0
    sc.upperBoundary = 80
    sc.nBins = 80
    sc.xAxisLabel = "Cluster charge"
    sc.yAxisLabel = "Events / " + sc.binWidth()
    plots.append(sc)

    mc = plot()
    mc.name = "maxCharge"
    mc.lowerBoundary = 0
    mc.upperBoundary = 40
    mc.nBins = 40
    mc.xAxisLabel = "Seed charge"
    mc.yAxisLabel = "Events / " + mc.binWidth()
    plots.append(mc)

    cs = plot()
    cs.name = "clusterSize"
    cs.lowerBoundary = 0
    cs.upperBoundary = 10
    cs.nBins = 10
    cs.xAxisLabel = "Cluster Size"
    cs.yAxisLabel = "Events / " + cs.binWidth()
    plots.append(cs)

    can = TCanvas()
    #can.SaveAs("clusterPlots_Pos" + cfg.position + ".pdf[")
    can.SaveAs(name + ".pdf[")
    for p in plots:
        hist = TH1D(p.name, p.name, p.nBins, p.lowerBoundary, p.upperBoundary)
        hist_sim = TH1D(p.name + "_sim", p.name + "_sim", p.nBins,
                        p.lowerBoundary, p.upperBoundary)
        #if p.name=="sumCharge":
        #	reweightHist(hist_sim, 1.2)

        #distance_from_track = 0 +/- 400

        t.Draw(p.name + ">>" + p.name,
               "distance_from_track<300&&distance_from_track>-300", "")
        t_sim.Draw(p.name + ">>" + p.name + "_sim")

        hist.GetXaxis().SetTitle(p.xAxisLabel)
        hist.GetYaxis().SetTitle(p.yAxisLabel)
        hist.SetStats(True)

        hist_sim.GetXaxis().SetTitle(p.xAxisLabel)
        hist_sim.GetYaxis().SetTitle(p.yAxisLabel)
        hist_sim.SetStats(True)

        hist_sim.SetMarkerColor(kRed)
        hist_sim.SetLineColor(kRed)
        hist_sim.SetMarkerStyle(kOpenCircle)

        hist.SetName("Data")
        hist_sim.SetName("Simulation")

        hist.Draw("e")
        can.Update()
        statbox = hist.GetListOfFunctions().FindObject('stats')

        #"""Moves the statbox to a new location.  Uses the NDC coordinates where the canvas is 1 wide and tall, (0,0) is the bottom left."""

        if not p.name == "sumCharge":
            statbox.SetY1NDC(0.4)
            statbox.SetY2NDC(0.6)
        else:
            statbox.SetX1NDC(0.5)
            statbox.SetX2NDC(0.7)

        hist_sim.Draw("e")
        can.Update()
        statbox_sim = hist_sim.GetListOfFunctions().FindObject('stats')
        statbox_sim.SetTextColor(kRed)

        #if hist.GetMaximum() > hist_sim.GetMaximum():
        if hist.GetMaximum() / hist.GetEntries() > hist_sim.GetMaximum(
        ) / hist_sim.GetEntries():
            hist.DrawNormalized("e")
            gPad.Modified()
            hist_sim.DrawNormalized("esames")
        else:
            hist_sim.DrawNormalized("e")
            gPad.Modified()
            hist.DrawNormalized("esames")

        #hist.Draw("esames")
        #can.SaveAs("clusterPlots_Pos" + cfg.position + ".pdf")
        can.SaveAs(name + ".pdf")

    #hist = f.Get("clusterShape")
    #hist_sim = f_sim.Get("clusterShape")
    #
    #hist.GetXaxis().SetRangeUser(0, 10)
    #hist_sim.GetXaxis().SetRangeUser(0, 10)
    #
    #hist.GetYaxis().SetRangeUser(0, 50)
    #hist_sim.GetYaxis().SetRangeUser(0, 50)
    #
    #hist.GetXaxis().SetTitle("Channel relative to seed")
    #hist.GetYaxis().SetTitle("Adc response")
    #hist.SetName("Data")
    #hist.SetStats(True)
    #
    #hist_sim.GetXaxis().SetTitle("Channel relative to seed")
    #hist_sim.GetYaxis().SetTitle("Adc response")
    #hist_sim.SetName("Simulation")
    #hist_sim.SetStats(True)
    #
    #hist_sim.SetMarkerColor(kRed)
    #hist_sim.SetLineColor(kRed)
    #hist_sim.SetMarkerStyle(kOpenCircle)
    #
    #
    #
    #hist.Draw("e")
    #can.Update()
    #statbox = hist.GetListOfFunctions().FindObject('stats')
    ##statbox.SetLabel("Data")
    ##hist_sim.Draw("e")
    ##statbox_sim = hist_sim.GetListOfFunctions().FindObject('stats')
    ##statbox_sim.SetName("Simulation")
    #
    #statbox.SetX1NDC(0.2)
    #statbox.SetX2NDC(0.4)
    ##statbox.SetY1NDC(y1)
    ##statbox.SetY2NDC(y2)
    #
    #hist_sim.Draw("e")
    #can.Update()
    #statbox_sim = hist_sim.GetListOfFunctions().FindObject('stats')
    #statbox_sim.SetTextColor(kRed)
    #
    #
    #
    #
    #if hist.GetMaximum() > hist_sim.GetMaximum():
    #	hist.Draw("e")
    #	gPad.Modified()
    #	hist_sim.Draw("esames")
    #else:
    #	hist_sim.Draw("e")
    #	gPad.Modified()
    #	hist.Draw("esames")
    #
    #
    #
    #
    #can.SaveAs("clusterPlots_Pos" + cfg.position + ".pdf")
    can.SaveAs(name + ".pdf]")
Exemple #25
0
def plotUpperLimits(labels, masses, **kwargs):
    print color("plotUpperLimits()", color="magenta", prepend=">>>\n>>> ")
    # https://raw.githubusercontent.com/nucleosynthesis/HiggsAnalysis-CombinedLimit/combine_tutorial_SWAN/combine_tutorials_2016/combine_intro/plotPvalue.py

    # SIGNAL strength & mass
    extralabel = kwargs.get('extralabel', "")

    # LOOP over LABELS
    for label in labels:
        print color("plotUpperLimits - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        N = len(masses)
        yellow = TGraph(2 * N)  # yellow band
        green = TGraph(2 * N)  # green band
        median = TGraph(N)  # median line

        up2s = []
        down2s = []
        for i, mass in enumerate(masses):
            filename = getOutputFilename(label, mass, extralabel=extralabel)
            limits = getLimits(filename)
            yellow.SetPoint(i, mass, limits[4])  # + 2 sigma
            green.SetPoint(i, mass, limits[3])  # + 1 sigma
            median.SetPoint(i, mass, limits[2])  # median
            green.SetPoint(2 * N - 1 - i, mass, limits[1])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, mass, limits[0])  # - 2 sigma
            down2s.append(limits[0])
            up2s.append(limits[4])

        ymax = max(up2s) * 1.20
        ymin = min(down2s)
        doLog = ymin and ymax / min(down2s) > 4
        xtitle = "m_{X} [GeV]"
        ytitle = "95% upper limit on #sigma#timesBR(X #rightarrow #tau#tau) [pb]"
        if "bbA" in extralabel:
            xtitle = "m_{A} [GeV]"
            ytitle = "95% upper limit on #sigma#timesBR(A #rightarrow #tau#tau) [pb]"

        W, H = 800, 600
        T, B = 0.08 * H, 0.12 * H
        L, R = 0.12 * W, 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.cd()
        if doLog:
            ymin = 0.1  #10**(floor(log(ymin,10))-1)
            ymax = 1000  #10**(ceil(log(ymax,10))+1)
            #ymin, ymax = 0.1, 1000
            canvas.SetLogy()
        else:
            ymin *= 0 if ymin > 0 else 1.20

        frame = canvas.DrawFrame(min(masses), ymin, max(masses), ymax)
        frame.GetYaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetLabelSize(0.044)
        frame.GetYaxis().SetLabelSize(0.044)
        frame.GetXaxis().SetLabelOffset(0.010)
        frame.GetXaxis().SetTitleOffset(1.04)
        frame.GetYaxis().SetTitleOffset(1.08)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitle(ytitle)
        frame.GetXaxis().SetTitle(xtitle)

        yellow.SetFillColor(kOrange)
        yellow.SetLineColor(kOrange)
        yellow.SetFillStyle(1001)
        yellow.Draw('F')

        green.SetFillColor(kGreen + 1)
        green.SetLineColor(kGreen + 1)
        green.SetFillStyle(1001)
        green.Draw('Fsame')

        median.SetLineColor(1)
        median.SetLineWidth(2)
        median.SetLineStyle(2)
        median.Draw('Lsame')

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame.Draw('sameaxis')

        width = 0.28
        height = 0.20
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.80
        x1 = x2 - width  # Right
        x2 = x1 + width

        y1 = 0.68
        y2 = y1 + height
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.040)
        legend.SetTextFont(62)
        legend.SetHeader("%s" % (label_dict[label + extralabel]))
        legend.SetTextFont(42)
        legend.AddEntry(median, "Asymptotic CL_{s} expected", 'L')
        legend.AddEntry(green, "#pm 1 std. deviation", 'f')
        #legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f')
        legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
        #legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f')
        legend.Draw()

        print " "
        canvas.SaveAs("%s/upperLimit-%s%s.png" %
                      (PLOTS_DIR, label, extralabel))
        canvas.SaveAs("%s/upperLimit-%s%s%s.pdf" %
                      (PLOTS_DIR, label, extralabel))
        canvas.Close()
Exemple #26
0
def overlap(outdir, file1, file2 = 0):

  file_1 = TFile(file1, "r")
  # file_2 = TFile(file2, "r")

  h_name = ["h_mass_sum_reco_jet_cone", "h_mass_pair_reco_jet_cone1", "h_mass_pair_reco_jet_cone2", "h_mass_true_reco_jet_cone"]

  for h in h_name:
    h_good = h + "_good"
    h_bad = h + "_wrong"

    cname = "c_"+ h + "good_bad_jet_association"
    canvas_name = TCanvas(cname, "c_", 800, 600)
    canvas_name.cd()

    file_1.cd()
    h_1 = gDirectory.Get(h_good)
    # h_reco1 = gDirectory.Get(h_reco)

    # file_2.cd()
    h_2 = gDirectory.Get(h_bad)
    # h_reco2 = gDirectory.Get(h_reco)

    h_1.SetLineColor(4)
    # h_reco1.SetLineColor(2)

    h_2.SetLineColor(2)
    # h_reco2.SetLineColor(6)

    # if (h == "h_beta_"):
    #     h_reco2.Draw("HIST E")
    #     h_gen2.Draw("HIST E SAMES")
    # else :
        # h_gen2.Draw("HIST E")
        # h_reco2.Draw("HIST E SAMES")

    h_1.Draw("HIST E")
    h_2.Draw("HIST E SAMES")


    # # # h_reclu.GetYaxis().SetRangeUser(0, 0.21)
    # # h_reclu.GetXaxis().SetRangeUser(-20, 20)
    # # h_reclu.GetXaxis().SetTitle("M_{comp} - M_{true} [GeV]")
    # # # fit_1.Draw("SAMES")
    # # # fit_2.Draw("SAMES")
    # # # if file3: 
    # # h_3.Draw("HIST E sames")
    # # # fit_3.Draw("SAMES")

    gPad.Update()
    stat_2 = h_2.GetListOfFunctions().FindObject("stats")
    # stat_2.SetOptStat(0000)
    stat_2.SetX1NDC(0.75)
    stat_2.SetX2NDC(0.9)
    stat_2.SetY1NDC(0.6)
    stat_2.SetY2NDC(0.75)
    stat_2.SetTextColor(2)
    stat_2.SetBorderSize(2)
    # stat_2.SetTitle("162.3 GeV Fit")
    gPad.Modified()
    gPad.Update()
    stat_1 = h_1.GetListOfFunctions().FindObject("stats")
    stat_1.SetX1NDC(0.75)
    stat_1.SetX2NDC(0.9)
    stat_1.SetY1NDC(0.45)
    stat_1.SetY2NDC(0.6)
    stat_1.SetTextColor(4)
    stat_1.SetBorderSize(4)
    # stat_1.SetTitle("240 GeV Fit")
    gPad.Modified()
    gPad.Update()
    # # stat_3 = h_3.GetListOfFunctions().FindObject("stats")
    # # stat_3.SetX1NDC(0.75)
    # # stat_3.SetX2NDC(0.9)
    # # stat_3.SetY1NDC(0.30)
    # # stat_3.SetY2NDC(0.45)
    # # #stat_3.SetTitle("240 GeV Fit")
    # # gPad.Modified()
    # # gPad.Update()

    mylegend = TLegend(0.15, 0.7, 0.4, 0.85)
    mylegend.SetFillColor(0)
    mylegend.SetBorderSize(2)
    mylegend.SetTextSize(0.02)
    mylegend.AddEntry(h_1, "good jets pairing", "l")
    mylegend.AddEntry(h_2, "wrong jets pairing", "l")
    # mylegend.AddEntry(h_gen2, "gen jets without cuts (curr.)", "l")
    # mylegend.AddEntry(h_reco2, "reco jets without cuts (curr.)", "l")
    mylegend.Draw()

    # # l = TLatex()
    # # l.SetTextSize(0.04)
    # # l.SetTextColor(16)
    # # l.DrawLatex(-18, 1500, "Preliminary results")
    # # l.DrawLatex(-18, 1900, "Without Detector")
    # # canvas_name.Update()

    raw_input("hit a key to exit")

    # write into the output file and close the file
    outfilename = "{}.root".format(outdir)
    outfile = TFile(outfilename, "UPDATE")
    canvas_name.Write("", TObject.kOverwrite)
    outfile.Write()
    outfile.Close()
Exemple #27
0
def compareUpperLimits(labels, masses, filelabels, **kwargs):
    print color("compareUpperLimits()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    extralabel = kwargs.get('extralabel', "")
    plotlabel = kwargs.get('plotlabel', "")

    # LOOP over LABELS
    for label in labels:
        print color("plotUpperLimits - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        ymax = -99999
        ymin = 99999
        medians = []

        for filelabel, title in filelabels:
            N = len(masses)
            median = TGraph(N)  # median line
            median.SetTitle(title)
            medians.append(median)
            for i, mass in enumerate(masses):
                filename = getOutputFilename(label, mass, extralabel=filelabel)
                limits = getLimits(filename)
                median.SetPoint(i, mass, limits[2])  # median
                if limits[2] > ymax: ymax = limits[2]
                if limits[2] < ymin: ymin = limits[2]

        median0 = medians[0]
        doLog = ymin and ymax / ymin > 6
        ymax = ymax * 1.40
        xtitle = "m_{X} [GeV]"
        ytitle = "95% upper limit on #sigma#timesBR(X #rightarrow #tau#tau) [pb]"
        if "bbA" in filelabels[0][0]:
            xtitle = "m_{A} [GeV]"
            ytitle = "95% upper limit on #sigma#timesBR(A #rightarrow #tau#tau) [pb]"

        W, H = 800, 800
        T, B = 0.10 * H, 0.16 * H
        L, R = 0.12 * W, 0.04 * W

        # MAIN plot
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.Divide(2)
        canvas.cd(1)
        gPad.SetPad("pad1", "pad1", 0, 0.37, 1, 1, 0, -1, 0)
        gPad.SetTopMargin(T / H)
        gPad.SetBottomMargin(0.01)
        gPad.SetLeftMargin(L / W)
        gPad.SetRightMargin(R / W)
        gPad.SetTickx(0)
        gPad.SetTicky(0)
        gPad.SetGrid()
        if doLog:
            ymin = 10**(floor(log(ymin, 10)))
            ymax = 10**(ceil(log(ymax, 10)))
            gPad.SetLogy()
        else:
            ymin *= 0 if ymin > 0 else 1.20

        width = 0.25
        height = 0.05 + len(medians) * 0.05
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.70
        x1 = x2 - width  # Right
        x2 = x1 + width
        y1 = 0.86
        y2 = y1 - height
        legend = TLegend(x1, y1, x2, y2)

        frame = gPad.DrawFrame(min(masses), ymin, max(masses), ymax)
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetTitleSize(0.058)
        frame.GetXaxis().SetLabelSize(0.050 * 0)
        frame.GetYaxis().SetLabelSize(0.053)
        frame.GetXaxis().SetLabelOffset(0.012)
        frame.GetXaxis().SetTitleOffset(1.02)
        frame.GetYaxis().SetTitleOffset(1.08)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitle(ytitle)
        frame.GetXaxis().SetTitle(xtitle)

        option = 'L'
        for i, median in enumerate(medians):
            median.SetLineColor(colors[i % len(colors)])
            median.SetLineStyle(styles[i % len(styles)])
            median.SetLineWidth(2 if styles[i % len(styles)] != kDotted else 3)
            median.Draw('L')
            legend.AddEntry(median, median.GetTitle(), 'L')
            if i == 0: option += ' SAME'

        CMS_lumi.CMS_lumi(gPad, 13, 0)
        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame.Draw('sameaxis')

        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(62)
        legend.SetHeader("%s" % (label_dict[label + extralabel]))
        legend.SetTextFont(42)
        legend.Draw()

        # RATIO plot
        canvas.cd(2)
        gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.36, 0, -1, 0)
        gPad.SetTopMargin(0.05)
        gPad.SetBottomMargin(0.24)
        gPad.SetLeftMargin(L / W)
        gPad.SetRightMargin(R / W)

        frame_ratio = gPad.DrawFrame(min(masses), 0.36, max(masses), 1.20)
        frame_ratio.GetYaxis().CenterTitle()
        frame_ratio.GetYaxis().SetTitleSize(0.055 * 1.79)
        frame_ratio.GetXaxis().SetTitleSize(0.058 * 1.79)
        frame_ratio.GetXaxis().SetLabelSize(0.052 * 1.79)
        frame_ratio.GetYaxis().SetLabelSize(0.050 * 1.79)
        frame_ratio.GetXaxis().SetLabelOffset(0.012)
        frame_ratio.GetXaxis().SetTitleOffset(1.00)
        frame_ratio.GetYaxis().SetTitleOffset(0.63)
        frame_ratio.GetXaxis().SetNdivisions(508)
        frame_ratio.GetYaxis().CenterTitle(True)
        frame_ratio.GetYaxis().SetTitle("ratio")
        frame_ratio.GetXaxis().SetTitle(xtitle)
        frame_ratio.GetYaxis().SetNdivisions(5)

        option = 'L'
        ratios = []
        for i, median in enumerate(medians):
            ratio = makeRatioTGraphs(median, median0)
            ratio.SetLineColor(median.GetLineColor())
            ratio.SetLineStyle(median.GetLineStyle())
            ratio.SetLineWidth(median.GetLineWidth())
            ratio.Draw('L')
            ratios.append(ratio)
            if i == 1: option += ' SAME'

        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame_ratio.Draw('sameaxis')

        print " "
        canvas.SaveAs("%s/upperLimit-%s%s_compare.png" %
                      (PLOTS_DIR, label, plotlabel))
        canvas.SaveAs("%s/upperLimit-%s%s_compare.pdf" %
                      (PLOTS_DIR, label, plotlabel))
        canvas.Close()
Exemple #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()
Exemple #29
0
def SAME2VsLumi(g1, g2,title, ptype, dataPeriod):
    canvas = makeCMSCanvas(str(random.random()),"canvas",900,700)
    canvas.cd()
    graph1=copy.deepcopy(g1)
    graph2=copy.deepcopy(g2)
    graph1.SetMarkerColor(kBlue)#electrons
    graph2.SetMarkerColor(kRed)#muons
    multigraph = TMultiGraph()
    multigraph.Add(graph1,"AP")
    multigraph.Add(graph2,"AP")
    multigraph.Draw("AP")
    TGaxis.SetMaxDigits(2)
    TGaxis.SetExponentOffset(-0.06, 0.02, "y")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetYaxis().SetTitleOffset(1.4)
    if(ptype == "ISO"):
        multigraph.GetYaxis().SetTitle("Isolation")
        gPad.Modified()
        multigraph.SetMinimum(0.5*gPad.GetUymin())
        multigraph.SetMaximum(1.5*gPad.GetUymax())
    elif(ptype == "SIP"):
        multigraph.GetYaxis().SetTitle("SIP")
        multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),1.))
        multigraph.SetMaximum(max(multigraph.GetHistogram().GetMinimum(),2.2))

        min(multigraph.GetHistogram().GetMinimum(),1.)
    printLumiPrelOut(canvas)

    
    # Draw legend 
    legend = TLegend(0.93,0.84,0.99,0.93)
    legend.AddEntry(graph1,"e^{+}e^{-}","P")
    legend.AddEntry(graph2,"#mu^{+}#mu^{-}","P")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()
    canvas.Update()

    

    # Draw letters for data-taking periods
    if(dataPeriod == "data2017"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray+1)
        textLetters.SetTextSize(0.03)
        if(ptype == "ISO"):
            textLetters.DrawLatex(2.,  0.8*gPad.GetUymax(),"B")
            textLetters.DrawLatex(9.5, 0.8*gPad.GetUymax(),"C")
            textLetters.DrawLatex(16., 0.8*gPad.GetUymax(),"D")
            textLetters.DrawLatex(23., 0.8*gPad.GetUymax(),"E")
            textLetters.DrawLatex(36., 0.8*gPad.GetUymax(),"F")
        elif(ptype == "SIP"):
            textLetters.DrawLatex(2.,  1.5,"B")    
            textLetters.DrawLatex(9.5, 1.5,"C")
            textLetters.DrawLatex(16., 1.5,"D")
            textLetters.DrawLatex(23., 1.5,"E")
            textLetters.DrawLatex(36., 1.5,"F")

    if(dataPeriod == "data2018"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray+1)
        textLetters.SetTextSize(0.03)
        if(ptype == "ISO"):
            textLetters.DrawLatex(6.,   0.8*gPad.GetUymax(), "A")
            textLetters.DrawLatex(16.,  0.8*gPad.GetUymax(), "B")
            textLetters.DrawLatex(23.,  0.8*gPad.GetUymax(), "C")
            textLetters.DrawLatex(43.,  0.8*gPad.GetUymax(), "D")
        elif(ptype == "SIP"):
            textLetters.DrawLatex(6.,  1.5, "A")    
            textLetters.DrawLatex(16., 1.5, "B")
            textLetters.DrawLatex(23., 1.5, "C")
            textLetters.DrawLatex(43., 1.5, "D")
         


    # ****
    if(dataPeriod == "data2018"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineA = TLine(13.48, down, 13.48, up) # Run2018A up to 13.48 fb-1
        lineA.SetLineColor(kBlack)
        lineA.SetLineStyle(2)
        lineA.Draw()
        
        lineB = TLine(20.265, down, 20.265, up) # Run2018B up to 20.265 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(26.877, down, 26.877, up) # Run2018C up to 26.877 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()
        
    # ****
    if(dataPeriod == "data2017"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineB = TLine(4.793, down, 4.793, up) # Run2017B up to 4.793 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(14.549, down, 14.549, up) # Run2017C up to 14.549 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()
        
        lineD = TLine(18.868, down, 18.868, up) # Run2017D up to 18.868 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()
        
        lineE = TLine(28.293, down, 28.293, up) # Run2017E up to 28.293 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()
    
    # ****
    if(dataPeriod == "data2016"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineB = TLine(5.789, down, 5.789, up) # Run2016B up to 5.789 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(8.366, down, 8.366, up) # Run2016C up to 8.366 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw() 
        
        lineD = TLine(12.616, down, 12.616, up) # Run2016D up to 12.616 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()    
        
        lineE = TLine(16.624, down, 16.624, up) # Run2016E up to 16.624 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()    
        
        lineF = TLine(19.725, down, 19.725, up) # Run2016F up to 19.725 fb-1
        lineF.SetLineColor(kBlack)
        lineF.SetLineStyle(2)
        lineF.Draw()    
        
        lineG = TLine(27.268, down, 27.268, up) # Run2016G up to 27.268 fb-1
        lineG.SetLineColor(kBlack)
        lineG.SetLineStyle(2)
        lineG.Draw()       
    # ****
    

    canvas.SaveAs(title + ".root")
    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return;
Exemple #30
0
def plot_results(caldac, no_mpa_light, x1, y1, c1, backup):
    savestr = str(caldac)
    col = 1
    xvec = np.array(x1, dtype='uint16')
    xdacval = 0.
    thdacvv = []
    yarrv = []
    xdvals = []
    linearr = []
    stackarr = []
    fitfuncarr = []
    fitparameterarray = []
    for i in range(0, no_mpa_light):
        if (backup.GetDirectory("MPA_" + str(i))):
            backup.cd("MPA_" + str(i))
        else:
            backup.mkdir("MPA_" + str(i))
            backup.cd("MPA_" + str(i))
        calibconfxmlroot = calibconfsxmlroot[i]
        xdvals.append(0.)
        c1.cd(i + 1)
        thdacv = []
        yarr = np.array(y1[i])
        linearr.append([])
        gr1 = []
        lines = []
        fitfuncarr.append([])
        fitfuncs = []
        fitparameterarray.append([])
        fitparams = []
        yarrv.append(yarr)
        stackarr.append(
            THStack('a', 'pixel curves;DAC Value (1.456 mV);Counts (1/1.456)'))
        for iy1 in range(0, len(yarr[0, :])):
            yvec = yarr[:, iy1]
            # if max(yvec)==0:
            # print "zero"
            gr1.append(
                TH1I(str(iy1), ';DAC Value (1.456 mV);Counts (1/1.456)',
                     len(x1), 0, x1[-1]))
            gr1[iy1].Sumw2(ROOT.kFALSE)
            for j in np.nditer(xvec):
                gr1[iy1].SetBinContent(gr1[iy1].FindBin(j),
                                       (np.array(yvec, dtype='int')[j]))
            gr1[iy1].Sumw2(ROOT.kTRUE)
            color = iy1 % 9 + 1
            gr1[iy1].SetLineColor(color)
            gr1[iy1].SetMarkerColor(color)
            gr1[iy1].SetFillColor(color)
            gr1[iy1].SetLineStyle(1)
            gr1[iy1].SetLineWidth(1)
            gr1[iy1].SetFillStyle(1)
            gr1[iy1].SetMarkerStyle(1)
            gr1[iy1].SetMarkerSize(.5)
            gr1[iy1].SetMarkerStyle(20)
            fitfuncs.append(TF1('gaus', 'gaus', 0, 256))
            fitfuncs[iy1].SetNpx(256)
            fitfuncs[iy1].SetParameters(gr1[iy1].GetMaximum(),
                                        gr1[iy1].GetMean(), gr1[iy1].GetRMS())
            cloned = gr1[iy1].Clone()
            cloned.SetDirectory(0)
            fitparams.append([])
            mean = 0
            if gr1[iy1].GetMaximum() < -1:
                gr1[iy1].Fit(fitfuncs[iy1], 'rq +rob=0.95', '', 0, 256)
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParameter(2))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(0))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(1))
                fitparams[iy1].append(fitfuncs[iy1].GetParError(2))
                if (fitfuncs[iy1].GetNDF() > 0):
                    fitparams[iy1].append(fitfuncs[iy1].GetChisquare() /
                                          fitfuncs[iy1].GetNDF())
                else:
                    fitparams[iy1].append(0)
                mean = fitfuncs[iy1].GetParameter(1)
            else:
                for kk in range(0, 7):
                    fitparams[iy1].append(0)
            fitparameterarray[i].append(fitparams[iy1])
            fitfuncarr[i].append(fitfuncs[iy1])
            stackarr[i].Add(cloned)
            if iy1 == (len(yarr[0, :]) - 1):
                stackarr[i].Draw('nostack hist e1 x0')
                # for fitfuncs1 in fitfuncarr[i]:
                # 	fitfuncs1.Draw("same")
                # for lines1 in linearr[i]:
                # 	lines1.Draw("same")
                if (stackarr[i].GetMaximum() > 1):
                    Maximum = TMath.Power(
                        10, (round(TMath.Log10(stackarr[i].GetMaximum())) - 1))
                    stackarr[i].SetMinimum(.1)
                    stackarr[i].SetMaximum(Maximum)
                    # gPad.SetLogy()
                gPad.Modified()
                gPad.Update()
            gr1[iy1].SetLineColor(1)
            gr1[iy1].SetMarkerColor(1)
            gr1[iy1].SetFillColor(1)
            gr1[iy1].Write(str(iy1) + 'CAL' + savestr)
            # fitfuncs[iy1].Write(str(iy1)+savestr+'fit')
        # print thdacv
    backup.cd()
    if (backup.GetDirectory("Canvas")):
        backup.cd("Canvas")
    else:
        backup.mkdir("Canvas")
        backup.cd("Canvas")
    c1.Write('CALDAC_' + savestr)
    c1.Clear('D')
    return 0