Ejemplo n.º 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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
 def plot( self, plotoptions, opt="?" ):
     vx= array( "d", self.aostand.getPointsCenter() )
     values= self.values
     sterrs= self.sterrs
     if "m" in opt:
         print "AnalysisObservable::plot: use errors from error matrix"
         sterrs= array( "d", self.aostand.getErrors( "m" ) )
     syerrs= self.syerrs
     npoints= len(vx)
     if "xshift" in plotoptions:
         for i in range(npoints):
             vx[i]+= plotoptions["xshift"]
     vex= array( "d", npoints*[0.0] )
     tgest= TGraphErrors( npoints, vx, values, vex, sterrs )
     toterrs= np.sqrt( np.add( np.square( sterrs ),  np.square( syerrs ) ) )
     tgesy= TGraphErrors( npoints, vx, values, vex, toterrs )
     tgesy.SetMarkerStyle( plotoptions["markerStyle"] )
     tgesy.SetMarkerSize( plotoptions["markerSize"] )
     drawas= plotoptions["drawas"] if "drawas" in plotoptions else "p"
     tgesy.SetName( self.obs )
     if "fillcolor" in plotoptions:
         tgesy.SetFillColor(plotoptions["fillcolor"])
         tgest.SetFillColor(plotoptions["fillcolor"])
     if "s" in opt:
         tgesy.Draw( "psame" )
     else:
         if "title" in plotoptions:
             tgesy.SetTitle( plotoptions["title"] )
         else:
             tgesy.SetTitle( self.obs )
         tgesy.SetMinimum( plotoptions["ymin"] )
         tgesy.SetMaximum( plotoptions["ymax"] )
         xaxis= tgesy.GetXaxis()
         xaxis.SetLimits( plotoptions["xmin"], plotoptions["xmax"] )
         if "xlabel" in plotoptions:
             xaxis.SetTitle( plotoptions["xlabel"] )
         if "ylabel" in plotoptions:
             tgesy.GetYaxis().SetTitle( plotoptions["ylabel"] )
         tgesy.Draw( "a"+drawas )
     optlogx= plotoptions["logx"] if "logx" in plotoptions else 0
     gPad.SetLogx( optlogx )
     optlogy= plotoptions["logy"] if "logy" in plotoptions else 0
     gPad.SetLogy( optlogy )
     tgest.Draw( "same"+drawas )
     return tgest, tgesy
def graphTruth():
    fname = "PionMinusG4.txt"
    kineticEnergy = []
    crossSec = []
    crossSec_el = []
    crossSec_inel = []
    zero = []

    title = ""
    with open(fname) as f:
        for fLine in f.readlines():
            w = fLine.split()
            if is_number(w[0]):
                runIn = int(w[0])
                ke = float(w[1])
                xstot = float(w[4])
                kineticEnergy.append(ke)
                crossSec.append(xstot)
                zero.append(0.)
            else:
                if "for" not in fLine:
                    continue
                title = fLine[9:]

    #define some data points . . .
    x = array('f', kineticEnergy)
    y = array('f', crossSec)
    y_el = array('f', crossSec_el)
    y_inel = array('f', crossSec_inel)
    exl = array('f', zero)
    exr = array('f', zero)

    nPoints = len(x)
    # . . . and hand over to TGraphErros object
    gr = TGraphErrors(nPoints, x, y, exl, exr)
    gr.SetTitle(title + "; Kinetic Energy [MeV]; Cross Section [barn]")
    gr.GetXaxis().SetRangeUser(0, 1000)
    gr.GetYaxis().SetRangeUser(0, 2.)
    gr.SetLineWidth(2)
    gr.SetLineColor(kGreen - 2)
    gr.SetFillColor(0)
    return gr
Ejemplo n.º 5
0
def tgrapherrors_from_lists(x, y, ex, ey):
    if ex is None and ey is None:
        n = min(len(x), len(y))
        tg = TGraphErrors(n, array.array('d', x[:n]), array.array('d', y[:n]),
                          array.array('d', [0] * n), array.array('d', [0] * n))
    elif ex is None:
        n = min(len(x), len(y), len(ey))
        tg = TGraphErrors(n, array.array('d', x[:n]), array.array('d', y[:n]),
                          array.array('d', [0] * n), array.array('d', ey[:n]))
    elif ey is None:
        n = min(len(x), len(ex), len(y))
        tg = TGraphErrors(n, array.array('d', x[:n]), array.array('d', y[:n]),
                          array.array('d', ex[:n]), array.array('d', [0] * n))
    else:
        n = min(len(x), len(ex), len(y), len(ey))
        tg = TGraphErrors(n, array.array('d', x[:n]), array.array('d', y[:n]),
                          array.array('d', ex[:n]), array.array('d', ey[:n]))
    keep(tg)
    tg.SetFillColor(0)
    return tg
Ejemplo n.º 6
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')
Ejemplo n.º 7
0
jetToMETRatePlot.SetPointError(41, 5, 24558.1623237245)
jetToMETRatePlot.SetPointError(42, 5, 25142.8804742893)
jetToMETRatePlot.SetPointError(43, 5, 25727.5986248542)
jetToMETRatePlot.SetPointError(44, 5, 26312.3167754191)
jetToMETRatePlot.SetPointError(45, 5, 26897.034925984)
jetToMETRatePlot.SetPointError(46, 5, 27481.7530765488)
jetToMETRatePlot.SetPointError(47, 5, 28066.4712271137)
jetToMETRatePlot.SetPointError(48, 5, 28651.1893776786)
jetToMETRatePlot.SetPointError(49, 5, 29235.9075282434)

ratePlot = TMultiGraph()

# Setting colours
# Black
jetRatePlot.SetLineColor(1)
jetRatePlot.SetFillColor(1)
# Red
jetToMuonRatePlot.SetLineColor(2)
jetToMuonRatePlot.SetFillColor(2)
# Green
jetToElectronRatePlot.SetLineColor(3)
jetToElectronRatePlot.SetFillColor(3)
# Blue
jetToMETRatePlot.SetLineColor(4)
jetToMETRatePlot.SetFillColor(4)

# Adding a legend

canvas = TCanvas("c1", "canvas")
canvas.SetLogy(True)
canvas.SetGridx()
Ejemplo n.º 8
0
xx = []
xxer = []
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(),
        #-------end of canvas BS
    #--drawing on pad1

            print ("gh 6")
            pad1.cd()
            NSMassPoint.GetXaxis().SetLabelSize(0.15)
            NSMassPoint.GetYaxis().SetLabelSize(0.05)
            NSMassPoint.GetYaxis().SetTitleOffset(0.42) # 1.2 = 20% larger
            NSMassPoint.SetTitleOffset(0.42) # 1.2 = 20% larger
            NSMassPoint.SetTitle("Bkg Estimtae in each signal injected mass point: Trijet Inclusive Window: "+str(windowWidth))
            NSMassPoint.SetMarkerStyle(1)
            NSMassPoint.GetYaxis().SetRange(1, 1000000)
            NSMassPoint.SetMarkerColor(0)
            NSMassPoint.SetLineColor(0)
            NSMassPoint.Draw() #this is to make sure the x axis of pad1 mataches that of pad2
            NSErrorBar.SetFillColor(29)
            NSErrorBar.SetMarkerColor(1)
            NSErrorBar.Draw("LE3 same")
            NSErrorBar.Draw("P same")
            #NSMassPoint.Draw("E same")
            print("N : ", NSErrorBar.GetN())
            #NSErrorBar.Draw("P")

            #JBMassPoint.SetMarkerStyle(2)
            #JBMassPoint.SetMarkerColor(2)
            #JBMassPoint.SetLineColor(2)
            #JBMassPoint.Draw("P same")
            JBGraph.SetMarkerStyle(5)
            JBGraph.SetMarkerColor(2)
            JBGraph.SetLineColor(2)
            JBGraph.Draw("P same")
Ejemplo n.º 10
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])
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
Ejemplo n.º 12
0
]

icol = 0
for iwidth in jitsWidth:
    for ilambdaB in jitsLambdaB:
        name = "limit_%d_%d" % (ilambdaB, iwidth)
        limit = TGraphErrors()
        limit.SetName(name)
        thefiles = GetFiles(files, ilambdaB, iwidth)
        gres = GetGraphs(thefiles)
        #		print len(gres)

        limit.SetMarkerStyle(20)
        limit.SetMarkerSize(0.7)
        limit.SetMarkerColor(cols[icol])
        limit.SetFillColor(cols[icol])
        limit.SetLineColor(cols[icol])
        GetLimitPlot(gres, limit, fit)
        limits.append(limit)
        icol += 1

print "number of limits: %d" % len(limits)

limits[0].SetTitle("limit sytematics on #lambda_{B} and #Gamma")
limits[0].GetXaxis().SetTitle("mass [GeV/c^{2}]")
limits[0].GetYaxis().SetTitle("#lambda_{s}")
limits[0].SetMinimum(0)
limits[0].SetMinimum(2)
limits[0].SetMaximum(8)
limits[0].Draw("ape")
Ejemplo n.º 13
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")
Ejemplo n.º 14
0
def drawMassRes(data, mc, output, rapidity, ptda, ptmc, trackType, funct,
                mcIsData, dataIsMC):
    style = setTDRStyle()

    pt_e = [0 for x in range(len(data))]
    pt_x = [0 for x in range(len(data))]
    for i, pt in enumerate(pt_x):
        pt_x[i] = ptbins[i] + (ptbins[i + 1] - ptbins[i]) / 2.
        pt_e[i] = (ptbins[i + 1] - ptbins[i]) / 2.
    if dataIsMC:
        (da_mean, da_meane, da_sig, da_sige,
         da_nChi2) = doFit(data, output, rapidity, "MC2", trackType, funct)
    else:
        (da_mean, da_meane, da_sig, da_sige,
         da_nChi2) = doFit(data, output, rapidity, "DATA", trackType, funct)
    if mcIsData:
        (mc_mean, mc_meane, mc_sig, mc_sige,
         mc_nChi2) = doFit(mc, output, rapidity, "DATA2", trackType, funct)
    else:
        (mc_mean, mc_meane, mc_sig, mc_sige,
         mc_nChi2) = doFit(mc, output, rapidity, "MC", trackType, funct)
    result = {}
    result["data_mean"] = da_mean
    result["data_meane"] = da_meane
    result["data_sig"] = da_sig
    result["data_sige"] = da_sige
    result["mc_mean"] = mc_mean
    result["mc_meane"] = mc_meane
    result["mc_sig"] = mc_sig
    result["mc_sige"] = mc_sige
    result["ptda"] = ptda
    result["ptmc"] = ptmc
    result["da_nChi2"] = da_nChi2
    result["mc_nChi2"] = mc_nChi2

    pklFile = open(
        output + "/MassResolutionVsPt_%s_%s.pkl" % (trackType, rapidity), "wb")
    pickle.dump(result, pklFile)
    pklFile.close()

    c2 = TCanvas("c2", "c2", 700, 700)
    c2.cd()

    # Upper plot will be in pad1
    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.SetGrid()  # Vertical grid
    pad1.SetBottomMargin(0.1)
    pad1.Draw()  # Draw the upper pad: pad1
    pad1.cd()  # pad1 becomes the current pad
    pad1.SetTicks()

    res_data = TGraphAsymmErrors()
    res_data.SetName("res_data")
    res_mc = TGraphAsymmErrors()
    res_mc.SetName("res_mc")
    ratio = TGraphErrors()
    ratio.SetName("ratio")
    #~ print len(pt_x)
    for i, pt in enumerate(pt_x):
        res_data.SetPoint(i, ptda[i], da_sig[i])
        res_data.SetPointError(i, ptda[i] - ptbins[i], ptbins[i + 1] - ptda[i],
                               da_sige[i], da_sige[i])
        res_mc.SetPoint(i, ptmc[i], mc_sig[i])
        res_mc.SetPointError(i, ptmc[i] - ptbins[i], ptbins[i + 1] - ptmc[i],
                             mc_sige[i], mc_sige[i])
        if mc_sig[i] > 0:
            ratio.SetPoint(i, pt, da_sig[i] / mc_sig[i])
            ratio.SetPointError(i, pt_e[i], (da_sig[i] / mc_sig[i]) *
                                math.sqrt((da_sige[i] / da_sig[i])**2 +
                                          (mc_sige[i] / mc_sig[i])**2))
    res_data.SetMarkerStyle(22)
    res_data.SetMarkerColor(kBlack)
    res_data.SetLineColor(kBlack)
    res_data.SetFillColor(0)
    res_data.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType)
    res_data.GetYaxis().SetTitle("Mass resolution at Z peak [GeV]")
    res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    res_data.GetYaxis().SetTitleOffset(1.2)
    res_data.GetYaxis().SetRangeUser(0., 6.)
    if trackType == "Outer":
        res_data.GetYaxis().SetRangeUser(1., 20.)
    res_data.GetXaxis().SetRangeUser(ptbins[0], ptbins[len(ptda)])
    res_data.Draw("AP E0")
    res_mc.SetMarkerStyle(22)
    res_mc.SetMarkerColor(kRed)
    res_mc.SetLineColor(kRed)
    res_mc.SetFillColor(0)
    res_mc.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType)
    res_mc.GetYaxis().SetTitle("Mass resolution at Z peak [GeV]")
    res_mc.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    res_mc.GetYaxis().SetTitleOffset(1.5)
    res_mc.Draw("P E0 SAME")
    if rapidity == "BB":
        leg = TLegend(0.25, 0.6, 0.50, 0.80, "both muons |#eta| < 1.2",
                      "brNDC")
    else:
        leg = TLegend(0.25, 0.6, 0.5, 0.8, "at least one muon |#eta| > 1.2",
                      "brNDC")
    if mcIsData:
        leg.AddEntry(res_data, "DATA 2017")
        leg.AddEntry(res_mc, "DATA 2016")
    elif dataIsMC:
        leg.AddEntry(res_data, "MC 2017")
        leg.AddEntry(res_mc, "MC 2016")
    else:
        leg.AddEntry(res_data, "DATA", "p")
        leg.AddEntry(res_mc, "Simulation")

    leg.SetTextFont(42)
    leg.SetBorderSize(0)
    leg.SetTextSize(.04)
    leg.Draw("SAME")
    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055 / 0.7)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03 / 0.7)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.78, 0.88, "CMS")
    yLabelPos = 0.84
    latexCMSExtra.DrawLatex(0.78, yLabelPos, "%s" % (cmsExtra))
    c2.cd()  # Go back to the main canvas before defining pad2
    pad2 = TPad("pad2", "pad2", 0, 0.1, 1, 0.30)
    pad2.SetTopMargin(0)
    pad2.SetBottomMargin(0.3)
    pad2.SetGrid()
    pad2.Draw()
    pad2.cd()
    pad2.SetTicks()
    ratio.SetMarkerColor(kBlue - 4)
    ratio.SetFillColor(kBlue - 4)
    ratio.SetTitle("")
    ratio.GetYaxis().SetTitle("Data/MC")
    if mcIsData:
        ratio.GetYaxis().SetTitle("Data 2017 / Data 2016")
    elif dataIsMC:
        ratio.GetYaxis().SetTitle("MC 2017 / MC 2016")
    ratio.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    ratio.GetYaxis().SetRangeUser(0.5, 1.5)
    ratio.GetXaxis().SetRangeUser(ptbins[0], ptbins[len(ptda)])
    ratio.GetYaxis().SetTitleOffset(0.50)
    ratio.GetYaxis().SetTitleSize(0.14)
    ratio.GetYaxis().SetLabelSize(0.14)
    ratio.GetYaxis().SetNdivisions(506)
    ratio.GetXaxis().SetTitleSize(0.12)
    ratio.GetXaxis().SetTitleOffset(1.2)
    ratio.GetXaxis().SetLabelSize(0.20)
    ratio.Draw("A P E2")
    pad2.Update()
    line = TLine(ptbins[0], 1, ptbins[len(ptda)], 1)

    line.SetLineColor(kBlue + 1)
    line.SetLineWidth(2)
    line.Draw()
    saveas = "/MassResolutionVsPt_%s_%s" % (trackType, rapidity)
    c2.SaveAs(output + saveas + ".png")
    c2.SaveAs(output + saveas + ".pdf")
    c2.SaveAs(output + saveas + ".root")
    c2.SaveAs(output + saveas + ".C")
Ejemplo n.º 15
0
gr.SetTitle(
    "K^{+}Ar Cross Section; Kinetic Energy [MeV]; Cross Section [barn]")
gr.GetXaxis().SetRangeUser(0, 800)
gr.GetYaxis().SetRangeUser(0, 1.0)

gr.GetYaxis().SetTitleOffset(1.2)

gr.SetLineWidth(2)
grel.SetLineWidth(2)
grinel.SetLineWidth(2)

gr.SetLineColor(kGreen - 2)
grel.SetLineColor(kBlue)
grinel.SetLineColor(kRed)

gr.SetFillColor(0)
grel.SetFillColor(0)
grinel.SetFillColor(0)

gr.Draw("APL")
grel.Draw("PLsame")
grinel.Draw("PLsame")
hTot.Draw("same")
hEla.Draw("same")
hIne.Draw("same")

legend = TLegend(.14, .68, .54, .88)

legend.AddEntry(gr, "G4 Prediction Tot XS")
legend.AddEntry(hTot, "True En Dep -- Tot XS")
Ejemplo n.º 16
0
def plot(name_f_json, projection=1):
    pulse_start = 35000
    pulse_width = 15000
    sweep_type = 'threshold'
    time_scale = 140000
    # one for each ASIC
    #pixels=[(0,1)]
    pixels = get_pixels(name_f_json + '.json')
    matrix = [0, 1, 2]
    hits = (0, 1, 2, 3, 4, 5, 6, 7)
    th_l = 0x0
    th_h = 0x800
    th_delta = 0x8
    thresholdCuts = range(th_l, th_h, th_delta)
    data_dic = {}
    pulse_end = pulse_start + pulse_width
    fast_range = 1500
    with open(name_f_json + '.json') as f:
        #with open('f_j.json') as f:
        hist = json.load(f, object_hook=dic2timep)
        data_dic = get_allHists(pixels, matrix, hits, thresholdCuts)
        #data_dic=get_allHists(pixels,matrix,thresholdCuts,hits)
        for a in hist:
            p1 = a.pixel[0]
            p2 = a.pixel[1]
            data_dic[(p1, p2)][a.matrix][a.index][a.threshold] = a.time
    rootf = TFile(name_f_json + '.root', "RECREATE")
    for key in data_dic:  #pixel
        print(key)
        for key1 in data_dic[key]:  #matri2x
            h = "hitnumber_pixel_" + str(key) + "_asic" + str(
                key1) + "_THsweep"
            h = TH1D(h, ";Hit;Hits number", 8, 0, 8)
            h_name_all = "cumulTimeHist_pixel_" + str(key) + "_asic" + str(
                key1) + "_THsweep"
            #h_name_g="cumulTimeHist_pixel_"+str(key)+"_asic"+str(key1)+"_THsweep_g"
            a = []
            for key3 in data_dic[key][key1][1]:  #threshold
                a.append(key3)
            a1 = [float(b) / 1241. for b in a]
            hist_name_all = TH2D(h_name_all, ";Threshold [V];Time [ns]",
                                 (th_h - th_l) / th_delta, min(a1), max(a1),
                                 2000, 0, time_scale)
            for key2 in data_dic[key][key1]:  #index
                h_name = "cumulTimeHist_pixel_" + str(key) + "_asic" + str(
                    key1) + "_hit_" + str(key2) + "_THsweep"
                hist_name = TH2D(h_name, ";Threshold [V];Time [ns]",
                                 (th_h - th_l) / th_delta, min(a1), max(a1),
                                 800, 0, time_scale)
                g_x = []
                g_y = []
                g_ex = []
                g_ey = []
                a = data_dic[key][key1][key2].keys()
                a.sort()
                for key3 in a:  #threhsold
                    #for key3 in data_dic[key][key1][key2]: #threhsold
                    t_aftercut = []
                    for val_i in range(len(data_dic[key][key1][key2][key3])):
                        timev = data_dic[key][key1][key2][key3][val_i]
                        #if timev>0:
                        #if (timev<35000):
                        if timev > 0:
                            t_aftercut.append(timev)
                            hist_name.Fill(float(key3) / 1241, timev)
                            hist_name_all.Fill(float(key3) / 1241, timev)
                            h.Fill(key2)
                    if len(t_aftercut) != 0:
                        t_aftercut_a = np.array(t_aftercut)
                        g_x.append(float(key3) / 1241)
                        #print(float(key3)/1241)
                        g_y.append(np.mean(t_aftercut_a))
                        g_ey.append(np.std(t_aftercut_a))
                        g_ex.append(0)
                hist_name.Write()
                g_ax = np.array(g_x)
                g_ay = np.array(g_y)
                g_aex = np.array(g_ex)
                g_aey = np.array(g_ey)
                #hist_name_g=TGraph(len(g_ax),g_ax,g_ay)
                #                #hist_name_g="cumulTimeHist_pixel_"+str(key)+"_asic"+str(key1)+"_hit_"+str(key2)+"_THsweep_g"
                if len(g_ax) != 0:
                    graph_g = TGraph(len(g_ax), g_ax, g_ay)
                    graph_g.SetName("cumulTimeHist_pixel_" + str(key) +
                                    "_asic" + str(key1) + "_hit_" + str(key2) +
                                    "_THsweep_graph")
                    graph_g.SetTitle(";Threshold [V];Time [ns]")
                    graph_g.SetMarkerStyle(20)
                    graph_g.SetMarkerSize(0.6)
                    graph_g.Write()
                    hist_name_g = TGraphErrors(len(g_ax), g_ax, g_ay, g_aex,
                                               g_aey)
                    hist_name_g.SetName("cumulTimeHist_pixel_" + str(key) +
                                        "_asic" + str(key1) + "_hit_" +
                                        str(key2) + "_THsweep_g")
                    hist_name_g.SetTitle(";Threshold [V];Time [ns]")
                    hist_name_g.SetFillColor(1)
                    hist_name_g.SetMarkerStyle(20)
                    hist_name_g.SetMarkerSize(0.6)
                    hist_name_g.Write()
                if projection:
                    cut1 = [min(a1), 0]
                    cut2 = [max(a1), 140000]
                    proj_x = get_proj_X(hist_name, h_name, cut1, cut2, min(a1),
                                        max(a1))
                    proj_y = get_proj_Y(hist_name, h_name, cut1, cut2, 0,
                                        time_scale)
                    proj_x.Write()
                    proj_y.Write()
                #hist_name_g="cumulTimeHist_pixel_"+str(key)+"_asic"+str(key1)+"_THsweep_g"
                #hist_name_g=TGraphErrors(n,g_ax,g_aex,g_ay,g_aey)
                #hist_name_g=TGraphErrors(n,g_ax,g_aex,g_ay,g_aey)
                #hist_name_g.SetTitle("cumulTimeHist_pixel_"+str(key)+"_asic"+str(key1)+"_THsweep_g")
                #hist_name_g=TGraphErrors(h_name_g,";Threshold [V];Time [ns]",n,g_x,g_y,g_ex,g_ey)
            hist_name_all.Write()
            h.Write()
            if projection:
                cut1 = [min(a1), 0]
                cut2 = [max(a1), 140000]
                proj_x_all = get_proj_X(hist_name_all, h_name_all, cut1, cut2,
                                        min(a1), max(a1))
                proj_y_all = get_proj_Y(hist_name_all, h_name_all, cut1, cut2,
                                        0, time_scale)
                proj_x_all.Write()
                proj_y_all.Write()

    rootf.Close()
Ejemplo n.º 17
0
#define some data points . . .
x = array('f', kineticEnergy)
y = array('f', crossSec)
exl = array('f', zero)
exr = array('f', zero)

nPoints = len(x)
# . . . and hand over to TGraphErros object
gr = TGraphErrors(nPoints, x, y, exl, exr)
gr.SetTitle(title + "; Kinetic Energy [MeV]; Cross Section [barn]")
gr.GetXaxis().SetRangeUser(0, 1000)
gr.GetYaxis().SetRangeUser(0, 2.)
gr.SetLineWidth(2)
gr.SetLineColor(kGreen - 2)
gr.SetFillColor(0)

## Data
data_FileName = "/Volumes/Seagate/Elena/TPC/Data60A.root"
data_File = TFile.Open(data_FileName)
interactingPlotString = "RecoXS/hRecoInteractingKE"
incidentPlotString = "RecoXS/hRecoIncidentKE"
data_Int = data_File.Get(interactingPlotString)
data_Inc = data_File.Get(incidentPlotString)
XSDataRecoPion = data_Int.Clone("pionMCXSData")
XSDataRecoPion.Sumw2()
data_Inc.Sumw2()
XSDataRecoPion.Scale(101.10968)
XSDataRecoPion.Divide(data_Inc)
XSDataRecoPion.SetLineColor(kBlack)
XSDataRecoPion.SetLineWidth(2)
Ejemplo n.º 18
0
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()