Example #1
0
def ROC_plot(SEff, BRej, model_id=""):
    root.TMVA.Tools.Instance()
    aplt.set_atlas_style()
    area = 0
    for index, xval in enumerate(SEff[:-1]):
        delta = SEff[index + 1] - xval
        area -= delta * BRej[index]

    XPlot, YPlot = array("d"), array("d")
    for x, y in zip(SEff, BRej):
        XPlot.append(x)
        YPlot.append(y)

    ndots = len(SEff)

    fig, ax = aplt.subplots(1, 1, name="fig", figsize=(800, 800))

    curve = root.TGraph(ndots, XPlot, YPlot)
    curve.SetLineColor(4)
    curve.SetLineWidth(2)
    curve.GetXaxis().SetTitle(f"BDTgrad_{model_id} signal efficiency")
    curve.GetYaxis().SetTitle(f"BDTgrad_{model_id} background rejection")
    curve.SetMarkerSize(0)

    ax.plot(curve)

    ax.text(0.19, 0.92, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=27, align=13)
    ax.text(0.195, 0.84, f"Area under ROC-curve: {round(area, 3)}")

    fig.savefig(f"BDTgrad_{model_id}_ROC_curve.pdf")
Example #2
0
def main():
    # Set the ATLAS Style
    aplt.set_atlas_style()

    # Create a figure and axes
    fig, ax = aplt.subplots(1, 1, name="fig1", figsize=(800, 600))

    # Randomly fill a 2D histogram
    hist = root.TH2F("hist", "Random Histogram", 50, 0, 10, 40, 0, 200)
    root.fillHist2D(hist, 50000)

    # Draw the histogram on these axes
    ax.plot2d(hist, "COLZ")

    # Change pad margins to allow space for z-axis colour bar and for ATLAS label
    ax.set_pad_margins(right=0.20, top=0.08)

    # Set axis titles
    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.set_zlabel("Events / (0.2 #times 5)", titleoffset=1.2)

    # Add the ATLAS Label
    aplt.atlas_label(ax.pad.GetLeftMargin(), 0.97, text="Internal", align=13)
    ax.text(1 - ax.pad.GetRightMargin(),
            0.97,
            "#sqrt{s} = 13 TeV, 139 fb^{-1}",
            size=22,
            align=33)

    # Save the plot as a PDF
    fig.savefig("hist2D.pdf")
Example #3
0
def BDT_output_hist_plot(SDataframe,
                         BDataframe,
                         model_id="",
                         output_name="output"):
    root.TMVA.Tools.Instance()
    aplt.set_atlas_style()
    Min = np.max(
        (np.min(SDataframe[output_name]), np.min(BDataframe[output_name])))
    Max = np.min(
        (np.max(SDataframe[output_name]), np.max(BDataframe[output_name])))

    # Min =-math.ceil(abs(Min))
    # Max = math.ceil(Max)

    SHist = root.TH1F("", "", 50, Min, Max)
    BHist = root.TH1F("", "", 50, Min, Max)

    SHist.SetStats(False)
    BHist.SetStats(False)
    SHist.SetMinimum(0)
    BHist.SetMinimum(0)
    SHist.SetLineWidth(2)
    BHist.SetLineWidth(2)
    SHist.SetLineColor(4)
    BHist.SetLineColor(2)
    SHist.SetMarkerSize(0)
    BHist.SetMarkerSize(0)

    SHist.SetFillColorAlpha(4, 0.2)
    BHist.SetFillColor(2)
    BHist.SetFillStyle(3004)

    for out, weight in zip(SDataframe[output_name],
                           SDataframe["weightModified"]):
        SHist.Fill(out, weight)
    for out, weight in zip(BDataframe[output_name],
                           BDataframe["weightModified"]):
        BHist.Fill(out, weight)

    hists_max = np.max((get_hist_max(SHist, 50), get_hist_max(BHist, 50)))
    margins = [Min, Max, 0, hists_max]

    fig, ax = aplt.subplots(1, 1, name="", figsize=(800, 600))
    ax.plot(SHist, margins, "E1")
    ax.plot(BHist, margins, "E1")
    ax.add_margins(top=0.1)

    ax.set_xlabel(f"BDTgrad_{model_id} classifier response")
    ax.set_ylabel("Fraction of events")
    ax.text(0.2, 0.92, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=27, align=13)

    legend = root.TLegend(0.65, 0.8, 0.95, 0.92)
    legend.SetFillColorAlpha(0, 0)
    legend.AddEntry(SHist, "Signal", "F")
    legend.AddEntry(BHist, "Background", "F")
    legend.Draw()

    fig.savefig(f"BDTgrad_{model_id}_output.pdf")
Example #4
0
def main():
    # Set the ATLAS Style
    aplt.set_atlas_style()

    # Create a figure and axes
    fig, (ax1, ax2) = aplt.ratio_plot(name="fig1",
                                      figsize=(800, 800),
                                      hspace=0.05)

    # Define a distribution
    sqroot = root.TF1("sqroot", "x*gaus(0) + [3]*abs(sin(x)/x)", 0, 10)
    sqroot.SetParameters(10, 4, 1, 20)

    # Randomly fill two histograms according to the above distribution
    hist1 = root.TH1F("hist1", "Random Histogram 1", 50, 0, 10)
    hist1.FillRandom("sqroot", 20000)

    sqroot.SetParameters(10, 4, 1.1, 20)
    hist2 = root.TH1F("hist2", "Random Histogram 2", 50, 0, 10)
    hist2.FillRandom("sqroot", 20000)

    # Draw the histograms on these axes
    ax1.plot(hist1, linecolor=root.kRed + 1, label="Red", labelfmt="L")
    ax1.plot(hist2, linecolor=root.kBlue + 1, label="Blue", labelfmt="L")

    # Draw line at y=1 in ratio panel
    line = root.TLine(ax1.get_xlim()[0], 1, ax1.get_xlim()[1], 1)
    ax2.plot(line)

    # Calculate and draw the ratio
    ratio_hist = hist1.Clone("ratio_hist")
    ratio_hist.Divide(hist2)
    ax2.plot(ratio_hist, linecolor=root.kBlack)

    # Add extra space at top of plot to make room for labels
    ax1.add_margins(top=0.16)

    # Set axis titles
    ax2.set_xlabel("X [GeV]")
    ax1.set_ylabel("Events / 0.2 GeV")
    ax2.set_ylabel("Red / Blue", loc="centre")

    # Add extra space at top and bottom of ratio panel
    ax2.add_margins(top=0.1, bottom=0.1)

    # Go back to top axes to add labels
    ax1.cd()

    # Add the ATLAS Label
    aplt.atlas_label(text="Internal", loc="upper left")
    ax1.text(0.2, 0.84, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=22, align=13)

    # Add legend
    ax1.legend(loc=(0.78, 0.78, 1, 0.90))

    # Save the plot as a PDF
    fig.savefig("ratio.pdf")
Example #5
0
def main():
    # Set the ATLAS Style
    aplt.set_atlas_style()

    # Create a figure and axes
    fig, ax = aplt.subplots(1, 1, name="fig1", figsize=(800, 600))

    # Plot a line with Gaussian noise
    x = np.arange(20)
    y = 2 * x + np.random.normal(size=20)
    yerr = np.random.normal(loc=np.linspace(1, 2, num=20), scale=0.1, size=20)

    graph = ax.graph(x, y, yerr=yerr, label="Data", labelfmt="EP")

    # Fit the graph; store graphics func but do not draw
    graph.Fit("pol1", "0")

    # Add extra space at top of plot to make room for labels
    ax.add_margins(top=0.18, left=0.05, right=0.05, bottom=0.05)

    # Plot fit function and extend its range to fill plot area
    func = graph.GetFunction("pol1")
    func.SetRange(*ax.get_xlim())
    func.SetNpx(1000)
    ax.plot(func,
            linecolor=root.kRed + 1,
            expand=False,
            label="Fit",
            labelfmt="L")

    # Set axis titles
    ax.set_xlabel("x")
    ax.set_ylabel("y")

    # Add the ATLAS Label
    aplt.atlas_label(text="Simulation Internal", loc="upper left")

    # Add legend
    ax.legend(loc=(0.65, 0.8, 0.95, 0.92))

    # Save the plot as a PDF
    fig.savefig("numpy_graph.pdf")
Example #6
0
def main():
    # Set the ATLAS Style
    aplt.set_atlas_style()

    # Create a figure and axes
    fig, ax = aplt.subplots(1, 1, name="fig1", figsize=(800, 600))

    # Define a distribution
    sqroot = root.TF1("sqroot", "x*gaus(0) + [3]*abs(sin(x)/x)", 0, 10)
    sqroot.SetParameters(10, 4, 1, 20)

    # Randomly fill the histogram according to the above distribution
    hist = root.TH1F("hist", "Random Histogram", 50, 0, 10)
    hist.FillRandom("sqroot", 20000)

    # Fit the histogram with the original distribution; store graphics func but do not draw
    hist.Fit("sqroot", "0")

    # Draw the histogram on these axes
    ax.plot(hist, label="Random Hist", labelfmt="F")

    # Draw the fit function
    sqroot.SetNpx(1000)
    ax.plot(sqroot, label="Fit", labelfmt="L", linecolor=root.kRed + 1)

    # Add extra space at top of plot to make room for labels
    ax.add_margins(top=0.16)

    # Set axis titles
    ax.set_xlabel("X [GeV]")
    ax.set_ylabel("Events / 0.2 GeV")

    # Add the ATLAS Label
    aplt.atlas_label(text="Internal", loc="upper left")
    ax.text(0.2, 0.86, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=22, align=13)

    # Add legend
    ax.legend(loc=(0.65, 0.8, 0.95, 0.92))

    # Save the plot as a PDF
    fig.savefig("hist.pdf")
Example #7
0
def main():
    # Set the ATLAS Style
    aplt.set_atlas_style()

    # Create a figure and axes
    fig, (ax1, ax2) = aplt.ratio_plot(name="fig1",
                                      figsize=(800, 800),
                                      hspace=0.05)

    # Define a distribution
    sqroot = root.TF1("sqroot", "x*gaus(0) + [3]*abs(sin(x)/x)", 0, 10)
    sqroot.SetParameters(10, 4, 1, 20)

    # Randomly fill the histogram according to the above distribution
    hist = root.TH1F("hist", "Random Histogram", 50, 0, 10)
    hist.FillRandom("sqroot", 20000)

    # Fit the histogram with the original distribution; store graphics func but do not draw
    hist.Fit("sqroot", "0")

    # Draw the histogram on these axes
    ax1.plot(hist, "EP X0", linewidth=1, label="Random Hist", labelfmt="EP")

    # Draw the fit function
    sqroot.SetNpx(1000)
    ax1.plot(sqroot, linecolor=root.kRed + 1, label="Fit", labelfmt="L")

    # Draw line at y=0 in residuals panel
    line = root.TLine(ax1.get_xlim()[0], 0, ax1.get_xlim()[1], 0)
    ax2.plot(line)

    # Calculate and draw the fit residuals
    resids = hist.Clone("resids")
    for i in range(1, resids.GetNbinsX()):
        resids.SetBinContent(
            i,
            hist.GetBinContent(i) - sqroot.Eval(hist.GetBinCenter(i)))
        resids.SetBinError(i, hist.GetBinError(i))

    ax2.plot(resids, "EP X0", linewidth=1)

    # Add extra space at top of plot to make room for labels
    ax1.add_margins(top=0.16)

    # Add extra space at top and bottom of residuals panel
    ax2.add_margins(top=0.1, bottom=0.1)

    # Set axis titles
    ax2.set_xlabel("X [GeV]")
    ax1.set_ylabel("Events / 0.2 GeV")
    ax2.set_ylabel("Data - Fit", loc="center")

    # Go back to top axes to add labels
    ax1.cd()

    # Add the ATLAS Label
    aplt.atlas_label(text="Internal", loc="upper left")
    ax1.text(0.2, 0.84, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=22, align=13)

    # Add legend
    ax1.legend(loc=(0.65, 0.78, 0.92, 0.90))

    # Save the plot as a PDF
    fig.savefig("fit_and_resids.pdf")
Example #8
0
def build_reader():
	reader = root.TMVA.Reader("reader")

	var_mJJ 				= array('f',[0])
	var_deltaYJJ 			= array('f',[0])
	var_metPt 				= array('f',[0])
	var_ptBalance 			= array('f',[0])
	var_subleadJetEta 		= array('f',[0])
	var_leadJetPt 			= array('f',[0])
	var_photonEta 			= array('f',[0])
	var_ptBalanceRed 		= array('f',[0])
	var_nJets 				= array('f',[0])
	var_sinDeltaPhiJJOver2 	= array('f',[0])
	var_deltaYJPh 			= array('f',[0])

	reader.AddVariable("mJJ",				var_mJJ)
	reader.AddVariable("deltaYJJ",			var_deltaYJJ)
	reader.AddVariable("metPt",				var_metPt)
	reader.AddVariable("ptBalance",			var_ptBalance)
	reader.AddVariable("subleadJetEta",		var_subleadJetEta)
	reader.AddVariable("leadJetPt",			var_leadJetPt)
	reader.AddVariable("photonEta",			var_photonEta)
	reader.AddVariable("ptBalanceRed",		var_ptBalanceRed)
	reader.AddVariable("nJets",				var_nJets)
	reader.AddVariable("sinDeltaPhiJJOver2",var_sinDeltaPhiJJOver2)
	reader.AddVariable("deltaYJPh",			var_deltaYJPh)

	reader.BookMVA("MLP", "dataloader/weights/TMVAClassification_MLP.weights.xml")

	SDataframe, BDataframe = extract()
	SDataframe["BDToutput"] = 0.0
	BDataframe["BDToutput"] = 0.0

	output = []
	for i, row in SDataframe.iterrows():
		var_mJJ[0]					= row["mJJ"]
		var_deltaYJJ[0]				= row["deltaYJJ"]
		var_metPt[0]				= row["metPt"]
		var_ptBalance[0]			= row["ptBalance"]
		var_subleadJetEta[0]		= row["subleadJetEta"]
		var_leadJetPt[0]			= row["leadJetPt"]
		var_photonEta[0]			= row["photonEta"]
		var_ptBalanceRed[0]			= row["ptBalanceRed"]
		var_nJets[0]				= row["nJets"]
		var_sinDeltaPhiJJOver2[0]	= row["sinDeltaPhiJJOver2"]
		var_deltaYJPh[0]			= row["deltaYJPh"]
		output.append(reader.EvaluateMVA("MLP"))
	SDataframe["BDToutput"] = output

	output = []
	for i, row in BDataframe.iterrows():
		var_mJJ[0]					= row["mJJ"]
		var_deltaYJJ[0]				= row["deltaYJJ"]
		var_metPt[0]				= row["metPt"]
		var_ptBalance[0]			= row["ptBalance"]
		var_subleadJetEta[0]		= row["subleadJetEta"]
		var_leadJetPt[0]			= row["leadJetPt"]
		var_photonEta[0]			= row["photonEta"]
		var_ptBalanceRed[0]			= row["ptBalanceRed"]
		var_nJets[0]				= row["nJets"]
		var_sinDeltaPhiJJOver2[0]	= row["sinDeltaPhiJJOver2"]
		var_deltaYJPh[0]			= row["deltaYJPh"]
		output.append(reader.EvaluateMVA("MLP"))
	BDataframe["BDToutput"] = output

	print("После отборов классификатора")
	print(sum(SDataframe[SDataframe["BDToutput"] > 0.682]["weightModified"]))
	print(sum(BDataframe[BDataframe["BDToutput"] > 0.682]["weightModified"]))


	print("Фиксированные")
	df = SDataframe[SDataframe["phCentrality"] < 0.455]
	df = df[df["mJJ"] > 697]
	df = df[df["ptBalance"] < 0.064]
	df = df[df["deltaYJJ"] > 2.227]
	print(sum(df["weightModified"]))

	df = BDataframe[BDataframe["phCentrality"] < 0.455]
	df = df[df["mJJ"] > 697]
	df = df[df["ptBalance"] < 0.064]
	df = df[df["deltaYJJ"] > 2.227]
	print(sum(df["weightModified"]))

	# import matplotlib.pyplot as plt

	# fig, ax = plt.subplots()
	# ax.hist(SDataframe["BDToutput"], weights=SDataframe["weightModified"], bins=50, color="blue", alpha=0.5, label="signal")
	# ax.hist(BDataframe["BDToutput"], weights=BDataframe["weightModified"], bins=50, color="red", alpha=0.5, label="background")
	# ax.legend()
	# ax.set_xlabel("BDToutput")
	# ax.set_ylabel("N of events")
	# plt.show()

	# canvas = root.TCanvas("canvas", "CANVAS", 1920, 1080)
	SHist = root.TH1F("", "", 50, 0, 1)
	BHist = root.TH1F("", "", 50, 0, 1)

	BHist.SetStats(False)
	SHist.SetStats(False)
	BHist.SetLineWidth(2)	
	BHist.SetLineColor(2)
	BHist.SetFillColor(2)
	BHist.SetFillStyle(3004)

	BHist.GetXaxis().CenterTitle()
	BHist.GetYaxis().SetTitle("Fraction of events")
	BHist.GetYaxis().CenterTitle()
	BHist.GetXaxis().SetTitleOffset(1.2)
	BHist.SetMinimum(0)

	SHist.SetLineWidth(2)
	SHist.SetLineColor(4)
	SHist.SetFillColorAlpha(4, 0.2)

	SHist.GetXaxis().CenterTitle()
	SHist.GetYaxis().SetTitle("Fraction of events")
	SHist.GetYaxis().CenterTitle()
	SHist.GetXaxis().SetTitleOffset(1.2)
	SHist.SetMinimum(0)


	for out, weight in zip(SDataframe["BDToutput"], SDataframe["weightModified"]):
		SHist.Fill(out, weight)
	for out, weight in zip(BDataframe["BDToutput"], BDataframe["weightModified"]):
		BHist.Fill(out, weight)

	aplt.set_atlas_style()
	fig, ax = aplt.subplots(1, 1, name="fig1", figsize=(800, 600))
	#####################################
	ax.plot(SHist, "E1")
	ax.plot(BHist, "E1")
	######################################
	ax.add_margins(top=0.16)
	ax.set_xlabel("MLP classifier response")
	ax.set_ylabel("Fraction of events")

	# aplt.atlas_label(text="Internal", loc="upper left")
	ax.text(0.2, 0.92, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=27, align=13)
	# ax.text(0.205, 0.865, "Z_{#gamma} inc. region", size=27, align=13)

	legend = root.TLegend(0.65, 0.8, 0.95, 0.92)
	legend.SetFillColorAlpha(0, 0)
	legend.AddEntry(SHist, "Signal", "F")
	legend.AddEntry(BHist, "Background", "F")
	legend.Draw()

	# fig.savefig("histogramms/{}.pdf".format("BDToutput"))

	# input()

	return make_selections(SDataframe, BDataframe)
Example #9
0
def build_reader(model_id):
    reader = root.TMVA.Reader("reader")

    var_mJJ = array('f', [0])
    var_deltaYJJ = array('f', [0])
    var_metPt = array('f', [0])
    var_ptBalance = array('f', [0])
    var_subleadJetEta = array('f', [0])
    var_leadJetPt = array('f', [0])
    var_photonEta = array('f', [0])
    var_ptBalanceRed = array('f', [0])
    var_nJets = array('f', [0])
    var_sinDeltaPhiJJOver2 = array('f', [0])
    var_deltaYJPh = array('f', [0])

    reader.AddVariable("mJJ", var_mJJ)
    reader.AddVariable("deltaYJJ", var_deltaYJJ)
    reader.AddVariable("metPt", var_metPt)
    reader.AddVariable("ptBalance", var_ptBalance)
    reader.AddVariable("subleadJetEta", var_subleadJetEta)
    reader.AddVariable("leadJetPt", var_leadJetPt)
    reader.AddVariable("photonEta", var_photonEta)
    reader.AddVariable("ptBalanceRed", var_ptBalanceRed)
    reader.AddVariable("nJets", var_nJets)
    reader.AddVariable("sinDeltaPhiJJOver2", var_sinDeltaPhiJJOver2)
    reader.AddVariable("deltaYJPh", var_deltaYJPh)

    reader.BookMVA(
        "MLP",
        f"dataloader/weights/TMVAClassification_MLP{model_id}.weights.xml")

    SDataframe, BDataframe = extract()
    SDataframe["BDToutput"] = 0.0
    BDataframe["BDToutput"] = 0.0
    print("Веса до применения классификатора:")
    print(np.sum(SDataframe["weightModified"]))
    print(np.sum(BDataframe["weightModified"]))

    output = []
    for i, row in SDataframe.iterrows():
        var_mJJ[0] = row["mJJ"]
        var_deltaYJJ[0] = row["deltaYJJ"]
        var_metPt[0] = row["metPt"]
        var_ptBalance[0] = row["ptBalance"]
        var_subleadJetEta[0] = row["subleadJetEta"]
        var_leadJetPt[0] = row["leadJetPt"]
        var_photonEta[0] = row["photonEta"]
        var_ptBalanceRed[0] = row["ptBalanceRed"]
        var_nJets[0] = row["nJets"]
        var_sinDeltaPhiJJOver2[0] = row["sinDeltaPhiJJOver2"]
        var_deltaYJPh[0] = row["deltaYJPh"]
        output.append(reader.EvaluateMVA("MLP"))
    SDataframe["BDToutput"] = output

    output = []
    for i, row in BDataframe.iterrows():
        var_mJJ[0] = row["mJJ"]
        var_deltaYJJ[0] = row["deltaYJJ"]
        var_metPt[0] = row["metPt"]
        var_ptBalance[0] = row["ptBalance"]
        var_subleadJetEta[0] = row["subleadJetEta"]
        var_leadJetPt[0] = row["leadJetPt"]
        var_photonEta[0] = row["photonEta"]
        var_ptBalanceRed[0] = row["ptBalanceRed"]
        var_nJets[0] = row["nJets"]
        var_sinDeltaPhiJJOver2[0] = row["sinDeltaPhiJJOver2"]
        var_deltaYJPh[0] = row["deltaYJPh"]
        output.append(reader.EvaluateMVA("MLP"))
    BDataframe["BDToutput"] = output

    SHist = root.TH1F("", "", 50, 0, 1)
    BHist = root.TH1F("", "", 50, 0, 1)

    BHist.SetStats(False)
    SHist.SetStats(False)
    BHist.SetLineWidth(2)
    BHist.SetLineColor(2)
    BHist.SetFillColor(2)
    BHist.SetFillStyle(3004)

    BHist.GetXaxis().CenterTitle()
    BHist.GetYaxis().SetTitle("Fraction of events")
    BHist.GetYaxis().CenterTitle()
    BHist.GetXaxis().SetTitleOffset(1.2)
    BHist.SetMinimum(0)

    SHist.SetLineWidth(2)
    SHist.SetLineColor(4)
    SHist.SetFillColorAlpha(4, 0.2)

    SHist.GetXaxis().CenterTitle()
    SHist.GetYaxis().SetTitle("Fraction of events")
    SHist.GetYaxis().CenterTitle()
    SHist.GetXaxis().SetTitleOffset(1.2)
    SHist.SetMinimum(0)

    for out, weight in zip(SDataframe["BDToutput"],
                           SDataframe["weightModified"]):
        SHist.Fill(out, weight)
    for out, weight in zip(BDataframe["BDToutput"],
                           BDataframe["weightModified"]):
        BHist.Fill(out, weight)

    aplt.set_atlas_style()
    fig, ax = aplt.subplots(1, 1, name="fig1", figsize=(800, 600))
    #####################################
    ax.plot(SHist, "E1")
    ax.plot(BHist, "E1")
    ######################################
    ax.add_margins(top=0.16)
    # ax.add_margins(top=0.2)

    ax.set_xlabel(f"MLP{model_id} classifier response")
    ax.set_ylabel("Fraction of events")

    ax.text(0.2, 0.92, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=27, align=13)

    legend = root.TLegend(0.65, 0.8, 0.95, 0.92)
    legend.SetFillColorAlpha(0, 0)
    legend.AddEntry(SHist, "Signal", "F")
    legend.AddEntry(BHist, "Background", "F")
    legend.Draw()

    fig.savefig(f"MLP{model_id}output.pdf")

    # input()

    return make_selections(SDataframe, BDataframe)
Example #10
0
def significance_plot(SDataframe,
                      BDataframe,
                      ratio,
                      ndots=1000,
                      model_id="",
                      output_name="output",
                      ROC=True):
    root.TMVA.Tools.Instance()
    aplt.set_atlas_style()
    Min = np.max(
        (np.min(SDataframe[output_name]), np.min(BDataframe[output_name])))
    Max = np.min(
        (np.max(SDataframe[output_name]), np.max(BDataframe[output_name])))
    SWSum = np.sum(SDataframe["weightModified"])
    BWSum = np.sum(BDataframe["weightModified"])

    XData = np.linspace(Min, Max, ndots)
    SData, BData = np.array([]), np.array([])
    for cursor in XData:
        S = np.sum(
            SDataframe[SDataframe[output_name] >= cursor]["weightModified"])
        B = np.sum(
            BDataframe[BDataframe[output_name] >= cursor]["weightModified"])
        SData = np.append(SData, S)
        BData = np.append(BData, B)

    YData = SData / np.sqrt(ratio * (SData + BData))
    SEff = SData / SWSum
    BRej = 1 - BData / BWSum

    XPlot, YPlot = array("d"), array("d")
    for x, y in zip(XData, YData):
        XPlot.append(x)
        YPlot.append(y)

    curve = root.TGraph(ndots, XPlot, YPlot)
    curve.SetLineColor(2)

    curve.SetLineWidth(2)
    curve.SetMarkerColor(2)
    curve.SetMarkerSize(0)
    curve.GetXaxis().SetRangeUser(Min, Max)
    curve.GetXaxis().SetTitle(f"Cut value applied on BDTgrad{model_id} output")
    curve.GetYaxis().SetTitle('Significance')

    fig, ax = aplt.subplots(1, 1, name="", figsize=(800, 600))
    ax.plot(curve)

    ax.add_margins(top=0.16)

    peak_index = YData.argmax()
    cut = XData[peak_index]
    sig_max = YData[peak_index]

    ax.text(0.2, 0.92, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=27, align=13)

    text1 = "For {} signal and {} background".\
     format(round(np.sum(SDataframe["weightModified"])),
         round(np.sum(BDataframe["weightModified"])))

    text2 = "events the maximum {} is".format("S/#sqrt{S+B}")
    text3 = "{} when cutting at {}".format(round(sig_max, 3), round(cut, 3))

    ax.text(0.2, 0.3, text1, size=20, align=13)
    ax.text(0.2, 0.27, text2, size=20, align=13)
    ax.text(0.2, 0.22, text3, size=20, align=13)

    line = root.TLine(cut, 0, cut, 4)
    line.SetLineStyle(10)
    line.SetLineColor(6)
    ax.plot(line)

    fig.savefig(f"BDTgrad_{model_id}_outputCut.pdf")

    SWCut = np.array(
        SDataframe[SDataframe[output_name] > cut]["weightModified"])
    BWCut = np.array(
        BDataframe[BDataframe[output_name] > cut]["weightModified"])
    print("Significance error:")
    print(error(SWCut, BWCut) /
          np.sqrt(ratio))  ### Нужно ли делить на sqrt(ratio)?

    if ROC:
        ROC_plot(SEff, BRej, model_id=model_id)
Example #11
0
def setup(fontsize=27):
	root.TMVA.Tools.Instance()
	aplt.set_atlas_style(fontsize)
	root.gStyle.SetErrorX(0.5)
	root.gStyle.SetEndErrorSize(0.1)
Example #12
0
import ROOT as root
import numpy as np

import atlasplots as aplt
aplt.set_atlas_style()

fig, ax = aplt.subplots(1, 1, name="fig", figsize=(800, 800))
print(dir(ax.get_ylabel()))
input()

# c1 = root.TCanvas("c1","hists with different scales",600,400)
hist = root.TH1F("", "", 20, -1, 1)

a = np.random.randn(1000, 1).ravel()
for el in a:
    hist.Fill(el, 0.5)

width = hist.GetBinWidth(1)

root.gStyle.SetErrorX(0.5)

ax.plot(hist, [-1, 1, 0, 30], options="E1")
# hist.Draw("E1")
input()
Example #13
0
def main():
    # Set the ATLAS Style
    aplt.set_atlas_style()

    # Create a figure and axes
    fig, (ax1, ax2) = aplt.ratio_plot(name="fig1",
                                      figsize=(800, 800),
                                      hspace=0.05)

    # Define "background", "signal" and "data" distributions
    bkg_func = root.TF1("bkg_func", "[0]*exp([1]*x)", 0, 10)
    bkg_func.SetParameters(20, -0.5)

    sig_func = root.TF1("sig_func", "x*gaus(0)", 0, 10)
    sig_func.SetParameters(10, 4, 1)

    # Randomly fill histograms according to the above distributions
    bkg_hist = root.TH1F("bkg_hist", "Background", 50, 0, 10)
    bkg_hist.FillRandom("bkg_func", 10000)
    bkg_hist.SetFillColor(root.kRed + 1)
    bkg_hist.SetLineWidth(0)
    bkg_hist.Sumw2()

    sig_hist = root.TH1F("sig_hist", "Signal", 50, 0, 10)
    sig_hist.FillRandom("sig_func", 10000)
    sig_hist.SetFillColor(root.kAzure + 1)
    sig_hist.SetLineWidth(0)
    sig_hist.Sumw2()

    data_hist = root.TH1F("data_hist", "Data", 50, 0, 10)
    data_hist.FillRandom("bkg_func", 10000)
    data_hist.FillRandom("sig_func", 10000)
    data_hist.Sumw2()
    data_hist.SetBinErrorOption(
        root.TH1.EBinErrorOpt.kPoisson)  # Use 68% Poisson errors

    # Stack the background and signal histograms
    bkg_and_sig = root.THStack("bkg_and_sig", "")
    bkg_and_sig.Add(bkg_hist)
    bkg_and_sig.Add(sig_hist)

    # Draw the stacked histogram on these axes
    ax1.plot(bkg_and_sig)

    # Plot the MC stat error as a hatched band
    err_band = aplt.root_helpers.hist_to_graph(bkg_and_sig.GetStack().Last(),
                                               show_bin_width=True)
    ax1.plot(err_band, "2", fillcolor=1, fillstyle=3254, linewidth=0)

    # ax1.set_yscale("log")  # uncomment to use log scale for y axis

    # Plot the data as a graph
    data_graph = aplt.root_helpers.hist_to_graph(data_hist)
    ax1.plot(data_graph, "P")

    # Use same x-range in lower axes as upper axes
    ax2.set_xlim(ax1.get_xlim())

    # Draw line at y=1 in ratio panel
    line = root.TLine(ax1.get_xlim()[0], 1, ax1.get_xlim()[1], 1)
    ax2.plot(line)

    # Plot the relative error on the ratio axes
    err_band_ratio = aplt.root_helpers.hist_to_graph(
        bkg_and_sig.GetStack().Last(), show_bin_width=True, norm=True)
    ax2.plot(err_band_ratio, "2", fillcolor=1, fillstyle=3254)

    # Calculate and draw the ratio
    ratio_hist = data_hist.Clone("ratio_hist")
    ratio_hist.Divide(bkg_and_sig.GetStack().Last())
    ratio_graph = aplt.root_helpers.hist_to_graph(ratio_hist)
    ax2.plot(ratio_graph, "P0")

    # Add extra space at top of plot to make room for labels
    ax1.add_margins(top=0.16)

    # Set axis titles
    ax2.set_xlabel("X [GeV]")
    ax1.set_ylabel("Events / 0.2 GeV")
    ax2.set_ylabel("Data / Pred.", loc="centre")

    ax2.set_ylim(0.75, 1.25)
    ax2.draw_arrows_outside_range(ratio_graph)

    # Go back to top axes to add labels
    ax1.cd()

    # Add the ATLAS Label
    aplt.atlas_label(text="Internal", loc="upper left")
    ax1.text(0.2, 0.84, "#sqrt{s} = 13 TeV, 139 fb^{-1}", size=22, align=13)

    # Add legend
    legend = ax1.legend(loc=(0.68, 0.65, 1 - root.gPad.GetRightMargin() - 0.03,
                             1 - root.gPad.GetTopMargin() - 0.03),
                        textsize=22)
    legend.AddEntry(data_graph, "Data", "EP")
    legend.AddEntry(sig_hist, "Signal", "F")
    legend.AddEntry(bkg_hist, "Background", "F")
    legend.AddEntry(err_band, "MC Stat. Unc.", "F")

    # Save the plot as a PDF
    fig.savefig("data_vs_mc.pdf")