def rooFit106():

    print ">>> setup model..."
    x = RooRealVar("x", "x", -3, 3)
    mean = RooRealVar("mean", "mean of gaussian", 1, -10, 10)
    sigma = RooRealVar("sigma", "width of gaussian", 1, 0.1, 10)
    gauss = RooGaussian("gauss", "gauss", x, mean, sigma)
    data = gauss.generate(RooArgSet(x), 10000)  # RooDataSet
    gauss.fitTo(data)

    print ">>> plot pdf and data..."
    frame = x.frame(Name("frame"), Title("RooPlot with decorations"),
                    Bins(40))  # RooPlot
    data.plotOn(frame)
    gauss.plotOn(frame)

    print ">>> RooGaussian::paramOn - add box with pdf parameters..."
    # https://root.cern.ch/doc/master/classRooAbsPdf.html#aa43b2556a1b419bad2b020ba9b808c1b
    # Layout(Double_t xmin, Double_t xmax, Double_t ymax)
    # left edge of box starts at 20% of x-axis
    gauss.paramOn(frame, Layout(0.55))

    print ">>> RooDataSet::statOn - add box with data statistics..."
    # https://root.cern.ch/doc/master/classRooAbsData.html#a538d58020b296a1623323a84d2bb8acb
    # x size of box is from 55% to 99% of x-axis range, top of box is at 80% of y-axis range)
    data.statOn(frame, Layout(0.20, 0.55, 0.8))

    print ">>> add text and arrow..."
    text = TText(2, 100, "Signal")
    text.SetTextSize(0.04)
    text.SetTextColor(kRed)
    frame.addObject(text)

    arrow = TArrow(2, 100, -1, 50, 0.01, "|>")
    arrow.SetLineColor(kRed)
    arrow.SetFillColor(kRed)
    arrow.SetLineWidth(3)
    frame.addObject(arrow)

    print ">>> persist frame with all decorations in ROOT file..."
    file = TFile("rooFit106.root", "RECREATE")
    frame.Write()
    file.Close()

    # To read back and plot frame with all decorations in clean root session do
    #   [0] TFile f("rooFit106.root")
    #   [1] xframe->Draw()

    print ">>> draw functions and toy data on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.05)
    frame.GetYaxis().SetTitleOffset(1.6)
    frame.GetYaxis().SetLabelOffset(0.010)
    frame.GetYaxis().SetTitleSize(0.045)
    frame.GetYaxis().SetLabelSize(0.042)
    frame.GetXaxis().SetTitleSize(0.045)
    frame.GetXaxis().SetLabelSize(0.042)
    frame.Draw()
    canvas.SaveAs("rooFit106.png")
示例#2
0
def plot(path, pt_title, ecms, arrow_left, arrow_bottom, arrow_right,
         arrow_top):
    try:
        f_incMC1 = TFile(path[0])
        f_incMC2 = TFile(path[1])
        f_sigMC1 = TFile(path[2])
        f_sigMC2 = TFile(path[3])
        t_incMC1 = f_incMC1.Get('save')
        t_incMC2 = f_incMC2.Get('save')
        t_sigMC1 = f_sigMC1.Get('save')
        t_sigMC2 = f_sigMC2.Get('save')
        entries_incMC1 = t_incMC1.GetEntries()
        entries_incMC2 = t_incMC2.GetEntries()
        entries_sigMC1 = t_sigMC1.GetEntries()
        entries_sigMC2 = t_sigMC2.GetEntries()
        logging.info('inclusive MC (qqbar) entries :' + str(entries_incMC1))
        logging.info('inclusive MC (open charm) entries :' +
                     str(entries_incMC2))
        logging.info('D1(2420) signal MC entries :' + str(entries_sigMC1))
        logging.info('psi(3770) signal MC entries :' + str(entries_sigMC2))
    except:
        logging.error('Files are invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    xbins = 150
    M_Dplus = 1.86965
    step = (1.91965 - M_Dplus) / xbins

    h_FOM, ientry, arrow_top = cal_significance(t_incMC1, t_incMC2, t_sigMC1,
                                                t_sigMC2, xbins, step, ecms)
    h_FOM.Draw()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    arrow_left = ientry * step + step
    arrow_right = ientry * step + step
    arrow_bottom = 0.
    arrow = TArrow(arrow_left, arrow_bottom, arrow_right, arrow_top, 0.01, '>')
    set_arrow(arrow)
    arrow.Draw()

    pt = TPaveText(0.6, 0.8, 0.85, 0.85, "BRNDC")
    set_pavetext(pt)
    pt.Draw()
    pt.AddText(pt_title)

    mass_low = str(M_Dplus - (step + step * ientry))
    mass_up = str(M_Dplus + (step + step * ientry))
    window_width = str(2 * (step + step * ientry))
    range = 'Recoiling mass window of D^{+}#pi^{+}#pi^{-}: : [' + mass_low + ', ' + mass_up + '] GeV/c2' + ' with mass window width: ' + window_width + ' GeV/c2'
    print range

    mbc.Update()
    mbc.SaveAs('./figs/opt_rm_Dpipi_' + str(ecms) + '.pdf')
示例#3
0
def DrawUL(gUL):
    alist = TList()
    for i in range(gUL.GetN()):
        a = TArrow(gUL.GetX()[i],
                   gUL.GetY()[i],
                   gUL.GetX()[i],
                   gUL.GetY()[i] / 3., 0.01, ">")
        a.SetLineColor(gUL.GetLineColor())
        a.Draw()
        alist.Add(a)

    return alist
示例#4
0
def plot(path, pt_title, ecms, arrow_left, arrow_bottom, arrow_right,
         arrow_top):
    try:
        f_incMC1 = TFile(path[0])
        f_incMC2 = TFile(path[1])
        f_sigMC1 = TFile(path[2])
        f_sigMC2 = TFile(path[3])
        t_incMC1 = f_incMC1.Get('save')
        t_incMC2 = f_incMC2.Get('save')
        t_sigMC1 = f_sigMC1.Get('save')
        t_sigMC2 = f_sigMC2.Get('save')
        entries_incMC1 = t_incMC1.GetEntries()
        entries_incMC2 = t_incMC2.GetEntries()
        entries_sigMC1 = t_sigMC1.GetEntries()
        entries_sigMC2 = t_sigMC2.GetEntries()
        logging.info('inclusive MC (qqbar) entries :' + str(entries_incMC1))
        logging.info('inclusive MC (open charm) entries :' +
                     str(entries_incMC2))
        logging.info('D1(2420) signal MC entries :' + str(entries_sigMC1))
        logging.info('psi(3770) signal MC entries :' + str(entries_sigMC2))
    except:
        logging.error('Files are invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    xbins = 100
    step = 100 / xbins

    h_FOM, ientry = cal_significance(t_incMC1, t_incMC2, t_sigMC1, t_sigMC2,
                                     xbins, step, ecms)
    h_FOM.Draw()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    arrow = TArrow(arrow_left, arrow_bottom, arrow_right, arrow_top, 0.01, '>')
    set_arrow(arrow)
    arrow.Draw()

    pt = TPaveText(0.6, 0.8, 0.85, 0.85, "BRNDC")
    set_pavetext(pt)
    pt.Draw()
    pt.AddText(pt_title)

    range = 'chi2 of kinematic fit of D^{+}D_{miss}#pi^{+}#pi^{+}: ' + str(
        arrow_right)
    print range

    mbc.Update()
    mbc.SaveAs('./figs/opt_chi2_kf_' + str(ecms) + '.pdf')
示例#5
0
文件: rutil.py 项目: apjd/usercode
 def addLine(self, x1, y1, x2, y2, arrow="", arrowsize=0.1):
     if arrow == "":
         tl = TLine(x1, y1, x2, y2)
     elif arrow == "<->":
         tl = TArrow(x1, y1, x2, y2, arrowsize, "<|>")
     elif arrow == "->":
         print x2, y2, arrowsize
         tl = TArrow(x1, y1, x2, y2, arrowsize, "|>")
         tl.SetAngle(40)
         tl.SetLineWidth(1)
         tl.SetFillColor(1)
     tl.Draw("same")
     self.tlines.append(tl)
     return tl
示例#6
0
def createOutOfRangeArrows(obj,
                           minimum,
                           maximum,
                           arrowSize=0.01,
                           arrowLength=0.2,
                           arrowStyle='|>',
                           style=Style(kRed, lineWidth=2, fillStyle=1001)):
    ## Creates TArrow objects to indicate where points lie if they are
    #  outside of the given boundaries.
    #  @param obj          TGraph or TH1 object
    #  @param minimum      minimum to be considered
    #  @param maximum      maximum to be considered
    #  @param arrowSize    size of the arrow tip in units of the pad size
    #  @param arrowLength  length of the arrow in units of (maximum - minimum)
    #  @param arrowStyle   style of the arrow tip (see TArrow documentation)
    #  @style              Style object defining the arrow color
    #  @return list of TArrow objects
    from ROOT import TArrow, TGraph, TH1, Double
    arrows = []
    arrowLength = arrowLength * (maximum - minimum)
    if isinstance(obj, TH1):
        for iBin in xrange(1, obj.GetNbinsX() + 1):
            x = obj.GetBinCenter(iBin)
            y = obj.GetBinContent(iBin)
            if minimum > y:
                arrows.append(
                    TArrow(x, minimum + 1.1 * arrowLength, x,
                           minimum + 0.1 * arrowLength, arrowSize, arrowStyle))
            elif maximum < y:
                arrows.append(
                    TArrow(x, maximum - 1.1 * arrowLength, x,
                           maximum - 0.1 * arrowLength, arrowSize, arrowStyle))
    elif isinstance(obj, TGraph):
        x, y = (Double(), Double())
        for iBin in xrange(0, obj.GetN()):
            obj.GetPoint(iBin, x, y)
            if minimum > y:
                arrows.append(
                    TArrow(x, minimum + 1.1 * arrowLength, x,
                           minimum + 0.1 * arrowLength, arrowSize, arrowStyle))
            elif maximum < y:
                arrows.append(
                    TArrow(x, maximum - 1.1 * arrowLength, x,
                           maximum - 0.1 * arrowLength, arrowSize, arrowStyle))
    if style:
        for arrow in arrows:
            style.apply(arrow)
    return arrows
示例#7
0
def plot(path, pt_title, ecms):
    try:
        f_data = TFile(path[0])
        f_sigMC = TFile(path[1])
        t_data = f_data.Get('save')
        t_sigMC = f_sigMC.Get('save')
        entries_data = t_data.GetEntries()
        entries_sigMC = t_sigMC.GetEntries()
        logging.info('data entries :' + str(entries_data))
        logging.info('MC(DDPI) entries :' + str(entries_sigMC))
    except:
        logging.error('Files are invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    h_FOM = cal_significance(t_data, t_sigMC)
    h_FOM.Draw('col')

    pt = TPaveText(0.6, 0.6, 0.85, 0.85, "BRNDC")
    set_pavetext(pt)
    pt.Draw()
    pt.AddText(pt_title)

    D0_W = width('D0')
    Dm_W = width('Dm')
    Arr_Dm = TArrow(Dm_W, 0, Dm_W, 0.35, 0.01, '')
    set_arrow(Arr_Dm, 1)
    Arr_Dm.Draw()
    Arr_D0 = TArrow(0, D0_W, 0.3, D0_W, 0.01, '')
    set_arrow(Arr_D0, 1)
    Arr_D0.Draw()

    mbc.RedrawAxis()
    mbc.Update()
    mbc.SaveAs('./figs/opt_' + str(ecms) + '_2D.pdf')

    raw_input('Enter anything to end...')
示例#8
0
def plot(path, pt_title, ecms):
    try:
        f_data = TFile(path[0])
        f_sideband = TFile(path[1])
        t_data = f_data.Get('save')
        t_sideband = f_sideband.Get('save')
        entries_data = t_data.GetEntries()
        entries_sideband = t_sideband.GetEntries()
        logging.info('data entries :' + str(entries_data))
        logging.info('data (sideband) entries :' + str(entries_sideband))
    except:
        logging.error('Files are invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)

    h_FOM = cal_significance(t_data, t_sideband)
    h_FOM.Draw('colz')

    pt = TPaveText(0.6, 0.8, 0.85, 0.85, "BRNDC")
    set_pavetext(pt)
    pt.Draw()
    pt.AddText(pt_title)

    Arr_Vr = TArrow(0.55, 0, 0.55, 10., 0.01, '')
    set_arrow(Arr_Vr, 1)
    Arr_Vr.Draw()
    Arr_Vz = TArrow(0, 3., 1., 3., 0.01, '')
    set_arrow(Arr_Vz, 1)
    Arr_Vz.Draw()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    mbc.RedrawAxis()
    mbc.Update()
    mbc.SaveAs('./figs/opt_Vr_Vz_' + str(ecms) + '.pdf')

    raw_input('Enter anything to end...')
示例#9
0
 def addArrow(self, x1, y1, x2, y2, color, option, thickness=0.):
     arrow = TArrow(x1, y1, x2, y2, 0.05, option)
     arrow.SetLineColor(color)
     if thickness:
         arrow.SetLineWidth(thickness)
     self.arrows.append(arrow)
示例#10
0
def drawDataMC(region):
    hists=allHists()
    os.mkdir("plots/%s" % region)
    for variable in variables:
        hist_data=hists[region+"_"+variable+"_data"]
        hist_signal=hists[region+"_"+variable+"_tth"]
        mchists=[]
        for i in processes:
            if i != 'data' and i != 'tth':
                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: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 processes:
             if i != 'data' and i != 'tth': leg.AddEntry(hists[region+"_"+variable+"_"+i], i, "f")
        leg.AddEntry(h_bkg,"uncertainty",'f')
        Ymaximum = 3.*hist_data.GetBinContent(hist_data.GetMaximumBin())
        hs.SetMaximum(Ymaximum)
        hs.SetMinimum(0.00001)
        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)
        if region != 'OneL2tauSR' or isBlinded == False :
           hist_data.Draw("e x0 same")
        hist_signal.SetLineColor(kRed)
        hist_signal.SetLineStyle(kDashed)
        if hist_signal.Integral(0, hist_signal.GetNbinsX()+1) != 0:
           hist_signal.Scale(hist_data.Integral(0,hist_data.GetNbinsX()+1)/hist_signal.Integral(0, hist_signal.GetNbinsX()+1)) #scale to data
        hist_signal.Draw("hist same")
        createLabels()
        leg.Draw("same")
        #ratio plot
        pad2.cd()
        h_ratio_err.SetMinimum(0.000001)# also to avoid drawing markers for ratio with 0 contents (P doesn't work)
        h_ratio_err.SetMaximum(2.0)
        h_ratio_err.GetYaxis().SetTitle("Data/Bkg")
        h_ratio_err.GetYaxis().SetTitleSize(0.06)
        h_ratio_err.GetYaxis().SetTitleOffset(1)
        h_ratio_err.GetXaxis().SetTitle(XTitle)
        h_ratio_err.GetXaxis().SetLabelSize(0.14)
        h_ratio_err.GetXaxis().SetLabelOffset(0.025)
        h_ratio_err.GetXaxis().SetTitleSize(0.13)
        h_ratio_err.GetXaxis().SetTitleOffset(1.05)
        h_ratio_err.GetYaxis().SetLabelSize(0.1)
        h_ratio_err.GetYaxis().SetTitleSize(0.14)
        h_ratio_err.GetYaxis().SetTitleOffset(0.40)
        h_ratio_err.GetYaxis().SetNdivisions(505)
        h_ratio.SetMarkerStyle(20)
        h_ratio.SetMarkerSize(0.8)
        h_ratio_err.SetMarkerSize(0)
        h_ratio_err.SetFillColor(17)
        h_ratio_err.Draw("e2")
        if region != 'OneL2tauSR' or isBlinded == False :
           h_ratio.Draw("E0 P 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))
示例#11
0
def main():

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

    gStyle.SetOptStat(0)
    gStyle.SetGridStyle(1)
    gStyle.SetGridColor(11)
    hh = TH2D('hh', ';Y;X', 2, 2, 4, 14, 2, 16)
    hi = TH2I('hi', ';Y;X', 2, 2, 4, 14, 2, 16)
    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)
    gPad.SetRightMargin(0.12)

    tt1 = TPaveText(0.05, 0.94, 0.22, 1.0, 'NDC')
    ttL = TPaveText(0.05, 0.905, 0.2, 0.93, 'NDC')
    ttR = TPaveText(0.75, 0.905, 0.9, 0.93, 'NDC')

    ttLM = TPaveText(2, 0.5, 2.5, 1)
    ttRM = TPaveText(3.5, 0.5, 4, 1)

    ttM = TPaveText(0.6, 0.94, 0.9, 1, 'NDC')
    ttime = TPaveText(2.8, 1.5, 3.3, 1.9)
    tchan = TPaveText(0, 0, 0.9, 1)
    setupPaveTexts([tt1, ttM, ttime, tchan, ttL, ttR, ttLM, ttRM])
    ttM.SetTextColor(2)

    tarrow = TText(2.9, 0.25, 'Beam Left')
    arrow = TArrow(2.85, 0.5, 2.75, 0.5, 0.02, '|>')
    arrow.SetAngle(40)
    arrow.SetFillColor(1)
    arrow.SetLineWidth(2)

    tt = TText()
    tt.SetTextColor(1)
    tt.SetTextAngle(90)
    tt.SetTextSize(0.04)
    tt.DrawText(4.07, 9, 'kHz')
    tt.SetTextAngle(0)
    tt.SetTextColor(2)
    tt.DrawTextNDC(0.23, 0.905, 'SHMS PCAL FADC SCALERS')
    ttL.AddText('Left+')
    ttR.AddText('-Right')

    cc.cd()
    for xx in [ttM, tt1, ttL, ttR, arrow, tarrow, ttime, ttLM, ttRM]:
        xx.Draw()
    cc2.cd()
    tchan.Draw('NDC')
    cc.cd()

    xmin, xmax = xax.GetXmin(), xax.GetXmax()
    ymin, ymax = yax.GetXmin(), yax.GetXmax()

    gPad.SetEditable(0)

    while True:

        zvals = getScalars()

        for ii in range(len(zvals)):
            hh.SetBinContent(xax.FindBin(XVALS[ii] + 1),
                             yax.FindBin(16 - YVALS[ii]), zvals[ii])
            hi.SetBinContent(xax.FindBin(XVALS[ii] + 1),
                             yax.FindBin(16 - YVALS[ii]), zvals[ii])

        for xx in [ttime, ttM, tt1, ttLM, ttRM]:
            xx.Clear()
        [left, right, maximum] = calcRates(zvals)
        tt1.AddText('Total:  %.1f MHz' % ((left + right) / 1000))
        ttLM.AddText('Left total: %.1f MHz' % (left / 1000))
        ttRM.AddText('Right total: %.1f MHz' % (right / 1000))
        ttM.AddText('MAX SINGLE CRYSTAL = %.0f kHz' % (maximum))
        ttime.AddText(makeTime())

        if not gPad: sys.exit()

        #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)
示例#12
0
offset.AddText('Offset of events in fBuffer')
offset.AddText('Array of fEventOffsetLen Integers')
offset.AddText('(if variable length structure)')
offset.SetFillColor(offsetcolor)
offset.Draw()
buffer = TPaveText(.55, .05, .9, .1)
buffer.AddText('Basket buffer')
buffer.AddText('Array of fBasketSize chars')
buffer.SetFillColor(offsetcolor)
buffer.Draw()
zipbuffer = TPaveText(.55, -.05, .75, .0)
zipbuffer.AddText('Basket compressed buffer')
zipbuffer.AddText('(if compression)')
zipbuffer.SetFillColor(offsetcolor)
zipbuffer.Draw()
ar1 = TArrow()
ar1.SetLineWidth(2)
ar1.SetLineColor(1)
ar1.SetFillStyle(1001)
ar1.SetFillColor(1)
ar1.DrawArrow(.21, .275, .39, .275, 0.015, '|>')
ar1.DrawArrow(.23, .375, .39, .375, 0.015, '|>')
ar1.DrawArrow(.25, .775, .39, .775, 0.015, '|>')
ar1.DrawArrow(.50, .775, .59, .775, 0.015, '|>')
ar1.DrawArrow(.70, .775, .79, .775, 0.015, '|>')
ar1.DrawArrow(.50, .275, .59, .275, 0.015, '|>')
ar1.DrawArrow(.70, .275, .79, .275, 0.015, '|>')
ar1.DrawArrow(.45, .175, .54, .175, 0.015, '|>')
ar1.DrawArrow(.43, .075, .54, .075, 0.015, '|>')
ar1.DrawArrow(.41, -.025, .54, -.025, 0.015, '|>')
ldot = TLine(.95, .92, .99, .92)
示例#13
0
def plot(data_path, pt_title, ecms, xmin, xmax, xbins, mode):
    try:
        f_data = TFile(data_path)
        t_data = f_data.Get('save')
        entries_data = t_data.GetEntries()
        logging.info('data entries :' + str(entries_data))
    except:
        logging.error('File paths are invalid!')
        sys.exit()

    set_pub_style()
    set_prelim_style()

    window_low = 1.86965 - window(ecms) / 2.
    window_up = 1.86965 + window(ecms) / 2.
    window_side_low_up = window_low - (window_up - window_low)
    window_side_low_low = window_side_low_up - (window_up - window_low)
    window_side_up_low = window_up + (window_up - window_low)
    window_side_up_up = window_side_up_low + (window_up - window_low)

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    content = (xmax - xmin) / xbins * 1000
    ytitle = 'Events/%.1f MeV/c^{2}' % content
    xtitle = 'RM(D^{+}#pi_{d}^{+}#pi_{d}^{-}) (GeV/c^{2})'
    h_data = TH1F('data', 'data', xbins, xmin, float(xmax))

    format_data_hist(h_data)
    if ecms == 4420 or ecms == 4680:
        h_data.GetYaxis().SetTitleOffset(1.15)
    h_data.GetXaxis().SetTitleOffset(0.99)
    name_axis(h_data, xtitle, ytitle)
    rm_Dpipi_fill(t_data, h_data, window_low, window_up)

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    if mode == 'after' and ecms == 4230:
        h_data.GetYaxis().SetRangeUser(0, 1.2 * h_data.GetMaximum())
    h_data.Draw('E1')

    if ecms == 4420 and mode == 'before': low = 380
    elif ecms == 4420 and mode == 'after': low = 240
    elif ecms == 4230 and mode == 'before': low = 14
    elif ecms == 4230 and mode == 'after': low = 0
    elif ecms == 4680 and mode == 'before': low = 950
    elif ecms == 4680 and mode == 'after': low = 620
    else: low = 0
    top = h_data.GetMaximum()
    if ecms == 4680: top = top / 0.88

    arrow1 = TArrow(window_low, low, window_low, 0.8 * top, 0.02, '<-')
    set_arrow(arrow1, ROOT.kRed)
    arrow1.SetLineStyle(2)
    arrow1.Draw()

    arrow2 = TArrow(window_up, low, window_up, 0.8 * top, 0.02, '<-')
    set_arrow(arrow2, ROOT.kRed)
    arrow2.SetLineStyle(2)
    arrow2.Draw()

    arrow3 = TArrow(window_side_low_low, low, window_side_low_low, 0.8 * top,
                    0.02, '<-')
    set_arrow(arrow3, ROOT.kBlue)
    arrow3.Draw()

    arrow4 = TArrow(window_side_low_up, low, window_side_low_up, 0.8 * top,
                    0.02, '<-')
    set_arrow(arrow4, ROOT.kBlue)
    arrow4.Draw()

    arrow5 = TArrow(window_side_up_low, low, window_side_up_low, 0.8 * top,
                    0.02, '<-')
    set_arrow(arrow5, ROOT.kBlue)
    arrow5.Draw()

    arrow6 = TArrow(window_side_up_up, low, window_side_up_up, 0.8 * top, 0.02,
                    '<-')
    set_arrow(arrow6, ROOT.kBlue)
    arrow6.Draw()

    leg = TLegend(position_convert(0.8 * (xmax - xmin) + xmin, xmin, xmax),
                  position_convert(0.8 * (top - low) + low, low, top),
                  position_convert(0.95 * (xmax - xmin) + xmin, xmin, xmax),
                  position_convert((top - low) + low, low, top), 'BRNDC')
    set_legend(leg, h_data, 'Data', pt_title)
    leg.Draw()

    h_data.Draw('sameE1')
    mbc.SaveAs('./figs/rm_Dpipi_' + str(ecms) + '_' + mode + '.pdf')

    raw_input('Enter anything to end...')
示例#14
0
c1.Range(1, 1, 19, 24.5)

title = TPaveLabel(4, 23, 16, 24.2, 'ROOT File/Directory/Key description')
title.SetFillColor(16)
title.Draw()

keycolor = 42
dircolor = 21
objcolor = 46
file = TPaveText(2, 19, 6, 22)
file.SetFillColor(39)
file.Draw()
file.SetTextSize(0.04)
file.AddText('TFile')
file.AddText('Header')
arrow = TArrow(6, 20.5, 17, 20.5, 0.02, '|>')
arrow.SetFillStyle(1001)
arrow.SetLineWidth(2)
arrow.Draw()
free = TPaveText(8, 20, 11, 21)
free.SetFillColor(18)
free.Draw()
free.AddText('First:Last')
free2 = TPaveText(12, 20, 15, 21)
free2.SetFillColor(18)
free2.Draw()
free2.AddText('First:Last')
tfree = TText(6.2, 21.2, 'fFree = TList of free blocks')
tfree.SetTextSize(0.02)
tfree.Draw()
tkeys = TText(5.2, 18.2, 'fKeys = TList of Keys')
示例#15
0
def main():

    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',22,-10.5,11.5,22,-10.5,11.5)
    hi=TH2I('hi',';X;Y',22,-10.5,11.5,22,-10.5,11.5)
    setupHists([hh,hi])
    xax,yax=hh.GetXaxis(),hh.GetYaxis()
    hh.Draw('COLZ')
    hi.Draw('TEXTSAME')

    gPad.SetLogz()
    gPad.SetGrid(1,1)
    gPad.SetLeftMargin(0.09)
    gPad.SetRightMargin(0.11)

    #tt2=TPaveText(0.7,0.96,0.9,0.99,'NDC')
    ttM=TPaveText(-3+0.05, 7-4.45, 4.0, 8-4.51)
    tt2=TPaveText(-3+0.05, 7-5.45, 4.0, 8-5.51)

    ttX=TPaveText(-2, 7-8.00, 3, 8-8.00)
    ttY=TPaveText(-2, 7-9.00, 3, 8-9.00)
    ttZ=TPaveText(-2, 6-8.80, 3, 8-9.30)
    ttZ.AddText("positive = beam top/right")

    ttime=TPaveText(-10,-12.5,10,-11.8)
    tchan=TPaveText(0,0,0.9,1)
    setupPaveTexts([tt2,ttM,ttime,tchan,ttX,ttY,ttZ])
    ttM.SetTextColor(2)
    ttM.SetFillStyle(0)
    ttZ.SetFillStyle(0)
    tt2.SetFillStyle(0)

    tarrow=TText(-0.9,0.7,'Beam Right')
    tarrow.SetTextSizePixels(15)
    arrow=TArrow(-1.4,0.5,2.4,0.5,0.02,'|>')
    arrow.SetAngle(40)
    arrow.SetFillColor(1)
    arrow.SetLineWidth(2)

    tt=TText()
    tt.SetTextColor(1)
    tt.SetTextAngle(90)
    tt.SetTextSize(0.04)
    tt.DrawText(12.4,0,'kHz')
    tt.SetTextAngle(0)
    tt.SetTextColor(1)
    tt.DrawTextNDC(0.3,0.92,'FTC FADC SCALERS')

    bb=TBox()
    bb.SetFillStyle(1001)
    bb.SetFillColor(0)
    bb.SetLineWidth(1)
    bb.SetLineColor(1)
    bb.DrawBox(-3.47,-1.47,4.47,2.46)
    bb.DrawBox(-1.47,-3.47,2.49,4.47)
    bb.DrawBox(-2.47,-2.47,3.49,3.47)

    cc.cd()
    for xx in [ttM,tt2,ttime,arrow,tarrow,ttX,ttY,ttZ]: xx.Draw()
    cc2.cd()
    tchan.Draw('NDC')
    cc.cd()

    gPad.SetEditable(0)

    while True:

            for ch in ECAL.chans:
              loadPV(ch)
              ch=ch.vals
              xx,yy=ch['X'],ch['Y']
              #if (ch['PVVAL']>10):
               # print xx,yy,ch['PVVAL']

              # swap x to make it downstream view:
              xx=-xx

              #after, fix the fact x=0 / y=0 don't exists
              if xx<0: xx+=1
              if yy<0: yy+=1
              hh.SetBinContent(xax.FindBin(xx),yax.FindBin(yy),ch['PVVAL'])
              hi.SetBinContent(xax.FindBin(xx),yax.FindBin(yy),ch['PVVAL'])

            for xx in [ttime,tt2,ttM,ttX,ttY]: xx.Clear()
            [total,maximum,top,bottom,left,right]=calcRates(ECAL.chans)

            tt2.AddText('Total:  %.1f MHz'%(total/1000))
            ttM.AddText('Max:  %.0f kHz'%(maximum))

            if total>1e2:
              xasy = (right-left)/total
              yasy = (top-bottom)/total
              ttX.AddText('X-Asy:  %+.1f%%'%(100*xasy))
              ttY.AddText('Y-Asy:  %+.1f%%'%(100*yasy))
            else:
              ttX.AddText('X-Asy:  N/A')
              ttY.AddText('Y-Asy:  N/A')

            ttime.AddText(makeTime())

            if not gPad: sys.exit()

            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(2)
示例#16
0
def main(options, args):

    from ROOT import gSystem, gROOT, gStyle
    gROOT.SetBatch()
    gSystem.Load("libRooFitCore")

    if options.doWebPage:
        from lip.Tools.rootutils import loadToolsLib, apply_modifs
        loadToolsLib()

    from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList
    from ROOT import kWhite, kBlue, kOpenSquare
    if options.doWebPage:
        from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot

    rootglobestyle.setTDRStyle()
    gStyle.SetMarkerSize(1.5)
    gStyle.SetTitleYOffset(1.5)

    gStyle.SetPadLeftMargin(0.16)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.13)

    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelOffset(0.007, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")

    gStyle.SetTitleSize(0.06, "XYZ")
    gStyle.SetTitleXOffset(0.9)
    gStyle.SetTitleYOffset(1.24)
    gStyle.SetTitleFont(42, "XYZ")

    ##
    ## Read files
    ##
    options.outdir = "%s_m%1.0f" % (options.outdir, options.mH)
    if options.fp:
        options.outdir += "_fp"

    ncat = options.ncat
    cats = options.cats
    if cats is "":
        categories = ["_cat%d" % i for i in range(0, ncat)]
    else:
        categories = ["_cat%s" % i for i in cats.split(",")]

    if options.mva:
        clables = {
            "_cat0": ("MVA > 0.89", ""),
            "_cat1": ("0.74 #leq MVA", "MVA < 0.89"),
            "_cat2": ("0.545 #leq MVA", "MVA < 0.74"),
            "_cat3": ("0.05 #leq MVA", "MVA < 0.545"),
            "_cat4": ("Di-jet", "Tagged"),
            "_cat5": ("Di-jet", "Tagged"),
            "_combcat": ("All Classes", "Combined")
        }
    else:
        clables = {
            "_cat0": ("max(|#eta|<1.5", "min(R_{9})>0.94"),
            "_cat1": ("max(|#eta|<1.5", "min(R_{9})<0.94"),
            "_cat2": ("max(|#eta|>1.5", "min(R_{9})>0.94"),
            "_cat3": ("max(|#eta|>1.5", "min(R_{9})<0.94"),
            "_cat4": ("Di-jet", "Tagged"),
            "_cat5": ("Di-jet", "Tagged"),
            "_combcat": ("All Classes", "Combined")
        }
    helper = Helper()

    fin = TFile.Open(options.infile)
    helper.files.append(fin)
    ws = fin.Get("cms_hgg_workspace")
    mass = ws.var("CMS_hgg_mass")
    mass.SetTitle("m_{#gamma#gamma}")
    mass.setUnit("GeV")
    mass.setRange(100., 150.)
    mass.setBins(100, "plot")
    mass.setBins(5000)

    print ws

    aset = RooArgSet(mass)

    helper.objs.append(mass)
    helper.objs.append(aset)

    fitopt = (RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False),
              RooFit.SumW2Error(False), RooFit.NumCPU(8))

    if not options.binned and not options.refit:
        finpdf = TFile.Open(options.infilepdf)
        helper.files.append(finpdf)
        wspdf = finpdf.Get("wsig")
    else:
        wspdf = ws

    for c in categories:
        processes = ["ggh", "vbf", "wzh"]
        if options.fp:
            processes = ["vbf", "wzh"]
        ### elif clables[c][0] == "Di-jet":
        ###     processes = [ "vbf", "ggh" ]

        dsname = "sig_mass_m%1.0f%s" % (options.mH, c)
        print dsname
        print ws
        ds = ws.data("sig_%s_mass_m%1.0f%s" %
                     (processes[0], options.mH, c)).Clone(dsname)
        for proc in processes[1:]:
            ds.append(ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c)))
        helper.dsets.append(ds)

        if options.binned:
            binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname,
                                    aset, ds)
            pdf = RooKeysPdf("pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname,
                             mass, ds)
            plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset,
                                  plot_ds)
            helper.add(binned_ds, binned_ds.GetName())
        else:
            if options.refit:
                if options.refitall and clables[c][0] != "Di-jet":
                    rpdfs = []
                    for proc in processes:
                        for ngaus in range(1, 4):
                            pp = build_pdf(ws, "%s_%s" % (c, proc), ngaus,
                                           ngaus == 3)
                            pp.fitTo(
                                ws.data("sig_%s_mass_m%1.0f%s" %
                                        (proc, options.mH, c)),
                                RooFit.Strategy(0), *fitopt)
                        rpdfs.append(pp)
                    pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c,
                                    RooArgList(*tuple(rpdfs)))
                else:
                    if options.refitall and clables[c][0] == "Di-jet":
                        for ngaus in range(1, 5):
                            pdf = build_pdf(ws, c, ngaus, ngaus == 5)
                            pdf.fitTo(ds, RooFit.Strategy(0), *fitopt)
                    else:
                        for ngaus in range(1, 4):
                            pdf = build_pdf(ws, c, ngaus, ngaus == 3)
                            pdf.fitTo(ds, RooFit.Strategy(0), *fitopt)
            else:
                pdfs = (wspdf.pdf("hggpdfrel%s_%s" % (c, p))
                        for p in processes)
                pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c,
                                RooArgList(*pdfs))
            helper.add(pdf, pdf.GetName())
            plot_pdf = pdf.Clone("pdf_%s" % dsname)

        plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset,
                              "plot")
        plot_ds.add(ds)

        cdf = pdf.createCdf(aset)
        hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10.,
                                  options.mH + 10.)
        wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10.,
                                   options.mH + 10.)
        ### hmin, hmax, hm = get_FWHM( points )

        helper.add(plot_ds, plot_ds.GetName())
        helper.add(plot_pdf, plot_pdf.GetName())
        helper.add((wmin, wmax), "eff_sigma%s" % c)
        helper.add((hmin, hmax, hm), "FWHM%s" % c)
        helper.add(ds.sumEntries(),
                   "sumEntries%s" % c)  # signal model integral

        # data integral for PAS tables
        data = ws.data("data_mass%s" % c)
        helper.add(
            data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f" %
                            (options.mH - 10., options.mH + 10.)),
            "data_sumEntries%s" % c)

        del cdf
        del pdf

    dsname = "sig_mass_m%1.0f_combcat" % options.mH
    print dsname
    combined_ds = helper.dsets[0].Clone(dsname)
    for d in helper.dsets[1:]:
        combined_ds.append(d)

    if options.binned:
        binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname,
                                aset, combined_ds)
        pdf = RooKeysPdf("pdf_%s" % (dsname), "pdf_%s" % dsname, mass,
                         combined_ds)
        plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset,
                              plot_ds)
        helper.add(binned_ds, binned_ds.GetName())
    else:
        #### pdf = build_pdf(ws,"_combcat")
        #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt )
        #### plot_pdf = pdf.Clone( "pdf_%s" % dsname )
        pdf = RooAddPdf(
            "pdf_%s" % dsname, "pdf_%s" % dsname,
            RooArgList(*(helper.histos["hggpdfrel%s" % c]
                         for c in categories)))
        plot_pdf = pdf

    cdf = pdf.createCdf(aset)

    plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot")
    plot_ds.add(combined_ds)

    wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10.,
                               options.mH + 10.)
    hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10.,
                              options.mH + 10.)

    helper.add(plot_ds, plot_ds.GetName())
    helper.add(plot_pdf, plot_pdf.GetName())
    helper.add((wmin, wmax), "eff_sigma_combcat")
    helper.add((hmin, hmax, hm), "FWHM_combcat")
    helper.add(plot_ds.sumEntries(), "sumEntries_combcat")

    mass.setRange("higgsrange", options.mH - 25., options.mH + 15.)

    del cdf
    del pdf
    del helper.dsets

    ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}")
    label = TLatex(0.7, 0.86,
                   "#scale[0.65]{#splitline{CMS preliminary}{Simulation}}")
    label.SetNDC(1)

    ##
    ## Make web page with plots
    ##
    if options.doWebPage:
        hth = HtmlHelper(options.outdir)
        hth.navbar().cell(HtmlTag("a")).firstChild().txt("..").set(
            "href", "../?C=M;O=D")
        hth.navbar().cell(HtmlTag("a")).firstChild().txt("home").set(
            "href", "./")

        tab = hth.body().add(HtmlTable())

    ip = 0
    for c in ["_combcat"] + categories:
        ### for c in categories:
        if options.doWebPage and ip % 4 == 0:
            row = tab.row()
        ip = ip + 1

        dsname = "sig_mass_m%1.0f%s" % (options.mH, c)
        canv = TCanvas(dsname, dsname, 600, 600)
        helper.objs.append(canv)

        ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322)
        leg = TLegend(0.2, 0.96, 0.5, 0.55)
        #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] )

        hplotcompint = mass.frame(RooFit.Bins(250), RooFit.Range("higgsrange"))
        helper.objs.append(hplotcompint)
        helper.objs.append(leg)

        plot_ds = helper.histos["plot_%s" % dsname]
        plot_pdf = helper.histos["pdf_%s" % dsname]
        wmin, wmax = helper.histos["eff_sigma%s" % c]
        hmin, hmax, hm = helper.histos["FWHM%s" % c]
        print hmin, hmax, hm

        style = (RooFit.LineColor(kBlue), RooFit.LineWidth(2),
                 RooFit.FillStyle(0))
        style_seff = (
            RooFit.LineWidth(2),
            RooFit.FillStyle(1001),
            RooFit.VLines(),
            RooFit.LineColor(15),
        )
        style_ds = (RooFit.MarkerStyle(kOpenSquare), )

        plot_ds.plotOn(hplotcompint, RooFit.Invisible())

        plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"),
                        RooFit.Range(wmin, wmax), RooFit.FillColor(19),
                        RooFit.DrawOption("F"), *style_seff)
        seffleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1))
        plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"),
                        RooFit.Range(wmin, wmax), RooFit.LineColor(15),
                        *style_seff)

        plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"),
                        RooFit.Range("higgsrange"), *style)
        pdfleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1))

        plot_ds.plotOn(hplotcompint, *style_ds)
        pointsleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1))

        iob = int(hplotcompint.numItems() - 1)
        leg.AddEntry(pointsleg, "Simulation", "pe")
        leg.AddEntry(pdfleg, "Parametric model", "l")
        leg.AddEntry(seffleg,
                     "#sigma_{eff} = %1.2f GeV " % (0.5 * (wmax - wmin)), "fl")

        clabel = TLatex(0.74, 0.65,
                        "#scale[0.65]{#splitline{%s}{%s}}" % clables[c])
        clabel.SetNDC(1)
        helper.objs.append(clabel)

        hm = hplotcompint.GetMaximum() * 0.5 * 0.9
        ### hm = pdfleg.GetMaximum()*0.5
        fwhmarrow = TArrow(hmin, hm, hmax, hm)
        fwhmarrow.SetArrowSize(0.03)
        helper.objs.append(fwhmarrow)
        fwhmlabel = TPaveText(0.20, 0.58, 0.56, 0.48, "brNDC")
        fwhmlabel.SetFillStyle(0)
        fwhmlabel.SetLineColor(kWhite)
        reducedFWHM = (hmax - hmin) / 2.3548200
        fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM)
        helper.objs.append(fwhmlabel)

        hplotcompint.SetTitle("")
        hplotcompint.GetXaxis().SetNoExponent(True)
        hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)")
        hplotcompint.GetXaxis().SetNdivisions(509)
        ## hplotcompint.GetYaxis().SetTitle("A.U.");
        ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4);
        hplotcompint.Draw()
        leg.Draw("same")
        label.Draw("same")
        clabel.Draw("same")
        fwhmarrow.Draw("<>")
        fwhmlabel.Draw("same")

        plot_ds.sumEntries()

        if options.doWebPage:
            hpl = HtmlPlot(canv, False, "", True, True, True)
            hpl.caption("<i>%s</i>" % canv.GetTitle())
            row.cell(hpl)
        else:
            if os.path.isdir(options.outdir) is False:
                os.mkdir(options.outdir)
            for ext in "C", "png", "pdf":
                canv.SaveAs(
                    os.path.join(options.outdir,
                                 "%s.%s" % (canv.GetName(), ext)))

        if "comb" in c:
            ip = 0

    if options.doWebPage:
        print "Creating pages..."
        hth.dump()

    for f in helper.files:
        f.Close()
    gROOT.Reset()

    from pprint import pprint
    pprint(helper)

    print 'Summary statistics per event class'
    print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35' % options.mH
    sigTotal = 0.
    dataTotal = 0.
    for c in categories:
        sigVal = helper.histos["sumEntries%s" % c]
        datVal = helper.histos["data_sumEntries%s" % c]
        sigTotal += sigVal
        dataTotal += datVal
    for c in categories:
        sigVal = helper.histos["sumEntries%s" % c]
        datVal = helper.histos["data_sumEntries%s" % c]
        effSig = 0.5 * (helper.histos["eff_sigma%s" % c][1] -
                        helper.histos["eff_sigma%s" % c][0])
        fwhm = (helper.histos["FWHM%s" % c][1] -
                helper.histos["FWHM%s" % c][0]) / 2.3548200
        print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f' % (
            sigVal, 100. * sigVal / sigTotal, datVal /
            (10. + 10.), 100. * datVal / dataTotal, effSig, fwhm)

    print "Done."
示例#17
0
def plot(path, pt_title, ecms, arrow_left, arrow_bottom, arrow_right,
         arrow_top, D_sample, D_type):
    try:
        f_incMC = TFile(path[0])
        f_sigMC = TFile(path[1])
        t_incMC = f_incMC.Get('save')
        t_sigMC = f_sigMC.Get('save')
        entries_incMC = t_incMC.GetEntries()
        entries_sigMC = t_sigMC.GetEntries()
        logging.info('inclusive MC entries :' + str(entries_incMC))
        logging.info('signal MC entries :' + str(entries_sigMC))
    except:
        logging.error('Files are invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    xbins = 100
    M_D1 = 0.
    M_D2 = 0.
    step = 0.
    if D_sample == 'Dplus' and D_type == 'D':
        M_D1 = 1.86483
        M_D2 = 1.86965
        step = (1.89555 - M_D1) / xbins
    if D_sample == 'Dplus' and D_type == 'Dst':
        M_D1 = 2.00685
        M_D2 = 1.86965
        step = (2.15 - M_D1) / xbins
    if D_sample == 'D0' and D_type == 'D':
        M_D1 = 1.86965
        M_D2 = 1.86483
        step = (1.95 - M_D1) / xbins

    h_FOM, ientry, arrow_top = cal_significance(t_incMC, t_sigMC, xbins, step,
                                                ecms, M_D1, M_D2, D_sample,
                                                D_type)
    h_FOM.Draw()

    # arrow_left = ientry*step + step
    # arrow_right = ientry*step + step
    arrow_top = 1.95
    # arrow_bottom = 0.
    arrow = TArrow(arrow_left, arrow_bottom, arrow_right, arrow_top, 0.01, '>')
    set_arrow(arrow)
    arrow.Draw()

    pt = TPaveText(0.6, 0.8, 0.85, 0.85, "BRNDC")
    set_pavetext(pt)
    pt.Draw()
    pt.AddText(pt_title)

    mass_low = 0.
    mass_up = 0.
    window = 0.
    if D_sample == 'Dplus' or D_sample == 'D0':
        mass_low = str(M_D1 - arrow_left)
        mass_up = str(M_D1 + arrow_left)
        window = str(2 * arrow_left)
    # mass_low = str(M_D1 - (ientry*step + step))
    # mass_up = str(M_D1 + (ientry*step + step))
    # window = str(2*(ientry*step + step))
    range = 'Mass window of rm_Dpi : [' + mass_low + ', ' + mass_up + '] GeV/c2' + ' with mass window width: ' + window + ' GeV/c2'
    print range

    if not os.path.exists('./txts/'):
        os.makedirs('./txts/')

    path_out = './txts/window_rm_Dpi_' + str(
        ecms) + '_' + D_sample + '_' + D_type + '.txt'
    f_out = open(path_out, 'w')
    f_out.write(range)
    f_out.close()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    mbc.Update()
    mbc.SaveAs('./figs/opt_rm_Dpi_' + str(ecms) + '_' + D_sample + '_' +
               D_type + '.pdf')

    raw_input('Enter anything to end...')
示例#18
0
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 )
line.DrawLine( 14.6, 8.0, 16, 8 )
ldot.DrawLine( 16, 8, 19, 8 )
vert = TText( 1.5, 9.75, 'File' )
vert.SetTextAlign( 21 )
vert.SetTextAngle( 90 )
vert.SetTextSize( 0.025 )
示例#19
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)
示例#20
0
    if 'x2' in g:
        if g['x2'] == "center":
            x2 = (level2.GetX1() + level2.GetX2()) / 2.0
        elif g['x2'] == "left":
            x2 = level2.GetX1()
        elif g['x2'] == "right":
            x2 = level2.GetX2()
    if x1 == x2:
        for arrow in arrows:
            if x1 == arrow.GetX1() and x1 == arrow.GetX2() and not (
                (y1 > arrow.GetY1() and y2 > arrow.GetY2()) or
                (y1 < arrow.GetY1() and y2 < arrow.GetY2())):
                x1 = x1 + 10
                x2 = x2 + 10

    arrows.append(TArrow(x1, y1, x2, y2))
    if 'energy' in g:
        gtexts.append(
            TText((x1 + x2) / 2.0 + param['GTextOffset'],
                  (level1.GetY1() + level2.GetY1()) / 2.0, str(g['energy'])))
    else:
        gtexts.append(
            TText((x1 + x2) / 2.0 + param['GTextOffset'],
                  (level1.GetY1() + level2.GetY1()) / 2.0,
                  str(level1.GetY1() - level2.GetY1())))

for arrow in arrows:
    arrow.SetLineWidth(param['ArrowWidth'])
    arrow.SetArrowSize(param['ArrowSize'])
    arrow.SetAngle(param['ArrowAngle'])
    arrow.Draw(param['ArrowOption'])
示例#21
0
                                       phiSpot + deltaSpot, maxH)
                box[iHisto].SetLineColor(kRed + 1)
                box[iHisto].SetLineWidth(3)
                box[iHisto].SetFillStyle(0)
                box[iHisto].Draw()
    elif (histoType == "1d_integralAbove"):
        maxH = histo[iHisto].GetMaximum() * 1.2
        histo[iHisto].SetMaximum(maxH)
        histo[iHisto].Draw()
        if not b_wholeHisto:
            line[iHisto] = TLine(integralAbove, 0, integralAbove, maxH)
            line[iHisto].SetLineColor(kRed + 1)
            line[iHisto].SetLineWidth(3)
            line[iHisto].Draw()
            arrow[iHisto] = TArrow(
                integralAbove, 0.2 * histo[iHisto].GetMaximum(),
                histo[iHisto].GetBinLowEdge(histo[iHisto].GetNbinsX()),
                0.2 * histo[iHisto].GetMaximum(), 0.02, ">")
            arrow[iHisto].SetLineColor(kRed + 1)
            arrow[iHisto].SetLineWidth(3)
            arrow[iHisto].Draw()

#########################################################################
# Extract the list of bins where to count.
# Scans the window to find all bins that fall in the window
# The regionBins is defined for each histogram allowing different binning
regionBins = {}
for iHisto in histoKeys:
    if b_wholeHisto:
        regionBins[iHisto] = []
        if ("2d" in histoType):
            maxBin = (histo[iHisto].GetNbinsX() +
示例#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))
示例#23
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)