示例#1
0
文件: kkmass2.py 项目: xshi/dhad
def fit_single_mode(datatype, mode, label, lowmass, highmass, test):
    evtpath = os.path.join(attr.datpath, 'sel', label, 'kkmass')
    modekey = tools.get_modekey(mode)
    tag = 'single'
    evtfile = tools.set_file('evt', datatype, modekey, tag,  prefix='',
                             forceCombine=1, extbase=evtpath)
    
    load_roofit_lib(datatype, label)
    cuts = '%f<kkmass && kkmass<%f' % (lowmass, highmass)
    #err_type = 'ASYM'
    err_type = 'SYMM'
    setGamma, setMres, setR, mc = get_common_parameters(datatype, label)
    Sigma, Fa, Fb, Sa, Sb = get_resolution_paras(modekey, label)

    N1, N2, Nbkgd1, Nbkgd2, md, p, sigmap1, xi = init_paras_single(
        label, datatype, 's', modekey)

    title1 = '%s : %s < KK mass < %s ' %(attr.modes[modekey]['uname'],
                                         lowmass, highmass)
    title2 = '%s : %s < KK mass < %s ' %(attr.modes[modekey]['unamebar'],
                                         lowmass, highmass)
    prefix='dir_%s/kkmass2/%s_%s' % (label, lowmass, highmass)
    epsfile = tools.set_file('eps', datatype, modekey, tag,
                             prefix=prefix, extbase=attr.figpath)
    txtfile = tools.set_file('txt', datatype, modekey, tag,
                             prefix=prefix, extbase=attr.fitpath)

    #mbc_gau_che(evtfile, mc, setMres, setGamma, setR, sigmap1, Sa, Sb, Fa,
    mbc_dline_che(evtfile, mc, setMres, setGamma, setR, sigmap1, Sa, Sb, Fa,
                  Fb, md, p, xi, N1, N2, Nbkgd1, Nbkgd2, title1, title2,
                  epsfile, txtfile, cuts=cuts, err_type=err_type, test=test)
    
    if not test:
        tools.eps2png(epsfile)
        tools.eps2pdf(epsfile)
示例#2
0
def stage_nondiag(dt_type, label, x, y, interact=False):
    if label != '281ipbv0.2':
        load_roofit_lib(dt_type, label)

    ROOT.gROOT.SetBatch(1)
    ROOT.gROOT.SetStyle("Plain")

    # STAGE 1: fit for non-diagonal
    sys.stdout.write('Stage 1: fit non-diagonal.\n')

    single_modes = [(pair, sign) for pair in modes for sign in [-1, 1]]

    prefix='dir_'+label+'/crossfeeds'
    
    #for x, y  in [(x, y) for x in single_modes for y in single_modes if x!=y]:
    if x[1] == 1:
        uname = modes[x[0]]['uname']
        fname = modes[x[0]]['fname']
    else:
        uname = modes[x[0]]['unamebar']
        fname = modes[x[0]]['fnamebar']
    if y[1] == 1:
        unameb = modes[y[0]]['uname']
        fnameb = modes[y[0]]['fname']
    else:
        unameb = modes[y[0]]['unamebar']
        fnameb = modes[y[0]]['fnamebar']

    title  = '%s fakes %s' % (uname, unameb)

    bkgname = ('%s_Single_%s_fakes_Single_%s.evt' %(dt_type, fname, fnameb))
    bkgfile = get_bkgfile(bkgname, label)

    epsname = '%s_Single_%s_fakes_Single_%s.eps' % (dt_type, fname, fnameb)
    epsfile  = tools.set_file(extbase=attr.figpath, prefix=prefix, comname=epsname)
    
    txtname = '%s_Single_%s_fakes_Single_%s.txt' % (dt_type, fname, fnameb)
    txtfile  = tools.set_file(extbase=attr.fitpath, prefix=prefix, comname=txtname)
    
    alpha, mass, n, sigma = get_paras(dt_type, label, fnameb)
    
    par_str = '("%s", "%s", "%s", "%s", %s, %s, %s, %s)'
    par_tuple = (title, bkgfile, epsfile, txtfile, alpha, mass, n, sigma)
    par = par_str % par_tuple
    
    source = 'crossfeeds_nondiag.C'
    #if interact:
    source = os.path.join(attr.srcfitpath, source)

    tools.print_sep()
    sys.stdout.write('       ROOT macro: %s \n' % source)
    tools.print_sep()
    ROOT.gROOT.Macro(source + par)
    
    tools.eps2png(epsfile)
    tools.eps2pdf(epsfile)
示例#3
0
def stage_diag(dt_type, label, mode, sign, interact=False):

    if label != '281ipbv0.2':
        load_roofit_lib(dt_type, label)

    ROOT.gROOT.SetBatch(1)
    ROOT.gROOT.SetStyle("Plain")

    sys.stdout.write('Stage 0: Do fits for diagonal. Mode: (%s, %s) \n' %(mode, sign))

    prefix='dir_'+label+'/crossfeeds'

    if sign == 1:
        uname = modes[mode]['uname']
        fname = modes[mode]['fname']
    else:
        uname = modes[mode]['unamebar']
        fname = modes[mode]['fnamebar']

    title  = '%s correct reco' % uname

    bkgname = ('%s_Single_%s_fakes_Single_%s.evt' %(dt_type, fname, fname))
    bkgfile = get_bkgfile(bkgname, label)

    epsname = '%s_Single_%s_fakes_Single_%s.eps' % (dt_type, fname, fname)
    epsfile  = tools.set_file(extbase=attr.figpath, prefix=prefix, comname=epsname)
    
    txtname = '%s_Single_%s_fakes_Single_%s.txt' % (dt_type, fname, fname)
    txtfile  = tools.set_file(extbase=attr.fitpath, prefix=prefix, comname=txtname)

    par_str = '("%s", "%s", "%s", "%s")'
    par_tuple = (title, bkgfile, epsfile, txtfile)
    par = par_str % par_tuple
    
    source = 'crossfeeds.C'
    #if interact:
    source = os.path.join(attr.srcfitpath, source)
        
    tools.print_sep()
    sys.stdout.write('       ROOT macro: %s \n' % source)
    tools.print_sep()

    ROOT.gROOT.Macro(source + par)
    tools.eps2png(epsfile)
    tools.eps2pdf(epsfile)
示例#4
0
def fit_sidebands_single_mode(datatype, mode, label, test):
    load_roofit_lib(datatype, label)

    dt_type = datatype.replace('/', '_')
    modekey = tools.get_modekey(mode)

    comname = '%s_%s' % (dt_type, mode)
    input_label = label

    sdbpath = os.path.join(attr.evtpath, input_label)
    sdbfile = set_file(extbase=sdbpath, comname=comname, ext='evt')

    has_charge_conjugate = False
    if '__' in mode:
        has_charge_conjugate = True

    if not os.access(sdbfile, os.F_OK):
        if has_charge_conjugate:
            sdbfile = set_file(extbase=sdbpath,
                               dt_type=dt_type,
                               tag='s',
                               mode=modekey,
                               comname=comname,
                               ext='evt',
                               forceCombine=1)
        else:
            raise ValueError(sdbfile)

    epspath = os.path.join(attr.figpath, label)
    epsfile = set_file(extbase=epspath, comname=comname, ext='eps')

    txtpath = os.path.join(attr.fitpath, label)
    txtfile = set_file(extbase=txtpath, comname=comname, ext='txt')

    if test:
        epsfile = epsfile + '.test'
        txtfile = txtfile + '.test'

    ROOT.gROOT.SetBatch(1)
    ROOT.gROOT.SetStyle('Plain')

    mbc = ROOT.RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    mbc_aset = ROOT.RooArgSet(mbc)

    ebeam = ROOT.RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV')

    dflav = ROOT.RooCategory('dflav', 'D0 flavor')

    dflav.defineType('dflav', 1)
    dflav.defineType('dbarflav', -1)

    dataset_args = ROOT.RooArgList(mbc, ebeam, dflav)

    dataset = ROOT.RooDataSet.read(sdbfile, dataset_args)

    arg_cutoff = ebeam
    arg_slope = ROOT.RooRealVar('arg_slope', 'Argus slope', -10, -100, -1)
    arg_power = ROOT.RooRealVar('arg_power', 'Argus power', 0.5, 0.1, 1.5)

    yld = ROOT.RooRealVar('yield', 'D yield', 100, 0, 200000)
    bkg = ROOT.RooRealVar('bkg', 'Background', 100, 0, 1000000)

    sigma = ROOT.RooRealVar('sigma', 'D width', 0.0001, 0.005, 'GeV')

    pars = [arg_slope, arg_power, bkg, sigma, yld]

    mbc_d0 = ROOT.RooRealVar('mbc_d0', 'D0 Mbc', 1.8647, 'GeV')
    mbc_dp = ROOT.RooRealVar('mbc_dp', 'D+ Mbc', 1.8694, 'GeV')

    gauss_d0 = ROOT.RooGaussian('gauss_d0', 'D0 gaussian', mbc, mbc_d0, sigma)
    gauss_dp = ROOT.RooGaussian('gauss_dp', 'D+ gaussian', mbc, mbc_dp, sigma)

    argus = ROOT.RooArgusBG('argus', 'Argus BG', mbc, arg_cutoff, arg_slope,
                            arg_power)
    sumpdf_d0 = ROOT.RooAddPdf('sumpdf_d0', 'D0 sum pdf',
                               ROOT.RooArgList(gauss_d0, argus),
                               ROOT.RooArgList(yld, bkg))
    sumpdf_dp = ROOT.RooAddPdf('sumpdf_dp', 'Dp sum pdf',
                               ROOT.RooArgList(gauss_dp, argus),
                               ROOT.RooArgList(yld, bkg))

    Extended = ROOT.RooFit.Extended(ROOT.kTRUE)  # e
    Save = ROOT.RooFit.Save(ROOT.kTRUE)  # r
    Hesse = ROOT.RooFit.Hesse(ROOT.kFALSE)  # no h
    Verbose = ROOT.RooFit.Verbose(ROOT.kFALSE)  # no q

    if 'D0' in mode:
        pdf = sumpdf_d0
    else:
        pdf = sumpdf_dp

    if has_charge_conjugate:
        yld_bar = ROOT.RooRealVar('yield_bar', 'Dbar yield', 100, 0, 200000)
        bkg_bar = ROOT.RooRealVar('bkg_bar', 'Background Bar', 100, 0, 1000000)
        pars.extend([yld_bar, bkg_bar])

        mbc_d0bar = ROOT.RooRealVar('mbc_d0bar', 'D0Bar Mbc', 1.8647, 'GeV')
        mbc_dm = ROOT.RooRealVar('mbc_dm', 'D- Mbc', 1.8694, 'GeV')

        gauss_d0bar = ROOT.RooGaussian('gauss_d0bar', 'D0bar gaussian', mbc,
                                       mbc_d0bar, sigma)
        gauss_dm = ROOT.RooGaussian('gauss_dm', 'D- gaussian', mbc, mbc_dm,
                                    sigma)

        sumpdf_d0bar = ROOT.RooAddPdf('sumpdf_d0bar', 'D0bar sum pdf',
                                      ROOT.RooArgList(gauss_d0bar, argus),
                                      ROOT.RooArgList(yld_bar, bkg_bar))
        sumpdf_dm = ROOT.RooAddPdf('sumpdf_dm', 'Dm sum pdf',
                                   ROOT.RooArgList(gauss_dm, argus),
                                   ROOT.RooArgList(yld_bar, bkg_bar))

        pdf = ROOT.RooSimultaneous('totalPdf', 'totalPdf', dflav)

        if 'D0' in mode:
            pdf.addPdf(sumpdf_d0, 'dflav')
            pdf.addPdf(sumpdf_d0bar, 'dbarflav')
        else:
            pdf.addPdf(sumpdf_dp, 'dflav')
            pdf.addPdf(sumpdf_dm, 'dbarflav')

    if 'nogaus' in label:
        yld.setVal(1)
        yld.setConstant(ROOT.kTRUE)
        pars.remove(yld)

    if 'floatsigma' not in label:
        datatype = 'data'
        tag = 'single'

        if '818ipb' in label:
            prefix = 'dir_818ipbv12'
            frame_max = 1500  #bkg_generic_ddbar_818_max[mode]
        else:
            raise NameError(label)

        tabfile = set_file('txt',
                           datatype,
                           modekey,
                           tag,
                           prefix=prefix,
                           extbase=attr.fitpath)

        sys.stdout.write('Using width from %s \n' % tabfile)
        tab = DHadTable(tabfile)
        sigmap1 = float(tab.cell_get('sigmap1', 'Value'))
        sigma.setVal(sigmap1)
        sigma.setConstant(ROOT.kTRUE)
        pars.remove(sigma)

    #res = pdf.fitTo(dataset, Extended, Save, Verbose)
    res = pdf.fitTo(dataset, 'emr')  #Migrad only, no MINOS
    res.Print('v')

    if not has_charge_conjugate:
        canvas = ROOT.TCanvas('canvas', 'canvas1', 600, 600)
        canvas.SetFixedAspectRatio(0)

        xframe = mbc.frame()

        xframe.SetMaximum(frame_max)
        xframe.SetMarkerSize(0.3)
        dataset.plotOn(xframe)
        pdf.plotOn(xframe)
        nfitParam = len(pars)
        chisq_ndof = xframe.chiSquare(nfitParam)

        nbin = xframe.GetNbinsX()
        ndof = nbin - nfitParam
        chisq = chisq_ndof * ndof

        chisqbox = ROOT.TPaveText(0.1, 0.1, 0.4, 0.15, 'BRNDC')
        chisqbox.SetFillColor(0)
        chisqbox.SetBorderSize(1)
        chisqbox.AddText('#chi^{2}/ndof = %.2f/%d =  %.2f' %
                         (chisq, ndof, chisq_ndof))
        xframe.addObject(chisqbox)

        pdf.paramOn(xframe, dataset)

        xframe.SetTitle('Sidebands of %s' % mode)
        xframe.GetYaxis().SetTitleSize(0.03)
        xframe.GetYaxis().SetLabelSize(0.03)
        xframe.GetYaxis().SetTitleOffset(1.8)
        xframe.GetXaxis().SetTitleSize(0.03)
        xframe.GetXaxis().SetLabelSize(0.03)
        xframe.GetXaxis().SetTitleOffset(1.2)
        xframe.Draw()
    else:
        canvas = ROOT.TCanvas('canvas', 'mbc', 1200, 400)
        canvas.Divide(3, 1)
        title1 = attr.modes[modekey]['uname']
        title2 = attr.modes[modekey]['unamebar']

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

        ebeam.setBins(900)

        canvas.cd(1)
        mbcFrame = mbc.frame()
        mbcFrame = mbc.frame(60)
        dflav.setLabel('dflav')
        ebeam_aset = ROOT.RooArgSet(ebeam, dflav)
        ebeamdata = ROOT.RooDataHist("ebeamdata", "ebeamdata", ebeam_aset,
                                     dataset)

        Cut = ROOT.RooFit.Cut("dflav==dflav::dflav")

        LineColor = ROOT.RooFit.LineColor(ROOT.kRed)
        LineWidth = ROOT.RooFit.LineWidth(1)
        #Slice = ROOT.RooFit.Slice(dflav, 'dflav')
        Slice = ROOT.RooFit.Slice(dflav)

        ProjWData = ROOT.RooFit.ProjWData(ebeam_aset, ebeamdata)

        dataset.plotOn(mbcFrame, Cut)
        mbcFrame.getAttMarker().SetMarkerSize(0.6)
        mbcFrame.Draw()

        pdf.plotOn(mbcFrame, LineColor, LineWidth, Slice, ProjWData)

        nfitParam = len(pars) - 2
        chisq_ndof = mbcFrame.chiSquare(nfitParam)

        nbin = mbcFrame.GetNbinsX()
        ndof = nbin - nfitParam
        chisq = chisq_ndof * ndof

        chisqbox = ROOT.TPaveText(0.1, 0.1, 0.55, 0.2, 'BRNDC')
        chisqbox.SetFillColor(0)
        chisqbox.SetBorderSize(1)
        chisqbox.AddText('#chi^{2}/ndof = %.2f/%d =  %.2f' %
                         (chisq, ndof, chisq_ndof))

        mbcFrame.addObject(chisqbox)

        mbcFrame.SetTitle(title1)
        mbcFrame.Draw()

        canvas.cd(2)
        mbcFrame = mbc.frame()
        mbcFrame = mbc.frame(60)
        dflav.setLabel('dbarflav')

        ebeam_aset = ROOT.RooArgSet(ebeam, dflav)
        ebeamdata = ROOT.RooDataHist("ebeamdata", "ebeamdata", ebeam_aset,
                                     dataset)

        Cut = ROOT.RooFit.Cut("dflav==dflav::dbarflav")

        LineColor = ROOT.RooFit.LineColor(ROOT.kRed)
        LineWidth = ROOT.RooFit.LineWidth(1)
        #Slice = ROOT.RooFit.Slice(dflav, 'dbarflav')
        Slice = ROOT.RooFit.Slice(dflav)

        ProjWData = ROOT.RooFit.ProjWData(ebeam_aset, ebeamdata)

        dataset.plotOn(mbcFrame, Cut)
        mbcFrame.getAttMarker().SetMarkerSize(0.6)
        mbcFrame.Draw()

        pdf.plotOn(mbcFrame, LineColor, LineWidth, Slice, ProjWData)

        nfitParam = len(pars) - 2
        chisq_ndof = mbcFrame.chiSquare(nfitParam)

        nbin = mbcFrame.GetNbinsX()
        ndof = nbin - nfitParam
        chisq = chisq_ndof * ndof

        chisqbox = ROOT.TPaveText(0.1, 0.1, 0.55, 0.2, 'BRNDC')
        chisqbox.SetFillColor(0)
        chisqbox.SetBorderSize(1)
        chisqbox.AddText('#chi^{2}/ndof = %.2f/%d =  %.2f' %
                         (chisq, ndof, chisq_ndof))

        mbcFrame.addObject(chisqbox)

        mbcFrame.SetTitle(title2)
        mbcFrame.Draw()

        canvas.cd(3)
        mbcFrame = mbc.frame()

        paramWin1 = pdf.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")
        mbcFrame.Draw()

    canvas.Print(epsfile)
    tools.save_fit_result(pars, txtfile)

    if not test:
        tools.eps2png(epsfile)
        tools.eps2pdf(epsfile)
示例#5
0
def output_multspec(reweight, pt, mode, selfile, label, test=False):
    mode, signs = tools.get_modekey_sign(mode)
    f = TFile(selfile, 'recreate')

    load_roofit_lib('signal', label)

    from ROOT import RooRealVar, RooDataSet, RooArgList, RooArgSet, \
         RooGaussian, RooArgusBG, RooCBShape, RooAddPdf, RooPolynomial, \
         gSystem, TCanvas

    efffile = selfile.replace('.root', '.db')
    effs = shelve.open(efffile)

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    weight2 = RooRealVar('weight2', 'weight', 1)
    weight3 = RooRealVar('weight3', 'weight', 1)
    mbc_aset = RooArgSet(mbc)

    ntrack_d0 = TH1F('ntrack_d0',
                     'Number of other side tracks for D^{0} #rightarrow K#pi',
                     10, 0, 9)
    ntrack_dp = TH1F(
        'ntrack_dp',
        'Number of other side tracks for D^{+} #rightarrow K#pi#pi', 10, 0, 9)

    unweight_sum = 0
    reweight_ntr_sum = 0
    reweight_npi0_sum = 0
    reweight_ntr_mcand_cnt = 0
    reweight_npi0_mcand_cnt = 0
    unweight_dmbc = TH1F('unweight_dmbc', 'm_{BC}, direct MC', 100, 1.83, 1.89)
    reweight_ntr_dmbc = TH1F('reweight_ntr_dmbc',
                             'm_{BC}, track reweighted MC', 100, 1.83, 1.89)
    reweight_npi0_dmbc = TH1F('reweight_npi0_dmbc',
                              'm_{BC}, #pi^{0} reweighted MC', 100, 1.83, 1.89)

    chgpart = (pdgid_pip, pdgid_pim, pdgid_Kp, pdgid_Km, pdgid_mup, pdgid_mum,
               pdgid_ep, pdgid_em)
    neupart = (pdgid_KL, pdgid_piz, pdgid_gamma)
    intpart = chgpart + neupart

    ntr_denoms = {}
    gen_dmbc_ntr = {}
    npi0_denoms = {}
    gen_dmbc_npi0 = {}
    for i in range(7 + 1):
        ntr_denoms[i] = 0
        gen_dmbc_ntr[i] = TH1F('gen_dmbc_ntr_' + ` i `,
                               'm_{BC} for ' + ` i ` + ' tracks', 100, 1.83,
                               1.89)
    for i in range(5 + 1):
        npi0_denoms[i] = 0
        gen_dmbc_npi0[i] = TH1F('gen_dmbc_npi0_' + ` i `,
                                'm_{BC} for ' + ` i ` + ' #pi^{0}', 100, 1.83,
                                1.89)

    ntotal = 0
    nselected = 0

    for pte in pt:
        ntotal += 1
        if test and nselected > 10:
            break

        if test and ntotal > 1000:
            break

        if pte.ecm < 3.7:
            continue
        othsidetrk = 0
        othsidepi0 = 0
        dtree = makeDDecaySubTree(pte, -1)

        ddesc = dtree[0].interestingDescendants(intpart, False, False)

        for i in ddesc:
            if i.pdgid in chgpart:
                othsidetrk += 1
            if (i.pdgid in chgpart and i.parent.pdgid == pdgid_KS
                    and len(i.parent.daughters) == 1):
                # This absurd special case is due to GEANT's "K_S -> pi" decay
                othsidetrk += 1
            if i.pdgid == pdgid_piz:
                othsidepi0 += 1
            if (i.pdgid == pdgid_KS) and len(i.daughters) != 2:
                print i

        if mode >= 200:
            mod2 = 1
        else:
            mod2 = 0

        if (othsidetrk % 2) != mod2:
            print '-----------------------------------', othsidetrk
            print chgpart
            # for node in makeDecayTree(pte):
            #  pass
            #  if len(node.daughters) == 0 and node.pdgid in chgpart:
            #  print node

        choice = chooseD(mode, pte, 1)

        if choice != None and not passDE(choice, pte):
            choice = None

        unweight_sum += 1

        index_tr = getindex(othsidetrk, ntr_denoms)
        ntr_denoms[index_tr] += 1
        index_pi0 = getpi0index(othsidepi0, npi0_denoms)
        npi0_denoms[index_pi0] += 1

        final_weight_vector_ntr = attr.multiplicity_weight_ntr[reweight]
        initial_weight_vector_ntr = attr.multiplicity_weight_ntr['init']

        final_weight_vector_npi0 = attr.multiplicity_weight_npi0[reweight]
        initial_weight_vector_npi0 = attr.multiplicity_weight_npi0['init']

        reweight_ntr_sum += (final_weight_vector_ntr[index_tr] /
                             initial_weight_vector_ntr[index_tr])
        reweight_npi0_sum += (final_weight_vector_npi0[index_pi0] /
                              initial_weight_vector_npi0[index_pi0])
        if choice != None:
            nselected += 1

            unweight_dmbc.Fill(pte.dmbc[choice])
            reweight_ntr_dmbc.Fill(pte.dmbc[choice],
                                   (final_weight_vector_ntr[index_tr] /
                                    initial_weight_vector_ntr[index_tr]))
            reweight_npi0_dmbc.Fill(pte.dmbc[choice],
                                    (final_weight_vector_npi0[index_pi0] /
                                     initial_weight_vector_npi0[index_pi0]))
            gen_dmbc_ntr[index_tr].Fill(pte.dmbc[choice])
            gen_dmbc_npi0[index_pi0].Fill(pte.dmbc[choice])
            mbc.setVal(pte.dmbc[choice])

    effs['npi0_denom'] = npi0_denoms
    effs['ntr_denom'] = ntr_denoms
    effs['unweight_sum'] = unweight_sum
    effs['reweight_ntr_sum'] = reweight_ntr_sum
    effs['reweight_npi0_sum'] = reweight_npi0_sum

    effs.close()
    #sys.stdout.write('Saved %s \n' %efffile)

    f.Write()
    f.Close()
    pt.Delete()

    return nselected, ntotal
示例#6
0
def fit_single_mode(datatype, mode, label, lowmass, highmass, test):
    evtpath = os.path.join(attr.datpath, 'sel', label, 'kpimass')
    modekey = tools.get_modekey(mode)
    tag = 'single'
    evtfile = tools.set_file('evt',
                             datatype,
                             modekey,
                             tag,
                             prefix='',
                             forceCombine=1,
                             extbase=evtpath)

    load_roofit_lib(datatype, label)
    cuts = '%f<kpimass && kpimass<%f' % (lowmass, highmass)
    err_type = 'ASYM'
    setGamma, setMres, setR, mc = get_common_parameters(datatype, label)
    Sigma, Fa, Fb, Sa, Sb = get_resolution_paras(modekey, label)

    N1, N2, Nbkgd1, Nbkgd2, md, p, sigmap1, xi = init_paras_single(
        label, datatype, 's', modekey)

    title1 = '%s : %s < Kpi mass < %s ' % (attr.modes[modekey]['uname'],
                                           lowmass, highmass)
    title2 = '%s : %s < Kpi mass < %s ' % (attr.modes[modekey]['unamebar'],
                                           lowmass, highmass)
    prefix = 'dir_%s/kpimass/%s_%s' % (label, lowmass, highmass)
    epsfile = tools.set_file('eps',
                             datatype,
                             modekey,
                             tag,
                             prefix=prefix,
                             extbase=attr.figpath)
    txtfile = tools.set_file('txt',
                             datatype,
                             modekey,
                             tag,
                             prefix=prefix,
                             extbase=attr.fitpath)

    mbc_single_3s(evtfile,
                  mc,
                  setMres,
                  setGamma,
                  setR,
                  sigmap1,
                  Sa,
                  Sb,
                  Fa,
                  Fb,
                  md,
                  p,
                  xi,
                  N1,
                  N2,
                  Nbkgd1,
                  Nbkgd2,
                  title1,
                  title2,
                  epsfile,
                  txtfile,
                  cuts=cuts,
                  err_type=err_type,
                  test=test)

    #mbc_gau_che(evtfile, mc, setMres, setGamma, setR, sigmap1, Sa, Sb, Fa,
    #            Fb, md, p, xi, N1, N2, Nbkgd1, Nbkgd2, title1, title2,
    #            epsfile, txtfile, cuts=cuts, err_type=err_type, test=test)

    if not test:
        tools.eps2png(epsfile)
        tools.eps2pdf(epsfile)
示例#7
0
文件: sidebands.py 项目: xshi/dhad
def fit_sidebands_single_mode(datatype, mode, label, test):
    load_roofit_lib(datatype, label)

    dt_type=datatype.replace('/', '_')
    modekey = tools.get_modekey(mode)
    
    comname = '%s_%s' %(dt_type, mode)
    input_label = label

    sdbpath = os.path.join(attr.evtpath, input_label)
    sdbfile = set_file(extbase=sdbpath, comname=comname, ext='evt')

    has_charge_conjugate = False
    if '__' in mode:
        has_charge_conjugate = True
    
    if not os.access(sdbfile, os.F_OK):
        if has_charge_conjugate:
            sdbfile = set_file(extbase=sdbpath, dt_type=dt_type,
                               tag='s', mode=modekey, 
                               comname=comname, ext='evt', forceCombine=1)
        else:
            raise ValueError(sdbfile)
        
    epspath = os.path.join(attr.figpath, label)    
    epsfile = set_file(extbase=epspath, comname=comname, ext='eps')

    txtpath = os.path.join(attr.fitpath, label)    
    txtfile = set_file(extbase=txtpath, comname=comname, ext='txt')

    if test:
        epsfile = epsfile + '.test'
        txtfile = txtfile + '.test'

    ROOT.gROOT.SetBatch(1)
    ROOT.gROOT.SetStyle('Plain')

    mbc = ROOT.RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    mbc_aset = ROOT.RooArgSet(mbc)

    ebeam = ROOT.RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV')

    dflav = ROOT.RooCategory('dflav','D0 flavor')

    dflav.defineType('dflav',1)
    dflav.defineType('dbarflav',-1)

    dataset_args = ROOT.RooArgList(mbc, ebeam, dflav)

    dataset = ROOT.RooDataSet.read(sdbfile, dataset_args)

    arg_cutoff = ebeam
    arg_slope = ROOT.RooRealVar('arg_slope', 'Argus slope', -10, -100, -1)
    arg_power = ROOT.RooRealVar('arg_power', 'Argus power', 0.5, 0.1, 1.5)
    
    yld = ROOT.RooRealVar('yield', 'D yield', 100, 0, 200000)
    bkg = ROOT.RooRealVar('bkg', 'Background', 100, 0, 1000000)

    sigma = ROOT.RooRealVar('sigma', 'D width', 0.0001, 0.005, 'GeV')

    pars = [arg_slope, arg_power, bkg, sigma, yld]
    
    mbc_d0 = ROOT.RooRealVar('mbc_d0', 'D0 Mbc', 1.8647, 'GeV')
    mbc_dp = ROOT.RooRealVar('mbc_dp', 'D+ Mbc', 1.8694, 'GeV')
    
    gauss_d0 = ROOT.RooGaussian('gauss_d0', 'D0 gaussian', mbc, mbc_d0, sigma)
    gauss_dp = ROOT.RooGaussian('gauss_dp', 'D+ gaussian', mbc, mbc_dp, sigma)

    argus = ROOT.RooArgusBG('argus', 'Argus BG', mbc, arg_cutoff, arg_slope,
                            arg_power)
    sumpdf_d0 = ROOT.RooAddPdf('sumpdf_d0', 'D0 sum pdf',
                          ROOT.RooArgList(gauss_d0, argus),
                          ROOT.RooArgList(yld, bkg))
    sumpdf_dp = ROOT.RooAddPdf('sumpdf_dp', 'Dp sum pdf',
                               ROOT.RooArgList(gauss_dp, argus),
                               ROOT.RooArgList(yld, bkg))


    Extended = ROOT.RooFit.Extended(ROOT.kTRUE)  # e
    Save = ROOT.RooFit.Save(ROOT.kTRUE)          # r
    Hesse = ROOT.RooFit.Hesse(ROOT.kFALSE)       # no h
    Verbose = ROOT.RooFit.Verbose(ROOT.kFALSE)   # no q 

    if 'D0' in mode:
        pdf = sumpdf_d0
    else:
        pdf = sumpdf_dp


    if has_charge_conjugate:
        yld_bar = ROOT.RooRealVar('yield_bar', 'Dbar yield', 100, 0, 200000)
        bkg_bar = ROOT.RooRealVar('bkg_bar', 'Background Bar', 100, 0, 1000000)
        pars.extend([yld_bar, bkg_bar])

        mbc_d0bar = ROOT.RooRealVar('mbc_d0bar', 'D0Bar Mbc', 1.8647, 'GeV')
        mbc_dm = ROOT.RooRealVar('mbc_dm', 'D- Mbc', 1.8694, 'GeV')
        
        gauss_d0bar = ROOT.RooGaussian('gauss_d0bar', 'D0bar gaussian',
                                       mbc, mbc_d0bar, sigma)
        gauss_dm = ROOT.RooGaussian('gauss_dm', 'D- gaussian',
                                    mbc, mbc_dm, sigma)
        
        sumpdf_d0bar = ROOT.RooAddPdf('sumpdf_d0bar', 'D0bar sum pdf',
                                      ROOT.RooArgList(gauss_d0bar, argus),
                                      ROOT.RooArgList(yld_bar, bkg_bar))
        sumpdf_dm = ROOT.RooAddPdf('sumpdf_dm', 'Dm sum pdf',
                                   ROOT.RooArgList(gauss_dm, argus),
                                   ROOT.RooArgList(yld_bar, bkg_bar))

        pdf = ROOT.RooSimultaneous('totalPdf', 'totalPdf', dflav)

        if 'D0' in mode:
            pdf.addPdf(sumpdf_d0, 'dflav')
            pdf.addPdf(sumpdf_d0bar, 'dbarflav')
        else:
            pdf.addPdf(sumpdf_dp, 'dflav')
            pdf.addPdf(sumpdf_dm, 'dbarflav')
            

    if 'nogaus' in label:
        yld.setVal(1)
        yld.setConstant(ROOT.kTRUE)
        pars.remove(yld)

    if 'floatsigma' not in label:
        datatype = 'data'
        tag = 'single'

        if '818ipb' in label:
            prefix = 'dir_818ipbv12'
            frame_max = 1500 #bkg_generic_ddbar_818_max[mode]
        else:
            raise NameError(label)


        tabfile = set_file('txt', datatype, modekey, tag,
                           prefix=prefix,
                           extbase=attr.fitpath)

        sys.stdout.write('Using width from %s \n' %tabfile)
        tab = DHadTable(tabfile)
        sigmap1 = float(tab.cell_get('sigmap1', 'Value'))
        sigma.setVal(sigmap1)
        sigma.setConstant(ROOT.kTRUE)
        pars.remove(sigma)
        
    #res = pdf.fitTo(dataset, Extended, Save, Verbose)
    res = pdf.fitTo(dataset, 'emr') #Migrad only, no MINOS
    res.Print('v')


    if not has_charge_conjugate:
        canvas = ROOT.TCanvas('canvas', 'canvas1', 600, 600)
        canvas.SetFixedAspectRatio(0)
        
        xframe = mbc.frame()
        
        xframe.SetMaximum(frame_max)
        xframe.SetMarkerSize(0.3)
        dataset.plotOn(xframe)
        pdf.plotOn(xframe)
        nfitParam = len(pars)
        chisq_ndof = xframe.chiSquare(nfitParam)
        
        nbin = xframe.GetNbinsX()
        ndof = nbin - nfitParam
        chisq = chisq_ndof * ndof
    
        chisqbox = ROOT.TPaveText(0.1, 0.1, 0.4, 0.15, 'BRNDC')
        chisqbox.SetFillColor(0)
        chisqbox.SetBorderSize(1)
        chisqbox.AddText('#chi^{2}/ndof = %.2f/%d =  %.2f' %
                         (chisq, ndof, chisq_ndof))
        xframe.addObject(chisqbox)

        pdf.paramOn(xframe, dataset)        

        xframe.SetTitle('Sidebands of %s' % mode)
        xframe.GetYaxis().SetTitleSize(0.03) 
        xframe.GetYaxis().SetLabelSize(0.03) 
        xframe.GetYaxis().SetTitleOffset(1.8)
        xframe.GetXaxis().SetTitleSize(0.03) 
        xframe.GetXaxis().SetLabelSize(0.03) 
        xframe.GetXaxis().SetTitleOffset(1.2)
        xframe.Draw()
    else:
        canvas = ROOT.TCanvas('canvas','mbc', 1200, 400);
        canvas.Divide(3,1)
        title1 = attr.modes[modekey]['uname']
        title2 = attr.modes[modekey]['unamebar']
        
        canvas_1 = canvas.GetListOfPrimitives().FindObject('canvas_1')
        canvas_2 = canvas.GetListOfPrimitives().FindObject('canvas_2')
        canvas_1.SetLogy() 
        canvas_2.SetLogy()
        
        ebeam.setBins(900)

        canvas.cd(1)
        mbcFrame=mbc.frame()
        mbcFrame=mbc.frame(60)
        dflav.setLabel('dflav')
        ebeam_aset = ROOT.RooArgSet(ebeam, dflav)
        ebeamdata = ROOT.RooDataHist("ebeamdata", "ebeamdata", 
                                     ebeam_aset, dataset)

        Cut = ROOT.RooFit.Cut("dflav==dflav::dflav")

        LineColor = ROOT.RooFit.LineColor(ROOT.kRed)
        LineWidth = ROOT.RooFit.LineWidth(1)
        #Slice = ROOT.RooFit.Slice(dflav, 'dflav')
        Slice = ROOT.RooFit.Slice(dflav)

        ProjWData = ROOT.RooFit.ProjWData(ebeam_aset, ebeamdata)
        
        dataset.plotOn(mbcFrame, Cut)
        mbcFrame.getAttMarker().SetMarkerSize(0.6)
        mbcFrame.Draw()


        pdf.plotOn(mbcFrame, LineColor, LineWidth, Slice, ProjWData)

        nfitParam = len(pars) - 2
        chisq_ndof = mbcFrame.chiSquare(nfitParam)
        
        nbin = mbcFrame.GetNbinsX()
        ndof = nbin - nfitParam
        chisq = chisq_ndof * ndof
    
        chisqbox = ROOT.TPaveText(0.1, 0.1, 0.55, 0.2, 'BRNDC')
        chisqbox.SetFillColor(0)
        chisqbox.SetBorderSize(1)
        chisqbox.AddText('#chi^{2}/ndof = %.2f/%d =  %.2f' %
                         (chisq, ndof, chisq_ndof))

        mbcFrame.addObject(chisqbox)

        mbcFrame.SetTitle(title1)
        mbcFrame.Draw()

        canvas.cd(2)
        mbcFrame = mbc.frame()
        mbcFrame=mbc.frame(60)
        dflav.setLabel('dbarflav')

        ebeam_aset = ROOT.RooArgSet(ebeam, dflav)
        ebeamdata = ROOT.RooDataHist("ebeamdata", "ebeamdata", 
                                     ebeam_aset, dataset)

        Cut = ROOT.RooFit.Cut("dflav==dflav::dbarflav")

        LineColor = ROOT.RooFit.LineColor(ROOT.kRed)
        LineWidth = ROOT.RooFit.LineWidth(1)
        #Slice = ROOT.RooFit.Slice(dflav, 'dbarflav')
        Slice = ROOT.RooFit.Slice(dflav)

        ProjWData = ROOT.RooFit.ProjWData(ebeam_aset, ebeamdata)
        
        dataset.plotOn(mbcFrame, Cut)
        mbcFrame.getAttMarker().SetMarkerSize(0.6)
        mbcFrame.Draw()


        pdf.plotOn(mbcFrame, LineColor, LineWidth, Slice, ProjWData)

        nfitParam = len(pars) - 2
        chisq_ndof = mbcFrame.chiSquare(nfitParam)
        
        nbin = mbcFrame.GetNbinsX()
        ndof = nbin - nfitParam
        chisq = chisq_ndof * ndof
    
        chisqbox = ROOT.TPaveText(0.1, 0.1, 0.55, 0.2, 'BRNDC')
        chisqbox.SetFillColor(0)
        chisqbox.SetBorderSize(1)
        chisqbox.AddText('#chi^{2}/ndof = %.2f/%d =  %.2f' %
                         (chisq, ndof, chisq_ndof))

        mbcFrame.addObject(chisqbox)

        mbcFrame.SetTitle(title2)
        mbcFrame.Draw()


        canvas.cd(3)
        mbcFrame = mbc.frame()
        
        paramWin1 = pdf.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") 
        mbcFrame.Draw() 
 

    canvas.Print(epsfile)
    tools.save_fit_result(pars, txtfile)

    if not test:
        tools.eps2png(epsfile)
        tools.eps2pdf(epsfile)
示例#8
0
文件: multspec.py 项目: xshi/dhad
def output_multspec(reweight, pt, mode, selfile, label, test=False):
    mode, signs = tools.get_modekey_sign(mode)
    f = TFile(selfile, 'recreate')

    load_roofit_lib('signal', label)
    
    from ROOT import RooRealVar, RooDataSet, RooArgList, RooArgSet, \
         RooGaussian, RooArgusBG, RooCBShape, RooAddPdf, RooPolynomial, \
         gSystem, TCanvas

    efffile = selfile.replace('.root', '.db')
    effs = shelve.open(efffile)

    mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV')
    weight2 = RooRealVar('weight2', 'weight', 1)
    weight3 = RooRealVar('weight3', 'weight', 1)
    mbc_aset = RooArgSet(mbc)

    ntrack_d0 = TH1F('ntrack_d0', 'Number of other side tracks for D^{0} #rightarrow K#pi', 10, 0, 9)
    ntrack_dp = TH1F('ntrack_dp', 'Number of other side tracks for D^{+} #rightarrow K#pi#pi', 10, 0, 9)
    
    unweight_sum = 0
    reweight_ntr_sum = 0; reweight_npi0_sum = 0
    reweight_ntr_mcand_cnt = 0; reweight_npi0_mcand_cnt = 0
    unweight_dmbc = TH1F('unweight_dmbc', 'm_{BC}, direct MC', 100, 1.83, 1.89)
    reweight_ntr_dmbc = TH1F('reweight_ntr_dmbc', 'm_{BC}, track reweighted MC',
                             100, 1.83, 1.89)
    reweight_npi0_dmbc = TH1F('reweight_npi0_dmbc', 'm_{BC}, #pi^{0} reweighted MC',
                              100, 1.83, 1.89)
    
    chgpart = (pdgid_pip, pdgid_pim, pdgid_Kp, pdgid_Km, pdgid_mup, pdgid_mum,
               pdgid_ep, pdgid_em)
    neupart = (pdgid_KL, pdgid_piz, pdgid_gamma)
    intpart = chgpart + neupart

    ntr_denoms = {}; gen_dmbc_ntr = {}; npi0_denoms = {}; gen_dmbc_npi0 = {}
    for i in range(7+1):
        ntr_denoms[i] = 0
        gen_dmbc_ntr[i] = TH1F('gen_dmbc_ntr_'+`i`, 'm_{BC} for '+`i`+' tracks',
                               100, 1.83, 1.89)
    for i in range(5+1):
        npi0_denoms[i] = 0
        gen_dmbc_npi0[i] = TH1F('gen_dmbc_npi0_'+`i`, 'm_{BC} for '+`i`+' #pi^{0}',
                                100, 1.83, 1.89)

    ntotal = 0
    nselected = 0

    for pte in pt:
        ntotal += 1
        if test and nselected > 10:
            break

        if test and ntotal > 1000:
            break
        
        if pte.ecm < 3.7:
            continue
        othsidetrk = 0; othsidepi0 = 0
        dtree = makeDDecaySubTree(pte, -1)
    
        ddesc = dtree[0].interestingDescendants(intpart, False, False)

        for i in ddesc:
            if i.pdgid in chgpart:
                othsidetrk += 1
            if (i.pdgid in chgpart and i.parent.pdgid == pdgid_KS and
                len(i.parent.daughters) == 1):
                # This absurd special case is due to GEANT's "K_S -> pi" decay
                othsidetrk += 1
            if i.pdgid == pdgid_piz:
                othsidepi0 += 1
            if (i.pdgid == pdgid_KS) and len(i.daughters) != 2:
                print i

        if mode >= 200:
            mod2 = 1
        else:
            mod2 = 0

        if (othsidetrk % 2) != mod2:
            print '-----------------------------------', othsidetrk
            print chgpart
            # for node in makeDecayTree(pte):
            #  pass
            #  if len(node.daughters) == 0 and node.pdgid in chgpart:
            #  print node

        choice = chooseD(mode, pte, 1)

        if choice != None and not passDE(choice, pte):
            choice = None
            
        unweight_sum += 1
        
        index_tr = getindex(othsidetrk, ntr_denoms)
        ntr_denoms[index_tr] += 1
        index_pi0 = getpi0index(othsidepi0, npi0_denoms)
        npi0_denoms[index_pi0] += 1

        final_weight_vector_ntr = attr.multiplicity_weight_ntr[reweight]
        initial_weight_vector_ntr = attr.multiplicity_weight_ntr['init']

        final_weight_vector_npi0 = attr.multiplicity_weight_npi0[reweight]
        initial_weight_vector_npi0 = attr.multiplicity_weight_npi0['init']

        reweight_ntr_sum += (final_weight_vector_ntr[index_tr]/
                             initial_weight_vector_ntr[index_tr])
        reweight_npi0_sum += (final_weight_vector_npi0[index_pi0]/
                              initial_weight_vector_npi0[index_pi0])
        if choice != None:
            nselected += 1
            
            unweight_dmbc.Fill(pte.dmbc[choice])
            reweight_ntr_dmbc.Fill(pte.dmbc[choice],
                                    (final_weight_vector_ntr[index_tr]/
                                     initial_weight_vector_ntr[index_tr]))
            reweight_npi0_dmbc.Fill(pte.dmbc[choice],
                                    (final_weight_vector_npi0[index_pi0]/
                                     initial_weight_vector_npi0[index_pi0]))
            gen_dmbc_ntr[index_tr].Fill(pte.dmbc[choice])
            gen_dmbc_npi0[index_pi0].Fill(pte.dmbc[choice])
            mbc.setVal(pte.dmbc[choice])
            

    effs['npi0_denom'] = npi0_denoms
    effs['ntr_denom'] = ntr_denoms
    effs['unweight_sum'] = unweight_sum
    effs['reweight_ntr_sum'] = reweight_ntr_sum
    effs['reweight_npi0_sum'] = reweight_npi0_sum
    
    effs.close()
    #sys.stdout.write('Saved %s \n' %efffile)

    f.Write()
    f.Close()
    pt.Delete()

    return nselected, ntotal