def shape_variation(var, plot_range, varname, recreate, out_name): tot_hists = OrderedDict() tdrstyle() for wn, w in [ ("unw", Weight("1.0")), ("nominal", Weights.wjets_madgraph_shape_weight("nominal")), ("shape_up", Weights.wjets_madgraph_shape_weight("wjets_up")), ("shape_down", Weights.wjets_madgraph_shape_weight("wjets_down")) ]: p = data_mc( var, "2J0T_%s" % (wn), cut, Weights.total("mu", "nominal")*w, samples, ".", recreate, lumi_iso["mu"], plot_range=plot_range, ) for hn, h in p.hists.items(): logger.debug("%s %.2f" % (hn, h.Integral())) #sumw = [(sample.name, numpy.mean(root_numpy.root2array(sample.tfile.GetPath()[:-2], "trees/WJets_weights", branches=[str(w)])[str(w)])) for sample in samples] s = sum(p.hists.values()).Clone() tot_hists[wn] = s hc = HistCollection(tot_hists, name=out_name) for hn, h in hc.hists.items(): print hn, h.Integral() canv = plot_hists_dict(hc.hists, do_chi2=False, do_ks=True, x_label=varname, legend_pos="top-left") hc.hists.values()[0].SetTitle("shape variation") canv.SaveAs(out_name + ".png") hc.save(out_name) return hc, canv
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')
from plots.common.sample import get_paths, Sample from plots.common.utils import NestedDict from plots.common.cuts import Cuts from plots.common.cross_sections import lumi_iso from plots.common.utils import merge_hists from plots.common.histogram import HistCollection, norm from plots.common.hist_plots import plot_hists_dict import numpy, copy from plots.common.odict import OrderedDict from plots.common.tdrstyle import tdrstyle 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"}
""" A crude way to change the MC samples from nominal to a specific systematic run. Args: paths: a list with the filesystem paths to change. dest: the destination systematics. Returns: a list with the changed paths. """ return map(lambda x: x.replace("nominal", dest) if "nominal" in x else x, paths) if __name__=="__main__": logger.setLevel(logging.DEBUG) tdrstyle.tdrstyle() parser = argparse.ArgumentParser( description='Creates the final plots' ) parser.add_argument( "-c", "--channel", type=str, required=False, choices=["mu", "ele"], action="append", dest="channels", default=None, help="the lepton channel to use" ) parser.add_argument( "-i", "--indir", type=str, required=False, default=(os.environ["STPOL_DIR"] + "/step3_latest"), help="the input directory, which is expected to contain the subdirectories: mu/ele" ) parser.add_argument(
#Anti-iso region for s in systematics: if s == "Nominal": make_histogram(var, dataGroup, cuts.name, openedFiles, lumis, s, "antiiso", cuts.antiIsoCutsData) stack = make_stack(var, cuts.name + s, MCGroups, dataGroup, openedFiles, s, "antiiso", lumis, cuts.antiIsoCutsMC, cuts.antiIsoCutsData, "", cuts.name) stacks[var.name + s + "antiiso"] = stack #print "cuts",cuts.isoCutsData tdrstyle.tdrstyle() cst = TCanvas("Histogram", "Jet Systematics in final selection", 10, 10, 1000, 1000) lumibox = lumi_textbox(lumi_iso["mu"]) histos = [] hData = dataGroup.getHistogram(var, "Nominal", "iso" + cuts.name) #hQCDShapeOrig = dataGroup.getHistogram(var, "Nominal", "antiiso") hData.Draw("e1") hData.SetMarkerStyle(20) hData.SetAxisRange(0, 1000, "Y") stackSys = THStack("Stacksys", "stackName") for s in systematics: if s == "Nominal": stackNom = stacks[var.name + s + "iso"]
def plot_fit(fit, infile, outfile, result): tdrstyle() spl = fit.filename.split("__") var = spl[1] procstyles = OrderedDict() procstyles["tchan"] = "T_t" procstyles["wzjets"] = "WJets_inclusive" procstyles["top"] = "TTJets_FullLept" procstyles["qcd"] = "QCD" procnames = OrderedDict() procnames["wzjets"] = "W, Z" procnames["top"] = "t, #bar{t}" procnames["tchan"] = "signal (t-channel)" procnames["qcd"] = "QCD" hists_mc_pre = OrderedDict() hists_mc_post = OrderedDict() print "IN",infile print outfile fi1 = File(infile) fi2 = File(outfile) hist_data = fi1.Get(var+"__DATA") def loadhists(f): out = OrderedDict() for k in procnames.keys(): out[k] = f.Get(var+"__" + k) out[k].SetTitle(procnames[k]) Styling.mc_style(out[k], procstyles[k]) return out hists_mc_pre = loadhists(fi1) hists_mc_post = loadhists(fi2) print hists_mc_pre, hists_mc_post Styling.data_style(hist_data) of = OutputFolder(subdir="plots/final_fit") def plot_data_mc(hists_mc, hist_data, name): canv = ROOT.TCanvas() p1 = ROOT.TPad("p1", "p1", 0, 0.3, 1, 1) p1.Draw() p1.SetTicks(1, 1); p1.SetGrid(); p1.SetFillStyle(0); p1.cd() stacks_d = OrderedDict() print "MC",hists_mc print "VAL",hists_mc.values() stacks_d["mc"] = hists_mc.values() stacks_d["data"] = [hist_data] stacks = plot_hists_stacked( p1, stacks_d, x_label=var, y_label="", do_log_y=True ) leg = legend([hist_data] + list(reversed(hists_mc.values())), styles=["p", "f"]) print canv, hist_data print get_stack_total_hist(stacks["mc"]) ratio_pad, hratio = plot_data_mc_ratio(canv, get_stack_total_hist(stacks["mc"]), hist_data) plot_info = PlotMetaInfo( name, "CUT", "WEIGHT", [infile], subdir=fit.name, comments=str(result[SIGNAL]) ) of.savePlot(canv, plot_info) canv.Close() plot_data_mc(hists_mc_post, hist_data, "post_fit") plot_data_mc(hists_mc_pre, hist_data, "pre_fit")
for process in histos: dirs[process] = p.mkdir(process) #print histos for process in histos: dirs[process].cd() for subproc in histos[process]: histos[process][subproc].Write(hist_name + subproc) print process, subproc, hist_name #for subproc in histos[process]: # dirs[process] = p.mkdir(process) p.Close() tdrstyle() canvases = {} for process in histos: #Create the canvas canv = ROOT.TCanvas("c" + process, "c") canv.SetWindowSize(1000, 1000) canv.SetCanvasSize(1000, 1000) outf.write("\\begin{frame}[fragile]\n") outf.write("\\begin{verbatim}" + process + "\\end{verbatim}\n") outf.write("""\\begin{center} \\begin{tabular}{ l || c | c | r } \hline """) outf.write("Systematic & yield & Chi2/NDF & p-value \\\\ \hline\n")