def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig, lower1sig, upper2sig, lower2sig): channel = np.array( [3. * nchannels - 1.5 - 3. * i for i in range(0, nchannels)]) ey = np.array([0.8 for i in range(0, nchannels)]) zero = np.zeros(nchannels) gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig, upper1sig, ey, ey) gexpect1sig.SetFillColor(kGreen) gexpect1sig.SetLineWidth(2) gexpect1sig.SetLineStyle(2) gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig, upper2sig, ey, ey) gexpect2sig.SetFillColor(kYellow) gexpect2sig.SetLineWidth(2) gexpect2sig.SetLineStyle(2) gexpect2sig.Draw("2") gexpect1sig.Draw("2") gobs = TGraphErrors(nchannels, obs, channel, zero, ey) gobs.SetMarkerStyle(21) gobs.SetMarkerSize(1.5) gobs.SetLineWidth(2) gobs.Draw("pz") # dashed line at median expected limits l = TLine() l.SetLineStyle(2) l.SetLineWidth(2) for bin in range(nchannels): l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin], channel[bin] + ey[bin]) # line to separate individual and combined limits l.SetLineStyle(1) l.SetLineWidth(1) l.DrawLine(xmin, 0, xmax, 0) # legend x1 = gStyle.GetPadLeftMargin() + 0.01 y2 = 1 - gStyle.GetPadTopMargin() - 0.01 leg = TLegend(x1, y2 - 0.17, x1 + 0.25, y2) leg.SetFillColor(4000) leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL") leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL") leg.AddEntry(gobs, "Observed", "pl") leg.Draw() return gobs, gexpect1sig, gexpect2sig, leg
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig, lower1sig, upper2sig, lower2sig): channel = np.array( [nchannels - 1.5 - float(i) for i in range(0, nchannels)]) ey = np.full(nchannels, 0.494) zero = np.zeros(nchannels) gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig, upper1sig, ey, ey) gexpect1sig.SetFillColor(kGreen) gexpect1sig.SetLineWidth(2) gexpect1sig.SetLineStyle(2) gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig, upper2sig, ey, ey) gexpect2sig.SetFillColor(kYellow) gexpect2sig.SetLineWidth(2) gexpect2sig.SetLineStyle(2) gexpect2sig.Draw("2") gexpect1sig.Draw("2") gobs = TGraphErrors(nchannels, obs, channel, zero, ey) gobs.SetMarkerStyle(21) gobs.SetMarkerSize(1.5) gobs.SetLineWidth(2) #gobs.Draw("pz") # dashed line at median expected limits l = TLine() l.SetLineStyle(2) l.SetLineWidth(2) for bin in range(nchannels): l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin], channel[bin] + ey[bin]) # line to separate individual and combined limits l.SetLineStyle(1) l.SetLineWidth(1) l.DrawLine(xmin, 0, xmax, 0) # legend leg = TLegend(0.75, 0.75, 0.95, 0.9) leg.SetFillColor(4000) leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL") leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL") #leg.AddEntry( gobs, "Observed", "pl" ) leg.Draw() return gobs, gexpect1sig, gexpect2sig, leg
def getEff(name, den_input, num_input, rebin=0, xtitle='', ytitle=''): c = TCanvas(name + '_Canvas') legend = TLegend(0.8, 0.1, 0.999, 0.6) legend.SetFillColor(kWhite) den = den_input.Clone() num = num_input.Clone() if rebin != 0: den.Rebin(rebin) num.Rebin(rebin) error_bars = TGraphAsymmErrors() error_bars.Divide(num, den, "cl=0.683 b(1,1) mode") error_bars.SetLineWidth(3) if xtitle == '': error_bars.GetXaxis().SetTitle(num.GetXaxis().GetTitle()) else: error_bars.GetXaxis().SetTitle(xtitle) if ytitle == '': error_bars.GetYaxis().SetTitle(num.GetYaxis().GetTitle()) else: error_bars.GetYaxis().SetTitle(ytitle) error_bars.GetXaxis().SetRangeUser(400, 2000) error_bars.SetLineColor(kBlack) error_bars.SetMaximum(1.01) error_bars.SetMinimum(0.) if ytitle == '': error_bars.GetYaxis().SetTitle("Trigger rate") else: error_bars.GetYaxis().SetTitle(ytitle) error_bars.SetTitle('') error_bars.Draw('AP') c.SaveAs('pdf/' + name + '.pdf') c.Write(name + '_Canvas') error_bars.Write(name)
def bestfit(): xmin = -10 xmax = 6 c, h = draw_canvas_histo( xmin, xmax, "Best fit #mu = #sigma/#sigma_{SM} at m_{H} = 125 GeV") # line at SM expectation of mu = 1 l = TLine() l.SetLineStyle(2) l.DrawLine(1.0, -1.0, 1.0, -1.0 + nchannels) mu = np.array([-0.4, -4.734, -2.014]) upper = np.array([2.12, 3.688, 1.80]) lower = np.array([2.08, 3.754, 1.8224]) channel = np.array([1.5, 0.5, -0.5]) zero = np.zeros(nchannels) gmu = TGraphAsymmErrors(nchannels, mu, channel, lower, upper, zero, zero) gmu.SetMarkerStyle(21) gmu.SetMarkerSize(1.5) gmu.SetLineColor(2) gmu.SetLineWidth(2) gmu.Draw("pz") #draw_disclaimer() c.RedrawAxis() c.Modified() c.Update() c.SaveAs("bestfit.pdf")
def makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20): binning = [20, 30, 40, 50, 60, 70, 80, 100, 150, 200] c = TCanvas() if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) elif option == 'nvtx': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(vbinning) - 1, array('d', vbinning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(vbinning) - 1, array('d', vbinning)) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.BayesDivide(_ahist_, _hist_) g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return copy.deepcopy(g_efficiency)
def ratioplot(): # create required parts leg = getLegend() latex = getLatex() c = TCanvas() c.SetLogy() #Draw input histograms hists = ['h_frac_recoil_', 'h_full_recoil_'] label = ['recoil with MET triggers', 'recoil without MET triggers'] combineHist(hists, label, leg) #leg.Draw() #c.SaveAs("Combinehists_D.pdf") ratio = [] h1 = f.Get('h_frac_recoil_') #h1=setHistStyle(h1,bins) h2 = f.Get('h_full_recoil_') #h2=setHistStyle(h2,bins) h3 = createRatio(h1, h2) gr = TGraphAsymmErrors(h1, h2) gr.GetXaxis().SetRangeUser(0, 1500) gr.GetYaxis().SetRangeUser(0, 1.2) gr.SetMarkerStyle(20) gr.SetMarkerSize(0.5) gr.SetLineColor(1) gr.GetYaxis().SetTitle("Trigger Efficiency") gr.GetXaxis().SetTitle("Recoil [GeV]") gr.SetTitle("") # print ("ratio",ratio ) # c, pad1, pad2 = createCanvasPads() # # # draw everything # pad1.cd() # h1.Draw() # h2.Draw("same") # to avoid clipping the bottom zero, redraw a small axis # h1.GetYaxis().SetLabelSize(0.0) # axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "") # axis.SetLabelFont(43) # axis.SetLabelSize(15) # axis.Draw() # pad2.cd() gr.Draw() latex.DrawLatex(0.41, 0.93, "Trigger Efficincy in MET Run2017E") xmin = 0.0 line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1500, 1) line.SetLineColor(1) line.SetLineWidth(1) line.SetLineStyle(7) line.Draw() #h3.Draw('pl') c.SaveAs("test.pdf")
def makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20, col=1): binning = [20, 200] if args.onebin else [ 20, 30, 40, 50, 60, 70, 80, 100, 150, 200 ] if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.Divide(_ahist_, _hist_, "cl=0.683 b(1,1) mode") g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.SetMarkerColor(col) g_efficiency.SetLineColor(col) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return g_efficiency
def make_eff_pt2(): #efficiency vs. pT^2 ptbin = 0.005 ptmin = 0. ptmax = 0.12 # 0.3 mmin = 2.8 mmax = 3.2 strsel = "jRecM>{0:.3f} && jRecM<{1:.3f}".format(mmin, mmax) can = ut.box_canvas() nbins, ptmax = ut.get_nbins(ptbin, ptmin, ptmax) hPtRec = TH1D("hPtRec", "hPtRec", nbins, ptmin, ptmax) hPtGen = TH1D("hPtGen", "hPtGen", nbins, ptmin, ptmax) #hPtRec = ut.prepare_TH1D("hPtRec", ptbin, ptmin, ptmax) #hPtGen = ut.prepare_TH1D("hPtGen", ptbin, ptmin, ptmax) hPtRec.Sumw2() hPtGen.Sumw2() ut.set_margin_lbtr(gPad, 0.11, 0.09, 0.01, 0.02) #generated trees tree_coh_gen = inp_coh.Get("jGenTree") tree_incoh_gen = inp_incoh.Get("jGenTree") tree_coh.Draw("jGenPt*jGenPt >> hPtRec", strsel) tree_coh_gen.Draw("jGenPt*jGenPt >> hPtGen") #tree_incoh.Draw("jGenPt*jGenPt >>+ hPtRec", strsel) #tree_incoh_gen.Draw("jGenPt*jGenPt >>+ hPtGen") #tree_incoh.Draw("jGenPt*jGenPt >> hPtRec", strsel) #tree_incoh_gen.Draw("jGenPt*jGenPt >> hPtGen") #calculate the efficiency hEff = TGraphAsymmErrors(hPtRec, hPtGen) #hPtRec.Divide(hPtGen) #hPtRec.Draw() #hPtGen.Draw("same") hEff.Draw() ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def plotTriggerEfficiency(self, passesHist, totalHist, label=""): if self._fout and self._canvas: passesHist = passesHist.Rebin(self._rebinFactor, "passesHist") totalHist = totalHist.Rebin(self._rebinFactor, "totalHist") self.makePassesConsistentWithTotal(passesHist, totalHist) metGraph = TGraphAsymmErrors(passesHist, totalHist) metGraph.SetEditable(0) pt = TPaveText(0.409774, 0.843023, 0.809524, 0.890827, "brNDC") pt.SetBorderSize(0) pt.SetFillStyle(0) pt.SetTextFont(42) pt.SetTextSize(0.0387597) pt.AddText(str(self._plotLabel)) cmsLabel = TPaveText(0.134085, 0.937984, 0.418546, 0.984496, "brNDC") cmsLabel.SetBorderSize(0) cmsLabel.SetFillStyle(0) cmsLabel.SetTextFont(62) cmsLabel.SetTextSize(0.0387597) cmsLabel.AddText("CMS Preliminary") lumiLabel = TPaveText(0.575188, 0.937339, 0.874687, 0.992894, "brNDC") lumiLabel.SetBorderSize(0) lumiLabel.SetFillStyle(0) lumiLabel.SetTextFont(42) lumiLabel.SetTextSize(0.0387597) lumiLabel.AddText(str(self._luminosityLabel)) setStyle(metGraph) self._canvas.cd() metGraph.Draw("ap") setAxisStyle(metGraph, "E_{T}^{miss, no #mu} [GeV]", label + " trigger efficiency", (0.0, 500.0), (0.0, 1.4)) pt.Draw("same") cmsLabel.Draw("same") lumiLabel.Draw("same") self._fout.cd() self._canvas.Write("triggerEfficiency_" + label) else: print "A TFile and TCanvas must be added. Not making plots..."
def makeEffPlotsVars(tree, varx, numeratorAddSelection, baseSelection, binning, xtitle='', header='', addon='', marker=20, col=1): _denomHist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, binning) _nominatorHist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, binning) tree.Draw(varx + ' >> ' + _denomHist_.GetName(), baseSelection) tree.Draw(varx + ' >> ' + _nominatorHist_.GetName(), baseSelection + ' && ' + numeratorAddSelection) g_eff = TGraphAsymmErrors() g_eff.Divide(_nominatorHist_, _denomHist_, "cl=0.683 b(1,1) mode") g_eff.GetXaxis().SetTitle(xtitle) g_eff.GetYaxis().SetTitle('efficiency') g_eff.GetYaxis().SetNdivisions(507) g_eff.SetLineWidth(3) g_eff.SetName(header) g_eff.SetMinimum(0.) g_eff.GetYaxis().SetTitleOffset(1.3) g_eff.SetMarkerStyle(marker) g_eff.SetMarkerSize(1) g_eff.SetMarkerColor(col) g_eff.SetLineColor(col) g_eff.Draw('ap') return g_eff
def makeLimitPlot(output, obs, exp, chan, printStats=False, obs2="", ratioLabel=""): #fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE") fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) print massPoint, limits[massPoint][medianNr] expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] xPointsForErrors = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) xPointsForErrors.append(0) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) xPointsErrors = numpy.array(xPointsForErrors) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY, numpy.array(xPointsErrors), numpy.array(xPointsErrors), numpy.array(expected2SigLow), numpy.array(expected2SigHigh)) GraphErr1SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY, numpy.array(xPointsErrors), numpy.array(xPointsErrors), numpy.array(expected1SigLow), numpy.array(expected1SigHigh)) GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kOrange) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen + 1) #cCL=TCanvas("cCL", "cCL",0,0,567,384) cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450) gStyle.SetOptStat(0) gStyle.SetPadRightMargin(0.063) gStyle.SetPadLeftMargin(0.14) gStyle.SetPadBottomMargin(0.12) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) if SPIN2: signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"] elif GUT: signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"] else: signals = ["ssm", "psi"] xSecCurves = [] for signal in signals: xSecCurves.append(getXSecCurve(signal, kFacs[signal])) #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True)) #Draw the graphs: plotPad.SetLogy() DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500) DummyGraph.GetXaxis().SetTitle("M [GeV]") if SPIN2: DummyGraph.GetYaxis().SetTitle( "[#sigma#upoint#font[12]{B}] G_{KK} / [#sigma#upoint#font[12]{B}] Z" ) else: DummyGraph.GetYaxis().SetTitle( "[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z") # if SPIN2: # if chan=="mumu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)") # elif chan=="elel": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)") # elif chan=="elmu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)") # else: # if chan=="mumu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)") # elif chan=="elel": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)") # elif chan=="elmu": # DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)") gStyle.SetOptStat(0) DummyGraph.GetXaxis().SetRangeUser(200, 5500) DummyGraph.SetMinimum(1e-8) DummyGraph.SetMaximum(1e-4) DummyGraph.GetXaxis().SetLabelSize(0.055) DummyGraph.GetXaxis().SetTitleSize(0.055) DummyGraph.GetXaxis().SetTitleOffset(1.05) DummyGraph.GetYaxis().SetLabelSize(0.055) DummyGraph.GetYaxis().SetTitleSize(0.055) DummyGraph.GetYaxis().SetTitleOffset(1.3) DummyGraph.Draw() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") if not EXPONLY: GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") for curve in xSecCurves: curve.Draw("lsame") plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetFillStyle(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.16, .76, .27, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetFillStyle(0) plPrelim.SetBorderSize(0) if "2017" in output or "Combination" in output: plPrelim.Draw() cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC") Default leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC") if SPIN2: leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.0425) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") print ratioLabels leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l") leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l") else: if not EXPONLY: leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l") leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f") leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f") leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC") leg1.SetTextSize(0.05) if GUT: leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC") if SPIN2: leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC") leg1.SetTextSize(0.045) for index, signal in enumerate(signals): xSecCurves[index].SetName(labels[signal]) xSecCurves[index].Write(labels[signal]) leg1.AddEntry(xSecCurves[index], labels[signal], "l") leg1.SetBorderSize(0) leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetFillStyle(0) leg.SetLineColor(0) leg.Draw("hist") leg1.SetLineWidth(0) leg1.SetLineStyle(0) leg1.SetFillStyle(0) leg1.SetLineColor(0) leg1.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .885, .9, .99, "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .885, .9, .99, "35.9 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .27, .885, .9, .99, "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") elif "2017" in output or "Combination" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .885, .9, .99, "42.4 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .885, .9, .99, "41.4 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .27, .885, .9, .99, "77.3 fb^{-1} (13 TeV, ee) + 78.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC") else: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") plLumi.SetTextSize(0.5) plLumi.SetTextFont(42) plLumi.SetFillColor(0) plLumi.SetBorderSize(0) plLumi.Draw() plotPad.SetTicks(1, 1) plotPad.RedrawAxis() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(200, 1, 5500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") #GraphErr2SigForHEPData.SetName("graph2Sig") #GraphErr2SigForHEPData.Write("graph2Sig") #GraphErr1SigForHEPData.SetName("graph1Sig") #GraphErr1SigForHEPData.Write("graph1Sig") #GraphExp.SetName("graphExp") #GraphExp.Write("graphExp") #GraphObs.SetName("graphObs") #GraphObs.Write("graphObs") #fileForHEPData.Write() #fileForHEPData.Close() cCL.Update() printPlots(cCL, output)
def draw(hist, channel, data, back, sign, snorm=1, lumi=-1, ratio=0, log=False): # If not present, create BkgSum if not 'BkgSum' in hist.keys(): hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) hist['BkgSum'].SetMarkerStyle(0) # Set Poisson error bars #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work alpha = 1 - 0.6827 hist['data_obs'].SetBinErrorOption(TH1.kPoisson) data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX()) data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle()) data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize()) res_graph = data_graph.Clone() for i in range(hist['data_obs'].GetNbinsX()): N = hist['data_obs'].GetBinContent(i + 1) B = hist['BkgSum'].GetBinContent(i + 1) L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.) U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1) data_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N if not N == 0 else -1.e99) data_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N) res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N / B if not B == 0 and not N == 0 else -1.e99) res_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., (N - L) / B if not B == 0 else -1.e99, (U - N) / B if not B == 0 else -1.e99) # Create stack bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']]) leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'].replace("m_{#Chi}=1 GeV", ""), "fl") # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if ratio else 600) if ratio: c1.Divide(1, 2) setTopPad(c1.GetPad(1), ratio) setBotPad(c1.GetPad(2), ratio) c1.cd(1) c1.GetPad(bool(ratio)).SetTopMargin(0.06) c1.GetPad(bool(ratio)).SetRightMargin(0.05) c1.GetPad(bool(ratio)).SetTicks(1, 1) if log: c1.GetPad(bool(ratio)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg #if len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data data_graph.Draw("SAME, PE") for i, s in enumerate(sign): if sample[s]['plot']: hist[s].DrawNormalized("SAME, HIST", hist[s].Integral() * snorm) # signals bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075) bkg.SetMaximum((2. if log else 1.2) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) #if log: bkg.SetMinimum(1) leg.Draw() drawCMS(lumi, "Preliminary") drawRegion(channel) drawAnalysis(channel) #if nm1 and not cutValue is None: drawCut(cutValue, bkg.GetMinimum(), bkg.GetMaximum()) #FIXME if len(sign) > 0: if channel.startswith('X') and len(sign) > 0: drawNorm(0.9 - 0.04 * (n + 1), "#sigma(X) #times B(X #rightarrow Vh) = %.1f pb" % snorm) #elif "SR" in channel: drawNorm(0.9-0.04*(n+1), "DM+bb/tt, scaled by %.0f" % snorm, "m_{#chi}=1 GeV, scalar mediator") elif "SR" in channel: drawNorm(0.9 - 0.04 * (n + 1), "DM+bb/tt, m_{#chi}=1 GeV", "scalar mediator") setHistStyle(bkg, 1.2 if ratio else 1.1) setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1) if ratio: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if len(data) > 0: #res.Draw("SAME, PE0") res_graph.Draw("SAME, PE0") # if len(err.GetXaxis().GetBinLabel(1))==0: # Bin labels: not a ordinary plot # drawRatio(hist['data_obs'], hist['BkgSum']) # drawKolmogorov(hist['data_obs'], hist['BkgSum']) c1.Update() # return list of objects created by the draw() function return [c1, bkg, leg, err, errLine, res, data_graph, res_graph]
file = TFile(output + ".root") runPileup = None ipoint = 0 for key in file.GetListOfKeys(): kname = key.GetName() if (kname.find('pileup_') < 0): continue runnb = int(kname.split('_')[1]) h = file.Get(kname) avgpileup = h.GetMean() rmspileup = h.GetRMS() evol.SetPoint(ipoint, runnb, avgpileup) evol.SetPointError(ipoint, 0, 0, rmspileup, rmspileup) ipoint = ipoint + 1 if (runPileup is None): runPileup = h.Clone('runPileup') formatPlot(runPileup, 1, 1, 1, 20, 0, True, True, 1, 1, 1) file.Close() setStyle() c = getNewCanvas("evolc", "evolc", False) c.SetWindowSize(1200, 600) c.Divide(2, 1) c.cd(1) evol.Draw('ap') c.cd(2) runPileup.DrawNormalized('hist') c.SaveAs(output + "_summary.C") c.SaveAs(output + "_summary.root") print "Average pileup: " + str(runPileup.GetMean()) + ' +/- ' + str( runPileup.GetMeanError())
gxs.SetLineStyle(5) gxs.SetLineWidth(3) gxs.SetLineColor(ROOT.kRed) canvasName = 'Limits' if useSub: canvasName = 'Limits_Sub' can = TCanvas(canvasName,canvasName,900,600) gPad.SetLogy() g2.GetXaxis().SetTitle(' qg resonance Mass (TeV)') g2.GetYaxis().SetTitle('#sigma #times A #times BR (q*#rightarrow jj) (pb)') #g2.GetYaxis().SetTitle('#sigma #times BR (q*#rightarrow jj) (pb)') g2.GetYaxis().CenterTitle(ROOT.kTRUE) g2.GetYaxis().SetNdivisions(510) g2.GetYaxis().SetRangeUser(1e-3,10) g2.Draw('AE3') g1.Draw('sameE3') gExp.Draw('sameL') gObs.Draw('sameLP') gxs.Draw('sameL') if superimpose: gExpDinko.Draw('sameL') leg = TLegend(0.65,0.65,0.9,0.9) if useSub: leg.SetHeader('Substructure Selection') else: leg.SetHeader('Simple Dijet Selection') leg.AddEntry(gObs,'Observed','LP') leg.AddEntry(gExp,'Expected','L') leg.AddEntry(g1,'Expected #pm 1 #sigma','F')
exp68Hv) expected68.SetFillColor(ROOT.kGreen) expected95 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp95Lv, exp95Hv) expected95.SetFillColor(ROOT.kYellow) c4 = TCanvas("c4", "Diphoton c = 01 Limits", 1000, 800) c4.SetBottomMargin(0.15) c4.SetRightMargin(0.06) #c4.SetLogy(1) #expected95.SetMinimum(0.0001); expected95.SetMaximum(0.0057) expected95.Draw("a3") expected95.GetXaxis().SetTitle("Diphoton Mass [GeV/c^{2}]") expected95.GetYaxis().SetTitle("#sigma(G_{RS} #rightarrow #gamma #gamma)[pb]") expected68.Draw("3same") expected_p.Draw("csame") observed_p.Draw("cpsame") theory.Draw("same") latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextAlign(31) # align right latex.DrawLatex(0.45, 0.95, "CMS Preliminary") latex2 = TLatex() latex2.SetNDC()
def ratioplot(): # create required parts leg = getLegend() latex = getLatex() c = SetCanvas() #c.SetLogy() #c = TCanvas() #c.SetLogy() h1 = f.Get('h_num_calo_') #'calo',pf h1 = setHistStyle(h1, bins) h2 = f.Get('h_den_calo_') h2 = setHistStyle(h2, bins) h11 = f2.Get('h_num_calo_') h11 = setHistStyle(h11, bins) h21 = f2.Get('h_den_calo_') h21 = setHistStyle(h21, bins) gr = TGraphAsymmErrors(30) #gr.Divide(h1,h2) gr = TGraphAsymmErrors(h1, h2) gr2 = TGraphAsymmErrors(h11, h21) gr2.SetMarkerStyle(20) gr2.GetXaxis().SetRangeUser(0, 1000) gr2.SetMarkerSize(1.5) gr2.SetLineColor(2) gr2.SetLineWidth(1) gr2.SetMarkerColor(2) gr.GetXaxis().SetRangeUser(0, 1000) # gr.GetYaxis().SetRangeUser(0.0001,1.2) gr.SetMarkerStyle(20) gr.SetMarkerSize(1.5) gr.SetLineColor(1) gr.SetLineWidth(1) gr.SetMarkerColor(1) gr.GetYaxis().SetTitle("Trigger Efficiency") gr.GetXaxis().SetTitle("MET [GeV]") gr.SetTitle("") #base histogram histogram_base = TH1F("histogram_base", "", 1000, 0, 1000.) histogram_base.SetTitle("") histogram_base.SetStats(0) histogram_base.SetMarkerSize(2) #histogram_base.SetMinimum(0.0) histogram_base.SetMaximum(1.2) histogram_base.GetXaxis().SetTitle("Online E_{T}^{miss} (GeV)") histogram_base.GetYaxis().SetTitle("Efficiency") histogram_base = setHistStyle(histogram_base, bins) histogram_base.Draw("HIST") # c.SaveAs() gr.Draw('P same') gr2.Draw('P same') latex.DrawLatex(0.49, 0.93, " EGamma Run2018C, 13 TeV") xmin = 0.0 line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1000, 1) line.SetLineColor(1) line.SetLineWidth(1) line.SetLineStyle(7) line.Draw() leg.AddEntry(gr, 'With HBHENoise filter', 'P') leg.AddEntry(gr2, 'Without HBHENoise filter', 'P') leg.Draw() txt = 'Path: HLT_PFMETTypeOne200_HBHE_BeamHaloCleaned' texcms = AddText(txt) texcms.Draw("same") c.SaveAs('testTurnOn_EGamma.png')
def pullsVertical(fileName): content = filterPullFile(fileName) nbins, off = len(content), 0.10 b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off) s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off) # for i, s in enumerate(content): l = s.split() b_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) s_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) b_pulls.SetBinContent(i + 1, float(l[1])) b_pulls.SetBinError(i + 1, float(l[2])) s_pulls.SetBinContent(i + 1, float(l[3])) s_pulls.SetBinError(i + 1, float(l[4])) b_pulls.SetFillStyle(3005) b_pulls.SetFillColor(923) b_pulls.SetLineColor(923) b_pulls.SetLineWidth(1) b_pulls.SetMarkerStyle(20) b_pulls.SetMarkerSize(1.25) s_pulls.SetLineColor(602) s_pulls.SetMarkerColor(602) s_pulls.SetMarkerStyle(24) #24 s_pulls.SetLineWidth(1) b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5) # Graphs h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins) B_pulls = TGraphAsymmErrors(nbins) S_pulls = TGraphAsymmErrors(nbins) boxes = [] canvas = TCanvas("canvas", "Pulls", 600, 150 + nbins * 10) #nbins*20) canvas.cd() canvas.SetGrid(0, 1) canvas.GetPad(0).SetTopMargin(0.01) canvas.GetPad(0).SetRightMargin(0.01) canvas.GetPad(0).SetBottomMargin(0.05) canvas.GetPad(0).SetLeftMargin(0.25) #(0.25)#(0.065) canvas.GetPad(0).SetTicks(1, 1) for i, s in enumerate(content): l = s.split() if "1034h" in l[0]: l[0] = "CMS_PDF_13TeV" h_pulls.GetYaxis().SetBinLabel(i + 1, l[0].replace('CMS2016_', '')) #C #y1 = gStyle.GetPadBottomMargin() #y2 = 1. - gStyle.GetPadTopMargin() #h = (y2 - y1) / float(nbins) #y1 = y1 + float(i) * h #y2 = y1 + h #box = TPaveText(0, y1, 1, y2, 'NDC') #box.SetFillColor(0) #box.SetTextSize(0.02) #box.SetBorderSize(0) #box.SetTextAlign(12) #box.SetMargin(0.005) #if i % 2 == 0: # box.SetFillColor(18) #box.Draw() #boxes.append(box) B_pulls.SetPoint(i + 1, float(l[1]), float(i + 1) - 0.3) #C B_pulls.SetPointError(i + 1, float(l[2]), float(l[2]), 0., 0.) #C for i, s in enumerate(content): l = s.split() S_pulls.SetPoint(i + 1, float(l[3]), float(i + 1) - 0.7) #C S_pulls.SetPointError(i + 1, float(l[4]), float(l[4]), 0., 0.) #C h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta") h_pulls.GetXaxis().SetLabelOffset(-0.01) h_pulls.GetXaxis().SetTitleOffset(.6) h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0) B_pulls.SetFillColor(1) B_pulls.SetLineColor(1) B_pulls.SetLineStyle(1) B_pulls.SetLineWidth(2) B_pulls.SetMarkerColor(1) B_pulls.SetMarkerStyle(20) B_pulls.SetMarkerSize(1) #(0.75) S_pulls.SetFillColor(629) S_pulls.SetLineColor(629) S_pulls.SetMarkerColor(629) S_pulls.SetLineWidth(2) S_pulls.SetMarkerStyle(20) S_pulls.SetMarkerSize(1) box1 = TBox(-1., 0., 1., nbins) box1.SetFillStyle(3001) #box1.SetFillStyle(0) box1.SetFillColor(417) box1.SetLineWidth(2) box1.SetLineStyle(2) box1.SetLineColor(417) box2 = TBox(-2., 0., 2., nbins) box2.SetFillStyle(3001) #box2.SetFillStyle(0) box2.SetFillColor(800) box2.SetLineWidth(2) box2.SetLineStyle(2) box2.SetLineColor(800) leg = TLegend(0.1, -0.05, 0.7, 0.08) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetNColumns(2) leg.AddEntry(B_pulls, "B-only fit", "lp") leg.AddEntry(S_pulls, "S+B fit", "lp") if text: leg.AddEntry(0, text, "") h_pulls.Draw("") box2.Draw() box1.Draw() B_pulls.Draw("P6SAME") S_pulls.Draw("P6SAME") leg.Draw() # drawCMS(35867, "Preliminary") # drawAnalysis("VH") # drawRegion(outName) canvas.Print(outName + ".png") canvas.Print(outName + ".pdf") if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
selden2 = 'cmgMuonSelVec.size()>1 && cmgMuonSel[1].getSelection(\"cuts_vbtfmuon\")' LPcanvas.cd(1) cmg.Draw('cmgMuonSel[0].pt()>>den1', selden1) LPcanvas.cd(2) cmg.Draw('cmgMuonSel[1].pt()>>den2', selden2) LPcanvas.cd(3) cmg.Draw('cmgMuonSel[0].pt()>>num1', selnum1) LPcanvas.cd(4) cmg.Draw('cmgMuonSel[1].pt()>>num2', selnum2) eff1 = TGraphAsymmErrors(num1, den1) eff2 = TGraphAsymmErrors(num2, den2) LPcanvas.cd(5) eff1.Draw('AP') sRedPoints.formatHisto(eff2) eff2.Draw('P') #LPnocut = TH1F('LPnocut', 'LPnocut', 20, -0.5, 1.5) LPplus = TH1F('LPplus', 'LPplus', 20, -0.5, 1.5) LPplus.Sumw2() LPminus = TH1F('LPminus', 'LPminus', 20, -0.5, 1.5) LPminus.Sumw2() sBlack.formatHisto(LPplus) sRedPoints.formatHisto(LPminus) LPcanvas.cd(6) #cmg.Draw('LPWMuNu[0].lp()>>LPnocut', 'LPWMuNuVec.size()>0') selection = 'LPWMuNuVec.size()>0 && LPWMuNu.getSelection(\"cuts_ptLoose\") && LPPFJetSelVec.size()>1 && LPMHTPFJet30LooseSelVec.size()>0' cmg.Draw(
def doit(): frame = h.ProfileX(hname + "_frame", 1, -1, "s") gr1 = TGraphAsymmErrors(h.GetNbinsX()) gr2 = TGraphAsymmErrors(h.GetNbinsX()) gr1_aspt = TGraphAsymmErrors(h.GetNbinsX()) gr2_aspt = TGraphAsymmErrors(h.GetNbinsX()) # Apply gaussian fits for i in xrange(h.GetNbinsX()): h_py = h.ProjectionY("_py", i + 1, i + 1) if 50 <= i <= 60: # high pT, not enough entries (300 bins -> 150) h_py.Rebin(2) elif i >= 78: # low pT, resolution affected by finite bin width h_py = h.ProjectionY("_py", i + 1, i + 2) # merge i & (i+1) entries if i == 82: # even lower pT, resolution affected by finite bin width h_py = h.ProjectionY("_py", i + 1, i + 4) # merge i & (i+4) entries elif i >= 82: continue if h_py.Integral() < 20: continue r = h_py.Fit("gaus", "SNQ", "", -1, 1.2) #r = h_py.Fit("gaus", "SNQ", "", h_py.GetMean() - 0.04*5, h_py.GetMean() + 0.04*5) mean, sigma, meanErr, sigmaErr = r.Parameter(1), r.Parameter( 2), r.ParError(1), r.ParError(2) gr1.SetPoint(i, h.GetXaxis().GetBinCenter(i + 1), mean) gr1.SetPointError(i, 0, 0, sigma, sigma) gr2.SetPoint(i, h.GetXaxis().GetBinCenter(i + 1), sigma) gr2.SetPointError(i, 0, 0, sigmaErr, sigmaErr) gr1_aspt.SetPoint(i, 1.0 / h.GetXaxis().GetBinCenter(i + 1), mean) gr1_aspt.SetPointError(i, 0, 0, sigma, sigma) gr2_aspt.SetPoint(i, 1.0 / h.GetXaxis().GetBinCenter(i + 1), sigma) gr2_aspt.SetPointError(i, 0, 0, sigmaErr, sigmaErr) # Draw h.Draw("COLZ") gPad.SetLogx(0) #draw_cms_lumi() #gPad.Print("figures_perf/" + hname + "_omtf" + ".png") #gPad.Print("figures_perf/" + hname + "_omtf" + ".pdf") # frame.Reset() frame.SetBins(50, 0, 50) frame.GetXaxis().SetTitle("gen p_{T} [GeV]") frame.GetYaxis().SetTitle("#Delta(p_{T})/p_{T} bias") frame.SetMaximum(0.5) frame.SetMinimum(-0.5) frame.SetStats(0) frame.Draw() gr1_aspt.SetLineColor(col) gr1_aspt.SetMarkerColor(col) gr1_aspt.Draw("p") gPad.SetLogx() draw_cms_lumi() gPad.Print("figures_perf/" + hname + "_bias" + "_omtf" + ".png") gPad.Print("figures_perf/" + hname + "_bias" + "_omtf" + ".pdf") # frame.GetXaxis().SetTitle("gen p_{T} [GeV]") frame.GetYaxis().SetTitle("#Delta(p_{T})/p_{T} resolution") frame.SetMaximum(0.6) frame.SetMinimum(0.0) frame.SetStats(0) frame.Draw() gr2_aspt.SetLineColor(col) gr2_aspt.SetMarkerColor(col) gr2_aspt.Draw("p") #gr2_aspt.Fit("pol1", "", "", 10, 40) gPad.SetLogx() draw_cms_lumi() gPad.Print("figures_perf/" + hname + "_res" + "_omtf" + ".png") gPad.Print("figures_perf/" + hname + "_res" + "_omtf" + ".pdf") # h.cache = [frame, gr1, gr2, gr1_aspt, gr2_aspt]
def makePlot(finname,foutname,plottitle='',masstitle='',scale=False): xsecs = resonantXsecs if 'resonant' in finname else fcncXsecs points = {} if BLIND: cls = [2.5, 16, 50, 84, 97.5] else: cls = [2.5, 16, 50, 84, 97.5,'Observed'] xaxis = [] for cl in cls: points[cl] = [] xsec=1 for l in open(finname): try: if l.strip()[0]=='#': continue if 'MASS' in l: if scale: xsec = xsecs[int(l.split()[1])] if VERBOSE: print '' stdout.write('$%6s$ & $%7.3g$'%(l.split()[1],xsec/(0.667))) xaxis.append(float(l.split()[1])) else: cl,val = parseLine(l) points[cl].append(val/xsec) if VERBOSE and (cl==50 or cl=='Observed'): stdout.write(' & $%10.4g$'%(val/xsec)) except: pass if VERBOSE: print '' N = len(xaxis) up1Sigma=[]; up2Sigma=[] down1Sigma=[]; down2Sigma=[] for iM in xrange(N): up1Sigma.append(points[84][iM]-points[50][iM]) up2Sigma.append(points[97.5][iM]-points[50][iM]) down1Sigma.append(-points[16][iM]+points[50][iM]) down2Sigma.append(-points[2.5][iM]+points[50][iM]) up1Sigma = array('f',up1Sigma) up2Sigma = array('f',up2Sigma) down1Sigma = array('f',down1Sigma) down2Sigma = array('f',down2Sigma) cent = array('f',points[50]) if not BLIND: obs = array('f',points['Observed']) xarray = array('f',xaxis) xsecarray = array('f',[xsecs[xx] for xx in xaxis]) xsecarrayLow = array('f',[0.0625*xsecs[xx] for xx in xaxis]) onearray = array('f',[1 for xx in xaxis]) graphXsec = TGraph(N,xarray,xsecarray) graphXsecLow = TGraph(N,xarray,xsecarrayLow) graphOne = TGraph(N,xarray,onearray) zeros = array('f',[0 for i in xrange(N)]) graphCent = TGraph(N,xarray,cent) if not BLIND: 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]') if scale: graph2Sigma.GetYaxis().SetTitle('Upper limit [#sigma/#sigma_{theory}]') else: graph2Sigma.GetYaxis().SetTitle("Upper limit [#sigma] [pb]") graph2Sigma.SetLineColor(5) graph1Sigma.SetLineColor(3) graph2Sigma.SetFillColor(5) graph1Sigma.SetFillColor(3) graph2Sigma.SetMinimum(0.5*min(points[2.5])) if scale: graph2Sigma.SetMaximum(10*max(max(points[97.5]),max(xsecarray),4)) else: graph2Sigma.SetMaximum(10*max(max(points[97.5]),max(xsecarray))) graphCent.SetLineWidth(2) graphCent.SetLineStyle(2) if not BLIND: graphObs.SetLineColor(1) graphObs.SetLineWidth(3) 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','L') leg.AddEntry(graph1Sigma,'1 #sigma','F') leg.AddEntry(graph2Sigma,'2 #sigma','F') leg.SetFillStyle(0) leg.SetBorderSize(0) graph2Sigma.Draw('A3') graph1Sigma.Draw('3 same') graphCent.Draw('same L') if not BLIND: graphObs.Draw('same L') if scale: graphOne.SetLineColor(2) graphOne.SetLineWidth(2) graphOne.SetLineStyle(2) graphOne.Draw('same L') else: graphXsec.SetLineColor(2) graphXsecLow.SetLineColor(4) subscript = 'SR' if 'Resonant' in plottitle else 'FC' if 'Resonant' in plottitle: leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=0.1}{m_{#chi}=100 GeV}'%(subscript,subscript),'l') else: leg.AddEntry(graphXsec,'Theory a_{%s}=b_{%s}=0.1'%(subscript,subscript),'l') # leg.AddEntry(graphXsecLow,'Theory a_{%s}=b_{%s}=0.025'%(subscript,subscript),'l') for g in [graphXsec]: g.SetLineWidth(2) g.SetLineStyle(2) g.Draw('same L') leg.Draw() label = TLatex() label.SetNDC() label.SetTextFont(62) label.SetTextAlign(11) label.DrawLatex(0.19,0.85,"CMS") label.SetTextFont(52) label.DrawLatex(0.28,0.85,"Preliminary") label.SetTextFont(42) label.SetTextSize(0.6*c.GetTopMargin()) label.DrawLatex(0.19,0.77,plottitle) if scale: if 'Resonant' in plottitle: label.DrawLatex(0.19,0.7,"a_{SR} = b_{SR} = 0.1") label.DrawLatex(0.19,0.64,"m_{#chi}=100 GeV") else: label.DrawLatex(0.19,0.7,"a_{FC} = b_{FC} = 0.1") label.SetTextSize(0.5*c.GetTopMargin()) label.SetTextFont(42) label.SetTextAlign(31) # align right label.DrawLatex(0.9, 0.94,"%.1f fb^{-1} (13 TeV)"%(plotConfig.lumi)) c.SaveAs(foutname+'.pdf') c.SaveAs(foutname+'.png')
def limit(): method = '' channel = "bb" particleP = "Z'" particle = channel multF = ZPTOBB THEORY = ['A1', 'B3'] suffix = "_" + BTAGGING if ISMC: suffix += "_MC" if SY: suffix += "_comb" #if method=="cls": suffix="_CLs" if SY: filename = "./combine/limits/MANtag_study/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt" else: filename = "./combine/limits/MANtag_study/" + BTAGGING + "/" + YEAR + "_M%d.txt" if CATEGORY != "": filename = filename.replace( BTAGGING + "/", BTAGGING + "/single_category/" + CATEGORY + "_") suffix += "_" + CATEGORY if ISMC: filename = filename.replace(".txt", "_MC.txt") mass, val = fillValues(filename) #print "mass =",mass #print "val =", val Obs0s = TGraph() Exp0s = TGraph() Exp1s = TGraphAsymmErrors() Exp2s = TGraphAsymmErrors() Sign = TGraph() pVal = TGraph() Best = TGraphAsymmErrors() Theory = {} for i, m in enumerate(mass): if not m in val: print "Key Error:", m, "not in value map" continue n = Exp0s.GetN() Obs0s.SetPoint(n, m, val[m][0] * multF) Exp0s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF, val[m][4] * multF - val[m][3] * multF) Exp2s.SetPoint(n, m, val[m][3] * multF) Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF, val[m][5] * multF - val[m][3] * multF) if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6]) if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7]) if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8]) if len(val[m]) > 10: Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10]) for t in THEORY: Theory[t] = TGraphAsymmErrors() addXZH = True for m in sorted(HVT[t]['W']['XS'].keys()): if m < mass[0] or m > mass[-1]: continue if m > 4500: continue ## for now because I don't have the higher mass xs FIXME XsZ, XsZ_Up, XsZ_Down = 0., 0., 0. if addXZH: XsZ = 1000. * HVT[t]['Z']['XS'][ m] * 0.12 #temporary BR value set to 0.12 FIXME XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1., HVT[t]['Z']['PDF'][m][0] - 1.)) XsZ_Down = XsZ * (1. - math.hypot(1. - HVT[t]['Z']['QCD'][m][0], 1. - HVT[t]['Z']['PDF'][m][0])) n = Theory[t].GetN() Theory[t].SetPoint(n, m, XsZ) Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down), (XsZ_Up - XsZ)) Theory[t].SetLineColor(theoryLineColor[t]) Theory[t].SetFillColor(theoryFillColor[t]) Theory[t].SetFillStyle(theoryFillStyle[t]) Theory[t].SetLineWidth(2) #Theory[t].SetLineStyle(7) Exp2s.SetLineWidth(2) Exp2s.SetLineStyle(1) Obs0s.SetLineWidth(3) Obs0s.SetMarkerStyle(0) Obs0s.SetLineColor(1) Exp0s.SetLineStyle(2) Exp0s.SetLineWidth(3) Exp1s.SetFillColor(417) #kGreen+1 Exp1s.SetLineColor(417) #kGreen+1 Exp2s.SetFillColor(800) #kOrange Exp2s.SetLineColor(800) #kOrange Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25) Exp2s.GetXaxis().SetNoExponent(True) Exp2s.GetXaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetTitle("#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP + " #rightarrow " + particle + ") (fb)") Exp2s.GetYaxis().SetTitleOffset(1.5) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetMoreLogLabels() Sign.SetLineWidth(2) Sign.SetLineColor(629) Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1) Sign.GetYaxis().SetTitle("Significance") pVal.SetLineWidth(2) pVal.SetLineColor(629) pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1) pVal.GetYaxis().SetTitle("local p-Value") Best.SetLineWidth(2) Best.SetLineColor(629) Best.SetFillColor(629) Best.SetFillStyle(3003) Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1) Best.GetYaxis().SetTitle("Best Fit (pb)") c1 = TCanvas("c1", "Exclusion Limits", 800, 600) c1.cd() #SetPad(c1.GetPad(0)) c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetLeftMargin(0.12) c1.GetPad(0).SetTicks(1, 1) #c1.GetPad(0).SetGridx() #c1.GetPad(0).SetGridy() c1.GetPad(0).SetLogy() Exp2s.Draw("A3") Exp1s.Draw("SAME, 3") for t in THEORY: Theory[t].Draw("SAME, L3") Theory[t].Draw("SAME, L3X0Y0") Exp0s.Draw("SAME, L") if not options.blind: Obs0s.Draw("SAME, L") #setHistStyle(Exp2s) Exp2s.GetXaxis().SetTitleSize(0.050) Exp2s.GetYaxis().SetTitleSize(0.050) Exp2s.GetXaxis().SetLabelSize(0.045) Exp2s.GetYaxis().SetLabelSize(0.045) Exp2s.GetXaxis().SetTitleOffset(0.90) Exp2s.GetYaxis().SetTitleOffset(1.25) Exp2s.GetYaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3) #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2) #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6)) Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1]) #drawAnalysis(channel) drawAnalysis("") #drawRegion(channel, True) drawRegion("", True) #drawCMS(LUMI, "Simulation Preliminary") #Preliminary drawCMS(LUMI, "Work in Progress", suppressCMS=True) # legend top = 0.9 nitems = 4 + len(THEORY) leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top) #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("95% CL upper limits") leg.AddEntry(Obs0s, "Observed", "l") leg.AddEntry(Exp0s, "Expected", "l") leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f") leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f") for t in THEORY: leg.AddEntry(Theory[t], theoryLabel[t], "fl") leg.Draw() latex = TLatex() latex.SetNDC() latex.SetTextSize(0.045) latex.SetTextFont(42) #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h") leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225) leg2.SetBorderSize(0) leg2.SetFillStyle(0) #1001 leg2.SetFillColor(0) c1.GetPad(0).RedrawAxis() leg2.Draw() if not options.blind: Obs0s.Draw("SAME, L") c1.GetPad(0).Update() if not gROOT.IsBatch(): raw_input("Press Enter to continue...") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".png") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".pdf") if 'ah' in channel or 'sl' in channel: c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".C") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".root") for t in THEORY: print "Model", t, ":", for m in range(mass[0], mass[-1], 1): if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == ( Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)): print m, print "" return
def limit2HDM(): global signals signals = range(800, 2000 + 1, 50) multF = HTOBB THEORY = ['T1', 'T2'] mass, val = fillValues("./combine/AZh/AZh_M%d.txt") Obs0s = TGraph() Exp0s = TGraph() Exp1s = TGraphAsymmErrors() Exp2s = TGraphAsymmErrors() massB, valB = fillValues("./combine/BBAZh/BBAZh_M%d.txt") Obs0sB = TGraph() Exp0sB = TGraph() Exp1sB = TGraphAsymmErrors() Exp2sB = TGraphAsymmErrors() for i, m in enumerate(mass): if not m in val: print "Key Error:", m, "not in value map" continue n = Exp0s.GetN() Obs0s.SetPoint(n, m, val[m][0] * multF) Exp0s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF, val[m][4] * multF - val[m][3] * multF) Exp2s.SetPoint(n, m, val[m][3] * multF) Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF, val[m][5] * multF - val[m][3] * multF) Obs0sB.SetPoint(n, m, valB[m][0] * multF) Exp0sB.SetPoint(n, m, valB[m][3] * multF) Exp1sB.SetPoint(n, m, valB[m][3] * multF) Exp1sB.SetPointError(n, 0., 0., valB[m][3] * multF - valB[m][2] * multF, valB[m][4] * multF - valB[m][3] * multF) Exp2sB.SetPoint(n, m, valB[m][3] * multF) Exp2sB.SetPointError(n, 0., 0., valB[m][3] * multF - valB[m][1] * multF, valB[m][5] * multF - valB[m][3] * multF) col = 629 Exp2s.SetLineWidth(2) Exp2s.SetLineStyle(1) Obs0s.SetLineWidth(3) Obs0s.SetMarkerStyle(0) Obs0s.SetLineColor(1) Exp0s.SetLineStyle(2) Exp0s.SetLineWidth(3) Exp0s.SetLineColor(1) # Exp1s.SetFillColorAlpha(col, 0.4) #kGreen+1 # Exp1s.SetLineColorAlpha(col, 0.4) # Exp2s.SetFillColorAlpha(col, 0.2) #kOrange # Exp2s.SetLineColorAlpha(col, 0.2) Exp1s.SetFillColor(417) Exp1s.SetLineColor(417) Exp2s.SetFillColor(800) Exp2s.SetLineColor(800) colB = 922 Exp2sB.SetLineWidth(2) Obs0sB.SetLineStyle(9) Obs0sB.SetLineWidth(3) Obs0sB.SetMarkerStyle(0) Obs0sB.SetLineColor(colB) Exp0sB.SetLineStyle(8) Exp0sB.SetLineWidth(3) Exp0sB.SetLineColor(colB) Exp1sB.SetFillColorAlpha(colB, 0.4) #kGreen+1 Exp1sB.SetLineColorAlpha(colB, 0.4) Exp2sB.SetFillColorAlpha(colB, 0.2) #kOrange Exp2sB.SetLineColorAlpha(colB, 0.2) Exp2s.GetXaxis().SetTitle("m_{A} (GeV)") Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25) Exp2s.GetXaxis().SetNoExponent(True) Exp2s.GetXaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetTitle( "#sigma(A) #bf{#it{#Beta}}(A #rightarrow Zh) #bf{#it{#Beta}}(h #rightarrow bb) (fb)" ) Exp2s.GetYaxis().SetTitleOffset(1.5) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetMoreLogLabels() Theory = {} #for t in THEORY: # Theory[t] = TGraphAsymmErrors() # for m in sorted(THDM[t]['ggA'].keys()): # if m < mass[0] or m > mass[-1]: continue # Xs, Xs_Up, Xs_Down = 0., 0., 0. # Xs = THDM[t]['ggA'][m] # Xs_Up = Xs*(1.+math.sqrt((THDM['PDF']['ggA'][m][0]-1.)**2 + (THDM['QCD']['ggA'][m][0]-1.)**2)) # Xs_Down = Xs*(1.-math.sqrt((1.-THDM['PDF']['ggA'][m][1])**2 + (1.-THDM['QCD']['ggA'][m][1])**2)) # n = Theory[t].GetN() # Theory[t].SetPoint(n, m, Xs) # Theory[t].SetPointError(n, 0., 0., (Xs-Xs_Down), (Xs_Up-Xs)) # Theory[t].SetLineColor(theoryLineColor[t]) # Theory[t].SetFillColor(theoryFillColor[t]) # Theory[t].SetFillStyle(theoryFillStyle[t]) # Theory[t].SetLineWidth(2) # #Theory[t].SetLineStyle(7) c1 = TCanvas("c1", "Exclusion Limits", 800, 600) c1.cd() #SetPad(c1.GetPad(0)) c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetLeftMargin(0.12) c1.GetPad(0).SetTicks(1, 1) c1.GetPad(0).SetLogy() Exp2s.Draw("A3") Exp1s.Draw("SAME, 3") Exp0s.Draw("SAME, L") # Exp2sB.Draw("SAME, 3") # Exp1sB.Draw("SAME, 3") Exp0sB.Draw("SAME, L") if not options.blind: Obs0s.Draw("SAME, L") Obs0sB.Draw("SAME, L") for t in THEORY: Theory[t].Draw("SAME, L3") Theory[t].Draw("SAME, L3X0Y0") #setHistStyle(Exp2s) # Exp2s.GetXaxis().SetTitleSize(0.045) # Exp2s.GetYaxis().SetTitleSize(0.04) # Exp2s.GetXaxis().SetLabelSize(0.04) # Exp2s.GetYaxis().SetLabelSize(0.04) # Exp2s.GetXaxis().SetTitleOffset(1) # Exp2s.GetYaxis().SetTitleOffset(1.25) Exp2s.GetXaxis().SetTitleSize(0.050) Exp2s.GetYaxis().SetTitleSize(0.050) Exp2s.GetXaxis().SetLabelSize(0.045) Exp2s.GetYaxis().SetLabelSize(0.045) Exp2s.GetXaxis().SetTitleOffset(0.90) Exp2s.GetYaxis().SetTitleOffset(1.25) Exp2s.GetYaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetRangeUser(0.5, 1.e3) Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1]) drawAnalysis('AZh') drawRegion('AZHsl', True) drawCMS(LUMI, "") #Preliminary #drawCMS(LUMI, "Work in Progress", suppressCMS=True) # legend leg = TLegend(0.6, 0.90, 0.99, 0.90) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("95% CL upper limits") leg.AddEntry(None, "gg #rightarrow A #rightarrow Zh", "") #"95% CL upper limits" leg.AddEntry(Obs0s, "Observed", "l") leg.AddEntry(Exp0s, "Expected", "l") leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f") leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f") leg.AddEntry(None, "", "") leg.AddEntry(None, "bbA #rightarrow Zh", "") leg.AddEntry(Obs0sB, "Observed", "l") leg.AddEntry(Exp0sB, "Expected", "l") leg.SetY1(leg.GetY2() - leg.GetNRows() * 0.045) leg.Draw() # latex = TLatex() # latex.SetNDC() # latex.SetTextSize(0.040) # latex.SetTextFont(42) # latex.DrawLatex(0.65, leg.GetY1()-0.045, "cos(#beta-#alpha)=0.25, tan(#beta)=1") # legB = TLegend(0.12, 0.4-4*0.3/5., 0.65, 0.4) legB = TLegend(0.15, 0.27, 0.68, 0.27) legB.SetBorderSize(0) legB.SetFillStyle(0) #1001 legB.SetFillColor(0) for t in THEORY: legB.AddEntry(Theory[t], theoryLabel[t], "fl") legB.AddEntry(None, "cos(#beta-#alpha)=0.25, tan(#beta)=1", "") legB.SetY1(legB.GetY2() - legB.GetNRows() * 0.045) legB.Draw() c1.GetPad(0).RedrawAxis() leg.Draw() c1.Update() if not gROOT.IsBatch(): raw_input("Press Enter to continue...") c1.Print("plotsLimit/Exclusion/THDM.png") c1.Print("plotsLimit/Exclusion/THDM.pdf")
gDplusOverD0.Draw('p') gDplusOverD0.Fit('fDplusOverD0', 'rq') hFrameDstar = cRatios.cd(2).DrawFrame( 0., 0., 50., 1.5, ';#it{p}_{T} (GeV/#it{c}); D*^{+} / D^{0}') hFrameDstar.GetYaxis().SetDecimals() gDstarOverD0.Draw('p') gDstarOverD0.Fit('fDstarOverD0', 'rq') hFrameDs = cRatios.cd(3).DrawFrame( 0., 0., 50., 1.5, ';#it{p}_{T} (GeV/#it{c}); D_{s}^{+} / D^{0}') hFrameDs.GetYaxis().SetDecimals() gDsOverD0.Draw('p') gDsOverD0.Fit('fDsOverD0', 'rq') hFrameLc = cRatios.cd(4).DrawFrame( 0., 0., 50., 1.5, ';#it{p}_{T} (GeV/#it{c}); #Lambda_{c}^{+} / D^{0}') hFrameLc.GetYaxis().SetDecimals() gLcOverD0.Draw('p') gLcOverD0.Fit('fLcOverD0', 'r') dfDplus = dfD0FONLL.copy() for col in dfDplus.columns: if col not in ['ptmin', 'ptmax']: dfDplus[col] = dfDplus.apply(lambda x: x[col] * gDplusOverD0.Eval( (x['ptmax'] + x['ptmin']) / 2), axis=1) dfDs = dfD0FONLL.copy() for col in dfDs.columns: if col not in ['ptmin', 'ptmax']: dfDs[col] = dfDs.apply(lambda x: x[col] * gDsOverD0.Eval( (x['ptmax'] + x['ptmin']) / 2), axis=1)
def significanceSB(cutlist, labellist): basecut = labellist[0] dim = len(cutlist) significance = [0] * (dim + 1) file = {} tree = {} effs = {} hist = {} GrAsym = {} yErrorUp = {} yErrorDown = {} totEve = 0 GrAsym = TGraphAsymmErrors() cuts = "" for j, c in enumerate(cutlist): s = 0. b = 0. cuts += cutlist[0] if j == 0 else " && " + cutlist[j] print "cuts = ", cuts for num1, v in enumerate(signals): #print "Signal = ", v for num2, filename in enumerate(samples[v]['files']): #print "Signal rootfile read = ", filename file[filename] = TFile(NTUPLESIG + filename + ".root", "READ") # Read TFile tree[filename] = file[filename].Get("Events") # Read TTree nevents = float(sample[filename]['nevents']) xs = float(sample[filename]['xsec']) * float( sample[filename]['kfactor']) LumiMC = nevents / xs Weight = float(LUMI) / float(LumiMC) sig_entries = tree[filename].GetEntries(cuts) #print "s = ", float(sig_entries) * float(Weight) s += float(sig_entries) * float(Weight) print "TOT SIG = ", s for num1, k in enumerate(back): #print "backgrounds = ", k for num2, filename in enumerate(samples[k]['files']): #print "backgrounds rootfile read = ", filename file[filename] = TFile(NTUPLEDIR + filename + ".root", "READ") # Read TFile tree[filename] = file[filename].Get("Events") # Read TTree nevents = float(sample[filename]['nevents']) xs = float(sample[filename]['xsec']) * float( sample[filename]['kfactor']) LumiMC = nevents / xs Weight = float(LUMI) / float(LumiMC) bkg_entries = tree[filename].GetEntries(cuts) #print "b = ", float(bkg_entries) * float(Weight) b += float(bkg_entries) * float(Weight) print "TOT BKG = ", b ##End of cutlist #COMPUTE #print "s = ", s #print "b = ", b #print "sqrt(b) = ", math.sqrt(b) #print "significance = ", float(s/math.sqrt(b)) significance[j] = float(s / math.sqrt(b)) yErrorUp[j] = float( TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, True) - significance[j]) yErrorDown[j] = float( significance[j] - TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, False)) GrAsym.SetPoint(j, j + 0.5, significance[j]) GrAsym.SetPointError(j, 0, 0, yErrorUp[j], yErrorDown[j]) for k, cs in enumerate(labellist): GrAsym.GetHistogram().GetXaxis().Set(dim, 0, dim) GrAsym.GetHistogram().GetXaxis().SetBinLabel(k + 1, "%s" % labellist[k]) GrAsym.SetLineColor(2) GrAsym.SetLineWidth(3) GrAsym.SetMarkerStyle(8) GrAsym.SetMarkerColor(2) c1 = TCanvas("c1", "Signals Acceptance", 800, 600) c1.cd() c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetTicks(1, 1) gStyle.SetOptStat(0) #GrAsym.SetMaximum(1.3) #GrAsym.SetMinimum(0.) GrAsym.GetHistogram().GetXaxis().SetTitle("") GrAsym.GetHistogram().GetYaxis().SetTitle("Significance (S/#sqrt{B})") GrAsym.Draw("pa") drawCMS(LUMI, "Work In Progress") drawRegion(basecut) if not os.path.exists('plots/Signal/Significance/'): os.system('mkdir -p plots/Signal/Significance/') c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".png") c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".pdf") #if not options.runBash: raw_input("Press Enter to continue...") pass
gSignifCatania.Write('gSignifCatania') hSignifCatania.Write('hSignifCatania') cSignif.Write() cSignif.SaveAs('%s_Significance.pdf' % outFileName) cBackground = TCanvas('cBackground', '', 500, 500) cBackground.SetLogy() hBackground.Draw() hBackground.Write('hBackground') cBackground.SaveAs('%s_Background.pdf' % outFileName) cFprompt = TCanvas('cFprompt', '', 500, 500) cFprompt.DrawFrame(cutVars['Pt']['min'][0], 0., cutVars['Pt']['max'][len(cutVars['Pt']['max']) - 1], 1., ';#it{p}_{T} (GeV/#it{c});#it{f}_{prompt} (#it{f}_{c})') gFprompt.Draw('p') gFprompt.Write('gFprompt') cFprompt.SaveAs('%s_Fprompt.pdf' % outFileName) cEff = TCanvas('cEff', '', 500, 500) cEff.DrawFrame( cutVars['Pt']['min'][0], 1.e-4, cutVars['Pt']['max'][len(cutVars['Pt']['max']) - 1], 1., ';#it{p}_{T} (GeV/#it{c});(Acc #times #epsilon) #times 2#it{y}_{fid}') cEff.SetLogy() hAccEffPrompt.Draw('same') hAccEffFD.Draw('same') hAccEffPrompt.Write() hAccEffFD.Write() cEff.Write() cEff.SaveAs('%s_Efficiency.pdf' % outFileName)
gr_s.SetTitle('ROC') gr_s.SetFillColor(632 - 9) gr_sc.SetLineColor(4) c1.cd(1) gr.GetXaxis().SetRangeUser(0, 0.5) gr.GetYaxis().SetRangeUser(0.00001, 0.01) gr_c.GetXaxis().SetRangeUser(0, 0.5) gr_c.GetXaxis().SetRangeUser(0.00001, 0.01) gr_LC.GetXaxis().SetRangeUser(0, 0.5) gr_LC.GetYaxis().SetRangeUser(0.00001, 0.01) gr_c.SetLineColor(4) gr.Draw('SAME 3A') gr_c.Draw('SAME XLP') gr_LC.Draw('SAME A') c1.cd(2) gr_s.Draw('SAME 3A') gr_sc.Draw('SAME XLP') slp(2) c1.Print('roc.png') c1.Update() ########### # # # BackUps #
def pullsVertical_noBonly(fileName): content = filterPullFile(fileName) nbins, off = len(content), 0.10 # Graphs h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins) S_pulls = TGraphAsymmErrors(nbins) boxes = [] canvas = TCanvas("canvas", "Pulls", 720, 300 + nbins * 18) #nbins*20) canvas.cd() canvas.SetGrid(0, 1) canvas.SetTopMargin(0.01) canvas.SetRightMargin(0.01) canvas.SetBottomMargin(0.10) canvas.SetLeftMargin(0.40) canvas.SetTicks(1, 1) for i, s in enumerate(content): l = s.split() h_pulls.GetYaxis().SetBinLabel(i + 1, l[0]) S_pulls.SetPoint(i, float(l[3]), float(i + 1) - 0.5) S_pulls.SetPointError(i, float(l[4]), float(l[4]), 0., 0.) h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta") h_pulls.GetXaxis().SetLabelOffset(0.0) h_pulls.GetXaxis().SetTitleOffset(0.8) h_pulls.GetXaxis().SetLabelSize(0.045) h_pulls.GetXaxis().SetTitleSize(0.050) h_pulls.GetYaxis().SetLabelSize(0.046) h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0) S_pulls.SetFillColor(kBlack) S_pulls.SetLineColor(kBlack) S_pulls.SetMarkerColor(kBlack) S_pulls.SetLineWidth(2) S_pulls.SetMarkerStyle(20) S_pulls.SetMarkerSize(1) box1 = TBox(-1., 0., 1., nbins) #box1.SetFillStyle(3001) # 3001 checkered #box1.SetFillStyle(0) box1.SetFillColor(kGreen + 1) # 417 box1.SetLineWidth(2) box1.SetLineStyle(2) box1.SetLineColor(kGreen + 1) # 417 box2 = TBox(-2., 0., 2., nbins) #box2.SetFillStyle(3001) # 3001 checkered #box2.SetFillStyle(0) box2.SetFillColor(kOrange) # 800 box2.SetLineWidth(2) box2.SetLineStyle(2) box2.SetLineColor(kOrange) # 800 leg = TLegend(0.01, 0.01, 0.3, 0.15) leg.SetTextSize(0.05) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) #leg.SetNColumns(2) leg.AddEntry(S_pulls, "S+B fit", "lp") if text: leg.AddEntry(0, text, "") h_pulls.Draw("") box2.Draw() box1.Draw() S_pulls.Draw("P6SAME") leg.Draw() canvas.RedrawAxis() canvas.Print(outName + ".png") canvas.Print(outName + ".pdf") if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
def draw(hist, data, back, sign, snorm=1, ratio=0, poisson=False, log=False): # If not present, create BkgSum if not 'BkgSum' in hist.keys(): hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) hist['BkgSum'].SetMarkerStyle(0) # Some style for i, s in enumerate(data): hist[s].SetMarkerStyle(21) hist[s].SetMarkerSize(1.25) for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(data + back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow # Set Poisson error bars #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work # Poisson error bars for data if poisson: alpha = 1 - 0.6827 hist['data_obs'].SetBinErrorOption(TH1.kPoisson) data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX()) data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle()) data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize()) res_graph = data_graph.Clone() for i in range(hist['data_obs'].GetNbinsX()): N = hist['data_obs'].GetBinContent(i + 1) B = hist['BkgSum'].GetBinContent(i + 1) L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.) U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1) data_graph.SetPoint( i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N if not N == 0 else -1.e99) data_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N) res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N / B if not B == 0 and not N == 0 else -1.e99) res_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., (N - L) / B if not B == 0 else -1.e99, (U - N) / B if not B == 0 else -1.e99) # Create stack bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend n = len([x for x in data + back + ['BkgSum'] + sign if samples[x]['plot']]) for i, s in enumerate(sign): if 'sublabel' in samples[s]: n += 1 if 'subsublabel' in samples[s]: n += 1 #leg = TLegend(0.68, 0.9-0.05*n, 0.93, 0.9) leg = TLegend(0.68 - 0.05, 0.9 - 0.05 * n, 0.93, 0.9) #DCMS leg.SetTextSize(0.03) #DCMS leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("Signal x-sec=%.0f pb" % (1 * snorm)) if len(data) > 0: leg.AddEntry(hist[data[0]], samples[data[0]]['label'], "ple1") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], samples[s]['label'], "f") for i, s in enumerate(sign): leg.AddEntry(hist[s], samples[s]['label'], "f") # --- Display --- c1 = TCanvas("c1", hist.values()[-1].GetXaxis().GetTitle(), 1000, 800 if ratio else 700) if ratio: c1.Divide(1, 2) setTopPad(c1.GetPad(1), ratio) setBotPad(c1.GetPad(2), ratio) c1.cd(1) c1.GetPad(bool(ratio)).SetTopMargin(0.06) c1.GetPad(bool(ratio)).SetRightMargin(0.05) c1.GetPad(bool(ratio)).SetTicks(1, 1) if log: c1.GetPad(bool(ratio)).SetLogy() #c1.GetPad(bool(ratio)).SetLogx() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if poisson: data_graph.Draw("SAME, PE") elif len(data) > 0: hist['data_obs'].Draw("SAME, PE") for i, s in enumerate(sign): if samples[s]['plot']: hist[s].DrawNormalized("SAME, HIST", hist[s].Integral() * snorm) # signals bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075) # Determine range if 'data_obs' in hist: bkg.SetMaximum((2.5 if log else 1.2) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) bkg.SetMinimum( max( min( hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) else: bkg.SetMaximum(bkg.GetMaximum() * (2.5 if log else 1.2)) bkg.SetMinimum(5.e-1 if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) leg.Draw() #drawCMS(LUMI, "Preliminary") #drawRegion(channel) #drawAnalysis("LL") setHistStyle(bkg, 1.2 if ratio else 1.1) setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1) if ratio: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(2) errLine.SetFillStyle(0) errLine.SetLineColor(2) #L# errLine.SetLineStyle(2) #L# #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if 'data_obs' in hist: res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(res) if poisson: res_graph.Draw("SAME, PE0") else: res.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawKolmogorov(hist['data_obs'], hist['BkgSum']) else: res = None c1.Update() # return list of objects created by the draw() function return [ c1, bkg, leg, err if ratio else None, errLine if ratio else None, res if ratio else None, data_graph if poisson else None, res_graph if poisson else None ]
def makeLimitPlot(output, obs, exp, chan, printStats=False, obs2="", ratioLabel=""): fileObs = open(obs, 'r') fileExp = open(exp, 'r') observedx = [] observedy = [] obsLimits = {} for entry in fileObs: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits: obsLimits[massPoint] = [] obsLimits[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits) for massPoint in sorted(obsLimits): observedx.append(massPoint) observedy.append(numpy.mean(obsLimits[massPoint])) if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits[massPoint]), " std dev: ", numpy.std( obsLimits[massPoint]), " from: ", obsLimits[massPoint] if not obs2 == "": fileObs2 = open(obs2, 'r') observedx2 = [] observedy2 = [] obsLimits2 = {} for entry in fileObs2: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in obsLimits2: obsLimits2[massPoint] = [] obsLimits2[massPoint].append(limitEntry) if printStats: print "len obsLimits:", len(obsLimits2) for massPoint in sorted(obsLimits2): observedx2.append(massPoint) observedy2.append(numpy.mean(obsLimits2[massPoint])) if (numpy.std(obsLimits2[massPoint]) / numpy.mean(obsLimits2[massPoint]) > 0.05): print massPoint, " mean: ", numpy.mean( obsLimits2[massPoint]), " std dev: ", numpy.std( obsLimits2[massPoint] ), " from: ", obsLimits2[massPoint] limits = {} expectedx = [] expectedy = [] expected1SigLow = [] expected1SigHigh = [] expected2SigLow = [] expected2SigHigh = [] for entry in fileExp: massPoint = float(entry.split()[0]) limitEntry = float(entry.split()[1]) if massPoint not in limits: limits[massPoint] = [] limits[massPoint].append(limitEntry) if printStats: print "len limits:", len(limits) for massPoint in sorted(limits): limits[massPoint].sort() numLimits = len(limits[massPoint]) nrExpts = len(limits[massPoint]) medianNr = int(nrExpts * 0.5) #get indexes: upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5)) lower1Sig = int(nrExpts * (1 - 0.68) * 0.5) upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5)) lower2Sig = int(nrExpts * (1 - 0.95) * 0.5) if printStats: print massPoint, ":", limits[massPoint][lower2Sig], limits[ massPoint][lower1Sig], limits[massPoint][medianNr], limits[ massPoint][upper1Sig], limits[massPoint][upper2Sig] #fill lists: expectedx.append(massPoint) expectedy.append(limits[massPoint][medianNr]) expected1SigLow.append(limits[massPoint][lower1Sig]) expected1SigHigh.append(limits[massPoint][upper1Sig]) expected2SigLow.append(limits[massPoint][lower2Sig]) expected2SigHigh.append(limits[massPoint][upper2Sig]) expX = numpy.array(expectedx) expY = numpy.array(expectedy) values2 = [] xPointsForValues2 = [] values = [] xPointsForValues = [] if printStats: print "length of expectedx: ", len(expectedx) if printStats: print "length of expected1SigLow: ", len(expected1SigLow) if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh) #Here is some Voodoo via Sam: for x in range(0, len(expectedx)): values2.append(expected2SigLow[x]) xPointsForValues2.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values2.append(expected2SigHigh[x]) xPointsForValues2.append(expectedx[x]) if printStats: print "length of values2: ", len(values2) for x in range(0, len(expectedx)): values.append(expected1SigLow[x]) xPointsForValues.append(expectedx[x]) for x in range(len(expectedx) - 1, 0 - 1, -1): values.append(expected1SigHigh[x]) xPointsForValues.append(expectedx[x]) if printStats: print "length of values: ", len(values) exp2Sig = numpy.array(values2) xPoints2 = numpy.array(xPointsForValues2) exp1Sig = numpy.array(values) xPoints = numpy.array(xPointsForValues) if printStats: print "xPoints2: ", xPoints2 if printStats: print "exp2Sig: ", exp2Sig if printStats: print "xPoints: ", xPoints if printStats: print "exp1Sig: ", exp1Sig GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig) GraphErr2Sig.SetFillColor(ROOT.kYellow + 1) GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig) GraphErr1Sig.SetFillColor(ROOT.kGreen) cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500) gStyle.SetOptStat(0) if not obs2 == "": plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad.Draw() plotPad.cd() expX = numpy.array(expectedx) expY = numpy.array(expectedy) GraphExp = TGraph(len(expX), expX, expY) GraphExp.SetLineWidth(3) GraphExp.SetLineStyle(2) GraphExp.SetLineColor(ROOT.kBlue) obsX = numpy.array(observedx) obsY = numpy.array(observedy) if printStats: print "obsX: ", obsX if printStats: print "obsY: ", obsY if SMOOTH: smooth_obs = TGraphSmooth("normal") GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY) GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005) else: GraphObs = TGraph(len(obsX), obsX, obsY) GraphObs.SetLineWidth(3) if not obs2 == "": ratio = [] ratiox = [] for index, val in enumerate(observedy): mass = observedx[index] foundIndex = -1 for index2, mass2 in enumerate(observedx2): if mass == mass2: foundIndex = index2 if foundIndex > 0: ratio.append(observedy2[foundIndex] / val) ratiox.append(mass) ratioA = numpy.array(ratio) ratioX = numpy.array(ratiox) obsX2 = numpy.array(observedx2) obsY2 = numpy.array(observedy2) ratioGraph = TGraph(len(ratioX), ratioX, ratioA) if printStats: print "obsX2: ", obsX2 if printStats: print "obsY2: ", obsY2 if SMOOTH: smooth_obs2 = TGraphSmooth("normal") GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2) GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear", 0, 0.005) else: GraphObs2 = TGraph(len(obsX2), obsX2, obsY2) GraphObs2.SetLineWidth(3) smoother = TGraphSmooth("normal") smoother2 = TGraphSmooth("normal") zprimeX = [] zprimeY = [] fileZPrime = open('tools/xsec_SSM.txt', 'r') for entries in fileZPrime: entry = entries.split() zprimeX.append(float(entry[0])) zprimeY.append(float(entry[1]) * 1.3 / 1928) zpX = numpy.array(zprimeX) zpY = numpy.array(zprimeY) GraphZPrime = TGraph(481, zpX, zpY) GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear") GraphZPrimeSmooth.SetLineWidth(3) GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3) GraphZPrimeSmooth.SetLineStyle(2) zprimePsiX = [] zprimePsiY = [] fileZPrimePsi = open('tools/xsec_PSI.txt', 'r') for entries in fileZPrimePsi: entry = entries.split() zprimePsiX.append(float(entry[0])) zprimePsiY.append(float(entry[1]) * 1.3 / 1928) zpPsiX = numpy.array(zprimePsiX) zpPsiY = numpy.array(zprimePsiY) GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY) GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear") GraphZPrimePsiSmooth.SetLineWidth(3) GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue) #Draw the graphs: plotPad.SetLogy() if "Moriond" in output: DummyGraph = TH1F("DummyGraph", "", 100, 120, 4500) else: DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500) DummyGraph.GetXaxis().SetTitle("M [GeV]") if chan == "mumu": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)" ) elif chan == "elel": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)" ) elif chan == "elmu": DummyGraph.GetYaxis().SetTitle( "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)" ) gStyle.SetOptStat(0) if "Moriond" in output: DummyGraph.GetXaxis().SetRangeUser(120, 4500) else: DummyGraph.GetXaxis().SetRangeUser(400, 4500) DummyGraph.SetMinimum(1e-8) DummyGraph.SetMaximum(4e-4) DummyGraph.GetXaxis().SetLabelSize(0.04) DummyGraph.GetXaxis().SetTitleSize(0.045) DummyGraph.GetXaxis().SetTitleOffset(1.) DummyGraph.GetYaxis().SetLabelSize(0.04) DummyGraph.GetYaxis().SetTitleSize(0.045) DummyGraph.GetYaxis().SetTitleOffset(1.) DummyGraph.Draw() if (FULL): GraphErr2Sig.Draw("F") GraphErr1Sig.Draw("F") GraphExp.Draw("lpsame") else: if obs2 == "": GraphExp.Draw("lp") GraphObs.Draw("plsame") if not obs2 == "": GraphObs2.SetLineColor(ROOT.kRed) GraphObs2.SetLineStyle(ROOT.kDashed) GraphObs2.Draw("plsame") if not SPIN2: GraphZPrimeSmooth.Draw("lsame") GraphZPrimePsiSmooth.Draw("lsame") cCL.SetTickx(1) cCL.SetTicky(1) cCL.RedrawAxis() cCL.Update() #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC") leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC") # leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC") leg.SetTextSize(0.032) if not obs2 == "": if ratioLabel == "": ratioLabel = "Variant/Default" ratioLabels = ratioLabel.split("/") leg.AddEntry(GraphObs, "% Observed 95% CL limit" % ratioLabel[1], "l") leg.AddEntry(GraphObs2, "%s Observed 95% CL limit" % ratioLabel[0], "l") else: leg.AddEntry(GraphObs, "Observed 95% CL limit", "l") leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l") if (FULL): leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f") leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f") leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC") leg1.SetTextSize(0.032) if not SPIN2: leg1.AddEntry(GraphZPrimePsiSmooth, "Z'_{#Psi} (LOx1.3)", "l") leg1.AddEntry(GraphZPrimeSmooth, "Z'_{SSM} (LOx1.3)", "l") leg.SetLineWidth(0) leg.SetLineStyle(0) leg.SetLineColor(0) leg.Draw("hist") leg1.SetLineWidth(0) leg1.SetLineStyle(0) leg1.SetLineColor(0) leg1.Draw("hist") if "Moriond" in output: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") else: if (chan == "mumu"): plLumi = TPaveLabel(.65, .905, .9, .99, "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") elif (chan == "elel"): plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)", "NBNDC") elif (chan == "elmu"): plLumi = TPaveLabel( .4, .905, .9, .99, "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC") plLumi.SetTextSize(0.5) plLumi.SetTextFont(42) plLumi.SetFillColor(0) plLumi.SetBorderSize(0) plLumi.Draw() plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC") #plCMS.SetTextSize(0.8) plCMS.SetTextAlign(12) plCMS.SetTextFont(62) plCMS.SetFillColor(0) plCMS.SetBorderSize(0) plCMS.Draw() plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC") plPrelim.SetTextSize(0.6) plPrelim.SetTextAlign(12) plPrelim.SetTextFont(52) plPrelim.SetFillColor(0) plPrelim.SetBorderSize(0) plPrelim.Draw() if not obs2 == "": ratioPad.cd() line = ROOT.TLine(400, 1, 4500, 1) line.SetLineStyle(ROOT.kDashed) ROOT.gStyle.SetTitleSize(0.12, "Y") ROOT.gStyle.SetTitleYOffset(0.35) ROOT.gStyle.SetNdivisions(000, "Y") ROOT.gStyle.SetNdivisions(408, "Y") ratioPad.DrawFrame(400, 0.9, 4500, 1.1, "; ; %s" % ratioLabel) line.Draw("same") ratioGraph.Draw("sameP") cCL.Update() printPlots(cCL, output)
gr_c = gr.Clone() gr_sc = gr_s.Clone() gr.SetTitle('ROC(zoomed in)') #gr.SetMarkerColor(8) #gr.SetMarkerStyle(21) gr.SetFillColor(632 - 9) gr_s.SetTitle('ROC') gr_s.SetFillColor(632 - 9) gr_sc.SetLineColor(4) c1.cd(1) gr.GetXaxis().SetRangeUser(0, 0.5) gr.GetYaxis().SetRangeUser(0.00001, 0.01) gr_c.GetXaxis().SetRangeUser(0, 0.5) gr_c.GetXaxis().SetRangeUser(0.00001, 0.01) gr_c.SetLineColor(4) gr.Draw('SAME 3A') gr_c.Draw('SAME XLP') c1.cd(2) gr_s.Draw('SAME 3A') gr_sc.Draw('SAME XLP') slp(12) c1.Print('roc.png') c1.Update()