示例#1
0
 def setcanvas(self, **kwargs):
     """Make canvas and pads for ratio plots."""
     square = kwargs.get('square', False)
     double = kwargs.get('ratio', False)  # include lower panel
     width = kwargs.get('width', 900 if square else 800 if double else 800)
     height = kwargs.get('height',
                         900 if square else 750 if double else 600)
     lmargin = kwargs.get('lmargin', 1.)
     rmargin = kwargs.get('rmargin', 1.)
     tmargin = kwargs.get('tmargin', 1.)
     bmargin = kwargs.get('bmargin', 1.)
     pads = kwargs.get('pads', [])  # pass list as reference
     #if not CMSStyle.lumi_13TeV:
     #  tmargin *= 0.7
     if square:
         lmargin *= 1.15
         tmargin *= 0.90
         #rmargin *= 3.6
         #CMSStyle.relPosX = 0.15
     canvas = TCanvas('canvas', 'canvas', 100, 100, width, height)
     canvas.SetFillColor(0)
     #canvas.SetFillStyle(0)
     canvas.SetBorderMode(0)
     canvas.SetFrameBorderMode(0)
     if double:
         canvas.SetMargin(0.0, 0.0, 0.0, 0.0)  # LRBT
         canvas.Divide(2)
         canvas.cd(1)
         gPad.SetPad('pad1', 'pad1', 0.0, 0.33, 1.0, 1.0)
         gPad.SetMargin(0.145 * lmargin, 0.04 * rmargin, 0.029,
                        0.075 * tmargin)
         gPad.SetFillColor(0)
         gPad.SetFillStyle(4000)  # transparant (for pdf)
         #gPad.SetFillStyle(0)
         gPad.SetBorderMode(0)
         gPad.Draw()
         canvas.cd(2)
         gPad.SetPad('pad2', 'pad2', 0.0, 0.0, 1.0, 0.33)
         gPad.SetMargin(0.145 * lmargin, 0.04 * rmargin, 0.355 * bmargin,
                        0.04)
         gPad.SetFillColor(0)  #gPad.SetFillColorAlpha(0,0.0)
         gPad.SetFillStyle(4000)  # transparant (for pdf)
         gPad.SetBorderMode(0)
         gPad.Draw()
         canvas.cd(1)
     else:
         canvas.SetMargin(0.145 * lmargin, 0.05 * rmargin, 0.145 * bmargin,
                          0.06 * tmargin)
     return canvas
示例#2
0
def PlotPosteriors(ListOfPosteriors, outputname = ""):
    RepeatIteration = False
    if (outputname != "" ):
        outputname = "_"+outputname
    c = TCanvas("Posteriors"+outputname,"Posteriors"+outputname,0,0,1600, 1600)
    c.Divide(math.ceil(pow(len(ListOfPosteriors),0.5)),math.ceil(pow(len(ListOfPosteriors),0.5)))
    legends = []
    for i in range(len(ListOfPosteriors)):
        ListOfPosteriors[i].SetMaximum(ListOfPosteriors[i].GetMaximum()*2.0)
        #ListOfPosteriors[i].Fit("gaus")
        fit = ListOfPosteriors[i].GetFunction("gaus") 
        chi2 = fit.GetChisquare()
        p1 = fit.GetParameter(1)
        #p0 = fit.GetParameter(0)
        p2 = fit.GetParameter(2)
        FitIntegral = fit.Integral(p1-10*p2,p1+10*p2) # fit integral , get mean plus minus 10 sigma
        PriorIntegral = ListOfPosteriors[i].Integral("width")
        Percentage = round((100*PriorIntegral/FitIntegral),0)
        c.cd(i+1)
        gPad.SetFrameFillColor(10)
        if (Percentage < 90):
            gPad.SetFillColor(kRed-4)
            RepeatIteration = True
        else:
            gPad.SetFillColor(8)
        leg = TLegend(0.1,0.5,0.85,0.9)
        leg.SetFillStyle(0)
        leg.AddEntry(None,"MeanHist = "+str(round(ListOfPosteriors[i].GetMean(),0))+", RMShist = "+str(round(ListOfPosteriors[i].GetRMS(),0))+", MeanFit = "+str(round(p1,0))+", #sigma_{fit} = "+str(round(p2,0)),"")
        leg.AddEntry(ListOfPosteriors[i],"Posterior ","l")
        leg.AddEntry(fit,"Fit ","l")
        leg.AddEntry(None,"#chi^{2}/NDF = "+str(round(chi2/len(ListOfPosteriors),2)),"")
        leg.AddEntry(None,"Integral Prior/Fit = "+str(round(Percentage,0))+" %","")
        leg.SetBorderSize(0)
        legends.append(leg)
        ListOfPosteriors[i].SetTitle("Posterior in bin "+str(i+1))
        gStyle.SetOptStat(0)
        ListOfPosteriors[i].Draw()
        legends[i].Draw("same")
        if (round(chi2/len(ListOfPosteriors),2)) > 20.0:
            RepeatIteration = True
        #c.Update()

    c.cd(1)
    gStyle.SetOptStat(0)
    #gPad.Modified()
    #c.Update()
    PrintCan(c,c.GetName()+"_posteriors")
    return RepeatIteration
示例#3
0
 def setPadStyle():
     gPad.SetLeftMargin(0.05)
     gPad.SetRightMargin(0.08)
     gPad.SetTopMargin(0.10)
     gPad.SetBottomMargin(0.10)
     gPad.SetLogz(plots[plot].zLog)
     gPad.SetFillColor(kWhite)
     gPad.SetBorderMode(0)
示例#4
0
文件: usefun.py 项目: pfjoker/phe_eff
def setpad(left, right, top, bottom):
    gPad.SetFillColor(10)
    gPad.SetBorderMode(0)
    gPad.SetBorderSize(0)
    gPad.SetFrameFillColor(10)
    gPad.SetFrameBorderMode(0)
    gPad.SetFrameBorderSize(0)
    gPad.SetLeftMargin(left)
    gPad.SetRightMargin(right)
    gPad.SetTopMargin(top)
    gPad.SetBottomMargin(bottom)
    gPad.SetGridx(0)
    gPad.SetGridy(0)
    gStyle.SetOptStat(0)
示例#5
0
def fitChicSpectrum(dataset, binname):
    """ Fit chic spectrum"""

    x = RooRealVar('Qvalue', 'Q', 9.7, 10.1)
    x.setBins(80)

    mean_1 = RooRealVar("mean_1", "mean ChiB1", 9.892, 9, 10, "GeV")
    sigma_1 = RooRealVar("sigma_1", "sigma ChiB1", 0.0058, 'GeV')
    a1_1 = RooRealVar('#alpha1_1', '#alpha1_1', 0.748)
    n1_1 = RooRealVar('n1_1', 'n1_1', 2.8)
    a2_1 = RooRealVar('#alpha2_1', '#alpha2_1', 1.739)
    n2_1 = RooRealVar('n2_1', 'n2_1', 3.0)

    deltam = RooRealVar('deltam', 'deltam', 0.01943)

    mean_2 = RooFormulaVar("mean_2", "@0+@1", RooArgList(mean_1, deltam))
    sigma_2 = RooRealVar("sigma_2", "sigma ChiB2", 0.0059, 'GeV')
    a1_2 = RooRealVar('#alpha1_2', '#alpha1_2', 0.738)
    n1_2 = RooRealVar('n1_2', 'n1_2', 2.8)
    a2_2 = RooRealVar('#alpha2_2', '#alpha2_2', 1.699)
    n2_2 = RooRealVar('n2_2', 'n2_2', 3.0)

    parameters = RooArgSet()

    parameters.add(RooArgSet(sigma_1, sigma_2))
    parameters = RooArgSet(a1_1, a2_1, n1_1, n2_1)
    parameters.add(RooArgSet(a1_2, a2_2, n1_2, n2_2))

    chib1_pdf = My_double_CB('chib1', 'chib1', x, mean_1, sigma_1, a1_1, n1_1,
                             a2_1, n2_1)
    chib2_pdf = My_double_CB('chib2', 'chib2', x, mean_2, sigma_2, a1_2, n1_2,
                             a2_2, n2_2)

    #background
    q01S_Start = 9.5
    alpha = RooRealVar("#alpha", "#alpha", 1.5, -1, 3.5)  #0.2 anziche' 1
    beta = RooRealVar("#beta", "#beta", -2.5, -7., 0.)
    q0 = RooRealVar("q0", "q0", q01S_Start)  #,9.5,9.7)
    delta = RooFormulaVar("delta", "TMath::Abs(@0-@1)", RooArgList(x, q0))
    b1 = RooFormulaVar("b1", "@0*(@1-@2)", RooArgList(beta, x, q0))
    signum1 = RooFormulaVar("signum1", "( TMath::Sign( -1.,@0-@1 )+1 )/2.",
                            RooArgList(x, q0))

    background = RooGenericPdf("background", "Background",
                               "signum1*pow(delta,#alpha)*exp(b1)",
                               RooArgList(signum1, delta, alpha, b1))

    parameters.add(RooArgSet(alpha, beta, q0))

    #together
    chibs = RooArgList(chib1_pdf, chib2_pdf, background)

    n_chib = RooRealVar("n_chib", "n_chib", 2075, 0, 100000)
    ratio_21 = RooRealVar("ratio_21", "ratio_21", 0.5, 0, 1)
    n_chib1 = RooFormulaVar("n_chib1", "@0/(1+@1)",
                            RooArgList(n_chib, ratio_21))
    n_chib2 = RooFormulaVar("n_chib2", "@0/(1+1/@1)",
                            RooArgList(n_chib, ratio_21))
    n_background = RooRealVar('n_background', 'n_background', 4550, 0, 50000)
    ratio_list = RooArgList(n_chib1, n_chib2, n_background)

    modelPdf = RooAddPdf('ModelPdf', 'ModelPdf', chibs, ratio_list)

    frame = x.frame(RooFit.Title('m'))
    range = x.setRange('range', 9.7, 10.1)
    result = modelPdf.fitTo(dataset, RooFit.Save(), RooFit.Range('range'))
    dataset.plotOn(frame, RooFit.MarkerSize(0.7))

    modelPdf.plotOn(frame, RooFit.LineWidth(2))

    #plotting
    canvas = TCanvas('fit', "", 1400, 700)
    canvas.Divide(1)
    canvas.cd(1)
    gPad.SetRightMargin(0.3)
    gPad.SetFillColor(10)
    modelPdf.paramOn(frame, RooFit.Layout(0.725, 0.9875, 0.9))
    frame.Draw()
    canvas.SaveAs('out-' + binname + '.png')
示例#6
0
def fitChicSpectrum(dataset, binname):
    """ Fit chic spectrum"""

    x = RooRealVar('s', 's', -2, 2)

    x.setBins(200)

    #signal model

    q_chi1 = RooRealVar('qchi1', 'q_{#chi 1}', 0.414, 0.2, 0.6)
    q_chi2 = RooRealVar('qchi2', 'q_{#chi 2}', 0.430, 0.2, 0.6)

    delta_chi10 = RooRealVar('delta_chi10', 'delta_chi10', 0.09591)
    q_chi0 = RooFormulaVar('q_chi0', '@0 - @1',
                           RooArgList(q_chi1, delta_chi10))

    alphacb_chi1 = RooRealVar('alphacb_chi1', '#alpha^{CB}_{#chi 1}', 0.6, 0,
                              2)
    alphacb_chi2 = RooRealVar('alphacb_chi2', '#alpha^{CB}_{#chi 2}', 0.4, 0,
                              2)
    sigmacb_chi1 = RooRealVar('sigmacb_chi1', '#sigma^{CB}_{#chi 1}', 0.005, 0,
                              1)
    sigmacb_chi2 = RooRealVar('sigmacb_chi2', '#sigma^{CB}_{#chi 2}', 0.005, 0,
                              1)
    n_cb = RooRealVar('ncb', 'n^{CB}', 3.0, 0., 5.)

    gamma_chi0 = RooRealVar('gamma_chi0', 'gamma_chi0', 0.0104)
    sigmacb_chi0 = RooRealVar('sigmacb_chi0', '#sigma^{CB}_{#chi 0}', 0.005)

    chi0_sig = RooVoigtian('chi0sig', 'chi0sig,', x, q_chi0, sigmacb_chi0,
                           gamma_chi0)
    chi1_sig = RooCBShape('chi1sig', 'chi1sig', x, q_chi1, sigmacb_chi1,
                          alphacb_chi1, n_cb)
    chi2_sig = RooCBShape('chi2sig', 'chi2sig', x, q_chi2, sigmacb_chi2,
                          alphacb_chi2, n_cb)

    fchi0 = RooRealVar('fchi0', 'f_{#chi 0}', 0.01, 0, 1)
    fchi1 = RooRealVar('fchi1', 'f_{#chi 1}', 0.5, 0, 1)
    fchi2 = RooFormulaVar('fchi2', '1-@0-@1', RooArgList(fchi0, fchi1))
    fbck = RooRealVar('fbck', 'f_{bck}', 0.2, 0, 1)

    sigmodel = RooAddPdf('sigm', 'sigm',
                         RooArgList(chi0_sig, chi1_sig, chi2_sig),
                         RooArgList(fchi0, fchi1, fchi2))

    #background model

    q0Start = 0.0
    a_bck = RooRealVar('a_bck', 'a_{bck}', 0.5, -5, 5)
    b_bck = RooRealVar('b_bck', 'b_{bck}', -2.5, -7., 0.)
    q0 = RooRealVar('q0', 'q0', q0Start)
    delta = RooFormulaVar('delta', 'TMath::Abs(@0-@1)', RooArgList(x, q0))
    bfun = RooFormulaVar('bfun', '@0*(@1-@2)', RooArgList(b_bck, x, q0))
    signum = RooFormulaVar('signum', '( TMath::Sign( -1.,@0-@1 )+1 )/2.',
                           RooArgList(x, q0))

    background = RooGenericPdf('background', 'Background',
                               'signum*pow(delta,a_bck)*exp(bfun)',
                               RooArgList(signum, delta, a_bck, bfun))

    modelPdf = RooAddPdf('chicmodel', 'chicmodel',
                         RooArgList(sigmodel, background), RooArgList(fbck))

    frame = x.frame(RooFit.Title('Q'))
    range = x.setRange('range', 0, 2)
    #    result = modelPdf.fitTo(dataset,RooFit.Save(),RooFit.Range('range'))
    dataset.plotOn(frame, RooFit.MarkerSize(0.7))

    modelPdf.plotOn(frame, RooFit.LineWidth(2))

    #plotting
    canvas = TCanvas('fit', "", 1400, 700)
    canvas.Divide(1)
    canvas.cd(1)
    gPad.SetRightMargin(0.3)
    gPad.SetFillColor(10)
    modelPdf.paramOn(frame, RooFit.Layout(0.725, 0.9875, 0.9))
    frame.Draw()
    canvas.SaveAs('out-' + binname + '.png')
    canvas.SaveAs('out-' + binname + '.root')
示例#7
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()
示例#8
0
def dofit(roodataset, hname):

    mass_chib = 10.5103  # from PES uncorrected mass measurement

    deltaM = 0.0105  #  MeV theoretical expectations
    ratio21 = 0.45  # same as chic2/chic1 and chib2/chib1

    # the following numbers are from an old 3P gun simulation
    # that needs to be re-done

    sigma1 = 0.003  #0.0031
    sigma2 = 0.003  #0.0035

    alpha1 = 0.95
    alpha2 = 1.12

    n = 2.5

    mass1_v = RooRealVar('mchi1', 'm_{#chi1}', mass_chib)
    deltaM_v = RooRealVar('deltaM', '#Delta_{m}', deltaM, 0.005, 0.015)
    mass2_v = RooFormulaVar('mchi2', '@0+@1', RooArgList(mass1_v, deltaM_v))
    sigma1_v = RooRealVar('sigma1', '#sigma_1', sigma1)
    sigma2_v = RooRealVar('sigma2', '#sigma_2', sigma2)

    alpha1_v = RooRealVar('alpha1', '#alpha_1', alpha1)
    alpha2_v = RooRealVar('alpha2', '#alpha_2', alpha2)

    n_v = RooRealVar('n', 'n', n)

    ratio21_v = RooRealVar('ratio21', 'r_{21}', ratio21)

    x = RooRealVar("invm3S", "#chi_{b} Data", 10.4, 10.7)

    # choose here binning of mass plot
    x.setBins(150)

    #signal pdf
    chib1 = RooCBShape('chib1', 'chib1', x, mass1_v, sigma1_v, alpha1_v, n_v)
    chib2 = RooCBShape('chib2', 'chib2', x, mass2_v, sigma2_v, alpha2_v, n_v)

    # define background
    q01S_Start = 10.4
    alpha = RooRealVar("#alpha", "#alpha", 1.5, 0.2, 3.5)
    beta = RooRealVar("#beta", "#beta", -2.5, -7., 0.)
    #q0   =      RooRealVar("q0","q0",q01S_Start,q01S_Start-0.05,q01S_Start+0.05)
    q0 = RooRealVar("q0", "q0", q01S_Start)
    delta = RooFormulaVar("delta", "TMath::Abs(@0-@1)", RooArgList(x, q0))
    b1 = RooFormulaVar("b1", "@0*(@1-@2)", RooArgList(beta, x, q0))
    signum1 = RooFormulaVar("signum1", "( TMath::Sign( -1.,@0-@1 )+1 )/2.",
                            RooArgList(x, q0))

    background = RooGenericPdf("background", "Background",
                               "signum1*pow(delta,#alpha)*exp(b1)",
                               RooArgList(signum1, delta, alpha, b1))

    n_evts_1 = RooRealVar('N_{3P_{1}}', 'N_{3P_{1}}', 50, 30, 1000)
    n_evts_2 = RooFormulaVar('N_{3P_{2}}', '@0*@1',
                             RooArgList(n_evts_1, ratio21_v))
    n_bck = RooRealVar('nbkg', 'n_{bkg}', 500, 0, 100000)

    #build final pdf
    modelPdf = RooAddPdf('ModelPdf', 'ModelPdf',
                         RooArgList(chib1, chib2, background),
                         RooArgList(n_evts_1, n_evts_2, n_bck))

    # fit
    low_cut = x.setRange("low_cut", 10.4, 10.7)
    result = modelPdf.fitTo(roodataset, RooFit.Save(), RooFit.Range("low_cut"))

    frame = x.frame(RooFit.Title("m(#chi_{b}(3P))"))
    roodataset.plotOn(frame, RooFit.MarkerSize(0.7))
    modelPdf.plotOn(frame, RooFit.LineWidth(1))

    modelPdf.plotOn(frame, RooFit.LineWidth(2))

    frame.GetXaxis().SetTitle(
        'm_{#gamma #mu^{+} #mu^{-}} - m_{#mu^{+} #mu^{-}} + m^{PDG}_{#Upsilon(3S)}  [GeV/c^{2}]'
    )
    #frame.GetYaxis().SetTitle( "Events/15.0 MeV " )
    frame.GetXaxis().SetTitleSize(0.04)
    frame.GetYaxis().SetTitleSize(0.04)
    frame.GetXaxis().SetTitleOffset(1.1)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)

    frame.SetLineWidth(1)
    frame.SetName("fit_resonance")

    chi2 = frame.chiSquare()
    chi2 = round(chi2, 2)
    leg = TLegend(0.50, 0.7, 0.60, 0.8)
    leg.AddEntry(0, '#chi^{2} =' + str(chi2), '')
    leg.SetBorderSize(0)
    leg.SetFillColor(0)
    leg.SetTextSize(0.06)

    gROOT.SetStyle("Plain")

    frame.SaveAs(str(hname) + '.root')

    #   param_set = RooArgSet(n_evts_Roo4, m_chib[1][3],alpha, beta, q0)

    canvas = TCanvas('fit', "", 1400, 700)
    canvas.Divide(1)
    canvas.cd(1)
    gPad.SetRightMargin(0.3)
    gPad.SetFillColor(10)
    #   modelPdf.paramOn(frame, RooFit.Layout(0.725,0.9875,0.9), RooFit.Parameters(param_set))
    modelPdf.paramOn(frame, RooFit.Layout(0.725, 0.9875, 0.9))
    frame.Draw()
    leg.Draw("same")
    canvas.SaveAs(str(hname) + '.png')
示例#9
0
def dofit(roodataset, hname):

    x = RooRealVar("ups_mass", "m_{#mu #mu}", 8.5, 11.0)

    # choose here binning of mass plot
    x.setBins(250)

    # model signal
    # one CB for each Y(nS) or sum of two CB for each Y(nS)

    # CB parameters
    mass1S = RooRealVar('mass1S', 'mass1S', 9.4603, 9.400, 9.500)
    mass2S = RooRealVar('mass2S', 'mass2S', 10.022, 10.000, 10.040)
    mass3S = RooRealVar('mass3S', 'mass3S', 10.3552, 10.300, 10.370)

    sigma1S_1 = RooRealVar('sigma1S_1', 'sigma1S_1', 0.080, 0.010, 0.100)
    sigma1S_2 = RooRealVar('sigma1S_2', 'sigma1S_2', 0.085, 0.010, 0.100)
    sigma2S_1 = RooRealVar('sigma2S_1', 'sigma2S_1', 0.085, 0.020, 0.100)
    sigma2S_2 = RooRealVar('sigma2S_2', 'sigma2S_2', 0.090, 0.020, 0.100)
    sigma3S_1 = RooRealVar('sigma3S_1', 'sigma3S_1', 0.090, 0.020, 0.100)
    sigma3S_2 = RooRealVar('sigma3S_2', 'sigma3S_2', 0.095, 0.020, 0.100)

    alpha = RooRealVar('alpha', 'alpha', 0.5, 0, 5)
    n = RooRealVar('n', 'n', 0.5, 0, 5)  # fix n

    #signal model
    cb1S_1 = RooCBShape('y1S_1', 'y1S_1', x, mass1S, sigma1S_1, alpha, n)
    cb1S_2 = RooCBShape('y1S_2', 'y1S_2', x, mass1S, sigma1S_2, alpha, n)
    cb2S_1 = RooCBShape('y2S_1', 'y2S_1', x, mass2S, sigma2S_1, alpha, n)
    cb2S_2 = RooCBShape('y2S_2', 'y2S_2', x, mass2S, sigma2S_2, alpha, n)
    cb3S_1 = RooCBShape('y3S_1', 'y3S_1', x, mass3S, sigma3S_1, alpha, n)
    cb3S_2 = RooCBShape('y3S_2', 'y3S_2', x, mass3S, sigma3S_2, alpha, n)

    cb1frac1S = RooRealVar("cb1frac1S", "cc", 0.1, 0., 1.)
    cb1frac2S = RooRealVar("cb1frac2S", "cc", 0.1, 0., 1.)
    cb1frac3S = RooRealVar("cb1frac3S", "cc", 0.1, 0., 1.)

    # sum of two CB
    sig1S = RooAddPdf("sig1S", "Signal1S", RooArgList(cb1S_1, cb1S_2),
                      RooArgList(cb1frac1S))
    sig2S = RooAddPdf("sig2S", "Signal2S", RooArgList(cb2S_1, cb2S_2),
                      RooArgList(cb1frac2S))
    sig3S = RooAddPdf("sig3S", "Signal3S", RooArgList(cb3S_1, cb3S_2),
                      RooArgList(cb1frac3S))

    #background model
    c1 = RooRealVar('c1', 'c1', 200, 0, 3000000)
    c2 = RooRealVar('c2', 'c2', -1, -50, 50)
    background = RooPolynomial('bkg', 'bkg', x, RooArgList(c1, c2))

    # complete model

    n1S = RooRealVar('n1s', '', 100000, 0, 10000000)
    n2S = RooRealVar('n2s', '', 100000, 0, 10000000)
    n3S = RooRealVar('n3s', '', 100000, 0, 10000000)
    nbck = RooRealVar('nbck', '', 100000, 0, 10000000)

    # sum of two CB for each Y(nS)
    modelPdf = RooAddPdf('model', 'model',
                         RooArgList(sig1S, sig2S, sig3S, background),
                         RooArgList(n1S, n2S, n3S, nbck))

    # or one CB for each Y(nS)
    #modelPdf = RooAddPdf('model','model',RooArgList(cb1S_1,cb2S_1,cb3S_1,background),RooArgList(n1S,n2S,n3S,nbck))

    rcut = x.setRange('rcut', 8.5, 11.0)
    result = modelPdf.fitTo(roodataset, RooFit.Save(), RooFit.Range('rcut'))

    frame = x.frame(RooFit.Title('mass'))
    roodataset.plotOn(frame, RooFit.MarkerSize(0.7))

    modelPdf.plotOn(frame, RooFit.LineWidth(2))

    #plotting
    canvas = TCanvas('fit', "", 1400, 700)
    canvas.Divide(1)
    canvas.cd(1)
    gPad.SetRightMargin(0.3)
    gPad.SetFillColor(10)
    modelPdf.paramOn(frame, RooFit.Layout(0.725, 0.9875, 0.9))
    frame.Draw()
    canvas.SaveAs(str(hname) + '.png')
示例#10
0
def smear(mu, sigma0, smearfactor, N=100000, lcut=None, ucut=None, nbins=80):
    print ">>> smearing for N(%s,%s) with a factor of %s" % (mu, sigma0,
                                                             smearfactor)

    # HISTS
    xmin, xmax = mu - sigma0 * 5, mu + sigma0 * 4
    sigma1 = sigma0 * (1 + smearfactor)
    histname0 = "unsmeared"
    histname1 = "smeared"
    histtitle0 = "unsmeared, #sigma_{0} = %s" % (sigma0)
    histtitle1 = "smeared, #sigma_{new} = %s" % (sigma1)
    hist0 = TH1F(histname0, histtitle0, nbins, xmin, xmax)
    hist1 = TH1F(histname1, histtitle1, nbins, xmin, xmax)

    # FIT FUNCTIONS
    xminf = xmin if lcut == None else lcut
    xmaxf = xmax if ucut == None else ucut
    gaus0 = TF1("gaus0", "gaus", xminf, xmaxf)
    gaus1 = TF1("gaus1", "gaus", xminf, xmaxf)
    gaus0.SetTitle("%s fit" % histname0)
    gaus1.SetTitle("%s fit" % histname1)
    gaus0.SetParameters(N, mu, sigma0)
    gaus1.SetParameters(N, mu, sigma1)
    #gaus0.SetParLimits(2,sigma0*0.9,sigma0*1.1)
    #gaus1.SetParLimits(2,sigma1*0.9,sigma1*1.1)
    hists = [(hist0, gaus0), (hist1, gaus1)]

    # SMEAR & FILL
    #sigma1 = smearfactor
    #sigma1 = (smearfactor**2)/2.
    #sigma1 = sqrt(2.*(smearfactor))
    #sigma1 = sqrt(-2.*log(smearfactor))
    #sigma1 = 1./(2*smearfactor**2)
    sigma2 = sqrt(sigma1**2 - sigma0**2)
    print ">>>   sigma0 = %.3f, sigma1 = %.3f, sigma2 = %.3f" % (
        sigma0, sigma1, sigma2)
    print ">>>   generating %s events..." % (N)
    for i in xrange(N):
        xval0 = gRandom.Gaus(mu, sigma0)
        if lcut != None and xval0 < lcut: continue
        if ucut != None and xval0 > ucut: continue
        #rand  = gRandom.Gaus(1,smearfactor)
        #xval1 = xval0 * rand
        #rand  = gRandom.Gaus(0,1+smearfactor)
        #xval1 = xval0 + rand
        rand = gRandom.Gaus(0, 1)
        xval1 = xval0 + sigma2 * rand
        hist0.Fill(xval0)
        if lcut != None and xval1 < lcut: continue
        if ucut != None and xval1 > ucut: continue
        hist1.Fill(xval1)

    # PLOT SETTINGS
    xtitle = "x variable"
    ytitle = "events"
    title = "Gauss(%s,%s)" % (mu, "#sigma")
    canvasname = "smear_%.1f-%.1f_by_%.2f" % (mu, sigma0, smearfactor)
    if lcut != None: canvasname += "_gt%.1f" % (lcut)
    if ucut != None: canvasname += "_lt%.1f" % (ucut)
    canvasname = canvasname.replace('.', 'p')
    ymin, ymax = 0, 1.14 * max(hist0.GetMaximum(), hist1.GetMaximum())
    rmin, rmax = 0.60, 1.40
    lmargin, rmargin = 0.14, 0.04

    # CANVAS
    print ">>> plotting..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 800)
    canvas.Divide(2)

    # MAIN plot
    canvas.cd(1)
    gPad.SetPad("pad1", "pad1", 0, 0.33, 1, 1, 0, -1, 0)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetFrameFillStyle(0)
    gPad.SetFrameBorderMode(0)
    gPad.SetTopMargin(0.06)
    gPad.SetBottomMargin(0.02)
    gPad.SetLeftMargin(lmargin)
    gPad.SetRightMargin(rmargin)
    gPad.SetGrid()
    gPad.cd()

    textsize = 0.050
    x1, width = 0.18, 0.25
    y1, height = 0.89, textsize * 1.08 * 5
    legend = TLegend(x1, y1, x1 + width, y1 - height)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetTextFont(62)
    legend.SetHeader(title)
    legend.SetTextFont(42)

    # FRAME
    frame = gPad.DrawFrame(xmin, ymin, xmax, ymax)
    frame.GetYaxis().SetTitleSize(0.070)
    frame.GetXaxis().SetTitleSize(0.070)
    frame.GetXaxis().SetLabelSize(0.000)
    frame.GetYaxis().SetLabelSize(0.060)
    frame.GetXaxis().SetTitleOffset(1.00)
    frame.GetYaxis().SetTitleOffset(1.06)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetXaxis().SetTitle(xtitle)
    frame.GetYaxis().SetTitle(ytitle)

    # DRAW & FIT
    print ">>>   fitting..."
    fits = []
    for i, (hist, gaus) in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.SetLineStyle(1)
        gaus.SetLineColor(color + 1)
        gaus.SetLineWidth(2)
        gaus.SetLineStyle(2)
        hist.Fit(gaus.GetName(), '0', '', xminf, xmaxf)
        hist.Draw('SAME')
        gaus.Draw('SAME')
        gtitle = "#sigma_{fit} = %.3f" % (gaus.GetParameter(2)
                                          )  #gaus.GetTitle()
        legend.AddEntry(hist, hist.GetTitle(), 'l')
        legend.AddEntry(gaus, gtitle, 'l')
    print ">>>   real unsmeared sigma:    %5.3f" % (sigma0)
    print ">>>   fitted unsmeared sigma:  %5.3f" % (gaus0.GetParameter(2))
    print ">>>   real smear factor:       %5.3f" % (smearfactor)
    print ">>>   fitted smeared sigma:    %5.3f" % (gaus1.GetParameter(2))

    legend.Draw()
    frame.Draw('SAMEAXIS')
    gPad.Modified()

    # RATIO plot
    canvas.cd(2)
    gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.32, 0, -1, 0)
    gPad.SetTopMargin(0.04)
    gPad.SetBottomMargin(0.29)
    gPad.SetLeftMargin(lmargin)
    gPad.SetRightMargin(rmargin)

    # RATIO FRAME
    rframe = gPad.DrawFrame(xmin, rmin, xmax, rmax)
    rframe.GetYaxis().CenterTitle()
    rframe.GetXaxis().SetTitleSize(0.144)
    rframe.GetYaxis().SetTitleSize(0.140)
    rframe.GetXaxis().SetLabelSize(0.130)
    rframe.GetYaxis().SetLabelSize(0.120)
    rframe.GetXaxis().SetLabelOffset(0.012)
    rframe.GetXaxis().SetTitleOffset(0.85)
    rframe.GetYaxis().SetTitleOffset(0.53)
    rframe.GetXaxis().SetNdivisions(508)
    rframe.GetYaxis().CenterTitle(True)
    rframe.GetYaxis().SetTitle("ratio")
    rframe.GetXaxis().SetTitle(xtitle)
    rframe.GetYaxis().SetNdivisions(5)

    # RATIO
    ratios = []
    for i, (hist, gaus) in enumerate(hists):
        #if i==0: continue
        #ratio = hist.Clone(hist.GetName()+"_ratio")
        #ratio.Divide(hist0)
        ratio = divideHists(hist, hist0, name=hist.GetName() + "_ratio")
        ratio.Draw('HISTSAME')
        ratios.append(ratio)
        #ratiof = createTH1FromTF1(gaus,nbins,xmin,xmax)
        #ratiof.Divide(hist0)
        ratiof = divideTF1ByTH1(gaus, hist0, name=gaus.GetName() + "_ratio")
        ratiof.Draw('HISTSAME')
        ratios.append(ratiof)
        print ratiof
    #line = TLine(xmin,1.,xmax,1.)
    #line.SetLineColor(hist0.GetLineColor())
    #line.SetLineWidth(hist0.GetLineWidth())
    #line.SetLineStyle(1)
    #line.Draw('SAME')

    gPad.SetGrid()
    gPad.Modified()
    rframe.Draw('sameaxis')

    canvas.SaveAs(canvasname + ".png")
    canvas.SaveAs(canvasname + ".pdf")
    canvas.Close()
    print ">>> "