Example #1
0
def rf501_simultaneouspdf():
    # C r e a t e   m o d e l   f o r   p h y s i c s   s a m p l e
    # -------------------------------------------------------------

    # Create observables
    x = RooRealVar( "x", "x", -8, 8 ) 

    # Construct signal pdf
    mean = RooRealVar( "mean", "mean", 0, -8, 8 ) 
    sigma = RooRealVar( "sigma", "sigma", 0.3, 0.1, 10 ) 
    gx = RooGaussian( "gx", "gx", x, mean, sigma ) 

    # Construct background pdf
    a0 = RooRealVar( "a0", "a0", -0.1, -1, 1 ) 
    a1 = RooRealVar( "a1", "a1", 0.004, -1, 1 ) 
    px = RooChebychev( "px", "px", x, RooArgList( a0, a1 ) ) 

    # Construct composite pdf
    f = RooRealVar( "f", "f", 0.2, 0., 1. ) 
    model = RooAddPdf( "model", "model", RooArgList( gx, px ), RooArgList( f ) ) 



    # C r e a t e   m o d e l   f o r   c o n t r o l   s a m p l e
    # --------------------------------------------------------------

    # Construct signal pdf. 
    # NOTE that sigma is shared with the signal sample model
    mean_ctl = RooRealVar( "mean_ctl", "mean_ctl", -3, -8, 8 ) 
    gx_ctl = RooGaussian( "gx_ctl", "gx_ctl", x, mean_ctl, sigma ) 

    # Construct the background pdf
    a0_ctl = RooRealVar( "a0_ctl", "a0_ctl", -0.1, -1, 1 ) 
    a1_ctl = RooRealVar( "a1_ctl", "a1_ctl", 0.5, -0.1, 1 ) 
    px_ctl = RooChebychev( "px_ctl", "px_ctl", x, RooArgList( a0_ctl, a1_ctl ) ) 

    # Construct the composite model
    f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 1. ) 
    model_ctl = RooAddPdf( "model_ctl", "model_ctl", RooArgList( gx_ctl, px_ctl ),
                           RooArgList( f_ctl ) ) 
    


    # G e n e r a t e   e v e n t s   f o r   b o t h   s a m p l e s 
    # ---------------------------------------------------------------

    # Generate 1000 events in x and y from model
    data = model.generate( RooArgSet( x ), 100 ) 
    data_ctl = model_ctl.generate( RooArgSet( x ), 2000 ) 



    # C r e a t e   i n d e x   c a t e g o r y   a n d   j o i n   s a m p l e s 
    # ---------------------------------------------------------------------------
    # Define category to distinguish physics and control samples events
    sample = RooCategory( "sample", "sample" ) 
    sample.defineType( "physics" ) 
    sample.defineType( "control" ) 

    # Construct combined dataset in (x,sample)
    combData = RooDataSet( "combData", "combined data", RooArgSet(x), RooFit.Index( sample ),
                          RooFit.Import( "physics", data ),
                          RooFit.Import( "control", data_ctl ) ) 



    # C o n s t r u c t   a   s i m u l t a n e o u s   p d f   i n   ( x , s a m p l e )
    # -----------------------------------------------------------------------------------

    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous( "simPdf", "simultaneous pdf", sample ) 

    # Associate model with the physics state and model_ctl with the control state
    simPdf.addPdf( model, "physics" ) 
    simPdf.addPdf( model_ctl, "control" ) 



    # P e r f o r m   a   s i m u l t a n e o u s   f i t
    # ---------------------------------------------------

    # Perform simultaneous fit of model to data and model_ctl to data_ctl
    simPdf.fitTo( combData ) 



    # P l o t   m o d e l   s l i c e s   o n   d a t a    s l i c e s 
    # ----------------------------------------------------------------

    # Make a frame for the physics sample
    frame1 = x.frame( RooFit.Bins( 30 ), RooFit.Title( "Physics sample" ) ) 

    # Plot all data tagged as physics sample
    combData.plotOn( frame1, RooFit.Cut( "sample==sample::physics" ) ) 

    # Plot "physics" slice of simultaneous pdf. 
    # NBL You _must_ project the sample index category with data using ProjWData 
    # as a RooSimultaneous makes no prediction on the shape in the index category 
    # and can thus not be integrated
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.ProjWData( RooArgSet(sample), combData ) ) 
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.Components( "px" ),
                   RooFit.ProjWData( RooArgSet(sample), combData ),
                   RooFit.LineStyle( kDashed ) ) 

    # The same plot for the control sample slice
    frame2 = x.frame( RooFit.Bins( 30 ), RooFit.Title( "Control sample" ) ) 
    combData.plotOn( frame2, RooFit.Cut( "sample==sample::control" ) ) 
    simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ),
                  RooFit.ProjWData( RooArgSet(sample), combData ) ) 
    simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ),
                  RooFit.Components( "px_ctl" ),
                  RooFit.ProjWData( RooArgSet(sample), combData ),
                  RooFit.LineStyle( kDashed ) ) 



    c = TCanvas( "rf501_simultaneouspdf", "rf403_simultaneouspdf", 800, 400 ) 
    c.Divide( 2 ) 
    c.cd( 1 )
    gPad.SetLeftMargin( 0.15 )
    frame1.GetYaxis().SetTitleOffset( 1.4 )
    frame1.Draw() 
    c.cd( 2 )
    gPad.SetLeftMargin( 0.15 )
    frame2.GetYaxis().SetTitleOffset( 1.4 )
    frame2.Draw() 
    raw_input()
fitregion_1S = x.setRange('fitregion_1S',10.35,10.8)
fitregion_2S = x.setRange('fitregion_2S',10.35,10.8)
fitregion_3S = x.setRange('fitregion_3S',10.35,10.8)

#simPdf.fitTo(combData,RooFit.Save(), RooFit.Range('fitregion'),RooFit.SplitRange())


simPdf.fitTo(combData,RooFit.Save())

#plotting
frame1 = x.frame()
combData.plotOn(frame1,
                RooFit.Cut("sample==sample::b1"),
                RooFit.MarkerSize(0.7))
simPdf.plotOn(frame1, RooFit.Slice(sample,'b1'),
              RooFit.ProjWData(RooArgSet(sample),combData),
              RooFit.LineWidth(2))

c1 = TCanvas('c1','c1')
frame1.Draw()

frame2 = x.frame()
combData.plotOn(frame2,
                RooFit.Cut("sample==sample::b2"),
                RooFit.MarkerSize(0.7))
simPdf.plotOn(frame2, RooFit.Slice(sample,'b2'),
              RooFit.ProjWData(RooArgSet(sample),combData),
              RooFit.LineWidth(2))

dataset2S.plotOn(frame2)
Example #3
0
File: fits.py Project: xshi/dhad
def mbc_gau_che(evtfile, mc, setMres, setGamma, setR, sp1, sp2, sp3, fa,
                fb, setmd, setp, setxi, setN1, setN2, setNbkgd1, setNbkgd2,
                title1, title2, epsfile, txtfile, ymin=0.5,
                cuts=None, err_type='SYMM', test=False):
    
    from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet,
                      RooFit, RooGaussian, RooArgList, RooAddPdf, RooSimultaneous,
                      RooArgusBG, RooFormulaVar, RooChebychev, RooAbsData,
                      RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta,
                      TPaveText)
    set_root_style(stat=1, grid=0)

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    ebeam = RooRealVar('ebeam','Ebeam', 1.8815, 1.892, 'GeV')

    dflav = RooCategory('dflav','D0 flavor')
    dflav.defineType('dflav',1)
    dflav.defineType('dbarflav',-1)

    if cuts != None:
        if 'kkmass' in cuts:
            kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90, 'GeV')
            ras = RooArgSet(mbc, ebeam, kkmass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        elif 'kpimass' in cuts:
            kpimass = RooRealVar('kpimass', 'Kpi invariant mass', 0.6, 1.4, 'GeV')
            ras = RooArgSet(mbc, ebeam, kpimass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        else:
            raise NameError(cuts)

        sys.stdout.write('Using cuts: %s...' %cuts)
        dataset = dataset.reduce(cuts)
        sys.stdout.write(' selected %s events.\n' % dataset.numEntries())
    else:
        ras = RooArgSet(mbc, ebeam, dflav)
        dataset = RooDataSet.read(evtfile, ras)

    #sigma = RooRealVar('sigma', 'D width', 0.0001, 0.005, 'GeV')
    sigma = RooRealVar('sigma', 'D width', 0.00468, 'GeV')
    mbc_dp = RooRealVar('mbc_dp', 'D+ Mass', 1.86962, 'GeV')
    sigpdf = RooGaussian('gauss_dp', 'D+ gaussian', mbc, mbc_dp, sigma)
    
    #arg_cutoff = RooRealVar('arg_cutoff', 'Argus cutoff', 1.88, 1.89, 'GeV')
    #arg_slope = RooRealVar('arg_slope', 'Argus slope', -10, -100, -1)
    #bkgpdf = RooArgusBG('argus', 'Argus BG', mbc, arg_cutoff, arg_slope)

    con0 = RooRealVar('c0', 'constant', -1, 1)
    con1 = RooRealVar('c1', 'linear', -10, 10)
    con2 = RooRealVar('c2', 'quadratic', 1)

    bkgpdf = RooChebychev('bkgpdf', 'Background',
                          mbc, RooArgList(con1, con2))

    yld = RooRealVar('yld', 'D yield', 100, 0, 2000)
    bkg = RooRealVar('bkg', 'Background', 100, 0, 1000)

    sumpdf = RooAddPdf('sumpdf', 'Sum pdf', RooArgList(sigpdf, bkgpdf),
                       RooArgList(yld, bkg))

    yldbar = RooRealVar('yldbar', 'Dbar yield', 100, 0, 2000)
    bkgbar = RooRealVar('bkgbar', 'Background', 100, 0, 1000)

    sumpdfbar = RooAddPdf('sumpdfbar', 'Sum pdf', RooArgList(sigpdf, bkgpdf),
                          RooArgList(yldbar, bkgbar))

    totalpdf = RooSimultaneous('rs', 'Simultaneous PDF', dflav)
    totalpdf.addPdf(sumpdf, 'dflav')
    totalpdf.addPdf(sumpdfbar, 'dbarflav')

    MINUIT = 'ermh4'

    if err_type == 'ASYM':
        MINUIT = 'erh4'
        
    if test:
        sys.stdout.write('Will save epsfile as: %s \n' %epsfile)
        sys.stdout.write('Will save txtfile as: %s \n' %txtfile)
        return
    
    if dataset.numEntries() == 0:
        yld.setVal(0)
        yldbar.setVal(0)
    else:
        # Start Fitting
        fitres = totalpdf.fitTo(dataset, MINUIT)
        fitres.Print('v')

    # Save plots
    canvas = TCanvas('canvas','mbc', 400, 400);
    xframe=mbc.frame(50)
    ProjWData = RooFit.ProjWData(dataset)
    RooAbsData.plotOn(dataset, xframe)
    totalpdf.plotOn(xframe, ProjWData)
    totalpdf.paramOn(xframe)
    xframe.Draw()
    canvas.Print(epsfile)

    # Save fitting parameters
    pars = [bkg, bkgbar, con1, yld, yldbar]
    save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
Example #4
0
File: fits.py Project: xshi/dhad
def mbc_dline_che(evtfile, mc, setMres, setGamma, setR, sp1, sp2, sp3, fa,
                  fb, setmd, setp, setxi, setN1, setN2, setNbkgd1, setNbkgd2,
                  title1, title2, epsfile, txtfile, ymin=0.5,
                  cuts=None, err_type='SYMM', test=False):
    
    from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet,
                      RooFit, RooGaussian, RooArgList, RooAddPdf, RooSimultaneous,
                      RooArgusBG, RooFormulaVar, RooChebychev, RooAbsData,
                      RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta,
                      TPaveText, RooDLineShape)
    set_root_style(stat=1, grid=0)

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    ebeam = RooRealVar('ebeam','Ebeam', 1.8815, 1.892, 'GeV')

    dflav = RooCategory('dflav','D0 flavor')
    dflav.defineType('dflav',1)
    dflav.defineType('dbarflav',-1)

    if cuts != None:
        if 'kkmass' in cuts:
            kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90, 'GeV')
            ras = RooArgSet(mbc, ebeam, kkmass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        else:
            raise NameError(cuts)

        sys.stdout.write('Using cuts: %s...' %cuts)
        dataset = dataset.reduce(cuts)
        sys.stdout.write(' selected %s events.\n' % dataset.numEntries())
    else:
        ras = RooArgSet(mbc, ebeam, dflav)
        dataset = RooDataSet.read(evtfile, ras)

    res = RooRealVar("datares", "datares", mc)
    mres = RooRealVar("mres","mres", setMres)
    gamma = RooRealVar('gamma', 'gamma', setGamma)

    r = RooRealVar('r', 'r', setR)
    sigmaE = RooRealVar("sigmaE","sigmaE", 0.0021)

    sigmap1 = RooRealVar("sigmap1","sigmap1", sp1, 0.002, 0.040)

    scalep2 = RooRealVar("scalep2","scalep2",2.00,1.500,5.500)
    scalep3 = RooRealVar("scalep3","scalep3",5.00,3.00,10.000)
   
    scalep2.setVal(sp2)
    scalep2.setConstant(1)
    scalep3.setVal(sp3)
    scalep3.setConstant(1)

    as12 = RooArgList(sigmap1,scalep2)
    sigmap2 = RooFormulaVar("sigmap2","sigma2","sigmap1*scalep2", as12)

    as123 = RooArgList(sigmap1,scalep2,scalep3)
    sigmap3 = RooFormulaVar("sigmap3","sigma3","sigmap1*scalep2*scalep3",
                            as123)
    
    md = RooRealVar("md","md", setmd,1.863,1.875)

    f2 = RooRealVar("f2","f2", fa)
    f3 = RooRealVar("f3","f3", fb)
    al23 = RooArgList(f2,f3)
    f1 = RooFormulaVar("f1","f1","1.0-f2-f3", al23)

    # Construct signal shape

    fcn1_1 = RooDLineShape("DLineshape1_1","DLineShape1_1",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap1,md,res)
    fcn1_2 = RooDLineShape("DLineshape1_2","DLineShape1_2",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap2,md,res)
    fcn1_3 = RooDLineShape("DLineshape1_3","DLineShape1_3",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap3,md,res)

    fcn2_1 = RooDLineShape("DLineshape2_1","DLineShape2_1",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap1,md,res)
    fcn2_2 = RooDLineShape("DLineshape2_2","DLineShape2_2",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap2,md,res)
    fcn2_3 = RooDLineShape("DLineshape2_3","DLineShape2_3",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap3,md,res)


    alf1_123 = RooArgList(fcn1_1,fcn1_2,fcn1_3)
    af12 = RooArgList(f1,f2) 
    sigpdf = RooAddPdf("signal1_3","signal1_3", alf1_123, af12)

    alf2_123 = RooArgList(fcn2_1,fcn2_2,fcn2_3)
    
    sigbarpdf = RooAddPdf("signal2_3","signal2_3", alf2_123, af12)

    con0 = RooRealVar('c0', 'constant', -1, 1)
    con1 = RooRealVar('c1', 'linear', -10, 10)
    con2 = RooRealVar('c2', 'quadratic', 1)

    bkgpdf = RooChebychev('bkgpdf', 'Background', mbc, RooArgList(con1, con2))
    
    bkgbarpdf = RooChebychev('bkgbarpdf', 'Background',
                             mbc, RooArgList(con1, con2))

    yld = RooRealVar('yld', 'D yield', 100, 0, 2000)
    bkg = RooRealVar('bkg', 'Background', 100, 0, 1000)

    sumpdf = RooAddPdf('sumpdf', 'Sum pdf', RooArgList(sigpdf, bkgpdf),
                       RooArgList(yld, bkg))
    yldbar = RooRealVar('yldbar', 'Dbar yield', 100, 0, 2000)
    bkgbar = RooRealVar('bkgbar', 'Background', 100, 0, 1000)

    sumpdfbar = RooAddPdf('sumpdfbar', 'Sum pdf', RooArgList(sigbarpdf, bkgbarpdf),
                          RooArgList(yldbar, bkgbar))

    totalpdf = RooSimultaneous('rs', 'Simultaneous PDF', dflav)
    totalpdf.addPdf(sumpdf, 'dflav')
    totalpdf.addPdf(sumpdfbar, 'dbarflav')

    MINUIT = 'ermh4'

    if err_type == 'ASYM':
        MINUIT = 'erh4'
        
    if test:
        sys.stdout.write('Will save epsfile as: %s \n' %epsfile)
        sys.stdout.write('Will save txtfile as: %s \n' %txtfile)
        return
    
    if dataset.numEntries() == 0:
        yld.setVal(0)
        yldbar.setVal(0)
    else:
        # Start Fitting
        fitres = totalpdf.fitTo(dataset, MINUIT)
        fitres.Print('v')

    # Save plots
    canvas = TCanvas('canvas','mbc', 400, 400);
    xframe=mbc.frame(50)
    ProjWData = RooFit.ProjWData(dataset)
    RooAbsData.plotOn(dataset, xframe)
    totalpdf.plotOn(xframe, ProjWData)
    totalpdf.paramOn(xframe)
    xframe.Draw()
    canvas.Print(epsfile)

    # Save fitting parameters
    pars = [bkg, bkgbar, con1, md, sigmap1, yld, yldbar]
    save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
Example #5
0
def mbc_dline_che(evtfile,
                  mc,
                  setMres,
                  setGamma,
                  setR,
                  sp1,
                  sp2,
                  sp3,
                  fa,
                  fb,
                  setmd,
                  setp,
                  setxi,
                  setN1,
                  setN2,
                  setNbkgd1,
                  setNbkgd2,
                  title1,
                  title2,
                  epsfile,
                  txtfile,
                  ymin=0.5,
                  cuts=None,
                  err_type='SYMM',
                  test=False):

    from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet,
                      RooFit, RooGaussian, RooArgList, RooAddPdf,
                      RooSimultaneous, RooArgusBG, RooFormulaVar, RooChebychev,
                      RooAbsData, RooDataHist, TCanvas, kRed, kBlue, kGreen,
                      kMagenta, TPaveText, RooDLineShape)
    set_root_style(stat=1, grid=0)

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV')

    dflav = RooCategory('dflav', 'D0 flavor')
    dflav.defineType('dflav', 1)
    dflav.defineType('dbarflav', -1)

    if cuts != None:
        if 'kkmass' in cuts:
            kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90,
                                'GeV')
            ras = RooArgSet(mbc, ebeam, kkmass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        else:
            raise NameError(cuts)

        sys.stdout.write('Using cuts: %s...' % cuts)
        dataset = dataset.reduce(cuts)
        sys.stdout.write(' selected %s events.\n' % dataset.numEntries())
    else:
        ras = RooArgSet(mbc, ebeam, dflav)
        dataset = RooDataSet.read(evtfile, ras)

    res = RooRealVar("datares", "datares", mc)
    mres = RooRealVar("mres", "mres", setMres)
    gamma = RooRealVar('gamma', 'gamma', setGamma)

    r = RooRealVar('r', 'r', setR)
    sigmaE = RooRealVar("sigmaE", "sigmaE", 0.0021)

    sigmap1 = RooRealVar("sigmap1", "sigmap1", sp1, 0.002, 0.040)

    scalep2 = RooRealVar("scalep2", "scalep2", 2.00, 1.500, 5.500)
    scalep3 = RooRealVar("scalep3", "scalep3", 5.00, 3.00, 10.000)

    scalep2.setVal(sp2)
    scalep2.setConstant(1)
    scalep3.setVal(sp3)
    scalep3.setConstant(1)

    as12 = RooArgList(sigmap1, scalep2)
    sigmap2 = RooFormulaVar("sigmap2", "sigma2", "sigmap1*scalep2", as12)

    as123 = RooArgList(sigmap1, scalep2, scalep3)
    sigmap3 = RooFormulaVar("sigmap3", "sigma3", "sigmap1*scalep2*scalep3",
                            as123)

    md = RooRealVar("md", "md", setmd, 1.863, 1.875)

    f2 = RooRealVar("f2", "f2", fa)
    f3 = RooRealVar("f3", "f3", fb)
    al23 = RooArgList(f2, f3)
    f1 = RooFormulaVar("f1", "f1", "1.0-f2-f3", al23)

    # Construct signal shape

    fcn1_1 = RooDLineShape("DLineshape1_1", "DLineShape1_1", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap1, md, res)
    fcn1_2 = RooDLineShape("DLineshape1_2", "DLineShape1_2", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap2, md, res)
    fcn1_3 = RooDLineShape("DLineshape1_3", "DLineShape1_3", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap3, md, res)

    fcn2_1 = RooDLineShape("DLineshape2_1", "DLineShape2_1", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap1, md, res)
    fcn2_2 = RooDLineShape("DLineshape2_2", "DLineShape2_2", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap2, md, res)
    fcn2_3 = RooDLineShape("DLineshape2_3", "DLineShape2_3", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap3, md, res)

    alf1_123 = RooArgList(fcn1_1, fcn1_2, fcn1_3)
    af12 = RooArgList(f1, f2)
    sigpdf = RooAddPdf("signal1_3", "signal1_3", alf1_123, af12)

    alf2_123 = RooArgList(fcn2_1, fcn2_2, fcn2_3)

    sigbarpdf = RooAddPdf("signal2_3", "signal2_3", alf2_123, af12)

    con0 = RooRealVar('c0', 'constant', -1, 1)
    con1 = RooRealVar('c1', 'linear', -10, 10)
    con2 = RooRealVar('c2', 'quadratic', 1)

    bkgpdf = RooChebychev('bkgpdf', 'Background', mbc, RooArgList(con1, con2))

    bkgbarpdf = RooChebychev('bkgbarpdf', 'Background', mbc,
                             RooArgList(con1, con2))

    yld = RooRealVar('yld', 'D yield', 100, 0, 2000)
    bkg = RooRealVar('bkg', 'Background', 100, 0, 1000)

    sumpdf = RooAddPdf('sumpdf', 'Sum pdf', RooArgList(sigpdf, bkgpdf),
                       RooArgList(yld, bkg))
    yldbar = RooRealVar('yldbar', 'Dbar yield', 100, 0, 2000)
    bkgbar = RooRealVar('bkgbar', 'Background', 100, 0, 1000)

    sumpdfbar = RooAddPdf('sumpdfbar', 'Sum pdf',
                          RooArgList(sigbarpdf, bkgbarpdf),
                          RooArgList(yldbar, bkgbar))

    totalpdf = RooSimultaneous('rs', 'Simultaneous PDF', dflav)
    totalpdf.addPdf(sumpdf, 'dflav')
    totalpdf.addPdf(sumpdfbar, 'dbarflav')

    MINUIT = 'ermh4'

    if err_type == 'ASYM':
        MINUIT = 'erh4'

    if test:
        sys.stdout.write('Will save epsfile as: %s \n' % epsfile)
        sys.stdout.write('Will save txtfile as: %s \n' % txtfile)
        return

    if dataset.numEntries() == 0:
        yld.setVal(0)
        yldbar.setVal(0)
    else:
        # Start Fitting
        fitres = totalpdf.fitTo(dataset, MINUIT)
        fitres.Print('v')

    # Save plots
    canvas = TCanvas('canvas', 'mbc', 400, 400)
    xframe = mbc.frame(50)
    ProjWData = RooFit.ProjWData(dataset)
    RooAbsData.plotOn(dataset, xframe)
    totalpdf.plotOn(xframe, ProjWData)
    totalpdf.paramOn(xframe)
    xframe.Draw()
    canvas.Print(epsfile)

    # Save fitting parameters
    pars = [bkg, bkgbar, con1, md, sigmap1, yld, yldbar]
    save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
Example #6
0
File: fits.py Project: xshi/dhad
def mbc_single_3s(evtfile, mc, setMres, setGamma, setR, sp1, sp2, sp3, fa,
                  fb, setmd, setp, setxi, setN1, setN2, setNbkgd1, setNbkgd2,
                  title1, title2, epsfile, txtfile, ymin=0.5,
                  cuts=None, err_type='SYMM', test=False):

    from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet,
                      RooFit, RooGaussian, RooArgList, RooAddPdf, RooSimultaneous,
                      RooArgusBG, RooFormulaVar, RooDLineShape, RooAbsData,
                      RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta,
                      TPaveText)
    set_root_style(stat=1, grid=0)
    
    # // sp1 = sigma of signal
    # // sp2 = ratio of sigmas betwwen sigma2 sigma 1
    # // sp3 = ratio of sigmas betwwen sigma3 sigma 2
    # // fa, fb, - fractions
    # // xi_side - slope of argus
    # // p_side - power of argus

    # mc = 1  Monte Carlo Model: EvtGenModels/Class/EvtVPHOtoVISR.cc
    # mc = 3  Data Model: with BES 2007 paper (BES2006 lineshape hepex/0612056) 

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV')

    dflav = RooCategory('dflav','D flavor')
    dflav.defineType('dflav', 1)
    dflav.defineType('dbarflav', -1)

    if cuts != None:
        if 'kkmass' in cuts:
            kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90, 'GeV')
            ras = RooArgSet(mbc, ebeam, kkmass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        elif 'kpimass' in cuts:
            kpimass = RooRealVar('kpimass', 'Kpi invariant mass', 0.6, 1.4, 'GeV')
            ras = RooArgSet(mbc, ebeam, kpimass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        else:
            raise NameError(cuts)

        sys.stdout.write('Using cuts: %s...' %cuts)
        dataset = dataset.reduce(cuts)
        sys.stdout.write(' selected %s events.\n' % dataset.numEntries())
    else:
        ras = RooArgSet(mbc, ebeam, dflav)
        dataset = RooDataSet.read(evtfile, ras)

    res = RooRealVar("datares", "datares", mc)
    mres = RooRealVar("mres","mres", setMres)
    gamma = RooRealVar('gamma', 'gamma', setGamma)

    r = RooRealVar('r', 'r', setR)
    sigmaE = RooRealVar("sigmaE","sigmaE", 0.0021)

    sigmap1 = RooRealVar("sigmap1","sigmap1", sp1, 0.002, 0.040)

    scalep2 = RooRealVar("scalep2","scalep2",2.00,1.500,5.500)
    scalep3 = RooRealVar("scalep3","scalep3",5.00,3.00,10.000)
   
    scalep2.setVal(sp2)
    scalep2.setConstant(1)
    scalep3.setVal(sp3)
    scalep3.setConstant(1)

    as12 = RooArgList(sigmap1,scalep2)
    sigmap2 = RooFormulaVar("sigmap2","sigma2","sigmap1*scalep2", as12)

    as123 = RooArgList(sigmap1,scalep2,scalep3)
    sigmap3 = RooFormulaVar("sigmap3","sigma3","sigmap1*scalep2*scalep3",
                            as123)
    
    md = RooRealVar("md","md", setmd,1.863,1.875)

    f2 = RooRealVar("f2","f2", fa)
    f3 = RooRealVar("f3","f3", fb)
    al23 = RooArgList(f2,f3)
    f1 = RooFormulaVar("f1","f1","1.0-f2-f3", al23)

    # Construct signal shape

    fcn1_1 = RooDLineShape("DLineshape1_1","DLineShape1_1",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap1,md,res)
    fcn1_2 = RooDLineShape("DLineshape1_2","DLineShape1_2",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap2,md,res)
    fcn1_3 = RooDLineShape("DLineshape1_3","DLineShape1_3",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap3,md,res)

    fcn2_1 = RooDLineShape("DLineshape2_1","DLineShape2_1",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap1,md,res)
    fcn2_2 = RooDLineShape("DLineshape2_2","DLineShape2_2",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap2,md,res)
    fcn2_3 = RooDLineShape("DLineshape2_3","DLineShape2_3",4,mbc,ebeam,
                           mres,gamma,r,sigmaE,sigmap3,md,res)


    alf1_123 = RooArgList(fcn1_1,fcn1_2,fcn1_3)
    af12 = RooArgList(f1,f2) 
    signal1_3 = RooAddPdf("signal1_3","signal1_3", alf1_123, af12)

    alf2_123 = RooArgList(fcn2_1,fcn2_2,fcn2_3)
    
    signal2_3 = RooAddPdf("signal2_3","signal2_3", alf2_123, af12)

    p = RooRealVar("p","p", setp, 0.1, 1.5)
    xi= RooRealVar("xi","xi",setxi,-100.0,-0.1)

    Bkgd1 = RooArgusBG("argus1","argus1",mbc,ebeam,xi,p)
    Bkgd2 = RooArgusBG("argus2","argus2",mbc,ebeam,xi,p)

    shapes1 = RooArgList(signal1_3)
    shapes1.add(signal1_3)
    shapes1.add(Bkgd1)    

    shapes2 = RooArgList(signal2_3)
    shapes2.add(signal2_3)
    shapes2.add(Bkgd2)

    N1 = RooRealVar("N1","N1",setN1,0.0,200000000.0)
    N2 = RooRealVar("N2","N2",setN2,0.0,200000000.0)

    Nbkgd1 = RooRealVar("Nbkgd1","Nbkgd1",setNbkgd1, 0.0, 200000000.0)
    Nbkgd2 = RooRealVar("Nbkgd2","Nbkgd2",setNbkgd2, 0.0, 200000000.0)

    yields1 = RooArgList(N1)
    yields1.add(N1)
    yields1.add(Nbkgd1)

    yields2 = RooArgList(N2)
    yields2.add(N2)
    yields2.add(Nbkgd2)

    
    totalPdf1 = RooAddPdf("totalPdf1","totalPdf1", shapes1,yields1)
    totalPdf2 = RooAddPdf("totalPdf2","totalPdf2", shapes2,yields2)

    totalPdf = RooSimultaneous("totalPdf","totalPdf",dflav)
    totalPdf.addPdf(totalPdf1,"dflav")
    totalPdf.addPdf(totalPdf2,"dbarflav")

    # Check fitTo options at:
    # http://root.cern.ch/root/html512/RooAbsPdf.html#RooAbsPdf:fitTo
    #
    # Available fit options:
    #  "m" = MIGRAD only, i.e. no MINOS
    #  "s" = estimate step size with HESSE before starting MIGRAD
    #  "h" = run HESSE after MIGRAD
    #  "e" = Perform extended MLL fit
    #  "0" = Run MIGRAD with strategy MINUIT 0
    #  (no correlation matrix calculation at end)
    #   Does not apply to HESSE or MINOS, if run afterwards.

    #  "q" = Switch off verbose mode
    #  "l" = Save log file with parameter values at each MINUIT step
    #  "v" = Show changed parameters at each MINUIT step
    #  "t" = Time fit
    #  "r" = Save fit output in RooFitResult object 
    # Available optimizer options
    #  "c" = Cache and precalculate components of PDF that exclusively
    #  depend on constant parameters
    #  "2" = Do NLL calculation in multi-processor mode on 2 processors
    #  "3" = Do NLL calculation in multi-processor mode on 3 processors
    #  "4" = Do NLL calculation in multi-processor mode on 4 processors

    MINUIT = 'ermh4'

    if err_type == 'ASYM':
        MINUIT = 'erh4'
        
    if test:
        sys.stdout.write('Will save epsfile as: %s \n' %epsfile)
        sys.stdout.write('Will save txtfile as: %s \n' %txtfile)
        return
    
    if dataset.numEntries() == 0:
        N1.setVal(0)
        N2.setVal(0)
    else:
        # Start Fitting
        fitres = totalPdf.fitTo(dataset, MINUIT)
        fitres.Print('v')

    # Save plots
    canvas = TCanvas('canvas','mbc', 1200, 400);
    canvas.Divide(3,1)

    canvas_1 = canvas.GetListOfPrimitives().FindObject('canvas_1')
    canvas_2 = canvas.GetListOfPrimitives().FindObject('canvas_2')
    canvas_1.SetLogy(1) 
    canvas_2.SetLogy(1)

    LineColorRed = RooFit.LineColor(kRed)
    LineColorBlue = RooFit.LineColor(kBlue)
    LineWidth = RooFit.LineWidth(1) #0.6)

    # Plot the D 
    canvas.cd(1)
    mbcFrame=mbc.frame()
    mbcFrame=mbc.frame(60)

    dflav.setLabel('dflav')
    ebas = RooArgSet(ebeam, dflav)
    ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset)
    
    dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dflav"))
    mbcFrame.getAttMarker().SetMarkerSize(0.6)
    mbcFrame.Draw()

    Slice = RooFit.Slice(dflav)
    ProjWData = RooFit.ProjWData(ebas, ebeamdata)
    
    totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData)
    chisq1 = mbcFrame.chiSquare()*mbcFrame.GetNbinsX()
    mbcFrame.Draw()

    as_bkg1 = RooArgSet(Bkgd1)
    cp_bkg1 = RooFit.Components(as_bkg1)

    totalPdf.plotOn(mbcFrame, cp_bkg1, Slice, LineColorBlue, LineWidth, ProjWData)

    mbcFrame.SetTitle(title1)
    mbcFrame.SetMinimum(ymin)

    mbcFrame.Draw()

    # Plot the D bar
    canvas.cd(2)
    mbcFrame=mbc.frame()
    mbcFrame=mbc.frame(60)

    dflav.setLabel('dbarflav')
    ebas = RooArgSet(ebeam, dflav)
    ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset)
    
    dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dbarflav"))
    mbcFrame.getAttMarker().SetMarkerSize(0.6)
    mbcFrame.Draw()

    Slice = RooFit.Slice(dflav)
    ProjWData = RooFit.ProjWData(ebas, ebeamdata)
    
    totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData)
    chisq2 = mbcFrame.chiSquare()*mbcFrame.GetNbinsX()
    mbcFrame.Draw()

    as_bkg2 = RooArgSet(Bkgd2)
    cp_bkg2 = RooFit.Components(as_bkg2)

    totalPdf.plotOn(mbcFrame, cp_bkg2, Slice, LineColorBlue, LineWidth, ProjWData)

    mbcFrame.SetTitle(title2)
    mbcFrame.SetMinimum(ymin)

    mbcFrame.Draw()

    # Plot Statistics Box
    canvas.cd(3)
    mbcFrame = mbc.frame()

    paramWin1 = totalPdf.paramOn(mbcFrame,dataset, "",2,"NELU",0.1,0.9,0.9)

    mbcFrame.GetXaxis().SetLabelSize(0) 
    mbcFrame.GetXaxis().SetTickLength(0) 
    mbcFrame.GetXaxis().SetLabelSize(0) 
    mbcFrame.GetXaxis().SetTitle("") 
    mbcFrame.GetXaxis().CenterTitle() 
    
    mbcFrame.GetYaxis().SetLabelSize(0) 
    mbcFrame.GetYaxis().SetTitleSize(0.03) 
    mbcFrame.GetYaxis().SetTickLength(0) 

    paramWin1.getAttText().SetTextSize(0.06) 
  
    mbcFrame.Draw() 
    mbcFrame.SetTitle("Fit Parameters") 
    ATextBox = TPaveText(.1, .1, .8, .2,"BRNDC") 

    tempString = "#chi^{2}_{1} = %.1f, #chi^{2}_{2} = %.1f" % (chisq1,chisq2)  
    ATextBox.AddText(tempString) 
    ATextBox.SetFillColor(0)
    ATextBox.SetBorderSize(1)

    mbcFrame.addObject(ATextBox) 
    mbcFrame.Draw() 
    canvas.Print(epsfile)
    rootfile = epsfile.replace('.eps', '.root')
    canvas.Print(rootfile)

    # Save fitting parameters
    pars = [N1, N2, Nbkgd1, Nbkgd2, md, p, sigmap1, xi]
    save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
Example #7
0
def mbc_single_3s(evtfile,
                  mc,
                  setMres,
                  setGamma,
                  setR,
                  sp1,
                  sp2,
                  sp3,
                  fa,
                  fb,
                  setmd,
                  setp,
                  setxi,
                  setN1,
                  setN2,
                  setNbkgd1,
                  setNbkgd2,
                  title1,
                  title2,
                  epsfile,
                  txtfile,
                  ymin=0.5,
                  cuts=None,
                  err_type='SYMM',
                  test=False):

    from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet,
                      RooFit, RooGaussian, RooArgList, RooAddPdf,
                      RooSimultaneous, RooArgusBG, RooFormulaVar,
                      RooDLineShape, RooAbsData, RooDataHist, TCanvas, kRed,
                      kBlue, kGreen, kMagenta, TPaveText)
    set_root_style(stat=1, grid=0)

    # // sp1 = sigma of signal
    # // sp2 = ratio of sigmas betwwen sigma2 sigma 1
    # // sp3 = ratio of sigmas betwwen sigma3 sigma 2
    # // fa, fb, - fractions
    # // xi_side - slope of argus
    # // p_side - power of argus

    # mc = 1  Monte Carlo Model: EvtGenModels/Class/EvtVPHOtoVISR.cc
    # mc = 3  Data Model: with BES 2007 paper (BES2006 lineshape hepex/0612056)

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV')

    dflav = RooCategory('dflav', 'D flavor')
    dflav.defineType('dflav', 1)
    dflav.defineType('dbarflav', -1)

    if cuts != None:
        if 'kkmass' in cuts:
            kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90,
                                'GeV')
            ras = RooArgSet(mbc, ebeam, kkmass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        elif 'kpimass' in cuts:
            kpimass = RooRealVar('kpimass', 'Kpi invariant mass', 0.6, 1.4,
                                 'GeV')
            ras = RooArgSet(mbc, ebeam, kpimass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        else:
            raise NameError(cuts)

        sys.stdout.write('Using cuts: %s...' % cuts)
        dataset = dataset.reduce(cuts)
        sys.stdout.write(' selected %s events.\n' % dataset.numEntries())
    else:
        ras = RooArgSet(mbc, ebeam, dflav)
        dataset = RooDataSet.read(evtfile, ras)

    res = RooRealVar("datares", "datares", mc)
    mres = RooRealVar("mres", "mres", setMres)
    gamma = RooRealVar('gamma', 'gamma', setGamma)

    r = RooRealVar('r', 'r', setR)
    sigmaE = RooRealVar("sigmaE", "sigmaE", 0.0021)

    sigmap1 = RooRealVar("sigmap1", "sigmap1", sp1, 0.002, 0.040)

    scalep2 = RooRealVar("scalep2", "scalep2", 2.00, 1.500, 5.500)
    scalep3 = RooRealVar("scalep3", "scalep3", 5.00, 3.00, 10.000)

    scalep2.setVal(sp2)
    scalep2.setConstant(1)
    scalep3.setVal(sp3)
    scalep3.setConstant(1)

    as12 = RooArgList(sigmap1, scalep2)
    sigmap2 = RooFormulaVar("sigmap2", "sigma2", "sigmap1*scalep2", as12)

    as123 = RooArgList(sigmap1, scalep2, scalep3)
    sigmap3 = RooFormulaVar("sigmap3", "sigma3", "sigmap1*scalep2*scalep3",
                            as123)

    md = RooRealVar("md", "md", setmd, 1.863, 1.875)

    f2 = RooRealVar("f2", "f2", fa)
    f3 = RooRealVar("f3", "f3", fb)
    al23 = RooArgList(f2, f3)
    f1 = RooFormulaVar("f1", "f1", "1.0-f2-f3", al23)

    # Construct signal shape

    fcn1_1 = RooDLineShape("DLineshape1_1", "DLineShape1_1", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap1, md, res)
    fcn1_2 = RooDLineShape("DLineshape1_2", "DLineShape1_2", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap2, md, res)
    fcn1_3 = RooDLineShape("DLineshape1_3", "DLineShape1_3", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap3, md, res)

    fcn2_1 = RooDLineShape("DLineshape2_1", "DLineShape2_1", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap1, md, res)
    fcn2_2 = RooDLineShape("DLineshape2_2", "DLineShape2_2", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap2, md, res)
    fcn2_3 = RooDLineShape("DLineshape2_3", "DLineShape2_3", 4, mbc, ebeam,
                           mres, gamma, r, sigmaE, sigmap3, md, res)

    alf1_123 = RooArgList(fcn1_1, fcn1_2, fcn1_3)
    af12 = RooArgList(f1, f2)
    signal1_3 = RooAddPdf("signal1_3", "signal1_3", alf1_123, af12)

    alf2_123 = RooArgList(fcn2_1, fcn2_2, fcn2_3)

    signal2_3 = RooAddPdf("signal2_3", "signal2_3", alf2_123, af12)

    p = RooRealVar("p", "p", setp, 0.1, 1.5)
    xi = RooRealVar("xi", "xi", setxi, -100.0, -0.1)

    Bkgd1 = RooArgusBG("argus1", "argus1", mbc, ebeam, xi, p)
    Bkgd2 = RooArgusBG("argus2", "argus2", mbc, ebeam, xi, p)

    shapes1 = RooArgList(signal1_3)
    shapes1.add(signal1_3)
    shapes1.add(Bkgd1)

    shapes2 = RooArgList(signal2_3)
    shapes2.add(signal2_3)
    shapes2.add(Bkgd2)

    N1 = RooRealVar("N1", "N1", setN1, 0.0, 200000000.0)
    N2 = RooRealVar("N2", "N2", setN2, 0.0, 200000000.0)

    Nbkgd1 = RooRealVar("Nbkgd1", "Nbkgd1", setNbkgd1, 0.0, 200000000.0)
    Nbkgd2 = RooRealVar("Nbkgd2", "Nbkgd2", setNbkgd2, 0.0, 200000000.0)

    yields1 = RooArgList(N1)
    yields1.add(N1)
    yields1.add(Nbkgd1)

    yields2 = RooArgList(N2)
    yields2.add(N2)
    yields2.add(Nbkgd2)

    totalPdf1 = RooAddPdf("totalPdf1", "totalPdf1", shapes1, yields1)
    totalPdf2 = RooAddPdf("totalPdf2", "totalPdf2", shapes2, yields2)

    totalPdf = RooSimultaneous("totalPdf", "totalPdf", dflav)
    totalPdf.addPdf(totalPdf1, "dflav")
    totalPdf.addPdf(totalPdf2, "dbarflav")

    # Check fitTo options at:
    # http://root.cern.ch/root/html512/RooAbsPdf.html#RooAbsPdf:fitTo
    #
    # Available fit options:
    #  "m" = MIGRAD only, i.e. no MINOS
    #  "s" = estimate step size with HESSE before starting MIGRAD
    #  "h" = run HESSE after MIGRAD
    #  "e" = Perform extended MLL fit
    #  "0" = Run MIGRAD with strategy MINUIT 0
    #  (no correlation matrix calculation at end)
    #   Does not apply to HESSE or MINOS, if run afterwards.

    #  "q" = Switch off verbose mode
    #  "l" = Save log file with parameter values at each MINUIT step
    #  "v" = Show changed parameters at each MINUIT step
    #  "t" = Time fit
    #  "r" = Save fit output in RooFitResult object
    # Available optimizer options
    #  "c" = Cache and precalculate components of PDF that exclusively
    #  depend on constant parameters
    #  "2" = Do NLL calculation in multi-processor mode on 2 processors
    #  "3" = Do NLL calculation in multi-processor mode on 3 processors
    #  "4" = Do NLL calculation in multi-processor mode on 4 processors

    MINUIT = 'ermh4'

    if err_type == 'ASYM':
        MINUIT = 'erh4'

    if test:
        sys.stdout.write('Will save epsfile as: %s \n' % epsfile)
        sys.stdout.write('Will save txtfile as: %s \n' % txtfile)
        return

    if dataset.numEntries() == 0:
        N1.setVal(0)
        N2.setVal(0)
    else:
        # Start Fitting
        fitres = totalPdf.fitTo(dataset, MINUIT)
        fitres.Print('v')

    # Save plots
    canvas = TCanvas('canvas', 'mbc', 1200, 400)
    canvas.Divide(3, 1)

    canvas_1 = canvas.GetListOfPrimitives().FindObject('canvas_1')
    canvas_2 = canvas.GetListOfPrimitives().FindObject('canvas_2')
    canvas_1.SetLogy(1)
    canvas_2.SetLogy(1)

    LineColorRed = RooFit.LineColor(kRed)
    LineColorBlue = RooFit.LineColor(kBlue)
    LineWidth = RooFit.LineWidth(1)  #0.6)

    # Plot the D
    canvas.cd(1)
    mbcFrame = mbc.frame()
    mbcFrame = mbc.frame(60)

    dflav.setLabel('dflav')
    ebas = RooArgSet(ebeam, dflav)
    ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset)

    dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dflav"))
    mbcFrame.getAttMarker().SetMarkerSize(0.6)
    mbcFrame.Draw()

    Slice = RooFit.Slice(dflav)
    ProjWData = RooFit.ProjWData(ebas, ebeamdata)

    totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData)
    chisq1 = mbcFrame.chiSquare() * mbcFrame.GetNbinsX()
    mbcFrame.Draw()

    as_bkg1 = RooArgSet(Bkgd1)
    cp_bkg1 = RooFit.Components(as_bkg1)

    totalPdf.plotOn(mbcFrame, cp_bkg1, Slice, LineColorBlue, LineWidth,
                    ProjWData)

    mbcFrame.SetTitle(title1)
    mbcFrame.SetMinimum(ymin)

    mbcFrame.Draw()

    # Plot the D bar
    canvas.cd(2)
    mbcFrame = mbc.frame()
    mbcFrame = mbc.frame(60)

    dflav.setLabel('dbarflav')
    ebas = RooArgSet(ebeam, dflav)
    ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset)

    dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dbarflav"))
    mbcFrame.getAttMarker().SetMarkerSize(0.6)
    mbcFrame.Draw()

    Slice = RooFit.Slice(dflav)
    ProjWData = RooFit.ProjWData(ebas, ebeamdata)

    totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData)
    chisq2 = mbcFrame.chiSquare() * mbcFrame.GetNbinsX()
    mbcFrame.Draw()

    as_bkg2 = RooArgSet(Bkgd2)
    cp_bkg2 = RooFit.Components(as_bkg2)

    totalPdf.plotOn(mbcFrame, cp_bkg2, Slice, LineColorBlue, LineWidth,
                    ProjWData)

    mbcFrame.SetTitle(title2)
    mbcFrame.SetMinimum(ymin)

    mbcFrame.Draw()

    # Plot Statistics Box
    canvas.cd(3)
    mbcFrame = mbc.frame()

    paramWin1 = totalPdf.paramOn(mbcFrame, dataset, "", 2, "NELU", 0.1, 0.9,
                                 0.9)

    mbcFrame.GetXaxis().SetLabelSize(0)
    mbcFrame.GetXaxis().SetTickLength(0)
    mbcFrame.GetXaxis().SetLabelSize(0)
    mbcFrame.GetXaxis().SetTitle("")
    mbcFrame.GetXaxis().CenterTitle()

    mbcFrame.GetYaxis().SetLabelSize(0)
    mbcFrame.GetYaxis().SetTitleSize(0.03)
    mbcFrame.GetYaxis().SetTickLength(0)

    paramWin1.getAttText().SetTextSize(0.06)

    mbcFrame.Draw()
    mbcFrame.SetTitle("Fit Parameters")
    ATextBox = TPaveText(.1, .1, .8, .2, "BRNDC")

    tempString = "#chi^{2}_{1} = %.1f, #chi^{2}_{2} = %.1f" % (chisq1, chisq2)
    ATextBox.AddText(tempString)
    ATextBox.SetFillColor(0)
    ATextBox.SetBorderSize(1)

    mbcFrame.addObject(ATextBox)
    mbcFrame.Draw()
    canvas.Print(epsfile)
    rootfile = epsfile.replace('.eps', '.root')
    canvas.Print(rootfile)

    # Save fitting parameters
    pars = [N1, N2, Nbkgd1, Nbkgd2, md, p, sigmap1, xi]
    save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
Example #8
0
def mbc_gau_che(evtfile,
                mc,
                setMres,
                setGamma,
                setR,
                sp1,
                sp2,
                sp3,
                fa,
                fb,
                setmd,
                setp,
                setxi,
                setN1,
                setN2,
                setNbkgd1,
                setNbkgd2,
                title1,
                title2,
                epsfile,
                txtfile,
                ymin=0.5,
                cuts=None,
                err_type='SYMM',
                test=False):

    from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet,
                      RooFit, RooGaussian, RooArgList, RooAddPdf,
                      RooSimultaneous, RooArgusBG, RooFormulaVar, RooChebychev,
                      RooAbsData, RooDataHist, TCanvas, kRed, kBlue, kGreen,
                      kMagenta, TPaveText)
    set_root_style(stat=1, grid=0)

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV')

    dflav = RooCategory('dflav', 'D0 flavor')
    dflav.defineType('dflav', 1)
    dflav.defineType('dbarflav', -1)

    if cuts != None:
        if 'kkmass' in cuts:
            kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90,
                                'GeV')
            ras = RooArgSet(mbc, ebeam, kkmass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        elif 'kpimass' in cuts:
            kpimass = RooRealVar('kpimass', 'Kpi invariant mass', 0.6, 1.4,
                                 'GeV')
            ras = RooArgSet(mbc, ebeam, kpimass, dflav)
            dataset = RooDataSet.read(evtfile, ras)
        else:
            raise NameError(cuts)

        sys.stdout.write('Using cuts: %s...' % cuts)
        dataset = dataset.reduce(cuts)
        sys.stdout.write(' selected %s events.\n' % dataset.numEntries())
    else:
        ras = RooArgSet(mbc, ebeam, dflav)
        dataset = RooDataSet.read(evtfile, ras)

    #sigma = RooRealVar('sigma', 'D width', 0.0001, 0.005, 'GeV')
    sigma = RooRealVar('sigma', 'D width', 0.00468, 'GeV')
    mbc_dp = RooRealVar('mbc_dp', 'D+ Mass', 1.86962, 'GeV')
    sigpdf = RooGaussian('gauss_dp', 'D+ gaussian', mbc, mbc_dp, sigma)

    #arg_cutoff = RooRealVar('arg_cutoff', 'Argus cutoff', 1.88, 1.89, 'GeV')
    #arg_slope = RooRealVar('arg_slope', 'Argus slope', -10, -100, -1)
    #bkgpdf = RooArgusBG('argus', 'Argus BG', mbc, arg_cutoff, arg_slope)

    con0 = RooRealVar('c0', 'constant', -1, 1)
    con1 = RooRealVar('c1', 'linear', -10, 10)
    con2 = RooRealVar('c2', 'quadratic', 1)

    bkgpdf = RooChebychev('bkgpdf', 'Background', mbc, RooArgList(con1, con2))

    yld = RooRealVar('yld', 'D yield', 100, 0, 2000)
    bkg = RooRealVar('bkg', 'Background', 100, 0, 1000)

    sumpdf = RooAddPdf('sumpdf', 'Sum pdf', RooArgList(sigpdf, bkgpdf),
                       RooArgList(yld, bkg))

    yldbar = RooRealVar('yldbar', 'Dbar yield', 100, 0, 2000)
    bkgbar = RooRealVar('bkgbar', 'Background', 100, 0, 1000)

    sumpdfbar = RooAddPdf('sumpdfbar', 'Sum pdf', RooArgList(sigpdf, bkgpdf),
                          RooArgList(yldbar, bkgbar))

    totalpdf = RooSimultaneous('rs', 'Simultaneous PDF', dflav)
    totalpdf.addPdf(sumpdf, 'dflav')
    totalpdf.addPdf(sumpdfbar, 'dbarflav')

    MINUIT = 'ermh4'

    if err_type == 'ASYM':
        MINUIT = 'erh4'

    if test:
        sys.stdout.write('Will save epsfile as: %s \n' % epsfile)
        sys.stdout.write('Will save txtfile as: %s \n' % txtfile)
        return

    if dataset.numEntries() == 0:
        yld.setVal(0)
        yldbar.setVal(0)
    else:
        # Start Fitting
        fitres = totalpdf.fitTo(dataset, MINUIT)
        fitres.Print('v')

    # Save plots
    canvas = TCanvas('canvas', 'mbc', 400, 400)
    xframe = mbc.frame(50)
    ProjWData = RooFit.ProjWData(dataset)
    RooAbsData.plotOn(dataset, xframe)
    totalpdf.plotOn(xframe, ProjWData)
    totalpdf.paramOn(xframe)
    xframe.Draw()
    canvas.Print(epsfile)

    # Save fitting parameters
    pars = [bkg, bkgbar, con1, yld, yldbar]
    save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
def rf501_simultaneouspdf():
    signal_1, bkg_1, signal_2, bkg_2 = get_templates()
    # C r e a t e   m o d e l   f o r   p h y s i c s   s a m p l e
    # -------------------------------------------------------------

    # Create observables
    x = RooRealVar( "x", "x", 0, 200 ) 
    x.setBins(n_bins)
    nsig = RooRealVar( "nsig", "#signal events", N_signal_obs, 0., 2*N_data )
    nbkg = RooRealVar( "nbkg", "#background events", N_bkg1_obs, 0., 2*N_data )

    # Construct signal pdf
#     mean = RooRealVar( "mean", "mean", mu4, 40, 200 ) 
#     sigma = RooRealVar( "sigma", "sigma", sigma4, 0.1, 20 )
#     gx = RooGaussian( "gx", "gx", x, mean, sigma ) 
    roofit_signal_1 = RooDataHist( 'signal_1', 'signal_1', RooArgList(x), signal_1 )
    signal_1_pdf = RooHistPdf ( 'signal_1_pdf' , 'signal_1_pdf', RooArgSet(x), roofit_signal_1) 

    # Construct background pdf
#     mean_bkg = RooRealVar( "mean_bkg", "mean_bkg", mu3, 40, 200 ) 
#     sigma_bkg = RooRealVar( "sigma_bkg", "sigma_bkg", sigma3, 0.1, 20 ) 
#     px = RooGaussian( "px", "px", x, mean_bkg, sigma_bkg ) 
    roofit_bkg_1 = RooDataHist( 'bkg_1', 'bkg_1', RooArgList(x), bkg_1 )
    bkg_1_pdf = RooHistPdf ( 'bkg_1_pdf' , 'bkg_1_pdf', RooArgSet(x), roofit_bkg_1) 

    # Construct composite pdf
    model = RooAddPdf( "model", "model", RooArgList( signal_1_pdf, bkg_1_pdf ), RooArgList( nsig, nbkg ) ) 



    # C r e a t e   m o d e l   f o r   c o n t r o l   s a m p l e
    # --------------------------------------------------------------

    # Construct signal pdf. 
    # NOTE that sigma is shared with the signal sample model
    y = RooRealVar( "y", "y", 0, 200 )
    y.setBins(n_bins)
    mean_ctl = RooRealVar( "mean_ctl", "mean_ctl", mu2, 0, 200 ) 
    sigma_ctl = RooRealVar( "sigma", "sigma", sigma2, 0.1, 10 ) 
    gx_ctl = RooGaussian( "gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl ) 

    # Construct the background pdf
    mean_bkg_ctl = RooRealVar( "mean_bkg_ctl", "mean_bkg_ctl", mu1, 0, 200 ) 
    sigma_bkg_ctl = RooRealVar( "sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1, 20 ) 
    px_ctl = RooGaussian( "px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl ) 

    # Construct the composite model
#     f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. ) 
    model_ctl = RooAddPdf( "model_ctl", "model_ctl", RooArgList( gx_ctl, px_ctl ),
                           RooArgList( nsig, nbkg ) ) 
    


    # G e t   e v e n t s   f o r   b o t h   s a m p l e s 
    # ---------------------------------------------------------------
    real_data, real_data_ctl = get_data()
    real_data_hist = RooDataHist( 'real_data_hist',
                                 'real_data_hist',
                                 RooArgList( x ),
                                 real_data )
    real_data_ctl_hist = RooDataHist( 'real_data_ctl_hist',
                                     'real_data_ctl_hist',
                                     RooArgList( y ),
                                     real_data_ctl )
    input_hists = MapStrRootPtr()
    input_hists.insert( StrHist( "physics", real_data ) )
    input_hists.insert( StrHist( "control", real_data_ctl ) )

    # C r e a t e   i n d e x   c a t e g o r y   a n d   j o i n   s a m p l e s 
    # ---------------------------------------------------------------------------
    # Define category to distinguish physics and control samples events
    sample = RooCategory( "sample", "sample" ) 
    sample.defineType( "physics" ) 
    sample.defineType( "control" ) 

    # Construct combined dataset in (x,sample)
    combData = RooDataHist( "combData", "combined data", RooArgList( x), sample ,
                           input_hists )


    # C o n s t r u c t   a   s i m u l t a n e o u s   p d f   i n   ( x , s a m p l e )
    # -----------------------------------------------------------------------------------

    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous( "simPdf", "simultaneous pdf", sample ) 

    # Associate model with the physics state and model_ctl with the control state
    simPdf.addPdf( model, "physics" ) 
    simPdf.addPdf( model_ctl, "control" ) 

#60093.048127    173.205689173    44.7112503776

    # P e r f o r m   a   s i m u l t a n e o u s   f i t
    # ---------------------------------------------------
    model.fitTo( real_data_hist,
                RooFit.Minimizer( "Minuit2", "Migrad" ),
                        RooFit.NumCPU( 1 ),
#                         RooFit.Extended(),
#                         RooFit.Save(), 
                        )
    summary = 'fit in signal region\n'
    summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' 
    summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n'
#     
#     model_ctl.fitTo( real_data_ctl_hist )
#     summary += 'fit in control region\n'
#     summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' 
#     summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n' 
# 
#     # Perform simultaneous fit of model to data and model_ctl to data_ctl
#     simPdf.fitTo( combData ) 
#     summary += 'Combined fit\n'
#     summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' 
#     summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n' 


    # P l o t   m o d e l   s l i c e s   o n   d a t a    s l i c e s 
    # ----------------------------------------------------------------

    # Make a frame for the physics sample
    frame1 = x.frame( RooFit.Bins( 30 ), RooFit.Title( "Physics sample" ) ) 

    # Plot all data tagged as physics sample
    combData.plotOn( frame1, RooFit.Cut( "sample==sample::physics" ) ) 

    # Plot "physics" slice of simultaneous pdf. 
    # NBL You _must_ project the sample index category with data using ProjWData 
    # as a RooSimultaneous makes no prediction on the shape in the index category 
    # and can thus not be integrated
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.ProjWData( RooArgSet( sample ), combData ), ) 
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.Components( "signal_1_pdf" ),
                   RooFit.ProjWData( RooArgSet( sample ), combData ),
                   RooFit.LineStyle( kDashed ),
                   ) 
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.Components( "bkg_1_pdf" ),
                   RooFit.ProjWData( RooArgSet( sample ), combData ),
                   RooFit.LineStyle( kDashed ),
                   RooFit.LineColor( kRed ) ) 

    # The same plot for the control sample slice
    frame2 = y.frame( RooFit.Bins( 30 ), RooFit.Title( "Control sample" ) ) 
    combData.plotOn( frame2, RooFit.Cut( "sample==sample::control" ) ) 
    simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ),
                  RooFit.ProjWData( RooArgSet( sample ), combData ) ) 
    simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ),
                  RooFit.Components( "px_ctl" ),
                  RooFit.ProjWData( RooArgSet( sample ), combData ),
                  RooFit.LineStyle( kDashed ) ) 



    c = TCanvas( "rf501_simultaneouspdf", "rf403_simultaneouspdf", 800, 400 ) 
    c.Divide( 2 ) 
    c.cd( 1 )
    gPad.SetLeftMargin( 0.15 )
    frame1.GetYaxis().SetTitleOffset( 1.4 )
    frame1.Draw() 
    c.cd( 2 )
    gPad.SetLeftMargin( 0.15 )
    frame2.GetYaxis().SetTitleOffset( 1.4 )
    frame2.Draw() 
    
    print summary
    print real_data.Integral()
    raw_input()
Example #10
0
total_pdf.fitTo(datahist)


#Plotting fits
canvs = []
fitPads = []
pullPads = []
pulls = []
for i in range(n_regions) :
    region = regions[i]
    canvs.append(TCanvas(region+"_canv", region+" D0 Mass Region Fit"))    

    frame = deltam.frame()
    datahist.plotOn(frame, Cut("regionIndex==regionIndex::"+region))
    regionIndexSet = RooArgSet(regionIndex)
    total_pdf.plotOn(frame, Slice(regionIndex, region), ProjWData(regionIndexSet, datahist))
    pulls.append(frame.pullHist())
    total_pdf.plotOn(frame, Slice(regionIndex, region), ProjWData(regionIndexSet, datahist), Components("bg_pdf"), LineColor(kGreen+2), LineStyle(2))
    total_pdf.plotOn(frame, Slice(regionIndex, region), ProjWData(regionIndexSet, datahist), Components("signal_pdf_"+region), LineColor(kRed+2), LineStyle(3))
    
    #Creating pad to plot fit to data
    fitPads.append(TPad("fitPad_{}".format(i), "fitPad_{}".format(i), 0., 0.3, 1., 1.)) 
    fitPads[i].SetMargin(0.08, 0.05, 0.05, 0.1)
    fitPads[i].Draw()
    fitPads[i].cd()
    frame.Draw()

    #Creating pad to plot pull ( (actual - fit) / uncertainty )
    canvs[i].cd() 
    pullPads.append(TPad("pullPad_{}".format(i), "pullPad_{}".format(i), 0., 0., 1., 0.3))
    pullPads[i].SetMargin(0.08, 0.05, 0.1, 0.05)
Example #11
0
def rf501_simultaneouspdf():
    # C r e a t e   m o d e l   f o r   p h y s i c s   s a m p l e
    # -------------------------------------------------------------

    # Create observables
    x = RooRealVar("x", "x", 40, 200)
    nsig = RooRealVar("nsig", "#signal events", 200, 0., 10000)
    nbkg = RooRealVar("nbkg", "#background events", 800, 0., 200000)
    # Construct signal pdf
    mean = RooRealVar("mean", "mean", mu4, 40, 200)
    sigma = RooRealVar("sigma", "sigma", sigma4, 0.1, 20)
    gx = RooGaussian("gx", "gx", x, mean, sigma)

    # Construct background pdf
    mean_bkg = RooRealVar("mean_bkg", "mean_bkg", mu3, 40, 200)
    sigma_bkg = RooRealVar("sigma_bkg", "sigma_bkg", sigma3, 0.1, 20)
    px = RooGaussian("px", "px", x, mean_bkg, sigma_bkg)

    # Construct composite pdf
    model = RooAddPdf("model", "model", RooArgList(gx, px),
                      RooArgList(nsig, nbkg))

    # C r e a t e   m o d e l   f o r   c o n t r o l   s a m p l e
    # --------------------------------------------------------------

    # Construct signal pdf.
    # NOTE that sigma is shared with the signal sample model
    y = RooRealVar("y", "y", 40, 200)

    mean_ctl = RooRealVar("mean_ctl", "mean_ctl", mu2, 40, 200)
    sigma_ctl = RooRealVar("sigma", "sigma", sigma2, 0.1, 10)
    gx_ctl = RooGaussian("gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl)

    # Construct the background pdf
    mean_bkg_ctl = RooRealVar("mean_bkg_ctl", "mean_bkg_ctl", mu1, 40, 200)
    sigma_bkg_ctl = RooRealVar("sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1,
                               20)
    px_ctl = RooGaussian("px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl)

    # Construct the composite model
    #     f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. )
    model_ctl = RooAddPdf("model_ctl", "model_ctl", RooArgList(gx_ctl, px_ctl),
                          RooArgList(nsig, nbkg))

    # G e t   e v e n t s   f o r   b o t h   s a m p l e s
    # ---------------------------------------------------------------
    real_data, real_data_ctl = get_data()
    real_data_hist = RooDataHist('real_data_hist', 'real_data_hist',
                                 RooArgList(x), real_data)
    real_data_ctl_hist = RooDataHist('real_data_ctl_hist',
                                     'real_data_ctl_hist', RooArgList(y),
                                     real_data_ctl)
    input_hists = MapStrRootPtr()
    input_hists.insert(StrHist("physics", real_data))
    input_hists.insert(StrHist("control", real_data_ctl))

    # C r e a t e   i n d e x   c a t e g o r y   a n d   j o i n   s a m p l e s
    # ---------------------------------------------------------------------------
    # Define category to distinguish physics and control samples events
    sample = RooCategory("sample", "sample")
    sample.defineType("physics")
    sample.defineType("control")

    # Construct combined dataset in (x,sample)
    combData = RooDataHist("combData", "combined data", RooArgList(x), sample,
                           input_hists)

    # C o n s t r u c t   a   s i m u l t a n e o u s   p d f   i n   ( x , s a m p l e )
    # -----------------------------------------------------------------------------------

    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample)

    # Associate model with the physics state and model_ctl with the control state
    simPdf.addPdf(model, "physics")
    simPdf.addPdf(model_ctl, "control")

    # P e r f o r m   a   s i m u l t a n e o u s   f i t
    # ---------------------------------------------------
    model.fitTo(real_data_hist)
    summary = 'fit in signal region\n'
    summary += 'nsig: ' + str(nsig.getValV()) + ' +- ' + str(
        nsig.getError()) + '\n'
    summary += 'nbkg: ' + str(nbkg.getValV()) + ' +- ' + str(
        nbkg.getError()) + '\n'

    model_ctl.fitTo(real_data_ctl_hist)
    summary += 'fit in control region\n'
    summary += 'nsig: ' + str(nsig.getValV()) + ' +- ' + str(
        nsig.getError()) + '\n'
    summary += 'nbkg: ' + str(nbkg.getValV()) + ' +- ' + str(
        nbkg.getError()) + '\n'

    # Perform simultaneous fit of model to data and model_ctl to data_ctl
    simPdf.fitTo(combData)
    summary += 'Combined fit\n'
    summary += 'nsig: ' + str(nsig.getValV()) + ' +- ' + str(
        nsig.getError()) + '\n'
    summary += 'nbkg: ' + str(nbkg.getValV()) + ' +- ' + str(
        nbkg.getError()) + '\n'

    # P l o t   m o d e l   s l i c e s   o n   d a t a    s l i c e s
    # ----------------------------------------------------------------

    # Make a frame for the physics sample
    frame1 = x.frame(RooFit.Bins(30), RooFit.Title("Physics sample"))

    # Plot all data tagged as physics sample
    combData.plotOn(frame1, RooFit.Cut("sample==sample::physics"))

    # Plot "physics" slice of simultaneous pdf.
    # NBL You _must_ project the sample index category with data using ProjWData
    # as a RooSimultaneous makes no prediction on the shape in the index category
    # and can thus not be integrated
    simPdf.plotOn(frame1, RooFit.Slice(sample, "physics"),
                  RooFit.ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame1, RooFit.Slice(sample, "physics"),
                  RooFit.Components("px"),
                  RooFit.ProjWData(RooArgSet(sample), combData),
                  RooFit.LineStyle(kDashed))

    # The same plot for the control sample slice
    frame2 = y.frame(RooFit.Bins(30), RooFit.Title("Control sample"))
    combData.plotOn(frame2, RooFit.Cut("sample==sample::control"))
    simPdf.plotOn(frame2, RooFit.Slice(sample, "control"),
                  RooFit.ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame2, RooFit.Slice(sample, "control"),
                  RooFit.Components("px_ctl"),
                  RooFit.ProjWData(RooArgSet(sample), combData),
                  RooFit.LineStyle(kDashed))
    simPdf.plotOn(frame2, RooFit.Slice(sample, "control"),
                  RooFit.Components("gx_ctl"),
                  RooFit.ProjWData(RooArgSet(sample), combData),
                  RooFit.LineStyle(kDashed))

    c = TCanvas("rf501_simultaneouspdf", "rf403_simultaneouspdf", 800, 400)
    c.Divide(2)
    c.cd(1)
    gPad.SetLeftMargin(0.15)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.Draw()
    c.cd(2)
    gPad.SetLeftMargin(0.15)
    frame2.GetYaxis().SetTitleOffset(1.4)
    frame2.Draw()

    print summary
    raw_input()
def rf501_simultaneouspdf():
    # C r e a t e   m o d e l   f o r   p h y s i c s   s a m p l e
    # -------------------------------------------------------------

    # Create observables
    x = RooRealVar("x", "x", 40, 200)
    nsig = RooRealVar("nsig", "#signal events", 200, 0.0, 10000)
    nbkg = RooRealVar("nbkg", "#background events", 800, 0.0, 200000)
    # Construct signal pdf
    mean = RooRealVar("mean", "mean", mu4, 40, 200)
    sigma = RooRealVar("sigma", "sigma", sigma4, 0.1, 20)
    gx = RooGaussian("gx", "gx", x, mean, sigma)

    # Construct background pdf
    mean_bkg = RooRealVar("mean_bkg", "mean_bkg", mu3, 40, 200)
    sigma_bkg = RooRealVar("sigma_bkg", "sigma_bkg", sigma3, 0.1, 20)
    px = RooGaussian("px", "px", x, mean_bkg, sigma_bkg)

    # Construct composite pdf
    model = RooAddPdf("model", "model", RooArgList(gx, px), RooArgList(nsig, nbkg))

    # C r e a t e   m o d e l   f o r   c o n t r o l   s a m p l e
    # --------------------------------------------------------------

    # Construct signal pdf.
    # NOTE that sigma is shared with the signal sample model
    y = RooRealVar("y", "y", 40, 200)

    mean_ctl = RooRealVar("mean_ctl", "mean_ctl", mu2, 40, 200)
    sigma_ctl = RooRealVar("sigma", "sigma", sigma2, 0.1, 10)
    gx_ctl = RooGaussian("gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl)

    # Construct the background pdf
    mean_bkg_ctl = RooRealVar("mean_bkg_ctl", "mean_bkg_ctl", mu1, 40, 200)
    sigma_bkg_ctl = RooRealVar("sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1, 20)
    px_ctl = RooGaussian("px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl)

    # Construct the composite model
    #     f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. )
    model_ctl = RooAddPdf("model_ctl", "model_ctl", RooArgList(gx_ctl, px_ctl), RooArgList(nsig, nbkg))

    # G e t   e v e n t s   f o r   b o t h   s a m p l e s
    # ---------------------------------------------------------------
    real_data, real_data_ctl = get_data()
    real_data_hist = RooDataHist("real_data_hist", "real_data_hist", RooArgList(x), real_data)
    real_data_ctl_hist = RooDataHist("real_data_ctl_hist", "real_data_ctl_hist", RooArgList(y), real_data_ctl)
    input_hists = MapStrRootPtr()
    input_hists.insert(StrHist("physics", real_data))
    input_hists.insert(StrHist("control", real_data_ctl))

    # C r e a t e   i n d e x   c a t e g o r y   a n d   j o i n   s a m p l e s
    # ---------------------------------------------------------------------------
    # Define category to distinguish physics and control samples events
    sample = RooCategory("sample", "sample")
    sample.defineType("physics")
    sample.defineType("control")

    # Construct combined dataset in (x,sample)
    combData = RooDataHist("combData", "combined data", RooArgList(x), sample, input_hists)

    # C o n s t r u c t   a   s i m u l t a n e o u s   p d f   i n   ( x , s a m p l e )
    # -----------------------------------------------------------------------------------

    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample)

    # Associate model with the physics state and model_ctl with the control state
    simPdf.addPdf(model, "physics")
    simPdf.addPdf(model_ctl, "control")

    # P e r f o r m   a   s i m u l t a n e o u s   f i t
    # ---------------------------------------------------
    model.fitTo(real_data_hist)
    summary = "fit in signal region\n"
    summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n"
    summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n"

    model_ctl.fitTo(real_data_ctl_hist)
    summary += "fit in control region\n"
    summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n"
    summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n"

    # Perform simultaneous fit of model to data and model_ctl to data_ctl
    simPdf.fitTo(combData)
    summary += "Combined fit\n"
    summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n"
    summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n"

    # P l o t   m o d e l   s l i c e s   o n   d a t a    s l i c e s
    # ----------------------------------------------------------------

    # Make a frame for the physics sample
    frame1 = x.frame(RooFit.Bins(30), RooFit.Title("Physics sample"))

    # Plot all data tagged as physics sample
    combData.plotOn(frame1, RooFit.Cut("sample==sample::physics"))

    # Plot "physics" slice of simultaneous pdf.
    # NBL You _must_ project the sample index category with data using ProjWData
    # as a RooSimultaneous makes no prediction on the shape in the index category
    # and can thus not be integrated
    simPdf.plotOn(frame1, RooFit.Slice(sample, "physics"), RooFit.ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(
        frame1,
        RooFit.Slice(sample, "physics"),
        RooFit.Components("px"),
        RooFit.ProjWData(RooArgSet(sample), combData),
        RooFit.LineStyle(kDashed),
    )

    # The same plot for the control sample slice
    frame2 = y.frame(RooFit.Bins(30), RooFit.Title("Control sample"))
    combData.plotOn(frame2, RooFit.Cut("sample==sample::control"))
    simPdf.plotOn(frame2, RooFit.Slice(sample, "control"), RooFit.ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(
        frame2,
        RooFit.Slice(sample, "control"),
        RooFit.Components("px_ctl"),
        RooFit.ProjWData(RooArgSet(sample), combData),
        RooFit.LineStyle(kDashed),
    )
    simPdf.plotOn(
        frame2,
        RooFit.Slice(sample, "control"),
        RooFit.Components("gx_ctl"),
        RooFit.ProjWData(RooArgSet(sample), combData),
        RooFit.LineStyle(kDashed),
    )

    c = TCanvas("rf501_simultaneouspdf", "rf403_simultaneouspdf", 800, 400)
    c.Divide(2)
    c.cd(1)
    gPad.SetLeftMargin(0.15)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.Draw()
    c.cd(2)
    gPad.SetLeftMargin(0.15)
    frame2.GetYaxis().SetTitleOffset(1.4)
    frame2.Draw()

    print summary
    raw_input()
def rooFit501():

    print ">>> setup model for physics sample..."
    x = RooRealVar("x", "x", -8, 8)
    mean = RooRealVar("mean", "mean", 0, -8, 8)
    sigma = RooRealVar("sigma", "sigma", 0.3, 0.1, 10)
    gauss = RooGaussian("gx", "gx", x, mean, sigma)
    a0 = RooRealVar("a0", "a0", -0.1, -1, 1)
    a1 = RooRealVar("a1", "a1", 0.004, -1, 1)
    px = RooChebychev("px", "px", x, RooArgList(a0, a1))
    f = RooRealVar("f", "f", 0.2, 0., 1.)
    model = RooAddPdf("model", "model", RooArgList(gauss, px), RooArgList(f))

    print ">>> setup model for control sample..."
    # NOTE: sigma is shared with the signal sample model
    mean_ctrl = RooRealVar("mean_ctrl", "mean_ctrl", -3, -8, 8)
    gauss_ctrl = RooGaussian("gauss_ctrl", "gauss_ctrl", x, mean_ctrl, sigma)
    a0_ctrl = RooRealVar("a0_ctrl", "a0_ctrl", -0.1, -1, 1)
    a1_ctrl = RooRealVar("a1_ctrl", "a1_ctrl", 0.5, -0.1, 1)
    px_ctrl = RooChebychev("px_ctrl", "px_ctrl", x,
                           RooArgList(a0_ctrl, a1_ctrl))
    f_ctrl = RooRealVar("f_ctrl", "f_ctrl", 0.5, 0., 1.)
    model_ctrl = RooAddPdf("model_ctrl", "model_ctrl",
                           RooArgList(gauss_ctrl, px_ctrl), RooArgList(f_ctrl))

    print ">>> generate events for both samples..."
    data = model.generate(RooArgSet(x), 100)  # RooDataSet
    data_ctrl = model_ctrl.generate(RooArgSet(x), 2000)  # RooDataSet

    print ">>> create index category and join samples..."
    # Define category to distinguish physics and control samples events
    sample = RooCategory("sample", "sample")
    sample.defineType("physics")
    sample.defineType("control")

    print ">>> construct combined dataset in (x,sample)..."
    combData = RooDataSet("combData", "combined data", RooArgSet(x),
                          Index(sample), Import("physics", data),
                          Import("control", data_ctrl))

    print ">>> construct a simultaneous pdf in (x,sample)..."
    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample)

    # Associate model with the physics state and model_ctrl with the control state
    simPdf.addPdf(model, "physics")
    simPdf.addPdf(model_ctrl, "control")

    print ">>> perform a simultaneous fit..."
    # Perform simultaneous fit of model to data and model_ctrl to data_ctrl
    simPdf.fitTo(combData)

    print "\n>>> plot model slices on data slices..."
    frame1 = x.frame(Bins(30), Title("Physics sample"))  # RooPlot
    combData.plotOn(frame1, Cut("sample==sample::physics"))

    # Plot "physics" slice of simultaneous pdf.
    # NBL You _must_ project the sample index category with data using ProjWData
    # as a RooSimultaneous makes no prediction on the shape in the index category
    # and can thus not be integrated
    simPdf.plotOn(frame1, Slice(sample, "physics"),
                  ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame1, Slice(sample, "physics"), Components("px"),
                  ProjWData(RooArgSet(sample), combData), LineStyle(kDashed))

    print "\n>>> plot control sample slices..."
    frame2 = x.frame(Bins(30), Title("Control sample"))  # RooPlot
    combData.plotOn(frame2, Cut("sample==sample::control"))
    simPdf.plotOn(frame2, Slice(sample, "control"),
                  ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame2, Slice(sample, "control"), Components("px_ctrl"),
                  ProjWData(RooArgSet(sample), combData), LineStyle(kDashed))

    print "\n>>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 1400, 600)
    canvas.Divide(2)
    canvas.cd(1)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.6)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    canvas.cd(2)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame2.GetYaxis().SetLabelOffset(0.008)
    frame2.GetYaxis().SetTitleOffset(1.6)
    frame2.GetYaxis().SetTitleSize(0.045)
    frame2.GetXaxis().SetTitleSize(0.045)
    frame2.Draw()
    canvas.SaveAs("rooFit501.png")
Example #14
0
data_fail = gauss1.generate(RooArgSet(Mkk), 4000)
combData = RooDataSet("combData", "combined data", RooArgSet(Mkk),
                      RooFit.Index(myFitCat), RooFit.Import("pass", data_pass),
                      RooFit.Import("fail", data_fail))

#FIT
totalPdf.fitTo(combData)

#PLOT
sampleSet = RooArgSet(myFitCat)
frame1 = Mkk.frame(RooFit.Bins(50), RooFit.Title("Passed sample"))

# Plot all data tagged as passed sample
combData.plotOn(frame1, RooFit.Cut("myFitCat==myFitCat::pass"))
totalPdf.plotOn(frame1, RooFit.Slice(myFitCat, "pass"),
                RooFit.ProjWData(sampleSet, combData),
                RooFit.LineStyle(kDashed))
totalPdf.paramOn(frame1, RooFit.Layout(0.55, 0.9, 0.9),
                 RooFit.Format("NEU", RooFit.AutoPrecision(1)))

# The same plot for the failled sample slice
frame2 = Mkk.frame(RooFit.Bins(50), RooFit.Title("Failed sample"))
combData.plotOn(frame2, RooFit.Cut("myFitCat==myFitCat::fail"))
totalPdf.plotOn(frame2, RooFit.Slice(myFitCat, "fail"),
                RooFit.ProjWData(sampleSet, combData))
#simPdf.plotOn(frame2, RooFit.Slice(myFitCat, "fail"), RooFit.ProjWData(sampleSet, combData), RooFit.LineStyle(kDashed))

c = TCanvas("simultaneouspdf", "simultaneouspdf", 800, 400)
c.Divide(2)
c.cd(1)
frame1.Draw()
# 2. Fit model to data
simPdf.fitTo(combined)

# 3. Create frame
frame1 = x.frame(RooFit.Bins(30), RooFit.Title("Passed sample"))
frame2 = x.frame(RooFit.Bins(30), RooFit.Title("Failed sample"))

# 4. Put data on frame
combined.plotOn(frame1, RooFit.Cut("myCat==myCat::passed"))
combined.plotOn(frame2, RooFit.Cut("myCat==myCat::failed"))

sampleSet = RooArgSet(myCat)
# 5. Put model on frame
# put one component
simPdf.plotOn(frame1, RooFit.Slice(myCat,
                                   "passed"), RooFit.Components("px_ctl"),
              RooFit.ProjWData(sampleSet, combined), RooFit.LineStyle(kDashed),
              RooFit.LineColor(kRed))
# put one component
simPdf.plotOn(frame1, RooFit.Slice(myCat,
                                   "passed"), RooFit.Components("gx_ctl"),
              RooFit.ProjWData(sampleSet, combined), RooFit.LineColor(kBlack),
              RooFit.LineStyle(kDashed))
# put whole model
simPdf.plotOn(frame2, RooFit.Slice(myCat, "failed"),
              RooFit.ProjWData(sampleSet, combined), RooFit.LineStyle(kDashed),
              RooFit.LineColor(kRed))
simPdf.paramOn(frame2, RooFit.Layout(0.55, 0.9, 0.9),
               RooFit.Format("NEU", RooFit.AutoPrecision(1)))

c = TCanvas("c", "c", 1000, 600)
c.Divide(2)