Exemple #1
0
def plotCutFlow(in_file_paths, out_file_path, in_file_path_names, ignore_weights=False, output_name = None):
    in_file_paths = makeList(in_file_paths)
    in_file_path_names = makeList(in_file_path_names)
    if len(in_file_paths) != len(in_file_path_names):
        print 'inconsistent file paths and names'
        exit(0)

    list_of_cut_hist = []
    tex_names = []
    x_name = []
    #If one input file, plot keys on x
    if len(in_file_paths) == 1:
        in_file = TFile(in_file_paths[0], 'read')
        key_names = [k[0] for k in rootFileContent(in_file, starting_dir = 'cutflow')]
        in_file.Close()
        list_of_cut_hist.append(ROOT.TH1D('cutflow', 'cutflow', len(key_names), 0, len(key_names)))
        for i, k in enumerate(key_names):
            if ignore_weights:
                list_of_cut_hist[0].SetBinContent(i+1, getObjFromFile(in_file_paths[0], k).GetEntries())
            else:
                list_of_cut_hist[0].SetBinContent(i+1, getObjFromFile(in_file_paths[0], k).GetSumOfWeights())
        tex_names = in_file_path_names
        x_name = [k.split('/')[-1] for k in key_names]
    #Plot samples on x
    else:
        in_file = TFile(in_file_paths[0])
        key_names = [k[0] for k in rootFileContent(in_file, starting_dir='cutflow')]
        in_file.Close()
        for j, k in enumerate(key_names):
            list_of_cut_hist.append(ROOT.TH1D('cutflow_'+k, 'cutflow_'+k, len(in_file_paths), 0, len(in_file_paths)))
            for i, ifp in enumerate(in_file_paths):
                if ignore_weights:
                    print ifp, k
                    list_of_cut_hist[j].SetBinContent(i+1, getObjFromFile(ifp, k).GetEntries())
                else:
                    list_of_cut_hist[j].SetBinContent(i+1, getObjFromFile(ifp, k).GetSumOfWeights())
        tex_names = [k.split('/')[-1] for k in key_names]
        x_name = in_file_path_names

    p = Plot(list_of_cut_hist, tex_names, name = 'cutflow' if output_name is None else output_name, x_name = x_name, y_log = True)
    p.drawBarChart(out_file_path, index_colors=True, parallel_bins=True)
Exemple #2
0
def plotGeneralGroups(signal_hist,
                      bkgr_hist,
                      tex_names,
                      out_path,
                      region_name,
                      extra_text=None,
                      sample_groups=False):
    for group in region_groups[region_name].keys():
        group_signal_hist = []
        group_bkgr_hist = []
        for ish, sh in enumerate(signal_hist):
            group_signal_hist.append(
                ROOT.TH1D(
                    'tmp_signal_' + tex_names[ish] + '_' + group + out_path,
                    'tmp_signal', len(region_groups[region_name][group]), 0.5,
                    len(region_groups[region_name][group]) + 0.5))
            for ib, b in enumerate(region_groups[region_name][group]):
                group_signal_hist[ish].SetBinContent(ib + 1,
                                                     sh.GetBinContent(b))
                group_signal_hist[ish].SetBinError(ib + 1, sh.GetBinError(b))

        for ish, sh in enumerate(bkgr_hist):
            group_bkgr_hist.append(
                ROOT.TH1D(
                    'tmp_bkgr_' + tex_names[ish] + '_' + group + out_path,
                    'tmp_bkgr', len(region_groups[region_name][group]), 0.5,
                    len(region_groups[region_name][group]) + 0.5))
            for ib, b in enumerate(region_groups[region_name][group]):
                group_bkgr_hist[ish].SetBinContent(ib + 1, sh.GetBinContent(b))
                group_bkgr_hist[ish].SetBinError(ib + 1, sh.GetBinError(b))

        draw_ratio = 'errorsOnly' if len(group_signal_hist) > 0 and len(
            group_bkgr_hist) > 0 else None
        if sample_groups:
            p = Plot(group_signal_hist,
                     tex_names,
                     bkgr_hist=group_bkgr_hist,
                     name=group,
                     x_name='Search region',
                     y_name='Events',
                     y_log=True,
                     extra_text=extra_text,
                     color_palette='AN2017',
                     color_palette_bkgr='AN2017',
                     syst_hist=0.1,
                     draw_ratio=draw_ratio)
        else:
            p = Plot(group_signal_hist,
                     tex_names,
                     bkgr_hist=group_bkgr_hist,
                     name=group,
                     x_name='Search region',
                     y_name='Events',
                     y_log=True,
                     extra_text=extra_text,
                     syst_hist=0.1,
                     draw_ratio=draw_ratio)
        p.drawHist(output_dir=out_path, min_cutoff=1.)

        del p, group_signal_hist, group_bkgr_hist
Exemple #3
0
def plotHighMassRegions(signal_hist,
                        bkgr_hist,
                        tex_names,
                        out_path,
                        extra_text=None,
                        sample_groups=False):

    #Plot per grouping

    plotGeneralGroups(signal_hist,
                      bkgr_hist,
                      tex_names,
                      out_path,
                      'oldAN_highMass',
                      extra_text=extra_text,
                      sample_groups=sample_groups)

    draw_ratio = 'errorsOnly' if len(signal_hist) > 0 and len(
        bkgr_hist) > 0 else None
    if sample_groups:
        p = Plot(signal_hist,
                 tex_names,
                 bkgr_hist=bkgr_hist,
                 name='All',
                 x_name='Search region',
                 y_name='Events',
                 y_log=True,
                 extra_text=extra_text,
                 color_palette='AN2017',
                 color_palette_bkgr='AN2017',
                 syst_hist=0.1,
                 draw_ratio=draw_ratio)
    else:
        p = Plot(signal_hist,
                 tex_names,
                 bkgr_hist=bkgr_hist,
                 name='All',
                 x_name='Search region',
                 y_name='Events',
                 y_log=True,
                 extra_text=extra_text,
                 syst_hist=0.1,
                 draw_ratio=draw_ratio)
    p.drawHist(output_dir=out_path, min_cutoff=1.)
Exemple #4
0
                                getMuWPs(algo)[l], tx, 0.32, None, 22))
                        extra_text.append(
                            extraTextFormat(
                                getCorrespondingLightLepDiscr(algo)[1], tx,
                                None, None, 22))

                    extra_text.append(extraTextFormat(algo, 0.2, 0.8))
                    extra_text.append(
                        extraTextFormat(
                            ele_wp + ' ' +
                            getCorrespondingLightLepDiscr(algo)[0]))

                    p = Plot(list_of_hist[channel][algo][ele_wp]['Signal'],
                             tex_names,
                             name='_'.join([channel, algo, ele_wp]),
                             bkgr_hist=list_of_hist[channel][algo][ele_wp]
                             ['Background'],
                             y_log=True,
                             draw_significance=True,
                             extra_text=extra_text)
                    out_dir = os.path.join(
                        os.getcwd(), 'data', 'Results',
                        __file__.split('.')[0].rsplit('/')[-1], args.year,
                        'Plots')
                    if args.masses:
                        out_dir = os.path.join(
                            out_dir, '-'.join([str(m) for m in args.masses]))
                    p.drawHist(output_dir=out_dir,
                               custom_labels=custom_labels,
                               draw_lines=lines_to_draw)

closeLogger(log)
Exemple #5
0
    exit(0)

#
# Necessary imports
#
from HNL.Plotting.plot import Plot
from HNL.Tools.helpers import makePathTimeStamped

#
# Set output directory, taking into account the different options
#
output_dir = os.path.join(os.getcwd(), 'data', 'Results',
                          __file__.split('.')[0], args.year)

output_dir = makePathTimeStamped(output_dir)

#
# Create plots for each category
#
for v in var:
    # Create plot object (if signal and background are displayed, also show the ratio)
    p = Plot(list_of_hist[v],
             legend_names[v],
             v,
             y_log=False,
             color_palette='StackTauPOGbyName',
             year=args.year)

    # Draw
    p.drawHist(output_dir=output_dir, draw_option='Stack')
Exemple #6
0
    merge(mf)

input_signal = glob.glob(os.getcwd()+'/data/compareLightLeptonId/'+args.signal+'/*ROC-'+args.flavor+'.root')
bkgr_prefix = os.getcwd()+'/data/compareLightLeptonId/'+args.bkgr

from HNL.Plotting.plot import Plot

output_dir = makePathTimeStamped(os.getcwd()+'/data/Results/compareLightLeptonId/ROC/'+args.signal+'-'+args.bkgr)
curves = []
ordered_f_names = []
for f_path in input_signal:
    f_name = f_path.rsplit('/', 1)[1].split('.')[0]
    ordered_f_names.append(f_name)
    roc_curve = ROC(f_name.split('-')[0], 1., '', f_path, misid_path =bkgr_prefix + '/'+f_name+'.root')
    curves.append(roc_curve.returnGraph())
p = Plot(curves, ordered_f_names, args.signal+'_'+args.flavor, 'efficiency', 'misid', y_log=True)
p.drawGraph(output_dir = output_dir)
       
from HNL.Tools.efficiency import Efficiency
from HNL.Tools.helpers import rootFileContent
from ROOT import TFile
var = ['pt', 'eta']
inputFiles = {'efficiency' : glob.glob(os.getcwd()+'/data/compareLightLeptonId/'+args.signal+'/efficiency-'+str(args.flavor)+'.root'), 'fakerate': glob.glob(os.getcwd()+'/data/compareLightLeptonId/'+args.bkgr+'/fakerate-'+str(args.flavor)+'.root')}
for eff_name in ['efficiency', 'fakerate']:
    for f in inputFiles[eff_name]:
        print f
        rf = TFile(f)
        key_names = [k[0] for k in rootFileContent(rf)]
        filtered_key_names = {fk.rsplit('-', 1)[0].split('/')[-1] for fk in key_names}
        list_of_eff = {}
        for fk in filtered_key_names: #algo
Exemple #7
0
                    eff_list = [
                        eff.getEfficiency()
                        for eff in eff_lists[trigger_cat_name][v]
                    ]
                    if args.separateTriggers is None or args.separateTriggers == 'full':
                        trigger_list = ['allTriggers']
                    else:
                        trigger_list = returnCategoryTriggerNames(
                            TRIGGER_CATEGORIES[trigger_cat_name][0])

                    if args.separateTriggers == 'cumulative':
                        out_dir = os.getcwd(
                        ) + '/data/Results/' + args.separateTriggers + '/' + f_name + '/' + timestamp
                        p = Plot(eff_list,
                                 trigger_list,
                                 trigger_cat_name + '_' + v,
                                 eff_list[0].GetXaxis().GetTitle(),
                                 eff_list[0].GetYaxis().GetTitle(),
                                 extra_text=extra_text)
                        names = [
                            trigger_cat_name + '_' + v + '_' + k
                            for k in trigger_list
                        ]
                        if '2D' in v:
                            p.draw2D(output_dir=out_dir + '/' + sample,
                                     names=names)
                        else:
                            p.drawHist(output_dir=out_dir + '/' + sample)
        else:
            to_merge = [eff_list[c] for c in CATEGORIES]
            eff_lists['all'] = mergeEfficiencies(to_merge, 'all')
Exemple #8
0
        for c in getCategories():
            closureObjects[sample_name][c] = {}
            for v in var:
                closureObjects[sample_name][c][v] = ClosureObject(
                    'closure-' + v + '-' + c, None, None,
                    in_file + '/events.root')

    if not args.inData and not args.stackMC:
        for sample_name in closureObjects.keys():
            for c in getCategories():
                for v in var:
                    p = Plot(name=v,
                             signal_hist=closureObjects[sample_name][c]
                             [v].getObserved(),
                             bkgr_hist=closureObjects[sample_name][c]
                             [v].getSideband(),
                             color_palette='Black',
                             color_palette_bkgr='Stack',
                             tex_names=["Observed", 'Predicted'],
                             draw_ratio=True)
                    p.drawHist(output_dir=output_dir + '/' + sample_name +
                               '/' + c,
                               draw_option='EP')
    else:
        for c in getCategories():
            for v in var:
                if args.inData:
                    backgrounds = [closureObjects["Data"][c][v].getSideband()]
                    background_names = ['Predicted']
                else:
                    backgrounds = []
Exemple #9
0
    sub_files = glob.glob(input_name + '/'+f_name+'.root')


#
#   TODO: THIS CODE SEEMS VERY OUTDATED, PLEASE UPDATE
#

    print 'plotting', f_name
    for f in sub_files:
        output_dir = os.path.join(os.getcwd(), 'data', 'Results', 'calcSignalEfficiency', f_name, category_split_str, trigger_str, mass_str, flavor_name)
        output_dir = makePathTimeStamped(output_dir)

        eff = Efficiency('efficiency_noCategories', None, None, f, subdirs = ['efficiency_noCategories', 'l1_r_l2_e_l3_g'])
        h = eff.getEfficiency()

        p = Plot(h, 'V_{'+args.flavor+'N} = 0.01', 'efficiency', h.GetXaxis().GetTitle(), h.GetYaxis().GetTitle(), x_log=True, color_palette = 'Black')
        p.drawHist(output_dir = output_dir, draw_option = 'EP')



#         dict_of_categories = {}
#         dict_of_names = {}
#         for category in CATEGORIES:
#             dict_of_categories[category] = []
#             dict_of_names[category] = []
    
#         rf = ROOT.TFile(f)
#         if args.triggerTest or args.cumulativeCuts:    get_nested = True
#         else:                   get_nested = False

#         keyNames = [k[0] for k in rootFileContent(rf, getNested=get_nested)]
Exemple #10
0
            args.flavor, '-'.join([region_to_select, args.selection]))

    in_files = glob.glob(os.path.join(base_path_in, '*'))
    merge(in_files,
          __file__,
          jobs, ('sample', 'subJob'),
          argParser,
          istest=args.isTest)

    if args.inData:
        os.system("hadd -f " + base_path_in + "/events.root " + base_path_in +
                  '/*/events.root')

    samples_to_plot = ['Data'] if args.inData else sample_manager.getOutputs()

    for sample_output in samples_to_plot:
        if args.isTest and sample_output != 'DY': continue
        if args.inData:
            output_dir = makePathTimeStamped(base_path_out)
            in_file = base_path_in + '/events.root'
        else:
            output_dir = makePathTimeStamped(base_path_out + '/' +
                                             sample_output)
            in_file = base_path_in + '/' + sample_output + '/events.root'

        fakerates = createFakeRatesWithJetBins('tauttl', None, None, in_file)
        for fr in fakerates.bin_collection:
            ttl = fakerates.getFakeRate(fr).getEfficiency()

            p = Plot(signal_hist=ttl, name='ttl_' + fr, year=int(args.year))
            p.draw2D(output_dir=output_dir, names=['ttl_' + fr])
Exemple #11
0
        from ROOT import kRed
        lines = [drawLineFormat(x0 = 20., x1=20., color=kRed)] if args.flavor == 'tau' else None

        from HNL.Plotting.plot import Plot
        extra_text = [extraTextFormat('V_{'+args.flavor+'N} = 0.01')]
        for i, c_key in enumerate(efficiency[cut_str].keys()):
            category_name = CATEGORY_NAMES[c_key] if c_key in CATEGORIES else c_key
            for j, t_key in enumerate(efficiency[cut_str][c_key].keys()):
                h_bkgr = efficiency[cut_str][c_key][t_key].getEfficiency()
                h_signal = [efficiency[n][c_key][t_key].getEfficiency() for n in args.stackBaselineCuts] if args.stackBaselineCuts is not None else None
                bkgr_names = args.stackBaselineCuts if args.stackBaselineCuts else []
                draw_ratio = True if len(bkgr_names) > 0 else None
                extra_text_cat = extra_text + [extraTextFormat(category_name)]
                # legend_names = [legend_dict[x] for x in [cut_str]+bkgr_names]
                legend_names = [legend_dict[x] for x in bkgr_names+[cut_str]]
                p = Plot(h_signal, legend_names, 'efficiency_'+str(category_name), h_bkgr.GetXaxis().GetTitle(), 'Efficiency', bkgr_hist = h_bkgr, x_log=True, y_log=True, 
                        extra_text=extra_text_cat, draw_ratio = draw_ratio, color_palette = 'Didar', color_palette_bkgr = 'Black')
                p.drawHist(output_dir = output_dir, draw_option = 'EP', bkgr_draw_option = 'EP', draw_lines = lines)

        # hist_for_special_plot = [efficiency['threeLeptonGenFilter']['NoTau']['regularRun'], efficiency['hadronicTauGenFilter']['TauFinalStates']['regularRun']]
        # p = Plot(hist_for_special_plot, ['leptonic decay', 'hadronic decay'], 'efficiency_special', h_signal[0].GetXaxis().GetTitle(), 'Efficiency', x_log = True, y_log=True, extra_text=extra_text, color_palette = 'Didar')
        # p.drawHist(output_dir, draw_option = 'EP')

        # spec_signal = efficiency['tauPlusLightGenFilter']['Total']['regularRun'].getDenominator()
        # spec_signal.Add(efficiency['tauPlusLightGenFilterInverted']['Total']['regularRun'].getDenominator())
        # spec_bkgr =  efficiency['noFilter']['Total']['regularRun'].getDenominator()
        # p = Plot(spec_signal, ['sum', 'total'], 'efficiency_summation', h_bkgr.GetXaxis().GetTitle(), 'Efficiency', bkgr_hist = spec_bkgr, x_log=True, y_log=True, extra_text=extra_text_cat, draw_ratio = draw_ratio, color_palette = 'Didar', color_palette_bkgr = 'Black')
        # p.drawHist(output_dir = output_dir, draw_option = 'EP', bkgr_draw_option = 'EP')

    #TODO: Implement plotting for compareTriggerCuts
    
Exemple #12
0
        observed_AN = getObjFromFile(os.path.join(os.path.expandvars('$CMSSW_BASE'), 'src', 'HNL', 'Stat', 'data', 'StateOfTheArt', 'limitsMuonMixing.root'), 'observed_promptDecays')
        expected_AN = getObjFromFile(os.path.join(os.path.expandvars('$CMSSW_BASE'), 'src', 'HNL', 'Stat', 'data', 'StateOfTheArt', 'limitsMuonMixing.root'), 'expected_central')
        tex_names = ['observed (EXO-17-012)', 'expected (EXO-17-012)']

    else:
        observed_AN = None
        expected_AN = None
        tex_names = None

    coupling_dict = {'tau':'#tau', 'mu':'#mu', 'e':'e', '2l':'l'}
    from HNL.Plotting.plot import Plot
    destination = makePathTimeStamped(os.path.expandvars('$CMSSW_BASE/src/HNL/Stat/data/Results/runAsymptoticLimits/'+args.strategy+'-'+args.selection+'/'+args.flavor+'/'+card+'/'+ year_to_read))
    if observed_AN is None and expected_AN is None:
        bkgr_hist = None
    else:
        bkgr_hist = [observed_AN, expected_AN]

    if args.compareToCards is not None:
        for compare_key in compare_graphs.keys():
            compare_sel, compare_reg = compare_key.split(' ')
            if bkgr_hist is None:
                bkgr_hist = [compare_graphs[compare_key][0]]
                tex_names = [compare_dict[compare_sel] + ' ' +compare_reg]
            else:
                bkgr_hist.append(compare_graphs[compare_key][0])
                tex_names.append(compare_dict[compare_sel] + ' ' +compare_reg)

    year = args.year[0] if len(args.year) == 1 else 'all'
    # p = Plot(graphs, tex_names, 'limits', bkgr_hist = bkgr_hist, y_log = True, x_log=False, x_name = 'm_{N} [GeV]', y_name = '|V_{'+coupling_dict[args.flavor]+' N}|^{2}', year = year)
    p = Plot(graphs, tex_names, 'limits', bkgr_hist = bkgr_hist, y_log = True, x_log=True, x_name = 'm_{N} [GeV]', y_name = '|V_{'+coupling_dict[args.flavor]+' N}|^{2}', year = year)
    p.drawBrazilian(output_dir = destination)
Exemple #13
0
                    # hist_to_plot[sample_name] = ROOT.TH1D(sample_name, sample_name, len(list_of_values['bkgr'][sample_name]), 0, len(list_of_values['bkgr'][sample_name]))
                    hist_to_plot[sample_name] = ROOT.TH1D(
                        sample_name + supercat, sample_name + supercat,
                        len(SUPER_CATEGORIES[supercat]), 0,
                        len(SUPER_CATEGORIES[supercat]))
                    for i, c in enumerate(SUPER_CATEGORIES[supercat]):
                        # hist_to_plot[sample_name].SetBinContent(i+1, list_of_values['bkgr'][sample_name][c]['total'].getHist().GetSumOfWeights())
                        hist_to_plot[sample_name].SetBinContent(
                            i + 1,
                            list_of_values['bkgr'][sample_name][c]['total'])
                x_names = [
                    CATEGORY_TEX_NAMES[n] for n in SUPER_CATEGORIES[supercat]
                ]
                p = Plot(hist_to_plot.values(),
                         hist_to_plot.keys(),
                         name='Events-bar-bkgr-' + supercat,
                         x_name=x_names,
                         y_name='Events',
                         y_log='SingleTau' in supercat)
                p.drawBarChart(output_dir=destination + '/BarCharts',
                               message=args.message)

                #
                # Signal
                #
                hist_to_plot = []
                hist_names = []
                for sn, sample_name in enumerate(
                        sorted(list_of_values['signal'].keys(),
                               key=lambda k: int(k.split('-m')[-1]))):
                    # hist_to_plot.append(ROOT.TH1D(sample_name, sample_name, len(list_of_values['signal'][sample_name]), 0, len(list_of_values['signal'][sample_name])))
                    hist_to_plot.append(
Exemple #14
0
            bkgr_hist = list_of_hist[c][v]['bkgr'].values()
       
        # Make list of signal histograms for the plot object
        if not list_of_hist[c][v]['signal'].values() or args.bkgrOnly: 
            signal_hist = None
        else:
            signal_hist = list_of_hist[c][v]['signal'].values()

        if args.includeData:
            observed_hist = list_of_hist[c][v]['data']
        else:
            observed_hist = None

        # Create plot object (if signal and background are displayed, also show the ratio)
        if args.groupSamples:
            p = Plot(signal_hist, legend_names, c_name+'-'+v, bkgr_hist = bkgr_hist, observed_hist = observed_hist, y_log = False, extra_text = extra_text, draw_ratio = (not args.signalOnly and not args.bkgrOnly), year = args.year, color_palette = 'AN2017', color_palette_bkgr = 'AN2017')
        else:
            p = Plot(signal_hist, legend_names, c_name+'-'+v, bkgr_hist = bkgr_hist, y_log = False, extra_text = extra_text, draw_ratio = (not args.signalOnly and not args.bkgrOnly), year = args.year)


        # Draw
        p.drawHist(output_dir = os.path.join(output_dir, c_name), normalize_signal=True, draw_option='Hist', min_cutoff = 1)
    
    #TODO: I broke this when changing the eventCategorization, fix this again
    # # If looking at signalOnly, also makes plots that compares the three lepton pt's for every mass point
    # if args.signalOnly:

    #     all_cuts = returnCategoryPtCuts(c)
        
    #     for cuts in all_cuts:   
 
Exemple #15
0
        weight.push_back(test_tree['weight'][i])
        for mname in mnames:
            mva_output[mname].push_back(test_tree[mname][i])

    ROC_integrals = []
    for iname, mname in enumerate(mnames):
        progress(iname, len(mnames))
        ROCs[mname] = ROOT.TMVA.ROCCurve(mva_output[mname], class_id, weight)
        ROC_integrals.append(ROCs[mname].GetROCIntegral())
        ROC_curve = ROCs[mname].GetROCCurve()
        ROC_curve = fillRandGraph(ROC_curve, 10)
        extra_text = [
            extraTextFormat("AUC: " + str(ROCs[mname].GetROCIntegral()))
        ]
        p = Plot(signal_hist=[ROC_curve],
                 tex_names=[mname],
                 name='roc_' + mname,
                 extra_text=extra_text)
        p.drawGraph(output_dir=out_file_name.rsplit('/', 1)[0] + '/kBDT/plots',
                    draw_style="AP")

    print 'Making pdf'
    mnames = sortByOtherList(mnames, ROC_integrals)
    mnames.reverse()
    pdf = FPDF()
    for mname in mnames:
        pdf.add_page()
        pdf.image(
            os.path.join(
                out_file_name.rsplit('/', 1)[0], 'kBDT', 'plots',
                'roc_' + mname + '.png'), 50., 50., 100., 100.)
        pdf.image(
Exemple #16
0
    observed_AN = getObjFromFile(
        os.path.join(os.path.expandvars('$CMSSW_BASE'), 'src', 'HNL', 'Stat',
                     'data', 'StateOfTheArt', 'limitsMuonMixing.root'),
        'observed_promptDecays')
    expected_AN = getObjFromFile(
        os.path.join(os.path.expandvars('$CMSSW_BASE'), 'src', 'HNL', 'Stat',
                     'data', 'StateOfTheArt', 'limitsMuonMixing.root'),
        'expected_central')
    tex_names = ['observed (AN-2017-014)', 'expected (AN-2017-014)']

else:
    observed_AN = None
    expected_AN = None
    tex_names = None

coupling_dict = {'tau': '#tau', 'mu': '#mu', 'e': 'e', '2l': 'l'}
from HNL.Plotting.plot import Plot
destination = makePathTimeStamped(
    os.path.expandvars(
        '$CMSSW_BASE/src/HNL/Stat/data/Results/runAsymptoticLimits/' +
        args.flavor))
p = Plot(graphs,
         tex_names,
         'limits',
         bkgr_hist=[observed_AN, expected_AN],
         y_log=True,
         x_log=True,
         x_name='m_{N} [GeV]',
         y_name='|V_{' + coupling_dict[args.flavor] + ' N}|^{2}')
p.drawBrazilian(output_dir=destination)
Exemple #17
0
    # if args.plotSoftTau and 'tau' in sample.name:
    #     print len(taus)
    #     if len(taus) > 0: pt_hist[3].Fill(taus[-1][0])
    #     if len(taus) > 1: pt_hist[4].Fill(taus[-2][0])

# if args.isTest: exit(0)

#Write and plot
out_file = ROOT.TFile(output_name, 'recreate')
out_file.cd()
for subh in pt_hist:
    subh.Write()
out_file.Close()

from HNL.Plotting.plot import Plot
# legend_names = ['leading gen p_{T}', 'subleading gen p_{T}', 'trailing gen p_{T}']
legend_names = ['l1 p_{T}', 'l2 p_{T}', 'l3 p_{T}']
if args.plotSoftTau and 'tau' in sample.name:
    legend_names.append('softest gen tau p_{T}')
    legend_names.append('subleading gen tau p_{T}')
plot = Plot(pt_hist,
            legend_names,
            name=sample.name,
            x_name='p_{T} [GeV]',
            y_name='Events')
plot_name = os.path.join(os.path.expandvars('$CMSSW_BASE/src/HNL/Test/data'),
                         os.path.basename(__file__).split('.')[0], 'Plots')
plot.drawHist(plot_name)

if args.isTest:
    closeLogger(log)
Exemple #18
0
#
from HNL.Plotting.plot import Plot
from HNL.Plotting.plottingTools import extraTextFormat
from HNL.Tools.helpers import makePathTimeStamped
from HNL.EventSelection.eventCategorization import returnCategoryPtCuts

#
# Set output directory, taking into account the different options
#
output_dir = os.path.join(os.getcwd(), 'data', 'Results', 'plotTau',
                          reco_or_gen_str)

output_dir = makePathTimeStamped(output_dir)

#
# Create plots for each category
#
for sample in list_of_hist.keys():
    for v in var:
        legend_names = [sample]
        # Create plot object (if signal and background are displayed, also show the ratio)
        p = Plot([list_of_hist[sample][v]],
                 legend_names,
                 sample + '-' + v,
                 y_log=True)

        # Draw
        p.drawHist(output_dir=output_dir,
                   signal_style=True,
                   draw_option='EHist')
Exemple #19
0
         for k in key_names if algo in k
     }
     mu_wp[algo] = {
         k.split('/')[1].split('-')[2]
         for k in key_names if algo in k
     }
     rf.Close()
     for ewp in ele_wp[algo]:
         for mwp in mu_wp[algo]:
             roc_curve = ROC('-'.join([algo, ewp, mwp]),
                             signal_path,
                             misid_path=bkgr_path)
             p = Plot(roc_curve.returnGraph(),
                      algo,
                      '-'.join([algo, ewp, mwp]),
                      'efficiency',
                      'misid',
                      y_log=True,
                      extra_text=extra_text)
             output_path = os.path.join(
                 os.getcwd(), 'data', 'Results', 'compareTauID',
                 reco_names[args.includeReco], d,
                 signal_name + '-' + bkgr_name, algo)
             p.drawGraph(output_dir=output_path)
     curves.append(
         ROC('-'.join([algo, 'None', 'None']),
             signal_path,
             misid_path=bkgr_path).returnGraph())
     ordered_names.append(algo)
 p = Plot(curves,
          ordered_names,
Exemple #20
0
samples = {f.split('/')[-2] for f in inputfiles_eff}
from HNL.Tools.efficiency import Efficiency
from HNL.Tools.helpers import getObjFromFile
for sample in samples:
    eff = Efficiency('efficiency_pt', None, None, input_file_path + sample+'/efficiency.root', subdirs = ['deeptauVSjets-none-none-'+args.wp, 'efficiency_pt'])
    if 'HNL' in sample:
        list_of_signal_eff[sample] = eff.getEfficiency() 
        list_of_signal_pt[sample] = getObjFromFile(os.path.expandvars('$CMSSW_BASE/src/HNL/Test/data/plotTau/gen/' + sample + '/variables.root'), 'pt/'+sample+'-pt')
        list_of_signal_pt[sample].Scale(1./list_of_signal_pt[sample].GetSumOfWeights())
    else:
        list_of_bkgr_eff[sample] = eff.getEfficiency()
        list_of_bkgr_pt[sample] = getObjFromFile(os.path.expandvars('$CMSSW_BASE/src/HNL/Test/data/plotTau/gen/' + sample + '/variables.root'), 'pt/'+sample+'-pt')
        list_of_bkgr_pt[sample].Scale(1./list_of_bkgr_pt[sample].GetSumOfWeights())

from HNL.Plotting.plot import Plot

if args.isTest:
    output_dir = os.getcwd()+'/data/testArea/Results/compareTauID/includeReco/'
else:
    output_dir = os.getcwd()+'/data/Results/compareTauID/includeReco/'
if args.onlyReco:     output_dir += 'onlyReco/'
output_dir = makePathTimeStamped(output_dir)

for sample in list_of_signal_eff.keys():
    legend_names = ['efficiency in '+sample, 'efficiency in '+args.bkgr, 'tau distribution in '+sample, 'tau distribution in '+args.bkgr]
    p = Plot([list_of_signal_eff[sample], list_of_bkgr_eff[args.bkgr]], legend_names, sample, bkgr_hist = [list_of_signal_pt[sample], list_of_bkgr_pt[args.bkgr]]) 
    final_dir = output_dir
    if not args.onlyReco:
        final_dir += '/'+args.wp+'/'
    p.drawHist(output_dir = final_dir, draw_option = 'EP',  bkgr_draw_option = 'EHist')  
Exemple #21
0
# It assumes the samples are ordered by mass in the input list
#
from HNL.Tools.helpers import getMassRange
from HNL.Tools.histogram import Histogram

mass_range = getMassRange([sample_name for sample_name in sample_manager.sample_names if '-'+args.flavor+'-' in sample_name])

#
# Define the variables and axis name of the variable to fill and create efficiency objects
#
import numpy as np
var = {'HNLmass': (lambda c : c.HNLmass,        np.array(mass_range),   ('m_{N} [GeV]', 'Cross Section (pb)'))}

hist = Histogram('xsec', var['HNLmass'][0], var['HNLmass'][2], var['HNLmass'][1])

for sample in sample_manager.sample_list:
    if sample.name not in sample_manager.sample_names: continue
    if '-'+args.flavor+'-' not in sample.name: continue
    #
    # Load in sample and chain
    #
    chain = sample.initTree()

    chain.HNLmass = sample.getMass()
    chain.year = int(args.year)
    hist.fill(chain, sample.xsec)

from HNL.Plotting.plot import Plot
p = Plot([hist], sample.output, y_log=True)
p.drawHist(output_dir = os.path.expandvars('$CMSSW_BASE/src/HNL/Test/data/plotCrossSection'), draw_option="Hist")
Exemple #22
0
def plotLowMassRegions(signal_hist,
                       bkgr_hist,
                       tex_names,
                       out_path,
                       extra_text=None,
                       sample_groups=False):
    #Plot per grouping
    plotGeneralGroups(signal_hist,
                      bkgr_hist,
                      tex_names,
                      out_path,
                      'oldAN_lowMass',
                      extra_text=extra_text,
                      sample_groups=sample_groups)

    #
    # All groups in 1 plot
    # Need a line to distinguish leading pt regions (so at 4.5)
    #
    line_collection = [drawLineFormat(x0=4.5, color=ROOT.kRed)]
    #
    # Accompanying extra text
    #
    if extra_text is None: extra_text = []
    extra_text.append(
        extraTextFormat('p_{T}(leading) < 30 GeV',
                        tdrStyle_Left_Margin + (plotsize / 4.), 0.68, None,
                        22))
    extra_text.append(
        extraTextFormat('30 GeV < p_{T}(leading) < 55 GeV',
                        tdrStyle_Left_Margin + (plotsize * 3 / 4.), 0.68, None,
                        22))

    # Custom labels
    custom_labels = ['0-10', '10-20', '20-30', '> 30'] * 2

    if sample_groups:
        p = Plot(signal_hist,
                 tex_names,
                 bkgr_hist=bkgr_hist,
                 name='All',
                 x_name='M_{2lOS}^{min} [GeV]',
                 y_name='Events',
                 extra_text=extra_text,
                 y_log=True,
                 color_palette='AN2017',
                 color_palette_bkgr='AN2017',
                 syst_hist=0.1,
                 draw_ratio='errorsOnly')
    else:
        p = Plot(signal_hist,
                 tex_names,
                 bkgr_hist=bkgr_hist,
                 name='All',
                 x_name='M_{2lOS}^{min} [GeV]',
                 y_name='Events',
                 extra_text=extra_text,
                 y_log=True,
                 syst_hist=0.1,
                 draw_ratio='errorsOnly')

    p.drawHist(output_dir=out_path,
               draw_lines=line_collection,
               min_cutoff=0.1,
               custom_labels=custom_labels)
Exemple #23
0
                        legend_names = signal_legendnames + bkgr_legendnames
                    elif args.signalOnly:
                        legend_names = signal_legendnames
                    else:
                        legend_names = bkgr_legendnames

                    # Create plot object (if signal and background are displayed, also show the ratio)

                    draw_ratio = None if args.signalOnly or args.bkgrOnly else True
                    if args.groupSamples:
                        p = Plot(signal_hist,
                                 legend_names,
                                 c_name + '-' + v,
                                 bkgr_hist=bkgr_hist,
                                 observed_hist=observed_hist,
                                 y_log=True,
                                 extra_text=extra_text,
                                 draw_ratio=draw_ratio,
                                 year=int(year),
                                 color_palette='Didar',
                                 color_palette_bkgr='AN2017')
                        # p = Plot(signal_hist, legend_names, c_name+'-'+v, bkgr_hist = bkgr_hist, observed_hist = observed_hist, y_log = False, extra_text = extra_text, draw_ratio = draw_ratio, year = int(year),
                        # color_palette = 'Didar', color_palette_bkgr = 'AN2017')
                    else:
                        p = Plot(signal_hist,
                                 legend_names,
                                 c_name + '-' + v,
                                 bkgr_hist=bkgr_hist,
                                 y_log=False,
                                 extra_text=extra_text,
                                 draw_ratio=draw_ratio,