Beispiel #1
0
                        sig_hslice = hslice[Plotter.signal_samples]
                        SM_hslice = hslice[Plotter.nonsignal_samples]

                        # plot signal
                        if sig_hslice.values():
                            for signal in sig_hslice.values().keys():
                                fig, ax = plt.subplots()
                                fig.subplots_adjust(hspace=.07)

                                sig_hist = sig_hslice[signal].integrate(
                                    'process')
                                Plotter.plot_1D(
                                    *sig_hist.values().values(),
                                    sig_hist.axis(xaxis_name).edges(),
                                    xlabel=new_xtitle,
                                    xlimits=x_lims,
                                    ax=ax,
                                    label='%s, %s' %
                                    (plt_tools.get_label(
                                        signal[0], styles.styles),
                                     signal[0].split('_')[-1]))
                                ax.legend(loc='upper right')
                                # add lepton/jet multiplicity label
                                ax.text(0.02,
                                        0.85,
                                        "%s, %s\n%s" %
                                        (lep_cats[lepcat], jet_mults[jmult],
                                         btag_cats[btagregion]),
                                        horizontalalignment='left',
                                        verticalalignment='bottom',
                                        transform=ax.transAxes)
                                hep.cms.label(
Beispiel #2
0
        for ttbar_type in sorted(set([key[1] for key in histo.values().keys()])):
            decay_label = "%s %s" % (plt_tools.get_label(dataset, styles), ttdecay_types[ttbar_type])
            #decay_label = ttdecay_types[ttbar_type]
            pltdir = os.path.join(outdir, dataset, ttbar_type) if isSignal(dataset) else os.path.join(outdir, "ttJets", ttbar_type)
            if not os.path.isdir(pltdir):
                os.makedirs(pltdir)
            for genobj, (objlabel, mass_range) in objects[ttbar_type].items():
                new_xtitle = xtitle.replace("obj", objlabel)
                if hname == "mass":
                    x_lims = mass_range
                tt_histo = histo[genobj, ttbar_type].integrate("objtype").integrate("ttdecay")
        
                fig, ax = plt.subplots()
                fig.subplots_adjust(hspace=.07)
    
                Plotter.plot_1D(tt_histo.values()[()], tt_histo.axis(xaxis_name).edges(), xlabel=new_xtitle, xlimits=x_lims, ax=ax, histtype="step")
                hep.cms.label(ax=ax, data=False, paper=False, year=args.year, lumi=round(lumi_to_use, 1))

                #set_trace()
                    # add lepton/jet multiplicity label
                if isSignal(dataset):
                    if "Int" in dataset:
                        sig_type = "Int, w $<$ 0" if "Int_neg" in dataset else "Int, w $>$ 0"
                    else:
                        sig_type = "Res"
                    sig_label = "%s\n%s" % (decay_label, sig_type)
                    ax.text(
                        0.95, 0.85, sig_label,
                        horizontalalignment="right", verticalalignment="bottom", transform=ax.transAxes
                    )
                else:
Beispiel #3
0
                plot.plot1d(
                    hslice,
                    overlay=hslice.axes()[0].name,
                    ax=ax,
                    clear=False,
                    line_opts={'linestyle': '-'},
                )

                # norm
                #set_trace()
                for corr in sorted(hslice.values().keys()):
                    Plotter.plot_1D(values=hslice.values()[corr] /
                                    np.sum(hslice.values()[corr]),
                                    bins=hslice.dense_axes()[0].edges(),
                                    ax=ax_norm,
                                    xlimits=x_lims,
                                    xlabel=xtitle,
                                    ylabel='Probability Density',
                                    label=corr[0],
                                    histtype='step')

                ## set legend and corresponding colors
            handles, labels = ax.get_legend_handles_labels()
            for idx, label in enumerate(labels):
                if label == '4Jets':
                    labels[idx] = jet_mults[label]
                    handles[idx].set_color('b')
                    handles[idx].set_linewidth(2)
                elif label == '5PJets':
                    labels[idx] = jet_mults[label]
                    handles[idx].set_color('g')
                        }  # use SL+DL+Had events

                        fig, (ax, rax) = plt.subplots(
                            2,
                            1,
                            gridspec_kw={"height_ratios": (3, 1)},
                            sharex=True)
                        fig.subplots_adjust(hspace=.07)

                        for rewt, hslice in allTT_hslices.items():
                            vals, bins = hslice.values()[(
                            )], hslice.axis(xaxis_name).edges()
                            ax = Plotter.plot_1D(
                                vals,
                                bins,
                                xlimits=x_lims,
                                ax=ax,
                                histtype='step',
                                label=rewt_style_dict[rewt][0],
                                color=rewt_style_dict[rewt][1])

                            if (rewt != nominal_jobid) and (
                                    nominal_jobid in rewt_style_dict.keys()):
                                ratio_vals, ratio_bins = Plotter.get_ratio_arrays(
                                    num_vals=vals,
                                    denom_vals=allTT_hslices[nominal_jobid].
                                    values()[()],
                                    input_bins=bins)
                                rax.step(ratio_bins,
                                         ratio_vals,
                                         where='post',
                                         **{
Beispiel #5
0
                    #set_trace()
                    hslices = {
                        rewt:
                        histo['ttJets', jmult, btagregion,
                              lepcat].integrate('jmult').integrate('lepcat').
                        integrate('btag').integrate('process')
                        for rewt, histo in histos.items()
                    }
                    logy_min, logy_max = 1e-1, 0.
                    for rewt, hslice in hslices.items():
                        vals, bins = hslice.values()[(
                        )], hslice.axis(xaxis_name).edges()
                        ax = Plotter.plot_1D(vals,
                                             bins,
                                             xlimits=x_lims,
                                             ytitle='$t\\bart$ Events',
                                             ax=ax,
                                             histtype='step',
                                             label=rewt_style_dict[rewt][0],
                                             color=rewt_style_dict[rewt][1])

                        if rewt != nominal_jobid:
                            ratio_vals, ratio_bins = Plotter.get_ratio_arrays(
                                num_vals=vals,
                                denom_vals=hslices[nominal_jobid].values()[()],
                                input_bins=bins)
                            rax.step(ratio_bins,
                                     ratio_vals,
                                     where='post',
                                     **{
                                         'linestyle': '-',
                                         'color': rewt_style_dict[rewt][1]
                    print(', '.join([jmult, lepcat, btagregion, hname,
                                     sample]))
                    fig, ax = plt.subplots()
                    fig.subplots_adjust(hspace=.07)

                    hslice = histo[sample, jmult, btagregion,
                                   lepcat].integrate('jmult').integrate(
                                       'lepcat').integrate('btag').integrate(
                                           'dataset')

                    if hslice.values():
                        Plotter.plot_1D(
                            *hslice.values().values(),
                            histo.axis(xaxis_name).edges(),
                            xlimits=(-5., 5.)
                            if sample.startswith('QCD') else x_lims,
                            xlabel=xtitle,
                            ylabel='Events (Unweighted)',
                            ax=ax,
                            label='%s\n%s' %
                            (sample, format(lumi_correction[sample], '.3f')))
                        ax.legend(loc='upper right')

                        # add lepton/jet multiplicity label
                        ax.text(0.02,
                                0.88,
                                "%s, %s\n%s" %
                                (lep_cats[lepcat], jet_mults[jmult],
                                 btag_cats[btagregion]),
                                fontsize=rcParams['font.size'] * 0.75,
                                horizontalalignment='left',
                                verticalalignment='bottom',
                                    for sig in samples:
                                        boson, mass, width, shape = sig.split(
                                            '_')
                                        opts = Plotter.styles.styles[width]

                                        pos_histo = histo[
                                            '%s_pos' % sig, jmult, btagregion,
                                            lepcat].integrate(
                                                'jmult'
                                            ).integrate('lepcat').integrate(
                                                'btag').integrate('dataset')
                                        Plotter.plot_1D(
                                            pos_histo.values()[()],
                                            pos_histo.dense_axes()[0].edges(),
                                            ax=pos_ax,
                                            xlimits=x_lims,
                                            xlabel=xtitle,
                                            color=opts['color'],
                                            label=opts['name'],
                                            histtype='step')
                                        neg_histo = histo[
                                            '%s_neg' % sig, jmult, btagregion,
                                            lepcat].integrate(
                                                'jmult'
                                            ).integrate('lepcat').integrate(
                                                'btag').integrate('dataset')
                                        Plotter.plot_1D(
                                            neg_histo.values()[()],
                                            neg_histo.dense_axes()[0].edges(),
                                            ax=neg_ax,
                                            xlimits=x_lims,
                        os.makedirs(pltdir)

                    print(', '.join([jmult, lepcat, btagregion, hname])) 
                    hslice = histo[:, jmult, btagregion, lepcat].integrate('jmult').integrate('lepcat').integrate('btag')

                    if hname == 'Lep_iso':
                        if args.lepton == 'Muon':
                            x_lims = (0., 0.15) if lepcat == 'Tight' else (0.15, 1.)
                        if args.lepton == 'Electron':
                            x_lims = (0., 0.1) if lepcat == 'Tight' else (0., 0.5)

                        # plot original yields
                    fig, ax = plt.subplots()
                    fig.subplots_adjust(hspace=.07)

                    Plotter.plot_1D(hslice.values()[('Before',)], hslice.axis(xaxis_name).edges(), xlimits=x_lims, ax=ax, label='Runs $<$ 319077')
                    Plotter.plot_1D(hslice.values()[('After',)], hslice.axis(xaxis_name).edges(), xlimits=x_lims, xlabel=xtitle, color='r', ax=ax, label='Runs $\\geq$ 319077')
                    ax.legend(loc='upper right')

                    if hname == 'Jets_njets':
                        print(jmult)
                        #set_trace() 
                        rows = [("Lumi: %s fb^-1" % format(data_lumi_year['%ss' % args.lepton]/1000., '.1f'), "Yield", "Error", "Frac")]
                        rows += [("Runs < 319077", format(sum(hslice.values(overflow='all')[('Before',)]), '.1f'), format(np.sqrt(sum(hslice.values(overflow='all', sumw2=True)[('Before',)][1])), '.1f'),
                            format(sum(hslice.values(overflow='all')[('Before',)])/sum(hslice.sum('hem').values(overflow='all')[()]), '.3f'))]
                        rows += [("Runs >= 319077", format(sum(hslice.values(overflow='all')[('After',)]), '.1f'), format(np.sqrt(sum(hslice.values(overflow='all', sumw2=True)[('After',)][1])), '.1f'),
                            format(sum(hslice.values(overflow='all')[('After',)])/sum(hslice.sum('hem').values(overflow='all')[()]), '.3f'))]
                        rows += [("Total", format(sum(hslice.sum('hem').values(overflow='all')[()]), '.1f'), format(np.sqrt(sum(hslice.sum('hem').values(overflow='all', sumw2=True)[()][1])), '.1f'), "")]

                        frac_name = '%s_yields_and_fracs.txt' % '_'.join([jmult, args.lepton, lepcat, btagregion])
                        plt_tools.print_table(rows, filename=os.path.join(pltdir, frac_name), print_output=True)
        fig, ax = plt.subplots()
        fig.subplots_adjust(hspace=.07)
        ax.axhline(1, **{"linestyle": "--", "color": (0, 0, 0, 0.5), "linewidth": 1})
        ax.text(
            0.02, 0.90, "$t\\bart \\rightarrow e/\mu + jets$\nparton level",
            fontsize=rcParams["font.size"], horizontalalignment="left", verticalalignment="bottom", transform=ax.transAxes
        )
    
    #set_trace()
    for year in years_to_run:
        histo = ratios[year][var] # get histogram

        if histo._dimension == 1:
            orig_bins, orig_vals = histo._axes, histo._values
                # plot original distribution
            Plotter.plot_1D(orig_vals, orig_bins, xlabel=var_opts[var]["xtitle"], ylabel=var_opts[var]["ytitle"], color=year_opts[year]["col"], ax=ax, label="%s Original" % year_opts[year]["leg_title"])

                # get interpolated values from ROOT Interpolate
            orig_ratio_hist = Hist(orig_bins, name="", title="")
            for xbin in range(1, orig_bins.size):
                orig_ratio_hist[xbin] = orig_vals[xbin-1]

            output_bins = np.arange(min(orig_bins), max(orig_bins)+10, 10)
            interped_array = np.zeros(output_bins.size-1)
            for xbin in range(output_bins.size-1):
                interped_array[xbin] = orig_ratio_hist.Interpolate(output_bins[xbin])

            Plotter.plot_1D(interped_array, output_bins, xlabel=var_opts[var]["xtitle"], ylabel=var_opts[var]["ytitle"], color=year_opts[year]["col"], ax=ax, label="%s Interp" % (year_opts[year]["leg_title"]), linestyle="--")

            if args.save_ratios:
                lookup = dense_lookup(*(interped_array, output_bins))