Example #1
0
def applyacc(wbin, q2bin, iedges, vedges, weights):
    # TODO: clone 2d hists to keep snapshots between steps of acceptance
    # corrections and zero-filling
    vals = ibins2vals(wbin, q2bin)
    (wval, wlo, whi) = (vals[0][0], vals[0][1], vals[0][2])
    (q2val, q2lo, q2hi) = (vals[1][0], vals[1][1], vals[1][2])
    h2s = (hexpsig, hexpsb, h2thr, h2acc) = h2costphis(wbin, q2bin, iedges)
    h2rec_acor = h2thr.Clone('h2r_acor')
    h2rec_acor.Multiply(h2acc)
    inth2r = h2rec_acor.Integral()  # integral of reconstructed simulated events
    h2rec_acor.Divide(h2acc)        # thrown events with acceptance holes
    h2thr.Add(h2rec_acor, -1)       # thrown events IN acceptance holes
    [h2thr.SetBinError(i, j, sqrt(h2thr.GetBinContent(i, j))) for i in range(1, h2thr.GetNbinsX()) for j in range(1, h2thr.GetNbinsY())]
    hexpsb.Scale(weights[0])  # weightsb
    hexpsig.Add(hexpsb, -1)
    inth2e = hexpsig.Integral()/weights[1]  # integral of signal region with 3-sigma cut correction
    hexpsig.Divide(h2acc)
    h2thr.Scale(inth2e/inth2r)
    hexpsig.Add(h2thr)

    cmmp = Canvas(name='hcostphi_%d_%d' % (round(1000*wval), round(1000*q2val)),
                  title='Angular Distributions, W, Q2 = %.3f GeV,%.3f GeV2' % (wval, q2val))
    cmmp.Divide(2, 2)
    for ipad, h2 in enumerate(h2s):
        cmmp.cd(ipad+1)
        r.gPad.Update()
        h2.Draw('colz')

    wait()
    return hexpsig
Example #2
0
def testme(wbin=15, q2bin=5):
    sigsbparms = fitbin(wbin, q2bin)
    if sigsbparms:
        (haccdists, herrdists) = applythresholds(h4_a, 0.01)
        haccdists.Draw()
        wait()
        # virtual photon flux factors and cc-cut efficiency factors
        # already applied in h6maker.h!
	# ... but not in DH_H6Maker.h
        h2e = applyacc(wbin, q2bin, *sigsbparms)

        vals = ibins2vals(wbin, q2bin)
        (wval, wlo, whi) = (vals[0][0], vals[0][1], vals[0][2])
        (q2val, q2lo, q2hi) = (vals[1][0], vals[1][1], vals[1][2])

        d2wq2 = (whi-wlo)*(q2hi-q2lo)
        branch = 0.891
        lum = 19.844*(1e6)
        h2e.Scale(1/(d2wq2*branch*lum))
        h2e.Scale(1/vgflux(wval, q2val))
        hcost = h2e.ProjectionY(str(h2e.GetName().replace('h2costphi', 'hcost')), 0, -1, 'e')
        hcost.Scale(1, 'width')
        h2e.Scale(1, 'width')
        hcost.SetDirectory(fout)
        errh2e = r.Double(0)
        inth2e = h2e.IntegralAndError(1, h2e.GetNbinsX(), 1, h2e.GetNbinsY(), errh2e, 'width')
        foutrecs.write(',%.0f,%.0f,%s\n' % (inth2e, errh2e, hcost.GetName()))
    foutrecs.close()
    fout.Write()
    fout.Close()
def luminosity_vs_time(timing_list, luminosity_list, style, run_name):
    '''

    :param timing_list: Python list containing the timing data
    :param luminosity_list: Python list containing the luminosity data
    :param style: ROOT style in string, such as 'ATLAS'
    :return:
    '''
    # Set ROOT graph style
    set_style(str(style))

    # create graph
    graph = Graph(len(timing_list))
    for i, (xx, yy) in enumerate(zip(timing_list, luminosity_list)):
        graph.SetPoint(i, xx, yy)

        # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("Time")
    graph.yaxis.SetTitle("Luminosity")
    graph.xaxis.SetRangeUser(min(timing_list), max(timing_list))
    graph.yaxis.SetRangeUser(min(luminosity_list), max(luminosity_list))

    # plot with ROOT
    canvas = Canvas()
    graph.Draw("AP")
    label = ROOT.TText(0.8, 0.9, str(run_name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
def extract_MET(f_tt, f_qcd, f_wjet):

    # get trees from files
    t_tt = f_tt.Get("Delphes")
    t_qcd = f_qcd.Get("Delphes")
    t_wjet = f_wjet.Get("Delphes")

    # get number of entries
    tt_n_entries = t_tt.GetEntries()
    qcd_n_entries = t_qcd.GetEntries()
    wjet_n_entries = t_wjet.GetEntries()

    # define leaves
    var_tt = "MissingET.MET"
    var_qcd = "MissingET.MET"
    var_wjet = "MissingET.MET"

    leaf_tt = t_tt.GetLeaf(var_tt)
    leaf_qcd = t_qcd.GetLeaf(var_qcd)
    leaf_wjet = t_wjet.GetLeaf(var_wjet)

    # create the histograms
    MET_tt = Hist(MET_NBINS, MET_NLO, MET_NHI, title='MET_tt', legendstyle='L')
    MET_qcd = Hist(MET_NBINS,
                   MET_NLO,
                   MET_NHI,
                   title='MET_qcd',
                   legendstyle='L')
    MET_wjet = Hist(MET_NBINS,
                    MET_NLO,
                    MET_NHI,
                    title='MET_wjet',
                    legendstyle='L')

    # FILLING THE TREE
    fill_MET_tree(tt_n_entries, t_tt, leaf_tt, MET_tt)
    fill_MET_tree(qcd_n_entries, t_qcd, leaf_qcd, MET_qcd)
    fill_MET_tree(wjet_n_entries, t_wjet, leaf_wjet, MET_wjet)

    #set line colors
    MET_tt.SetLineColor('blue')
    MET_qcd.SetLineColor('green')
    MET_wjet.SetLineColor('red')

    #begin drawing stuff
    c1 = Canvas()
    MET_qcd.SetStats(0)
    MET_qcd.Draw('HIST')
    MET_tt.Draw('HIST SAME')
    MET_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([MET_tt, MET_qcd, MET_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("../plots/MET_plots/MET.pdf")

    #make the plots wait on screen
    wait(True)
Example #5
0
def draw_DR(DR_tt, DR_qcd, DR_wjet):

    #set line colors
    DR_tt.SetLineColor(4)
    DR_qcd.SetLineColor(8)
    DR_wjet.SetLineColor(2)

    DR_tt.legendstyle = 'L'
    DR_qcd.legendstyle = 'L'
    DR_wjet.legendstyle = 'L'

    #begin drawing stuff
    c1 = Canvas()
    DR_qcd.SetStats(0)
    DR_qcd.Draw('HIST')
    DR_tt.Draw('HIST SAME')
    DR_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([DR_tt, DR_qcd, DR_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("DeltaR.pdf")

    #make the plots wait on screen
    wait(True)
def plot_raw_detector_vs_detector(detector_one_data, detector_two_data, style, name):
    # Set ROOT graph style
    set_style(str(style))
    detector_one_list = []
    detector_two_list = []
    for block in range(len(detector_one_data)):
        for bcid in range(len(detector_one_data[block])):
            detector_one_list.append(detector_one_data[block][bcid])
            detector_two_list.append(detector_two_data[block][bcid])
    # create graph
    graph = Graph(len(detector_one_list))
    for i, (xx, yy) in enumerate(zip(detector_one_list, detector_two_list)):
        graph.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("BCM V [Raw Rate]")
    graph.yaxis.SetTitle("LUCID BI [Raw Rate]")
    graph.xaxis.SetRangeUser(0, 1)
    graph.yaxis.SetRangeUser(0, 1)

    # plot with ROOT
    canvas = Canvas()
    graph.Draw("AP")
    label = ROOT.TText(0.6, 0.9, str(name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
def plot_percent_luminosity_ratio(detector_one_data, detector_two_data, style, run_name):
    '''

    :param detector_one_data: Data from one detector type, such as ATLAS' LUCID, in a list of lists, every entry is one
    luminsoity block, with the luminosity block being a list of BCID data, assumed to be same
    length as detector_two_data
    :param detector_two_data: Data from another detector type, such as ATLAS' LUCID, in a list of lists, every entry is
    one luminosity block, with the luminosity block being a list of BCID data, assumed to be same
    length as detector_one_data
    :param style: The ROOT style for the graph, generally 'ATLAS'
    :return: ROOT plots of the ratio of luminosities over the luminosity, as percetnage difference from first data point
    '''
    # Set ROOT graph style
    set_style(str(style))

    print("Number of Luminosity Blocks included: " + str(len(detector_one_data)))
    # Get ratio of the detectors
    luminosity_ratio = []
    lumi_blocks = []
    for block in range(len(detector_one_data)):
        for bcid in range(len(detector_one_data[block])):
            detector_one_point = detector_one_data[block][bcid]
            detector_two_point = detector_two_data[block][bcid]
            # Check if the blocks are zero
            if detector_one_point != 0.0 and detector_two_point != 0.0:
                ratio = -math.log(1 - detector_one_point) / -math.log(1 - detector_two_point)
                luminosity_ratio.append(ratio)
                lumi_blocks.append(block)

    # Get percentage difference based off the first block and BCID
    first_point = luminosity_ratio[0]

    for index in range(len(luminosity_ratio)):
        luminosity_ratio[index] = (luminosity_ratio[index] / first_point) - 1

    # create graph
    graph = Graph(len(lumi_blocks), title=run_name)
    for i, (xx, yy) in enumerate(zip(lumi_blocks, luminosity_ratio)):
        graph.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("Luminosity Block")
    graph.yaxis.SetTitle("Luminosity [Percent Ratio]")
    graph.xaxis.SetRangeUser(min(lumi_blocks), max(lumi_blocks))
    graph.yaxis.SetRangeUser(min(luminosity_ratio), max(luminosity_ratio))

    # plot with ROOT
    canvas = Canvas()
    graph.Draw("AP")
    label = ROOT.TText(0.8, 0.9, str(run_name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
Example #8
0
def do_stuff(file_name, plot=True):
    tiq_data = TIQData(file_name)
    NFRAMES = 100
    LFRAMES = 1024

    tiq_data.read(nframes=NFRAMES, lframes=LFRAMES, sframes=1)
    center = tiq_data.center

    # do fft
    ff, pp, _ = tiq_data.get_fft()

    freq_lower = center + ff[0] / 1e6
    freq_upper = center + ff[-1] / 1e6

    # create hist
    h1 = Hist(NFRAMES * LFRAMES,
              freq_lower,
              freq_upper,
              name='h1',
              title='Frequency Spectrum',
              drawstyle='hist',
              legendstyle='F',
              fillstyle='/',
              linecolor='green')

    for i in range(len(pp)):
        h1.set_bin_content(i, pp[i])

    # set visual attributes
    h1.GetXaxis().SetTitle('Freuqency [MHz]')
    h1.linecolor = 'green'
    # h1.fillcolor = 'green'
    # h1.fillstyle = '/'

    if plot:
        # plot
        c = Canvas(name='c1', width=700, height=500)
        c.set_left_margin(0.15)
        c.set_bottom_margin(0.15)
        c.set_top_margin(0.10)
        c.set_right_margin(0.05)
        c.toggle_editor()
        c.toggle_event_status()
        c.toggle_tool_bar()
        # c.set_crosshair()

        h1.Draw()

        # create the legend
        legend = Legend([h1],
                        pad=c,
                        header='Header',
                        leftmargin=0.05,
                        rightmargin=0.5)
        legend.Draw()

        # wait for key press
        wait()
Example #9
0
def do_stuff(file_name, plot=True):
    tiq_data = TIQData(file_name)
    NFRAMES = 100
    LFRAMES = 1024

    tiq_data.read(nframes=NFRAMES, lframes=LFRAMES, sframes=1)
    center = tiq_data.center

    # do fft
    ff, pp, _ = tiq_data.get_fft()

    freq_lower = center + ff[0] / 1e6
    freq_upper = center + ff[-1] / 1e6

    # create hist
    h1 = Hist(NFRAMES * LFRAMES, freq_lower, freq_upper, name='h1', title='Frequency Spectrum',
              drawstyle='hist',
              legendstyle='F',
              fillstyle='/',
              linecolor='green')

    for i in range(len(pp)):
        h1.set_bin_content(i, pp[i])

    # set visual attributes
    h1.GetXaxis().SetTitle('Freuqency [MHz]')
    h1.linecolor = 'green'
    # h1.fillcolor = 'green'
    # h1.fillstyle = '/'

    if plot:
        # plot
        c = Canvas(name='c1', width=700, height=500)
        c.set_left_margin(0.15)
        c.set_bottom_margin(0.15)
        c.set_top_margin(0.10)
        c.set_right_margin(0.05)
        c.toggle_editor()
        c.toggle_event_status()
        c.toggle_tool_bar()
        # c.set_crosshair()

        h1.Draw()

        # create the legend
        legend = Legend([h1], pad=c,
                        header='Header',
                        leftmargin=0.05,
                        rightmargin=0.5)
        legend.Draw()

        # wait for key press
        wait()
Example #10
0
def test_cmstdr():

    style = get_style('CMSTDR')
    with style:
        canvas = Canvas()
        hpx = Hist(100, -4, 4, name="hpx", title="This is the px distribution")
        ROOT.gRandom.SetSeed()
        for i in xrange(1000):
            hpx.Fill(ROOT.gRandom.Gaus())
        hpx.GetXaxis().SetTitle("random variable [unit]")
        hpx.GetYaxis().SetTitle("#frac{dN}{dr} [unit^{-1}]")
        hpx.SetMaximum(100.)
        hpx.Draw()
        CMS_label("Testing 2050", sqrts=100)
        if INTERACTIVE:
            wait()
Example #11
0
def test_lhcb():
    style = get_style('LHCb')

    with style:
        canvas = Canvas()
        hpx = Hist(100, -4, 4, name="hpx", title="This is the px distribution")
        ROOT.gRandom.SetSeed()
        for i in xrange(1000):
            hpx.Fill(ROOT.gRandom.Gaus())
        hpx.GetXaxis().SetTitle("random variable [unit]")
        hpx.GetYaxis().SetTitle("#frac{dN}{dr} [unit^{-1}]")
        hpx.SetMaximum(80.)
        hpx.Draw()
        LHCb_label("R", "preliminary")
        if INTERACTIVE:
            wait()
Example #12
0
def drawxint():
    df = pd.read_csv('out/ana_bd.dat')
    # dftmp = df[['W', 'Q2', 'xsect', 'err', 'fsigchi2']][
    #    (df['fsigchi2'] < 3) & (df['fsigchi2'] > 0) & (df['weightsb'] > 0) & (df['weight3s'] > 0)]

    q2groups = df[(df['fsigchi2'] < 3) & (df['fsigchi2'] > 0.5) & (
        df['fsigstat'] == 'CONVERGED ') & (df['weightsb'] > 0) & (df['weight3s'] > 0) & (df['fsigpar2'] > 0.008) & (df['fsigpar2'] < 0.035)].groupby(df.Q2)
    # xerrs = np.array(48 * [0.0])
    gtitle = '$Q^2 = %.3f$ $GeV^2$'

    for q2, grp in q2groups:
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        ax1.errorbar(grp.W, grp.xsect, grp.err, ls='none', marker='o', ms=4, color='black')
        ax1.set_ylim(-50, ax1.get_ylim()[1])
        ax1.set_xlim((1.6, 3.0))
        ax1.set_title(gtitle % q2, fontsize=20, y=1.025)
        ax1.set_xlabel('W (GeV)', fontsize=16)
        ax1.set_ylabel('$\sigma$  ($nb^{-1}$)', fontsize=20)
        plt.grid(b=True, which='major', color='black', ls='-')
        plt.grid(b=True, which='minor', color='black', ls='dotted')
        ax1.minorticks_on()
        plt.axhline(0, color='blue', ls='-', linewidth=1.25)

        ax2 = ax1.twinx()
        ax2.set_ylabel('$\~{\chi}^{2}$', color='r', fontsize=20)
        ax2.set_ylim(0, 3)
        ax2.plot(grp.W, grp.fsigchi2, marker='o', ms=4, ls='none', color='r')
        for tickl in ax2.get_yticklabels():
            tickl.set_color('r')

        # ax2 = ax1.twinx()
        # ax2.set_ylabel('$\sigma_{g}$', color='r')
        # ax2.set_ylim(0.008, 0.035)
        # ax2.plot(grp.W, grp.fsigpar2, marker='o', ms=4, ls='none', color='r')
        # for tickl in ax2.get_yticklabels():
        #     tickl.set_color('r')
        # plt.tight_layout()
        plt.show()
        wait()
def root_plot(hists, fitfuncs={}, outfile=None, title=''):
    if not hists:
        print_err('No hists to plot')
        return

    single = len(hists) is 1

    ROOT.gROOT.Reset()
    c1 = ROOT.TCanvas('c1', str(title) , 200, 10, 700, 500 )
    c1.SetGrid()
    legend = ROOT.TLegend(0.5, 0.8, 0.9,0.9)
    
    if not single:
        ROOT.gStyle.SetOptStat(0)  # Hide statistics
    
    for idx, k in enumerate(sorted(hists)):
        hist = hists[k]

        hist_color = next(colors)
        hist.SetLineColor(hist_color);
        
        if idx == 0:
            hist.Draw('HIST')
        else:
            hist.Draw('HIST SAMES')

        legend.AddEntry(hist, str(k), "f")   
        
        if k in fitfuncs:
            fitfunc = fitfuncs[k]

            fitfunc.SetLineColor(hist_color);
            fitfunc.Draw('same')

    
    if not single:
        legend.Draw()
        
    c1.Update()
    wait(True)
def root_plot(hists, fitfuncs={}, outfile=None, title=''):
    if not hists:
        print_err('No hists to plot')
        return

    single = len(hists) is 1

    ROOT.gROOT.Reset()
    c1 = ROOT.TCanvas('c1', str(title), 200, 10, 700, 500)
    c1.SetGrid()
    legend = ROOT.TLegend(0.5, 0.8, 0.9, 0.9)

    if not single:
        ROOT.gStyle.SetOptStat(0)  # Hide statistics

    for idx, k in enumerate(sorted(hists)):
        hist = hists[k]

        hist_color = next(colors)
        hist.SetLineColor(hist_color)

        if idx == 0:
            hist.Draw('HIST')
        else:
            hist.Draw('HIST SAMES')

        legend.AddEntry(hist, str(k), "f")

        if k in fitfuncs:
            fitfunc = fitfuncs[k]

            fitfunc.SetLineColor(hist_color)
            fitfunc.Draw('same')

    if not single:
        legend.Draw()

    c1.Update()
    wait(True)
def luminosity_block_log_time(luminosity_list, style):
    '''

    :param timing_list: Python list containing the timing data
    :param luminosity_list: Python list containing the luminosity data
    :param style: ROOT style in string, such as 'ATLAS'
    :return: Graph of the luminosity over a single block
    '''
    # Set ROOT graph style
    set_style(str(style))

    luminosity_ratio = []
    for bcid in range(len(luminosity_list)):
        detector_one_point = luminosity_list[bcid]
        # Check if the blocks are zero
        if detector_one_point != 0.0:
            ratio = -math.log(1 - detector_one_point)
            luminosity_ratio.append(ratio)

    # create graph
    graph = Graph(len(luminosity_ratio))
    for i, (xx, yy) in enumerate(zip(range(len(luminosity_ratio)), luminosity_ratio)):
        graph.SetPoint(i, xx, yy)

        # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("Time")
    graph.yaxis.SetTitle("-Ln(1 - Rate) [Single Detector]")
    graph.xaxis.SetRangeUser(0, 3564)
    graph.yaxis.SetRangeUser(min(luminosity_ratio), max(luminosity_ratio))

    # plot with ROOT
    canvas = Canvas()
    graph.Draw("AP")
    wait(True)
Example #16
0
hist2d_adc_sigma.SetTitle("ADC Sigma of 1600 Channels")
hist2d_adc_sigma.GetXaxis().SetNdivisions(40)
hist2d_adc_sigma.GetYaxis().SetNdivisions(40)
for i in xrange(40):
    if (i % 8 == 0):
        hist2d_adc_sigma.GetXaxis().SetBinLabel(i + 1, "%02d" % i)
        hist2d_adc_sigma.GetYaxis().SetBinLabel(i + 1, "%02d" % i)

ROOT.gStyle.SetOptStat(0)

for i in xrange(25):
    for j in xrange(64):
        hist2d_adc_per_kev.SetBinContent(
            ijtox(i, j) + 1,
            ijtoy(i, j) + 1, adc_per_kev[i][j])
        hist2d_adc_sigma.SetBinContent(
            ijtox(i, j) + 1,
            ijtoy(i, j) + 1, adc_sigma[i][j])

c1 = ROOT.TCanvas()
c1.SetWindowSize(1600, 800)
c1.Divide(2, 1)
c1.cd(1)
c1.GetPad(1).SetGrid()
hist2d_adc_per_kev.Draw("COLZ")
c1.cd(2)
c1.GetPad(2).SetGrid()
hist2d_adc_sigma.Draw("COLZ")

wait(True)
    mg[flv].GetHistogram().GetYaxis().SetTitleSize(0.045)
    mg[flv].GetHistogram().GetYaxis().SetTitleOffset(1.)
    #   line = TLine(0.,1.,1200.,1.);
    #   line.Draw("same");

    canvas[flv].Modified()
    canvas[flv].Update()
    resdir = './results'
    if not os.path.exists(resdir):
        os.makedirs(resdir)
    outfile = resdir + '/btag_eff_' + flv + 'jets_' + year1 + '_' + balgo1 + '_' + bwp1 + '_' + h_mu1 + '_' + trg1
    if len(sys.argv) > 3:
        outfile += '_x_' + balgo2 + '_' + bwp2 + '_' + year2 + '_' + balgo2 + '_' + bwp2 + '_' + h_mu2 + '_' + trg2
    outfile += '.png'

    canvas[flv].SaveAs(outfile)

    if flv == 'udsg':
        mg[flv].GetHistogram().GetYaxis().SetRangeUser(0.005, 1.19)
        if bwp1 == 'tight' or bwp2 == 'tight':
            mg[flv].GetHistogram().GetYaxis().SetRangeUser(0.0005, 1.19)
        canvas[flv].SetLogy()
        outfile = resdir + '/btag_eff_' + flv + 'jets_' + year1 + '_' + balgo1 + '_' + bwp1 + '_' + h_mu1 + '_' + trg1
        if len(sys.argv) > 3:
            outfile += '_x_' + balgo2 + '_' + bwp2 + '_' + year2 + '_' + balgo2 + '_' + bwp2 + '_' + h_mu2 + '_' + trg2
        outfile += '_log.png'

        canvas[flv].SaveAs(outfile)

wait(True)  # close with middle mouse button
Example #18
0
def make1DLimitPlot(xtitle, xvals, obs, exp, exp1plus, exp1minus, exp2plus, exp2minus, theory):
    gStyle.SetOptTitle(0)

    axisTitleSize = 0.041
    axisTitleOffset = 1.2
    axisTitleSizeRatioX   = 0.18
    axisLabelSizeRatioX   = 0.12
    axisTitleOffsetRatioX = 0.94
    axisTitleSizeRatioY   = 0.15
    axisLabelSizeRatioY   = 0.108
    axisTitleOffsetRatioY = 0.32

    leftMargin   = 0.15
    rightMargin  = 0.12
    topMargin    = 0.05
    bottomMargin = 0.14
    bottomMargin2 = 0.22

    #c1 = TCanvas() #'c1', '', 200, 10, 700, 500 )
    c1 = TCanvas( "c1", "c2", 200, 10, 700, 600 )

    c1.SetHighLightColor(2)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetBorderSize(2)
    c1.SetLeftMargin(leftMargin)
    c1.SetRightMargin(rightMargin)
    c1.SetTopMargin(topMargin)
    c1.SetBottomMargin(bottomMargin)
    c1.SetFrameBorderMode(0)
    c1.SetFrameBorderMode(0)
    c1.SetLogy(1)
    #c1.SetLogx(1)
    c1.SetTickx(1)
    c1.SetTicky(1)
    #c1.SetGridx(True);
    #c1.SetGridy(True);
    if "c#tau" in xtitle:
        c1.SetLogx(1);

    exp2sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
           array('d', [0]), array('d', [0]), array('d', exp2minus), array('d', exp2plus))
    exp2sigma_xsec.Sort()
    exp2sigma_xsec.Draw('A3')
    exp2sigma_xsec.SetFillStyle(1001);
    exp2sigma_xsec.SetFillColor(kOrange);
    exp2sigma_xsec.SetLineColor(kOrange);
    exp2sigma_xsec.GetYaxis().SetRangeUser(0.001,100);
    exp2sigma_xsec.GetXaxis().SetLimits(0.8*min(xvals),1.1*max(xvals));
    #exp2sigma_xsec.GetXaxis().SetTitle('m_{1} [GeV]')
    #exp2sigma_xsec.GetXaxis().SetTitle('c#tau [cm]')
    exp2sigma_xsec.GetXaxis().SetTitle(xtitle)
    exp2sigma_xsec.GetXaxis().SetTitleOffset(axisTitleOffset)
    exp2sigma_xsec.GetYaxis().SetTitle('95% C.L. #sigma(pp #rightarrow #chi_{1} #chi_{1} #mu^{+} #mu^{-}) [pb]')
    exp2sigma_xsec.GetYaxis().SetTitleOffset(axisTitleOffset+0.1)

    exp1sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
            array('d', [0]), array('d', [0]), array('d', exp1minus), array('d', exp1plus))
    exp1sigma_xsec.Sort()
    exp1sigma_xsec.SetFillStyle(1001);
    exp1sigma_xsec.SetFillColor(kGreen+1);
    exp1sigma_xsec.SetLineColor(kGreen+1);
    exp1sigma_xsec.Draw('3 SAME')

    exp_xsec = TGraph(len(xvals), array('d', xvals), array('d', exp))
    exp_xsec.Sort()
    exp_xsec.SetLineWidth(2)
    exp_xsec.SetLineStyle(1)
    exp_xsec.SetLineColor(kRed)
    exp_xsec.Draw('C SAME')

    obs_xsec = TGraph(len(xvals), array('d', xvals), array('d', obs))
    obs_xsec.Sort()
    obs_xsec.SetLineWidth(3)
    obs_xsec.SetLineColor(kBlack)
    obs_xsec.SetMarkerColor(kBlack)
    obs_xsec.SetMarkerStyle(20)
    obs_xsec.SetMarkerSize(1)
    obs_xsec.Draw('PC SAME')

    theory_xsec = TGraph(len(xvals), array('d', xvals), array('d', theory))
    theory_xsec.Sort()
    theory_xsec.SetLineWidth(2)
    theory_xsec.SetLineStyle(8)
    theory_xsec.SetLineColor(kBlue)
    theory_xsec.Draw('C SAME')

    leg = TLegend(0.50,0.70,0.8,0.90);
    leg.SetBorderSize(0);
    leg.SetFillStyle(0);
    leg.AddEntry(theory_xsec, "Theory", "l");
    leg.AddEntry(obs_xsec, "Observed Limit", "pl");
    leg.AddEntry(exp_xsec, "Expected Limit", "l");
    leg.AddEntry(exp1sigma_xsec, "#pm 1 std. dev.", "f");
    leg.AddEntry(exp2sigma_xsec, "#pm 2 std. dev.", "f");
    leg.Draw()

    drawCMSLogo(c1, 13, 122450)

    # TCanvas.Update() draws the frame, after which one can change it
    # c1.Update()
    # c1.Modified()
    # c1.Update()

    c1.RedrawAxis()
    c1.Draw()
    
    wait(True)
Example #19
0
def make2DLimitPlot(xtitle, xvals, yvals, obs, exp, exp1plus, exp1minus,
                    exp2plus, exp2minus, theory, **kwargs):
    use_ctau = kwargs.pop('use_ctau', False)
    do_interpolation = kwargs.pop('do_interpolation', True)
    debug = kwargs.pop('debug', True)
    mass_splitting = kwargs.pop('mass_splitting', '0.1')

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)

    axisTitleSize = 0.041
    axisTitleOffset = 1.2

    leftMargin = 0.15
    rightMargin = 0.18
    topMargin = 0.06
    bottomMargin = 0.14

    c1 = TCanvas("c1", "c1", 200, 10, 700, 600)
    c1.SetHighLightColor(2)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetBorderSize(2)
    c1.SetLeftMargin(leftMargin)
    c1.SetRightMargin(rightMargin)
    c1.SetTopMargin(topMargin)
    c1.SetBottomMargin(bottomMargin)
    c1.SetFrameBorderMode(0)
    c1.SetLogy(1)
    c1.SetLogx(1)
    c1.SetLogz(1)
    c1.SetTickx(1)
    c1.SetTicky(1)

    stops = np.array([0.00, 0.34, 0.61, 0.84, 1.00])
    red = np.array([0.50, 0.50, 1.00, 1.00, 1.00])
    green = np.array([0.50, 1.00, 1.00, 0.60, 0.50])
    blue = np.array([1.00, 1.00, 0.50, 0.40, 0.50])
    TColor.CreateGradientColorTable(len(stops), stops, red, green, blue, 255)
    gStyle.SetNumberContours(255)

    if debug:
        print "list of m1s:", xvals
        print "list of ys: ", yvals
        print "list of obs limits: ", obs

    if do_interpolation:
        data = interpolateObsLimit(xvals,
                                   yvals,
                                   obs,
                                   debug=debug,
                                   mass_splitting=mass_splitting)
    else:
        data = np.array([xvals, yvals, obs])

    widthx = sorted(data[0])[0] / 10
    widthy = sorted(data[1])[0] / 10

    lowXs = [xval - widthx / 2 for xval in data[0]]
    highXs = [xval + widthx / 2 for xval in data[0]]
    lowYs = [yval - widthy / 2 for yval in data[1]]
    highYs = [yval + widthy / 2 for yval in data[1]]
    binsX = sorted(list(dict.fromkeys(lowXs + highXs)))
    binsY = sorted(list(dict.fromkeys(lowYs + highYs)))
    binsX = [(binsX[i] + binsX[i + 1]) / 2 if i != len(binsX) - 1 else binsX[i]
             for i in range(1,
                            len(binsX) - 1, 2)]
    binsY = [(binsY[i] + binsY[i + 1]) / 2 if i != len(binsY) - 1 else binsY[i]
             for i in range(1,
                            len(binsY) - 1, 2)]
    binsX.insert(0, sorted(lowXs)[0])
    binsX.insert(len(binsX), sorted(highXs)[-1])
    binsY.insert(0, sorted(lowYs)[0])
    binsY.insert(len(binsY), sorted(highYs)[-1])

    if debug:
        print "binsX ", binsX
        print "binsY ", binsY

    obs_xsec = TH2D('', '',
                    len(binsX) - 1, array('d', binsX),
                    len(binsY) - 1, array('d', binsY))

    obs_xsec.GetXaxis().SetTitleSize(axisTitleSize)
    obs_xsec.GetXaxis().SetTitleOffset(axisTitleOffset - 0.3)
    obs_xsec.GetXaxis().SetTitle("m_{1} [GeV]")
    obs_xsec.GetXaxis().SetMoreLogLabels()

    obs_xsec.GetYaxis().SetTitleSize(axisTitleSize)
    obs_xsec.GetYaxis().SetTitleOffset(axisTitleOffset + 0.1)
    if use_ctau:
        obs_xsec.GetYaxis().SetTitle("c#tau [cm]")
    else:
        obs_xsec.GetYaxis().SetTitle(
            "y = #epsilon^{2} #alpha_{D} (m_{1}/m_{A'})^{4}")

    obs_xsec.GetZaxis().SetTitleSize(axisTitleSize - 0.005)
    obs_xsec.GetZaxis().SetTitleOffset(axisTitleOffset + 0.1)
    obs_xsec.GetZaxis().SetTitle(
        "#sigma_{95% CL} Br(A' #rightarrow #mu#mu) [pb]")

    obs_xsec.FillN(len(data[0]), array('d', data[0]), array('d', data[1]),
                   array('d', data[2]))
    obs_xsec.GetZaxis().SetRangeUser(1e-4, 1e2)

    if do_interpolation:
        obs_xsec.Draw("COLZ")
    else:
        obs_xsec.Draw("COLZ TEXT")

    obs_mu = [x / y for x, y in zip(obs, theory)]
    plotLimitBoundary(c1,
                      xvals,
                      yvals,
                      obs_mu, [1, kBlack],
                      debug=debug,
                      mass_splitting=mass_splitting)

    exp_mu = [x / y for x, y in zip(exp, theory)]
    plotLimitBoundary(c1,
                      xvals,
                      yvals,
                      exp_mu, [2, kRed],
                      debug=debug,
                      mass_splitting=mass_splitting)

    CMS_lumi(c1, "137.2 fb^{-1} (13 TeV)", 0)

    c1.RedrawAxis()
    c1.Draw()

    wait(True)
def plot_percent_luminosity_ratio_sum(detector_one_data, detector_two_data, style, run_name):
    '''

    :param detector_one_data: Data from one detector type, such as ATLAS' LUCID, in a list of lists, every entry is one
    luminsoity block, with the luminosity block being a list of BCID data, assumed to be same
    length as detector_two_data
    :param detector_two_data: Data from another detector type, such as ATLAS' LUCID, in a list of lists, every entry is
    one luminosity block, with the luminosity block being a list of BCID data, assumed to be same
    length as detector_one_data
    :param style: The ROOT style for the graph, generally 'ATLAS'
    :return: ROOT plots of the ratio of luminosity sums over the luminosity, as percentage difference from first data point
    '''
    # Set ROOT graph style
    set_style(str(style))

    print("Number of Luminosity Blocks included: " + str(len(detector_one_data)))

    # Get average value of the rate for each luminosity block
    temp_detector_one = [[] for _ in xrange(len(detector_one_data))]
    temp_detector_two = [[] for _ in xrange(len(detector_one_data))]
    for block in range(len(detector_one_data)):
        detector_one_avg = 0
        one_count = 0
        detector_two_avg = 0
        two_count = 0
        for bcid in range(len(detector_one_data[block])):
            detector_one_point = detector_one_data[block][bcid]
            detector_two_point = detector_two_data[block][bcid]
            detector_one_avg += detector_one_point
            one_count += 1
            detector_two_avg += detector_two_point
            two_count += 1
        if one_count != 0:
            detector_one_avg = detector_one_avg / one_count
            detector_two_avg = detector_two_avg / two_count
            temp_detector_one[block].append(detector_one_avg)
            temp_detector_two[block].append(detector_two_avg)

    # Reassign temp to the original lists
    detector_one_data = temp_detector_one
    detector_two_data = temp_detector_two

    # Get ratio of the detectors
    luminosity_ratio = []
    lumi_blocks = []
    for block in range(len(detector_one_data)):
        for bcid in range(len(detector_one_data[block])):
            detector_one_point = detector_one_data[block][bcid]
            detector_two_point = detector_two_data[block][bcid]
            # Check if the blocks are zero
            if detector_one_point != 0.0 and detector_two_point != 0.0:
                ratio = -math.log(1 - detector_one_point) / -math.log(1 - detector_two_point)
                luminosity_ratio.append(ratio)
                lumi_blocks.append(block)

    # Get percentage difference based off the first block and BCID
    first_point = luminosity_ratio[0]

    for index in range(len(luminosity_ratio)):
        luminosity_ratio[index] = (luminosity_ratio[index] / first_point) - 1

    # Delete last point, when the beams are being shut down and there are massive spikes
    luminosity_ratio = luminosity_ratio[:-1]
    lumi_blocks = lumi_blocks[:-1]
    # create graph
    graph = Graph(len(lumi_blocks), title=run_name)
    for i, (xx, yy) in enumerate(zip(lumi_blocks, luminosity_ratio)):
        graph.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("Luminosity Block")
    graph.yaxis.SetTitle("Luminosity [Average Percent Ratio]")
    graph.xaxis.SetRangeUser(min(lumi_blocks), max(lumi_blocks))
    graph.yaxis.SetRangeUser(min(luminosity_ratio), max(luminosity_ratio))

    # plot with ROOT
    canvas = Canvas()
    graph.Draw("AP")
    label = ROOT.TText(0.8, 0.9, str(run_name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
def plot_all_luminosity_block_ratio(all_detector_one_data, all_detector_two_data, background_list, status_data, style, name,
                                    detector_one_calibration, detector_two_calibration):
    '''

    :param all_detector_one_data: A dictionary of the run name to a list of lists of luminosity blocks
    :param all_detector_two_data: A dictionary of the run name to a list of lists of luminosity blocks
    :param style: a string corresponding to a ROOT graphing style, e.g. 'ATLAS'
    :return: Plot of all the detector data on a graph chronologically according to run number
    '''
    # Set ROOT graph style
    set_style(str(style))

    # Get average value of the rate for each luminosity block
    temp_detector_one = copy.deepcopy(all_detector_one_data)
    temp_detector_two = copy.deepcopy(all_detector_two_data)
    # print(sorted(all_detector_one_data.keys()))
    for run in sorted(all_detector_one_data.keys()):
        block_count = 0
        print"Starting run", run
        for block in range(len(all_detector_one_data.get(run)) - 1):
            del temp_detector_one.get(run)[block][:]
            del temp_detector_two.get(run)[block][:]
            block_count += 1
            detector_one_avg = 0
            one_count = 0
            detector_two_avg = 0
            two_count = 0
            for bcid in range(len(all_detector_one_data.get(run)[block])):
                # Gets the previous BCID luminosity to subtract as the background
                if run in background_list:
                    if status_data.get(run)[block][bcid - 1] <= 0.0:
                        detector_one_point_background = all_detector_one_data.get(run)[block][bcid - 1]
                        detector_two_point_background = all_detector_two_data.get(run)[block][bcid - 1]
                        print("BCID [N-1] Stability: " + str(status_data.get(run)[block][bcid - 1]))
                    else:
                        print("No empty BCID to subtract background from")
                    if all_detector_one_data.get(run)[block][bcid] < 1 and all_detector_two_data.get(run)[block][bcid] < 1:
                        print("BCID [N] Stability: " + str(status_data.get(run)[block][bcid]))
                        detector_one_point = -math.log(1 - all_detector_one_data.get(run)[block][bcid]) \
                                             + math.log(1 - detector_one_point_background)
                        print("Detector 1 Point: " + str(detector_one_point))
                        detector_two_point = -math.log(1 - all_detector_two_data.get(run)[block][bcid]) \
                                             + math.log(1 - detector_two_point_background)
                        print("Detector 2 Point: " + str(detector_two_point))
                        detector_one_avg += detector_one_point
                        one_count += 1
                        detector_two_avg += detector_two_point
                        two_count += 1
                else:
                    #print("         RUN:     " + str(run) + "                    END")
                    #print(all_detector_one_data.get(run)[block][bcid])
                    # Checking if the status is stable
                    if 1 > all_detector_one_data.get(run)[block][bcid] > 0.0 and 1 > all_detector_two_data.get(run)[block][bcid] > 0.0\
                            and status_data.get(run)[block][bcid] > 0.0:
                        #print("Value of Block, BCID: " + str(block) + " " + str(bcid) + " " + str(all_detector_one_data.get(run)[block][bcid]))
                        detector_one_point = -math.log(1 - all_detector_one_data.get(run)[block][bcid])
                        detector_two_point = -math.log(1 - all_detector_two_data.get(run)[block][bcid])
                        detector_one_avg += detector_one_point
                        one_count += 1
                        detector_two_avg += detector_two_point
                        two_count += 1
            if one_count != 0:
                detector_one_avg = detector_one_avg / one_count
                detector_two_avg = detector_two_avg / two_count
                if run == "286282":
                    print("One Average: " + str(detector_one_avg))
                temp_detector_one.get(run)[block_count - 1].append(detector_one_avg)
                temp_detector_two.get(run)[block_count - 1].append(detector_two_avg)
        # Remove the last luminosity block from each run, the one that generally spikes
        temp_detector_one[run] = temp_detector_one[run][:-10]
        temp_detector_two[run] = temp_detector_two[run][:-10]
    # Reassign temp to the original lists
    all_detector_one_data = temp_detector_one
    all_detector_two_data = temp_detector_two

    # Get ratio of the detectors
    luminosity_ratio = []
    lumi_blocks = []
    block_count1 = 0
    for run in sorted(all_detector_one_data.keys()):
        for block in range(len(all_detector_one_data.get(run))):
            block_count1 += 1
            for bcid in range(len(all_detector_one_data.get(run)[block])):
                detector_one_point = all_detector_one_data.get(run)[block][bcid]
                detector_two_point = all_detector_two_data.get(run)[block][bcid]
                # Check if the blocks are zero
                if detector_one_point != 0.0 or detector_two_point != 0.0:
                    ratio = detector_one_point / detector_two_point
                    luminosity_ratio.append(ratio)
                    lumi_blocks.append(block_count1)
                else:
                    print("Run", str(run), " Block:", str(block), "One:", str(detector_one_point),
                          "Two:", str(detector_two_point))

    print("Length lumi_blocks: " + str(len(lumi_blocks)))
    print("length lumi_ratio: " + str((len(luminosity_ratio))))

    # Get percentage difference based off the first block and BCID
    first_point = detector_one_calibration / detector_two_calibration

    for index in range(len(luminosity_ratio)):
        luminosity_ratio[index] = 100 * ((luminosity_ratio[index] / first_point) - 1)

    # create graph
    graph = Graph(len(lumi_blocks))
    for i, (xx, yy) in enumerate(zip(lumi_blocks, luminosity_ratio)):
        #print (xx, yy)
        graph.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("Luminosity Block")
    graph.yaxis.SetTitle("Luminosity [Average Percent Ratio]")
    graph.xaxis.SetRangeUser(min(lumi_blocks), max(lumi_blocks))
    #graph.yaxis.SetRangeUser(min(luminosity_ratio), max(luminosity_ratio))
    graph.yaxis.SetRangeUser(-5, 5)

    # plot with ROOT
    canvas = Canvas()

    graph.Draw("AP")
    # Draw lines for different runs
    run_length = 0
    for run in sorted(all_detector_one_data.keys()):
        #print("Length of Run " + str(run) + ": " + str(len(all_detector_one_data.get(run))))
        run_length += len(all_detector_one_data.get(run))
        line = ROOT.TLine(run_length, -5, #min(luminosity_ratio),
                          run_length, 5,)  # max(luminosity_ratio))
        line.Draw()
        line_label = ROOT.TText(run_length - 30, 5 -1.5, str(run)) #max(luminosity_ratio) - 1.5, str(run))
        line_label.SetTextAngle(90)
        line_label.SetTextSize(18)
        line_label.SetTextFont(43)
        line_label.Draw()
    label = ROOT.TText(0.7, 0.8, str(name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
Example #22
0
    axes.plot(x, y, 'o-', markeredgewidth=0)
    axes.set_xlabel(r"$E_T$ [GeV]",
                    horizontalalignment="right", x=1, labelpad=20)
    axes.set_ylabel(r"$d\sigma_{jet}/dE_{T,jet}$ [fb/GeV]",
                    horizontalalignment="right", y=1, labelpad=32)
    axes.set_xlim(0, 3500)
    axes.set_ylim(0, 1)

    return fig, axes

# plot without style
fig1, axes1 = plot_with_matplotlib()
axes1.text(0.4, 0.8, 'matplotlib (no style)',
           verticalalignment='center', horizontalalignment='center',
           transform=axes1.transAxes, fontsize=20)

# plot with ATLAS style
set_style('ATLAS', mpl=True)
fig2, axes2 = plot_with_matplotlib()
axes2.text(0.4, 0.8, 'matplotlib',
           verticalalignment='center', horizontalalignment='center',
           transform=axes2.transAxes, fontsize=20)
axes2.xaxis.set_minor_locator(AutoMinorLocator())
axes2.yaxis.set_minor_locator(AutoMinorLocator())

if not ROOT.gROOT.IsBatch():
    plt.show()

# wait for you to close the canvas before exiting
wait(True)
def plot_multiple_all_luminosity_block_ratio(all_detector_one_data, all_detector_two_data, all_detector_three_data,
                                             background_list, style, name):
    '''

    :param all_detector_one_data: A dictionary of the run name to a list of lists of luminosity blocks
    :param all_detector_two_data: A dictionary of the run name to a list of lists of luminosity blocks
    :param style: a string corresponding to a ROOT graphing style, e.g. 'ATLAS'
    :return: Plot of all the detector data on a graph chronologically according to run number
    '''
    # Set ROOT graph style
    set_style(str(style))

    # Get average value of the rate for each luminosity block
    temp_detector_one = copy.deepcopy(all_detector_one_data)
    temp_detector_two = copy.deepcopy(all_detector_two_data)
    temp_detector_three = copy.deepcopy(all_detector_three_data)
    print(sorted(all_detector_one_data.keys()))
    for run in sorted(all_detector_one_data.keys()):
        block_count = 0
        for block in range(len(all_detector_one_data.get(run)) - 1):
            del temp_detector_one.get(run)[block][:]
            del temp_detector_two.get(run)[block][:]
            del temp_detector_three.get(run)[block][:]
            block_count += 1
            detector_one_avg = 0
            one_count = 0
            detector_two_avg = 0
            two_count = 0
            detector_three_avg = 0
            three_count = 0
            for bcid in range(len(all_detector_one_data.get(run)[block])):
                # Gets the previous BCID luminosity to subtract as the background
                if run == "286282":
                    detector_one_point_background = all_detector_one_data.get(run)[block][bcid - 1]
                    detector_two_point_background = all_detector_two_data.get(run)[block][bcid - 1]
                    detector_three_point_background = all_detector_three_data.get(run)[block][bcid - 1]
                    print("BCID [N-1]: " + str(detector_one_point_background))
                    print("BCID [N]: " + str(all_detector_one_data.get(run)[block][bcid]))
                    detector_one_point = -math.log(1 - all_detector_one_data.get(run)[block][bcid]) \
                                         + math.log(1 - detector_one_point_background)
                    detector_three_point = -math.log(1 - all_detector_three_data.get(run)[block][bcid]) \
                                           + math.log(1 - detector_three_point_background)
                    print("Detector 1 Point: " + str(detector_one_point))
                    detector_two_point = -math.log(1 - all_detector_two_data.get(run)[block][bcid]) \
                                         + math.log(1 - detector_two_point_background)
                    detector_one_avg += detector_one_point
                    one_count += 1
                    detector_two_avg += detector_two_point
                    two_count += 1
                    detector_three_avg += detector_three_point
                    three_count += 1
                else:
                    detector_one_point = -math.log(1 - all_detector_one_data.get(run)[block][bcid])
                    detector_two_point = -math.log(1 - all_detector_two_data.get(run)[block][bcid])
                    detector_three_point = -math.log(1 - all_detector_three_data.get(run)[block][bcid])
                    detector_one_avg += detector_one_point
                    one_count += 1
                    detector_two_avg += detector_two_point
                    two_count += 1
                    detector_three_avg += detector_three_point
                    three_count += 1
            if one_count != 0:
                detector_one_avg = detector_one_avg / one_count
                detector_two_avg = detector_two_avg / two_count
                detector_three_avg = detector_three_avg / three_count
                temp_detector_one.get(run)[block_count - 1].append(detector_one_avg)
                temp_detector_two.get(run)[block_count - 1].append(detector_two_avg)
                temp_detector_three.get(run)[block_count - 1].append(detector_three_avg)
        # Remove the last luminosity block from each run, the one that generally spikes
        temp_detector_one[run] = temp_detector_one[run][:-10]
        temp_detector_two[run] = temp_detector_two[run][:-10]
        temp_detector_three[run] = temp_detector_three[run][:-10]
    # Reassign temp to the original lists
    all_detector_one_data = temp_detector_one
    all_detector_two_data = temp_detector_two
    all_detector_three_data = temp_detector_three

    # Get ratio of the detectors 1 and 2
    luminosity_ratio = []
    lumi_blocks = []
    block_count1 = 0
    for run in sorted(all_detector_one_data.keys()):
        for block in range(len(all_detector_one_data.get(run))):
            block_count1 += 1
            for bcid in range(len(all_detector_one_data.get(run)[block])):
                detector_one_point = all_detector_one_data.get(run)[block][bcid]
                detector_two_point = all_detector_two_data.get(run)[block][bcid]
                # Check if the blocks are zero
                if detector_one_point != 0.0 and detector_two_point != 0.0:
                    ratio = detector_one_point / detector_two_point
                    luminosity_ratio.append(ratio)
                    lumi_blocks.append(block_count1)

    # Get ratio of the detectors 1 and 3
    luminosity_ratio_1 = []
    lumi_blocks_1 = []
    block_count2 = 0
    for run in sorted(all_detector_one_data.keys()):
        for block in range(len(all_detector_one_data.get(run))):
            block_count2 += 1
            for bcid in range(len(all_detector_one_data.get(run)[block])):
                detector_one_point = all_detector_one_data.get(run)[block][bcid]
                detector_three_point = all_detector_three_data.get(run)[block][bcid]
                # Check if the blocks are zero
                if detector_one_point != 0.0 and detector_three_point != 0.0:
                    ratio = detector_one_point / detector_three_point
                    luminosity_ratio_1.append(ratio)
                    lumi_blocks_1.append(block_count2)

    # Get percentage difference based off the first block and BCID
    first_point = luminosity_ratio[0]
    first_point_1 = luminosity_ratio_1[0]

    for index in range(len(luminosity_ratio)):
        luminosity_ratio[index] = 100 * ((luminosity_ratio[index] / first_point) - 1)

    for index in range(len(luminosity_ratio_1)):
        luminosity_ratio_1[index] = 100 * ((luminosity_ratio_1[index] / first_point_1) - 1)

    # create graph
    graph = Graph(len(lumi_blocks))
    for i, (xx, yy) in enumerate(zip(lumi_blocks, luminosity_ratio)):
        graph.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("Luminosity Block")
    graph.yaxis.SetTitle("Luminosity [Average Percent Ratio]")
    graph.xaxis.SetRangeUser(min(lumi_blocks), max(lumi_blocks))
    graph.yaxis.SetRangeUser(min(luminosity_ratio), max(luminosity_ratio))

    # plot with ROOT
    canvas = Canvas()

    graph.Draw("AP")
    canvas.Update()

    # add points from detectors 1 and 3
    # create graph
    graph1 = Graph(len(lumi_blocks_1))
    for i, (xx, yy) in enumerate(zip(lumi_blocks_1, luminosity_ratio_1)):
        graph1.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph1.linecolor = 'white'  # Hides the lines at this time
    graph1.markercolor = 'red'
    # graph1.xaxis.SetRangeUser(min(lumi_blocks_1), max(lumi_blocks_1))
    # graph1.yaxis.SetRangeUser(min(luminosity_ratio_1), max(luminosity_ratio_1))

    graph1.Draw("P")
    canvas.Update()
    # Draw lines for different runs
    run_length = 0
    for run in sorted(all_detector_one_data.keys()):
        run_length += len(all_detector_one_data.get(run))
        line = ROOT.TLine(run_length, min(luminosity_ratio),
                          run_length, max(luminosity_ratio))
        line.Draw()
        line_label = ROOT.TText(run_length - 30, max(luminosity_ratio) - 1.5, str(run))
        line_label.SetTextAngle(90)
        line_label.SetTextSize(18)
        line_label.SetTextFont(43)
        line_label.Draw()
    label = ROOT.TText(0.7, 0.8, str(name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
Example #24
0
    Hist(100, -5, 5, color='salmon',
         drawstyle='hist').FillRandom(F1('TMath::Gaus(x, 2, 1)'), 500))
stack.Add(
    Hist(100, -5, 5, color='powderblue',
         drawstyle='hist').FillRandom(F1('TMath::Gaus(x, 2, 0.6)'), 300))
objects.append(stack)

# create some random histograms
for i, (mu, sigma, n, c,
        s) in enumerate(zip(mus, sigmas, events, colors, styles)):
    hist = Hist(100,
                -5,
                5,
                color=c,
                fillstyle=s,
                drawstyle='hist' if i % 2 == 0 else '')
    hist.FillRandom(F1('TMath::Gaus(x,{0},{1})'.format(mu, sigma)), n)
    objects.append(hist)

# create a graph
graph = Graph(10, drawstyle='P')
for i in range(10):
    x = -2 + i * 4 / 10.
    graph.SetPoint(i, x, 40 + 10 * sin(x))
objects.append(graph)

draw(objects, xtitle='Some Variable [Units]', ytitle='Events', ypadding=0.05)
# see rootpy.plotting.utils.get_limits for details on what arguments are
# supported for setting the axes ranges.
wait()
def plot_normalized_luminosity_ratio(detector_one_data, detector_two_data, style, run_name):
    '''

    :param detector_one_data: Data from one detector type, such as ATLAS' LUCID, in a list of lists, every entry is one
    luminsoity block, with the luminosity block being a list of BCID data, assumed to be same
    length as detector_two_data
    :param detector_two_data: Data from another detector type, such as ATLAS' LUCID, in a list of lists, every entry is
    one luminosity block, with the luminosity block being a list of BCID data, assumed to be same
    length as detector_one_data
    :param style: The ROOT style for the graph, generally 'ATLAS'
    :return: ROOT plots of the ratio of luminosities over the luminosity, normalized to one
    '''

    # Set ROOT graph style
    set_style(str(style))

    print("Number of Luminosity Blocks included: " + str(len(detector_one_data)))

    # Get ratio of the detectors
    luminosity_ratio = []
    lumi_blocks = []
    for block in range(len(detector_one_data)):
        for bcid in range(len(detector_one_data[block])):
            detector_one_point = detector_one_data[block][bcid]
            detector_two_point = detector_two_data[block][bcid]
            # Check if the blocks are zero
            if detector_one_point != 0.0 and detector_two_point != 0.0:
                ratio = -math.log(1 - detector_one_point) / -math.log(1 - detector_two_point)
                luminosity_ratio.append(ratio)
                lumi_blocks.append(block)

    # Normalize the ratios
    def normalize(x, x_min, x_max):
        top = x - x_min
        bottom = x_max - x_min
        return top / bottom

    max_ratio = max(luminosity_ratio)
    min_ratio = min(luminosity_ratio)
    print("Max ratio: " + str(max_ratio))
    print("Min Ratio: " + str(min_ratio))
    for ratio_entry in range(len(luminosity_ratio)):
        luminosity_ratio[ratio_entry] = normalize(luminosity_ratio[ratio_entry], x_max=max_ratio, x_min=min_ratio)

    # create graph
    graph = Graph(len(lumi_blocks), title=run_name)
    for i, (xx, yy) in enumerate(zip(lumi_blocks, luminosity_ratio)):
        graph.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph.markercolor = 'blue'
    graph.xaxis.SetTitle("Luminosity Block")
    graph.yaxis.SetTitle("Luminosity [Normalized Ratio]")
    graph.xaxis.SetRangeUser(min(lumi_blocks), max(lumi_blocks))
    graph.yaxis.SetRangeUser(min(luminosity_ratio), max(luminosity_ratio))

    # plot with ROOT
    canvas = Canvas()
    graph.Draw("AP")
    label = ROOT.TText(0.8, 0.9, str(run_name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
Example #26
0
def make2DLimitPlot(xtitle, xvals, yvals, obs, exp, exp1plus, exp1minus,
                    exp2plus, exp2minus, theory):
    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)

    axisTitleSize = 0.041
    axisTitleOffset = 1.2

    leftMargin = 0.15
    rightMargin = 0.18
    topMargin = 0.06
    bottomMargin = 0.14

    c1 = TCanvas("c1", "c1", 200, 10, 700, 600)
    c1.SetHighLightColor(2)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetBorderSize(2)
    c1.SetLeftMargin(leftMargin)
    c1.SetRightMargin(rightMargin)
    c1.SetTopMargin(topMargin)
    c1.SetBottomMargin(bottomMargin)
    c1.SetFrameBorderMode(0)
    c1.SetLogy(1)
    c1.SetLogx(0)
    c1.SetLogz(1)
    c1.SetTickx(1)
    c1.SetTicky(1)

    stops = np.array([0.00, 0.34, 0.61, 0.84, 1.00])
    red = np.array([0.50, 0.50, 1.00, 1.00, 1.00])
    green = np.array([0.50, 1.00, 1.00, 0.60, 0.50])
    blue = np.array([1.00, 1.00, 0.50, 0.40, 0.50])
    TColor.CreateGradientColorTable(len(stops), stops, red, green, blue, 255)
    gStyle.SetNumberContours(255)

    print "list of m1s:", xvals
    print "list of ys: ", yvals
    print "list of obs limits: ", obs

    widthx = sorted(xvals)[0] / 10
    widthy = sorted(yvals)[0] / 10

    lowXs = [xval - widthx / 2 for xval in xvals]
    highXs = [xval + widthx / 2 for xval in xvals]
    lowYs = [yval - widthy / 2 for yval in yvals]
    highYs = [yval + widthy / 2 for yval in yvals]
    binsX = sorted(list(dict.fromkeys(lowXs + highXs)))
    binsY = sorted(list(dict.fromkeys(lowYs + highYs)))
    binsX = [(binsX[i] + binsX[i + 1]) / 2 if i != len(binsX) - 1 else binsX[i]
             for i in range(1,
                            len(binsX) - 1, 2)]
    binsY = [(binsY[i] + binsY[i + 1]) / 2 if i != len(binsY) - 1 else binsY[i]
             for i in range(1,
                            len(binsY) - 1, 2)]
    binsX.insert(0, sorted(lowXs)[0])
    binsX.insert(len(binsX), sorted(highXs)[-1])
    binsY.insert(0, sorted(lowYs)[0])
    binsY.insert(len(binsY), sorted(highYs)[-1])

    print "binsX ", binsX
    print "binsY ", binsY

    obs_xsec = TH2D('', '',
                    len(binsX) - 1, array('d', binsX),
                    len(binsY) - 1, array('d', binsY))

    obs_xsec.GetXaxis().SetTitleSize(axisTitleSize)
    obs_xsec.GetXaxis().SetTitleOffset(axisTitleOffset - 0.2)
    obs_xsec.GetXaxis().SetTitle("m_{1} [GeV]")

    obs_xsec.GetYaxis().SetTitleSize(axisTitleSize)
    obs_xsec.GetYaxis().SetTitleOffset(axisTitleOffset + 0.1)
    obs_xsec.GetYaxis().SetTitle(
        "y = #epsilon^{2} #alpha_{D} (m_{1}/m_{A'})^{4}")
    #obs_xsec.GetYaxis().SetTitle("c#tau [cm]")

    obs_xsec.GetZaxis().SetTitleSize(axisTitleSize - 0.005)
    obs_xsec.GetZaxis().SetTitleOffset(axisTitleOffset + 0.1)
    obs_xsec.GetZaxis().SetTitle("#sigma_{95% CL} [pb]")

    obs_xsec.FillN(len(xvals), array('d', xvals), array('d', yvals),
                   array('d', obs))

    obs_xsec.GetZaxis().SetRangeUser(1e-4, 1e1)
    obs_xsec.Draw("COLZ")
    obs_xsec.Draw("TEXT SAME")

    obs_mu = [x / y for x, y in zip(obs, theory)]
    plotLimitBoundary(c1, xvals, yvals, obs_mu, [1, kBlack])
    #obs_mu_cont = obs_xsec.Clone()
    #obs_mu_cont.Reset()
    #obs_mu_cont.FillN(len(xvals), array('d', xvals), array('d', yvals), array('d', obs_mu))
    #obs_mu_cont.SetContour(1);
    #obs_mu_cont.SetContourLevel(0, 1);
    #obs_mu_cont.SetLineColor(kBlack);
    #obs_mu_cont.SetLineWidth(3);
    #obs_mu_cont.Draw("CONT3 SAME")

    exp_mu = [x / y for x, y in zip(exp, theory)]
    plotLimitBoundary(c1, xvals, yvals, exp_mu, [2, kRed])
    #exp_mu_cont = obs_xsec.Clone()
    #exp_mu_cont.Reset()
    #exp_mu_cont.FillN(len(xvals), array('d', xvals), array('d', yvals), array('d', exp_mu))
    #exp_mu_cont.SetContour(1);
    #exp_mu_cont.SetContourLevel(0, 1);
    #exp_mu_cont.SetLineColor(kRed);
    #exp_mu_cont.SetLineStyle(2);
    #exp_mu_cont.SetLineWidth(3);
    #exp_mu_cont.Draw("CONT3 SAME")

    CMS_lumi(c1, "106.71 fb^{-1} (13 TeV)", 0)

    #exp2sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
    #       array('d', [0]), array('d', [0]), array('d', exp2minus), array('d', exp2plus))
    #exp2sigma_xsec.Sort()
    #exp2sigma_xsec.Draw('A3')
    #exp2sigma_xsec.SetFillStyle(1001);
    #exp2sigma_xsec.SetFillColor(kOrange);
    #exp2sigma_xsec.SetLineColor(kOrange);
    #exp2sigma_xsec.GetYaxis().SetRangeUser(0.001,100);
    #exp2sigma_xsec.GetXaxis().SetLimits(0.8*min(xvals),1.1*max(xvals));
    ##exp2sigma_xsec.GetXaxis().SetTitle('m_{1} [GeV]')
    ##exp2sigma_xsec.GetXaxis().SetTitle('c#tau [cm]')
    #exp2sigma_xsec.GetXaxis().SetTitle(xtitle)
    #exp2sigma_xsec.GetYaxis().SetTitle('95% C.L. #sigma(pp #rightarrow #chi_{1} #chi_{1} #mu^{+} #mu_{-}) [pb]')

    #exp1sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
    #        array('d', [0]), array('d', [0]), array('d', exp1minus), array('d', exp1plus))
    #exp1sigma_xsec.Sort()
    #exp1sigma_xsec.SetFillStyle(1001);
    #exp1sigma_xsec.SetFillColor(kGreen+1);
    #exp1sigma_xsec.SetLineColor(kGreen+1);
    #exp1sigma_xsec.Draw('3 SAME')

    #exp_xsec = TGraph(len(xvals), array('d', xvals), array('d', exp))
    #exp_xsec.Sort()
    #exp_xsec.SetLineWidth(2)
    #exp_xsec.SetLineStyle(1)
    #exp_xsec.SetLineColor(kRed)
    #exp_xsec.Draw('C SAME')

    #obs_xsec = TGraph(len(xvals), array('d', xvals), array('d', obs))
    #obs_xsec.Sort()
    #obs_xsec.SetLineWidth(2)
    #obs_xsec.SetLineColor(kBlack)
    #obs_xsec.SetMarkerColor(kBlack)
    #obs_xsec.SetMarkerStyle(20)
    #obs_xsec.SetMarkerSize(1)
    #obs_xsec.Draw('PC SAME')

    #theory_xsec = TGraph(len(xvals), array('d', xvals), array('d', theory))
    #theory_xsec.Sort()
    #theory_xsec.SetLineWidth(2)
    #theory_xsec.SetLineStyle(8)
    #theory_xsec.SetLineColor(kBlue)
    #theory_xsec.Draw('C SAME')

    #leg = TLegend(0.50,0.65,0.8,0.85);
    #leg.SetBorderSize(0);
    #leg.SetFillStyle(0);
    #leg.AddEntry(theory_xsec, "Theory", "l");
    #leg.AddEntry(obs_xsec, "Observed Limit", "pl");
    #leg.AddEntry(exp_xsec, "Expected Limit", "l");
    #leg.AddEntry(exp1sigma_xsec, "#pm 1 std. dev.", "f");
    #leg.AddEntry(exp2sigma_xsec, "#pm 2 std. dev.", "f");
    #leg.Draw()

    # TCanvas.Update() draws the frame, after which one can change it
    # c1.Update()
    # c1.Modified()
    # c1.Update()

    c1.RedrawAxis()
    c1.Draw()

    wait(True)
def plot_all_integrated_luminosity(all_detector_one_data, all_detector_two_data, all_detector_three_data, block_length,
                                   bcid_status, background_list, style, name, detector_one_calibration,
                                   detector_two_calibration, detector_three_calibration):
    '''
    Take all the luminosity ratio for each luminosity block and multiply by the time to get the integrated luminosity
    :param all_detector_one_data: A dictionary of the run name to a list of lists of luminosity blocks
    :param all_detector_two_data: A dictionary of the run name to a list of lists of luminosity blocks
    :param block_length: A dictionary the same length as the detector arrays containing the luminosity block length (time)
    :param style: a string corresponding to a ROOT graphing style, e.g. 'ATLAS'
    :return: Plot of all the detector data on a graph chronologically according to run number
    '''
    # Set ROOT graph style
    set_style(str(style))

    # Get average value of the rate for each luminosity block
    temp_detector_one = copy.deepcopy(all_detector_one_data)
    temp_detector_two = copy.deepcopy(all_detector_two_data)
    temp_detector_three = copy.deepcopy(all_detector_three_data)
    print(sorted(all_detector_one_data.keys()))
    for run in sorted(all_detector_one_data.keys()):
        block_count = 0
        for block in range(len(all_detector_one_data.get(run)) - 1):
            del temp_detector_one.get(run)[block][:]
            del temp_detector_two.get(run)[block][:]
            del temp_detector_three.get(run)[block][:]
            block_count += 1
            detector_one_avg = 0
            one_count = 0
            detector_two_avg = 0
            two_count = 0
            detector_three_avg = 0
            three_count = 0
            for bcid in range(len(all_detector_one_data.get(run)[block])):
                # Gets the previous BCID luminosity to subtract as the background
                if run in background_list:
                    if bcid_status.get(run)[block][bcid - 1] == 0:
                        detector_one_point_background = all_detector_one_data.get(run)[block][bcid - 1]
                        detector_two_point_background = all_detector_two_data.get(run)[block][bcid - 1]
                        detector_three_point_background = all_detector_three_data.get(run)[block][bcid - 1]
                        print("BCID [N-1] Stability: " + str(bcid_status.get(run)[block][bcid - 1]))
                        print("BCID [N] Stability: " + str(bcid_status.get(run)[block][bcid]))
                        detector_one_point = -math.log(1 - all_detector_one_data.get(run)[block][bcid]) \
                                             + math.log(1 - detector_one_point_background)
                        print("Detector 1 Point: " + str(detector_one_point))
                        detector_two_point = -math.log(1 - all_detector_two_data.get(run)[block][bcid]) \
                                             + math.log(1 - detector_two_point_background)
                        print("Detector 2 Point: " + str(detector_two_point))
                        detector_three_point = -math.log(1 - all_detector_three_data.get(run)[block][bcid]) \
                                               + math.log(1 - detector_three_point_background)
                        detector_one_avg += detector_one_point
                        one_count += 1
                        detector_two_avg += detector_two_point
                        two_count += 1
                        detector_three_avg += detector_three_point
                        three_count += 1
                    else:
                        print("No empty BCID to subtract background from")
                        '''
                        print("BCID [N] Stability: " + str(bcid_status.get(run)[block][bcid]))
                        detector_one_point = -math.log(1 - all_detector_one_data.get(run)[block][bcid]) #\
                                             #+ math.log(1 - detector_one_point_background)
                        print("Detector 1 Point: " + str(detector_one_point))
                        detector_two_point = -math.log(1 - all_detector_two_data.get(run)[block][bcid]) #\
                                             #+ math.log(1 - detector_two_point_background)
                        print("Detector 2 Point: " + str(detector_two_point))
                        detector_three_point = -math.log(1 - all_detector_three_data.get(run)[block][bcid]) #\
                                               #+ math.log(1 - detector_three_point_background)
                        detector_one_avg += detector_one_point
                        one_count += 1
                        detector_two_avg += detector_two_point
                        two_count += 1
                        detector_three_avg += detector_three_point
                        three_count += 1
                        '''
                if bcid_status.get(run)[block][bcid] > 0.0:
                    detector_one_point = -math.log(1 - all_detector_one_data.get(run)[block][bcid])
                    detector_two_point = -math.log(1 - all_detector_two_data.get(run)[block][bcid])
                    detector_three_point = -math.log(1 - all_detector_three_data.get(run)[block][bcid])
                    detector_one_avg += detector_one_point
                    one_count += 1
                    detector_two_avg += detector_two_point
                    two_count += 1
                    detector_three_avg += detector_three_point
                    three_count += 1
            if one_count != 0:
                detector_one_avg = detector_one_avg / one_count
                detector_two_avg = detector_two_avg / two_count
                detector_three_avg = detector_three_avg / three_count
                temp_detector_one.get(run)[block_count - 1].append(detector_one_avg)
                temp_detector_two.get(run)[block_count - 1].append(detector_two_avg)
                temp_detector_three.get(run)[block_count - 1].append(detector_three_avg)
        # Remove the last luminosity block from each run, the one that generally spikes
        temp_detector_one[run] = temp_detector_one[run][:-10]
        temp_detector_two[run] = temp_detector_two[run][:-10]
        temp_detector_three[run] = temp_detector_three[run][:-10]
    # Reassign temp to the original lists
    all_detector_one_data = temp_detector_one
    all_detector_two_data = temp_detector_two
    all_detector_three_data = temp_detector_three

    # Get integrated luminosity of the detectors
    integrated_luminosity_one = []
    integrated_luminosity_two = []
    integrated_luminosity_three = []
    luminosity_ratio_two = []
    luminosity_ratio_three = []
    lumi_blocks = []
    block_count1 = 0
    lumi_total = 0
    lumi_total_two = 0
    lumi_total_three = 0
    # To keep track of how long each run actually is when plotting
    run_length_dict = {}
    for run in sorted(all_detector_one_data.keys()):
        run_length_dict[run] = 0
        for block in range(len(all_detector_one_data.get(run))):
            block_count1 += 1
            for bcid in range(len(all_detector_one_data.get(run)[block])):
                detector_one_point = all_detector_one_data.get(run)[block][bcid]
                detector_two_point = all_detector_two_data.get(run)[block][bcid]
                detector_three_point = all_detector_three_data.get(run)[block][bcid]
                if detector_one_point != 0.0 and detector_two_point != 0.0 and detector_three_point != 0.0:
                    # Use conversion factor
                    converted_point_one = convert_to_raw_luminosity(11.245, 20.8, detector_one_point)
                    converted_point_two = convert_to_raw_luminosity(11.245, 20.8, detector_two_point)
                    converted_point_three = convert_to_raw_luminosity(11.245, 20.8, detector_three_point)
                    ratio_one_two = converted_point_one / converted_point_two
                    ratio_one_three = converted_point_one / converted_point_three
                    luminosity_ratio_two.append(ratio_one_two)
                    luminosity_ratio_three.append(ratio_one_three)
                    length = block_length.get(run)[block][bcid]
                    lumi_total += converted_point_one * length
                    lumi_total_two += converted_point_two * length
                    lumi_total_three += converted_point_three * length
                    integrated_luminosity_one.append(lumi_total)
                    integrated_luminosity_two.append(lumi_total_two)
                    integrated_luminosity_three.append(lumi_total_three)
                    lumi_blocks.append(block_count1)
                    run_length_dict[run] += 1

    # Get percentage difference based off the first block and BCID
    first_point = detector_one_calibration / detector_two_calibration
    third_point = detector_one_calibration / detector_three_calibration

    for index in range(len(integrated_luminosity_one)):
        luminosity_ratio_two[index] = 100 * ((luminosity_ratio_two[index] / first_point) - 1)
        luminosity_ratio_three[index] = 100 * ((luminosity_ratio_three[index] / third_point) - 1)

    # create graph
    graph = Graph(len(integrated_luminosity_one))
    for i, (xx, yy) in enumerate(zip(integrated_luminosity_one, luminosity_ratio_two)):
        graph.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    # Set temp list for the min and max functions
    luminosity_ratio = luminosity_ratio_two + luminosity_ratio_three
    integrated_luminosity = integrated_luminosity_one
    #integrated_luminosity = lumi_blocks

    graph.markercolor = 'blue'
    graph.yaxis.SetTitle("Luminosity Ratio [Percent]")
    graph.xaxis.SetTitle("Luminosity [Integrated]")
    graph.yaxis.SetRangeUser(min(luminosity_ratio),
                             max(luminosity_ratio))
    graph.xaxis.SetRangeUser(min(integrated_luminosity),
                             max(integrated_luminosity))

    # plot with ROOT
    canvas = Canvas()

    graph.Draw("AP")
    canvas.Update()

    # add points from detectors 1 and 3
    # create graph
    graph1 = Graph(len(integrated_luminosity))
    for i, (xx, yy) in enumerate(zip(integrated_luminosity, luminosity_ratio_three)):
        graph1.SetPoint(i, float(xx), float(yy))

    # set visual attributes

    graph1.linecolor = 'white'  # Hides the lines at this time
    graph1.markercolor = 'red'

    graph1.Draw("P")
    canvas.Update()
    # Draw lines for different runs
    run_length = 0
    total_length = 0
    num_run = 0
    print"Integrated Luminosity length: ",len(integrated_luminosity)
    for run in sorted(all_detector_one_data.keys()):
        print str(run)
        total_length += run_length_dict[run]
        print"Total Length: ",total_length
        #run_length = integrated_luminosity[total_length - 1]
        print"Run Length", run_length
        line = ROOT.TLine(run_length, min(luminosity_ratio),
                          run_length, max(luminosity_ratio))
        line.Draw()
        line_label = ROOT.TText(run_length - 30, max(luminosity_ratio) - 1.5, str(run))
        line_label.SetTextAngle(90)
        line_label.SetTextSize(18)
        line_label.SetTextFont(43)
        line_label.Draw()
    label = ROOT.TText(0.2, 0.9, str(name))
    label.SetTextFont(43)
    label.SetTextSize(25)
    label.SetNDC()
    label.Draw()
    canvas.Modified()
    canvas.Update()
    wait(True)
def extract_JetBTag(f_tt, f_qcd, f_wjet):

    # get trees from files
    t_tt = f_tt.Get("Delphes")
    t_qcd = f_qcd.Get("Delphes")
    t_wjet = f_wjet.Get("Delphes")

    # get number of entries
    tt_n_entries = t_tt.GetEntries()
    qcd_n_entries = t_qcd.GetEntries()
    wjet_n_entries = t_wjet.GetEntries()

    # define leaves
    var_tt = "Jet.BTag"
    var_qcd = "Jet.BTag"
    var_wjet = "Jet.BTag"

    leaf_tt = t_tt.GetLeaf(var_tt)
    leaf_qcd = t_qcd.GetLeaf(var_qcd)
    leaf_wjet = t_wjet.GetLeaf(var_wjet)

    # create the histograms
    loose_tt = Hist(NBINS, NLO, NHI, title='loose_tt', legendstyle='L')
    medium_tt = Hist(NBINS, NLO, NHI, title='medium_tt', legendstyle='L')
    tight_tt = Hist(NBINS, NLO, NHI, title='tight_tt', legendstyle='L')

    loose_qcd = Hist(NBINS, NLO, NHI, title='loose_qcd', legendstyle='L')
    medium_qcd = Hist(NBINS, NLO, NHI, title='medium_qcd', legendstyle='L')
    tight_qcd = Hist(NBINS, NLO, NHI, title='tight_qcd', legendstyle='L')

    loose_wjet = Hist(NBINS, NLO, NHI, title='loose_wjet', legendstyle='L')
    medium_wjet = Hist(NBINS, NLO, NHI, title='medium_wjet', legendstyle='L')
    tight_wjet = Hist(NBINS, NLO, NHI, title='tight_wjet', legendstyle='L')

    # FILLING THE TREE
    fill_JetBTag_tree(tt_n_entries, t_tt, leaf_tt, loose_tt, medium_tt,
                      tight_tt)
    fill_JetBTag_tree(qcd_n_entries, t_qcd, leaf_qcd, loose_qcd, medium_qcd,
                      tight_qcd)
    fill_JetBTag_tree(wjet_n_entries, t_wjet, leaf_wjet, loose_wjet,
                      medium_wjet, tight_wjet)

    #set line colors
    loose_tt.SetLineColor('blue')
    medium_tt.SetLineColor('green')
    tight_tt.SetLineColor('red')

    loose_qcd.SetLineColor('blue')
    medium_qcd.SetLineColor('green')
    tight_qcd.SetLineColor('red')

    loose_wjet.SetLineColor('blue')
    medium_wjet.SetLineColor('green')
    tight_wjet.SetLineColor('red')

    #begin drawing stuff
    c1 = Canvas()
    tight_tt.SetStats(0)
    tight_tt.Draw('HIST')
    medium_tt.Draw('HIST SAME')
    loose_tt.Draw('HIST SAME')

    #make legend
    l1 = Legend([tight_tt, medium_tt, loose_tt], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("../plots/JetBTag_plots/btag_tt.pdf")

    c2 = Canvas()
    tight_qcd.SetStats(0)
    tight_qcd.Draw('HIST')
    medium_qcd.Draw('HIST SAME')
    loose_qcd.Draw('HIST SAME')

    #make legend
    l2 = Legend([tight_qcd, medium_qcd, loose_qcd], textfont=42, textsize=.03)
    l2.Draw()

    #save as pdf
    c2.SaveAs("../plots/JetBTag_plots/btag_qcd.pdf")

    c3 = Canvas()
    tight_wjet.SetStats(0)
    tight_wjet.Draw('HIST')
    medium_wjet.Draw('HIST SAME')
    loose_wjet.Draw('HIST SAME')

    #make legend
    l3 = Legend([tight_wjet, medium_wjet, loose_wjet],
                textfont=42,
                textsize=.03)
    l3.Draw()

    #save as pdf
    c3.SaveAs("../plots/JetBTag_plots/btag_wjet.pdf")

    wait(True)
def make1DLimitPlot(xtitle, xvals, obs, exp, exp1plus, exp1minus, exp2plus,
                    exp2minus, theory, alphaD, xvar):
    gStyle.SetOptTitle(0)

    axisTitleSize = 0.041
    axisTitleOffset = 1.2
    axisTitleSizeRatioX = 0.18
    axisLabelSizeRatioX = 0.12
    axisTitleOffsetRatioX = 0.94
    axisTitleSizeRatioY = 0.15
    axisLabelSizeRatioY = 0.108
    axisTitleOffsetRatioY = 0.32

    leftMargin = 0.15
    rightMargin = 0.12
    topMargin = 0.05
    bottomMargin = 0.14
    bottomMargin2 = 0.22

    #c1 = TCanvas() #'c1', '', 200, 10, 700, 500 )
    c1 = TCanvas("c1", "c2", 200, 10, 700, 600)

    c1.SetHighLightColor(2)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetBorderSize(2)
    c1.SetLeftMargin(leftMargin)
    c1.SetRightMargin(rightMargin)
    c1.SetTopMargin(topMargin)
    c1.SetBottomMargin(bottomMargin)
    c1.SetFrameBorderMode(0)
    c1.SetFrameBorderMode(0)
    c1.SetLogy(1)
    #c1.SetLogx(1)
    c1.SetTickx(1)
    c1.SetTicky(1)
    #c1.SetGridx(True);
    #c1.SetGridy(True);
    if "c#tau" in xtitle:
        c1.SetLogx(1)

    exp2sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
           array('d', [0]), array('d', [0]), array('d', exp2minus), array('d', exp2plus))
    exp2sigma_xsec.Sort()
    exp2sigma_xsec.Draw('A3')
    exp2sigma_xsec.SetFillStyle(1001)
    exp2sigma_xsec.SetFillColor(kOrange)
    exp2sigma_xsec.SetLineColor(kOrange)
    exp2sigma_xsec.GetYaxis().SetRangeUser(1e-4, 1e3)
    if xvar == 'mass':
        exp2sigma_xsec.GetXaxis().SetLimits(1, 80)
    elif xvar == 'ctau':
        exp2sigma_xsec.GetXaxis().SetLimits(0.1, 100)
    else:
        exp2sigma_xsec.GetXaxis().SetLimits(0.8 * min(xvals), 1.1 * max(xvals))
    #exp2sigma_xsec.GetXaxis().SetTitle('m_{1} [GeV]')
    #exp2sigma_xsec.GetXaxis().SetTitle('c#tau [cm]')
    exp2sigma_xsec.GetXaxis().SetTitle(xtitle)
    exp2sigma_xsec.GetXaxis().SetTitleOffset(axisTitleOffset)
    exp2sigma_xsec.GetYaxis().SetTitle(
        "#sigma_{95% CL} Br(A' #rightarrow #mu#mu) [pb]")
    exp2sigma_xsec.GetYaxis().SetTitleOffset(axisTitleOffset + 0.1)

    exp1sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
            array('d', [0]), array('d', [0]), array('d', exp1minus), array('d', exp1plus))
    exp1sigma_xsec.Sort()
    exp1sigma_xsec.SetFillStyle(1001)
    exp1sigma_xsec.SetFillColor(kGreen + 1)
    exp1sigma_xsec.SetLineColor(kGreen + 1)
    exp1sigma_xsec.Draw('3 SAME')

    exp_xsec = TGraph(len(xvals), array('d', xvals), array('d', exp))
    exp_xsec.Sort()
    exp_xsec.SetLineWidth(2)
    exp_xsec.SetLineStyle(1)
    exp_xsec.SetLineColor(kRed)
    exp_xsec.Draw('C SAME')

    obs_xsec = TGraph(len(xvals), array('d', xvals), array('d', obs))
    obs_xsec.Sort()
    obs_xsec.SetLineWidth(3)
    obs_xsec.SetLineColor(kBlack)
    obs_xsec.SetMarkerColor(kBlack)
    obs_xsec.SetMarkerStyle(20)
    obs_xsec.SetMarkerSize(1)
    obs_xsec.Draw('PC SAME')

    theory_xsec = TGraph(len(xvals), array('d', xvals), array('d', theory))
    theory_xsec.Sort()
    theory_xsec.SetLineWidth(2)
    theory_xsec.SetLineStyle(8)
    theory_xsec.SetLineColor(kBlue)
    theory_xsec.Draw('C SAME')

    leg = TLegend(0.50, 0.70, 0.8, 0.90)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.AddEntry(theory_xsec, "Theory", "l")
    leg.AddEntry(obs_xsec, "Observed Limit", "pl")
    leg.AddEntry(exp_xsec, "Expected Limit", "l")
    leg.AddEntry(exp1sigma_xsec, "#pm 1 std. dev.", "f")
    leg.AddEntry(exp2sigma_xsec, "#pm 2 std. dev.", "f")
    leg.Draw()

    drawCMSLogo(c1, 13, 122450)

    if alphaD != '':
        aDtext = TLatex()
        #baseSize = 25
        aDtext.SetNDC()
        aDtext.SetTextAngle(0)
        aDtext.SetTextColor(1)
        #aDtext.SetTextFont(61)
        #aDtext.SetTextAlign(11)
        aDtext.SetTextSize(0.0375)
        aDtext.DrawLatex(0.7, 0.9, "#alpha_{D} = " + alphaD)

    # TCanvas.Update() draws the frame, after which one can change it
    # c1.Update()
    # c1.Modified()
    # c1.Update()

    c1.RedrawAxis()
    c1.Draw()

    wait(True)
def extract_Electron(f_tt, f_qcd, f_wjet):
    
    # get trees from files
    t_tt = f_tt.Get("Delphes")
    t_qcd = f_qcd.Get("Delphes")
    t_wjet = f_wjet.Get("Delphes")
    
    # get number of entries
    tt_n_entries = t_tt.GetEntries()
    qcd_n_entries = t_qcd.GetEntries()
    wjet_n_entries = t_wjet.GetEntries()
    
    # define leaves
    var_tt = "Electron.PT"
    var_qcd = "Electron.PT"
    var_wjet = "Electron.PT"
    
    leaf_tt = t_tt.GetLeaf(var_tt)
    leaf_qcd = t_qcd.GetLeaf(var_qcd)
    leaf_wjet = t_wjet.GetLeaf(var_wjet)
   
    
    # create the histograms
    numElectrons_tt = Hist(NBINS,NLO,NHI, title = 'numElectrons_tt', legendstyle = 'L')
    numElectrons_qcd = Hist(NBINS,NLO,NHI, title = 'numElectrons_qcd', legendstyle = 'L')
    numElectrons_wjet = Hist(NBINS,NLO,NHI, title = 'numElectrons_wjet', legendstyle = 'L')
    
    # interesting values to plot
    max_ept_per_event_tt = Hist(PT_NBINS,PT_NLO,PT_NHI, title = 'Max ElectronPT/Event tt', legendstyle = 'L')
    min_ept_per_event_tt = Hist(PT_NBINS,PT_NLO,PT_NHI, title = 'Min ElectronPT/Event tt', legendstyle = 'L')
    
    max_ept_per_event_qcd = Hist(PT_NBINS,PT_NLO,PT_NHI, title = 'Max ElectronPT/Event qcd', legendstyle = 'L')
    min_ept_per_event_qcd = Hist(PT_NBINS,PT_NLO,PT_NHI, title = 'Min ElectronPT/Event qcd', legendstyle = 'L')
    
    max_ept_per_event_wjet = Hist(PT_NBINS,PT_NLO,PT_NHI, title = 'Max ElectronPT/Event wjet', legendstyle = 'L')
    min_ept_per_event_wjet = Hist(PT_NBINS,PT_NLO,PT_NHI, title = 'Min ElectronPT/Event wjet', legendstyle = 'L')

   
    # FILLING THE TREE
    fill_Electron_tree(tt_n_entries, t_tt, leaf_tt, numElectrons_tt, min_ept_per_event_tt, max_ept_per_event_tt)
    fill_Electron_tree(qcd_n_entries, t_qcd, leaf_qcd, numElectrons_qcd, min_ept_per_event_qcd, max_ept_per_event_qcd)
    fill_Electron_tree(wjet_n_entries, t_wjet, leaf_wjet, numElectrons_wjet, min_ept_per_event_wjet, max_ept_per_event_wjet)
    
    #set line colors
    numElectrons_tt.SetLineColor('blue')
    numElectrons_qcd.SetLineColor('green')
    numElectrons_wjet.SetLineColor('red')
       
    
    #begin drawing stuff
    c1 = Canvas()
    numElectrons_wjet.SetStats(0)
    numElectrons_wjet.Draw('HIST')
    numElectrons_tt.Draw('HIST SAME')
    numElectrons_qcd.Draw('HIST SAME')
    
    
    #make legend
    l1 = Legend([numElectrons_tt, numElectrons_qcd, numElectrons_wjet], textfont = 42, textsize = .03)
    l1.Draw()
    
    #save as pdf
    c1.SaveAs("../plots/ElectronPT_plots/numElectrons.pdf");
    
    
    
    ################ MIN MAX STUFF
    
    # TT
    
    #set line colors
    max_ept_per_event_tt.SetLineColor('blue')
    min_ept_per_event_tt.SetLineColor('green')  
    
    #begin drawing stuff
    c2 = Canvas()
    min_ept_per_event_tt.SetStats(0)
    min_ept_per_event_tt.Draw('HIST')
    max_ept_per_event_tt.Draw('HIST SAME')
    
    #make legend
    l2 = Legend([min_ept_per_event_tt, max_ept_per_event_tt], textfont = 42, textsize = .03)
    l2.Draw()
    
    #save as pdf
    c2.SaveAs("../plots/ElectronPT_plots/e_maxminpt_tt.pdf")
    
    # QCD
    
    #set line colors
    max_ept_per_event_qcd.SetLineColor('blue')
    min_ept_per_event_qcd.SetLineColor('green')  
    
    #begin drawing stuff
    c3 = Canvas()
    
    max_ept_per_event_qcd.SetStats(0)
    max_ept_per_event_qcd.Draw('HIST')
    min_ept_per_event_qcd.Draw('HIST SAME')
    
    #make legend
    l3 = Legend([min_ept_per_event_qcd, max_ept_per_event_qcd], textfont = 42, textsize = .03)
    l3.Draw()

    #save as pdf
    c3.SaveAs("../plots/ElectronPT_plots/e_maxminpt_qcd.pdf")



    #WJET
    #set line colors
    max_ept_per_event_wjet.SetLineColor('blue')
    min_ept_per_event_wjet.SetLineColor('green')  
    
    #begin drawing stuff
    c4 = Canvas()
    
    min_ept_per_event_wjet.SetStats(0)
    min_ept_per_event_wjet.Draw('HIST')
    max_ept_per_event_wjet.Draw('HIST SAME')
    
    #make legend
    l4 = Legend([min_ept_per_event_wjet, max_ept_per_event_wjet], textfont = 42, textsize = .03)
    l4.Draw()
    
    #save as pdf
    c4.SaveAs("../plots/ElectronPT_plots/e_maxminpt_wjet.pdf")
    
    
    #make the plots wait on screen
    wait(True)
NModel  = "CFG"
#NModel  = "CFGnBack"
#NModel = "CFGnForward"

nuFlux = "Ev from mcc6"
#nuFlux = "monochromatic neutrino 300 MeV"

Path = "/Users/erezcohen/Desktop/uboone/AnaFiles/"



PpPmuMin = [0   , 400 , 600 , 800 ]
PpPmuMax = [400 , 600 , 800 , 3000]
hEflux   = []
for i in range(0,len(PpPmuMin)):
    hEflux.append(analysis.GetHistoFromAFile("/Users/erezcohen/Desktop/uBoone/SpecialAttention/Data/MCC6recEventsEv.root"
                                        , "hEflux_%dPpPlusPmu%d"%(int(PpPmuMin[i]),int(PpPmuMax[i]))))
    OutFile = ROOT.TFile(Path+"CCinteractions"+NModel+"_%d_PpPmu_%d"%(int(PpPmuMin[i]),int(PpPmuMax[i]))+".root","recreate")
    OutTree = ROOT.TTree("anaTree","nu-n QE" + "("+NModel + ")" + ", " + "%.0f<p(p)+p(#mu)<%.0f MeV/c )"%(int(PpPmuMin[i]),int(PpPmuMax[i])))
    nuNCC   = EnuNCC( OutTree )
    nuNCC.ImpXsecGraph("/Users/erezcohen/Desktop/uboone/SpecialAttention/Data/Xsec.dat" , 70 , DoDraw )    # v-n cross section [A. Schukraft]
    if (DoDraw) : wait()
    nuNCC.ImpMomentumDist( DoDraw )    # neutron momentum distribution
    if (DoDraw) : wait()
    nuNCC.ImpEfluxHisto( hEflux[i] ,  DoDraw) #nuNCC.ImpEfluxGraph( "/Users/erezcohen/Desktop/uboone/SpecialAttention/Data/Eflux.dat" , 166 ,  DoDraw )    # BNB energy flux at uboone
    if (DoDraw) : wait()
    nuNCC.RunInteractions( NModel , nuFlux , 100000 , False )       # run interactions and fill output tree
    print "done filling %d events " % OutTree.GetEntries() + "in " + OutTree.GetTitle()
    OutTree.Write()
    OutFile.Close()
Example #32
0
import time
ROOT.gStyle.SetOptStat(0000)
ROOT.gStyle.SetOptFit(1111)



AnalysisType = "F1/F2 from paper"


dirfmt = "~/Desktop/%4d-%02d-%02d"
dirname = dirfmt % time.localtime()[0:3]
try:
    os.makedirs(dirname)
except OSError, e:
    if e.errno != 17:
        raise # This was not a "directory exist" error..


if AnalysisType == "F1/F2 from paper":
    anaF1 = TPlots("/Users/erezcohen/Desktop/MAINZ/Software/MediumModifications/F1P_Solid.root","ntuple","F1")
    anaF2 = TPlots("/Users/erezcohen/Desktop/MAINZ/Software/MediumModifications/F2P_Solid.root","ntuple","F2")
    c = anaF1.CreateCanvas("F1 and F2","Divide",2,1)
    c.cd(1)
    hF1 = anaF1.H2("q2","f",ROOT.TCut(),"",100,0.1,0.9,100,0,2.0,"F1","Q^{2}  (GeV/c) ^{2}","F _{1}")
    hF1.Fit("pol9","","R",0.133,0.88)
    c.cd(2)
    hF2 = anaF2.H2("q2","f",ROOT.TCut(),"",100,0.1,0.9,100,0,2.0,"F2","Q^{2} (GeV/c) ^{2}","F _{2}")
    hF2.Fit("pol9","","R",0.2,0.88)
    c.Update()
    wait()
    c.SaveAs(dirname+"/F1F2.pdf")
Example #33
0
def fitbin(wbin, q2bin):
    # get bin center and edges
    vals = ibins2vals(wbin, q2bin)
    (wval, wlo, whi) = (vals[0][0], vals[0][1], vals[0][2])
    (q2val, q2lo, q2hi) = (vals[1][0], vals[1][1], vals[1][2])
    record = {'W': wval, 'Wlo': wlo, 'Whi': whi, 'Wbin': wbin,
              'Q2': q2val, 'Q2lo': q2lo, 'Q2hi': q2hi, 'Q2bin': q2bin}

    # get MMp mass distribution for current W/Q2 bin
    h = asrootpy(hmmp(wbin, q2bin, vals))

    # fit the background
    fbg = fitbg(h)
    record['fbgstat'] = r.gMinuit.fCstatu
    for ipar in range(0, fbg.GetNpar()):
        record['fbgpar%d' % ipar] = fbg.GetParameter(ipar)

    # subtract background fit function
    hsig = asrootpy(h.Clone('%s_hsig' % h.GetName()))
    hsig.Add(fbg, -1)

    # fit signal
    fsig = fitsig(hsig)
    record['fsigstat'] = r.gMinuit.fCstatu
    for ipar in range(0, fsig.GetNpar()):
        record['fsigpar%d' % ipar] = fsig.GetParameter(ipar)

    # get signal boundaries and integral correction factor
    gm = fsig.GetParameter(1)
    gs = fsig.GetParameter(2)
    mmplo, mmphi = gm-cutsigma*gs, gm+cutsigma*gs
    mmpbinlo, mmpbinhi = h.FindBin(mmplo), h.FindBin(mmphi)
    mmplo, mmphi = h.GetBinLowEdge(mmpbinlo), h.GetBinLowEdge(mmpbinhi+1)
    intfull = fsig.Integral(*fitrange)
    int3s = fsig.Integral(mmplo, mmphi)
    hsigint = hsig.Integral(mmpbinlo, mmpbinhi)
    weight3s = int3s/intfull if intfull > 0 else -1
    record['hsigint3s'] = hsigint
    record['weight3s'] = weight3s

    # define signal/sideband edges and sideband weight factor
    vedges = (fitrange[0], mmplo, mmphi, fitrange[1])
    iedges = (1, mmpbinlo, mmpbinhi, h.GetNbinsX())
    intsig = fbg.Integral(vedges[1], vedges[2])
    intsb1 = h.Integral(iedges[0], iedges[1]-1, 'width')
    intsb2 = h.Integral(iedges[2]+1, iedges[3], 'width')
    weightsb = intsig/(intsb1+intsb2) if intsb1+intsb2 > 0 else -1
    record['weightsb'] = weightsb

    # draw canvas
    cmmp = Canvas(name='bgsigfit_%d_%d' % (round(1000*wval), round(1000*q2val)),
                  title='MMp Fits, W, Q2 = %.3f GeV,%.3f GeV2' % (wval, q2val))
    hs = r.THStack('hs_%d_%d' % (round(1000*wval), round(1000*q2val)),
                   hstitle % (wlo, whi, q2lo, q2hi))
    hsig.SetColor('blue')
    hsig.GetListOfFunctions().FindObject('fsig').SetLineColor(r.kBlue)
    hs.Add(hsig)
    hs.Add(h)
    hs.Draw('nostack')
    r.gPad.Update()
    hs.GetHistogram().GetXaxis().SetTitle(h.GetXaxis().GetTitle())
    hs.GetHistogram().GetYaxis().SetTitle('yield')
    chi2sig, ndfsig = fsig.GetChisquare(), fsig.GetNDF()
    rchi2sig = chi2sig/ndfsig if ndfsig > 0 else -1
    record['fsigchi2'] = rchi2sig
    chi2bg, ndfbg = fbg.GetChisquare(), fbg.GetNDF()
    rchi2bg = chi2bg/ndfbg if ndfbg > 0 else -1
    record['fbgchi2'] = rchi2bg
    ylo, yhi = r.gPad.GetUymin(), r.gPad.GetUymax()
    xlo, xhi = r.gPad.GetUxmin(), r.gPad.GetUxmax()
    for l in [r.TLine(mmplo, ylo, mmplo, yhi), r.TLine(mmphi, ylo, mmphi, yhi)]:
        hsig.GetListOfFunctions().Add(l)
        l.SetLineColor(r.kBlue)
    yscale = yhi-ylo
    xscale = xhi-xlo
    tchi2 = r.TLatex(xlo+tchi2posX*xscale, ylo+tchi2posY*yscale, tchi2str % (chi2sig, ndfsig, rchi2sig))
    tchi2.Draw()
    r.gPad.Update()
    cmmp.SaveAs('out/%s.pdf' % cmmp.GetName())

    # output
    for (k, v) in record.items():
        if isinstance(v, float):
            record[k] = '%.5f' % v if k.startswith('fsig') else '%.3f' % v
        if isinstance(v, basestring):
            record[k] = '\"%s\"' % v
    for i, k in enumerate(keyorder):
        if i > 0:
            foutrecs.write(',')
        foutrecs.write(str(record[k]))

    wait()
    return (iedges, vedges, [weightsb, weight3s])