def savePlots(title, saveName, listFromats, plot, Histos, keyHisto, listLegend, options, ratios=None, legendName=""): #create canvas c = {} pads = {} if options.doRatio: c[keyHisto] = TCanvas(saveName, keyHisto + plot.title, 700, 700 + 24 * len(listFlavors)) pads["hist"] = TPad("hist", saveName + plot.title, 0, 0.11 * len(listFlavors), 1.0, 1.0) else: c[keyHisto] = TCanvas(keyHisto, saveName + plot.title, 700, 700) pads["hist"] = TPad("hist", saveName + plot.title, 0, 0., 1.0, 1.0) pads["hist"].Draw() if ratios: for r in range(0, len(ratios)): pads["ratio_" + str(r)] = TPad("ratio_" + str(r), saveName + plot.title + str(r), 0, 0.11 * r, 1.0, 0.11 * (r + 1)) pads["ratio_" + str(r)].Draw() pads["hist"].cd() #canvas style if plot.logY: pads["hist"].SetLogy() if plot.grid: pads["hist"].SetGrid() #legend leg = TLegend(0.6, 0.4, 0.8, 0.6) leg.SetMargin(0.12) leg.SetTextSize(0.035) leg.SetFillColor(10) leg.SetBorderSize(0) #draw histos first = True option = drawOption optionSame = drawOption + "same" if plot.doPerformance: option = "AP" optionSame = "sameP" for i in range(0, len(Histos)): if Histos[i] is None: continue if first: if not plot.doPerformance: Histos[i].GetPainter().PaintStat(ROOT.gStyle.GetOptStat(), 0) Histos[i].SetTitle(title) Histos[i].Draw(option) first = False else: Histos[i].Draw(optionSame) #Fill legend if plot.legend and len(Histos) % len(listLegend) == 0: r = len(Histos) / len(listLegend) index = i - r * len(listLegend) while (index < 0): index += len(listLegend) legName = legendName.replace("KEY", listLegend[index]) if i < len(listLegend): legName = legName.replace("isVAL", options.ValRel) else: legName = legName.replace("isVAL", options.RefRel) if drawOption == "HIST": leg.AddEntry(Histos[i], legName, "L") else: leg.AddEntry(Histos[i], legName, "P") #Draw legend if plot.legend and options.drawLegend: leg.Draw("same") tex = None if options.printBanner: print type(options.printBanner) tex = TLatex(0.55, 0.75, options.Banner) tex.SetNDC() tex.SetTextSize(0.05) tex.Draw() #save canvas if ratios: for r in range(0, len(ratios)): pads["ratio_" + str(r)].cd() if ratios[r] is None: continue pads["ratio_" + str(r)].SetGrid() ratios[r].GetYaxis().SetTitle(listLegend[r] + "-jets") ratios[r].GetYaxis().SetTitleSize(0.15) ratios[r].GetYaxis().SetTitleOffset(0.2) ratios[r].GetYaxis().SetNdivisions(3, 3, 2) ratios[r].Draw("") unity.Draw("same") for format in listFromats: save = saveName + "." + format c[keyHisto].Print(save) return [c, leg, tex, pads]
def ATLAS_LABEL(x, y, color=1): l = TLatex() l.SetNDC() l.SetTextFont(72) l.SetTextColor(color) l.DrawLatex(x, y, "ATLAS")
def CMS_lumi(pad, iPeriod, iPosX, lumiText="", **kwargs): global outOfFrame if iPosX / 10 == 0: outOfFrame = True lumiTextSize_ = lumiTextSize relPosX_ = kwargs.get('relPosX', relPosX) if lumiText == "": if iPeriod == 1: lumiText += lumi_7TeV lumiText += " (7 TeV)" elif iPeriod == 2: lumiText += lumi_8TeV lumiText += " (8 TeV)" elif iPeriod == 3: lumiText = lumi_8TeV lumiText += " (8 TeV)" lumiText += " + " lumiText += lumi_7TeV lumiText += " (7 TeV)" elif iPeriod == 4: lumiText += lumi_13TeV lumiText += " (13 TeV)" elif iPeriod == 7: if outOfFrame: lumiTextSize_ *= 0.85 lumiText += lumi_13TeV lumiText += " (13 TeV)" lumiText += " + " lumiText += lumi_8TeV lumiText += " (8 TeV)" lumiText += " + " lumiText += lumi_7TeV lumiText += " (7 TeV)" elif iPeriod == 12: lumiText += "8 TeV" else: if outOfFrame: lumiTextSize_ *= 0.90 if iPeriod == 13: lumiText += lumi_13TeV lumiText += " (13 TeV)" elif iPeriod == 2016: lumiText += lumi_2016 lumiText += " (13 TeV)" elif iPeriod == 2017: lumiText += lumi_2017 lumiText += " (13 TeV)" elif iPeriod == 2018: lumiText += lumi_2018 lumiText += " (13 TeV)" elif iPeriod == 14: lumiText += lumi_14TeV lumiText += " (14 TeV, 200 PU)" #print lumiText alignY_ = 3 alignX_ = 2 if iPosX == 0: alignY_ = 1 if iPosX / 10 == 0: alignX_ = 1 elif iPosX / 10 == 1: alignX_ = 1 elif iPosX / 10 == 2: alignX_ = 2 elif iPosX / 10 == 3: alignX_ = 3 align = 10 * alignX_ + alignY_ extraTextSize = extraOverCmsTextSize * cmsTextSize H = pad.GetWh() W = pad.GetWw() l = pad.GetLeftMargin() t = pad.GetTopMargin() r = pad.GetRightMargin() b = pad.GetBottomMargin() e = 0.025 pad.cd() latex = TLatex() latex.SetNDC() latex.SetTextAngle(0) latex.SetTextColor(kBlack) latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(lumiTextSize_ * t) if lumiText: latex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText) if iPosX == 0: relPosX_ = relPosX_ * 32 * t posX = l + relPosX_ * (1 - l - r) posY = 1 - t + lumiTextOffset * t else: posX = 0 posY = 1 - t - relPosY * (1 - t - b) if iPosX % 10 <= 1: posX = l + relPosX_ * (1 - l - r) # left aligned elif iPosX % 10 == 2: posX = l + 0.5 * (1 - l - r) # centered elif iPosX % 10 == 3: posX = 1 - r - relPosX_ * (1 - l - r) # right aligned if outOfFrame: #TGaxis.SetExponentOffset(-0.074,0.015,'y') latex.SetTextFont(cmsTextFont) latex.SetTextAlign(11) latex.SetTextSize(cmsTextSize * t) latex.DrawLatex(l, 1 - t + lumiTextOffset * t, cmsText) if writeExtraText: latex.SetTextFont(extraTextFont) latex.SetTextSize(extraTextSize * t) latex.SetTextAlign(align) latex.DrawLatex(posX, posY, extraText) elif drawLogo: posX = l + 0.045 * (1 - l - r) * W / H posY = 1 - t - 0.045 * (1 - t - b) xl_0 = posX yl_0 = posY - 0.15 xl_1 = posX + 0.15 * H / W yl_1 = posY CMS_logo = TASImage("CMS-BW-label.png") pad_logo = TPad("logo", "logo", xl_0, yl_0, xl_1, yl_1) pad_logo.Draw() pad_logo.cd() CMS_logo.Draw('X') pad_logo.Modified() pad.cd() else: latex.SetTextFont(cmsTextFont) latex.SetTextSize(cmsTextSize * t) latex.SetTextAlign(align) latex.DrawLatex(posX, posY, cmsText) if writeExtraText: latex.SetTextFont(extraTextFont) latex.SetTextAlign(align) latex.SetTextSize(extraTextSize * t) latex.DrawLatex(posX, posY - relExtraDY * cmsTextSize * t, extraText) pad.Update()
def plotter_flavours(eff_type): if eff_type == "real": hist_eff_type = "Real" elif eff_type == "fake": hist_eff_type = "Fake" basepath = "$HOME/PhD/ttH_MultiLeptons/RUN2/HTopMultilepAnalysisCode/trunk/HTopMultilepAnalysis/PlotUtils/" # --------------------------- # HTop Tag & Probe efficiency # --------------------------- file_TP_path = basepath + "blahblah" if args.closure: if "SLT" in args.trigger: file_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_HTopTP/OutputPlots_MMClosureRates_HTopTagProbe_NoCorr_SLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root" elif "DLT" in args.trigger: #file_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_HTopTP/OutputPlots_MMClosureRates_HTopTagProbe_NoCorr_DLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root" file_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" print( "------------------------------------------------------------------------------------------" ) print("HTop Tag & Probe efficiency - Opening file:\n{0}".format( file_TP_path)) print( "------------------------------------------------------------------------------------------" ) file_TP = TFile(file_TP_path) if args.closure: hist_TP = (file_TP.Get(hist_eff_type + "_El_Pt_Efficiency_expectedbkg"), file_TP.Get(hist_eff_type + "_Mu_Pt_Efficiency_expectedbkg"))[bool( args.flavour == "mu")] else: hist_TP = (file_TP.Get(hist_eff_type + "_El_Pt_Efficiency_observed_sub"), file_TP.Get(hist_eff_type + "_Mu_Pt_Efficiency_observed_sub"))[bool( args.flavour == "mu")] print("Reading histogram {0} from file {1}".format(hist_TP.GetName(), file_TP_path)) hist_TP.SetLineWidth(2) hist_TP.SetMarkerSize(1.0) hist_TP.GetXaxis().SetTitleOffset(1.0) hist_TP.GetYaxis().SetTitleOffset(1.0) lepton = ("e", "#mu")[bool(args.flavour == "mu")] hist_TP.GetXaxis().SetTitle("p_{T}^{" + lepton + "} [GeV]") hist_TP.GetYaxis().SetTitle("efficiency") hist_TP.GetYaxis().SetRangeUser(0.0, 1.0) hist_TP.SetLineColor(kRed) hist_TP.SetMarkerColor(kRed) #c = TCanvas("c1","Temp",50,50,1000,900) c = TCanvas("c1", "Temp", 50, 50, 1300, 800) legend = TLegend( 0.45, 0.5, 0.925, 0.8 ) # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) ) legend.SetHeader("#epsilon_{" + eff_type + "}") legend.SetBorderSize(0) # no border legend.SetFillStyle(0) # Legend transparent background legend.SetTextSize(0.04) # Increase entry font size! legend.SetTextFont(42) # Helvetica leg_ATLAS = TLatex() leg_lumi = TLatex() leg_ATLAS.SetTextSize(0.03) leg_ATLAS.SetNDC() leg_lumi.SetTextSize(0.03) leg_lumi.SetNDC() #hist_TP.Draw("E0") #legend.AddEntry(hist_TP, "HTop Tag & Probe (ICHEP)", "P") # --------------------------- # New Tag & Probe efficiency # --------------------------- file_SUSY_TP_path = basepath + "blahblah" if args.closure: if "SLT" in args.trigger: #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_SFmuSFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_OFmuOFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_SFmuSFel_massClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_SFmuSFel_deltaRClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v23_OLD_EL_BINNING/LeptonEfficiencies.root" # #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_ForceProbeToBeFake/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_TightTagIso/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_TightTagIsoTagPt30/LeptonEfficiencies.root" file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_TightTagIsoTagPt30_ForceProbeToBeFake/LeptonEfficiencies.root" elif "DLT" in args.trigger: #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_massClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_deltaRClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root" print( "------------------------------------------------------------------------------------------" ) print("New Tag & Probe efficiency - Opening file:\n{0}".format( file_SUSY_TP_path)) print( "------------------------------------------------------------------------------------------" ) file_SUSY_TP = TFile(file_SUSY_TP_path) if args.closure: hist_SUSY_TP = ( file_SUSY_TP.Get(hist_eff_type + "_El_Pt_Efficiency_expectedbkg"), file_SUSY_TP.Get(hist_eff_type + "_Mu_Pt_Efficiency_expectedbkg"))[bool( args.flavour == "mu")] else: hist_SUSY_TP = ( file_SUSY_TP.Get(hist_eff_type + "_El_Pt_Efficiency_observed_sub"), file_SUSY_TP.Get(hist_eff_type + "_Mu_Pt_Efficiency_observed_sub"))[bool( args.flavour == "mu")] print("Reading histogram {0} from file {1}".format(hist_SUSY_TP.GetName(), file_SUSY_TP_path)) hist_SUSY_TP.SetLineColor(kMagenta) hist_SUSY_TP.SetMarkerColor(kMagenta) hist_SUSY_TP.GetXaxis().SetTitle("p_{T}^{" + lepton + "} [GeV]") hist_SUSY_TP.GetYaxis().SetTitle("#varepsilon") if eff_type == "real": hist_SUSY_TP.GetYaxis().SetRangeUser(0.5, 1.0) elif eff_type == "fake": if args.flavour == "el": hist_SUSY_TP.GetYaxis().SetRangeUser(0.0, 0.7) if args.flavour == "mu": hist_SUSY_TP.GetYaxis().SetRangeUser(0.0, 0.5) hist_SUSY_TP.Draw("E0") legend.AddEntry(hist_SUSY_TP, "Tag & Probe", "P") # ---------------------------- # TRUTH Tag & Probe efficiency # ---------------------------- file_TRUTH_TP_path = basepath + "blahblah" if args.closure: if "SLT" in args.trigger: #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root" #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_OFmuOFel_25ns_v23/LeptonEfficiencies.root" #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_25ns_v23/LeptonEfficiencies.root" #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_25ns_v23_OLD_EL_BINNING/LeptonEfficiencies.root" # file_TRUTH_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_25ns_v24/LeptonEfficiencies.root" elif "DLT" in args.trigger: file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_DLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root" print( "------------------------------------------------------------------------------------------" ) print("TRUTH Tag & Probe efficiency - Opening file:\n{0}".format( file_TRUTH_TP_path)) print( "------------------------------------------------------------------------------------------" ) file_TRUTH_TP = TFile(file_TRUTH_TP_path) if args.closure: hist_TRUTH_TP = ( file_TRUTH_TP.Get(hist_eff_type + "_El_Pt_Efficiency_expectedbkg"), file_TRUTH_TP.Get(hist_eff_type + "_Mu_Pt_Efficiency_expectedbkg"))[bool( args.flavour == "mu")] else: hist_TRUTH_TP = ( file_TRUTH_TP.Get(hist_eff_type + "_El_Pt_Efficiency_observed_sub"), file_TRUTH_TP.Get(hist_eff_type + "_Mu_Pt_Efficiency_observed_sub"))[bool( args.flavour == "mu")] print("Reading histogram {0} from file {1}".format(hist_TRUTH_TP.GetName(), file_TRUTH_TP_path)) hist_TRUTH_TP.SetLineWidth(2) hist_TRUTH_TP.SetLineColor(kBlack) hist_TRUTH_TP.SetLineStyle(2) hist_TRUTH_TP.SetMarkerSize(1.0) hist_TRUTH_TP.SetMarkerColor(kBlack) hist_TRUTH_TP.SetMarkerStyle(24) hist_TRUTH_TP.Draw("E0 SAME") legend.AddEntry(hist_TRUTH_TP, "Truth", "P") # --------------------- # Likelihood efficiency # --------------------- #""" LH_init_path = basepath + "blahblah" if args.closure: if "SLT" in args.trigger: #LH_init_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_SFmuSFel_SLT_25ns_v21/LeptonEfficiencies_LH/" #LH_init_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_INCLUSIVE_FLAV_SLT_25ns_v24/LeptonEfficiencies_LH/" LH_init_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_INCLUSIVE_FLAV_DLT_25ns_v24/LeptonEfficiencies_LH/" elif "DLT" in args.trigger: LH_init_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_SFmuSFel_DLT_25ns_v21/LeptonEfficiencies_LH/" hist_LH_list = [] if eff_type == "real": flav_comp_list = args.flavRealCR elif eff_type == "fake": flav_comp_list = args.flavFakeCR if (args.flavour == "mu" and "elel" in flav_comp_list): flav_comp_list.remove("elel") if (args.flavour == "el" and "mumu" in flav_comp_list): flav_comp_list.remove("mumu") for idx, flavcomp in enumerate(flav_comp_list, start=0): file_LH_path = LH_init_path + "LH_" + flavcomp + "/LH_efficiencies_" + eff_type + "_" + args.flavour + "_" + flavcomp + ".root" print( "\t------------------------------------------------------------------------------------------" ) print("\tLikelihood efficiency - Opening file:\n{0}".format( file_LH_path)) print( "\t------------------------------------------------------------------------------------------" ) file_LH = TFile(file_LH_path) if eff_type == "real": hist_LH_name = "r_hist" elif eff_type == "fake": hist_LH_name = "f_hist" hist_LH = file_LH.Get(hist_LH_name) print("Reading histogram {0} from file {1} - index : {2}".format( hist_LH.GetName(), file_LH_path, idx)) # A dirty hack to make multiple plots superimposed with a small offset offsets = [] for ibin in range(0, hist_LH.GetNbinsX() + 1): offset = (idx + 1) * 0.15 * hist_LH.GetBinWidth(ibin) # hardcoded...so ugly, any better ideas? if ibin == 4: offset = (idx + 1) * 0.05 * hist_LH.GetBinWidth(ibin) if ibin == 5: offset = (idx + 1) * 0.01 * hist_LH.GetBinWidth(ibin) offsets.append(offset) print("offsets per bin: {0}".format(offsets)) binlist = [] for ibin in range(0, hist_LH.GetNbinsX() + 1): binlist.append(hist_LH.GetXaxis().GetBinUpEdge(ibin) + offsets[ibin]) print("shifted bins: {0}".format(binlist)) binlist_arr = array.array("d", binlist) shiftedhist = TH1D(hist_LH.GetName() + "_shift", hist_LH.GetTitle(), len(binlist) - 1, binlist_arr) for ibin in range(1, hist_LH.GetNbinsX() + 1): shiftedhist.SetBinContent(ibin, hist_LH.GetBinContent(ibin)) shiftedhist.SetBinError(ibin, hist_LH.GetBinError(ibin)) shiftedhist.SetLineWidth(2) shiftedhist.SetMarkerSize(1.0) lepton = ("e", "#mu")[bool(args.flavour == "mu")] shiftedhist.GetXaxis().SetTitle("p_{T}^{" + lepton + "} [GeV]") shiftedhist.GetYaxis().SetTitle("efficiency") shiftedhist.GetXaxis().SetTitleOffset(1.0) shiftedhist.GetYaxis().SetTitleOffset(1.0) shiftedhist.GetYaxis().SetRangeUser(0.0, 1.0) if idx == 0: shiftedhist.SetLineColor(kBlue) shiftedhist.SetMarkerColor(kBlue) elif idx == 1: shiftedhist.SetLineColor(kBlue + 3) shiftedhist.SetMarkerColor(kBlue + 3) elif idx == 2: shiftedhist.SetLineColor(kAzure + 1) shiftedhist.SetMarkerColor(kAzure + 1) elif idx == 3: shiftedhist.SetLineColor(kCyan) shiftedhist.SetMarkerColor(kCyan) shiftedhist.SetDirectory(0) pair = (flavcomp, shiftedhist) hist_LH_list.append(pair) #gPad.SetLogx() #hist_TP.GetXaxis().SetMoreLogLabels() for idx, histpair in enumerate(hist_LH_list, start=0): #histpair[1].GetXaxis().SetMoreLogLabels() #if idx == 0: # histpair[1].Draw("E0") #else: # histpair[1].Draw("E0,SAME") # TEMP: plot LH efficiency only for fake muon if not (eff_type == "fake" and args.flavour == "mu"): continue histpair[1].Draw("E0,SAME") if histpair[0] == "mumu": flag = "#mu#mu" else: flag = histpair[0] legend.AddEntry(histpair[1], "Likelihood - " + flag, "P") #""" legend.Draw() leg_ATLAS.DrawLatex(0.6, 0.35, "#bf{#it{ATLAS}} Work In Progress") leg_lumi.DrawLatex( 0.6, 0.27, "#sqrt{{s}} = 13 TeV, #int L dt = {0:.1f} fb^{{-1}}".format(args.lumi)) # Add a vertical line to highlight relevant bins if eff_type == "real": low_y_edge = 0.5 up_y_edge = 1.0 elif eff_type == "fake": low_y_edge = 0.0 if args.flavour == "el": up_y_edge = 0.7 elif args.flavour == "mu": up_y_edge = 0.5 if "SLT" in args.trigger: if args.flavour == "el": refl_vert0 = TLine(26.0, 0, 26.0, up_y_edge) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") refl_vert1 = TLine(60.0, low_y_edge, 60.0, up_y_edge) refl_vert1.SetLineStyle(2) refl_vert1.SetLineWidth(2) refl_vert1.Draw("SAME") refl_vert2 = TLine(140.0, low_y_edge, 140.0, up_y_edge) refl_vert2.SetLineStyle(2) refl_vert2.SetLineWidth(2) refl_vert2.Draw("SAME") elif args.flavour == "mu": refl_vert0 = TLine(26.0, low_y_edge, 26.0, up_y_edge) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") refl_vert1 = TLine(50.0, low_y_edge, 50.0, up_y_edge) refl_vert1.SetLineStyle(2) refl_vert1.SetLineWidth(2) refl_vert1.Draw("SAME") elif "DLT" in args.trigger: if args.flavour == "el": refl_vert0 = TLine(17.0, low_y_edge, 17.0, up_y_edge) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") elif args.flavour == "mu": refl_vert0 = TLine(22.0, low_y_edge, 22.0, up_y_edge) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") canvasname = (eff_type + "_eff_el_TP_LH", eff_type + "_eff_mu_TP_LH")[bool(args.flavour == "mu")] c.SaveAs(canvasname + "_" + args.trigger[0] + ".png")
hhs = {} ff = TFile(sys.argv[1]) for kk in ff.GetListOfKeys(): obj = kk.ReadObj() hhs[obj.GetName()] = obj base = os.path.basename(ff.GetName()) print('Analysing file %s' % (base)) mon_out_file_name = 'monitor_kin_corr2d_' + datatype + '.pdf' can = TCanvas('can', 'can') can.SetCanvasSize(1200, 1200) can.Print('{}['.format(mon_out_file_name)) lab = TLatex() lab.SetNDC() lab.SetTextFont(42) lab.SetTextSize(0.05) lab.SetTextColor(1) gStyle.SetOptStat(00000) ###################### ## check 2D Histograms ## delta p vs p p_ele_dp_ele_from_ang_ctof_isr = {} p_ele_dp_ele_from_ang_ftof_isr = {} p_ele_dp_ele_from_ang_ctof_fsr = {} p_ele_dp_ele_from_ang_ftof_fsr = {}
def drawRegion(channel, left=False): region = { "SR": "1 + 2 b-tag categories", "SR1": "1 b-tag category", "SR2": "2 b-tag category", "ZCR": "Z region", "ZeeCR": "2e region", "ZeebCR": "2e, 1 b-tag region", "ZeebbCR": "2e, 2 b-tag region", "ZmmCR": "2#mu region", "ZmmbCR": "2#mu, 1 b-tag region", "ZmmbbCR": "2#mu, 2 b-tag region", "WCR": "W region", "WeCR": "1e region", "WebCR": "1e, 1 b-tag region", "WebbCR": "1e, 2 b-tag region", "WmCR": "1#mu region", "WmbCR": "1#mu, 1 b-tag region", "WmbbCR": "1#mu, 2 b-tag region", "TCR": "1#mu, 1e region", "TbCR": "1#mu, 1e, 1 b-tag region", "TbbCR": "1#mu, 1e, 2 b-tag region", "CR": "Control regions", "ZmmInc": "2#mu selection", "ZeeInc": "2e selection", "WmInc": "1#mu selection", "WeInc": "1e selection", "TInc": "1#mu, 1e selection", "XVh": "0l, 1l, 2l channel", "XZh": "0l, 2l channel", "XWh": "1l channel", "XZhnn": "0l channel", "XZhll": "2l channel", "XZhee": "2e channel", "XZhmm": "2#mu channel", "XWhen": "1e channel", "XWhmn": "1#mu channel" } text = "" if channel in region: text = region[channel] else: #if channel.startswith('X') or channel.startswith('A'): # leptons if 'ee' in channel: text += "2e" elif 'mm' in channel: text += "2#mu" elif (('me' in channel) or ('em' in channel)): text += "1e 1#mu" elif 'e' in channel: text += "1e" elif 'm' in channel: text += "1#mu" elif 'll' in channel: text += "2l" elif 'l' in channel: text += "1l" elif 'nn' in channel: text += "0l" if 'Top' in channel: text += "top" # b-tag if 'bb' in channel: text += ", 2 b-tag" elif 'b' in channel: text += ", 1 b-tag" # purity if 'lp' in channel: text += ", low purity" elif 'hp' in channel: text += ", high purity" # region if 'TR' in channel: text += ", top control region" elif 'Inc' in channel: text += ", inclusive region" elif 'SB' in channel: text += ", sidebands region" elif 'SR' in channel: text += ", signal region" elif 'NR' in channel: text += ", inclusive region" elif 'MC' in channel: text += ", simulation" # else: # return False latex = TLatex() latex.SetNDC() latex.SetTextFont(72) #52 latex.SetTextSize(0.035) if left: latex.DrawLatex(0.15, 0.75, text) else: latex.SetTextAlign(22) latex.DrawLatex(0.5, 0.85, text)
curGraph_1s.SetFillColor(ROOT.kGreen) curGraph_2s.SetFillColor(ROOT.kYellow) tGraphs.append(curGraph_exp) tGraphs.append(curGraph_obs) tGraphs.append(curGraph_1s) tGraphs.append(curGraph_2s) # ## MakePlots(tGraphs); # ---------------------------- # Drawing time banner = TLatex( 0.25, 0.92, ("CMS Preliminary, 19.2-19.3 fb^{-1} at #sqrt{s}=8TeV, e+#mu")) banner.SetNDC() banner.SetTextSize(0.028) leg = ROOT.TLegend(0.15, 0.7, 0.85, 0.9) leg.SetFillStyle(0) leg.SetBorderSize(0) leg.SetNColumns(2) for k in range(nCprimes): print "k: ", k if k == 0: leg.AddEntry(tGraphs[0], "expected, C' = 1", "L") tmplabel = "observed, C' = %1.1f" % (float( (11. - cprime[k]) / 10.)) leg.AddEntry(tGraphs[k * 4 + 1], tmplabel, "L") drawColors = [] drawColors.append(ROOT.kRed + 2)
hdict_trig = plotTools.ConstructHDict( infile_trig.Get("h_HT_j1pt_pre_effph_l"), name="", #name="#splitline{Preselection}{SingleL}", title="", xtitle="H_{T} (GeV)", ytitle="p_{T}(j_{1}) (GeV)", ztitle="Efficiency", drawoption="colz", palette="SMS") canvasname = "h_HT_j1pt_pre_eff_ph_l" #plotTools.Plot2DPAS(hdict_trig,outputdir,outfile,cname=canvasname,scale="No",logscale=False,lumitext=" Preliminary", zmax=1.) text1 = TLatex( 0.15, 0.2, "#splitline{SingleL, preselection,}{unc = max(err+, diff)}") text1.SetNDC() text1.SetTextSize(0.05) text1.SetTextFont(42) hdict_trig2 = plotTools.ConstructHDict( infile_trig.Get("h_HT_j1pt_0_pre_errdiff_up_ph_l"), name="", #name="#splitline{Preselection}{SingleL}", title="", xtitle="H_{T} (GeV)", ytitle="p_{T}(j_{1}) (GeV)", ztitle="Efficiency uncertainty", drawoption="colz", palette="SMS") canvasname = "h_HT_j1pt_0_pre_errdiff_up_ph_l_forThesis" plotTools.Plot2DPAS(hdict_trig2,
def make1DLimitPlot(xtitle, xvals, obs, exp, exp1plus, exp1minus, exp2plus, exp2minus, theory, alphaD, xvar): gStyle.SetOptTitle(0) axisTitleSize = 0.041 axisTitleOffset = 1.2 axisTitleSizeRatioX = 0.18 axisLabelSizeRatioX = 0.12 axisTitleOffsetRatioX = 0.94 axisTitleSizeRatioY = 0.15 axisLabelSizeRatioY = 0.108 axisTitleOffsetRatioY = 0.32 leftMargin = 0.15 rightMargin = 0.12 topMargin = 0.05 bottomMargin = 0.14 bottomMargin2 = 0.22 #c1 = TCanvas() #'c1', '', 200, 10, 700, 500 ) c1 = TCanvas("c1", "c2", 200, 10, 700, 600) c1.SetHighLightColor(2) c1.SetFillColor(0) c1.SetBorderMode(0) c1.SetBorderSize(2) c1.SetLeftMargin(leftMargin) c1.SetRightMargin(rightMargin) c1.SetTopMargin(topMargin) c1.SetBottomMargin(bottomMargin) c1.SetFrameBorderMode(0) c1.SetFrameBorderMode(0) c1.SetLogy(1) #c1.SetLogx(1) c1.SetTickx(1) c1.SetTicky(1) #c1.SetGridx(True); #c1.SetGridy(True); if "c#tau" in xtitle: c1.SetLogx(1) exp2sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \ array('d', [0]), array('d', [0]), array('d', exp2minus), array('d', exp2plus)) exp2sigma_xsec.Sort() exp2sigma_xsec.Draw('A3') exp2sigma_xsec.SetFillStyle(1001) exp2sigma_xsec.SetFillColor(kOrange) exp2sigma_xsec.SetLineColor(kOrange) exp2sigma_xsec.GetYaxis().SetRangeUser(1e-4, 1e3) if xvar == 'mass': exp2sigma_xsec.GetXaxis().SetLimits(1, 80) elif xvar == 'ctau': exp2sigma_xsec.GetXaxis().SetLimits(0.1, 100) else: exp2sigma_xsec.GetXaxis().SetLimits(0.8 * min(xvals), 1.1 * max(xvals)) #exp2sigma_xsec.GetXaxis().SetTitle('m_{1} [GeV]') #exp2sigma_xsec.GetXaxis().SetTitle('c#tau [cm]') exp2sigma_xsec.GetXaxis().SetTitle(xtitle) exp2sigma_xsec.GetXaxis().SetTitleOffset(axisTitleOffset) exp2sigma_xsec.GetYaxis().SetTitle( "#sigma_{95% CL} Br(A' #rightarrow #mu#mu) [pb]") exp2sigma_xsec.GetYaxis().SetTitleOffset(axisTitleOffset + 0.1) exp1sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \ array('d', [0]), array('d', [0]), array('d', exp1minus), array('d', exp1plus)) exp1sigma_xsec.Sort() exp1sigma_xsec.SetFillStyle(1001) exp1sigma_xsec.SetFillColor(kGreen + 1) exp1sigma_xsec.SetLineColor(kGreen + 1) exp1sigma_xsec.Draw('3 SAME') exp_xsec = TGraph(len(xvals), array('d', xvals), array('d', exp)) exp_xsec.Sort() exp_xsec.SetLineWidth(2) exp_xsec.SetLineStyle(1) exp_xsec.SetLineColor(kRed) exp_xsec.Draw('C SAME') obs_xsec = TGraph(len(xvals), array('d', xvals), array('d', obs)) obs_xsec.Sort() obs_xsec.SetLineWidth(3) obs_xsec.SetLineColor(kBlack) obs_xsec.SetMarkerColor(kBlack) obs_xsec.SetMarkerStyle(20) obs_xsec.SetMarkerSize(1) obs_xsec.Draw('PC SAME') theory_xsec = TGraph(len(xvals), array('d', xvals), array('d', theory)) theory_xsec.Sort() theory_xsec.SetLineWidth(2) theory_xsec.SetLineStyle(8) theory_xsec.SetLineColor(kBlue) theory_xsec.Draw('C SAME') leg = TLegend(0.50, 0.70, 0.8, 0.90) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.AddEntry(theory_xsec, "Theory", "l") leg.AddEntry(obs_xsec, "Observed Limit", "pl") leg.AddEntry(exp_xsec, "Expected Limit", "l") leg.AddEntry(exp1sigma_xsec, "#pm 1 std. dev.", "f") leg.AddEntry(exp2sigma_xsec, "#pm 2 std. dev.", "f") leg.Draw() drawCMSLogo(c1, 13, 122450) if alphaD != '': aDtext = TLatex() #baseSize = 25 aDtext.SetNDC() aDtext.SetTextAngle(0) aDtext.SetTextColor(1) #aDtext.SetTextFont(61) #aDtext.SetTextAlign(11) aDtext.SetTextSize(0.0375) aDtext.DrawLatex(0.7, 0.9, "#alpha_{D} = " + alphaD) # TCanvas.Update() draws the frame, after which one can change it # c1.Update() # c1.Modified() # c1.Update() c1.RedrawAxis() c1.Draw() wait(True)
def train_and_apply(): np.random.seed(1) ROOT.gROOT.SetBatch() #Extract data from root file tree = uproot.open("out_all.root")["outA/Tevts"] branch_mc = [ "MC_B_P", "MC_B_eta", "MC_B_phi", "MC_B_pt", "MC_D0_P", "MC_D0_eta", "MC_D0_phi", "MC_D0_pt", "MC_Dst_P", "MC_Dst_eta", "MC_Dst_phi", "MC_Dst_pt", "MC_Est_mu", "MC_M2_miss", "MC_mu_P", "MC_mu_eta", "MC_mu_phi", "MC_mu_pt", "MC_pis_P", "MC_pis_eta", "MC_pis_phi", "MC_pis_pt", "MC_q2" ] branch_rec = [ "B_P", "B_eta", "B_phi", "B_pt", "D0_P", "D0_eta", "D0_phi", "D0_pt", "Dst_P", "Dst_eta", "Dst_phi", "Dst_pt", "Est_mu", "M2_miss", "mu_P", "mu_eta", "mu_phi", "mu_pt", "pis_P", "pis_eta", "pis_phi", "pis_pt", "q2" ] nvariable = len(branch_mc) x_train = tree.array(branch_mc[0], entrystop=options.maxevents) for i in range(1, nvariable): x_train = np.vstack( (x_train, tree.array(branch_mc[i], entrystop=options.maxevents))) x_test = tree.array(branch_rec[0], entrystop=options.maxevents) for i in range(1, nvariable): x_test = np.vstack( (x_test, tree.array(branch_rec[i], entrystop=options.maxevents))) x_train = x_train.T x_test = x_test.T x_test = array2D_float(x_test) #Different type of reconstruction variables #BN normalization gamma = 0 beta = 0.2 ar = np.array(x_train) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_train = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_train = np.vstack((x_train, a)) x_train = x_train.T ar = np.array(x_test) a = K.constant(ar[:, 0]) mean = K.mean(a) var = K.var(a) x_test = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) for i in range(1, nvariable): a = K.constant(ar[:, i]) mean = K.mean(a) var = K.var(a) a = K.eval(K.batch_normalization(a, mean, var, gamma, beta)) x_test = np.vstack((x_test, a)) x_test = x_test.T #Add noise, remain to be improved noise = np.random.normal(loc=0.0, scale=0.01, size=x_train.shape) x_train_noisy = x_train + noise noise = np.random.normal(loc=0.0, scale=0.01, size=x_test.shape) x_test_noisy = x_test + noise x_train = np.clip(x_train, -1., 1.) x_test = np.clip(x_test, -1., 1.) x_train_noisy = np.clip(x_train_noisy, -1., 1.) x_test_noisy = np.clip(x_test_noisy, -1., 1.) # Network parameters input_shape = (x_train.shape[1], ) batch_size = 128 latent_dim = 2 # Build the Autoencoder Model # First build the Encoder Model inputs = Input(shape=input_shape, name='encoder_input') x = inputs # Shape info needed to build Decoder Model shape = K.int_shape(x) # Generate the latent vector latent = Dense(latent_dim, name='latent_vector')(x) # Instantiate Encoder Model encoder = Model(inputs, latent, name='encoder') encoder.summary() # Build the Decoder Model latent_inputs = Input(shape=(latent_dim, ), name='decoder_input') x = Dense(shape[1])(latent_inputs) x = Reshape((shape[1], ))(x) outputs = Activation('tanh', name='decoder_output')(x) # Instantiate Decoder Model decoder = Model(latent_inputs, outputs, name='decoder') decoder.summary() # Autoencoder = Encoder + Decoder # Instantiate Autoencoder Model autoencoder = Model(inputs, decoder(encoder(inputs)), name='autoencoder') autoencoder.summary() autoencoder.compile(loss='mse', optimizer='adam') # Train the autoencoder autoencoder.fit(x_train_noisy, x_train, validation_data=(x_test_noisy, x_test), epochs=options.epochs, batch_size=batch_size) # Predict the Autoencoder output from corrupted test imformation x_decoded = autoencoder.predict(x_test_noisy) # Draw Comparision Plots c = TCanvas("c", "c", 700, 700) fPads1 = TPad("pad1", "Run2", 0.0, 0.29, 1.00, 1.00) fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.29) fPads1.SetBottomMargin(0.007) fPads1.SetLeftMargin(0.10) fPads1.SetRightMargin(0.03) fPads2.SetLeftMargin(0.10) fPads2.SetRightMargin(0.03) fPads2.SetBottomMargin(0.25) fPads1.Draw() fPads2.Draw() fPads1.cd() nbin = 50 min = -1. max = 1. variable = "P^{B}" lbin = (max - min) / nbin lbin = str(float((max - min) / nbin)) xtitle = branch_rec[options.branch - 1] ytitle = "Events/" + lbin + "GeV" h_rec = TH1D("h_rec", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_rec.Sumw2() h_pre = TH1D("h_pre", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max) h_pre.Sumw2() for i in range(x_test_noisy.shape[0]): h_rec.Fill(x_test_noisy[i][options.branch - 1]) h_pre.Fill(x_decoded[i][options.branch - 1]) h_rec = UnderOverFlow1D(h_rec) h_pre = UnderOverFlow1D(h_pre) maxY = TMath.Max(h_rec.GetMaximum(), h_pre.GetMaximum()) h_rec.SetLineColor(2) h_rec.SetFillStyle(0) h_rec.SetLineWidth(2) h_rec.SetLineStyle(1) h_pre.SetLineColor(3) h_pre.SetFillStyle(0) h_pre.SetLineWidth(2) h_pre.SetLineStyle(1) h_rec.SetStats(0) h_pre.SetStats(0) h_rec.GetYaxis().SetRangeUser(0, maxY * 1.1) h_rec.Draw("HIST") h_pre.Draw("same HIST") h_rec.GetYaxis().SetTitleSize(0.06) h_rec.GetYaxis().SetTitleOffset(0.78) theLeg = TLegend(0.5, 0.45, 0.95, 0.82, "", "NDC") theLeg.SetName("theLegend") theLeg.SetBorderSize(0) theLeg.SetLineColor(0) theLeg.SetFillColor(0) theLeg.SetFillStyle(0) theLeg.SetLineWidth(0) theLeg.SetLineStyle(0) theLeg.SetTextFont(42) theLeg.SetTextSize(.05) theLeg.AddEntry(h_rec, "Reconstruction", "L") theLeg.AddEntry(h_pre, "Prediction", "L") theLeg.SetY1NDC(0.9 - 0.05 * 6 - 0.005) theLeg.SetY1(theLeg.GetY1NDC()) fPads1.cd() theLeg.Draw() title = TLatex( 0.91, 0.93, "AE prediction compare with reconstruction, epochs=" + str(options.epochs)) title.SetNDC() title.SetTextSize(0.05) title.SetTextFont(42) title.SetTextAlign(31) title.SetLineWidth(2) title.Draw() fPads2.cd() h_Ratio = h_pre.Clone("h_Ratio") h_Ratio.Divide(h_rec) h_Ratio.SetLineColor(1) h_Ratio.SetLineWidth(2) h_Ratio.SetMarkerStyle(8) h_Ratio.SetMarkerSize(0.7) h_Ratio.GetYaxis().SetRangeUser(0, 2) h_Ratio.GetYaxis().SetNdivisions(504, 0) h_Ratio.GetYaxis().SetTitle("Pre/Rec") h_Ratio.GetYaxis().SetTitleOffset(0.35) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetTitleSize(0.13) h_Ratio.GetYaxis().SetLabelSize(0.11) h_Ratio.GetXaxis().SetLabelSize(0.1) h_Ratio.GetXaxis().SetTitleOffset(0.8) h_Ratio.GetXaxis().SetTitleSize(0.14) h_Ratio.SetStats(0) axis1 = TGaxis(min, 1, max, 1, 0, 0, 0, "L") axis1.SetLineColor(1) axis1.SetLineWidth(1) for i in range(1, h_Ratio.GetNbinsX() + 1, 1): D = h_rec.GetBinContent(i) eD = h_rec.GetBinError(i) if D == 0: eD = 0.92 B = h_pre.GetBinContent(i) eB = h_pre.GetBinError(i) if B < 0.1 and eB >= B: eB = 0.92 Err = 0. if B != 0.: Err = TMath.Sqrt((eD * eD) / (B * B) + (D * D * eB * eB) / (B * B * B * B)) h_Ratio.SetBinContent(i, D / B) h_Ratio.SetBinError(i, Err) if B == 0.: Err = TMath.Sqrt((eD * eD) / (eB * eB) + (D * D * eB * eB) / (eB * eB * eB * eB)) h_Ratio.SetBinContent(i, D / 0.92) h_Ratio.SetBinError(i, Err) if D == 0 and B == 0: h_Ratio.SetBinContent(i, -1) h_Ratio.SetBinError(i, 0) h_Ratio.Draw("e0") axis1.Draw() c.SaveAs(branch_rec[options.branch - 1] + "_comparision.png")
def process(self, set): self.message('Processing channel %s' % set['channel']) # Setting the indir directory indir = '%s/scratch/%s/YieldHistograms' % (Common.NeatDirectory, self.getParameter('input')) if self.isParameter('xcheck'): indir = '%s/scratch/%s/XCheckHistograms/%s' % ( Common.NeatDirectory, self.getParameter('input'), self.getParameter('xcheck')) # Setting the self.__outdir directory outdir = '%s/scratch/%s/YieldPlots' % (Common.NeatDirectory, self.getParameter('input')) if self.isParameter('xcheck'): outdir = '%s/scratch/%s/XCheckPlots/%s' % ( Common.NeatDirectory, self.getParameter('input'), self.getParameter('xcheck')) # Check for output directory if not os.path.exists(outdir): os.makedirs(outdir) # Create the list of sample samples = None if type(Common.YieldSignals) == list: samples = Common.YieldBackgrounds + Common.YieldSignals else: samples = Common.YieldBackgrounds + [Common.YieldSignals] samples = samples + [Common.Data] # Set canvas canvas = TCanvas("canvas", "Data/MC for NEAT discriminator.", 1000, 800) canvas.Clear() canvas.SetLeftMargin(0.14) canvas.SetRightMargin(0.05) canvas.SetBottomMargin(0.13) canvas.SetTopMargin(0.03) # Loop over the different binning for bin in Common.Binning: # Histogram holder histograms = {} stack = THStack('stack', '%s' % set['channel']) # Legend leg = TLegend(1.0, 0.6, 0.6, 1.0) leg.SetNColumns(2) # Loop over signal+backgorund files for sample in samples: # Merge to create the combined channels # self.merge(sample, set, indir) # Input file with histograms infile = '%s/%s.root' % (indir, Common.filename(set, sample)) print 'Processing sample:', infile # Open the file with histograms file = TFile(infile) # Reading and clonning the histogram histogram = file.Get('%s_%s' % (Common.NeatOutputName, bin)) # Check for signal and background samples if sample in Common.YieldSignals: # Add all the signal samples if not 'signals' in histograms: histograms['signals'] = histogram.Clone() else: histograms['signals'].Add(histogram) elif sample in Common.YieldBackgrounds: # Add all the background samples if not 'backgrounds' in histograms: histograms['backgrounds'] = histogram.Clone() else: histograms['backgrounds'].Add(histogram) # Do not add data to the stack if sample != Common.Data: histogram.SetLineColor(Common.ColorCodes[sample]) histogram.SetFillColor(Common.ColorCodes[sample]) histograms[sample] = histogram.Clone() stack.Add(histograms[sample]) leg.AddEntry(histogram, '%s' % sample, 'f') else: histogram.SetLineColor(Common.ColorCodes[sample]) histogram.SetMarkerStyle(8) histograms[sample] = histogram.Clone() # Creating the data/mc # Stack axes only exist after drawing stack.Draw('hist') # Compute user range maxdata = histograms[Common.Data].GetMaximum() + histograms[ Common.Data].GetBinError( histograms[Common.Data].GetMaximumBin()) maxcount = max(stack.GetMaximum(), maxdata) signalName = '' # Signal name if type(Common.YieldSignals) == list: signalName = ''.join(Common.YieldSignals) else: signalName = Common.YieldSignals histograms[Common.Data].GetXaxis().SetTitle('%s NEAT output' % signalName) histograms[Common.Data].GetYaxis().SetTitle('Event Yield') histograms[Common.Data].GetYaxis().SetTitleOffset(1.2) histograms[Common.Data].GetYaxis().SetRangeUser(0, 1.1 * maxcount) histograms[Common.Data].SetMarkerSize(3) if histograms[Common.Data].GetNbinsX() >= 50: histograms[Common.Data].SetMarkerSize(2) histograms[Common.Data].SetLineWidth(3) histograms[Common.Data].SetMarkerStyle(8) histograms[Common.Data].Draw('e1') stack.Draw('samehist') # Draw data point histograms[Common.Data].Draw('e1,same') # Draw legend if self.getParameter('discriminator-legends', 'false') == 'true': leg.Draw() # Draw text text = TLatex() text.SetTextFont(62) text.SetTextAlign(32) text.SetNDC() text.SetTextSize(0.050) text.DrawLatex( 0.94, 0.94 - 0 * 0.05, 'CMS %s fb^{-1}' % Common.Luminosity[set['channel']]) text.SetTextColor(13) text.DrawLatex(0.94, 0.94 - 1 * 0.05, '%s' % Common.Labels[set['channel']]) # Update canvas canvas.Update() # Save the canvas outfile = '%s/%s_%s' % (outdir, Common.filename(set), bin) canvas.SaveAs('%s.eps' % outfile) canvas.SaveAs('%s.png' % outfile) # Creating the discriminator shapes # No profile plots for xchecks if self.isParameter('xcheck'): continue # Normalizing the histograms histograms['signals'].Scale(1. / histograms['signals'].Integral()) # Normalizing the histograms histograms['backgrounds'].Scale( 1. / histograms['backgrounds'].Integral()) # Legend #if self.isParameter('legend'): leg2 = TLegend(1.0, 0.8, 0.8, 1.0) #else: #leg2 = TLegend(0,0,0,0) # Signal is blue and solid fill style histograms['signals'].SetLineColor(ROOT.kBlue) histograms['signals'].SetFillColor(ROOT.kBlue) histograms['signals'].SetFillStyle(3002) histograms['signals'].SetLineWidth(3) histograms['signals'].GetXaxis().SetTitle('%s NEAT output' % signalName) leg2.AddEntry(histograms['signals'], 'Signal', 'f') # Background is red and filled with diagonal lines histograms['backgrounds'].SetLineColor(ROOT.kRed) histograms['backgrounds'].SetFillColor(ROOT.kRed) histograms['backgrounds'].SetFillStyle(3004) histograms['backgrounds'].SetLineWidth(3) histograms['backgrounds'].GetXaxis().SetTitle('%s NEAT output' % signalName) leg2.AddEntry(histograms['backgrounds'], 'Background', 'f') # Plot first the one with largest amplitud smax = histograms['signals'].GetMaximum() bmax = histograms['backgrounds'].GetMaximum() if smax > bmax: histograms['signals'].Draw('hist') histograms['backgrounds'].Draw('samehist') else: histograms['backgrounds'].Draw('hist') histograms['signals'].Draw('samehist') if self.getParameter('profile-legends', 'true') == 'true': leg2.Draw() # Save the canvas outfile = '%s/profiles_%s_%s' % (outdir, set['channel'], bin) canvas.SaveAs('%s.eps' % outfile) canvas.SaveAs('%s.png' % outfile)
def plotUpperLimits(labels, values): # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/ N = len(labels) yellow = TGraph(2 * N) # yellow band green = TGraph(2 * N) # green band median = TGraph(N) # median line up2s = [] for i in range(N): # file_name = "higgsCombine"+labels[i]+"AsymptoticLimits.mH125.root" file_name = "higgsCombine.AsymptoticLimits.mH125." + labels[i] + ".root" limit = getLimits(file_name) # print'limit = ',limit # print'values[i] = ',values[i] up2s.append(limit[4]) yellow.SetPoint(i, values[i], limit[4]) # + 2 sigma green.SetPoint(i, values[i], limit[3]) # + 1 sigma median.SetPoint(i, values[i], limit[2]) # median green.SetPoint(2 * N - 1 - i, values[i], limit[1]) # - 1 sigma yellow.SetPoint(2 * N - 1 - i, values[i], limit[0]) # - 2 sigma W = 800 H = 600 T = 0.08 * H B = 0.12 * H L = 0.12 * W R = 0.04 * W c = TCanvas("c", "c", 100, 100, W, H) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin(L / W) c.SetRightMargin(R / W) c.SetTopMargin(T / H) c.SetBottomMargin(B / H) c.SetTickx(0) c.SetTicky(0) c.SetGrid() # c.SetLogy() # gPad.SetLogy() c.cd() # ROOT.gPad.SetLogy() # c.SetLogy() frame = c.DrawFrame(1.4, 0.001, 4.1, 10) frame.GetYaxis().CenterTitle() frame.GetYaxis().SetTitleSize(0.05) frame.GetXaxis().SetTitleSize(0.05) frame.GetXaxis().SetLabelSize(0.04) frame.GetYaxis().SetLabelSize(0.04) frame.GetYaxis().SetTitleOffset(0.9) frame.GetXaxis().SetNdivisions(508) frame.GetYaxis().CenterTitle(True) # frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}") if (args.atlas_compare): frame.GetYaxis().SetTitle( "95% CL limits on #sigma(gg#rightarrow X)#times B(X#rightarrow HH) [pb]" ) elif (args.CMS_compare): frame.GetYaxis().SetTitle( "95% CL limit on #sigma(gg#rightarrow X#rightarrow HH) (fb)") # frame.GetYaxis().SetTitle("95% upper limit on #sigma #times BR / (#sigma #times BR)_{SM}") # frame.GetXaxis().SetTitle("background systematic uncertainty [%]") #if(args.SM_Radion): frame.GetXaxis.SetTitle("Standard Model") #else: frame.GetXaxis().SetTitle("Radion Mass (GeV)") # frame.SetMinimum(0) # frame.SetMinimum(1) # need Minimum > 0 for log scale frame.SetMinimum(1.000001) # need Minimum > 0 for log scale # frame.SetMaximum(max(up2s)*1.05) # frame.SetMaximum(max(up2s)*2) # frame.SetMaximum(1000.) if (args.atlas_compare): frame.SetMaximum(7 * 1e2) # ATLAS elif (args.CMS_compare): frame.SetMaximum(8 * 1e4) # CMS HH #frame.GetXaxis().SetLimits(min(values),max(values)) # frame.SetLogy() frame.GetXaxis().SetLimits(min(values) - 10, max(values) + 10) yellow.SetFillColor(ROOT.kOrange) yellow.SetLineColor(ROOT.kOrange) yellow.SetFillStyle(1001) yellow.Draw('F') green.SetFillColor(ROOT.kGreen + 1) green.SetLineColor(ROOT.kGreen + 1) green.SetFillStyle(1001) green.Draw('Fsame') median.SetLineColor(1) median.SetLineWidth(2) median.SetLineStyle(2) median.Draw('Lsame') CMS_lumi.CMS_lumi(c, 4, 11) ROOT.gPad.SetTicks(1, 1) frame.Draw('sameaxis') # yboost = 0.075 yboost = -0.2 x1 = 0.15 x2 = x1 + 0.24 y2 = 0.76 + yboost y1 = 0.60 + yboost legend = TLegend(x1, y1, x2, y2) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextSize(0.041) legend.SetTextFont(42) legend.AddEntry(median, "AsymptoticLimits CL_{s} expected", 'L') legend.AddEntry(green, "#pm 1 std. deviation", 'f') # legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 1 std. deviation",'f') legend.AddEntry(yellow, "#pm 2 std. deviation", 'f') # legend.AddEntry("","STAT Only","") # legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 2 std. deviation",'f') legend.Draw() label = TLatex() label.SetNDC() label.SetTextAngle(0) label.SetTextColor(kBlack) label.SetTextFont(42) label.SetTextSize(0.045) label.SetLineWidth(2) label.DrawLatex(0.7, 0.7 + yboost, "STAT only") print " " # c.SaveAs("UpperLimit.png") outFile = '' if (args.CMS_compare): outFile += "CMS_Compare_" if (args.atlas_compare): outFile += "atlas_Compare_" if args.SM_Radion: outFile += "SM_" c.SaveAs(outFile + "UpperLimit.pdf") c.SaveAs(outFile + "UpperLimit.C") c.Close()
if pi.Pt() < 100: print (child.text) print ("met",pi.Pt()) for met in genMET: h_genMET.Fill(met) hists.append(h_genMET) c = TCanvas() legend=TLegend(.53,.59,.87,.89) legend.SetTextSize(0.038) leg_entry=['M_{a}=100 GeV','M_{a}=200 GeV','M_{a}=300 GeV','M_{a}=400 GeV','M_{A}=500 GeV'] cmsname = TLatex(); cmsname.SetTextSize(0.036) cmsname.SetTextAlign(12) cmsname.SetNDC(1) cmsname.SetTextFont(61) #print len(hists) for hist in range(len(hists)): print (hist) if hist==0: hists[hist].SetXTitle("genMET[GeV]") hists[hist].SetYTitle("Events") hists[hist].SetLineColor(hist+1) hists[hist].Rebin(5) hists[hist].SetLineWidth(3) hists[hist].Scale(1/hists[hist].Integral()) hists[hist].SetMaximum(2) legend.AddEntry(hists[hist],leg_entry[hist],"L") hists[hist].Draw('HIST')
#lint = s_lumi + "fb^{-1}"+ CoMEr; lint = CoMEr # Draw Plots now # ************************************************************************************ # Signal Mass c1 = TCanvas("c1", "SignalOverLay", 900, 900) c1.cd() cmstex = TLatex() #cmstex = ROOT.TLatex() cmstex.SetTextAlign(12) cmstex.SetTextSize(0.035) cmstex.SetTextFont(22) cmstex.SetTextAngle(0) cmstex.SetTextColor(kBlack) cmstex.SetNDC() cmstex.DrawLatex(0.20, 0.865, "CMS") cmstex.DrawLatex(0.20, 0.832, "Preliminary") cmstex.DrawLatex(0.72, 0.920, lint) hZmass.SetTitle("Z Mass") hZmass.Draw() hZmassSg.Draw("sames") hZmass.GetXaxis().SetRangeUser(50.0, 150.0) #Add Legend lsg = TLegend(0.60, 0.70, 0.94, 0.90) lsg.SetBorderSize(1) lsg.SetFillColor(19) lsg.AddEntry(hZmass, "Total Z Candidates", "l") lsg.AddEntry(hZmassSg, "76GeV/c^{2} < Mass < 100 GeV/c^{2}", "l") lsg.SetTextSize(0.02)
def show(self, outDir): if len(self.mc) == 0: print '%s is empty' % self.name return canvas = TCanvas('c_' + self.name, 'C', 600, 600) canvas.cd() t1 = TPad("t1", "t1", 0.0, 0.20, 1.0, 1.0) t1.SetBottomMargin(0) t1.Draw() t1.cd() self.garbageList.append(t1) frame = None # leg = TLegend(0.15,0.9,0.9,0.95) leg = TLegend(0.6, 0.7, 0.92, 0.89) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.04) nlegCols = 0 maxY = 1.0 if self.data is not None: leg.AddEntry(self.data, self.data.GetTitle(), 'p') frame = self.data.Clone('frame') self.garbageList.append(frame) maxY = self.data.GetMaximum() * 1.1 frame.Reset('ICE') totalMC = None stack = THStack('mc', 'mc') for h in self.mc: stack.Add(h, 'hist') leg.AddEntry(h, h.GetTitle(), 'f') nlegCols = nlegCols + 1 if totalMC is None: totalMC = h.Clone('totalmc') self.garbageList.append(totalMC) totalMC.SetDirectory(0) else: totalMC.Add(h) if totalMC is not None: maxY = max(totalMC.GetMaximum(), maxY) if frame is None: frame = totalMC.Clone('frame') frame.Reset('ICE') self.garbageList.append(frame) if self.data is not None: nlegCols = nlegCols + 1 if nlegCols == 0: print '%s is empty' % self.name return frame.GetYaxis().SetRangeUser(1e-2, 1.2 * maxY) frame.SetDirectory(0) frame.Draw() frame.GetYaxis().SetTitleOffset(1.6) stack.Draw('hist same') if self.data is not None: self.data.Draw('P same') # leg.SetNColumns(nlegCols) leg.SetNColumns(2) leg.Draw() ## Draw CMS Preliminary label tlat = TLatex() tlat.SetNDC() tlat.SetTextFont(62) tlat.SetTextSize(0.04) tlat.SetTextAlign(31) prelim_text = 'CMS work in progress, #sqrt{s} = 8 TeV' tlat.DrawLatex(0.92, 0.92, prelim_text) if totalMC is None or self.data is None: t1.SetPad(0, 0, 1, 1) t1.SetBottomMargin(0.12) else: canvas.cd() t2 = TPad("t2", "t2", 0.0, 0.0, 1.0, 0.2) self.garbageList.append(t2) t2.SetTopMargin(0) t2.SetBottomMargin(0.4) t2.SetGridy() t2.Draw() t2.cd() ratio = self.data.Clone('ratio') self.garbageList.append(ratio) ratio.Divide(totalMC) ratio.SetDirectory(0) ratio.Draw('e1') ratio.GetYaxis().SetRangeUser(0.62, 1.38) ratio.GetYaxis().SetTitle('Data/#SigmaBkg') ratio.GetYaxis().SetNdivisions(5) ratio.GetYaxis().SetLabelSize(0.15) ratio.GetYaxis().SetTitleSize(0.18) ratio.GetXaxis().SetLabelSize(0.18) ratio.GetXaxis().SetTitleSize(0.2) ratio.GetYaxis().SetTitleOffset(0.3) ratio.GetXaxis().SetTitleOffset(0.8) canvas.cd() canvas.Modified() canvas.Update() for ext in ['pdf', 'png']: canvas.SaveAs(outDir + '/' + self.name + '.' + ext)
def plotHistos(dac, histVals, qiCalib = None, outDir = "results", currentMode = ""): adcGraphs = [] chargeGraphs = [] gStyle.SetMarkerColor(kBlue) gStyle.SetLineColor(kBlack) convFactor = 1. if qiCalib is None: # Use nominal qiCalib print "Using nominal QI calibrations" if currentMode == "low": convFactor = 1.375 elif currentMode == "high": convFactor = 7.7 offset = 0. else: print "Using custom QI calibrations" #for i in range(len(histVals[dac[0]])): for i in range(12): adcGr = TGraphAsymmErrors() adcGr.SetMarkerStyle(22) #adcGr.SetMarkerSize(1.0) adcGr.SetName("h%d_ADC" % i) adcGr.SetTitle("h%d ADC vs %s" % (i, "Charge %s current mode" % currentMode if currentMode in ["low", "high"] else "DAC value")) chGr = TGraphAsymmErrors() chGr.SetMarkerStyle(22) #chGr.SetMarkerSize(1.3) chGr.SetName("h%d_LinADC" % i) chGr.SetTitle("h%d Lin ADC vs %s" % (i, "Charge %s current mode" % currentMode if currentMode in ["low", "high"] else "DAC value")) adcGraphs.append(adcGr) chargeGraphs.append(chGr) for i, dv in enumerate(dac): for n in range(len(adcGraphs)): mean = histVals[dv][n]["mean"] err = histVals[dv][n]["rms"] if qiCalib is not None: QIchan = int(n/6)*8 + n%6 + 1 convFactor = qiCalib[QIchan]["slope"] offset = qiCalib[QIchan]["offset"] # Index of new point np = adcGraphs[n].GetN() # Set value and error adcGraphs[n].SetPoint(np, dv*convFactor + offset, mean) adcGraphs[n].SetPointError(np, 0., 0., err, err) chMean, chErr = linADC(mean, err) chargeGraphs[n].SetPoint(np, dv*convFactor + offset, chMean) chargeGraphs[n].SetPointError(np, 0., 0., chErr, chErr) if outDir[-1] == "/": outDir = outDir[:-1] os.system("mkdir -p %s/adcH; mkdir -p %s/chargeH" % (outDir, outDir) ) c1 = TCanvas('c1','c1', 1200, 800) c1.SetLeftMargin(0.15); c1.SetRightMargin(0.25) c1.SetBottomMargin(0.25); pad1=TPad('p1','p1',0.,0.,1.0,1.0) pad1.Draw() outF = TFile.Open(outDir + "/histos.root", "RECREATE") xAxisTitle = "Charge [fC]" if currentMode in ["low", "high"] else "DAC value" for i,adcGr in enumerate(adcGraphs): """ adcGr.Fit('pol1', "Q") # Q: Quiet mode f = adcGr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %.3f #pm %.2f slope %.3f #pm %.6f" % (p0, p0_err, p1, p1_err) """ adcGr.GetXaxis().SetTitle(xAxisTitle) adcGr.GetYaxis().SetTitle("ADC") adcGr.GetYaxis().SetTitleOffset(1.2) pad1.cd() pad1.SetLogx(True) adcGr.Draw("AP") adcGr.Write() Quiet(c1.SaveAs)(outDir + "/adcH/adc_hist_%d.png" % i) c1.SetLogy(True) for i,chGr in enumerate(chargeGraphs): chGr.Fit('pol1', "Q") # Q: Quiet mode f = chGr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %.3f #pm %.2f slope %.3f #pm %.6f" % (p0, p0_err, p1, p1_err) chGr.GetXaxis().SetTitle(xAxisTitle) chGr.GetYaxis().SetTitle("Linearized ADC") chGr.GetYaxis().SetTitleOffset(1.2) pad1.cd() pad1.SetLogx(True) pad1.SetLogy(True) chGr.Draw("AP") chGr.Write() txt=TLatex() txt.SetNDC(True) txt.SetTextFont(43) txt.SetTextSize(20) txt.SetTextAlign(12) txt.DrawLatex(0.45,0.87, fitline) Quiet(c1.SaveAs)(outDir + "/chargeH/charge_hist_%d.png" % i) # for g in adcGraphs: # # g.Write() # for g in chargeGraphs: # g.Write() #outF.Write() outF.Close()
cv[thesuper[ikey].name].SetGrid() # test smearing #rn = ROOT.TRandom(12345) #for iibin in range(0,tmpsumth.GetNbinsX()): # tmpsumth.SetBinContent(iibin, rn.Poisson(tmpsumth.GetBinContent(iibin)) ) # if tmpsumth.GetBinContent(iibin) == 0: # tmpsumth.SetBinError(iibin, 0 ) # else: # tmpsumth.SetBinError(iibin, 1/math.sqrt(tmpsumth.GetBinContent(iibin)) ) #tmpsumth.Draw("same E1") if printBanner: tex = TLatex(0.35, 0.95, Banner) tex.SetNDC() tex.SetTextSize(0.05) tex.Draw() cv[thesuper[ikey].name].Update() #cv[thesuper[ikey].name].Print("test.png") # pause if option.wait: raw_input('Press ENTER to continue\n ') #********************************************************************** thegraph = dh.graph if verbose: print("= Create graph histograms:") for ikey in thegraph:
def plotQIcalibration(results, outDir = "results", currentMode = ""): gROOT.SetBatch(True) calibGraphs = [] gStyle.SetMarkerColor(kBlue) gStyle.SetLineColor(kBlack) #for ch in xrange(1, len(results)+1): # Number of channels for ch in sorted(results.keys()): gr = TGraphAsymmErrors() gr.SetMarkerStyle(22) gr.SetMarkerSize(1.2) gr.SetName("Channel_%d_Charge_vs_DAC" % ch) gr.SetTitle("Channel %d Charge vs DAC value%s" % (ch, " %s current mode" % currentMode if currentMode in ["low", "high"] else "")) res = results[ch] for i, dacVal in enumerate(sorted(res.keys())): mean = res[dacVal]["mean"] * 25.e6 # Convert to fC err = res[dacVal]["std"] * 25.e6 # Index of new point np = gr.GetN() # Set value and error gr.SetPoint(np, dacVal, mean) gr.SetPointError(np, 0., 0., err, err) calibGraphs.append((gr,ch)) if outDir[-1] == "/": outDir = outDir[:-1] os.system("mkdir -p %s/calibGraphs" % outDir ) c1 = TCanvas('c1','c1', 1200, 800) c1.SetLeftMargin(0.15); c1.SetRightMargin(0.25) c1.SetBottomMargin(0.25); pad1=TPad('p1','p1',0.,0.,1.0,1.0) pad1.Draw() outF = TFile.Open(outDir + "/calibration.root", "RECREATE") fitParams = {} # Converted to charge by * 25ns for i,(gr,ch) in enumerate(calibGraphs): gr.Fit('pol1', "Q") # Q: Quiet mode f = gr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %g #pm %g slope %g #pm %g" % (p0, p0_err, p1, p1_err) # Convert to fC fitParams[ch] = {"slope":(p1), "offset":(p0)} #fitParams[(i+1)] = {"slope":(p1), "offset":(p0)} gr.GetXaxis().SetTitle("DAC value") gr.GetYaxis().SetTitle("Charge [fC]") if currentMode == "low": gr.GetYaxis().SetTitleOffset(1.37) pad1.cd() gr.Draw("AP") gr.Write() txt=TLatex() txt.SetNDC(True) txt.SetTextFont(43) txt.SetTextSize(20) txt.SetTextAlign(12) txt.DrawLatex(0.40,0.87, fitline) Quiet(c1.SaveAs)(outDir + "/calibGraphs/channel_%d.png" % (i+1)) # for g in adcGraphs: # # g.Write() # for g in chargeGraphs: # g.Write() #outF.Write() outF.Close() return fitParams
def add_alice_text(): tex = TLatex(0.52, 0.75, "#scale[0.8]{ALICE work in progress}") tex.SetTextSize(0.04) tex.SetNDC() return tex
def calc_punzi_FOM_vs_ctau(cutlist, labellist=[],mass_point=40,additional_string="",alpha=2,CL=5,FOM='punzi',header=""): file = {} nevt = {} tree = {} effs = {} chain = {} hist = {} eff_dict = { k:{} for k in cutlist} back_int = { k:{} for k in cutlist} back_int_weight = { k:{} for k in cutlist} back_eff = { k:{} for k in cutlist} punzi_dict = { k:{} for k in cutlist} graph = {} back_graph = {} ncuts = len(cutlist) if labellist == []: labellist=cutlist print NTUPLEDIR print "............." #prepare ctau ordered array for 1D plot mass_array = [] ctau_array = [] #for signal we have the normal efficiency for i, s in enumerate(sign): file[s] = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") # Read TFile tree[s] = file[s].Get("ntuple/tree") # Read TTree nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)# all gen events before cuts! #tree[s] = file[s].Get("skim") # Read TTree #nevt[s] = tree[s].GetEntries("")#if the tree is skimmed, this becomes a relative denominator #nevt[s] = (file[s].Get('c_nEvents')).GetBinContent(1)# all gen events before cuts! filename = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") if verbose_add: print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' if verbose_add: print filename if verbose_add: print "x-check: n gen events in counter, first bin:" if verbose_add: print (filename.Get('c_nEvents')).GetBinContent(1) if verbose_add: print "x-check: n entries in counter:" if verbose_add: print (filename.Get('c_nEvents')).GetEntries() effs[s] = [0]*(ncuts+1) effs[s] = [0]*(ncuts+1) weight = "1"#"EventWeight" var = "isMC" if samples[s]['mass'] not in mass_array: mass_array.append(samples[s]['mass']) if samples[s]['ctau'] not in ctau_array: ctau_array.append(samples[s]['ctau']) for j, c in enumerate(cutlist): tot_gen = nevt[s] n = tree[s].GetEntries("(" + cutlist[j] + ")") #wat?#test_op = cutlist[j] + " && number_of_matched_Jets>=1" #wat?#n = tree[s].GetEntries("(" + test_op + ")") ###BUGFIX: efficiency should be computed w.r.t. histo integral #hist[s+"_cut"+str(j)] = TH1F(s+"_cut"+str(j), ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max']) #hist[s+"_cut"+str(j)].Sumw2() #cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "") #tree[s].Project(s+"_cut"+str(j), var, cutstring) #hist[s+"_cut"+str(j)].SetOption("%s" % tree[s].GetTree().GetEntriesFast()) if verbose_add: print '\n' if verbose_add: print '**********************************************' if verbose_add: print "cut: ", c if verbose_add: print 'over signal ', s if verbose_add: print '\n' if verbose_add: print "signal num: ", n if verbose_add: print "signal den: ", tot_gen #if verbose_add: print "BUGFIX!!!!!!!!!!!" #if verbose: print "BUGFIX!!!!!!!!!!!" #if verbose_add: print "signal num from integral: ", hist[s+"_cut"+str(j)].Integral() #if verbose_add: print "signal den from generator: ", tot_gen #if verbose: print "BUGFIX!!!!!!!!!!!" if verbose_add: print ("signal eff %.2f") % (float(n)/(tot_gen)*100) if tot_gen==0: effs[s][j] = float(0.) else: effs[s][j] = (float(n)/(tot_gen)) eff_dict[c][s] = {'mass' : samples[s]['mass'], 'ctau' : samples[s]['ctau'], 'eff' :effs[s][j], 'nevents' : n} #sort mass array masses = np.array(mass_array) masses.sort() ctaus = np.array(ctau_array) ctaus.sort() #define multigraph mg = TMultiGraph() #leg = TLegend(0.78, 0.7, 0.98, 0.98) #leg2 = TLegend(0., 0.4, 0.98, 0.98) #leg2 = TLegend(0.3, 0.11, 0.65, 0.45)#DCMS,gen matching leg2 = TLegend(0.4, 0.11, 0.85, 0.45)#DCMS,summary plot leg2 = TLegend(0.4-0.3, 0.11+0.43, 0.85+0.05-0.3, 0.45+0.43)#EXO,summary plot leg2 = TLegend(0.4, 0.11, 0.85+0.05, 0.45)#EXO,summary plot leg3 = TLegend(0., 0.5, 0.5, 1.)#2 plots leg = TLegend(0., 0.4, 0.98, 0.98) leg.SetTextSize(0.03) leg2.SetTextSize(0.03) leg2.SetTextSize(0.025) leg.SetBorderSize(0) leg2.SetBorderSize(0) leg.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") leg2.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") leg3.SetTextSize(0.03) leg3.SetTextSize(0.025) leg3.SetBorderSize(0) leg3.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV") #for background let's first consider the cut for j, c in enumerate(cutlist): print '\n' print "cut: ", c print 'over background' print '\n' #then loop over background integral = 0 weighted_integral = 0 back_tot_events = 0 for i, s in enumerate(back): chain[s] = TChain("ntuple/tree") #chain[s] = TChain("skim") #print "back: ", s back_file = {} for p, ss in enumerate(samples[s]['files']): back_file[ss] = TFile(NTUPLEDIR + ss + ".root", "READ") # Read TFile #?#if verbose: print "file: ", ss #?#if verbose: print "gen events: ", (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1) #?#if verbose: print "tree events: ", (back_file[ss].Get('ntuple/tree')).GetEntries() back_tot_events += (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1) #back_tot_events += (back_file[ss].Get('c_nEvents')).GetBinContent(1) chain[s].Add(NTUPLEDIR + ss + ".root") #print "MODIFIED WEIGHT!!!!!!" #weight = ("EventWeight*%s/5000." % str(back_tot_events)) weight = "EventWeight" #var = "nCHSJets" var = "isMC" hist[s] = TH1F(s, ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max']) hist[s].Sumw2() cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "") chain[s].Project(s, var, "")#"1*"+"("+weight+")") hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast()) #if verbose: print "Hist content, no cut:" #if verbose: print hist[s].Print() #?#if verbose: print "events in the histo with get entries with empty project: ", hist[s].GetEntries() #?#if verbose: print "area under histo with empty project: ", hist[s].Integral() chain[s].Project(s, var, cutstring)#"1*"+"("+weight+")") hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast()) hist[s].Scale(samples[s]['weight'] if hist[s].Integral() >= 0 else 0) #?#if verbose: print "events in the histo with get entries after project: ", hist[s].GetEntries() #?#if verbose: print "area under histo after project: ", hist[s].Integral() if verbose: print "Hist content, with cut:" if verbose: print hist[s].Print() integral += hist[s].GetEntries() weighted_integral += hist[s].Integral() back_int[c] = integral back_int_weight[c] = weighted_integral if back_tot_events==0: back_eff[c] = float(0.) else: back_eff[c] = float(integral)/float(back_tot_events) if verbose: print "cut: ", c if verbose: print "back tot events (unweighted):", back_tot_events if verbose: print "back integral (unweighted): ", back_int[c] if verbose: print "back integral (weighted): ", back_int_weight[c] if verbose: print "back eff (unweighted): ", back_eff[c]*100 if FOM=="signaleff": punzi_dict[c]['back'] = {'back' : back_eff[c]*100} for i, s in enumerate(sign): if verbose: print "signal efficiency: ", eff_dict[c][s]['eff']*100 if FOM=="punzi": punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']/(CL**2/2. + alpha*math.sqrt(back_int_weight[c]) + (CL/2.)*math.sqrt(CL**2 + 4*alpha*math.sqrt(back_int_weight[c]) + 4*back_int_weight[c]))} elif FOM=="signaleff": punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']*100} elif FOM=="entries": punzi_dict[c][s] = {'sign': eff_dict[c][s]['nevents']} else: print "not punzi FOM, aborting!" exit() if FOM=="signaleff": dummy = TGraph()#len(ct),ct, np.array(ct)) dummy.SetMarkerStyle(0) dummy.SetLineWidth(2) dummy.SetMarkerSize(1.) dummy.SetLineColor(15) dummy.SetLineStyle(2) if header!="": leg2.AddEntry(dummy, header,'') leg3.AddEntry(dummy, header,'') #for each cut, we need a graph for j, c in enumerate(cutlist): #first let's build the ordered punzi vector w.r.t. masses, for a chosen ctau punzi_array = [] back_array = [] for la in ctaus: #la = str(a) if la== 0.001: st = CHANNEL+"_M"+str(mass_point)+"_ctau0" elif la==0.05 or la==0.1: st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(str(la).replace("0.","0p")) else: st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(int(la)) #st = "VBFH_M"+str(mass_point)+"_ctau"+str(a) punzi_array.append(punzi_dict[c][st]['sign']) mass = array('d', masses) ct = array('d', ctaus) p_array = array('d',punzi_array) #graph[c] = TGraph(len(mass),mass, np.array(p_array)) graph[c] = TGraph(len(ct),ct, np.array(p_array)) graph[c].SetMarkerStyle(markers[j])#21 graph[c].SetLineWidth(3) graph[c].SetMarkerSize(1.2) graph[c].SetMarkerColor(colors[j]) graph[c].SetLineColor(colors[j]) graph[c].SetFillColor(colors[j]) #graph[c].SetLogx() leg.AddEntry(graph[c],labellist[j],'PL') leg2.AddEntry(graph[c],labellist[j],'PL') leg3.AddEntry(graph[c],labellist[j],'PL') mg.Add(graph[c]) if FOM=="signaleff": #add plot for background for a in ctaus: back_array.append(punzi_dict[c]['back']['back']) mass = array('d', masses) ct = array('d', ctaus) e_array = array('d',back_array) #back_graph[c] = TGraph(len(mass),mass, np.array(e_array)) back_graph[c] = TGraph(len(ct),ct, np.array(e_array)) back_graph[c].SetMarkerStyle(0) back_graph[c].SetLineWidth(2) back_graph[c].SetMarkerSize(1.) back_graph[c].SetMarkerColor(colors[j]) back_graph[c].SetLineColor(colors[j]) back_graph[c].SetLineStyle(2) back_graph[c].SetFillColor(colors[j]) #back_graph[c].SetLogx() #leg.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL') #w#leg2.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL') #w#mg.Add(back_graph[c]) if FOM=="signaleff": dummy = TGraph(len(ct),ct, np.array(e_array)) dummy.SetMarkerStyle(0) dummy.SetLineWidth(2) dummy.SetMarkerSize(1.) dummy.SetLineColor(15) dummy.SetLineStyle(2) #w#leg2.AddEntry(dummy, 'cuts on bkg.','PL') #cmg = TCanvas("cmg", "cmg", 2000, 1400) #cmg = TCanvas("cmg", "cmg", 2000, 800)#best #cmg = TCanvas("cmg", "cmg", 1200, 1000) cmg = TCanvas("cmg", "cmg", 1300, 800)#DCMS cmg.cd() cmg.SetGrid() cmg.SetLogx() #if FOM=="signaleff": # cmg.SetLogx() #pad1 = TPad("pad1", "pad1", 0, 0., 0.85, 1.0) #pad1 = TPad("pad1", "pad1", 0, 0., 0.7, 1.0) #pad1.SetGrid() #pad1.SetLogx() if FOM=="signaleff": print "LOL" #pad1.SetLogy() #pad1.SetLogy() #pad1.Draw() #pad1.cd() #W#if FOM=="signaleff": #w#mg.SetMaximum(101) #mg.SetMinimum(1.e-50) mg.SetMinimum(0.)#!! mg.Draw("APL") mg.GetXaxis().SetTitleSize(0.05) mg.GetYaxis().SetTitleSize(0.05) mg.GetXaxis().SetTitle('c#tau_{#pi} (mm)') mg.GetYaxis().SetTitleOffset(0.9); if FOM=="punzi": mg.GetYaxis().SetTitle('Punzi significance @ '+str(alpha)+' #sigma, '+CHANNEL+' cuts') #mg.GetYaxis().SetTitleOffset(1.5) elif FOM=="signaleff": #mg.GetYaxis().SetTitle('Signal efficiency, '+CHANNEL+' cuts (%)') mg.GetYaxis().SetTitle('Signal gen-matching efficiency, '+CHANNEL+' (%)') elif FOM=="entries": mg.GetYaxis().SetTitle('Signal entries surviving cuts') else: print "not punzi FOM, aborting" latex = TLatex() latex.SetNDC() latex.SetTextSize(0.05) latex.SetTextColor(1) latex.SetTextFont(42) latex.SetTextAlign(33) latex.SetTextFont(62) latex.DrawLatex(0.25, 0.96, "CMS") latex.SetTextFont(52) latex.DrawLatex(0.66, 0.96, "Simulation Preliminary") cmg.Update() cmg.cd() leg2.SetTextSize(0.04) #leg.Clear()#????????? #w#leg2.Draw() #cmgL = TCanvas("cmgL", "cmgL", 2000, 800)#DCMS #cmgL.cd() #pad2 = TPad("pad2", "pad2", 0.85, 0., 1, 1.0) #pad2 = TPad("pad2", "pad2", 0.7, 0., 1, 1.0) #pad2.SetGrid() #pad2.SetLogx()macro/VBF_punzi_LLP_AOD.py #pad2.Draw() #pad2.cd() leg3.SetTextSize(0.04) #leg.Clear()#????????? leg3.Draw() #cmgL.Update() if FOM=="punzi": cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".pdf") cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".png") cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.png") elif FOM=="signaleff": cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf") cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png") cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png") elif FOM=="entries": cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf") cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png") cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf") cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png") else: print "not punzi FOM, aborting" if not options.bash: raw_input("Press Enter to continue...") cmg.Close()
def makePlot1D(filepath,foutname,plottitle='',masstitle=''): br = 1 if 'Resonant' in plottitle else 0.68 limits = parseLimitFiles2D(filepath,br) xaxis = []; xseclist = [] xsecerr = [] cent = []; obs = [] up1 = []; up2 = [] down1 = []; down2 = [] maxval = 0; minval = 999 for m in sorted(limits): l = limits[m] xaxis.append(m) xseclist.append(l.xsec) xsecerr.append(l.xsec*.2) cent.append(l.cent) up1.append(l.up1-l.cent) up2.append(l.up2-l.cent) down1.append(l.cent-l.down1) down2.append(l.cent-l.down2) obs.append(l.obs) maxval = max(maxval,l.up2) minval = min(minval,l.down2) N = len(xaxis) up1Sigma = array('f',up1) up2Sigma = array('f',up2) down1Sigma = array('f',down1) down2Sigma = array('f',down2) cent = array('f',cent) obs = array('f',obs) xarray = array('f',xaxis) xsecarray = array('f',xseclist) xsecerrarray = array('f',xsecerr) zeros = array('f',[0 for i in xrange(N)]) graphXsec = TGraphErrors(N,xarray,xsecarray,zeros,xsecerrarray) graphCent = TGraph(N,xarray,cent) graphObs = TGraph(N,xarray,obs) graph1Sigma = TGraphAsymmErrors(N,xarray,cent,zeros,zeros,down1Sigma,up1Sigma) graph2Sigma = TGraphAsymmErrors(N,xarray,cent,zeros,zeros,down2Sigma,up2Sigma) c = TCanvas('c','c',700,600) c.SetLogy() c.SetLeftMargin(.15) graph2Sigma.GetXaxis().SetTitle(masstitle+' [GeV]') graph2Sigma.GetYaxis().SetTitle('95% C.L. upper limit [#sigma/#sigma_{theory}]') c2 = root.kOrange c1 = root.kGreen+1 graph2Sigma.SetLineColor(c2) graph1Sigma.SetLineColor(c1) graph2Sigma.SetFillColor(c2) graph1Sigma.SetFillColor(c1) graph2Sigma.SetMinimum(0.5*minval) graph2Sigma.SetMaximum(10*maxval) graphCent.SetLineWidth(2) graphCent.SetLineStyle(2) graphObs.SetLineColor(1) graphObs.SetLineWidth(3) graphObs.SetMarkerStyle(20) graphObs.SetMarkerSize(1) graphObs.SetMarkerColor(1) graph1Sigma.SetLineStyle(0) graph2Sigma.SetLineStyle(0) leg = TLegend(0.55,0.7,0.9,0.9) leg.AddEntry(graphCent,'Expected','L') if not BLIND: leg.AddEntry(graphObs,'Observed','Lp') leg.AddEntry(graph1Sigma,'1 std. dev.','F') leg.AddEntry(graph2Sigma,'2 std. dev.','F') leg.SetFillStyle(0) leg.SetBorderSize(0) graph2Sigma.Draw('A3') graph1Sigma.Draw('3 same') graphCent.Draw('same L') if not BLIND: graphObs.Draw('same Lp') subscript = 'SR' if 'Resonant' in plottitle else 'FC' coupling = '0.1' if 'Resonant' in plottitle else '0.25' graphXsec.SetLineColor(2) graphXsec.SetLineWidth(2) graphXsec.SetLineStyle(2) graphXsec.SetFillColor(2) graphXsec.SetFillStyle(3005) graphXsec.Draw('same L3') ''' if not scale: if 'Resonant' in plottitle: leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l') else: leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l') ''' if not BLIND: findIntersect1D(graphObs,graphXsec,xaxis[0],xaxis[-1]) findIntersect1D(graphCent,graphXsec,xaxis[0],xaxis[-1]) leg.Draw() label = TLatex() label.SetNDC() label.SetTextSize(0.8*c.GetTopMargin()) label.SetTextFont(62) label.SetTextAlign(11) label.DrawLatex(0.15,0.94,"CMS") label.SetTextFont(52) label.SetTextSize(0.6*c.GetTopMargin()) label.DrawLatex(0.25,0.94,"Preliminary") label.SetTextFont(42) label.SetTextSize(0.7*c.GetTopMargin()) label.DrawLatex(0.19,0.83,plottitle) if 'Resonant' in plottitle: label.DrawLatex(0.19,0.75,"a_{SR} = b_{SR} = %s"%coupling) label.DrawLatex(0.19,0.68,"m_{#chi}=100 GeV") else: label.DrawLatex(0.19,0.75,"g_{DM}^{V}=1,g_{q}^{V}=0.25") label.DrawLatex(0.19,0.68,"m_{#chi}=1 GeV") label.SetTextSize(0.6*c.GetTopMargin()) label.SetTextFont(42) label.SetTextAlign(31) # align right label.DrawLatex(0.95, 0.94,"%.1f fb^{-1} (13 TeV)"%(plotConfig.lumi)) c.SaveAs(foutname+'.pdf') c.SaveAs(foutname+'.png')
isMonsoon = (gain < 100) pixmax = 4.0 * gain pixmin = -1.0 * gain pixnbin = 50 pixbinning = "({0},{1},{2})".format(pixnbin, pixmin, pixmax) binwidth = (pixmax - pixmin) / pixnbin c = TCanvas("c", "c", 1200, 900) c.Print(outfilename + ".pdf[") outfile = TFile(outfilename + ".root", "RECREATE") latex = TLatex() latex.SetNDC(True) #x=0 and y=0 look weird (negative or extreme values) #x=[370,450] is overscan #x=[1,7] is prescan #x=[8,369] looks real - matches dimension in paper (362 pixels) #y=[625,700] is vertical overscan #y=[1,624] looks real - matches dimension in paper (624 pixels) ohdus = [] htypes = ["allpix", "prescan", "overscan", "active"] regioncuts = [ "x>0 && y>0", "x>0 && x<8 && y>0", "x>369 && y>0", "x>=8 && x<=369 && y>0 && y<=624" ]
def plotter_triggereff(eff_type): if "SLT" in args.trigger: basepath = "$HOME/PhD/ttH_MultiLeptons/RUN2/HTopMultilepAnalysisCode/trunk/HTopMultilepAnalysis/PlotUtils/OutputPlots_TTbar_RealFakeLep_TriggerEff_SLT/EfficiencyPlots_TriggerEff/BasicPlots/" elif "DLT" in args.trigger: basepath = "$HOME/PhD/ttH_MultiLeptons/RUN2/HTopMultilepAnalysisCode/trunk/HTopMultilepAnalysis/PlotUtils/OutputPlots_TTbar_RealFakeLep_TriggerEff_DLT/EfficiencyPlots_TriggerEff/BasicPlots/" filename_L = "RealFake_L_TriggerEfficiency.root" filename_T = "RealFake_T_TriggerEfficiency.root" filename_AntiT = "RealFake_AntiT_TriggerEfficiency.root" file_L = TFile(basepath + filename_L) file_T = TFile(basepath + filename_T) file_AntiT = TFile(basepath + filename_AntiT) if args.flavour == "mu": flavour = "Mu" elif args.flavour == "el": flavour = "El" if eff_type == "real": efficiency = "Real" elif eff_type == "fake": efficiency = "Fake" variable = "Pt" append = ("_observed_sub", "_expectedbkg")[bool(args.closure)] histname_L = efficiency + "_" + flavour + "_" + variable + "_L_TriggerEfficiency" + append histname_T = efficiency + "_" + flavour + "_" + variable + "_T_TriggerEfficiency" + append histname_AntiT = efficiency + "_" + flavour + "_" + variable + "_AntiT_TriggerEfficiency" + append print("Try to get histogram:\n{0}\nfrom file:\n{1}\n".format( histname_L, basepath + filename_L)) print("Try to get histogram:\n{0}\nfrom file:\n{1}\n".format( histname_T, basepath + filename_T)) print("Try to get histogram:\n{0}\nfrom file:\n{1}\n".format( histname_AntiT, basepath + filename_AntiT)) file_L.cd() hist_L = file_L.Get(histname_L) hist_L.SetDirectory(0) file_T.cd() hist_T = file_T.Get(histname_T) hist_T.SetDirectory(0) file_AntiT.cd() hist_AntiT = file_AntiT.Get(histname_AntiT) hist_AntiT.SetDirectory(0) hist_L.SetLineStyle(1) hist_L.SetLineColor(kBlack) hist_T.SetLineStyle(2) hist_T.SetLineColor(kBlack) hist_T.SetMarkerStyle(24) delta_eff = hist_L.Clone("DeltaEff") delta_eff.SetXTitle(hist_L.GetXaxis().GetTitle()) delta_eff.SetYTitle("#Delta#varepsilon/#varepsilon [%]") delta_eff.GetXaxis().SetTitleSize(0.15) delta_eff.GetYaxis().SetTitleSize(0.15) delta_eff.GetXaxis().SetTitleOffset(0.90) delta_eff.GetYaxis().SetTitleOffset(0.35) delta_eff.GetXaxis().SetLabelSize(0.15) delta_eff.GetYaxis().SetLabelSize(0.12) delta_eff.GetYaxis().SetRangeUser(-50.0, 20.0) delta_eff.GetYaxis().SetNdivisions(505) #(5) delta_eff.SetLineColor(kRed) delta_eff.SetMarkerColor(kRed) delta_eff.SetMarkerSize(1) delta_eff.Add(hist_T, -1) delta_eff.Divide(hist_T) delta_eff.Scale(100.0) legend = TLegend( 0.6, 0.4, 0.8, 0.55 ) # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) ) legend.SetHeader(flavour + " - " + efficiency) legend.SetBorderSize(0) # no border legend.SetFillStyle(0) # Legend transparent background legend.SetTextSize(0.04) # Increase entry font size! legend.SetTextFont(42) # Helvetica legend.AddEntry(hist_T, "Trigger efficiency - T", "P") legend.AddEntry(hist_L, "Trigger efficiency - L", "P") leg_ATLAS = TLatex() leg_lumi = TLatex() leg_ATLAS.SetTextSize(0.04) leg_ATLAS.SetNDC() leg_lumi.SetTextSize(0.04) leg_lumi.SetNDC() # --------------------------------------------------------------- c = TCanvas("c1", "Temp", 50, 50, 800, 600) pad1 = TPad("pad1", "", 0, 0.25, 1, 1) pad2 = TPad("pad2", "", 0, 0, 1, 0.25) pad1.SetBottomMargin(0.02) pad2.SetBottomMargin(0.4) pad1.Draw() pad2.Draw() pad1.cd() hist_L.GetXaxis().SetLabelSize(0) hist_L.GetXaxis().SetLabelOffset(999) hist_L.Draw("E0") hist_T.Draw("E0 SAME") if "SLT" in args.trigger: if args.flavour == "el": refl_vert0 = TLine(26.0, hist_L.GetMinimum(), 26.0, hist_L.GetMaximum()) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") refl_vert1 = TLine(60.0, hist_L.GetMinimum(), 60.0, hist_L.GetMaximum()) refl_vert1.SetLineStyle(2) refl_vert1.SetLineWidth(2) refl_vert1.Draw("SAME") refl_vert2 = TLine(140.0, hist_L.GetMinimum(), 140.0, hist_L.GetMaximum()) refl_vert2.SetLineStyle(2) refl_vert2.SetLineWidth(2) refl_vert2.Draw("SAME") elif args.flavour == "mu": refl_vert0 = TLine(26.0, hist_L.GetMinimum(), 26.0, hist_L.GetMaximum()) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") refl_vert1 = TLine(50.0, hist_L.GetMinimum(), 50.0, hist_L.GetMaximum()) refl_vert1.SetLineStyle(2) refl_vert1.SetLineWidth(2) refl_vert1.Draw("SAME") elif "DLT" in args.trigger: if args.flavour == "el": refl_vert0 = TLine(17.0, hist_L.GetMinimum(), 17.0, hist_L.GetMaximum()) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") elif args.flavour == "mu": refl_vert0 = TLine(22.0, hist_L.GetMinimum(), 22.0, hist_L.GetMaximum()) refl_vert0.SetLineStyle(2) refl_vert0.SetLineWidth(2) refl_vert0.Draw("SAME") legend.Draw() leg_ATLAS.DrawLatex(0.6, 0.27, "#bf{#it{ATLAS}} Work In Progress") leg_lumi.DrawLatex( 0.6, 0.2, "#sqrt{{s}} = 13 TeV, #int L dt = {0:.1f} fb^{{-1}}".format(args.lumi)) pad2.cd() delta_eff.Draw("E0") refl = TLine(delta_eff.GetBinLowEdge(1), 0.0, delta_eff.GetBinLowEdge(delta_eff.GetNbinsX() + 1), 0.0) refl.SetLineStyle(2) refl.SetLineWidth(2) refl.Draw("SAME") outpath = basepath if outpath[-1] == '/': outpath = outpath[:-1] c.SaveAs(outpath + "/TriggerEfficiencyRatio_" + efficiency + "_" + flavour + "_" + variable + ".png")
eU[i], eD[i] = eD[i], eU[i] gSyst = TGraphAsymmErrors(len(x), xHere, y, eL, eH, eU, eU) gSyst.SetName(nm) gSyst.SetMarkerStyle(mc[j][0]) gSyst.SetMarkerColor(mc[j][1]) gSyst.SetLineColor(mc[j][1]) leg.AddEntry(gSyst, nm, "lep") mg.Add(gSyst, "p") mg.Add(gNomGeV, "p") mg.Draw("ap") mg.GetXaxis().SetTitle("#tau p_{T} [GeV]") mg.SetMinimum(0.) text = TLatex() text.SetNDC() text.SetTextFont(72) text.SetTextSize(0.045) # text.DrawLatex(0.51, 0.86, "ATLAS") # text.SetTextFont(42) # text.DrawLatex(0.51 + 0.16, 0.86, "Internal") # text.SetTextSize(0.040) # text.DrawLatex(0.51, 0.80, "#sqrt{s} = 13 TeV, 139 fb^{-1}") text.SetTextFont(42) text.SetTextSize(0.040) text.DrawLatex(0.46, 0.86, f"trigger: {trig}, prong: {prong}") leg.Draw("SAME") c.SaveAs(fileName)
def make_ratioplot(name, ttbar_file=0, qcd_file=0, signal_files=[], histo=0, rebin=1, minx=0, maxx=0, miny=0, maxy=0, logy=False, xtitle='', ytitle='', textsizefactor=1, signal_legend=[], outfile=0, signal_colors=[], signal_zoom=1, qcd_zoom=1, ttbar_zoom=1, ttbar_legend='t#bar{t}', qcd_legend='QCD from MC', dosys=False, docms=True, legendtitle=''): ###canvas setting up canvas = 0 canvas = TCanvas(name, '', 0, 0, 600, 600) canvas.SetLeftMargin(0.15) canvas.SetRightMargin(0.05) canvas.SetTopMargin(0.10) canvas.SetBottomMargin(0.10) charsize = 0.04 offset = 1.9 ###latex label latex = 0 latex = TLatex(0.6, 0.7, '13 TeV, 2.69 fb^{-1}') latex.SetTextSize(charsize) latex.SetNDC(1) latex.SetTextFont(42) ###legend setting up #legend=TLegend(0.0,0.75,0.99,1.04) legend = TLegend(0.4, 0.6, 0.94, 0.95) legend.SetNColumns(2) legend.SetHeader('') legend.SetFillStyle(0) legend.SetBorderSize(0) ###mc stack stack = THStack(name + '_stack', '') qcd_histo = qcd_file.Get(histo).Clone(name + '_make_plot') qcd_histo.Rebin(rebin) ttbar_histo = ttbar_file.Get(histo).Clone() ttbar_histo.Rebin(rebin) ttbar_histo.SetFillColor(kRed - 9) ttbar_histo.SetLineColor(kRed - 9) ttbar_histo.SetMarkerColor(kRed - 9) if ttbar_zoom != 1: ttbar_histo.Scale(ttbar_zoom) legend.AddEntry(ttbar_histo, ttbar_legend, 'f') qcd_histo.SetFillColor(kOrange - 5) qcd_histo.SetLineColor(kOrange - 5) qcd_histo.SetMarkerColor(kOrange - 5) if qcd_zoom != 1: qcd_histo.Scale(qcd_zoom) legend.AddEntry(qcd_histo, qcd_legend, 'f') sum_mc = qcd_histo.Clone(histo + 'tmp') sum_mc.Add(ttbar_histo) stack.Add(ttbar_histo) stack.Add(qcd_histo) sum_mc.SetLineColor(kBlack) sum_mc.SetFillStyle(0) err = TGraphAsymmErrors(sum_mc) legend.AddEntry(err, 'Total uncertainty', 'f') if legendtitle == '': legend.AddEntry(0, "", '') legend.AddEntry(0, "g_{RS} #rightarrow t#bar{t} (2pb)", '') else: legend.AddEntry(0, "", '') legend.AddEntry(0, legendtitle, '') ###signal setting up signal_histos = [] colors = [ kBlack, kRed, kOrange, kBlue, kGreen + 3, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ] styles = [ 1, 3, 5, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] if signal_colors != []: colors = signal_colors for i in range(len(signal_files)): signal_histos.append(signal_files[i].Get(histo).Clone()) signal_histos[i].SetLineWidth(3) signal_histos[i].SetLineStyle(styles[i]) signal_histos[i].SetLineColor(colors[i]) signal_histos[i].SetMarkerColor(colors[i]) signal_histos[i].Rebin(rebin) if signal_zoom != 1: signal_histos[i].Scale(signal_zoom) legend.AddEntry(signal_histos[i], signal_legend[i], 'l') ###mc shape line ttbar_line = 0 ttbar_line = ttbar_histo.Clone() ttbar_line.SetLineColor(kBlack) ttbar_line.SetFillStyle(0) ###mc errors if dosys: sys_diff_qcd = [] sys_diff_ttbar = [] for imtt in range(1, ttbar_histo.GetNbinsX() + 1): sys_diff_qcd.append([]) sys_diff_ttbar.append([]) #adding stat uncertainties <--removed # for imtt in range(1,ttbar_histo.GetNbinsX()+1): # sys_diff_ttbar[imtt-1].append(ttbar_histo.GetBinError(imtt)) # sys_diff_ttbar[imtt-1].append(-ttbar_histo.GetBinError(imtt)) # sys_diff_qcd[imtt-1].append(qcd_histo.GetBinError(imtt)) # sys_diff_qcd[imtt-1].append(-qcd_histo.GetBinError(imtt)) #adding flat uncertainties for imtt in range(1, ttbar_histo.GetNbinsX() + 1): #ttbar for i in [ 2.4, #pdf 10.0, #mu 3.0, #xsec 6.0, #toppt 1.0, #lumi 3.5, #jec 3.0, #jer 10.0, #btag #3.0,#trig 10.0, #toptag 3.0 ]: #pileup sys_diff_ttbar[imtt - 1].append( i / 100.0 * ttbar_histo.GetBinContent(imtt)) sys_diff_ttbar[imtt - 1].append( -i / 100.0 * ttbar_histo.GetBinContent(imtt)) closureunc = 5.0 # if '1b' in histo: # closureunc=5.0 # elif '2b' in histo: # closureunc=10.0 for i in [ 2.0, #modmass closureunc ]: #closure sys_diff_qcd[imtt - 1].append(i / 100.0 * qcd_histo.GetBinContent(imtt)) sys_diff_qcd[imtt - 1].append(-i / 100.0 * qcd_histo.GetBinContent(imtt)) # #3% trigger # sys_diff_ttbar[imtt-1].append(0.03*ttbar_histo.GetBinContent(imtt)) # sys_diff_ttbar[imtt-1].append(-0.03*ttbar_histo.GetBinContent(imtt)) # #2.7% lumi # sys_diff_ttbar[imtt-1].append(0.023*ttbar_histo.GetBinContent(imtt)) # sys_diff_ttbar[imtt-1].append(-0.023*ttbar_histo.GetBinContent(imtt)) # #15% ttbar # #sys_diff_ttbar[imtt-1].append(0.15*ttbar_histo.GetBinContent(imtt)) # #sys_diff_ttbar[imtt-1].append(-0.15*ttbar_histo.GetBinContent(imtt)) # #2.8% QCD # sys_diff_qcd[imtt-1].append(0.028*qcd_histo.GetBinContent(imtt)) # sys_diff_qcd[imtt-1].append(-0.028*qcd_histo.GetBinContent(imtt)) #combining uncertainties sys_tot_ttbar = [] sys_tot_qcd = [] sys_tot = [] sys_global_ttbar = [0.0, 0.0] sys_global_qcd = [0.0, 0.0] nevt_global = [0.0, 0.0, 0.0] for imtt in range(1, ttbar_histo.GetNbinsX() + 1): uperr_qcd = 0 downerr_qcd = 0 uperr_ttbar = 0 downerr_ttbar = 0 for error in sys_diff_ttbar[imtt - 1]: if error < 0: downerr_ttbar = downerr_ttbar + error * error else: uperr_ttbar = uperr_ttbar + error * error for error in sys_diff_qcd[imtt - 1]: if error < 0: downerr_qcd = downerr_qcd + error * error else: uperr_qcd = uperr_qcd + error * error sys_tot_ttbar.append( [math.sqrt(downerr_ttbar), math.sqrt(uperr_ttbar)]) sys_tot_qcd.append([math.sqrt(downerr_qcd), math.sqrt(uperr_qcd)]) sys_tot.append([ math.sqrt(downerr_qcd + downerr_ttbar), math.sqrt(uperr_qcd + uperr_ttbar) ]) sys_global_qcd[0] = sys_global_qcd[0] + downerr_qcd sys_global_qcd[1] = sys_global_qcd[1] + uperr_qcd sys_global_ttbar[0] = sys_global_ttbar[0] + downerr_ttbar sys_global_ttbar[1] = sys_global_ttbar[1] + uperr_ttbar # nevt_global[0]=nevt_global[0]+data_histo.GetBinContent(imtt) nevt_global[1] = nevt_global[1] + qcd_histo.GetBinContent(imtt) nevt_global[2] = nevt_global[2] + ttbar_histo.GetBinContent(imtt) #print 'ttbar+qcd',math.sqrt(uperr_qcd+uperr_ttbar),math.sqrt(downerr_qcd+downerr_ttbar) #print 'qcd',math.sqrt(uperr_qcd),math.sqrt(downerr_qcd) #print 'ttbar',math.sqrt(uperr_ttbar),math.sqrt(downerr_ttbar) err.SetPointEYhigh(imtt - 1, math.sqrt(uperr_qcd + uperr_ttbar)) err.SetPointEYlow(imtt - 1, math.sqrt(downerr_qcd + downerr_ttbar)) sys_global = [0.0, 0.0] sys_global[0] = math.sqrt(sys_global_qcd[0] + sys_global_ttbar[0]) sys_global[1] = math.sqrt(sys_global_qcd[1] + sys_global_ttbar[1]) sys_global_qcd[0] = math.sqrt(sys_global_qcd[0]) sys_global_qcd[1] = math.sqrt(sys_global_qcd[1]) sys_global_ttbar[0] = math.sqrt(sys_global_ttbar[0]) sys_global_ttbar[1] = math.sqrt(sys_global_ttbar[1]) # print name # print "\hline" # print "Multijet QCD & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1],sys_global_qcd[1],sys_global_qcd[0]) # print "SM ttbar & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[2],sys_global_ttbar[1],sys_global_ttbar[0]) # print "\hline" # print "Total background & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1]+nevt_global[2],sys_global[1],sys_global[0]) # print 'DATA & %.0f' %nevt_global[0] err.SetFillStyle(3145) err.SetFillColor(kGray + 1) ###drawing top canvas.cd() stack.Draw('hist') stack.GetXaxis().SetTitle(ttbar_histo.GetXaxis().GetTitle()) stack.GetYaxis().SetTitle(ttbar_histo.GetYaxis().GetTitle()) stack.GetXaxis().SetLabelSize(charsize) stack.GetXaxis().SetTitleSize(charsize) stack.GetYaxis().SetLabelSize(charsize) stack.GetYaxis().SetTitleSize(charsize) stack.GetYaxis().SetTitleOffset(offset) if minx != 0 or maxx != 0: stack.GetXaxis().SetRangeUser(minx, maxx) #else: # stack.GetXaxis().SetRangeUser(0,4000) if miny != 0 or maxy != 0: stack.SetMaximum(maxy) stack.SetMinimum(miny) else: if logy: stack.SetMaximum(stack.GetMaximum() * 10) stack.SetMinimum(0.2) else: stack.SetMaximum(stack.GetMaximum() * 2.0) stack.SetMinimum(0.001) err.Draw('2') sum_mc.Draw('samehist') if ttbar_file != 0: ttbar_line.Draw('samehist') for i in signal_histos: i.Draw('samehist') if logy: canvas.SetLogy() legend.Draw() latex2text = '' if 'ldy_0b' in name: latex2text = '#Deltay < 1; 0 b tag' elif 'ldy_1b' in name: latex2text = '#Deltay < 1; 1 b tag' elif 'ldy_2b' in name: latex2text = '#Deltay < 1; 2 b tag' elif 'hdy_0b' in name: latex2text = '#Deltay > 1; 0 b tag' elif 'hdy_1b' in name: latex2text = '#Deltay > 1; 1 b tag' elif 'hdy_2b' in name: latex2text = '#Deltay > 1; 2 b tag' latex2 = TLatex(0.19, 0.7, latex2text) latex2.SetTextSize(0.03) latex2.SetNDC(1) latex2.SetTextFont(42) latex2.Draw() if docms: if '3000' in name: CMS_lumi.CMS_lumi(canvas, 3, 11) elif '1000' in name: CMS_lumi.CMS_lumi(canvas, 2, 11) elif '300' in name: CMS_lumi.CMS_lumi(canvas, 1, 11) elif '36' in name: CMS_lumi.CMS_lumi(canvas, 0, 11) ###saving canvas.SaveAs('pdf/' + name + '.pdf') if outfile != 0: canvas.Write()
def createCompoundPlots(detector, plot, geometry): """Produce the requested plot for the specified detector. Function that will plot the requested @plot for the specified @detector. The specified detector could either be a real detector or a compound one. The list of available plots are the keys of plots dictionary (imported from plot_utils. """ setTDRStyle() theDirname = 'Images' if not checkFile_(theDirname): os.mkdir(theDirname) goodToGo, theDetectorFilename = paramsGood_(detector, plot, geometry) if not goodToGo: return hist_X0_elements = OrderedDict() # stack stackTitle = "%s;%s;%s" % (detector, plots[plot].abscissa, plots[plot].ordinate) stack_X0 = THStack("stack_X0", stackTitle) theLegend = TLegend(0.50, 0.70, 0.70, 0.90) def setRanges(h): legendSpace = 1. + 0.3 # 30% minY = h.GetYaxis().GetXmin() maxY = h.GetBinContent(h.GetMaximumBin()) * legendSpace h.GetYaxis().SetRangeUser(minY, maxY) for label, [num, color, leg] in six.iteritems(hist_label_to_num): # We don't want the sum to be added as part of the stack if label is 'SUM': continue hist_X0_elements[label] = get1DHisto_(detector, num + plots[plot].plotNumber, geometry) hist_X0_elements[label].SetFillColor(color) hist_X0_elements[label].SetLineColor(kBlack) stack_X0.Add(hist_X0_elements[label]) if hist_X0_elements[label].Integral() > 0.: theLegend.AddEntry(hist_X0_elements[label], leg, "f") # canvas canname = "MBCan_1D_%s_%s" % (detector, plot) can = TCanvas(canname, canname, 800, 800) can.Range(0, 0, 25, 25) gStyle.SetOptTitle(0) # Draw setRanges(stack_X0.GetStack().Last()) stack_X0.Draw("HIST") stack_X0.GetXaxis().SetLabelSize(0.035) stack_X0.GetYaxis().SetLabelSize(0.035) theLegend.Draw() cmsMark = TLatex() cmsMark.SetNDC() cmsMark.SetTextAngle(0) cmsMark.SetTextColor(kBlack) cmsMark.SetTextFont(61) cmsMark.SetTextSize(5e-2) cmsMark.SetTextAlign(11) cmsMark.DrawLatex(0.16, 0.86, "CMS") simuMark = TLatex() simuMark.SetNDC() simuMark.SetTextAngle(0) simuMark.SetTextColor(kBlack) simuMark.SetTextSize(3e-2) simuMark.SetTextAlign(11) simuMark.DrawLatex(0.16, 0.82, "#font[52]{Simulation Internal}") # Store can.Update() can.SaveAs("%s/%s_%s_%s.pdf" % (theDirname, detector, plot, geometry)) can.SaveAs("%s/%s_%s_%s.png" % (theDirname, detector, plot, geometry))
def cal_fraction(year, outputdir, eORb, pt_down, pt_up, fit_type, fdata, ftrue, ffake): sieie_cut = 0 if eORb == "barrel": sieie_cut = 0.01015 if eORb == "endcap": sieie_cut = 0.0272 lumi = 0 if year == "2016": lumi = 35.92 if year == "2017": lumi = 41.50 if year == "2018": lumi = 59.74 histname = "hist_" + eORb + "_" + str(pt_down) + "to" + str(pt_up) hdata = fdata.Get(histname) htrue = ftrue.Get(histname) hfake = ffake.Get(histname) c1 = TCanvas(histname, histname, 1000, 700) htrue.Scale(lumi) if fit_type == 'closureTEST': hdata.Scale(lumi) hfake.Scale(lumi) for i in range(hdata.GetNbinsX() + 2): if hdata.GetBinContent(i) < 0: hdata.SetBinContent(i, 0) if htrue.GetBinContent(i) < 0: htrue.SetBinContent(i, 0) if hfake.GetBinContent(i) < 0: hfake.SetBinContent(i, 0) mc = TObjArray(2) mc.Add(htrue) mc.Add(hfake) fit = TFractionFitter(hdata, mc) fit.Constrain(1, 0.0, 1.0) status = fit.Fit() val0, err0, val1, err1 = ROOT.Double(0), ROOT.Double(0), ROOT.Double( 0), ROOT.Double(0) n_data_total = hdata.Integral() fit.GetResult(0, val0, err0) fit.GetResult(1, val1, err1) # get fake rate nbin = hdata.FindFixBin(sieie_cut) - 1 nbins = hdata.GetNbinsX() fake_err_in_window, fake_err_total, data_err_in_window, data_err_total = ROOT.Double( 0), ROOT.Double(0), ROOT.Double(0), ROOT.Double(0) n_hfake_in_window = hfake.IntegralAndError(1, nbin, fake_err_in_window) n_hfake_total = hfake.IntegralAndError(1, nbins, fake_err_total) sector1 = n_hfake_in_window / n_hfake_total n_hdata_in_window = hdata.IntegralAndError(1, nbin, data_err_in_window) n_hdata_total = hdata.IntegralAndError(1, nbins, data_err_total) sector2 = n_hdata_in_window / n_hdata_total fakerate = val1 * sector1 / sector2 err_sector1 = sqrt( (sector1)**2 * ((fake_err_in_window / n_hfake_in_window)**2 + (fake_err_total / n_hfake_total)**2)) err_sector2 = sqrt( (sector2)**2 * ((data_err_in_window / n_hdata_in_window)**2 + (data_err_total / n_hdata_total)**2)) tmp = val1 * sector1 tmp_err = sqrt( (val1 * sector1)**2 * ((err_sector1 / sector1)**2 + (err1 / val1)**2)) fakerate_err = sqrt( (tmp / sector2)**2 * ((tmp_err / tmp)**2 + (err_sector2 / sector2)**2)) result = fit.GetPlot() hdata.Draw("p e") hdata.GetYaxis().SetTitle("Events/bin") hdata.GetYaxis().SetTitleOffset(1.45) hdata.GetXaxis().SetTitle("#sigma_{i#etai#eta}") hdata.SetStats(0) hdata.SetLineColor(1) hdata.SetMarkerStyle(20) result.Draw("HIST same") result.SetLineColor(8) result.SetLineWidth(2) result.SetStats(0) htrue.SetLineColor(2) htrue.SetLineWidth(2) htrue.SetStats(0) htrue.DrawNormalized("HIST e same", val0 * n_data_total) hfake.SetLineColor(4) hfake.SetLineWidth(2) hfake.SetStats(0) hfake.DrawNormalized("HIST e same", val1 * n_data_total) maximum = 1.3 * hdata.GetMaximum() hdata.SetMaximum(maximum) leg = TLegend(0.53, 0.48, 0.88, 0.88, "brNDC") leg.SetFillStyle(0) leg.SetLineColor(0) leg.SetFillColor(10) leg.SetBorderSize(0) leg.SetHeader( str(pt_down) + "GeV<p_{T}^{#gamma}<" + str(pt_up) + "GeV", "c") leg.AddEntry(hdata, "Data", "LPE") leg.AddEntry(result, "Template prediction", "LPE") leg.AddEntry(htrue, "True template from W#gamma", "LPE") leg.AddEntry(hfake, "Fake template from Data", "LPE") leg.Draw("same") statusStr = "fit status: " + str(int(status)) chi2 = fit.GetChisquare() ndf = fit.GetNDF() chi2ToNDF = chi2 / ndf chiInt = (100 * chi2ToNDF) strChi = "#chi^{2}/ndf = " + str(round( chiInt / 100, 3)) #+ '.' + str(round(chiInt % 100,3)) FRInt = (10000 * fakerate) FRErrInt = (10000 * fakerate_err) strFR = "fake rate = (" + str(round(FRInt / 100, 3)) + '#pm' + str( round(FRErrInt / 100, 3)) + '%)' latex = TLatex() latex.SetNDC() latex.SetTextSize(0.03) latex.SetLineWidth(1) latex.DrawLatex(0.75, 0.90, eORb) latex.DrawLatex(0.55, 0.44, statusStr) latex.DrawLatex(0.55, 0.38, strChi) latex.DrawLatex(0.55, 0.34, strFR) PNG_name = outputdir + '/' + str(year) + '_' + histname + '.png' c1.SaveAs(PNG_name) return fakerate, fakerate_err
h_DYToLL.Integral(bin1, bin2) + h_WToLNu.Integral(bin1, bin2))) x.append(3000) y.append(100 * h_TbjM3W1.Integral(bin1, bin2) / (h_top.Integral(bin1, bin2) + h_st.Integral(bin1, bin2) + h_DYToLL.Integral(bin1, bin2) + h_WToLNu.Integral(bin1, bin2))) gr = TGraph(5, x, y) gr.SetLineColor(8) gr.SetLineWidth(4) gr.SetMarkerColor(1) gr.SetMarkerStyle(2) gr.SetTitle('Signal Efficiency') gr.GetXaxis().SetTitle('Mass (GeV)') gr.GetYaxis().SetTitle('Efficiency %') gr.Draw('ALP') ll = TLatex() ll.SetNDC(kTRUE) ll.SetTextSize(0.05) ll.DrawLatex(0.5, 0.92, "3000 fb^{-1} (14 TeV)") prel = TLatex() prel.SetNDC(kTRUE) prel.SetTextFont(52) prel.SetTextFont(52) prel.SetTextSize(0.05) prel.DrawLatex(0.28, 0.92, "Simulation") cms = TLatex() cms.SetNDC(kTRUE) cms.SetTextFont(61) cms.SetTextFont(61) cms.SetTextSize(0.05)
# Setup basic drawer gROOT.LoadMacro("tdrstyle.C") gROOT.ProcessLine("setTDRStyle();") #gROOT.SetBatch(True) gStyle.SetPadGridX(True) gStyle.SetPadGridY(True) gStyle.SetMarkerStyle(1) gStyle.SetEndErrorSize(0) gROOT.ForceStyle() tline = TLine() tline.SetLineColor(920 + 2) # kGray+2 tline.SetLineStyle(2) tlatexCMS1 = TLatex() tlatexCMS1.SetNDC() tlatexCMS1.SetTextFont(61) tlatexCMS1.SetTextSize(0.75 * 0.05) tlatexCMS2 = TLatex() tlatexCMS2.SetNDC() tlatexCMS2.SetTextFont(52) tlatexCMS2.SetTextSize(0.60 * 0.05) tlatexCMS3 = TLatex() tlatexCMS3.SetNDC() tlatexCMS3.SetTextFont(42) tlatexCMS3.SetTextSize(0.60 * 0.05) tlatexCMS3.SetTextAlign(11) def draw_cms_lumi():
h_nue_parent_muonplus.Draw("same"); h_nue_parent_kaonlong.Draw("same"); #h_nue_parent_totall.Draw("Same"); leg = TLegend(.55, .5, 0.8, .70) leg.SetFillStyle(0); #gStyle.SetLegendTextSize(2/30.); leg.AddEntry(h_nue_parent_muonplus, "#mu^{+}", "l"); leg.AddEntry(h_nue_parent_kaonplus, "K^{+}", "l"); leg.AddEntry(h_nue_parent_kaonlong, "K^{0}_{L}", "l"); #leg.AddEntry(h_nue_parent_totall, "total #nu_{e} flux", "l"); leg.Draw(); t = TLatex(.5, .625, "#nu_{e}"); t.SetTextColor(ROOT.kBlack); t.SetNDC(); t.SetTextSize(2/30.); t.SetTextAlign(32); t.Draw(); #t2 = TLatex(.51, .48, "#splitline{Off-axis NuMI Flux}{at MicroBooNE}"); #t2.SetTextColor(ROOT.kRed+2); #t2.SetNDC(); #t2.SetTextSize(1.4/30.); #t2.SetTextAlign(11); #t2.Draw(); #t3 = TLatex(.51, .40, "Anti-Neutrino Mode"); #t3.SetTextColor(ROOT.kBlack); #t3.SetNDC(); #t3.SetTextSize(1.4/30.);