def plotAllData(self, trigger): # paramlist == fits missing_fit = False if not self.plotting_data.has_key(trigger): print "\tERROR: Trigger not found in plotting data - %s" % trigger return False else: data = self.plotting_data[ trigger] # { run_number: ( [x_vals], [y_vals], [det_status], [phys_status] ) } bad_ls_x = array.array('f') bad_ls_y = array.array('f') # Separate the good and bad LS points if self.ls_options['rm_bad_beams']: # Remove 'non-stable' beams LS for run in data: res = self.fitFinder.removeBadLS(data[run][0], data[run][1], data[run][3]) data[run][0] = res[0] data[run][1] = res[1] bad_ls_x += res[2] bad_ls_y += res[3] elif self.ls_options['rm_bad_det']: # Remove 'bad' detector LS # NOTE: These LS are a super-set of the 'non-stable' LS for run in data: res = self.fitFinder.removeBadLS(data[run][0], data[run][1], data[run][2]) data[run][0] = res[0] data[run][1] = res[1] bad_ls_x += res[2] bad_ls_y += res[3] skip_bad_ls_plot = (len(bad_ls_x) == 0 or len(bad_ls_y) == 0 or not self.ls_options['show_bad_ls']) run_count = 0 num_pts = 0 for run in data: x_pts, y_pts = self.fitFinder.removePoints(data[run][0], data[run][1]) x_pts, y_pts = self.fitFinder.getGoodPoints(x_pts, y_pts) num_pts += len(y_pts) if len(data[run][0]) > 0: run_count += 1 if num_pts < self.min_plot_pts: #print "\tSkipping %s: Not enough plot points, %d" % (trigger,num_pts) return False if self.use_fit and not self.fits.has_key(trigger): # No fit found for this plot print "\tWARNING: Missing fit - %s" % trigger missing_fit = True # Find max and min values maximumRR = array.array('f') maximumVals = array.array('f') minimumVals = array.array('f') max_xaxis_val = 0 min_xaxis_val = 9999 max_yaxis_val = 0 cut_sigma = 6 # Sigma used to remove points from the plot points display_sigma = 4 # Sigma used to cap max y-axis value # Calculate the avg and std dev using only the upper half of points # NOTE: This leverages the assumption that trigger rates increase with PU # TODO: Only use the x_cut when we have some minimum number of plot points xVals, yVals = self.combinePoints(data) xVals, yVals = self.fitFinder.removePoints(xVals, yVals, 0) x_cut = (max(xVals) - min(xVals)) / 2 xVals, yVals = self.combinePoints(data, x_cut) avg_y, std_y = self.fitFinder.getSD(yVals) # Remove points that are extremely far outside of the avg. for run in data: data[run][0], data[run][1] = self.fitFinder.getGoodPoints( data[run][0], data[run][1], avg_y, std_y, cut_sigma) # Recalculate the avg and std dev xVals, yVals = self.combinePoints(data) avg_y, std_y = self.fitFinder.getSD(yVals) # Find minima and maxima so we create graphs of the right size for run in data: if len(data[run][0]) > 0: maximumVals.append(max(data[run][0])) minimumVals.append(min(data[run][0])) tmp_max_y = max(data[run][1]) if abs(tmp_max_y - avg_y) < std_y * display_sigma: # Don't let the maximum be set by rate 'spikes' maximumRR.append(max(data[run][1])) else: maximumRR.append(avg_y + std_y * display_sigma) if not skip_bad_ls_plot: # TODO: Possibly apply same 'spike' check to the bad LS lists maximumVals.append(max(bad_ls_x)) minimumVals.append(min(bad_ls_x)) maximumRR.append(max(bad_ls_y)) if len(maximumRR) > 0: max_yaxis_val = max(maximumRR) else: print "\tERROR: Invalid boundary for plot axis!" return False if len(maximumVals) > 0: max_xaxis_val = max(maximumVals) min_xaxis_val = min(minimumVals) else: print "\tERROR: Invalid boundary for plot axis!" return False if max_xaxis_val == 0 or max_yaxis_val == 0: print "\tERROR: Invalid boundary for plot axis!" return False canvas = TCanvas(self.var_X, self.var_Y, 1000, 600) canvas.SetName(trigger + "_" + self.var_X + "_vs_" + self.var_Y) if self.use_fit and not missing_fit: plot_func_str = {} func_str = {} fit_func = {} fit_mse = {} for fit_type in self.fits[trigger]: fit_params = self.fits[trigger][fit_type] plot_func_str[fit_type], func_str[fit_type] = self.getFuncStr( fit_params) fit_func[fit_type] = TF1("Fit_" + trigger, plot_func_str[fit_type], 0., 1.1 * max_xaxis_val) fit_mse[fit_type] = fit_params[5] graphList = [] color_map = self.getColorMap() leg_entries = 0 if self.color_by_fill: leg_entries += self.fill_count else: leg_entries += run_count if self.use_fit and not missing_fit: if self.use_multi_fit: leg_entries += len(self.fits[trigger].keys()) else: leg_entries += 1 legend = self.getLegend(num_entries=leg_entries) old_fill = -1 counter = 0 for run in sorted(data): #data[run][0],data[run][1] = self.fitFinder.getGoodPoints(data[run][0],data[run][1]) num_LS = len(data[run][0]) if num_LS == 0: continue graphList.append(TGraph(num_LS, data[run][0], data[run][1])) graphColor = color_map[run] graphList[-1].SetMarkerStyle(7) graphList[-1].SetMarkerSize(1.0) graphList[-1].SetLineColor(graphColor) graphList[-1].SetFillColor(graphColor) graphList[-1].SetMarkerColor(graphColor) graphList[-1].SetLineWidth(2) #graphList[-1].GetXaxis().SetTitle(self.name_X+" "+self.units_X) graphList[-1].GetXaxis().SetTitle(self.label_X) graphList[-1].GetXaxis().SetLimits(0, 1.1 * max_xaxis_val) graphList[-1].GetYaxis().SetTitle(self.label_Y) graphList[-1].GetYaxis().SetTitleOffset(1.2) graphList[-1].SetMinimum(0) graphList[-1].SetMaximum(1.2 * max_yaxis_val) graphList[-1].SetTitle(trigger) if counter == 0: graphList[-1].Draw("AP") else: graphList[-1].Draw("P") canvas.Update() if self.bunch_map.has_key(run): bunches = str(self.bunch_map[run]) else: bunches = "-" legendStr = "" if self.color_by_fill: new_fill = self.fill_map[run] if new_fill != old_fill: old_fill = new_fill legendStr = "%s (%s b)" % (new_fill, bunches) legend.AddEntry(graphList[-1], legendStr, "f") else: legendStr = "%s (%s b)" % (run, bunches) legend.AddEntry(graphList[-1], legendStr, "f") counter += 1 if self.use_fit and not missing_fit: # Display all the fit functions color_counter = 0 for fit_type in sorted(self.fits[trigger]): legend.AddEntry( fit_func[fit_type], "%s Fit ( %s \sigma )" % (fit_type, self.sigmas)) fit_func[fit_type].SetLineColor( self.fit_color_list[color_counter % len(self.fit_color_list)]) fit_func[fit_type].Draw("same") color_counter += 1 if self.show_errors and not self.use_multi_fit: # Display the error band fit_error_band = self.getErrorGraph( fit_func[fit_type], fit_mse[fit_type]) fit_error_band.Draw("3") if self.show_eq and not self.use_multi_fit: # Display the fit equation func_leg = TLegend(.146, .71, .47, .769) func_leg.SetHeader("f(x) = " + func_str[fit_type]) func_leg.SetFillColor(0) #func_leg.SetFillColorAlpha(0,0.5) func_leg.Draw() canvas.Update() if not skip_bad_ls_plot: bad_ls_graph = TGraph(len(bad_ls_x), bad_ls_x, bad_ls_y) bad_ls_graph.SetMarkerStyle(self.ls_options['bad_marker_style']) bad_ls_graph.SetMarkerSize(self.ls_options['bad_marker_size']) bad_ls_graph.SetMarkerColor(self.ls_options['bad_marker_color']) bad_ls_graph.SetLineWidth(2) bad_ls_graph.GetXaxis().SetTitle(self.label_X) bad_ls_graph.GetXaxis().SetLimits(0, 1.1 * max_xaxis_val) bad_ls_graph.GetYaxis().SetTitle(self.label_Y) bad_ls_graph.SetMinimum(0) bad_ls_graph.SetMaximum(1.2 * max_yaxis_val) bad_ls_graph.SetTitle(trigger) bad_ls_graph.Draw("P") canvas.Update() # draw text latex = TLatex() latex.SetNDC() latex.SetTextColor(1) latex.SetTextAlign(11) latex.SetTextFont(62) latex.SetTextSize(0.05) latex.DrawLatex(0.15, 0.84, "CMS") latex.SetTextSize(0.035) latex.SetTextFont(52) latex.DrawLatex(0.15, 0.80, "Rate Monitoring") canvas.SetGridx(1) canvas.SetGridy(1) canvas.Update() # Draw Legend if self.color_by_fill: legend.SetHeader("%s fills (%s runs):" % (self.fill_count, run_count)) else: legend.SetHeader("%s runs:" % (run_count)) legend.SetFillColor(0) legend.Draw() canvas.Update() if self.save_root_file: self.saveRootFile(canvas) if self.save_png: self.savePlot(trigger, canvas) return True
line1, line2, line3, line4, line5, line6, line7, line8, line9, line10, line11, line12, line13, line14, line15, line16, line17, line18, line19, line20, line21, line22, line23, line24, line25, line26, line27, line28, line29, line30, line31, line32, line33, line34, line35, line36, line37, line38, line39, line40, line41, line42, line43, line44, line45, line46, line47, line48, line49, line50, line51, line52, line53, line54, line55, line56, line57, line58, line59, line60, line61, line62, line63, line64 ] for line in lineVector: line.SetLineColor(ROOT.kBlack) line.SetLineWidth(3) line.Draw() leg = TLegend(.64, .82, .68, .86) leg.SetFillStyle(0) leg.SetLineWidth(4) leg.Draw() text = TLatex(.41, .825, "NA49 Coverage") text.SetTextColor(ROOT.kBlack) text.SetNDC() text.SetTextSize(1.4 / 30.) text.SetTextAlign(11) #text.DrawLatex(.48, .55, "#Square"); text.Draw() c4.Print("plots/pionplus_NA49.pdf") # raw_input("Please press enter to exit.")
extraText = "" extraOverCmsTextSize = 0.76 extraTextFont = 52 if year == '2016': lumiText = "35.9 fb^{#minus1} (13 TeV)" if year == '2017': lumiText = "41.50 fb^{#minus1} (13 TeV)" if year == '2018': lumiText = "59.74 fb^{#minus1} (13 TeV)" lumiTextSize = 0.55 lumiTextOffset = 0.2 relExtraDY = 1.2 latex.SetTextAngle(0) latex.SetTextColor(kBlack) extraTextSize = extraOverCmsTextSize * cmsTextSize latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(lumiTextSize * t) latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(lumiTextSize * t) latex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText) latex.SetTextFont(cmsTextFont) latex.SetTextAlign(11) latex.SetTextSize(cmsTextSize * t) latex.DrawLatex(1.15 * l, 1 - t + lumiTextOffset * t, cmsText)
def limit(): method = '' channel = "bb" if INCLUDEACC: particleP = "X" else: particleP = "Z'" particle = 'b#bar{b}' multF = ZPTOBB THEORY = ['bstar'] if INCLUDEACC: THEORY.append('SSM') suffix = "_" + BTAGGING if ISMC: suffix += "_MC" if SY: suffix += "_comb" #if method=="cls": suffix="_CLs" if INCLUDEACC: suffix += "_acc" if SY: filename = "./combine/limits/bstar/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt" else: filename = "./combine/limits/bstar/" + BTAGGING + "/" + YEAR + "_M%d.txt" if CATEGORY != "": if SY: filename = filename.replace( BTAGGING + "/combined_run2/", BTAGGING + "/single_category/combined_run2/" + CATEGORY + "_") else: 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 if INCLUDEACC: acc_factor = ACCEPTANCE[m] else: acc_factor = 1. n = Exp0s.GetN() Obs0s.SetPoint(n, m, val[m][0] * multF * acc_factor) Exp0s.SetPoint(n, m, val[m][3] * multF * acc_factor) Exp1s.SetPoint(n, m, val[m][3] * multF * acc_factor) Exp1s.SetPointError(n, 0., 0., (val[m][3] - val[m][2]) * multF * acc_factor, (val[m][4] - val[m][3]) * multF * acc_factor) Exp2s.SetPoint(n, m, val[m][3] * multF * acc_factor) Exp2s.SetPointError(n, 0., 0., (val[m][3] - val[m][1]) * multF * acc_factor, (val[m][5] - val[m][3]) * multF * acc_factor) 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() if 'bstar' == t: x = [] y = [] with open('bstar_deta1p1_lhc13TeV2.txt') as fin: for line in fin.readlines(): x.append(float(line.split()[0])) y.append(float(line.split()[1]) * 1000) for ind in range(len(x)): Theory[t].SetPoint(ind + 1, x[ind], y[ind]) Theory[t].SetLineColor(theoryLineColor[t]) Theory[t].SetFillColor(theoryFillColor[t]) Theory[t].SetFillStyle(theoryFillStyle[t]) Theory[t].SetLineWidth(2) continue Xs_dict = HVT[t]['Z']['XS'] if t != 'SSM' else SSM['Z'] for m in sorted(Xs_dict.keys()): if INCLUDEACC and t != 'SSM': acc_factor = ACCEPTANCE[m] else: acc_factor = 1. if m < SIGNALS[0] or m > SIGNALS[-1]: continue #if m < mass[0] or m > mass[-1]: continue #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs if m > 4500: continue XsZ, XsZ_Up, XsZ_Down = 0., 0., 0. if t != 'SSM': XsZ = 1000. * HVT[t]['Z']['XS'][m] * SSM["BrZ"][ m] #assuming the same BR as the SSM Z' one 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])) else: XsZ = 1000. * SSM['Z'][m] * SSM["BrZ"][m] XsZ_Up = XsZ * (1. + math.hypot(HVT['A1']['Z']['QCD'][m][0] - 1., HVT['A1']['Z']['PDF'][m][0] - 1.)) XsZ_Down = XsZ * (1. - math.hypot(1. - HVT['A1']['Z']['QCD'][m][0], 1. - HVT['A1']['Z']['PDF'][m][0])) n = Theory[t].GetN() Theory[t].SetPoint(n, m, XsZ * acc_factor) Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down) * acc_factor, (XsZ_Up - XsZ) * acc_factor) 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)".format(" #times #Alpha" if INCLUDEACC else "")) 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) if INCLUDEACC: Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3) else: 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 if CATEGORY == "": #drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawCMS(LUMI, "", suppressCMS=True) else: #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True) drawCMS(LUMI, CAT_LABELS[CATEGORY], 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/" + YEAR + suffix + ".png") c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".pdf") if 'ah' in channel or 'sl' in channel: c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".C") c1.Print("combine/plotsLimit/ExclusionLimits/" + 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 ##FIXME # ---------- Significance ---------- c2 = TCanvas("c2", "Significance", 800, 600) c2.cd() c2.GetPad(0).SetTopMargin(0.06) c2.GetPad(0).SetRightMargin(0.05) c2.GetPad(0).SetTicks(1, 1) c2.GetPad(0).SetGridx() c2.GetPad(0).SetGridy() Sign.GetYaxis().SetRangeUser(0., 5.) Sign.Draw("AL3") #drawCMS(LUMI, "Preliminary") drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawAnalysis(channel[1:3]) c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".png") c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".pdf") # c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root") # c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C") # ---------- p-Value ---------- c3 = TCanvas("c3", "p-Value", 800, 600) c3.cd() c3.GetPad(0).SetTopMargin(0.06) c3.GetPad(0).SetRightMargin(0.05) c3.GetPad(0).SetTicks(1, 1) c3.GetPad(0).SetGridx() c3.GetPad(0).SetGridy() c3.GetPad(0).SetLogy() pVal.Draw("AL3") pVal.GetYaxis().SetRangeUser(2.e-7, 0.5) ci = [ 1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303, 0.000000001973 ] line = TLine() line.SetLineColor(922) line.SetLineStyle(7) text = TLatex() text.SetTextColor(922) text.SetTextSize(0.025) text.SetTextAlign(12) for i in range(1, len(ci) - 1): line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2, pVal.GetXaxis().GetXmax(), ci[i] / 2) text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2, "%d #sigma" % i) #drawCMS(LUMI, "Preliminary") drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawAnalysis(channel[1:3]) c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".png") c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".pdf") # c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root") # c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C") # --------- Best Fit ---------- c4 = TCanvas("c4", "Best Fit", 800, 600) c4.cd() c4.GetPad(0).SetTopMargin(0.06) c4.GetPad(0).SetRightMargin(0.05) c4.GetPad(0).SetTicks(1, 1) c4.GetPad(0).SetGridx() c4.GetPad(0).SetGridy() Best.Draw("AL3") #drawCMS(LUMI, "Preliminary") drawCMS(LUMI, "Work in Progress", suppressCMS=True) drawAnalysis(channel[1:3]) c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".png") c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".pdf") # c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root") # c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C") if not gROOT.IsBatch(): raw_input("Press Enter to continue...") if 'ah' in channel: outFile = TFile("bands.root", "RECREATE") outFile.cd() pVal.Write("graph") Best.Write("best") outFile.Close()
def PoissonError(nObs, ErrorType, plot=""): # Prepare histograms LambdaMin = 0. LambdaMax = nObs + 6*np.sqrt(nObs) Nsteps = 1000 h_likelihood = TH1D( "h_likelihood","",Nsteps,LambdaMin,LambdaMax ) h_2loglik = TH1D( "h_2loglik","",Nsteps,LambdaMin,LambdaMax ) h_pdf_full = TH1D( "h_pdf_full","",Nsteps,LambdaMin,LambdaMax ) IntFraction =ROOT.Math.gaussian_cdf(-1,1,0) # loop over possible Lambda values for iBin in range(1,Nsteps+1): Lambda=h_likelihood.GetBinCenter(iBin) PoissonProb = TMath.Poisson(nObs,Lambda) LogLikelihood = -2.*TMath.Log(PoissonProb) h_likelihood.Fill( Lambda,PoissonProb ) h_2loglik.Fill( Lambda, LogLikelihood ) h_pdf_full.Fill( Lambda, PoissonProb*1. ) # get characteristic values bin_central = h_2loglik.GetMinimumBin() LoglikMin = h_2loglik.GetBinContent(bin_central) Lambda_central = h_2loglik.GetBinCenter(bin_central) LambdaLow = -1. LambdaUp = -1. if ErrorType=="ClassicalCentral": # Frequentist NobsMax = nObs+100 for iBin in range(1,h_pdf_full.GetNbinsX()+1): Lambda = h_pdf_full.GetBinCenter(iBin) PoissonSumLow = 0. PoissonSumUp = 0. for i in range(nObs,NobsMax+1): PoissonSumLow += TMath.Poisson(i,Lambda) if( PoissonSumLow>IntFraction and LambdaLow<0 ): LambdaLow = Lambda for i in range(0,nObs+1): PoissonSumUp += TMath.Poisson(i,Lambda) if( PoissonSumUp<IntFraction and LambdaUp<0 ): LambdaUp = Lambda cvs = TCanvas("Standard Canvas","",600,600) cvs.Divide(1,2) cvs.cd(1) hLow = TH1D("hLow","CLASSICAL CENTRAL",1000,0,17) for i in range(1,hLow.GetNbinsX()+1): hLow.SetBinContent(i, TMath.Poisson( hLow.GetBinCenter(i),LambdaLow )) hLow.SetLineColor(1) hLow.GetXaxis().SetTitle(r"#mu") h_conf = hLow.Clone("h_conf") for i in range(1,h_conf.GetNbinsX()+1): if(h_conf.GetBinCenter(i)<=nObs): h_conf.SetBinContent(i, 0) h_conf.SetFillColorAlpha(9,0.5) h_conf.SetLineWidth(1) h_conf.SetLineColor(1) LowLine = TLine(LambdaLow,0,LambdaLow,hLow.GetBinContent(hLow.FindBin(LambdaLow))) hLow.SetStats(kFALSE) hLow.Draw("l") h_conf.Draw("l same") LowLine.Draw() text = TLatex() text.SetTextSize(0.5) text.SetTextColor(1) text.DrawLatex(0.5,0.8, "LOL") cvs.cd(2) hUp = TH1D("hUp","",1000,0,17) for i in range(1,hUp.GetNbinsX()+1): hUp.SetBinContent(i, TMath.Poisson( hLow.GetBinCenter(i),LambdaUp )) hUp.SetLineColor(1) hUp.GetXaxis().SetTitle(r"#mu") h_conf1 = hUp.Clone("h_conf") for i in range(1,h_conf.GetNbinsX()+1): if(h_conf.GetBinCenter(i)>=nObs): h_conf1.SetBinContent(i, 0) h_conf1.SetFillColorAlpha(9,0.5) h_conf1.SetLineWidth(1) h_conf1.SetLineColor(1) UpLine = TLine(LambdaUp,0,LambdaUp,hUp.GetBinContent(hUp.FindBin(LambdaUp))) hUp.SetStats(kFALSE) hUp.Draw("l") h_conf1.Draw("l same") UpLine.Draw() cvs.cd() leg1 = TLegend(0.35,0.70,0.90,0.85) leg1.SetBorderSize(1); leg1.SetFillColor(0); h_conf.SetMarkerColor(0) leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04); leg1.Draw() cvs.Print("Plots/Errors_"+ErrorType+".eps") if ErrorType=="LikelihoodRatio": for i in range(1,h_2loglik.GetNbinsX()+1): if (h_2loglik.GetBinCenter(i)<LoglikMin and h_2loglik.GetBinContent(i)-LoglikMin>=1.): LambdaLow=h_2loglik.GetBinCenter(i) if (h_2loglik.GetBinCenter(i)>LoglikMin and h_2loglik.GetBinContent(i)-LoglikMin<=1.): LambdaUp=h_2loglik.GetBinCenter(i) cvs = TCanvas("Standard Canvas","",600,400) cvs.cd() LowLine = TLine(LambdaLow,2,LambdaLow,h_2loglik.GetBinContent(h_2loglik.FindBin(LambdaLow))); LowLine.SetLineWidth(1) UpLine = TLine(LambdaUp,2,LambdaUp,h_2loglik.GetBinContent(h_2loglik.FindBin(LambdaUp))); UpLine.SetLineWidth(1) ObsLine = TLine(nObs,2,nObs,h_2loglik.GetBinContent(h_2loglik.FindBin(nObs))); ObsLine.SetLineWidth(1); ObsLine.SetLineColor(2); ObsLine.SetLineStyle(7) h_2loglik.SetFillColor(0) h_2loglik.SetStats(kFALSE) h_2loglik.SetTitle("LIKELIHOOD RATIO") h_2loglik.SetAxisRange(0.8,8,"X") h_2loglik.SetAxisRange(2,7,"Y") h_2loglik.Draw("hist lp") h_2loglik.GetXaxis().SetTitle(r"#mu") h_conf = h_2loglik.Clone("h_conf") for i in range(1,h_conf.GetNbinsX()+1): if(h_conf.GetBinCenter(i)>LambdaLow and h_conf.GetBinCenter(i)<LambdaUp): h_conf.SetBinContent(i,0) h_conf.SetFillColor(9) h_conf.Draw("hist same") leg1 = TLegend(0.55,0.70,0.90,0.85) leg1.SetBorderSize(1); leg1.SetFillColor(0); h_conf.SetMarkerColor(0) leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04); leg1.Draw() LowLine.Draw() UpLine.Draw() ObsLine.Draw() cvs.Print("Plots/Errors_"+ErrorType+".eps") if ErrorType=="BayesCentral": # Work on likelihood as PDF Integral = h_likelihood.Integral() for i in range(1,h_likelihood.GetNbinsX()+1): h_likelihood.SetBinContent(i,h_likelihood.GetBinContent(i)/Integral) # Sum over bins until reached CL Sum_low = 0. Sum_up = 0. for i in range(1,bin_central+1): if Sum_low<=IntFraction: Sum_low += h_likelihood.GetBinContent(i) LambdaLow = h_likelihood.GetBinCenter(i) for i in range(h_likelihood.GetNbinsX(),bin_central,-1): if Sum_up<=IntFraction: Sum_up += h_likelihood.GetBinContent(i) LambdaUp = h_likelihood.GetBinCenter(i) cvs = TCanvas("Standard Canvas","",600,400) cvs.cd() LowLine = TLine(LambdaLow,0,LambdaLow,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaLow))); LowLine.SetLineWidth(1) UpLine = TLine(LambdaUp,0,LambdaUp,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaUp))); UpLine.SetLineWidth(1) ObsLine = TLine(nObs,0,nObs,h_likelihood.GetBinContent(h_2loglik.FindBin(nObs))); ObsLine.SetLineWidth(1); ObsLine.SetLineColor(2); ObsLine.SetLineStyle(7) h_likelihood.SetFillColor(0) h_likelihood.SetStats(kFALSE) h_likelihood.SetTitle("BAYES CENTRAL") #h_likelihood.SetAxisRange(0.8,8,"X") #h_likelihood.SetAxisRange(2,7,"Y") h_likelihood.Draw("hist lp") h_likelihood.GetXaxis().SetTitle(r"#mu") h_conf = h_likelihood.Clone("h_conf") for i in range(1,h_conf.GetNbinsX()+1): if(h_conf.GetBinCenter(i)>LambdaLow and h_conf.GetBinCenter(i)<LambdaUp): h_conf.SetBinContent(i,0) h_conf.SetFillColor(9) h_conf.Draw("hist same") leg1 = TLegend(0.55,0.70,0.90,0.85) leg1.SetBorderSize(1); leg1.SetFillColor(0); h_conf.SetMarkerColor(0) leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04); leg1.Draw() LowLine.Draw() UpLine.Draw() ObsLine.Draw() cvs.Print("Plots/Errors_"+ErrorType+".eps") if ErrorType=="BayesHDI": # Work on likelihood as PDF Integral = h_likelihood.Integral() for i in range(1,h_likelihood.GetNbinsX()+1): h_likelihood.SetBinContent(i,h_likelihood.GetBinContent(i)/Integral) Area = 0. RightIndex=bin_central while Area<=(1-2*IntFraction): RightIndex+=1 # find corresponding bin on left side for i in range(1,bin_central): if h_likelihood.GetBinContent(i)<=h_likelihood.GetBinContent(RightIndex): LeftIndex=i Area = h_likelihood.Integral( LeftIndex,RightIndex ) LambdaLow = h_likelihood.GetBinCenter(LeftIndex) LambdaUp = h_likelihood.GetBinCenter(RightIndex) cvs = TCanvas("Standard Canvas","",600,400) cvs.cd() LowLine = TLine(LambdaLow,0,LambdaLow,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaLow))); LowLine.SetLineWidth(1) UpLine = TLine(LambdaUp,0,LambdaUp,h_likelihood.GetBinContent(h_likelihood.FindBin(LambdaUp))); UpLine.SetLineWidth(1) ObsLine = TLine(nObs,0,nObs,h_likelihood.GetBinContent(h_2loglik.FindBin(nObs))); ObsLine.SetLineWidth(1); ObsLine.SetLineColor(2); ObsLine.SetLineStyle(7) h_likelihood.SetFillColor(0) h_likelihood.SetStats(kFALSE) h_likelihood.SetTitle("BAYES SHORTEST") h_likelihood.Draw("hist lp") h_likelihood.GetXaxis().SetTitle(r"#mu") h_conf = h_likelihood.Clone("h_conf") for i in range(1,h_conf.GetNbinsX()+1): if(h_conf.GetBinCenter(i)>LambdaLow and h_conf.GetBinCenter(i)<LambdaUp): h_conf.SetBinContent(i,0) h_conf.SetFillColor(9) h_conf.Draw("hist same") leg1 = TLegend(0.55,0.70,0.90,0.85) leg1.SetBorderSize(1); leg1.SetFillColor(0); h_conf.SetMarkerColor(0) leg1a = leg1.AddEntry(h_conf, r"(#mu_{low}, #mu_{up}) = ("+str(round(LambdaLow,2))+","+str(round(LambdaUp,2))+")","p"); leg1a.SetTextSize(0.04); leg1.Draw() LowLine.Draw() UpLine.Draw() ObsLine.Draw() cvs.Print("Plots/Errors_"+ErrorType+".eps") return [LambdaLow, LambdaUp] return