示例#1
0
文件: histo.py 项目: HEP-KBFI/stpol
def analysis_tree_all_reweighed(graph, cuts, snodes, **kwargs):
    cutnodes = []
    for cut_name, cut in cuts:
        lepton = cut_name.split("_")[0]

        cutnode = tree.CutNode(cut, graph, cut_name, snodes, [],
            filter_funcs=[
                lambda x,lepton=lepton: tree.is_samp(x, lepton)
        ])
        cutnodes.append(
            cutnode
        )

        #an extra QCD cleaning cut on top of the previous cut, which is only done in antiiso
        for syst in ["nominal", "up", "down"]:
            cn = tree.CutNode(
                Cuts.antiiso(lepton, syst) * Cuts.deltaR_QCD(),
                graph, "antiiso_%s" % syst, [cutnode], [],
                filter_funcs=[
                    lambda p: tree.is_samp(p, "antiiso")
                ]
            )
            cutnodes.append(
                cn
            )

    from histo_descs import create_plots
    create_plots(graph, cutnodes, **kwargs)
示例#2
0
    def test_plot(self):

        tdrstyle()
        paths = get_paths()
        dataset = 'Jul15'
        lepton = 'mu'
        systematic = 'nominal'
        iso = 'iso'

        #Define the different plots to make
        items = [
            ('tchan1', paths[dataset]['mc'][lepton][systematic][iso], 'T_t_ToLeptons.root', Cuts.n_jets(2), '1.0'),
            ('tbarchan1', '-.-', 'Tbar_t_ToLeptons.root', Cuts.n_jets(2), '1.0'),

            ('tchan2', '-.-', 'T_t_ToLeptons.root', Cuts.n_jets(2)*Cuts.n_tags(1), '1.0'),
            ('tbarchan2', '-.-', 'Tbar_t_ToLeptons.root', Cuts.n_jets(2)*Cuts.n_tags(1), '1.0'),
        ]
        items = fill_list(items)

        #Dewfine a callbakc for normalization
        def normalize(hn, h):
            norm(h)
            return h

        #The final plot definition to draw
        plot_def = {
            'var': 'mt_mu',
            'range': [20, 0, 300],
            'items': items,
            'merge_cmds': {'signal 2J1T':['tchan2', 'tbarchan2'], 'signal 2J':['tchan1', 'tbarchan1']},
            'xlab': 'M_t(W)'
            #'hist_callback': normalize
        }

        #Now do the draw comparison
        canv, hists = compare_plot(plot_def)

        #Do some post-checking that everything went fine
        for hn, h in hists.items():
            if hn=='signal 2J':
                self.assertAlmostEqual(h.Integral(), 39472.452918)
            elif hn=='signal 2J1T':
                self.assertAlmostEqual(h.Integral(), 16414.4804941)

        print "Saving the plot to test_plot.png"
        canv.SaveAs('test_plot.png')
示例#3
0
 def gen_hist(sample):
     hi = sample.drawHistogram("true_cos_theta", str(Cuts.true_lepton(lep)), binning=list(binning))
     hi.Scale(s.lumiScaleFactor(lumi))
     return hi
示例#4
0
文件: data_mc.py 项目: HEP-KBFI/stpol
def data_mc_plot(samples, plot_def, name, lepton_channel, lumi, weight, physics_processes, use_antiiso=False):

    logger.info('Plot in progress %s' % name)

    merge_cmds = PhysicsProcess.get_merge_dict(physics_processes) #The actual merge dictionary

    var = plot_def['var']

    #Id var is a list/tuple, assume
    if not isinstance(var, basestring):
        try:
            if lepton_channel == 'ele':
                var = var[0]
            elif lepton_channel == 'mu':
                var = var[1]
        except Exception as e:
            logger.error("Plot variable 'var' specification incorrect for multi-variable plot: %s" % str(var))
            raise e
    cut = None
    if lepton_channel == 'ele':
        cut = plot_def['elecut']
    elif lepton_channel == 'mu':
        cut = plot_def['mucut']

    cut_str = str(cut)

    plot_range = plot_def['range']

    do_norm = False
    if 'normalize' in plot_def.keys() and plot_def['normalize']:
        do_norm = True
    hists_mc = dict()
    hists_data = dict()
    for name, sample in samples.items():
        logger.debug("Starting to plot %s" % name)
        if sample.isMC:
            hist = sample.drawHistogram(var, cut_str, weight=str(weight), plot_range=plot_range)
            hist.Scale(sample.lumiScaleFactor(lumi))
            hists_mc[sample.name] = hist
            if do_norm:
                Styling.mc_style_nostack(hists_mc[sample.name], sample.name)
            else:
                Styling.mc_style(hists_mc[sample.name], sample.name)

            if "fitpars" in plot_def.keys():
                rescale_to_fit(sample.name, hist, plot_def["fitpars"][lepton_channel])
        elif "antiiso" in name and plot_def['estQcd'] and not use_antiiso:

            # Make loose template
            #Y U NO LOOP :) -JP
            region = '2j1t'
            if '2j0t' in plot_def['estQcd']: region='2j0t'
            if '3j0t' in plot_def['estQcd']: region='3j0t'
            if '3j1t' in plot_def['estQcd']: region='3j1t'
            if '3j2t' in plot_def['estQcd']: region='3j2t'

            qcd_extra_cut = Cuts.deltaR(0.3)*Cuts.antiiso(lepton_channel)

            #Take the loose template with a good shape from the N-jet, M-tag, post lepton selection region with high statistics
            qcd_loose_cut = cutlist[region]*cutlist['presel_'+lepton_channel]*qcd_extra_cut

            #Take the template which can be correctly normalized from the actual region with inverted isolation cuts
            qcd_cut = cut*qcd_extra_cut

            hist_qcd_loose = sample.drawHistogram(var, str(qcd_loose_cut), weight="1.0", plot_range=plot_range)
            hist_qcd = sample.drawHistogram(var, str(qcd_cut), weight="1.0", plot_range=plot_range)
            logger.debug("Using the QCD scale factor %s: %.2f" % (plot_def['estQcd'], qcdScale[lepton_channel][plot_def['estQcd']]))
            

            hist_qcd.Scale(qcdScale[lepton_channel][plot_def['estQcd']])
            hist_qcd_loose.Scale(hist_qcd.Integral()/hist_qcd_loose.Integral())
            if var=='cos_theta':
                hist_qcd=hist_qcd_loose
            sampn = "QCD"+sample.name

            #Rescale the QCD histogram to the eta_lj fit
            if "fitpars" in plot_def.keys():
                rescale_to_fit(sampn, hist_qcd, plot_def["fitpars"][lepton_channel])

            hists_mc[sampn] = hist_qcd
            hists_mc[sampn].SetTitle('QCD')
            if do_norm:
                Styling.mc_style_nostack(hists_mc[sampn], 'QCD')
            else:
                Styling.mc_style(hists_mc[sampn], 'QCD')

        #Real ordinary data in the isolated region
        elif not "antiiso" in name or use_antiiso:
            hist_data = sample.drawHistogram(var, cut_str, weight="1.0", plot_range=plot_range)
            hist_data.SetTitle('Data')
            Styling.data_style(hist_data)
            hists_data[name] = hist_data


    if len(hists_data.values())==0:
        raise Exception("Couldn't draw the data histogram")

    #Combine the subsamples to physical processes
    hist_data = sum(hists_data.values())
    merge_cmds['QCD']=["QCD"+merge_cmds['data'][0]]
    order=['QCD']+PhysicsProcess.desired_plot_order
    if plot_def['log']:
        order = PhysicsProcess.desired_plot_order_log+['QCD']
    merged_hists = merge_hists(hists_mc, merge_cmds, order=order)

    if hist_data.Integral()<=0:
        logger.error(hists_data)
        logger.error("hist_data.entries = %d" % hist_data.GetEntries())
        logger.error("hist_data.integral = %d" % hist_data.Integral())
        raise Exception("Histogram for data was empty. Something went wrong, please check.")

    if do_norm:
        for k,v in merged_hists.items():
            v.Scale(1./v.Integral())
        hist_data.Scale(1./hist_data.Integral())

    htot = sum(merged_hists.values())

    chi2 = hist_data.Chi2Test(htot, "UW CHI2/NDF")
    if chi2>20:#FIXME: uglyness
        logger.error("The chi2 between data and MC is large (%s, chi2=%.2f). You may have errors with your samples!" %
            (name, chi2)
        )
        logger.info("MC  : %s" % " ".join(map(lambda x: "%.1f" % x, list(htot.y()))))
        logger.info("DATA: %s" % " ".join(map(lambda x: "%.1f" % x, list(hist_data.y()))))
        logger.info("diff: %s" % str(
            " ".join(map(lambda x: "%.1f" % x, numpy.abs(numpy.array(list(htot.y())) - numpy.array(list(hist_data.y())))))
        ))

    merged_hists_l = merged_hists.values()

    PhysicsProcess.name_histograms(physics_processes, merged_hists)

    leg_style = ['p','f']
    if do_norm:
        leg_style=['p','l']
    leg = legend([hist_data] + list(reversed(merged_hists_l)), legend_pos=plot_def['labloc'], styles=leg_style)

    canv = ROOT.TCanvas()

    #Make the stacks
    stacks_d = OrderedDict()
    stacks_d["mc"] = merged_hists_l
    stacks_d["data"] = [hist_data]

    #label
    xlab = plot_def['xlab']
    if not isinstance(xlab, basestring):
        if lepton_channel == 'ele':
            xlab = xlab[0]
        else:
            xlab = xlab[1]
    ylab = 'N / '+str((1.*(plot_range[2]-plot_range[1])/plot_range[0]))
    if plot_def['gev']:
        ylab+=' GeV'
    fact = 1.5
    if plot_def['log']:
        fact = 10

    plow=0.3
    if do_norm:
        plow=0

    #Make a separate pad for the stack plot
    p1 = ROOT.TPad("p1", "p1", 0, plow, 1, 1)
    p1.Draw()
    p1.SetTicks(1, 1);
    p1.SetGrid();
    p1.SetFillStyle(0);
    p1.cd()

    stacks = plot_hists_stacked(p1, stacks_d, x_label=xlab, y_label=ylab, max_bin_mult = fact, do_log_y = plot_def['log'], stack = (not do_norm))

    #Put the the lumi box where the legend is not
    boxloc = 'top-right'
    if plot_def['labloc'] == 'top-right':
        boxloc = 'top-left'
    chan = 'Electron'
    if lepton_channel == "mu":
        chan = 'Muon'

    additional_comments = ""
    if 'cutname' in plot_def.keys():
        additional_comments += ", " + plot_def['cutname'][lepton_channel]
    lbox = lumi_textbox(lumi,
        boxloc,
        'preliminary',
        chan + ' channel' + additional_comments
    )

    #Draw everything
    lbox.Draw()
    leg.Draw()
    canv.Draw()

    #Keep the handles just in case
    canv.PAD1 = p1
    canv.STACKS = stacks
    canv.LEGEND = legend
    canv.LUMIBOX = lbox

    return canv, merged_hists, htot, hist_data
示例#5
0
    #isolated files are by default in $STPOL_DIR/step3_latest/mu/iso/nominal/*.root
    datadirs["iso"] = "/".join((os.environ["STPOL_DIR"], "step3_latest", "mu" ,"iso", "nominal"))
    #Use the anti-isolated data for QCD $STPOL_DIR/step3_latest/mu/antiiso/nominal/SingleMu.root
    datadirs["antiiso"] = "/".join((os.environ["STPOL_DIR"], "step3_latest", "mu" ,"antiiso", "nominal"))

    #Load all the samples in the isolated directory
    samples = Sample.fromDirectory(datadirs["iso"], out_type="dict")
    samples["SingleMu_aiso"] = Sample.fromFile(datadirs["antiiso"] + "/SingleMu.root")

    hists_mc = dict()
    hist_data = None

    #Define the variable, cut, weight and lumi
    var = "cos_theta"
    cut_name = "2j1t"
    cut_str = str(Cuts.n_jets(2)*Cuts.n_tags(1)*Cuts.lepton_veto*Cuts.one_muon*Cuts.mt_mu*Cuts.top_mass_sig*Cuts.eta_lj)
    weight_str = "1.0"
    lumi = 20000 #FIXME: take from the step2 output filelists/step2/latest/iso/nominal/luminosity.txt

    #nbins, min, max
    plot_range= [20, -1, 1]

    for name, sample in samples.items():
        if sample.isMC:
            hist = sample.drawHistogram(var, cut_str, weight=weight_str, plot_range=plot_range)
            hist.Scale(sample.lumiScaleFactor(lumi)*mc_sf)
            hists_mc[sample.name] = hist.hist
            Styling.mc_style(hists_mc[sample.name], sample.name)
        elif name == "SingleMu":
            hist_data = sample.drawHistogram(var, cut_str, weight="1.0", plot_range=plot_range)
            Styling.data_style(hist_data)
示例#6
0
from plots.common.sample import Sample
from plots.common.sample_style import ColorStyleGen
from plots.common.hist_plots import plot_hists
from plots.common.cuts import Cuts, Weights
from plots.common.legend import legend
from plots.common.tdrstyle import tdrstyle

if __name__=="__main__":
	samp = Sample.fromFile("~/Documents/stpol/data/out_step3_joosep_11_07_19_44/mu/iso/nominal/W4Jets_exclusive.root")
	samp.tree.AddFriend("trees/WJets_weights", samp.file_name)

	tdrstyle()
	
	cut = str(Cuts.final(2,0)*Cuts.Wflavour("W_heavy"))
	mean_weight = samp.drawHistogram(str(Weights.wjets_madgraph_weight("nominal")), cut, weight="1.0", plot_range=[200, 0, 2]).hist.GetMean()
	print "mean weight=%.2f" % mean_weight
	hi0 = samp.drawHistogram("cos_theta", cut, weight="1.0", plot_range=[20, -1, 1]).hist
	hi0.Scale(samp.lumiScaleFactor(20000))
	hi1 = samp.drawHistogram("cos_theta", cut, weight=str(Weights.wjets_madgraph_weight("nominal")), plot_range=[20, -1, 1]).hist
	hi1.Scale(samp.lumiScaleFactor(20000))
	hi2 = samp.drawHistogram("cos_theta", cut, weight=str(Weights.wjets_madgraph_weight("wjets_up")), plot_range=[20, -1, 1]).hist
	hi2.Scale(samp.lumiScaleFactor(20000))
	hi3 = samp.drawHistogram("cos_theta", cut, weight=str(Weights.wjets_madgraph_weight("wjets_down")), plot_range=[20, -1, 1]).hist
	hi3.Scale(samp.lumiScaleFactor(20000))

	hists = [hi0, hi1, hi2, hi3]
	#for h in hists:
	#	h.Scale(1.0/h.Integral())
	hi0.SetTitle("unweighted")
	hi1.SetTitle("weighted")
	hi2.SetTitle("weighted wjets_up")
示例#7
0
mvaFileList['sig']['eval']= [
    'T_t_ToLeptons',
    'Tbar_t_ToLeptons'
]
mvaFileList['bg']['train']= [
    'TTJets_MassiveBinDECAY',
    'WJets_inclusive'
]
mvaFileList['bg']['eval']= [
    'TTJets_FullLept',
    'TTJets_SemiLept',
    'W1Jets_exclusive',
    'W2Jets_exclusive',
    'W3Jets_exclusive',
    'W4Jets_exclusive'
]

varList={}
varList['ele'] = [ 'top_mass','eta_lj','C','met','mt_el','mass_bj','mass_lj','el_pt','pt_bj' ]
varList['mu']  = [ 'top_mass','eta_lj','C','met','mt_mu','mass_bj','mass_lj','mu_pt','pt_bj' ]

varRank={}
varRank['ele'] = ['top_mass', 'C', 'eta_lj', 'el_pt', 'mt_el', 'pt_bj', 'mass_bj', 'met', 'mass_lj']
varRank['mu'] = ['top_mass', 'eta_lj', 'C', 'mu_pt', 'mt_mu', 'met', 'mass_bj', 'pt_bj', 'mass_lj']

from plots.common.cuts import Cut,Cuts

cuts = {}
cuts['ele'] = Cuts.n_jets(2)*Cuts.n_tags(1)*Cuts.hlt_isoele*Cuts.lepton_veto*Cuts.pt_jet*Cuts.one_electron*Cuts.rms_lj*Cuts.met()
cuts['mu']  = Cuts.n_jets(2)*Cuts.n_tags(1)*Cuts.hlt_isomu*Cuts.lepton_veto*Cuts.pt_jet*Cuts.one_muon*Cuts.rms_lj*Cuts.mt_mu()
示例#8
0
from plots.common.cuts import Cuts,Cut
import copy
from plots.common.utils import PhysicsProcess, NestedDict

cp = copy.deepcopy

#FIXME: these cutlists need to be factorised away badly!
cutlist={}
cutlist['2j']=Cuts.n_jets(2)
cutlist['3j']=Cuts.n_jets(3)

cutlist['2j1t']=Cuts.n_jets(2)*Cuts.n_tags(1)
cutlist['2j0t']=Cuts.n_jets(2)*Cuts.n_tags(0)
cutlist['3j0t']=Cuts.n_jets(3)*Cuts.n_tags(0)
cutlist['3j1t']=Cuts.n_jets(3)*Cuts.n_tags(1)
cutlist['3j2t']=Cuts.n_jets(3)*Cuts.n_tags(2)


#Needed for RMS cut validation
cutlist['presel_ele_no_rms']=Cuts.hlt_isoele*Cuts.lepton_veto*Cuts.pt_jet*Cuts.one_electron
cutlist['presel_mu_no_rms']=Cuts.hlt_isomu*Cuts.lepton_veto*Cuts.pt_jet*Cuts.one_muon

cutlist['presel_ele'] = cutlist['presel_ele_no_rms']*Cuts.rms_lj
cutlist['presel_mu'] = cutlist['presel_mu_no_rms']*Cuts.rms_lj

cutlist['nomet_ele']=cutlist['presel_ele']*Cuts.top_mass_sig*Cuts.eta_lj
cutlist['nomt_mu']=cutlist['presel_mu']*Cuts.top_mass_sig*Cuts.eta_lj
cutlist['noeta_ele']=cutlist['presel_ele']*Cuts.top_mass_sig*Cuts.met()
cutlist['noeta_mu']=cutlist['presel_mu']*Cuts.top_mass_sig*Cuts.mt_mu()
cutlist['final_ele']=cutlist['nomet_ele']*Cuts.met()
cutlist['final_mu']=cutlist['nomt_mu']*Cuts.mt_mu()
示例#9
0
文件: yields.py 项目: HEP-KBFI/stpol
from plots.common.cuts import Cuts
import sys

if __name__=="__main__":

    for fi in sys.argv[1:]:
        print fi
        samp = Sample.fromFile(fi)
        print "Lumi scale factor: ", samp.lumiScaleFactor(20000)
        for lep in ["mu", "ele"]:
            if "/%s/"%lep not in fi:
                continue
            print lep
            cut = None
            for cutname, _cut in [
                ("hlt", Cuts.hlt(lep)),
                ("lep", Cuts.single_lepton(lep)),
                ("2J", Cuts.n_jets(2)),
                ("1T", Cuts.n_tags(1)),
                ("MET/MtW", Cuts.metmt(lep)),
                ("rms", Cuts.rms_lj),
                ("Mtop", Cuts.top_mass_sig),
                ("etalj", Cuts.eta_lj)
                ]:
                if not cut:
                    cut = _cut
                else:
                    cut *= _cut
                try:
                    hi = samp.drawHistogram("eta_lj", str(cut), binning=[50, -5, 5])
                    hi.Scale(samp.lumiScaleFactor(20000))
示例#10
0
    merge_cmd["WJets incl"] = ["WJets_inclusive"]
    merge_cmd["WJets excl"] = [
        "W1Jets_exclusive", "W2Jets_exclusive", "W3Jets_exclusive",
        "W4Jets_exclusive"
    ]
    merged_hists = merge_hists(histsD, merge_cmd)

    normd = dict()
    for hn, h in merged_hists.items():
        normd[hn] = get_hist_int_err(h)
    return merged_hists, normd


if __name__ == "__main__":
    #cut = Cuts.mu * Cuts.n_jets(2) * Cuts.mt_mu * Cuts.top_mass_sig * Cuts.eta_lj * Cuts.n_tags(1)
    cut = Cuts.mu * Cuts.final(2, 1)

    cutsref = [
        ("1mu", Cuts.mu, (5879691, 268238, 50236)),
        ("2J", Cuts.mu * Cuts.n_jets(2), (972069, 75674, 22387)),
        ("met", Cuts.mu * Cuts.n_jets(2) * Cut("met>45"), (404707, 46185,
                                                           11052)),
        ("0T", Cuts.mu * Cuts.n_jets(2) * Cut("met>45") * Cuts.n_tags(0),
         (-1, -1, -1)),
        ("rmslj_0T", Cuts.mu * Cuts.n_jets(2) * Cut("met>45") *
         Cuts.n_tags(0) * Cuts.rms_lj, (-1, -1, -1)),
        ("1T", Cuts.mu * Cuts.n_jets(2) * Cut("met>45") * Cuts.n_tags(1),
         (6197, 17505, 4173)),
        ("rmslj_1T", Cuts.mu * Cuts.n_jets(2) * Cut("met>45") *
         Cuts.n_tags(1) * Cuts.rms_lj, (5095, 14197, 3664)),
    ]
示例#11
0
文件: flat.py 项目: HEP-KBFI/stpol
        
        #ROOT functions can be used
        ("abs_eta_lj", "abs(eta_lj)", [20, 0, 5]),

        ("bdt", Cuts.mva_vars['mu'], [60, -1, 1]),
    ]

    #Define all the weight strategies that we want to apply
    weights = [
        ("weight__nominal", Weights.total_weight("mu")),

        #Demonstrate reweighting
        ("weight__puw", Weights.pu("nominal")),
        ("weight__puw_up", Weights.pu("up")),
    ]

    #All the cut regions that we are interested in
    cuts = [
        ("2j0t", Cuts.mt_mu()*Cuts.n_jets(2)*Cuts.n_tags(0)*Cuts.lepton("mu")*Cuts.hlt("mu")),
        ("2j1t", Cuts.mt_mu()*Cuts.n_jets(2)*Cuts.n_tags(1)*Cuts.lepton("mu")*Cuts.hlt("mu")),
        ("final_cb_2j1t", Cuts.final(2,1))
    ]

    #Construct the analysis chain
    snodes, out = analysis_tree(cuts, weights, variables, args.infiles, args.outfile)

    print "Recursing down"
    for sn in snodes:
        sn.recurseDown()

    out.close()
示例#12
0
文件: tree.py 项目: HEP-KBFI/stpol
    #Create the sink to a file
    hsaver = ObjectSaver(args.outfile)

    #Load the samples
    sample_nodes = [
        SampleNode(hsaver, graph, inf, [], []) for inf in args.infiles
    ]

    #Different lepton channels
    channel = Node(graph, "channel", sample_nodes, [])
    channels = dict()

    # sample --> channels['mu'], channels['ele']
    channels['mu'] = CutNode(
        Cuts.hlt("mu")*Cuts.lepton("mu"),
        graph, "mu", [channel], [], filter_funcs=[lambda x: is_samp(x, 'mu')]
    )
    channels['ele'] = CutNode(
        Cuts.hlt("ele")*Cuts.lepton("ele"),
        graph,
        "ele", [channel], [], filter_funcs=[lambda x: is_samp(x, 'ele')]
    )

    # muons: channels['mu'] --> [iso, antiiso]
    # electrons: channels['ele'] --> [iso, antiiso]
    isos = dict()
    isol = []
    for lep, par in [
        ('mu', [channels['mu']]),
        ('ele', [channels['ele']])
示例#13
0
proc = 'ele'
if '/mu/' in dir:
    prt = 'mu'
    proc = 'mu'

physics_processes = PhysicsProcess.get_proc_dict(lepton_channel=proc)
merge_cmds = PhysicsProcess.get_merge_dict(physics_processes)

if len(sys.argv) == 3:
    flist=[dir+'/'+sys.argv[2]]
else:
    flist=get_file_list(merge_cmds,sys.argv[1])

cut = str(cutlist['2j1t']*cutlist['presel_ele']*Cuts.met)
if '/mu/' in dir:
    cut = str(cutlist['2j1t']*cutlist['presel_mu']*Cuts.mt_mu())

for f in flist:
    print "Starting:",f
    tf=TFile(f,'UPDATE')
    t=tf.Get("trees/Events")
    t.AddFriend('trees/WJets_weights')
    print cut
    ct=t.CopyTree(cut)
    print t, ct
    print t.GetEntries(), ct.GetEntries()
    ct.SetName("Events_MVAwQCD")
    tf.cd("trees")
    ct.Write("", TObject.kOverwrite)
    tf.Close()
示例#14
0
import logging
if __name__=="__main__":

	tdrstyle()

	logging.basicConfig(level=logging.INFO)
	basepath = get_paths(samples_dir="data/83a02e9_Jul22_sftotal/", dataset="latest")
	sampnames = [
		"TTJets_FullLept", "TTJets_SemiLept",
		"T_t_ToLeptons", "Tbar_t_ToLeptons",
		"W1Jets_exclusive", "W2Jets_exclusive", "W3Jets_exclusive", "W4Jets_exclusive"

	]
	path = basepath["mc"]["mu"]["nominal"]["iso"]

	cut = Cuts.final(2,1)*Cuts.mu
	var = "cos_theta"
	plot_range=[20, -1, 1]
	lumi = lumi_iso["mu"]
	plot_args = {"x_label": "cos #theta"}


	weights = [
	    ("unw", "1.0"),
	    ("nom", "b_weight_nominal"),
	    ("bc_up", "b_weight_nominal_BCup"),
	    ("bc_down", "b_weight_nominal_BCdown"),
	    ("l_up", "b_weight_nominal_Lup"),
	    ("l_down", "b_weight_nominal_Ldown"),
	]
	hists = NestedDict()
示例#15
0
文件: met_phi.py 项目: HEP-KBFI/stpol
        "binning": [20, -1, 1]
    }
    variables["bdt"] = {
        "name": "bdt",
        "var": Cuts.mva_vars['mu'],
        "binning": [60, -1, 1]
    }

    weights = [
        ("weight__nominal", Weights.total_weight("mu")),
    ]


    c1 = (
        "2j0t",
        Cuts.mt_mu()*Cuts.n_jets(2)*Cuts.n_tags(0)*Cuts.lepton("mu")*Cuts.hlt("mu"),
    )
    c2 = (
        "2j1t",
        Cuts.mt_mu()*Cuts.n_jets(2)*Cuts.n_tags(1)*Cuts.lepton("mu")*Cuts.hlt("mu"),
    )
    c3 = (
        "final_cb_2j1t",
        Cuts.final(2,1),
    )
    cuts = [c1, c2, c3]

    varnodes = {}
    for k, v in variables.items():
        for c in cuts:
            vn = tree.hist_node(graph, v, c, weights)
示例#16
0
文件: histo.py 项目: HEP-KBFI/stpol
    parser = argparse.ArgumentParser(
        description='Produces a hierarchy of histograms corresponding to cuts and weights.'
    )

    parser.add_argument('outfile', action='store',
        help="The output file name."
    )

    parser.add_argument('infiles', nargs='+',
        help="The input file names"
    )

    args = parser.parse_args()

    cuts_jet_tag = [
        ("%dj%dt"%(n,m), Cuts.n_jets(n)*Cuts.n_tags(m)) for n in [2,3] for m in [0,1,2]
    ]
    # cuts_jet_tag = [
    #     ("2j1t", Cuts.n_jets(2)*Cuts.n_tags(1))
    # ]

    cuts = []
    for cutname, cbline in cuts_jet_tag:
        for lep in ["mu", "ele"]:
            cn = "%s_%s" % (lep, cutname)
            baseline = Cuts.lepton(lep) * Cuts.hlt(lep) * Cuts.metmt(lep) * Cuts.rms_lj
            cuts += [
                #Without the MET cut
                ("%s_nomet" % cn, Cuts.lepton(lep) * Cuts.hlt(lep) * Cuts.rms_lj * cbline),

                #Baseline for fit
示例#17
0
                s.tree.AddFriend("trees/WJets_weights", s.tfile)

    else:
        samples = {}

    out_dir = os.environ["STPOL_DIR"] + "/out/plots/wjets"
    if args.tag:
        out_dir += "/" + args.tag
    mkdir_p(out_dir)

    # plot_ratios("2J0T", Cuts.final(2,0), samples, out_dir, args.recreate)
    # plot_ratios("2J1T", Cuts.final(2,1), samples, out_dir, args.recreate)

    colls_in, colls_out = plot_sherpa_vs_madgraph(
        costheta, "2J",
        Cuts.mu*Cuts.final_jet(2),
        samples.values(), out_dir, recreate=args.recreate, legend_pos="top-left", nudge_x=-0.03, nudge_y=0, systematic="nominal"
    )

    coll_in, coll_out = plot_sherpa_vs_madgraph(
        costheta, "2J0T",
        Cuts.mu*Cuts.final(2,0),
        samples.values(), out_dir, recreate=args.recreate, legend_pos="top-left", nudge_x=-0.03, nudge_y=0
    )

    coll_in, coll_out = plot_sherpa_vs_madgraph(
        costheta, "2J1T",
        Cuts.mu*Cuts.final(2,1),
        samples.values(), out_dir, recreate=args.recreate, legend_pos="top-left", nudge_x=-0.03, nudge_y=0
    )
示例#18
0
from plots.common.sample import Sample
from plots.common.cuts import Cuts
import sys

if __name__=="__main__":
    if len(sys.argv)!=2:
        print "Usage: %s /path/to/mu/iso/nominal/T_t_ToLeptons.root" % sys.argv[1]
        sys.exit(0)

    s = Sample.fromFile(sys.argv[1])
    cut = Cuts.final(2,1)
    nentries = s.tree.Draw("cos_theta", str(cut))
    print "Nentries=",nentries
示例#19
0
            cuts[c0].setBaseCuts("n_jets == %d && n_tags == %d && n_veto_ele==0 && n_veto_mu==0" % (nj,nt))
            cuts[c0].setFinalCuts(str(Cuts.top_mass_sig))

            #Final cut in Njets, Ntags
            #This is the _FINAL_ cut, where we show cos_theta
            c1 = "final__%dj%dt" % (nj, nt)
            cuts[c1] = FitConfig(c1)
            cuts[c1].setFinalCuts(
                str(final_cut)
            )
            cuts[c].setBaseCuts("n_jets == %d && n_tags == %d && n_veto_ele==0 && n_veto_mu==0" % (nj,nt))
            

        s = "%dj" % nj
        cuts[s] = FitConfig(s)
        bc = str(Cuts.n_jets(nj)*Cuts.rms_lj*Cuts.lepton_veto)
        cuts[s].setBaseCuts(bc)
        cuts[s].setFinalCuts("1")

        s = "final_%dj" % nj
        cuts[s] = FitConfig(s)
        bc = str(Cuts.n_jets(nj)*Cuts.rms_lj)
        cuts[s].setBaseCuts(bc)
        cuts[s].setFinalCuts(str(final_cut))
    #Remove the name of this script from the argument list in order to not confuse ArgumentParser
    try:
        sys.argv.pop(sys.argv.index("get_qcd_yield.py"))
    except ValueError:
        pass
    import argparse
示例#20
0
    merge_cmd["t#bar{t} excl"] = ["TTJets_FullLept", "TTJets_SemiLept"]
    merge_cmd["QCD (MC)"] = ["QCDMu"]
    merge_cmd["t#bar{t} incl"] = ["TTJets_MassiveBinDECAY"]
    merge_cmd["WJets incl"] = ["WJets_inclusive"]
    merge_cmd["WJets excl"] = ["W1Jets_exclusive", "W2Jets_exclusive", "W3Jets_exclusive", "W4Jets_exclusive"]
    merged_hists = merge_hists(histsD, merge_cmd)

    normd = dict()
    for hn, h in merged_hists.items():
        normd[hn] = get_hist_int_err(h)
    return merged_hists, normd


if __name__=="__main__":
    #cut = Cuts.mu * Cuts.n_jets(2) * Cuts.mt_mu * Cuts.top_mass_sig * Cuts.eta_lj * Cuts.n_tags(1)
    cut = Cuts.mu * Cuts.final(2,1)

    cutsref = [
        ("1mu", Cuts.mu, (5879691, 268238, 50236)),
        ("2J", Cuts.mu*Cuts.n_jets(2), (972069, 75674, 22387)),
        ("met", Cuts.mu*Cuts.n_jets(2)*Cut("met>45"), (404707, 46185, 11052)),
        ("0T", Cuts.mu*Cuts.n_jets(2)*Cut("met>45")*Cuts.n_tags(0), (-1, -1, -1)),
        ("rmslj_0T", Cuts.mu*Cuts.n_jets(2)*Cut("met>45")*Cuts.n_tags(0)*Cuts.rms_lj, (-1, -1, -1)),
        ("1T", Cuts.mu*Cuts.n_jets(2)*Cut("met>45")*Cuts.n_tags(1), (6197, 17505, 4173)),
        ("rmslj_1T", Cuts.mu*Cuts.n_jets(2)*Cut("met>45")*Cuts.n_tags(1)*Cuts.rms_lj, (5095, 14197, 3664)),
    ]

    for (name, cut, (refW, refTT, refT)) in cutsref:
        #hist, norms = mc_amount(cut, "pu_weight*muon_IDWeight*muon_IsoWeight")
        hist, norms = mc_amount(cut, "1.0")
        print 80*"-"
示例#21
0
if __name__ == "__main__":
    logging.basicConfig(level=logging.WARNING)
    tdrstyle()
    ROOT.gStyle.SetOptTitle(0)
    out_dir = "/".join((os.environ["STPOL_DIR"], "out", "plots", "wjets", "flavour"))
    doHists = True
    doPlots = True
    if doHists:
        samps = [
            "W1Jets_exclusive.root",
            "W2Jets_exclusive.root",
            "W3Jets_exclusive.root",
            "W4Jets_exclusive.root",
            "WJets_sherpa.root",
        ]
        make_histos("2J", Cuts.one_muon * Cuts.n_jets(2), samps, out_dir)
        # make_histos("2J1T", Cuts.final(2, 1), samps, out_dir)
    if doPlots:
        cut_name = "2J"
        fnames = glob.glob(out_dir + "/%s/WJets_flavour_fracs__*.root" % cut_name)
        files = {}
        hists = {}
        for fn in fnames:
            files[re.match(".*__(.*).root", fn).group(1)] = File(fn)
        logging.info("files = %s" % str(files))

        for sn, fi in files.items():
            hi = fi.Get("flavour_counts")
            hi.SetName(sn)
            pn = sn
            Styling.mc_style(hi, pn)