Beispiel #1
0
def plot(template, name):
    plt.clf()

    #ax = hist.plot2d(template, xaxis = "jet_rho",  patch_opts={"vmin":0.5, "vmax":0.99})#,xoverflow='all',yoverflow='all')
    ax = hist.plot2d(template,
                     xaxis="jet_rho",
                     patch_opts={
                         "vmin": 0.5,
                         "vmax": 1.
                     })  #,xoverflow='all',yoverflow='all')
    cmstext = plt.text(0.0,
                       1.,
                       "CMS",
                       fontsize=12,
                       horizontalalignment='left',
                       verticalalignment='bottom',
                       fontweight='bold',
                       transform=ax.transAxes)
    addtext = plt.text(0.11,
                       1.,
                       "Simulation Preliminary",
                       fontsize=10,
                       horizontalalignment='left',
                       verticalalignment='bottom',
                       style='italic',
                       transform=ax.transAxes)

    plt.ylim(200, 1200)
    plt.xlim(-5.5, -2)
    plt.savefig('plots/' + name + '.pdf')
    plt.savefig('plots/' + name + '.png')
def make_2d_hist(h,
                 xaxis,
                 title=None,
                 zscale='linear',
                 text_opts=None,
                 **kwargs):
    """
    more kwargs see `coffea.hist.plot2d`
    (https://github.com/CoffeaTeam/coffea/blob/master/coffea/hist/plot.py#L388)
    """
    import matplotlib.pyplot as plt
    from coffea import hist

    fig, ax = plt.subplots(1, 1, figsize=(8, 6))
    if zscale == 'log':
        from matplotlib.colors import LogNorm
        hist.plot2d(h,
                    xaxis,
                    ax=ax,
                    patch_opts=dict(norm=LogNorm()),
                    text_opts=text_opts)
    else:
        hist.plot2d(h, xaxis, ax=ax, text_opts=text_opts)

    if 'xlabel' in kwargs: ax.set_xlabel(kwargs['xlabel'])
    if 'ylabel' in kwargs: ax.set_ylabel(kwargs['ylabel'])
    ax.set_xlabel(ax.get_xlabel(), x=1, ha='right')
    ax.set_ylabel(ax.get_ylabel(), y=1, ha="right")

    if 'xlim' in kwargs: ax.set_xlim(*kwargs['xlim'])
    if 'ylim' in kwargs: ax.set_ylim(*kwargs['ylim'])

    ax.set_title(title, x=0.0, ha="left")
    ax.text(1,
            1,
            '59.74/fb (13TeV)',
            ha='right',
            va='bottom',
            transform=ax.transAxes)

    return fig, ax
Beispiel #3
0
def responsematrix():
    for btype in ["Bu", "Bs", "Bd"]:
        if btype == "Bu":
            dataset_bname = "Bu2KJpsi2KMuMu"
            histogram_bname = "BuToKMuMu"
            axis_bname = "BToKMuMu"
        elif btype == "Bs":
            dataset_bname = "Bs2PhiJpsi2KKMuMu"
            histogram_bname = "BsToKKMuMu"
            axis_bname = "BsToKKMuMu"
        elif btype == "Bd":
            dataset_bname = "Bd2KstarJpsi2KPiMuMu"
            histogram_bname = "BdToKPiMuMu"
            axis_bname = "BdToKPiMuMu"
        for selection in ["tag", "probe", "inclusive"]:
            if selection == "inclusive":
                hist2d = histograms[btype][
                    f"Truth{histogram_bname}_truthpt_recopt"].integrate(
                        "dataset", ([f"{dataset_bname}_inclusive"])).integrate(
                            "selection", "inclusive")
            elif selection == "tag":
                hist2d = histograms[btype][
                    f"Truth{histogram_bname}_truthpt_recopt"].integrate(
                        "dataset", ([f"{dataset_bname}_inclusive"])).integrate(
                            "selection", "matched_tag")
            elif selection == "probe":
                hist2d = histograms[btype][
                    f"Truth{histogram_bname}_truthpt_recopt"].integrate(
                        "dataset",
                        ([f"{dataset_bname}_probefilter"])).integrate(
                            "selection", "matched_probe")
            fig, ax = plt.subplots(1, 1, figsize=(
                10, 7))  #, gridspec_kw={"height_ratios": (3, 1)}, sharex=True)
            hist2d = hist2d.rebin(f"reco_pt", coarse_reco_pt_axis)
            hist2d = hist2d.rebin(f"truth_pt", coarse_truth_pt_axis)
            hist.plot2d(hist2d, xaxis="coarse_reco_pt", ax=ax)
            plt.tight_layout()
            fig.savefig(
                f"{figure_directory}/responsematrix_{btype}_{selection}.png")
Beispiel #4
0
def test_plot2d():
    # histogram creation and manipulation
    from coffea import hist
    # matplotlib
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt

    lepton_kinematics = fill_lepton_kinematics()

    # looking at lepton pt for all eta
    muon_kinematics = lepton_kinematics.integrate("flavor", "muon")

    fig, ax, primitives = hist.plot2d(muon_kinematics, "eta")
Beispiel #5
0
def test_plot2d():
    # histogram creation and manipulation
    from coffea import hist
    # matplotlib
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    plt.switch_backend('agg')

    lepton_kinematics = fill_lepton_kinematics()

    # looking at lepton pt for all eta
    muon_kinematics = lepton_kinematics.integrate("flavor", "muon")

    ax = hist.plot2d(muon_kinematics, "eta")

    return ax.figure
def plot_iso_2d(output, isotype, njet='both', issignal=False):
    """
    make 2D plot with each leptonjet isolation value on XY axis. 2mu2e left/4mu right.

    :param hist.Hist output: histogram
    :param str isotype: all05/nopu05/dbeta
    :param str njet: both/sr/cr
    :param bool issignal: `output` from signal?
    :return: (fig, axes) / dictionary of (fig, ax)
    :rtype: tuple / dict
    """

    if issignal:
        res = {}
        for d in output['ljpfiso'].identifiers('dataset'):
            res[str(d)] = plt.subplots(1, 1, figsize=(7, 5))
            fig, ax = res[str(d)]
            histo = output['ljpfiso'].integrate('dataset', d).integrate(
                'isotype', isotype)
            chan_ = str(d).split('/')[0]
            if njet == 'both':
                hist.plot2d(
                    histo.integrate('channel', chan_).sum('njet'),
                    xaxis='lj0iso',
                    ax=ax,
                )
            elif njet == "sr":
                hist.plot2d(
                    histo.integrate('channel',
                                    chan_).integrate('njet', slice(0, 4)),
                    xaxis='lj0iso',
                    ax=ax,
                )
            elif njet == 'cr':
                hist.plot2d(
                    histo.integrate('channel',
                                    chan_).integrate('njet', slice(4, 10)),
                    xaxis='lj0iso',
                    ax=ax,
                )

            ax.set_title(f'[{chan_}] leptonjet isolation ({isotype})',
                         x=0,
                         ha="left")
            ax.text(1,
                    1,
                    '59.74/fb (13TeV)',
                    ha='right',
                    va='bottom',
                    transform=ax.transAxes)
            if chan_ == '2mu2e':
                ax.set_xlabel('EGM-type lj isolation value', x=1, ha='right')
                ax.set_ylabel('Mu-type lj isolation value', y=1, ha='right')
            if chan_ == '4mu':
                ax.set_xlabel('Mu-type lj0 isolation value', x=1, ha='right')
                ax.set_ylabel('Mu-type lj1 isolation value', y=1, ha='right')
        return res

    else:
        fig, axes = plt.subplots(1, 2, figsize=(14, 5))
        histo = output['ljpfiso_cat'].sum('cat').integrate('isotype', isotype)
        if njet == "both":
            hist.plot2d(histo.integrate('channel', '2mu2e').sum('njet'),
                        xaxis='lj0iso',
                        ax=axes[0],
                        patch_opts=dict(norm=LogNorm()))
            hist.plot2d(histo.integrate('channel', '4mu').sum('njet'),
                        xaxis='lj0iso',
                        ax=axes[1],
                        patch_opts=dict(norm=LogNorm()))
        elif njet == "sr":
            hist.plot2d(histo.integrate('channel', '2mu2e').integrate(
                'njet', slice(0, 4)),
                        xaxis='lj0iso',
                        ax=axes[0],
                        patch_opts=dict(norm=LogNorm()))
            hist.plot2d(histo.integrate('channel',
                                        '4mu').integrate('njet', slice(0, 4)),
                        xaxis='lj0iso',
                        ax=axes[1],
                        patch_opts=dict(norm=LogNorm()))
        elif njet == 'cr':
            hist.plot2d(histo.integrate('channel',
                                        '2mu2e').integrate('njet',
                                                           slice(4, 10),
                                                           overflow='over'),
                        xaxis='lj0iso',
                        ax=axes[0],
                        patch_opts=dict(norm=LogNorm()))
            hist.plot2d(histo.integrate('channel',
                                        '4mu').integrate('njet',
                                                         slice(4, 10),
                                                         overflow='over'),
                        xaxis='lj0iso',
                        ax=axes[1],
                        patch_opts=dict(norm=LogNorm()))

        axes[0].set_title(f'[2mu2e] leptonJet isolation ({isotype})',
                          x=0.0,
                          ha="left")
        axes[0].set_xlabel('EGM-type lj isolation value')
        axes[0].set_ylabel('Mu-type lj isolation value')
        axes[1].set_title(f'[4mu] leptonJet isolation ({isotype})',
                          x=0.0,
                          ha="left")
        axes[1].set_xlabel('Mu-type lj0 isolation value')
        axes[1].set_ylabel('Mu-type lj1 isolation value')
        for ax in axes:
            ax.text(1,
                    1,
                    '59.74/fb (13TeV)',
                    ha='right',
                    va='bottom',
                    transform=ax.transAxes)
            ax.set_xlabel(ax.get_xlabel(), x=1.0, ha="right")
            ax.set_ylabel(ax.get_ylabel(), y=1.0, ha="right")
        return fig, axes
Beispiel #7
0
        'node0_score',
        'score',
        data=[],
        bins=score_bins,
        log=False,
        normalize=False,
        axis_label=r'score',
        shape=True,
        ymax=0.35,
        new_colors=my_colors,
        new_labels=my_labels,
        order=['TTW'],
        signals=['topW_v3', 'topW_EFT_cp8', 'topW_EFT_mix'],
        omit=[
            'DoubleMuon', 'MuonEG', 'EGamma', 'diboson', 'ttbar', 'TTH', 'TTZ'
        ],
        save=os.path.expandvars(plot_dir + '/SS/ML_node0_score_shape'),
    )

    fig, ax = plt.subplots(1, 1, figsize=(10, 10))
    ax = hist.plot2d(
        output['chargeFlip_vs_nonprompt']['ttbar'].sum('n_ele').sum('dataset'),
        xaxis='n1',
        ax=ax,
        text_opts={'format': '%.3g'},
        patch_opts={},
    )
    ax.set_xlabel(r'$N_{charge flips}$')
    ax.set_ylabel(r'$N_{nonprompt}$')
    fig.savefig(plot_dir + '/SS/nChargeFlip_vs_nNonprompt_ttbar')
Beispiel #8
0
        ymin = 1.
        ymax = -1.
        for dataset, values_arr in hy[(sels), :].values().items():
            if np.max(values_arr) > ymax:
                ymax = np.max(values_arr)
        ax_y.set_ylim(1., ymax * 10.)
        plt.tight_layout()
        fig_y.savefig(
            f"{figure_directory}/kinematic/data/{channel}_{side}_y_SR.png")
        plt.close(fig_y)

        # 2D plots
        fig_pt_mass, ax_pt_mass = plt.subplots()
        h_pt_mass = hists[f"{channel}_fit_pt_y_mass"].integrate(
            "fit_y", y_slice).integrate("selection", (f"{side}_HLT_Mu9_IP6"))
        hist.plot2d(h_pt_mass, xaxis="fit_mass")
        fig_pt_mass.savefig(
            f"{figure_directory}/kinematic/data/{channel}_{side}_pt_mass_SR.png"
        )
        plt.close(fig_pt_mass)

        fig_pt_y, ax_pt_y = plt.subplots()
        h_pt_y = hists[f"{channel}_fit_pt_y_mass"].integrate(
            "fit_mass").integrate("selection", (f"{side}_HLT_Mu9_IP6"))
        hist.plot2d(h_pt_y, xaxis="fit_y")
        fig_pt_y.savefig(
            f"{figure_directory}/kinematic/data/{channel}_{side}_pt_y_SR.png")
        plt.close(fig_pt_y)

        # pT subslices
        for pt_subslice in [