Ejemplo n.º 1
0
    def double_profile(tprofile_x, tprofile_y):
        """creates a graph with points whose x and y values and errors are taken from the bins of two profiles with identical binning"""
        ## Note: underflow and overflow bins are discarded

        if len(tprofile_x) != len(tprofile_y):
            raise ValueError(
                "Cannot build double profile: x and y profiles "
                "have different number or bins ({} and {})".format(
                    len(tprofile_x) - 2,
                    len(tprofile_y) - 2))

        _dp_graph = Graph(len(tprofile_x) - 2,
                          type='errors')  # symmetric errors

        _i_point = 0
        for _i_bin, (_bin_proxy_x,
                     _bin_proxy_y) in enumerate(zip(tprofile_x, tprofile_y)):
            # disregard overflow/underflow bins
            if _i_bin == 0 or _i_bin == len(tprofile_x) - 1:
                continue

            if _bin_proxy_y.value:
                _dp_graph.SetPoint(_i_point, _bin_proxy_x.value,
                                   _bin_proxy_y.value)
                _dp_graph.SetPointError(_i_point, _bin_proxy_x.error,
                                        _bin_proxy_y.error)
                _i_point += 1

        # remove "unfilled" points
        while (_dp_graph.GetN() > _i_point):
            _dp_graph.RemovePoint(_dp_graph.GetN() - 1)

        return _dp_graph
Ejemplo n.º 2
0
def get_uncertainty_graph(hnom, curve_uncert):
    """
    Convert an histogram and a RooCurve
    into a TGraphAsymmError

    Parameters
    ----------
    hnom: TH1F, TH1D, ...
        The histogram of nominal values
    curve_uncert: RooCurve
        The uncertainty band around the nominal value

    TODO: Improve the handling of the underflow and overflow bins
    """
    graph = Graph(hnom.GetNbinsX())
    for ibin in xrange(1, hnom.GetNbinsX() + 1):
        uncerts = []
        for ip in xrange(3, curve_uncert.GetN() - 3):
            x, y = ROOT.Double(0.), ROOT.Double(0.)
            curve_uncert.GetPoint(ip, x, y)
            if hnom.GetBinLowEdge(ibin) <= x < hnom.GetBinLowEdge(ibin + 1):
                uncerts.append(y)
        log.debug('{0}, bin {1}: {2}'.format(hnom.name, ibin, uncerts))
        low, high = min(uncerts), max(uncerts)
        bin_center = 0.5 * (hnom.GetBinLowEdge(ibin + 1) +
                            hnom.GetBinLowEdge(ibin))
        e_x_low = bin_center - hnom.GetBinLowEdge(ibin)
        e_x_high = hnom.GetBinLowEdge(ibin + 1) - bin_center
        bin_content = hnom.GetBinContent(ibin)
        e_y_low = hnom.GetBinContent(ibin) - low
        e_y_high = high - hnom.GetBinContent(ibin)
        graph.SetPoint(ibin - 1, bin_center, bin_content)
        graph.SetPointError(ibin - 1, e_x_low, e_x_high, e_y_low, e_y_high)
    return graph
Ejemplo n.º 3
0
def remap_x_values(hist, corr_hist):
    """
    Map the x values of hist to the y values of map_hist.
    In order to do so, it is necessary that the x values of hist are also present as x-values in map_hist.

    Parameters
    ----------
    hist : Hist1D
    corr_hist : Hist2D
                Correlations between the quantity on hist's x-axis (also corr_hist's xaxis) and the new
                quantity to plot agains (on corr_hist's y-axis.

    Returns
    -------
    Graph
            Graph of the remapped hist. Errors are ??? TODO
    """
    hist = asrootpy(hist)
    corr_hist = asrootpy(corr_hist)
    profx = asrootpy(corr_hist.ProfileX(gen_random_name()))

    rt_graph = Graph()
    for i, (nch_ref_bin,
            counter_bin) in enumerate(zip(profx.bins(), hist.bins())):
        rt_graph.SetPoint(i, nch_ref_bin.value, counter_bin.value)
        xerr, yerr = nch_ref_bin.error / 2.0, counter_bin.error / 2.0
        rt_graph.SetPointError(i, xerr, xerr, yerr, yerr)
    return rt_graph
Ejemplo n.º 4
0
def grrScale(gr1, scale):
    x1 = Double()
    x_ = Double()
    x1e = Double()

    y1 = Double()
    y1e = Double()

    y = []
    ex = []
    ey = []

    NC = gr1.GetN()
    x = [0 for i in range(NC)]

    for ii in range(NC):
        x1e = gr1.GetErrorX(ii)
        y1e = gr1.GetErrorY(ii)
        gr1.GetPoint(ii, x_, y1)
        x1 = x_ * 1.0
        x[ii] = x1
        y.append(y1 * scale)
        ex.append(x1e)
        ey.append(y1e * scale)

    gr = Graph(NC)
    for x0, y0, x0e, y0e, i in zip(x, y, ex, ey, range(NC)):
        gr.SetPoint(i, x0, y0)
        gr.SetPointError(i, x0e, x0e, y0e, y0e)
    return gr
Ejemplo n.º 5
0
def get_mean_rms(category, var):
    gr_mean = Graph(len(SIGNALS_14TEV))
    gr_rms = Graph(len(SIGNALS_14TEV))
    for ip, signal in enumerate(SIGNALS_14TEV):
        with root_open('efficiencies/eff_presel_{0}_v{1}.root'.format(
                signal, VERSION)) as fsig:
            h_s = fsig[category].Get('h_' + category + '_' + var['name'])
            gr_mean.SetPoint(ip, DATASETS[signal]['mu'], h_s.GetMean())
            gr_mean.SetPointError(ip, 0, 0, h_s.GetMeanError(),
                                  h_s.GetMeanError())
            gr_rms.SetPoint(ip, DATASETS[signal]['mu'], h_s.GetRMS())
            gr_rms.SetPointError(ip, 0, 0, h_s.GetRMSError(),
                                 h_s.GetRMSError())
    gr_mean.xaxis.title = 'Average Interactions Per Bunch Crossing'
    gr_mean.yaxis.title = 'Mean of ' + get_label(var)
    gr_rms.xaxis.title = 'Average Interactions Per Bunch Crossing'
    gr_rms.yaxis.title = 'RMS of ' + get_label(var)
    return gr_mean, gr_rms
Ejemplo n.º 6
0
def addConstantError(gr1, error, **kwargs):
    x_ = Double()
    x1e = Double()
    y1_ = Double()
    y1e = Double()
    NC = gr1.GetN()
    y2 = [0 for i in range(NC)]
    ex = []
    ey = []
    x = [0 for i in range(NC)]
    gr = Graph(NC)
    for ii in range(NC):
        x1e = gr1.GetErrorX(ii)
        y1e = gr1.GetErrorY(ii)
        gr1.GetPoint(ii, x_, y1_)
        print("{} {} {}".format(i, x_, y1_))
        x1 = x_ * 1.0

        x[ii] = x1
        y1 = y1_ * 1.0
        y2[ii] = y1
        print("Append y with {}".format(y1))
        print(y2)
        ex.append(x1e)
        if (kwargs.get('rel'), False):
            ey.append(math.sqrt(y1e**2 + (error * y1)**2))
            print("Old error: {}, New Error: {}".format(
                y1e, math.sqrt(y1e**2 + (error * y1)**2)))
        else:
            ey.append(math.sqrt(y1e**2 + error**2))


#     gr.SetPoint(i,x1,y1)
#     print("Set point {} {},{}".format(i,x1,y1))
#
#     if(kwargs.get('rel'),False):
#       gr.SetPointError(i,x1e,x1e,math.sqrt(y1e**2+(error*y1)**2),math.sqrt(y1e**2+(error*y1)**2))
#       print("Set point Error {} {},{}".format(i,x1e,math.sqrt(y1e**2+(error*y1)**2)))
#     else:
#       gr.SetPointError(i,x1e,x1e,math.sqrt(y1e**2+error**2),math.sqrt(y1e**2+error**2))

    gr = Graph(NC)
    print(x)
    print(y2)
    print(ex)
    print(ey)
    for x0, y0, x0e, y0e, i in zip(x, y2, ex, ey, range(NC)):
        gr.SetPoint(i, x0, y0)
        print("Set point {} {},{}".format(i, x0, y0))
        gr.SetPointError(i, x0e, x0e, y0e, y0e)
        print("Set point Error {} {},{}".format(i, x0e, y0e))

    print(gr)
    return gr
Ejemplo n.º 7
0
def draw_curve_7(_func, name, title, ylow, yhigh):
    """ Draw 7TeV trigger efficiency curves """
    graphs = []
    for (trigger, color) in triggers:
        tool = ROOT.TauTriggerCorrections(
            os.path.join(base, 'triggerSF_%s.root' % trigger))
        func = getattr(tool, _func)
        eff = map(lambda x: func(x, 0), pt)
        eff_low = map(lambda x: func(x, -1), pt)
        eff_high = map(lambda x: func(x, 1), pt)
        graph = Graph(len(pt), name=trigger)
        for i, (p, e, e_low,
                e_high) in enumerate(zip(pt, eff, eff_low, eff_high)):
            graph.SetPoint(i, p / 1000, e)
            graph.SetPointError(i, 0.4, 0.4, e - e_low, e_high - e)
        graph.linecolor = color
        graph.linewidth = 2
        graph.fillstyle = '/'
        graph.fillcolor = color
        graphs.append(graph)
    c = Canvas()
    leg = Legend(len(graphs),
                 pad=c,
                 topmargin=0.4,
                 leftmargin=0.3,
                 textsize=25,
                 margin=0.2)
    for i, g in enumerate(graphs):
        if i == 0:
            g.Draw('3AC')
            g.xaxis.title = '#font[52]{p}_{T} [GeV]'
            g.xaxis.SetLimits(20, 100)
            g.yaxis.SetLimits(ylow, yhigh)
            g.yaxis.SetRangeUser(ylow, yhigh)
            g.yaxis.title = title
        else:
            g.Draw('3C SAME')
        leg.AddEntry(g, g.name, 'L')
    leg.Draw()
    lines = []
    for thresh in (25, 35):
        line = Line(thresh, ylow, thresh, yhigh)
        line.linestyle = 'dashed'
        line.linewidth = 2
        line.Draw()
        lines.append(line)
    c.SaveAs('trigger_{0}.png'.format(name))
    c.SaveAs('trigger_{0}.eps'.format(name))
Ejemplo n.º 8
0
def get_rebinned_graph(graph_origin, binning=None):
    if binning is None:
        return graph_origin
    graph_rebin = Graph(len(binning) - 1)
    if len(graph_origin) != len(graph_rebin):
        log.warning('uniform: {0} bins != rebinned: {1} bins'.format(
            len(graph_origin), len(graph_rebin)))
        raise RuntimeError('wrong binning')
    for ipoint, (y,
                 yerr) in enumerate(zip(graph_origin.y(),
                                        graph_origin.yerr())):
        x_rebin_err = 0.5 * (binning[ipoint + 1] - binning[ipoint])
        x_rebin = binning[ipoint] + x_rebin_err
        graph_rebin.SetPoint(ipoint, x_rebin, y)
        graph_rebin.SetPointError(ipoint, x_rebin_err, x_rebin_err, yerr[0],
                                  yerr[1])
    return graph_rebin
Ejemplo n.º 9
0
def UncertGraph(hnom, curve_uncert):
    """
    Convert an histogram and a RooCurve
    into a TGraphAsymmError

    Parameters
    ----------
    hnom: TH1F, TH1D,...
        The histogram of nominal values
    curve_uncert: RooCurve
        The uncertainty band around the nominal value
    curve_uncert: RooCurve
    TODO: Improve the handling of the underflow and overflow bins
    """

    graph = Graph(hnom.GetNbinsX())
    # ---------------------------------------------
    for ibin in xrange(1, hnom.GetNbinsX() + 1):
        uncerts = []
        for ip in xrange(3, curve_uncert.GetN() - 3):
            x, y = ROOT.Double(0.), ROOT.Double(0.)
            curve_uncert.GetPoint(ip, x, y)
            if int(x) == int(hnom.GetBinLowEdge(ibin)):
                uncerts.append(y)
        uncerts.sort()
        log.info('{0}: {1}'.format(hnom.name, uncerts))
        if len(uncerts) != 2:
            for val in uncerts:
                if val in uncerts:
                    uncerts.remove(val)
        if len(uncerts) != 2:
            raise RuntimeError(
                'Need exactly two error values and got {0}'.format(uncerts))

        bin_center = 0.5 * (hnom.GetBinLowEdge(ibin + 1) +
                            hnom.GetBinLowEdge(ibin))
        e_x_low = bin_center - hnom.GetBinLowEdge(ibin)
        e_x_high = hnom.GetBinLowEdge(ibin + 1) - bin_center
        bin_content = hnom.GetBinContent(ibin)
        e_y_low = hnom.GetBinContent(ibin) - uncerts[0]
        e_y_high = uncerts[1] - hnom.GetBinContent(ibin)
        graph.SetPoint(ibin - 1, bin_center, bin_content)
        graph.SetPointError(ibin - 1, e_x_low, e_x_high, e_y_low, e_y_high)
    # ---------------------------------------------
    return graph
Ejemplo n.º 10
0
def makeSystError(gr1, gr2, **kwargs):
    x_ = Double()
    x1e = Double()
    x2 = Double()
    x2e = Double()
    y1 = Double()
    y1e = Double()
    y2 = Double()
    y2e = Double()
    NC = gr1.GetN()
    print("Number of points: {}".format(NC))
    y = []
    ex = []
    ey = []
    x = [0 for i in range(NC)]

    for ii in range(NC):
        x1e = gr1.GetErrorX(ii)
        y1e = gr1.GetErrorY(ii)
        gr1.GetPoint(ii, x_, y1)
        x1 = x_ * 1.0
        gr2.GetPoint(ii, x2, y2)
        x2e = gr2.GetErrorX(ii)
        y2e = gr2.GetErrorY(ii)
        x[ii] = x1
        if (kwargs.get('abs', False)):
            y.append(math.fabs(y1 - y2))
        elif (kwargs.get('rel', False)):
            y.append((y1 - y2) / (y1 + y2))
        else:
            y.append(y1 - y2)
        ex.append(x1e)
        ey.append(math.sqrt(y1e**2 + y2e**2))
    gr = Graph(NC)
    for x0, y0, x0e, y0e, i in zip(x, y, ex, ey, range(NC)):
        gr.SetPoint(i, x0, y0)
        print("Set point {} {},{}".format(i, x0, y0))
        gr.SetPointError(i, x0e, x0e, y0e, y0e)
    return gr
Ejemplo n.º 11
0
def grrDivide(gr1, gr2):
    x1 = Double()
    x_ = Double()
    x1e = Double()
    x2 = Double()
    x2e = Double()
    y1 = Double()
    y1e = Double()
    y2 = Double()
    y2e = Double()
    test = []
    y = []
    ex = []
    ey = []

    NC = gr1.GetN()
    x = [0 for i in range(NC)]
    test = [0 for i in range(NC)]

    for ii in range(NC):
        x1e = gr1.GetErrorX(ii)
        y1e = gr1.GetErrorY(ii)
        gr1.GetPoint(ii, x_, y1)
        x1 = x_ * 1.0
        gr2.GetPoint(ii, x2, y2)
        x2e = gr2.GetErrorX(ii)
        y2e = gr2.GetErrorY(ii)
        x[ii] = x1
        y.append(y1 / y2 if y2 != 0 else 0)
        ex.append(x2e)
        ey.append(
            math.sqrt(pow(y1e / y2, 2) + pow(y1 * y2e /
                                             (y2 * y2), 2)) if y2 != 0 else 0)

    gr = Graph(NC)
    for x0, y0, x0e, y0e, i in zip(x, y, ex, ey, range(NC)):
        gr.SetPoint(i, x0, y0)
        gr.SetPointError(i, x0e, x0e, y0e, y0e)
    return gr
Ejemplo n.º 12
0
def main(args):

    fileList = glob('/data/nawoods/lepsForSIP/*.root')
    files = {int(f.split('_M')[1].split('.')[0]) : f for f in fileList}

    checkers = {m : MuonSIPChecker('m={}'.format(m), [f]) for m,f in files.iteritems()}
    sipRMS = Graph(len(fileList), type='errors')
    sipHists = []
    dxyRMS = Graph(len(fileList), type='errors')
    dxyHists = []
    dzRMS = Graph(len(fileList), type='errors')
    dzHists = []

    ipHists = []
    ipErrHists = []

    fracFailing = Graph(len(fileList), type='errors')
    for i, m in enumerate(sorted(files.keys())):

        checkers[m].processSample()

        checkers[m].hists['sip'].Sumw2()
        sipRMS.SetPoint(i, float(m), checkers[m].hists['sip'].GetRMS())
        sipRMS.SetPointError(i, 0., checkers[m].hists['sip'].GetRMSError())
        sipHists.append(checkers[m].hists['sip'])
        sipHists[-1].color = getColor(m)
        sipHists[-1].title = "m_{{H}} = {}".format(m)
        sipHists[-1].drawstyle = 'hist'
        sipHists[-1].legendstyle = 'L'
        sipHists[-1].linewidth = 2
        sipHists[-1].scale(1./sipHists[-1].integral())

        ipHists.append(checkers[m].hists['ip'])
        ipHists[-1].color = getColor(m)
        ipHists[-1].title = "m_{{H}} = {}".format(m)
        ipHists[-1].drawstyle = 'hist'
        ipHists[-1].legendstyle = 'L'
        ipHists[-1].linewidth = 2
        ipHists[-1].scale(1./ipHists[-1].integral())

        ipErrHists.append(checkers[m].hists['ipErr'])
        ipErrHists[-1].color = getColor(m)
        ipErrHists[-1].title = "m_{{H}} = {}".format(m)
        ipErrHists[-1].drawstyle = 'hist'
        ipErrHists[-1].legendstyle = 'L'
        ipErrHists[-1].linewidth = 2
        ipErrHists[-1].scale(1./ipErrHists[-1].integral())

        checkers[m].hists['dxy'].Sumw2()
        dxyRMS.SetPoint(i, float(m), checkers[m].hists['dxy'].GetRMS())
        dxyRMS.SetPointError(i, 0., checkers[m].hists['dxy'].GetRMSError())
        dxyHists.append(checkers[m].hists['dxy'])
        dxyHists[-1].color = getColor(m)
        dxyHists[-1].title = "m_{{H}} = {}".format(m)
        dxyHists[-1].drawstyle = 'hist'
        dxyHists[-1].legendstyle = 'L'
        dxyHists[-1].linewidth = 2
        dxyHists[-1].scale(1./dxyHists[-1].integral())
        
        checkers[m].hists['dz'].Sumw2()
        dzRMS.SetPoint(i, float(m), checkers[m].hists['dz'].GetRMS())
        dzRMS.SetPointError(i, 0., checkers[m].hists['dz'].GetRMSError())
        dzHists.append(checkers[m].hists['dz'])
        dzHists[-1].color = getColor(m)
        dzHists[-1].title = "m_{{H}} = {}".format(m)
        dzHists[-1].drawstyle = 'hist'
        dzHists[-1].legendstyle = 'L'
        dzHists[-1].linewidth = 2
        dzHists[-1].scale(1./dzHists[-1].integral())

        fracFailing.SetPoint(i, float(m),
                             1. - float(checkers[m].nPassSIP) / checkers[m].nTot)

    
    cSIP = Canvas(1000,1000)
    draw(sipHists, cSIP, xtitle='#frac{IP_{3D}}{#sigma_{IP_{3D}}}',
         ytitle='arb.')
    legSIP = Legend(sipHists, cSIP, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04)
    legSIP.Draw("same")
    cSIP.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/sips.png')
    cSIPLog = Canvas(1000,1000)
    draw(sipHists, cSIPLog, xtitle='#frac{IP_{3D}}{#sigma_{IP_{3D}}}',
         ytitle='arb.', logy=True)
    legSIPLog = Legend(sipHists, cSIPLog, textsize=.027, entrysep=0.012, leftmargin=0.6, entryheight=0.03)
    legSIPLog.Draw("same")
    cSIPLog.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/sipsLog.png')
    
    cSIPRMS = Canvas(1000, 1000)
    sipRMS.color = 'b'
    sipRMS.drawstyle = 'PE'
    sipRMS.legendstyle = 'PE'
    draw(sipRMS, cSIPRMS, xtitle="m_{H}", ytitle="RMS(SIP_{3D})", xlimits=(0.,2600.))
    cSIPRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/sipRMS.png')
    
    cIP = Canvas(1000,1000)
    draw(ipHists, cIP, xtitle='IP_{3D}',
         ytitle='arb.')
    legIP = Legend(ipHists, cIP, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04)
    legIP.Draw("same")
    cIP.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ips.png')
    cIPLog = Canvas(1000,1000)
    draw(ipHists, cIPLog, xtitle='#frac{IP_{3D}}{#sigma_{IP_{3D}}}',
         ytitle='arb.', logy=True)
    legIPLog = Legend(ipHists, cIPLog, textsize=.027, entrysep=0.012, leftmargin=0.6, entryheight=0.03)
    legIPLog.Draw("same")
    cIPLog.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ipsLog.png')
    
    cIPErr = Canvas(1000,1000)
    draw(ipErrHists, cIPErr, xtitle='#sigma_{IP_{3D}}',
         ytitle='arb.')
    legIPErr = Legend(ipErrHists, cIPErr, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04)
    legIPErr.Draw("same")
    cIPErr.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ipErrs.png')
    cIPErrLog = Canvas(1000,1000)
    draw(ipErrHists, cIPErrLog, xtitle='#sigma_{IP_{3D}}',
         ytitle='arb.', logy=True)
    legIPErrLog = Legend(ipErrHists, cIPErrLog, textsize=.027, entrysep=0.012, leftmargin=0.6, entryheight=0.03)
    legIPErrLog.Draw("same")
    cIPErrLog.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/ipErrsLog.png')
    
    cFail = Canvas(1000, 1000)
    fracFailing.color = 'b'
    fracFailing.drawstyle = 'PE'
    fracFailing.legendstyle = 'PE'
    draw(fracFailing, cSIPRMS, xtitle="m_{H}", ytitle="Fraction failing SIP", xlimits=(0.,2600.))
    cSIPRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/fracFailing.png')
    
    cDXY = Canvas(1000,1000)
    draw(dxyHists, cDXY, xtitle='#Delta_{xy}',
         ytitle='arb.')
    legDXY = Legend(dxyHists, cDXY, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04)
    legDXY.Draw("same")
    cDXY.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dxys.png')

    cDXYRMS = Canvas(1000, 1000)
    dxyRMS.color = 'b'
    dxyRMS.drawstyle = 'PE'
    dxyRMS.legendstyle = 'PE'
    draw(dxyRMS, cDXYRMS, xtitle="m_{H}", ytitle="RMS(#Delta_{xy})", xlimits=(0.,2600.))
    cDXYRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dxyRMS.png')
    
    cDZ = Canvas(1000,1000)
    draw(dzHists, cDZ, xtitle='#Delta_{z}',
         ytitle='arb.')
    legDZ = Legend(dzHists, cDZ, textsize=.03, entrysep=0.015, leftmargin=0.6, entryheight=0.04)
    legDZ.Draw("same")
    cDZ.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dzs.png')

    cDZRMS = Canvas(1000, 1000)
    dzRMS.color = 'b'
    dzRMS.drawstyle = 'PE'
    dzRMS.legendstyle = 'PE'
    draw(dzRMS, cDZRMS, xtitle="m_{H}", ytitle="RMS(#Delta_{z})", xlimits=(0.,2600.))
    cDZRMS.Print('/afs/cern.ch/user/n/nawoods/www/sipStudy/dzRMS.png')
Ejemplo n.º 13
0
def main():
    print('Number of arguments: ', len(sys.argv), 'arguments.')
    print('Argument list:', str(sys.argv))
    filename = sys.argv[1]
    if len(sys.argv) > 2:
        fileData = sys.argv[2]
    else:
        fileData = None
    print("Input file: ")
    print(filename)
    Njets = 9

    if fileData is not None:
        fD = root_open(fileData, 'read')
        iS = 0
        gGausRMSData = fD.Get("gGausRMS{:02d}".format(iS))
        gGausRMSerrData = fD.Get("gGausRMS{:02d}_Systematics".format(iS))
        gGausYieldData = fD.Get("gGausYield{:02d}".format(iS))
        gGausYielderrData = fD.Get("gGausYield{:02d}_Systematics".format(iS))
        gGammaRMSData = fD.Get("gGammaRMS{:02d}".format(iS))
        gGammaRMSerrData = fD.Get("gGammaRMS{:02d}_Systematics".format(iS))
        gGammaYieldData = fD.Get("gGammaYield{:02d}".format(iS))
        gGammaYielderrData = fD.Get("gGammaYield{:02d}_Systematics".format(iS))

    with root_open(filename, 'read') as f:
        FullJets_jT = []
        colors = (1, 2, 3)
        for iF, c in zip((8, 6, 7), colors):
            jT = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/JetConeJtWeightBin/JetConeJtWeightBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)) for ij in range(Njets)
            ]
            bgJt = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/BgJtWeightBin/BgJtWeightBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)) for ij in range(Njets)
            ]
            jetPtBin = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/JetPtBin/JetPtBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)) for ij in range(Njets)
            ]
            nJets = [h.Integral() for h in jetPtBin]
            nBgs = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/BgTrkNumberBin/BgTrkNumberBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)).Integral() for ij in range(Njets)
            ]
            FullJets_jT.append(jT)
            #FullJets_bgJt.append(bgJt)
            #FullJets_jetPtBin.append(jetPtBin)
            for j, b, nj, nb in zip(jT, bgJt, nJets, nBgs):
                j.Rebin(2)
                b.Rebin(2)
                j.Scale(1.0 / nj, "width")
                b.Scale(1.0 / nb, "width")
                j.SetMarkerColor(c)
                b.SetMarkerColor(c)
                j.Add(b, -1.0)

        jetPt = [
            (int(
                re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                          h.GetTitle(), re.M | re.I).group(1)),
             int(
                 re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                           h.GetTitle(), re.M | re.I).group(2)))
            for h in FullJets_jT[0]
        ]  #Use regular expressions to extract jet pT range from histogram titles
        jetPtCenter = array('d', [(a + b) / 2.0 for a, b in jetPt])
        jetPtErrors = array('d', [(b - a) / 2.0 for a, b in jetPt])
        print(jetPt, type(jetPt))
        print(jetPtCenter, type(jetPtCenter))
        print(jetPtErrors, type(jetPtErrors))

        FullJets_fit = []
        FullJets_parameters = []
        FullJets_gausRMS = []
        FullJets_gammaRMS = []
        FullJets_gausYield = []
        FullJets_gammaYield = []
        for jT in FullJets_jT:
            gausRMS = []
            gammaRMS = []
            gausRMSe = []
            gammaRMSe = []
            gausYield = []
            gammaYield = []
            gausYielde = []
            gammaYielde = []
            fits = []
            parameters = []
            for h, i in zip(jT, range(Njets)):
                fit, d = fitJtHisto(h, '', 1, i, 8)
                fits.append(fit)
                parameters.append(d)
                gausRMS.append(d['gausRMS'])
                gausRMSe.append(d['gausRMSe'])
                gammaRMS.append(d['gammaRMS'])
                gammaRMSe.append(d['gammaRMSe'])
                gausYield.append(d['gausYield'])
                gausYielde.append(d['gausYielde'])
                gammaYield.append(d['gammaYield'])
                gammaYielde.append(d['gammaYielde'])

            gausRMSg = Graph(len(gausRMS) - 2)
            gammaRMSg = Graph(len(gammaRMS) - 2)
            gausYieldg = Graph(len(gausYield) - 2)
            gammaYieldg = Graph(len(gammaYield) - 2)
            for h, he, g in zip((gausYield, gammaYield),
                                (gausYielde, gammaYielde),
                                (gausYieldg, gammaYieldg)):
                for x, xe, a, e, i in zip(jetPtCenter[2:],
                                          jetPtErrors[2:], h[2:], he[2:],
                                          range(len(gausRMS) - 2)):
                    g.SetPoint(i, x, a)
                    g.SetPointError(i, xe, xe, e, e)

            for a, b, c, d, e, f, i in zip(gausRMS[2:], gammaRMS[2:],
                                           gausRMSe[2:], gammaRMSe[2:],
                                           jetPtCenter[2:], jetPtErrors[2:],
                                           range(len(gausRMS) - 2)):
                gausRMSg.SetPoint(i, e, a)
                gausRMSg.SetPointError(i, f, f, c, c)
                gammaRMSg.SetPoint(i, e, b)
                gammaRMSg.SetPointError(i, f, f, d, d)

            FullJets_gausRMS.append(gausRMSg)
            FullJets_gammaRMS.append(gammaRMSg)
            FullJets_gausYield.append(gausYieldg)
            FullJets_gammaYield.append(gammaYieldg)
            FullJets_fit.append(fits)
            FullJets_parameters.append(parameters)

        if fileData is not None:
            FullJets_gausRMS.append(gGausRMSData)
            FullJets_gammaRMS.append(gGammaRMSData)
            FullJets_gausYield.append(gGausYieldData)
            FullJets_gammaYield.append(gGammaYieldData)

        fig, axs = plt.subplots(2, 1, figsize=(7, 7))
        ax = axs[0]
        ax.set_xlim([0.1, 15])
        ax.set_ylim([5e-6, 2e3])
        ax.set_xlabel(r'$j_{T}\left(GeV/c\right)$', fontsize=labelsize)
        ax.set_ylabel(r'$\frac{1}{N_{jets}}\frac{dN}{j_{T}dj_{T}}$',
                      fontsize=labelsize)
        ratios = []
        ax.set_xscale('log')
        ax.set_yscale('log')
        for h, c, R in zip(FullJets_jT, (0, 1, 2, 3), Rs):
            h[6].SetMarkerColor(colors[c])
            h[6].SetMarkerStyle(styles[c])
            h[6].SetLineColor(colors[c])
            ratio = h[6].Clone()
            ratio.Divide(FullJets_jT[1][6])
            ratios.append(ratio)
            plot = rplt.errorbar(h[6],
                                 xerr=False,
                                 emptybins=False,
                                 label='R = {:.1f}'.format(R),
                                 axes=ax,
                                 fmt='+')
            line = plot.get_children()[0]
            line.set_markersize(mSize)
            if (styles[c] > 23):
                line.set_markerfacecolor('none')
                #line.set_markeredgecolor(color)
                line.set_color(colors[c])

        ax.text(
            0.15,
            0.001,
            'Pythia \n Full Jets\n' + r'Anti-$k_T$' + '\n' +
            r'$p_{{T,\mathrm{{jet}}}}$: {:02d}-{:02d} GeV/c'.format(60, 80),
            fontsize=10)
        handles, labels = ax.get_legend_handles_labels()
        handles = [
            container.ErrorbarContainer(h, has_xerr=False, has_yerr=True)
            if isinstance(h, container.ErrorbarContainer) else h
            for h in handles
        ]
        ax.legend(handles,
                  labels,
                  loc='upper right',
                  numpoints=1,
                  prop={'family': 'monospace'})
        #ax.legend(loc = 'upper right')
        ax.set_xlim([0.1, 15])
        ax.set_ylim([5e-6, 2e3])
        ax.grid(True)

        ax = axs[1]
        ax.grid(True)
        ax.set_xlabel(r'$j_{T}\left[GeV\right]$', fontsize=labelsize)
        ax.set_ylabel('Ratio',
                      fontsize=labelsize)  #Add x-axis labels for bottom row
        for ratio, c in zip(ratios, (0, 1, 2, 3)):
            #ratio.SetMarkerColor(c)
            #ratio.SetMarkerStyle(24)
            plot = rplt.errorbar(ratio, xerr=False, emptybins=False, axes=ax)
            line = plot.get_children()[0]
            line.set_markersize(mSize)
            if (styles[c] > 23):
                line.set_markerfacecolor('none')
                #line.set_markeredgecolor(color)
                line.set_color(colors[c])
        ax.set_xlim([0.1, 15])
        ax.set_ylim([0.1, 3])
        ax.set_xscale('log')
        plt.tight_layout()
        plt.subplots_adjust(wspace=0,
                            hspace=0)  #Set space between subfigures to 0
        plt.savefig("PythonFigures/RcomparisonSignalPt6080.pdf".format(file),
                    format='pdf')  #Save figure

        plt.show()  #Draw figure on screen

        drawWithErrors2Combined(FullJets_gausRMS,
                                FullJets_gammaRMS,
                                15,
                                500,
                                1,
                                0,
                                1.65,
                                0,
                                r'jet $p_T (GeV/c)$',
                                r'$\sqrt{\left<j_T^2\right>}$',
                                'Pythia',
                                'PythonFigures/RcomparisonRMS',
                                separate=True)
        return
        drawWithErrors2Combined(
            FullJets_gausYield,
            FullJets_gammaYield,
            15,
            500,
            1,
            0,
            10,
            0,
            r'jet $p_T$',
            r'Yield',
            'Pythia',
            'PythonFigures/RcomparisonYield',
        )

        ratios = []
        for hists in FullJets_jT:
            if hists is not None:
                ratio = []
                for h, true in zip(hists, FullJets_jT[1]):
                    h2 = h.Clone()
                    h2.Divide(true)
                    ratio.append(h2)
            else:
                ratio = None
            ratios.append(ratio)

        fig, axs = defs.makegrid(4,
                                 2,
                                 xlog=True,
                                 ylog=False,
                                 d=d,
                                 shareY=False)
        axs = axs.reshape(8)
        axs[4].set_ylabel("Ratio to R = 0.4", fontsize=labelsize)
        axs[7].set_ylabel("Ratio to R = 0.4", fontsize=labelsize)

        axs[1].text(
            0.02,
            0.005, 'Pythia\n'
            r'pPb $\sqrt{s_{NN}} = 5.02 \mathrm{TeV}$'
            '\n Full jets \n'
            r'Anti-$k_T$',
            fontsize=7
        )  #Add text to second subfigure, first parameters are coordinates in the drawn scale/units
        for hists, R in zip(FullJets_jT, Rs):
            for jT, ax, i, pT in zip(hists[2:], axs[0:4], range(0, 9),
                                     jetPt[2:]):
                rplt.errorbar(jT,
                              emptybins=False,
                              xerr=False,
                              label="R = {:.1f}".format(R),
                              axes=ax,
                              fmt='o')  #Plot jT histogram,
                ax.text(
                    0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:'
                    '\n'
                    r' {:02d}-{:02d} GeV'.format(pT[0], pT[1]))
                ax.set_xlim([0.01, 20])  #Set x-axis limits
                ax.set_ylim([5e-4, 2e3])  #Set y-axis limits
                ax.set_yscale('log')
                ax.grid(True)

        for ratio in ratios:
            for r, ax in zip(ratio[2:], axs[4:8]):
                rplt.errorbar(r, axes=ax, emptybins=False, xerr=False)
                ax.set_xlim([0.01, 20])
                ax.set_ylim([0.1, 3])
                ax.grid(True)

        axs[0].legend(loc='lower left')

        plt.savefig("PythonFigures/RcomparisonSignal.pdf",
                    format='pdf')  #Save figure
        plt.show()  #Draw figure on screen
Ejemplo n.º 14
0
def main():
    print("Number of arguments: ", len(sys.argv), "arguments.")
    print("Argument list:", str(sys.argv))
    filename = sys.argv[1]
    if len(sys.argv) > 2:
        fileData = sys.argv[2]
    else:
        fileData = None
    print("Input file: ")
    print(filename)
    Njets = 9
    # FullJets_R04 = dataset("FullR04",NFIN=6,filename=filename,directory='AliJJetJtTask/AliJJetJtHistManager',color=2,style=24,rebin=5)
    # FullJets_R05 = dataset("FullR05",NFIN=7,filename=filename,directory='AliJJetJtTask/AliJJetJtHistManager',color=3,style=24,rebin=5)
    # FullJets_R03 = dataset("FullR06",NFIN=8,filename=filename,directory='AliJJetJtTask/AliJJetJtHistManager',color=4,style=24,rebin=5)

    if fileData is not None:
        fD = root_open(fileData, "read")
        iS = 0
        gGausRMSData = fD.Get("gGausRMS{:02d}".format(iS))
        gGausRMSerrData = fD.Get("gGausRMS{:02d}_Systematics".format(iS))
        gGausYieldData = fD.Get("gGausYield{:02d}".format(iS))
        gGausYielderrData = fD.Get("gGausYield{:02d}_Systematics".format(iS))
        gGammaRMSData = fD.Get("gGammaRMS{:02d}".format(iS))
        gGammaRMSerrData = fD.Get("gGammaRMS{:02d}_Systematics".format(iS))
        gGammaYieldData = fD.Get("gGammaYield{:02d}".format(iS))
        gGammaYielderrData = fD.Get("gGammaYield{:02d}_Systematics".format(iS))

    # errGraph = [fD.Get('JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Systematics'.format(iS,i)) for i in range(2,Njets)]  #Get jT histograms from file an array
    # hJtSignalGraph = [fD.Get('JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Statistics'.format(iS,i)) for i in range(2,Njets)]  #Get jT histograms from file an array

    with root_open(filename, "read") as fin:
        FullJets_jT = []
        FullJets_fit = []
        FullJets_parameters = []
        FullJets_gausRMS = []
        FullJets_gammaRMS = []
        FullJets_gausYield = []
        FullJets_gammaYield = []
        colors = (1, 2, 3)
        for iF in (6, 7, 8):
            # iF = 8
            c = 1
            jT = [
                fin.get(
                    "AliJJetJtTask/AliJJetJtHistManager/JetConeJtWeightBin/JetConeJtWeightBinNFin{:02d}JetPt{:02d}"
                    .format(iF, ij)) for ij in range(Njets)
            ]
            bgJt = [
                fin.get(
                    "AliJJetJtTask/AliJJetJtHistManager/BgJtWeightBin/BgJtWeightBinNFin{:02d}JetPt{:02d}"
                    .format(iF, ij)) for ij in range(Njets)
            ]
            jetPtBin = [
                fin.get(
                    "AliJJetJtTask/AliJJetJtHistManager/JetPtBin/JetPtBinNFin{:02d}JetPt{:02d}"
                    .format(iF, ij)) for ij in range(Njets)
            ]
            nJets = [h.Integral() for h in jetPtBin]
            nBgs = [
                fin.get(
                    "AliJJetJtTask/AliJJetJtHistManager/BgTrkNumberBin/BgTrkNumberBinNFin{:02d}JetPt{:02d}"
                    .format(iF, ij)).Integral() for ij in range(Njets)
            ]
            FullJets_jT.append(jT)
            for j, b, nj, nb in zip(jT, bgJt, nJets, nBgs):
                j.Rebin(4)
                b.Rebin(4)
                j.Scale(1.0 / nj, "width")
                b.Scale(1.0 / nb, "width")
                j.SetMarkerColor(c)
                b.SetMarkerColor(c)
                j.Add(b, -1.0)

        print(h.GetTitle())
        jetPt = [
            (
                int(
                    re.search(
                        r"p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*",
                        h.GetTitle(),
                        re.M | re.I,
                    ).group(1)),
                int(
                    re.search(
                        r"p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*",
                        h.GetTitle(),
                        re.M | re.I,
                    ).group(2)),
            ) for h in FullJets_jT[0]
        ]  # Use regular expressions to extract jet pT range from histogram titles
        jetPtCenter = array("d", [(a + b) / 2.0 for a, b in jetPt])
        jetPtErrors = array("d", [(b - a) / 2.0 for a, b in jetPt])
        print(jetPt, type(jetPt))
        print(jetPtCenter, type(jetPtCenter))
        print(jetPtErrors, type(jetPtErrors))

        for i, jT in enumerate(FullJets_jT):
            print(i)
            print(jT)
            gausRMS = []
            gammaRMS = []
            gausRMSe = []
            gammaRMSe = []
            gausYield = []
            gammaYield = []
            gausYielde = []
            gammaYielde = []
            fits = []
            parameters = []
            for h, i in zip(jT, range(Njets)):
                fit, d = fitJtHisto(h, "", 1, i, 8)
                fits.append(fit)
                parameters.append(d)
                gausRMS.append(d["gausRMS"])
                gausRMSe.append(d["gausRMSe"])
                gammaRMS.append(d["gammaRMS"])
                gammaRMSe.append(d["gammaRMSe"])
                gausYield.append(d["gausYield"])
                gausYielde.append(d["gausYielde"])
                gammaYield.append(d["gammaYield"])
                gammaYielde.append(d["gammaYielde"])

            gausRMSg = Graph(len(gausRMS) - 2)
            gammaRMSg = Graph(len(gammaRMS) - 2)
            gausYieldg = Graph(len(gausYield) - 2)
            gammaYieldg = Graph(len(gammaYield) - 2)
            for h, he, g in zip(
                (gausYield, gammaYield),
                (gausYielde, gammaYielde),
                (gausYieldg, gammaYieldg),
            ):
                for x, xe, a, e, i in zip(
                        jetPtCenter[2:],
                        jetPtErrors[2:],
                        h[2:],
                        he[2:],
                        range(len(gausRMS) - 2),
                ):
                    g.SetPoint(i, x, a)
                    g.SetPointError(i, xe, xe, e, e)

            for a, b, c, d, e, f, i in zip(
                    gausRMS[2:],
                    gammaRMS[2:],
                    gausRMSe[2:],
                    gammaRMSe[2:],
                    jetPtCenter[2:],
                    jetPtErrors[2:],
                    range(len(gausRMS) - 2),
            ):
                gausRMSg.SetPoint(i, e, a)
                gausRMSg.SetPointError(i, f, f, c, c)
                gammaRMSg.SetPoint(i, e, b)
                gammaRMSg.SetPointError(i, f, f, d, d)

            FullJets_gausRMS.append(gausRMSg)
            print(len(FullJets_gausRMS))
            FullJets_gammaRMS.append(gammaRMSg)
            FullJets_gausYield.append(gausYieldg)
            FullJets_gammaYield.append(gammaYieldg)
            FullJets_fit.append(fits)
            FullJets_parameters.append(parameters)

        if fileData is not None:

            FullJets_gausRMS.append(gGausRMSData)
            FullJets_gammaRMS.append(gGammaRMSData)
            FullJets_gausYield.append(gGausYieldData)
            FullJets_gammaYield.append(gGammaYieldData)

        print(len(FullJets_gausRMS))
        drawWithErrors2Combined(
            FullJets_gausRMS,
            FullJets_gammaRMS,
            15,
            500,
            1,
            0,
            1.65,
            0,
            r"$p_\mathrm{T,jet}$",
            r"$\sqrt{\left<j_\mathrm{T}^2\right>}$",
            "Pythia Truth",
            "PythonFigures/RcomparisonRMS",
        )
        drawWithErrors2Combined(
            FullJets_gausYield,
            FullJets_gammaYield,
            15,
            500,
            1,
            0,
            10,
            0,
            r"$p_\mathrm{T,jet}$",
            r"Yield",
            "Pythia Truth",
            "PythonFigures/RcomparisonYield",
        )

        ratios = []
        for hists in FullJets_jT:
            if hists is not None:
                ratio = []
                for h, true in zip(hists, FullJets_jT[1]):
                    h2 = h.Clone()
                    h2.Divide(true)
                    ratio.append(h2)
            else:
                ratio = None
            ratios.append(ratio)

        fig, axs = defs.makegrid(4,
                                 2,
                                 xlog=True,
                                 ylog=False,
                                 d=d,
                                 shareY=False)
        axs = axs.reshape(8)
        axs[4].set_ylabel("Ratio to R = 0.4")
        axs[7].set_ylabel("Ratio to R = 0.4")

        axs[1].text(
            0.02,
            0.005,
            "Pythia\n"
            r"pPb $\sqrt{s_{NN}} = 5.02 \mathrm{TeV}$"
            "\n Full jets \n"
            r"Anti-$k_\mathrm{T}$",
            fontsize=7,
        )  # Add text to second subfigure, first parameters are coordinates in the drawn scale/units
        for hists, R in zip(FullJets_jT, Rs):
            for jT, ax, i, pT in zip(hists[2:], axs[0:4], range(0, 9),
                                     jetPt[2:]):
                rplt.errorbar(
                    jT,
                    emptybins=False,
                    xerr=False,
                    label="R = {:.1f}".format(R),
                    axes=ax,
                    fmt="o",
                )  # Plot jT histogram,
                ax.text(
                    0.3,
                    1e2,
                    r"$p_\mathrm{T,jet}$:"
                    "\n"
                    r" {:02d}-{:02d} GeV".format(pT[0], pT[1]),
                )
                ax.set_xlim([0.01, 20])  # Set x-axis limits
                ax.set_ylim([5e-4, 2e3])  # Set y-axis limits
                ax.set_yscale("log")
                ax.grid(True)

        for ratio in ratios:
            for r, ax in zip(ratio[2:], axs[4:8]):
                rplt.errorbar(r, axes=ax, emptybins=False, xerr=False)
                ax.set_xlim([0.01, 20])
                ax.set_ylim([0.1, 3])
                ax.grid(True)

        axs[0].legend(loc="lower left")

        plt.savefig("PythonFigures/RcomparisonSignal.pdf",
                    format="pdf")  # Save figure
        plt.show()  # Draw figure on screen
Ejemplo n.º 15
0
def main(): 
  
  JetPtBins = [5,10,20,30,40,60,80,100,150,500]
  jetPt = [(JetPtBins[i],JetPtBins[i+1]) for i in range(8)]
  print(jetPt)
  #JetPtCenter = [7.5,15,25,35,50,70,90,125,325]
  JetPtCenter = [6.5,12.45,23.34,33.83,46.75,67.73,88.01,116.11,194.61]
  LeadPtMode = [2.0,3.0,5.6,8.9,9.9,14.8,20.7,26.0,34.6]
  LeadPtMean = [2.35,3.72,6.66,9.59,13.58,17.98,23.27,27.55,31.68]
  LeadPtError = [0.93,1.69,3.18,4.43,6.74,8.34,9.68,10.27,10.55]
  JetPtError = [2.5,5,5,5,10,10,10,25,175]
  JetPtLeadPtG = Graph(len(JetPtCenter)) #Gives jet pT as a function of leading pT
  JetPtLeadPtGerr = Graph(len(JetPtCenter))
  LeadPtJetPtG = Graph(len(JetPtCenter))
  LeadPtJetPtGerr = Graph(len(JetPtCenter))
  for i,(x,y,e) in enumerate(zip(LeadPtMean,JetPtCenter,JetPtError)):
    JetPtLeadPtG.SetPoint(i,x,y)
    JetPtLeadPtGerr.SetPoint(i,x,e)
  for i,(x,y,e) in enumerate(zip(JetPtCenter,LeadPtMean,LeadPtError)):
    LeadPtJetPtG.SetPoint(i,x,y)
    LeadPtJetPtGerr.SetPoint(i,x,e)
  
  Njets = 8
  

  
  
  topcomment = "_systematics_Triggered"
  
  finderName = ["Full jets, Anti-k_\mathrm{T} R = 0.4","Charged Jets, Anti-k_\mathrm{T} R = 0.4"]
  finderType = ["Full","Charged"]
  setTitle = ["0","1","2","3","4","5"]
  finderR = {4,4}
  
  iC = 0
  logx = 1
  doWeight = 1
  iS = 0

  f = root_open("errors_test.root", 'read')

  gGausRMS = f.Get("gGausRMS{:02d}".format(iS))
  gGausRMSerr = f.Get("gGausRMS{:02d}_Systematics".format(iS))
  gGausYield = f.Get("gGausYield{:02d}".format(iS))
  gGausYielderr = f.Get("gGausYield{:02d}_Systematics".format(iS))
  gGammaRMS = f.Get("gGammaRMS{:02d}".format(iS))
  gGammaRMSerr = f.Get("gGammaRMS{:02d}_Systematics".format(iS))
  gGammaYield = f.Get("gGammaYield{:02d}".format(iS))
  gGammaYielderr = f.Get("gGammaYield{:02d}_Systematics".format(iS))
  
  start = 4
  iS = 0
  stats = [None if ij < start else f.Get("JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Statistics".format(iS,ij)) for ij in range(8)]
  fits = [None if ij < start else f.Get("JetConeJtWeightBinNFin{:02d}JetPt{:02d}_FitFunction".format(iS,ij)) for ij in range(8)]
  print(fits)


  print(stats)

  n_figs = 2
  
  
  
#   if(n_figs == 2):
#     fig,axs = defs.makeRatio(xlog=True,ylog=True,d=d,shareY=False,figsize = (5,6),grid=False)
#   else:
#     fig, axs = defs.makegrid(n_figs/2,2,xlog=True,ylog=True,d=d,shareY=False,figsize= (10,7.5) if n_figs == 4 else (n_figs*15/8,7.5) )
#   axs = axs.reshape(n_figs)
#   if(n_figs == 2):
#     pT = jetPt[start]
#     print(pT)
#     axs[0].text(0.8,7,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n' + d['cut'] + '\n' + r'${:02d}\:\mathrm{{GeV}}/c < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c$'.format(pT[0],pT[1]),fontsize = 10)
#   else:
#     axs[1].text(0.12,0.002,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n' + d['cut'],fontsize = 11)
#   
  ratios = []
  xs2 = []

  for jT,pT,ij,fit in zip(stats[start:],jetPt[start:],range(start,9),fits[start:]):
    color = colors[1]
    fig,axs = defs.makeRatio(xlog=True,ylog=True,d=d,shareY=False,figsize = (5,6),grid=False)
    axs = axs.reshape(n_figs)
    axs[0].text(0.8,7,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n' + d['cut'] + '\n' + r'${:02d}\:\mathrm{{GeV}}/c < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c$'.format(pT[0],pT[1]),fontsize = 10)
    ax = axs[0]
    xs = np.arange(0,xhigh,0.01).tolist()
    for ii in range(6):
      print(fit.GetParameter(ii))
    #B2 is Gauss normalization
    #B3 is Gamma normalization
    gauss = fit.Clone()
    gauss.SetParameter(3,0)
    gamma = fit.Clone()
    gamma.SetParameter(0,0)
    ys = [fit.Eval(x) for x in xs]
    ys2 = [gauss.Eval(x) for x in xs]
    ys3 = [gamma.Eval(x) for x in xs]
    ax.plot(xs,ys2,'b:',label="Narrow")
    ax.plot(xs,ys3,'r--',label="Wide")
    ax.plot(xs,ys,'k',label="Total")

    jT.SetMarkerColor(color)
    jT.SetMarkerStyle(24)
    jT.SetLineColor(color)
    jT.SetMarkerSize(mSize)
    plot = rplt.errorbar(jT,xerr=False,emptybins=False,axes=ax,label="ALICE",fmt='o',fillstyle='none') #Plot jT histogram, 
    line = plot.get_children()[0]
    line.set_markersize(mSize)
    if(True):
      line.set_markerfacecolor('none')
      #line.set_markeredgecolor(color)
      line.set_color(color)
#     line.set_markerfacecolor('none')
#     line.set_markeredgecolor(colors[c])
#     line.set_markerfacecolor('none')
#     line.set_markeredgecolor('none')
#     line.set_drawstyle('default')
#     line.set_linestyle('dashed')  
#     line.set_color(colors[c])
    if(n_figs > 2):
      ax.text(0.5,1e2,r'${:02d}\:\mathrm{{GeV}} < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}$'.format(pT[0],pT[1])) 
    ax.set_xlim([xlow,xhigh]) #Set x-axis limits
    ax.set_ylim([1e-6,2e3]) #Set y-axis limits
    #ax.set_xticklabels(ax.get_xticklabels(),horizontalalignment='left')
    x_ = Double()
    y1 = Double()
    xe = Double()
    ye = Double()
    NC = jT.GetN()
    y2 = []
    y2e = []
    xs=[]
    ex = []
    for ii in range(NC):
      jT.GetPoint(ii,x_,y1)
      xe = jT.GetErrorX(ii)
      ye = jT.GetErrorY(ii)
      x1 = x_*1.0
      xs.append(x1)
      ex.append(xe)
      if(y1 > 0):
        y2.append(y1/fit.Eval(x1))
        y2e.append(ye/fit.Eval(x1))
      else:
        y2.append(0)
        y2e.append(0)
    #ratio = jT.Clone()
    ratio= Graph(NC)

    print(xs[::5])
    print(y2[::5])
    print(ex[::5])
    print(y2e[::5])
    for x0,y0,x0e,y0e,i in zip(xs,y2,ex,y2e,range(NC)):
      ratio.SetPoint(i,x0,y0)
      ratio.SetPointError(i,x0e,x0e,y0e,y0e)
    ratios.append(ratio)
    print(ratio)
    ax = axs[1]
  #for ratio,pT,ax,color in zip(ratios,jetPt[start:],axs[n_figs/2:n_figs+1],colors[1:]):
    
    print("Debug")
    ratio.SetMarkerColor(color)
    ratio.SetLineColor(color)
    ratio.SetMarkerStyle(24)
    ax.plot([0,20],[1,1],'k--')
    #ratio.SetMarkerSize(mSize)
    plot = rplt.errorbar(ratio,xerr=False,emptybins=False,axes=ax,label=r"Ratio",fmt='o',fillstyle='none') #Plot jT histogram, 
    line = plot.get_children()[0]
    line.set_markersize(mSize)
    if(True):
      line.set_markerfacecolor('none')
      #line.set_markeredgecolor(color)
      line.set_color(color)
    #ax.plot(xs2,ratio)
    ax.set_yscale('linear')
    ax.set_xlim([xlow,xhigh]) #Set x-axis limits
    ax.set_ylim([0,2.75]) #Set y-axis limits  
    ax.set_ylabel('Signal/Fit',fontsize=14) #Add y-axis labels to left- and righmost subfigures

    
    handles, labels = axs[0].get_legend_handles_labels()
    handles = [handles[3],handles[2],handles[0],handles[1]]
    labels = [labels[3],labels[2],labels[0],labels[1]]
  
    handles = [container.ErrorbarContainer(h,has_xerr=False,has_yerr=True) if isinstance(h, container.ErrorbarContainer) else h for h in handles]
    axs[0].legend(handles,labels,loc = 'lower left',numpoints=1)
  
    axs[0].text(0.11,3e2,"ALICE",weight='bold')
  
    fig.align_labels()
    print("Save PythonFigures/JtSignalFinalFitJetPt{}.pdf".format(ij))
    plt.savefig("PythonFigures/JtSignalFinalFitJetPt{}.pdf".format(ij),format='pdf') #Save figure
    plt.show() #Draw figure on screen
Ejemplo n.º 16
0
    h_truth = asrootpy(
        inputFile.unfoldingAnalyserElectronChannel.truth.Rebin(
            nbins, 'truth_new', bins))
    print 'old:', get_bin_centers(bins)
    new_centers = barycenters(h_truth_finebinned, h_truth)
    print 'centre of mass:', new_centers
    new_centers = calculate_correct_x_coordinates(h_truth_finebinned, bins)
    print 'correct:', new_centers
    data = list(h_truth.y())
    h_truth_new = Hist(new_centers)
    bin_widths = [25, 20, 25, 30, 1000]
    g_truth_new = Graph(len(new_centers))
    for i, (x, y, width) in enumerate(zip(new_centers, data, bin_widths)):
        g_truth_new.SetPoint(i, x, y / width)
        error = h_truth.GetBinError(i + 1)
        g_truth_new.SetPointError(i, 0, 0, error, error)

    for bin_i in range(len(data)):
        h_truth_new.SetBinContent(bin_i + 1, data[bin_i] / bin_widths[bin_i])
        h_truth.SetBinContent(bin_i + 1, data[bin_i] / bin_widths[bin_i])

    h_truth_finebinned.SetFillStyle(0)
    h_truth_finebinned.Smooth(500)
    x, y = list(h_truth_finebinned.x()), list(h_truth_finebinned.y())
    bin_edges = np.array(list(h_truth_finebinned.xedges()))
    bincenters = 0.5 * (bin_edges[1:] + bin_edges[:-1])
    g_truth = Graph(h_truth)
    #    g_truth_new = Graph(len(h_truth), h_truth_new)
    g_truth_new.SetLineColor('red')
    g_truth_new.SetMarkerColor('red')
    h_truth_finebinned.axis().SetRange(0, 1000)
Ejemplo n.º 17
0
def draw_curve_8(_func, name, title, ylow, yhigh, num_errs=1):
    """ Draw 8TeV trigger efficiency curves """
    graphs = []
    for (trigger, color) in triggers:
        tool = ROOT.TrigTauEfficiency()
        tool.loadInputFile(
            os.path.join(base, 'triggerSF_{0}.root'.format(trigger)))
        func = getattr(tool, _func)
        eff = np.array(
            map(lambda x: func(x, eta, 0, period, prong, wpflag, eveto), pt))
        errs_low = []
        errs_high = []
        for ierr in xrange(num_errs):
            eff_low = np.array(
                map(lambda x: func(x, eta, -1, period, prong, wpflag, eveto),
                    pt))
            eff_high = np.array(
                map(lambda x: func(x, eta, 1, period, prong, wpflag, eveto),
                    pt))
            errs_low.append(eff_low)
            errs_high.append(eff_high)
        # quadrature sum of error
        eff_low = np.sqrt(
            np.sum([np.power(err, 2) for err in errs_low], axis=0))
        eff_high = np.sqrt(
            np.sum([np.power(err, 2) for err in errs_high], axis=0))
        graph = Graph(len(pt), name=trigger)
        for i, (p, e, e_low,
                e_high) in enumerate(zip(pt, eff, eff_low, eff_high)):
            graph.SetPoint(i, p / 1000, e)
            graph.SetPointError(i, 0.4, 0.4, e_low, e_high)
        graph.linecolor = color
        graph.linewidth = 2
        graph.fillstyle = '/'
        graph.fillcolor = color
        graphs.append(graph)
    c = Canvas()
    leg = Legend(len(graphs),
                 pad=c,
                 topmargin=0.6,
                 leftmargin=0.3,
                 textsize=25,
                 margin=0.2)
    for i, g in enumerate(graphs):
        if i == 0:
            g.Draw('3AL')
            g.xaxis.title = '#font[52]{p}_{T} [GeV]'
            g.xaxis.SetLimits(20, 100)
            g.yaxis.SetLimits(ylow, yhigh)
            g.yaxis.SetRangeUser(ylow, yhigh)
            g.yaxis.title = title
        else:
            g.Draw('3L SAME')
        leg.AddEntry(g, g.name, 'L')
    leg.Draw()
    lines = []
    for thresh in (25, 35):
        line = Line(thresh, ylow, thresh, yhigh)
        line.linestyle = 'dashed'
        line.linewidth = 2
        line.Draw()
        lines.append(line)
    c.SaveAs('trigger_{0}.png'.format(name))
    c.SaveAs('trigger_{0}.eps'.format(name))
Ejemplo n.º 18
0
def main(): 
  print('Number of arguments: ', len(sys.argv), 'arguments.')
  print('Argument list:',str(sys.argv))
  filename = sys.argv[1]
  separate = int(sys.argv[2])
  if(len(sys.argv) > 3):
    start = int(sys.argv[3])
    end = int(sys.argv[4])
  else:
    start = 1
    end = 6
  n_figs = end-start
  print("Number of figs: {}".format(n_figs))
  print("Input file: ")
  print(filename)
  FullJets_R04 = dataset('Full jets R=0.4',NFIN=0,range=(start,end),filename=filename,directory='AliJJetJtTask/AliJJetJtHistManager',color=2,style=24,rebin=2)
  #Mixed_FullJets_R04 = datasetMixed("Full jets R=0.4",NFIN=0,range=5,filename=filename,directory='AliJJetJtTask/AliJJetJtHistManager',directory2='AliJJetJtTask_kEMCEJE/AliJJetJtHistManager',color=2,style=24,rebin=2)
  #signal,jetPt = FullJets_R04.getHist('JtWeightBin',jetpt = True)
  #signal2 = FullJets_R04.getHist('JtWeightLeadingRefBin',jetpt=False)
  compareHistsWithRatio(FullJets_R04,['JtWeightBin','JtWeightLeadingRefBin','JtWeightLeadingRefBin','JtWeightLeadingRefBin','JtWeightLeadingRefBin'],['Jet axis ref.','leading ref. (xlong 0.0-0.2)','leading ref. (xlong 0.2-0.4)','leading ref. (xlong 0.4-0.6)','leading ref. (xlong 0.6-1.0)'],step=1,extras=['','Xlong00','Xlong01','Xlong02','Xlong03'])
  plt.savefig("PythonFigures/JetVsLeadingRefConst.pdf",format='pdf') #Save figure
  plt.show()
  sets = compareHistsWithRatio(FullJets_R04,['JetConeJtWeightBin','JetConeJtWeightLeadingRefBin','JetConeJtWeightLeadingRefBin','JetConeJtWeightLeadingRefBin','JetConeJtWeightLeadingRefBin'],['Jet axis ref.','leading ref.(xlong 0.0-0.2)','leading ref.(xlong 0.2-0.4)','leading ref.(xlong 0.4-0.6)','leading ref. (xlong 0.6-1.0)'],step=1,extras=['','Xlong00','Xlong01','Xlong02','Xlong03'])
  plt.savefig("PythonFigures/JetVsLeadingRefJetCone.pdf",format='pdf') #Save figure
  plt.show()
  
  JtJet = sets[0][0]
  JtLeadingxlong00 = sets[1][0]
  JtLeadingxlong01 = sets[2][0]
  JtLeadingxlong02 = sets[3][0]
  JtLeadingxlong03 = sets[4][0]
  JtLeading = [h.clone() for h in sets[1][0]]
  for h,s,s2,s3 in zip(JtLeading,sets[2][0],sets[3][0],sets[4][0]):
    h.Add(s,1)
    h.Add(s2,1)
    h.Add(s3,1)
#   print(JtLeading)
#   for set in sets[2:]:
#     for h,s in zip(JtLeading,set[0]):
#       print(s)
#       h.Add(s,1)
  jetPt = sets[0][1]
  jetPtCenter = array('d',[(a+b)/2.0 for a,b in jetPt])
  jetPtErrors = array('d',[(b-a)/2.0 for a,b in jetPt])
  
  FullJets_fit = []
  FullJets_parameters = []
  FullJets_gausRMS = []
  FullJets_gammaRMS = []
  FullJets_gausYield = []
  FullJets_gammaYield = []
  for jT,title in zip((JtJet,JtLeading,JtLeadingxlong00,JtLeadingxlong01,JtLeadingxlong02),("Jet ref.","Leading ref","Leading ref.(xlong 0.0-0.2)","Leading ref.(xlong 0.2-0.4)","Leading ref.(xlong 0.4-0.6)","Leading ref.(xlong 0.6-1.0)")):
    gausRMS = []
    gammaRMS = []
    gausRMSe = []
    gammaRMSe = []
    gausYield = []
    gammaYield = []
    gausYielde = []
    gammaYielde = []
    fits = []
    parameters = []
    for h,i in zip(jT,range(Njets)):
      fit,d = defs.fitJtHisto(h,'',1,i,8,title,draw=False)
      fits.append(fit)
      parameters.append(d)
      gausRMS.append(d['gausRMS'])
      gausRMSe.append(d['gausRMSe'])
      gammaRMS.append(d['gammaRMS'])
      gammaRMSe.append(d['gammaRMSe'])
      gausYield.append(d['gausYield'])
      gausYielde.append(d['gausYielde'])
      gammaYield.append(d['gammaYield'])
      gammaYielde.append(d['gammaYielde'])
      
    gausRMSg = Graph(len(gausRMS)-2)
    gammaRMSg = Graph(len(gammaRMS)-2)
    gausYieldg = Graph(len(gausYield) -2)
    gammaYieldg = Graph(len(gammaYield)-2)
    for h,he,g in zip((gausYield,gammaYield),(gausYielde,gammaYielde),(gausYieldg,gammaYieldg)):
      for x,xe,a,e,i in zip(jetPtCenter[2:],jetPtErrors[2:],h[2:],he[2:],range(len(gausRMS)-2)):
        g.SetPoint(i,x,a)
        g.SetPointError(i,xe,xe,e,e)
    
    for a,b,c,d,e,f,i in zip(gausRMS[2:],gammaRMS[2:],gausRMSe[2:],gammaRMSe[2:],jetPtCenter[2:],jetPtErrors[2:],range(len(gausRMS)-2)):
      gausRMSg.SetPoint(i,e,a)
      gausRMSg.SetPointError(i,f,f,c,c)
      gammaRMSg.SetPoint(i,e,b)
      gammaRMSg.SetPointError(i,f,f,d,d)
    
    
    FullJets_gausRMS.append(gausRMSg)
    FullJets_gammaRMS.append(gammaRMSg)
    FullJets_gausYield.append(gausYieldg)
    FullJets_gammaYield.append(gammaYieldg)
    FullJets_fit.append(fits)
    FullJets_parameters.append(parameters)
  
  print(gausRMS[2:])
  print(gammaRMS[2:])
  print(jetPtCenter[2:])
  
  drawWithErrors2Combined(FullJets_gausRMS,FullJets_gammaRMS,["Jet ref.","Leading ref.","Leading ref.(xlong 0.0-0.2)","Leading ref.(xlong 0.2-0.4)","Leading ref.(xlong 0.4-0.6)"],15,500,1,0,1.85,0,r'jet $p_T$',r'$\sqrt{\left<j_T^2\right>}$','Pythia','PythonFigures/JetVsLeadingRefJetConeFits')
  return

  if(separate > 0):
    fig = plt.figure(1)
    ax = fig.add_subplot(1,1,1)
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.text(0.2,0.0005,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n Jet Cone',fontsize = 7)
    rplt.errorbar(signal[separate],xerr=False,emptybins=False,axes=ax,label="Jet axis reference",fmt='o') #Plot jT histogram, 
    rplt.errorbar(signal2[separate],xerr=False,emptybins=False,axes=ax,label="Leading track reference",fmt='o')
    ax.text(0.3,1e2,r'$p_{{T,\mathrm{{jet}}}}$:''\n'r' {:02d}-{:02d} GeV'.format(jetPt[separate][0],jetPt[separate][1])) 
    ax.set_xlim([0.1,12])
    ax.set_ylim([5e-6,1.5e3])
    ax.legend(loc = 'lower left')
    
    plt.savefig("PythonFigures/MixedFullJetsR04JetConeJtLeadingRefJetPt{0}.pdf".format(separate),format='pdf') #Save figure
    plt.show() #Draw figure on screen

  else:
    n_rows = n_figs//4
    print(n_rows)
    fig, axs = defs.makegrid(4,n_figs//4,xlog=True,ylog=True,d=d,shareY=True,figsize=(10,5))
    axs = axs.reshape(n_figs)
    axs[1].text(0.12,0.002,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n Jet Cone',fontsize = 7)
    for jT,jT2,pT,ax,i in zip(signal[start:],signal2[start:],jetPt[start:],axs,range(0,9)):
      jT.SetMarkerColor(1)
      jT2.SetMarkerColor(2)
      plot = rplt.errorbar(jT,xerr=False,emptybins=False,axes=ax,label="Jet axis reference",fmt='o',fillstyle='none',ecolor='black') #Plot jT histogram, 
      plot = rplt.errorbar(jT2,xerr=False,emptybins=False,axes=ax,label="Leading track reference",fmt='o',fillstyle='none',ecolor='red') #Plot jT histogram, 
      ax.text(0.3,1e2,r'$p_{{T,\mathrm{{jet}}}}$:''\n'r' {:02d}-{:02d} GeV'.format(pT[0],pT[1])) 
  
      ax.set_xlim([0.1,22]) #Set x-axis limits
      ax.set_ylim([5e-4,2e3]) #Set y-axis limits
      ax.set_xticklabels(ax.get_xticklabels(),horizontalalignment='left')
     
    axs[0].legend(loc = 'lower left')
        
    plt.savefig("PythonFigures/MixedFullJetsR04JetConeJtLeadingRefPtFrom{}To{}.pdf".format(start,end),format='pdf') #Save figure
    plt.show() #Draw figure on screen
Ejemplo n.º 19
0
def main():

    JetPtBins = [5, 10, 20, 30, 40, 60, 80, 100, 150, 500]
    jetPt = [(JetPtBins[i], JetPtBins[i + 1]) for i in range(8)]
    print(jetPt)
    #JetPtCenter = [7.5,15,25,35,50,70,90,125,325]
    JetPtCenter = [
        6.5, 12.45, 23.34, 33.83, 46.75, 67.73, 88.01, 116.11, 194.61
    ]
    LeadPtMode = [2.0, 3.0, 5.6, 8.9, 9.9, 14.8, 20.7, 26.0, 34.6]
    LeadPtMean = [2.35, 3.72, 6.66, 9.59, 13.58, 17.98, 23.27, 27.55, 31.68]
    LeadPtError = [0.93, 1.69, 3.18, 4.43, 6.74, 8.34, 9.68, 10.27, 10.55]
    JetPtError = [2.5, 5, 5, 5, 10, 10, 10, 25, 175]
    JetPtLeadPtG = Graph(
        len(JetPtCenter))  #Gives jet pT as a function of leading pT
    JetPtLeadPtGerr = Graph(len(JetPtCenter))
    LeadPtJetPtG = Graph(len(JetPtCenter))
    LeadPtJetPtGerr = Graph(len(JetPtCenter))
    for i, (x, y, e) in enumerate(zip(LeadPtMean, JetPtCenter, JetPtError)):
        JetPtLeadPtG.SetPoint(i, x, y)
        JetPtLeadPtGerr.SetPoint(i, x, e)
    for i, (x, y, e) in enumerate(zip(JetPtCenter, LeadPtMean, LeadPtError)):
        LeadPtJetPtG.SetPoint(i, x, y)
        LeadPtJetPtGerr.SetPoint(i, x, e)

    Njets = 8

    topcomment = "_systematics_Triggered"

    finderName = [
        "Full jets, Anti-k_\mathrm{T} R = 0.4",
        "Charged Jets, Anti-k_\mathrm{T} R = 0.4"
    ]
    finderType = ["Full", "Charged"]
    setTitle = ["0", "1", "2", "3", "4", "5"]
    finderR = {4, 4}

    iC = 0
    logx = 1
    doWeight = 1
    iS = 0
    start = 5
    iS = 0

    if (os.path.exists('RootFiles/Fig2.root')):
        inFile = "RootFiles/Fig2.root"
        inF = root_open(inFile, 'r')
        stats = [
            None
            if ij < start else inF.Get("jTSignalJetPt_Stat{:02d}".format(ij))
            for ij in range(8)
        ]
        fits = [
            None
            if ij < start else inF.Get("jTSignalJetPt_fit{:02d}".format(ij))
            for ij in range(8)
        ]
        errGraph = [
            None
            if ij < start else inF.Get("jTSignalJetPt_syst{:02d}".format(ij))
            for ij in range(8)
        ]

    else:
        f = root_open("RootFiles/jtSystematics.root", 'read')

        stats = [
            None if ij < start else f.Get(
                "JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Statistics".format(
                    iS, ij)) for ij in range(8)
        ]
        fits = [
            None if ij < start else f.Get(
                "JetConeJtWeightBinNFin{:02d}JetPt{:02d}_FitFunction".format(
                    iS, ij)) for ij in range(8)
        ]
        errGraph = [
            None if ij < start else f.Get(
                'JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Systematics'.format(
                    iS, ij)) for ij in range(8)
        ]  #Get jT histograms from file an array

        outFile = "RootFiles/Fig2.root"
        outF = root_open(outFile, "w+")
        for s, f, e, i in zip(stats, fits, errGraph, range(10)):
            if (s):
                s.SetName("jTSignalJetPt_Stat{:02d}".format(i))
                s.Write()
                f.SetName("jTSignalJetPt_fit{:02d}".format(i))
                f.Write()
                e.SetName("jTSignalJetPt_syst{:02d}".format(i))
                e.Write()
        outF.Close()

    n_figs = 2

    ratios = []
    xs2 = []

    for jT, pT, ij, fit, jT_sys in zip(stats[start:], jetPt[start:],
                                       range(start, 9), fits[start:],
                                       errGraph[start:]):
        color = colors[1]
        fig, axs = defs.makeRatio(xlog=True,
                                  ylog=True,
                                  d=d,
                                  shareY=False,
                                  figsize=(5, 6),
                                  grid=False)
        axs = axs.reshape(n_figs)
        axs[0].text(
            0.6,
            40,
            d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] + '\n' +
            d['cut'] + '\n' +
            r'${:02d}\: < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c$'.
            format(pT[0], pT[1]),
            fontsize=10)
        ax = axs[0]
        xs = np.arange(0, xhigh, 0.01).tolist()
        for ii in range(6):
            print(fit.GetParameter(ii))

        gauss = fit.Clone()
        gauss.SetParameter(3, 0)
        gamma = fit.Clone()
        gamma.SetParameter(0, 0)
        ys = [fit.Eval(x) for x in xs]
        ys2 = [gauss.Eval(x) for x in xs]
        ys3 = [gamma.Eval(x) for x in xs]
        ax.plot(xs, ys2, 'b:', label="Narrow")
        ax.plot(xs, ys3, 'r--', label="Wide")
        ax.plot(xs, ys, 'k', label="Total")

        jT.SetMarkerColor(color)
        jT.SetMarkerStyle(24)
        jT.SetLineColor(color)
        jT.SetMarkerSize(mSize)
        plot = rplt.errorbar(jT,
                             xerr=False,
                             emptybins=False,
                             axes=ax,
                             label="ALICE",
                             fmt='o',
                             fillstyle='none')  #Plot jT histogram,
        line = plot.get_children()[0]
        line.set_markersize(mSize)
        line.set_markerfacecolor('none')
        line.set_color(color)

        errorboxes = []
        ratioBoxes = []

        n = jT_sys.GetN()
        xs = jT_sys.GetX()
        ys = jT_sys.GetY()
        xerrs = jT_sys.GetEX()
        yerrs = jT_sys.GetEY()
        for x in (xs, ys, xerrs, yerrs):
            x.SetSize(n)
        for x, y, xe, ye in zip(xs, ys, xerrs, yerrs):
            rect = Rectangle((x - xe, (y - ye)), xe * 2, ye * 2)
            errorboxes.append(rect)
            rect2 = Rectangle((x - xe, (y - ye) / fit.Eval(x)), xe * 2,
                              ye / fit.Eval(x) * 2)
            ratioBoxes.append(rect2)
        pc = PatchCollection(errorboxes,
                             facecolor='r',
                             alpha=0.5,
                             edgecolor='None')
        ax.add_collection(pc)

        if (n_figs > 2):
            ax.text(
                0.5, 1e2,
                r'${:02d}\:\mathrm{{GeV}} < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}$'
                .format(pT[0], pT[1]))
        ax.set_xlim([xlow, xhigh])  #Set x-axis limits
        ax.set_ylim([1e-3, 5e3])  #Set y-axis limits
        x_ = Double()
        y1 = Double()
        xe = Double()
        ye = Double()
        NC = jT.GetN()
        y2 = []
        y2e = []
        xs = []
        ex = []

        for ii in range(NC):
            jT.GetPoint(ii, x_, y1)
            xe = jT.GetErrorX(ii)
            ye = jT.GetErrorY(ii)
            x1 = x_ * 1.0
            xs.append(x1)
            ex.append(xe)
            if (y1 > 0):
                y2.append(y1 / fit.Eval(x1))
                y2e.append(ye / fit.Eval(x1))
            else:
                y2.append(0)
                y2e.append(0)
        #ratio = jT.Clone()
        ratio = Graph(NC)
        """
           ratioBoxes = []
        N = div.GetNbinsX()
        for box,i in zip(syst,range(1,N)):
          y = div.GetBinContent(i)
          x1,x2,y1,y2,yc,error,ratio,ratioerror = box
          rect = Rectangle((x1,ratio-ratioerror),x2-x1,ratioerror*2)
          ratioBoxes.append(rect)
        
        pc = PatchCollection(ratioBoxes, facecolor=colorsBox[j], alpha=0.5,edgecolor=colorsBox[j])
        ax.add_collection(pc)
    
    """

        print(xs[::5])
        print(y2[::5])
        print(ex[::5])
        print(y2e[::5])
        for x0, y0, x0e, y0e, i in zip(xs, y2, ex, y2e, range(NC)):
            ratio.SetPoint(i, x0, y0)
            ratio.SetPointError(i, x0e, x0e, y0e, y0e)
        ratios.append(ratio)
        print(ratio)
        ax = axs[1]
        pc2 = PatchCollection(ratioBoxes,
                              facecolor='r',
                              alpha=0.5,
                              edgecolor='None')
        ax.add_collection(pc2)
        #for ratio,pT,ax,color in zip(ratios,jetPt[start:],axs[n_figs/2:n_figs+1],colors[1:]):

        ratio.SetMarkerColor(color)
        ratio.SetLineColor(color)
        ratio.SetMarkerStyle(24)
        ax.plot([0, 20], [1, 1], 'k--')
        #ratio.SetMarkerSize(mSize)
        plot = rplt.errorbar(ratio,
                             xerr=False,
                             emptybins=False,
                             axes=ax,
                             label=r"Ratio",
                             fmt='o',
                             fillstyle='none')  #Plot jT histogram,
        line = plot.get_children()[0]
        line.set_markersize(mSize)
        if (True):
            line.set_markerfacecolor('none')
            #line.set_markeredgecolor(color)
            line.set_color(color)
        #ax.plot(xs2,ratio)
        ax.set_yscale('linear')
        ax.set_xlim([xlow, xhigh])  #Set x-axis limits
        ax.set_ylim([0, 2.75])  #Set y-axis limits
        ax.set_ylabel(
            'Signal/Fit',
            fontsize=14)  #Add y-axis labels to left- and righmost subfigures

        handles, labels = axs[0].get_legend_handles_labels()
        handles = [handles[3], handles[2], handles[0], handles[1]]
        labels = [labels[3], labels[2], labels[0], labels[1]]

        handles = [
            container.ErrorbarContainer(h, has_xerr=False, has_yerr=True)
            if isinstance(h, container.ErrorbarContainer) else h
            for h in handles
        ]
        axs[0].legend(handles, labels, loc='lower left', numpoints=1)

        #axs[0].text(0.11,1e3,"ALICE",weight='bold')
        axs[0].text(0.12, 7e2, "ALICE", fontsize=20)

        fig.align_labels()
        print("Save PythonFigures/JtSignalFinalFitJetPt{}.pdf".format(ij))
        plt.savefig("PythonFigures/JtSignalFinalFitJetPt{}.pdf".format(ij),
                    format='pdf')  #Save figure
        plt.show()  #Draw figure on screen
Ejemplo n.º 20
0
def main():
    print('Number of arguments: ', len(sys.argv), 'arguments.')
    print('Argument list:', str(sys.argv))
    filename = "rootFiles/legotrain_CF_pPb_2305_20190109_LHC13bcde_minimal.root"
    separate = 0
    start = 2
    end = 6
    n_figs = end - start

    Mixed_FullJets_R04 = datasetMixed(
        "Full jets R=0.4",
        NFIN=0,
        range=(1, 5),
        filename=filename,
        directory='AliJJetJtTask/AliJJetJtHistManager',
        directory2='AliJJetJtTask_kEMCEJE/AliJJetJtHistManager',
        color=2,
        style=24,
        rebin=2)
    compareHistsWithRatio(
        Mixed_FullJets_R04,
        ['JtWeightBin', 'JtWeightLeadingRefBin', 'JtWeightLeadingRefBin'], [
            'Jet axis ref.', 'leading ref. (xlong 0.0-0.2)',
            'leading ref. (xlong 0.2-0.4)'
        ],
        step=1,
        start=1,
        extras=['', 'Xlong00', 'Xlong01'])
    plt.savefig("PythonFigures/JetVsLeadingRefConst.pdf",
                format='pdf')  #Save figure
    plt.show()
    sets = compareHistsWithRatio(
        Mixed_FullJets_R04, [
            'JetConeJtWeightBin', 'JetConeJtWeightLeadingRefBin',
            'JetConeJtWeightLeadingRefBin', 'JetConeJtWeightLeadingRefBin',
            'JetConeJtWeightLeadingRefBin'
        ], [
            'Jet axis ref.', 'leading ref.(xlong 0.0-0.2)',
            'leading ref.(xlong 0.2-0.4)', 'leading ref.(xlong 0.4-0.6)',
            'leading ref. (xlong 0.6-1.0)'
        ],
        step=1,
        extras=['', 'Xlong00', 'Xlong01', 'Xlong02', 'Xlong03'])

    plt.savefig("PythonFigures/JetVsLeadingRefJetCone.pdf",
                format='pdf')  #Save figure
    plt.show()

    JtJet = sets[0][0]
    JtLeadingxlong00 = sets[1][0]
    JtLeadingxlong01 = sets[2][0]
    JtLeadingxlong02 = sets[3][0]
    JtLeadingxlong03 = sets[4][0]
    JtLeading = [h.clone() for h in sets[1][0]]
    for h, s, s2, s3 in zip(JtLeading, sets[2][0], sets[3][0], sets[4][0]):
        h.Add(s, 1)
        h.Add(s2, 1)
        h.Add(s3, 1)

    jetPt = sets[0][1]
    jetPtCenter = array('d', [(a + b) / 2.0 for a, b in jetPt])
    jetPtErrors = array('d', [(b - a) / 2.0 for a, b in jetPt])

    FullJets_fit = []
    FullJets_parameters = []
    FullJets_gausRMS = []
    FullJets_gammaRMS = []
    FullJets_gausYield = []
    FullJets_gammaYield = []
    for jT, title in zip(
        (JtJet, JtLeading, JtLeadingxlong00, JtLeadingxlong01,
         JtLeadingxlong02),
        ("Jet ref.", "Leading ref", "Leading ref.(xlong 0.0-0.2)",
         "Leading ref.(xlong 0.2-0.4)", "Leading ref.(xlong 0.4-0.6)",
         "Leading ref.(xlong 0.6-1.0)")):
        gausRMS = []
        gammaRMS = []
        gausRMSe = []
        gammaRMSe = []
        gausYield = []
        gammaYield = []
        gausYielde = []
        gammaYielde = []
        fits = []
        parameters = []
        for h, i in zip(jT, range(Njets)):
            fit, d = defs.fitJtHisto(h, '', 1, i, 8, title, draw=False)
            fits.append(fit)
            parameters.append(d)
            gausRMS.append(d['gausRMS'])
            gausRMSe.append(d['gausRMSe'])
            gammaRMS.append(d['gammaRMS'])
            gammaRMSe.append(d['gammaRMSe'])
            gausYield.append(d['gausYield'])
            gausYielde.append(d['gausYielde'])
            gammaYield.append(d['gammaYield'])
            gammaYielde.append(d['gammaYielde'])

        gausRMSg = Graph(len(gausRMS) - 2)
        gammaRMSg = Graph(len(gammaRMS) - 2)
        gausYieldg = Graph(len(gausYield) - 2)
        gammaYieldg = Graph(len(gammaYield) - 2)
        for h, he, g in zip((gausYield, gammaYield), (gausYielde, gammaYielde),
                            (gausYieldg, gammaYieldg)):
            for x, xe, a, e, i in zip(jetPtCenter[2:], jetPtErrors[2:], h[2:],
                                      he[2:], range(len(gausRMS) - 2)):
                g.SetPoint(i, x, a)
                g.SetPointError(i, xe, xe, e, e)

        for a, b, c, d, e, f, i in zip(gausRMS[2:], gammaRMS[2:], gausRMSe[2:],
                                       gammaRMSe[2:],
                                       jetPtCenter[2:], jetPtErrors[2:],
                                       range(len(gausRMS) - 2)):
            gausRMSg.SetPoint(i, e, a)
            gausRMSg.SetPointError(i, f, f, c, c)
            gammaRMSg.SetPoint(i, e, b)
            gammaRMSg.SetPointError(i, f, f, d, d)

        FullJets_gausRMS.append(gausRMSg)
        FullJets_gammaRMS.append(gammaRMSg)
        FullJets_gausYield.append(gausYieldg)
        FullJets_gammaYield.append(gammaYieldg)
        FullJets_fit.append(fits)
        FullJets_parameters.append(parameters)

    print(gausRMS[2:])
    print(gammaRMS[2:])
    print(jetPtCenter[2:])

    drawWithErrors2Combined(FullJets_gausRMS, FullJets_gammaRMS, [
        "Jet ref.", "Leading ref.", "Leading ref.(xlong 0.0-0.2)",
        "Leading ref.(xlong 0.2-0.4)", "Leading ref.(xlong 0.4-0.6)"
    ], 15, 500, 1, 0, 1.85, 0, r'jet $p_T$', r'$\sqrt{\left<j_T^2\right>}$',
                            'Pythia',
                            'PythonFigures/JetVsLeadingRefJetConeFits')

    if (separate > 0):
        fig = plt.figure(1)
        ax = fig.add_subplot(1, 1, 1)
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.text(0.2,
                0.0005,
                d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                '\n Jet Cone',
                fontsize=7)
        rplt.errorbar(signal[separate],
                      xerr=False,
                      emptybins=False,
                      axes=ax,
                      label="Jet axis reference",
                      fmt='o')  #Plot jT histogram,
        rplt.errorbar(signal2[separate],
                      xerr=False,
                      emptybins=False,
                      axes=ax,
                      label="Leading track reference",
                      fmt='o')
        ax.text(
            0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:'
            '\n'
            r' {:02d}-{:02d} GeV'.format(jetPt[separate][0],
                                         jetPt[separate][1]))
        ax.set_xlim([0.1, 12])
        ax.set_ylim([5e-6, 1.5e3])
        ax.legend(loc='lower left')

        plt.savefig(
            "PythonFigures/MixedFullJetsR04JetConeJtLeadingRefJetPt{0}.pdf".
            format(separate),
            format='pdf')  #Save figure
        plt.show()  #Draw figure on screen

    else:
        n_rows = n_figs // 4
        print(n_rows)
        fig, axs = defs.makegrid(4,
                                 2,
                                 xlog=True,
                                 ylog=True,
                                 d=d,
                                 shareY=False,
                                 figsize=(10, 5))
        axs = axs.reshape(8)
        #axs[1].text(0.12,0.002,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n Jet Cone',fontsize = 7)
        ratios = []
        for jT, jT2, pT, ax, i in zip(JtJet[start:], JtLeading[start:],
                                      jetPt[start:], axs[0:4], range(0, 9)):
            jT.SetMarkerColor(1)
            jT.SetMarkerStyle(24)
            jT.SetLineColor(1)
            #jT.SetMarkerSize(mSize)
            jT2.SetMarkerColor(2)
            jT2.SetMarkerStyle(25)
            #jT2.SetMarkerSize(mSize)
            jT2.SetLineColor(2)
            ratio = jT2.Clone()
            ratio.Divide(jT)
            ratios.append(ratio)
            plot = rplt.errorbar(jT,
                                 xerr=False,
                                 emptybins=False,
                                 axes=ax,
                                 label="Jet axis reference",
                                 fmt='o',
                                 fillstyle='none',
                                 ecolor='black')  #Plot jT histogram,
            line = plot.get_children()[0]
            line.set_markersize(mSize)
            line.set_markerfacecolor('none')

            plot = rplt.errorbar(jT2,
                                 xerr=False,
                                 emptybins=False,
                                 axes=ax,
                                 label="Leading track reference",
                                 fmt='o',
                                 fillstyle='none',
                                 ecolor='red')  #Plot jT histogram,
            line = plot.get_children()[0]
            line.set_markersize(mSize)
            line.set_markerfacecolor('none')
            #line.set_color(color)

            ax.text(
                0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:'
                '\n'
                r' {:02d}-{:02d} GeV'.format(pT[0], pT[1]))

            ax.set_xlim([0.1, 22])  #Set x-axis limits
            ax.set_ylim([5e-5, 2e3])  #Set y-axis limits
            ax.set_xticklabels(ax.get_xticklabels(),
                               horizontalalignment='left')

        for ratio, ax, i in zip(ratios, axs[4:], range(0, 9)):
            plot = rplt.errorbar(ratio,
                                 xerr=False,
                                 emptybins=False,
                                 axes=ax,
                                 fmt='o',
                                 fillstyle='none',
                                 ecolor='black')  #Plot jT histogram,
            line = plot.get_children()[0]
            line.set_markersize(mSize)
            line.set_markerfacecolor('none')
            ax.set_yscale('linear')
            ax.set_xlim([0.1, 22])  #Set x-axis limits
            ax.set_ylim([0, 5])  #Set y-axis limits

        handles, labels = axs[0].get_legend_handles_labels()
        handles = [
            container.ErrorbarContainer(h, has_xerr=False, has_yerr=True)
            if isinstance(h, container.ErrorbarContainer) else h
            for h in handles
        ]
        axs[0].legend(handles, labels, loc='lower left', numpoints=1)
        axs[4].set_ylabel('Ratio')
        axs[7].set_ylabel('Ratio')

        plt.savefig(
            "PythonFigures/MixedFullJetsR04JetConeJtLeadingRefPtFrom{}To{}.pdf"
            .format(start, end),
            format='pdf')  #Save figure
        plt.show()  #Draw figure on screen
Ejemplo n.º 21
0
def main():

    Njets = 9

    if (os.path.exists('RootFiles/Fig6.root')):
        inFile = "RootFiles/Fig6.root"
        inF = root_open(inFile, 'r')
        FullJets_gausRMS = [
            inF.Get("FullJets_gausRMS_R{:02d}".format(int(R * 10))) for R in Rs
        ]
        FullJets_gammaRMS = [
            inF.Get("FullJets_gammaRMS_R{:02d}".format(int(R * 10)))
            for R in Rs
        ]
        FullJets_jT = []
        for R in Rs:
            h = [
                inF.Get("jTSignalJetPt{:02d}_R{:02d}".format(ij, int(R * 10)))
                for ij in range(8)
            ]
            FullJets_jT.append(h)
        jetPt = [
            (int(
                re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                          h.GetTitle(), re.M | re.I).group(1)),
             int(
                 re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                           h.GetTitle(), re.M | re.I).group(2)))
            for h in FullJets_jT[0]
        ]  #Use regular expressions to extract jet pT range from histogram titles
        jetPtCenter = array('d', [(a + b) / 2.0 for a, b in jetPt])
        jetPtErrors = array('d', [(b - a) / 2.0 for a, b in jetPt])
    else:
        filename = "CF_pPb_MC_legotrain/legotrain_610_20181010-1926_LHCb4_fix_CF_pPb_MC_ptHardMerged.root"
        f = root_open(filename, 'read')
        FullJets_jT = []
        for iF, c in zip((8, 6, 7), colors):
            jT = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/JetConeJtWeightBin/JetConeJtWeightBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)) for ij in range(Njets)
            ]
            bgJt = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/BgJtWeightBin/BgJtWeightBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)) for ij in range(Njets)
            ]
            jetPtBin = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/JetPtBin/JetPtBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)) for ij in range(Njets)
            ]
            nJets = [h.Integral() for h in jetPtBin]
            nBgs = [
                f.get(
                    'AliJJetJtTask/AliJJetJtHistManager/BgTrkNumberBin/BgTrkNumberBinNFin{:02d}JetPt{:02d}'
                    .format(iF, ij)).Integral() for ij in range(Njets)
            ]
            FullJets_jT.append(jT)
            #FullJets_bgJt.append(bgJt)
            #FullJets_jetPtBin.append(jetPtBin)
            for j, b, nj, nb in zip(jT, bgJt, nJets, nBgs):
                j.Rebin(2)
                b.Rebin(2)
                j.Scale(1.0 / nj, "width")
                b.Scale(1.0 / nb, "width")
                j.SetMarkerColor(c)
                b.SetMarkerColor(c)
                j.Add(b, -1.0)

        jetPt = [
            (int(
                re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                          h.GetTitle(), re.M | re.I).group(1)),
             int(
                 re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                           h.GetTitle(), re.M | re.I).group(2)))
            for h in FullJets_jT[0]
        ]  #Use regular expressions to extract jet pT range from histogram titles
        jetPtCenter = array('d', [(a + b) / 2.0 for a, b in jetPt])
        jetPtErrors = array('d', [(b - a) / 2.0 for a, b in jetPt])

        FullJets_fit = []
        FullJets_parameters = []
        FullJets_gausRMS = []
        FullJets_gammaRMS = []
        FullJets_gausYield = []
        FullJets_gammaYield = []
        for jT in FullJets_jT:
            gausRMS = []
            gammaRMS = []
            gausRMSe = []
            gammaRMSe = []
            gausYield = []
            gammaYield = []
            gausYielde = []
            gammaYielde = []
            fits = []
            parameters = []
            for h, i in zip(jT, range(Njets)):
                fit, d = fitJtHisto(h, '', 1, i, 8)
                fits.append(fit)
                parameters.append(d)
                gausRMS.append(d['gausRMS'])
                gausRMSe.append(d['gausRMSe'])
                gammaRMS.append(d['gammaRMS'])
                gammaRMSe.append(d['gammaRMSe'])
                gausYield.append(d['gausYield'])
                gausYielde.append(d['gausYielde'])
                gammaYield.append(d['gammaYield'])
                gammaYielde.append(d['gammaYielde'])

            gausRMSg = Graph(len(gausRMS) - 2)
            gammaRMSg = Graph(len(gammaRMS) - 2)
            gausYieldg = Graph(len(gausYield) - 2)
            gammaYieldg = Graph(len(gammaYield) - 2)
            for h, he, g in zip((gausYield, gammaYield),
                                (gausYielde, gammaYielde),
                                (gausYieldg, gammaYieldg)):
                for x, xe, a, e, i in zip(jetPtCenter[2:],
                                          jetPtErrors[2:], h[2:], he[2:],
                                          range(len(gausRMS) - 2)):
                    g.SetPoint(i, x, a)
                    g.SetPointError(i, xe, xe, e, e)

            for a, b, c, d, e, f, i in zip(gausRMS[2:], gammaRMS[2:],
                                           gausRMSe[2:], gammaRMSe[2:],
                                           jetPtCenter[2:], jetPtErrors[2:],
                                           range(len(gausRMS) - 2)):
                gausRMSg.SetPoint(i, e, a)
                gausRMSg.SetPointError(i, f, f, c, c)
                gammaRMSg.SetPoint(i, e, b)
                gammaRMSg.SetPointError(i, f, f, d, d)

            FullJets_gausRMS.append(gausRMSg)
            FullJets_gammaRMS.append(gammaRMSg)
            FullJets_gausYield.append(gausYieldg)
            FullJets_gammaYield.append(gammaYieldg)
            FullJets_fit.append(fits)
            FullJets_parameters.append(parameters)

        outFile = "Python/RootFiles/Fig6.root"
        outF = root_open(outFile, "w+")
        for h1, h2, jT, R in zip(FullJets_gausRMS, FullJets_gammaRMS,
                                 FullJets_jT, Rs):
            h1.SetName("FullJets_gausRMS_R{:02d}".format(int(R * 10)))
            h1.Write()
            h2.SetName("FullJets_gammaRMS_R{:02d}".format(int(R * 10)))
            h2.Write()
            for h, i in zip(jT, range(10)):
                h.SetName("jTSignalJetPt{:02d}_R{:02d}".format(i, int(R * 10)))
                h.Write()
        outF.Close()

    fig, axs = plt.subplots(2, 1, figsize=(7, 7))
    ax = axs[0]
    ax.set_xlim([0.1, 15])
    ax.set_ylim([5e-6, 2e3])
    ax.set_xlabel(r'$j_{T}\left(GeV/c\right)$', fontsize=labelsize)
    ax.set_ylabel(r'$\frac{1}{N_{jets}}\frac{dN}{j_{T}dj_{T}}$',
                  fontsize=labelsize)
    ratios = []
    ax.set_xscale('log')
    ax.set_yscale('log')
    for h, c, R in zip(FullJets_jT, (0, 1, 2, 3), Rs):
        h[6].SetMarkerColor(colors[c])
        h[6].SetMarkerStyle(styles[c])
        h[6].SetLineColor(colors[c])
        ratio = h[6].Clone()
        ratio.Divide(FullJets_jT[1][6])
        ratios.append(ratio)
        plot = rplt.errorbar(h[6],
                             xerr=False,
                             emptybins=False,
                             label='R = {:.1f}'.format(R),
                             axes=ax,
                             fmt='+')
        line = plot.get_children()[0]
        line.set_markersize(mSize)
        if (styles[c] > 23):
            line.set_markerfacecolor('none')
            #line.set_markeredgecolor(color)
            line.set_color(colors[c])

    ax.text(0.15,
            0.001,
            'Pythia \n Full Jets\n' + r'Anti-$k_T$' + '\n' +
            r'$p_{{T,\mathrm{{jet}}}}$: {:02d}-{:02d} GeV/c'.format(60, 80),
            fontsize=10)
    handles, labels = ax.get_legend_handles_labels()
    handles = [
        container.ErrorbarContainer(h, has_xerr=False, has_yerr=True)
        if isinstance(h, container.ErrorbarContainer) else h for h in handles
    ]
    ax.legend(handles, labels, loc='upper right', numpoints=1)
    #ax.legend(loc = 'upper right')
    ax.set_xlim([0.1, 15])
    ax.set_ylim([5e-6, 2e3])
    ax.grid(True)

    ax = axs[1]
    ax.grid(True)
    ax.set_xlabel(r'$j_{T}\left[GeV\right]$', fontsize=labelsize)
    ax.set_ylabel('Ratio',
                  fontsize=labelsize)  #Add x-axis labels for bottom row
    for ratio, c in zip(ratios, (0, 1, 2, 3)):
        #ratio.SetMarkerColor(c)
        #ratio.SetMarkerStyle(24)
        plot = rplt.errorbar(ratio, xerr=False, emptybins=False, axes=ax)
        line = plot.get_children()[0]
        line.set_markersize(mSize)
        if (styles[c] > 23):
            line.set_markerfacecolor('none')
            #line.set_markeredgecolor(color)
            line.set_color(colors[c])
    ax.set_xlim([0.1, 15])
    ax.set_ylim([0.1, 3])
    ax.set_xscale('log')
    plt.tight_layout()
    plt.subplots_adjust(wspace=0, hspace=0)  #Set space between subfigures to 0
    #plt.savefig("PythonFigures/RcomparisonSignalPt6080.pdf".format(file),format='pdf') #Save figure

    plt.show()  #Draw figure on screen
    drawWithErrors2Combined(FullJets_gausRMS,
                            FullJets_gammaRMS,
                            15,
                            500,
                            1,
                            0,
                            1.65,
                            0,
                            r'jet $p_T (GeV/c)$',
                            r'$\sqrt{\left<j_T^2\right>}$',
                            'Pythia',
                            'PythonFigures/RcomparisonRMS',
                            separate=True)