コード例 #1
0
def TGraph(x, y, yError=None, xError=None, **kwargs):

    __parseDrawOptions(kwargs)

    import sys
    #TODO: Need to check the types
    try:
        assert (len(x) == len(y))
    except AssertionError:
        print "Oops! Data points x and y aren't of the same size!"
        sys.exit()

    nPoints = len(x)

    from array import array
    if xError is None: xError = __zeros(nPoints)
    if yError is None: yError = __zeros(nPoints)

    from ROOT import TGraphErrors
    graph = TGraphErrors(nPoints, array('d', x), array('d', y),
                         array('d', xError), array('d', yError))
    graph.SetTitle(__drawOptions['title'])
    graph.SetMarkerStyle(__drawOptions['mstyle'])
    graph.SetMarkerSize(__drawOptions['msize'])
    graph.SetMarkerColor(__drawOptions['mcolour'])
    graph.SetFillStyle(0)
    graph.SetFillColor(0)
    return graph
コード例 #2
0
ファイル: Sigma_Calc.py プロジェクト: valsdav/ECAL_Weights_MC
def Sigma_Calc(g,i_,x,y,xe,ye,percentage):
    #print'Creating TGraph with new uncertainty band'
    # sigma factor. What to multiply uncertainties by, assuming current uncertainties are 1 sigma. 
    #print'percentage/100. = ',percentage/100.
    sf = TMath.ErfInverse(percentage/100.)*TMath.Sqrt(2) # sigma value for desired percentage events contained in distribution 
    #print"sf = ",sf

    #for i in range(i_ - 1):
    #print'i_ = ',i_
    for i in range(i_):
        ye[i] = ye[i]*sf # multiply 1 sigma uncertainties by new sigma value. 

    #print sf,'sig errors = ',ye   

    #ng = TGraphErrors(i_ - 1, x, y, xe, ye)
    ng = TGraphErrors(i_, x, y, xe, ye)

    if percentage == 90: j = 2
    if percentage == 99.5: j = 4

    ng.SetMarkerStyle(g.GetMarkerStyle())
    ng.SetLineStyle(g.GetLineStyle())
    #ng.SetMarkerColor(g.GetMarkerColor() + j)
    #ng.SetLineColor(g.GetLineColor() + j)
    ng.SetFillColor(g.GetFillColor() + j)
    #ng.SetName(g.GetName())

    ng.SetFillStyle(g.GetFillStyle())

    return ng
コード例 #3
0
def makePlot1D(filepath, foutname, plottitle='', masstitle=''):
    br = 1 if 'Resonant' in plottitle else 0.68
    limits = parseLimitFiles2D(filepath, br)

    xaxis = []
    xseclist = []
    xsecerr = []
    cent = []
    obs = []
    up1 = []
    up2 = []
    down1 = []
    down2 = []
    maxval = 0
    minval = 999
    for m in sorted(limits):
        l = limits[m]
        xaxis.append(m)
        xseclist.append(l.xsec)
        xsecerr.append(l.xsec * .2)
        cent.append(l.cent)
        up1.append(l.up1 - l.cent)
        up2.append(l.up2 - l.cent)
        down1.append(l.cent - l.down1)
        down2.append(l.cent - l.down2)
        obs.append(l.obs)
        maxval = max(maxval, l.up2)
        minval = min(minval, l.down2)

    N = len(xaxis)

    up1Sigma = array('f', up1)
    up2Sigma = array('f', up2)
    down1Sigma = array('f', down1)
    down2Sigma = array('f', down2)
    cent = array('f', cent)
    obs = array('f', obs)
    xarray = array('f', xaxis)
    xsecarray = array('f', xseclist)
    xsecerrarray = array('f', xsecerr)
    zeros = array('f', [0 for i in xrange(N)])

    graphXsec = TGraphErrors(N, xarray, xsecarray, zeros, xsecerrarray)

    graphCent = TGraph(N, xarray, cent)
    graphObs = TGraph(N, xarray, obs)
    graph1Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down1Sigma,
                                    up1Sigma)
    graph2Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down2Sigma,
                                    up2Sigma)

    c = TCanvas('c', 'c', 700, 600)
    c.SetLogy()
    c.SetLeftMargin(.15)

    graph2Sigma.GetXaxis().SetTitle(masstitle + ' [GeV]')
    graph2Sigma.GetYaxis().SetTitle(
        '95% C.L. upper limit [#sigma/#sigma_{theory}]')
    c2 = root.kOrange
    c1 = root.kGreen + 1
    graph2Sigma.SetLineColor(c2)
    graph1Sigma.SetLineColor(c1)
    graph2Sigma.SetFillColor(c2)
    graph1Sigma.SetFillColor(c1)
    graph2Sigma.SetMinimum(0.5 * minval)
    graph2Sigma.SetMaximum(10 * maxval)
    graphCent.SetLineWidth(2)
    graphCent.SetLineStyle(2)
    graphObs.SetLineColor(1)
    graphObs.SetLineWidth(3)
    graphObs.SetMarkerStyle(20)
    graphObs.SetMarkerSize(1)
    graphObs.SetMarkerColor(1)
    graph1Sigma.SetLineStyle(0)
    graph2Sigma.SetLineStyle(0)

    leg = TLegend(0.55, 0.7, 0.9, 0.9)
    leg.AddEntry(graphCent, 'Expected', 'L')
    if not BLIND:
        leg.AddEntry(graphObs, 'Observed', 'Lp')
    leg.AddEntry(graph1Sigma, '1 std. dev.', 'F')
    leg.AddEntry(graph2Sigma, '2 std. dev.', 'F')
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    graph2Sigma.Draw('A3')
    graph1Sigma.Draw('3 same')
    graphCent.Draw('same L')
    if not BLIND:
        graphObs.Draw('same Lp')

    subscript = 'SR' if 'Resonant' in plottitle else 'FC'
    coupling = '0.1' if 'Resonant' in plottitle else '0.25'

    graphXsec.SetLineColor(2)
    graphXsec.SetLineWidth(2)
    graphXsec.SetLineStyle(2)
    graphXsec.SetFillColor(2)
    graphXsec.SetFillStyle(3005)
    graphXsec.Draw('same L3')
    '''
  if not scale:
    if 'Resonant' in plottitle:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l')
    else:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l')
  '''
    if not BLIND:
        findIntersect1D(graphObs, graphXsec, xaxis[0], xaxis[-1])
    findIntersect1D(graphCent, graphXsec, xaxis[0], xaxis[-1])

    leg.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.8 * c.GetTopMargin())
    label.SetTextFont(62)
    label.SetTextAlign(11)
    label.DrawLatex(0.15, 0.94, "CMS")
    label.SetTextFont(52)
    label.SetTextSize(0.6 * c.GetTopMargin())
    #  label.DrawLatex(0.25,0.94,"Preliminary")
    label.SetTextFont(42)
    label.SetTextSize(0.7 * c.GetTopMargin())
    label.DrawLatex(0.19, 0.83, plottitle)
    if 'Resonant' in plottitle:
        label.DrawLatex(0.19, 0.75, "a_{SR} = b_{SR} = %s" % coupling)
        label.DrawLatex(0.19, 0.68, "m_{#chi}=100 GeV")
    else:
        label.DrawLatex(0.19, 0.75, "g_{DM}^{V}=1,g_{q}^{V}=0.25")
        label.DrawLatex(0.19, 0.68, "m_{#chi}=1 GeV")
    label.SetTextSize(0.6 * c.GetTopMargin())
    label.SetTextFont(42)
    label.SetTextAlign(31)  # align right
    label.DrawLatex(0.95, 0.94, "%.1f fb^{-1} (13 TeV)" % (plotConfig.lumi))

    c.SaveAs(foutname + '.pdf')
    c.SaveAs(foutname + '.png')
コード例 #4
0
leg.SetHeader("Single object rates")
leg.AddEntry(jetRatePlot, "Jets", "l")
leg.AddEntry(jetToMETRatePlot, "MET", "l")
leg.AddEntry(jetToElectronRatePlot, "Electrons", "l")
leg.AddEntry(jetToMuonRatePlot, "Muons", "l")

## Removing stat info
#jetRatePlot.SetStats(False)
#jetToMuonRatePlot.SetStats(False)
#jetToElectronRatePlot.SetStats(False)
## jetToPhotonRatePlot.SetStats(False)
#jetToMETRatePlot.SetStats(False)

# Plotting stuff
ratePlot.Add(jetRatePlot, "A3L")
jetRatePlot.SetFillStyle(1001)
jetRatePlot.SetLineWidth(2)
jetRatePlot.SetLineStyle(1)
ratePlot.Add(jetToMuonRatePlot, "A3")
jetToMuonRatePlot.SetFillStyle(1001)
jetToMuonRatePlot.SetLineWidth(2)
jetToMuonRatePlot.SetLineStyle(1)
ratePlot.Add(jetToElectronRatePlot, "A3")
jetToElectronRatePlot.SetFillStyle(1001)
jetToElectronRatePlot.SetLineWidth(2)
jetToElectronRatePlot.SetLineStyle(1)
# ratePlot.Add(jetToPhotonRatePlot, "A3")
# jetToPhotonRatePlot.SetFillStyle(1001)
# jetToPhotonRatePlot.SetLineWidth(2)
# jetToPhotonRatePlot.SetLineStyle(1)
ratePlot.Add(jetToMETRatePlot, "A3")
コード例 #5
0
yy = []
yyer = []
for i in range(0, hmctotqcd.GetNbinsX() + 2):
    yy.append(float(hmctotqcd.GetBinContent(i)))
    yyer.append(float(hmctotqcd.GetBinError(i)))
    xx.append(float(hmctotqcd.GetBinCenter(i)))
    xxer.append(float(hmctotqcd.GetBinWidth(i) / 2))

x_ = array("d", xx)
xer = array("d", xxer)
y_ = array("d", yy)
yer = array("d", yyer)
gr = TGraphErrors(len(x_), x_, y_, xer, yer)
gr.SetFillColor(ROOT.kBlack)
#gr.SetFillStyle(3144);
gr.SetFillStyle(3244)
gr.Draw("same,2")

c.Print("m3Hist.png")

h_background_m3Hist = h_wjets_m3HistS.Clone("h_background_m3Hist")
#h_background_m3Hist.Add(h_wjets_m3Hist)
h_background_m3Hist.Add(h_singletop_t_m3HistS)
h_background_m3Hist.Add(h_zjets_m3HistS)

rttbar = n_ttbar / (n_ttbar + n_background)  #+n_qcd)

x = RooRealVar("x", "x",
               h_zjets_m3Hist.GetXaxis().GetXmin(),
               h_zjets_m3Hist.GetXaxis().GetXmax())
k2 = RooRealVar("k2", "normalization factor", 1.0, 0.5, 1.5)
コード例 #6
0
def studyVqqResolution(rootFile):

    #get all from file
    histos = {}
    inF = TFile.Open(rootFile)
    keys = inF.GetListOfKeys()
    for k in keys:
        obj = inF.Get(k.GetName())
        obj.SetDirectory(0)
        histos[k.GetName()] = obj
    inF.Close()

    #plot
    gROOT.SetBatch()
    gROOT.SetStyle('Plain')
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(1111)
    gStyle.SetOptTitle(0)
    gStyle.SetStatFont(42)

    kin = ['', '30to40', '40to50', '50to75', '75to100', '100toInf']
    for k in kin:
        c = TCanvas('c', 'c', 600, 600)
        c.cd()
        c.SetCanvasSize(1000, 500)
        c.SetWindowSize(1000, 500)
        c.Divide(2, 1)
        c.cd(1)
        histos['deta' + k + 'barrel'].SetLineWidth(2)
        histos['deta' + k + 'barrel'].SetTitle('barrel')
        histos['deta' + k + 'barrel'].Draw('hist')
        histos['deta' + k + 'endcap'].SetLineWidth(2)
        histos['deta' + k + 'endcap'].SetLineStyle(7)
        histos['deta' + k + 'endcap'].SetTitle('endcap')
        histos['deta' + k + 'endcap'].Draw('histsame')
        leg = TLegend(0.6, 0.92, 0.9, 0.98)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextFont(42)
        leg.AddEntry(histos['deta' + k + 'barrel'], 'barrel', 'f')
        leg.AddEntry(histos['deta' + k + 'endcap'], 'endcap', 'f')
        leg.SetNColumns(2)
        leg.Draw()
        drawHeader()
        c.cd(2)
        histos['dphi' + k + 'barrel'].SetLineWidth(2)
        histos['dphi' + k + 'barrel'].SetTitle('barrel')
        histos['dphi' + k + 'barrel'].Draw('hist')
        histos['dphi' + k + 'endcap'].SetLineWidth(2)
        histos['dphi' + k + 'endcap'].SetLineStyle(7)
        histos['dphi' + k + 'endcap'].SetTitle('endcap')
        histos['dphi' + k + 'endcap'].Draw('histsame')
        c.Modified()
        c.Update()
        c.SaveAs('dr_%s.png' % k)

    labels = []
    responseVars = ['dpt', 'den', 'dphi', 'deta', 'dr']
    for r in responseVars:
        barrelResponse = TGraphErrors()
        barrelResponse.SetName(r + 'barrelresponse')
        barrelResponse.SetLineWidth(2)
        barrelResponse.SetFillStyle(0)
        barrelResponse.SetMarkerStyle(20)
        barrelCoreResponse = barrelResponse.Clone(r + 'barrelcoreresponse')
        endcapResponse = TGraphErrors()
        endcapResponse.SetName(r + 'endcapresponse')
        endcapResponse.SetLineWidth(2)
        endcapResponse.SetFillStyle(0)
        endcapResponse.SetMarkerStyle(24)
        endcapCoreResponse = endcapResponse.Clone(r + 'endcapresponse')
        for k in kin:
            c.cd()
            c.Clear()
            c.SetWindowSize(1000, 500)
            c.Divide(2, 1)
            for i in [1, 2]:
                c.cd(i)
                reg = 'barrel'
                if i == 2: reg = 'endcap'

                h = histos[r + k + reg]
                x = RooRealVar("x",
                               h.GetXaxis().GetTitle(),
                               h.GetXaxis().GetXmin(),
                               h.GetXaxis().GetXmax())
                data = RooDataHist("data", "dataset with x", RooArgList(x), h)
                frame = x.frame()
                RooAbsData.plotOn(data, frame,
                                  RooFit.DataError(RooAbsData.SumW2))

                mean1 = RooRealVar("mean1", "mean1", 0, -0.5, 0.5)
                sigma1 = RooRealVar("sigma1", "sigma1", 0.1, 0.01, 1.0)
                gauss1 = RooGaussian("g1", "g", x, mean1, sigma1)

                if r == 'dpt' or r == 'den':
                    mean2 = RooRealVar("mean2", "mean2", 0, -0.5, 0.5)
                    sigma2 = RooRealVar("sigma2", "sigma2", 0.1, 0.01, 1.0)
                    alphacb = RooRealVar("alphacb", "alphacb", 1, 0.1, 3)
                    ncb = RooRealVar("ncb", "ncb", 4, 1, 100)
                    gauss2 = RooCBShape("cb2", "cb", x, mean2, sigma2, alphacb,
                                        ncb)
                else:
                    mean1.setRange(0, 0.5)
                    mean2 = RooRealVar("mean2", "mean", 0, 0, 1)
                    sigma2 = RooRealVar("sigma2", "sigma", 0.1, 0.01, 1.0)
                    gauss2 = RooGaussian("g2", "g", x, mean2, sigma2)

                frac = RooRealVar("frac", "fraction", 0.9, 0.0, 1.0)
                if data.sumEntries() < 100:
                    frac.setVal(1.0)
                    frac.setConstant(True)
                model = RooAddPdf("sum", "g1+g2", RooArgList(gauss1, gauss2),
                                  RooArgList(frac))

                status = model.fitTo(data, RooFit.Save()).status()
                if status != 0: continue

                model_cdf = model.createCdf(RooArgSet(x))
                cl = 0.90
                ul = 0.5 * (1.0 + cl)
                closestToCL = 1.0
                closestToUL = -1
                closestToMedianCL = 1.0
                closestToMedian = -1
                for ibin in xrange(1, h.GetXaxis().GetNbins() * 10):
                    xval = h.GetXaxis().GetXmin() + (
                        ibin - 1) * h.GetXaxis().GetBinWidth(ibin) / 10.
                    x.setVal(xval)
                    cdfValToCL = math.fabs(model_cdf.getVal() - ul)
                    if cdfValToCL < closestToCL:
                        closestToCL = cdfValToCL
                        closestToUL = xval
                    cdfValToCL = math.fabs(model_cdf.getVal() - 0.5)
                    if cdfValToCL < closestToMedianCL:
                        closestToMedianCL = cdfValToCL
                        closestToMedian = xval

                RooAbsPdf.plotOn(model, frame)
                frame.Draw()

                if i == 1: drawHeader()
                labels.append(TPaveText(0.6, 0.92, 0.9, 0.98, 'brNDC'))
                ilab = len(labels) - 1
                labels[ilab].SetName(r + k + 'txt')
                labels[ilab].SetBorderSize(0)
                labels[ilab].SetFillStyle(0)
                labels[ilab].SetTextFont(42)
                labels[ilab].SetTextAlign(12)
                kinReg = k.replace('to', '-')
                kinReg = kinReg.replace('Inf', '#infty')
                labels[ilab].AddText('[' + reg + '] ' + kinReg)
                labels[ilab].Draw()

                resolutionVal = math.fabs(closestToUL - closestToMedian)
                responseGr = barrelResponse
                responseCoreGr = barrelCoreResponse
                coreResolutionVal = sigma1.getVal()
                coreResolutionErr = sigma1.getError()
                if frac.getVal() < 0.7 and (sigma2.getVal() < sigma1.getVal()):
                    coreResolutionVal = sigma2.getVal()
                    coreResolutionErr = sigma2.getError()

                if i == 2:
                    responseGr = endcapResponse
                    responseCoreGr = endcapCoreResponse
                if k != '':
                    nrespPts = responseGr.GetN()
                    kinAvg = 150
                    kinWidth = 50
                    if k == '30to40':
                        kinAvg = 35
                        kinWidth = 5
                    if k == '40to50':
                        kinAvg = 45
                        kinWidth = 5
                    if k == '50to75':
                        kinAvg = 62.5
                        kinWidth = 12.5
                    elif k == '75to100':
                        kinAvg = 87.5
                        kinWidth = 12.5
                    responseGr.SetPoint(nrespPts, kinAvg, resolutionVal)
                    responseCoreGr.SetPoint(nrespPts, kinAvg,
                                            coreResolutionVal)
                    responseCoreGr.SetPointError(nrespPts, kinWidth,
                                                 coreResolutionErr)

                labels.append(TPaveText(0.15, 0.7, 0.4, 0.9, 'brNDC'))
                ilab = len(labels) - 1
                labels[ilab].SetName(r + k + 'fitrestxt')
                labels[ilab].SetBorderSize(0)
                labels[ilab].SetFillStyle(0)
                labels[ilab].SetTextFont(42)
                labels[ilab].SetTextAlign(12)
                labels[ilab].AddText('Gaussian #1 (f=%3.3f)' % frac.getVal())
                labels[ilab].AddText('#mu=%3.3f#pm%3.3f' %
                                     (mean1.getVal(), mean1.getError()))
                labels[ilab].AddText('#sigma=%3.3f#pm%3.3f' %
                                     (sigma1.getVal(), sigma1.getError()))
                labels[ilab].AddText('Gaussian #2 (f=%3.3f)' %
                                     (1 - frac.getVal()))
                labels[ilab].AddText('#mu=%3.3f#pm%3.3f' %
                                     (mean2.getVal(), mean2.getError()))
                labels[ilab].AddText('#sigma=%3.3f#pm%3.3f' %
                                     (sigma2.getVal(), sigma2.getError()))

                labels[ilab].Draw()

            c.Modified()
            c.Update()
            c.SaveAs(r + 'res_' + k + '.png')

        frame = TGraphErrors()
        frame.SetPoint(0, 0, 0)
        frame.SetPoint(1, 200, 0.3)
        frame.SetMarkerStyle(1)
        frame.SetFillStyle(0)
        frame.SetName('frame')
        cresp = TCanvas('cresp', 'cresp', 500, 500)
        cresp.cd()
        frame.Draw('ap')
        barrelResponse.Draw('pl')
        endcapResponse.Draw('pl')
        frame.GetXaxis().SetTitle("Quark transverse momentum [GeV]")
        frame.GetYaxis().SetTitle("Resolution %3.2f C.L." % cl)
        frame.GetYaxis().SetTitleOffset(1.4)
        frame.GetYaxis().SetNdivisions(10)
        drawHeader()
        leg = TLegend(0.6, 0.92, 0.9, 0.98)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextFont(42)
        leg.AddEntry(barrelResponse, 'barrel', 'fp')
        leg.AddEntry(endcapResponse, 'endcap', 'fp')
        leg.SetNColumns(2)
        leg.Draw()
        cresp.Modified()
        cresp.Update()
        cresp.SaveAs(r + 'res_evol.png')

        frameCore = frame.Clone('framecore')
        cresp.Clear()
        frameCore.Draw('ap')
        barrelCoreResponse.Draw('pl')
        endcapCoreResponse.Draw('pl')
        frameCore.GetXaxis().SetTitle("Quark transverse momentum [GeV]")
        frameCore.GetYaxis().SetTitle("Core resolution")
        frameCore.GetYaxis().SetTitleOffset(1.4)
        frameCore.GetYaxis().SetNdivisions(10)
        frameCore.GetYaxis().SetRangeUser(0, 0.2)
        drawHeader()
        leg = TLegend(0.6, 0.92, 0.9, 0.98)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextFont(42)
        leg.AddEntry(barrelCoreResponse, 'barrel', 'fp')
        leg.AddEntry(endcapCoreResponse, 'endcap', 'fp')
        leg.SetNColumns(2)
        leg.Draw()
        cresp.Modified()
        cresp.Update()
        cresp.SaveAs(r + 'rescore_evol.png')

    bosons = ['h', 'z', 'w']
    kin = ['', '50', '100']
    region = ['', 'bb', 'eb', 'ee']
    for k in kin:
        for r in region:

            c = TCanvas('c', 'c', 600, 600)
            c.cd()
            histos['mjj' + k + r].Rebin()
            histos['mjj' + k + r].Draw()
            ic = 1
            leg = TLegend(0.6, 0.92, 0.9, 0.98)
            leg.SetFillStyle(0)
            leg.SetBorderSize(0)
            leg.SetTextFont(42)
            leg.AddEntry(histos['mjj' + k + r], 'inclusive', 'f')
            for b in bosons:
                if histos[b + 'mjj' + k + r].Integral() <= 0: continue
                ic = ic + 1
                histos[b + 'mjj' + k + r].Rebin()
                histos[b + 'mjj' + k + r].SetLineColor(ic)
                histos[b + 'mjj' + k + r].SetLineWidth(2)
                histos[b + 'mjj' + k + r].SetMarkerColor(ic)
                histos[b + 'mjj' + k + r].SetMarkerStyle(1)
                histos[b + 'mjj' + k + r].SetFillStyle(3000 + ic)
                histos[b + 'mjj' + k + r].SetFillColor(ic)
                histos[b + 'mjj' + k + r].Draw('histsame')
                leg.AddEntry(histos[b + 'mjj' + k + r], b, "f")
            leg.SetNColumns(ic)
            leg.Draw()
            drawHeader()
            labels.append(TPaveText(0.65, 0.8, 0.9, 0.9, 'brNDC'))
            ilab = len(labels) - 1
            labels[ilab].SetName(k + r + 'mjj')
            labels[ilab].SetBorderSize(0)
            labels[ilab].SetFillStyle(0)
            labels[ilab].SetTextFont(42)
            labels[ilab].SetTextAlign(12)
            regionTitle = "inclusive"
            if r == 'bb': regionTitle = 'barrel-barrel'
            if r == 'eb': regionTitle = 'endcap-barrel'
            if r == 'ee': regionTitle = 'endcap-endcap'
            labels[ilab].AddText(regionTitle)
            ptthreshold = 30
            if k != '': ptthreshold = float(k)
            labels[ilab].AddText('p_{T}>%3.0f GeV' % ptthreshold)
            labels[ilab].Draw()

            c.Modified()
            c.Update()
            c.SaveAs('mjj' + k + r + '.png')

    massResolutionGrs = []
    for r in region:
        massResolution = TGraphErrors()
        massResolution.SetName(r + 'dm')
        massResolution.SetLineWidth(2)
        massResolution.SetFillStyle(0)
        massResolution.SetMarkerStyle(20 + len(massResolutionGrs))
        massResolution.SetMarkerColor(1 + len(massResolutionGrs))
        massResolution.SetLineColor(1 + len(massResolutionGrs))
        massResolution.SetFillColor(1 + len(massResolutionGrs))
        massResolutionGrs.append(massResolution)

        for k in kin:

            c = TCanvas('c', 'c', 600, 600)
            c.cd()
            h = histos['dmjj' + k + r]
            x = RooRealVar("x",
                           h.GetXaxis().GetTitle(),
                           h.GetXaxis().GetXmin(),
                           h.GetXaxis().GetXmax())
            data = RooDataHist("data", "dataset with x", RooArgList(x), h)
            frame = x.frame()
            RooAbsData.plotOn(data, frame, RooFit.DataError(RooAbsData.SumW2))

            mean1 = RooRealVar("mean1", "mean1", 0, -0.5, 0.5)
            sigma1 = RooRealVar("sigma1", "sigma1", 0.1, 0.01, 1.0)
            gauss1 = RooGaussian("g1", "g", x, mean1, sigma1)
            mean2 = RooRealVar("mean2", "mean2", 0, -0.5, 0.5)
            sigma2 = RooRealVar("sigma2", "sigma2", 0.1, 0.01, 1.0)
            alphacb = RooRealVar("alphacb", "alphacb", 1, 0.1, 3)
            ncb = RooRealVar("ncb", "ncb", 4, 1, 100)
            gauss2 = RooCBShape("cb2", "cb", x, mean2, sigma2, alphacb, ncb)
            frac = RooRealVar("frac", "fraction", 0.9, 0.0, 1.0)
            model = RooAddPdf("sum", "g1+g2", RooArgList(gauss1, gauss2),
                              RooArgList(frac))
            status = model.fitTo(data, RooFit.Save()).status()
            if status != 0: continue
            RooAbsPdf.plotOn(model, frame)
            frame.Draw()

            labels.append(TPaveText(0.6, 0.65, 0.85, 0.9, 'brNDC'))
            ilab = len(labels) - 1
            labels[ilab].SetName(r + k + 'dmfitrestxt')
            labels[ilab].SetBorderSize(0)
            labels[ilab].SetFillStyle(0)
            labels[ilab].SetTextFont(42)
            labels[ilab].SetTextAlign(12)
            labels[ilab].AddText('Gaussian #1 (f=%3.3f)' % frac.getVal())
            labels[ilab].AddText('#mu=%3.3f#pm%3.3f' %
                                 (mean1.getVal(), mean1.getError()))
            labels[ilab].AddText('#sigma=%3.3f#pm%3.3f' %
                                 (sigma1.getVal(), sigma1.getError()))
            labels[ilab].AddText('Gaussian #2 (f=%3.3f)' % (1 - frac.getVal()))
            labels[ilab].AddText('#mu=%3.3f#pm%3.3f' %
                                 (mean2.getVal(), mean2.getError()))
            labels[ilab].AddText('#sigma=%3.3f#pm%3.3f' %
                                 (sigma2.getVal(), sigma2.getError()))
            labels[ilab].Draw()

            drawHeader()
            labels.append(TPaveText(0.15, 0.8, 0.4, 0.9, 'brNDC'))
            ilab = len(labels) - 1
            labels[ilab].SetName(k + r + 'dmjj')
            labels[ilab].SetBorderSize(0)
            labels[ilab].SetFillStyle(0)
            labels[ilab].SetTextFont(42)
            labels[ilab].SetTextAlign(12)
            regionTitle = "inclusive"
            if r == 'bb': regionTitle = 'barrel-barrel'
            if r == 'eb': regionTitle = 'endcap-barrel'
            if r == 'ee': regionTitle = 'endcap-endcap'
            labels[ilab].AddText(regionTitle)
            ptthreshold = 30
            if k != '': ptthreshold = float(k)
            labels[ilab].AddText('p_{T}>%3.0f GeV' % ptthreshold)
            labels[ilab].Draw()

            c.Modified()
            c.Update()
            c.SaveAs('dmjj' + k + r + '.png')

            massResolution.SetTitle(regionTitle)
            ip = massResolution.GetN()
            x = 40
            xerr = 10
            if k == '50':
                x = 75
                xerr = 25
            elif k == '100':
                x = 150
                xerr = 50
            y = sigma1.getVal()
            yerr = sigma1.getError()
            if frac.getVal() < 0.8:
                if sigma2.getVal() < sigma1.getVal():
                    y = sigma2.getVal()
                    ey = sigma2.getError()
            massResolution.SetPoint(ip, x, y)
            massResolution.SetPointError(ip, xerr, yerr)

    frame = TGraphErrors()
    frame.SetPoint(0, 0, 0)
    frame.SetPoint(1, 200, 0.2)
    frame.SetMarkerStyle(1)
    frame.SetFillStyle(0)
    frame.SetName('dmframe')
    cdmevol = TCanvas('cdmevol', 'cdmevol', 500, 500)
    cdmevol.cd()
    frame.Draw('ap')
    leg = TLegend(0.6, 0.92, 0.9, 0.98)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    for dmGr in massResolutionGrs:
        dmGr.Draw('pl')
        leg.AddEntry(dmGr, dmGr.GetTitle(), 'fp')
    frame.GetXaxis().SetTitle("Leading quark transverse momentum [GeV]")
    frame.GetYaxis().SetTitle("Core resolution")
    frame.GetYaxis().SetTitleOffset(1.4)
    frame.GetYaxis().SetNdivisions(10)
    drawHeader()
    leg.SetNColumns(2)
    leg.Draw()
    cdmevol.Modified()
    cdmevol.Update()
    cdmevol.SaveAs('dm_evol.png')

    c = TCanvas('c', 'c', 600, 600)
    c.cd()
    histos['sel'].Draw('histtext')
    drawHeader()
    c.Modified()
    c.Update()
    c.SaveAs('selection.png')

    return
コード例 #7
0
def crossSectionRatioPlot(group,groups,keys_no_comb,
                          sigmas,stats,systs,lumis,tots):
    delChars = '#\\/+.~${}><,?[]|&^_!@%*()-`;:\'\"'
    sigmas_lcl = array('d',sigmas[:])
    stats_lcl  = array('d',stats[:])
    systs_lcl  = array('d',systs[:])
    tots_lcl   = array('d',tots[:])
    lumis_lcl  = array('d',lumis[:])
    tots_theory = array('d')
    
    if 'combined' in groups[group]:
        sig, sta, sys, tot = getCSInfo(groups[group]['combined'])
        sigmas_lcl.insert(0,sig)
        stats_lcl.insert(0,sta)
        systs_lcl.insert(0,sys)
        tots_lcl.insert(0,tot)
        lumis_lcl.insert(0,sig*lumi_err/100.0)
    
    for i in range(len(sigmas_lcl)):
        tots_lcl[i] = tots_lcl[i]/sigmas_lcl[i]
        sigmas_lcl[i] = sigmas_lcl[i]/mc_info['sigma']        
        tots_theory.append(hypot(tots_lcl[i],
                                 mc_info['theory_err']/mc_info['sigma']))
    
    yvals   = array('d',[i*2 for i in range(1,len(sigmas_lcl)+1)])    
    xones   = array('d',[1 for i in range(len(sigmas_lcl))])
    x1serrs = array('d',[lumi_err/100.0 for i in range(len(sigmas_lcl))])
    yerrs   = array('d',[0 for i in range(len(sigmas_lcl))])
    y1serrs = array('d',[2 for i in range(len(sigmas_lcl))])

    gStats = TGraphErrors(len(sigmas_lcl),sigmas_lcl,yvals,tots_lcl,yerrs)
    gTotes = TGraphErrors(len(sigmas_lcl),sigmas_lcl,yvals,tots_theory,yerrs)
    gLine  = TGraphErrors(len(sigmas_lcl),xones,yvals,x1serrs,y1serrs)

    lOne = TLine(1,0,1,2*(len(sigmas_lcl)+1))    
    
    canv = TCanvas(group+'val','',500,500)
    canv.cd()
    frame = canv.DrawFrame(0.1,0,2,2*(len(sigmas_lcl)+1))
    frame.GetXaxis().SetTitle("Ratio (CMS/Theory)")
    unshitify(frame)
    gLine.SetFillColor(6)
    gLine.SetFillStyle(3004)
    gLine.Draw("E2")
    lOne.SetLineWidth(2)
    lOne.SetLineColor(6)
    lOne.Draw()
    gTotes.SetMarkerColor(2)
    gTotes.SetMarkerStyle(20)
    gTotes.SetLineColor(4)
    gTotes.SetLineWidth(2)
    gTotes.Draw("PE1")
    gStats.SetMarkerColor(2)
    gStats.SetMarkerStyle(20)
    gStats.SetLineColor(1)
    gStats.SetLineWidth(2)
    gStats.Draw("PE1")    

    tex1 = TLatex()
    tex1.SetTextSize(0.04)
    tex2 = TLatex()
    tex2.SetTextSize(0.03)    
    xmin = 0.1
    xmax = 2.0
    xscale = xmax - xmin
    xpad = xmin + xscale*xpadfactor

    ymin = 0
    ymax = 2*(len(sigmas_lcl)+1)
    yscale = ymax-ymin
    ypad = ymin + yscale*ypadfactor

    for i in range(len(sigmas_lcl)):
        if('combined' in groups[group]):
            if( i == 0 ):
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{BLUE Combination}")
            else:
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{%s: %s}"%(group,
                                                     keys_no_comb[i-1]))
        else:
            if 'combined' in group:
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{BLUE Comb.: %s}"%keys_no_comb[i])
            else:
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{%s: %s}"%(group,
                                                     keys_no_comb[i]))
                
        tex2.DrawLatex(4.60*xpad,yvals[i]-0.009*yscale,
                       "#font[132]{%.2f #pm "%sigmas_lcl[i]+
                       "%.2f_{exp} #pm "%tots_lcl[i]+
                       "%.2f_{theo}}"%(mc_info['theory_err']/mc_info['sigma']))

    #flavor text
    tex1.DrawLatex(0.85*xpad,yvals[-1] + 0.95*ypad,
                   "#font[132]{%s}"%luminosity)
    
    for i,flav in enumerate(flavor_text.split('\\')):
        tex1.DrawLatex(3.7*xpad,
                       yvals[-1] + (1.40-0.50*i)*ypad,
                       "#font[132]{%s}"%flav)
        

    tex1.DrawLatex(xmin,ymax+0.08,
                   "#font[132]{CMS Preliminary 2011}")
    tex1.DrawLatex(xmin+0.78*xscale,
                   ymax+0.08,
                   "#font[132]{#sqrt{s} = 7 TeV}")

    #lumi uncertainty
    tex1.SetTextColor(6)
    tex1.DrawLatex(3.7*xpad,
                   yvals[0] - 1.5*ypad,
                   "#font[132]{lumi. uncertainty %.1f}"%lumi_err
                   + "%")                      
    
    saneName = group.translate(None,delChars)
    valName = saneName+"_CS_ratio_plot"

    canv.Print(valName+".png")
    canv.Print(valName+".eps")
    canv.Print(valName+".pdf")
コード例 #8
0
def plot2BodyDist(theFitter, pars, chi2, ndf, 
                  Err = -1, NP = False, Prefix = "Mjj", Left = False):
    from ROOT import gPad, TLatex, TCanvas, kRed, kCyan, kBlue, \
         RooFit, RooPlot, RooCurve, RooAbsReal, TGraphErrors, TLine, \
         RooWjjMjjFitter

    if pars.includeMuons and pars.includeElectrons:
        modeString = ''
    elif pars.includeMuons:
        modeString = 'Muon'
    elif pars.includeElectrons:
        modeString = 'Electron'
    else:
        modeString = ''

    mf = theFitter.stackedPlot(False, RooWjjMjjFitter.mjj, Left)
    mf.SetName("%s_Stacked" % (Prefix));
    sf = theFitter.residualPlot(mf, "h_background", "dibosonPdf", False)
    sf.SetName("%s_Subtracted" % (Prefix));
    pf = theFitter.residualPlot(mf, "h_total", "", True)
    pf.SetName("%s_Pull" % (Prefix))
    pf2 = pf.emptyClone("%s_Pull_Corrected" % (Prefix))
    pf2.SetMinimum(-5.)
    pf2.SetMaximum(5.)
    corrPull = False
    lf = theFitter.stackedPlot(True, RooWjjMjjFitter.mjj, Left)
    lf.SetName("%s_Stacked_Log" % (Prefix));

    if Err > 0:
        totalPdf = theFitter.getWorkSpace().pdf('totalPdf')
        ## Ntotal = totalPdf.expectedEvents(iset)

        ## print 'Ntotal:',Ntotal
        h_dibosonPdf = sf.getCurve('h_dibosonPdf')
        totalPdf.plotOn(sf,
                        RooFit.ProjWData(theFitter.getWorkSpace().data('data')),
                        RooFit.Normalization(Err, RooAbsReal.Raw),
                        #RooFit.AddTo('h_dibosonPdf', 1., 1.),
                        #RooFit.Invisible(),
                        RooFit.Name('h_ErrUp'),
                        RooFit.Range('RangeForPlot'),
                        RooFit.NormRange('RangeForPlot'),
                        RooFit.LineColor(kRed), RooFit.LineStyle(3))
        h_ErrUp = sf.getCurve('h_ErrUp')
        sf.remove('h_ErrUp', False)

        ErrBand = TGraphErrors(h_dibosonPdf.GetN(), h_dibosonPdf.GetX(),
                               h_dibosonPdf.GetY())
        for pt in range(1, ErrBand.GetN()):
            ErrBand.SetPointError(pt, 0,
                                  h_ErrUp.interpolate(ErrBand.GetX()[pt]))
        ErrBand.SetName("ErrBand")
        ErrBand.SetTitle("Uncertainty")
        ErrBand.SetLineColor(kRed)
##         ErrBand.SetLineWidth(0)
##         ErrBand.SetLineStyle(0)
        ErrBand.SetFillColor(kRed)
        ErrBand.SetFillStyle(3353)

        
        #ErrBand.Draw('ap3')
        #h_ErrUp.Draw('lp')
        #gPad.Update()
        #gPad.WaitPrimitive()
##         h_ErrUp.Draw("al")
##         h_ErrUp.GetXaxis().Set(36, 40., 400.)
##         gPad.Update()
##         gPad.WaitPrimitive()
##         h_UpBand = RooCurve("h_UpBand", "Uncertainty", h_dibosonPdf, h_ErrUp,
##                             1., 1.)
##         h_UpBand.SetLineStyle(3)
##         h_UpBand.SetLineColor(kBlue+1)
##         h_DownBand = RooCurve("h_DownBand", "Uncertainty", h_dibosonPdf, h_ErrUp,
##                               1., -1.)
##         h_DownBand.SetLineStyle(3)
##         h_DownBand.SetLineColor(kBlue+1)

##         sf.addPlotable(h_UpBand, "L")
##         sf.addPlotable(h_DownBand, "L")
        sf.addObject(ErrBand, "3")
        #sf.Print("v")
        sf.drawAfter('h_dibosonPdf', 'ErrBand')
        #sf.Print("v")
        sf.drawAfter('ErrBand', 'theData')
        #sf.Print("v")
        sf.findObject('theLegend').AddEntry(ErrBand, 'Uncertainty', 'f')
        sf.findObject('theLegend').SetY1NDC(sf.findObject('theLegend').GetY1NDC() - 0.057)
        sf.findObject('theLegend').SetY1(sf.findObject('theLegend').GetY1NDC())

        corrPull = True
        pf2.addObject(sub2pull(sf.getHist('theData'),
                               sf.findObject('ErrBand')),
                      'p0')
        for item in range(0, int(pf.numItems())):
            firstItem = pf.getObject(item)
            if (type(firstItem) == TLine):
                newLine = TLine(firstItem)
                newLine.SetY1(4.)
                newLine.SetY2(-4.)
                pf2.addObject(newLine, 'l')
                #SetOwnership(newLine, False)


    if NP:
        NPPdf = theFitter.makeNPPdf();
        NPNorm = 4.*0.11*46.8/12.*pars.intLumi

        if (modeString == 'Electron'):
            if pars.njets == 2:
                NPNorm *= 0.0381
            elif pars.njets == 3:
                NPNorm *= 0.0123
        else:
            if pars.njets == 2:
                NPNorm *= 0.0550
            elif pars.njets == 3:
                NPNorm *= 0.0176

        print '**** N_NP:', NPNorm,'****'

        NPPdf.plotOn(sf, RooFit.ProjWData(theFitter.getWorkSpace().data('data')),
                     RooFit.Normalization(NPNorm, RooAbsReal.Raw),
                     RooFit.AddTo('h_dibosonPdf', 1., 1.),
                     RooFit.Name('h_NP'),
                     RooFit.Range('RangeForPlot'),
                     RooFit.NormRange('RangeForPlot'),
                     RooFit.LineColor(kBlue), RooFit.LineStyle(2))

        h_NP = sf.getCurve('h_NP')

        sf.drawBefore('h_dibosonPdf', 'h_NP')
        #sf.Print("v")
        sf.findObject('theLegend').AddEntry(h_NP, "CDF-like Signal", "L")
        sf.findObject('theLegend').SetY1NDC(sf.findObject('theLegend').GetY1NDC() - 0.057)
        sf.findObject('theLegend').SetY1(sf.findObject('theLegend').GetY1NDC())

    l = TLatex()
    l.SetNDC()
    l.SetTextSize(0.045)
    l.SetTextFont(42)

    cstacked = TCanvas("cstacked", "stacked")
    mf.Draw()
    if (chi2 > 0):
        l.DrawLatex(0.55, 0.49,
                    '#chi^{2}/dof = %0.3f/%d' % (chi2, ndf)
                    )
    pyroot_logon.cmsLabel(cstacked, pars.intLumi/1000, prelim = True)
    cstacked.Print('Wjj_%s_%s_%ijets_Stacked.pdf' % (Prefix, modeString,
                                                     pars.njets))
    cstacked.Print('Wjj_%s_%s_%ijets_Stacked.png' % (Prefix, modeString,
                                                     pars.njets))
    c2 = TCanvas("c2", "stacked_log")
    c2.SetLogy()
    lf.Draw()
    pyroot_logon.cmsPrelim(c2, pars.intLumi/1000)
    c2.Print('Wjj_%s_%s_%ijets_Stacked_log.pdf' % (Prefix, modeString,
                                                    pars.njets))
    c2.Print('Wjj_%s_%s_%ijets_Stacked_log.png' % (Prefix, modeString,
                                                    pars.njets))
    c3 = TCanvas("c3", "subtracted")
    sf.Draw()
    pyroot_logon.cmsLabel(c3, pars.intLumi/1000, prelim = True)
    c3.Print('Wjj_%s_%s_%ijets_Subtracted.pdf' % (Prefix, modeString,
                                                  pars.njets))
    c3.Print('Wjj_%s_%s_%ijets_Subtracted.png' % (Prefix, modeString,
                                                  pars.njets))
    c4 = TCanvas("c4", "pull")
    pf.Draw()
    c4.SetGridy()
    pyroot_logon.cmsPrelim(c4, pars.intLumi/1000)
    c4.Print('Wjj_%s_%s_%ijets_Pull.pdf' % (Prefix, modeString, pars.njets))
    c4.Print('Wjj_%s_%s_%ijets_Pull.png' % (Prefix, modeString, pars.njets))

    c5 = None
    if corrPull:
        c5 = TCanvas("c5", "corrected pull")
        pf2.Draw()
        c5.SetGridy()
        pyroot_logon.cmsPrelim(c5, pars.intLumi/1000)
        c5.Print('Wjj_%s_%s_%ijets_Pull_Corrected.pdf' % (Prefix, modeString,
                                                          pars.njets))
        c5.Print('Wjj_%s_%s_%ijets_Pull_Corrected.png' % (Prefix, modeString,
                                                          pars.njets))

    return ([mf,sf,pf2,lf],[cstacked,c2,c3,c5])
コード例 #9
0
from ROOT import TCanvas
from ROOT import gStyle

jetToElectronRatioGraph = TGraphErrors("jetToElectronFactors.dat",
                                       "%lg %lg %lg %lg")
jetToMuonRatioGraph = TGraphErrors("jetToMuonFactors.dat", "%lg %lg %lg %lg")
jetToMETRatioGraph = TGraphErrors("jetToMETFactors.dat", "%lg %lg %lg %lg")

jetToElectronRatioGraph.SetMarkerColor(2)
jetToElectronRatioGraph.SetMarkerStyle(21)
jetToMuonRatioGraph.SetMarkerColor(3)
jetToMuonRatioGraph.SetMarkerStyle(21)
jetToMETRatioGraph.SetMarkerColor(4)
jetToMETRatioGraph.SetMarkerStyle(21)

jetToElectronRatioGraph.SetFillStyle(1001)
jetToElectronRatioGraph.SetFillColor(2)
jetToMuonRatioGraph.SetFillStyle(1001)
jetToMuonRatioGraph.SetFillColor(3)
jetToMETRatioGraph.SetFillStyle(1001)
jetToMETRatioGraph.SetFillColor(4)

jetToObjectRatioGraphs = TMultiGraph()

jetToObjectRatioGraphs.Add(jetToElectronRatioGraph, "")
jetToObjectRatioGraphs.Add(jetToMuonRatioGraph, "")
jetToObjectRatioGraphs.Add(jetToMETRatioGraph, "")

canvas = TCanvas()
canvas.SetGrid()
canvas.SetLogy()