filelist = UserInput.getListOfFiles(args.files_to_plot, args.selection)
if not args.no_data:
    data_hist = cutflow_maker.getHist("data_2016", "stat", args.hist_file)
else:
    data_hist = 0
hist_stack = getMonteCarloStack("stack", cutflow_maker, filelist,
                                args.uncertainties, not args.no_scalefactors,
                                args.hist_file)
signal_stack = 0
if len(args.signal_files) > 0:
    signal_filelist = UserInput.getListOfFiles(args.signal_files,
                                               args.selection)
    signal_stack = getMonteCarloStack("signal_stack", cutflow_maker,
                                      signal_filelist, args.uncertainties,
                                      not args.no_scalefactors, args.hist_file)
hist_stack.Draw()
canvas = helper.makePlots([hist_stack], [data_hist], "yieldByChan", args,
                          [signal_stack])
canvas.SetRightMargin(0.3)
ratioPad = ROOT.gPad.GetListOfPrimitives().FindObject("ratioPad")
hist = ratioPad.GetListOfPrimitives().FindObject(
    'yieldByChan_canvas_central_ratioHist')
hist.GetXaxis().SetLabelSize(0.2)
makeLogFile(channels, hist_stack, data_hist, signal_stack)

plot_name = 'yieldByChannel'
if args.append_to_name != "":
    plot_name += "_" + args.append_to_name
(plot_path, html_path) = helper.getPlotPaths(args.selection, args.folder_name)
helper.savePlot(canvas, plot_path, html_path, plot_name, True, args)
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)

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