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)
Beispiel #2
0
def plotSummary(name, closure, xmin=0, xmax=1, xTitle='m_{vis} [GeV]'):
    histoSmoothRatios = []
    for hname, graph in closure.data['True/Est'].items():
        if 'Histo' in hname and 'Smooth' in hname and not 'Error' in hname:
            histoSmoothRatios.append(graph)
    ################ Plot ratios
    histoDummyRatio = Hist(1, xmin, xmax, type='F')
    values = []
    for ratio in histoSmoothRatios:
        for p in xrange(ratio.GetN()):
            values.append(ratio.GetY()[p])
    maxi = max(values)
    mini = min(values)
    maxi = maxi * 1.1 if maxi > 0 else maxi * 0.9
    mini = mini * 1.1 if mini < 0 else mini * 0.9
    histoDummyRatio.SetAxisRange(mini, maxi, 'Y')
    ##
    for ratio in histoSmoothRatios:
        ratio.SetLineColor(ROOT.kGray + 3)
        ratio.SetLineWidth(1)
    ##
    canvasRatio = Canvas(800, 800)
    canvasRatio.SetName('Ratio_Summary_Canvas')
    histoDummyRatio.SetXTitle(xTitle)
    histoDummyRatio.SetYTitle('Ratio')
    histoDummyRatio.Draw()
    for ratio in histoSmoothRatios:
        ratio.Draw('l same')
    canvasRatio.Print(
        'results/{NAME}_NonClosure_Ratio_Summary.png'.format(NAME=name))
Beispiel #3
0
    def __init__(self, width=None, height=None,
                 xtitle=None, ytitle=None,
                 tick_length=15,
                 logy=False):

        super(SimplePlot, self).__init__(width=width, height=height)
        left, right, bottom, top = self.margin
        self.SetMargin(0, 0, 0, 0)

        # top pad for histograms
        with self:
            main = Pad(0., 0., 1., 1.)
            if logy:
                main.SetLogy()
            main.margin = (left, right, bottom, top)
            main.Draw()

        # draw axes
        with main:
            main_hist = Hist(1, 0, 1)
            main_hist.Draw('AXIS')

        if xtitle is not None:
            main_hist.xaxis.title = xtitle
        if ytitle is not None:
            main_hist.yaxis.title = ytitle

        # set the tick lengths
        tick_length_pixels(main, main_hist.xaxis, main_hist.yaxis,
                           tick_length)

        self.main = main
        self.main_hist = main_hist
        self.logy = logy
Beispiel #4
0
def plotResults(variable, data, templates, results):

    resCan = Canvas()
    leg = Legend(nTemplates + 2)

    data.Draw('PE')
    leg.AddEntry(data, style='LEP')
    nBins = len(inputTemplates[variable]['data'][whichBinFromFile])
    h_tSumAfter = Hist(nBins, 0, nBins, title='after_' + variable)

    if useT1:
        plotTemplateAfter(templates[tNames['t1']], results[tNames['t1']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT2:
        plotTemplateAfter(templates[tNames['t2']], results[tNames['t2']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT3:
        plotTemplateAfter(templates[tNames['t3']], results[tNames['t3']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT4:
        plotTemplateAfter(templates[tNames['t4']], results[tNames['t4']][0],
                          resCan, leg, h_tSumAfter)
        pass
    leg.Draw()

    h_tSumAfter.SetLineColor(2)
    h_tSumAfter.SetLineStyle(7)
    h_tSumAfter.SetMarkerSize(0)
    h_tSumAfter.Draw('SAME HIST')
    resCan.Update()

    return resCan, h_tSumAfter
def checkOnMC(unfolding, method):
    global bins, nbins
    RooUnfold.SVD_n_toy = 1000
    pulls = []
    for sub in range(1,9):
        inputFile2 = File('../data/unfolding_merged_sub%d.root' % sub, 'read')
        h_data = asrootpy(inputFile2.unfoldingAnalyserElectronChannel.measured.Rebin(nbins, 'measured', bins))
        nEvents = inputFile2.EventFilter.EventCounter.GetBinContent(1)
        lumiweight = 164.5 * 5050 / nEvents
#        print sub, nEvents
        h_data.Scale(lumiweight)
        doUnfoldingSequence(unfolding, h_data, method, '_sub%d' %sub)
        pull = unfolding.pull_inputErrorOnly()
#        unfolding.printTable()
        pulls.append(pull)
        unfolding.Reset()
    allpulls = []

    for pull in pulls:
        allpulls.extend(pull)
    h_allpulls = Hist(100,-30,30)
    filling = h_allpulls.Fill
    for entry in allpulls:
        filling(entry)
    fit = h_allpulls.Fit('gaus', 'WWS')
    h_fit = asrootpy(h_allpulls.GetFunction("gaus").GetHistogram())
    canvas = Canvas(width=1600, height=1000)
    canvas.SetLeftMargin(0.15)
    canvas.SetBottomMargin(0.15)
    canvas.SetTopMargin(0.10)
    canvas.SetRightMargin(0.05)
    h_allpulls.Draw()
    fit.Draw('same')
    canvas.SaveAs('plots/Pull_allBins_withFit.png')
    
    
    
    plt.figure(figsize=(16, 10), dpi=100)
    rplt.errorbar(h_allpulls, label=r'Pull distribution for all bins',  emptybins=False)
    rplt.hist(h_fit, label=r'fit')
    plt.xlabel('(unfolded-true)/error', CMS.x_axis_title)
    plt.ylabel('entries', CMS.y_axis_title)
    plt.title('Pull distribution for all bins', CMS.title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.legend(numpoints=1)
    plt.savefig('plots/Pull_allBins.png')
    
    #individual bins
    for bin_i in range(nbins):
        h_pull = Hist(100,-30,30)
        for pull in pulls:
            h_pull.Fill(pull[bin_i])
        plt.figure(figsize=(16, 10), dpi=100)
        rplt.errorbar(h_pull, label=r'Pull distribution for bin %d' % (bin_i + 1), emptybins=False)
        plt.xlabel('(unfolded-true)/error', CMS.x_axis_title)
        plt.ylabel('entries', CMS.y_axis_title)
        plt.title('Pull distribution for  bin %d' % (bin_i + 1), CMS.title)
        plt.savefig('Pull_bin_%d.png' % (bin_i + 1))
Beispiel #6
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()
Beispiel #7
0
def test_atlas():

    style = get_style('ATLAS')
    with style:
        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()
        ATLAS_label(.4, .8)
Beispiel #8
0
def test_cmstdr():

    style = get_style('CMSTDR')
    with style:
        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()
        labels.CMS_label("Testing 2050", sqrts=100)
Beispiel #9
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()
Beispiel #10
0
def draw_efficiencies(effs, field, category, textsize=22):

    xtitle = get_xtitle(field)

    c = Canvas()
    c.SetGridx()
    c.SetGridy()
    if not isinstance(effs, (list, tuple)):
        effs = [effs]

    h = Hist(10, effs[0].painted_graph.xaxis.min,
             effs[0].painted_graph.xaxis.max)
    h.yaxis.SetRangeUser(0.0, 1.1)
    h.Draw('HIST')
    h.yaxis.title = 'Efficiency'
    h.xaxis.title = xtitle

    colors = [
        'black',
        'red',
        'orange',
        'blue',
        'green',
        'purple',
        'yellow',
        'pink',
    ]
    if len(effs) > len(colors):
        colors = len(effs) * colors
    for eff, col in zip(effs, colors):
        eff.color = col
        eff.color = col
        eff.painted_graph.legendstyle = 'l'
        eff.painted_graph.Draw('SAMEP')
    label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label)
    label.SetNDC()
    label.SetTextFont(43)
    label.SetTextSize(textsize)
    label.Draw()
    leg = Legend(effs, pad=c, textsize=20)
    # textsize=20, leftmargin=0.6, topmargin=0.6)
    leg.Draw('same')
    return c
def plotDataMC(name, closureData, closureMC, bins, xTitle='m_{vis} [GeV]'):
    binid = hash(str(bins))
    #
    histoRatioData = closureData.data['True/Est']['Histo_{H}'.format(H=binid)]
    histoSmoothRatioData = closureData.data['True/Est'][
        'Histo_{H}_Smooth'.format(H=binid)]
    histoSmoothRatioErrorData = closureData.data['True/Est'][
        'Histo_{H}_SmoothError'.format(H=binid)]
    histoRatioMC = closureMC.data['True/Est']['Histo_{H}'.format(H=binid)]
    histoSmoothRatioMC = closureMC.data['True/Est']['Histo_{H}_Smooth'.format(
        H=binid)]
    histoSmoothRatioErrorMC = closureMC.data['True/Est'][
        'Histo_{H}_SmoothError'.format(H=binid)]
    #
    ################ Plot ratios
    histoDummyRatio = Hist(1, bins[0], bins[-1], type='F')
    values = []
    values.append(histoRatioData.GetMaximum())
    values.append(histoRatioData.GetMinimum())
    values.append(histoRatioMC.GetMaximum())
    values.append(histoRatioMC.GetMinimum())
    maxi = max(values)
    mini = min(values)
    maxi = maxi * 1.1 if maxi > 0 else maxi * 0.9
    mini = mini * 1.1 if mini < 0 else mini * 0.9
    histoDummyRatio.SetAxisRange(mini, maxi, 'Y')
    ##
    histoRatioData.SetMarkerColor(ROOT.kBlack)
    histoSmoothRatioData.SetLineColor(ROOT.kGray + 3)
    histoSmoothRatioData.SetLineWidth(2)
    histoSmoothRatioErrorData.SetLineColor(ROOT.kGray + 1)
    histoSmoothRatioErrorData.SetFillColor(ROOT.kGray + 1)
    ##
    histoRatioMC.SetMarkerColor(ROOT.kRed)
    histoRatioMC.SetMarkerStyle(21)
    histoSmoothRatioMC.SetLineColor(ROOT.kRed)
    histoSmoothRatioMC.SetLineWidth(2)
    histoSmoothRatioErrorMC.SetLineColor(ROOT.kRed - 7)
    #histoSmoothRatioErrorMC.SetFillColorAlpha(ROOT.kRed-7, 0.35)
    histoSmoothRatioErrorMC.SetFillStyle(3344)
    histoSmoothRatioErrorMC.SetFillColor(ROOT.kRed - 7)
    ##
    canvasRatio = Canvas(800, 800)
    canvasRatio.SetName('{NAME}_Ratio_Canvas'.format(NAME=name))
    histoDummyRatio.SetXTitle(xTitle)
    histoDummyRatio.SetYTitle('Ratio')
    histoDummyRatio.Draw()
    histoSmoothRatioErrorData.Draw('fl same')
    histoSmoothRatioData.Draw('pl same')
    histoSmoothRatioErrorMC.Draw('fl same')
    histoSmoothRatioMC.Draw('pl same')
    histoRatioData.Draw('E1 same')
    histoRatioMC.Draw('E1 same')
    #
    legend = ROOT.TLegend(0.15, 0.75, 0.45, 0.9)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    legend.AddEntry(histoRatioMC, 'MC', 'lp')
    legend.AddEntry(histoRatioData, 'Data', 'lp')
    legend.Draw()
    canvasRatio.Print('results/{NAME}_NonClosure_Ratio.png'.format(NAME=name))
Beispiel #12
0
    def __init__(self,
                 width=None,
                 height=None,
                 offset=0,
                 ratio_height=None,
                 ratio_margin=26,
                 ratio_limits=(0, 2),
                 ratio_divisions=4,
                 prune_ratio_ticks=False,
                 ratio_line_values=(1, ),
                 ratio_line_width=2,
                 ratio_line_style='dashed',
                 xtitle=None,
                 ytitle=None,
                 ratio_title=None,
                 tick_length=15,
                 logy=False):

        # first init as normal canvas
        super(RatioPlot, self).__init__(width=width, height=height)

        # get margins in pixels
        left, right, bottom, top = self.margin_pixels
        default_height = self.height
        default_frame_height = default_height - bottom - top

        if ratio_height is None:
            ratio_height = default_height / 4.

        self.height += int(ratio_height) + ratio_margin + offset
        self.margin = (0, 0, 0, 0)

        main_height = default_frame_height + top + ratio_margin / 2. + offset
        ratio_height += ratio_margin / 2. + bottom

        # top pad for histograms
        with self:
            main = Pad(0., ratio_height / self.height, 1., 1.)
            if logy:
                main.SetLogy()
            main.margin_pixels = (left, right, ratio_margin / 2., top)
            main.Draw()

        # bottom pad for ratio plot
        with self:
            ratio = Pad(0, 0, 1, ratio_height / self.height)
            ratio.margin_pixels = (left, right, bottom, ratio_margin / 2.)
            ratio.Draw()

        # draw main axes
        with main:
            main_hist = Hist(1, 0, 1)
            main_hist.Draw('AXIS')

        # hide x-axis labels and title on main pad
        xaxis, yaxis = main_hist.xaxis, main_hist.yaxis
        xaxis.SetLabelOffset(1000)
        xaxis.SetTitleOffset(1000)
        # adjust y-axis title spacing
        yaxis.SetTitleOffset(yaxis.GetTitleOffset() * self.height /
                             default_height)

        # draw ratio axes
        with ratio:
            ratio_hist = Hist(1, 0, 1)
            ratio_hist.Draw('AXIS')

        # adjust x-axis label and title spacing
        xaxis, yaxis = ratio_hist.xaxis, ratio_hist.yaxis

        xaxis.SetLabelOffset(xaxis.GetLabelOffset() * self.height /
                             ratio_height)
        xaxis.SetTitleOffset(xaxis.GetTitleOffset() * self.height /
                             ratio_height)
        # adjust y-axis title spacing
        yaxis.SetTitleOffset(yaxis.GetTitleOffset() * self.height /
                             default_height)

        if ratio_limits is not None:
            low, high = ratio_limits
            if prune_ratio_ticks:
                delta = 0.01 * (high - low) / float(ratio_divisions % 100)
                low += delta
                high -= delta
            yaxis.SetLimits(low, high)
            yaxis.SetRangeUser(low, high)
            yaxis.SetNdivisions(ratio_divisions)

        if xtitle is not None:
            ratio_hist.xaxis.title = xtitle
        if ytitle is not None:
            main_hist.yaxis.title = ytitle
        if ratio_title is not None:
            ratio_hist.yaxis.title = ratio_title

        # set the tick lengths
        tick_length_pixels(main, main_hist.xaxis, main_hist.yaxis, tick_length)
        tick_length_pixels(ratio, ratio_hist.xaxis, ratio_hist.yaxis,
                           tick_length)

        # draw ratio lines
        lines = []
        if ratio_line_values:
            with ratio:
                for value in ratio_line_values:
                    line = Line(0, value, 1, value)
                    line.linestyle = ratio_line_style
                    line.linewidth = ratio_line_width
                    line.Draw()
                    lines.append(line)
        self.lines = lines

        self.main = main
        self.main_hist = main_hist
        self.ratio = ratio
        self.ratio_hist = ratio_hist
        self.ratio_limits = ratio_limits
        self.logy = logy
Beispiel #13
0
          legendstyle='l')
h2 = Hist(100,
          -5,
          5,
          name="h2",
          title="Histogram 2",
          linecolor='blue',
          legendstyle='l')

for ievt in range(10000):
    h1.Fill(rand.Gaus(0, 0.8))
    h2.Fill(rand.Gaus(0, 1))

pad = c.cd(1)

h1.Draw('hist')
h2.Draw('hist same')

leg = Legend([h1, h2],
             pad=pad,
             leftmargin=0.5,
             topmargin=0.11,
             rightmargin=0.05,
             textsize=20)
leg.Draw()

pad = c.cd(2)

gr = qqgraph(h1, h2)

gr.xaxis.title = h1.title
Beispiel #14
0
                                total_vs_pu).decorate(linecolor='green',
                                                      linewidth=2,
                                                      markerstyle=20,
                                                      markercolor='green')

frame = Hist(*binning)

frame.SetMaximum(1)
frame.SetMinimum(0)
frame.axis().SetTitle("Number of vertices")
frame.axis(2).SetTitle("Efficiency (w.r.t. reco. p_{T}>40 GeV)")

canvas.SetLogy(False)
canvas.SetLeftMargin(0.2)

frame.Draw()
l1_efficiency.Draw('pe same')
uct_efficiency.Draw('pe same')
uct_iso_efficiency.Draw('pe same')

legend = Legend(3, topmargin=0.25, leftmargin=0.25)
legend.AddEntry(l1_efficiency, 'lp', 'Current Tau44')
legend.AddEntry(uct_efficiency, 'lp',
                'Upgrade RlxTau25 Rel. Rate %0.2f' % (9488. / 9355))
legend.AddEntry(uct_iso_efficiency, 'lp',
                'Upgrade IsoTau25 Rel. Rate %0.2f' % (6224. / 9355))
legend.SetBorderSize(0)
legend.SetTextSize(0.03)

legend.Draw()
Beispiel #15
0
            i, modules_hist[j].GetBinContent(i) / args.bw)
        modules_hist[j].SetBinError(i,
                                    modules_hist[j].GetBinError(i) / args.bw)
print ' - drawing ... '
y_max = 0
for i in xrange(25):
    if modules_hist[i].GetMaximum() > y_max:
        y_max = modules_hist[i].GetMaximum()
for i in xrange(25):
    modules_hist[i].SetMaximum(y_max * 1.1)

canvas_trigger = Canvas(1000,
                        800,
                        name="canvas_trigger",
                        title="rate of event trigger")
canvas_trigger.ToggleEventStatus()
canvas_trigger.cd()
trigger_hist.Draw('EH')
canvas_modules = Canvas(1500,
                        1000,
                        name="canvas_modules",
                        title="rate of 25 modules")
canvas_modules.ToggleEventStatus()
canvas_modules.Divide(5, 5)
for i in xrange(25):
    canvas_modules.cd(5 * (i % 5) + i / 5 + 1)
    modules_hist[i].Draw('EH')

sci_trigger_r_obj.close_file()
wait(True)
Beispiel #16
0
ROOT.gStyle.SetNumberContours(255)

#mask.fillstyle = 3354
#mask.fillcolor = 1
#mask.zaxis.range_user = (-0.9, 0.9)

hdrawopts = 'HIST text' if args.conly else 'colz text'
fitdrawopts = '' if args.conly else 'P SAME'

if not args.conly:
    lbias.Draw(hdrawopts)
    fitted.Draw(fitdrawopts)
    canvas.SaveAs('%s/lbias.png' % indir)
    canvas.SaveAs('%s/lbias.pdf' % indir)

cbias.Draw(hdrawopts)
if args.conly:
    fitted.SetY1(-0.13)
    fitted.SetY2(-0.19)
fitted.Draw(fitdrawopts)
canvas.SaveAs('%s/cbias.png' % indir)
canvas.SaveAs('%s/cbias.pdf' % indir)

ROOT.TColor.CreateGradientColorTable(2, array('d', [0., 1.]),
                                     array('d',
                                           [0., 1.]), array('d', [0., 0.]),
                                     array('d', [1., 0.]), 256)
failing.Draw(hdrawopts)  #'HIST' if args.conly else 'colz')
getattr(failing, axis).range_user = (-0.1, 1)
if args.conly:
    fitted.SetY1(0.075)
Beispiel #17
0
                   linewidth=2)
up.Reset()
up.fill_array(transform(up_scores))

dn = nominal.Clone(title='Down',
                   linecolor='blue',
                   linestyle='dashed',
                   linewidth=2)
dn.Reset()
dn.fill_array(transform(dn_scores))

# Plot the nominal, up, and down scores

canvas = Canvas()
nominal.SetMaximum(max(dn) * 1.1)
nominal.Draw()
nominal.xaxis.SetTitle('BDT Score')
nominal.yaxis.SetTitle('Events')

up.Draw('same hist')
dn.Draw('same hist')

leg = Legend(3, pad=canvas, leftmargin=.5)
leg.AddEntry(nominal, style='LEP')
leg.AddEntry(up, style='L')
leg.AddEntry(dn, style='L')
leg.Draw()
canvas.SaveAs('canvas_original.png')

# Take the ratio of systematic / nominal
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)
Beispiel #19
0
sys = nom.Clone(linewidth=2, linestyle='dashed')
nom.Smooth(10)

for i, bin in enumerate(sys.bins()):
    bin.value += i / 10.

smooth_sys = smooth(nom,
                    sys,
                    10,
                    linecolor='red',
                    linewidth=2,
                    linestyle='dashed')
smooth_alt_sys = smooth_alt(nom,
                            sys,
                            linecolor='blue',
                            linewidth=2,
                            linestyle='dashed')

nom.SetMaximum(
    max(nom.GetMaximum(), sys.GetMaximum(), smooth_sys.GetMaximum(),
        smooth_alt_sys.GetMaximum()) * 1.2)
nom.SetMinimum(-1)

nom.Draw('hist')
sys.Draw('hist same')
smooth_sys.Draw('hist same')
smooth_alt_sys.Draw('hist same')

wait()
Beispiel #20
0
def pvalue_plot(poi,
                pvalues,
                pad=None,
                xtitle='X',
                ytitle='P_{0}',
                linestyle=None,
                linecolor=None,
                yrange=None,
                verbose=False):
    """
    Draw a pvalue plot

    Parameters
    ----------
    poi : list
        List of POI values tested
    pvalues : list
        List of p-values or list of lists of p-values to overlay
        multiple p-value curves
    pad : Canvas or Pad, optional (default=None)
        Pad to draw onto. Create new pad if None.
    xtitle : str, optional (default='X')
        The x-axis label (POI name)
    ytitle : str, optional (default='P_{0}')
        The y-axis label
    linestyle : str or list, optional (default=None)
        Line style for the p-value graph or a list of linestyles for
        multiple p-value graphs.
    linecolor : str or list, optional (default=None)
        Line color for the p-value graph or a list of linestyles for
        multiple p-value graphs.

    Returns
    -------
    pad : Canvas
        The pad.
    graphs : list of Graph
        The p-value graphs

    """
    if not pvalues:
        raise ValueError("pvalues is empty")
    if not poi:
        raise ValueError("poi is empty")
    # determine if pvalues is list or list of lists
    if not isinstance(pvalues[0], (list, tuple)):
        pvalues = [pvalues]
    if linecolor is not None:
        if not isinstance(linecolor, list):
            linecolor = [linecolor]
        linecolor = cycle(linecolor)
    if linestyle is not None:
        if not isinstance(linestyle, list):
            linestyle = [linestyle]
        linestyle = cycle(linestyle)

    with preserve_current_canvas():
        if pad is None:
            pad = Canvas()
        pad.cd()
        pad.SetLogy()

        # create the axis
        min_poi, max_poi = min(poi), max(poi)
        haxis = Hist(1000, min_poi, max_poi)
        xaxis = haxis.xaxis
        yaxis = haxis.yaxis
        xaxis.SetRangeUser(min_poi, max_poi)
        haxis.Draw('AXIS')

        min_pvalue = float('inf')
        graphs = []
        for ipv, pv in enumerate(pvalues):
            graph = Graph(len(poi),
                          linestyle='dashed',
                          drawstyle='L',
                          linewidth=2)
            for idx, (point, pvalue) in enumerate(zip(poi, pv)):
                graph.SetPoint(idx, point, pvalue)
            if linestyle is not None:
                graph.linestyle = linestyle.next()
            if linecolor is not None:
                graph.linecolor = linecolor.next()
            graphs.append(graph)
            curr_min_pvalue = min(pv)
            if curr_min_pvalue < min_pvalue:
                min_pvalue = curr_min_pvalue

        if verbose:
            for graph in graphs:
                log.info(['{0:1.1f}'.format(xval) for xval in list(graph.x())])
                log.info(['{0:0.3f}'.format(yval) for yval in list(graph.y())])

        # automatically handles axis limits
        axes, bounds = draw(graphs,
                            pad=pad,
                            same=True,
                            logy=True,
                            xtitle=xtitle,
                            ytitle=ytitle,
                            xaxis=xaxis,
                            yaxis=yaxis,
                            ypadding=(0.2, 0.1),
                            logy_crop_value=1E-300)

        if yrange is not None:
            xaxis, yaxis = axes
            yaxis.SetLimits(*yrange)
            yaxis.SetRangeUser(*yrange)
            min_pvalue = yrange[0]

        # draw sigma levels up to minimum of pvalues
        line = Line()
        line.SetLineStyle(2)
        line.SetLineColor(2)
        latex = ROOT.TLatex()
        latex.SetNDC(False)
        latex.SetTextSize(20)
        latex.SetTextColor(2)
        sigma = 0
        while True:
            pvalue = gaussian_cdf_c(sigma)
            if pvalue < min_pvalue:
                break
            keepalive(
                pad,
                latex.DrawLatex(max_poi, pvalue, " {0}#sigma".format(sigma)))
            keepalive(pad, line.DrawLine(min_poi, pvalue, max_poi, pvalue))
            sigma += 1

        pad.RedrawAxis()
        pad.Update()
    return pad, graphs
Beispiel #21
0
map(h2.Fill, x2)

# normalize the histograms
h1 /= h1.Integral()
h2 /= h2.Integral()

# set visual attributes
h1.SetFillStyle("solid")
h1.SetFillColor("green")
h1.SetLineColor("green")

h2.SetFillStyle("solid")
h2.SetFillColor("red")
h2.SetLineColor("red")

# plot with ROOT
h1.GetXaxis().SetTitle('Smarts')
h1.GetYaxis().SetTitle('Probability')
h1.SetTitle("Histogram of IQ: #mu=100, #sigma=15")
h1.Draw("hist")
h2.Draw("same")

# plot with matplotlib
plt.figure()
rplt.hist(h1, alpha=0.75)
rplt.hist(h2, alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
plt.show()
map(h.Fill, x)

# normalize the histogram
h /= h.Integral()

# set visual attributes
h.SetFillStyle('/')
h.SetFillColor('green')
h.SetLineColor('green')

# plot with ROOT
c = Canvas(width=800, height=600)
h.GetXaxis().SetTitle('Smarts')
h.GetYaxis().SetTitle('Probability')
h.SetTitle("Histogram of IQ: #mu=100, #sigma=15")
h.Draw("hist")
legend = Legend(1)
legend.AddEntry(h, 'F')
legend.Draw()
c.SaveAs('root_hist.png')

# plot with matplotlib
plt.figure(figsize=(8, 6), dpi=100)
rplt.hist(h, label=r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
plt.legend()
plt.savefig('matplotlib_hist.png')
plt.show()
Beispiel #23
0
from rootpy.extern.six.moves import range

try:
    kwargs = {}
    for arg in extra:
        name, value = arg.lstrip('--').split('=')
        kwargs[name] = value
except ValueError:
    print("specify style parameters with --name=value")

try:
    style = get_style(args.style, **kwargs)
except ValueError:
    print('Invalid style: `{0}`. Using the `ATLAS` style.'.format(args.style))
    style = get_style('ATLAS')

# Use styles as context managers. The selected style will only apply
# within the following context:
with style:
    c = Canvas()
    hpx = Hist(100, -4, 4, name="hpx", title="This is the px distribution")
    # generate some random data
    ROOT.gRandom.SetSeed()
    for i in range(25000):
        hpx.Fill(ROOT.gRandom.Gaus())
    hpx.GetXaxis().SetTitle("random variable [unit]")
    hpx.GetYaxis().SetTitle("#frac{dN}{dr} [unit^{-1}]")
    hpx.SetMaximum(1000.)
    hpx.Draw()
    wait()
        h_data_toUse.SetBinContent(bin, newContent)
        h_data_toUse.SetBinError(bin, sqrt(newContent))

    h_measured_toUse = asrootpy(h_measured)

    # Remove fakes before unfolding
    h_fakes = h_measured_toUse - h_response.ProjectionX()
    nonFakeRatio = 1 - h_fakes / h_measured_toUse
    h_measured_toUse *= nonFakeRatio / nonFakeRatio
    h_data_toUse *= nonFakeRatio / nonFakeRatio

    # Unfold with SVD
    response = RooUnfoldResponse(h_measured_toUse, h_truth, h_response)
    svdUnfolding = RooUnfoldSvd(response, h_data_toUse, 0.7)
    svdUnfolding.SetVerbose(0)
    h_unfolded_data_svd = svdUnfolding.Hreco(3)

    # Unfold with Bayes
    response_bayes = RooUnfoldResponse(h_measured_toUse, h_truth, h_response)
    bayesUnfolding = RooUnfoldBayes(response_bayes, h_data_toUse, 4)
    h_unfolded_data_bayes = bayesUnfolding.Hreco(3)

    # Store result of first bin
    h_svdFirstBin.Fill(h_unfolded_data_svd.GetBinContent(1))
    h_bayesFirstBin.Fill(h_unfolded_data_bayes.GetBinContent(1))

# Draw histograms
h_svdFirstBin.Draw()
raw_input('SVD')
h_bayesFirstBin.Draw()
raw_input('Bayes')
Beispiel #25
0
    else:
        axis = 0
    # randomly choose starting bin
    start = randint(1, h.nbins(axis) - 1)
    end = randint(start + 1, min(start + 5 * h.GetDimension(), h.nbins(axis)))
    return h.merge_bins([(start, end)], axis=axis)

# create an animation of a 1D histogram
c1 = Canvas()
if not BATCH and os.path.isfile('binmerge1d.gif'):
    os.unlink('binmerge1d.gif')
a = Hist(100, -5, 5)
a.fill_array(np.random.randn(10000))
while a.nbins(0) > 1:
    a = random_bin_merge(a)
    a.Draw('hist')
    if not BATCH:
        c1.Print('binmerge1d.gif+20')
        time.sleep(.1)
if not BATCH:
    c1.Print('binmerge1d.gif++')

# create an animation of a 2D histogram
c2 = Canvas()
if not BATCH and os.path.isfile('binmerge2d.gif'):
    os.unlink('binmerge2d.gif')
c2.SetRightMargin(0.1)
b = Hist2D(100, -5, 5, 100, -5, 5)
b.fill_array(np.random.randn(10000, 2))
while b.nbins(0) > 1 or b.nbins(1) > 1:
    b = random_bin_merge(b)
Beispiel #26
0
h_t4.SetLineColor(7)
h_data.SetLineColor(1)
h_data.SetMarkerColor(1)

ymax = getMax([h_data, h_t1, h_t2, h_t3])
ymax = ymax * 1.1
h_data.GetYaxis().SetRangeUser(0, ymax)
h_t1.GetYaxis().SetRangeUser(0, ymax)
h_t2.GetYaxis().SetRangeUser(0, ymax)
h_t3.GetYaxis().SetRangeUser(0, ymax)
h_t4.GetYaxis().SetRangeUser(0, ymax)

c = Canvas()
c.Divide(2)
c.cd(1)
h_data.Draw('PE')
h_t1.Draw('SAME HIST')
h_t2.Draw('SAME HIST')
h_t3.Draw('SAME HIST')
h_t4.Draw('SAME HIST')

templates = {}
if useT1: templates['t1'] = h_t1
if useT2: templates['t2'] = h_t2
if useT3: templates['t3'] = h_t3
if useT4: templates['t4'] = h_t4

fit_data = FitData(h_data, templates, fit_boundaries=(0, h_data.nbins()))

fit_collection = FitDataCollection()
fit_collection.add(fit_data)
Beispiel #27
0
h_simple.linecolor = 'blue'
h_simple.fillcolor = 'green'
h_simple.fillstyle = '/'

# attributes may be accessed in the same way
print(h_simple.name)
print(h_simple.title)
print(h_simple.markersize)

# plot
canvas = Canvas(width=700, height=500)
canvas.SetLeftMargin(0.15)
canvas.SetBottomMargin(0.15)
canvas.SetTopMargin(0.10)
canvas.SetRightMargin(0.05)
h_simple.Draw()

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

# 2D and 3D histograms are handled in the same way
# the constructor arguments are repetitions of #bins, left bound, right bound.
h2d = Hist2D(10, 0, 1, 50, -40, 10, name='2d hist')
h3d = Hist3D(3, -1, 4, 10, -1000, -200, 2, 0, 1, name='3d hist')

# variable-width bins may be created by passing the bin edges directly:
Beispiel #28
0
def mpe_fitting(filename, run, num_photons, use_ideal=True):

    run_number = int(run)

    if filename[-5:] == '.root':
        filename = filename[:-5]

    s_data_path = './data/%s.p' % filename

    if filename[:5] == 'nerix':
        file_identifier = filename
    else:
        file_identifier = filename[-9:]

    a_integral = pickle.load((open(s_data_path, 'r')))

    # max_num_events used to limit amplitudes
    max_num_events = len(a_integral)

    s_path_to_save = './results/%s/' % (file_identifier)
    l_colors = [4, 2, 8, 7, 5, 9] + [4, 2, 8, 7, 5, 9]

    d_mpe_fit = {}

    if file_identifier == '0062_0061':
        d_mpe_fit['settings'] = [250, -1e6, 2e7]

        d_mpe_fit['bkg_mean_low'] = -1e6
        d_mpe_fit['bkg_mean_high'] = 2e6
        d_mpe_fit['bkg_width_low'] = 1e4
        d_mpe_fit['bkg_width_high'] = 1e6
        d_mpe_fit['spe_mean_low'] = 3.5e6
        d_mpe_fit['spe_mean_high'] = 1e7
        d_mpe_fit['spe_width_low'] = 8e5
        d_mpe_fit['spe_width_high'] = 3e6
        d_mpe_fit['ua_mean_low'] = 1e5
        d_mpe_fit['ua_mean_high'] = 5e6
        d_mpe_fit['ua_width_low'] = 1e4
        d_mpe_fit['ua_width_high'] = 1e6

        d_mpe_fit['spe_mean_guess'] = 6e6
        d_mpe_fit['spe_width_guess'] = 1.9e6
    
    elif file_identifier == '0066_0065':
        d_mpe_fit['settings'] = [250, -1e6, 1.2e7]

        d_mpe_fit['bkg_mean_low'] = -1e6
        d_mpe_fit['bkg_mean_high'] = 2e6
        d_mpe_fit['bkg_width_low'] = 1e4
        d_mpe_fit['bkg_width_high'] = 1e6
        d_mpe_fit['spe_mean_low'] = 2e6
        d_mpe_fit['spe_mean_high'] = 6e6
        d_mpe_fit['spe_width_low'] = 8e5
        d_mpe_fit['spe_width_high'] = 3e6
        d_mpe_fit['ua_mean_low'] = 1e5
        d_mpe_fit['ua_mean_high'] = 5e6
        d_mpe_fit['ua_width_low'] = 1e4
        d_mpe_fit['ua_width_high'] = 1e6

        d_mpe_fit['spe_mean_guess'] = 3.6e6
        d_mpe_fit['spe_width_guess'] = 1.1e6

    elif file_identifier == '0067_0068':
        d_mpe_fit['settings'] = [250, -1e6, 7.5e6]

        d_mpe_fit['bkg_mean_low'] = -5e5
        d_mpe_fit['bkg_mean_high'] = 5e5
        d_mpe_fit['bkg_width_low'] = 1e4
        d_mpe_fit['bkg_width_high'] = 1e6
        d_mpe_fit['spe_mean_low'] = 1.2e6
        d_mpe_fit['spe_mean_high'] = 3.5e6
        d_mpe_fit['spe_width_low'] = 3e5
        d_mpe_fit['spe_width_high'] = 1e6
        d_mpe_fit['ua_mean_low'] = 1e5
        d_mpe_fit['ua_mean_high'] = 1.5e6
        d_mpe_fit['ua_width_low'] = 1e4
        d_mpe_fit['ua_width_high'] = 1e6

        d_mpe_fit['spe_mean_guess'] = 2.1e6
        d_mpe_fit['spe_width_guess'] = 6.6e5

    elif file_identifier == '0071_0072':
        d_mpe_fit['settings'] = [250, -1e6, 3.4e7]

        d_mpe_fit['bkg_mean_low'] = -1e6
        d_mpe_fit['bkg_mean_high'] = 2e6
        d_mpe_fit['bkg_width_low'] = 1e4
        d_mpe_fit['bkg_width_high'] = 1e6
        d_mpe_fit['spe_mean_low'] = 7.5e6
        d_mpe_fit['spe_mean_high'] = 1.4e7
        d_mpe_fit['spe_width_low'] = 1e6
        d_mpe_fit['spe_width_high'] = 3.5e6
        d_mpe_fit['ua_mean_low'] = 1e5
        d_mpe_fit['ua_mean_high'] = 5e6
        d_mpe_fit['ua_width_low'] = 1e4
        d_mpe_fit['ua_width_high'] = 1e6

        d_mpe_fit['spe_mean_guess'] = 9.5e6
        d_mpe_fit['spe_width_guess'] = 2.9e6

    elif file_identifier == '0073_0074':
        d_mpe_fit['settings'] = [50, -1e6, 4.2e7]

        d_mpe_fit['bkg_mean_low'] = -1e6
        d_mpe_fit['bkg_mean_high'] = 2e6
        d_mpe_fit['bkg_width_low'] = 1e5
        d_mpe_fit['bkg_width_high'] = 2e6
        d_mpe_fit['spe_mean_low'] = 8.5e6
        d_mpe_fit['spe_mean_high'] = 1.4e7
        d_mpe_fit['spe_width_low'] = 1.5e6
        d_mpe_fit['spe_width_high'] = 4.5e6
        d_mpe_fit['ua_mean_low'] = 5e5
        d_mpe_fit['ua_mean_high'] = 4e6
        d_mpe_fit['ua_width_low'] = 0.5e6
        d_mpe_fit['ua_width_high'] = 1e6

        d_mpe_fit['spe_mean_guess'] = 9.5e6
        d_mpe_fit['spe_width_guess'] = 2.9e6

    elif file_identifier == 'nerix_160418_1523':
        d_mpe_fit['settings'] = [50, -5e5, 3.e6]
        
        d_mpe_fit['bkg_mean_low'] = -5e5
        d_mpe_fit['bkg_mean_high'] = 5e5
        d_mpe_fit['bkg_width_low'] = 1e4
        d_mpe_fit['bkg_width_high'] = 5e5
        d_mpe_fit['spe_mean_low'] = 6e5
        d_mpe_fit['spe_mean_high'] = 11e5
        d_mpe_fit['spe_width_low'] = 3e5
        d_mpe_fit['spe_width_high'] = 9e5
        d_mpe_fit['ua_mean_low'] = 1e3
        d_mpe_fit['ua_mean_high'] = 5e5
        d_mpe_fit['ua_width_low'] = 1e4
        d_mpe_fit['ua_width_high'] = 5e5

    elif file_identifier == 'nerix_160418_1531':
        d_mpe_fit['settings'] = [50, -5e5, 4.e6]
        
        d_mpe_fit['bkg_mean_low'] = -5e5
        d_mpe_fit['bkg_mean_high'] = 5e5
        d_mpe_fit['bkg_width_low'] = 1e4
        d_mpe_fit['bkg_width_high'] = 5e5
        d_mpe_fit['spe_mean_low'] = 6e5
        d_mpe_fit['spe_mean_high'] = 11e5
        d_mpe_fit['spe_width_low'] = 3e5
        d_mpe_fit['spe_width_high'] = 9e5
        d_mpe_fit['ua_mean_low'] = 1e3
        d_mpe_fit['ua_mean_high'] = 5e5
        d_mpe_fit['ua_width_low'] = 1e4
        d_mpe_fit['ua_width_high'] = 5e5

    else:
        print '\n\nSettings do not exist for given setup: %s\n\n' % (file_identifier)
        sys.exit()

    l_plots = ['plots', file_identifier]


    par_names = ['p0_ampl', 'mean_bkg', 'width_bkg', 'mean_spe', 'width_spe'] + ['p%d_ampl' % (i + 1) for i in xrange(num_photons)]




    a_integral = pickle.load((open(s_data_path, 'r')))

    if use_ideal:
        l_mpe_fit_func = ['[5]/(2*3.14*%d*[4]**2.)**0.5*TMath::Poisson(%d, [0])*exp(-0.5/%.1f*((x - %.1f*[3])/[4])**2)' % (iElectron, iElectron, iElectron, iElectron) for iElectron in xrange(1, num_photons + 1)]
    else:
        l_mpe_fit_func = ['[5]/(2*3.14*([2]**2. + %d*[4]**2.))**0.5*TMath::Poisson(%d, [0])*exp(-0.5*((x - %.1f*[3] - [1])/(%.1f*[4]**2 + [2]**2)**0.5)**2)' % (iElectron, iElectron, iElectron, iElectron) for iElectron in xrange(1, num_photons + 1)]

    h_mpe_spec = Hist(*d_mpe_fit['settings'], name='h_mpe_spec', title='MPE Spectrum with Gaussian Fit - %s' % filename)
    h_mpe_spec.SetMarkerSize(0)
    h_mpe_spec.fill_array(a_integral)

    c1 = Canvas()

    h_mpe_spec.Draw()

    s_bkg = '[5]/(2*3.14*[2]**2.)**0.5*TMath::Poisson(0, [0])*exp(-0.5*((x - [1])/[2])**2)'
    s_under_amplified = '[6]/(2*3.14*[8]**2.)**0.5*exp(-0.5*((x - [7])/[8])**2)'
    s_fit_mpe = '(%s) + (%s) + (%s)' % (s_bkg, s_under_amplified, ' + '.join(l_mpe_fit_func))
    s_fit_mpe = '(%s)*([1] < [3] ? 1. : 0.)*([1] < [7] ? 1. : 0.)*([7] < [3] ? 1. : 0.)' % (s_fit_mpe)
    fit_mpe = root.TF1('fit_mpe', s_fit_mpe, *d_mpe_fit['settings'][1:])
    fit_mpe.SetLineColor(46)
    fit_mpe.SetLineStyle(2)
    fit_mpe.SetLineWidth(3)

    h_mpe_spec.GetXaxis().SetTitle('Integrated Charge [e-]')
    h_mpe_spec.GetYaxis().SetTitle('Counts')
    h_mpe_spec.GetYaxis().SetTitleOffset(1.4)
    h_mpe_spec.SetStats(0)

    c1.SetLogy()


    fit_mpe.SetParLimits(0, 0.9, 2.5)
    fit_mpe.SetParameter(0, 1.3)
    fit_mpe.SetParLimits(1, d_mpe_fit['bkg_mean_low'], d_mpe_fit['bkg_mean_high'])
    fit_mpe.SetParameter(1, (d_mpe_fit['bkg_mean_low']+d_mpe_fit['bkg_mean_high'])/2.)
    fit_mpe.SetParLimits(2, d_mpe_fit['bkg_width_low'], d_mpe_fit['bkg_width_high'])
    fit_mpe.SetParameter(2, (d_mpe_fit['bkg_width_low']+d_mpe_fit['bkg_width_high'])/2.)
    fit_mpe.SetParLimits(3, d_mpe_fit['spe_mean_low'], d_mpe_fit['spe_mean_high'])
    fit_mpe.SetParameter(3, d_mpe_fit['spe_mean_guess'])
    fit_mpe.SetParLimits(4, d_mpe_fit['spe_width_low'], d_mpe_fit['spe_width_high'])
    fit_mpe.SetParameter(4, d_mpe_fit['spe_width_guess'])
    fit_mpe.SetParLimits(5, 10, max_num_events*1e6)
    fit_mpe.SetParameter(5, (10+max_num_events*1e6)/2.)
    fit_mpe.SetParLimits(6, 10, max_num_events*1e6)
    fit_mpe.SetParameter(6, (10+max_num_events*1e6)/2.)
    fit_mpe.SetParLimits(7, d_mpe_fit['ua_mean_low'], d_mpe_fit['ua_mean_high'])
    fit_mpe.SetParameter(7, (d_mpe_fit['ua_mean_low']+d_mpe_fit['ua_mean_high'])/2.)
    fit_mpe.SetParLimits(8, d_mpe_fit['ua_width_low'], d_mpe_fit['ua_width_high'])
    fit_mpe.SetParameter(8, (d_mpe_fit['ua_width_low']+d_mpe_fit['ua_width_high'])/2.)


    """
    for i, guess in enumerate(mpe_par_guesses):
        fit_mpe.SetParameter(i, guess)

    for i in xrange(len(par_names)):
        fit_mpe.SetParName(i, par_names[i])


    for photon in xrange(num_photons):
        fit_mpe.SetParLimits(5 + photon, 0, max_num_events)
    """

    fitResult = h_mpe_spec.Fit('fit_mpe', 'MILES')



    # draw individual peaks
    s_gaussian = '[0]*exp(-0.5/%.1f*((x - %.1f*[1])/[2])**2)'
    l_functions = []
    l_individual_integrals = [0. for i in xrange(num_photons+2)]
    for i in xrange(num_photons + 2):
        l_functions.append(root.TF1('peak_%d' % i, '[0]*exp(-0.5*((x - [1])/[2])**2)', *d_mpe_fit['settings'][1:]))

        # set parameters
        if i == 0:
            ampl = fit_mpe.GetParameter(5)*root.TMath.Poisson(0, fit_mpe.GetParameter(0))
            mean = fit_mpe.GetParameter(1)
            width = fit_mpe.GetParameter(2)
            if width > 0:
                ampl /= (2*3.14*width**2.)**0.5
            l_functions[i].SetParameters(ampl, mean, width)
            
        # under amplified peak
        elif i == (num_photons + 1):
            ampl = fit_mpe.GetParameter(6)
            mean = fit_mpe.GetParameter(7)
            width = fit_mpe.GetParameter(8)
            if width > 0:
                ampl /= (2*3.14*width**2.)**0.5
            l_functions[i].SetParameters(ampl, mean, width)

        else:
            ampl = fit_mpe.GetParameter(5)*root.TMath.Poisson(i, fit_mpe.GetParameter(0))
            if use_ideal:
                mean = fit_mpe.GetParameter(3) * i
                width = fit_mpe.GetParameter(4)*i**0.5
            else:
                mean = fit_mpe.GetParameter(3)*i + fit_mpe.GetParameter(1)
                width = (fit_mpe.GetParameter(4)**2*i + fit_mpe.GetParameter(2)**2)**0.5

            if width > 0:
                ampl /= (2*3.14*width**2.)**0.5

            l_functions[i].SetParameters(ampl, mean, width)



        l_individual_integrals[i] = ampl*width*(2*3.1415)**0.5
        l_functions[i].SetLineColor(l_colors[i])
        l_functions[i].Draw('same')




    c1.Update()


    fitStatus = fitResult.CovMatrixStatus()
    if fitStatus != 3:
        neriX_analysis.failure_message('Fit failed, please adjust guesses and try again.')
        fit_successful = False
    else:
        neriX_analysis.success_message('Fit successful, please copy output to appropriate files.')
        fit_successful = True

    #if not os.path.exists(sPathToSaveOutput):
    #    os.makedirs(sPathToSaveOutput)

    fitter = root.TVirtualFitter.Fitter(fit_mpe)
    #fitter = root.TVirtualFitter.GetFitter()
    amin = np.asarray([0], dtype=np.float64)
    dum1 = np.asarray([0], dtype=np.float64)
    dum2 = np.asarray([0], dtype=np.float64)
    dum3 = np.asarray([0], dtype=np.int32)
    dum4 = np.asarray([0], dtype=np.int32)

    fitter.GetStats(amin, dum1, dum2, dum3, dum4)


    print '\n\namin for %d photons: %f' % (num_photons, amin)
    print 'fAmin for %d photons: %f\n\n' % (num_photons, root.gMinuit.fAmin)
    print fit_mpe.GetChisquare()


    # draw tpavetext
    tpt_mpe = root.TPaveText(.55,.75,.85,.85,'blNDC')
    tpt_mpe.AddText('#mu_{SPE} = %.2e #pm %.2e' % (fit_mpe.GetParameter(3), fit_mpe.GetParError(3)))
    tpt_mpe.AddText('#sigma_{SPE} = %.2e #pm %.2e' % (fit_mpe.GetParameter(4), fit_mpe.GetParError(4)))
    tpt_mpe.Draw('same')

    tpt_mpe.SetTextColor(root.kBlack)
    tpt_mpe.SetFillStyle(0)
    tpt_mpe.SetBorderSize(0)

    c1.Update()


    neriX_analysis.save_plot(l_plots, c1, 'mpe_poisson_gaussian_fit_%s' % (file_identifier))


    return (0,0,0)
Beispiel #29
0
    for ievt in xrange(10000):
        #some test histograms:
        #1. let 2 histograms screwed
        #h1.Fill(rand.Gaus(0.5, 0.8))
        #h2.Fill(rand.Gaus(0, 1))

        #2. long tail and short tail
        h1.Fill(rand.Gaus(0, 0.8))
        h2.Fill(rand.Gaus(0, 1))

    #hs = ROOT.THStack("hs", "2 example distributions")
    #hs.Add(h1)
    #hs.Add(h2)
    #hs.Draw("nostack")

    h1.Draw()
    h2.Draw('same')

    #draw legend
    leg = ROOT.TLegend(0.7, 0.7, 0.89, 0.89)
    leg.SetFillColor(0)
    leg.AddEntry(h1, h1.GetTitle(), "pl")
    leg.AddEntry(h2, h2.GetTitle(), "pl")
    leg.Draw()
    can.Modified()
    can.Update()

    gr = qqplot(h1, h2)

    gr.SetLineColor(ROOT.kRed + 2)
    gr.SetMarkerColor(ROOT.kRed + 2)
Beispiel #30
0
def make_plot():
    canvas = Canvas(700, 500)
    hist = Hist(10, -3, 3)
    hist.FillRandom('gaus')
    hist.Draw()
    return canvas