class CutFlowHistMaker(object):
    def __init__(self, dataset_manager, analysis):
        self.entries = []
        self.states = []
        self.luminosity = 0
        self.config_factory = ConfigHistFactory(dataset_manager,
            analysis + "/CutFlow",
        )
    def setLuminosity(self, lumi):
        self.luminosity = lumi
        for entry in self.entries:
            entry.setLuminosity(lumi)
    def setStates(self, states):
        self.states = states
        for entry in self.entries:
            entry.setStates(states)
    def addEntry(self, entry):
        if self.luminosity != 0:
            entry.setLuminosity(self.luminosity)
        if self.states != []:
            entry.setStates(self.states)
        self.entries.append(entry)
    def setLogFile(log_file):
        self.log_file = log_file
    def getHist(self, plot_group):
        nbins = len(self.entries)
        hist = ROOT.TH1F(plot_group, plot_group, nbins, 0, nbins)
        for i, entry in enumerate(self.entries):
            hist.SetBinContent(i+1, entry.getValue(plot_group))
            hist.GetXaxis().SetBinLabel(i+1, entry.getName())
        self.config_factory.setHistAttributes(hist, "CutFlow", plot_group)
        return hist
class CutFlowHistMaker(object):
    def __init__(self, name, dataset_manager, analysis):
        self.name = name
        self.entries = []
        self.states = []
        self.luminosity = 0
        self.config_factory = ConfigHistFactory(dataset_manager,
            analysis.split("_")[0],
        )
    def setLuminosity(self, lumi):
        self.luminosity = lumi
        for entry in self.entries:
            entry.setLuminosity(lumi)
    def setStates(self, states):
        self.states = states
        for entry in self.entries:
            entry.setStates(states)
    def addEntry(self, entry):
        if self.luminosity != 0:
            entry.setLuminosity(self.luminosity)
        if self.states != []:
            entry.setStates(self.states)
        self.entries.append(entry)
    def setLogFile(log_file):
        self.log_file = log_file
    def getHist(self, plot_group, unc, hist_file, scale_facs=False):
        nbins = len(self.entries)
        hist = ROOT.TH1D(plot_group, plot_group, nbins, 0, nbins)
        for i, entry in enumerate(self.entries):
            value, error = entry.getValue(plot_group, unc, hist_file, scale_facs)
            hist.SetBinContent(i+1, value)
            hist.SetBinError(i+1, error)
            hist.GetXaxis().SetBinLabel(i+1, entry.getName())
        self.config_factory.setHistAttributes(hist, self.name, plot_group)
        return hist
 def __init__(self, name, dataset_manager, analysis):
     self.name = name
     self.entries = []
     self.states = []
     self.luminosity = 0
     self.config_factory = ConfigHistFactory(dataset_manager,
         analysis.split("_")[0],
     )
 def __init__(self, dataset_manager, analysis):
     self.entries = []
     self.states = []
     self.luminosity = 0
     self.config_factory = ConfigHistFactory(dataset_manager,
         analysis + "/CutFlow",
     )
 def __init__(self, name, dataset_manager, analysis):
     self.name = name
     self.analysis = analysis 
     self.config_factory = ConfigHistFactory(
         dataset_manager,
         self.analysis,
     )
     self.states = "eee,eem,emm,mmm"
     self.luminosity = 1.
     self.additional_cut = ""
def main():
    args = getComLineArgs()
    ROOT.gROOT.SetBatch(True)
    ROOT.TProof.Open("workers=12")
    filelist = getListOfFiles(args.files_to_plot, args.selection)
    path = "/cms/kdlong" if "hep.wisc.edu" in os.environ["HOSTNAME"] else "/afs/cern.ch/user/k/kelong/work"
    print "MANAGER PATH IS ", path
    config_factory = ConfigHistFactory("%s/AnalysisDatasetManager" % path, args.selection, args.object_restrict)
    branches = (
        config_factory.getListOfPlotObjects()
        if args.branches == "all"
        else [x.strip() for x in args.branches.split(",")]
    )
    cut_string = args.make_cut
    (plot_path, html_path) = helper.getPlotPaths(args.selection, args.folder_name, True)
    for branch_name in branches:
        hist_stack = getStacked(
            config_factory,
            args.selection,
            filelist,
            branch_name,
            args.channels,
            not args.no_overflow,
            cut_string,
            args.luminosity,
            args.no_scalefactors,
            args.uncertainties,
        )
        if not args.no_data:
            data_hist = helper.getConfigHist(
                config_factory, "data", args.selection, branch_name, args.channels, not args.no_overflow, cut_string
            )
            with open("temp.txt", "a") as events_log_file:
                events_log_file.write("\nNumber of events in data: %i" % data_hist.Integral())
        else:
            data_hist = 0
        canvas = helper.makePlot(hist_stack, data_hist, branch_name, args)
        helper.savePlot(canvas, plot_path, html_path, branch_name, True, args)
        makeSimpleHtml.writeHTML(html_path, args.selection)
def main():
    args = getComLineArgs()
    ROOT.gROOT.SetBatch(True)

    (plot_path, html_path) = helper.getPlotPaths(args.selection,
                                                 args.folder_name, True)

    meta_info = '-'*80 + '\n' + \
        'Script called at %s\n' % datetime.datetime.now() + \
        'The command was: %s\n' % ' '.join(sys.argv) + \
        '-'*80 + '\n'

    rtfile = ROOT.TFile(args.hist_file)

    channels = args.channels.split(",")
    hist_info = {}
    hist_info["predyield"] = OrderedDict(
        {chan: [0, 0]
         for chan in channels + ["total"]})
    for branch in args.branches.split(","):
        with open("temp.txt", "w") as mc_file:
            mc_file.write(meta_info)
            mc_file.write("Selection: %s" % args.selection)
            mc_file.write("\nPlotting branch: %s\n" % branch)

        plot_name = branch
        if args.append_to_name:
            plot_name += "_" + args.append_to_name
        hist_stack = ROOT.THStack("stack_postfit", "stack_postfit")
        signal_stack = ROOT.THStack("signalstack_prefit", "sig_prefit")
        data_hist = 0
        plot_groups = args.files_to_plot.split(",")
        if not args.no_data:
            plot_groups.append("data")
        if args.signal_files:
            plot_groups.extend(args.signal_files.split(","))
        isHiggs = "higgs" in args.signal_files.lower()
        for i, plot_group in enumerate(plot_groups):
            hist_info[plot_group] = OrderedDict(
                {chan: [0, 0]
                 for chan in channels + ["total"]})
            isSignal = False
            central_hist = 0
            for chan in channels:
                folder = "shapes_fit_b" if args.backgroundOnly else "shapes_fit_s"
                if i >= len(
                        args.files_to_plot.split(",")) + (not args.no_data):
                    isSignal = True
                    if plot_group != "EW-WZjj":
                        folder = "shapes_prefit"
                hist_name = "/".join([
                    folder, chan, plot_group
                    if plot_group != "wzjj-ewk_filled" else "EW-WZjj"
                ])

                hist = rtfile.Get(hist_name)
                if not hist:
                    raise RuntimeError("Error: Failed to find hist %s" %
                                       hist_name)
                if hist.InheritsFrom("TGraph"):
                    hist = histFromGraph(hist, "_".join([plot_group, chan]))
                if args.noCR:
                    hist = removeControlRegion(hist)
                if "MTWZ" in plot_name:
                    hist = rebinMTWZ(hist, hist_name, isHiggs)
                elif args.rebin:
                    hist = setBinning(hist, hist_name, args.rebin)

                if "yieldByChannel" in plot_name:
                    hist = getYieldByChannelHist(hist, chan)

                if not central_hist:
                    central_hist = hist
                    central_hist.SetName(plot_group)
                else:
                    central_hist.Add(hist)
                error = array.array('d', [0])
                integral = hist.IntegralAndError(0, hist.GetNbinsX(), error)
                hist_info[plot_group][chan] = (integral, error[0])
                with open("temp.txt", "a") as mc_file:
                    mc_file.write(
                        "\nYield for %s in channel %s is %0.3f $pm$ %0.3f" %
                        (plot_group, chan, integral, error[0]))
            path = "/cms/USER" if "hep.wisc.edu" in os.environ['HOSTNAME'] else \
                "/afs/cern.ch/user/k/USER/work"
            path = path.replace("USER", os.environ["USER"])
            config_factory = ConfigHistFactory(
                "%s/AnalysisDatasetManager" % path,
                args.selection.split("_")[0],
            )
            scale_fac = 1
            scale = False
            error = array.array('d', [0])

            integral = central_hist.IntegralAndError(0,
                                                     central_hist.GetNbinsX(),
                                                     error)
            hist_info[plot_group]["total"] = (integral, error[0])
            with open("temp.txt", "a") as mc_file:
                mc_file.write("\nCombined yield for %s is %0.3f $pm$ %0.3f" %
                              (plot_group, integral, error[0]))

            config_factory.setHistAttributes(central_hist, branch, plot_group)

            if plot_group != "data" and not isSignal:
                hist_stack.Add(central_hist)
            elif isSignal:
                signal_stack.Add(central_hist)
            else:
                data_hist = central_hist
                data_hist.Sumw2(False)
                data_hist.SetBinErrorOption(ROOT.TH1.kPoisson)
        if not signal_stack.GetHists():
            signal_stack = 0
        error_hist = 0
        bkerror_hist = 0
        folder = "shapes_fit_b" if args.backgroundOnly else "shapes_fit_s"
        for chan in channels:
            bkerror_chan = rtfile.Get("/".join(
                [folder, chan, "total_background"]))
            error_chan = rtfile.Get("/".join([folder, chan, "total"]))
            if args.noCR:
                error_chan = removeControlRegion(error_chan)
                bkerror_chan = removeControlRegion(bkerror_chan)
            if "MTWZ" in plot_name:
                error_chan = rebinMTWZ(error_chan, "tmp", isHiggs)
                bkerror_chan = rebinMTWZ(bkerror_chan, "bktmp", isHiggs)
            if "yieldByChannel" in plot_name:
                error_chan = getYieldByChannelHist(error_chan, chan)
                bkerror_chan = getYieldByChannelHist(bkerror_chan, chan)
            if not error_hist:
                error_hist = error_chan.Clone("errors")
                bkerror_hist = bkerror_chan.Clone("bkerrors")
            else:
                error_hist.Add(error_chan)
                bkerror_hist.Add(bkerror_chan)
            error = array.array('d', [0])
            integral = bkerror_chan.IntegralAndError(0,
                                                     bkerror_chan.GetNbinsX(),
                                                     error)
            hist_info["predyield"][chan] = (integral, error[0])

        error = array.array('d', [0])
        integral = bkerror_hist.IntegralAndError(1, bkerror_hist.GetNbinsX(),
                                                 error)
        hist_info["predyield"]["total"] = (integral, error[0])

        plotter.setErrorsStyle(error_hist)
        canvas = helper.makePlots([hist_stack], [data_hist],
                                  plot_name,
                                  args,
                                  signal_stacks=[signal_stack],
                                  errors=[error_hist] if error_hist else [])
        if "CR" not in plot_name and "unrolled" in plot_name:
            ratioPad = canvas.GetListOfPrimitives().FindObject("ratioPad")
            stackPad = canvas.GetListOfPrimitives().FindObject("stackPad")
            ratiohist = ratioPad.GetListOfPrimitives().FindObject(
                '%s_canvas_central_ratioHist' % plot_name)
            xaxis = hist.GetXaxis()
            maximum = hist_stack.GetHistogram().GetMaximum()
            for i in [4, 8]:
                line = ROOT.TLine(xaxis.GetBinUpEdge(i),
                                  hist_stack.GetMinimum(),
                                  xaxis.GetBinUpEdge(i), maximum)
                line.SetLineStyle(7)
                line.SetLineColor(ROOT.kGray + 2)
                line.SetLineWidth(2)
                stackPad.cd()
                line.Draw()
                ROOT.SetOwnership(line, False)
            for i, label in enumerate(
                ["#in [2.5, 4.0]", "#in [4.0, 5.0]", "#geq 5.0   "]):
                xmin = 0.215 + 0.24 * i + 0.052 * (i == 2)
                ymin = 0.12 if i == 2 else 0.5
                ymax = ymin + (0.2 if i == 0 else 0.18)
                xmax = xmin + (0.19 if i == 0 else 0.175)
                text_box = ROOT.TPaveText(xmin, ymin, xmax, ymax, "NDCnb")
                text_box.SetFillColor(0)
                text_box.SetTextFont(42)
                text_box.AddText("|#scale[0.5]{ }#Delta#eta_{jj}| %s" % label)
                text_box.Draw()
                ROOT.SetOwnership(text_box, False)

        makeLogFile(channels, hist_info, args)
        stackPad = canvas.GetListOfPrimitives().FindObject("stackPad")
        stackPad.RedrawAxis()
        # Force it to offset in desperate situations
        #ratioPad = canvas.GetListOfPrimitives().FindObject("ratioPad")
        #ratiohist = ratioPad.GetListOfPrimitives().FindObject('%s_canvas_central_ratioHist' % plot_name)
        #ratiohist.GetXaxis().SetTitleOffset(1.5)
        canvas.Modified()
        canvas.Update()
        helper.savePlot(canvas, plot_path, html_path, plot_name, True, args)
        makeSimpleHtml.writeHTML(html_path.replace("/plots", ""),
                                 args.selection)
def main():
    args = getComLineArgs()
    logging.basicConfig(level=(logging.DEBUG if args.debug else (logging.ERROR if args.quiet else logging.INFO)))

    ROOT.gROOT.SetBatch(True)
    ROOT.gStyle.SetOptDate(0)
    if args.hist_file == "":
        ROOT.TProof.Open('workers=12')
    filelist = UserInput.getListOfFiles(args.files_to_plot, args.selection)
    path = "/cms/kdlong" if "hep.wisc.edu" in os.environ['HOSTNAME'] else \
        "/afs/cern.ch/work/m/mumuhamm/WBoson/CMSSW_11_0_0/src/Data_Manager"
    config_factory = ConfigHistFactory(
        "%s/AnalysisDatasetManager" % path,
        #args.selection.split("_")[0],
        args.selection,
        args.object_restrict
    )
    branches = config_factory.getListOfPlotObjects() if args.branches == "all" \
            else [x.strip() for x in args.branches.split(",")]
    cut_string = args.make_cut
    (plot_path, html_path) = helper.getPlotPaths(args.selection, args.folder_name, True)
    meta_info = '-'*80 + '\n' + \
        'Script called at %s\n' % datetime.datetime.now() + \
        'The command was: %s\n' % ' '.join(sys.argv) + \
        '-'*80 + '\n'
    for branch in branches:
        hist_stacks = []
        signal_stacks = []
        data_hists = []
        for branch_name in branch.split("+"):
            with open("temp.txt", "w") as mc_file:
                mc_file.write(meta_info)
                mc_file.write("Selection: %s" % args.selection)
                mc_file.write("\nAdditional cut: %s" % ("None" if cut_string == "" else cut_string))
                mc_file.write("\nLuminosity: %0.2f fb^{-1}" % (args.luminosity))
                mc_file.write("\nPlotting branch: %s\n" % branch_name)
            try:
                hist_stack = getStacked("stack_"+branch_name, config_factory, args.selection, filelist, 
                        branch_name, args.channels, args.blinding, not args.no_overflow, args.latex, cut_string,
                        args.luminosity, args.rebin, args.uncertainties, args.hist_file, args.scale)
            except ValueError as e:
                logging.warning('\033[91m'+ str(e)+'\033[0m')
                continue
            if args.data != 'none':
                if args.hist_file == "":
                    data_hist = helper.getConfigHistFromTree(config_factory, args.data, args.selection, 
                            branch_name, args.channels, args.blinding, 1, not args.no_overflow, args.rebin, 
                            cut_string)
                else:
                    data_hist = helper.getConfigHistFromFile(args.hist_file, config_factory, args.data, 
                            args.selection, branch_name, args.channels,addOverflow=(not args.no_overflow), rebin=args.rebin)
                with open("temp.txt", "a") as events_log_file:
                    events_log_file.write("\nNumber of events in data: %i\n" % data_hist.Integral())
            else:
                data_hist = 0
            signal_stack = 0
            if len(args.signal_files) > 0:
                signal_filelist = UserInput.getListOfFiles(args.signal_files, args.selection)
                signal_stack = getStacked("signal_stack_"+branch_name, config_factory, args.selection, signal_filelist, 
                        branch_name, args.channels, args.blinding, not args.no_overflow, args.latex, cut_string,
                        args.luminosity, args.rebin, args.uncertainties, args.hist_file)
            hist_stacks.append(hist_stack)
            signal_stacks.append(signal_stack)
            data_hists.append(data_hist)
        if not hist_stacks:
            continue
        name = branch.replace("+","_")
        plot_name = name if args.append_to_name == "" else "_".join([name, args.append_to_name])

        #embed()
        canvas = helper.makePlots(hist_stacks, data_hists, name, args, signal_stacks)

        #ratioPad = canvas.GetListOfPrimitives().FindObject("ratioPad")
        #stackPad = canvas.GetListOfPrimitives().FindObject("stackPad")
        #ratiohist = ratioPad.GetListOfPrimitives().FindObject('%s_canvas_central_ratioHist' % name)
        #for i in ratioPad.GetListOfPrimitives(): print i
        #xaxis = hist.GetXaxis()
        #xaxis.SetLabelOffset(1.2)

        helper.savePlot(canvas, plot_path, html_path, plot_name, True, args)
        makeSimpleHtml.writeHTML(html_path.replace("/plots",""), args.selection)
def main():
    args = getComLineArgs()
    ROOT.gROOT.SetBatch(True)

    branches = [x.strip() for x in args.branches.split(",")]

    (plot_path, html_path) = helper.getPlotPaths(args.selection,
                                                 args.folder_name, True)

    meta_info = '-'*80 + '\n' + \
        'Script called at %s\n' % datetime.datetime.now() + \
        'The command was: %s\n' % ' '.join(sys.argv) + \
        '-'*80 + '\n'

    rtfile = ROOT.TFile(args.hist_file)

    for branch in args.branches.split(","):
        with open("temp.txt", "w") as mc_file:
            mc_file.write(meta_info)
            mc_file.write("Selection: %s" % args.selection)
            mc_file.write("\nPlotting branch: %s\n" % branch)

        systematics = args.systematics.split(",")
        systs = "_".join(systematics)
        plot_name = "_".join([branch, systs]) if args.append_to_name == "" \
                else "_".join([branch, systs, args.append_to_name])
        hist_stack = ROOT.THStack("stack_" + branch, "stack_" + branch)
        file_names = args.files_to_plot.split(",")
        for i, file_name in enumerate(file_names):
            systematic = systematics[i]
            central_hist = 0
            for chan in args.channels.split(","):
                hist_name = file_name.replace(
                    "_standalone", "") + "/" + "_".join([branch, chan])
                uphist_name = hist_name.replace(
                    chan, "_".join([systematic + "Up", chan]))
                downhist_name = hist_name.replace(
                    chan, "_".join([systematic + "Down", chan]))

                if not central_hist:
                    central_hist = rtfile.Get(hist_name)
                    up_hist = rtfile.Get(uphist_name)
                    down_hist = rtfile.Get(downhist_name)
                    central_hist = rebinHist(central_hist, args.rebin)
                    up_hist = rebinHist(up_hist, args.rebin)
                    down_hist = rebinHist(down_hist, args.rebin)
                    central_hist.Draw()
                else:
                    if i == 0 or file_name != file_names[i - 1]:
                        central_hist_chan = rtfile.Get(hist_name)
                        central_hist_chan = rebinHist(central_hist_chan,
                                                      args.rebin)
                        central_hist.Add(central_hist_chan)
                    up_hist_chan = rtfile.Get(uphist_name)
                    down_hist_chan = rtfile.Get(downhist_name)
                    up_hist_chan = rebinHist(up_hist_chan, args.rebin)
                    down_hist_chan = rebinHist(down_hist_chan, args.rebin)
                    up_hist.Add(up_hist_chan)
                    down_hist.Add(down_hist_chan)
            path = "/cms/uhussain" if "hep.wisc.edu" in os.environ['HOSTNAME'] else \
                "/afs/cern.ch/user/u/uhussain/work"
            config_factory = ConfigHistFactory(
                "%s/ZZ4lAnalysisDatasetManager" % path,
                args.selection.split("_")[0],
            )
            scale_fac = 1
            scale = True
            # Normalize to data in CR
            if file_name in ["wz", "wz_standalone"]:
                scale_fac = 0.8224
            elif file_name in ["wz-powheg", "wz-powheg_standalone"]:
                scale_fac = (191 - (28.78 + 3.84 + 18.35 + 22.27)) / 139.43
            if scale:
                central_hist.Scale(scale_fac)
                up_hist.Scale(scale_fac)
                down_hist.Scale(scale_fac)
            with open("temp.txt", "a") as mc_file:
                mc_file.write("\nYield for %s is %0.2f" %
                              (file_name, central_hist.Integral()))

            branch_name = branch.replace("_Fakes", "")
            config_factory.setHistAttributes(central_hist, branch_name,
                                             file_name)
            config_factory.setHistAttributes(up_hist, branch_name, file_name)
            config_factory.setHistAttributes(down_hist, branch_name, file_name)

            central_hist.SetMinimum(0.001)
            central_hist.SetFillColor(0)
            up_hist.SetFillColor(0)
            down_hist.SetFillColor(0)

            central_hist.SetLineStyle(1)
            central_hist.SetLineWidth(2)
            up_hist.SetLineWidth(2)
            down_hist.SetLineWidth(2)
            up_hist.SetLineStyle(5)
            down_hist.SetLineStyle(5)
            #down_hist.SetLineColor(ROOT.TColor.GetColor("#980000"))

            if "wzQCDModeling" in up_hist.GetName():
                print "Oui oui"
                up_hist.SetLineColor(ROOT.TColor.GetColor("#980000"))
                down_hist.SetLineColor(ROOT.TColor.GetColor("#980000"))
            #elif "wz-mgmlm_scale" in up_hist.GetName():
            #    up_hist.SetLineColor(ROOT.TColor.GetColor("#016300"))

            hist_stack.Add(central_hist)
            hist_stack.Add(up_hist)
            hist_stack.Add(down_hist)

        canvas_dimensions = [800, 800
                             ] if "unrolled" not in branch else [1200, 800]
        canvas = ROOT.TCanvas("canvas", "canvas", *canvas_dimensions)
        hist_stack.Draw("nostack hist")
        hist_stack.SetMinimum(central_hist.GetMinimum() * args.scaleymin)
        hist_stack.SetMaximum(central_hist.GetMaximum() * args.scaleymax)
        hist_stack.GetHistogram().GetYaxis().SetTitle("Events / bin")
        hist_stack.GetHistogram().GetYaxis().SetTitleOffset(1.05)

        if not args.no_decorations:
            ROOT.dotrootImport('uhussain/CMSPlotDecorations')
            scale_label = "Normalized to Unity" if args.luminosity < 0 else \
                "%0.1f fb^{-1}" % args.luminosity

            lumi_text = ""
            if args.thesis:
                lumi_text = "Thesis"
            elif args.preliminary:
                lumi_text = "Preliminary"
            if args.simulation:
                lumi_text += "Simulation"

            ROOT.CMSlumi(canvas, 0, 11, "%s (13 TeV)" % scale_label, lumi_text)
            #"Preliminary Simulation" if args.simulation else "Preliminary")
        text_box = ROOT.TPaveText(0.65, 0.75 - 0.1 * len(systematics), 0.9,
                                  0.85, "NDCnb")
        text_box.SetFillColor(0)
        text_box.SetTextFont(42)
        text_box.AddText("Systematic variation")
        for s in systematics:
            text_box.AddText(s)
        text_box.AddText("; ".join(file_names))
        for line, h in zip(text_box.GetListOfLines()[1:],
                           hist_stack.GetHists()[1::3]):
            line.SetTextColor(h.GetLineColor())
        text_box.Draw()
        if args.logy:
            canvas.SetLogy()

        if not args.no_ratio:
            canvas = plotter.splitCanvas(canvas, canvas_dimensions,
                                         "syst./cent.",
                                         [float(i) for i in args.ratio_range])
            ratioPad = canvas.FindObject("ratioPad")
            hist = ratioPad.GetListOfPrimitives().FindObject(
                "canvas_central_ratioHist")
            hist.GetXaxis().SetLabelSize(0.175)
            hist.GetXaxis().SetLabelOffset(0.03)
            hist.GetXaxis().SetTitleOffset(1.15)
            canvas.Update()
        helper.savePlot(canvas, plot_path, html_path, plot_name, True, args)
        makeSimpleHtml.writeHTML(html_path.replace("/plots", ""),
                                 args.selection)
Exemple #10
0
def main():
    #pdb.set_trace()
    args = getComLineArgs()
    with open('varsFile.json') as var_json_file:
        myvar_dict = json.load(var_json_file)
    for key in myvar_dict.keys():
        if args.branches==str(key):
            args.rebin = myvar_dict[key]['_binning']
            
    ROOT.gROOT.SetBatch(True)
    ROOT.gStyle.SetOptDate(0)
    if args.hist_file == "":
        ROOT.TProof.Open('workers=12')
    filelist = UserInput.getListOfFiles(args.files_to_plot, args.selection)
    print filelist
    path = "/cms/uhussain" if "hep.wisc.edu" in os.environ['HOSTNAME'] else \
        "/afs/cern.ch/user/h/hehe/new_ZZ_test_Sep9/CMSSW_10_3_1/src/Data_manager"
    config_factory = ConfigHistFactory(
        "%s/ZZ4lRun2DatasetManager" % path,
        args.selection.split("_")[0],
        args.object_restrict
    )
    #print args.selection, args.selection.split("_")[0]
    #print args.rebin
    branches = config_factory.getListOfPlotObjects() if args.branches == "all" \
            else [x.strip() for x in args.branches.split(",")]
    print branches
    cut_string = args.make_cut
    (plot_path, html_path) = helper.getPlotPaths(args.selection, args.folder_name, True)
    meta_info = '-'*80 + '\n' + \
        'Script called at %s\n' % datetime.datetime.now() + \
        'The command was: %s\n' % ' '.join(sys.argv) + \
        '-'*80 + '\n'
    for branch in branches:
        hist_stacks = []
        signal_stacks = []
        data_hists = []
        for branch_name in branch.split("+"):
            with open("temp.txt", "w") as mc_file:
                mc_file.write(meta_info)
                mc_file.write("Selection: %s" % args.selection)
                mc_file.write("\nAdditional cut: %s" % ("None" if cut_string == "" else cut_string))
                mc_file.write("\nLuminosity: %0.2f fb^{-1}" % (args.luminosity))
                mc_file.write("\nPlotting branch: %s\n" % branch_name)
            try:
                #pdb.set_trace()
                hist_stack = getStacked("stack_"+branch_name, config_factory, args.selection, filelist, 
                        branch_name, args.channels, args.blinding, not args.no_overflow, args.latex, cut_string,
                        args.luminosity, args.rebin, args.uncertainties, args.hist_file)
            except ValueError as e:
                logging.warning('\033[91m'+ str(e)+'\033[0m')
                continue
            if not args.no_data:
                #pdb.set_trace()
                if args.hist_file == "":
                    #data_hist = helper.getConfigHistFromTree(config_factory, "data_all", args.selection, 
                    data_hist = helper.getConfigHistFromTree(config_factory, "data_all", args.selection, 
                            branch_name, args.channels, args.blinding, 1, not args.no_overflow, args.rebin, 
                            cut_string)
                else:
                    #data_hist = helper.getConfigHistFromFile(args.hist_file, config_factory, "data_all",
                    data_hist = helper.getConfigHistFromFile(args.hist_file, config_factory, "data_all", 
                            args.selection, branch_name, args.channels,addOverflow=(not args.no_overflow), rebin=args.rebin)
                with open("temp.txt", "a") as events_log_file:
                    events_log_file.write("\nNumber of events in data: %i\n" % data_hist.Integral())
            else:
                data_hist = 0
            signal_stack = 0
            if len(args.signal_files) > 0:
                signal_filelist = UserInput.getListOfFiles(args.signal_files, args.selection)
                signal_stack = getStacked("signal_stack_"+branch_name, config_factory, args.selection, signal_filelist, 
                        branch_name, args.channels, args.blinding, not args.no_overflow, args.latex, cut_string,
                        args.luminosity, args.rebin, args.uncertainties, args.hist_file)
            hist_stacks.append(hist_stack)
            signal_stacks.append(signal_stack)
            data_hists.append(data_hist)
        if not hist_stacks:
            continue
        name = branch.replace("+","_")
        plot_name = name if args.append_to_name == "" else "_".join([name, args.append_to_name])

        #embed()
        canvas = helper.makePlots(hist_stacks, data_hists, name, args, signal_stacks)
        helper.savePlot(canvas, plot_path, html_path, plot_name, True, args)
        makeSimpleHtml.writeHTML(html_path.replace("/plots",""), args.selection)
Exemple #11
0
def main():
    args = getComLineArgs()
    ROOT.gROOT.SetBatch(True)

    branches = [x.strip() for x in args.branches.split(",")]

    (plot_path, html_path) = helper.getPlotPaths(args.selection,
                                                 args.folder_name, True)

    meta_info = '-'*80 + '\n' + \
        'Script called at %s\n' % datetime.datetime.now() + \
        'The command was: %s\n' % ' '.join(sys.argv) + \
        '-'*80 + '\n'

    rtfile = ROOT.TFile(args.hist_file)
    colors = [
        ROOT.TColor.GetColor(x) for x in [
            "#a6cee3",
            "#1f78b4",
            "#b2df8a",
            "#33a02c",
            "#fb9a99",
            "#fdbf6f",
            "#e31a1c",
            "#ff7f00",
            "#cab2d6",
            "#6a3d9a",
            "#ffff99",
            "#b15928",
        ]
    ]

    for branch in args.branches.split(","):
        with open("temp.txt", "w") as mc_file:
            mc_file.write(meta_info)
            mc_file.write("Selection: %s" % args.selection)
            mc_file.write("\nPlotting branch: %s\n" % branch)

        systematics = args.systematics.split(",")
        systs = "_".join(systematics)
        plot_name = "_".join([branch, systs]) + args.append_to_name
        hist_stack = ROOT.THStack("stack_" + branch, "stack_" + branch)
        file_names = args.files_to_plot.split(",")
        if plot_name.count(file_names[0]) > 1:
            names = plot_name.split("_" + file_names[0])
            plot_name = "".join([names[0], "_" + file_names[0]] + names[1:])
        for i, file_name in enumerate(file_names):
            systematic = systematics[i]
            central_hist = 0
            for chan in args.channels.split(","):
                hist_name = file_name.replace(
                    "_standalone", "") + "/" + "_".join([branch, chan])
                uphist_name = hist_name.replace(
                    "_" + chan, "_" + "_".join([systematic + "Up", chan]))
                downhist_name = hist_name.replace(
                    "_" + chan, "_" + "_".join([systematic + "Down", chan]))

                if not central_hist:
                    central_hist = rtfile.Get(hist_name)
                    central_hist.SetName(hist_name + "_%i" % i)
                    if not central_hist:
                        raise ValueError("Failed to find hist %s in file %s" %
                                         (hist_name, file_name))
                    up_hist = rtfile.Get(uphist_name)
                    up_hist.SetName(uphist_name + "_%i" % i)
                    down_hist = rtfile.Get(downhist_name)
                    down_hist.SetLineColor(ROOT.kYellow)
                    down_hist.SetName(downhist_name + "_%i" % i)
                    if not up_hist or not down_hist:
                        raise ValueError(
                            "Failed to find hist %s for variation %s in file %s"
                            % (uphist_name, systematic, file_name))
                    central_hist = rebinHist(central_hist, args.rebin)
                    up_hist = rebinHist(up_hist, args.rebin)
                    down_hist = rebinHist(down_hist, args.rebin)
                    central_hist.Draw()
                else:
                    central_hist_chan = rtfile.Get(hist_name)
                    central_hist_chan.SetName(hist_name + "_%i" % i)
                    central_hist_chan = rebinHist(central_hist_chan,
                                                  args.rebin)
                    central_hist.Add(central_hist_chan)
                    up_hist_chan = rtfile.Get(uphist_name)
                    down_hist_chan = rtfile.Get(downhist_name)
                    up_hist_chan = rebinHist(up_hist_chan, args.rebin)
                    down_hist_chan = rebinHist(down_hist_chan, args.rebin)
                    up_hist.Add(up_hist_chan)
                    down_hist.Add(down_hist_chan)
            path = "/cms/kdlong" if "hep.wisc.edu" in os.environ['HOSTNAME'] else \
                "/afs/cern.ch/work/m/mumuhamm/WBoson/CMSSW_11_0_0/src/Data_Manager"
            config_factory = ConfigHistFactory(
                "%s/AnalysisDatasetManager" % path,
                args.selection.split("_")[0],
            )
            scale_fac = 1
            scale = True
            # Normalize to data in CR
            if file_name in ["wz", "wz_standalone"]:
                scale_fac = 0.8224
            elif file_name in ["wz-powheg", "wz-powheg_standalone"]:
                scale_fac = (191 - (28.78 + 3.84 + 18.35 + 22.27)) / 139.43
            if scale:
                central_hist.Scale(scale_fac)
                up_hist.Scale(scale_fac)
                down_hist.Scale(scale_fac)
            with open("temp.txt", "a") as mc_file:
                mc_file.write("\nYield for %s is %0.2f" %
                              (file_name, central_hist.Integral()))
                mc_file.write("\nYield up for var %s for %s is %0.2f" %
                              (file_name, systematic, up_hist.Integral()))
                mc_file.write("\nYield down for var %s for %s is %0.2f" %
                              (file_name, systematic, down_hist.Integral()))

            branch_name = branch.replace("_Fakes", "")
            config_factory.setHistAttributes(central_hist, branch_name,
                                             file_name)
            config_factory.setHistAttributes(up_hist, branch_name, file_name)
            config_factory.setHistAttributes(down_hist, branch_name, file_name)

            central_hist.SetMinimum(0.001)
            central_hist.SetFillColor(0)
            up_hist.SetFillColor(0)
            down_hist.SetFillColor(0)

            central_hist.SetLineStyle(1)
            central_hist.SetLineWidth(2)
            up_hist.SetLineWidth(2)
            down_hist.SetLineWidth(2)
            up_hist.SetLineStyle(5)
            down_hist.SetLineStyle(5)
            if i != 0:
                up_hist.SetLineColor(colors[i])
                down_hist.SetLineColor(colors[i])

            hist_stack.Add(central_hist)
            hist_stack.Add(up_hist)
            hist_stack.Add(down_hist)

        canvas_dimensions = [800, 800
                             ] if "unrolled" not in branch else [1200, 800]
        canvas = ROOT.TCanvas("canvas", "canvas", *canvas_dimensions)
        hist_stack.Draw("nostack hist")
        hist_stack.SetMinimum(central_hist.GetMinimum() * args.scaleymin)
        hist_stack.SetMaximum(central_hist.GetMaximum() * args.scaleymax)
        hist_stack.GetHistogram().GetYaxis().SetTitle("Events / bin")
        hist_stack.GetHistogram().GetYaxis().SetTitleOffset(1.05)

        text_box = ROOT.TPaveText(
            0.65, 0.75 - (0.1 * len(systematics)) * args.scalelegy, 0.9, 0.85,
            "NDCnb")
        text_box.SetFillColor(0)
        text_box.SetTextFont(42)
        text_box.AddText("Systematic variation")
        for s in systematics:
            text_box.AddText(s)
        text_box.AddText("; ".join(set(file_names)))
        for line, h in zip(text_box.GetListOfLines()[1:],
                           hist_stack.GetHists()[1::3]):
            line.SetTextColor(h.GetLineColor())
        text_box.Draw()
        if args.logy:
            canvas.SetLogy()

        if not args.no_ratio:
            canvas = plotter.splitCanvas(canvas, canvas_dimensions,
                                         "syst./cent.",
                                         [float(i) for i in args.ratio_range],
                                         args.uncertainties == "none")
            ratioPad = canvas.FindObject("ratioPad")
            hist = ratioPad.GetListOfPrimitives().FindObject(
                "canvas_central_ratioHist")
            hist.GetXaxis().SetLabelSize(0.175)
            hist.GetXaxis().SetLabelOffset(0.03)
            hist.GetXaxis().SetTitleOffset(1.15)
            canvas.Update()
        helper.savePlot(canvas, plot_path, html_path, plot_name, True, args)
        makeSimpleHtml.writeHTML(html_path.replace("/plots", ""),
                                 args.selection)