Beispiel #1
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()
def makeDiscr(discr_dict,
              outfile,
              xtitle="discriminator",
              nbins=30,
              x_min=0,
              x_max=1):
    c = ROOT.TCanvas("c", "c", 800, 500)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1)
    #ROOT.gPad.SetLogy(1)
    #ROOT.gPad.SetGrid(1,1)
    ROOT.gStyle.SetGridColor(17)
    l = TLegend(0.17, 0.75, 0.88, 0.88)
    l.SetTextSize(0.055)
    l.SetBorderSize(0)
    l.SetFillStyle(0)
    l.SetNColumns(2)

    colors = [2, 4, 8, ROOT.kCyan + 2]
    counter = 0
    for leg, discr in discr_dict.iteritems():
        a = Hist(nbins, x_min, x_max)
        #fill_hist_with_ndarray(a, discr)
        a.fill_array(discr)
        a.SetLineColor(colors[counter])
        a.SetLineWidth(2)
        a.GetXaxis().SetTitle(xtitle)
        a.GetXaxis().SetLabelSize(0.05)
        a.GetXaxis().SetTitleSize(0.05)
        a.GetXaxis().SetTitleOffset(1.45)
        a.GetYaxis().SetTitle("a.u.")
        a.GetYaxis().SetTickSize(0)
        a.GetYaxis().SetLabelSize(0)
        a.GetYaxis().SetTitleSize(0.06)
        a.GetYaxis().SetTitleOffset(0.9)
        a.Scale(1. / a.Integral())
        #a.GetYaxis().SetRangeUser(0.00001,100)
        a.GetYaxis().SetRangeUser(0, 0.2)
        if counter == 0: a.draw("hist")
        else: a.draw("same hist")
        l.AddEntry(a, leg, "l")
        counter += 1

    l.Draw("same")
    c.SaveAs(outfile)
Beispiel #3
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 #4
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 #5
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 #6
0
def rate_test(et_values, event_runs, et_cuts):
    events = {}
    for et, (run_event) in zip(et_values, event_runs):
        event = tuple(run_event)
        if event in events:
            if et > events[event]: events[event] = et
        else: events[event] = et
    histo = Hist(256, -0.5, 255.5)
    for event, et in events.items():
        histo.Fill(et)
    total_events = histo.integral(overflow=True)
    rates = []
    for et_cut in et_cuts:
        bin = histo.GetXaxis().FindBin(et_cut)
        pass_events = histo.integral(bin, overflow=True)
        rates.append([
            et_cut,
            float(pass_events) / float(total_events) * nbunches * c_light /
            lhc_length * 1.e-3
        ])
    return np.array(rates, dtype=np.float64)
Beispiel #7
0
    gr.SetFillColor(17)
    gr.SetFillStyle(1001)

    c = Canvas(name="c", title="QQ with CL", width=600, height=450)
    gr.Draw("ap")
    x_min = gr.GetXaxis().GetXmin()
    x_max = gr.GetXaxis().GetXmax()
    y_min = gr.GetXaxis().GetXmin()
    y_max = gr.GetXaxis().GetXmax()
    c.Clear()
    gr.Draw('a3')
    gr.Draw('Xp same')

    # a straight line y=x to be a reference
    f_dia = ROOT.TF1("f_dia", "x",
                     h1.GetXaxis().GetXmin(),
                     h1.GetXaxis().GetXmax())
    f_dia.SetLineColor(9)
    f_dia.SetLineWidth(2)
    f_dia.SetLineStyle(2)
    f_dia.Draw("same")

    leg = ROOT.TLegend(0.52, 0.15, 0.87, 0.35)
    leg.SetFillColor(0)
    leg.SetShadowColor(17)
    leg.SetBorderSize(3)
    leg.AddEntry(gr, "QQ points", "p")
    leg.AddEntry(gr, "68% CL band", "f")
    leg.AddEntry(f_dia, "Diagonal line", "l")
    leg.Draw()
Beispiel #8
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()
Beispiel #9
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()
Beispiel #10
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)
        def make_plot(raw_data, binning, title_text, outfn):
            h = Hist(*binning,
                     drawstyle='hist e1',
                     color=sigCOLORS[0],
                     linewidth=2,
                     title=';Percent difference[%];Events')
            for sample, value in raw_data.items():
                h.Fill(value['variation'], value['count'])
            hc = asrootpy(h.GetCumulative())
            hc.linecolor = 'gold'
            hc.fillcolor = 'lightyellow'
            hc.fillstyle = 'solid'
            hc.scale(h.max(include_error=True) / hc.max())
            xmin_, xmax_, ymin_, ymax_ = get_limits([h, hc])
            draw([hc, h], ylimits=(0, ymax_))

            x95, x99 = None, None
            cumsum = 0
            for i in range(1, h.GetNbinsX() + 1):
                cumsum += h.GetBinContent(i)
                if x95 is None and cumsum / h.Integral() > 0.95:
                    x95 = h.GetXaxis().GetBinUpEdge(i)
                if x99 is None and cumsum / h.Integral() > 0.99:
                    x99 = h.GetXaxis().GetBinUpEdge(i)

            title = TitleAsLatex(title_text)
            title.Draw()

            # print(title_text, ROOT.gPad.GetUymax(), hc.max())
            # draw a second axis on the right.
            ROOT.gPad.SetTicks(
                1, 0
            )  # Draw top ticks but not right ticks (https://root.cern.ch/root/roottalk/roottalk99/2908.html)
            low, high = 0, ROOT.gPad.GetUymax() / hc.max()
            raxis = ROOT.TGaxis(ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin(),
                                ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax(),
                                low, high, 510, "+L")
            raxis.SetLabelSize(0.03)
            raxis.SetLabelFont(42)
            raxis.SetLabelColor(convert_color('gold', 'root'))
            raxis.Draw()

            frame = canvas.FindObject('TFrame')
            lo, hi = frame.GetY1(), frame.GetY2()
            l95 = ROOT.TLine(x95, lo, x95, hi)
            l95.SetLineStyle(2)
            l95.SetLineColor(convert_color(sigCOLORS[1], 'root'))
            l95.SetLineWidth(2)
            l95.Draw()
            l99 = ROOT.TLine(x99, lo, x99, hi)
            l99.SetLineStyle(3)
            l99.SetLineColor(convert_color(sigCOLORS[2], 'root'))
            l99.Draw()

            leg = Legend(3,
                         margin=0.25,
                         leftmargin=0.45,
                         topmargin=0.02,
                         entrysep=0.01,
                         entryheight=0.02,
                         textsize=10)
            leg.AddEntry(hc, label='cumulative (norm.)', style='LF')
            leg.AddEntry(l95, label='95% @ {}'.format(x95), style='L')
            leg.AddEntry(l99, label='99% @ {}'.format(x99), style='L')
            leg.Draw()

            canvas.SaveAs(outfn)
            canvas.clear()
Beispiel #12
0
def makeDiscr(train_discr_dict, discr_dict, outfile, xtitle="discriminator"):
    c = ROOT.TCanvas("c", "c", 800, 500)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1)
    #ROOT.gPad.SetLogy(1)
    #ROOT.gPad.SetGrid(1,1)
    ROOT.gStyle.SetGridColor(17)
    l = TLegend(0.17, 0.75, 0.88, 0.88)
    l.SetTextSize(0.055)
    l.SetBorderSize(0)
    l.SetFillStyle(0)
    l.SetNColumns(2)

    colors = [2, 1, 4, ROOT.kCyan + 2]
    counter = 0
    for leg, discr in train_discr_dict.iteritems():
        a = Hist(30, 0, 1)
        #fill_hist_with_ndarray(a, discr)
        a.fill_array(discr)
        a.SetLineColor(colors[counter])
        a.SetLineWidth(2)
        a.GetXaxis().SetTitle(xtitle)
        a.GetXaxis().SetLabelSize(0.05)
        a.GetXaxis().SetTitleSize(0.06)
        a.GetXaxis().SetTitleOffset(1.45)
        a.GetYaxis().SetTitle("a.u.")
        a.GetYaxis().SetTickSize(0)
        a.GetYaxis().SetLabelSize(0)
        a.GetYaxis().SetTitleSize(0.06)
        a.GetYaxis().SetTitleOffset(0.9)
        a.Scale(1. / a.Integral())
        #a.GetYaxis().SetRangeUser(0.00001,100)
        a.GetYaxis().SetRangeUser(0, 0.9)
        if counter == 0: a.draw("hist")
        else: a.draw("same hist")
        l.AddEntry(a, leg, "l")
        counter += 1

    counter = 0
    for leg, discr in discr_dict.iteritems():
        a = Hist(30, 0, 1)
        #fill_hist_with_ndarray(a, discr)
        a.fill_array(discr)
        a.SetLineColor(colors[counter])
        a.SetMarkerColor(colors[counter])
        a.SetMarkerStyle(34)
        a.SetMarkerSize(1.8)
        a.SetLineWidth(2)
        a.GetXaxis().SetTitle(xtitle)
        a.GetXaxis().SetLabelSize(0.05)
        a.GetXaxis().SetTitleSize(0.06)
        a.GetXaxis().SetTitleOffset(1.45)
        a.GetYaxis().SetTitle("a.u.")
        a.GetYaxis().SetTickSize(0)
        a.GetYaxis().SetLabelSize(0)
        a.GetYaxis().SetTitleSize(0.06)
        a.GetYaxis().SetTitleOffset(0.9)
        a.Scale(1. / a.Integral())
        #a.GetYaxis().SetRangeUser(0.00001,100)
        a.GetYaxis().SetRangeUser(0, 0.4)
        a.draw("same p X0")
        l.AddEntry(a, leg, "p")
        counter += 1

    # counter = 0


#     for leg,discr in train_discr_dict.iteritems():
#         d = Hist(30, 0, 1)
#         d.fill_array(discr)
#         d.SetLineColor(colors[counter])
#         d.SetLineWidth(2)
#         l.AddEntry(d,leg,"l")
#
#         b = Hist(30, 0, 1)
#         d.fill_array(discr_dict[leg.split(" ")[0] + " test"])
#         b.SetLineColor(colors[counter])
#         b.SetMarkerColor(colors[counter])
#         b.SetMarkerStyle(34)
#         b.SetMarkerSize(1.8)
#         b.SetLineWidth(2)
#         l.AddEntry(b,leg,"p")
#         counter += 1

    l.Draw("same")

    c.SaveAs(outfile)
def main(parameters):
  input_files = parameters.input_files
  tree_name = parameters.input_tree
  means = Hist(4*len(input_files), 0, 4*len(input_files), name='mean values')
  rmss = Hist(4*len(input_files), 0, 4*len(input_files), name='rms values')
  cov_means = Hist(2*len(input_files), 0, 2*len(input_files), name='covariance mean values')
  cov_rmss = Hist(2*len(input_files), 0, 2*len(input_files), name='covariance rms values')
  means.SetYTitle('Variance mean [cm^{2}]')
  rmss.SetYTitle('Variance RMS [cm^{2}]')
  cov_means.SetYTitle('Covariance mean [cm^{2}]')
  cov_rmss.SetYTitle('Covariance RMS [cm^{2}]')
  with root_open(parameters.output_file, 'recreate') as output_file:
    for i, (name, input_file_name) in enumerate(input_files):
      means.GetXaxis().SetBinLabel(i*4+1, name+' x')
      means.GetXaxis().SetBinLabel(i*4+2, name+' y')
      means.GetXaxis().SetBinLabel(i*4+3, name+' u')
      means.GetXaxis().SetBinLabel(i*4+4, name+' v')
      rmss.GetXaxis().SetBinLabel(i*4+1, name+' x')
      rmss.GetXaxis().SetBinLabel(i*4+2, name+' y')
      rmss.GetXaxis().SetBinLabel(i*4+3, name+' u')
      rmss.GetXaxis().SetBinLabel(i*4+4, name+' v')
      cov_means.GetXaxis().SetBinLabel(i*2+1, name+' x/y')
      cov_rmss.GetXaxis().SetBinLabel(i*2+1, name+' x/y')
      cov_means.GetXaxis().SetBinLabel(i*2+2, name+' u/v')
      cov_rmss.GetXaxis().SetBinLabel(i*2+2, name+' u/v')
      with root_open(input_file_name) as input_file:
        tree = input_file.Get(tree_name)
        moment_2nd_x, moment_2nd_y, moment_2nd_xy, moment_2nd_u, moment_2nd_v, moment_2nd_uv = shape_distribution(tree, parameters.log_weights)
        print name
        print 'x variance Mu =', moment_2nd_x.GetMean(), '+/-', moment_2nd_x.GetMeanError(), 'RMS =', moment_2nd_x.GetRMS(), '+/-', moment_2nd_x.GetRMSError()
        print 'y variance Mu =', moment_2nd_y.GetMean(), '+/-', moment_2nd_y.GetMeanError(), 'RMS =', moment_2nd_y.GetRMS(), '+/-', moment_2nd_y.GetRMSError()
        print 'u variance Mu =', moment_2nd_u.GetMean(), '+/-', moment_2nd_u.GetMeanError(), 'RMS =', moment_2nd_u.GetRMS(), '+/-', moment_2nd_u.GetRMSError()
        print 'v variance Mu =', moment_2nd_v.GetMean(), '+/-', moment_2nd_v.GetMeanError(), 'RMS =', moment_2nd_v.GetRMS(), '+/-', moment_2nd_v.GetRMSError()
        print 'x-y covariance Mu =', moment_2nd_xy.GetMean(), '+/-', moment_2nd_xy.GetMeanError(), 'RMS =', moment_2nd_xy.GetRMS(), '+/-', moment_2nd_xy.GetRMSError()
        print 'u-v covariance Mu =', moment_2nd_uv.GetMean(), '+/-', moment_2nd_uv.GetMeanError(), 'RMS =', moment_2nd_uv.GetRMS(), '+/-', moment_2nd_uv.GetRMSError()
        # fill mean values of variances
        means.SetBinContent(i*4+1, moment_2nd_x.GetMean())
        means.SetBinError(i*4+1, moment_2nd_x.GetMeanError())
        means.SetBinContent(i*4+2, moment_2nd_y.GetMean())
        means.SetBinError(i*4+2, moment_2nd_y.GetMeanError())
        means.SetBinContent(i*4+3, moment_2nd_u.GetMean())
        means.SetBinError(i*4+3, moment_2nd_u.GetMeanError())
        means.SetBinContent(i*4+4, moment_2nd_v.GetMean())
        means.SetBinError(i*4+4, moment_2nd_v.GetMeanError())
        # fill rms values of variances
        rmss.SetBinContent(i*4+1, moment_2nd_x.GetRMS())
        rmss.SetBinError(i*4+1, moment_2nd_x.GetRMSError())
        rmss.SetBinContent(i*4+2, moment_2nd_y.GetRMS())
        rmss.SetBinError(i*4+2, moment_2nd_y.GetRMSError())
        rmss.SetBinContent(i*4+3, moment_2nd_u.GetRMS())
        rmss.SetBinError(i*4+3, moment_2nd_u.GetRMSError())
        rmss.SetBinContent(i*4+4, moment_2nd_v.GetRMS())
        rmss.SetBinError(i*4+4, moment_2nd_v.GetRMSError())
        # fill mean values of covariances
        cov_means.SetBinContent(i*2+1, moment_2nd_xy.GetMean())
        cov_means.SetBinError(i*2+1, moment_2nd_xy.GetMeanError())
        cov_means.SetBinContent(i*2+2, moment_2nd_uv.GetMean())
        cov_means.SetBinError(i*2+2, moment_2nd_uv.GetMeanError())
        # fill rms values of covariances
        cov_rmss.SetBinContent(i*2+1, moment_2nd_xy.GetRMS())
        cov_rmss.SetBinError(i*2+1, moment_2nd_xy.GetRMSError())
        cov_rmss.SetBinContent(i*2+2, moment_2nd_uv.GetRMS())
        cov_rmss.SetBinError(i*2+2, moment_2nd_uv.GetRMSError())
        # write variance distributions
        moment_2nd_x.SetName(moment_2nd_x.GetName()+'_'+name)
        moment_2nd_y.SetName(moment_2nd_y.GetName()+'_'+name)
        moment_2nd_xy.SetName(moment_2nd_xy.GetName()+'_'+name)
        moment_2nd_u.SetName(moment_2nd_u.GetName()+'_'+name)
        moment_2nd_v.SetName(moment_2nd_v.GetName()+'_'+name)
        output_file.cd()
        moment_2nd_x.Write()   
        moment_2nd_y.Write()
        moment_2nd_xy.Write()
        moment_2nd_u.Write()
        moment_2nd_v.Write()
    means.Write()
    rmss.Write()
    cov_means.Write()
    cov_rmss.Write()