示例#1
0
 def _make_fit_model(self):
     p0 = RooRealVar("p0", "p0", 100, -10000, 10000)
     p1 = RooRealVar("p1", "p1", 100, -10000, 10000)
     p2 = RooRealVar("p2", "p2", 100, -10000, 10000)
     p3 = RooRealVar("p3", "p3", 100, -10000, 10000)
     bgd = RooPolynomial("bgd", "bgd", self.xvar,
                         RooArgList(p0, p1, p2, p3))
示例#2
0
def rooFit203():

    print ">>> setup model..."
    x = RooRealVar("x", "x", -10, 10)
    mean = RooRealVar("mean", "mean of gaussian", 0, -10, 10)
    gauss = RooGaussian("gauss", "gaussian PDF", x, mean, RooConst(1))

    # Construct px = 1 (flat in x)
    px = RooPolynomial("px", "px", x)

    # Construct model = f*gx + (1-f)px
    f = RooRealVar("f", "f", 0., 1.)
    model = RooAddPdf("model", "model", RooArgList(gauss, px), RooArgList(f))
    data = model.generate(RooArgSet(x), 10000)  # RooDataSet

    print ">>> fit to full data range..."
    result_full = model.fitTo(data, Save(kTRUE))  # RooFitResult

    print "\n>>> fit \"signal\" range..."
    # Define "signal" range in x as [-3,3]
    x.setRange("signal", -3, 3)
    result_sig = model.fitTo(data, Save(kTRUE),
                             Range("signal"))  # RooFitResult

    print "\n>>> plot and print results..."
    # Make plot frame in x and add data and fitted model
    frame1 = x.frame(Title("Fitting a sub range"))  # RooPlot
    data.plotOn(frame1, Name("data"))
    model.plotOn(frame1, Range("Full"), LineColor(kBlue),
                 Name("model"))  # Add shape in full ranged dashed
    model.plotOn(frame1, LineStyle(kDashed), LineColor(kRed),
                 Name("model2"))  # By default only fitted range is shown

    print "\n>>> result of fit on all data:"
    result_full.Print()

    print "\n>>> result of fit in in signal region (note increased error on signal fraction):"
    result_sig.Print()

    print ">>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    legend = TLegend(0.2, 0.85, 0.4, 0.65)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.14)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data", "data", 'LEP')
    legend.AddEntry("model", "fit (full range)", 'L')
    legend.AddEntry("model2", "fit (signal range)", 'L')
    legend.Draw()
    canvas.SaveAs("rooFit203.png")
示例#3
0
def RooFitHist(inputhist, title='title', path='.'):
    # RooFit.gErrorIgnoreLevel = RooFit.kInfo # <6.02
    # RooFit.SetSilentMode()# >6.02
    # RooMsgService().instance().SetSilentMode(kTRUE)
    fitbinning = array('d')
    binwidth = 200
    #NBins=(14000/binwidth) - ( (1040/binwidth) + 1 )
    NBins = (14000 / binwidth) - ((1040 / binwidth) + 1)
    for i in range(NBins + 1):
        fitbinning.append(1050 + i * binwidth)
        # print(fitbinning)

    hist = inputhist.Rebin(NBins, "fit parameter", fitbinning)
    meanstart = hist.GetBinCenter(hist.GetMaximumBin())
    sigmastart = hist.GetRMS()
    print('meanstart:', meanstart, 'sigmastart:', sigmastart)

    # inputhist.Draw()
    # hist.Draw()

    # hold=raw_input('press enter to exit.')

    gStyle.SetOptFit(1100)

    gStyle.SetOptTitle(0)
    RooFit.SumW2Error(kTRUE)

    mjj = RooRealVar('mjj', 'M_{jj-AK8}', fitbinning[0],
                     fitbinning[len(fitbinning) - 1], 'GeV')
    mjjral = RooArgList(mjj)
    dh = RooDataHist('dh', 'dh', mjjral, RooFit.Import(hist))

    shapes = {}

    #Gaussian
    gaussmean = RooRealVar('#mu_{gauss}', 'mass mean value', meanstart, 0,
                           2 * meanstart)
    gausssigma = RooRealVar('#sigma_{gauss}', 'mass resolution', sigmastart, 0,
                            2 * sigmastart)
    gauss = RooGaussian('gauss', 'gauss', mjj, gaussmean, gausssigma)
    shapes.update({'Gauss': gauss})

    #CrystalBall
    mean = RooRealVar('#mu', 'mean', meanstart, 0, 2 * meanstart)
    sigma = RooRealVar('#sigma', 'sigma', sigmastart, 0, 2 * sigmastart)
    alpha = RooRealVar('#alpha', 'Gaussian tail', -1000, 0)
    n = RooRealVar('n', 'Normalization', -1000, 1000)
    cbshape = RooCBShape('cbshape', 'crystalball PDF', mjj, mean, sigma, alpha,
                         n)
    shapes.update({'CrystalBall': cbshape})

    #Voigt
    voigtmean = RooRealVar('#mu', 'mass mean value', meanstart, 0,
                           2 * meanstart)
    voigtwidth = RooRealVar('#gamma', 'width of voigt', 0, 5000)
    voigtsigma = RooRealVar('#sigma', 'mass resolution', sigmastart, 0,
                            2 * sigmastart)
    voigt = RooVoigtian('voigt', 'voigt', mjj, voigtmean, voigtwidth,
                        voigtsigma)
    shapes.update({'Voigt': voigt})

    #BreitWigner
    bwmean = RooRealVar('#mu', 'mass mean value', meanstart, 0, 2 * meanstart)
    bwwidth = RooRealVar('#sigma', 'width of bw', sigmastart, 0,
                         2 * sigmastart)
    bw = RooBreitWigner('bw', 'bw', mjj, bwmean, bwwidth)
    shapes.update({'BreitWigner': bw})

    #Landau
    landaumean = RooRealVar('#mu_{landau}', 'mean landau', meanstart, 0,
                            2 * meanstart)
    landausigma = RooRealVar('#sigma_{landau}', 'mass resolution', sigmastart,
                             0, 2 * sigmastart)
    landau = RooLandau('landau', 'landau', mjj, landaumean, landausigma)
    shapes.update({'Landau': landau})

    #LandauGauss Convolution
    landaugauss = RooFFTConvPdf('landaugauss', 'landau x gauss', mjj, landau,
                                gauss)
    shapes.update({'LandauGauss': landaugauss})

    #Logistics
    # logisticsmean=RooRealVar('#mu_{logistics}','mean logistics',meanstart,0,2*meanstart)
    # logisticssigma= RooRealVar('#sigma_{logistics}','mass resolution',sigmastart,0,2*sigmastart)
    # logistics=RooLogistics('logistics','logistics',mjj,logisticsmean,logisticssigma)
    # shapes.update({'Logistics':logistics})

    #ExpAndGauss
    # expgaussmean=RooRealVar('#mu_{expgauss}','mean expgauss',meanstart,0,2*meanstart)
    # expgausssigma= RooRealVar('#sigma_{expgauss}','mass resolution',sigmastart,0,2*sigmastart)
    # expgausstrans= RooRealVar('trans','trans',0,100)
    # expgauss=RooExpAndGauss('expgauss','expgauss',mjj,expgaussmean,expgausssigma,expgausstrans)
    # shapes.update({'ExpAndGauss':expgauss})

    #BifurGauss
    BifurGaussmean = RooRealVar('#mu_{BifurGauss}', 'mean BifurGauss',
                                meanstart, 0, 2 * meanstart)
    BifurGausslsigma = RooRealVar('#sigma_{left}', 'mass resolution',
                                  sigmastart, 0, 2 * sigmastart)
    BifurGaussrsigma = RooRealVar('#sigma_{right}', 'mass resolution',
                                  sigmastart, 0, 2 * sigmastart)
    BifurGauss = RooBifurGauss('BifurGauss', 'BifurGauss', mjj, BifurGaussmean,
                               BifurGausslsigma, BifurGaussrsigma)
    shapes.update({'BifurGauss': BifurGauss})

    #Chebychev
    Chebychev1 = RooRealVar('c0', 'Chebychev0', -1000, 1000)
    Chebychev2 = RooRealVar('c1', 'Chebychev1', -1000, 1000)
    Chebychev3 = RooRealVar('c2', 'Chebychev2', 2, -1000, 1000)
    Chebychev = RooChebychev('Chebychev', 'Chebychev', mjj,
                             RooArgList(Chebychev1, Chebychev2, Chebychev3))
    shapes.update({'Chebychev': Chebychev})

    #Polynomial
    Polynomial1 = RooRealVar('Polynomial1', 'Polynomial1', 100, 0, 1000)
    Polynomial2 = RooRealVar('Polynomial2', 'Polynomial2', 100, 0, 1000)
    Polynomial = RooPolynomial('Polynomial', 'Polynomial', mjj,
                               RooArgList(Polynomial1, Polynomial2))
    shapes.update({'Polynomial': Polynomial})

    # mjj.setRange("FitRange",1050.,14000.)

    # for fname in ['Gauss','Logistics','BifurGauss']:
    for fname in ['BifurGauss']:

        plottitle = '%s Fit of %s' % (fname, title)
        shape = shapes[fname]
        # shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.SumW2Error(True))
        shape.fitTo(dh, RooFit.SumW2Error(True))

        frame = mjj.frame(RooFit.Title(plottitle))
        frame.GetYaxis().SetTitleOffset(2)

        dh.plotOn(frame, RooFit.MarkerStyle(4))
        shape.plotOn(frame, RooFit.LineColor(2))

        ndof = dh.numEntries() - 3

        #chiSquare legend
        chi2 = frame.chiSquare()
        probChi2 = TMath.Prob(chi2 * ndof, ndof)
        chi2 = round(chi2, 2)
        probChi2 = round(probChi2, 2)
        leg = TLegend(0.5, 0.5, 0.9, 0.65)
        leg.SetBorderSize(0)
        leg.SetFillStyle(0)
        shape.paramOn(frame, RooFit.Layout(0.5, 0.9, 0.9))
        leg.AddEntry(0, '#chi^{2} =' + str(chi2), '')
        leg.AddEntry(0, 'Prob #chi^{2} = ' + str(probChi2), '')
        leg.SetTextSize(0.04)
        frame.addObject(leg)

        canv = TCanvas(plottitle, plottitle, 700, 700)
        canv.SetLogy()
        canv.SetLeftMargin(0.20)
        canv.cd()

        frame.SetMinimum(10**(-3))

        frame.Draw()
        canv.Print(path + '/%s__%s.eps' % (title, fname))
        return chi2
示例#4
0
def buildTimePdf(config):
    """
    build time pdf, return pdf and associated data in dictionary
    """
    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])

    # start building the fit
    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))

    # start by defining observables
    time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
    qf = WS(ws, RooCategory('qf', 'final state charge'))
    qf.defineType('h+', +1)
    qf.defineType('h-', -1)
    qt = WS(ws, RooCategory('qt', 'tagging decision'))
    qt.defineType('B+', +1)
    qt.defineType('Untagged', 0)
    qt.defineType('B-', -1)

    # now other settings
    Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661))  # ps^-1
    DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106))  # ps^-1
    Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719))  # ps^-1

    # HACK (1/2): be careful about lower bound on eta, since mistagpdf below
    # is zero below a certain value - generation in accept/reject would get
    # stuck
    eta = WS(
        ws,
        RooRealVar(
            'eta', 'eta', 0.35, 0.0 if 'FIT' in config['Context'] else
            (1. + 1e-5) * max(0.0, config['TrivialMistagParams']['omega0']),
            0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))

    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance

    obs = [qt, qf, time, eta, timeerr]

    acc, accnorm = buildSplineAcceptance(
        ws, time, 'Bs2DsPi_accpetance',
        config['SplineAcceptance']['KnotPositions'],
        config['SplineAcceptance']['KnotCoefficients'][config['Context']],
        'FIT' in config['Context'])  # float for fitting
    if 'GEN' in config['Context']:
        acc = accnorm  # use normalised acceptance for generation
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)

    # build a (mock) mistag distribution
    mistagpdfparams = {}  # start with parameters of mock distribution
    for sfx in ('omega0', 'omegaavg', 'f'):
        mistagpdfparams[sfx] = WS(
            ws,
            RooRealVar('Bs2DsPi_mistagpdf_%s' % sfx,
                       'Bs2DsPi_mistagpdf_%s' % sfx,
                       config['TrivialMistagParams'][sfx]))
    # build mistag pdf itself
    mistagpdf = WS(
        ws,
        MistagDistribution('Bs2DsPi_mistagpdf', 'Bs2DsPi_mistagpdf', eta,
                           mistagpdfparams['omega0'],
                           mistagpdfparams['omegaavg'], mistagpdfparams['f']))
    # build mistag calibration
    mistagcalibparams = {}  # start with parameters of calibration
    for sfx in ('p0', 'p1', 'etaavg'):
        mistagcalibparams[sfx] = WS(
            ws,
            RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx,
                       'Bs2DsPi_mistagpdf_%s' % sfx,
                       config['MistagCalibParams'][sfx]))
    for sfx in ('p0', 'p1'):  # float calibration paramters
        mistagcalibparams[sfx].setConstant(False)
        mistagcalibparams[sfx].setError(0.1)
    # build mistag pdf itself
    omega = WS(
        ws,
        MistagCalibration('Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib', eta,
                          mistagcalibparams['p0'], mistagcalibparams['p1'],
                          mistagcalibparams['etaavg']))
    # build mock decay time error distribution (~ timeerr^6 * exp(-timerr /
    # (timerr_av / 7))
    terrpdf_shape = WS(
        ws,
        RooConstVar('timeerr_ac', 'timeerr_ac',
                    config['DecayTimeResolutionAvg'] / 7.))
    terrpdf_truth = WS(
        ws, RooTruthModel('terrpdf_truth', 'terrpdf_truth', timeerr))
    terrpdf_i0 = WS(
        ws,
        RooDecay('terrpdf_i0', 'terrpdf_i0', timeerr, terrpdf_shape,
                 terrpdf_truth, RooDecay.SingleSided))
    terrpdf_i1 = WS(
        ws,
        RooPolynomial('terrpdf_i1', 'terrpdf_i1', timeerr,
                      RooArgList(zero, zero, zero, zero, zero, zero, one), 0))
    terrpdf = WS(ws, RooProdPdf('terrpdf', 'terrpdf', terrpdf_i0, terrpdf_i1))

    # build the time pdf
    pdf = buildBDecayTimePdf(config,
                             'Bs2DsPi',
                             ws,
                             time,
                             timeerr,
                             qt,
                             qf, [[omega]], [tageff],
                             Gamma,
                             DGamma,
                             Dm,
                             C=one,
                             D=zero,
                             Dbar=zero,
                             S=zero,
                             Sbar=zero,
                             timeresmodel=resmodel,
                             acceptance=acc,
                             timeerrpdf=terrpdf,
                             mistagpdf=[mistagpdf],
                             mistagobs=eta)
    return {  # return things
        'ws': ws,
        'pdf': pdf,
        'obs': obs
    }
mumuMassE = RooRealVar("mumuMassE", "mumuMassE", 0, 10000)
tagB0 = RooRealVar("tagB0", "tagB0", 0, 2)

tagged_mass.setRange("full", 5.0, 5.6)
thevars = RooArgSet()
thevars.add(tagged_mass)
thevars.add(mumuMass)
thevars.add(mumuMassE)
thevars.add(tagB0)

fulldata = RooDataSet('fulldata', 'fulldataset', tData, RooArgSet(thevars))

## add to the data dataset a random variable, in order to scale it to desired stat
nDataEntries = fulldata.sumEntries()
randVar = RooRealVar("rand", "rand", 0, 1)
p0 = RooPolynomial("px", "px", randVar)
rDataset = p0.generate(RooArgSet(randVar), int(nDataEntries))
fulldata.merge(rDataset)

## add to the input tree the combination of the variables, to be used for the cuts on the dimuon mass
deltaB0Mfunc = RooFormulaVar("deltaB0M", "deltaB0M", "@0 - @1",
                             RooArgList(tagged_mass, B0Mass))
deltaJMfunc = RooFormulaVar("deltaJpsiM", "deltaJpsiM", "@0 - @1",
                            RooArgList(mumuMass, JPsiMass))
deltaPMfunc = RooFormulaVar("deltaPsiPM", "deltaPsiPM", "@0 - @1",
                            RooArgList(mumuMass, PsiPMass))
deltaB0M = fulldata.addColumn(deltaB0Mfunc)
deltaJpsiM = fulldata.addColumn(deltaJMfunc)
deltaPsiPM = fulldata.addColumn(deltaPMfunc)

thevars.add(deltaB0M)
示例#6
0
def RooFitHist(inputhist,title='title',path='.'):
   # RooFit.gErrorIgnoreLevel = RooFit.kInfo # <6.02
   # RooFit.SetSilentMode()# >6.02
   # RooMsgService().instance().SetSilentMode(kTRUE)

   fitbinning=array('d')
   binwidth=200
   #NBins=(14000/binwidth) - ( (1040/binwidth) + 1 ) Mjj
   NBins=(8000/binwidth) - ( (200/binwidth)+1 )#pT
   for i in range(NBins+1):
      fitbinning.append(210+i*binwidth)# Mjj 1050
   #   print(fitbinning)

   #import numpy as np
   #fitbinning=np.linspace(0,8000,81)
  

   hist=inputhist.Rebin(NBins,"fit parameter",fitbinning) 
   #hist=inputhist.Rebin(80,"fit parameter", fitbinning)
   #meanstart=hist.GetBinCenter(2000)
   meanstart=hist.GetBinCenter(hist.GetMaximumBin())#maximum
   sigmastart=hist.GetRMS()
   #sigmastart=3000
   print('meanstart:',meanstart,'sigmastart:',sigmastart)
   # inputhist.Draw()  
   # hist.Draw()

   # hold=raw_input('press enter to exit.')
   gStyle.SetOptFit(1111)
   gStyle.SetOptTitle(0)

   RooFit.SumW2Error(kTRUE)
   RooFit.Extended(kTRUE)

   # RooDataHist::adjustBinning(dh): fit range of variable mjj expanded to nearest bin boundaries: [1050,13850] --> [1050,13850]
   mjj=RooRealVar('mjj','P_{T-AK8}',fitbinning[0],fitbinning[len(fitbinning)-1],'GeV')
   mjjral=RooArgList(mjj)
   dh=RooDataHist('dh','dh',mjjral,RooFit.Import(hist))
   #shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.Extended(True),RooFit.SumW2Error(False))

   shapes={}
   #Gaussian not really
   # 3rd, 4th and 5th arguments are: (starting value, minimum possible value, maximum possible value) -- not goot
   gaussmean = RooRealVar('#mu_{gauss}','mass mean value',meanstart,0,2*meanstart)
   gausssigma= RooRealVar('#sigma_{gauss}','mass resolution',sigmastart,0,2*meanstart)            
   gauss=RooGaussian('gauss','gauss',mjj,gaussmean,gausssigma)
   shapes.update({'Gauss':gauss})

   #poisson
   poissonmean = RooRealVar('#mu_{poisson}', 'pT mean value', meanstart,0,2*meanstart)
   poissonsigma = RooRealVar('#sigma_{poisson]', 'pT resolution', sigmastart, 0, 2*sigmastart)
   poisson = RooPoisson('poisson', 'poisson', mjj, poissonmean, False)
   shapes.update({'Poisson': poisson})

   #Landau -- not good
   landaumean=RooRealVar('#mu_{landau}','mean landau',meanstart,0,2*meanstart)
   landausigma= RooRealVar('#sigma_{landau}','mass resolution',sigmastart,0,2*sigmastart)#bzw8
   landau=RooLandau('landau','landau',mjj,landaumean,landausigma)
   shapes.update({'Landau':landau})

   #CrystalBall -> this is close to be good but matrix error :( 
   mean = RooRealVar('#mu','mean',meanstart,0,2*meanstart)
   sigma= RooRealVar('#sigma','sigma',sigmastart,0,2*sigmastart)
   alpha=RooRealVar('#alpha','Gaussian tail',-1000,0)
   n=RooRealVar('n','Normalization',-1000,1000)            
   cbshape=RooCBShape('cbshape','crystalball PDF',mjj,mean,sigma,alpha,n)
   shapes.update({'CrystalBall':cbshape})

   #Voigt ---pff
   voigtmean = RooRealVar('#mu','mass mean value',meanstart,0,2*meanstart)
   voigtwidth = RooRealVar('#gamma','width of voigt',0,100)
   voigtsigma= RooRealVar('#sigma','mass resolution',sigmastart,0,150)
   voigt=RooVoigtian('voigt','voigt',mjj,voigtmean,voigtwidth,voigtsigma)
   shapes.update({'Voigt':voigt})

   #BreitWigner--worst
   bwmean = RooRealVar('#mu','mass mean value',meanstart,0,2*meanstart)
   bwwidth = RooRealVar('#sigma','width of bw',sigmastart,100, 150)            
   bw=RooBreitWigner('bw','bw',mjj,bwmean,bwwidth)
   shapes.update({'BreitWigner':bw})

   #Logistics
   #logisticsmean=RooRealVar('#mu_{logistics}','mean logistics',meanstart,0,2*meanstart)
   #logisticssigma= RooRealVar('#sigma_{logistics}','mass resolution',sigmastart,0,2*sigmastart)
   #logistics=RooLogistics('logistics','logistics',mjj,logisticsmean,logisticssigma)
   #shapes.update({'Logistics':logistics})

   #ExpAndGauss
   expgaussmean=RooRealVar('#mu_{expgauss}','mean expgauss',meanstart,490,900)
   expgausssigma= RooRealVar('#sigma_{expgauss}','mass resolution',sigmastart,20,3*sigmastart)
   expgausstrans= RooRealVar('trans','trans',0,1000)
   ExpAndGauss=RooExpAndGauss('expgauss','expgauss',mjj,expgaussmean,expgausssigma,expgausstrans)
   shapes.update({'ExpAndGauss':ExpAndGauss})
   

   #Exp
   #expmean=RooRealVar('')

   #BifurGauss -bad
   BifurGaussmean=RooRealVar('#mu_{BifurGauss}','mean BifurGauss',meanstart,0,2*meanstart)
   BifurGausslsigma= RooRealVar('#sigma_{left}','mass resolution',sigmastart,200,2*sigmastart)#2*sigmastart
   BifurGaussrsigma= RooRealVar('#sigma_{right}','mass resolution',sigmastart,200,2*sigmastart)
   BifurGauss=RooBifurGauss('BifurGauss','BifurGauss',mjj,BifurGaussmean,BifurGausslsigma,BifurGaussrsigma)
   shapes.update({'BifurGauss':BifurGauss})

   #Chebychev -nope
   Chebychev1=RooRealVar('c0','Chebychev0',-1000,1000)
   Chebychev2= RooRealVar('c1','Chebychev1',-1000,1000)        
   Chebychev3= RooRealVar('c2','Chebychev2',2,-1000,1000)        
   Chebychev=RooChebychev('Chebychev','Chebychev',mjj,RooArgList(Chebychev1,Chebychev2,Chebychev3))
   shapes.update({'Chebychev':Chebychev})

   #Polynomial -nope
   Polynomial1=RooRealVar('Polynomial1','Polynomial1',100,0,1000)
   Polynomial2= RooRealVar('Polynomial2','Polynomial2',100,0,1000)
   Polynomial=RooPolynomial('Polynomial','Polynomial',mjj,RooArgList(Polynomial1,Polynomial2))
   shapes.update({'Polynomial':Polynomial})

   #pareto
   
   #___________________________________________________________We will see
   #Convolutions 
   #-> use bin > 1000 for better accuracy  -----cyclic trouble 
   #-> Convolution depends on order!!!  RooFFTConvPdf the first p.d.f. is the theory model and that the second p.d.f. is the resolution model
   #
   #LandauGauss Convolution  - really bad                   
   landaugauss=RooFFTConvPdf('landaugauss','landau x gauss',mjj,landau, gauss) 
   #landaugauss.setBufferFraction(126)           
   shapes.update({'LandauGauss':landaugauss})

   #GaussLandau Convolution -> Better but NOT posdef. ...but for 100 it is
   gausslandau=RooFFTConvPdf('gausslandau','gauss x landau ',mjj,gauss,landau)  
   #gausslandau.setBufferFraction(126)          
   shapes.update({'GaussLandau':gausslandau})
   
   #CrystalBallLandau Convolution  cbshape x landau looks better -> status failed 
   crystlandau=RooFFTConvPdf('crystallandau','cbshape x landau', mjj, landau, cbshape)
   crystlandau.setBufferFraction(39)
   shapes.update({'CrystLandau': crystlandau})

   #BifurGaussLandau Convolution -> Better in look, NO matrix error for Binwidth 200
   BifurGaussLandau=RooFFTConvPdf('bifurgausslandau','landau x bifurgauss',mjj,landau, BifurGauss)   
   BifurGaussLandau.setBufferFraction(39) #against over cycling        
   shapes.update({'BifurGaussLandau':BifurGaussLandau})

   #CrystalGauss Convolution   looks better -> status failed 
   crystgauss=RooFFTConvPdf('crystalgauss','cbshape x gauss', mjj, cbshape, gauss)
   #crystgauss.setBufferFraction(39)
   shapes.update({'CrystGauss': crystgauss})

   #BreitWignerLandau Convolution (Breitwigner = Lorentz)-> status OK....
   BreitWignerLandau=RooFFTConvPdf('breitwignerlandau','breitwigner x landau',mjj,landau,bw,3)
   #BreitWignerLandau.setBufferFraction(48) #setBufferFraction(fraction of the sampling array size) ->cyclic behaviour fix
   #crystgauss.setShift(0,0)
   #s1 and s2 are the amounts by which the sampling ranges for pdf's are shifted respectively  
   #(0,-(xmin+xmax)/2) replicates the default behavior
   #(0,0) disables the shifting feature altogether        
   shapes.update({'BreitWignerLandau':BreitWignerLandau}) 


   for fname in ['ExpAndGauss']:    
      plottitle='%s Fit of %s'%(fname,title)
      shape=shapes[fname]
     # shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.SumW2Error(True))
      #shape.fitTo(dh,RooFit.Extended(True),RooFit.SumW2Error(True))
      mjj.setRange("FitRange",500,4000)#tried
      shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.Extended(False),RooFit.SumW2Error(True))
     

      frame=mjj.frame(RooFit.Title(plottitle))
      #frame.GetYaxis().SetTitleOffset(2)

      dh.plotOn(frame,RooFit.MarkerStyle(4))
      shape.plotOn(frame,RooFit.LineColor(2))

      ndof=dh.numEntries()-3      

      print ('ndof', ndof)
      
      #chiSquare legend
      chi2 = frame.chiSquare()#there are 2 chiSquare. the 2cond returns chi2/ndf /// \return \f$ \chi^2 / \mathrm{ndf} \f$
      print ('chi2', chi2)
      probChi2 = TMath.Prob(chi2*ndof, ndof)# why chi2*ndof ?! makes no sense to me

      #Double_t Prob(Double_t chi2, Int_t ndf)
      #Computation of the probability for a certain Chi-squared (chi2)
      #and number of degrees of freedom (ndf).

      #P(a,x) represents the probability that the observed Chi-squared
      #for a correct model should be less than the value chi2.

      #The returned probability corresponds to 1-P(a,x),                !!!!
      #which denotes the probability that an observed Chi-squared exceeds
      #the value chi2 by chance, even for a correct model.
      #--- NvE 14-nov-1998 UU-SAP Utrecht

      #probChi2=TMath.Prob(chi2, ndof)
      chi2 = round(chi2,2)
      #probChi2 = round(probChi2,2)
      leg = TLegend(0.5,0.5,0.5,0.65)#0.9
      leg.SetBorderSize(0)
      leg.SetFillStyle(0)
      shape.paramOn(frame, RooFit.Layout(0.5,0.9,0.9))
      leg.AddEntry(0,'#chi^{2} ='+str(chi2),'')
      leg.AddEntry(0,'Prob #chi^{2} = '+str(probChi2),'')
      leg.SetTextSize(0.04)
      frame.addObject(leg)
      
      canv=TCanvas(plottitle,plottitle,700,700)
      canv.SetLogy()
      canv.SetLeftMargin(0.20) 
      canv.cd()
 
      frame.SetMaximum(10**(1))
      frame.SetMinimum(10**(-11))#from -3 -> -6
      frame.Draw()
      #canv.Print(path+'/%s__%sS2MoreLessY.pdf'%(title,fname))
      raw_input('press enter to continue')
      return chi2
def fitData(fulldata, ibin, w):

    cut  = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)'%(q2binning[ibin], q2binning[ibin+1])
    data = fulldata.reduce(RooArgSet(tagged_mass,mumuMass,mumuMassE), cut)

    nrt_mc = _getFittedVar("nRT_%s"%ibin, w)
    nwt_mc = _getFittedVar("nWT_%s"%ibin, w)
    fraction = nrt_mc / (nrt_mc + nwt_mc)
    print 'mistag fraction on MC for bin ', ibin , ' : ' , fraction.n , '+/-', fraction.s 
    
    ### creating RT component
    w.loadSnapshot("reference_fit_RT_%s"%ibin)
    mean_rt      = w.var("mean^{RT%s}"%ibin)
    sigma_rt1    = w.var("#sigma_{RT1}^{%s}"%ibin)

    sigma_rt2 = RooRealVar()
    alpha_rt1 = RooRealVar()
    alpha_rt2 = RooRealVar()
    n_rt1     = RooRealVar()
    n_rt2     = RooRealVar()
    f1rt     = RooRealVar()

    ## double cb fast
    if ibin < 4:
        alpha_rt1    = w.var("#alpha_{RT1}^{%s}"%ibin)
        alpha_rt2    = w.var("#alpha_{RT2}^{%s}"%ibin)
        n_rt1        = w.var("n_{RT1}^{%s}"%ibin)
        n_rt2        = w.var("n_{RT2}^{%s}"%ibin)

    ## double cb old
    else:
        sigma_rt2    = w.var("#sigma_{RT2}^{%s}"%ibin)
        alpha_rt1    = w.var("#alpha_{RT1}^{%s}"%ibin)
        alpha_rt2    = w.var("#alpha_{RT2}^{%s}"%ibin)
        n_rt1        = w.var("n_{RT1}^{%s}"%ibin)
        n_rt2        = w.var("n_{RT2}^{%s}"%ibin)
        f1rt        = w.var("f^{RT%s}"%ibin)

    theRTgauss  = w.pdf("doublecb_RT%s"%ibin)   

    ### creating WT component
    w.loadSnapshot("reference_fit_WT_%s"%ibin)
    mean_wt      = w.var("mean_{WT}^{%s}"%ibin)
    sigma_wt     = w.var("#sigma_{WT1}^{%s}"%ibin)
    alpha_wt1    = w.var("#alpha_{WT1}^{%s}"%ibin)
    alpha_wt2    = w.var("#alpha_{WT2}^{%s}"%ibin)
    n_wt1        = w.var("n_{WT1}^{%s}"%ibin)
    n_wt2        = w.var("n_{WT2}^{%s}"%ibin)
    theWTgauss  = w.pdf("doublecb_%s"%ibin)   

    ### creating variable for the difference between the two peaks
    deltaPeaks = RooFormulaVar("deltaPeaks%s"%ibin, "@0 - @1", RooArgList(mean_rt, mean_wt))  
    frt              = RooRealVar ("F_{RT}%s"%ibin   , "frt"             , fraction.n , 0, 1)
    signalFunction   = RooAddPdf  ("sumgaus%s"%ibin  , "rt+wt"           , RooArgList(theRTgauss,theWTgauss), RooArgList(frt))

    ### now create background parametrization
    slope         = RooRealVar    ("slope_%s"%ibin   , "slope"           ,    0.5,   -10, 10);
    bkg_exp       = RooExponential("bkg_exp%s"%ibin , "exponential"     ,  slope,   tagged_mass  );
    pol_c1        = RooRealVar    ("p1_%s"%ibin      , "coeff x^0 term"  ,    0.5,   -10, 10);
    pol_c2        = RooRealVar    ("p2_%s"%ibin      , "coeff x^1 term"  ,    0.5,   -10, 10);
    bkg_pol       = RooPolynomial ("bkg_pol%s"%ibin  , "2nd order pol"   ,  tagged_mass, RooArgList(pol_c1, pol_c2));

    fsig          = RooRealVar("fsig%s"%ibin   , "fsig"    ,     0.9,     0,   1);
#     nsig          = RooRealVar("Yield%s"%ibin  , "signal frac"    ,     1000,     0,   10000);
#     nbkg          = RooRealVar("nbkg%s"%ibin   , "bkg fraction"   ,     1000,     0,   500000);
    nsig        = RooRealVar("Yield"         , "signal frac"   ,   600000,     0,   5000000);
    nbkg        = RooRealVar("nbkg"          , "bkg fraction"  ,   100000,     0,   2000000);

#     if ibin==4:  
#         nsig.setRange(500000,1500000)
#         nsig.setVal(900000)
#         nbkg.setRange(80000,1000000)
#         nbkg.setVal(100000)


    ### creating constraints
    c_vars = RooArgSet()
    c_pdfs = RooArgSet()

    c_sigma_rt1   = _constrainVar(sigma_rt1, 1)
    c_alpha_rt1   = _constrainVar(alpha_rt1, 1)
    c_alpha_rt2   = _constrainVar(alpha_rt2, 1)
    c_n_rt1       = _constrainVar(n_rt1, 1)
    c_n_rt2       = _constrainVar(n_rt2, 1)

    c_sigma_wt    = _constrainVar(sigma_wt,  1)
    c_alpha_wt1   = _constrainVar(alpha_wt1, 1)
    c_alpha_wt2   = _constrainVar(alpha_wt2, 1)
    c_n_wt1       = _constrainVar(n_wt1, 1)
    c_n_wt2       = _constrainVar(n_wt2, 1)


    if ibin < 4:
        c_pdfs = RooArgSet(c_sigma_rt1, c_alpha_rt1, c_alpha_rt2, c_n_rt1, c_n_rt2)
        c_vars = RooArgSet(sigma_rt1,     alpha_rt1,   alpha_rt2,   n_rt1,   n_rt2)
    else:
        c_sigma_rt2   = _constrainVar(sigma_rt2, 1)
        c_pdfs = RooArgSet(c_sigma_rt1, c_sigma_rt2, c_alpha_rt1, c_alpha_rt2, c_n_rt1, c_n_rt2)
        c_vars = RooArgSet(  sigma_rt1,   sigma_rt2,   alpha_rt1,   alpha_rt2,   n_rt1,   n_rt2)
    
    c_pdfs.add(c_sigma_wt);  c_vars.add(sigma_wt)
    c_pdfs.add(c_alpha_wt1); c_vars.add(alpha_wt1)
    c_pdfs.add(c_alpha_wt2); c_vars.add(alpha_wt2)
    c_pdfs.add(c_n_wt1);     c_vars.add(n_wt1)
    c_pdfs.add(c_n_wt2);     c_vars.add(n_wt2)

    c_deltaPeaks = RooGaussian("c_deltaPeaks%s"%ibin , "c_deltaPeaks", deltaPeaks, ROOT.RooFit.RooConst( deltaPeaks.getVal() ), 
                                ROOT.RooFit.RooConst( 0.0005 )  ## value to be checked
                                ) 
    c_pdfs.add(c_deltaPeaks)
    c_vars.add(deltaPeaks)
    c_frt            = RooGaussian("c_frt%s"%ibin    , "c_frt"           , frt,  ROOT.RooFit.RooConst(fraction.n) , ROOT.RooFit.RooConst(frt_sigma[ibin]) )
    c_pdfs.add(c_frt)
    c_vars.add(frt)
    
    constr_list = RooArgList(c_pdfs)
    constr_list.add(signalFunction)
    c_signalFunction = RooProdPdf ("c_signalFunction", "c_signalFunction", constr_list)     

#     mean        = RooRealVar ("mass"         , "mean"          ,  B0Mass_,   3,    7, "GeV")
#     sigma       = RooRealVar ("#sigma_{1}"   , "sigma"         ,  0.028,     0,   10, "GeV")
#     signalGauss = RooGaussian("signalGauss"  , "signal gauss"  ,  tagged_mass,  mean,sigma)
#     
#     sigma2       = RooRealVar ("#sigma_{2}"    , "sigma2"         ,  0.048,     0,   0.07, "GeV")
#     signalGauss2 = RooGaussian("signalGauss2"  , "signal gauss2"  ,  tagged_mass,  mean,sigma2)
#     f1           = RooRealVar ("f1"            , "f1"             ,  0.8  ,     0.,   1.)
#     gaus         = RooAddPdf  ("gaus"          , "gaus1+gaus2"    , RooArgList(signalGauss,signalGauss2), RooArgList(f1))
    
#     pol_c1      = RooRealVar ("p1"           , "coeff x^0 term",    0.5,   -10, 10);
#     pol_c2      = RooRealVar ("p2"           , "coeff x^1 term",    0.5,   -10, 10);
#     pol_c3      = RooRealVar ("p3"           , "coeff x^2 term",    0.5,   -10, 10);
#     slope       = RooRealVar ("slope"        , "slope"         ,    0.5,   -10, 10);
#     bkg_exp     = RooExponential("bkg_exp"   , "exponential"   ,  slope,   tagged_mass  );
#     bkg_pol     = RooChebychev("bkg_pol"     , "2nd order pol" ,  tagged_mass, RooArgList(pol_c1,pol_c2));

    fitFunction = RooAddPdf ("fitfunction%s"%ibin , "fit function"  ,  RooArgList(c_signalFunction, bkg_exp), RooArgList(nsig, nbkg))
    
#     r = fitFunction.fitTo(data, 
# #                           RooFit.Extended(True), 
#                           RooFit.Range("full"), 
#                           ROOT.RooFit.Constrain(c_vars),
#                           ROOT.RooFit.Minimizer("Minuit2","migrad"),
#                           ROOT.RooFit.Hesse(True),
#                           ROOT.RooFit.Strategy(2),
#                           ROOT.RooFit.Minos(False),
#                          )
    print 'fit with Hesse strategy 2 done, now Minos'    
    r = fitFunction.fitTo(data, 
                          RooFit.Extended(True), 
                          RooFit.Save(), 
                          RooFit.Range("full"), 
                          RooFit.Verbose(False),
                          ROOT.RooFit.Constrain(c_vars),
#                           ROOT.RooFit.Minimizer("Minuit2","migrad"),
#                           ROOT.RooFit.Hesse(True),
#                           ROOT.RooFit.Strategy(2),
#                           ROOT.RooFit.Minos(False),
                         )

    r.Print()
    r.correlationMatrix().Print()
    fitStats['data%s'%(ibin)] = r.status()
    covStats['data%s'%(ibin)] = r.covQual()
    frame = tagged_mass.frame( RooFit.Range("full") )
    data.plotOn(frame, RooFit.Binning(nbins), RooFit.MarkerSize(.7))
    fitFunction.plotOn(frame, RooFit.NormRange("full"), RooFit.Range("full"))

    ## evaluate sort of chi2 and save number of RT/WT events
    observables = RooArgSet(tagged_mass)
    flparams = fitFunction.getParameters(observables)
    nparam = int(flparams.selectByAttrib("Constant",ROOT.kFALSE).getSize())
    pdfstring = "fitfunction%s_Norm[tagged_mass]_Range[full]_NormRange[full]"%ibin
    chi2s['data%s'%ibin] = frame.chiSquare(pdfstring, "h_fulldata",  nparam)
    frame. addObject(_writeChi2( chi2s['data%s'%ibin] ))

    drawPdfComponents(fitFunction, frame, ROOT.kAzure, RooFit.NormRange("full"), RooFit.Range("full"), isData = True)
#     fitFunction.paramOn(frame, RooFit.Layout(0.62,0.86,0.89))

    parList = RooArgSet (nsig, mean_rt, sigma_rt, alpha_rt1, alpha_rt2, n_rt1, n_rt2, mean_wt, sigma_wt)
#     parList.add(alphawt1)
#     parList.add(alphawt2)
#     parList.add(nwt1)
#     parList.add(nwt2)
    parList.add(frt)
    fitFunction.paramOn(frame, RooFit.Parameters(parList), RooFit.Layout(0.62,0.86,0.89))

    frame.Draw()
    niceFrame(frame, '')
    frame. addObject(_writeFitStatus(r))

    c1 = ROOT.TCanvas() 
    upperPad = ROOT.TPad('upperPad' , 'upperPad' , 0., 0.35 , 1.,  1.    )  
    lowerPad = ROOT.TPad('lowerPad' , 'lowerPad' , 0., 0.0  , 1.,  0.345 )  
    upperPad.SetBottomMargin(0.012)
    lowerPad.SetTopMargin(0)
    lowerPad.SetBottomMargin(0.2)

    upperPad.Draw(); lowerPad.Draw()
    upperPad.cd()
    frame.Draw()
    if not args.year=='test':  writeCMS(frame, args.year, [ q2binning[ibin], q2binning[ibin+1] ], 0)
    frame.Draw()

    ## add plot of pulls
    lowerPad.cd()
    hpull = frame.pullHist("h_fulldata", pdfstring)
    frame2 =  tagged_mass.frame(RooFit.Range("full"), RooFit.Title(''))
    frame2.addPlotable(hpull,"P") 
    niceFrameLowerPad(frame2, 'pull')
    frame2.Draw()
    line = ROOT.TLine(5.0,1,5.6,1)
    line.SetLineColor(ROOT.kGreen+3)
    line.Draw()

    for ilog in [True,False]:
        upperPad.SetLogy(ilog)
        c1.SaveAs('fit_results_mass/save_fit_data_%s_%s_LMNR_Update%s_newSigmaFRT_pars_Jpsi.pdf'%(ibin, args.year, '_logScale'*ilog))


    out_f.cd()
    r.Write('results_data_%s'%(ibin))

    params = fitFunction.getParameters(RooArgSet(tagged_mass)) 
    out_w.saveSnapshot("reference_fit_data_%s"%(ibin),params,ROOT.kTRUE) 
    getattr(out_w, 'import')(fitFunction)
示例#8
0
x = RooRealVar("x","x", 50, 150);
x.setBins(100)

nsig = 1000
ysig = 1
ybgd = 8 * ysig
ndata = nsig * (1 + ybgd / ysig) 

######### underlying model 

mean = RooRealVar("mean","mean", 125, 100, 150);
sigma = RooRealVar("sigma","sigma", 2, 0, 10);

sig = RooGaussian("sig", "sig", x, mean, sigma)
bgd = RooPolynomial("bgd", "bgd", x)               

c1 = TCanvas()

pframe = x.frame() 
sig.plotOn(pframe)
bgd.plotOn(pframe)
pframe.Draw()

vysig = RooRealVar("nsig", 'nsig', ysig, 0, 100000)
vybgd = RooRealVar("nbgd", 'nbgd', ybgd, 0, 100000)
model = RooAddPdf("model", "model", RooArgList(sig, bgd),
                  RooArgList(vysig, vybgd))
#model = RooAddPdf("model", "model", RooArgList(sig),
#                  RooArgList(vysig))
示例#9
0
def fit_mbc():
    from tools import normalizedRooFitIntegral, RooFitIntegral
    from ROOT import RooRealVar, RooDataSet, RooArgList, RooArgSet, \
         RooGaussian, RooArgusBG, RooCBShape, RooAddPdf, RooPolynomial, \
         RooDataHist, RooFit, kTRUE, kFALSE

    signal_margins = [1.86, 1.87]
    sb_margins = [1.84, 1.85]

    # Right here we compute background yield
    mbc = RooRealVar('mbc', 'mbc', 1.83, 1.89, 'GeV')
    arg_cutoff = RooRealVar('arg_cutoff', 'Argus cutoff', 1.8869, 1.885, 1.888, 'GeV')
    arg_slope = RooRealVar('arg_slope', 'Argus slope', -13, -100, -1)
    mbc_d0 = RooRealVar('mbc_d0', 'D0 Mbc', 1.8647, 'GeV')
    mbc_dp = RooRealVar('mbc_dp', 'D+ Mbc', 1.8694, 'GeV')
    mbc_float = RooRealVar('mbc_float', 'Floating D mass', 1.869, 1.855, 1.875, 'GeV')
    sigma = RooRealVar('sigma', 'D width', 0.00145, 0.0001, 0.0025, 'GeV')
    sigma2 = RooRealVar('sigma2', 'CB width', 0.00145, 0.0001, 0.005,
                        'GeV')
    alpha = RooRealVar('alpha', 'CB shape cutoff', -1.515, -2., 2)
    n = RooRealVar('n', 'CB tail parameter', 6, 0, 20)
    gauss_d0 = RooGaussian('gauss_d0', 'D0 gaussian', mbc, mbc_d0, sigma2)
    gauss_dp = RooGaussian('gauss_dp', 'D+ gaussian', mbc, mbc_dp, sigma2)
    gauss_float = RooGaussian('gauss_float', 'Floating gaussian',
                                                    mbc, mbc_float, sigma2)
    cb_d0 = RooCBShape('cb_d0', 'D0 Crystal Barrel', mbc,
                   mbc_d0, sigma, alpha, n)
    cb_dp = RooCBShape('cb_dp', 'D+ Crystal Barrel', mbc,
                       mbc_dp, sigma, alpha, n)
    cb_float = RooCBShape('cb_float', 'Floating Crystal Barrel', mbc,
                          mbc_float, sigma, alpha, n)
    argus = RooArgusBG('argus', 'Argus BG', mbc, arg_cutoff, arg_slope)
    yld = RooRealVar('yield', 'D yield', 25700, 0, 100000)
    yld2 = RooRealVar('yield2', '2nd yield', 100, 0, 2000)
    bkg = RooRealVar('bkg', 'Background', 1300, 0, 40000)
    a = RooRealVar('a', 'Norm', 1)
    poly = RooPolynomial('poly', 'poly PDF', mbc, RooArgList(a), 0)
    sumpdf_d0 = RooAddPdf('sumpdf_d0', 'D0 sum pdf',
                          RooArgList(cb_d0, argus),
                          RooArgList(yld, bkg))
    sumpdf_dp = RooAddPdf('sumpdf_dp', 'Dp sum pdf',
                          RooArgList(cb_dp, argus),
                          RooArgList(yld, bkg))
    sumpdf_float = RooAddPdf('sumpdf_float', 'Generic D sum pdf',
                             RooArgList(cb_float, argus),
                             RooArgList(yld, bkg))

    width_modes = { '0': 0.00150, '1': 0.001831, '3': 0.001426, '200': 0.001387,
                    '202': 0.001407 }

    n_modes = { '0': 2.68, '1': 4.06, '3': 4.34, '200': 4.05, '202': 5.26 }
    alpha_modes = { '0': -1.6145, '1': -1.4562, '3': -1.5834, '200': -1.6538,
                    '202': -1.5598 }


    pdf = sumpdf_float


    sigma.setVal(width_modes['1']) # sigma.setConstant()


    n.setVal(n_modes['1']) #n.setConstant()

    alpha.setVal(alpha_modes['1']) #alpha.setConstant()
    #sigma.setConstant()
    #arg_cutoff.setVal(1.8865); #arg_cutoff.setConstant()

    c1.Divide(1,2)
    c1.cd(1)
    dset = RooDataHist('dsetmc', 'title', RooArgList(mbc), h_mbc['mc'])

    #pdf.fitTo(dset, 'eq')
    Extended = RooFit.Extended(kTRUE) # e
    Verbose = RooFit.Verbose(kFALSE) #q

    pdf.fitTo(dset, Extended, Verbose)

    # xframe = mbc.frame()
    # dset.plotOn(xframe)
    # pdf.plotOn(xframe)
    # pdf.paramOn(xframe,dset)
    # xframe.SetTitle('Fake type 1, MC')
    # xframe.Draw()
    c1.cd(2)
    dset = RooDataHist('dsetdata', 'title', RooArgList(mbc), h_mbc['data'])
    #pdf.fitTo(dset, 'eq')
    pdf.fitTo(dset, Extended, Verbose)
    # xframe = mbc.frame()
    # dset.plotOn(xframe)
    # pdf.plotOn(xframe)
    # pdf.paramOn(xframe,dset)
    # xframe.SetTitle('Fake type 1, data')
    # xframe.Draw()
    sb_scale = (normalizedRooFitIntegral(argus, mbc, signal_margins[0],
                                         signal_margins[1])/
                normalizedRooFitIntegral(argus, mbc, sb_margins[0], sb_margins[1]))
示例#10
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')
# Create model for physics sample
# -------------------------------------------------------------

# Create observables
x = RooRealVar("x", "x", -5.05, 5.05)
y = RooRealVar("y", "y", 0, 1)
# Construct signal pdf
mean = RooRealVar("mean", "mean", 0, -5, 5)
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 = RooPolynomial("px", "px", x, RooArgList(a0, a1), 1)

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

# Create model for control sample
# --------------------------------------------------------------

# Construct signal pdf.
# NOTE that sigma is shared with the signal sample model
mean_ctl = RooRealVar("mean_ctl", "mean_ctl", -3, -5, 5)
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)