Exemplo n.º 1
0
def plot_proj_both(frame2, frame_east, frame_west, adc_bin, adc_min, adc_max,
                   ptmax, mmin, mmax):

    can = ut.box_canvas(800, 700)  #900, 700

    xp = Double(0)
    yp = Double(0)

    #east data on the left
    hEast = frame_east.getHist("data")
    plot_east = frame2.Clone("plot_east")
    plot_east.SetMarkerStyle(22)
    plot_east.SetMarkerSize(1.4)
    ut.set_H1D_col(plot_east, rt.kBlue)
    for ibin in xrange(hEast.GetN()):
        hEast.GetPoint(ibin, xp, yp)
        plot_east.SetBinContent(ibin + 1, yp)
        plot_east.SetBinError(ibin + 1, hEast.GetErrorY(ibin))

    frame2.SetMaximum(1.2 * plot_east.GetMaximum())  # 1.15

    #west data on the right
    hWest = frame_west.getHist("data")
    plot_west = frame2.Clone("plot_west")
    plot_west.SetMarkerStyle(21)
    ut.set_H1D_col(plot_west, rt.kRed)
    for i in xrange(hWest.GetN()):
        hWest.GetPoint(i, xp, yp)
        ibin = frame2.GetNbinsX() - i
        plot_west.SetBinContent(ibin, yp)
        plot_west.SetBinError(ibin, hWest.GetErrorY(i))

    #east fit
    cEast = frame_east.getCurve("model")
    gEast = TGraph(cEast.GetN() - 1)
    for i in xrange(cEast.GetN() - 1):
        cEast.GetPoint(i, xp, yp)
        gEast.SetPoint(i, xp, yp)

    gEast.SetLineColor(rt.kBlue)
    gEast.SetLineWidth(3)
    gEast.SetLineStyle(rt.kDashed)
    #gEast.SetLineStyle(rt.kDashDotted)

    #west fit on the left
    cWest = frame_west.getCurve("model")
    gWest = TGraph(cWest.GetN() - 1)
    xmax = frame2.GetBinCenter(
        frame2.GetNbinsX()) + frame2.GetBinWidth(frame2.GetNbinsX()) / 2.
    for i in xrange(cWest.GetN() - 1):
        cWest.GetPoint(i, xp, yp)
        xplot = xmax - xp
        gWest.SetPoint(i, xplot, yp)

    gWest.SetLineColor(rt.kRed)
    gWest.SetLineWidth(3)
    #gWest.SetLineStyle(rt.kDashDotted)
    #gWest.SetLineStyle(rt.kDashed)

    #horizontal axis
    frame2.SetMinimum(0)
    #frame2.SetMinimum(0.98)
    frame2.GetXaxis().SetNdivisions(0, rt.kFALSE)
    #east axis
    ypos = frame2.GetYaxis().GetXmin()
    axisE = TGaxis(adc_min, ypos, adc_max, ypos, adc_min, adc_max)
    ut.set_axis(axisE)
    axisE.SetWmin(axisE.GetWmin() * 0.01)
    axisE.SetWmax(axisE.GetWmax() * 0.01)
    axisE.SetTitle("ZDC East #times100")
    axisE.SetTitleOffset(1.1)
    #west axis
    xpos = frame2.GetXaxis().GetXmax()
    axisW = TGaxis(xpos, ypos, xpos - adc_max, ypos, adc_min, adc_max, 510,
                   "-")
    ut.set_axis(axisW)
    axisW.SetWmin(axisW.GetWmin() * 0.01)
    axisW.SetWmax(axisW.GetWmax() * 0.01)
    axisW.SetLabelOffset(-0.024)
    axisW.SetTitle("ZDC West #times100")
    axisW.SetTitleOffset(1.1)

    #vertical axis
    yvpos = 1. * frame2.GetMaximum()
    axisV = TGaxis(xpos, 0, xpos, yvpos, 0, yvpos, 510, "+L")
    #axisV = TGaxis(xpos, 0, xpos, yvpos, 0.98, yvpos, 510, "+G")
    ut.set_axis(axisV)

    frame2.SetYTitle("ZDC East / ({0:.0f} ADC units)".format(adc_bin))
    axisV.SetTitle("ZDC West / ({0:.0f} ADC units)".format(adc_bin))

    frame2.GetYaxis().SetTitleOffset(1.5)
    axisV.SetTitleOffset(1.5)

    gPad.SetTopMargin(0.05)  # 0.01
    gPad.SetRightMargin(0.1)
    gPad.SetBottomMargin(0.08)
    gPad.SetLeftMargin(0.1)

    frame2.Draw()
    plot_east.Draw("e1same")
    plot_west.Draw("e1same")
    gEast.Draw("lsame")
    gWest.Draw("lsame")

    axisE.Draw()
    axisW.Draw()
    axisV.Draw()

    #kinematics legend
    #kleg = ut.prepare_leg(0.16, 0.78, 0.32, 0.2, 0.035)
    kleg = ut.prepare_leg(0.16, 0.73, 0.32, 0.2, 0.035)
    kleg.AddEntry(None, "AuAu@200 GeV", "")
    kleg.AddEntry(None, "UPC sample", "")
    ut.add_leg_pt_mass(kleg, ptmax, mmin, mmax)
    kleg.Draw("same")

    #data legend
    dleg = ut.prepare_leg(0.6, 0.8, 0.15, 0.08, 0.03)
    dleg.AddEntry(plot_east, "ZDC East", "p")
    dleg.AddEntry(plot_west, "ZDC West", "p")
    #dleg.Draw("same")

    #projections legend
    #pleg = ut.prepare_leg(0.24, 0.56, 0.25, 0.2, 0.035)
    pleg = ut.prepare_leg(0.24, 0.51, 0.25, 0.2, 0.035)
    pleg.AddEntry(plot_east, "ZDC East", "p")
    pleg.AddEntry(plot_west, "ZDC West", "p")
    pleg.AddEntry(gEast, "Fit projection to east", "l")
    pleg.AddEntry(gWest, "Fit projection to west", "l")
    pleg.Draw("same")

    #gPad.SetLogy()
    #gPad.SetGrid()

    #ut.invert_col(gPad)
    can.SaveAs("01fig.pdf")
def main():  # pylint: disable=too-many-locals, too-many-statements, too-many-branches
    """
    Main plotting function
    """
    gROOT.SetBatch(True)

    # pylint: disable=unused-variable

    parser = argparse.ArgumentParser()
    parser.add_argument("--database-analysis",
                        "-d",
                        dest="database_analysis",
                        help="analysis database to be used",
                        required=True)
    parser.add_argument("--analysis",
                        "-a",
                        dest="type_ana",
                        help="choose type of analysis",
                        required=True)
    parser.add_argument("--input",
                        "-i",
                        dest="input_file",
                        help="results input file",
                        required=True)

    args = parser.parse_args()

    typean = args.type_ana
    shape = typean[len("jet_"):]
    print("Shape:", shape)

    file_in = args.input_file
    with open(args.database_analysis, "r") as file_db:
        data_param = yaml.safe_load(file_db)
    case = list(data_param.keys())[0]
    datap = data_param[case]

    logger = get_logger()

    i_cut = file_in.rfind("/")
    rootpath = file_in[:i_cut]

    # plotting
    # LaTeX string
    p_latexnhadron = datap["analysis"][typean]["latexnamehadron"]
    p_latexbin2var = datap["analysis"][typean]["latexbin2var"]
    v_varshape_latex = datap["analysis"][typean]["var_shape_latex"]

    # first variable (hadron pt)
    lpt_finbinmin = datap["analysis"][typean]["sel_an_binmin"]
    lpt_finbinmax = datap["analysis"][typean]["sel_an_binmax"]
    var1ranges = lpt_finbinmin.copy()
    var1ranges.append(lpt_finbinmax[-1])

    # second variable (jet pt)
    v_var2_binning = datap["analysis"][typean]["var_binning2"]  # name
    lvar2_binmin_reco = datap["analysis"][typean].get("sel_binmin2_reco", None)
    lvar2_binmax_reco = datap["analysis"][typean].get("sel_binmax2_reco", None)
    p_nbin2_reco = len(lvar2_binmin_reco)  # number of reco bins
    lvar2_binmin_gen = datap["analysis"][typean].get("sel_binmin2_gen", None)
    lvar2_binmax_gen = datap["analysis"][typean].get("sel_binmax2_gen", None)
    p_nbin2_gen = len(lvar2_binmin_gen)  # number of gen bins
    var2ranges_reco = lvar2_binmin_reco.copy()
    var2ranges_reco.append(lvar2_binmax_reco[-1])
    var2binarray_reco = array(
        "d",
        var2ranges_reco)  # array of bin edges to use in histogram constructors
    var2ranges_gen = lvar2_binmin_gen.copy()
    var2ranges_gen.append(lvar2_binmax_gen[-1])
    var2binarray_gen = array(
        "d",
        var2ranges_gen)  # array of bin edges to use in histogram constructors

    # observable (z, shape,...)
    v_varshape_binning = datap["analysis"][typean][
        "var_binningshape"]  # name (reco)
    v_varshape_binning_gen = datap["analysis"][typean][
        "var_binningshape_gen"]  # name (gen)
    lvarshape_binmin_reco = \
        datap["analysis"][typean].get("sel_binminshape_reco", None)
    lvarshape_binmax_reco = \
        datap["analysis"][typean].get("sel_binmaxshape_reco", None)
    p_nbinshape_reco = len(lvarshape_binmin_reco)  # number of reco bins
    lvarshape_binmin_gen = \
        datap["analysis"][typean].get("sel_binminshape_gen", None)
    lvarshape_binmax_gen = \
        datap["analysis"][typean].get("sel_binmaxshape_gen", None)
    p_nbinshape_gen = len(lvarshape_binmin_gen)  # number of gen bins
    varshaperanges_reco = lvarshape_binmin_reco.copy()
    varshaperanges_reco.append(lvarshape_binmax_reco[-1])
    varshapebinarray_reco = array(
        "d", varshaperanges_reco
    )  # array of bin edges to use in histogram constructors
    varshaperanges_gen = lvarshape_binmin_gen.copy()
    varshaperanges_gen.append(lvarshape_binmax_gen[-1])
    varshapebinarray_gen = array(
        "d", varshaperanges_gen
    )  # array of bin edges to use in histogram constructors

    file_results = TFile.Open(file_in)
    if not file_results:
        logger.fatal(make_message_notfound(file_in))

    ibin2 = 1

    suffix = "%s_%g_%g" % (v_var2_binning, lvar2_binmin_gen[ibin2],
                           lvar2_binmax_gen[ibin2])

    # HF data
    nameobj = "%s_hf_data_%d_stat" % (shape, ibin2)
    hf_data_stat = file_results.Get(nameobj)
    if not hf_data_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_hf_data_%d_syst" % (shape, ibin2)
    hf_data_syst = file_results.Get(nameobj)
    if not hf_data_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # HF PYTHIA
    nameobj = "%s_hf_pythia_%d_stat" % (shape, ibin2)
    hf_pythia_stat = file_results.Get(nameobj)
    if not hf_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # HF ratio
    nameobj = "%s_hf_ratio_%d_stat" % (shape, ibin2)
    hf_ratio_stat = file_results.Get(nameobj)
    if not hf_ratio_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_hf_ratio_%d_syst" % (shape, ibin2)
    hf_ratio_syst = file_results.Get(nameobj)
    if not hf_ratio_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive data
    nameobj = "%s_incl_data_%d_stat" % (shape, ibin2)
    incl_data_stat = file_results.Get(nameobj)
    if not incl_data_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_data_%d_syst" % (shape, ibin2)
    incl_data_syst = file_results.Get(nameobj)
    if not incl_data_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive PYTHIA
    nameobj = "%s_incl_pythia_%d_stat" % (shape, ibin2)
    incl_pythia_stat = file_results.Get(nameobj)
    if not incl_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_pythia_%d_syst" % (shape, ibin2)
    incl_pythia_syst = file_results.Get(nameobj)
    if not incl_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive ratio
    nameobj = "%s_incl_ratio_%d_stat" % (shape, ibin2)
    incl_ratio_stat = file_results.Get(nameobj)
    if not incl_ratio_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_ratio_%d_syst" % (shape, ibin2)
    incl_ratio_syst = file_results.Get(nameobj)
    if not incl_ratio_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # quark PYTHIA
    nameobj = "%s_quark_pythia_%d_stat" % (shape, ibin2)
    quark_pythia_stat = file_results.Get(nameobj)
    if not quark_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_quark_pythia_%d_syst" % (shape, ibin2)
    quark_pythia_syst = file_results.Get(nameobj)
    if not quark_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # gluon PYTHIA
    nameobj = "%s_gluon_pythia_%d_stat" % (shape, ibin2)
    gluon_pythia_stat = file_results.Get(nameobj)
    if not gluon_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_gluon_pythia_%d_syst" % (shape, ibin2)
    gluon_pythia_syst = file_results.Get(nameobj)
    if not gluon_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # plot the results with systematic uncertainties and models

    size_can = [800, 800]
    offsets_axes = [0.8, 1.1]
    margins_can = [0.1, 0.13, 0.1, 0.03]
    size_thg = 0.05
    offset_thg = 0.85

    gStyle.SetErrorX(0)  # do not plot horizontal error bars of histograms
    fontsize = 0.035
    opt_leg_g = "FP"
    opt_plot_g = "2"

    list_new = []  # list to avoid loosing objects created in loops

    # labels

    x_latex = 0.16
    y_latex_top = 0.83
    y_step = 0.055

    title_x = v_varshape_latex
    title_y = "(1/#it{N}_{jet}) d#it{N}/d%s" % v_varshape_latex
    title_full = ";%s;%s" % (title_x, title_y)
    title_full_ratio = ";%s;data/MC: ratio of %s" % (title_x, title_y)

    text_alice = "#bf{ALICE} Preliminary, pp, #sqrt{#it{s}} = 13 TeV"
    text_alice_sim = "#bf{ALICE} Simulation, pp, #sqrt{#it{s}} = 13 TeV"
    text_pythia = "PYTHIA 8 (Monash)"
    text_pythia_split = "#splitline{PYTHIA 8}{(Monash)}"
    text_jets = "charged jets, anti-#it{k}_{T}, #it{R} = 0.4"
    text_ptjet = "%g #leq %s < %g GeV/#it{c}, #left|#it{#eta}_{jet}#right| #leq 0.5" % (
        lvar2_binmin_reco[ibin2], p_latexbin2var, lvar2_binmax_reco[ibin2])
    text_pth = "%g #leq #it{p}_{T}^{%s} < %g GeV/#it{c}, #left|#it{y}_{%s}#right| #leq 0.8" % (
        lpt_finbinmin[0], p_latexnhadron,
        min(lpt_finbinmax[-1], lvar2_binmax_reco[ibin2]), p_latexnhadron)
    text_ptcut = "#it{p}_{T, incl. ch. jet}^{leading track} #geq 5.33 GeV/#it{c}"
    text_ptcut_sim = "#it{p}_{T, incl. ch. jet}^{leading h^{#pm}} #geq 5.33 GeV/#it{c} (varied)"
    text_sd = "Soft Drop (#it{z}_{cut} = 0.1, #it{#beta} = 0)"

    title_thetag = "#it{#theta}_{g} = #it{R}_{g}/#it{R}"
    radius_jet = 0.4

    # colour and marker indeces
    c_hf_data = 0
    c_incl_data = 1
    c_hf_mc = 2
    c_incl_mc = 6
    c_quark_mc = 5
    c_gluon_mc = 0

    # markers
    m_hf_data = get_marker(0)
    m_incl_data = get_marker(1)
    m_hf_mc = get_marker(0, 2)
    m_incl_mc = get_marker(1, 2)
    m_quark_mc = get_marker(2)
    m_gluon_mc = get_marker(3)

    # make the horizontal error bars smaller
    if shape == "nsd":
        for gr in [
                hf_data_syst, incl_data_syst, hf_ratio_syst, incl_ratio_syst,
                incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst
        ]:
            for i in range(gr.GetN()):
                gr.SetPointEXlow(i, 0.1)
                gr.SetPointEXhigh(i, 0.1)

    # data, HF and inclusive

    hf_data_syst_cl = hf_data_syst.Clone()

    leg_pos = [.72, .75, .85, .85]
    list_obj = [hf_data_syst, incl_data_syst, hf_data_stat, incl_data_stat]
    labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive", "", ""]
    colours = [
        get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data,
                                          c_incl_data), (2, 2, 1, 1))
    ]
    markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_data, list_obj_data_new = make_plot("cshape_data_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip((hf_data_syst, incl_data_syst), (c_hf_data, c_incl_data)):
        gr.SetMarkerColor(get_colour(c))
    list_obj_data_new[0].SetTextSize(fontsize)
    if shape == "nsd":
        hf_data_syst.GetXaxis().SetNdivisions(5)
    # Draw a line through the points.
    if shape == "nsd":
        for h in (hf_data_stat, incl_data_stat):
            h_line = h.Clone(h.GetName() + "_line")
            h_line.SetLineStyle(2)
            h_line.Draw("l hist same")
            list_new.append(h_line)
    cshape_data.Update()
    if shape == "rg":
        # plot the theta_g axis
        gr_frame = hf_data_syst
        axis_rg = gr_frame.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data = []
    for text_latex in [
            text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data.Update()
    cshape_data.SaveAs("%s/%s_data_%s.pdf" % (rootpath, shape, suffix))

    # data and PYTHIA, HF

    leg_pos = [.72, .65, .85, .85]
    list_obj = [hf_data_syst_cl, hf_data_stat, hf_pythia_stat]
    labels_obj = ["data", "", text_pythia_split]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_hf_data, c_hf_data, c_hf_mc), (2, 1, 1))
    ]
    markers = [m_hf_data, m_hf_data, m_hf_mc]
    y_margin_up = 0.4
    y_margin_down = 0.05
    cshape_data_mc_hf, list_obj_data_mc_hf_new = make_plot("cshape_data_mc_hf_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip([hf_data_syst_cl], [c_hf_data]):
        gr.SetMarkerColor(get_colour(c))
    leg_data_mc_hf = list_obj_data_mc_hf_new[0]
    leg_data_mc_hf.SetHeader("%s-tagged" % p_latexnhadron)
    leg_data_mc_hf.SetTextSize(fontsize)
    if shape == "nsd":
        hf_data_syst_cl.GetXaxis().SetNdivisions(5)
        #axis_nsd = hf_data_syst_cl.GetHistogram().GetXaxis()
        #x1 = axis_nsd.GetBinLowEdge(1)
        #x2 = axis_nsd.GetBinUpEdge(axis_nsd.GetNbins())
        #axis_nsd.Set(5, x1, x2)
        #for ibin in range(axis_nsd.GetNbins()):
        #    axis_nsd.SetBinLabel(ibin + 1, "%d" % ibin)
        #axis_nsd.SetNdivisions(5)
    cshape_data_mc_hf.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_data_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data_mc_hf.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data_mc_hf.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data_mc_hf = []
    for text_latex in [text_alice, text_jets, text_ptjet, text_pth, text_sd]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data_mc_hf.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data_mc_hf.Update()
    cshape_data_mc_hf.SaveAs("%s/%s_data_mc_hf_%s.pdf" %
                             (rootpath, shape, suffix))

    # data and PYTHIA, inclusive

    #leg_pos = [.68, .65, .85, .85]
    list_obj = [
        incl_data_syst, incl_pythia_syst, incl_data_stat, incl_pythia_stat
    ]
    labels_obj = ["data", text_pythia_split]
    colours = [
        get_colour(i, j) for i, j in zip((c_incl_data, c_incl_mc, c_incl_data,
                                          c_incl_mc), (2, 2, 1, 1))
    ]
    markers = [m_incl_data, m_incl_mc, m_incl_data, m_incl_mc]
    y_margin_up = 0.4
    y_margin_down = 0.05
    cshape_data_mc_incl, list_obj_data_mc_incl_new = make_plot("cshape_data_mc_incl_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip([incl_data_syst, incl_pythia_syst],
                     [c_incl_data, c_incl_mc]):
        gr.SetMarkerColor(get_colour(c))
    leg_data_mc_incl = list_obj_data_mc_incl_new[0]
    leg_data_mc_incl.SetHeader("inclusive")
    leg_data_mc_incl.SetTextSize(fontsize)
    if shape == "nsd":
        incl_data_syst.GetXaxis().SetNdivisions(5)
    cshape_data_mc_incl.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = incl_data_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data_mc_incl.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data_mc_incl.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data_mc_incl = []
    for text_latex in [text_alice, text_jets, text_ptjet, text_ptcut, text_sd]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data_mc_incl.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data_mc_incl.Update()
    cshape_data_mc_incl.SaveAs("%s/%s_data_mc_incl_%s.pdf" %
                               (rootpath, shape, suffix))

    # Ratios data/MC, HF and inclusive

    line_1 = TLine(lvarshape_binmin_reco[0], 1, lvarshape_binmax_reco[-1], 1)
    line_1.SetLineStyle(9)
    line_1.SetLineColor(1)
    line_1.SetLineWidth(3)

    #leg_pos = [.72, .7, .85, .85] # with header
    leg_pos = [.72, .75, .85, .85]  # without header
    list_obj = [
        hf_ratio_syst, line_1, incl_ratio_syst, hf_ratio_stat, incl_ratio_stat
    ]
    labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive"]
    colours = [
        get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data,
                                          c_incl_data), (2, 2, 1, 1))
    ]
    markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data]
    y_margin_up = 0.52
    y_margin_down = 0.05
    if shape == "nsd":
        y_margin_up = 0.22
    cshape_ratio, list_obj_ratio_new = make_plot("cshape_ratio_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full_ratio)
    cshape_ratio.Update()
    for gr, c in zip((hf_ratio_syst, incl_ratio_syst),
                     (c_hf_data, c_incl_data)):
        gr.SetMarkerColor(get_colour(c))
    leg_ratio = list_obj_ratio_new[0]
    leg_ratio.SetTextSize(fontsize)
    #leg_ratio.SetHeader("data/MC")
    if shape == "nsd":
        hf_ratio_syst.GetXaxis().SetNdivisions(5)
    cshape_ratio.Update()
    if shape == "rg":
        # plot the theta_g axis
        gr_frame = hf_ratio_syst
        axis_rg = gr_frame.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_ratio.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_ratio.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_ratio = []
    for text_latex in [
            text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd,
            text_pythia
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_ratio.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_ratio.Update()
    cshape_ratio.SaveAs("%s/%s_ratio_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, inclusive, quark, gluon

    incl_pythia_syst_cl = incl_pythia_syst.Clone()

    y_min_h, y_max_h = get_y_window_his([
        hf_pythia_stat, incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat
    ])
    y_min_g, y_max_g = get_y_window_gr(
        [incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst])
    y_min = min(y_min_h, y_min_g)
    y_max = max(y_max_h, y_max_g)
    y_margin_up = 0.46
    y_margin_down = 0.05
    y_min_plot, y_max_plot = get_plot_range(y_min, y_max, y_margin_down,
                                            y_margin_up)

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .55, .85, .85]
    list_obj = [
        incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat,
        incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["inclusive", "quark", "gluon", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_mc, c_quark_mc, c_gluon_mc, c_hf_mc, c_incl_mc,
                         c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1, 1))
    ]
    markers = [
        m_incl_mc, m_quark_mc, m_gluon_mc, m_hf_mc, m_incl_mc, m_quark_mc,
        m_gluon_mc
    ]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    cshape_mc.Update()
    for gr, c in zip((incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst),
                     (c_incl_mc, c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        incl_pythia_syst.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, quark, gluon

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .61, .85, .85]
    list_obj = [
        quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat,
        quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["quark", "gluon", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_quark_mc, c_gluon_mc, c_hf_mc, c_quark_mc,
                         c_gluon_mc), (2, 2, 1, 1, 1))
    ]
    markers = [m_quark_mc, m_gluon_mc, m_hf_mc, m_quark_mc, m_gluon_mc]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_qgd_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    cshape_mc.Update()
    for gr, c in zip((quark_pythia_syst, gluon_pythia_syst),
                     (c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        quark_pythia_syst.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_qgd_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, inclusive

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .67, .85, .85]
    list_obj = [incl_pythia_syst_cl, incl_pythia_stat, hf_pythia_stat]
    labels_obj = ["inclusive", "", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_mc, c_incl_mc, c_hf_mc), (2, 1, 1))
    ]
    markers = [m_incl_mc, m_incl_mc, m_hf_mc]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_id_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    # Draw a line through the points.
    if shape == "nsd":
        for h in (incl_pythia_stat, hf_pythia_stat):
            h_line = h.Clone(h.GetName() + "_line")
            h_line.SetLineStyle(2)
            h_line.Draw("l hist same")
            list_new.append(h_line)
    cshape_mc.Update()
    incl_pythia_syst_cl.SetMarkerColor(get_colour(c_incl_mc))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        incl_pythia_syst_cl.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_id_%s.pdf" % (rootpath, shape, suffix))

    # data inclusive vs PYTHIA, quark, gluon

    #leg_pos = [.6, .65, .75, .85]
    #leg_pos = [.72, .55, .85, .85]
    leg_pos = [.6, .7, .85, .85]
    list_obj = [
        incl_data_syst, quark_pythia_syst, gluon_pythia_syst, incl_data_stat,
        quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["inclusive (data)", "quark (PYTHIA 8)", "gluon (PYTHIA 8)"]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_data, c_quark_mc, c_gluon_mc, c_incl_data,
                         c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1))
    ]
    markers = [
        m_incl_data, m_quark_mc, m_gluon_mc, m_incl_data, m_quark_mc,
        m_gluon_mc
    ]
    y_margin_up = 0.3
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_data_iqg" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip((incl_data_syst, quark_pythia_syst, gluon_pythia_syst),
                     (c_incl_data, c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_data_i_mc_qg_%s.pdf" % (rootpath, shape, suffix))
Exemplo n.º 3
0
class Frame:

    markers = {
        "opencircle": (24, 1),
        "smallopencircle": (24, 0.5),
        "fullcircle": (20, 1),
        "smallfullcircle": (20, 0.5),
        "opensquare": (25, 1),
        "smallopensquare": (25, 0.5),
        "fullsquare": (21, 1),
        "smallfullsquare": (21, 0.5),
        "opentriangle": (26, 1),
        "smallopentriangle": (26, 0.5),
        "fulltriangle": (22, 1),
        "smallfulltriangle": (22, 0.5),
        "opencross": (28, 1),
        "smallopencross": (28, 0.5),
        "fullcross": (34, 1),
        "smallfullcross": (34, 0.5),
        "opendiamond": (27, 1),
        "smallopendiamond": (27, 0.5),
        "fulldiamond": (33, 1),
        "smallfulldiamond": (33, 0.5)
    }

    #http://root.cern.ch/root/html/TAttMarker.html

    def __init__(self,
                 title,
                 xtitle="",
                 xmin=0,
                 xmax=1.,
                 ytitle="",
                 ymin=0,
                 ymax=0.,
                 option="",
                 nxbin=2,
                 nybin=2,
                 logy=False,
                 logx=False):
        randomid = "%d" % (random.randint(10000000000, 99999999999))
        self.ymin = ymin
        self.ymax = ymax
        self.xmin = xmin
        self.xmax = xmax
        self.palette = (1, 2, 4, 8, 9, 42, 46, 38, 31)
        self.logy = logy
        if logy and self.ymin <= 0:
            self.ymin = 1.e-5

        self.logx = logx
        if logx and self.xmin <= 0:
            self.xmin = 1.e-5

        if ymax > ymin:
            self.hF = TH2F(randomid, title, nxbin, xmin, xmax, nybin, ymin,
                           ymax)
        else:
            self.hF = TH2F(randomid, title, nxbin, xmin, xmax, nybin, ymin,
                           ymin + 1)
            ymax = ymin + 1

        self.yaxis2 = None
        self.hF.GetXaxis().SetTitle(xtitle)
        self.hF.GetYaxis().SetTitle(ytitle)

        if logy:
            gPad.SetLogy()
        if logx:
            gPad.SetLogx()
        self.hF.SetStats(0)
        self.hF.Draw()
        self.pad = gPad.cd()  # yes, the cd() is needed, gPad is special

        self.items = []
        self.options = []
        self.labels = []
        # list of options (e.g. logy), comma or white-space separated
        self.frame_options = option.replace(",", " ").split()

        self.tls = []
        self.tlines = []

    def process_options(self, h, opts):
        """ FIXME, work in progress, to be used in add and drawLegend consistently """
        if opts == "":
            optstring = h.GetDrawOption()
            if optstring == "same":
                optsring = "L"
        else:
            optstring = ""
            for o in opts.split("+"):
                if o == "hist":
                    optstring += "L"
                elif o.lower() in self.markers:
                    optstring += "P"
                elif o == "L":
                    optstring += "L"
                elif o == "C":
                    optstring += "C"
                else:
                    print "unknown option : ", o
        print "optstring ", optstring, "opts", opts

    def auto_color(self):
        return self.palette[(len(self.items) - 1) % len(self.palette)]

    def auto_marker_color(self):
        markers = ("fullcircle", "opencircle", "fullsquare", "opensquare",
                   "fulltriangle", "opentriangle")
        n = len(self.items) - 1
        m = n % len(markers)
        c = (m + n // len(markers)) % len(self.palette)
        return "small" + markers[m], self.palette[c]

    def add(self,
            item,
            drawOption="",
            label=None,
            color=None,
            size=None,
            f=None,
            axis=1,
            add_to_legend=True):
        self.items.append(item)
        self.options.append(drawOption)

        if add_to_legend == False:
            self.labels.append(None)
        elif label:
            self.labels.append(label)
        else:
            try:
                if item.file.label:
                    self.labels.append(item.file.label)
                elif item.file.info:
                    self.labels.append(item.file.info)
                else:
                    self.labels.append("")
            except AttributeError:
                # histogram may not have a file attribute
                self.labels.append("")

        if color is None and drawOption == "auto":
            drawOption, color = self.auto_marker_color()
            self.options[-1] = drawOption

        elif color is None:
            color = self.auto_color()

        item.SetLineColor(color)
        item.SetMarkerColor(color)

        if size is not None:
            item.SetMarkerSize(size)

        if drawOption == "P" and item.GetMarkerStyle() == 1:
            item.SetMarkerStyle(20)

        if drawOption.lower() in self.markers:
            item.SetMarkerStyle(self.markers[drawOption.lower()][0])
            item.SetMarkerSize(self.markers[drawOption.lower()][1])
            drawOption = "P"

        if drawOption.startswith(
                "L+") and drawOption[2:].lower() in self.markers:
            item.SetMarkerStyle(self.markers[drawOption[2:].lower()][0])
            item.SetMarkerSize(self.markers[drawOption[2:].lower()][1])
            drawOption = "PL"

        if drawOption == "fill":
            drawOption = "hist"
            if color:
                item.SetFillColor(color)

        if drawOption == "box":
            item.SetFillColor(0)
            item.SetLineColor(color)

        if f is not None:
            f(item)

        if axis == 2 and self.yaxis2 is not None:
            yscale = (self.ymax - self.ymin) / (self.ymax2 - self.ymin2)
            # rescale for the second axis
            if type(item) is TGraph:
                xdata = [x for x in item.GetX()]
                ydata = [
                    self.ymin + (y - self.ymin2) * yscale for y in item.GetY()
                ]
                for n in range(len(ydata)):
                    item.SetPoint(n, xdata[n], ydata[n])

        self.pad.cd()
        item.Draw("same0 " + drawOption)
        self.pad.Update()

    def addLatex(self, x, y, text, textsize=0.3, textcolor=1):
        tl = TLatex(x, y, text)
        tl.SetTextSize(textsize)
        tl.SetTextColor(textcolor)
        tl.Draw("same")
        self.tls.append(tl)
        return tl

    def addLine(self, x1, y1, x2, y2, arrow="", arrowsize=0.1):
        if arrow == "":
            tl = TLine(x1, y1, x2, y2)
        elif arrow == "<->":
            tl = TArrow(x1, y1, x2, y2, arrowsize, "<|>")
        elif arrow == "->":
            print x2, y2, arrowsize
            tl = TArrow(x1, y1, x2, y2, arrowsize, "|>")
            tl.SetAngle(40)
            tl.SetLineWidth(1)
            tl.SetFillColor(1)
        tl.Draw("same")
        self.tlines.append(tl)
        return tl

    def drawLegend(self,
                   xl=0.8,
                   yl=0.8,
                   xh=0.95,
                   yh=0.95,
                   title="",
                   columns=1):
        self.pad.cd()
        self.legend = TLegend(xl, yl, xh, yh, title)
        self.legend.SetNColumns(columns)
        self.legend.SetFillColor(0)
        for h, l, o in zip(self.items, self.labels, self.options):
            if l is None or l == "":
                continue
            if o == "":
                o = h.GetDrawOption()
                if o == "same":
                    o = "L"
            if o == "hist" or o == "H":
                o = "L"
            elif o.lower() in self.markers:
                o = "P"
            self.legend.AddEntry(h, l, o)
        self.legend.Draw()
        self.Draw()

    def DrawLegend(self,
                   xl=0.8,
                   yl=0.8,
                   xh=0.95,
                   yh=0.95,
                   title="",
                   columns=1):
        self.drawLegend(xl, yl, xh, yh, title, columns)

    def Draw(self):
        ymax = self.ymax
        if self.ymax <= self.ymin:
            for h in self.items:
                try:
                    y = h.GetBinContent(h.GetMaximumBin()) * 1.10
                except AttributeError:
                    try:
                        y = max(h.GetY())
                    except AttributeError:
                        y = ymax

                if y > ymax: ymax = y

        if ymax <= self.ymin:
            ymax = self.ymin + 1
        self.hF.GetYaxis().SetLimits(self.ymin, ymax)

        if "logy" in self.frame_options:
            self.pad.SetLogy()
        if "logx" in self.frame_options:
            self.pad.SetLogx()
        if "grid" in self.frame_options or "gridxy" in self.frame_options:
            self.pad.SetGrid()
        if "gridx" in self.frame_options:
            self.pad.SetGridx()
        if "gridy" in self.frame_options:
            self.pad.SetGridy()

        self.pad.Update()

    def Print(self, filename=None):
        if filename:
            self.pad.Print(filename)

    def addVerticalAxis(self, title, ymin, ymax):
        self.yaxis2 = TGaxis(self.xmax, self.ymin, self.xmax, self.ymax, ymin,
                             ymax, 510, "+L")
        self.yaxis2.SetName("axis")
        self.yaxis2.SetLabelOffset(0.01)
        self.yaxis2.SetTitle(title)
        self.yaxis2.Draw()
        self.ymin2 = ymin
        self.ymax2 = ymax
        return self.yaxis2

    def getXaxis(self):
        """ return the x-axis (for setting attributes) """
        return self.hF.GetXaxis()

    def getYaxis(self):
        """ return the y-axis (for setting attributes) """
        return self.hF.GetYaxis()

    def getYaxis2(self):
        """ return the second y-axis (note: this is a TGaxis, not a TAxis)"""
        return self.axis2
Exemplo n.º 4
0
    lines[iLine].SetLineColor(iLine + 1)
    lines[iLine].Draw('same')

# add second axis
canv.SetRightMargin(0.1)
all_graphs[0].GetXaxis().SetRangeUser(0, 68)
all_graphs[0].GetXaxis().SetLabelOffset(0.02)
gPad.RangeAxis(0, gPad.GetUymin(), 68, gPad.GetUxmax())
axis = TGaxis(gPad.GetUxmin(), gPad.GetUymin(), gPad.GetUxmax(),
              gPad.GetUymin(),
              gPad.GetUxmin() * calo_init.args.X0density,
              gPad.GetUxmax() * calo_init.args.X0density, 506, "-")
axis.SetLabelSize(0.05)
axis.SetTitleSize(0.07)
axis.SetTitleOffset(0.9)
axis.SetLabelOffset(0.02)
axis.Draw()
axis.SetLabelFont(42)
unit1 = draw_text(['(cm)'], [0.91, 0.09, 1, 0.14], 1, 0)
unit1.SetTextSize(0.05)
unit1.SetTextFont(42)
unit2 = draw_text(['(X_{0})'], [0.91, 0.16, 1, 0.21], 1, 0)
unit2.SetTextSize(0.05)
unit2.SetTextFont(42)
canv.Update()

# Draw all labels
if calo_init.args.specialLabel:
    draw_text([calo_init.args.specialLabel], [0.57, 0.88, 0.85, 0.98],
              kGray + 3, 0).SetTextSize(0.05)
canv.Update()
    hMeanShift.SetBinContent(iPt, shift)
    hSyst.SetBinContent(iPt, syst)

cRMS = TCanvas('cRMS', '', 800, 800)
cRMS.DrawFrame(hRMS.GetBinLowEdge(1), 0.1, ptMax, 20.,
               ';#it{p}_{T} (GeV/#it{c});RMS (%)')
hRMS.DrawCopy('same')
axisSoverB = TGaxis(gPad.GetUxmax(), gPad.GetUymin(), gPad.GetUxmax(),
                    gPad.GetUymax(), 0.01, 20., 510, "+LG")
axisSoverB.SetLineColor(kRed + 1)
axisSoverB.SetLabelColor(kRed + 1)
axisSoverB.SetLabelFont(42)
axisSoverB.SetLabelSize(0.045)
axisSoverB.SetTitle('S/B (3#sigma)')
axisSoverB.SetTitleOffset(1.2)
axisSoverB.SetLabelOffset(0.012)
axisSoverB.SetTitleColor(kRed + 1)
axisSoverB.SetTitleFont(42)
axisSoverB.SetTitleSize(0.05)
axisSoverB.SetMaxDigits(3)
axisSoverB.Draw()
hSoverB.DrawCopy('same')
cRMS.Update()

cSyst = TCanvas('cSyst', '', 800, 800)
cSyst.DrawFrame(hSyst.GetBinLowEdge(1), 0.1, ptMax, 20.,
                ';#it{p}_{T} (GeV/#it{c}); Syst (%)')
SetObjectStyle(hRMS, color=kRed + 1, fillstyle=0, linewidth=3)
SetObjectStyle(hMeanShift, color=kBlack, fillstyle=0, linewidth=3)
SetObjectStyle(hSyst, color=kBlue + 1, fillstyle=0, linewidth=3)
hMeanShift.DrawCopy('same')
Exemplo n.º 6
0
class Differential1D:

    """ Base class for displaying 1D differential plots.  

    Produces a plot comparing the baseline geometry (base) to the geometry specified by
    the geom arguement.  The quantity plotted is given by the "stat" option, and is
    limited to the different statistics created by the StarBASE application.  At present,
    these include:

    stat="radlen"  :: plots number of radiation lengths of material encountered
                      ... need to add more stats

    The plot will show a solid histogram for the baseline geometry, with the comparison
    geometry shown with red hashes.  The fractional difference (baseline-comp)/baseline
    is shown at the bottom in blue, scaled according to the alternate axis at the right.

    base:       selects the baseline geometry.                     [Mandatory]
    geom:       selects the comparison geometry.                   [Mandatory]
    volume:     selects the volume to be compared.                 [Mandatory]
    geomvolume: selects the volume in the comparison geometry.     [Default: same]
    stat:       selects the statistic to compare.                  [Default: radlen]
    xmin, xmax: x-axis range.                                      [Optional]
    ymin, ymax: y-axis range.                                      [Optional]
    """

    def __init__(self, 
                 base,                   geom,
                 volume="EMSS",          geomvolume="same",
                 stat="radlen",                    
                 xmin=+0.,                xmax=-1.,
                 ymin=+0.,                ymax=-1.,
                 canvas=0,
                 legend=False
                 ):

        self.name = volume
        self.base = base
        self.geom = geom

        baseFile = get_geom_file(base)                                       # get the files
        compFile = get_geom_file(geom)

        hname = "h_"+stat+"_"+volume+"_eta"                             # retrive the histograms from the files
        print "Get histo: " + str(hname)


        self.histo_base = stat_histo( stat, volume, file=baseFile )
        if ( geomvolume == "same" ):
            self.histo_comp = stat_histo( stat, volume, compFile )
        else:
            self.histo_comp = stat_histo( stat, geomvolume, compFile )

        self.histo_diff = self.histo_base.Clone( hname + "_diff" )      # difference the histograms
        self.histo_diff.Add( self.histo_comp, -1.0 )
        self.histo_diff.Divide(self.histo_base)                         # diff will be (old-new)/old * 100%

        if ( canvas == 0 ):
            canvas = TCanvas("temp"+base+geom+volume+geomvolume,"Differential 1D: baseline="+base+" compare="+geom,500,400);
            self.canvas = canvas

        # Detect and apply optional x-axis range
        if ( xmax > xmin ):
            self.histo_base.GetXaxis().SetRangeUser(xmin,xmax)
            self.histo_comp.GetXaxis().SetRangeUser(xmin,xmax)
        # ... or zoom in on an appropriate scale
        else:
#            auto_range( self.histo_base )
#            auto_range( self.histo_comp )
            xmin = auto_min( self.histo_base )
            xmax = auto_max( self.histo_base )
            self.histo_base.GetXaxis().SetRangeUser(xmin,xmax)
            self.histo_comp.GetXaxis().SetRangeUser(xmin,xmax)

#        xmin = TMath.Min( self.histo_base.GetXaxis().GetXmin(),self.histo_comp.GetXaxis().GetXmin() )
#        xmax = TMath.Max( self.histo_base.GetXaxis().GetXmax(),self.histo_comp.GetXaxis().GetXmax() )

#        print "xmin="+str(xmin)
#        print "xmax="+str(xmax)

        # Detect and apply optional y-axis range
        if ( ymax > ymin ):
            self.histo_base.GetYaxis().SetRangeUser(ymin,ymax)
        else:
            ymin = self.histo_base.GetMinimum()
            ymax = TMath.Max( self.histo_base.GetMaximum(),
                              self.histo_comp.GetMaximum())
            ymax *= 1.05

        # Current range in y-axis extends from 0 to ymax.  We want
        # to expand this to go from -0.2*ymax to ymax.
        ymin = -0.2 * ymax
        self.histo_base.GetYaxis().SetRangeUser(ymin,ymax)

        # Draw the baseline and comparison histograms
        self.histo_base.SetLineWidth(2)
        self.histo_base.SetFillStyle(1001)
        self.histo_base.SetFillColor(22)
        self.histo_base.Draw()

        self.histo_comp.SetLineColor(2)
        self.histo_comp.SetLineStyle(2)
        self.histo_comp.SetFillStyle(3345)
        self.histo_comp.SetFillColor(2)
        self.histo_comp.Draw("same")

        # Rescale difference histogram so that it is in percent
        self.histo_diff.Scale(100.0)

        # This is the maximum of the histogram.
        yfull_max = self.histo_diff.GetMaximum()
        yfull_min = self.histo_diff.GetMinimum()
        yfull = TMath.Max( yfull_max, TMath.Abs( yfull_min ) )
        self.max_differential = yfull

        yfull *= 1.3

        if ( yfull == 0. ):
            yfull = 1.0

        # We need to rescale the histogram so that it fits w/in 10% of ymax
        self.histo_diff.Scale( 0.10 * ymax / yfull )

        # Next we shift the histogram down by 0.1 * ymax
        nbinx=self.histo_diff.GetNbinsX();
        i=1
        while ( i<=nbinx ):
            self.histo_diff[i] -= 0.1 * ymax
            i+=1
        
        # Reset the line color and draw on the same plot
        self.histo_diff.SetLineColor(4)
        self.histo_diff.Draw("same")

        self.line = TLine(xmin, -0.1 * ymax, xmax, -0.1*ymax )
        self.line.SetLineStyle(3)
        self.line.Draw()

        # And superimpose an axis on the  new plot
        xa = xmax

        self.axis = TGaxis( xa, -0.2*ymax, xa, 0.0, -yfull, +yfull, 50510, "-+L" )
        self.axis.SetLabelSize(0.03)
        self.axis.SetLabelOffset(-0.02)
        self.axis.SetLineColor(4)
        self.axis.SetTextColor(4)
        self.axis.SetLabelColor(4)
        self.axis.SetNdivisions(4)
#       self.axis.SetTitle("(base-comp)/base [%]")
        self.axis.SetTitleSize(0.0175)
        self.axis.SetTitleOffset(-0.5)
        self.axis.Draw();

        # Add the legend if requested
        if ( legend ):
            self.legend = TLegend( 0.78, 0.80, 0.98, 0.98 )
            self.legend.AddEntry( self.histo_base, base )
            self.legend.AddEntry( self.histo_comp, geom )
            self.legend.AddEntry( self.histo_diff, "#frac{"+base+"-"+geom+"}{"+base+"} [%]" )
            self.legend.Draw()