Ejemplo n.º 1
0
    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
    print bin, content
    alpha_h.SetBinContent(bin, content)
    alpha_h.SetBinError(bin, error)

alpha_h.SetLineColor(kRed)
alpha_h.SetLineWidth(2)
alpha_h.SetMarkerColor(kRed)
alpha_h.SetMarkerSize(1)
alpha_h.SetMarkerStyle(20)
alpha_h.Draw("EP")

refl = TLine(alpha_h.GetXaxis().GetBinLowEdge(1), 1.0,
             alpha_h.GetXaxis().GetBinLowEdge(n), 1.0)
refl.SetLineStyle(2)
refl.Draw("SAME")

leg_alpha = TLatex()
leg_alpha.SetTextSize(0.06)
leg_alpha.SetNDC()
leg_alpha.DrawLatex(
    0.7, 0.3, "#alpha=#frac{f_{#gamma}^{ee}-f_{#gamma}^{OF}}{f_{#gamma}^{OF}}")

outputpath = "./PLOTS_25ns_v28/OutputPlots_FakeOriginFrac_TTBarTTBarGamma_25ns_v28_vPP6"

for ext in ["pdf", "png"]:
    c.SaveAs(outputpath + "/alpha." + ext)

outputfile = TFile(outputpath + "/" + "alpha.root", "RECREATE")
outputfile.cd()
alpha_h.Write()
Ejemplo n.º 3
0
    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], [status] ) }

        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')

        xVals = array.array('f')
        yVals = array.array('f')

        # Find minima and maxima so we create graphs of the right size
        for run in data:
            xVals, yVals = self.fitFinder.getGoodPoints(
                data[run][0], data[run][1])
            if len(xVals) > 0:
                maximumRR.append(max(yVals))
                maximumVals.append(max(xVals))
                minimumVals.append(min(xVals))

        if len(maximumRR) > 0:
            max_yaxis_value = 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_value == 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)
                if fit_type == "sinh":
                    fit_func[fit_type] = TF1("Fit_" + trigger,
                                             plot_func_str[fit_type], 0.,
                                             1.1 * max_xaxis_val)
                    #fit_func[fit_type].SetParameter(0,fit_params[1])
                    #fit_func[fit_type].SetParameter(1,fit_params[2])
                    #fit_func[fit_type].SetParameter(2,fit_params[3])
                else:
                    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_value)
            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.Draw()
                    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
Ejemplo n.º 4
0
def dijet(category):

    channel = 'bb'
    stype = channel
    isSB = True  # relict from using Alberto's more complex script
    isData = not ISMC
    nTupleDir = NTUPLEDIR

    samples = data if isData else back
    pd = []
    if options.test:
        if ISMC and YEAR == '2016':
            pd.append("MC_QCD_" + YEAR)
            nTupleDir = NTUPLEDIR.replace("weighted/", "test_for_fit/")
        else:
            print "No test sample for real data was implemented. Select '-M' if you want to test on a small MC QCD sample."
            sys.exit()
    else:
        for sample_name in samples:
            if YEAR == 'run2':
                pd += sample[sample_name]['files']
            else:
                pd += [x for x in sample[sample_name]['files'] if YEAR in x]
    print "datasets:", pd
    if not os.path.exists(PLOTDIR): os.makedirs(PLOTDIR)
    if BIAS: print "Running in BIAS mode"

    order = 0
    RSS = {}

    X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV")
    j1_pt = RooRealVar("jpt_1", "jet1 pt", 0., 13000., "GeV")
    jbtag_WP_1 = RooRealVar("jbtag_WP_1", "", -1., 4.)
    jbtag_WP_2 = RooRealVar("jbtag_WP_2", "", -1., 4.)
    fatjetmass_1 = RooRealVar("fatjetmass_1", "", -1., 2500.)
    fatjetmass_2 = RooRealVar("fatjetmass_2", "", -1., 2500.)
    jnmuons_1 = RooRealVar("jnmuons_1", "j1 n_{#mu}", -1., 8.)
    jnmuons_2 = RooRealVar("jnmuons_2", "j2 n_{#mu}", -1., 8.)
    jmuonpt_1 = RooRealVar("jmuonpt_1", "j1 muon pt", 0., 13000.)
    jmuonpt_2 = RooRealVar("jmuonpt_2", "j2 muon pt", 0., 13000.)
    jid_1 = RooRealVar("jid_1", "j1 ID", -1., 8.)
    jid_2 = RooRealVar("jid_2", "j2 ID", -1., 8.)
    nmuons = RooRealVar("nmuons", "n_{#mu}", -1., 10.)
    nelectrons = RooRealVar("nelectrons", "n_{e}", -1., 10.)
    jj_deltaEta = RooRealVar("jj_deltaEta_widejet", "", 0., 5.)
    HLT_AK8PFJet500 = RooRealVar("HLT_AK8PFJet500", "", -1., 1.)
    HLT_PFJet500 = RooRealVar("HLT_PFJet500", "", -1., 1.)
    HLT_CaloJet500_NoJetID = RooRealVar("HLT_CaloJet500_NoJetID", "", -1., 1.)
    HLT_PFHT900 = RooRealVar("HLT_PFHT900", "", -1., 1.)
    HLT_AK8PFJet550 = RooRealVar("HLT_AK8PFJet550", "", -1., 1.)
    HLT_PFJet550 = RooRealVar("HLT_PFJet550", "", -1., 1.)
    HLT_CaloJet550_NoJetID = RooRealVar("HLT_CaloJet550_NoJetID", "", -1., 1.)
    HLT_PFHT1050 = RooRealVar("HLT_PFHT1050", "", -1., 1.)
    HLT_DoublePFJets100_CaloBTagDeepCSV_p71 = RooRealVar(
        "HLT_DoublePFJets100_CaloBTagDeepCSV_p71", "", -1., 1.)
    HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 = RooRealVar(
        "HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1.)
    HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 = RooRealVar(
        "HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1.)
    HLT_DoublePFJets200_CaloBTagDeepCSV_p71 = RooRealVar(
        "HLT_DoublePFJets200_CaloBTagDeepCSV_p71", "", -1., 1.)
    HLT_DoublePFJets350_CaloBTagDeepCSV_p71 = RooRealVar(
        "HLT_DoublePFJets350_CaloBTagDeepCSV_p71", "", -1., 1.)
    HLT_DoublePFJets40_CaloBTagDeepCSV_p71 = RooRealVar(
        "HLT_DoublePFJets40_CaloBTagDeepCSV_p71", "", -1., 1.)

    weight = RooRealVar("eventWeightLumi", "", -1.e9, 1.e9)

    variables = RooArgSet(X_mass)
    variables.add(
        RooArgSet(jbtag_WP_1, jbtag_WP_2, fatjetmass_1, fatjetmass_2,
                  jnmuons_1, jnmuons_2, nmuons, nelectrons, weight))
    variables.add(
        RooArgSet(j1_pt, jj_deltaEta, jid_1, jid_2, jmuonpt_1, jmuonpt_2))
    variables.add(
        RooArgSet(HLT_AK8PFJet500, HLT_PFJet500, HLT_CaloJet500_NoJetID,
                  HLT_PFHT900, HLT_AK8PFJet550, HLT_PFJet550,
                  HLT_CaloJet550_NoJetID, HLT_PFHT1050))
    variables.add(
        RooArgSet(HLT_DoublePFJets100_CaloBTagDeepCSV_p71,
                  HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71,
                  HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71,
                  HLT_DoublePFJets200_CaloBTagDeepCSV_p71,
                  HLT_DoublePFJets350_CaloBTagDeepCSV_p71,
                  HLT_DoublePFJets40_CaloBTagDeepCSV_p71))

    if VARBINS:
        binsXmass = RooBinning(len(abins) - 1, abins)
        X_mass.setBinning(RooBinning(len(abins_narrow) - 1, abins_narrow))
        #binsXmass = RooBinning(len(abins)-1, abins)
        #X_mass.setBinning(binsXmass)
        plot_binning = RooBinning(
            int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(),
            X_mass.getMax())
    else:
        X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10))
        binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100),
                               X_mass.getMin(), X_mass.getMax())
        plot_binning = binsXmass

    if BTAGGING == 'semimedium':
        baseCut = aliasSM[category]
    else:
        baseCut = alias[category].format(WP=working_points[BTAGGING])

    if ADDSELECTION: baseCut += SELECTIONS[options.selection]

    print stype, "|", baseCut

    print " - Reading from Tree"
    treeBkg = TChain("tree")
    if options.unskimmed or options.test:
        for i, ss in enumerate(pd):
            j = 0
            while True:
                if os.path.exists(nTupleDir + ss + "/" + ss +
                                  "_flatTuple_{}.root".format(j)):
                    treeBkg.Add(nTupleDir + ss + "/" + ss +
                                "_flatTuple_{}.root".format(j))
                    j += 1
                else:
                    print "found {} files for sample:".format(j), ss
                    break
    else:
        for ss in pd:
            if os.path.exists(nTupleDir + ss + ".root"):
                treeBkg.Add(nTupleDir + ss + ".root")
            else:
                print "found no file for sample:", ss
    #setData = RooDataSet("setData", "Data" if isData else "Data (QCD MC)", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeBkg))
    if isData or options.test:
        setData = RooDataSet("setData", "Data", variables, RooFit.Cut(baseCut),
                             RooFit.Import(treeBkg))
    else:
        setData = RooDataSet("setData", "Data (QCD+TTbar MC)", variables,
                             RooFit.Cut(baseCut), RooFit.WeightVar(weight),
                             RooFit.Import(treeBkg))

    nevents = setData.sumEntries()
    dataMin, dataMax = array('d', [0.]), array('d', [0.])
    setData.getRange(X_mass, dataMin, dataMax)
    xmin, xmax = dataMin[0], dataMax[0]

    lastBin = X_mass.getMax()
    if VARBINS:
        for b in narrow_bins:  # switched to narrow bins here
            if b > xmax:
                lastBin = b
                break

    print "Imported", (
        "data" if isData else "MC"
    ), "RooDataSet with", nevents, "events between [%.1f, %.1f]" % (xmin, xmax)
    #xmax = xmax+binsXmass.averageBinWidth() # start form next bin

    # 1 parameter
    print "fitting 1 parameter model"
    p1_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p1_1", "p1", 7.0, 0.,
                      2000.)
    modelBkg1 = RooGenericPdf("Bkg1", "Bkg. fit (2 par.)",
                              "1./pow(@0/13000, @1)", RooArgList(X_mass, p1_1))
    normzBkg1 = RooRealVar(
        modelBkg1.GetName() + "_norm", "Number of background events", nevents,
        0., 5. * nevents)  #range dependent of actual number of events!
    modelExt1 = RooExtendPdf(modelBkg1.GetName() + "_ext",
                             modelBkg1.GetTitle(), modelBkg1, normzBkg1)
    fitRes1 = modelExt1.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes1.Print()
    RSS[1] = drawFit("Bkg1", category, X_mass, modelBkg1, setData, binsXmass,
                     [fitRes1], normzBkg1.getVal())

    # 2 parameters
    print "fitting 2 parameter model"
    p2_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_1", "p1", 0., -100.,
                      1000.)
    p2_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_2", "p2",
                      p1_1.getVal(), -100., 600.)
    modelBkg2 = RooGenericPdf("Bkg2", "Bkg. fit (3 par.)",
                              "pow(1-@0/13000, @1) / pow(@0/13000, @2)",
                              RooArgList(X_mass, p2_1, p2_2))
    normzBkg2 = RooRealVar(modelBkg2.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt2 = RooExtendPdf(modelBkg2.GetName() + "_ext",
                             modelBkg2.GetTitle(), modelBkg2, normzBkg2)
    fitRes2 = modelExt2.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes2.Print()
    RSS[2] = drawFit("Bkg2", category, X_mass, modelBkg2, setData, binsXmass,
                     [fitRes2], normzBkg2.getVal())

    # 3 parameters
    print "fitting 3 parameter model"
    p3_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_1", "p1",
                      p2_1.getVal(), -2000., 2000.)
    p3_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_2", "p2",
                      p2_2.getVal(), -400., 2000.)
    p3_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_3", "p3", -2.5,
                      -500., 500.)
    modelBkg3 = RooGenericPdf(
        "Bkg3", "Bkg. fit (4 par.)",
        "pow(1-@0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))",
        RooArgList(X_mass, p3_1, p3_2, p3_3))
    normzBkg3 = RooRealVar(modelBkg3.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt3 = RooExtendPdf(modelBkg3.GetName() + "_ext",
                             modelBkg3.GetTitle(), modelBkg3, normzBkg3)
    fitRes3 = modelExt3.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes3.Print()
    RSS[3] = drawFit("Bkg3", category, X_mass, modelBkg3, setData, binsXmass,
                     [fitRes3], normzBkg3.getVal())

    # 4 parameters
    print "fitting 4 parameter model"
    p4_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_1", "p1",
                      p3_1.getVal(), -2000., 2000.)
    p4_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_2", "p2",
                      p3_2.getVal(), -2000., 2000.)
    p4_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_3", "p3",
                      p3_3.getVal(), -50., 50.)
    p4_4 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_4", "p4", 0.1, -50.,
                      50.)
    modelBkg4 = RooGenericPdf(
        "Bkg4", "Bkg. fit (5 par.)",
        "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000)+@4*pow(log(@0/13000), 2))",
        RooArgList(X_mass, p4_1, p4_2, p4_3, p4_4))
    normzBkg4 = RooRealVar(modelBkg4.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt4 = RooExtendPdf(modelBkg4.GetName() + "_ext",
                             modelBkg4.GetTitle(), modelBkg4, normzBkg4)
    fitRes4 = modelExt4.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes4.Print()
    RSS[4] = drawFit("Bkg4", category, X_mass, modelBkg4, setData, binsXmass,
                     [fitRes4], normzBkg4.getVal())

    # Normalization parameters are should be set constant, but shape ones should not
    #    if BIAS:
    #        p1_1.setConstant(True)
    #        p2_1.setConstant(True)
    #        p2_2.setConstant(True)
    #        p3_1.setConstant(True)
    #        p3_2.setConstant(True)
    #        p3_3.setConstant(True)
    #        p4_1.setConstant(True)
    #        p4_2.setConstant(True)
    #        p4_3.setConstant(True)
    #        p4_4.setConstant(True)
    normzBkg1.setConstant(True)
    normzBkg2.setConstant(True)
    normzBkg3.setConstant(True)
    normzBkg4.setConstant(True)

    #*******************************************************#
    #                                                       #
    #                         Fisher                        #
    #                                                       #
    #*******************************************************#

    # Fisher test
    with open(PLOTDIR + "/Fisher_" + category + ".tex", 'w') as fout:
        fout.write(r"\begin{tabular}{c|c|c|c|c}")
        fout.write("\n")
        fout.write(r"function & $\chi^2$ & RSS & ndof & F-test \\")
        fout.write("\n")
        fout.write("\hline")
        fout.write("\n")
        CL_high = False
        for o1 in range(1, 5):
            o2 = min(o1 + 1, 5)
            if o2 > len(RSS):
                fout.write("%d par & %.2f & %.2f & %d & " %
                           (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"],
                            RSS[o1]["nbins"] - RSS[o1]["npar"]))
                fout.write(r"\\")
                fout.write("\n")
                continue  #order==0 and

            CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1 + 1., o2 + 1.,
                            RSS[o1]["nbins"])
            if CL > 0.10:  # The function with less parameters is enough
                if not CL_high:
                    order = o1
                    fout.write("\\rowcolor{MarkerColor}\n")
                    CL_high = True
            else:
                #fout.write( "%d par are needed " % (o2+1))
                if not CL_high:
                    order = o2
            fout.write("%d par & %.2f & %.2f & %d & " %
                       (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"],
                        RSS[o1]["nbins"] - RSS[o1]["npar"]))
            fout.write("CL=%.3f " % (CL))
            fout.write(r"\\")
            fout.write("\n")
        fout.write("\hline")
        fout.write("\n")
        fout.write(r"\end{tabular}")

    print "saved F-test table as", PLOTDIR + "/Fisher_" + category + ".tex"

    #print "-"*25
    #print "function & $\\chi^2$ & RSS & ndof & F-test & result \\\\"
    #print "\\multicolumn{6}{c}{", "Zprime_to_bb", "} \\\\"
    #print "\\hline"
    #CL_high = False
    #for o1 in range(1, 5):
    #    o2 = min(o1 + 1, 5)
    #    print "%d par & %.2f & %.2f & %d & " % (o1+1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"]-RSS[o1]["npar"]),
    #    if o2 > len(RSS):
    #        print "\\\\"
    #        continue #order==0 and
    #    CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1+1., o2+1., RSS[o1]["nbins"])
    #    print "%d par vs %d par CL=%f & " % (o1+1, o2+1, CL),
    #    if CL > 0.10: # The function with less parameters is enough
    #        if not CL_high:
    #            order = o1
    #            print "%d par are sufficient" % (o1+1),
    #            CL_high=True
    #    else:
    #        print "%d par are needed" % (o2+1),
    #        if not CL_high:
    #            order = o2
    #    print "\\\\"
    #print "\\hline"
    #print "-"*25
    #print "@ Order is", order, "("+category+")"

    #order = min(3, order)
    #order = 2
    if order == 1:
        modelBkg = modelBkg1  #.Clone("Bkg")
        modelAlt = modelBkg2  #.Clone("BkgAlt")
        normzBkg = normzBkg1  #.Clone("Bkg_norm")
        fitRes = fitRes1
    elif order == 2:
        modelBkg = modelBkg2  #.Clone("Bkg")
        modelAlt = modelBkg3  #.Clone("BkgAlt")
        normzBkg = normzBkg2  #.Clone("Bkg_norm")
        fitRes = fitRes2
    elif order == 3:
        modelBkg = modelBkg3  #.Clone("Bkg")
        modelAlt = modelBkg4  #.Clone("BkgAlt")
        normzBkg = normzBkg3  #.Clone("Bkg_norm")
        fitRes = fitRes3
    elif order == 4:
        modelBkg = modelBkg4  #.Clone("Bkg")
        modelAlt = modelBkg3  #.Clone("BkgAlt")
        normzBkg = normzBkg4  #.Clone("Bkg_norm")
        fitRes = fitRes4
    else:
        print "Functions with", order + 1, "or more parameters are needed to fit the background"
        exit()

    modelBkg.SetName("Bkg_" + YEAR + "_" + category)
    modelAlt.SetName("Alt_" + YEAR + "_" + category)
    normzBkg.SetName("Bkg_" + YEAR + "_" + category + "_norm")

    print "-" * 25

    # Generate pseudo data
    setToys = RooDataSet()
    setToys.SetName("data_toys")
    setToys.SetTitle("Data (toys)")
    if not isData:
        print " - Generating", nevents, "events for toy data"
        setToys = modelBkg.generate(RooArgSet(X_mass), nevents)
        #setToys = modelAlt.generate(RooArgSet(X_mass), nevents)
        print "toy data generated"

    if VERBOSE: raw_input("Press Enter to continue...")

    #*******************************************************#
    #                                                       #
    #                         Plot                          #
    #                                                       #
    #*******************************************************#

    print "starting to plot"
    c = TCanvas("c_" + category, category, 800, 800)
    c.Divide(1, 2)
    setTopPad(c.GetPad(1), RATIO)
    setBotPad(c.GetPad(2), RATIO)
    c.cd(1)
    frame = X_mass.frame()
    setPadStyle(frame, 1.25, True)
    if VARBINS: frame.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin)
    signal = getSignal(
        category, stype,
        2000)  #replacing Alberto's getSignal by own dummy function

    graphData = setData.plotOn(frame, RooFit.Binning(plot_binning),
                               RooFit.Scaling(False), RooFit.Invisible())
    modelBkg.plotOn(frame, RooFit.VisualizeError(fitRes, 1, False),
                    RooFit.LineColor(602), RooFit.FillColor(590),
                    RooFit.FillStyle(1001), RooFit.DrawOption("FL"),
                    RooFit.Name("1sigma"))
    modelBkg.plotOn(frame, RooFit.LineColor(602), RooFit.FillColor(590),
                    RooFit.FillStyle(1001), RooFit.DrawOption("L"),
                    RooFit.Name(modelBkg.GetName()))
    modelAlt.plotOn(frame, RooFit.LineStyle(7), RooFit.LineColor(613),
                    RooFit.FillColor(609), RooFit.FillStyle(1001),
                    RooFit.DrawOption("L"), RooFit.Name(modelAlt.GetName()))
    if not isSB and signal[0] is not None:  # FIXME remove /(2./3.)
        signal[0].plotOn(
            frame,
            RooFit.Normalization(signal[1] * signal[2], RooAbsReal.NumEvent),
            RooFit.LineStyle(3), RooFit.LineWidth(6), RooFit.LineColor(629),
            RooFit.DrawOption("L"), RooFit.Name("Signal"))
    graphData = setData.plotOn(
        frame, RooFit.Binning(plot_binning), RooFit.Scaling(False),
        RooFit.XErrorSize(0 if not VARBINS else 1),
        RooFit.DataError(RooAbsData.Poisson if isData else RooAbsData.SumW2),
        RooFit.DrawOption("PE0"), RooFit.Name(setData.GetName()))
    fixData(graphData.getHist(), True, True, not isData)
    pulls = frame.pullHist(setData.GetName(), modelBkg.GetName(), True)
    chi = frame.chiSquare(setData.GetName(), modelBkg.GetName(), True)
    #setToys.plotOn(frame, RooFit.DataError(RooAbsData.Poisson), RooFit.DrawOption("PE0"), RooFit.MarkerColor(2))
    frame.GetYaxis().SetTitle("Events / ( 100 GeV )")
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.Draw()
    #print "frame drawn"
    # Get Chi2
    #    chi2[1] = frame.chiSquare(modelBkg1.GetName(), setData.GetName())
    #    chi2[2] = frame.chiSquare(modelBkg2.GetName(), setData.GetName())
    #    chi2[3] = frame.chiSquare(modelBkg3.GetName(), setData.GetName())
    #    chi2[4] = frame.chiSquare(modelBkg4.GetName(), setData.GetName())

    frame.SetMaximum(frame.GetMaximum() * 10)
    frame.SetMinimum(max(frame.GetMinimum(), 1.e-1))
    c.GetPad(1).SetLogy()

    drawAnalysis(category)
    drawRegion(category, True)
    #drawCMS(LUMI, "Simulation Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawCMS(LUMI, "", suppressCMS=True)

    leg = TLegend(0.575, 0.6, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.AddEntry(setData.GetName(),
                 setData.GetTitle() + " (%d events)" % nevents, "PEL")
    leg.AddEntry(modelBkg.GetName(), modelBkg.GetTitle(),
                 "FL")  #.SetTextColor(629)
    leg.AddEntry(modelAlt.GetName(), modelAlt.GetTitle(), "L")
    if not isSB and signal[0] is not None:
        leg.AddEntry("Signal", signal[0].GetTitle(), "L")
    leg.SetY1(0.9 - leg.GetNRows() * 0.05)
    leg.Draw()

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.04)
    latex.SetTextFont(42)
    if not isSB:
        latex.DrawLatex(leg.GetX1() * 1.16,
                        leg.GetY1() - 0.04, "HVT model B (g_{V}=3)")
    #    latex.DrawLatex(0.67, leg.GetY1()-0.045, "#sigma_{X} = 1.0 pb")

    c.cd(2)
    frame_res = X_mass.frame()
    setPadStyle(frame_res, 1.25)
    frame_res.addPlotable(pulls, "P")
    setBotStyle(frame_res, RATIO, False)
    if VARBINS: frame_res.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin)
    frame_res.GetYaxis().SetRangeUser(-5, 5)
    frame_res.GetYaxis().SetTitle("pulls(#sigma)")
    frame_res.GetYaxis().SetTitleOffset(0.3)
    frame_res.Draw()
    fixData(pulls, False, True, False)

    drawChi2(RSS[order]["chi2"], RSS[order]["nbins"] - (order + 1), True)
    line = drawLine(X_mass.getMin(), 0, lastBin, 0)

    if VARBINS:
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf")
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png")
    else:
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf")
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png")

    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    if BIAS:
        gSystem.Load("libHiggsAnalysisCombinedLimit.so")
        from ROOT import RooMultiPdf
        cat = RooCategory("pdf_index", "Index of Pdf which is active")
        pdfs = RooArgList(modelBkg, modelAlt)
        roomultipdf = RooMultiPdf("roomultipdf", "All Pdfs", cat, pdfs)
        normulti = RooRealVar("roomultipdf_norm",
                              "Number of background events", nevents, 0., 1.e6)

    normzBkg.setConstant(
        False
    )  ## newly put here to ensure it's freely floating in the combine fit

    # create workspace
    w = RooWorkspace("Zprime_" + YEAR, "workspace")
    # Dataset
    if isData: getattr(w, "import")(setData, RooFit.Rename("data_obs"))
    else: getattr(w, "import")(setToys, RooFit.Rename("data_obs"))
    #getattr(w, "import")(setData, RooFit.Rename("data_obs"))
    if BIAS:
        getattr(w, "import")(cat, RooFit.Rename(cat.GetName()))
        getattr(w, "import")(normulti, RooFit.Rename(normulti.GetName()))
        getattr(w, "import")(roomultipdf, RooFit.Rename(roomultipdf.GetName()))
    getattr(w, "import")(modelBkg, RooFit.Rename(modelBkg.GetName()))
    getattr(w, "import")(modelAlt, RooFit.Rename(modelAlt.GetName()))
    getattr(w, "import")(normzBkg, RooFit.Rename(normzBkg.GetName()))
    w.writeToFile(
        WORKDIR + "%s_%s%s.root" %
        (DATA_TYPE + "_" + YEAR, category, "_test" if options.test else ""),
        True)
    print "Workspace", WORKDIR + "%s_%s%s.root" % (
        DATA_TYPE + "_" + YEAR, category,
        "_test" if options.test else ""), "saved successfully"
    if VERBOSE: raw_input("Press Enter to continue...")
Ejemplo n.º 5
0
        stack.Add(background)
        stack.Add(signal)
        stack.Draw('HISTSAME')
        datahist.Draw('PE1SAME')

        gPad.RedrawAxis()
        legend = TLegend(0.5, 0.7, 0.8, 0.92)
        legend.SetFillStyle(0)
        legend.SetTextSize(0.04)
        legend.SetMargin(0.4)
        # legend.SetNColumns(2)
        # legend.SetColumnSeparation(0.3)
        legend.AddEntry(signal, 'Signal', 'f')
        legend.AddEntry(background, 'Background', 'f')
        legend.AddEntry(datahist, 'PseudoData', 'lep')
        legend.Draw('SAME')

        latex = TLatex()
        latex.SetNDC(kTRUE)
        latex.SetTextSize(24)
        if ('VV' in name):
            latextitle = '!VBF'
        else:
            latextitle = 'VBF'
        latex.DrawLatex(0.45, 0.953, latextitle)
        # latex.DrawLatex(0.35,0.953,canvTitle)

        canv.Print('combinedFitPlot_' + name + pointname + '.eps')
        del dummy, canv, datahist, datahist1, tcanv
Ejemplo n.º 6
0
class parameter_descriptor(object):
   #inserts list of parameters and values aligned to the equal sign
   #_____________________________________________________________________________
   def __init__(self, frame, x, y, sep, nsep=0.01):
      self.frame = frame
      #position and separations relative to the frame coordinates
      gxmin = self.frame.GetXaxis().GetXmin()
      gxmax = self.frame.GetXaxis().GetXmax()
      if frame.InheritsFrom(rt.TGraph.Class()) == True:
        gymin = self.frame.GetYaxis().GetXmin()
        gymax = self.frame.GetYaxis().GetXmax()
      else:
        gymin = self.frame.GetMinimum()
        gymax = self.frame.GetMaximum()
      self.xpos = gxmin + (gxmax-gxmin)*x # horizontal position of first equal sign
      self.ypos = gymin + (gymax-gymin)*y # vertical position of first equal sign
      self.itsep = (gymax-gymin)*sep # vertical separation of items
      self.eqsep = (gxmax-gxmin)*nsep # space between name of the variable and equal sign
      self.tsiz = 0.035 #text size
      self.prec = 3 # precision
      self.fmt = "f" # notation, fixed point on exponent
      self.lnam = TLatex() # put names
      self.lnam.SetTextFont(42)
      self.lnam.SetTextSize(self.tsiz)
      self.lnam.SetTextAlign(31)
      self.lval = TLatex() # put values
      self.lval.SetTextFont(42)
      self.lval.SetTextSize(self.tsiz)
      self.item_list = []

   #_____________________________________________________________________________
   def itemRes(self, nam, r1, ipar, col=rt.kBlack):
      #from TFitResult
      self.itemD(nam, r1.Parameter(ipar), r1.ParError(ipar), col)

   #_____________________________________________________________________________
   def itemR(self, nam, x, col=rt.kBlack):
      #from RooRealVar
      self.itemD(nam, x.getVal(), x.getError(), col)

   #_____________________________________________________________________________
   def itemD(self, nam, val, err=-1., col=rt.kBlack):
      #sval = "{0:.{1:d}f}".format(val, self.prec)
      sval = "{0:.{1:d}{2:s}}".format(val, self.prec, self.fmt)
      if err > -1.: sval = self.put_err(sval, err)
      self.item(nam, sval, col)

   #_____________________________________________________________________________
   def item(self, nam, val="", col=rt.kBlack):
      if val != "":
         val = "= " + val
      self.item_list.append([col, nam, val])

   #_____________________________________________________________________________
   def draw(self):
      for icnt in range(len(self.item_list)):
         putY = self.ypos - self.itsep*icnt # linear y axis
         self.lnam.SetTextColor(self.item_list[icnt][0])
         self.lnam.DrawLatex(self.xpos-self.eqsep, putY, self.item_list[icnt][1])
         if self.item_list[icnt][2] != "":
            self.lval.DrawLatex(self.xpos, putY, self.item_list[icnt][2])

   #_____________________________________________________________________________
   def put_err(self, val, err):
      val += " #pm {0:.{1:d}{2:s}}".format(err, self.prec, self.fmt)
      return val

   #_____________________________________________________________________________
   def set_text_size(self, siz):
      self.tsiz = siz
      self.lnam.SetTextSize(self.tsiz)
      self.lval.SetTextSize(self.tsiz)
Ejemplo n.º 7
0
legEff = TLegend(0.4, 0.2, 0.8, 0.45)
legEff.SetTextSize(0.05)
legEff.SetFillStyle(0)
for (hist, legname) in zip(hEffAccPrompt, cfg['legendnames']):
    legEff.AddEntry(hist, legname, 'lp')

cSignificanceVsPt = TCanvas('cSignificanceVsPt', '', 500, 500)
hFrameVsPt = cSignificanceVsPt.DrawFrame(hSignificanceCent[0].GetBinLowEdge(1), 1.e-1, \
    hSignificanceCent[0].GetXaxis().GetBinUpEdge(hSignificanceCent[0].GetNbinsX()), 4.e3, \
        ';#it{p}_{T} (GeV/#it{c});Expected significance (3#sigma)')
hFrameVsPt.GetYaxis().SetTitleOffset(1.2)
cSignificanceVsPt.SetLogy()
for hist, gr in zip(hSignificanceCent, gSignificance):
    gr.Draw('2')
    hist.DrawCopy('same')
lat.DrawLatex(0.18, 0.89, 'ALICE Upgrade projection')
lat.DrawLatex(0.18, 0.82, 'pp, #sqrt{#it{s}} = 14 TeV, #it{L}_{int} = 200 pb^{-1}')
legSignif.Draw()

cSignificanceVsLumi = TCanvas('cSignificanceVsLumi', '', 500, 500)
hFrameVsLumi = cSignificanceVsLumi.DrawFrame(0.1, 0.01, 200, 4.e2, \
    ';#it{L}_{int} (pb^{-1});Expected significance (3#sigma)')
hFrameVsLumi.GetYaxis().SetTitleOffset(1.2)
cSignificanceVsLumi.SetLogy()
cSignificanceVsLumi.SetLogx()
for hist, gr in zip(hSignificanceVsLumi, gSignificanceVsLumi):
    gr.Draw('C4')
lineAtFive.Draw("same")
lat.DrawLatex(0.18, 0.89, 'ALICE Upgrade projection')
lat.DrawLatex(0.18, 0.82, 'pp, #sqrt{#it{s}} = 14 TeV, %0.f < #it{p}_{T} < %0.f GeV/#it{c}' \
    % (hSignificanceCent[0].GetBinLowEdge(ptbinvsLint), \
Ejemplo n.º 8
0
theory.SetLineColor(2)
theory.SetLineStyle(1)
theory.SetLineWidth(2)
theory.Draw("same")

sensitivityline = TLine(sensitivity, yrange_min, sensitivity, yrange_max)
sensitivityline.Draw("same")
insensitivityline = TLine(insensitivity, yrange_min, insensitivity, yrange_max)
insensitivityline.Draw("same")

prelimtex = TLatex()
prelimtex.SetNDC()
prelimtex.SetTextSize(0.03)
prelimtex.SetTextAlign(11)  # align right
prelimtex.DrawLatex(0.58, 0.96,
                    "CMS Preliminary, " + str(lumiPlot) + " fb^{-1} (13 TeV)")

folder = '.'
if not os.path.exists(folder + '/' + limitDir.split('/')[-3] + 'plots'):
    os.system('mkdir ' + folder + '/' + limitDir.split('/')[-3] + 'plots')
c0.SaveAs(folder + '/' + limitDir.split('/')[-3] + 'plots/PlotCombined' +
          distribution + postfix + limitDir.split('/')[-2] + isRebinned +
          '_logy.pdf')
c0.SaveAs(folder + '/' + limitDir.split('/')[-3] + 'plots/PlotCombined' +
          distribution + postfix + limitDir.split('/')[-2] + isRebinned +
          '_logy.png')
c0.SaveAs(folder + '/' + limitDir.split('/')[-3] + 'plots/PlotCombined' +
          distribution + postfix + limitDir.split('/')[-2] + isRebinned +
          '_logy.eps')

c1 = TCanvas("c1", "Limits", 1000, 800)
lat.SetTextSize(0.045)
lat.SetTextFont(42)
lat.SetTextColor(kBlack)

# plot fractions
cNonPromptFracs = TCanvas('cNonPromptFracs', '', 800, 800)
DivideCanvas(cNonPromptFracs, len(multClasses))
for iMult, mult in enumerate(multClasses):
    cNonPromptFracs.cd(iMult + 1).DrawFrame(
        0., 0., hFracNonPrompt[mult][-1].GetXaxis().GetBinUpEdge(
            hFracNonPrompt[mult][-1].GetNbinsX()) + 1,
        hFracNonPrompt[mult][-1].GetMaximum() * 2,
        ';#it{p}_{T} (GeV/#it{c}); #it{f}_{non-prompt}')
    for iVar, _ in enumerate(hFracNonPrompt[mult]):
        hFracNonPrompt[mult][iVar].Draw('same')
    lat.DrawLatex(0.25, 0.8, label[mult])
cNonPromptFracs.Modified()
cNonPromptFracs.Update()

cPromptFracs = TCanvas('cPromptFracs', '', 800, 800)
DivideCanvas(cPromptFracs, len(multClasses))
for iMult, mult in enumerate(multClasses):
    cPromptFracs.cd(iMult + 1).DrawFrame(
        0., hFracPrompt[mult][-1].GetMinimum() * 0.75,
        hFracPrompt[mult][-1].GetXaxis().GetBinUpEdge(
            hFracPrompt[mult][-1].GetNbinsX()) + 1, 1,
        ';#it{p}_{T} (GeV/#it{c}); #it{f}_{prompt}')
    for iVar, _ in enumerate(hFracPrompt[mult]):
        hFracPrompt[mult][iVar].DrawCopy('same')
    lat.DrawLatex(0.25, 0.25, label[mult])
cPromptFracs.Modified()
Ejemplo n.º 10
0
def plotUpperLimits(masses, limit, ALP_xs, name):
    N = len(masses)
    print str(N) + ' mass points'

    yellow = TGraph(2 * N)  # yellow band
    green = TGraph(2 * N)  # green band
    median = TGraph(N)  # median line

    print 'limit = ', limit

    for i in range(N):
        print 'ALP mass: ' + str(masses[i]) + ' GeV'
        x_mass = masses[i]
        yellow.SetPoint(i, x_mass, limit[x_mass][4] * ALP_xs)  # + 2 sigma
        green.SetPoint(i, x_mass, limit[x_mass][3] * ALP_xs)  # + 1 sigma
        median.SetPoint(i, x_mass, limit[x_mass][2] * ALP_xs)  # median
        green.SetPoint(2 * N - 1 - i, x_mass,
                       limit[x_mass][1] * ALP_xs)  # - 1 sigma
        yellow.SetPoint(2 * N - 1 - i, x_mass,
                        limit[x_mass][0] * ALP_xs)  # - 2 sigma

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()

    frame = c.DrawFrame(1.4, 0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.04)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(1.3)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    frame.GetXaxis().SetTitle("m_{a} [GeV]")

    if (args.pb):
        frame.GetYaxis().SetTitle(
            "95% CL limits on #sigma(gg#rightarrow H)#times B(X#rightarrow HH) [pb]"
        )
    elif (args.fb):
        if name == 'coeff':
            frame.GetYaxis().SetTitle(
                "95% CL limits on |C_{Zh}^{eff}| [#frac{#Lambda}{1 TeV}]")
            frame.SetMinimum(0.01)  # need Minimum > 0 for log scale
            frame.SetMaximum(1.)  # CMS HH
        elif name == 'Br':
            #frame.GetYaxis().SetTitle("95% CL limits on #sigma(gg#rightarrow H#rightarrow Za#rightarrow 2l + 2#gamma)(fb)")
            frame.GetYaxis().SetTitle(
                "95% CL limits on Br(pp#rightarrow H#rightarrow Za#rightarrow 2l + 2#gamma)"
            )
            frame.SetMinimum(0.000001)  # need Minimum > 0 for log scale
            frame.SetMaximum(1.)  # CMS HH
        else:
            frame.GetYaxis().SetTitle(
                "95% CL limits on #sigma(pp#rightarrow H#rightarrow Za#rightarrow 2l + 2#gamma)(fb)"
            )
            frame.SetMinimum(0.1)  # need Minimum > 0 for log scale
            frame.SetMaximum(8 * 1e4)  # CMS HH

    frame.GetXaxis().SetLimits(0, 32)

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    CMS_lumi.CMS_lumi(c, 4, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    # yboost = 0.075
    yboost = -0.2

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.88 + yboost
    y1 = 0.80 + yboost
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.035)
    legend.SetTextFont(42)
    legend.AddEntry(median, "AsymptoticLimits CL_{s} expected", 'L')
    legend.AddEntry(green, "#pm 1 std. deviation", 'f')
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 1 std. deviation",'f')
    legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
    # legend.AddEntry("","STAT Only","")
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextAngle(0)
    label.SetTextColor(kBlack)
    label.SetTextFont(42)
    label.SetTextSize(0.045)
    label.SetLineWidth(2)
    label.DrawLatex(0.7, 0.7 + yboost, "STAT only")
    print " "
    # c.SaveAs("UpperLimit.png")

    outFile = "ALP_"

    if args.SM_Radion: outFile += "SM_"

    c.SaveAs(outFile + name + "_UpperLimit.pdf")
    c.SaveAs(outFile + name + "_UpperLimit.C")
    c.Close()
Ejemplo n.º 11
0
leg.SetTextSize(0.045)
leg.SetBorderSize(0)

tt = TLatex()
tt.SetNDC()
tt.SetTextFont(42)

if options.closureTest == False:
    leg.AddEntry(hReco, 'Unfolded data', 'p')
    leg.AddEntry(hTrue, 'Generated (Powheg)', 'l')
    leg.AddEntry(hMeas, 'Raw data', 'p')
else:
    leg.AddEntry(hReco, 'Unfolded MC (Powheg)', 'p')
    leg.AddEntry(hTrue, 'Generated (Powheg)', 'l')
    leg.AddEntry(hMeas, 'Reco-level (Powheg)', 'p')
    tt.DrawLatex(0.55, 0.45, "MC closure test")

leg.Draw()

# write histograms to file
if options.closureTest:
    hReco.SetName("UnfoldedMC")
else:
    hReco.SetName("UnfoldedData")

hReco.Write()
hTrue.Write()
hMeas.Write()

text1 = TLatex()
text1.SetNDC()
Ejemplo n.º 12
0
    lineOneSigma.Draw()
    lineMinusOneSigma.Draw()
    gMassNsigma[iPt].Draw('c')
    lineNsigma.Draw()

    cMassFit[iPt].cd(3).DrawFrame(minMass, gMassPValue[iPt].GetMinimum(),
                                  maxMass, 1., f';{massTitle}; p-value')
    cMassFit[iPt].cd(3).SetLogy()
    gMassPValue[iPt].Draw('c')
    linePval.Draw()
    lineProbOneSigma.Draw()
    lineProbTwoSigma.Draw()
    lineProbThreeSigma.Draw()
    cMassFit[iPt].Update()
    cMassFit[iPt].Modified()
    lat.DrawLatex(maxMass * 1.01, 0.1585, '1#sigma')
    lat.DrawLatex(maxMass * 1.01, 0.0225, '2#sigma')
    lat.DrawLatex(maxMass * 1.01, 0.0015, '3#sigma')

# save outputs
if not os.path.isdir(args.outputPath):
    os.mkdir(args.outputPath)
for iPt, (ptMin,
          ptMax) in enumerate(zip(cutVars['Pt']['min'], cutVars['Pt']['max'])):
    cMass[iPt].SaveAs(
        os.path.join(
            args.outputPath,
            f'{mesonName}MassDistr_w_wo_selection_pT{ptMin}-{ptMax}.pdf'))
    cMassVsML[iPt].SaveAs(
        os.path.join(args.outputPath,
                     f'{mesonName}Mass_vs_MLoutput_pT{ptMin}-{ptMax}.pdf'))
Ejemplo n.º 13
0
    cEff[iPt].DrawFrame(0.5, 1.e-5, nSets+0.5, 1.,
                        f'{ptMin:.0f} < #it{{p}}_{{T}} < {ptMax:.0f} GeV/#it{{c}};cut set;efficiency')
    cEff[iPt].SetLogy()
    hEffPromptVsCut[iPt].DrawCopy('same')
    hEffFDVsCut[iPt].DrawCopy('same')
    legEff.Draw()

    cDistr.append(TCanvas(f'cDistr_pT{ptMin:.0f}_{ptMax:.0f}', '', 800, 800))
    cDistr[iPt].DrawFrame(0.5, 0., nSets+0.5, hRawYieldsVsCut[iPt].GetMaximum()*1.2,
                          f'{ptMin:.0f} < #it{{p}}_{{T}} < {ptMax:.0f} GeV/#it{{c}};cut set;raw yield')
    hRawYieldsVsCut[iPt].Draw('same')
    hRawYieldPromptVsCut[iPt].DrawCopy('histsame')
    hRawYieldFDVsCut[iPt].DrawCopy('histsame')
    hRawYieldsVsCutReSum[iPt].Draw('same')
    legDistr.Draw()
    latInfo.DrawLatex(0.47, 0.65, f'#chi^{{2}} / ndf = {chiSquare:.3f}')

    cFrac.append(TCanvas(f'cFrac_pT{ptMin:.0f}_{ptMax:.0f}', '', 800, 800))
    cFrac[iPt].DrawFrame(0.5, 0., nSets+0.5, 1.8,
                         f'{ptMin:.0f} < #it{{p}}_{{T}} < {ptMax:.0f} GeV/#it{{c}};cut set;fraction')
    hPromptFracVsCut[iPt].DrawCopy('Esame')
    hFDFracVsCut[iPt].DrawCopy('Esame')
    if compareToFc:
        gPromptFracFcVsCut[iPt].Draw('PZ')
        gFDFracFcVsCut[iPt].Draw('PZ')
    if compareToNb:
        gPromptFracNbVsCut[iPt].Draw('PZ')
        gFDFracNbVsCut[iPt].Draw('PZ')
    legFrac.Draw()

    cCorrMatrix.append(TCanvas(f'cCorrMatrix_pT{ptMin:.0f}_{ptMax:.0f}', '', 800, 800))
Ejemplo n.º 14
0
    def makeCertifySummary(self, run, pred_data, log_file):
        # NOTE: pred_data should have keys that only corresponds to triggers in the monitorlist, but self.plotting_data should have *ALL* trigger data
        # UNFINISHED

        gStyle.SetOptStat(0)

        ls_set = set()
        bad_ls = {}  # The total number of bad paths in a given LS, {LS: int}
        trg_bad_ls = {}  # List of bad LS for each trigger
        for trigger in pred_data:
            # data - ( [x_vals], [y_vals], [status] )
            data = self.plotting_data[trigger][run]
            ls_set.update(data[0])
            for LS, pred, err in pred_data[trigger]:
                for data_ls, data_rate in zip(data[0], data[1]):
                    if data_ls != LS:
                        continue
                    for pred_ls, pred_rate, pred_err in pred_data[trigger]:
                        if pred_ls != data_ls:
                            continue
                        if abs(data_rate - pred_rate) > pred_err:
                            if not trg_bad_ls.has_key(trigger):
                                trg_bad_ls[trigger] = []
                            trg_bad_ls[trigger].append(int(LS))

                            if bad_ls.has_key(LS):
                                bad_ls[LS] += 1
                            else:
                                bad_ls[LS] = 1

        max_bad_paths = 1
        bad_ls_inverted = {}  # {int: [LS]}
        for LS in bad_ls:
            count = bad_ls[LS]
            if count > max_bad_paths:
                max_bad_paths = count

            if not bad_ls_inverted.has_key(count):
                bad_ls_inverted[count] = []
            bad_ls_inverted[count].append(int(LS))

        ### MAKE THE SUMMARY TEXT FILE ###
        log_file.write("\n")
        log_file.write("     TRIGGERS: BAD LUMIECTION(S)\n")
        log_file.write("\n")

        for trigger in sorted(trg_bad_ls.keys()):
            log_file.write("     %s: " % trigger)
            formatted_list = "["
            sorted_ls = sorted(trg_bad_ls[trigger])
            min_ls = sorted_ls[0]
            max_ls = sorted_ls[-1]
            for LS in sorted_ls:
                if LS == max_ls + 1 or LS == min_ls:
                    max_ls = LS
                    continue
                else:
                    formatted_list += "[%d,%d], " % (min_ls, max_ls)
                    min_ls = LS
                    max_ls = LS
            if formatted_list == "[":
                # Only possible for ls lists of length 1 or a single contigous block of bad ls
                formatted_list = "[[%d,%d]]" % (min_ls, max_ls)
            else:
                formatted_list += "[%d,%d]]" % (min_ls, max_ls)

            log_file.write(formatted_list + "\n")

        log_file.write("\n")
        log_file.write("     # OF BAD PATHS : LUMISECTION(S)\n")
        log_file.write("\n")

        min_ls = min(ls_set)
        max_ls = max(ls_set)
        tot_ls = len(ls_set)

        for count in sorted(bad_ls_inverted.keys(), reverse=True):
            log_file.write("     %d : %s\n" %
                           (count, str(bad_ls_inverted[count])))

        log_file.write("\n")
        log_file.write("BAD LS SUMMARY:\n")
        log_file.write("\n")

        #bad_count = sum([bad_ls[x] for x in bad_ls.keys()])
        bad_count = len(bad_ls.keys())
        total_count = len(ls_set)

        log_file.write(
            "---- Total bad LS: %d ( bad LS: >= 1 trigger(s) deviating more than 3 sigma from prediction )\n"
            % bad_count)
        log_file.write("---- Total LS: %d\n" % total_count)
        log_file.write("---- Fraction bad LS: %.2f\n" %
                       (100. * float(bad_count) / float(total_count)))

        log_file.write("\n")
        log_file.write("BAD PATH SUMMARY:\n")
        log_file.write("\n")

        bad_count = len(trg_bad_ls.keys())
        total_count = len(pred_data.keys())

        log_file.write("---- Total Bad Paths: %d\n" % bad_count)
        log_file.write("---- Total Possible Paths: %d\n" % total_count)
        log_file.write("---- Fraction that are Bad Paths: %.2f\n" %
                       (100. * float(bad_count) / float(total_count)))

        ### MAKE THE SUMMARY HISTOGRAM ###

        canvas = TCanvas("canv", "canv", 1000, 600)
        canvas.SetName("Certification Summary of Run %s" % run)
        canvas.SetGridx(1)
        canvas.SetGridy(1)

        summary_hist = TH1D("Certification_Summary_of_Run%s" % (run),
                            "Run %s" % (run), (tot_ls + 2), (min_ls - 1),
                            (max_ls + 1))
        summary_hist.GetXaxis().SetTitle("LS")
        summary_hist.GetYaxis().SetTitle("Number of bad paths")
        summary_hist.SetMaximum(1.2 * max_bad_paths)

        for LS in bad_ls:
            summary_hist.Fill(LS, bad_ls[LS])

        max_line = TLine(min_ls - 1, max_bad_paths, max_ls + 1, max_bad_paths)
        max_line.SetLineStyle(9)
        max_line.SetLineColor(2)
        max_line.SetLineWidth(2)

        summary_hist.Draw("hist")
        summary_hist.SetLineColor(4)
        summary_hist.SetFillColor(4)
        summary_hist.SetFillStyle(3004)

        canvas.Update()

        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.Update()

        max_line.Draw("same")

        canvas.Update()

        #canvas.Modified()
        #canvas.Write()

        if self.save_root_file:
            self.saveRootFile(canvas)

        if self.save_png:
            canvas.Print(
                self.save_dir + "/" + "CertificationSummary_run%d" % run +
                ".png", "png")
            #self.savePlot("CertificationSummary_run%d" % run,canvas)

        gStyle.SetOptStat(1)
Ejemplo n.º 15
0
setTitle(hs, var)

gPad.RedrawAxis()

ll = TLatex()

ll.SetNDC(kTRUE)

ll.SetTextSize(0.05)

#AI:

ll.SetTextFont(42)

ll.DrawLatex(0.7, 0.92, "136.65 fb^{-1} (13 TeV)")
#2.2

cms = TLatex()

cms.SetNDC(kTRUE)

cms.SetTextFont(61)

#AI:

cms.SetTextSize(0.06)

cms.DrawLatex(0.16, 0.82, "CMS")

#print ("y-coord = ", 1-t+0.2*t)
Ejemplo n.º 16
0
def plotUpperLimits(labels, values):
    # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/

    #N = len(label)
    N = 11
    print N
    yellow = TGraph(2 * N)  # yellow band
    green = TGraph(2 * N)  # green band
    median = TGraph(N)  # median line
    #file_name = "higgsCombine.AsymptoticLimits.mH125." + labels[0] +  ".root"
    file_name = "higgsCombineX250.AsymptoticLimits.mH125.root"
    limit = getLimits(file_name)
    print 'limit = ', limit
    up2s = []
    for i in range(N):
        # file_name = "higgsCombine"+labels[i]+"AsymptoticLimits.mH125.root"
        print labels
        #file_name = "higgsCombine.AsymptoticLimits.mH125." + labels[i] +  ".root"
        limit = getLimits(file_name)
        print i
        print 'limit = ', limit
        print 'values =', values
        print 'values[i] = ', values[i]
        up2s.append(limit[4])
        yellow.SetPoint(i, values[i], limit[4])  # + 2 sigma
        green.SetPoint(i, values[i], limit[3])  # + 1 sigma
        median.SetPoint(i, values[i], limit[2])  # median
        green.SetPoint(2 * N - 1 - i, values[i], limit[1])  # - 1 sigma
        yellow.SetPoint(2 * N - 1 - i, values[i], limit[0])  # - 2 sigma

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    # c.SetLogy()
    # gPad.SetLogy()
    c.cd()
    # ROOT.gPad.SetLogy()
    # c.SetLogy()
    frame = c.DrawFrame(1.4, 0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    # frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")

    if (args.atlas_compare):
        frame.GetYaxis().SetTitle(
            "95% CL limits on #sigma(gg#rightarrow X)#times B(X#rightarrow HH) [pb]"
        )
    elif (args.CMS_compare):
        frame.GetYaxis().SetTitle(
            "95% CL limit on #sigma(gg#rightarrow X#rightarrow HH) (fb)")
#    frame.GetYaxis().SetTitle("95% upper limit on #sigma #times BR / (#sigma #times BR)_{SM}")
# frame.GetXaxis().SetTitle("background systematic uncertainty [%]")
#if(args.SM_Radion): frame.GetXaxis.SetTitle("Standard Model")
#else: frame.GetXaxis().SetTitle("Radion Mass (GeV)")
# frame.SetMinimum(0)
# frame.SetMinimum(1) # need Minimum > 0 for log scale
    frame.SetMinimum(1.000001)  # need Minimum > 0 for log scale
    # frame.SetMaximum(max(up2s)*1.05)
    # frame.SetMaximum(max(up2s)*2)
    # frame.SetMaximum(1000.)

    if (args.atlas_compare):
        frame.SetMaximum(7 * 1e2)  # ATLAS
    elif (args.CMS_compare):
        frame.SetMaximum(8 * 1e4)  # CMS HH
    #frame.GetXaxis().SetLimits(min(values),max(values))
    # frame.SetLogy()
    frame.GetXaxis().SetLimits(min(values), max(values))

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    CMS_lumi.CMS_lumi(c, 4, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    # yboost = 0.075
    yboost = -0.2

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.88 + yboost
    y1 = 0.80 + yboost
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.035)
    legend.SetTextFont(42)
    legend.AddEntry(median, "AsymptoticLimits CL_{s} expected", 'L')
    legend.AddEntry(green, "#pm 1 std. deviation", 'f')
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 1 std. deviation",'f')
    legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
    # legend.AddEntry("","STAT Only","")
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextAngle(0)
    label.SetTextColor(kBlack)
    label.SetTextFont(42)
    label.SetTextSize(0.045)
    label.SetLineWidth(2)
    label.DrawLatex(0.7, 0.7 + yboost, "STAT only")
    print " "
    # c.SaveAs("UpperLimit.png")

    outFile = ''
    if (args.CMS_compare):
        outFile += "CMS_Compare_"
    if (args.atlas_compare):
        outFile += "atlas_Compare_"

    if args.SM_Radion: outFile += "SM_"

    c.SaveAs(outFile + "UpperLimit.pdf")
    c.SaveAs(outFile + "UpperLimit.C")
    c.Close()
Ejemplo n.º 17
0
def do_plot(categories):
    #this sets how tall the canvas is
    N_cats = len(plot_categories.keys())
    #sets the number of divisions on the plot
    N_cuts = max(len(cuts) for cuts in plot_categories.itervalues())
    canv = TCanvas('theorycomp', '', 500, 500 + 200 * N_cats)
    main_pad_ylow = 1 - (500.0 / (500 + 200 * N_cats))
    rat_pad_height = main_pad_ylow / N_cats
    canv.cd()

    max_cs = get_max_cs(categories)
    min_cs = get_min_cs(categories)

    scaffold = TH1F('scaf', '', N_cuts, 0, N_cuts)
    scaffold.GetYaxis().SetLimits(10 * max_cs, min_cs / 10.0)
    scaffold.GetYaxis().SetRangeUser(min_cs / 10.0, 10 * max_cs)
    scaffold.SetNdivisions(100 * N_cuts)
    scaffold.SetStats(False)
    scaffold.GetYaxis().SetTitle(y_axis_title)
    unshitify(scaffold)

    main_pad = TPad('main_plot', '', 0, main_pad_ylow, 1, 1, 0, 0, 0)
    main_pad.SetLogy()

    main_pad.Draw()
    main_pad.cd()
    scaffold.Draw()

    cut_labels = TLatex()
    cut_labels.SetNDC()
    plot_start = 0.15
    column_width = (0.945 - plot_start) / N_cuts
    cut_labels.SetTextSize(0.045)
    cut_labels.SetTextFont(62)
    #    cut_labels.DrawLatex(0.18,0.96,
    #                         "CMS Preliminary %i, #sqrt{s} = %s"%(year,sqrts))
    #    cut_labels.DrawLatex(0.77,0.96,luminosity)
    cut_labels.DrawLatex(0.17, 0.96, "CMS Preliminary, L = 5.0 fb^{-1}")
    cut_labels.DrawLatex(0.76, 0.96, "#sqrt{s} = 7 TeV")

    labels_drawn = 0
    ratio_pads = []
    cat_meass = []
    cat_preds = []
    cat_meas_rats = []
    cat_pred_rats = []

    legend = TLegend(0.45, 0.7, 0.93, 0.93)
    legend.SetTextFont(62)
    legend.SetTextSize(0.038)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    legend.SetBorderSize(1)

    for j, (cat, cuts) in enumerate(plot_categories.iteritems()):
        canv.cd()
        ratio_pads.append(
            TPad(cat, '', 0, rat_pad_height * j + 0.075, 1,
                 rat_pad_height * (j + 1) + rat_pad_height / 4, 0, 0, 0))
        ratio_pads[-1].Draw()
        ratio_pads[-1].cd()
        rat_scaf = scaffold.DrawCopy()
        rat_scaf.GetYaxis().SetLimits(-1, 3)
        rat_scaf.GetYaxis().SetRangeUser(0, 2)
        rat_scaf.GetYaxis().SetNdivisions(105)
        rat_scaf.GetYaxis().SetTitle("#frac{Data}{%s}" % (prediction_name))
        rat_scaf.GetYaxis().SetTitleOffset(0.6)
        rat_scaf.GetYaxis().SetTitleSize(0.10)

        main_pad.cd()
        print j, cat

        cat_meass.append([])
        cat_preds.append(TGraphErrors())
        cat_meas_rats.append([])
        cat_pred_rats.append(TGraphErrors())

        cat_preds[-1].SetName("%s (%s)" % (prediction_name, cat))

        added_channels = False

        for i, cut in enumerate(cuts):
            cut_name = cut.keys()[0]
            if len(cuts) == N_cuts and labels_drawn != len(cuts):
                canv.cd()
                cut_labels.DrawLatex(plot_start + column_width * (i + 0.35),
                                     0.05, cut_name)
                labels_drawn += 1
            main_pad.cd()
            print '\t%i : %s' % (i, cut_name)

            realkeys = list(cut[cut_name].keys())
            realkeys.remove('PREDICTION')
            nchan = len(realkeys)
            divsize = 1.0 / (nchan)

            if not added_channels:
                cat_meass[-1] += [TGraphErrors() for l in range(nchan)]
                cat_meas_rats[-1] += [TGraphErrors() for l in range(nchan)]
                print cat_meass[-1]
                added_channels = True

            #graph entries for prediction
            pcs, perr = cut[cut_name]['PREDICTION']

            cat_preds[-1].SetPoint(i, i + 0.5, pcs)
            cat_preds[-1].SetPointError(i, 0.5, perr)

            cat_pred_rats[-1].SetPoint(i, i + 0.5, 1.0)
            cat_pred_rats[-1].SetPointError(i, 0.5, perr / pcs)

            #graph entries for data measurement
            for k, key in enumerate(realkeys):
                gidx = i
                print cut[cut_name][key]
                cs, stat, syst = cut[cut_name][key]
                err = hypot(stat, syst)

                cat_meass[-1][k].SetName("%s (%s)" % (key, cat))

                cat_meass[-1][k].SetPoint(gidx, i + (k + 0.5) * divsize, cs)
                cat_meass[-1][k].SetPointError(gidx, 0, err)

                cat_meas_rats[-1][k].SetPoint(gidx, i + (k + 0.5) * divsize,
                                              cs / pcs)
                cat_meas_rats[-1][k].SetPointError(gidx, 0, err / pcs)


#                                                   err/pcs)
        main_pad.cd()
        cat_preds[-1].SetFillColor(fill_colors[j] - 3)
        cat_preds[-1].Draw('2')
        legend.AddEntry(cat_preds[-1], cat_preds[-1].GetName(), 'f')
        for i, gr in enumerate(cat_meass[-1]):
            gr.SetMarkerStyle(20 + 4 * j + i)
            gr.Draw('pe1')
            legend.AddEntry(gr, gr.GetName(), 'pl')

        ratio_pads[-1].cd()
        cat_pred_rats[-1].SetFillColor(fill_colors[j] - 3)
        cat_pred_rats[-1].Draw('2')
        for i, gr in enumerate(cat_meas_rats[-1]):
            gr.SetMarkerStyle(20 + 4 * j + i)
            gr.Draw('pe1')
    main_pad.cd()
    legend.Draw()

    canv.cd()
    cut_labels.DrawLatex(0.80, 0.015, 'E_{T}^{#gamma} (GeV)')

    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.pdf')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.eps')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.png')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.gif')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.root')
Ejemplo n.º 18
0
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')
  subscript = 'SR' if 'Resonant' in plottitle else 'FC'
  coupling = '0.1' if 'Resonant' in plottitle else '0.25'
  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)
    if 'Resonant' in plottitle:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l')
    else:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l')
#    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')
  if not BLIND:
    gx = graphOne if scale else graphXsec
    obslimit = findIntersect(graphObs,gx,xaxis[0],xaxis[-1])
    if obslimit:
      obslimit.SetMarkerStyle(29); obslimit.SetMarkerSize(3)
      obslimit.Draw('p same')
    explimit = findIntersect(graphCent,gx,xaxis[0],xaxis[-1])
    if explimit:
      explimit.SetMarkerStyle(30); explimit.SetMarkerSize(3)
      explimit.Draw('p same')
  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} = %s"%coupling)
      label.DrawLatex(0.19,0.64,"m_{#chi}=100 GeV")
    else:
      label.DrawLatex(0.19,0.7,"a_{FC} = b_{FC} = %s"%coupling)
      label.DrawLatex(0.19,0.64,"m_{#chi}=10 GeV")
  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 compareMassRes(trackType):

    file2016BB = open("default/MassResolutionVsMass_%s_BB.pkl" % trackType,
                      "rb")
    file2016BE = open("default/MassResolutionVsMass_%s_BE.pkl" % trackType,
                      "rb")
    file2017BB = open("cruijff/MassResolutionVsMass_%s_BB.pkl" % trackType,
                      "rb")
    file2017BE = open("cruijff/MassResolutionVsMass_%s_BE.pkl" % trackType,
                      "rb")
    fileCBB = open("crystal/MassResolutionVsMass_%s_BB.pkl" % trackType, "rb")
    fileCBE = open("crystal/MassResolutionVsMass_%s_BE.pkl" % trackType, "rb")

    results2016BB = pickle.load(file2016BB)
    results2016BE = pickle.load(file2016BE)
    results2017BB = pickle.load(file2017BB)
    results2017BE = pickle.load(file2017BE)
    resultsCBB = pickle.load(fileCBB)
    resultsCBE = pickle.load(fileCBE)

    graph2016BB = getGraph(results2016BB, "DCBBB")
    graph2016BE = getGraph(results2016BE, "DCBBE")
    graph2017BB = getGraph(results2017BB, "CruijffBB")
    graph2017BE = getGraph(results2017BE, "CruijffBE")
    graphCBB = getGraph(resultsCBB, "CBB")
    graphCBE = getGraph(resultsCBE, "CBE")

    ratioBB = getRatio(results2016BB, results2017BB, "ratioBB")
    ratioBE = getRatio(results2016BE, results2017BE, "ratioBE")
    ratioCBB = getRatio(results2016BB, resultsCBB, "ratioCBB")
    ratioCBE = getRatio(results2016BE, resultsCBE, "ratioCBE")

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.08
    if trackType == "Inner":
        xMax = 0.2
    if trackType == "Outer":
        xMax = 0.4

    plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution")

    graph2016BB.Draw("samepe")
    graph2017BB.Draw("samepe")
    graphCBB.Draw("samepe")
    graph2017BB.SetLineColor(kRed)
    graph2017BB.SetMarkerColor(kRed)
    graphCBB.SetLineColor(kBlue)
    graphCBB.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016BB, "Cruijff", "l")
    leg.AddEntry(graph2017BB, "Double CB", "l")
    leg.AddEntry(graphCBB, "Crystal Ball", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBB.SetLineColor(kRed)
    ratioCBB.SetLineColor(kBlue)

    ratioPad.DrawFrame(0, 0.5, 6000, 1.5, ";ratio")

    ratioBB.Draw("samepe")
    ratioCBB.Draw("samepe")

    canv.Print("massResolutionCompareFunc_%s_BB.pdf" % trackType)

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.08
    if trackType == "Inner":
        xMax = 0.2
    if trackType == "Outer":
        xMax = 0.4

    plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution")

    graph2016BE.Draw("samepe")
    graph2017BE.Draw("samepe")
    graphCBE.Draw("samepe")
    graph2017BE.SetLineColor(kRed)
    graph2017BE.SetMarkerColor(kRed)
    graphCBE.SetLineColor(kBlue)
    graphCBE.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BE" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016BE, "Cruijff", "l")
    leg.AddEntry(graph2017BE, "Double CB", "l")
    leg.AddEntry(graphCBE, "Crystal Ball", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBE.SetLineColor(kRed)
    ratioCBE.SetLineColor(kBlue)

    ratioPad.DrawFrame(0, 0.5, 6000, 1.5, ";;ratio")

    ratioBE.Draw("samepe")
    ratioCBE.Draw("samepe")

    canv.Print("massResolutionCompareFunc_%s_BE.pdf" % trackType)
Ejemplo n.º 20
0
def SAME3VsLumi(g1, g2, g3, title, ptype, lineMC1, lineDATA1, lineMC2,
                lineDATA2, lineMC3, lineDATA3, DoInclusive, dataPeriod):
    canvas = makeCMSCanvas(str(random.random()), "canvas", 900, 700)
    canvas.cd()
    graph2 = copy.deepcopy(g2)
    graph3 = copy.deepcopy(g3)
    graph2.SetMarkerColor(kBlue)  #electrons
    graph3.SetMarkerColor(kRed)  #muons
    multigraph = TMultiGraph()
    if (DoInclusive):
        graph1 = copy.deepcopy(g1)
        multigraph.Add(graph1, "AP")
    multigraph.Add(graph2, "AP")
    multigraph.Add(graph3, "AP")
    multigraph.Draw("AP")
    TGaxis.SetMaxDigits(2)
    TGaxis.SetExponentOffset(-0.05, 0.02, "y")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetYaxis().SetTitleOffset(1.4)
    if (ptype == "Zmass"):
        multigraph.GetYaxis().SetTitle("M_{Z} [GeV]")
        # multigraph.GetYaxis().SetTitle("M_{l^{+}l^{-}} [GeV]")
        multigraph.SetMaximum(max(multigraph.GetHistogram().GetMaximum(),
                                  91.4))
        multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),
                                  89.6))
    elif (ptype == "Zwidth"):
        multigraph.GetYaxis().SetTitle("#Gamma_{Z} [GeV]")
    elif (ptype == "Zmult"):
        multigraph.GetYaxis().SetTitle("#Z / fb^{-1}")
        if (not DoInclusive):
            multigraph.SetMaximum(
                max(multigraph.GetHistogram().GetMaximum(),
                    60000.))  # set y axis minimum at 60000.
            multigraph.SetMinimum(0.)  # set y axis minimum at 0.
            # multigraph.SetMaximum(60000.)  #second type: vs 2016 plots
            # multigraph.SetMinimum(25000.)
    printLumiPrelOut(canvas)

    # Draw legend
    legend = TLegend(0.93, 0.84, 0.99, 0.93)
    if (DoInclusive):
        #legend.AddEntry(graph1,"inclusive","P")
        legend.AddEntry(graph1, "BB", "P")
        legend.AddEntry(graph2, "BE", "P")
        legend.AddEntry(graph3, "EE", "P")
    else:
        legend.AddEntry(graph2, "e^{+}e^{-}", "P")
        legend.AddEntry(graph3, "#mu^{+}#mu^{-}", "P")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()
    canvas.Update()

    # Draw letters for data-taking periods
    if (dataPeriod == "data2017"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray + 1)
        textLetters.SetTextSize(0.03)
        if (ptype == "Zmass"):
            textLetters.DrawLatex(2., gPad.GetUymin() + 0.2, "B")
            textLetters.DrawLatex(9.5, gPad.GetUymin() + 0.2, "C")
            textLetters.DrawLatex(16., gPad.GetUymin() + 0.2, "D")
            textLetters.DrawLatex(23., gPad.GetUymin() + 0.2, "E")
            textLetters.DrawLatex(36., gPad.GetUymin() + 0.2, "F")
        elif (ptype == "Zwidth"):
            textLetters.DrawLatex(2., gPad.GetUymin() + 0.3, "B")
            textLetters.DrawLatex(9.5, gPad.GetUymin() + 0.3, "C")
            textLetters.DrawLatex(16., gPad.GetUymin() + 0.3, "D")
            textLetters.DrawLatex(23., gPad.GetUymin() + 0.3, "E")
            textLetters.DrawLatex(36., gPad.GetUymin() + 0.3, "F")
        elif (ptype == "Zmult"):
            textLetters.DrawLatex(2., 260000, "B")
            textLetters.DrawLatex(9.5, 260000, "C")
            textLetters.DrawLatex(16., 260000, "D")
            textLetters.DrawLatex(23., 260000, "E")
            textLetters.DrawLatex(36., 260000, "F")

    if (dataPeriod == "data2018"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray + 1)
        textLetters.SetTextSize(0.03)
        if (ptype == "Zmass"):
            textLetters.DrawLatex(2., gPad.GetUymin() + 0.6, "Av1")
            textLetters.DrawLatex(9.5, gPad.GetUymin() + 0.6, "Av2")
            textLetters.DrawLatex(12.5, gPad.GetUymin() + 0.6, "Av3")
            textLetters.DrawLatex(15., gPad.GetUymin() + 0.6, "Bv1")
        elif (ptype == "Zwidth"):
            textLetters.DrawLatex(2., gPad.GetUymin() + 0.3, "Av1")
            textLetters.DrawLatex(9.5, gPad.GetUymin() + 0.3, "Av2")
            textLetters.DrawLatex(12.5, gPad.GetUymin() + 0.3, "Av3")
            textLetters.DrawLatex(15., gPad.GetUymin() + 0.3, "Bv1")
        elif (ptype == "Zmult"):
            textLetters.DrawLatex(2., 260000, "Av1")
            textLetters.DrawLatex(9.5, 260000, "Av2")
            textLetters.DrawLatex(12.5, 260000, "Av3")
            textLetters.DrawLatex(15., 260000, "Bv1")

    # ****
    if (dataPeriod == "data2018"):
        # draw vertical lines that divide different data taking periods
        down = gPad.GetUymin()
        up = gPad.GetUymax()

        lineAv1 = TLine(7.643, down, 7.643, up)  # Run2018Av1 up to 7.643 fb-1
        lineAv1.SetLineColor(kBlack)
        lineAv1.SetLineStyle(2)
        lineAv1.Draw()

        lineAv2 = TLine(12.441, down, 12.441,
                        up)  # Run2018Av2 up to 12.441 fb-1
        lineAv2.SetLineColor(kBlack)
        lineAv2.SetLineStyle(2)
        lineAv2.Draw()

        lineAv3 = TLine(12.863, down, 12.863,
                        up)  # Run2018Av3 up to 12.863 fb-1
        lineAv3.SetLineColor(kBlack)
        lineAv3.SetLineStyle(2)
        lineAv3.Draw()

    if (dataPeriod == "data2017"):
        # draw vertical lines that divide different data taking periods
        down = gPad.GetUymin()
        up = gPad.GetUymax()

        lineB = TLine(4.793, down, 4.793, up)  # Run2017B up to 4.793 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()

        lineC = TLine(14.549, down, 14.549, up)  # Run2017C up to 14.549 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()

        lineD = TLine(18.868, down, 18.868, up)  # Run2017D up to 18.868 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()

        lineE = TLine(28.293, down, 28.293, up)  # Run2017E up to 28.293 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()

    if (dataPeriod == "data2016"):
        # draw vertical lines that divide different data taking periods
        down = gPad.GetUymin()
        up = gPad.GetUymax()

        lineB = TLine(5.789, down, 5.789, up)  # Run2016B up to 5.789 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()

        lineC = TLine(8.366, down, 8.366, up)  # Run2016C up to 8.366 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()

        lineD = TLine(12.616, down, 12.616, up)  # Run2016D up to 12.616 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()

        lineE = TLine(16.624, down, 16.624, up)  # Run2016E up to 16.624 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()

        lineF = TLine(19.725, down, 19.725, up)  # Run2016F up to 19.725 fb-1
        lineF.SetLineColor(kBlack)
        lineF.SetLineStyle(2)
        lineF.Draw()

        lineG = TLine(27.268, down, 27.268, up)  # Run2016G up to 27.268 fb-1
        lineG.SetLineColor(kBlack)
        lineG.SetLineStyle(2)
        lineG.Draw()
    # ****

    # draw orizontal lines for MC and DATA fit
    if (ptype == "Zmass" or ptype == "Zwidth"):

        leftEnd = gPad.GetUxmin()
        rightEnd = gPad.GetUxmax()

        if (DoInclusive):
            line1 = TLine(leftEnd, lineMC1, rightEnd, lineMC1)
            line1.SetLineColor(kBlack)
            line1.SetLineStyle(1)
            line1.Draw()

            line2 = TLine(leftEnd, lineDATA1, rightEnd, lineDATA1)
            line2.SetLineColor(kBlack)
            line2.SetLineStyle(2)
            line2.Draw()

        # line for graph 2: color blue
        line3 = TLine(leftEnd, lineMC2, rightEnd, lineMC2)
        line3.SetLineColor(kBlue)
        line3.SetLineStyle(1)
        line3.Draw()

        line4 = TLine(leftEnd, lineDATA2, rightEnd, lineDATA2)
        line4.SetLineColor(kBlue)
        line4.SetLineStyle(2)
        line4.Draw()

        # line for graph 3: color red
        line5 = TLine(leftEnd, lineMC3, rightEnd, lineMC3)
        line5.SetLineColor(kRed)
        line5.SetLineStyle(1)
        line5.Draw()

        line6 = TLine(leftEnd, lineDATA3, rightEnd, lineDATA3)
        line6.SetLineColor(kRed)
        line6.SetLineStyle(2)
        line6.Draw()
    # ***

    canvas.SaveAs(title + ".root")
    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return
Ejemplo n.º 21
0
            h.SetContour(1000)
#            if vars[var] == "nSaturatedStrips_vs_lumi":
#                h.SetMaximum(1.0e-6)
#                h.SetMinimum(1.0e-7)
#                h.GetYaxis().SetRangeUser(5.0e-7, 5.0e-6)
#                c1.Update()
        else:
            c1.SetLogy(1)
            h.GetYaxis().SetTitle(vars[var][1].split(':')[0])
            h.GetXaxis().SetTitle(vars[var][1].split(':')[1])
#            h.GetXaxis().SetTitle(vars[var][1])
        latexLabel = TLatex()
        latexLabel.SetTextSize(0.75 * c1.GetTopMargin())
        latexLabel.SetNDC()
        latexLabel.SetTextFont(42)  # helvetica
        latexLabel.DrawLatex(0.27, 0.96, cut)
        c1.Print(plotdir + "/" + vars[var][0] + "_" + cut + ".png")
        c1.Print(plotdir + "/" + vars[var][0] + "_" + cut + ".pdf")
        # now with profiles for 2D
        if len(var.split(":")) > 1:
            p = h.ProfileX()
            #            if len(vars[var]) > 2:
            #                p.GetYaxis().SetRangeUser(vars[var][2][0], vars[var][2][1])
            p.GetYaxis().SetTitle(vars[var][1].split(':')[0])
            p.GetXaxis().SetTitle(vars[var][1].split(':')[1])
            p.Draw()
            c1.Print(plotdir + "/profileX_" + vars[var][0] + "_" + cut +
                     ".png")
            c1.Print(plotdir + "/profileX_" + vars[var][0] + "_" + cut +
                     ".pdf")
Ejemplo n.º 22
0
def SAME2VsLumi(g1, g2, title, ptype, dataPeriod):
    canvas = makeCMSCanvas(str(random.random()), "canvas", 900, 700)
    canvas.cd()
    graph1 = copy.deepcopy(g1)
    graph2 = copy.deepcopy(g2)
    graph1.SetMarkerColor(kBlue)  #electrons
    graph2.SetMarkerColor(kRed)  #muons
    multigraph = TMultiGraph()
    multigraph.Add(graph1, "AP")
    multigraph.Add(graph2, "AP")
    multigraph.Draw("AP")
    TGaxis.SetMaxDigits(2)
    TGaxis.SetExponentOffset(-0.06, 0.02, "y")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetYaxis().SetTitleOffset(1.4)
    if (ptype == "ISO"):
        multigraph.GetYaxis().SetTitle("Isolation")
        gPad.Modified()
        multigraph.SetMinimum(0.5 * gPad.GetUymin())
        multigraph.SetMaximum(1.5 * gPad.GetUymax())
    elif (ptype == "SIP"):
        multigraph.GetYaxis().SetTitle("SIP")
        multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(), 1.))
        multigraph.SetMaximum(max(multigraph.GetHistogram().GetMinimum(), 2.2))

        min(multigraph.GetHistogram().GetMinimum(), 1.)
    printLumiPrelOut(canvas)

    # Draw legend
    legend = TLegend(0.93, 0.84, 0.99, 0.93)
    legend.AddEntry(graph1, "e^{+}e^{-}", "P")
    legend.AddEntry(graph2, "#mu^{+}#mu^{-}", "P")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()
    canvas.Update()

    # Draw letters for data-taking periods
    if (dataPeriod == "data2017"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray + 1)
        textLetters.SetTextSize(0.03)
        if (ptype == "ISO"):
            textLetters.DrawLatex(2., 0.8 * gPad.GetUymax(), "B")
            textLetters.DrawLatex(9.5, 0.8 * gPad.GetUymax(), "C")
            textLetters.DrawLatex(16., 0.8 * gPad.GetUymax(), "D")
            textLetters.DrawLatex(23., 0.8 * gPad.GetUymax(), "E")
            textLetters.DrawLatex(36., 0.8 * gPad.GetUymax(), "F")
        elif (ptype == "SIP"):
            textLetters.DrawLatex(2., 1.5, "B")
            textLetters.DrawLatex(9.5, 1.5, "C")
            textLetters.DrawLatex(16., 1.5, "D")
            textLetters.DrawLatex(23., 1.5, "E")
            textLetters.DrawLatex(36., 1.5, "F")

    if (dataPeriod == "data2018"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray + 1)
        textLetters.SetTextSize(0.03)
        if (ptype == "ISO"):
            textLetters.DrawLatex(2., 0.8 * gPad.GetUymax(), "Av1")
            textLetters.DrawLatex(9.5, 0.8 * gPad.GetUymax(), "Av2")
            textLetters.DrawLatex(12.5, 0.8 * gPad.GetUymax(), "Av3")
            textLetters.DrawLatex(15., 0.8 * gPad.GetUymax(), "Bv1")
        elif (ptype == "SIP"):
            textLetters.DrawLatex(2., 1.5, "Av1")
            textLetters.DrawLatex(9.5, 1.5, "Av2")
            textLetters.DrawLatex(12.5, 1.5, "Av3")
            textLetters.DrawLatex(15., 1.5, "Bv1")

    # ****
    if (dataPeriod == "data2018"):
        # draw vertical lines that divide different data taking periods
        down = gPad.GetUymin()
        up = gPad.GetUymax()

        lineAv1 = TLine(7.643, down, 7.643, up)  # Run2018Av1 up to 7.643 fb-1
        lineAv1.SetLineColor(kBlack)
        lineAv1.SetLineStyle(2)
        lineAv1.Draw()

        lineAv2 = TLine(12.441, down, 12.441,
                        up)  # Run2018Av2 up to 12.441 fb-1
        lineAv2.SetLineColor(kBlack)
        lineAv2.SetLineStyle(2)
        lineAv2.Draw()

        lineAv3 = TLine(12.863, down, 12.863,
                        up)  # Run2018Av3 up to 12.863 fb-1
        lineAv3.SetLineColor(kBlack)
        lineAv3.SetLineStyle(2)
        lineAv3.Draw()

    # ****
    if (dataPeriod == "data2017"):
        # draw vertical lines that divide different data taking periods
        down = gPad.GetUymin()
        up = gPad.GetUymax()

        lineB = TLine(4.793, down, 4.793, up)  # Run2017B up to 4.793 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()

        lineC = TLine(14.549, down, 14.549, up)  # Run2017C up to 14.549 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()

        lineD = TLine(18.868, down, 18.868, up)  # Run2017D up to 18.868 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()

        lineE = TLine(28.293, down, 28.293, up)  # Run2017E up to 28.293 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()

    # ****
    if (dataPeriod == "data2016"):
        # draw vertical lines that divide different data taking periods
        down = gPad.GetUymin()
        up = gPad.GetUymax()

        lineB = TLine(5.789, down, 5.789, up)  # Run2016B up to 5.789 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()

        lineC = TLine(8.366, down, 8.366, up)  # Run2016C up to 8.366 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()

        lineD = TLine(12.616, down, 12.616, up)  # Run2016D up to 12.616 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()

        lineE = TLine(16.624, down, 16.624, up)  # Run2016E up to 16.624 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()

        lineF = TLine(19.725, down, 19.725, up)  # Run2016F up to 19.725 fb-1
        lineF.SetLineColor(kBlack)
        lineF.SetLineStyle(2)
        lineF.Draw()

        lineG = TLine(27.268, down, 27.268, up)  # Run2016G up to 27.268 fb-1
        lineG.SetLineColor(kBlack)
        lineG.SetLineStyle(2)
        lineG.Draw()
    # ****

    canvas.SaveAs(title + ".root")
    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return
Ejemplo n.º 23
0
        graphs_L1[j].SetLineStyle(2)
        if i==imin:
            graphs_L1[j].Draw("APL")
        else:
            graphs_L1[j].Draw("PL")

leg_L1.Draw()
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextColor(1)
latex.SetTextFont(42)
latex.SetTextAlign(33)
latex.SetTextSize(0.04)
latex.SetTextFont(62)
latex.DrawLatex(0.30, 0.96, "GIF++")
etichetta = TLatex()
etichetta.SetNDC()
etichetta.SetTextSize(0.04)
etichetta.SetTextColor(4)
etichetta.SetTextFont(102)
etichetta.DrawLatex(0.45, 0.93, "SL1_L1 HV scan")
#etichetta.DrawLatex(0.45, 0.8, "#splitline{SL1_L1 threshold scan}{Runs: "+str(run_interval)+"}")
can_HV_scan_SL1_L1.Update()
can_HV_scan_SL1_L1.Print(outpath + "Compare_HV_scan_SL1_L1.png")
can_HV_scan_SL1_L1.Print(outpath + "Compare_HV_scan_SL1_L1.pdf")

##Efficiency SL1_L4    
can_HV_scan_SL1_L4 = TCanvas("can_compare_HV_scan_SL1_L4","can_compare_HV_scan_SL1_L4", 1000, 800)
can_HV_scan_SL1_L4.SetGrid()
can_HV_scan_SL1_L4.cd()
Ejemplo n.º 24
0
def plotUpperLimits(labels, values, prefix, outputLabel):

    N = len(labels)
    yellow = TGraph(2 * N)
    green = TGraph(2 * N)
    median = TGraph(N)

    up2s = []
    upm = []
    text_limits = open("TextLimits%s" % (prefix) + outputLabel + ".txt", "w")
    for i in range(N):
        file_name = "higgsCombine" + prefix + labels[
            i] + ".AsymptoticLimits.mH120.root"
        print "filename:  ", file_name
        limit = getLimits(file_name)
        up2s.append(limit[4])
        upm.append(limit[2])
        yellow.SetPoint(i, values[i], limit[4])  # + 2 sigma
        green.SetPoint(i, values[i], limit[3])  # + 1 sigma
        median.SetPoint(i, values[i], limit[2])  #    median
        green.SetPoint(2 * N - 1 - i, values[i], limit[1])  # - 1 sigma
        yellow.SetPoint(2 * N - 1 - i, values[i], limit[0])  # - 2 sigma
        text_limits.write("bdt %.2f     median exp %.2f\n" %
                          (values[i], limit[2]))

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetGrid()
    c.SetFrameLineWidth(3)
    c.SetTickx()
    c.SetTicky()
    c.cd()
    frame = c.DrawFrame(1.4, 0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()

    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(False)
    frame.GetYaxis().SetTitle("B(#tau #rightarrow #mu#mu#mu) #times 10^{-7}")
    frame.GetXaxis().SetTitle("bdt")

    frame.SetMinimum(0.5)
    frame.SetMaximum(10.)

    frame.GetXaxis().SetLimits(min(values), max(values) * 1.2)

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    #    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    #    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')
    median.Draw()

    CMS_lumi.CMS_lumi(c, 13, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.76
    y1 = 0.60
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median, "Asymptotic CL_{s} expected", 'L')
    #    legend.AddEntry(green, "#pm 1 std. deviation",'f')
    #    legend.AddEntry(yellow,"#pm 2 std. deviation",'f')

    legend.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextAngle(0)
    latex.SetTextFont(42)
    latex.SetTextAlign(31)

    latex.DrawLatex(0.57, 0.85, prefix)
    latex.Draw('same')
    print " "
    c.SaveAs("Limit" + prefix + outputLabel + ".png")
    c.Close()
    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)

posX_ = 0
posX_ = l + relPosX * (1 - l - r)
posY_ = 1 - t - relPosY * (1 - t - b)
posX_ = l + relPosX * (1 - l - r)
posY_ = 1 - t + lumiTextOffset * t
alignX_ = 1
alignY_ = 1
align_ = 10 * alignX_ + alignY_
latex.SetTextFont(extraTextFont)
Ejemplo n.º 26
0
def plot_BDT(channel, var, massPoint, bin, low, high, ylabel, xlabel, save, nBtags = -1, setLog = False, finalcuts = False):

    if (channel == 'electron'):      
        cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && elec_1_pt_WprimeCalc > 32 && abs(elec_1_eta_WprimeCalc) < 2.5 && elec_1_RelIso_WprimeCalc < 0.1 && corr_met_WprimeCalc > 20' 
        #cut = 'jet_0_pt_WprimeCalc >= 100 && jet_1_pt_WprimeCalc >= 40 && elec_1_pt_WprimeCalc > 30 && abs(elec_1_eta_WprimeCalc) < 2.5 && elec_1_RelIso_WprimeCalc < 0.1 && corr_met_WprimeCalc > 35' 

    if (channel == 'muon'):      
        cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && muon_1_pt_WprimeCalc > 26 && abs(muon_1_eta_WprimeCalc) < 2.1 && muon_1_RelIso_WprimeCalc < 0.12 && corr_met_WprimeCalc > 20'
        #cut = 'jet_0_pt_WprimeCalc >= 100 && jet_1_pt_WprimeCalc >= 40 && muon_1_pt_WprimeCalc > 26 && abs(muon_1_eta_WprimeCalc) < 2.1 && muon_1_RelIso_WprimeCalc < 0.12 && corr_met_WprimeCalc > 35' 


    if finalcuts: cut+= '&& BestTop_LjetsTopoCalcNew > 130 && BestTop_LjetsTopoCalcNew < 210 &&  BestTop_Pt_LjetsTopoCalcNew > 75  && Jet1Jet2_Pt_LjetsTopoCalcNew > 100'   
    njets = ""

    if nBtags == -1:
        cutbtag = ''
        save = save     
    if nBtags == 0:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc + jet_2_tag_WprimeCalc + jet_3_tag_WprimeCalc + jet_4_tag_WprimeCalc + jet_5_tag_WprimeCalc + jet_6_tag_WprimeCalc + jet_7_tag_WprimeCalc + jet_8_tag_WprimeCalc + jet_9_tag_WprimeCalc) == 0 )'
        save = save + '_0bTags'
        njets = "N_{b tags} = 0"
    if nBtags == 1:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc) == 1)'
        save = save + '_1bTags'
        njets = "N_{b tags} = 1"
    if nBtags == 2:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc) >= 1 ) '
        save = save + '_GE1bTags'
        njets = "N_{b tags} #geq 1"


    cutwbb = ' && n_Bjets_WprimeCalc > 0' # Wb(b)
    cutwcc = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc>0' # Wc(c)
    cutwjj = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc==0' # W+light
    #cutwbb = ' ' # Wb(b)
    #cutwcc = ' ' # Wc(c)
    #cutwjj = ' ' # W+light
                                                                                                                   
    SFWjmu = 1.08*0.85
    SFWcmu = 1.06*0.92*1.66
    SFWbmu = 1.06*0.92*1.21
    #SFWjmu = 1.0
    #SFWcmu = 1.0
    #SFWbmu = 1.0

    WjjHist = TH1D('WjjHist', 'WjjHist', bin,low,high)
    WccHist = TH1D('WccHist', 'WccHist', bin,low,high)
    WbbHist = TH1D('WbbHist', 'WbbHist', bin,low,high)

    Variables = {}
    efficiency = {}
   
    BkgList = []

    for Type in Samples:

        #print channel,' ',Type

        if (Type.endswith('_el') and channel == 'muon'): continue
        if (Type.endswith('_mu') and channel == 'electron'): continue
        if (not Type.startswith(massPoint) ): continue

        Variables[Type] = TH1D(Type+var+channel, Type+var+channel, bin, low, high)
        histName = Type+var+channel
     
        if (channel == 'electron'): chan = '_el'
        if (channel == 'muon'): chan = '_mu'

        if (channel == 'electron'): weight = 'weight_PU_ABC_PileUpCalc*weight_ElectronEff_WprimeCalc'
        if (channel == 'muon'): weight = 'weight_PU_ABC_PileUpCalc*weight_MuonEff_WprimeCalc'
        
        if ((not Type == massPoint+massPoint+chan) and (not Type == massPoint+'_data'+chan)): BkgList.extend([Type])

        if Type.endswith('wjets'+chan):
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "("+weight+")*(" + str(SFWjmu) + ")*(" + cut + cutbtag + cutwjj + ")", 'goff')
            Trees[Type].Draw(var + " >> " + "WbbHist","("+weight+")*(" + str(SFWbmu) + ")*(" + cut + cutbtag + cutwbb + ")", 'goff')
            Trees[Type].Draw(var + " >> " + "WccHist","("+weight+")*(" + str(SFWcmu) + ")*(" + cut + cutbtag + cutwcc + ")", 'goff')
            #print 'Raw Wjj ',Variables['WJets'].Integral()
            Variables[Type].Add(WbbHist)
            #print 'Raw Wjj + Wbb ',Variables['WJets'].Integral()
            Variables[Type].Add(WccHist) 
            #print 'Raw Wjj + Wbb + Wcc',Variables['WJets'].Integral()

        elif Type.endswith('data'+chan):
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "(" + cut + cutbtag + ")", 'goff')
        else:
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "("+weight+")*(" + cut + cutbtag + ")", 'goff')
            
        if (not Type.endswith('data'+chan)):

            SF = 1.0
            if (channel == 'electron'):
                lumi = lumi_el
            if (channel == 'muon'):
                lumi = lumi_mu

            if (Type.startswith(massPoint+'_'+massPoint)): SF *= 20
            #print 'EVENTS Before Scaling FOR ',Type,' = ',Variables[Type].Integral()
            #print 'Pre Events before scaling for ',Type,' = ',VariablesPre[Type].Integral()
            #print str(SF),' ',str(lumi),' ',str(xsec_norm[Type]),' ',str(Nevents[Type])

            if Variables[Type].Integral() != 0:
                #print Type,' Lumi scaling: ',str(SF*lumi*xsec[Type]/Nevents[Type])
                Variables[Type].Scale ( SF*Yield[Type]/Variables[Type].Integral() ) 
                efficiency[Type] = Variables[Type].Integral()/Nevents[Type]
            else:
                efficiency[Type] = 0

    
    Variables[massPoint+'_ttbar'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_s'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_bs'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_t'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_bt'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_tw'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_btw'+chan].SetFillColor(ROOT.kRed-7)

    Variables[massPoint+'_s'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_bs'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_t'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_bt'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_tw'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_btw'+chan].SetLineColor(ROOT.kRed-7)

    Variables[massPoint+'_wjets'+chan].SetFillColor(ROOT.kGreen-3)
    Variables[massPoint+'_zjets'+chan].SetFillColor(ROOT.kGreen-3)
    Variables[massPoint+'_ww'+chan].SetFillColor(ROOT.kGreen-3)

    Variables[massPoint+'_zjets'+chan].SetLineColor(ROOT.kGreen-3)
    Variables[massPoint+'_ww'+chan].SetLineColor(ROOT.kGreen-3)
    
    Variables[massPoint+'_ttbar'+chan].SetLineWidth(2)
    Variables[massPoint+'_wjets'+chan].SetLineWidth(2)

    Variables[massPoint+'_'+massPoint+chan].SetLineColor(1)
    Variables[massPoint+'_'+massPoint+chan].SetLineWidth(2)
    Variables[massPoint+'_'+massPoint+chan].SetLineStyle(6)

    stack = THStack('a', 'a')
    added = TH1D('a', 'a',bin,low,high)
    topadded  = TH1D('topadded', 'topadded', bin, low, high)
    wjetsadded = TH1D('wjetsadded', 'wjetsadded',bin,low,high)

    wjetsadded = Variables[massPoint+'_wjets'+chan].Clone()
    wjetsadded.Add(Variables[massPoint+'_ww'+chan])
    wjetsadded.Add(Variables[massPoint+'_zjets'+chan])

    topadded = Variables[massPoint+'_ttbar'+chan].Clone()
    topadded.Add(Variables[massPoint+'_s'+chan])
    topadded.Add(Variables[massPoint+'_bs'+chan])
    topadded.Add(Variables[massPoint+'_t'+chan])
    topadded.Add(Variables[massPoint+'_bt'+chan])
    topadded.Add(Variables[massPoint+'_tw'+chan])
    topadded.Add(Variables[massPoint+'_btw'+chan])

    wjetsadded.SetFillColor(ROOT.kGreen-3)
    wjetsadded.SetLineColor(1)
    wjetsadded.SetLineWidth(2)
    topadded.SetFillColor(ROOT.kRed-7)
    topadded.SetLineColor(1)
    topadded.SetLineWidth(2)

    stack.Add(wjetsadded)
    stack.Add(topadded)
    added.Add(wjetsadded)  
    added.Add(topadded)

    print 'Data: ',Variables[massPoint+'_data'+chan].Integral(),' Background: ',added.Integral(),' Data/Background: ',Variables[massPoint+'_data'+chan].Integral()/added.Integral()

    lumi_error = 0.022
    ttbar_error = 0.15
    wjets_error = 0.20
    other_error = 0.20

    uncert_list = []
    lumiband = added.Clone();
    
    for hbin in range(0,lumiband.GetNbinsX()+1): 

        uncert_lumi = 0 
        uncert_xsec = 0
        uncert_stat = 0
 
        for i in BkgList:

            error = 0
             
            if i in xsec.keys(): 
                if (i.startswith(massPoint+'_t') or i.startswith(massPoint+'_b') or i.startswith(massPoint+'_s')): 
                    error = ttbar_error
                    uncert_lumi += (efficiency[i]*xsec[i])**2 
                    uncert_xsec += (Variables[i].GetBinContent(hbin+1)*error)**2
                    uncert_stat += Variables[i].GetBinError(hbin+1)**2
                elif (i.startswith(massPoint+'_w') or i.startswith(massPoint+'_z')):
                    error = wjets_error
                    uncert_lumi += (efficiency[i]*xsec[i])**2 
                    uncert_xsec += (Variables[i].GetBinContent(hbin+1)*error)**2         
                    uncert_stat += Variables[i].GetBinError(hbin+1)**2

        #print 'uncert_lumi: ',uncert_lumi,' uncert_xsec ',uncert_xsec,' uncert_stat ',uncert_stat
        uncert = sqrt( (lumi_error**2)*uncert_lumi + uncert_xsec + uncert_stat )

        if lumiband.GetBinContent(hbin+1) != 0:
            dummy = 1.0
            #print lumiband.GetBinContent(hbin+1),'+/-',uncert,'(',100*uncert/lumiband.GetBinContent(hbin+1),'%)'
        lumiband.SetBinError(hbin+1,uncert);
        added.SetBinError(hbin+1,uncert);
        uncert_list . append(uncert)
    
    #gStyle.SetHatchesSpacing(2.0);
    gStyle.SetHatchesLineWidth(1);
            
    lumiband.SetFillStyle(3344);
    #lumiband.SetFillStyle(3001);
    lumiband.SetFillColor(1);
      
    legend = TLegend(.60,.70,.90,.90)
    legend . AddEntry( Variables[massPoint+'_data'+chan], 'Data' , "lp")
    legend . AddEntry( Variables[massPoint+'_ttbar'+chan], "t#bar{t} + Single-Top", "f")
    legend . AddEntry( Variables[massPoint+'_wjets'+chan], "W#rightarrowl#nu + Z/#gamma*#rightarrowl^{+}l^{-} + VV" , "f")
 
    if (massPoint.endswith('R')): coupling = 'R'
    if (massPoint.endswith('L')): coupling = 'L'
    if (massPoint.endswith('RL')): coupling = 'RL'

    massval = copy.copy(massPoint)
    massval = massval.lstrip('wp')
    massval = massval.rstrip('00'+coupling)
    if (len(massval)==1): massval = '0'+massval
    massval = massval[0]+'.'+massval[1]

    legend . AddEntry( Variables[massPoint+'_'+massPoint+chan], "W'_{"+coupling+"} x 20, m="+massval+" TeV", "l")
    legend . AddEntry( lumiband , "Uncertainty" , "f")

    c4 = TCanvas("c4","c4", 1000, 800)
    
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)
    stack.SetMaximum( 2*stack.GetMaximum() ) 
    if setLog:
        c4.SetLogy()
        stack.SetMaximum( stack.GetMaximum()  +  30*stack.GetMaximum() ) 

    stack.SetMinimum(0.1 )
    #stack.SetMarkerSize(0)
    stack.Draw("") 
    stack.GetYaxis().CenterTitle() 
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetXaxis().SetLabelSize(0)
    #stack.GetXaxis().SetTitle(xlabel)
    lumiband.Draw("samee2")
    #lumiband.Draw("esame")
    
    legend.SetShadowColor(0);
    legend.SetFillColor(0);
    legend.SetLineColor(0);
    legend.Draw("same")    

    if (Variables[massPoint+'_data'+chan].GetBinContent(bin+1)>0):
        print "Overflow for ",massPoint+"_"+channel," data "
    Variables[massPoint+'_data'+chan].SetMarkerStyle(20)
    Variables[massPoint+'_data'+chan].Draw('SAMES:E1')
 
    Variables[massPoint+'_'+massPoint+chan].Draw("same")

    latex2 = TLatex()
    latex2.SetNDC()
    latex2.SetTextSize(0.04)
    latex2.SetTextAlign(31) # align right
    if channel == ('electron'): 
        latex2.DrawLatex(0.87, 0.95, "CMS Preliminary, "+lumiPlot_el+" fb^{-1} at #sqrt{s} = 8 TeV");
    if channel == ('muon'): 
        latex2.DrawLatex(0.87, 0.95, "CMS Preliminary, "+lumiPlot_mu+" fb^{-1} at #sqrt{s} = 8 TeV");

    latex3 = TLatex()
    latex3.SetNDC()
    latex3.SetTextSize(0.04)
    latex3.SetTextAlign(31) # align right

    if (channel == 'electron'):
        latex3.DrawLatex(0.47, 0.85, "e+jets " + njets);   
    if (channel == 'muon'):
        latex3.DrawLatex(0.47, 0.85, "#mu+jets " + njets);   
 
    latex4 = TLatex()
    latex4.SetNDC()
    latex4.SetTextSize(0.03)
    latex4.SetTextAlign(22) # align right
    latex4.SetTextAngle(90) # align right
    #latex4.DrawLatex(0.905, 0.56, "overflow")
    
    Pull  = TH1D('Pull', 'Pull', bin, low, high)  
    Pull = Variables[massPoint+'_data'+chan].Clone();
    Pull.Add(added,-1)
    Pull.Divide(added)

    for i in range(bin):
        i += 1
        #print i+1,' ',added.GetBinContent(i+1)
        if (Pull.GetBinContent(i+1) != 0 and Pull.GetBinError(i+1) != 0):
            Pull.SetBinContent(i+1,Pull.GetBinContent(i+1)/Pull.GetBinError(i+1))
        else: Pull.SetBinContent(i+1,0)

    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    pad.SetTopMargin(0.7)
    pad.SetFillColor(0)
    pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw()
    pad.cd(0)
    pad.SetRightMargin(0.06)

    Pull.SetMarkerStyle(20)
    Pull.SetMaximum(3.0 )
    Pull.SetMinimum(-3.0)
    Pull.SetFillColor(2)
    Pull.GetXaxis().SetTitle(xlabel)
    Pull.GetYaxis().SetTitleSize(0.04)
    Pull.GetYaxis().SetTitle('#sigma(Data-MC)')
    Pull.SetMarkerSize(0.7)
    Pull.GetYaxis().SetNdivisions(5);
    Pull.Draw("HIST")
    
    c4.SaveAs('Wprime_Plots/StackedHisto_' + save + '.pdf')
      
    del c4
    #del pad
    del stack
    del Variables
Ejemplo n.º 27
0
#expected95.SetMinimum(0.0001);
expected95.SetMaximum(0.0056)
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()
latex2.SetTextSize(0.04)
latex2.SetTextAlign(31)  # align right
latex2.DrawLatex(0.87, 0.95, "19.37 fb^{-1} at #sqrt{s} = 8 TeV")

latex4 = TLatex()
latex4.SetNDC()
latex4.SetTextSize(0.04)
latex4.SetTextAlign(31)  # align right
latex4.DrawLatex(0.80, 0.87, "")

legend = TLegend(.53, .637, .84, .84)
legend.AddEntry(observed_p, '95% C.L. Observed', "lp")
    gr_extrapol.SetLineWidth(1)
    gr_extrapol.SetLineColor(920)  # kGray

    frame = TH1F("frame", "; PU; Trigger rate [kHz]", 100, 0, 350)
    frame.SetMinimum(0)
    frame.SetMaximum(25)
    frame.Draw()

    #gr_denom.Draw("P")
    gr_numer.Draw("P")
    gr_extrapol.Draw("C")

    for i, x in enumerate(rates):
        pu, emtf_rate, emtf_rate_err, emtf2026_rate, emtf2026_rate_err = x
        #tlatex.DrawLatex(pu - 3, emtf_rate + 4, "%.1f" % emtf_rate)
        tlatex.DrawLatex(pu - 3, emtf2026_rate + 2, "%.1f" % emtf2026_rate)

    def draw_cms_lumi_1():
        tlatexCMS1.SetTextSize(0.75 * 0.05)
        tlatexCMS2.SetTextSize(0.60 * 0.05)
        tlatexCMS3.SetTextSize(0.60 * 0.05)
        tlatexCMS1.DrawLatex(0.164, 0.965, 'CMS')
        tlatexCMS2.DrawLatex(0.252, 0.965, 'Phase-2 Simulation')
        tlatexCMS3.DrawLatex(0.675, 0.965, '<PU>=140, 200, 250, 300')

    draw_cms_lumi_1()
    imgname = "emtf_ptmin20_qmin12_pu"
    gPad.Print("figures_perf/" + imgname + "_omtf" + ".png")
    gPad.Print("figures_perf/" + imgname + "_omtf" + ".pdf")
    donotdelete.append([frame, gr_denom, gr_numer])
Ejemplo n.º 29
0
    def makeCertifyPlot(self, trigger, run, lumi_info):
        if not self.fits.has_key(trigger):
            # Missing the fit for this trigger, so skip it
            return False
        elif not self.plotting_data.has_key(trigger):
            print "\tERROR: Trigger not found in plotting data, %s" % trigger
            return False
        elif not self.plotting_data[trigger].has_key(run):
            print "\tERROR: Trigger is missing run, %s" % run
            return False
        else:
            data = self.plotting_data[trigger][
                run]  # ([x_vals], [y_vals], [status])

        maximumRR = array.array('f')
        maximumVals = array.array('f')
        minimumVals = array.array('f')

        yVals = array.array('f')
        xVals = array.array('f')

        xVals, yVals = self.fitFinder.getGoodPoints(data[0], data[1])
        if len(xVals) > 0:
            maximumRR.append(max(yVals))
            maximumVals.append(max(xVals))
            minimumVals.append(min(xVals))

        if len(maximumRR) > 0: max_yaxis_value = max(maximumRR)
        else: return False

        if len(maximumVals) > 0:
            max_xaxis_val = max(maximumVals)
            min_xaxis_val = min(minimumVals)
        else:
            return False

        if max_xaxis_val == 0 or max_yaxis_value == 0: return

        canvas = TCanvas(self.var_X, self.var_Y, 1000, 600)
        canvas.SetName(trigger + "_" + self.var_X + "_vs_" + self.var_Y)

        best_fit_type, best_fit = self.fitFinder.getBestFit(self.fits[trigger])
        predictionTGraph = self.getPredictionGraph(best_fit, min_xaxis_val,
                                                   max_xaxis_val,
                                                   max_yaxis_value, trigger,
                                                   run, lumi_info)
        num_LS = len(data[0])
        legend = self.getLegend(num_entries=2)
        plotTGraph = TGraph(num_LS, data[0], data[1])

        graph_color = self.getColorMap()[run]

        plotTGraph.SetMarkerStyle(7)
        plotTGraph.SetMarkerSize(1.0)
        plotTGraph.SetLineColor(graph_color)
        plotTGraph.SetFillColor(graph_color)
        plotTGraph.SetMarkerColor(graph_color)
        plotTGraph.SetLineWidth(2)
        #plotTGraph.GetXaxis().SetTitle(self.name_X+" "+self.units_X)
        plotTGraph.GetXaxis().SetTitle(self.label_X)
        plotTGraph.GetXaxis().SetLimits(0, 1.1 * max_xaxis_val)
        plotTGraph.GetYaxis().SetTitle(self.label_Y)
        plotTGraph.GetYaxis().SetTitleOffset(1.2)
        plotTGraph.SetMinimum(0)
        plotTGraph.SetMaximum(1.2 * max_yaxis_value)
        plotTGraph.SetTitle(trigger)

        plotTGraph.Draw("AP")
        canvas.Update()

        if self.bunch_map.has_key(run):
            bunches = str(self.bunch_map[run])
        else:
            bunches = "-"

        legend_str = ""
        legend_str = "%s (%s b)" % (run, bunches)
        legend.AddEntry(plotTGraph, legend_str, "f")

        legend.SetHeader("%s runs:" % 1)

        predictionTGraph.Draw("PZ3")
        canvas.Update()
        legend.AddEntry(predictionTGraph, "Fit ( %s \sigma )" % (self.sigmas))

        # 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()

        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
Ejemplo n.º 30
0
    l = TLegend(0.35, 0.70, 0.7, 0.9, "", "brNDC")
    l.SetBorderSize(0)
    l.SetFillColor(0)
    l.SetTextSize(.03)
    l.AddEntry(hist_Data, "SS Data ", "p")
    l.AddEntry(outHist[i], "BG Est.(Shape from Relaxed Tau Iso.)", "lpf")
    #    l.AddEntry(hist_Estimation_ff, "BG Est.(both tau Iso Reverted)", "lpf")
    l.Draw()

    #Text in Histogram
    t = TLatex()
    t.SetNDC()
    t.SetTextFont(62)
    t.SetTextAlign(12)
    t.SetTextSize(0.03)
    t.DrawLatex(0.1, .92, "CMS Preliminary 2012")
    t.DrawLatex(0.45, .92, "#sqrt{s} = 8 TeV, L = 19.7 fb^{-1}")
    t.DrawLatex(0.80, .92, "ll#tau#tau")
    #    t.DrawLatex(0.5, .60, "Data, SS, 10 GeV Tau LooseIso")
    #    t.DrawLatex(0.5, .52, "Data = " + str(DataNormalization))
    ############### Tp Print Normalization in the plots
    #    for i in range(len(testFiles)):
    #        clr = i + 1
    #        if i == 4: clr = 7
    #        t.SetTextColor(clr)
    #        t.DrawLatex(0.5, .52-((i + 1) / 20.), outName[i] + " = " + str(outEst[i]))

    canvas.SaveAs("Compare_tauFR2.pdf")
#    canvas.SaveAs("Compare_tauFR2.eps")
#    canvas.SaveAs("Compare_tauFR2.png")