Ejemplo n.º 1
0
Archivo: lat3.py Proyecto: gothman5/LAT
def MakeCutPlot(c,cal,var,eb,elo,ehi,vb,vlo,vhi,d2Cut,d1Cut,outPlot,fastMode):
    """ Creates a channel-specific energy calibration plot. """

    # Calculate cut vals (assumes plot range is correct)
    h1 = wl.H1D(cal,vb,vlo,vhi,var,d1Cut)
    h1Sum = h1.Integral()
    if h1Sum == 0:
        print "Error: Failed %s, histogram sum is 0 so cannot normalize, setting to [0,0,0,0,0]"%(var)
        return 0,0,0,0,0
    h1.Scale(1/h1Sum)
    try:
        cut99,cut95,cut01,cut05,cut90 = wl.GetIntegralPoints(h1)
    except:
        print "Error: Failed %s using cut %s, setting to [0,0,0,0,0]"%(var,d1Cut)
        return 0,0,0,0,0
    if fastMode:
        print "Returning fastMode output: ", cut99,cut95,cut01,cut05,cut90
        return cut99,cut95,cut01,cut05,cut90

    # Generate the plot for inspection.
    c.cd(2)
    gPad.SetLogy(0)
    h1.GetXaxis().SetRangeUser(cut01-abs(0.25*cut01), cut99 + abs(0.25*cut99) )
    h1.SetTitle("")
    h1.GetXaxis().SetTitle(var)
    h1.Draw("hist")

    c.cd(1)
    gPad.SetLogy(0)
    cal.Draw("%s:trapENFCal>>b(%d,%d,%d,%d,%.3E,%.3E)"%(var,eb+10,elo-5,ehi+5,vb,cut01-abs(0.25*cut01),cut99+abs(0.25*cut99)) ,d2Cut)

    l1, l2, l3 = TLine(), TLine(), TLine()
    l1.SetLineColor(ROOT.kGreen)
    l2.SetLineColor(ROOT.kRed)
    l3.SetLineColor(ROOT.kMagenta)

    l1.DrawLine(elo-5, cut99, ehi+5, cut99)
    l2.DrawLine(elo-5, cut95, ehi+5, cut95)
    l2.DrawLine(elo-5, cut05, ehi+5, cut05)
    l1.DrawLine(elo-5, cut01, ehi+5, cut01)

    c.cd(3)
    x_h1, y_h1 = wl.npTH1D(h1)
    int_h1 = wl.integFunc(y_h1)
    g2 = TGraph(len(x_h1), x_h1, int_h1)
    g2.GetXaxis().SetRangeUser(cut01-abs(0.3*cut01), cut99 + abs(0.3*cut99) )
    g2.SetTitle("")
    g2.GetXaxis().SetTitle(var)
    g2.GetYaxis().SetTitle("Percentile")
    g2.Draw("ACP")
    l1.DrawLine(cut99, 0, cut99, 1)
    l2.DrawLine(cut95, 0, cut95, 1)
    l1.DrawLine(cut01, 0, cut01, 1)
    l2.DrawLine(cut05, 0, cut05, 1)

    c.Print(outPlot)
    return cut99,cut95,cut01,cut05,cut90
Ejemplo n.º 2
0
    def DrawRatioLines(self, hist, frac=0.2, y0=1.):
        '''Draw a line at y = 1, at 1+frac, and at 1-frac.

        hist is used to get the x axis range.'''
        xmin = hist.obj.GetXaxis().GetXmin()
        xmax = hist.obj.GetXaxis().GetXmax()
        line = TLine()
        line.DrawLine(xmin, y0, xmax, y0)
        line.DrawLine(xmin, y0 + frac, xmax, y0 + frac)
        line.DrawLine(xmin, y0 - frac, xmax, y0 - frac)
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [3. * nchannels - 1.5 - 3. * i for i in range(0, nchannels)])
    ey = np.array([0.8 for i in range(0, nchannels)])
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    x1 = gStyle.GetPadLeftMargin() + 0.01
    y2 = 1 - gStyle.GetPadTopMargin() - 0.01
    leg = TLegend(x1, y2 - 0.17, x1 + 0.25, y2)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    leg.AddEntry(gobs, "Observed", "pl")
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
Ejemplo n.º 4
0
    def DrawRatioLines(self, hist, xmin, xmax, frac=0.2):
        '''Draw a line at y = 1, at 1+frac, and at 1-frac.

        hist is used to get the y axis range.'''
        if xmin is None:
            xmin = hist.obj.GetXaxis().GetXmin()
        if xmax is None:
            xmax = hist.obj.GetXaxis().GetXmax()
        line = TLine()
        line.DrawLine(xmin, 1, xmax, 1)
        line.DrawLine(xmin, 1 + frac, xmax, 1 + frac)
        line.DrawLine(xmin, 1 - frac, xmax, 1 - frac)
Ejemplo n.º 5
0
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [nchannels - 1.5 - float(i) for i in range(0, nchannels)])
    ey = np.full(nchannels, 0.494)
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    leg = TLegend(0.75, 0.75, 0.95, 0.9)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
Ejemplo n.º 6
0
def bestfit():

    xmin = -10
    xmax = 6

    c, h = draw_canvas_histo(
        xmin, xmax, "Best fit #mu = #sigma/#sigma_{SM} at m_{H} = 125 GeV")

    # line at SM expectation of mu = 1
    l = TLine()
    l.SetLineStyle(2)
    l.DrawLine(1.0, -1.0, 1.0, -1.0 + nchannels)

    mu = np.array([-0.4, -4.734, -2.014])
    upper = np.array([2.12, 3.688, 1.80])
    lower = np.array([2.08, 3.754, 1.8224])

    channel = np.array([1.5, 0.5, -0.5])
    zero = np.zeros(nchannels)

    gmu = TGraphAsymmErrors(nchannels, mu, channel, lower, upper, zero, zero)
    gmu.SetMarkerStyle(21)
    gmu.SetMarkerSize(1.5)
    gmu.SetLineColor(2)
    gmu.SetLineWidth(2)
    gmu.Draw("pz")

    #draw_disclaimer()

    c.RedrawAxis()
    c.Modified()
    c.Update()
    c.SaveAs("bestfit.pdf")
Ejemplo n.º 7
0
def overlayAndRatio(canvas, min_ratio, max_ratio, h1, h2):
    canvas.ResetAttPad()
    canvas.Clear()
    pad = TPad("main", "main", 0, 0.3, 1, 1)
    pad.SetBottomMargin(0.05)
    pad.Draw()
    pad.cd()
    h1.Draw()
    h2.SetLineColor(kOrange + 10)
    h2.Draw('SAME')
    canvas.cd()
    ratio = TPad("ratio", "ratio", 0, 0.05, 1, 0.3)
    ratio.SetTopMargin(0.05)
    ratio.Draw()
    ratio.cd()
    if isinstance(h1, TProfile) and isinstance(h2, TProfile):
        h1_p = h1.ProjectionX()
        h2_p = h2.ProjectionX()
        h1_p.Divide(h2_p)
        h1_p.SetMaximum(max_ratio)
        h1_p.SetMinimum(min_ratio)
        h1_p.SetMarkerStyle(kFullCircle)
        h1_p.SetMarkerSize(0.6)
        h1_p.SetTitle('')
        h1_p.GetXaxis().SetLabelFont(42)
        h1_p.GetXaxis().SetLabelSize(0.1)
        h1_p.GetYaxis().SetLabelFont(42)
        h1_p.GetYaxis().SetLabelSize(0.1)
        h1_p.GetYaxis().SetNdivisions(505)
        equality = TLine()
        h1_p.Draw("SAME HIST P")
        equality.SetLineColor(kOrange + 10)
        equality.DrawLine(h1_p.GetXaxis().GetXmin(), 1,
                          h1_p.GetXaxis().GetXmax(), 1)
Ejemplo n.º 8
0
def MakeCutPlot(c, cal, var, eb, elo, ehi, vb, vlo, vhi, d2Draw, d2Cut, d1Cut,
                outPlot, fastMode):
    """ Repeated code is the DEVIL.  Even if you have to pass in 1,000,000 arguments. """

    # Calculate cut vals (assumes plot range is correct)
    h1 = wl.H1D(cal, vb, vlo, vhi, var, d1Cut)
    h1Sum = h1.Integral()
    if h1Sum == 0:
        return 0, 0, 0, 0, 0
    h1.Scale(1 / h1Sum)
    cut99, cut95, cut01, cut05, cut90 = wl.GetIntegralPoints(h1)
    if fastMode:
        return cut99, cut95, cut01, cut05, cut90

    # Generate the plot for inspection.
    c.cd(2)
    gPad.SetLogy(0)
    h1.Draw("hist")

    c.cd(1)
    gPad.SetLogy(0)
    cal.Draw(d2Draw, d2Cut)

    l1, l2 = TLine(), TLine()
    l1.SetLineColor(ROOT.kGreen)
    l2.SetLineColor(ROOT.kRed)

    l1.DrawLine(elo, cut99, ehi, cut99)
    l2.DrawLine(elo, cut95, ehi, cut95)
    l2.DrawLine(elo, cut05, ehi, cut05)
    l1.DrawLine(elo, cut01, ehi, cut01)

    c.cd(3)
    x_h1, y_h1 = wl.npTH1D(h1)
    int_h1 = wl.integFunc(y_h1)
    g2 = TGraph(len(x_h1), x_h1, int_h1)
    g2.Draw("ACP")
    l1.DrawLine(cut99, 0, cut99, 1)
    l2.DrawLine(cut95, 0, cut95, 1)
    l1.DrawLine(cut01, 0, cut01, 1)
    l2.DrawLine(cut05, 0, cut05, 1)

    c.Print(outPlot)
    return cut99, cut95, cut01, cut05, cut90
Ejemplo n.º 9
0
def drawComparisons(hGabriel, hEGamma):
    setRed(hGabriel)
    c = TCanvas("c", "c", 1)
    c.Divide(1, 2)
    c.cd(1).SetPad(0, 0.2, 1, 1)
    c.cd(2).SetPad(0, 0, 1, 0.25)

    c.cd(1)
    hEGamma.Draw()
    hGabriel.Draw("same")

    leg = TLegend(0.7, 0.9, 0.9, 0.75)
    leg.AddEntry(hEGamma, "EGamma", "l")
    leg.AddEntry(hGabriel, "Gabriel", "l")
    leg.Draw()

    c.cd(2)
    hRatio = hGabriel.Clone("hRatio")
    hRatio.Divide(hEGamma)

    hRatio.SetTitle("")
    hRatio.GetXaxis().SetLabelOffset(999)
    hRatio.GetXaxis().SetLabelSize(0)
    hRatio.GetXaxis().SetTitle("")
    hRatio.GetYaxis().SetTitle("Mine/EG")
    hRatio.GetYaxis().SetTitleSize(0.1)
    hRatio.GetYaxis().SetTitleOffset(0.4)
    hRatio.GetYaxis().SetLabelSize(0.08)
    hRatio.SetMarkerStyle(20)
    hRatio.GetYaxis().SetRangeUser(0.985, 1.015)
    hRatio.Draw()

    line = TLine()
    line1 = line.DrawLine(hRatio.GetXaxis().GetXmin(), 1.,
                          hRatio.GetXaxis().GetXmax(), 1.)
    line1.SetLineStyle(2)
    line1.SetLineWidth(2)

    name = hEGamma.GetName()
    name = name + ".pdf"
    c.Print(name)
Ejemplo n.º 10
0
text = TLatex()
text.SetTextSize(0.04)
text.SetTextColor(1)

h.Draw()

text.SetTextSize(0.04)
text.SetTextColor(kGreen - 6)
text.DrawLatex(5., 0.18, "Null-Hypothesis (background-only):  #lambda_{b} = 4")
text.SetTextColor(1)
text.DrawLatex(5.6, 0.144, "Observation d = 7")
text.SetTextColor(4)
text.SetTextSize(0.06)
text.DrawLatex(7.8, 0.048, "#alpha")

g.Draw("lf,same")
a.Draw("lf,same")
fga.Draw("l,same")
falt.Draw("l,same")

text.SetTextColor(kOrange)
text.DrawLatex(6, 0.012, "#beta")
text.SetTextColor(kRed)
text.SetTextSize(0.04)
text.DrawLatex(10.8, 0.121, "Alternative hypothesis: #lambda_{s+b} = 15")
text.DrawLatex(12, 0.11, "(signal + background)")
line.DrawLine(7, 0.14, 7, 0.0)
gPad.RedrawAxis()

c1.SaveAs("bgd_plus_s_py.pdf")
Ejemplo n.º 11
0
def drawCorrEvolution(detector,
                      labelList,
                      drawErrors=False,
                      drawLine=True,
                      whichdof=-1,
                      outputFormat=1):
    from ROOT import TCanvas
    from ROOT import TH1F
    from ROOT import gPad
    from ROOT import TLegend
    from ROOT import TLine
    import time
    import os
    #check with environment variable if server runs as local test
    runLocalTest = False
    try:
        runLocalTest = os.getenv('RUNLOCALTEST', False)
    except:
        runLocalTest = False

    doDebug = True
    showErrors = True
    drawAllDofs = True
    nUsedDofs = 7

    if (whichdof != -1):
        drawAllDofs = False
        if (whichdof > 5):
            nUsedDofs = 7  # 7/oct/2015 with the BowX we may have up to 7 dofs. Unless stated draw the ordinary 6.

    lowerDof = 0
    upperDof = 6

    if (not drawAllDofs):
        lowerDof = whichdof
        upperDof = whichdof

    # output formats
    ALLINONE = 1
    ONEBYONE = 2
    SPLITBYSTRUCT = 3

    Alldetector = {}  # list of canvas
    finalName = ["", "", "", "", "", "", ""]  #name of the output files

    gridALLENTRIES = 1
    gridNEWRUN = 2
    xGridType = gridNEWRUN

    #
    pathfiles = "."
    if (runLocalTest):
        pathfiles = "/Users/martis/projectes/atlas/alineament/webmonitoringtest/InDetAlignmentWebMonitor/trunk/WebPage/constant/"

    plotfile = {}

    rootSetup()

    # -- start the body of the code --
    if (doDebug):
        print "\n -- drawCorrEvolution -- START -- \n"
        print "              runLocalTest= ", runLocalTest
        print "                 pathfiles= ", pathfiles
        print "              outputFormat= ", outputFormat

    # list of the histograms
    hCorrectionsEvol = {}
    hCorrectionsEvolStruct = {}
    # min axis range for each dof
    #         Tx     Ty     Tz     Rx    Ry    Rz    Bx
    yrange = [0.002, 0.002, 0.002, 0.01, 0.01, 0.01,
              0.002]  # minimum is 0.001 (mm or mrad)

    # here detector = num of iterations
    numberOfSamples = len(detector)
    if (doDebug):
        print " -- drawCorrEvolution -- numberOfSamples=", numberOfSamples
    numOfAlignableStruct = detector[0].nModules()
    if (doDebug): print " numOfAlignableStructe=", numOfAlignableStruct
    EvolColor = AutoColors(numOfAlignableStruct)

    # a canvas for all dofs
    ThisCanvas = TCanvas("AlignmentCorrectionsEvol",
                         "Evolution of alignment corrections (All)", 920, 600)
    if (drawAllDofs and outputFormat == ALLINONE): ThisCanvas.Divide(3, 2)

    # find out range
    #for i in range(lowerDof, upperDof):
    for i in range(nUsedDofs):
        for iter in range(numberOfSamples):
            for bin in range(detector[iter].nModules()):
                thisValue = abs(detector[iter].GetModule(bin).GetDoF(
                    i)[1]) + detector[iter].GetModule(bin).GetDoFError(i)[1]
                if abs(thisValue) > yrange[i]:
                    yrange[i] = thisValue
        yrange[i] *= 1.025
        if (doDebug): print " dof=", i, " --> range: ", yrange[i]

    #
    #  --- Y range of the plots --- cap the drawing range
    # maximum range
    maxTransRange = 0.100
    if (yrange[0] > maxTransRange): yrange[0] = maxTransRange
    if (yrange[1] > maxTransRange): yrange[1] = maxTransRange
    if (yrange[2] > maxTransRange): yrange[2] = maxTransRange
    if (yrange[6] > maxTransRange): yrange[6] = maxTransRange  #Bx

    # Tx and Ty should have the same range
    if (yrange[0] > yrange[1]):
        yrange[1] = yrange[0]
    else:
        yrange[0] = yrange[1]
    # Tz range should be as minimum as Tx and Ty
    if (yrange[2] < yrange[0]): yrange[2] = yrange[0]

    #Bx range --> keep it independent

    # Rx and Ry should have the same range
    if (yrange[3] > yrange[4]):
        yrange[4] = yrange[3]
    else:
        yrange[3] = yrange[4]

    # Rz keep it independent

    #yrange[0] = 0.004
    yrange[1] = 0.0065
    #yrange[2] = 0.040
    #yrange[3] = 0.04
    #yrange[4] = 0.04
    #yrange[5] = 0.06
    yrange[6] = 0.0025

    #
    # prepare the legend
    #
    myLegend = TLegend(0.80, 0.85, 0.99, 0.99)
    myLegend.SetFillColor(0)  # white
    # and a line to split the runs if xGridType = gridNEWRUN
    myGridLine = TLine()
    myGridLine.SetLineStyle(3)

    # loop dof by dof (Tx, Ty...) and fill a polyline with teh corrections for each iteration
    if (doDebug):
        print " -- drawCorrEvolution -- going to draw form lowerDof=", lowerDof, " to upperDof = ", upperDof

    #for dof in range(nUsedDofs):
    for dof in range(lowerDof, upperDof + 1):
        #for dof in range(lowerDof, 6):
        # extract dof name
        name = detector[0].GetModule(0).GetDoF(dof)[0]
        if (doDebug):
            print "\n -- drawCorrEvolution -- going to draw dof= %d (%s)" % (
                dof, name)

        #dealing with canvases
        if (outputFormat == ALLINONE):
            ThisCanvas.cd()
            if (drawAllDofs):
                ThisCanvas.cd(dof + 1)
        if (outputFormat == ONEBYONE):
            Alldetector[dof] = {}
            Alldetector[dof] = TCanvas(
                "AlignCorrectionsEvol_%s" % (name),
                "Alignment_corrections_evolution_%s" % (name), 920, 600)
            print " -- drawCorrEvolution -- new canvas declared %s" % Alldetector[
                dof].GetName()
        if (outputFormat == SPLITBYSTRUCT):
            Alldetector[dof] = {}
            Alldetector[dof] = TCanvas(
                "AlignCorrectionsEvol_%s_byDOF" % (name),
                "Alignment_corrections_evolution_%s_byDOF" % (name), 920, 600)
            if (numOfAlignableStruct >= 15):
                Alldetector[dof].Divide(5, 3)
                print " -- drawCorrEvolution -- Divide (5x3)"
            print " -- drawCorrEvolution -- new canvas declared %s for %d structures" % (
                Alldetector[dof].GetName(), numOfAlignableStruct)

        # prepare the histogram that will store the corrections
        hname = 'Dof_%s_corrections_Evol' % (name)
        htitle = 'Evolution of %s corrections' % (name)
        htitle = 'Evolution of d%s/dLB corrections' % (name)
        if (doDebug):
            print " -- drawCorrEvolution -- dof= %d  hname= %s" % (dof, hname)
            print "                                 htitle= ", htitle

        # build the histogram that is the main frame to plot the corrections for this dof (evolution of dof for each sample)
        hCorrectionsEvol[dof] = TH1F(
            hname, htitle, numberOfSamples - 1, -0.5,
            numberOfSamples * 1. - 1.5)  # the last sample is the accumulation

        # set the x axis labels
        hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.05)
        if (numberOfSamples > 8):  # this is in case there are too many
            hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.04)
            hCorrectionsEvol[dof].GetXaxis().SetBit(18)
            if (numberOfSamples > 16):  # reduce further the size
                hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.03)
            if (numberOfSamples > 24):  # reduce further the size
                hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.02)
        hCorrectionsEvol[dof].GetXaxis().SetLabelSize(0.05)
        hCorrectionsEvol[dof].GetYaxis().SetLabelSize(0.05)

        for iter in range(numberOfSamples):
            hCorrectionsEvol[dof].GetXaxis().SetBinLabel(
                iter + 1, 'Iter_%d' % (iter))
            if (len(labelList) > iter):  # use label given by user
                hCorrectionsEvol[dof].GetXaxis().SetBinLabel(
                    iter + 1, labelList[iter])

        # label of the Y axis
        if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx':
            hCorrectionsEvol[dof].SetYTitle("mm")
            hCorrectionsEvol[dof].SetYTitle("dTy/dLB [mm/25LB]")
        else:
            hCorrectionsEvol[dof].SetYTitle("mrad")

        # set the range
        hCorrectionsEvol[dof].GetYaxis().SetRangeUser(-yrange[dof],
                                                      yrange[dof])
        hCorrectionsEvol[dof].SetStats(False)
        # going to draw the frame
        # -be ware, in case of drawing by structure need to change to the right pad
        if (outputFormat == ALLINONE or outputFormat == ONEBYONE):
            hCorrectionsEvol[dof].DrawCopy()
            gPad.SetGridy()
            if (xGridType == gridALLENTRIES): gridPad.SetGridx()

        # draw the frame
        #hCorrectionsEvol[dof].DrawCopy()
        #gPad.SetGridx()
        #gPad.SetGridy()

        #
        # once the frame is plotted, loop on every structure and fill a histogram and draw it
        #
        if (doDebug):
            print "  -- drawCorrEvolution --  dealing with", name, "corrections. Y range for this dof: (", dof, ")   range: +-", yrange[
                dof]
            print "                           reminder: numOfAlignableStruct = ", numOfAlignableStruct

        #for struct in range(numOfAlignableStruct):
        for struct in range(2):
            if (doDebug and False): print " >> looping on struct:", struct
            if (outputFormat == SPLITBYSTRUCT):
                Alldetector[dof].cd(struct + 1)
                # then draw frame
                hCorrectionsEvol[dof].DrawCopy()
                gPad.SetGridy()
                if (xGridType == gridALLENTRIES): gridPad.SetGridx()
            hCorrectionsEvolStruct[dof] = {}
            hname = 'Dof_%s_corrections_Evol_struct_%d' % (name, struct)
            htitle = 'Corrections evolution for structure %s (struct %d)' % (
                name, struct)
            hCorrectionsEvolStruct[dof][struct] = TH1F(
                hname, htitle, numberOfSamples - 1, -0.5,
                numberOfSamples * 1. -
                1.5)  # last point is for the accumulation --> do not show
            #print " -- drawCorrEvolution -- hCorrectionsEvolStruct has ",hCorrectionsEvolStruct[dof][struct].GetNbinsX(), ' bins in X'
            hCorrectionsEvolStruct[dof][struct].SetLineColor(EvolColor[struct])
            hCorrectionsEvolStruct[dof][struct].SetStats(False)
            # once the histogram is created, fill it with the corrections of each iteration

            currentLabel = "000000"  # dummy value
            for iterval in range(numberOfSamples):
                value = detector[iterval].GetModule(struct).GetDoF(dof)[1]

                # derivatives
                if (iterval == 0): value = 0
                if (iterval > 0):
                    value = (
                        detector[iterval].GetModule(struct).GetDoF(dof)[1] -
                        detector[iterval - 1].GetModule(struct).GetDoF(dof)[1])
                print " iterval ", iterval, "   dx=", value, "   +-", detector[
                    iterval].GetModule(struct).GetDoFError(dof)[1]
                hCorrectionsEvolStruct[dof][struct].SetBinContent(
                    iterval + 1, value)
                if (drawErrors):
                    hCorrectionsEvolStruct[dof][struct].SetBinError(
                        iterval + 1, detector[iterval].GetModule(
                            struct).GetDoFError(dof)[1])
                # check the label in case it needs to be marked
                if (xGridType == gridNEWRUN and len(labelList) > 0
                        and iterval < len(labelList)):
                    thisLabel = labelList[iterval]
                    if (thisLabel != currentLabel and "LB" in thisLabel):
                        # new run found
                        currentLabel = thisLabel
                        #print " thisLabel = ", thisLabel,"  iterval = ",iterval
                        myGridLine.DrawLine(iterval, -yrange[dof], iterval,
                                            yrange[dof])

            # now draw the corrections for this structure
            if (drawErrors):
                hCorrectionsEvolStruct[dof][struct].SetFillColor(
                    EvolColor[struct])
                hCorrectionsEvolStruct[dof][struct].SetFillStyle(3354)
                # hCorrectionsEvolStruct[dof][struct].DrawCopy('same e3')
                # --> original hCorrectionsEvolStruct[dof][struct].DrawCopy('same e3')
                hCorrectionsEvolStruct[dof][struct].SetMarkerStyle(20)
                hCorrectionsEvolStruct[dof][struct].SetMarkerSize(0.5)
                hCorrectionsEvolStruct[dof][struct].SetMarkerColor(
                    EvolColor[struct])
                hCorrectionsEvolStruct[dof][struct].DrawCopy('same p e3 x0')
                for iterval in range(numberOfSamples):
                    hCorrectionsEvolStruct[dof][struct].SetBinError(
                        iterval + 1, 0)
                hCorrectionsEvolStruct[dof][struct].SetFillStyle(0)
                hCorrectionsEvolStruct[dof][struct].DrawCopy('l x0 e3 same')

            else:
                myOption = "same"
                if (drawLine):
                    myOption += " l"
                else:
                    myOption += " p"
                    hCorrectionsEvolStruct[dof][struct].SetMarkerStyle(20)
                    hCorrectionsEvolStruct[dof][struct].SetMarkerColor(
                        EvolColor[struct])

                hCorrectionsEvolStruct[dof][struct].DrawCopy(myOption)
            gPad.Update()
            #if (dof == 0 and True):
            if (True):
                if (dof == 0):
                    myLegend.AddEntry(hCorrectionsEvolStruct[dof][struct],
                                      detector[0].GetModule(struct).GetName(),
                                      "l")
                myLegend.Draw()
                gPad.Update()

        t = time.time()
        finalName[dof] = "%f_evolution_%s" % (t, name)
        gPad.Update()
        if (outputFormat == ONEBYONE or outputFormat == SPLITBYSTRUCT):
            #print " -- drawCorrEvol -- saving plots from ONEBYONE "
            Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".png", "png")
            Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".pdf", "pdf")
            #Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".root", "root")
            #Alldetector[dof].SaveAs(pathfiles + finalName[dof] + ".C", "C")

    if (outputFormat == ALLINONE):
        #print " -- drawCorrEvol -- saving plots from ALLINONE "
        t = time.time()
        myFinalName = "%f_evolution_dofs" % (t)
        ThisCanvas.SaveAs(pathfiles + myFinalName + ".png", "png")
        ThisCanvas.SaveAs(pathfiles + myFinalName + ".pdf", "pdf")
        plotfile['png'] = {0: myFinalName + ".png"}
        plotfile['pdf'] = {0: myFinalName + ".pdf"}

    if (outputFormat == ONEBYONE or outputFormat == SPLITBYSTRUCT):
        plotfile['png'] = {
            0: finalName[0] + ".png",
            1: finalName[1] + ".png",
            2: finalName[2] + ".png",
            3: finalName[3] + ".png",
            4: finalName[4] + ".png",
            5: finalName[5] + ".png",
            6: finalName[6] + ".png"
        }
        plotfile['pdf'] = {
            0: finalName[0] + ".pdf",
            1: finalName[1] + ".pdf",
            2: finalName[2] + ".pdf",
            3: finalName[3] + ".pdf",
            4: finalName[4] + ".pdf",
            5: finalName[5] + ".pdf",
            6: finalName[6] + ".pdf"
        }

    #return plotfile
    return ThisCanvas
Ejemplo n.º 12
0
def plot(pad,
         w,
         pdfname,
         dsetname,
         resid=False,
         cat=None,
         popts=None,
         dopts=None):

    if cat:
        if cat.startswith('b0_'): cat = cat.replace('b0_', '')
        if cat.startswith('bs_'): cat = cat.replace('bs_', '')

    xtitle = {
        'b0g': '#it{m}(' + rt.Dzb + rt.g + rt.Kp + rt.pim + ') [MeV/c^{2}]',
        'b0pi0':
        '#it{m}(' + rt.Dzb + rt.piz + rt.Kp + rt.pim + ') [MeV/c^{2}]',
        'bsg': '#it{m}(' + rt.Dzb + rt.g + rt.Km + rt.pip + ') [MeV/c^{2}]',
        'bspi0': '#it{m}(' + rt.Dzb + rt.piz + rt.Km + rt.pip + ') [MeV/c^{2}]'
    }
    leg = {
        'b0g':
        '#it{B}^{0} #rightarrow #bar{#it{D}}^{0}#it{#gamma}#it{K}^{+}#it{#pi}^{-}',
        'b0pi0':
        '#it{B}^{0} #rightarrow #bar{#it{D}}^{0}#it{#pi}^{0}#it{K}^{+}#it{#pi}^{-}',
        'bsg':
        '#it{B_{s}}^{#kern[-0.2]{0}} #rightarrow #bar{#it{D}}^{0}#it{#gamma}#it{K}^{-}#it{#pi}^{+}',
        'bspi0':
        '#it{B_{s}}^{#kern[-0.2]{0}} #rightarrow #bar{#it{D}}^{0}#it{#pi}^{0}#it{K}^{-}#it{#pi}^{+}'
    }

    if not popts: popts = RooLinkedList()
    if not dopts: dopts = RooLinkedList()

    pl = w.var('B_DTFDict_D0_B_M').frame()
    if cat: pl.GetXaxis().SetTitle(xtitle[cat])
    if w.data(dsetname): w.data(dsetname).plotOn(pl, dopts)
    if w.pdf(pdfname): w.pdf(pdfname).plotOn(pl, popts)
    if resid and w.data(dsetname) and w.pdf(pdfname):
        pu = TPad(pad.GetName() + '_pu', '', 0., 0.33, 1., 1.)
        pd = TPad(pad.GetName() + '_pd', '', 0., 0., 1., 0.33)
        pu.SetBottomMargin(0.03)
        pd.SetTopMargin(0.03)
        pd.SetBottomMargin(0.35)
        pad.cd()
        pu.Draw()
        pd.Draw()
        pu.cd()
        pl.GetYaxis().SetTitleOffset(1.1)
        pl.GetXaxis().SetLabelSize(0.)
        pl.Draw()
        pd.cd()
        pull = pl.pullHist()
        # roofit does something funny with pull hist range so need a dummy hist for it
        pull.Draw()
        ymax = max(abs(pull.GetYaxis().GetXmin()), pull.GetYaxis().GetXmax())
        pulld = TH1F(pull.GetName() + '_pd', '', pl.GetNbinsX(),
                     pl.GetXaxis().GetXmin(),
                     pl.GetXaxis().GetXmax())
        pulld.GetYaxis().SetRangeUser(-ymax, ymax)
        pulld.GetXaxis().SetTitle(pl.GetXaxis().GetTitle())
        pulld.GetYaxis().SetTitle("Pull")
        pl.GetXaxis().SetTitle("")
        pulld.GetXaxis().SetTitleSize(0.13)
        pulld.GetYaxis().SetTitleSize(0.13)
        pulld.GetXaxis().SetLabelSize(0.13)
        pulld.GetYaxis().SetLabelSize(0.13)
        pulld.GetXaxis().SetTitleOffset(1.1)
        pulld.GetYaxis().SetTitleOffset(0.6)
        pulld.GetYaxis().SetNdivisions(505)
        pulld.GetXaxis().SetTickLength(0.06)
        ll = TLine()
        ll.SetLineWidth(4)
        ll.SetLineColor(4)
        pd.cd()
        pd.Clear()
        pulld.Draw("HIST")
        pull.Draw("EPsame")
        ll.DrawLine(pulld.GetXaxis().GetXmin(), 0.,
                    pulld.GetXaxis().GetXmax(), 0.)
        pulld.Draw("AXISsame")
        gROOT.Append(pulld)
    else:
        pad.cd()
        pl.Draw()

    pad.cd()
    if cat:
        lat = TLatex()
        lat.SetTextSize(0.05)
        lat.SetNDC()
        lat.DrawLatex(0.6, 0.8, leg[cat])
        gROOT.Append(lat)
    pad.Update()
    pad.Modified()
Ejemplo n.º 13
0
def plotData(pad, w, pdfname, dsetname, resid=False, cat=None, log=False):

    if cat.startswith('b0_'): cat = cat.replace('b0_', '')
    if cat.startswith('bs_'): cat = cat.replace('bs_', '')

    xtitle = {
        'b0g': '#it{m}(' + rt.Dzb + rt.g + rt.Kp + rt.pim + ') [MeV/c^{2}]',
        'b0pi0':
        '#it{m}(' + rt.Dzb + rt.piz + rt.Kp + rt.pim + ') [MeV/c^{2}]',
        'bsg': '#it{m}(' + rt.Dzb + rt.g + rt.Km + rt.pip + ') [MeV/c^{2}]',
        'bspi0':
        '#it{m}(' + rt.Dzb + rt.piz + rt.Km + rt.pip + ') [MeV/c^{2}]',
        'cg': '#it{m}(' + rt.Dzb + rt.g + rt.pip + rt.pip + ') [MeV/c^{2}]',
        'cpi0': '#it{m}(' + rt.Dzb + rt.piz + rt.pim + rt.pip + ') [MeV/c^{2}]'
    }
    leg = {
        'b0g': {
            'sig': rt.Decay('Bd', 'Dzb', 'g', 'Kp', 'pim'),
            'misrec': rt.Decay('Bd', 'Dzb', 'piz', 'Kp', 'pim'),
            'bdstpp': rt.Decay('Bd', 'Dzb', 'g', 'pip', 'pim'),
            'bdstkk': rt.Decay('Bd', 'Dzb', 'g', 'Kp', 'Km'),
            'bsdstkk': rt.Decay('Bs', 'Dzb', 'g', 'Kp', 'Km'),
            'bdkp': rt.Decay('Bd', 'Dzb', 'Kp', 'pim'),
            'bdsth': rt.Decay('Bm', 'Dzb', 'g', 'pim'),
            'partrec': 'Part Reco',
            'lbdph': rt.Decay('Lb', 'Dzb', 'p', 'pim'),
            'lbdstph': rt.Decay('Lb', 'Dzb', 'g', 'p', 'pim'),
            'comb': 'Combinatorial'
        },
        'b0pi0': {
            'sig': rt.Decay('Bd', 'Dzb', 'piz', 'Kp', 'pim'),
            'misrec': rt.Decay('Bd', 'Dzb', 'g', 'Kp', 'pim'),
            'bdstpp': rt.Decay('Bd', 'Dzb', 'piz', 'pip', 'pim'),
            'bdstkk': rt.Decay('Bd', 'Dzb', 'piz', 'Kp', 'Km'),
            'bsdstkk': rt.Decay('Bs', 'Dzb', 'piz', 'Kp', 'Km'),
            'bdkp': rt.Decay('Bd', 'Dzb', 'Kp', 'pim'),
            'bdsth': rt.Decay('Bm', 'Dzb', 'piz', 'pim'),
            'partrec': 'Part Reco',
            'lbdph': rt.Decay('Lb', 'Dzb', 'p', 'pim'),
            'lbdstph': rt.Decay('Lb', 'Dzb', 'piz', 'p', 'pim'),
            'comb': 'Combinatorial'
        },
        'bsg': {
            'sig': rt.Decay('Bs', 'Dzb', 'g', 'Km', 'pip'),
            'misrec': rt.Decay('Bs', 'Dzb', 'piz', 'Km', 'pip'),
            'bdstpp': rt.Decay('Bs', 'Dzb', 'g', 'pim', 'pip'),
            'bdstkk': rt.Decay('Bs', 'Dzb', 'g', 'Km', 'Kp'),
            'bsdstkk': rt.Decay('Bs', 'Dzb', 'g', 'Km', 'Kp'),
            'bdkp': rt.Decay('Bs', 'Dzb', 'Km', 'pip'),
            'bdsth': rt.Decay('Bp', 'Dzb', 'g', 'pip'),
            'partrec': 'Part Reco',
            'lbdph': rt.Decay('Lb', 'Dzb', 'p', 'Km'),
            'lbdstph': rt.Decay('Lb', 'Dzb', 'g', 'p', 'Km'),
            'comb': 'Combinatorial'
        },
        'bspi0': {
            'sig': rt.Decay('Bs', 'Dzb', 'piz', 'Km', 'pip'),
            'misrec': rt.Decay('Bs', 'Dzb', 'g', 'Km', 'pip'),
            'bdstpp': rt.Decay('Bs', 'Dzb', 'piz', 'pim', 'pip'),
            'bdstkk': rt.Decay('Bs', 'Dzb', 'piz', 'Km', 'Kp'),
            'bsdstkk': rt.Decay('Bs', 'Dzb', 'piz', 'Km', 'Kp'),
            'bdkp': rt.Decay('Bs', 'Dzb', 'Km', 'pip'),
            'bdsth': rt.Decay('Bp', 'Dzb', 'piz', 'pip'),
            'partrec': 'Part Reco',
            'lbdph': rt.Decay('Lb', 'Dzb', 'p', 'Km'),
            'lbdstph': rt.Decay('Lb', 'Dzb', 'piz', 'p', 'Km'),
            'comb': 'Combinatorial'
        },
        'cg': {
            'sig': rt.Decay('Bd', 'Dzb', 'g', 'pip', 'pim'),
            'misrec': rt.Decay('Bd', 'Dzb', 'piz', 'pip', 'pim'),
            'bdstkp': rt.Decay('Bs', 'Dzb', 'g', 'Km', 'pip'),
            'bdkp': rt.Decay('Bd', 'Dzb', 'Kp', 'pim'),
            'bdsth': rt.Decay('Bm', 'Dzb', 'g', 'pim'),
            'comb': 'Combinatorial'
        },
        'cpi0': {
            'sig': rt.Decay('Bd', 'Dzb', 'piz', 'pip', 'pim'),
            'misrec': rt.Decay('Bd', 'Dzb', 'g', 'pip', 'pim'),
            'bdstkp': rt.Decay('Bs', 'Dzb', 'piz', 'Km', 'pip'),
            'bdkp': rt.Decay('Bd', 'Dzb', 'Kp', 'pim'),
            'bdsth': rt.Decay('Bm', 'Dzb', 'piz', 'pim'),
            'comb': 'Combinatorial'
        },
    }

    pl = w.var('B_DTFDict_D0_B_M').frame()
    if cat: pl.GetXaxis().SetTitle(xtitle[cat])
    tleg = TLegend(0.6, 0.5, 0.9, 0.95)
    tleg.SetFillColorAlpha(0, 0.)
    tleg.SetLineColor(0)
    if w.data(dsetname):
        w.data(dsetname).plotOn(pl)
    if w.pdf(pdfname):
        w.pdf(pdfname).plotOn(pl)
        w.pdf(pdfname).plotOn(pl, rf.Components('comb_mc_pdf_%s' % cat),
                              rf.LineStyle(2), rf.LineColor(kBlack))
        tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1), leg[cat]['comb'],
                      "L")
        if cat != 'cg' and cat != 'cpi0':
            w.pdf(pdfname).plotOn(pl, rf.Components('partrec_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kRed + 3))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['partrec'], "L")
            w.pdf(pdfname).plotOn(pl, rf.Components('lbdph_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kMagenta))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['lbdph'], "L")
            w.pdf(pdfname).plotOn(pl, rf.Components('lbdstph_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kMagenta + 3))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['lbdstph'], "L")
        w.pdf(pdfname).plotOn(pl, rf.Components('bdsth_mc_pdf_%s' % cat),
                              rf.LineStyle(2), rf.LineColor(kRed - 3))
        tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1), leg[cat]['bdsth'],
                      "L")
        if cat != 'cg' and cat != 'cpi0':
            w.pdf(pdfname).plotOn(pl, rf.Components('bdkp_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kOrange - 3))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['bdkp'], "L")
            w.pdf(pdfname).plotOn(pl, rf.Components('bsdstkk_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kGreen + 1))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['bsdstkk'], "L")
            w.pdf(pdfname).plotOn(pl, rf.Components('bdstkk_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kGreen + 3))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['bdstkk'], "L")
            w.pdf(pdfname).plotOn(pl, rf.Components('bdstpp_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kRed))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['bdstpp'], "L")
        else:
            w.pdf(pdfname).plotOn(pl, rf.Components('bdstkp_mc_pdf_%s' % cat),
                                  rf.LineStyle(2), rf.LineColor(kOrange - 3))
            tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1),
                          leg[cat]['bdstkp'], "L")
        w.pdf(pdfname).plotOn(pl, rf.Components('misrec_mc_pdf_%s' % cat),
                              rf.LineStyle(2), rf.LineColor(kCyan))
        tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1), leg[cat]['misrec'],
                      "L")
        w.pdf(pdfname).plotOn(pl, rf.Components('sig_mc_pdf_%s' % cat),
                              rf.LineStyle(2), rf.LineColor(kBlue + 3))
        tleg.AddEntry(pl.getObject(int(pl.numItems()) - 1), leg[cat]['sig'],
                      "L")
        w.pdf(pdfname).plotOn(pl)
    if resid and w.data(dsetname) and w.pdf(pdfname):
        pu = TPad(pad.GetName() + '_pu', '', 0., 0.33, 1., 1.)
        pd = TPad(pad.GetName() + '_pd', '', 0., 0., 1., 0.33)
        pu.SetBottomMargin(0.03)
        pd.SetTopMargin(0.03)
        pd.SetBottomMargin(0.35)
        pad.cd()
        pu.Draw()
        pd.Draw()
        pu.cd()
        pl.GetYaxis().SetTitleOffset(1.1)
        pl.GetXaxis().SetLabelSize(0.)
        pl.Draw()
        if log:
            pl.GetYaxis().SetRangeUser(0.1, 2. * pl.GetMaximum())
            pl.Draw()
            pu.SetLogy()
        pd.cd()
        pull = pl.pullHist()
        # roofit does something funny with pull hist range so need a dummy hist for it
        pull.Draw()
        ymax = max(abs(pull.GetYaxis().GetXmin()), pull.GetYaxis().GetXmax())
        pulld = TH1F(pull.GetName() + '_pd', '', pl.GetNbinsX(),
                     pl.GetXaxis().GetXmin(),
                     pl.GetXaxis().GetXmax())
        pulld.GetYaxis().SetRangeUser(-ymax, ymax)
        pulld.GetXaxis().SetTitle(pl.GetXaxis().GetTitle())
        pulld.GetYaxis().SetTitle("Pull")
        pl.GetXaxis().SetTitle("")
        pulld.GetXaxis().SetTitleSize(0.13)
        pulld.GetYaxis().SetTitleSize(0.13)
        pulld.GetXaxis().SetLabelSize(0.13)
        pulld.GetYaxis().SetLabelSize(0.13)
        pulld.GetXaxis().SetTitleOffset(1.1)
        pulld.GetYaxis().SetTitleOffset(0.6)
        pulld.GetYaxis().SetNdivisions(505)
        pulld.GetXaxis().SetTickLength(0.06)
        ll = TLine()
        ll.SetLineWidth(4)
        ll.SetLineColor(4)
        pd.cd()
        pd.Clear()
        pulld.Draw("HIST")
        pull.Draw("EPsame")
        ll.DrawLine(pulld.GetXaxis().GetXmin(), 0.,
                    pulld.GetXaxis().GetXmax(), 0.)
        pulld.Draw("AXISsame")
        gROOT.Append(pulld)
    else:
        pad.cd()
        pl.Draw()
        if log:
            pl.GetYaxis().SetRangeUser(0.1, 2 * pl.GetMaximum())
            pl.Draw()
            pad.SetLogy()

    gROOT.Append(tleg)
    pad.cd()
    if not log: tleg.Draw("same")
    pad.Update()
    pad.Modified()
Ejemplo n.º 14
0
arrow.DrawArrow(5, 17, 17, 17, 0.02, '|>')
line = TLine(5, 19, 5, 17)
line.SetLineWidth(2)
line.Draw()
key0 = TPaveText(7, 16, 10, 18)
key0.SetTextSize(0.04)
key0.SetFillColor(keycolor)
key0.AddText('Key 0')
key0.Draw()
key1 = TPaveText(12, 16, 15, 18)
key1.SetTextSize(0.04)
key1.SetFillColor(keycolor)
key1.AddText('Key 1')
key1.Draw()
line.DrawLine(3, 19, 3, 14)
line.DrawLine(3, 14, 18, 14)
obj0 = TPaveText(5, 13, 8, 15)
obj0.SetFillColor(objcolor)
obj0.AddText('Object')
obj0.Draw()
dir1 = TPaveText(10, 13, 13, 15)
dir1.SetFillColor(dircolor)
dir1.AddText('SubDir')
dir1.Draw()
obj1 = TPaveText(15, 13, 18, 15)
obj1.SetFillColor(objcolor)
obj1.AddText('Object')
obj1.Draw()
arrow.DrawArrow(12, 11, 17, 11, 0.015, '|>')
arrow.DrawArrow(11, 9, 17, 9, 0.015, '|>')
Ejemplo n.º 15
0
def plot_dir(dlist,
             binfo,
             outfile,
             prefix,
             infix,
             color=[kBlack],
             legend=[],
             norm=False):
    c = TCanvas()
    c.SetGrid(0)
    bnarr = binfo.keys()
    bnarr.sort()
    bncode = reduce(lambda x, y: x + y, bnarr)
    namex = bnarr[-2]
    namey = bnarr[-1]
    xarr = binfo[namex]
    yarr = binfo[namey]

    c.GetPad(0).SetMargin(0.2, 0.15, 0.2, 0.15)
    c.Divide(len(xarr) - 1, len(yarr) - 1, 0.0, 0.0)
    #CanvasPartition(c,len(xarr)-1,len(yarr)-1)
    Ntot = 1
    for k in range(len(bnarr) - 2):
        Ntot *= len(binfo[bnarr[k]]) - 1

    for k in range(Ntot):
        indarr = []
        fact = 1
        for n in range(len(bnarr) - 2):
            edg = binfo[bnarr[n]]
            indarr.append((k / fact) % (len(edg) - 1))
            fact *= len(binfo[bnarr[n]]) - 1

        for j in range(len(yarr) - 1, 0, -1):
            YMAX = -100000000.
            YMIN = 100000000.
            row = j
            for i in range(len(xarr) - 1):
                col = i + 1
                bcode = reduce(lambda x, y: str(x) + str(y), indarr)
                bcode = str(bcode) + str(col - 1) + str(row - 1)
                cnt = 0
                for d in dlist:
                    h = d.Get(prefix[cnt] + bncode + "_" + bcode)
                    maxb = h.GetMaximumBin()
                    minb = h.GetMinimumBin()
                    ymaxtest = h.GetBinContent(maxb)
                    ymintest = h.GetBinContent(minb)
                    #                    if True:
                    #                        print "before::" + d.GetPath() + "/" + h.GetName() + "::row::" + str(row) + ":: ymax / integral / bin / content(bin): " + str(ymaxtest) + " / " + str(h.Integral()) + " / " + str( maxb) +  " / " + str( h.GetBinContent(maxb))
                    if norm and h.Integral() != 0:
                        ymaxtest = ymaxtest / h.Integral()
                        ymintest = ymintest / h.Integral()
                    if norm and h.Integral() == 0:
                        ymaxtest = 0
                        ymintest = 0
                    if ymaxtest > YMAX:
                        YMAX = ymaxtest
                    if ymintest < YMIN:
                        YMIN = ymintest
                    cnt += 1

#               if norm:
#                   print bncode + "::row::" + str(row) + "::ymax: " + str(YMAX)

            for i in range(len(xarr) - 1):
                col = i + 1

                pad = c.cd(col + (len(yarr) - 1 - row) * (len(xarr) - 1))
                pad.SetGridy(0)
                #pad.SetGridx(0)
                pad.SetTicks(0, 0)
                bcode = reduce(lambda x, y: str(x) + str(y), indarr)
                bcode = str(bcode) + str(col - 1) + str(row - 1)
                cnt = 0
                leg = TLegend(0.77, 0.64, 0.95, 0.89)
                leg.SetTextSize(0.15)

                for d in dlist:
                    h = d.Get(prefix[cnt] + bncode + "_" + bcode)
                    h.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1)
                    if "ac" in prefix[cnt] or "Acceptance" in d.GetPath():
                        h.GetYaxis().SetRangeUser(0, 1)
                    h.GetYaxis().SetLabelSize(0.15)
                    h.GetXaxis().SetLabelSize(0.1)
                    h.GetYaxis().SetLabelSize(0.15)
                    xtitle = str(
                        binfo[namex][col - 1]) + '<' + namex + '<' + str(
                            binfo[namex][col]) + "     " + prefix[cnt].split(
                                '_')[0][1:]
                    h.GetXaxis().SetTitle(xtitle)
                    h.GetXaxis().CenterTitle()
                    h.GetXaxis().SetTitleSize(0.12)
                    ytitle = str(
                        binfo[namey][row - 1]) + '<' + namey + '<' + str(
                            binfo[namey][row])
                    h.GetXaxis().SetNdivisions(505)
                    h.GetYaxis().SetNdivisions(505)
                    h.SetLineWidth(3)
                    h.SetLineColor(color[cnt])
                    h.SetMarkerColor(color[cnt])
                    if (legend != []):
                        le = leg.AddEntry(h, legend[cnt], 'lp')
                        le.SetTextColor(color[cnt])
                    if cnt == 0:
                        if not norm: h.DrawCopy()
                        elif (h.Integral() != 0):
                            hnorm = h.DrawNormalized("e")
                            hnorm.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1)
                        else:
                            h.DrawCopy()
                        if 'hM_' in h.GetName():
                            rhopeak = TLine(0.77, 0, 0.77, YMAX)
                            rhopeak.SetLineStyle(kDashed)
                            rhopeak.SetLineWidth(1)
                            rhopeak.SetLineColor(kRed)
                            rhopeak.DrawLine(0.77, 0, 0.77, YMAX)
                        pad.Update()
                        pt = pad.FindObject("title")
                        pt.SetX1NDC(0.15)
                        pt.SetTextSizePixels(12)
                        if col == len(xarr) - 1:
                            yaxis = TGaxis(pad.GetUxmax(), pad.GetUymin(),
                                           pad.GetUxmax(), pad.GetUymax(), 0,
                                           1, 1, "U+-")
                            yaxis.SetTitle(ytitle + "     ")
                            yaxis.SetTitleSize(0.12)
                            yaxis.SetTitleOffset(-0.25)
                            yaxis.SetName(h.GetName() + "_ax_y")
                            yaxis.Draw("")
                            pad.GetListOfPrimitives().Add(yaxis)
                            pad.Update()
                    else:
                        if not norm: h.DrawCopy("same")
                        elif (h.Integral() != 0):
                            hnorm = h.DrawNormalized("samee")
                            hnorm.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1)
                        else:
                            h.DrawCopy("samee")
                    cnt += 1
                if (legend != []):
                    leg.Draw()
                    pad.GetListOfPrimitives().Add(leg)
        outfile.cd()
        bcode = reduce(lambda x, y: str(x) + str(y), indarr)
        cncode = reduce(lambda x, y: x + y, bnarr[-3])
        c.Write("can_" + infix + "_" + str(cncode) + "_" + str(bcode),
                TObject.kOverwrite)
Ejemplo n.º 16
0
tree.AddText('fMaxVirtualSize')
tree.AddText('fEntries')
tree.AddText('fDimension')
tree.AddText('fSelectedRows')
tree.Draw()
farm = TPavesText(.01, 1.02, .15, 1.1, 9, 'tr')
tfarm = farm.AddText('CHAIN')
tfarm.SetTextSize(0.024)
farm.AddText('Collection')
farm.AddText('of Trees')
farm.Draw()
link = TLine(.15, .92, .80, .92)
link.SetLineWidth(2)
link.SetLineColor(1)
link.Draw()
link.DrawLine(.21, .87, .21, .275)
link.DrawLine(.23, .87, .23, .375)
link.DrawLine(.25, .87, .25, .775)
link.DrawLine(.41, .25, .41, -.025)
link.DrawLine(.43, .25, .43, .075)
link.DrawLine(.45, .25, .45, .175)
branch0 = TPaveLabel(.20, .87, .35, .97, 'Branch 0')
branch0.SetTextSize(0.35)
branch0.SetFillColor(branchcolor)
branch0.Draw()
branch1 = TPaveLabel(.40, .87, .55, .97, 'Branch 1')
branch1.SetTextSize(0.35)
branch1.SetFillColor(branchcolor)
branch1.Draw()
branch2 = TPaveLabel(.60, .87, .75, .97, 'Branch 2')
branch2.SetTextSize(0.35)
Ejemplo n.º 17
0
def resComp(inFPath):
    """! 
    Plot two distributions on the same plot and also plot the ratio of the two. 
    The input file must have trees.
    """
    gROOT.SetBatch(True)
    gROOT.ForceStyle()
    setStyle()
    inF = TFile.Open(inFPath)
    tree = inF.Get('Ntuple')
    print tree.GetEntries()
    c = TCanvas('c', '', 800, 600)
    c.cd()
    pad = TPad("plotPad", "", 0, 0, 1, 1)
    pad.SetPad(0., 0.37, 1., 1.)
    pad.SetBottomMargin(0.02)
    pad.Draw()
    c.cd()
    ratioPad = TPad("ratioPad", "", 0., 0., 1., 1.)
    ratioPad.SetPad(0., 0.05, 1., 0.35)
    ratioPad.SetTopMargin(0.04)
    ratioPad.SetBottomMargin(0.3)
    ratioPad.Draw()
    refHists = {}
    compHists = {}
    ratioHists = {}

    for varName in compDict:
        pad.Clear()
        pad.SetLogy(False)
        ratioPad.Clear()
        refHistName = 'hist_' + varName.replace('[', '_').replace(
            ']', '_').replace('-', '_').replace('/', '_').replace(
                '(', '_').replace(')', '_')
        refHists[varName] = TH1F(refHistName, '', binning[varName][0],
                                 binning[varName][1], binning[varName][2])
        tree.Draw(varName + '>>' + refHistName)
        compHists[varName] = []
        ratioHists[varName] = []
        print varName, refHistName
        print refHists[varName].Integral()
        refHists[varName].Scale(1. / refHists[varName].Integral())
        maxY = refHists[varName].GetMaximum()
        for compVarI in range(len(compDict[varName])):
            compHistName = 'hist_' + compDict[varName][compVarI].replace(
                '[', '_').replace(']', '_').replace('-', '_').replace(
                    '/', '_').replace('(', '_').replace(')', '_')
            compHist = TH1F(compHistName, '', binning[varName][0],
                            binning[varName][1], binning[varName][2])
            tree.Draw(compDict[varName][compVarI] + '>>' + compHistName)
            compHists[varName].append(compHist)
            compHists[varName][compVarI].Scale(
                1. / compHists[varName][compVarI].Integral())

            if maxY < compHists[varName][compVarI].GetMaximum():
                maxY = compHists[varName][compVarI].GetMaximum()

        pad.Clear()
        refHists[varName].SetTitle('')
        refHists[varName].SetMaximum(1.2 * maxY)
        refHists[varName].Draw()
        unitsStr = ''
        if varNamesUnits[varName][1] != '':
            unitsStr = ' [' + varNamesUnits[varName][1] + ']'
        refHists[varName].GetXaxis().SetTitle(varNamesUnits[varName][0] +
                                              unitsStr)
        binSize = refHists[varName].GetBinLowEdge(
            2) - refHists[varName].GetBinLowEdge(1)
        roundTo = -int(math.floor(math.log10(abs(binSize))))
        roundedBinSize = round(binSize, roundTo)
        if roundTo < 0:
            binSizeStr = "%d" % roundedBinSize
        else:
            binSizeStr = "{0:.{1}f}".format(roundedBinSize, roundTo)
        yLabel = "1/N dN/(%s) [%s %s]^{-1}" % (
            varNamesUnits[varName][0], binSizeStr, varNamesUnits[varName][1])

        refHists[varName].GetYaxis().SetTitle(yLabel)

        ratioPad.Clear()
        for compVarI in range(len(compDict[varName])):
            pad.cd()
            compHists[varName][compVarI].SetLineColor(compVarI + 2)
            compHists[varName][compVarI].SetMarkerColor(compVarI + 2)
            compHists[varName][compVarI].Draw('same')
            ratioPad.cd()

            ratioHists[varName].append(refHists[varName].Clone())
            ratioHists[varName][compVarI].GetYaxis().SetTitleOffset(0.4)
            ratioHists[varName][compVarI].GetYaxis().SetDecimals(True)
            ratioHists[varName][compVarI].GetYaxis().CenterTitle(True)
            ratioHists[varName][compVarI].Divide(compHists[varName][compVarI])
            ratioHists[varName][compVarI].SetMaximum(2)
            ratioHists[varName][compVarI].SetMinimum(0.)
            ratioHists[varName][compVarI].GetYaxis().SetTitleSize(
                compHists[varName][compVarI].GetXaxis().GetTitleSize() * 2.1)
            ratioHists[varName][compVarI].GetXaxis().SetTitleSize(
                compHists[varName][compVarI].GetYaxis().GetTitleSize() * 2.1)

            ratioHists[varName][compVarI].GetYaxis().SetLabelSize(
                compHists[varName][compVarI].GetXaxis().GetLabelSize() * 2.1)
            ratioHists[varName][compVarI].GetXaxis().SetLabelSize(
                compHists[varName][compVarI].GetYaxis().GetLabelSize() * 2.1)
            ratioHists[varName][compVarI].GetYaxis().SetTitle('Reco/NN')

            ratioHists[varName][compVarI].SetLineColor(compVarI + 2)
            ratioHists[varName][compVarI].SetMarkerColor(compVarI + 2)
            if compVarI == 0:
                ratioHists[varName][compVarI].Draw()
            else:
                ratioHists[varName][compVarI].Draw('same')
            line = TLine()
            line.DrawLine(refHists[varName].GetXaxis().GetXmin(), 1,
                          refHists[varName].GetXaxis().GetXmax(), 1)
            line.SetLineWidth(1)
            line.SetLineStyle(2)
            line.SetLineColor(1)
            c.cd()
            leg = CompLegend((0.2, 0.8, 0.4, 0.9),
                             [refHists[varName]] + compHists[varName],
                             [compDictNames[varName]] + [
                                 compDictNames[compVarName]
                                 for compVarName in compDict[varName]
                             ])
            leg.Draw('same')
            c.Print(
                varName.replace('/', '_').replace('[', '_').replace(']', '_').
                replace('(', '').replace(')', '').rstrip('_').lstrip('_') +
                '.pdf')
            pad.SetLogy()
            refHists[varName].SetMaximum(10 * maxY)
            c.Print(
                varName.replace('/', '_').replace('[', '_').replace(']', '_').
                replace('(', '').replace(')', '').rstrip('_').lstrip('_') +
                '_log.pdf')
Ejemplo n.º 18
0
    leg.AddEntry(hC, "Z#rightarrowll")
    leg.AddEntry(hS, "Basic")
    leg.SetBorderSize(0)
    leg.Draw()
    os.system("mkdir -p plots/")
    c.SaveAs("plots/fakeTrkRate.pdf")
    c.Clear()
    c.SetLogy(0)
    hrat.SetLineColor(1)
    hrat.SetLineWidth(4)
    hrat.SetMarkerColor(1)
    hrat.SetMarkerStyle(21)
    hrat.Draw("pe x0")
    l = TLine()
    l.SetLineColor(2)
    l.DrawLine(2.5, 1.0, 6.5, 1.0)
    c.SaveAs("plots/fakeTrkRatio.pdf")

##################################################

###################################################
###################################################
###################################################

print "Finished running makeANTables.py"

print "Copy tables to AN area with: "
if user == "wulsin":
    print "scp tables/*tex [email protected]:/afs/cern.ch/user/w/wulsin/docs/cmsdocs/notes/AN-15-213/trunk/tables/"
    print "OR: "
    print "notes/AN-15-213/trunk> scp [email protected]:\"~/workdir76/tables/*tex\" tables/"
Ejemplo n.º 19
0
def main():

    cc.cd()
    cc.SetBorderMode(0)
    cc.SetFixedAspectRatio(1)
    cc.FeedbackMode(1)

    gStyle.SetOptStat(0)
    gStyle.SetGridStyle(0)
    gStyle.SetGridColor(18)

    nbinsX = 0
    for ix in range(len(SECTORSPERREGION)):
        nbinsX += SECTORSPERREGION[ix]
    hh = TH2D('hh', ';Strip;Sector', STRIPSPERSECTOR, 0, STRIPSPERSECTOR,
              nbinsX, 0, nbinsX)
    setupHists([hh])
    hh.Draw('COLZ')

    gPad.SetLogz()
    gPad.SetLeftMargin(0.09)
    gPad.SetRightMargin(0.11)

    tt2 = TPaveText(240, 43, 500, 45)
    ttime = TPaveText(100, -5.5, 412, -3)
    setupPaveTexts([tt2, ttime])
    tt2.SetTextSize(0.03)

    lll = TLine()
    lll.SetLineColor(15)
    y1 = SECTORSPERREGION[0]
    y2 = SECTORSPERREGION[0] + SECTORSPERREGION[1]
    lll.DrawLine(0, y1, STRIPSPERSECTOR, y1)
    lll.DrawLine(0, y2, STRIPSPERSECTOR, y2)

    tt = TText()
    tt.SetTextColor(1)
    tt.SetTextAngle(90)
    tt.SetTextSize(0.04)
    tt.DrawText(532, 22, 'Hz')
    tt.SetTextSize(0.06)
    tt.SetTextAngle(0)
    tt.SetTextColor(1)
    tt.DrawTextNDC(0.1, 0.93, 'SVT Scalers')

    tt.SetTextSize(0.03)
    tt.DrawText(-42, 4, 'R1')
    tt.DrawText(-42, 16, 'R2')
    tt.DrawText(-42, 32, 'R3')

    cc.cd()
    for xx in [ttime, tt2]:
        xx.Draw()
    cc.cd()

    gPad.SetEditable(0)

    while True:

        iy = 0
        for ch in SVT.chans:
            loadPV(ch)
            ch = ch.vals
            data = ch['PVVAL']
            time2 = ch['PVTIMEVAL']

            if time2 > 10:
                print 'More than 10 seconds since message:  ' + ch['PVNAME']
                for ii in range(512):
                    data[ii] = 0

            if iy < SECTORSPERREGION[0]:
                region = 1
                sector = iy
            elif iy < SECTORSPERREGION[0] + SECTORSPERREGION[1]:
                region = 2
                sector = iy - SECTORSPERREGION[0]
            else:
                region = 3
                sector = iy - SECTORSPERREGION[0] - SECTORSPERREGION[1]

            if data == None or len(data) != STRIPSPERSECTOR:
                print 'Error Reading ' + ch['PVNAME']
                continue
            for ix in range(STRIPSPERSECTOR):
                hh.SetBinContent(ix, iy + 1, data[ix])
            iy += 1

        for xx in [ttime, tt2]:
            xx.Clear()

        [r1, r2, r3] = calcRates(SVT.chans)
        tt2.AddText('Sums:  R1 / R2 / R3 = %.2E / %.2E / %.2E Hz' %
                    (r1, r2, r3))

        ttime.AddText(makeTime())

        if not gPad: sys.exit()

        cc.Modified()
        cc.Update()

        time.sleep(POLLPERIOD)
Ejemplo n.º 20
0
def draw():
      os.mkdir("plots/lowBDTOSFakes")
      hists_data=getHists("data","OneL2taulowBDTOS")
      hists_signal=getHists("tth","OneL2taulowBDTOS")
      for idy in range(len(variables)):
          variable=variables[idy]
          hist_data=hists_data[idy]
          hist_signal=hists_signal[idy]
          mchists=[]
          temps=[]
          for i in range(len(bkgs)):
              if bkgs[i]=='fakes' : temps=getHists(bkgs[i],"OneL2taulowBDTSS")
              else: temps=getHists(bkgs[i],"OneL2taulowBDTOStruth")
              mchists.append(temps[idy])
          hs=makeStack(mchists)
          h_bkg, h_ratio, h_ratio_err, upArrowBins= makeRatio(hist_data, mchists, hs)
          c, pad1, pad2=createCanvasPads()
          XTitle, YTitle=(titles[variable[0:len(variable)-2]])[0], (titles[variable[0:len(variable)-2]])[1]
          #stack plot
          pad1.cd()
          leg=TLegend(0.60,0.70,0.90,0.90)
          leg.SetNColumns(2)
          leg.SetFillStyle(0);
          leg.SetBorderSize(0);
          leg.AddEntry(hist_data, "data", "pe")
          leg.AddEntry(hist_signal, "tth", "l")
          for i in range(len(bkgs)):
              leg.AddEntry(mchists[i], bkgs[i], "f")
          leg.AddEntry(h_bkg,"uncertainty",'f')
          Ymaximum = 3.*hist_data.GetBinContent(hist_data.GetMaximumBin())
          hs.SetMaximum(Ymaximum)
          hs.SetMinimum(0.001)
          hs.SetTitle("")
          hs.Draw("hist") # thstack must draw first
          hs.GetYaxis().SetTitleSize(0.06)
          hs.GetYaxis().SetTitleOffset(1)
          hs.GetYaxis().SetTitle(YTitle)
          hs.GetXaxis().SetTitle("")
          hs.GetXaxis().SetTitleSize(0.)
          hs.GetXaxis().SetLabelSize(0.)
          h_bkg.Draw("E2 same")
          hist_data.SetMarkerStyle(20)
          hist_data.SetMarkerSize(0.8)
          hist_data.Draw("e x0 same")
          hist_signal.SetLineColor(kRed)
          hist_signal.SetLineStyle(kDashed)
          hist_signal.Scale(hist_data.Integral()/hist_signal.Integral()) #scale to data
          hist_signal.Draw("hist same")
          createLabels()
          leg.Draw("same")
          #ratio plot
          pad2.cd()
          h_ratio.SetMinimum(0.0)
          h_ratio.SetMaximum(2.0)
          h_ratio.GetYaxis().SetTitle("Data/Bkg")
          h_ratio.GetYaxis().SetTitleSize(0.06)
          h_ratio.GetYaxis().SetTitleOffset(1)
          h_ratio.GetXaxis().SetTitle(XTitle)
          h_ratio.GetXaxis().SetLabelSize(0.14)
          h_ratio.GetXaxis().SetLabelOffset(0.025)
          h_ratio.GetXaxis().SetTitleSize(0.13)
          h_ratio.GetXaxis().SetTitleOffset(1.05)
          h_ratio.GetYaxis().SetLabelSize(0.1)
          h_ratio.GetYaxis().SetTitleSize(0.14)
          h_ratio.GetYaxis().SetTitleOffset(0.40)
          h_ratio.GetYaxis().SetNdivisions(505)
          h_ratio.SetMarkerStyle(20)
          h_ratio.SetMarkerSize(0.8)
          h_ratio_err.SetMarkerSize(0)
          h_ratio_err.SetFillColor(17)
          h_ratio.Draw("e x0")
          h_ratio_err.Draw("e2 same")
          h_ratio.Draw("axis same")
          h_ratio.Draw("e x0 same")

          for iBin in upArrowBins :
            binCenter = h_ratio.GetBinCenter(iBin)
            a = TArrow(binCenter,1.7,binCenter,1.95,0.01,"|>")
            a.SetLineWidth(3)
            a.SetLineColor(2)
            a.SetFillColor(2)
            a.Draw()
  
          line=TLine()
          line.DrawLine(h_ratio.GetXaxis().GetXmin(),1.0,h_ratio.GetXaxis().GetXmax(),1.0)
          line.SetLineColor(kBlack)
          line.SetLineStyle(kDashed)
          line.DrawLine(h_ratio.GetXaxis().GetXmin(),0.5,h_ratio.GetXaxis().GetXmax(),0.5)
          line.DrawLine(h_ratio.GetXaxis().GetXmin(),1.5,h_ratio.GetXaxis().GetXmax(),1.5)

          c.SaveAs("plots/lowBDTOSFakes/%s.pdf" %variable)
Ejemplo n.º 21
0
def pulls(filename):
    
    with open(filename) as f:
        fullcontent = f.readlines()
    
#    content_nostat = [x for x in fullcontent if not 'CMS_stat' in x]
    content_nostat = [x for x in fullcontent if not 'mcstat_' in x]

    content = fullcontent if binbybin else content_nostat

    nbins = len(content)
    b_pulls = TH1F("b_pulls", ";;pulls", nbins, 0., nbins)
    s_pulls = TH1F("s_pulls", ";;pulls", nbins, 0., nbins)
    rho     = TH1F("rho",     ";;rho",   nbins, 0., nbins)
    
    for i, s in enumerate(content):
        l = s.split()

        b_pulls.GetXaxis().SetBinLabel(i+1, l[0])
        s_pulls.GetXaxis().SetBinLabel(i+1, l[0])
        rho.GetXaxis().SetBinLabel(    i+1, l[0])

        b_pulls.SetBinContent(i+1, float(l[1]))
        b_pulls.SetBinError  (i+1, float(l[2]))
        s_pulls.SetBinContent(i+1, float(l[3]))
        s_pulls.SetBinError  (i+1, float(l[4]))
        rho.SetBinContent    (i+1, float(l[5]))
    
    b_pulls.SetFillStyle(3003)
    b_pulls.SetFillColor(ROOT.kBlue+2)
    b_pulls.SetLineColor(0)
    b_pulls.SetMarkerColor(ROOT.kBlue+2)
    b_pulls.SetLineWidth(0)
    b_pulls.SetMarkerStyle(20)
    b_pulls.SetMarkerSize(1.2)

    s_pulls.SetLineColor(ROOT.kRed+2)
    s_pulls.SetMarkerColor(ROOT.kRed+2)
    s_pulls.SetMarkerStyle(24)
    s_pulls.SetLineWidth(2)

    rho.SetLineColor(ROOT.kRed+2)
    rho.SetMarkerColor(ROOT.kRed+2)
    rho.SetMarkerStyle(24)
    rho.SetLineWidth(2)

    b_pulls.GetYaxis().SetRangeUser(-3., 3.)
    s_pulls.GetYaxis().SetRangeUser(-3., 3.)
    rho.GetYaxis().SetRangeUser(-1.1, 1.1)
    
    
    c1 = TCanvas("c1", "pulls", 1600, 800)
    c1.cd()
    c1.SetTopMargin(0.06)
    c1.SetRightMargin(0.05)
    c1.SetTicks(1, 1)
    
    # Draw
    b_pulls.Draw("E2")
    s_pulls.Draw("SAME, PE1")
    
    leg = TLegend(0.35, 0.95, 0.65, 0.995)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetNColumns(2)
    leg.AddEntry(b_pulls, "bkg-only fit", "fp")
    leg.AddEntry(s_pulls, "sgn+bkg fit",  "lp")
    
    line0 = TLine()
    line0.SetLineColor(ROOT.kGray+2)
    line0.SetLineStyle(6)
    line0.SetLineWidth(2)
    line0.DrawLine(0.,  0., nbins,  0.)

    line1 = TLine()
    line1.SetLineColor(ROOT.kGreen+2)
    line1.SetLineStyle(6)
    line1.SetLineWidth(2)
    line1.DrawLine(0.,  1., nbins,  1.)
    line1.DrawLine(0., -1., nbins, -1.)
    
    line2 = TLine()
    line2.SetLineColor(ROOT.kYellow+2)
    line2.SetLineStyle(6)
    line2.SetLineWidth(2)
    line2.DrawLine(0.,  2., nbins,  2.)
    line2.DrawLine(0., -2., nbins, -2.)
    
    leg.Draw()

    suffix = "all" if binbybin else "no_binbybin"
    print suffix, binbybin
    outputname = "pulls_"+ suffix
    c1.Print(outputname+".png")
    c1.Print(outputname+".pdf")
    
    c2 = TCanvas("c2", "rho", 1600, 800)
    c2.cd()
    c2.SetTopMargin(0.06)
    c2.SetRightMargin(0.05)
    c2.SetTicks(1, 1)
    
    # Draw
    rho.Draw("E0")
    
    leg2 = TLegend(0.35, 0.95, 0.65, 0.995)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)
    leg2.SetFillColor(0)
    leg2.AddEntry(rho, "rho", "flp")
    
    outputname = "rho_"+ suffix
    c2.Print(outputname+".png")
    c2.Print(outputname+".pdf")
    
    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Ejemplo n.º 22
0
def draw():
    hists = allHists()
    for region in regions:
        os.mkdir("plots/%s" % region)
        for variable in variables:
            hist_data = hists[region + "_" + variable + "_data"]
            mchists = []
            for i in processes:
                if i != 'data':
                    temp = hists[region + "_" + variable + "_" + i]
                    mchists.append(temp)
            hs = makeStack(mchists)
            h_bkg, h_ratio, h_ratio_err, upArrowBins = makeRatio(
                hist_data, mchists, hs)
            c, pad1, pad2 = createCanvasPads()
            XTitle, YTitle = (titles[variable])[0], (titles[variable])[1]
            #stack plot
            pad1.cd()
            leg = TLegend(0.60, 0.70, 0.90, 0.90)
            leg.SetNColumns(2)
            leg.SetFillStyle(0)
            leg.SetBorderSize(0)
            leg.AddEntry(hist_data, "data", "pe")
            for i in processes:
                if i != 'data':
                    leg.AddEntry(hists[region + "_" + variable + "_" + i], i,
                                 "f")
            leg.AddEntry(h_bkg, "uncertainty", 'f')
            Ymaximum = 3.5 * hist_data.GetBinContent(hist_data.GetMaximumBin())
            hs.SetMaximum(Ymaximum)
            hs.SetMinimum(0.001)
            hs.SetTitle("")
            hs.Draw("hist")  # thstack must draw first
            hs.GetYaxis().SetTitleSize(0.06)
            hs.GetYaxis().SetTitleOffset(1)
            hs.GetYaxis().SetTitle(YTitle)
            hs.GetXaxis().SetTitle("")
            hs.GetXaxis().SetTitleSize(0.)
            hs.GetXaxis().SetLabelSize(0.)
            h_bkg.Draw("E2 same")
            hist_data.SetMarkerStyle(20)
            hist_data.SetMarkerSize(0.8)
            hist_data.Draw("e x0 same")
            createLabels()
            leg.Draw("same")
            #ratio plot
            pad2.cd()
            h_ratio.SetMinimum(0.0)
            h_ratio.SetMaximum(2.0)
            h_ratio.GetYaxis().SetTitle("Data/Bkg")
            h_ratio.GetYaxis().SetTitleSize(0.06)
            h_ratio.GetYaxis().SetTitleOffset(1)
            h_ratio.GetXaxis().SetTitle(XTitle)
            h_ratio.GetXaxis().SetLabelSize(0.14)
            h_ratio.GetXaxis().SetLabelOffset(0.025)
            h_ratio.GetXaxis().SetTitleSize(0.13)
            h_ratio.GetXaxis().SetTitleOffset(1.05)
            h_ratio.GetYaxis().SetLabelSize(0.1)
            h_ratio.GetYaxis().SetTitleSize(0.14)
            h_ratio.GetYaxis().SetTitleOffset(0.40)
            h_ratio.GetYaxis().SetNdivisions(505)
            h_ratio.SetMarkerStyle(20)
            h_ratio.SetMarkerSize(0.8)
            h_ratio_err.SetMarkerSize(0)
            h_ratio_err.SetFillColor(17)
            h_ratio.Draw("e x0")
            h_ratio_err.Draw("e2 same")
            h_ratio.Draw("axis same")
            h_ratio.Draw("e x0 same")

            for iBin in upArrowBins:
                binCenter = h_ratio.GetBinCenter(iBin)
                a = TArrow(binCenter, 1.7, binCenter, 1.95, 0.01, "|>")
                a.SetLineWidth(3)
                a.SetLineColor(2)
                a.SetFillColor(2)
                a.Draw()

            line = TLine()
            line.DrawLine(h_ratio.GetXaxis().GetXmin(), 1.0,
                          h_ratio.GetXaxis().GetXmax(), 1.0)
            line.SetLineColor(kBlack)
            line.SetLineStyle(kDashed)
            line.DrawLine(h_ratio.GetXaxis().GetXmin(), 0.5,
                          h_ratio.GetXaxis().GetXmax(), 0.5)
            line.DrawLine(h_ratio.GetXaxis().GetXmin(), 1.5,
                          h_ratio.GetXaxis().GetXmax(), 1.5)

            c.SaveAs("plots/%s/%s.pdf" % (region, variable))
    def sobWeightedPlot(self,
                        fileName,
                        datasetName,
                        channel,
                        cat,
                        log,
                        mass,
                        tanb,
                        blind,
                        sob=False):

        #        print 'yuta', channel, cat

        c = TCanvas(fileName, '', 600, 600)
        c.cd()
        if log: c.SetLogy(1)

        f = self.openTFile('Plot_' + fileName + '.root')

        isEMSM = fileName.find('SM') != -1 and fileName.find('em') != -1
        isETSM = fileName.find('SM') != -1 and fileName.find('et') != -1

        samples = ['ggH', 'Ztt', 'signal', 'data_obs', 'ttbar', 'EWK', 'Fakes']

        if isEMSM:
            samples.append('ggH_hww')
        if isETSM:
            samples.append('Zee')

        dataGraph = self.tfileGet(f, 'Graph_from_data_obs')

        histDict = {}
        for sample in samples:
            histDict[sample] = self.tfileGet(f, sample)
            #            print 'check :', sample, histDict[sample].GetSumOfWeights()
            if not histDict[sample]:
                print 'Missing histogram', sample, 'in file', 'Plot_' + fileName + '.root'

# original for plots
        xminInset = 60  # 0
        xmaxInset = 179  # 340 (for full range)

        # all range
        #        xminInset = 0 # 0
        #        xmaxInset = 350 # 340 (for full range)

        #        xminInset = 40 # 0
        #        xmaxInset = 200 # 340 (for full range)
        #        xminInset = 120 # 0
        #        xmaxInset = 251 # 340 (for full range)

        if tanb > 0:
            xminInset = mass - 100
            xmaxInset = mass + 100

        if sob:
            xminInset = 0.4
            xmaxInset = 0.7

        ztt = histDict['Ztt']
        ggH = histDict['ggH']
        data = histDict['data_obs']

        # This is to fix a weird plotting bug
        if sob:
            new_data = TH1F('new_data', '', ggH.GetNbinsX(), 0., 0.7)
            for i in range(1, new_data.GetNbinsX() + 1):
                new_data.SetBinContent(i, data.GetBinContent(i))
                # print data.GetBinContent(i)
            data = new_data

        ggH_hww = 0
        zee = 0

        signal = histDict['signal']
        if isEMSM:
            ggH_hww = histDict['ggH_hww']
        if isETSM:
            print 'retrieve Zee'
            zee = histDict['Zee']
        tt = histDict['ttbar']
        ewk = histDict['EWK']
        fakes = histDict['Fakes']

        ztt.GetYaxis().SetRangeUser(0., 1.3 * self.findMaxY(data, 0))
        if log:
            ztt.GetYaxis().SetRangeUser(0.001, 50. * self.findMaxY(data, 0))

        ztt.GetXaxis().SetTitle('#bf{m_{#tau#tau}  [GeV]}')
        ztt.GetYaxis().SetTitle('#bf{S/B Weighted dN/dm_{#tau#tau} [1/GeV]}')
        if tanb > 0. and not log:
            ztt.GetXaxis().SetRangeUser(0., mass + 200.)

        if sob:
            ztt.GetXaxis().SetTitle('S/(S+B)')
            ztt.GetYaxis().SetTitle('Events')

        ztt.SetTitleOffset(1.3, 'Y')
        ztt.SetTitleOffset(1., 'X')
        ztt.GetYaxis().SetNdivisions(505)
        ztt.SetNdivisions(505)

        for b in range(0, signal.GetNbinsX() + 2):
            if signal.GetBinCenter(
                    b) < xminInset or xmaxInset < signal.GetBinCenter(b):
                signal.SetBinContent(b, 0.)
                signal.SetBinError(b, 0.)

        signal.SetName('sig')
        signal.SetFillStyle(3353)  # 1001=solid , 3004,3005=diagonal
        signal.SetFillColor(2)
        signal.SetLineColor(2)
        signal.SetLineStyle(1)
        signal.SetLineWidth(0)

        ggH.SetBinContent(0, 0)  # remove red line on top of y axis in plot
        ggH.SetBinContent(ggH.GetNbinsX() + 1, 0)
        ggH.SetBinError(0, 0)
        ggH.SetBinError(ggH.GetNbinsX() + 1, 0)
        ggH.SetName('ggH')
        ggH.SetFillStyle(3353)  # 1001=solid , 3004,3005=diagonal
        ggH.SetFillColor(2)
        ggH.SetLineColor(2)
        ggH.SetLineStyle(1)
        ggH.SetLineWidth(0)

        if isEMSM:
            errorBand = TH1F(ggH_hww)
        else:
            errorBand = TH1F(ztt)
        errorBand.SetName("errorBand")

        errorBand.SetMarkerSize(0)
        errorBand.SetFillColor(1)
        errorBand.SetFillStyle(3013)
        errorBand.SetLineWidth(1)

        legend = TLegend()
        mssmLabel = ''
        if tanb > 0:
            mssmLabel = "tan#beta={tanb}".format(tanb=tanb)
        higgsLabel = "H(125 GeV)#rightarrow#tau#tau"
        if tanb > 0:
            higgsLabel = "H(125 GeV)#rightarrow#tau#tau"

        legend.SetFillStyle(0)
        legend.SetFillColor(0)
        legend.SetBorderSize(0)
        legend.AddEntry(ggH, higgsLabel, "F")
        if tanb > 0:
            legend.AddEntry(TObject(0), mssmLabel, "")
        legend.AddEntry(data, "observed", "LP")
        if isEMSM:
            legend.AddEntry(ggH_hww, "H(125 GeV)#rightarrowWW", "F")
        legend.AddEntry(ztt, "Z#rightarrow#tau#tau", "F")
        legend.AddEntry(tt, "t#bar{t}", "F")
        if isETSM:
            legend.AddEntry(zee, "Z#rightarrowee", "F")
        legend.AddEntry(ewk, "electroweak", "F")
        legend.AddEntry(fakes, "QCD", "F")

        legend.SetX1NDC(0.63)
        legend.SetX2NDC(1.05)
        legend.SetY1NDC(0.25)
        legend.SetY2NDC(0.46)
        if log:
            legend.SetX1NDC(0.18)
            legend.SetX2NDC(0.60)
            legend.SetY1NDC(0.17)
            legend.SetY2NDC(0.38)

        legend.SetTextSize(.028)
        legend.SetTextAlign(12)

        if isEMSM:
            dataDiff = self.diffPlot(data, ggH_hww, 1)
            dataDiffGraph = self.diffGraph(dataGraph, ggH_hww, 1)
            errBand = self.getErrorBand(ggH_hww)
        else:
            dataDiff = self.diffPlot(data, ztt, 1)
            dataDiffGraph = self.diffGraph(dataGraph, ztt, 1)
            errBand = self.getErrorBand(ztt)

        errBand.SetFillStyle(
            3013
        )  # 1001=solid , 3004,3005=diagonal, 3013=hatched official for H.tau tau
        errBand.SetFillColor(1)
        errBand.SetLineStyle(1)
        errBand.SetLineColor(1)
        errBand.SetLineWidth(1)

        errBandFrame = TH1F(
            'errBandFrame', '',
            int((xmaxInset - xminInset) / dataDiff.GetBinWidth(1)), xminInset,
            xmaxInset)

        errBandFrame.GetYaxis().SetTitle("")
        errBandFrame.GetYaxis().SetRangeUser(
            -1.1 * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset),
            2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset))
        #        errBandFrame.GetYaxis().SetRangeUser(-1.*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),1.1*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) # good !
        #        errBandFrame.GetYaxis().SetRangeUser(-0.2*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),0.5*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset))

        print 'Yuta', channel, cat
        if (channel == 'e#tau_{h}' and cat == 'vbf') or (channel == 'e#tau_{h}'
                                                         and cat == ''):
            print 'enter'
            errBandFrame.GetYaxis().SetRangeUser(
                -2. * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset),
                2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset))
        errBandFrame.GetYaxis().SetNdivisions(5)
        errBandFrame.GetYaxis().SetLabelSize(0.06)
        errBandFrame.GetXaxis().SetTitle("#bf{m_{#tau#tau} [GeV]}    ")
        errBandFrame.GetXaxis().SetTitleColor(kBlack)
        errBandFrame.GetXaxis().SetTitleSize(0.07)
        errBandFrame.GetXaxis().SetTitleOffset(0.85)
        errBandFrame.GetXaxis().SetLabelSize(0.06)
        errBandFrame.GetXaxis().SetNdivisions(506)
        #        errBandFrame.SetNdivisions(505)

        legendDiff = TLegend()
        legendDiff.SetFillStyle(0)
        legendDiff.SetFillColor(0)
        legendDiff.SetBorderSize(0)
        legendDiff.AddEntry(signal, higgsLabel, "F")

        if tanb > 0:
            legendDiff.AddEntry(TObject(0), mssmLabel,
                                '')  # That might not work in python
#        legendDiff.AddEntry(dataDiff,"Data - Background","LP")
        legendDiff.AddEntry(dataDiffGraph, "Data - Background", "LEP")
        legendDiff.AddEntry(errBand, "Bkg. Uncertainty", "F")
        legendDiff.SetX1NDC(0.45)
        legendDiff.SetX2NDC(0.88)
        legendDiff.SetY1NDC(0.67)
        legendDiff.SetY2NDC(0.88)
        if dataDiff.GetBinContent(dataDiff.FindBin(mass)) < 0.:
            legendDiff.SetX1NDC(0.45)
            legendDiff.SetX2NDC(0.88)
            legendDiff.SetY1NDC(0.24)
            legendDiff.SetY2NDC(0.45)

        legendDiff.SetTextSize(.045)
        legendDiff.SetTextAlign(12)

        padBack = TPad(
            "padBack", "padBack", 0.57, 0.58, 0.975,
            0.956)  # TPad must be created after TCanvas otherwise ROOT crashes
        padBack.SetFillColor(0)
        pad = TPad(
            "diff", "diff", 0.45, 0.5, 0.9765,
            0.957)  # TPad must be created after TCanvas otherwise ROOT crashes
        pad.cd()
        pad.SetFillColor(0)
        pad.SetFillStyle(0)
        errBandFrame.Draw()
        errBand.Draw("e2lsame")
        signal.Draw("histsame")
        line = TLine()
        line.DrawLine(xminInset, 0, xmaxInset, 0)
        # dataDiff.Draw("pe same")

        if blind == False:
            self.HideBin(dataDiffGraph)

        dataDiffGraph.SetMarkerSize(0.5)
        dataDiffGraph.Draw('pe same')

        for ibin in range(0, dataDiffGraph.GetN()):
            x = Double(0.)
            y = Double(0.)
            dataDiffGraph.GetPoint(ibin, x, y)

            print 'Yuta_bin=', ibin, 'x=', x, 'y=', y, dataDiffGraph.GetErrorYhigh(
                ibin), dataDiffGraph.GetErrorYlow(ibin)
            print 'Yuta_error=', ibin, errBand.GetXaxis().GetBinCenter(
                ibin + 1), errBand.GetBinError(ibin + 1)

        legendDiff.Draw()
        pad.RedrawAxis()

        c.cd()
        ztt.Draw("hist")
        ggH.Draw("hist same")
        if isEMSM:
            ggH_hww.Draw("hist same")
        ztt.Draw("hist same")
        errorBand.Draw("e2 same")
        tt.Draw("hist same")
        if isETSM:
            zee.Draw("hist same")
        ewk.Draw("hist same")
        fakes.Draw("hist same")

        # data.Draw("pe same")
        dataGraph.SetMarkerSize(1)
        dataGraph.Draw('PE same')

        if blind == False:
            self.HideBin(dataGraph)

        print '#####', data.Integral(), data.GetBinContent(1)
        legend.Draw()
        c.RedrawAxis()
        padBack.Draw()  # clear the background axe
        pad.Draw()
        if log: c.SetLogy(1)
        self.CMSPrelim(c, datasetName, channel, cat)

        savepath = 'figure/Plot_' + fileName
        if cat == '':
            savepath = savepath + '.pdf'
        else:
            savepath = savepath + '_' + cat + '.pdf'


#        c.Print('figure/Plot_'+fileName+".eps")
#        c.Print('figure/Plot_'+fileName+".png")
#        c.Print('figure/Plot_'+fileName+".pdf")
        c.Print(savepath)

        c.Close()
Ejemplo n.º 24
0
file = TPave( 1, 8.5, 20, 11 )
file.SetFillColor( 11 )
file.Draw()
fileh = TPave( 1, 8.5, 2.5, 11 )
fileh.SetFillColor( 44 )
fileh.Draw()
lrh = TPave( 2.5, 8.5, 3.3, 11, 1 )
lrh.SetFillColor( 33 )
lrh.Draw()
lrh.DrawPave( 6.9, 8.5, 7.7, 11, 1 )
lrh.DrawPave( 10.5, 8.5, 11.3, 11, 1 )
lrh.DrawPave( 14.5, 8.5, 15.3, 11, 1 )
ldot = TLine( 1, 8.5, 0.5, 6.5 )
ldot.SetLineStyle( 2 )
ldot.Draw()
ldot.DrawLine( 2.5, 8.5, 9.4, 6.5 )
ldot.DrawLine( 10.5, 8.5, 10, 6.5 )
ldot.DrawLine( 11.3, 8.5, 19.5, 6.5 )
line = TLine( 2.6, 11, 2.6, 11.5 )
line.Draw()
line.DrawLine( 2.6, 11.5, 7, 11.5 )
arrow = TArrow( 7, 11.5, 7, 11.1, 0.01, '|>' )
arrow.SetFillStyle( 1001 )
arrow.Draw()
line.DrawLine( 7, 8.5, 7, 8.0 )
line.DrawLine( 7, 8.0, 10.6, 8 )
arrow.DrawArrow( 10.6,8, 10.6, 8.4, 0.01, '|>' )
line.DrawLine( 10.6, 11, 10.6, 11.5 )
line.DrawLine( 10.6, 11.5, 14.6, 11.5 )
arrow.DrawArrow( 14.6, 11.5, 14.6, 11.1, 0.01, '|>' )
line.DrawLine( 14.6, 8.5, 14.6, 8.0 )
Ejemplo n.º 25
0
def limits():

    # put real limits here: lepton+jets, dilepton, combined
    obs = np.array([1, 1, 1])

    expect = np.array([1, 1, 1])
    upper1sig = np.array([1.352, 0.736390352249, 0.636])
    lower1sig = np.array([0.9153, 0.500572919846, 0.439])
    upper2sig = np.array([3.125, 1.66185164452, 1.455])
    lower2sig = np.array([1.4717, 0.805953979492, 0.715])

    channel = np.array([1.5, 0.5, -0.5])
    ey = np.array([0.495, 0.495, 0.495])
    zero = np.zeros(nchannels)

    xmin = 0.7
    xmax = 30

    c, h = draw_canvas_histo(
        xmin, xmax,
        "95% CL limit on #mu = #sigma/#sigma_{SM} at m_{H} = 125 GeV")
    c.SetLogx()

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    leg = TLegend(0.67, 0.75, 0.95, 0.9)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    #draw_disclaimer()

    c.RedrawAxis()
    c.Modified()
    c.Update()
    c.SaveAs("limits.pdf")
Ejemplo n.º 26
0
def runMCStudy():

    # load workspace
    f = TFile("./data/fitWorkspace.root")
    fitWorkspace = f.Get("fitWorkspace")
    fEnergy = fitWorkspace.var("energy_keV")
    model = fitWorkspace.pdf("model")
    fitResult = fitWorkspace.allGenericObjects().front()
    fitValsFinal = getRooArgDict(fitResult.floatParsFinal())
    pdfList = fitWorkspace.allPdfs()  # RooArgSet
    nExpected = int(model.expectedEvents(pdfList))

    # thank you, lindsey gray. http://www.hep.wisc.edu/~lgray/toyMC.py
    nSamples = 10
    args = [
        # RF.Binned(True),
        RF.Silence(),
        RF.FitOptions(RF.PrintEvalErrors(0),
                      RF.NumCPU(2))  # not sure numCPU is doing anything
    ]
    mcStudy = ROOT.RooMCStudy(model, ROOT.RooArgSet(fEnergy), *args)
    start = time.time()
    mcStudy.generateAndFit(
        nSamples, nExpected)  # nSamples (nToys), nEvtPerSample (nEvents)
    print "MC Study Complete. %i samples, %.2f seconds." % (
        nSamples, time.time() - start)

    parName = "amp-36Cl"
    parVal = fitResult.floatParsFinal().find(parName).getValV()
    parErr = fitResult.floatParsFinal().find(parName).getError()
    parVar = fitWorkspace.var(parName)

    # make 4 rooplot frames
    fParam = mcStudy.plotParam(parVar, RF.Bins(50))
    fError = mcStudy.plotError(
        parVar, RF.FrameRange(parErr - 0.5 * parErr, parErr + 0.5 * parErr),
        RF.Bins(50))
    fPull = mcStudy.plotPull(parVar, RF.FrameRange(-5, 5), RF.Bins(50))
    fNLL = mcStudy.plotNLL(RF.Bins(50))

    line = TLine()
    line.SetLineColor(ROOT.kBlue)
    line.SetLineWidth(2)
    line.SetLineStyle(3)

    c = TCanvas("c", "c", 1100, 800)
    c.Divide(2, 2)
    c.cd(1)
    fParam.SetTitle(parName)
    fParam.Draw()
    line.DrawLine(parVal, fParam.GetMinimum(), parVal,
                  fParam.GetMaximum())  # best fit

    c.cd(2)
    fError.SetTitle(parName + " Error")
    fError.Draw()
    line.DrawLine(parErr, fError.GetMinimum(), parErr, fError.GetMaximum())

    c.cd(3)
    fPull.SetTitle(parName + " Pull")
    fPull.Draw()

    c.cd(4)
    fNLL.SetTitle("-log(likelihood)")
    fNLL.Draw()
    line.DrawLine(fitResult.minNll(), fNLL.GetMinimum(), fitResult.minNll(),
                  fNLL.GetMaximum())

    c.Print("plots/mcStudy.pdf")
    """
    h1b_eff.SetConfidenceLevel(0.682689492137)  # one sigma
    h1b_eff.SetMarkerColor(600)  # kBlue
    h1b_eff.SetLineColor(600)  # kBlue
    h1b_eff.SetLineWidth(2)

    gr = h1a_eff.CreateGraph()
    gr.Draw("ap")
    frame = gr.GetHistogram()
    frame = frame.Clone(hname + "_frame")
    frame.GetYaxis().SetTitle("#varepsilon")
    frame.SetMinimum(0.0)
    frame.SetMaximum(1.2)
    frame.SetStats(0)
    frame.Draw()
    xmin, xmax = frame.GetXaxis().GetXmin(), frame.GetXaxis().GetXmax()
    tline.DrawLine(xmin, 1.0, xmax, 1.0)
    #h1a_eff.Draw("same")
    h1b_eff.Draw("same")

    draw_cms_lumi()
    gPad.Print("figures_perf/" + hname + "_omtf" + ".png")
    gPad.Print("figures_perf/" + hname + "_omtf" + ".pdf")
    donotdelete.append([frame, h1a_eff, h1b_eff])

    if False:
        outfile = TFile.Open("figures_perf/" + hname + ".root", "RECREATE")
        for obj in [frame, h1a_eff, h1b_eff]:
            obj.Write()
        outfile.Close()

    # ____________________________________________________________________________
Ejemplo n.º 28
0
def main():

    if True:
        mf=TGMainFrame(gClient.GetRoot(),1500,475)
        gvf=TGVerticalFrame(mf,1500,475)
        rec=TRootEmbeddedCanvas("ccc",gvf,1500,450)
        rec2=TRootEmbeddedCanvas("ccc2",gvf,1500,25)
        gvf.AddFrame(rec,TGLayoutHints(ROOT.kLHintsExpandX|ROOT.kLHintsTop))
        gvf.AddFrame(rec2,TGLayoutHints(ROOT.kLHintsExpandX|ROOT.kLHintsBottom))
        mf.AddFrame(gvf,TGLayoutHints(ROOT.kLHintsExpandX))
        cc=rec.GetCanvas()
        cc2=rec2.GetCanvas()
        mf.SetEditable(0)
        mf.SetWindowName('HPS ECAL FADC SCALERS')
        mf.MapSubwindows()
        mf.Resize(1501,476)# resize to get proper frame placement
        mf.MapWindow()
    else:
        cc=TCanvas('cc','',1500,450)
   
    cc.cd()
    cc.SetBorderMode(0)
    cc.SetFixedAspectRatio(1)
    cc.FeedbackMode(1)
    
    gStyle.SetOptStat(0)
    gStyle.SetGridStyle(1)
    gStyle.SetGridColor(11)

    hh=TH2D('hh',';X;Y',46,-22,24,11,-5,6)
    hi=TH2I('hi',';X;Y',46,-22,24,11,-5,6)
    setupHists([hh,hi])
    xax,yax=hh.GetXaxis(),hh.GetYaxis()
    hh.Draw('COLZ')
    hi.Draw('TEXTSAME')
    
    gPad.SetLogz()
    gPad.SetGrid(1,1)
    gPad.SetLeftMargin(0.05)
    
    tt1=TPaveText(0.1,0.9,0.3,1.0,'NDC')
    tt2=TPaveText(0.7,0.91,0.9,0.99,'NDC')
    ttT=TPaveText(-22+13+0.05,6-5,-22+22,7-5-0.05)
    ttB=TPaveText(-22+13+0.05,4-5+0.05,-22+22,5-5)
    ttM=TPaveText(-22+0+0.05,5-5+0.05,-22+13,6-5.01)
    ttime=TPaveText(-10,-6.5,10,-5.8)
    tchan=TPaveText(0,0,0.9,1)
    setupPaveTexts([tt1,tt2,ttT,ttB,ttM,ttime,tchan])
    ttM.SetTextColor(2)
    
    bb=TBox()
    bb.SetFillStyle(1001)
    bb.SetFillColor(0)
    bb.SetLineWidth(1)
    bb.SetLineColor(1)
    bb.DrawBox(-9+0.05,-1,0,1.97)
    bb.DrawBox(-24,0,24.05,0.97)
    
    tarrow=TText(14.5,0.3,'Beam Left')
    arrow=TArrow(19,0.5,23,0.5,0.02,'|>')
    arrow.SetAngle(40)
    arrow.SetFillColor(1)
    arrow.SetLineWidth(2)
    
    tt=TText()
    tt.SetTextColor(1)
    tt.SetTextAngle(90)
    tt.SetTextSize(0.08)
    tt.DrawText(25.4,0,'kHz')
    tt.SetTextAngle(0)
    tt.SetTextColor(2)
    tt.DrawTextNDC(0.3,0.92,'ECAL FADC SCALERS')
   
    cc.cd()
    for xx in [tt2,ttT,ttB,ttM,arrow,tarrow,ttime]: xx.Draw()
    cc2.cd()
    tchan.Draw('NDC')
    cc.cd()
    
    ll=TLine()
    ll.DrawLine(xax.GetXmin(),yax.GetXmin(),xax.GetXmax(),yax.GetXmin())
    ll.DrawLine(xax.GetXmin(),yax.GetXmax(),xax.GetXmax(),yax.GetXmax())
    ll.DrawLine(xax.GetXmin(),yax.GetXmin(),xax.GetXmin(),0)
    ll.DrawLine(xax.GetXmax(),yax.GetXmin(),xax.GetXmax(),0)
    ll.DrawLine(xax.GetXmin(),yax.GetXmax(),xax.GetXmin(),1)
    ll.DrawLine(xax.GetXmax(),yax.GetXmax(),xax.GetXmax(),1)
    ll.DrawLine(xax.GetXmax(),0,0,0)
    ll.DrawLine(xax.GetXmax(),1,0,1)
    ll.DrawLine(xax.GetXmin(),0,-9,0)
    ll.DrawLine(xax.GetXmin(),1,-9,1)
    ll.DrawLine(-9,-1,0,-1)
    ll.DrawLine(-9,2,0,2)
    ll.DrawLine(-9,1,-9,2)
    ll.DrawLine(-9,-1,-9,0)
    ll.DrawLine(0,-1,0,0)
    ll.DrawLine(0,1,0,2)
   
    gPad.SetEditable(0)

    while True:

#        try:

            zvals=getPVS()
            for ii in range(len(zvals)):
                hh.SetBinContent(xax.FindBin(XVALS[ii]),yax.FindBin(YVALS[ii]),zvals[ii])
                hi.SetBinContent(xax.FindBin(XVALS[ii]),yax.FindBin(YVALS[ii]),zvals[ii])
            
            for xx in [ttime,tt2,ttT,ttB,ttM]: xx.Clear()
            [top,bottom,maximum]=calcRates(zvals)
            tt2.AddText('Total:  %.1f MHz'%((top+bottom)/1000))
            ttT.AddText('%.1f MHz'%(top/1000))
            ttB.AddText('%.1f MHz'%(bottom/1000))
            ttM.AddText('MAX SINGLE CRYSTAL = %.0f kHz'%(maximum))
            ttime.AddText(makeTime())
          
            if gPad.GetEvent()==11:
                xy=pix2xy(gPad)
                ee=ECAL.findChannelXY(xy[0],xy[1])
                if ee:
                    tchan.Clear()
                    tchan.AddText(printChannel(ee))
                    cc2.Modified()
                    cc2.Update()
            elif gPad.GetEvent()==12:
                tchan.Clear()
                cc2.Modified()
                cc2.Update()
    
    
            cc.Modified()
            cc.Update()
        
            time.sleep(1)
Ejemplo n.º 29
0
def pulls(fileName):

    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10

    b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off)
    s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off)  #

    for i, s in enumerate(content):
        l = s.split()
        b_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        s_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        b_pulls.SetBinContent(i + 1, float(l[1]))
        b_pulls.SetBinError(i + 1, float(l[2]))
        s_pulls.SetBinContent(i + 1, float(l[3]))
        s_pulls.SetBinError(i + 1, float(l[4]))

    b_pulls.SetFillStyle(3005)
    b_pulls.SetFillColor(923)
    b_pulls.SetLineColor(923)
    b_pulls.SetLineWidth(2)
    b_pulls.SetMarkerStyle(20)
    b_pulls.SetMarkerSize(1.25)

    s_pulls.SetLineColor(602)
    s_pulls.SetMarkerColor(602)
    s_pulls.SetMarkerStyle(24)  #24
    s_pulls.SetLineWidth(2)

    b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5)

    canvas = TCanvas("canvas", "Pulls", 1600, 800)
    canvas.cd()
    canvas.GetPad(0).SetTopMargin(0.06)
    canvas.GetPad(0).SetRightMargin(0.05)
    canvas.GetPad(0).SetBottomMargin(0.15)
    canvas.GetPad(0).SetTicks(1, 1)

    #    box = TBox(950., 105., 2000., 200.)
    #    box.SetFillStyle(3354)
    #    #box.SetFillStyle(0)
    #    box.SetFillColor(1)
    #    box.SetLineWidth(2)
    #    box.SetLineStyle(2)
    #    box.SetLineColor(1)
    #    box.Draw()

    # Draw
    b_pulls.Draw("PE1")
    #b_pulls.Draw("B")
    s_pulls.Draw("SAME, PE1")

    leg = TLegend(0.25, 0.95, 0.75, 0.995)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetNColumns(2)
    leg.AddEntry(b_pulls, "background-only fit", "flp")
    leg.AddEntry(s_pulls, "signal+background fit", "lp")
    if text: leg.AddEntry(0, text, "")

    line = TLine()
    line.DrawLine(0., 0., nbins, 0.)
    line.SetLineStyle(7)
    line.SetLineWidth(2)
    line.SetLineColor(417)
    line.DrawLine(0., 1., nbins, 1.)
    line.DrawLine(0., -1., nbins, -1.)
    line.SetLineColor(800)
    line.DrawLine(0., 2., nbins, 2.)
    line.DrawLine(0., -2., nbins, -2.)

    leg.Draw()
    #    drawCMS(LUMI, "Simulation")
    #    drawAnalysis("DM")
    #    drawRegion(channel)

    #    canvas.Print(outName+".jpg")
    canvas.Print(outName + ".png")
    canvas.Print(outName + ".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Ejemplo n.º 30
0
                                      i + 1))
        hProj.append(h[4].ProjectionZ(sName + "DPTflipped", k + 1, k + 1,
                                      i + 1, i + 1))
        hProj.append(h[5].ProjectionZ(sName + "DPTok", k + 1, k + 1, i + 1,
                                      i + 1))

        # hProj.append(h[6].ProjectionZ(sName + "DRall", k+1, k+1, i+1, i+1))
        # hProj.append(h[7].ProjectionZ(sName + "DRflipped", k+1, k+1, i+1, i+1))
        # hProj.append(h[8].ProjectionZ(sName + "DRok", k+1, k+1, i+1, i+1))

        cDE.cd(j + 1).SetLogy()
        hProj[0].Draw()
        hProj[1].Draw("same")
        hProj[2].Draw("same")
        legArr[j].Draw()
        l.DrawLine(0, 0, 0, hProj[0].GetMaximum() * 1.9)

        cDPT.cd(j + 1).SetLogy()
        hProj[3].Draw()
        hProj[4].Draw("same")
        hProj[5].Draw("same")
        legArr[j].Draw()
        l.DrawLine(0, 0, 0, hProj[3].GetMaximum() * 1.9)

        cDR.cd(j + 1).SetLogy()
        # hProj[6].Draw()
        # hProj[7].Draw("same")
        # hProj[8].Draw("same")
        # legArr[j].Draw()
        # l.DrawLine(0, 0, 0, hProj[6].GetMaximum()*1.9)