예제 #1
0
def evt_Log10_Q2_y():

    #log_10(Q^2) and y

    lqbin = 5e-2
    #lqmin = -5
    lqmin = -10
    lqmax = -1.5

    ybin = 1e-2
    #ymin = 0.06
    ymin = 0
    ymax = 0.8

    yform = "(18.-el_gen)/18."

    hLog10Q2yTag = ut.prepare_TH2D("hLog10Q2yTag", ybin, ymin, ymax, lqbin,
                                   lqmin, lqmax)

    can = ut.box_canvas()

    tree.Draw(gL10Q2 + ":" + yform + " >> hLog10Q2yTag", gQ2sel)

    ut.put_yx_tit(hLog10Q2yTag, "log_{10}(#it{Q}^{2})", "y", 1.6, 1.4)

    gPad.SetLogx()

    hLog10Q2yTag.Draw()

    ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
예제 #2
0
def plot_ecal_flatten_hist(event1, event2, out_file, energy):
    c1 = TCanvas("c1", "", 200, 10, 700, 500)  #make
    hd = ROOT.TH1F("DATA", "", 100, -6, 0)
    hg = ROOT.TH1F("GAN", "GAN", 100, -6, 0)
    BinLogX(hd)
    BinLogX(hg)
    c1.SetGrid()
    gPad.SetLogx()

    fill_hist(hd, event1.flatten())
    fill_hist(hg, event2.flatten())
    if energy == 0:
        hd.SetTitle("Ecal Flat Histogram for Uniform Spectrum")
    else:
        hd.SetTitle("Ecal Flat Histogram for {} GeV".format(energy))
    hd.GetXaxis().SetTitle("Ecal GeV")
    #Eprof.GetYaxis().SetTitle("Ecal/Ep")
    #Eprof.GetYaxis().SetRangeUser(0, 2)
    hd.Draw()
    hd.SetLineColor(4)
    hg.SetLineColor(2)
    hg.Draw('sames')
    c1.Update()
    stat_pos(hg)
    c1.Update()
    legend = TLegend(.5, .8, .6, .9)
    legend.AddEntry(hd, "Data", "l")
    legend.AddEntry(hg, "GAN", "l")
    legend.Draw()
    c1.Modified()
    c1.Update()
    c1.Print(out_file)
예제 #3
0
def efficiencytracking():

    hadron_list = ["pion", "proton", "electron", "muon"]
    color_list = [1, 2, 4, 6]
    fileo2 = TFile("../codeHF/AnalysisResults_O2.root")

    c1 = TCanvas("c1", "A Simple Graph Example")
    c1.SetCanvasSize(1500, 1500)
    c1.cd()
    gPad.SetLogx()
    gPad.SetLogy()
    eff_list = []
    hempty = TH1F("hempty", ";p_{T};efficiency", 100, 0.001, 5.0)
    hempty.Draw()
    leg = TLegend(0.1, 0.7, 0.3, 0.9, "")
    leg.SetFillColor(0)

    for i, had in enumerate(hadron_list):
        hnum = fileo2.Get("qa-tracking-efficiency-%s/num" % had)
        hden = fileo2.Get("qa-tracking-efficiency-%s/den" % had)
        hnum.Rebin(4)
        hden.Rebin(4)
        eff = TEfficiency(hnum, hden)
        eff.SetLineColor(color_list[i])
        eff_list.append(eff)
        eff.Draw("same")
        leg.AddEntry(eff_list[i], had)
    leg.Draw()
    c1.SaveAs("efficiency_tracking.pdf")
예제 #4
0
def gen_xy():

    #distribution of x and y

    xbin = 2e-9
    xmin = 8e-14
    xmax = 2e-4

    ybin = 1e-2
    ymin = 0.06
    ymax = 1.1

    hXY = ut.prepare_TH2D("hXY", xbin, xmin, xmax, ybin, ymin, ymax)

    tree.Draw("gen_y:gen_x >> hXY")

    can = ut.box_canvas()

    ut.put_yx_tit(hXY, "#it{y}", "#it{x}", 1.4, 1.2)

    hXY.Draw()

    gPad.SetLogx()
    gPad.SetLogz()

    ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
def drawtwo(h, logx=False, logy=False, project=True, ratio=True, V=True):
    def equals(h1, h2, Ck):
        cmd = ["h1." + Ck, "h2." + Ck]
        cmdR = [eval(cmd[0]), eval(cmd[1])]
        V = cmdR[0] == cmdR[1]
        if not V:
            raise ValueError(h1, "differs from", h2, Ck, cmd, cmdR)

    for i in "GetName GetNbinsX GetXaxis().GetTitle".split():
        equals(h[0], h[1], i + "()")
    nextpad()
    if logy:
        gPad.SetLogy()
    if logx:
        gPad.SetLogx()
    hrun2 = h[0]
    hrun3 = h[1]
    if project and "TH2" in h[0].ClassName():
        hrun2 = h[0].ProjectionY("Y1_" + h[0].GetName())
        hrun3 = h[1].ProjectionY("Y2_" + h[1].GetName())
    if V:
        print("Drawing", h)
    if "TH2" in hrun2.ClassName() and not project:
        draw(hrun2, "COLZ")
        nextpad()
        if logy:
            gPad.SetLogy()
        if logx:
            gPad.SetLogx()
        draw(hrun3, "COLZ")
    else:
        draw(hrun2)
        draw(hrun3, "same")
        drawcounts([hrun2, hrun3])
    print(
        "Entries of", hrun2.GetName(), hrun2.GetEntries(), "vs", hrun3.GetEntries(),
    )
    if "TH1" in h[0].ClassName():
        legends[-1].Draw()
    if ratio:
        nextpad()
        drawrange(hrun2, [0.5, 1.5], ytit="Run2/Run3")
        hratio = draw(hrun2, "same", copy=True, labelize=False)
        hratio.SetTitle(hratio.GetTitle() + " Ratio")
        hratio.Divide(hrun3)
        gPad.Update()
예제 #6
0
파일: rutil.py 프로젝트: apjd/usercode
    def __init__(self,
                 title,
                 xtitle="",
                 xmin=0,
                 xmax=1.,
                 ytitle="",
                 ymin=0,
                 ymax=0.,
                 option="",
                 nxbin=2,
                 nybin=2,
                 logy=False,
                 logx=False):
        randomid = "%d" % (random.randint(10000000000, 99999999999))
        self.ymin = ymin
        self.ymax = ymax
        self.xmin = xmin
        self.xmax = xmax
        self.palette = (1, 2, 4, 8, 9, 42, 46, 38, 31)
        self.logy = logy
        if logy and self.ymin <= 0:
            self.ymin = 1.e-5

        self.logx = logx
        if logx and self.xmin <= 0:
            self.xmin = 1.e-5

        if ymax > ymin:
            self.hF = TH2F(randomid, title, nxbin, xmin, xmax, nybin, ymin,
                           ymax)
        else:
            self.hF = TH2F(randomid, title, nxbin, xmin, xmax, nybin, ymin,
                           ymin + 1)
            ymax = ymin + 1

        self.yaxis2 = None
        self.hF.GetXaxis().SetTitle(xtitle)
        self.hF.GetYaxis().SetTitle(ytitle)

        if logy:
            gPad.SetLogy()
        if logx:
            gPad.SetLogx()
        self.hF.SetStats(0)
        self.hF.Draw()
        self.pad = gPad.cd()  # yes, the cd() is needed, gPad is special

        self.items = []
        self.options = []
        self.labels = []
        # list of options (e.g. logy), comma or white-space separated
        self.frame_options = option.replace(",", " ").split()

        self.tls = []
        self.tlines = []
예제 #7
0
def conv_theta():

    #conversion probablity as a function of polar angle theta

    tbin = 2e-4
    tmin = 0
    tmax = 2.5e-3

    prec = 0.01
    delt = 1e-6

    gROOT.LoadMacro("get_ew_conv.C")
    #hEffV1 = rt.get_ew_conv(tree_v1, "phot_theta", "ew_conv", prec, delt, -1., TMath.Pi())
    hEffV2 = rt.get_ew_conv(tree_v2, "phot_theta", "ew_conv", prec, delt, -1.,
                            TMath.Pi())

    #hEffV1 = get_eff(tree_v1, "TMath::Pi()-phot_theta", "ew_conv", tbin, tmin, tmax)
    #hEffV2 = get_eff(tree_v2, "TMath::Pi()-phot_theta", "ew_conv", tbin, tmin, tmax)

    #ut.set_graph(hEffV1, rt.kBlue)
    #ut.set_graph(hEffV2, rt.kRed, rt.kFullTriangleUp)
    #hEffV2.SetMarkerSize(1.5)
    ut.set_graph(hEffV2)

    #plot the probability
    can = ut.box_canvas()

    frame = gPad.DrawFrame(tmin, 0.065, tmax, 0.095)

    frame.SetXTitle("Generated #vartheta (rad)")
    frame.SetYTitle("Conversion probability")

    frame.SetTitleOffset(2.1, "Y")
    frame.SetTitleOffset(1.5, "X")

    ut.set_margin_lbtr(gPad, 0.14, 0.11, 0.02, 0.01)

    frame.Draw()

    #hEffV1.Draw("psame")
    hEffV2.Draw("psame")

    leg = ut.prepare_leg(0.2, 0.84, 0.2, 0.1, 0.035)
    #leg.AddEntry(hEffV1, "Tilted plane", "lp")
    leg.AddEntry(hEffV2, "Half-cylinder", "lp")
    #leg.Draw("same")

    gPad.SetLogx()

    #ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
예제 #8
0
def gamma_p_sqrt_ys():

    #total gamma-proton cross section as a function of sqrt(sy), the CM energy s and generated y

    sqrt_s = 140.7  # GeV, 18x275
    #sqrt_s = 63.3 # GeV, 10x100
    #sqrt_s = 28.6 # GeV, 5x41

    #sqrt(sy) range
    sybin = 0.1
    symin = 0
    symax = 160

    #cross section range
    sigbin = 0.01
    sigmin = 0
    sigmax = 0.5

    hGPys = ut.prepare_TH2D("hGPys", sybin, symin, symax, sigbin, sigmin,
                            sigmax)

    #cross section formula
    scm = sqrt_s**2
    sig_form = "0.0677*TMath::Power((true_y*" + str(scm) + "), 0.0808)"
    sig_form += "+0.129*TMath::Power((true_y*" + str(scm) + "), -0.4525)"

    #sqrt(sy) formula
    syform = "TMath::Sqrt(true_y*" + str(scm) + ")"

    #print sig_form
    #print syform

    tree.Draw("(" + sig_form + "):(" + syform + ") >> hGPys")

    can = ut.box_canvas()

    ut.put_yx_tit(hGPys, "#sigma(#gamma p) (mb)", "#sqrt{ys}", 1.4, 1.2)

    hGPys.Draw()

    gPad.SetGrid()

    gPad.SetLogx()

    ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
예제 #9
0
파일: test.py 프로젝트: skluth/sjmanalysis
 def plot( self, plotoptions, opt="?" ):
     vx= array( "d", self.aostand.getPointsCenter() )
     values= self.values
     sterrs= self.sterrs
     if "m" in opt:
         print "AnalysisObservable::plot: use errors from error matrix"
         sterrs= array( "d", self.aostand.getErrors( "m" ) )
     syerrs= self.syerrs
     npoints= len(vx)
     if "xshift" in plotoptions:
         for i in range(npoints):
             vx[i]+= plotoptions["xshift"]
     vex= array( "d", npoints*[0.0] )
     tgest= TGraphErrors( npoints, vx, values, vex, sterrs )
     toterrs= np.sqrt( np.add( np.square( sterrs ),  np.square( syerrs ) ) )
     tgesy= TGraphErrors( npoints, vx, values, vex, toterrs )
     tgesy.SetMarkerStyle( plotoptions["markerStyle"] )
     tgesy.SetMarkerSize( plotoptions["markerSize"] )
     drawas= plotoptions["drawas"] if "drawas" in plotoptions else "p"
     tgesy.SetName( self.obs )
     if "fillcolor" in plotoptions:
         tgesy.SetFillColor(plotoptions["fillcolor"])
         tgest.SetFillColor(plotoptions["fillcolor"])
     if "s" in opt:
         tgesy.Draw( "psame" )
     else:
         if "title" in plotoptions:
             tgesy.SetTitle( plotoptions["title"] )
         else:
             tgesy.SetTitle( self.obs )
         tgesy.SetMinimum( plotoptions["ymin"] )
         tgesy.SetMaximum( plotoptions["ymax"] )
         xaxis= tgesy.GetXaxis()
         xaxis.SetLimits( plotoptions["xmin"], plotoptions["xmax"] )
         if "xlabel" in plotoptions:
             xaxis.SetTitle( plotoptions["xlabel"] )
         if "ylabel" in plotoptions:
             tgesy.GetYaxis().SetTitle( plotoptions["ylabel"] )
         tgesy.Draw( "a"+drawas )
     optlogx= plotoptions["logx"] if "logx" in plotoptions else 0
     gPad.SetLogx( optlogx )
     optlogy= plotoptions["logy"] if "logy" in plotoptions else 0
     gPad.SetLogy( optlogy )
     tgest.Draw( "same"+drawas )
     return tgest, tgesy
예제 #10
0
def plot_ecal_flatten_hist(event1,
                           event2,
                           out_file,
                           energy,
                           labels,
                           ifpdf=True):
    c1 = TCanvas("c1", "", 200, 10, 700, 500)  #make
    c1.SetGrid()
    color = 2
    gPad.SetLogx()
    hd = ROOT.TH1F("Geant4", "", 100, -6, 0)
    my.BinLogX(hd)
    my.fill_hist(hd, event1.flatten())
    if energy == 0:
        hd.SetTitle("Ecal Flat Histogram for Uniform Spectrum")
    else:
        hd.SetTitle("Ecal Flat Histogram for {} GeV".format(energy))
    hd.GetXaxis().SetTitle("Ecal GeV")
    hd.Draw()
    hd.SetLineColor(color)
    legend = TLegend(.5, .8, .6, .9)
    legend.AddEntry(hd, "Geant4", "l")
    color += 2
    hgs = []
    pos = 0
    for i, key in enumerate(event2):
        hgs.append(ROOT.TH1F("GAN" + str(i), "GAN" + str(i), 100, -6, 0))
        hg = hgs[i]
        my.BinLogX(hg)
        my.fill_hist(hg, event2[key].flatten())
        hg.SetLineColor(color)
        color += 2
        hg.Draw('sames')
        c1.Update()
        my.stat_pos(hg, pos)
        pos += 1
        c1.Update()
        legend.AddEntry(hg, "GAN {}".format(labels[i]), "l")
    legend.Draw()
    c1.Modified()
    c1.Update()
    if ifpdf:
        c1.Print(out_file + '.pdf')
    else:
        c1.Print(out_file + '.C')
예제 #11
0
def drawCorrVsHits(detector):
    from ROOT import TCanvas
    from ROOT import TGraph
    from array import array
    from ROOT import gPad
    CorrVsHits = TCanvas("CorrVsHits", "Alignment Corrections vs hits")
    CorrVsHits.Divide(3, 2)
    hCorrVsHits = {}
    Color = AutoColors(len(detector))
    for det in detector:
        hCorrVsHits[det] = {}
        for i in range(6):
            CorrVsHits.cd(i + 1)
            name, value = detector[det].GetModule(0).GetDoF(i)
            hname = 'CorrVsHits_%s_corrections_%d' % (name, det)
            htitle = '%s Corrections vs hits_%d' % (name, det)
            xpoints = []
            ypoints = []
            for j in range(detector[det].nModules()):
                xpoints.append(detector[det].GetModule(j).Hits)
                ypoints.append(detector[det].GetModule(j).GetDoF(i)[1])
            x = array("f", xpoints)
            y = array("f", ypoints)
            hCorrVsHits[det][name] = TGraph(detector[det].nModules(), x, y)
            hCorrVsHits[det][name].SetTitle(htitle)
            hCorrVsHits[det][name].GetXaxis().SetTitle("Hits per module")
            hCorrVsHits[det][name].GetYaxis().SetTitle(name)
            if name is 'Tx' or name is 'Ty' or name is 'Tz' or name is 'Bx':
                hCorrVsHits[det][name].GetYaxis().SetTitle(name + " (mm)")
            else:
                hCorrVsHits[det][name].GetYaxis().SetTitle(name + " (mrad)")
            hCorrVsHits[det][name].SetMarkerStyle(4)
            hCorrVsHits[det][name].SetMarkerSize(0.5)
            hCorrVsHits[det][name].SetMarkerColor(Color[det])
            if det == 0:
                hCorrVsHits[det][name].Draw("Ap")
            else:
                hCorrVsHits[det][name].Draw("psame")
            gPad.SetGridx()
            gPad.SetGridy()
            gPad.SetLogx()
    CorrVsHits.Update()
    return CorrVsHits, hCorrVsHits
예제 #12
0
def gen_true_W():

    #generator true W = sqrt( ys(1-x) ) with true x and y

    # GeV^2
    #scm = 19800.8 # 18x275
    #scm = 820.8 # 5x41

    #W range
    wbin = 0.1
    wmin = 0
    wmax = 200

    hW = ut.prepare_TH1D("hW", wbin, wmin, wmax)
    hW2 = ut.prepare_TH1D("hW2", wbin, wmin, wmax)

    #form = "TMath::Sqrt(true_y*"+str(scm)+"*(1.-true_x))"
    #form2 = "TMath::Sqrt(true_y*"+str(scm)+")"
    form3 = "TMath::Sqrt(true_W2)"

    #tree.Draw(form+" >> hW")
    tree.Draw(form3 + " >> hW")
    #tree.Draw(form2+" >> hW2")
    #tree.Draw(form3+" >> hW2")

    can = ut.box_canvas()

    ut.put_yx_tit(hW, "Events", "W (GeV)", 1.4, 1.2)

    #ut.set_H1D_col(hW2, rt.kRed)
    ut.line_h1(hW)
    #ut.line_h1(hW2, rt.kRed)

    hW.Draw()
    #hW2.Draw("e1same")

    gPad.SetGrid()
    gPad.SetLogy()
    gPad.SetLogx()

    ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
예제 #13
0
def el_theta_phi_tag():

    #electron generated polar and azimuthal angle for electrons hitting the tagger

    #bins in theta
    tbin = 1e-4
    tmin = 3e-4
    tmax = 1.1e-2

    #bins in phi
    pbin = 1e-1
    pmin = -TMath.Pi()
    pmax = TMath.Pi()

    can = ut.box_canvas()

    hThetaPhi = ut.prepare_TH2D("hThetaPhi", tbin, tmin, tmax, pbin, pmin,
                                pmax)
    hThetaPhiTag = ut.prepare_TH2D("hThetaPhiTag", tbin, tmin, tmax, pbin,
                                   pmin, pmax)

    tree.Draw("el_phi:TMath::Pi()-el_theta >> hThetaPhi")
    tree.Draw("el_phi:TMath::Pi()-el_theta >> hThetaPhiTag", gQ2sel)

    ytit = "Azimuthal angle #varphi (rad) / {0:.3f}".format(pbin)
    xtit = "Polar angle #theta (rad) / {0:.2f} mrad".format(tbin * 1e3)
    ut.put_yx_tit(hThetaPhiTag, ytit, xtit, 1.2, 1.4)

    ut.set_margin_lbtr(gPad, 0.09, 0.1, 0.03, 0.12)

    gPad.SetLogx()
    #gPad.SetLogz()

    hThetaPhiTag.GetXaxis().SetMoreLogLabels()

    #hThetaPhi.Draw()
    hThetaPhiTag.Draw()

    #ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
예제 #14
0
def gen_Q2():

    #plot the Q^2

    qbin = 1e-3
    qmin = 1e-4
    qmax = 1

    hQ2 = ut.prepare_TH1D("hQ2", qbin, qmin, qmax)

    tree.Draw("true_Q2 >> hQ2")

    can = ut.box_canvas()

    ut.put_yx_tit(hQ2, "Events", "#it{Q}^{2}", 1.4, 1.2)

    hQ2.Draw()

    gPad.SetLogx()
    gPad.SetLogy()

    ut.invert_col(rt.gPad)
    can.SaveAs("01fig.pdf")
예제 #15
0
def drawHistsWithRatio(hists, name, **kwargs):
    """Draw histograms with ratios."""

    title = kwargs.get('title', "")
    xtitle = kwargs.get('xtitle', "")
    ytitle = kwargs.get('ytitle', "")
    rtitle = kwargs.get('rtitle', "Ratio")
    xmin = kwargs.get('xmin', hists[0].GetXaxis().GetXmin())
    xmax = kwargs.get('xmax', hists[0].GetXaxis().GetXmax())
    ymin = kwargs.get('ymin', None)
    ymax = kwargs.get('ymax', None)
    rmin = kwargs.get('rmin', 0.45)
    rmax = kwargs.get('rmax', 1.55)
    logx = kwargs.get('logx', False)
    logy = kwargs.get('logy', False)
    denom = kwargs.get('denom', 1) - 1  # denominator for ratio
    textsize = kwargs.get('textsize', 0.045)
    texts = kwargs.get('text', [])
    #textheight = kwargs.get('textheight',   1.09                 )
    #ctext      = kwargs.get('ctext',        [ ]                  ) # corner text
    #cposition  = kwargs.get('cposition',    'topleft'            ).lower() # cornertext
    #ctextsize  = kwargs.get('ctextsize',    1.4*legendtextsize   )
    colors = kwargs.get('colors', linecolors)
    if not isinstance(texts, list) or isinstance(texts, tuple):
        texts = [texts]
    if ymax == None:
        ymax = 1.12 * max(h.GetMaximum() for h in hists)

    # MAIN plot
    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 800)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.Divide(2)
    canvas.SetMargin(0.0, 0.0, 0.0, 0.0)
    canvas.cd(1)
    gPad.SetPad('pad1', 'pad1', 0, 0.33, 1, 1)
    gPad.SetMargin(0.12, 0.04, 0.02, 0.08)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetTickx(0)
    gPad.SetTicky(0)
    gPad.SetGrid()
    gPad.Draw()
    canvas.cd(2)
    gPad.SetPad('pad2', 'pad2', 0, 0, 1, 0.33)
    gPad.SetMargin(0.12, 0.04, 0.30, 0.03)
    gPad.SetFillColor(0)
    gPad.SetFillStyle(4000)
    gPad.SetFrameFillStyle(0)
    gPad.SetBorderMode(0)
    gPad.Draw()

    # MAIN plot
    canvas.cd(1)
    for i, hist in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.Draw('HIST SAME')
    frame = hists[0]
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0)
    frame.GetXaxis().SetLabelSize(0)
    frame.GetYaxis().SetLabelSize(0.052)
    frame.GetXaxis().SetLabelOffset(0.010)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    if logy:
        gPad.Update()
        gPad.SetLogy()
    if ymin: frame.SetMinimum(ymin)
    if ymax: frame.SetMaximum(ymax)

    width = 0.25
    height = 1.1 * textsize * len([l for l in texts + hists if l])
    x1, y1 = 0.65, 0.88
    x2, y2 = x1 + width, y1 - height
    legend = TLegend(x1, y1, x2, y2)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetMargin(0.05 / width)
    if title:
        legend.SetTextFont(62)
        legend.SetHeader(title)
    legend.SetTextFont(42)
    for hist in hists:
        legend.AddEntry(hist, hist.GetTitle(), 'l')
    for text in texts:
        legend.AddEntry(0, text, '')
    legend.Draw()

    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame.Draw('AXIS SAME')
    CMS_style.CMS_lumi(gPad, 13, 0)

    # RATIO plot
    canvas.cd(2)
    ratios = []
    for i, hist in enumerate(hists):
        if i == denom: continue
        ratio = hist.Clone(hist.GetName() + "_ratio")
        ratio.Divide(hists[denom])
        ratio.Draw('HIST SAME')
        ratios.append(ratio)
    frame_ratio = ratios[0]
    frame_ratio.GetYaxis().SetRangeUser(rmin, rmax)
    frame_ratio.GetYaxis().CenterTitle()
    frame_ratio.GetYaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetLabelSize(0.12)
    frame_ratio.GetYaxis().SetLabelSize(0.11)
    frame_ratio.GetXaxis().SetLabelOffset(0.012)
    frame_ratio.GetXaxis().SetTitleOffset(1.02)
    frame_ratio.GetYaxis().SetTitleOffset(0.48)
    frame_ratio.GetXaxis().SetNdivisions(508)
    frame_ratio.GetYaxis().CenterTitle(True)
    frame_ratio.GetYaxis().SetTitle(rtitle)
    frame_ratio.GetXaxis().SetTitle(xtitle)
    frame_ratio.GetYaxis().SetNdivisions(505)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    line = TLine(xmin, 1., xmax, 1.)
    line.SetLineColor(hists[denom].GetLineColor())
    line.SetLineWidth(hists[denom].GetLineWidth())
    line.SetLineStyle(1)
    line.Draw('SAME')
    gPad.SetTicks(1, 1)
    gPad.Update()
    gPad.SetGrid()
    gPad.Modified()
    frame_ratio.Draw('SAME AXIS')

    canvas.SaveAs(name + ".png")
    canvas.SaveAs(name + ".pdf")
    canvas.Close()
예제 #16
0
    def setaxes(self, *args, **kwargs):
        """Make axis."""
        verbosity = LOG.getverbosity(self, kwargs)
        hists = []
        binning = []
        for arg in args[:]:
            if hasattr(arg, 'GetXaxis'):
                hists.append(arg)
            elif isinstance(arg, Ratio):
                hists.append(arg.frame)
            elif isnumber(arg):
                binning.append(arg)
        if not hists:
            LOG.warning(
                "Plot.setaxes: No objects (TH1, TGraph, ...) given in args %s to set axis..."
                % (args))
            return 0, 0, 100, 100
        frame = hists[0]
        if len(binning) >= 2:
            xmin, xmax = binning[:2]
        else:
            xmin, xmax = frame.GetXaxis().GetXmin(), frame.GetXaxis().GetXmax()
        nbins = frame.GetXaxis().GetNbins()
        binwidth = float(xmax - xmin) / nbins
        xmin = kwargs.get('xmin', xmin)
        xmax = kwargs.get('xmax', xmax)
        ymin = kwargs.get('ymin', None)
        ymax = kwargs.get('ymax', None)
        ratiorange = kwargs.get('rrange', None)
        binlabels = kwargs.get('binlabels', None)
        intbins = kwargs.get('intbins', True)  # allow integer binning
        logx = kwargs.get('logx', False)
        logy = kwargs.get('logy', False)
        ymargin = kwargs.get('ymargin', None) or (
            1.3 if logy else 1.2)  # margin between hist maximum and plot's top
        logyrange = kwargs.get(
            'logyrange', None) or 3  # log(y) range from hist maximum to ymin
        negativey = kwargs.get('negativey', True)  # allow negative y values
        xtitle = kwargs.get('xtitle', frame.GetTitle())
        ytitle = kwargs.get('ytitle', None)
        latex = kwargs.get('latex',
                           True)  # automatically format strings as LaTeX
        grid = kwargs.get('grid', False)
        ycenter = kwargs.get('center', False)
        nxdivisions = kwargs.get('nxdiv', 510)
        nydivisions = kwargs.get('nydiv', 510)
        main = kwargs.get('main', False)  # main panel of ratio plot
        scale = 600. / min(gPad.GetWh() * gPad.GetHNDC(),
                           gPad.GetWw() * gPad.GetWNDC())
        xtitlesize = kwargs.get('xtitlesize', _tsize) * scale
        ytitlesize = kwargs.get('ytitlesize', _tsize) * scale
        xlabelsize = kwargs.get('xlabelsize', _lsize) * scale
        ylabelsize = kwargs.get('ylabelsize', _lsize) * scale
        ytitleoffset = kwargs.get('ytitleoffset', 1.0) * 1.26 / scale
        xtitleoffset = kwargs.get('xtitleoffset', 1.0) * 1.00
        xlabeloffset = kwargs.get('xlabeloffset', 0.007)
        if main:
            xtitlesize = 0.0
            xlabelsize = 0.0
        if latex:
            xtitle = makelatex(xtitle)
        LOG.verb("Plot.setaxes: Binning (%s,%.1f,%.1f)" % (nbins, xmin, xmax),
                 verbosity, 2)

        if ratiorange:
            ymin, ymax = 1 - ratiorange, 1 + ratiorange
        if intbins and nbins < 15 and int(xmin) == xmin and int(
                xmax) == xmax and binwidth == 1:
            LOG.verb(
                "Plot.setaxes: Setting integer binning for (%r,%s,%d,%d)!" %
                (xtitle, nbins, xmin, xmax), verbosity, 1)
            binlabels = [str(i) for i in range(int(xmin), int(xmax) + 1)]
            xlabelsize *= 1.6
            xlabeloffset *= 0.88 * scale
        if logy:
            ylabelsize *= 1.08
        if binlabels:
            nxdivisions = 15

        # GET HIST MAX
        hmaxs = []
        hmins = [0]
        if isinstance(frame, THStack):
            hmaxs.append(frame.GetMaximum())
            #frame = frame.GetStack().Last()
            for hist in hists:
                hmaxs.append(
                    getTGraphYRange(hist)[1]
                    if isinstance(hist, TGraph) else hist.GetMaximum())
        else:
            for hist in hists:
                ymin1, ymax1 = getTGraphYRange(hist) if isinstance(
                    hist, TGraph) else hist.GetMinimum(), hist.GetMaximum()
                if negativey:
                    hmins.append(ymin1)
                hmaxs.append(ymax1)
            if ymin == None:
                ymin = min(hmins) * (1.1 if ymin > 0 else 0.9)
        hmax = max(hmaxs)
        hmin = min(hmins)

        # SET AXES RANGES
        if ymin == None:
            ymin = 0
        if logy:
            if not ymin or ymin <= 0:  # avoid zero or negative ymin for log plots
                ymin = 10**(magnitude(hmax) - logyrange
                            )  #max(0.1,10**(magnitude(ymax)-3))
                LOG.verb(
                    "Plot.setaxes: logy=%s, hmax=%6.6g, magnitude(hmax)=%s, logyrange=%s, ymin=%.6g"
                    % (logy, hmax, magnitude(hmax), logyrange, ymin),
                    verbosity, 2)
            if ymax == None:
                if hmax > ymin > 0:
                    span = abs(log10(hmax / ymin)) * ymargin
                    ymax = ymin * (10**span)
                    LOG.verb(
                        "Plot.setaxes: log10(hmax/ymin)=%6.6g, span=%6.6g, ymax=%.6g"
                        % (log10(hmax / ymin), span, ymax), verbosity, 2)
                else:
                    ymax = hmax * ymargin
            gPad.Update()
            gPad.SetLogy()
        elif ymax == None:
            ymax = hmax * ymargin
        if logx:
            if not xmin: xmin = 0.1
            xmax *= 0.9999999999999
            gPad.Update()
            gPad.SetLogx()
        if grid:
            gPad.SetGrid()
        frame.GetXaxis().SetRangeUser(xmin, xmax)
        frame.SetMinimum(ymin)
        frame.SetMaximum(ymax)

        if ytitle == None:
            #ytitle = "Events"
            if "multiplicity" in xtitle.lower():
                ytitle = "Events"
            elif hmax < 1.:
                ytitle = "A.U."
            else:
                binwidth = frame.GetXaxis().GetBinWidth(0)
                binwidstr = ("%.3f" % binwidth).rstrip('0').rstrip('.')
                units = re.findall(r' \[(.+)\]',
                                   xtitle)  #+ re.findall(r' (.+)',xtitle)
                if frame.GetXaxis().IsVariableBinSize():
                    if units:
                        ytitle = "Events / " + units[-1]
                    else:
                        ytitle = "Events / bin size"
                elif units:
                    if binwidth != 1:
                        ytitle = "Events / %s %s" % (binwidstr, units[-1])
                    else:
                        ytitle = "Events / " + units[-1]
                elif binwidth != 1:
                    ytitle = "Events / " + binwidstr
                else:
                    ytitle = "Events"
                LOG.verb(
                    "Plot.setaxes: ytitle=%r, units=%s, binwidth=%s, binwidstr=%r"
                    % (ytitle, units, binwidth, binwidstr), verbosity, 2)

        # alphanumerical bin labels
        if binlabels:
            if len(binlabels) < nbins:
                LOG.warning("Plot.setaxes: len(binlabels)=%d < %d=nbins" %
                            (len(binlabels), nbins))
            for i, binlabel in zip(range(1, nbins + 1), binlabels):
                frame.GetXaxis().SetBinLabel(i, binlabel)
            #frame.GetXaxis().LabelsOption('h')

        # X axis
        frame.GetXaxis().SetTitleSize(xtitlesize)
        frame.GetXaxis().SetTitleOffset(xtitleoffset)
        frame.GetXaxis().SetLabelSize(xlabelsize)
        frame.GetXaxis().SetLabelOffset(xlabeloffset)
        frame.GetXaxis().SetNdivisions(nxdivisions)
        frame.GetXaxis().SetTitle(xtitle)

        # Y axis
        if ymax >= 1e4:
            ylabelsize *= 0.95
        if ycenter:
            frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitleSize(ytitlesize)
        frame.GetYaxis().SetTitleOffset(ytitleoffset)
        frame.GetYaxis().SetLabelSize(ylabelsize)
        frame.GetYaxis().SetNdivisions(nydivisions)
        frame.GetYaxis().SetTitle(ytitle)

        if verbosity >= 1:
            print ">>> Plot.setaxes: xtitle=%r, [hmin,hmax] = [%.6g,%.6g], [xmin,xmax] = [%.6g,%.6g], [ymin,ymax] = [%.6g,%.6g]" % (
                xtitle, hmin, hmax, xmin, xmax, ymin, ymax)
        elif verbosity >= 2:
            print ">>> Plot.setaxes: frame=%s" % (frame)
            print ">>> Plot.setaxes: hists=%s" % (hists)
            print ">>> Plot.setaxes: [hmin,hmax] = [%.6g,%.6g], [xmin,xmax] = [%.6g,%.6g], [ymin,ymax] = [%.6g,%.6g]" % (
                hmin, hmax, xmin, xmax, ymin, ymax)
            print ">>> Plot.setaxes: xtitlesize=%4.4g, xlabelsize=%4.4g, xtitleoffset=%4.4g, xtitle=%r" % (
                xtitlesize, xlabelsize, xtitleoffset, xtitle)
            print ">>> Plot.setaxes: ytitlesize=%4.4g, ylabelsize=%4.4g, ytitleoffset=%4.4g, ytitle=%r" % (
                ytitlesize, ylabelsize, ytitleoffset, ytitle)
            print ">>> Plot.setaxes: scale=%4.4g, nxdivisions=%s, nydivisions=%s, ymargin=%.3f, logyrange=%.3f" % (
                scale, nxdivisions, nydivisions, ymargin, logyrange)
        if main:
            #if any(a!=None and a!=b for a, b in [(self.xmin,xmin),(self.xmax,xmax)]):
            #  LOG.warning("Plot.setaxes: x axis range changed: [xmin,xmax] = [%6.6g,%6.6g] -> [%6.6g,%6.6g]"%(
            #              self.xmin,self.xmax,xmin,xmax))
            #if any(a!=None and a!=b for a, b in [(self.ymin,ymin),(self.ymax,ymax)]):
            #  LOG.warning("Plot.setaxes: y axis range changed: [ymin,ymax] = [%6.6g,%6.6g] -> [%6.6g,%6.6g]"%(
            #              self.ymin,self.ymax,ymin,ymax))
            self.xmin, self.xmax = xmin, xmax
            self.ymin, self.ymax = ymin, ymax
        return xmin, xmax, ymin, ymax
예제 #17
0
    def makePlot(self, legend=None):

        if self.__props.get("xAxisTitle"):
            self.__hist.GetXaxis().SetTitle(self.__props["xAxisTitle"])
        if self.__props.get("yAxisTitle"):
            self.__hist.GetYaxis().SetTitle(self.__props["yAxisTitle"])

        if self.__props.get("xAxisRange"):
            self.__hist.GetXaxis().SetRangeUser(self.__props["xAxisRange"][0],
                                                self.__props["xAxisRange"][1])
        if self.__props.get("yAxisRange"):
            self.__hist.GetYaxis().SetRangeUser(self.__props["yAxisRange"][0],
                                                self.__props["yAxisRange"][1])

        if self.__props.get("normFactor"):
            normfactor = self.__props["normFactor"]
            if normfactor:
                self.__hist.Scale(normfactor / self.__hist.Integral())

        if self.__props.get("legend") and legend:
            legend.AddEntry(self.__hist, self.__props["legend"], "PL")

        if self.__props.get("setBinVals"):
            for tup in self.__props["setBinVals"]:
                self.__hist.SetBinContent(tup[0], tup[1])
        if self.__props.get("setBinErrs"):
            for tup in self.__props["setBinErrs"]:
                self.__hist.SetBinError(tup[0], tup[1])

        if not self.is2D:

            if self.__props.get("colour"):
                self.__hist.SetLineColor(self.__props["colour"])
                self.__hist.SetMarkerColor(self.__props["colour"])
            if self.__props.get("lineStyle"):
                self.__hist.SetLineStyle(self.__props["lineStyle"])
            if self.__props.get("lineWidth"):
                self.__hist.SetLineWidth(self.__props["lineWidth"])
            if self.__props.get("markerStyle"):
                self.__hist.SetMarkerStyle(self.__props["markerStyle"])
            if self.__props.get("markerSize"):
                self.__hist.SetMarkerSize(self.__props["markerSize"])
            if self.__props.get("markerColour"):
                self.__hist.SetMarkerColor(self.__props["markerColour"])

    # Draw the histogram on the Pad!

    # Create histogram with total systematic error if necessary

        if self.__syshists and not self.is2D:
            self.__syserrhist = self.__hist.Clone(self.__hist.GetName() +
                                                  "_SYST")
            self.__syserrhist.SetFillColor(kOrange)
            self.__syserrhist.SetLineColor(10)
            self.__syserrhist.SetLineStyle(1)
            self.__syserrhist.SetFillStyle(3356)
            gStyle.SetHatchesLineWidth(1)  #(2)
            gStyle.SetHatchesSpacing(0.4)  #(0.8)
            self.__syserrhist.SetMarkerSize(0)
            for ibin in range(0, self.__nbins):
                self.__syserrhist.SetBinError(ibin, self.__syssumquad[ibin])
                print("bin[{0}] : {1:.4f} +- {2:.4f}".format(
                    ibin, self.__syserrhist.GetBinContent(ibin),
                    self.__syserrhist.GetBinError(ibin)))
            if not gPad.GetListOfPrimitives().GetSize():
                self.__syserrhist.Draw("E2")
            else:
                self.__syserrhist.Draw("E2 SAME")
            self.__hist.Draw(self.__props["drawOpt"] + " SAME")
        else:
            self.__hist.Draw(self.__props["drawOpt"])

        self.__hist.GetYaxis().SetTitleOffset(1.4)

        # Set log axis if needed
        if self.__props.get("xAxisLog"):
            gPad.SetLogx(self.__props["xAxisLog"])
            if self.__props["xAxisLog"]:
                if self.__syshists:
                    self.__syserrhist.GetXaxis().SetMoreLogLabels()
                    self.__syserrhist.GetXaxis().SetNoExponent()
                else:
                    self.__hist.GetXaxis().SetMoreLogLabels()
                    self.__hist.GetXaxis().SetNoExponent()
        if self.__props.get("yaxisLog"):
            gPad.SetLogy(self.__props["yaxisLog"])
            if self.__props["yaxisLog"]:
                if self.__syshists:
                    self.__syserrhist.GetYaxis().SetMoreLogLabels()
                    self.__syserrhist.GetYaxis().SetNoExponent()
                else:
                    self.__hist.GetYaxis().SetMoreLogLabels()
                    self.__hist.GetYaxis().SetNoExponent()

    # Deal with alphanumeric axis labels

        if self.__props.get("xAxisLabels"):
            self.setAlphanumLabels(axis="X",
                                   labels=self.__props["xAxisLabels"],
                                   labelsopt="v")
            self.__hist.GetXaxis().SetTitleOffset(
                2.1)  # increase a bit the axis title offset
            self.__hist.GetXaxis().SetLabelSize(0.03)
            self.__hist.GetXaxis().SetTitleSize(0.04)
        if self.__props.get("yAxisLabels"):
            self.setAlphanumLabels(axis="Y",
                                   labels=self.__props["yAxisLabels"],
                                   labelsopt="h")
            self.__hist.GetYaxis().SetTitleOffset(
                2.255)  # increase a bit the axis title offset
            self.__hist.GetYaxis().SetLabelSize(0.03)
            self.__hist.GetYaxis().SetTitleSize(0.04)

    # For 2D histograms, this will change the size of the labels on the COLZ axis
    # NB: must be done after calling Draw()!

        if self.is2D:
            gPad.Update()
            palette = self.__hist.FindObject("palette")
            if palette:
                palette.GetAxis().SetLabelSize(0.05)

        if self.__props.get("drawGrid"):
            if self.__props["drawGrid"]:
                gPad.Update()
                gPad.SetGrid()
    def doit():
        frame = h.ProfileX(hname + "_frame", 1, -1, "s")
        gr1 = TGraphAsymmErrors(h.GetNbinsX())
        gr2 = TGraphAsymmErrors(h.GetNbinsX())
        gr1_aspt = TGraphAsymmErrors(h.GetNbinsX())
        gr2_aspt = TGraphAsymmErrors(h.GetNbinsX())
        # Apply gaussian fits
        for i in xrange(h.GetNbinsX()):
            h_py = h.ProjectionY("_py", i + 1, i + 1)

            if 50 <= i <= 60:  # high pT, not enough entries (300 bins -> 150)
                h_py.Rebin(2)
            elif i >= 78:  # low pT, resolution affected by finite bin width
                h_py = h.ProjectionY("_py", i + 1,
                                     i + 2)  # merge i & (i+1) entries
                if i == 82:  # even lower pT, resolution affected by finite bin width
                    h_py = h.ProjectionY("_py", i + 1,
                                         i + 4)  # merge i & (i+4) entries
                elif i >= 82:
                    continue

            if h_py.Integral() < 20: continue
            r = h_py.Fit("gaus", "SNQ", "", -1, 1.2)
            #r = h_py.Fit("gaus", "SNQ", "", h_py.GetMean() - 0.04*5, h_py.GetMean() + 0.04*5)
            mean, sigma, meanErr, sigmaErr = r.Parameter(1), r.Parameter(
                2), r.ParError(1), r.ParError(2)
            gr1.SetPoint(i, h.GetXaxis().GetBinCenter(i + 1), mean)
            gr1.SetPointError(i, 0, 0, sigma, sigma)
            gr2.SetPoint(i, h.GetXaxis().GetBinCenter(i + 1), sigma)
            gr2.SetPointError(i, 0, 0, sigmaErr, sigmaErr)
            gr1_aspt.SetPoint(i, 1.0 / h.GetXaxis().GetBinCenter(i + 1), mean)
            gr1_aspt.SetPointError(i, 0, 0, sigma, sigma)
            gr2_aspt.SetPoint(i, 1.0 / h.GetXaxis().GetBinCenter(i + 1), sigma)
            gr2_aspt.SetPointError(i, 0, 0, sigmaErr, sigmaErr)
        # Draw
        h.Draw("COLZ")
        gPad.SetLogx(0)
        #draw_cms_lumi()
        #gPad.Print("figures_perf/" + hname + "_omtf" + ".png")
        #gPad.Print("figures_perf/" + hname + "_omtf" + ".pdf")
        #
        frame.Reset()
        frame.SetBins(50, 0, 50)
        frame.GetXaxis().SetTitle("gen p_{T} [GeV]")
        frame.GetYaxis().SetTitle("#Delta(p_{T})/p_{T} bias")
        frame.SetMaximum(0.5)
        frame.SetMinimum(-0.5)
        frame.SetStats(0)
        frame.Draw()
        gr1_aspt.SetLineColor(col)
        gr1_aspt.SetMarkerColor(col)
        gr1_aspt.Draw("p")
        gPad.SetLogx()
        draw_cms_lumi()
        gPad.Print("figures_perf/" + hname + "_bias" + "_omtf" + ".png")
        gPad.Print("figures_perf/" + hname + "_bias" + "_omtf" + ".pdf")
        #
        frame.GetXaxis().SetTitle("gen p_{T} [GeV]")
        frame.GetYaxis().SetTitle("#Delta(p_{T})/p_{T} resolution")
        frame.SetMaximum(0.6)
        frame.SetMinimum(0.0)
        frame.SetStats(0)
        frame.Draw()
        gr2_aspt.SetLineColor(col)
        gr2_aspt.SetMarkerColor(col)
        gr2_aspt.Draw("p")
        #gr2_aspt.Fit("pol1", "", "", 10, 40)
        gPad.SetLogx()
        draw_cms_lumi()
        gPad.Print("figures_perf/" + hname + "_res" + "_omtf" + ".png")
        gPad.Print("figures_perf/" + hname + "_res" + "_omtf" + ".pdf")
        #
        h.cache = [frame, gr1, gr2, gr1_aspt, gr2_aspt]
예제 #19
0
 def adjust_pad():
     if logx:
         gPad.SetLogx()
     if logy:
         gPad.SetLogy()
예제 #20
0
leg.AddEntry(gr1, "#splitline{ALP#rightarrow gg;}{c_{g}=1}", "P")
leg.AddEntry(gr2, "#splitline{ALP#rightarrow gg;}{c_{g}=1/(4#pi)}", "P")
leg.AddEntry(gr3, "#splitline{ALP#rightarrow q#bar{q};}{c_{q}=1}", "P")
leg.AddEntry(gr4, "#splitline{ALP#rightarrow gg Theory Prediction;}{c_{g}=1}",
             "P")
leg.AddEntry(
    gr5, "#splitline{ALP#rightarrow gg Theory Prediction;}{c_{g}=1/(4#pi)}",
    "P")
leg.AddEntry(
    gr6, "#splitline{ALP#rightarrow q#bar{q} Theory Prediction;}{c_{q}=1}",
    "P")

# In[6]:

canvas = ROOT.TCanvas('', '', 200, 10, 1200, 800)
gPad.SetLogx()
gPad.SetLogy()
gr1.Draw('AP')
gr2.Draw('same P')
gr3.Draw('same P')
gr4.Draw('same P')
gr5.Draw('same P')
gr6.Draw('same P')
leg.Draw()

# In[7]:

canvas.Modified()
canvas.Update()
gROOT.GetListOfCanvases().Draw()
canvas.SaveAs("WidthsummaryPlot.pdf")
예제 #21
0
def create_firstroothistograms(PrimaryParticleName, VectorSignals, VectorSignalsCher, 
	GroupedVectorSignals, GroupedVectorSignalsCher, ScinTreshold, 
	CherTreshold, ScinMaxFiber, CherMaxFiber, NumFibers, NumModules):
	"""Function to perform ROOT histograms"""
	
	#Set ROOT histograms
	TH2Signals = TH2F("ScatterplotSignals",PrimaryParticleName,111*8,1.2*0,1.2*111,111*8,1.2*0,1.2*111)
	TH2SignalsGrouped = TH2F("ScatterplotSignalsGrouped",PrimaryParticleName,111,1.2*0,1.2*111,111,1.2*0,1.2*111)
	TH2SignalsCher = TH2F("ScatterplotSignalsCher",PrimaryParticleName,111*8,0.0*111,1.2*111,111*8,0.0*111,1.2*111)
	TH2SignalsCherGrouped = TH2F("ScatterplotSignalsCherGrouped",PrimaryParticleName,111,1.2*0,1.2*111,111,1.2*0,1.2*111)
	TH1Signals = TH1F("Scintillation",PrimaryParticleName,100,0.0,ScinMaxFiber+200.0)
	TH1SignalsCher = TH1F("Cherenkov",PrimaryParticleName,100,0.0,CherMaxFiber+5)

	#Fill histograms in for loop
	for fiberindex in range(NumFibers):
		X,Y = map.mapXY(fiberindex)
		if VectorSignals[fiberindex] > ScinTreshold:
			TH2Signals.Fill(X,Y,VectorSignals[fiberindex])
			TH1Signals.Fill(VectorSignals[fiberindex])
		if VectorSignalsCher[fiberindex] > CherTreshold:
			TH2SignalsCher.Fill(X,Y,VectorSignalsCher[fiberindex])
			TH1SignalsCher.Fill(VectorSignalsCher[fiberindex])

	for moduleindex in range(NumModules):
		X,Y = mapgroup.mapgroupedXY(moduleindex)
		TH2SignalsGrouped.Fill(X,Y,GroupedVectorSignals[moduleindex])
		TH2SignalsCherGrouped.Fill(X,Y,GroupedVectorSignalsCher[moduleindex])
		
	#Draw + DrawOptions histograms		
	Style = gStyle
	Style.SetPalette(1) #Root palette style
	Style.SetOptStat(0) #Do not show statistics
	TH2Signals.SetLineWidth(0) #TH2Signals #No line width
	TH2Signals.SetLineColor(2)
	#TH2Signals.SetFillColorAlpha(2, 0.)
	XAxis = TH2Signals.GetXaxis()
	XAxis.SetTitle("x (cm)")
	XAxis.CenterTitle()
	XAxis.SetTitleOffset(1.8)
	YAxis = TH2Signals.GetYaxis()
	YAxis.SetTitle("y (cm)")
	YAxis.CenterTitle()
	YAxis.SetTitleOffset(1.8)
	ZAxis = TH2Signals.GetZaxis()
	ZAxis.SetTitle("Energy (MeV)")
	ZAxis.SetTitleOffset(1.4)
	TH2Signals.Draw("LEGO2Z 0 FB")
	gPad.SaveAs("ImageScintillation.pdf")
	TH2SignalsGrouped.SetLineWidth(0) #TH2GroupedSignals #No line width
	TH2SignalsGrouped.SetLineColor(2)
	#TH2Signals.SetFillColorAlpha(2, 0.)
	XAxis = TH2SignalsGrouped.GetXaxis()
	XAxis.SetTitle("x (cm)")
	XAxis.CenterTitle()
	XAxis.SetTitleOffset(1.8)
	YAxis = TH2SignalsGrouped.GetYaxis()
	YAxis.SetTitle("y (cm)")
	YAxis.CenterTitle()
	YAxis.SetTitleOffset(1.8)
	ZAxis = TH2SignalsGrouped.GetZaxis()
	ZAxis.SetTitle("Energy (MeV)")
	ZAxis.SetTitleOffset(1.4)
	TH2SignalsGrouped.Draw("LEGO2Z 0 FB")
	gPad.SaveAs("ImageScintillationGrouped.pdf")
	TH2SignalsCherGrouped.SetLineWidth(0) #TH2GroupedCherSignals #No line width
	TH2SignalsCherGrouped.SetLineColor(4)
	#TH2Signals.SetFillColorAlpha(2, 0.)
	XAxis = TH2SignalsCherGrouped.GetXaxis()
	XAxis.SetTitle("x (cm)")
	XAxis.CenterTitle()
	XAxis.SetTitleOffset(1.8)
	YAxis = TH2SignalsCherGrouped.GetYaxis()
	YAxis.SetTitle("y (cm)")
	YAxis.CenterTitle()
	YAxis.SetTitleOffset(1.8)
	ZAxis = TH2SignalsCherGrouped.GetZaxis()
	ZAxis.SetTitle("Energy (MeV)")
	ZAxis.SetTitleOffset(1.4)
	TH2SignalsCherGrouped.Draw("LEGO2Z 0 FB")
	gPad.SaveAs("ImageCherenkovGrouped.pdf")
	TH2SignalsCher.SetLineWidth(0) #TH2SignalsCher #No line width
	TH2SignalsCher.SetLineColor(4)
	XAxis = TH2SignalsCher.GetXaxis()
	XAxis.SetTitle("x (cm)")
	XAxis.CenterTitle()
	XAxis.SetTitleOffset(1.8)
	YAxis = TH2SignalsCher.GetYaxis()
	YAxis.SetTitle("y (cm)")
	YAxis.CenterTitle()
	YAxis.SetTitleOffset(1.8)
	ZAxis = TH2SignalsCher.GetZaxis()
	ZAxis.SetTitle("Energy (MeV)")
	ZAxis.SetTitleOffset(1.4)
	TH2SignalsCher.Draw("LEGO2Z FB 0")
	gPad.SaveAs("ImageCherenkov.pdf")
	Style.SetLineWidth(1) #TH1Signals
	Style.SetOptStat(1) #Show statistics
	gPad.SetLogy()
	gPad.SetLogx()
	XAxis = TH1Signals.GetXaxis()
	XAxis.SetTitle("Energy (MeV)")
	XAxis.SetTitleOffset(1.2)
	YAxis = TH1Signals.GetYaxis()
	YAxis.SetTitle("# fibers")
	TH1Signals.Draw()
	gPad.SaveAs("EnergyFibers.pdf")
	XAxis = TH1SignalsCher.GetXaxis() #TH1SignalsCher
	XAxis.SetTitle("# Cher p.e.")
	XAxis.SetTitleOffset(1.2)
	YAxis = TH1SignalsCher.GetYaxis()
	YAxis.SetTitle("# fibers")
	TH1SignalsCher.Draw()
	gPad.SaveAs("CherpeFibers.pdf")
	gPad.Close()
예제 #22
0
                    h1.Fill(output1[0] / inputs1[0])
                    xrangesT[m].Fill(pT)

    pT = inputs2[0]
    eta = abs(inputs2[1])
    if (eta < Cut1):
        for m in range(len(ptBins) - 1):
            if (pT > ptBins[m] and pT < ptBins[m + 1]):
                if (output2[1] > 0):  # non-zero efficiency
                    h1 = histosN[m]
                    h1.Fill(output2[0] / inputs2[0])
                    xrangesN[m].Fill(pT)

h = gPad.DrawFrame(Xmin, Ymin, Xmax, Ymax)
gPad.SetLogy(0)
gPad.SetLogx(1)
ax = h.GetXaxis()
ax.SetTitleOffset(1.0)
ax.SetTitle("p_{T}^{jet} [GeV]")
ay = h.GetYaxis()
ay.SetTitle("#sigma (p_{T}^{jet}) / p_{T}^{jet}")
ay.SetTitleSize(0.05)
ax.SetTitleSize(0.05)
ay.SetLabelSize(0.04)
ax.SetTitleOffset(1.1)
ay.SetTitleOffset(1.25)
ay.SetLabelFont(42)
ax.SetLabelFont(42)
ax.SetLabelSize(0.04)

g1 = getResponseGraph(histosT, xrangesT)
예제 #23
0
def efficiencytracking(var):
    # plots the efficiency vs pT, eta and phi for all the species(it extracts the
    # Efficiency from qa - tracking - efficiency if you have ran with-- make - eff)
    hadron_list = [
        "pion",
        "proton",
        "kaon",
        "electron",
        "muon",
    ]
    color_list = [1, 2, 4, 6, 8]
    marker_list = [20, 21, 22, 34, 45]
    fileo2 = TFile("../codeHF/AnalysisResults_O2.root")

    c1 = TCanvas("c1", "Efficiency")
    gStyle.SetOptStat(0)
    gStyle.SetErrorX(0)
    gStyle.SetFrameLineWidth(2)
    gStyle.SetTitleSize(0.045, "x")
    gStyle.SetTitleSize(0.045, "y")
    gStyle.SetMarkerSize(1)
    gStyle.SetLabelOffset(0.015, "x")
    gStyle.SetLabelOffset(0.02, "y")
    gStyle.SetTickLength(-0.02, "x")
    gStyle.SetTickLength(-0.02, "y")
    gStyle.SetTitleOffset(1.1, "x")
    gStyle.SetTitleOffset(1.0, "y")

    c1.SetCanvasSize(800, 600)
    c1.cd()
    c1.SetGridy()
    c1.SetGridx()
    eff_list = []

    if var == "Pt":
        hempty = TH1F("hempty", ";Transverse Momentum(GeV/c);Efficiency", 100,
                      0.05, 10)
        gPad.SetLogx()
    elif var == "Eta":
        hempty = TH1F("hempty", ";Pseudorapidity;Efficiency", 100, -4.0, 4.0)
    elif var == "Phi":
        hempty = TH1F("hempty", ";Azimuthal angle(rad);Efficiency", 100, 0.0,
                      6.0)

    hempty.GetYaxis().CenterTitle()
    hempty.GetXaxis().CenterTitle()
    hempty.GetXaxis().SetNoExponent()
    hempty.GetXaxis().SetMoreLogLabels(1)
    hempty.Draw()
    leg = TLegend(0.55, 0.15, 0.89, 0.35, "P")
    leg.SetNColumns(2)
    leg.SetHeader("Minimum bias KrKr #sqrt{s} = 6.46TeV", "C")
    leg.SetFillColor(0)

    for i, had in enumerate(hadron_list):
        leff = fileo2.Get("qa-tracking-efficiency-%s/Efficiency" % had)
        if var == "Pt":
            eff = leff.At(0)
        elif var == "Eta":
            eff = leff.At(1)
        elif var == "Phi":
            eff = leff.At(2)
        gPad.Update()
        eff.Paint("p")
        gr = eff.GetPaintedGraph().Clone()
        for j in range(0, gr.GetN()):
            gr.GetEXlow()[j] = 0
            gr.GetEXhigh()[j] = 0

        gr.SetLineColor(color_list[i])
        gr.SetMarkerColor(color_list[i])
        gr.SetMarkerStyle(marker_list[i])
        eff_list.append(gr)
        gr.Draw(" same p")
        leg.AddEntry(eff_list[i], had, "p")
    leg.Draw()
    saveCanvas(c1, "efficiency_tracking_%s" % var)
예제 #24
0
    ut.log_results(out, "Fit parameters in 3-digit precision:")
    chistr = "chi2/ndf: {0:.3f}".format(r1.Chi2()/r1.Ndf())
    ut.log_results(out, chistr)
    for ipar in xrange(3):
        nam = fitFunc.GetParName(ipar)
        val = fitFunc.GetParameter(ipar)
        err = fitFunc.GetParError(ipar)
        ut.log_results(out, "{0:9} {1:.3f} +/- {2:.3f}".format(nam+":", val, err))

    #plot the efficiency
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)

    can = ut.box_canvas()

    if logx == True: gPad.SetLogx()

    gPad.SetTopMargin(0.01)
    gPad.SetRightMargin(0.01)
    gPad.SetBottomMargin(0.12)
    gPad.SetLeftMargin(0.1)

    ut.set_graph(hEff)

    hEff.GetYaxis().SetTitleOffset(1.4)
    hEff.GetXaxis().SetTitleOffset(1.5)

    hEff.GetXaxis().SetTitle("Track momentum #it{p}_{tot} at BEMC (GeV)")
    hEff.GetYaxis().SetTitle("BEMC efficiency")
    hEff.SetTitle("")