コード例 #1
0
def create_legend(xlo, xhi, yhi, n_plots):
    """
    Create a legend that fits all of the keys
    """
    leg = setup_legend(xlo, yhi - n_plots * 0.045, xhi, yhi)
    leg.SetTextSize(0.03)
    return leg
コード例 #2
0
def make_2d_contour_plot(input_files, var_pair):
    """Make one plot of all input_files"""
    varx, vary = var_pair
    graphs = [
        f.Get('corr_2d_{}_{}_1sigma'.format(varx, vary)) for f in input_files.values()
    ]

    # These are possibly stored in reversed order so the axis have to be
    # flipped
    if var_pair == ('r_chic1_jpsi', 'r_chic2_jpsi'):
        # try to get them the other way around
        graphs_2 = [
            f.Get('corr_2d_{}_{}_1sigma'.format(vary, varx)) for f in input_files.values()
        ]
        # Check which graphs are not present and replace them with the flipped axis version
        for i, g in enumerate(graphs):
            if not g:
                graphs[i] = flip_axis(graphs_2[i])


    if len(graphs) == 1:
        leg = None
        leg_entries = None
    else:
        leg = setup_legend(0.75, 0.8, 0.92, 0.8 + len(graphs) * 0.035)
        leg_entries = input_files.keys()

    can = mkplot(graphs, drawOpt='L', attr=default_attributes(line=1),
                 leg=leg, legEntries=leg_entries, legOpt='L',
                 yLabel=get_label(vary), yRange=get_range(vary),
                 xLabel=get_label(varx), xRange=get_range(varx))

    return can
コード例 #3
0
def make_plot(lth_g, dlth_g, lth2_g):
    """
    Make the plot as a function of pT/M according to Carlos specifications
    """
    lth_g = scale_graph_x(lth_g, 1 / m_psiPDG)
    dlth_g = scale_graph_x(dlth_g, 1 / m_psiPDG)
    lth2_g = scale_graph_x(lth2_g, 1 / m_psiPDG)
    lth2_g = shift_graph_horizontal(lth2_g, 0.1)

    leg = setup_legend(0.675, 0.74, 0.88, 0.88)
    can = mkplot([lth_g],
                 drawOpt='P',
                 attr=[ATTR['lth']],
                 xRange=XRANGE,
                 xLabel=PTMLABEL,
                 yRange=YRANGE,
                 yLabel='#lambda',
                 leg=leg,
                 legEntries=[YLABELS['lth']])
    mkplot([dlth_g, lth2_g],
           drawOpt='samePE',
           can=can,
           attr=[ATTR['dlth'], ATTR['lth2']],
           leg=leg,
           legEntries=[YLABELS['dlth'], YLABELS['lth2']])

    add_auxiliary_info(can, 2012, prelim=True, pos='left')

    return can
コード例 #4
0
def psi_pol(gfile):
    """psi(2S) and J/psi polarization plot"""
    leg = setup_legend(0.6, 0.2, 0.88, 0.36)

    can = mkplot([gfile.Get(n) for n in ['psip_pol_direct', 'jpsi_pol_full']],
                 drawOpt='L',
                 colors=[PSI_COL, JPSI_COL],
                 leg=leg,
                 legEntries=['#psi(2S) model', 'J/#psi model'],
                 legOpt='L',
                 xRange=[2, 30],
                 xLabel=PTM_LABEL,
                 yLabel=POL_LABEL,
                 yRange=[-1, 1])

    mkplot([gfile.Get(n) for n in ['psi2S_CMS_pol', 'jpsi_CMS_pol']],
           attr=[{
               'color': PSI_COL,
               'marker': 20,
               'size': 0.75
           }, {
               'color': JPSI_COL,
               'marker': 21,
               'size': 0.75
           }],
           can=can,
           drawOpt='PE same',
           leg=leg,
           legEntries=['#psi(2S) CMS', 'J/#psi CMS'])

    return can
コード例 #5
0
def psi2S_cs(gfile):
    """psi(2S) cross section plot"""
    names = ['psi2S_CMS_cs', 'psi2S_ATLAS_cs']
    leg_entries = [
        '#psi(2S) #rightarrow #mu#mu CMS',
        '#psi(2S) #rightarrow J/#psi #pi#pi ATLAS'
    ]

    graphs, leg_entries = _get_present(gfile, names, leg_entries)

    leg = setup_legend(0.5, 0.7, 0.88, 0.86)
    can = mkplot(graphs,
                 drawOpt='PE',
                 logy=True,
                 logx=True,
                 attr=DATA_ATTR,
                 leg=leg,
                 legEntries=leg_entries,
                 xRange=CS_RANGE,
                 xLabel=PTM_LABEL,
                 yLabel=CS_LABEL)

    mkplot(gfile.Get('psip_cs_direct'),
           can=can,
           drawOpt='Lsame',
           leg=leg,
           legEntries=['best fit'],
           legOpt='L')

    return can
コード例 #6
0
def chic_ratio_cs(gfile):
    """chic cross section ratio plot"""
    leg = setup_legend(0.6, 0.7, 0.88, 0.78)

    can = mkplot(scale_graph(r.TGraph(gfile.Get('chic_ratio_cs_full')),
                             B_CHIC2_JPSI / B_CHIC1_JPSI),
                 drawOpt='L',
                 attr=[{
                     'color': 1,
                     'line': 1,
                     'width': 2
                 }],
                 yRange=[0, 1],
                 xRange=[2, 10],
                 xLabel=PTM_LABEL,
                 yLabel='ratio',
                 leg=leg,
                 legEntries=['model'],
                 legOpt='L')

    mkplot(scale_graph(gfile.Get('chic_ratio_CMS_cs'),
                       B_CHIC2_JPSI / B_CHIC1_JPSI),
           drawOpt='PE same',
           can=can,
           attr=[{
               'color': COL[0],
               'marker': 20,
               'size': 1.8
           }],
           leg=leg,
           legEntries=['B #chi_{c2} / B #chi_{c1} CMS'])

    return can
コード例 #7
0
def make_ratio_plot(uncorr_ratio, corr_ratio, variable):
    """
    Make the comparison plot of corrected and uncorrected graphs
    """
    leg = setup_legend(*LEGEND_POS[variable])
    leg.SetTextSize(0.03)

    can = mkplot(corr_ratio,
                 drawOpt='PE',
                 attr=[{
                     'color': 1,
                     'size': 1,
                     'marker': 20
                 }],
                 yLabel=YLABELS.get('r_chic2_chic1'),
                 yRange=[0, 0.75],
                 leg=leg,
                 legEntries=['corrected'],
                 **VAR_PLOT[variable])

    shift = HORIZONTAL_SHIFT[variable]
    mkplot([
        shift_graph_horizontal(rescale_graph(uncorr_ratio, corr_ratio), shift),
        shift_graph_horizontal(uncorr_ratio, -shift)
    ],
           can=can,
           drawOpt='samePE',
           attr=default_attributes(open_markers=True),
           leg=leg,
           legEntries=['fitted (scaled)', 'fitted'])

    add_auxiliary_info(can, 2012, prelim=True)

    return can
コード例 #8
0
def make_limit_plot(graphs, variable):
    """
    Make a limit plot
    """
    leg = setup_legend(0.675, 0.74, 0.88, 0.88)
    can = mkplot(graphs.values(),
                 xRange=[8, 30],
                 xLabel=PTLABEL,
                 drawOpt='PE',
                 yRange=[-0.5, 1.1],
                 yLabel=YLABELS[variable],
                 leg=leg,
                 legOpt='L',
                 legEntries=['{} % C.L.'.format(v) for v in graphs.keys()])

    mkplot(r.TLine(8, -0.33333, 30, -0.33333),
           can=can,
           drawOpt='same',
           attr=[{
               'color': 12,
               'line': 7,
               'linewidth': 2
           }])

    add_auxiliary_info(can, 2012, prelim=True, pos='left')

    return can
コード例 #9
0
def make_plot(contours, best_fits, leg_keys, **kwargs):
    """Make the plot and return the canvas"""
    conts = contours.values()
    conf_levels = contours.keys()

    leg_coords = (0.2, 0.6, 0.4, 0.8)
    if len(conf_levels) > 1:
        leg_coords = (0.2, 0.6, 0.4, 0.84)

    leg = setup_legend(*leg_coords)


    can = mkplot(conts[0], drawOpt='L', leg=leg, legEntries=leg_keys,
                 attr=CONT_ATTRS[0], legOpt='L', **kwargs)

    if len(conts) > 1:
        leg_graphs = [r.TGraph(1, np.array([-1000]), np.array([-10000]))
                      for _ in conf_levels]
        mkplot(leg_graphs, drawOpt='Lsame', can=can, attr=LEG_C_ATTR,
               leg=leg, legEntries=['{:.1f}% CL'.format(v) for v in conf_levels],
               legOpt='L')

        for i in range(1, len(contours)):
            mkplot(conts[i], can=can, drawOpt='Lsame', attr=CONT_ATTRS[i])

    # best fit points
    mkplot(best_fits, drawOpt='Psame', can=can, attr=BF_ATTRS)
    leg_graph = r.TGraph(1, np.array([-1000]), np.array([-10000]))
    mkplot(leg_graph, drawOpt='Psame', can=can, leg=leg, legEntries=['best fit'],
           attr=LEG_BF_ATTR, legOpt='P')


    return can
コード例 #10
0
def make_ratio_plot(ratio, analytic_scens, variable):
    """
    Make the comparison plot of the ratio and the analytical scenarios
    """
    can = mkplot(ratio,
                 drawOpt='PE',
                 attr=[{
                     'color': 1,
                     'size': 1,
                     'marker': 20
                 }],
                 yLabel=YLABELS.get('r_chic2_chic1'),
                 yRange=[0, 0.75],
                 **VAR_PLOT[variable])

    chi2_ndfs = get_chi2_ndf(ratio, analytic_scens)

    leg = setup_legend(0.2, 0.15, 0.65, 0.3)
    mkplot(analytic_scens.values(),
           drawOpt='sameL',
           can=can,
           attr=ANALYTIC_ATTRS,
           leg=leg,
           legEntries=analytic_scens.keys(),
           legOpt='L')

    add_auxiliary_info(can, 2012, prelim=True)
    return can
コード例 #11
0
    def _plot_tot_long_signs(state):
        index = getattr(state_enum, f's{state}')
        sdc_long, sdc_tot = sdcs.lng[index], sdcs.tot[index]
        leg = setup_legend(0.75, 0.8, 0.93, 0.94)
        can = mkplot(
            [g for g in sdc_tot.asAlwaysPositiveGraphs() if g.GetN() > 0],
            drawOpt='P',
            logy=True,
            attr=ATTRS_LT[:2],
            xRange=XRANGE,
            xLabel='p_{T}/M',
            legOpt='P',
            leg=leg,
            legEntries=('tot +', 'tot -'),
            ydscale=0.1,
            yLabel=f'{state} SDCs')

        return mkplot(
            [g for g in sdc_long.asAlwaysPositiveGraphs() if g.GetN() > 0],
            can=can,
            drawOpt='P same',
            attr=ATTRS_LT[2:],
            legOpt='P',
            leg=leg,
            legEntries=('long +', 'long -'))
コード例 #12
0
def costh_ratios(gfile):
    """Make the costh ratio plots"""
    graphs = [
        gfile.Get(n) for n in list_obj(gfile, 'TGraph', 'chic_CMS_pol_ptM')
    ]

    cans = []
    for graph in graphs:
        ptm_s = graph.GetName().split('_')[-1]
        ptm = float(ptm_s.replace('p', '.'))

        leg = setup_legend(0.55, 0.7, 0.88, 0.78)
        can = mkplot(graph,
                     drawOpt='PE',
                     attr=DATA_ATTR,
                     leg=leg,
                     legEntries=['CMS @ p_{{T}} / M = {:.2f}'.format(ptm)],
                     xRange=[0, 1],
                     xLabel=CTH_LABEL,
                     yRange=[0.2, 0.6],
                     yLabel='#chi_{c2} / #chi_{c1}')

        model = gfile.Get('chic_pol_ptM_{}'.format(ptm_s))
        mkplot(model,
               can=can,
               drawOpt='Lsame',
               leg=leg,
               legEntries=['model'],
               legOpt='L')

        cans.append((ptm_s, can))

    return cans
コード例 #13
0
    def _plot_bin(self,
                  wsp,
                  full_data,
                  bin_name,
                  bin_borders,
                  n_bins,
                  publication=False):
        """Make the distribution plot for a given bin"""
        leg = setup_legend(*self.plot_config['legpos'])

        # In order to remove horizontal error bars from the plot the option
        # XErrorSize(0) has to be used, but that breaks the calculation of the
        # chi2 wrt a given curve since the x-errors are used to determine the
        # bin and the corresponding mean value of the data points in the bin
        # which is necessary to calculate the point at which the curve should be
        # evaluated. So here I plot two curves, the one labeled 'data_hist_plot'
        # is the visible one, whereas the one labeled 'data_hist' will be the
        # with associated x uncertainties that can be used to calculate the chi2
        # This will only be done in "publication mode"
        if publication:
            data_args = (rf.MarkerSize(0.5), rf.Name('data_hist_plot'),
                         rf.XErrorSize(0))
            leg.SetTextSize(0.04)
        else:
            data_args = (rf.MarkerSize(0.7), rf.Name('data_hist'))

        fit_var = get_var(wsp, self.fit_var)
        frame = fit_var.frame(rf.Bins(n_bins))

        cut = get_bin_cut(self.bin_cut_vars, bin_borders)
        full_data.reduce(cut).plotOn(frame, *data_args)
        if publication:
            full_data.reduce(cut).plotOn(frame, rf.MarkerSize(0),
                                         rf.Name('data_hist'), rf.LineColor(0),
                                         rf.LineWidth(0))

            leg.AddEntry(frame.getHist('data_hist_plot'), 'Data', 'PE')

        full_pdf = wsp.pdf(self.full_model + '_' + bin_name)
        full_pdf.plotOn(frame, rf.LineWidth(2), rf.Name('full_pdf_curve'))
        leg.AddEntry(frame.getCurve('full_pdf_curve'), 'Fit result', 'l')

        for name, settings in self.components:
            full_pdf.plotOn(frame, rf.Components(name + '_' + bin_name),
                            rf.LineStyle(settings['line']),
                            rf.LineColor(settings['color']), rf.LineWidth(2),
                            rf.Name(name))
            leg.AddEntry(frame.getCurve(name), settings['label'], 'l')

        # calculate the bin width in MeV
        bw_mev = lambda v, n: (v.getMax() - v.getMin()) / n * 1000
        frame.GetYaxis().SetTitleOffset(1.3)
        frame.GetYaxis().SetTitle('Events / {:.2f} MeV'.format(
            bw_mev(fit_var, n_bins)))

        frame.SetTitle("")

        return frame, leg
コード例 #14
0
def create_legend(xlo, xhi, ylo, plot_config, with_nominal):
    """
    Create a legend that fits all of the variations in plot_config
    """
    n_vars = len(plot_config['variations'])
    n_vars += with_nominal

    leg = setup_legend(xlo, ylo, xhi, ylo + n_vars * 0.045)
    leg.SetTextSize(0.03)
    return leg
コード例 #15
0
def main(args):
    """Main"""
    mcdata = get_dataframe(args.mcfile, columns=MC_VARIABLES)
    chi1data = get_dataframe(args.chic1file, 'tr', columns=TOY_VARIABLES)
    chi2data = get_dataframe(args.chic2file, 'tr', columns=TOY_VARIABLES)

    mc_ratios = OrderedDict()
    toy_ratios = OrderedDict()

    for name in SELECTIONS_TOY:
        toy_ratios[name] = OrderedDict()
        mc_ratios[name] = OrderedDict()

        toy_sel = SELECTIONS_TOY[name]
        mc_sel = SELECTIONS_MC[name]

        for var in VARIABLES:
            hist_sett = VARIABLES[var]['sett']
            toy_ratios[name][var] = get_ratio(chi1data, chi2data,
                                              VARIABLES[var]['var'], toy_sel,
                                              hist_sett, get_weight_func())
            mc_ratios[name][var] = get_ratio_mc(mcdata, VARIABLES[var]['var'],
                                                mc_sel, hist_sett)

    set_TDR_style()
    for name in SELECTIONS_TOY:
        for var in VARIABLES:
            leg = setup_legend(*LEGPOS[var])
            can = mkplot(mc_ratios[name][var],
                         attr=[PLOT_ATTRIBUTES[name]['mc']],
                         drawOpt='E2',
                         legOpt='F',
                         xLabel=LABELS[var],
                         yLabel='#chi_{c2} / #chi_{c1}',
                         leg=leg,
                         legEntries=['real mc'])
            can = mkplot(toy_ratios[name][var],
                         attr=[PLOT_ATTRIBUTES[name]['toy']],
                         drawOpt='E1same',
                         legOpt='PLE',
                         can=can,
                         xLabel=LABELS[var],
                         yLabel='#chi_{c2} / #chi_{c1}',
                         leg=leg,
                         legEntries=['toy mc'])
            latex = setup_latex()
            can.add_tobject(latex)
            put_on_latex(latex, [(0.18, 0.96, name)])
            savename = '_'.join(['comp_real_toy', name,
                                 var]).replace(' + ', '_')
            can.SaveAs(savename + '.pdf')
コード例 #16
0
def make_dlth_plot(ppd_files):
    """Make the plots for Delta lambda theta"""
    ppds = [get_scaled_ppd(f, 'dlth', 200) for f in ppd_files.values()]

    can = mkplot([r.TLine(v, 0, v, get_y_max(ppds) * 1.1) for v in [-1.6, 1.333]],
                 attr=BOUND_ATTR,
                 xRange=[-2, 2], xLabel='#Delta#lambda_{#vartheta}',
                 yRange=[0, get_y_max(ppds) * 1.1], yLabel='PPD [a.u.]')


    leg = setup_legend(0.56, 0.7, 0.88, 0.84)
    leg.SetTextSize(0.0425)
    leg.SetFillStyle(1001)

    can = mkplot(ppds, drawOpt='hist same', can=can,
                 leg=leg, legOpt='L',
                 legEntries=['{} < p_{{T}} < {} GeV'.format(*p) for p in ppd_files.keys()])

    return add_info(can)
コード例 #17
0
def make_dlph_plot(ppd_files):
    """Make the plots for Delta lambda phi"""
    ppds = [get_scaled_ppd(f, 'dlph', 400) for f in ppd_files.values()]

    can = mkplot([r.TLine(v, 0, v, get_y_max(ppds) * 1.1) for v in [-MAX_DLPH, MAX_DLPH]],
                 attr=BOUND_ATTR,
                 xRange=[-0.85, 0.85], xLabel='#Delta#lambda_{#varphi}',
                 yRange=[0, get_y_max(ppds) * 1.1], yLabel='PPD [a.u.]')

    leg = setup_legend(0.18, 0.7, 0.48, 0.84)
    leg.SetTextSize(0.0425)
    leg.SetFillStyle(1001)

    can = mkplot(ppds, drawOpt='hist same', can=can,
                 leg=leg, legOpt='L',
                 legEntries=['{} < p_{{T}} < {} GeV'.format(*p) for p in ppd_files.keys()])
    can.pltables[0].GetXaxis().SetNdivisions(507)

    return add_info(can, 'left')
コード例 #18
0
def make_lph_plot(ppd_files):
    """Make the plots for lph1 ppds"""
    ppds = [get_scaled_ppd(f, 'lph', 50) for f in ppd_files.values()]

    can = mkplot([r.TLine(v, 0, v, get_y_max(ppds) * 1.1) for v in [-1/3., 1/3.]],
                 xRange=[-1, 1], xLabel='#lambda_{#varphi}^{#chi_{c1}}',
                 yRange=[0, get_y_max(ppds) * 1.1], yLabel='PPD [a.u.]',
                 attr=BOUND_ATTR)

    leg = setup_legend(0.39, 0.25, 0.75, 0.39)
    leg.SetTextSize(0.0425)
    leg.SetFillStyle(1001)

    can = mkplot(ppds, drawOpt='hist same', can=can,
                 leg=leg, legOpt='L',
                 legEntries=['{} < p_{{T}} < {} GeV'.format(*p) for p in ppd_files.keys()])
    can.pltables[0].GetYaxis().SetNdivisions(505)
    can.pltables[0].GetXaxis().SetNdivisions(505)

    return add_info(can)
コード例 #19
0
def main(args):
    """Main"""
    dfr = get_dataframe(args.mcfile)
    costh_bins = get_costh_binning(dfr, args.nbins)

    h_int = create_mass_hist(dfr)
    h_int.Scale(1.0 / args.nbins)
    h_bins = [create_mass_hist(dfr, cbin) for cbin in costh_bins]

    attr = [{'color': 1, 'marker': 20, 'size': 1.0}]
    attr += default_attributes(size=1.0, open_markers=True) * 3

    legEntries = ['costh integrated']
    legEntries += [
        '{:.2f} < |cos#vartheta^{{HX}}| < {:.2f}'.format(*cbin)
        for cbin in costh_bins
    ]

    leg = setup_legend(0.675, 0.6, 0.95, 0.94)
    leg.SetTextSize(0.025)

    can = r.TCanvas('plot_can', '', 600, 600)
    can.SetRightMargin(0.02)
    can.SetTopMargin(0.05)
    can.SetLeftMargin(0.12)

    can = mkplot([h_int] + h_bins,
                 can=can,
                 xRange=[3.325, 3.725],
                 yRange=[0.1, None],
                 attr=attr,
                 logy=args.logy,
                 xLabel='M^{#chi}',
                 yLabel='# events',
                 legOpt='PLE',
                 leg=leg,
                 legEntries=legEntries)

    can.SaveAs(args.output)
コード例 #20
0
def chic_cs(gfile):
    """chic cross sections plot"""
    leg = setup_legend(0.6, 0.7, 0.88, 0.86)
    can = mkplot([gfile.Get(n) for n in ['chic1_ATLAS_cs', 'chic2_ATLAS_cs']],
                 drawOpt='PE',
                 logy=True,
                 attr=DATA_ATTR,
                 leg=leg,
                 legEntries=['#chi_{c1} ATLAS', '#chi_{c2} ATLAS'],
                 xRange=CS_RANGE,
                 xLabel=PTM_LABEL,
                 yLabel=CS_LABEL,
                 yRange=[1e-3, 40])

    mkplot([gfile.Get(n) for n in ['chic1_cs_full', 'chic2_cs_full']],
           drawOpt='Lsame',
           can=can,
           leg=leg,
           legEntries=['best fit', 'best fit'],
           legOpt='L')

    return can
コード例 #21
0
def jpsi_cs(gfile):
    """jpsi cross section plot"""
    graphs, leg_entries = _get_present(gfile, ['jpsi_CMS_cs'], ['J/#psi CMS'])

    leg = setup_legend(0.6, 0.7, 0.88, 0.82)
    can = mkplot(graphs,
                 drawOpt='PE',
                 logy=True,
                 logx=True,
                 attr=DATA_ATTR,
                 leg=leg,
                 legEntries=leg_entries,
                 xRange=CS_RANGE,
                 xLabel=PTM_LABEL,
                 yLabel=CS_LABEL)

    mkplot(gfile.Get('jpsi_cs_full'),
           can=can,
           drawOpt='Lsame',
           leg=leg,
           legEntries=['best fit'],
           legOpt='L')

    return can
コード例 #22
0
def make_uncer_plot(graphs, variable, levels):
    """
    Make the plot plotting the uncertainties and return the canvas
    """
    # All graphs have the same central values so it doesn't matter which one we
    # take
    cent_graph = remove_y_errors(graphs.values()[0])

    leg = setup_legend(0.675, 0.74, 0.88, 0.88)

    can = mkplot(cent_graph,
                 drawOpt='PE',
                 attr=ATTR['central'],
                 xRange=[8, 30],
                 xLabel=PTLABEL,
                 yRange=YRANGES[variable],
                 yLabel=YLABELS[variable],
                 leg=leg,
                 legEntries=['central'],
                 legOpt='P')

    for n_sig in levels:
        graph = graphs[n_sig]
        mkplot(graph,
               can=can,
               drawOpt='E2same',
               legOpt='F',
               attr=ATTR[n_sig],
               leg=leg,
               legEntries=[LEG_KEYS[n_sig]])

    mkplot(cent_graph, can=can, drawOpt='samePE', attr=ATTR['central'])

    add_auxiliary_info(can, 2012, prelim=True, pos='left')

    return can
コード例 #23
0
def make_lth_plot(ppd_files):
    """Make the plots for the lth1 ppds"""
    ppds = [get_scaled_ppd(f, 'lth') for f in ppd_files.values()]
    quantiles = [get_quantiles(p, 0.1) for p in ppds]
    ppds = [rebin(p, [(0, 100)]) for p in ppds] # for plotting

    leg = setup_legend(0.18, 0.7, 0.48, 0.84)
    leg.SetTextSize(0.0425)
    leg.SetFillColor(0)
    leg.SetFillStyle(1001)

    # Draw boundaries first to not draw it over the legend in the end
    can = mkplot(r.TLine(-1./3., 0, -1./3., get_y_max(ppds) * 1.1),
                 attr=BOUND_ATTR,
                 xRange=[-1, 1], xLabel='#lambda_{#vartheta}^{#chi_{c1}}',
                 yRange=[0, get_y_max(ppds) * 1.1], yLabel='PPD [a.u.]')

    can = mkplot(ppds, drawOpt='hist same', can=can,
                 leg=leg, legOpt='L',
                 legEntries=['{} < p_{{T}} < {} GeV'.format(*p) for p in ppd_files.keys()])
    can.pltables[0].GetYaxis().SetNdivisions(505)
    can.pltables[0].GetXaxis().SetNdivisions(505)

    mkplot([r.TLine(q, 0, q, 0.01) for q in quantiles], can=can, drawOpt='same')

    arrow_attr = default_attributes(open_markers=False)
    for att in arrow_attr:
        att['fill'] = att['color']
        att['width'] = 2

    mkplot([
        r.TArrow(q, v, q + 0.125, v, 0.025, '<|') for q, v in zip(quantiles, [0.0015, 0.003, 0.0045])
    ],
           can=can, drawOpt='same <|', attr=arrow_attr)

    return add_info(can, 'left')
コード例 #24
0
def make_comp_plot(graph, intgraph, fit=False):
    """
    Make one comparison plot and return the TCanvasWrapper
    """
    plt_attr = [{
        'color': default_colors()[0],
        'marker': 20,
        'size': 1.5
    }, {
        'color': default_colors()[1],
        'marker': 24,
        'size': 0.5,
        'fillalpha': (default_colors()[1], 0.5)
    }, {
        'color': default_colors()[4],
        'line': 2,
        'width': 2
    }]

    graph_name = graph.GetName().replace('_v_costh', '')
    if graph_name in FIX_RANGES:
        yRange = FIX_RANGES[graph_name]
    else:
        yRange = None

    ylabel = YLABELS[graph_name] if graph_name in YLABELS else graph_name

    can = mkplot(graph,
                 xRange=[0, 1],
                 drawOpt='PE',
                 attr=plt_attr[0:],
                 yRange=yRange,
                 yLabel=ylabel,
                 xLabel='|cos#vartheta^{HX}|')

    # some cosmetics
    can.SetTopMargin(0.05)
    can.SetRightMargin(0.02)
    can.SetLeftMargin(0.15)
    can.pltables[0].SetTitleOffset(2.1, 'Y')

    if intgraph is not None or fit:
        leg = setup_legend(0.65, 0.85, 0.97, 0.94)

    if intgraph is not None:
        can = mkplot(intgraph,
                     can=can,
                     drawOpt='sameP2',
                     attr=plt_attr[1:],
                     leg=leg,
                     legEntries=['cos#vartheta^{HX} int. fit'],
                     legOpt='PLEF')
        can = mkplot(intgraph, can=can, drawOpt='samePE', attr=plt_attr[1:])
    if fit:
        const = r.TF1('const', '[0]', 0, 1)
        const.SetParameter(0, np.array(graph.GetX())[0])
        fit_res = graph.Fit(const, 'NSEX0')

        can = mkplot(const,
                     can=can,
                     drawOpt='sameL',
                     attr=plt_attr[2:],
                     leg=leg,
                     legEntries=['fit to constant'],
                     legOpt='L')

        ltx = setup_latex()
        can.add_tobject(ltx)
        put_on_latex(ltx,
                     [(0.595, 0.2, 'c = {:.2e} +/- {:.2e}'.format(
                         const.GetParameter(0), const.GetParError(0))),
                      (0.595, 0.25, '#chi^{{2}} / ndf = {:.2f} / {}'.format(
                          fit_res.Chi2(), fit_res.Ndf()))],
                     ndc=True)
    can.Update()

    return can
コード例 #25
0
def _plot_state_sdcs(sdcdir, order, outdir, base_name, state_enum, states,
                     read_f):
    """Plot the total SDCs and the lth of all intermediate states for a given
    quarkonium state"""
    sdcs = read_f(sdcdir, order)

    def _plot_total_sdc(state, **kwargs):
        index = getattr(state_enum, f's{state}')
        sdc_tot = sdcs.tot[index]
        sdc_tot = scale_sdc(SCALE_FACTORS[state], sdc_tot)
        graphs = [g for g in sdc_tot.asAlwaysPositiveGraphs() if g.GetN() > 0]
        can = mkplot(graphs[0],
                     attr=ATTRS[state],
                     legEntries=[state],
                     legOpt='L',
                     **kwargs)
        if len(graphs) > 1:
            can = mkplot(graphs[1],
                         can=can,
                         drawOpt=kwargs.get('drawOpt', 'C') + 'same',
                         attr=ATTRS[state])
        return can

    leg = setup_legend(0.75, 0.75, 0.92, 0.91)
    can = _plot_total_sdc(states[0],
                          drawOpt='C',
                          leg=leg,
                          xRange=XRANGE,
                          xLabel='p_{T}/M',
                          logy=True,
                          yLabel='total SDCs',
                          yRange=[2e-2, 0.5e5])

    for state in states[1:]:
        can = _plot_total_sdc(state, drawOpt='C same', leg=leg, can=can)

    can.SaveAs(f'{outdir}/{base_name}_total_SDCs_{get_order_str(order)}.pdf')

    def _plot_lth(state, **kwargs):
        index = getattr(state_enum, f's{state}')
        f_long = sdcs.lng[index] / sdcs.tot[index]
        lth = lth_from_flong(f_long)
        return mkplot(lth.asTGraph(),
                      attr=ATTRS[state],
                      legEntries=[state],
                      legOpt='L',
                      **kwargs)

    leg = setup_legend(0.75, 0.8, 0.92, 0.94)
    can = _plot_lth(states[0],
                    drawOpt='C',
                    leg=leg,
                    xRange=XRANGE,
                    xLabel='p_{T}/M',
                    yRange=[-2, 2],
                    yLabel='#lambda_{#vartheta}^{#psi}')
    for state in states[1:]:
        can = _plot_lth(state, drawOpt='C same', leg=leg, can=can)

    can.SaveAs(f'{outdir}/{base_name}_lth_SDCs_{get_order_str(order)}.pdf')

    def _plot_tot_long_signs(state):
        index = getattr(state_enum, f's{state}')
        sdc_long, sdc_tot = sdcs.lng[index], sdcs.tot[index]
        leg = setup_legend(0.75, 0.8, 0.93, 0.94)
        can = mkplot(
            [g for g in sdc_tot.asAlwaysPositiveGraphs() if g.GetN() > 0],
            drawOpt='P',
            logy=True,
            attr=ATTRS_LT[:2],
            xRange=XRANGE,
            xLabel='p_{T}/M',
            legOpt='P',
            leg=leg,
            legEntries=('tot +', 'tot -'),
            ydscale=0.1,
            yLabel=f'{state} SDCs')

        return mkplot(
            [g for g in sdc_long.asAlwaysPositiveGraphs() if g.GetN() > 0],
            can=can,
            drawOpt='P same',
            attr=ATTRS_LT[2:],
            legOpt='P',
            leg=leg,
            legEntries=('long +', 'long -'))

    for state in states:
        can = _plot_tot_long_signs(state)
        can.SaveAs(
            f'{outdir}/{base_name}_tot_long_SDCs_{state}_{get_order_str(order)}.pdf'
        )
コード例 #26
0
def make_plot_with_syst(graphs,
                        variable,
                        syst_file,
                        add_fit=False,
                        vs_pt_m=False):
    """
    Make a plot including the systematic uncertainties.
    First combine the stat. and syst. errors by summing them in quadrature then
    plot the combined as well as the stat. only graphs onto the plot.
    Only uses the +/- 1 sigma stat. uncertainties
    """
    syst_graph = syst_file.Get('{}_v_pt_syst'.format(variable))
    stat_graph = graphs['1']
    comb_graph = get_combined_graph(stat_graph, syst_graph)

    xran = [8, 30]
    xlab = PTLABEL

    if vs_pt_m:
        xran = [v / m_psiPDG for v in xran]
        comb_graph = scale_graph_x(comb_graph, 1 / m_psiPDG)
        stat_graph = scale_graph_x(stat_graph, 1 / m_psiPDG)
        xlab = PTMLABEL

    leg = setup_legend(0.675, 0.74, 0.88, 0.88)
    can = mkplot(comb_graph,
                 drawOpt='PE2',
                 attr=ATTR['combined'],
                 xRange=xran,
                 xLabel=xlab,
                 yRange=YRANGES[variable],
                 yLabel=YLABELS[variable],
                 leg=leg,
                 legEntries=['stat. + syst.'],
                 legOpt='PF')

    # remove the x uncertainties to avoid having the vertical line in the plot
    # stat_graph = remove_x_errors(stat_graph)
    mkplot(stat_graph,
           can=can,
           drawOpt='PE2same',
           attr=ATTR['stat only'],
           leg=leg,
           legEntries=['stat. only'],
           legOpt='F')

    # stat only covers the point of the combined one. Plot them again
    mkplot(comb_graph, drawOpt='PEX0same', attr=ATTR['combined'], can=can)

    add_auxiliary_info(can, 2012, prelim=True, pos='left')

    if add_fit:
        lin_func = r.TF1('lin_func', '[0] + [1] * x[0]', *xran)
        fit_res = comb_graph.Fit(lin_func, 'SEX00')
        chi2, ndf = fit_res.Chi2(), fit_res.Ndf()
        p0, p1 = [lin_func.GetParameter(i) for i in [0, 1]]

        const_func = r.TF1('const_func', '[0]', *xran)
        fit_res = comb_graph.Fit(const_func, 'SEX00')
        chi2_c, ndf_c = fit_res.Chi2(), fit_res.Ndf()
        p0c, p0ce = [const_func.GetParameter(0), const_func.GetParError(0)]

        mkplot(lin_func, drawOpt='Lsame', can=can, attr=ATTR['fit'])

        ltx = setup_latex()
        put_on_latex(ltx, [
            (0.5, 0.35, 'linear fit: {:.3f} + {:.3f} x p_{{T}}'.format(p0,
                                                                       p1)),
            (0.5, 0.3, '#chi^{{2}} / ndf = {:.2f} / {}'.format(chi2, ndf)),
            (0.5, 0.25, 'const. fit: {:.3f} #pm {:.3f}'.format(p0c, p0ce)),
            (0.5, 0.2, '#chi^{{2}} / ndf = {:.2f} / {}'.format(chi2_c, ndf_c))
        ],
                     ndc=True)
        ltx.Draw()
        can.Update()

    return can
コード例 #27
0
def main(args):
    """Main"""
    set_TDR_style()
    fitfile = r.TFile.Open(args.fitfile)

    cont_1sigma = get_contour(fitfile.Get('chi2_scan_contour_1sigma'))
    cont_2sigma = get_contour(fitfile.Get('chi2_scan_contour_2sigma'))
    cont_3sigma = get_contour(fitfile.Get('chi2_scan_contour_3sigma'))

    leg = setup_legend(0.5, 0.78, 0.8, 0.94)
    leg.SetTextSize(0.035)
    leg.SetEntrySeparation(0.005)
    leg.SetFillStyle(1001)

    can = mkplot([cont_1sigma, cont_2sigma, cont_3sigma],
                 drawOpt='L',
                 xRange=[-1, 1.6],
                 xLabel='#lambda_{#vartheta}^{#chi_{c1}}',
                 yRange=[-1.2, 1.6],
                 yLabel='#lambda_{#vartheta}^{#chi_{c2}}',
                 attr=CONT_ATTR,
                 leg=leg,
                 legEntries=['{} % CL'.format(v) for v in [68, 95, 99]],
                 legOpt='L')

    mkplot(get_phys_region(),
           can=can,
           drawOpt='same',
           attr=[{
               'color': r.kRed,
               'line': 7,
               'width': 3
           }])

    mkplot([r.TLine(0, -1.2, 0, 1.6),
            r.TLine(-1, 0, 1.6, 0)],
           can=can,
           drawOpt='same',
           attr=[{
               'color': 12,
               'line': 7,
               'width': 2
           }])

    mkplot(r.TGraph(1, np.array([0]), np.array([0])),
           can=can,
           drawOpt='Psame',
           attr=[{
               'color': 1,
               'marker': 24,
               'size': 2.75
           }])

    mkplot(get_jz_graph(),
           can=can,
           drawOpt='Psame',
           attr=[{
               'color': 1,
               'marker': 30,
               'size': 3
           }])

    ltx = setup_latex()
    ltx.SetTextSize(0.04)
    put_on_latex(ltx, [(-0.4, 1.3, 'J_{z}'), (-0.4, 1.1, '#pm1'),
                       (0.975, 1.1, '0'), (-0.54, 0.95, '#pm2'),
                       (-0.54, -0.38, '#pm1'), (-0.47, -0.65, '0')],
                 ndc=False)

    add_auxiliary_info(can, 2012, 'left')
    can.SaveAs(args.outfile)
コード例 #28
0
def make_ratio_pull_plot(ratio, analytic_scens, variable):
    """
    Make a comparison plot with an additional pull panel at the bottom
    """
    # Scale all analytic scenarios first
    chi2_ndfs = get_chi2_ndf(ratio, analytic_scens)

    can = mkplot([])  # get a canvas that is already a TCanvasWrapper
    can.cd()
    rpad = r.TPad('ratio_pad', 'ratio pad', 0, 0.3, 1, 0.98)
    r.SetOwnership(rpad, False)
    rpad.SetBottomMargin(0)
    rpad.Draw()

    rpad = mkplot(ratio,
                  drawOpt='PE',
                  can=rpad,
                  attr=[{
                      'color': 1,
                      'size': 1,
                      'marker': 20
                  }],
                  yLabel=YLABELS.get('r_chic2_chic1'),
                  yRange=[0.001, 0.75],
                  **VAR_PLOT[variable])

    leg = setup_legend(0.2, 0.15, 0.65, 0.32)
    mkplot(analytic_scens.values(),
           drawOpt='sameL',
           can=rpad,
           attr=ANALYTIC_ATTRS,
           leg=leg,
           legEntries=analytic_scens.keys(),
           legOpt='L')

    can.cd()
    ppad = r.TPad('pull_pad', 'pull pad', 0, 0, 1, 0.3)
    r.SetOwnership(ppad, False)
    ppad.SetTopMargin(0)
    ppad.SetBottomMargin(0.3)
    ppad.Draw()

    # Draw grid first so that it is not overlaying the plotted points
    xran = VAR_PLOT[variable]['xRange']
    ppad = mkplot(
        r.TLine(xran[0], 0, xran[1], 0),
        can=ppad,
        attr=[{
            'color': 1,
            'width': 2,
            'line': 1
        }],
        yLabel='pulls',
        yRange=[-4.99, 4.99],  # grid=True,
        **VAR_PLOT[variable])
    mkplot([r.TLine(xran[0], v, xran[1], v) for v in [-3, 3]],
           drawOpt='same',
           can=ppad,
           attr=[{
               'color': 12,
               'width': 2,
               'line': 7
           }])

    pulls = [pull_graph(ratio, s) for s in analytic_scens.values()]
    ppad = mkplot(pulls,
                  drawOpt='samePE',
                  can=ppad,
                  attr=default_attributes(open_markers=False),
                  **VAR_PLOT[variable])

    phist = ppad.pltables[0]
    phist.SetNdivisions(505, "XYZ")
    phist.SetLabelFont(42, "XYZ")
    phist.SetLabelOffset(0.007, "XYZ")
    phist.SetLabelSize(0.12, "XYZ")
    phist.GetXaxis().SetTitleOffset(0.95)
    phist.GetYaxis().SetTitleOffset(0.52)
    phist.SetTitleSize(0.14, "XYZ")
    # ppad.SetGridy()

    can.add_tobject(rpad)
    can.add_tobject(ppad)

    add_auxiliary_info(can, 2012, prelim=True)
    return can
コード例 #29
0
def main(args):
    """Main"""

    with open(args.bininfo, 'r') as finfo:
        costh_info = json.load(finfo)

    fitfile = r.TFile.Open(args.fitres)
    wsp = fitfile.Get('ws_mass_fit')

    fit_graph = get_fit_graph(wsp, costh_info['costh_bins'],
                              costh_info['costh_means'])

    histfile = r.TFile.Open(args.histfile)
    histlist = list(set(b.GetName() for b in histfile.GetListOfKeys()))

    ratio_combs = get_ratio_combs([h for h in histlist if 'chic1' in h],
                                  [h for h in histlist if 'chic2' in h])

    ratios = []
    for chi1_hist, chi2_hist in ratio_combs:
        h_chi1 = histfile.Get(chi1_hist)
        h_chi1.Scale(1 / h_chi1.Integral())
        h_chi2 = histfile.Get(chi2_hist)
        h_chi2.Scale(1 / h_chi2.Integral())
        ratio = divide(h_chi2, h_chi1)
        ratio.SetBinContent(ratio.GetNbinsX() + 1, 0)
        ratio.SetBinError(ratio.GetNbinsX() + 1, 0)

        chisqu, fit_norm = calc_chi2(ratio, fit_graph)
        ratios.append((get_delta_lambda(chi1_hist, chi2_hist),
                       ratio, chisqu, fit_norm))
        ratio.Scale(fit_norm)

    ratios.sort(key=lambda rr: sp.N(rr[0]))
    # print before removing "duplicates"
    print ('# Delta lambda, N, chi2, p, sigma')
    for ratio in ratios:
        print('{}, {:.3f}, {:.2f}, {:.3e}, {:.1f}'
              .format(ratio[0], ratio[3], ratio[2],
                      chi2.sf(ratio[2], fit_graph.GetN() - 1),
                      norm.isf(chi2.sf(ratio[2], fit_graph.GetN() - 1))))

    # only retain one of the possible delta lambda = 0 results
    ratios = unique_w_key(ratios, lambda rr: rr[0])

    leg = setup_legend(0.12, 0.12, 0.5, 0.4)
    leg.SetNColumns(2)

    plot_toy = [sp.S(x) for x in ['-8/5', '-1', '-1/3', '0', '4/3']]

    can = mkplot([rr[1] for rr in ratios if rr[0] in plot_toy],
                 yRange=[0, 0.65], yLabel='#chi_{c2} / #chi_{c1}',
                 leg=leg, xRange=[0.0, 1.0], drawOpt='L',
                 legEntries=['#Delta#lambda_{#theta} = ' + str(rr[0])
                             for rr in ratios if rr[0] in plot_toy])

    can = mkplot(fit_graph, can=can, leg=can.attached_tobjects[0],
                 legEntries=['data'],
                 attr=[{'color': 1, 'marker': 20, 'size': 1.5}], drawOpt='samePE')

    can.SaveAs(args.output)
コード例 #30
0
def main(args):
    c1f = r.TFile.Open(args.corrmaps1)
    c2f = r.TFile.Open(args.corrmaps2)

    corrmap1 = get_corrmap(c1f, 'HX', args.corr_var, args.mask_acc, args.use_acc_only,
                           min_acc=args.min_acc, mask_prec=args.min_prec)
    corrmap2 = get_corrmap(c2f, 'HX', args.corr_var, args.mask_acc, args.use_acc_only,
                           min_acc=args.min_acc, mask_prec=args.min_prec)

    corrmap1_PX = get_corrmap(c1f, 'PX', args.corr_var, args.mask_acc, args.use_acc_only,
                           min_acc=args.min_acc, mask_prec=args.min_prec)
    corrmap2_PX = get_corrmap(c2f, 'PX', args.corr_var, args.mask_acc, args.use_acc_only,
                           min_acc=args.min_acc, mask_prec=args.min_prec)

    selections = create_selection(args.selection)


    scenarios = [
        ('chic1_R_2o3', 'chic2_R1_2o5_R2_2o5'),
        ('chic1_R_1', 'chic2_R1_0_R2_1'),
        ('chic1_R_0', 'chic2_R1_0_R2_0'),
    ]


    attr = default_attributes(size=1.0, open_markers=True)[:3]
    attr += [{'color': 13, 'line': 7, 'width': 2, 'marker': 1}]

    cond_mkdir(args.outbase)
    outfile = r.TFile('/'.join([args.outbase,
                                'costh_ratios_min_acc_{}_min_prec_{}_gen_{}.root'.format(pfloat(args.min_acc), pfloat(args.min_prec), args.gen_frame)]),
                      'recreate')

    for scen in scenarios:
        chi1_d, chi2_d = samples(args.toydatadir, scen, selections)

        print(scen)
        hists = OrderedDict()
        print('uncorr')
        hists['uncorr'] = (costh_h(chi2_d), costh_h(chi1_d))
        print('corr HX')
        hists['corr HX'] = (costh_h(chi2_d, corrmap2, 'HX', args.corr_var),
                            costh_h(chi1_d, corrmap1, 'HX', args.corr_var))
        print('corr PX')
        hists['corr PX'] = (costh_h(chi2_d, corrmap2_PX, 'PX', args.corr_var),
                            costh_h(chi1_d, corrmap1_PX, 'PX', args.corr_var))


        if args.gen_frame == 'HX':
            ratio_a, delta_lth = analytical_ratio(*scen)
        if args.gen_frame == 'CS':
            ratio_a, delta_lth = ratio_shape(*scen)

        ratios = OrderedDict()
        for case in hists:
            ratios[case] = divide(*hists[case])

            leg = setup_legend(0.15, 0.15, 0.55, 0.25)
            leg.SetNColumns(2)


        plots = scale_0(ratios.values())
        leg_entries = ratios.keys()
        if args.gen_frame == 'HX':
            plots.append(scale_func(ratio_a))
            leg_entries.append('analytical')

        can = mkplot(plots,
                     attr=attr,
                     xLabel='|cos#vartheta^{HX}|', yLabel='#chi_{c2} / #chi_{c1}', xRange=[0, 1],
                     leg=leg, legEntries=leg_entries,
                     drawOpt='E1',
                     legOpt='PLE')
        if args.gen_frame == 'CS':
            can = mkplot(scale_0(ratio_a), attr=[attr[-1]], leg=leg, legEntries=['analytical'],
                         drawOpt='HISTsame', legOpt='PLE',
                         can=can)

        can.SaveAs(pdfname(args.outbase, args.gen_frame, delta_lth, args.min_prec, args.min_acc))

        outfile.cd()
        for corr, ratio in ratios.iteritems():
            ratio.SetName('_'.join([
                scen[0], scen[1], 'ratio_costh_HX', corr.replace(' ', '_'), 'gen', args.gen_frame
            ]))
            ratio.Write()

        for corr in hists:
            hist1, hist2 = hists[corr]
            hist1.SetName('_'.join([
                scen[0], scen[1], 'chi1_costh_HX', corr.replace(' ', '_'), 'gen', args.gen_frame
            ]))
            hist1.Write()

            hist2.SetName('_'.join([
                scen[0], scen[1], 'chi2_costh_HX', corr.replace(' ', '_'), 'gen', args.gen_frame
            ]))
            hist2.Write()


    outfile.Close()