Exemplo n.º 1
0
def make_weighted_dataset(subproc,ws,tree,mc_events):
    data = RooDataSet('%s_shape_data'%subproc,
                      'M_{ll#gamma} Shape Data for %s'%subproc,
                      tree,
                      ws.set('vars_with_weights')                      
                      )

    mc_yield_var = RooConstVar('temp','temp',mc_events)
    weighter = RooFormulaVar('weight','weight','@0*@1/@2',
                             RooArgList( ws.var('procWeight'),
                                         ws.var('puWeight'),
                                         mc_yield_var )
                             )
    data.addColumn(weighter)

    data_total_weight = RooDataSet('%s_shape_data'%subproc,
                                   'M_{ll#gamma} Shape Data for %s'%subproc,
                                   data,
                                   ws.set('vars_with_weights_final'),
                                   '','weight')

    data_pu_weight = RooDataSet('%s_shape_data_puonly'%subproc,
                                'M_{ll#gamma} Shape Data for %s'%subproc,
                                data,
                                ws.set('vars_with_weights_final'),
                                '','puWeight')
    
    return data_total_weight, data_pu_weight
Exemplo n.º 2
0
    def __init__(self,name,inhist,binning,constant=False,forcePositive=True):
        '''Represents a binned distribution as a group of RooRealVar parameters.
        If constant == False, each bin is considered an unconstrained parameter of the model.

        Args:
            name (str): Unique name for the new object.
            inhist (TH2): Input 2D histogram to build set of variables.
            binning (Binning): Binning object used to create LOW, SIG, HIGH regions along X axis.
            constant (bool, optional): If true, use RooConstVars for bins. Defaults to False and RooRealVars are used.
            forcePositive (bool, optional). Defaults to True in which case the bin values will be lower bound by 1e-9
                and any shape templates will asymptotically approach zero as the associated nuisance increases/decreases.
        '''
        super(BinnedDistribution,self).__init__(name,binning,forcePositive=forcePositive)
        for cat in _subspace:
            cat_name = name+'_'+cat
            cat_hist = copy_hist_with_new_bins(cat_name,'X',inhist,self.binning.xbinByCat[cat])
            for ybin in range(1,cat_hist.GetNbinsY()+1):
                for xbin in range(1,cat_hist.GetNbinsX()+1):
                    bin_name = '%s_bin_%s-%s'%(cat_name,xbin,ybin)
                    if constant or self._nSurroundingZeros(cat_hist,xbin,ybin) > 7:
                        self.binVars[bin_name] = RooConstVar(bin_name, bin_name, cat_hist.GetBinContent(xbin,ybin))
                    else:
                        self.binVars[bin_name] = RooRealVar(bin_name, bin_name, max(5,cat_hist.GetBinContent(xbin,ybin)), 1e-6, 1e6)
                        self.nuisances.append({'name':bin_name, 'constraint':'flatParam', 'obj': self.binVars[bin_name]})
                    self._varStorage.append(self.binVars[bin_name]) # For safety if we add shape templates            
Exemplo n.º 3
0
def buildTimePdf(config, tupleDataSet, tupleDict):

    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])

    ws = RooWorkspace('ws_%s' % config['Context'])
    one = WS(ws, RooConstVar('one', '1', 1.0))
    zero = WS(ws, RooConstVar('zero', '0', 0.0))
    ###USE FIT CONTEXT
    """
    build time pdf, return pdf and associated data in dictionary
    """
    # start by defining observables
    time = WS(ws,
              tupleDataSet.get().find('ct'))
    #qt = WS(ws, tupleDataSet.get().find('ssDecision'));
    '''
    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
    if 'GEN' in config['Context'] or 'FIT' in config['Context']:
        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))

    mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
    terrpdf = WS(ws,
                 tupleDataSet.get().find('cterr'))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100))
    #MISTAGPDF
    # fit average mistag
    # add mistagged
    #ge rid of untagged events by putting restriction on qf or something when reduceing ds
    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance

    obs = [qf, qt, time]
    acc, accnorm = buildSplineAcceptance(
        ws, time, 'Bs2DsPi_accpetance',
        config['SplineAcceptance']['KnotPositions'],
        config['SplineAcceptance']['KnotCoefficients'][config['Context'][0:3]],
        'FIT' in config['Context'])  # float for fitting
    # get resolution model
    resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc)
    mistagpdf = WS(
        ws,
        RooArgList(tupleDataSet.get().find('ssMistag'),
                   tupleDataSet.get().find('osMistag')))
    #???
    '''
    if 'GEN' in config['Context']:
        # 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, [tupleDataSet.reduce('ssMistag'), tupleDataSet.reduce('osMistag')]);
        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 the time pdf
    if 'GEN' in config['Context']:
        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,
            mistagpdf = [mistagpdf], mistagobs = eta)
    else:
        pdf = buildBDecayTimePdf(
            config, 'Bs2DsPi', ws,
            time, timeerr, qt, qf, [ [ eta ] ], [ tageff ],
            Gamma, DGamma, Dm,
            C = one, D = zero, Dbar = zero, S = zero, Sbar = zero,
            timeresmodel = resmodel, acceptance = acc, timeerrpdf = None)
    '''

    pdf = buildBDecayTimePdf(config,
                             'Bs2DsPi',
                             ws,
                             time,
                             timeerr,
                             qt,
                             qf, [[eta]], [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
    }
Exemplo n.º 4
0
def fitMass(rangem=[0.4, 2.0], iflag=1, iopt_bkgshape=0, CBpar=[0., 0., 0.]):
    global myc, fitres
    m0 = sum(rangem) / 2
    #w0=(rangem[1]-rangem[0])/10
    w0 = 0.004
    mass = RooRealVar("ee_ivm", "ee_ivm", rangem[0], rangem[1])

    if iflag == 1:
        ###Construct signal pdf with gaus
        mean = RooRealVar("mean", "mean", m0)
        sigma = RooRealVar("sigma", "sigma", w0)
        signal = RooGaussian("signal", "signal", mass, mean, sigma)
    elif iflag == 2 or iflag == 3:
        ## Construct signal pdf with CB function
        ##print "outinfo",x,CBpar[0],CBpar[1],CBpar[2],CBpar[3]
        cbmean = RooRealVar("cbmean", "cbmean", m0)
        cbsigma = RooRealVar("cbsigma", "cbsigma", CBpar[0])
        n1 = RooRealVar("n1", "", CBpar[1])
        alpha = RooRealVar("alpha", "", CBpar[2])
        cbsigma.setConstant(ROOT.kTRUE)
        n1.setConstant(ROOT.kTRUE)
        alpha.setConstant(ROOT.kTRUE)
        signal = RooCBShape("cball", "crystal ball1", mass, cbmean, cbsigma,
                            alpha, n1)


#    elif iflag ==3:
#        pass
    else:
        print "ERROR, please specify signal shape for fitting!!"
        sys.exit()

    # Construct background pdf
    a0 = RooRealVar("a0", "a0", 0.1, -1, 1)
    a1 = RooRealVar("a1", "a1", 0.004, -1, 1)
    a2 = RooRealVar("a2", "a2", 0.001, -1, 1)
    if iopt_bkgshape == 0:
        background = RooChebychev("background", "background", mass,
                                  RooArgList(a0, a1))
    else:
        background = RooChebychev("background", "background", mass,
                                  RooArgList(a0, a1, a2))
    # Construct composite pdf
    if iflag == 1:
        up_nsig = 40
    else:
        up_nsig = 60
    nsig = RooRealVar("nsig", "nsig", 5, 0.0, up_nsig)
    nbkg = RooRealVar("nbkg", "nbkg", 800, 0, 3000)

    #frac = RooRealVar("frac", "frac", 0.001, 0.0001, 0.1)
    model = RooAddPdf("model", "model", RooArgList(signal, background),
                      RooArgList(nsig, nbkg))
    #model = RooAddPdf("model", "model", RooArgList(signal, background), RooArgList(frac))
    mcdata = RooDataSet(
        "ds", "ds", RooArgSet(mass), RooFit.Import(data),
        RooFit.Cut("ee_ivm<" + str(rangem[1]) + "&&ee_ivm>" + str(rangem[0])))
    if optp == 1:
        ipr = 1
        verbose = 0
    elif optp == 2:
        ipr = 1
        verbose = 1
    else:
        ipr = -1
        verbose = 0

    fitres=model.fitTo(mcdata,RooFit.Save(),RooFit.Minos(1), RooFit.Strategy(2),\
                       RooFit.PrintLevel(ipr), RooFit.Verbose(verbose))
    nll = RooNLLVar("nll", "nll", model, mcdata,
                    RooFit.Range(rangem[0], rangem[1]))
    pll = nll.createProfile(RooArgSet(nsig))
    Profile = RooProfileLL("Profile", "Profile", nll, RooArgSet(nsig))
    llhoodP = RooFormulaVar("llhoodP", "exp(-0.5*Profile)",
                            RooArgList(Profile))
    xframe2 = nsig.frame(RooFit.Title("number of signal"))
    nllplot = nll.plotOn(xframe2, RooFit.ShiftToZero())
    themin = RooConstVar("themin", "themin", nllplot.GetMinimum())

    llhood = RooFormulaVar("llhood", "exp(-0.5*(nll-themin*0.95))",
                           RooArgList(nll, themin))

    if optp:
        xframe = mass.frame(RooFit.Title("mass of ee pair"))

        xframe3 = nsig.frame(RooFit.Title("number of signal"))
        xframe3.SetYTitle("Likelihood")

        mcdata.plotOn(xframe)
        model.plotOn(xframe)
        model.plotOn(xframe, RooFit.Components("background"),
                     RooFit.LineStyle(ROOT.kDashed),
                     RooFit.LineColor(ROOT.kRed))
        model.plotOn(xframe, RooFit.Components("cball"),
                     RooFit.LineStyle(ROOT.kDashed),
                     RooFit.LineColor(ROOT.kGreen))

        myc.cd(1)
        xframe.Draw()

        #pll.plotOn(xframe2,RooFit.LineColor(ROOT.kRed))
        if optp: print "***** archmin ", themin.Print()
        #llhoodP.plotOn(xframe3, RooFit.LineColor(ROOT.kRed))

        llhood.plotOn(xframe3)
        myc.cd(2)

        xframe2.SetMinimum(0)
        xframe2.Draw()
        myc.cd(3)
        xframe3.Draw()
        myc.Update()
        raw_input()

    nsig.setRange("IntRange1", 0, 1000.)
    Int1 = llhood.createIntegral(RooArgSet(nsig),
                                 ROOT.RooFit.Range('IntRange1'))
    Int1Val = Int1.getVal()
    i = 0
    hit = False
    while not (hit):
        i = i + 1
        nsig.setRange("IntRange2", 0, float(i))
        Int2 = llhood.createIntegral(RooArgSet(nsig),
                                     ROOT.RooFit.Range('IntRange2'))
        if Int2.getVal() >= Int1Val * 0.9:
            if optp: print "&&& ", i
            hit = True
            return i
Exemplo n.º 5
0
    width = RooRealVar(
        'width',
        'width',
        sig_hist.GetRMS() / 5.,  #fpar[0],
        0.,
        50.,
        'fC')
    lnd = RooLandau('lnd', 'lnd', x, mpv, width)
    sigma = RooRealVar(
        'sigma',
        '#sigma',  #fpar[3],
        sig_hist.GetRMS() / 5.,
        0.,
        50.,
        'fC')
    mean = RooConstVar('mean', 'mean', 0.)
    res = RooGaussian('res', 'res', x, mean, sigma)

    lxg = RooFFTConvPdf('lxg', 'lxg', x, lnd, res)

    xf = x.frame(RooFit.Bins(Nbins))
    sigDS.plotOn(xf)

    fmip = RooRealVar('fmip', 'f_{mip}', 0.95, 0., 1.)
    if havePeds:
        if opts.sipm:
            lxgplus = RooAddPdf('lxgplus', 'lxgplus', lxg,
                                ws.pdf('pedPlusOne'), fmip)
        else:
            lxgplus = RooAddPdf('lxgplus', 'lxgplus', lxg, ws.pdf('ped'), fmip)
        ws.pdf('ped').plotOn(
Exemplo n.º 6
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
    }
Exemplo n.º 7
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

    mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 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 = [qf, qt, time]
    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 the time pdf
    pdf = buildBDecayTimePdf(config,
                             'Bs2DsPi',
                             ws,
                             time,
                             timeerr,
                             qt,
                             qf, [[mistag]], [tageff],
                             Gamma,
                             DGamma,
                             Dm,
                             C=one,
                             D=zero,
                             Dbar=zero,
                             S=zero,
                             Sbar=zero,
                             timeresmodel=resmodel,
                             acceptance=acc)
    return {  # return things
        'ws': ws,
        'pdf': pdf,
        'obs': obs
    }
Exemplo n.º 8
0
def prepare_truth_models(ws, cat, mass, channel, turnon, truth):
    if channel in study_inputs:
        bkg_data = RooDataSet("bkgdata_%s" % (channel),
                              "M_{ll#gamma} with Errors",
                              ws.set("observables_weight"), "weight")

        for k, file in enumerate(study_inputs[channel]):
            f_in = TFile.Open(file, "READ")
            gDirectory.cd(pwd)
            n_events = f_in.Get("eventCount").GetBinContent(1)
            tree = f_in.Get("selected_zg").CloneTree()
            tree.SetName("tree_%s_%i" % (channel, k))
            f_in.Close()

            d_in = RooDataSet("temp", "M_{ll#gamma} with Errors", tree,
                              ws.set("observables"))
            norm = RooConstVar("norm", "norm", n_events)
            weight = RooFormulaVar(
                "weight",
                "weight",
                "1.3*@0*@1/@2",  #1.3 gives 19.6/fb
                RooArgList(ws.var("puWeight"), ws.var("procWeight"), norm))
            d_in.addColumn(weight)
            d_in_weight = RooDataSet("temp_weight", "M_{ll#gamma} with Errors",
                                     d_in, ws.set("observables_weight"), '',
                                     'weight')
            bkg_data.append(d_in_weight)

        # split off data for each category, create the
        # toy dataset truth models
        data = bkg_data.reduce("Mz + Mzg > 185 && r94cat == %i" % cat)
        getattr(ws, 'import')(data,
                              RooFit.Rename('bkgdata_%s_%i' % (channel, cat)))
        nevts = data.sumEntries('Mzg > %f && Mzg < %f' %
                                (mass - 1.5, mass + 1.5))
        #for sigm turn on we want erf truth
        if turnon == 'sigm' and truth == 'exp':
            #make RooDecay 'truth' model with erf turn on
            ws.factory(
                'RooGaussModel::MzgResoShape_exp_erf_%s_cat%i(Mzg,'\
                'bias_exp_erf_%s_cat%i[120,90,150],sigma_exp_erf_%s_cat%i[1,0.01,10])'%(
                channel,cat,
                channel,cat,
                channel,cat)
                )
            ws.factory(
                'RooDecay::MzgTruthModelBase_exp_erf_%s_cat%i(Mzg,'\
                'tau_erf_%s_cat%i[25,0,50],MzgResoShape_exp_erf_%s_cat%i,'
                'RooDecay::SingleSided)'%(channel,cat,
                                          channel,cat,
                                          channel,cat)
                )
            ws.factory(
                'RooExtendPdf::MzgTruthModel_exp_erf_%s_cat%i('\
                'MzgTruthModelBase_exp_erf_%s_cat%i,'\
                'norm_truth_exp_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat,
                                                            channel,cat,
                                                            channel,cat,
                                                            nevts,
                                                            0.25*nevts,1.75*nevts)
                )
            ws.pdf('MzgTruthModel_exp_erf_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_exp_erf_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit', 'simplex'),
                RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_exp_erf_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.SumW2Error(True))
        if turnon == 'sigm' and truth == 'pow':
            #make power-law truth model with erf turn on
            ws.factory('EXPR::MzgTruthModelShape_pow_erf_%s_cat%i('\
                       '"1e-20 + (@0 > @1)*((@0)^(-@2))",'\
                       '{Mzg,step_pow_erf_%s_cat%i[105,100,130],'\
                       'pow_%s_cat%i[2,0,10]})'\
                       %(channel,cat,
                         channel,cat,
                         channel,cat))
            ws.factory(
                'RooGaussModel::MzgResoShape_pow_erf_%s_cat%i(Mzg,'\
                'bias_pow_erf_%s_cat%i[0],sigma_pow_erf_%s_cat%i[1,0.01,10])'%(
                channel,cat,
                channel,cat,
                channel,cat)
                )
            ws.factory('FCONV::MzgTruthModelBase_pow_erf_%s_cat%i(Mzg,'\
                       'MzgTruthModelShape_pow_erf_%s_cat%i,'\
                       'MzgResoShape_pow_erf_%s_cat%i)'%(channel,cat,
                                                         channel,cat,
                                                         channel,cat))
            ws.factory(
                'RooExtendPdf::MzgTruthModel_pow_erf_%s_cat%i('\
                'MzgTruthModelBase_pow_erf_%s_cat%i,'\
                'norm_truth_pow_erf_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat,
                                                                channel,cat,
                                                                channel,cat,
                                                                nevts,
                                                                0.25*nevts,1.75*nevts)
                )
            ws.pdf('MzgTruthModel_pow_erf_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_pow_erf_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit', 'simplex'),
                RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_pow_erf_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.SumW2Error(True))

        #for erf fitting turn on we want sigmoid truth
        if turnon == 'erf' and truth == 'exp':
            #build exponential convoluted with sigmoid turn-on
            ws.factory('RooStepExponential::MzgTruthModelShape_exp_sigm_%s_cat%i'\
                       '(Mzg,tau_sigm_%s_cat%i[-0.05,-10,0],'\
                       'step_exp_sigm_%s_cat%i[110,100,130])'%(channel,cat,
                         channel,cat,
                         channel,cat))
            ws.factory('RooLogistics::MzgResoShape_exp_sigm_%s_cat%i(%s)' %
                       (channel, cat, ','.join([
                           'Mzg',
                           'bias_exp_sigm_%s_cat%i[0]' % (channel, cat),
                           'sigma_exp_sigm_%s_cat%i[5,0.01,20]' %
                           (channel, cat)
                       ])))
            ws.factory('FCONV::MzgTruthModelBase_exp_sigm_%s_cat%i(Mzg,'\
                       'MzgTruthModelShape_exp_sigm_%s_cat%i,'\
                       'MzgResoShape_exp_sigm_%s_cat%i)'%(channel,cat,
                                                          channel,cat,
                                                          channel,cat))
            ws.factory(
                'RooExtendPdf::MzgTruthModel_exp_sigm_%s_cat%i('\
                'MzgTruthModelBase_exp_sigm_%s_cat%i,'\
                'norm_truth_exp_sigm_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat,
                                                                 channel,cat,
                                                                 channel,cat,
                                                                 nevts,
                                                                 0.25*nevts,1.75*nevts)
                )
            ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit', 'simplex'),
                RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.SumW2Error(True))
        if turnon == 'erf' and truth == 'pow':
            #build power-law convoluted with sigmoid turn-on
            ws.factory('EXPR::MzgTruthModelShape_pow_sigm_%s_cat%i('\
                       '"1e-20 + (@0 > @1)*((@0)^(-@2))",'\
                       '{Mzg,step_pow_sigm_%s_cat%i[105,100,130],'\
                       'pow_sigm_%s_cat%i[2,0,10]})'\
                       %(channel,cat,
                         channel,cat,
                         channel,cat))
            ws.factory('RooLogistics::MzgResoShape_pow_sigm_%s_cat%i(%s)' %
                       (channel, cat, ','.join([
                           'Mzg',
                           'bias_pow_sigm_%s_cat%i[0]' % (channel, cat),
                           'sigma_pow_sigm_%s_cat%i[5,0.01,20]' %
                           (channel, cat)
                       ])))
            ws.factory('FCONV::MzgTruthModelBase_pow_sigm_%s_cat%i(Mzg,'\
                       'MzgTruthModelShape_pow_sigm_%s_cat%i,'\
                       'MzgResoShape_pow_sigm_%s_cat%i)'%(channel,cat,
                                                          channel,cat,
                                                          channel,cat))
            ws.factory(
                'RooExtendPdf::MzgTruthModel_pow_sigm_%s_cat%i('\
                'MzgTruthModelBase_pow_sigm_%s_cat%i,'\
                'norm_truth_pow_sigm_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat,
                                                                 channel,cat,
                                                                 channel,cat,
                                                                 nevts,
                                                                 0.25*nevts,1.75*nevts)
                )
            ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.Minimizer('Minuit', 'simplex'),
                RooFit.SumW2Error(False))
            ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i' % (channel, cat)).fitTo(
                ws.data('bkgdata_%s_%i' % (channel, cat)),
                RooFit.SumW2Error(True))
Exemplo n.º 9
0
    'RooAdaptiveGaussKronrodIntegrator1D').setRealValue('maxSeg', 1000)
RooAbsReal.defaultIntegratorConfig().method1D().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')
RooAbsReal.defaultIntegratorConfig().method1DOpen().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')

# seed the Random number generator
rndm = TRandom3(SEED + 1)
RooRandom.randomGenerator().SetSeed(int(rndm.Uniform(4294967295)))
del rndm

# start building the fit
from B2DXFitters.WS import WS

ws = RooWorkspace('ws')
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
Exemplo n.º 10
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.3, 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.5))

    mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5))
    tageff = WS(ws, RooRealVar('tageff', 'tageff', 1.0))
    timeerr = WS(ws, RooRealVar('timeerr', 'timeerr',
                                0.039))  #CHANGE THIS LATER
    # fit average mistag
    # add mistagged
    #ge rid of untagged events by putting restriction on qf or something when reduceing ds
    # now build the PDF
    from B2DXFitters.timepdfutils import buildBDecayTimePdf
    from B2DXFitters.resmodelutils import getResolutionModel
    from B2DXFitters.acceptanceutils import buildSplineAcceptance

    if 'GEN' in config['Context']:
        obs = [qf, qt, time, eta]
    else:
        obs = [qf, qt, time]
    acc, accnorm = buildSplineAcceptance(
        ws, time, 'Bs2DsPi_accpetance',
        config['SplineAcceptance']['KnotPositions'],
        config['SplineAcceptance']['KnotCoefficients'][config['Context'][0:3]],
        '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)
    if 'GEN' in config['Context']:
        # 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']))
        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 the time pdf
    if 'GEN' in config['Context']:
        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=None,
                                 mistagpdf=[mistagpdf],
                                 mistagobs=eta)
    else:
        adet = WS(ws, RooRealVar('adet', 'adet', 0., -.15, .15))
        aprod = WS(ws, RooRealVar('aprod', 'aprod', 0., -.15, .15))
        adet.setError(0.005)
        aprod.setError(0.005)
        pdf = buildBDecayTimePdf(config,
                                 'Bs2DsPi',
                                 ws,
                                 time,
                                 timeerr,
                                 qt,
                                 qf, [[eta]], [tageff],
                                 Gamma,
                                 DGamma,
                                 Dm,
                                 C=one,
                                 D=zero,
                                 Dbar=zero,
                                 S=zero,
                                 Sbar=zero,
                                 timeresmodel=resmodel,
                                 acceptance=acc,
                                 timeerrpdf=None,
                                 aprod=aprod,
                                 adet=adet)

    return {  # return things
        'ws': ws,
        'pdf': pdf,
        'obs': obs
    }