示例#1
0
def plot_calibrations(group_data, voltage, cal_pars_list, stacked=False):
    group_name = str(group_data[0].run_number)
    run = group_data[2]
    name = str(run.run_number)
    hists_and_lines = []
    for cal_pars in cal_pars_list:
        pars = parameters.gain_pars[cal_pars]
        run.calibrate_energies(voltage, pars)
        hist = make_hist(name, run.calibrated_energies, 0, 3500)
        K_line = TLine(1460.820, 0, 1460.820, 1000000)
        K_line.SetLineColor(632)
        Tl_line = TLine(2614.511, 0, 2614.511, 1000000)
        Tl_line.SetLineColor(632)
        hists_and_lines.append([hist, K_line, Tl_line])

    if stacked:
        print('Plotting stacked calibrated histograms.')
        run_canvas = TCanvas()
        run_canvas.SetLogy()
        colors = [808, 397, 436, 424, 628, 852, 800, 863, 403, 797]
        color_index = 0
        hs = THStack('hs', 'Group %s Histograms' % group_name)
        for entry in hists_and_lines:
            title = str(run.run_number)
            entry[0].SetLineColor(colors[color_index])
            color_index += 1
            hs.Add(entry[0])
        hs.Draw('nostack')
        K_line = TLine(1460.820, 0, 1460.820, 1000000)
        K_line.SetLineColor(632)
        K_line.Draw()
        Tl_line = TLine(2614.511, 0, 2614.511, 1000000)
        Tl_line.SetLineColor(632)
        Tl_line.Draw()
        run_canvas.BuildLegend()
        path = 'output/group_' + str(group_data[0].run_number) + '/'
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf['))
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf'))
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf]'))
    else:
        print('Plotting calibrated energy histogram.')
        run_canvas = TCanvas("run_canvas", "run canvas")
        run_canvas.Divide(3, int(len(cal_pars_list) / 2))
        canvas_index = 1
        for entry in hists_and_lines:
            pad = run_canvas.cd(canvas_index)
            pad.SetLogy()
            entry[0].Draw()
            entry[1].Draw()
            entry[2].Draw()
            pad.Update()
            canvas_index += 1

            path = 'output/group_' + group_name + '/'
            run_canvas.Print((path + name + '_calibrated_histograms.pdf['))
            run_canvas.Print((path + name + '_calibrated_histograms.pdf'))
            run_canvas.Print((path + name + '_calibrated_histograms.pdf]'))
示例#2
0
def saveTuplePlot2D(events,
                    inHisto1,
                    inHisto2,
                    nBinsX,
                    minX,
                    maxX,
                    nBinsY,
                    minY,
                    maxY,
                    mincut,
                    maxcut,
                    outfile,
                    canvas,
                    XaxisTitle="",
                    YaxisTitle="",
                    plotTitle="",
                    stats=0,
                    logY=0):
    events.Draw("{0}:{1}>>histo({2},{3},{4},{5},{6},{7})".format(
        inHisto2, inHisto1, nBinsX, minX, maxX, nBinsY, minY, maxY))
    histo = ROOT.gROOT.FindObject("histo")
    histo.SetTitle(plotTitle)
    histo.GetXaxis().SetTitle(XaxisTitle)
    histo.GetYaxis().SetTitle(YaxisTitle)
    histo.SetStats(stats)
    histo.Draw("COLZ")
    minline = TLine(minX, mincut, maxX, mincut)
    minline.SetLineColor(2)
    minline.Draw("same")
    maxline = TLine(minX, maxcut, maxX, maxcut)
    maxline.SetLineColor(2)
    maxline.Draw("same")
    canvas.SetLogy(logY)
    canvas.Print(outfile + ".pdf")
    del histo
示例#3
0
def DrawScat2XLine(graph, title, fname, ycoord1, ycoord2):  #, grid):

    c = TCanvas("c", "c", 800, 600)

    graph.SetTitle(title)
    graph.GetXaxis().SetTitleSize(.04)
    graph.GetYaxis().SetTitleSize(.04)
    graph.GetXaxis().SetTitleOffset(1.2)
    graph.GetYaxis().SetTitleOffset(1.25)
    graph.GetXaxis().CenterTitle(1)
    graph.GetYaxis().CenterTitle(1)
    graph.GetYaxis().SetMaxDigits(4)
    graph.SetMarkerStyle(20)  # Full circle
    graph.Draw()

    gPad.Update()
    line1 = TLine(gPad.GetUxmin(), ycoord1, gPad.GetUxmax(), ycoord1)
    line2 = TLine(gPad.GetUxmin(), ycoord2, gPad.GetUxmax(), ycoord2)
    # print(gPad.GetUymin(),gPad.GetUymax())
    line1.SetLineStyle(2)
    line1.SetLineColor(2)
    line1.SetLineWidth(3)
    line2.SetLineStyle(2)
    line2.SetLineColor(2)
    line2.SetLineWidth(3)

    graph.Draw("AP")
    line1.Draw("same")
    line2.Draw("same")

    c.SaveAs(fname + ".C")
    c.SaveAs(fname + ".pdf")

    return
示例#4
0
def drawCut(hist):
    #drawCut(80, 140, 0., hist['BkgSum'].GetMaximum())
    line1 = TLine(80, 0, 80, hist['BkgSum'].GetMaximum())
    line1.SetLineWidth(2)
    line1.SetLineStyle(7)
    line1.SetLineColor(1)
    line1.Draw()

    line2 = TLine(140, 0, 140, hist['BkgSum'].GetMaximum())
    line2.SetLineWidth(2)
    line2.SetLineStyle(7)
    line2.SetLineColor(1)
    line2.Draw()

    line1 = TLine(0.841, 0, 0.841, 15)
    line1.SetLineWidth(2)
    line1.SetLineStyle(7)
    line1.SetLineColor(1)
    line1.Draw()

    line1 = TLine(100, 0, 100, hist['BkgSum'].GetMaximum())
    line1.SetLineWidth(2)
    line1.SetLineStyle(7)
    line1.SetLineColor(1)
    line1.Draw()
示例#5
0
def draw2d(hist, xtitle, ytitle, number=False, nxbins=0, nybins=0):
    """Draw 2D histogram."""
    tsize = 0.045
    lines = []
    xmin, xmax = hist.GetXaxis().GetXmin(), hist.GetXaxis().GetXmax()
    ymin, ymax = hist.GetYaxis().GetXmin(), hist.GetYaxis().GetXmax()
    canvas = TCanvas('canvas', 'canvas', 100, 100, 900, 800)
    canvas.SetMargin(0.11, 0.16, 0.10, 0.02)  # LRBT
    canvas.SetLogz()
    hist.GetXaxis().SetTitle(xtitle)
    hist.GetYaxis().SetTitle(ytitle)
    hist.GetZaxis().SetTitle("Events")
    hist.GetXaxis().SetTitleSize(tsize)
    hist.GetYaxis().SetTitleSize(tsize)
    hist.GetZaxis().SetTitleSize(tsize)
    hist.GetXaxis().SetLabelSize(0.9 * tsize)
    hist.GetYaxis().SetLabelSize(0.9 * tsize)
    hist.GetZaxis().SetLabelSize(0.9 * tsize)
    hist.GetXaxis().SetTitleOffset(1.04)
    hist.GetYaxis().SetTitleOffset(1.14)
    hist.GetZaxis().SetTitleOffset(1.08)
    hist.Draw('COLZ')
    if number:
        latex = TLatex()
        latex.SetTextSize(0.8 * tsize)
        latex.SetTextAlign(22)
        latex.SetTextFont(62)
        latex.SetTextColor(kRed)
        for ix in range(1, hist.GetXaxis().GetNbins() + 1):
            x = hist.GetXaxis().GetBinCenter(ix)
            for iy in range(1, hist.GetYaxis().GetNbins() + 1):
                y = hist.GetYaxis().GetBinCenter(iy)
                latex.DrawLatex(x, y, str(Unroll.GetBin(x, y)))
    if nxbins > 0:  # divide with nlines
        for i in range(1, nxbins):
            x = xmin + (xmax - xmin) * i / nxbins
            line = TLine(x, ymin, x, ymax)
            line.SetLineColor(kRed)
            line.SetLineStyle(kDashed)
            line.SetLineWidth(1)
            line.Draw()
            lines.append(line)
    if nybins > 0:  # divide with nlines
        for i in range(1, nybins):
            y = ymin + (ymax - ymin) * i / nybins
            line = TLine(xmin, y, xmax, y)
            line.SetLineColor(kRed)
            line.SetLineStyle(kDashed)
            line.SetLineWidth(2)
            line.Draw()
            lines.append(line)
    canvas.RedrawAxis()
    canvas.SaveAs(hist.GetName() + ".png")
    #canvas.SaveAs(hist.GetName()+".pdf")
    canvas.Close()
示例#6
0
def makePlot(mds, ds, pdf):
    """ Mass fit plot """
    frame = mds.frame()
    ds.plotOn(frame, DataError(RooAbsData.SumW2), MarkerSize(1))
    pdf.plotOn(frame, LineWidth(2))

    # pull histogram
    pullHist = frame.pullHist()
    pullFrame = mds.frame(Title(''))
    pullFrame.addPlotable(pullHist, 'P')
    pullFrame.GetYaxis().SetRangeUser(-5, 5)

    canvas = TCanvas('m(Ds)', 'm(Ds)', 600, 700)
    canvas.cd()

    pad1 = TPad('pad1', 'pad1', .01, .20, .99, .99)
    pad2 = TPad('pad2', 'pad2', .01, .01, .99, .20)
    pad1.Draw()
    pad2.Draw()

    pad1.cd()
    pad1.SetLeftMargin(0.15)
    pad1.SetFillColor(0)

    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleOffset(0.85)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(1.6)
    frame.Draw()

    pad2.cd()
    pad2.SetLeftMargin(0.15)
    pad2.SetFillColor(0)
    
    pullFrame.SetMarkerSize(0.05)
    pullFrame.Draw()

    mdsRange = fitRange()['mDs']
    lineUp = TLine(mdsRange[0], 3, mdsRange[1], 3)
    lineUp.SetLineColor(kBlue)
    lineUp.SetLineStyle(2)
    lineUp.Draw()

    lineCe = TLine(mdsRange[0], 0, mdsRange[1], 0)
    lineCe.SetLineColor(kBlue)
    lineCe.SetLineStyle(1)
    lineCe.SetLineWidth(2)
    lineCe.Draw()

    lineD0 = TLine(mdsRange[0], -3, mdsRange[0], -3)
    lineD0.SetLineColor(kBlue)
    lineD0.SetLineStyle(2)
    lineD0.Draw()

    canvas.Update()
示例#7
0
def plot_event_selection(canvas, histos, save_name, label):

    canvas.Clear()
    canvas.Divide(2, 1)

    histos['histos_w_in_ctof'].SetLineColor(1)
    histos['histos_w_pass_angle_in_ctof'].SetLineColor(1)
    histos['histos_w_pass_angle_in_ctof'].SetFillColorAlpha(64, 1.0)

    histos['histos_angle_ep'].SetLineColor(1)
    histos['histos_angle_ep_pass_w_in_ctof'].SetLineColor(1)
    histos['histos_angle_ep_pass_w_in_ctof'].SetFillColorAlpha(64, 1.0)

    histos['histos_w_in_ctof'].SetMinimum(0)
    histos['histos_w_pass_angle_in_ctof'].SetMinimum(0)

    # Fix missing bins
    histos['histos_w_in_ctof'].GetXaxis().SetRangeUser(0.7, 1.3)
    histos['histos_w_pass_angle_in_ctof'].GetXaxis().SetRangeUser(0.7, 1.3)

    wleft = TLine(0.8, histos['histos_w_in_ctof'].GetMinimum(), 0.8,
                  0.8 * histos['histos_w_in_ctof'].GetMaximum())
    wright = TLine(1.08, histos['histos_w_in_ctof'].GetMinimum(), 1.08,
                   0.8 * histos['histos_w_in_ctof'].GetMaximum())

    wleft.SetLineColor(99)
    wleft.SetLineWidth(1)
    wright.SetLineColor(99)
    wright.SetLineWidth(1)

    canvas.cd(1)
    histos['histos_w_in_ctof'].Draw()
    histos['histos_w_pass_angle_in_ctof'].Draw('same')
    wleft.Draw()
    wright.Draw()

    label.DrawLatex(0.1, 0.925, 'Electron (forward) and Proton (central)')
    label.DrawLatex(0.5, 0.015, 'W (GeV/c^{2})')
    label.DrawLatex(0.67, 0.86, '#color[64]{#phi_{ep} > 174}')

    canvas.cd(2)
    histos['histos_angle_ep'].Draw()
    histos['histos_angle_ep_pass_w_in_ctof'].Draw('same')

    left = TLine(174, 0.0, 174, 0.8 * histos['histos_angle_ep'].GetMaximum())
    left.SetLineColor(99)
    left.SetLineWidth(1)
    left.Draw()

    label.DrawLatex(0.1, 0.925, 'Electron (forward) and Proton (central)')
    label.DrawLatex(0.5, 0.015, '#phi_{ep}')
    label.DrawLatex(0.57, 0.86, '#color[64]{W \in [0.8, 1.08]}')

    canvas.Print(save_name)
def addLinesOfCenter(x, y):
    line = TLine(0, y, x, y)
    line1 = TLine(x, 0, x, y)
    line.SetLineColor(2)
    line1.SetLineColor(2)
    #line1.Draw('same')
    #line.Draw('same')
    lines = []
    lines.append(line1)
    lines.append(line)
    return lines
def addCuts(histdict, outdir):

    c_2D = TCanvas('c_2D', 'ISR photons theta versus Energy', 700, 500)

    c_2D.cd(1)
    histdict["h_ISR_Theta_vs_E"].Draw("colz")

    f1 = TF1("cutThetaPos", "1.48", -1., 200)
    f1.SetLineStyle(7)
    f1.SetLineColor(2)
    f1.Draw("same")

    f2 = TF1("cutThetaNeg", "-1.48", -1., 200)
    f2.SetLineStyle(7)
    f2.SetLineColor(2)
    f2.Draw("same")

    # gPad.DrawFrame(0, -3.5, 150, 3.5)
    cutE = TLine(0.2, -3.5, 0.2, 3.5)
    cutE.SetLineColor(2)
    cutE.SetLineStyle(7)
    cutE.Draw("same")

    outfilename = "{}.root".format(outdir)
    outfile = TFile(outfilename, "UPDATE")
    c_2D.Write("", TObject.kOverwrite)
    outfile.Write()
    outfile.Close()
示例#10
0
文件: usefun.py 项目: pfjoker/phe_eff
def drawLine(xlow, ylow, xup, yup, lineWidth, lineStyle, lineColor):
    L1 = TLine(xlow, ylow, xup, yup)
    L1.SetLineWidth(lineWidth)
    L1.SetLineColor(lineColor)
    L1.SetLineStyle(lineStyle)
    L1.Draw("same")
    return L1
示例#11
0
def overlayProfile(l_prof, l_axis, l_histo, l_legend, l_text, l_legInfo, saveAs, saveString):
    
    aString, xLabel, yLabel, xOffset, yOffset, aLabSize, aTextSize = l_axis
    hString, c_x, c_y, yMin, yMax, hBins, hFile = l_histo
    lString, l_x1, l_y1, l_x2, l_y2, l_textSize = l_legend
    t_str, plotText, t_textSize, t_alignment, t_start, t_gap, t_x = l_text

    l_bins = PythonUtils.makeListFromString(hBins, ';')

    gROOT.SetBatch(1)
    c = TCanvas('c', 'c', int(c_x), int(c_y))
    gStyle.SetOptStat(0)
    c.SetTicks(1, 1)

    for i in xrange(len(l_prof)):
        if i == 0:
            l_prof[i].Draw('eps')
            setupAxes(l_prof[i], xLabel, yLabel, xOffset, yOffset,
                      aTextSize, l_bins[0], l_bins[len(l_bins) -1], 1)
            l_prof[i].SetMinimum(float(yMin))
            l_prof[i].SetMaximum(float(yMax))
            l_prof[i].SetTitle('')
            hLine = TLine(l_prof[i].GetXaxis().GetXmin(), 1, l_prof[i].GetXaxis().GetXmax(), 1)
            hLine.SetLineWidth(2)
            hLine.SetLineColor(1)
            hLine.SetLineStyle(2)
            hLine.Draw('same')
        else:
            l_prof[i].Draw('eps same')

    setupTextOnPlot(plotText, t_textSize, t_alignment, t_x, t_start, t_gap)
    setupLegend(l_legInfo, l_x1, l_y1, l_x2, l_y2, l_textSize)
    savePlots(c, saveString, saveAs)
示例#12
0
def CheckToysTempFiles(sample='tW', histo='dnn'):
  path = baseoutpath%(year, ms, ml)
  f = TFile.Open(path+sample+ ('.root' if not sample.endswith('.root') else ''))
  hnom = f.Get(histo)
  nom = hnom.Integral()
  h = TH1F('h', 'h', 20, 0.24, 0.26)
  for i in range(nToys):
    ht = f.Get(histo+'_NormToy%i'%i)
    h.Fill(ht.Integral())

  c = TCanvas('c', 'c', 10, 10, 1200, 800)
  h.SetStats(0)
  h.SetTitle('')
  h.GetXaxis().SetTitle("Yield %s"%sample)
  h.GetYaxis().SetTitle("Number of toys")
  h.SetLineWidth(2); h.SetLineColor(kOrange+1)
  h.SetFillColor(0)
  h.Draw('hist')

  l = TLine(nom, 0, nom, h.GetMaximum())
  l.SetLineColor(kGray+3); l.SetLineWidth(2); l.SetLineStyle(2)
  l.Draw("same")

  name = 'toys_%s_%s'%(sample, histo)
  for form in ['png', 'pdf']: c.SaveAs(webpath+name+'.'+form)
示例#13
0
def myLineBoxTextBorder(x, y, lcolor, lstyle, bcolor, bstyle, bsize, tsize, text):
    l = TLatex()
    l.SetTextAlign(12)
    l.SetTextSize(tsize/2.5)
    l.SetNDC()
    l.DrawLatex(x,y,text)

    yl1 = y-0.25*bsize
    yl2 = y+0.25*bsize
    xl1 = x-0.25*bsize-0.4*bsize
    xl2 = x+0.25*bsize-0.4*bsize

    #print("line = ",xl1,yl1,xl2,yl2)
    mline = TLine(xl1,yl1,xl2,yl2)
    mline.SetLineColor(lcolor)
    mline.SetLineStyle(lstyle)
    mline.SetLineWidth(2)
    y_new=(yl1+yl2)/2.
    mline.DrawLineNDC(xl1,y_new,xl2,y_new)

    yb1 = y-0.15*bsize
    yb2 = y+0.15*bsize
    xb1 = x-0.25*bsize-0.4*bsize
    xb2 = x+0.25*bsize-0.4*bsize

    #print("box  = ",xb1,yb1,xb2,yb2)
    mbox = TPave(xb1,yb1,xb2,yb2,1,"NDC")
    mbox.SetLineWidth(2)
    mbox.SetLineColor(1)
    mbox.SetFillColor(bcolor)
    mbox.SetFillStyle(bstyle)
    mbox.Draw("l")
    
    return mbox
示例#14
0
def drawLine(x1, y1, x2, y2, color=1):
    line = TLine(x1, y1, x2, y2)
    line.SetLineStyle(2)
    line.SetLineWidth(2)
    line.SetLineColor(color)
    line.Draw()
    return line
示例#15
0
 def addLine(self, x1, y1, x2, y2, color, thickness=0.):
     line = TLine(x1, y1, x2, y2)
     line.SetLineColor(color)
     line.SetLineStyle(2)
     if thickness:
         line.SetLineWidth(thickness)
     self.lines.append(line)
示例#16
0
def write_spikeroothistogram(vectorspikes, histogramtitle, ytitle,
                             rootdirectory, deltatime):
    """Function to perform ROOT histograms"""

    #Set ROOT histograms
    TH1Hist = TH1F(histogramtitle, "", 3, 0, 3)

    vectorspikes = [x[5:len(x)] for x in vectorspikes]

    #Fill histograms in for loop
    for entry in range(len(vectorspikes)):
        TH1Hist.Fill(vectorspikes[entry], 1. / (deltatime / 60))

    #Draw + DrawOptions histograms
    c = TCanvas()
    c.SetName(histogramtitle + "_canvas")
    Style = gStyle
    Style.SetLineWidth(1)  #TH1Hist
    Style.SetOptStat(0)  #Show statistics
    gROOT.ForceStyle()
    TH1Hist.SetCanExtend(TH1.kAllAxes)
    TH1Hist.SetFillColor(38)
    TH1Hist.LabelsDeflate()
    TH1Hist.SetMinimum(0)
    TH1Hist.SetMaximum(2)
    YAxis = TH1Hist.GetYaxis()
    YAxis.SetTitle(ytitle)
    rootdirectory.WriteTObject(TH1Hist)
    line = TLine(0., 1.0, len(set(vectorspikes)), 1.0)
    line.SetLineStyle(2)
    line.SetLineColor(2)
    TH1Hist.Draw("histo")
    line.Draw()
    rootdirectory.WriteTObject(c)
示例#17
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)
示例#18
0
def plot_GOF(hist, obs, critical, p_value, alpha="0.05"):
    # canvas
    canv = TCanvas("canv", "canv", 600, 600)
    canv.SetBottomMargin(0.10)
    canv.SetLeftMargin(0.15)
    canv.SetRightMargin(0.12)
    # histograms
    hist.SetMarkerColor(0)
    hist.SetTitle("GOF test - toys {}".format(int(hist.GetEntries())))
    hist.GetXaxis().SetTitleFont(43)
    hist.GetYaxis().SetTitleFont(43)
    hist.GetXaxis().SetTitleSize(20)
    hist.GetYaxis().SetTitleSize(20)
    hist.GetXaxis().SetTitleOffset(0.8)
    hist.GetYaxis().SetTitleOffset(1.5)
    hist.GetXaxis().SetTitle("Statistics")
    hist.GetYaxis().SetTitle("Probability")
    hist.Draw("hist")
    up = hist.GetMaximum()
    hist.GetYaxis().SetRangeUser(0, 1.2 * up)
    # lines
    c_line = TLine(critical, 0, critical, 1.2 * up)
    c_line.SetLineColor(2)
    c_line.SetLineWidth(4)
    c_line.SetLineStyle(2)
    c_line.Draw("L same")
    obs_line = TLine(obs, 0, obs, 1.2 * up)
    obs_line.SetLineColor(1)
    obs_line.SetLineWidth(4)
    obs_line.Draw("L same")
    # legend
    leg = TLegend(0.6, 0.65, .95, .95)
    leg.SetFillColor(0)
    leg.SetShadowColor(0)
    leg.SetLineColor(0)
    leg.SetTextFont(43)
    leg.SetTextSize(18)
    leg.AddEntry(c_line, "alpha = {}".format(alpha), 'L')
    leg.AddEntry(obs_line, "data (p-value={0:.2f})".format(p_value), 'L')
    leg.AddEntry(hist, "toys", "L")
    leg.Draw("same")
    # save canvas
    canv.SaveAs("{}.pdf".format(saveout))
    canv.SaveAs("{}.png".format(saveout))
    canv.SaveAs("{}.root".format(saveout))

    return canv
示例#19
0
def GetLine(x1,y1,x2,y2,color,style,width, text=''):
  from ROOT import TLine
  l = TLine(x1,y1,x2,y2)
  l.SetNDC(False)
  l.SetLineColor(color)
  l.SetLineWidth(width)
  l.SetLineStyle(style)
  return l
示例#20
0
文件: lat3.py 项目: 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
示例#21
0
def draw_line(lineList,x1,x2,y1,y2,width=1,style=1,color=1):
    from ROOT import TLine
    l=TLine(x1,y1,x2,y2)
    l.SetBit(ROOT.kCanDelete)
    l.SetLineWidth(width)
    l.SetLineStyle(style)
    l.SetLineColor(color)
    l.Draw()
    lineList.append(l)
示例#22
0
def col_lin(col, w=4, st=rt.kSolid):

    #create line of a given color
    lin = TLine()
    lin.SetLineColor(col)
    lin.SetLineWidth(w)
    lin.SetLineStyle(st)

    return lin
示例#23
0
def ratioplot():
    # create required parts

    leg = getLegend()
    latex = getLatex()
    c = TCanvas()
    c.SetLogy()

    #Draw input histograms
    hists = ['h_frac_recoil_', 'h_full_recoil_']
    label = ['recoil with MET triggers', 'recoil without MET triggers']
    combineHist(hists, label, leg)
    #leg.Draw()
    #c.SaveAs("Combinehists_D.pdf")

    ratio = []
    h1 = f.Get('h_frac_recoil_')
    #h1=setHistStyle(h1,bins)
    h2 = f.Get('h_full_recoil_')
    #h2=setHistStyle(h2,bins)

    h3 = createRatio(h1, h2)
    gr = TGraphAsymmErrors(h1, h2)
    gr.GetXaxis().SetRangeUser(0, 1500)
    gr.GetYaxis().SetRangeUser(0, 1.2)
    gr.SetMarkerStyle(20)
    gr.SetMarkerSize(0.5)
    gr.SetLineColor(1)
    gr.GetYaxis().SetTitle("Trigger Efficiency")
    gr.GetXaxis().SetTitle("Recoil [GeV]")
    gr.SetTitle("")

    # print ("ratio",ratio )
    # c, pad1, pad2 = createCanvasPads()
    #
    # # draw everything
    # pad1.cd()
    # h1.Draw()
    # h2.Draw("same")
    # to avoid clipping the bottom zero, redraw a small axis
    # h1.GetYaxis().SetLabelSize(0.0)
    # axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "")
    # axis.SetLabelFont(43)
    # axis.SetLabelSize(15)
    # axis.Draw()
    # pad2.cd()
    gr.Draw()
    latex.DrawLatex(0.41, 0.93, "Trigger Efficincy in MET Run2017E")
    xmin = 0.0
    line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1500, 1)
    line.SetLineColor(1)
    line.SetLineWidth(1)
    line.SetLineStyle(7)
    line.Draw()
    #h3.Draw('pl')
    c.SaveAs("test.pdf")
示例#24
0
  def plotGraph(self, x='vv', y='acc'): 
    '''
    Plot a graph with specified quantities on x and y axes , and saves the graph
    '''

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

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

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

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

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

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

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

    self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph
    # add the graph container for memory?
    graph_saver.append(graph)
示例#25
0
文件: util.py 项目: kaducovas/ringer
def AddBinLines(can, hist, useHistMax=False, horizotalLine=1., lineStyle=2):
    tobject_collector = []
    from ROOT import TH1, TGraph, THStack, TColor, kGray, kBlue, TLine, kRed
    if can.GetPrimitive('pad_top'):
        tobject_collector.extend(
            AddBinLines(can.GetPrimitive('pad_top'), hist, useHistMax,
                        horizotalLine))
        if can.GetPrimitive('pad_bot'):
            # TODO Move this to another function
            pad = GetBotPad(can)
            tobject_collector.extend(AddBinLines(pad, hist))
            if horizotalLine is not None and pad.GetUymax(
            ) > horizotalLine > pad.GetUymin():
                pad.cd()
                maxValue = pad.GetUxmax()
                minValue = pad.GetUxmin()
                l = TLine(minValue, horizotalLine, maxValue, horizotalLine)
                l.SetLineColor(kRed)
                l.SetLineStyle(2)
                l.Draw()
                tobject_collector.append(l)
        return tobject_collector
    can.cd()
    #listOfPlottedObjects = [o for o in can.GetListOfPrimitives() if isinstance(o,(TH1, THStack))]
    #listOfPlottedObjects += [o.GetHistogram() for o in can.GetListOfPrimitives() if isinstance(o,TGraph)]
    #if listOfPlottedObjects:
    #maxValue = max([o.GetBinContent(o.GetMaximumBin()) + o.GetBinError(o.GetMaximumBin()) for o in listOfPlottedObjects])
    #minValue = min([o.GetBinContent(o.GetMinimumBin()) - o.GetBinError(o.GetMinimumBin()) for o in listOfPlottedObjects])
    maxValue = hist.GetBinContent(
        hist.GetMaximumBin()) if useHistMax else can.GetUymax()
    minValue = can.GetUymin()

    for x in range(2, hist.GetXaxis().GetNbins() + 1):
        xv = hist.GetBinLowEdge(x)
        line = TLine(xv, minValue, xv, maxValue)
        line.SetLineColor(17)
        line.SetLineStyle(lineStyle)
        line.Draw()
        tobject_collector.append(line)

    return tobject_collector
示例#26
0
def evalDiode():
    datalist = loadCSVToList('../data/part1/Kennlinie.txt')
    data = DataErrors()
    U0 = datalist[0][1]
    sU0 = 0.05 + 0.01 * U0
    for I, u in datalist:
        U = u - U0
        su = 5 + 0.01 * u
        sU = sqrt(su**2 + sU0**2)
        data.addPoint(I, U, 0.1, sU)
    xmin, xmax = 53, 71.5

    c = TCanvas('c_diode', '', 1280, 720)
    g = data.makeGraph('g_diode', "Laserstrom I_{L} / mA",
                       "Photodiodenspannung U_{ph} / mV")
    g.GetXaxis().SetRangeUser(-5, 90)
    g.SetMinimum(-50)
    g.SetMaximum(1400)
    g.Draw('APX')

    # y=0 line
    line = TLine(-5, 0, 90, 0)
    line.SetLineColor(OPData.CH2ECOLOR)
    line.Draw()

    data.filterX(xmin, xmax)
    g2 = data.makeGraph('g_diode_2', "Laserstrom I_{L} / mA",
                        "Photodiodenspannung U_{ph} / mV")
    g2.SetMarkerColor(OPData.CH1COLOR)
    g2.SetLineColor(OPData.CH1COLOR)

    fit = Fitter('fit_diode', '[0] * (x-[1])')
    fit.function.SetNpx(1000)
    fit.setParam(0, 'a', 1)
    fit.setParam(1, 'I_{th}', 50)
    fit.fit(g2, 40, 77)
    fit.saveData('../fit/part1/kennlinie.txt')

    l = TLegend(0.15, 0.55, 0.4, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Laserdiodenkennlinie', 'p')
    l.AddEntry(g2, 'Ausschnitt zum Fitten', 'p')
    l.AddEntry(fit.function, 'Fit mit U_{ph} = a (I_{ L} - I_{ th} )', 'l')
    fit.addParamsToLegend(l, (('%.1f', '%.1f'), ('%.2f', '%.2f')),
                          chisquareformat='%.2f',
                          units=['mV/mA', 'mA'])
    l.Draw()

    g.Draw('P')
    g2.Draw('P')

    c.Update()
    c.Print('../img/part1/diodenkennlinie.pdf', 'pdf')
def plot_sector_page_single(canvas,
                            histos,
                            title_formatter,
                            save_name,
                            xtitle=None,
                            ytitle=None,
                            title=None,
                            x_range=None,
                            log=False,
                            hline=None):
    """ Plot one histogram for each sector. """

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.045)

    canvas.Clear()
    canvas.Divide(3, 2)

    root_garbage_can = []
    for i in range(1, 7):
        canvas.cd(i)

        if x_range:
            histos.get(title_formatter.format(i),
                       default_histo2d).GetXaxis().SetRangeUser(
                           x_range[0], x_range[1])

        histos.get(title_formatter.format(i), default_histo2d).Draw('colz')
        if log:
            gPad.SetLogz()

        if title:
            label.DrawLatex(0.1, 0.925, title)

        if xtitle:
            label.DrawLatex(0.45, 0.015, xtitle)

        if ytitle:
            label.SetTextAngle(90)
            label.DrawLatex(0.0325, 0.65, ytitle)
            label.SetTextAngle(0)

        if hline:
            xmin = histos.get(title_formatter.format(i)).GetXaxis().GetXmin()
            xmax = histos.get(title_formatter.format(i)).GetXaxis().GetXmax()
            line = TLine(xmin, hline, xmax, hline)
            line.SetLineColor(1)
            line.SetLineStyle(1)
            line.Draw('same')
            root_garbage_can.append(line)

    canvas.Print(save_name)
示例#28
0
def myMarkerTextSmall2(x, y, lcolor, lstyle, mcolor, mstyle, msize, size,
                       text):

    l = TLatex()
    l.SetTextAlign(12)
    l.SetTextSize(size / 2.5)
    l.SetNDC()
    l.DrawLatex(x, y, text)

    yb1 = y - 0.15 * size
    yb2 = y + 0.15 * size
    xb1 = x - 0.28 * size - 0.45 * size
    xb2 = x + 0.28 * size - 0.45 * size

    print "box  = ", xb1, yb1, xb2, yb2

    #print "line = ",xl1,yl1,xl2,yl2
    mline1 = TLine(xb1, yb1, xb2, yb2)
    mline1.SetLineColor(lcolor)
    mline1.SetLineStyle(lstyle)
    mline1.SetLineWidth(2)
    y_new = (yb1 + yb2) / 2.
    mline1.DrawLineNDC(xb1, y_new, xb2, y_new)

    mline2 = TLine(xb1, yb1, xb2, yb2)
    mline2.SetLineColor(lcolor)
    mline2.SetLineStyle(lstyle)
    mline2.SetLineWidth(2)
    x_new = (xb1 + xb2) / 2.
    mline2.DrawLineNDC(x_new, yb1, x_new, yb2)

    marker = TMarker((xb1 + xb2) / 2.0, y, mstyle)
    marker.SetNDC()
    marker.SetMarkerColor(mcolor)
    marker.SetMarkerStyle(mstyle)
    marker.SetMarkerSize(msize)
    marker.Draw()

    return marker
示例#29
0
def plot_correction( h2, slope, offset, x_points, y_points, error_points, outname, 
                     xlabel='',
                     etBinIdx=None, 
                     etaBinIdx=None, 
                     etBins=None,
                     etaBins=None, 
                     label='Internal',
                     ref_value=None, 
                     pd_value=None,
                     palette=kBlackBody):

    def toStrBin(etlist = None, etalist = None, etidx = None, etaidx = None):
        if etlist and etidx is not None:
            etlist=copy(etlist)
            if etlist[-1]>9999:  etlist[-1]='#infty'
            binEt = (str(etlist[etidx]) + ' < E_{T} [GeV] < ' + str(etlist[etidx+1]) if etidx+1 < len(etlist) else
                                     'E_{T} > ' + str(etlist[etidx]) + ' GeV')
            return binEt
        if etalist and etaidx is not None:
            binEta = (str(etalist[etaidx]) + ' < |#eta| < ' + str(etalist[etaidx+1]) if etaidx+1 < len(etalist) else
                                        str(etalist[etaidx]) + ' <|#eta| < 2.47')
            return binEta

    canvas = TCanvas("canvas","canvas",500,500)
    rpl.set_figure(canvas)
    gStyle.SetPalette(palette)
    canvas.SetRightMargin(0.15)
    canvas.SetTopMargin(0.15)
    canvas.SetLogz()
    h2.GetXaxis().SetTitle('Neural Network output (Discriminant)')
    h2.GetYaxis().SetTitle(xlabel)
    h2.GetZaxis().SetTitle('Count')
    h2.Draw('colz')
    g = TGraphErrors(len(x_points), array.array('d',x_points), array.array('d',y_points), array.array('d',error_points), array.array('d',[0]*len(x_points)))
    g.SetMarkerColor(kBlue)
    g.SetMarkerStyle(8)
    g.SetMarkerSize(1)
    g.Draw("P same")
    line = TLine(slope*h2.GetYaxis().GetXmin()+offset,h2.GetYaxis().GetXmin(), slope*h2.GetYaxis().GetXmax()+offset, h2.GetYaxis().GetXmax())
    line.SetLineColor(kBlack)
    line.SetLineWidth(2)
    line.Draw()
    # Add text labels into the canvas
    text = toStrBin(etlist=etBins, etidx=etBinIdx)
    text+= ', '+toStrBin(etalist=etaBins, etaidx=etaBinIdx)
    if ref_value and pd_value:
        text+=', P_{D} = %1.2f (%1.2f) [%%]'%(pd_value*100, ref_value*100)
    rpl.add_text(0.15, 0.885, text, textsize=.03)
    rpl.set_atlas_label(0.15, 0.94, label)
    rpl.format_canvas_axes(XLabelSize=16, YLabelSize=16, XTitleOffset=0.87, ZLabelSize=16,ZTitleSize=16, YTitleOffset=0.87, ZTitleOffset=1.1)
    canvas.SaveAs(outname)
示例#30
0
def BuildTLine(xmin_in, ymin_in, xmax_in, ymax_in, Properties):

    xmin = Properties.get('xmin_tline', xmin_in)
    xmax = Properties.get('xmax_tline', xmax_in)
    ymin = Properties.get('ymin_tline', ymin_in)
    ymax = Properties.get('ymax_tline', ymax_in)

    linewidth = Properties.get('lineWidth_tline', 1)
    linestyle = Properties.get('lineStyle_tline', 1)
    linecolor = Properties.get('lineColor_tline', 1)

    line = TLine(xmin, ymin, xmax, ymax)
    line.SetLineWidth(linewidth)
    line.SetLineStyle(linestyle)
    line.SetLineColor(linecolor)

    return line