Exemplo n.º 1
0
def main():

    ############################################################################
    # Make a figure on which to plot stuff.
    # This would be the same as making a TCanvas object.
    ############################################################################
    fig1 = plt.figure(figsize=(8, 6), dpi=100, facecolor='w', edgecolor='k')

    ############################################################################
    # Now divide of the figure as if we were making a bunch of TPad objects.
    # These are called ``subplots".
    #
    # Usage is XYZ: X=how many rows to divide.
    #               Y=how many columns to divide.
    #               Z=which plot to plot based on the first being '1'.
    # So '111' is just one plot on the main figure.
    ############################################################################
    subplot = fig1.add_subplot(1, 1, 1)

    ############################################################################
    # Generate values drawn from a normal (Gaussian) distribution.
    ############################################################################
    mean = 5.0
    sigma = 1.0
    values = np.random.normal(mean, sigma, 10000)

    ############################################################################
    # Histogram of the data.
    ############################################################################
    h, xpts, ypts, xpts_err, ypts_err = lch.hist_err(values,
                                                     bins=50,
                                                     range=(0.0, 10.0),
                                                     color='pink')  #

    ############################################################################
    # Let's format this histogram.
    # Note that we will do this by changing the values on the subplot (Axes),
    # not the histogram object.
    ############################################################################
    subplot.set_xlim(-1, 11)

    subplot.set_xlabel('x variable', fontsize=20)
    subplot.set_ylabel('# events', fontsize=20)

    # Note that we can easily include Latex code
    subplot.set_title(r'$\mathrm{Gaussian\ distribution:}\ \mu=5,\ \sigma=1$',
                      fontsize=30)

    # Set the number of tick marks on the x-axis.
    subplot.locator_params(nbins=8)

    fit_params, fit_params_errs, cov_mat = lch.fit(lichen.pdf_gaussian(),
                                                   xpts,
                                                   ypts, [100.0, 5.0, 1.0],
                                                   yerr=ypts_err)

    # Need this command to display the figure.
    plt.show()
Exemplo n.º 2
0
def main():

    filenames = sys.argv[1:]

    print("Will open files:")
    for f in filenames:
        print(f)

    data = tbt.chain_pickle_files(filenames)

    mupt = data['mupt']
    muisPF = data['muisPF']
    muist = data['muist']
    muiso04 = data['muiso04']

    ################################################################################
    plt.figure()
    plt.subplot(3, 3, 1)
    lch.hist_err(mupt, bins=100, range=(0, 100), color='k')

    plt.subplot(3, 3, 2)
    lch.hist_err(muiso04[muiso04 > 0], bins=100, range=(0, .20), color='k')

    plt.subplot(3, 3, 5)
    lch.hist_2D(mupt[muiso04 > 0],
                muiso04[muiso04 > 0],
                xbins=100,
                ybins=100,
                xrange=(0, 100),
                yrange=(0, .20))
    #plt.xlim(50,150)
    #plt.ylim(0, 3.2)

    ################################################################################
    # Cut on the wmass
    #index = wmass>70.0
    #index *= wmass<95.0

    plt.show()
Exemplo n.º 3
0
def main():
    
    ############################################################################
    # Make a figure on which to plot stuff.
    # This would be the same as making a TCanvas object.
    ############################################################################
    fig1 = plt.figure(figsize=(8,6),dpi=100,facecolor='w',edgecolor='k')

    ############################################################################
    # Now divide of the figure as if we were making a bunch of TPad objects.
    # These are called ``subplots".
    #
    # Usage is XYZ: X=how many rows to divide.
    #               Y=how many columns to divide.
    #               Z=which plot to plot based on the first being '1'.
    # So '111' is just one plot on the main figure.
    ############################################################################
    subplot = fig1.add_subplot(1,1,1)

    ############################################################################
    # Generate values drawn from a normal (Gaussian) distribution.
    ############################################################################
    mean = 5.0
    sigma = 1.0
    values = np.random.normal(mean,sigma,10000)

    ############################################################################
    # Histogram of the data.
    ############################################################################
    h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(values,bins=50,range=(0.0,10.0),color='pink') # 

    ############################################################################
    # Let's format this histogram. 
    # Note that we will do this by changing the values on the subplot (Axes), 
    # not the histogram object.
    ############################################################################
    subplot.set_xlim(-1,11)
    
    subplot.set_xlabel('x variable',fontsize=20)
    subplot.set_ylabel('# events',fontsize=20)
    
    # Note that we can easily include Latex code
    subplot.set_title(r'$\mathrm{Gaussian\ distribution:}\ \mu=5,\ \sigma=1$',fontsize=30)

    # Set the number of tick marks on the x-axis.
    subplot.locator_params(nbins=8)

    fit_params,fit_params_errs,cov_mat = lch.fit(lichen.pdf_gaussian(),xpts,ypts,[100.0,5.0,1.0],yerr=ypts_err)

    # Need this command to display the figure.
    plt.show()
                    p4s.append(bjet)
                    p4s.append(jets[i])
                    p4s.append(jets[j])
                    m = invmass(p4s)
                    #print("mass: ",m)
                    jet3mass.append(m)
                    jet2mass.append(invmass([jets[i], jets[j]]))

muonpt = np.array(muonpt)
metpt = np.array(metpt)
jetbtag = np.array(jetbtag)
jet3mass = np.array(jet3mass)
jet2mass = np.array(jet2mass)

plt.figure()
lch.hist_err(metpt[metpt < 500])
plt.xlabel(r'$mising E_T$')

plt.figure()
lch.hist_err(muonpt[(muonpt < 200) * (muonpt > 30)])
plt.xlabel(r'$p_T \mu$')

plt.figure()
lch.hist_err(jetbtag[jetbtag >= 0])
plt.xlabel(r'jets b-tagging')

plt.figure()
lch.hist_err(jet3mass[jet3mass < 400])
plt.xlabel(r'3-jets mass')

plt.figure()
ax0 = fig0.add_subplot(1,2,1)
ax1 = fig0.add_subplot(1,2,2)
fig0.subplots_adjust(wspace=0.20,hspace=0.10,bottom=0.15,top=0.95,left=0.10,right=0.95)

ax0.set_xlim(ranges[0])
#ax0.set_ylim(0.0,50.0)
#ax0.set_ylim(0.0,92.0)
ax0.set_xlabel("Ionization Energy (keVee)",fontsize=12)
ax0.set_ylabel("Events/0.025 keVee",fontsize=12)

ax1.set_xlim(ranges[1])

ax1.set_xlabel("Days since 12/4/2009",fontsize=12)
ax1.set_ylabel("Event/30.6 days",fontsize=12)

lch.hist_err(data[0],bins=nbins[0],range=ranges[0],axes=ax0)
h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(data[1],bins=nbins[1],range=ranges[1],axes=ax1)

ax1.set_ylim(0.0,600)

# Do an acceptance correction of some t-bins by hand.
tbwidth = (ranges[1][1]-ranges[1][0])/float(nbins[1])
acc_corr = np.zeros(len(ypts))
# For 15 bins
#acc_corr[2] = tbwidth/(tbwidth-7.0)
#acc_corr[3] = tbwidth/(tbwidth-6.0)
#acc_corr[10] = tbwidth/(tbwidth-3.0)
# For 30 bins
#acc_corr[4] = tbwidth/(tbwidth-7.0)
#acc_corr[6] = tbwidth/(tbwidth-6.0)
#acc_corr[20] = tbwidth/(tbwidth-3.0)
                    elif (jets[k][4] > 1.0):
                        wmass = inv_mass([jets[i], jets[j]])
                        if wmass > 70 and wmass < 100:
                            invariant_mass_top.append(mass)
                            ntop += 1

    ntops.append(ntop)
    combos.append(ncombos)

    ##################################################################
    #### Find number of jets for QCD
    ##################################################################
    QCD_jets.append(len(jets))

#plt.figure(figsize=(9,9))
'''plt.figure(1)
#plt.subplot(3,3,1)
#plt.hist(invariant_mass_W,bins=150,range=(0,400))
lkn.hist_err(invariant_mass_W,bins=200,range=(0,400))
name = r"Hadronic Decay of W $%s$" % (sys.argv[1].split('/')[-1])
plt.title(name)
plt.ylabel(r"Frequency")
plt.xlabel(r"Invariant Mass")'''
'''plt.figure(2)

#plt.subplot(1,2,1)
plt.hist(invariant_mass_Z,bins=100, range=(0,200))
#lkn.hist_err(invariant_mass_Z,bins=200)
plt.xlim([0,200])
#plt.ylim([0,250])
name = r"Drell Yan Decay of Z $%s$" % (sys.argv[1].split('/')[-1])
Exemplo n.º 7
0
import numpy as np
import lichen.lichen as lch
import matplotlib.pyplot as plt

import sys

vals = np.loadtxt(sys.argv[1])

days = vals[:,0]
energies = vals[:,1]
risetimes = vals[:,2]

plt.figure(figsize=(12,4))

plt.subplot(1,3,1)
lch.hist_err(energies,bins=50)
plt.xlabel('Recoil energy (keVee)')
plt.ylim(0)

plt.subplot(1,3,2)
lch.hist_err(days,bins=50)
plt.xlabel('Days since XXX')
plt.ylim(0)

plt.subplot(1,3,3)
lch.hist_err(risetimes,bins=50,range=(0,6))
plt.xlabel(r'Rise times ($\mu$s)')
plt.ylim(0)
plt.xlim(0,6)

plt.tight_layout()
#print(bcand)
for icut, cut in enumerate(cuts):
    for j, key in enumerate(plotvars.keys()):
        var = plotvars[key]
        print(len(var["values"][icut]) / nentries)
#exit()

for icut, cut in enumerate(cuts):
    plt.figure(figsize=(10, 6))
    for j, key in enumerate(plotvars.keys()):
        var = plotvars[key]
        plt.subplot(4, 4, 1 + j)
        if key == "nphot" or key == "ncharged":
            lch.hist_err(var["values"][icut],
                         range=var["range"],
                         bins=20,
                         alpha=0.2,
                         markersize=0.5)
        else:
            lch.hist_err(var["values"][icut],
                         range=var["range"],
                         bins=50,
                         alpha=0.2,
                         markersize=0.5)
        plt.xlabel(var["xlabel"], fontsize=12)
        plt.ylabel(var["ylabel"], fontsize=12)
        print(len(var["values"][icut]))

    if icut == len(cuts) - 1:
        plt.figure(figsize=(10, 6))
        plt.subplot(1, 1, 1)
################################################################################
# Generate fake data points and plot them
################################################################################
mu = 1.5
sigma = 0.1
x = np.random.normal(mu, sigma, 70)

mylambda = 1.0
k = np.random.exponential(1 / mylambda, 1000)

plt.figure()
# lch.hist_err(x,bins=50,range=(0,4.0),color='red',ecolor='red')
# lch.hist_err(k,bins=50,range=(0,4.0),color='blue',ecolor='blue')

total = np.append(x, k)
lch.hist_err(total, bins=50, range=(0, 4.0), markersize=2)
################################################################################
# Now fit the data.
################################################################################

m = Minuit(
    negative_log_likelihood,
    mu=1.0,
    limit_mu=(0, 3.0),
    sigma=1.0,
    limit_sigma=(0, 3.0),
    mylambda=1.0,
    limit_mylambda=(0, 3.0),
    fraction=0.5,
    limit_fraction=(0, 3.14),
)
Exemplo n.º 10
0
        notx.append(vertexX)
        noty.append(vertexY)
        notz.append(vertexZ)
    #print(x, y, z)

x = np.array(x)
y = np.array(y)
z = np.array(z)

print(len(notx))

plt.figure()
ax = plt.axes(projection='3d')
ax.scatter(x, y, z, c='r')
#ax.scatter(notx,noty,notz,c='b')
#plt.show()

plt.figure()
plt.plot(x, y, '.', alpha=0.1)

plt.figure()
lch.hist_err(x)

plt.figure()
lch.hist_err(y)

plt.figure()
lch.hist_err(z)

plt.show()
Exemplo n.º 11
0
    tree.GetEntry(i)

    iso = tree.electronTkIso
    isoH = tree.electronHCIso
    isoE = tree.electronECIso
    nelec = tree.nelectron
    elecPT = tree.electronpt

    nelecs += nelec

    for j in range(nelec):
        #if elecPT[j] >= 30 and elecPT[j] <= 100:
        isovarE = (iso[j] + isoH[j] + isoE[j]) / elecPT[j]
        isoVarE.append(isovarE)
        isovarB = (iso[j] + isoH[j] + max(0., isoE[j] - 1)) / elecPT[j]
        isoVarB.append(isovarB)
        #print('Max: ', max(0.,isoE[j]-1))
        #print(isoE[j])

print(nelecs)

plt.figure()
lch.hist_err(isoVarB, bins=100, range=(0, 1))
plt.xlabel('dr03 Barrel Electron Isolation Variable')

plt.figure()
lch.hist_err(isoVarE, bins=100, range=(0, 1))
plt.xlabel('dr03 Endcap Electron Isolation Variable')

plt.show()
# This will find the mean, sum, and stddev of an array z of some peak

#index2 = energies>Xlo[3]
#index3 = energies<Xhi[3]
#index4 = index2*index3
index2 = energies>0.0
index3 = energies<15.0
index4 = index2*index3
print index4
z = energies[index4]
t = tdays[index4]

# plotting the peak
plt.figure(figsize=(8,6))
#plt.hist(z)
lch.hist_err(z)
#plt.xlabel('amplitude')
plt.xlabel('Energy (keVee)')
plt.ylabel('number of events')

##########################################
# plotting the time for the peak
plt.figure()
plt.hist(t,bins=100)
plt.xlabel('time')
plt.ylabel('number of events')

for h_l in H_L:
    tau = h_l / np.log(2)

    t0 = 0
Exemplo n.º 13
0
        #print(muonpt[j])
    njets = tree.njet
    jetpt = tree.jetpt

    nmuons.append(nmuon)
    njets.append(njet)
    for m in range(nmuon):
        mupt.append(muonpt[m])

    for j in range(njet):
        jpt.append(jetpt[j])

mupt = np.array(mupt)

plt.figure()
lch.hist_err(mupt[mupt > 0], range=(0, 100))
plt.xlabel("Muon p$_T$ (GeV/c)", fontsize=18)
#plt.yscale('log',nonposy = 'clip')
plt.tight_layout()
plt.savefig('muonpt0.png')

plt.figure()
lch.hist_err(mupt[mupt > 10], range=[0, 100])
plt.xlabel("Muon p$_T$ (GeV/c)", fontsize=18)
plt.tight_layout()
plt.savefig('muonpt1.png')

plt.figure()
lch.hist_err(jpt, range=(0, 300))
plt.xlabel("Jet p$_T$ (GeV/c)", fontsize=18)
plt.tight_layout()
def main():

    ############################################################################
    # Parse the command lines.
    ############################################################################
    parser = argparse.ArgumentParser()
    parser.add_argument('--fit', dest='fit', type=int,\
            default=0, help='Which fit to perform (0,1,2)')
    parser.add_argument('--verbose', dest='verbose', action='store_true',\
            default=False, help='Verbose output')
    parser.add_argument('--rt-parameters', dest='rt_parameters', type=str,\
            default='risetime_parameters_risetime_determination_nicole.py', help='File of rise-time parameters determined from wavelet or pulser data.')
    parser.add_argument('--batch', dest='batch', action='store_true',\
            default=False, help='Run in batch mode (exit on completion).')

    args = parser.parse_args()

    #tag = 'data_constrained_with_pulser_mean20_sigma20_slowsigfloat'
    #tag = 'data_constrained_with_pulser'
    #tag = 'data_constrained_with_simulated_Nicole'

    ############################################################################

    '''
    if args.help:
        parser.print_help()
        exit(-1)
    '''

    # Read in the parameters from the file passed in on the commandline
    rt_parameters_filename = args.rt_parameters.rstrip('.py')
    tag = rt_parameters_filename
    print(("Rise-time parameters_filename: %s" % (rt_parameters_filename)))
    rt_parameters_file = __import__(rt_parameters_filename)
    risetime_parameters = getattr(rt_parameters_file,'risetime_parameters')

    fast_mean_rel_k,fast_sigma_rel_k,fast_num_rel_k,fast_mean0_k,fast_sigma0_k,fast_num0_k = risetime_parameters()

    ############################################################################
    # Read in the data
    ############################################################################
    infile_name = 'data/LE.txt'
    #infile_name = 'data/HE.txt'
    #infile_name = 'data/pulser_data.dat'
    tdays,energies,rise_times = get_3yr_cogent_data(infile_name,first_event=first_event,calibration=0)
    print (tdays)
    print (energies)
    print (rise_times)

    print (energies)
    if args.verbose:
        print_data(energies,tdays,rise_times)

    #data = [energies.copy(),tdays.copy()]
    #print "data before range cuts: ",len(data[0]),len(data[1])

    # 3yr data
    data = [energies.copy(),tdays.copy(),rise_times.copy()]
    print(("data before range cuts: ",len(data[0]),len(data[1]),len(data[2])))
    #exit()


    ############################################################################
    # Declare the ranges.
    ############################################################################
    ranges,subranges,nbins = parameters.fitting_parameters(args.fit)
    
    bin_widths = np.ones(len(ranges))
    for i,n,r in zip(list(range(len(nbins))),nbins,ranges):
        bin_widths[i] = (r[1]-r[0])/n

    # Cut events out that fall outside the range.
    data = cut_events_outside_range(data,ranges)
    data = cut_events_outside_subrange(data,subranges[1],data_index=1)

    if args.verbose:
        print_data(energies,tdays)

    print(("data after  range cuts: ",len(data[0]),len(data[1])))

    nevents = float(len(data[0]))

    plt.figure()
    plt.plot(energies,rise_times,'o',markersize=1.5)
    plt.yscale('log')
    plt.ylim(0.1,10)

    plt.figure()
    plt.plot(tdays,rise_times,'o',markersize=1.5)
    plt.yscale('log')
    plt.ylim(0.1,10)

    ############################################################################
    # Plot the data
    ############################################################################
    ############################################################################
    # Look at the rise-time information.
    ############################################################################

    # For the data (two lognormals)
    #starting_params = [-0.6,0.6,0.2*nevents,  0.1,0.8,0.8*nevents]
    # For the pulser fast rise times (two lognormals)
    starting_params = [-0.6,0.5,0.6*nevents,  0.5,0.8,0.4*nevents]


    fit_parameters = []
    fit_errors = []
    fit_mnerrors = []
    nevs = []
    axrt = []

    elo = 0.0
    ehi = 1.0
    eoffset = 0.5

    ewidth = 0.100
    estep = 0.100

    #ewidth = 0.150
    #estep = 0.150 

    #ewidth = 0.200
    #estep = 0.050

    expts = []

    figcount = 0
    maxrange = int((ranges[0][1]-ranges[0][0])/ewidth)
    #for i in range(48,-1,-1):
    for i in range(0,maxrange):
        #j = 48-i
        j = i
        if j%6==0:
            figrt = plt.figure(figsize=(12,6),dpi=100)
        axrt.append(figrt.add_subplot(2,3, i%6 + 1))

        #figrt = plt.figure(figsize=(6,4),dpi=100)
        #axrt.append(figrt.add_subplot(1,1,1))

        data_to_fit = []
        #h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(data[1],bins=nbins[1],range=ranges[1],axes=ax1)

        if i>=0:
            elo = i*estep + eoffset
            ehi = elo + ewidth
            index0 = data[0]>=elo
            index1 = data[0]< ehi
            print((elo,ehi))
            index = index0*index1
            data_to_fit = data[2][index]

        if len(data_to_fit)>0:
            lch.hist_err(data_to_fit,bins=nbins[2],range=ranges[2],axes=axrt[j])
            plt.ylim(0)
            plt.xlim(ranges[2][0],ranges[2][1])
            name = "%0.2f-%0.2f" % (elo,ehi)
            plt.text(0.75,0.75,name,transform=axrt[j].transAxes)
            print ("=======-------- E BIN ----------===========")
            print (name)

        emid = (elo+ehi)/2.0
        #print "HERE ------------------------------- emid: ",emid

        # The entries for the narrow peak parameters.
        fast_mean0 = expfunc(fast_mean0_k,emid)
        fast_sigma0 = expfunc(fast_sigma0_k,emid)
        fast_num0 = expfunc(fast_num0_k,emid)

        # USE THIS FOR THE GAUSSIAN CONSTRAINT
        fast_mean0_optimal = fast_mean0
        fast_mean0_uncert = 0.30*fast_mean0

        fast_sigma0_optimal = fast_sigma0
        fast_sigma0_uncert = 0.30*fast_sigma0

        # The entries for the relationship between the broad and narrow peak.
        fast_mean_rel = expfunc(fast_mean_rel_k,emid)
        fast_sigma_rel = expfunc(fast_sigma_rel_k,emid)
        fast_logn_num_rel = expfunc(fast_num_rel_k,emid)

        fast_mean1 = fast_mean0 - fast_mean_rel
        fast_sigma1 = fast_sigma0 - fast_sigma_rel
        fast_num1 = fast_num0 / fast_logn_num_rel

        fast_logn_frac0 = fast_num0/(fast_num0+fast_num1)

        nevents = len(data_to_fit)
        print(("Nevents for this fit: ",nevents))
        #starting_params = [-0.1,0.8,0.2*nevents,  0.6,0.52,0.8*nevents]

        print((starting_params[4]))
        #exit()
        
        ############################################################################
        # Declare the fit parameters
        ############################################################################
        params_dict = {}
        params_dict['flag'] = {'fix':True,'start_val':args.fit} 
        params_dict['var_rt'] = {'fix':True,'start_val':0,'limits':(ranges[2][0],ranges[2][1])}

        params_dict['emid'] = {'fix':True,'start_val':emid,'limits':(ranges[0][0],ranges[0][1])}

        params_dict['fast_logn_mean0'] = {'fix':False,'start_val':fast_mean0,'limits':(-2,2),'error':0.01}
        params_dict['fast_logn_sigma0'] = {'fix':False,'start_val':fast_sigma0,'limits':(0.05,30),'error':0.01}
        params_dict['fast_logn_frac0'] = {'fix':True,'start_val':fast_logn_frac0,'limits':(0.0001,1.0),'error':0.01}

        #params_dict['fast_num'] = {'fix':False,'start_val':0.5*nevents,'limits':(0.0,1.5*nevents),'error':0.01}
        params_dict['fast_num'] = {'fix':False,'start_val':starting_params[2],'limits':(0.0,1.5*nevents),'error':0.01}

        params_dict['fast_logn_sigma0_optimal'] = {'fix':True,'start_val':fast_sigma0_optimal}
        params_dict['fast_logn_sigma0_uncert'] = {'fix':True,'start_val':fast_sigma0_uncert}

        params_dict['fast_logn_mean0_optimal'] = {'fix':True,'start_val':fast_mean0_optimal}
        params_dict['fast_logn_mean0_uncert'] = {'fix':True,'start_val':fast_mean0_uncert}

        #params_dict['fast_logn_mean1'] = {'fix':False,'start_val':starting_params[0],'limits':(-2,2),'error':0.01}
        #params_dict['fast_logn_sigma1'] = {'fix':False,'start_val':starting_params[1],'limits':(0.05,30),'error':0.01}
        #params_dict['fast_num1'] = {'fix':False,'start_val':nevents,'limits':(0.0,1.5*nevents),'error':0.01}

        # float them
        params_dict['slow_logn_mean'] = {'fix':False,'start_val':starting_params[3],'limits':(-2,2),'error':0.01}
        params_dict['slow_logn_sigma'] = {'fix':False,'start_val':starting_params[4],'limits':(0.05,30),'error':0.01}
        params_dict['slow_num'] = {'fix':False,'start_val':starting_params[5],'limits':(0.0,1.5*nevents),'error':0.01}

        # Fixed values
        params_dict['fast_mean_rel_k_0'] = {'fix':True,'start_val':fast_mean_rel_k[0],'limits':(-1e6,1e6),'error':0.01}
        params_dict['fast_mean_rel_k_1'] = {'fix':True,'start_val':fast_mean_rel_k[1],'limits':(-1e6,1e6),'error':0.01}
        params_dict['fast_mean_rel_k_2'] = {'fix':True,'start_val':fast_mean_rel_k[2],'limits':(-1e6,1e6),'error':0.01}

        params_dict['fast_sigma_rel_k_0'] = {'fix':True,'start_val':fast_sigma_rel_k[0],'limits':(-1e6,1e6),'error':0.01}
        params_dict['fast_sigma_rel_k_1'] = {'fix':True,'start_val':fast_sigma_rel_k[1],'limits':(-1e6,1e6),'error':0.01}
        params_dict['fast_sigma_rel_k_2'] = {'fix':True,'start_val':fast_sigma_rel_k[2],'limits':(-1e6,1e6),'error':0.01}

        params_dict['fast_num_rel_k_0'] = {'fix':True,'start_val':fast_num_rel_k[0],'limits':(-1e6,1e6),'error':0.01}
        params_dict['fast_num_rel_k_1'] = {'fix':True,'start_val':fast_num_rel_k[1],'limits':(-1e6,1e6),'error':0.01}
        params_dict['fast_num_rel_k_2'] = {'fix':True,'start_val':fast_num_rel_k[2],'limits':(-1e6,1e6),'error':0.01}

        '''
        if i==7:
            params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.57,'limits':(-2,2),'error':0.01}
        elif i==8:
            params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.55,'limits':(-2,2),'error':0.01}
        '''

        # Above some value, lock this down.
        '''
        if elo>=2.2:
            params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.0,'limits':(-2,2),'error':0.01}
            params_dict['slow_logn_sigma'] = {'fix':True,'start_val':1.0,'limits':(0.05,30),'error':0.01}
            params_dict['slow_num'] = {'fix':True,'start_val':1,'limits':(0.0,1.5*nevents),'error':0.01}
        '''

        '''
        if i==0:
            None
            # From Nicole's simulation.
            #params_dict['fast_logn_mean'] = {'fix':True,'start_val':-0.10,'limits':(-2,2),'error':0.01}
            # From Juan
            #params_dict['fast_logn_mean'] = {'fix':True,'start_val':-0.60,'limits':(-2,2),'error':0.01}
            #params_dict['slow_logn_sigma'] = {'fix':True,'start_val':0.50,'limits':(0.05,30),'error':0.01}
        '''

        # Try fixing the slow sigma
        #params_dict['slow_logn_sigma'] = {'fix':True,'start_val':0.60,'limits':(-2,2),'error':0.01}

        #figrt.subplots_adjust(left=0.07, bottom=0.15, right=0.95, wspace=0.2, hspace=None,top=0.85)
        #figrt.subplots_adjust(left=0.05, right=0.98)
        #figrt.subplots_adjust(left=0.15, right=0.98,bottom=0.15)
        figrt.subplots_adjust(left=0.07, right=0.98,bottom=0.10)
        #plt.show()
        #exit()

        ############################################################################
        # Fit
        ############################################################################

        if i>=0 and len(data_to_fit)>0:
            params_names,kwd = fitutils.dict2kwd(params_dict)
        
            #print data_to_fit
            f = fitutils.Minuit_FCN([[data_to_fit]],params_dict,emlf)

            # For maximum likelihood method.
            kwd['errordef'] = 0.5
            kwd['print_level'] = 0
            #print kwd

            m = minuit.Minuit(f,**kwd)

            m.print_param()

            m.migrad()
            #m.hesse()
            m.minos()

            print ("Finished fit!!\n")

            values = m.values # Dictionary
            errors = m.errors # Dictionary
            mnerrors = m.get_merrors()
            print ("MNERRORS: ")
            print (mnerrors)
            fit_parameters.append(values)
            fit_errors.append(errors)
            fit_mnerrors.append(mnerrors)
            nevs.append(len(data_to_fit))

            xpts = np.linspace(ranges[2][0],ranges[2][1],1000)
            tot_ypts = np.zeros(len(xpts))

            # The entries for the relationship between the broad and narrow peak.
            fast_logn_mean_rel = expfunc(fast_mean_rel_k,values['emid'])
            fast_logn_sigma_rel = expfunc(fast_sigma_rel_k,values['emid'])
            fast_logn_num_rel = expfunc(fast_num_rel_k,values['emid'])

            fast_logn_mean1 = values['fast_logn_mean0'] - fast_logn_mean_rel
            fast_logn_sigma1 = values['fast_logn_sigma0'] - fast_logn_sigma_rel

            tot_ypts_fast = np.zeros(len(xpts))

            ypts  = pdfs.lognormal(xpts,values['fast_logn_mean0'],values['fast_logn_sigma0'],ranges[2][0],ranges[2][1])
            y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=values['fast_logn_frac0']*values['fast_num'],fmt='r--',linewidth=2,axes=axrt[j])
            tot_ypts += y
            tot_ypts_fast += y
            # Only plot the second narrow bump above some value.
            if emid<=3.9: 
                ypts  = pdfs.lognormal(xpts,fast_logn_mean1,fast_logn_sigma1,ranges[2][0],ranges[2][1])
                y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=(1.0-values['fast_logn_frac0'])*values['fast_num'],fmt='r--',linewidth=2,axes=axrt[j])
                tot_ypts += y
                tot_ypts_fast += y

            ypts  = pdfs.lognormal(xpts,values['slow_logn_mean'],values['slow_logn_sigma'],ranges[2][0],ranges[2][1])
            y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=values['slow_num'],fmt='b-',linewidth=2,axes=axrt[j])
            tot_ypts += y

            axrt[j].plot(xpts,tot_ypts_fast,'r-',linewidth=2)

            axrt[j].plot(xpts,tot_ypts,'m',linewidth=2)
            axrt[j].set_ylabel(r'Events')
            axrt[j].set_xlabel(r'Rise time ($\mu$s)')
            axrt[j].set_xlim(0,5.0)
            if j%6==5:
                name = "Plots/rt_slice_%s_%d.png" % (tag,figcount)
                plt.savefig(name)
                figcount += 1

            #'''
            if math.isnan(values['fast_logn_mean0']) == False:
                starting_params = [ \
                values['fast_logn_mean0'], \
                values['fast_logn_sigma0'], \
                values['fast_num'], \
                values['slow_logn_mean'], \
                values['slow_logn_sigma'],
                values['slow_num'] \
                ]
            #'''

            expts.append((ehi+elo)/2.0)

    #plt.show()
    #exit()
    print (fit_parameters)
    print (nevs)
    
    ypts = [[],[],[],[],[],[]]
    yerr = [[],[],[],[],[],[]]
    yerrlo = [[],[],[],[],[],[]]
    yerrhi = [[],[],[],[],[],[]]
    npts = []

    if len(expts)>0:
        #for i,fp,fe,n in zip(xrange(len(nevs)),fit_parameters,fit_errors,nevs):
        for i,fp,fe,n in zip(list(range(len(nevs))),fit_parameters,fit_mnerrors,nevs):
            print ("----------")
            #ypts[0].append(fp['fast_logn_mean'])
            #ypts[1].append(fp['fast_logn_sigma'])
            #ypts[2].append(fp['fast_num'])
            #ypts[3].append(fp['slow_logn_mean'])
            #ypts[4].append(fp['slow_logn_sigma'])
            #ypts[5].append(fp['slow_num'])

            pars = ['fast_logn_mean0','fast_logn_sigma0','fast_num',\
                    'slow_logn_mean','slow_logn_sigma','slow_num']

            for i,p in enumerate(pars):
                #print "key ",p
                #if fe.has_key(p):
                if p in fe:
                    ypts[i].append(fp[p])
                    #print "val: ",fp[p]
                    yerrlo[i].append(abs(fe[p]['lower']))
                    yerrhi[i].append(abs(fe[p]['upper']))
                elif p=='slow_logn_sigma':
                    ypts[i].append(starting_params[4])
                    yerrlo[i].append(0.0)
                    yerrhi[i].append(0.0)
                else:
                    ypts[i].append(0.0)
                    yerrlo[i].append(0.0)
                    yerrhi[i].append(0.0)


            npts.append(n)

        for i in range(len(ypts)):
            ypts[i] = np.array(ypts[i])
            yerrlo[i] = np.array(yerrlo[i])
            yerrhi[i] = np.array(yerrhi[i])

        colors = ['r','b']
        labels = ['fast','slow']

        # Use all or some of the points
        nfitpts = len(expts)

        
        #xp = np.linspace(min(expts),max(expts),100)
        print ("herherherkehre")
        print (nfitpts)
        print (expts)
        xp = np.linspace(min(expts),expts[nfitpts-1],100)
        expts = np.array(expts)

        yfitpts = []

        '''
        fvals2 = plt.figure(figsize=(13,6),dpi=100)

        for k in range(0,3):
            # Some of the broad rise times are set to 0.
            #index0s = ypts[3+k]!=0
            index0s = np.ones(len(ypts[3+k])).astype(bool)
            #index0s = np.ones(nfitpts).astype(bool)

            fvals2.add_subplot(2,3,k+1)

            tempypts = ypts[0+k]-ypts[3+k]
            # Fractional error
            tempyerrlo = np.sqrt((yerrlo[0+k])**2 + (yerrlo[3+k])**2)
            tempyerrhi = np.sqrt((yerrhi[0+k])**2 + (yerrhi[3+k])**2)
            if k>1:
                tempypts = ypts[0+k][index0s]/ypts[3+k][index0s]
                tempyerrlo = np.sqrt((yerrlo[0+k][index0s]/ypts[3+k][index0s])**2 + (yerrlo[3+k][index0s]*(ypts[0+k][index0s]/(ypts[3+k][index0s]**2)))**2)
                tempyerrhi = np.sqrt((yerrhi[0+k][index0s]/ypts[3+k][index0s])**2 + (yerrhi[3+k][index0s]*(ypts[0+k][index0s]/(ypts[3+k][index0s]**2)))**2)

            print expts
            print index0s
            print expts[index0s]
            print tempypts[index0s]
            print tempyerrlo[index0s]
            print tempyerrhi[index0s]
            plt.errorbar(expts[index0s],tempypts[index0s],xerr=0.01,yerr=[tempyerrlo[index0s],tempyerrhi[index0s]],\
                    fmt='o',ecolor='k',mec='k',mfc='m',label='Ratio')

            plt.xlim(0.5,3.5)


            ########################################################################
            # Fit to exponentials.
            ########################################################################
            pinit = [1,1,1]
            if k==0:
                pinit = [1.0, 1.0, -1.2]
            elif k==1:
                pinit = [1.0, -1.0, -0.5]
            elif k==2:
                pinit = [-2.0, 1.0, 2.0]
            
            index = np.arange(0,len(tempypts))
            print "WHHHHYYYYYY"
            print expts
            print index
            print expts[index]
            print tempypts[index]
            print tempyerrlo[index]
            print tempyerrhi[index]
            if sum(tempypts[index]) > 0:
                out = leastsq(errfunc, pinit, args=(expts[index], tempypts[index], (tempyerrlo[index]+tempyerrhi[index])/2.0), full_output=1)
                z = out[0]
                zcov = out[1]
                print "Differences and ratios: %d [%f,%f,%f]" % (k,z[0],z[1],z[2])
                #print "zcov: ",zcov
                if zcov is not None:
                    print "Differences and ratios: %d [%f,%f,%f]" % (k,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]),np.sqrt(zcov[2][2]))
                yfitpts = expfunc(z,xp)
                #print zcov
                plt.plot(xp,yfitpts,'-',color='m')


        '''

        ########################################################################
        # Try to fit the individual distributions.
        ########################################################################

        # To hold the means and widths for the fast and slow rise-time distributions.
        means = []
        sigmas = []

        yfitpts = []
        for i in range(0,6):
            yfitpts.append(np.zeros(len(xp)))

        fvals = plt.figure(figsize=(13,4),dpi=100)
        for k in range(0,3):
            fvals.add_subplot(1,3,k+1)
            for ik in range(0,2):
                nindex = k+3*ik
                plt.errorbar(expts,ypts[nindex],xerr=0.01,yerr=[yerrlo[nindex],yerrhi[nindex]],\
                        fmt='o',ecolor='k',mec='k',mfc=colors[ik],label=labels[ik])

                #'''
                # Use part of the data
                #index0 = np.arange(0,3)
                #index1 = np.arange(7,len(expts))
                #index = np.append(index0,index1)

                # Use all or some of the points
                index = np.arange(0,len(expts))
                #index = np.arange(0,20)
                if ik>0:
                    index = np.arange(0,len(expts))
                #print index
                index = index[index!=7]
                index = index[index!=8]
                index = index[index!=17]
                index = index[index!=18]
                index = index[index!=19]

                ########################################################################
                # Fit to exponentials.
                ########################################################################
                pinit = [1,1,1]
                if ik==0 and k==0:
                    pinit = [1.0, 1.0, -1.2]
                elif ik==0 and k==1:
                    pinit = [4.0, 2.0, 0.0]
                elif ik==0 and k==2:
                    pinit = [2.0, 2000.0, 300.0]
                elif ik==1 and k==0:
                    pinit = [3.0, 1.5, 0.5]
                elif ik==1 and k==1:
                    pinit = [0.5, -0.1] # For linear ft
                    #pinit = [0.0001, 0.0001, starting_params[4]] # For exponential
                
                #print "before fit: ",ypts[nindex][index],yerrlo[nindex][index],yerrhi[nindex][index]
                print(("Fitting data!!!!!! --------------- %d %d" % (k,ik)))
                #print "before fit: ",ypts[nindex][index]
                if abs(sum(ypts[nindex][index])) > 0 and k<2:
                    print ("FITTING -----------")
                    #print expts[index]
                    #print ypts[nindex][index]
                    if k==1 and ik==1: ########## FIT WITH LINEAR TERM FOR SLOW SIGMA
                        out = leastsq(errfunc1, pinit, args=(expts[index], ypts[nindex][index], (yerrlo[nindex][index]+yerrhi[nindex][index])/2.0), full_output=1)
                        z = out[0]
                        zcov = out[1]
                        print(("Data points: %d %d [%f,%f]" % (k,ik,z[0],z[1])))
                        sigmas.append([z[0],z[1]])
                        '''
                        if zcov is not None:
                            print "Data points: %d %d [%f,%f]" % (k,ik,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]))
                        '''
                        yfitpts[nindex] = expfunc1(z,xp)
                        #print zcov
                        #print plt.gca()
                        plt.plot(xp,yfitpts[nindex],'-',color=colors[ik])
                    else:
                        out = leastsq(errfunc, pinit, args=(expts[index], ypts[nindex][index], (yerrlo[nindex][index]+yerrhi[nindex][index])/2.0), full_output=1)
                        z = out[0]
                        zcov = out[1]
                        print(("Data points: %d %d [%f,%f,%f]" % (k,ik,z[0],z[1],z[2])))
                        if k==1 and ik==0:
                            sigmas.append([z[0],z[1],z[2]])
                        elif k==0:
                            means.append([z[0],z[1],z[2]])

                        '''
                        if zcov is not None:
                            print "Data points: %d %d [%f,%f,%f]" % (k,ik,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]),np.sqrt(zcov[2][2]))
                        '''
                        yfitpts[nindex] = expfunc(z,xp)
                        #print zcov
                        #print plt.gca()
                        plt.plot(xp,yfitpts[nindex],'-',color=colors[ik])

            if k==0:
                plt.ylim(-1.5,1.5)
            elif k==1:
                plt.ylim(0.0,1.5)
            plt.xlabel('Energy (keVee)')
            if k==0:
                plt.ylabel(r'Lognormal $\mu$')
            elif k==1:
                plt.ylabel(r'Lognormal $\sigma$')
            elif k==2:
                plt.ylabel(r'Number of events')
            plt.legend()

        #fval
        '''
        fvals.add_subplot(2,3,4)
        plt.plot(xp,yfitpts[3]-yfitpts[0],'-',color='m')

        fvals.add_subplot(2,3,5)
        plt.plot(xp,yfitpts[4]-yfitpts[1],'-',color='m')

        fvals.add_subplot(2,3,6)
        plt.plot(xp,yfitpts[5]/yfitpts[2],'-',color='m')
        '''

        fvals.subplots_adjust(left=0.10, right=0.98,bottom=0.15,wspace=0.25,hspace=0.25)
        name = 'Plots/rt_summary_%s_0.png' % (tag)
        plt.savefig(name)

        np.savetxt('rt_parameters.txt',[expts,ypts[0],ypts[1],ypts[2],ypts[3],ypts[4],ypts[5],npts])

        #'''

    #print "Sum ypts[5]: ",sum(ypts[5])
    print (means)
    print (sigmas)
    print((fast_mean_rel_k,fast_sigma_rel_k,fast_num_rel_k))

    outfilename = "risetime_parameters_from_data_%s.py" % (tag)
    outfile = open(outfilename,'w')
    outfile.write("def risetime_parameters():\n\n")

    output = "\n\t%s = [%f,%f,%f]\n" % ("fast_mean_rel_k",fast_mean_rel_k[0],fast_mean_rel_k[1],fast_mean_rel_k[2])
    outfile.write(output)
    output = "\t%s = [%f,%f,%f]\n" % ("fast_sigma_rel_k",fast_sigma_rel_k[0],fast_sigma_rel_k[1],fast_sigma_rel_k[2])
    outfile.write(output)
    output = "\t%s = [%f,%f,%f]\n" % ("fast_num_rel_k",fast_num_rel_k[0],fast_num_rel_k[1],fast_num_rel_k[2])
    outfile.write(output)
    output = "\n\t%s = [%f,%f,%f]\n" % ("mu0",means[0][0],means[0][1],means[0][2])
    outfile.write(output)
    output = "\t%s = [%f,%f,%f]\n" % ("sigma0",sigmas[0][0],sigmas[0][1],sigmas[0][2])
    outfile.write(output)
    output = "\n\t%s = [%f,%f,%f]\n" % ("mu1",means[1][0],means[1][1],means[1][2])
    outfile.write(output)
    output = "\t%s = [%f,%f] # This has only two parameters.\n" % ("sigma1",sigmas[1][0],sigmas[1][1])
    outfile.write(output)
    output = "\n\treturn fast_mean_rel_k,fast_sigma_rel_k,fast_num_rel_k,mu0,sigma0,mu1,sigma1\n"
    outfile.write(output)

        




    if not args.batch:
        plt.show()
Exemplo n.º 15
0
fig0 = plt.figure(figsize=(12,4),dpi=100)
ax00 = fig0.add_subplot(1,2,1)
ax01 = fig0.add_subplot(1,2,2)

################################################################################
# Generate the fitting templates
################################################################################

mu = 2.0
sigma = 0.2
ngen = 100000
nbins = 100
ranges = [0.0, 5.0]

data = np.random.normal(mu,sigma,ngen)
h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(data,bins=nbins,range=ranges,axes=ax00)

norm = float(sum(ypts))
template0 = [xpts.copy(),ypts.copy()/norm]

yexp = stats.expon(loc=0.0,scale=6.0)
data = yexp.rvs(ngen)
data = data[data<ranges[1]]

h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(data,bins=nbins,range=ranges,axes=ax01)

norm = float(sum(ypts))
template1 = [xpts.copy(),ypts.copy()/norm]

print template0
print template1
Exemplo n.º 16
0
    tree.GetEntry(i)

    jetbtag = tree.jetbtag
    jpt = tree.jetpt
    njets = tree.njet

    for j in range(njets):
        btags.append(jetbtag[j])
        jetpt.append(jpt[j])
        #print(jetbtag[j])

btags = np.array(btags)
jetpt = np.array(jetpt)

plt.figure()
lch.hist_err(btags, bins=100, range=(0, 1.25))
plt.xlabel("b-tagging variable", fontsize=18)

plt.figure()
lch.hist_err(btags[jetpt < 30], bins=100, range=(0, 1.25))
plt.xlabel("CSV2 b-tag output, jet p$_T < $ 30", fontsize=18)
plt.savefig('/home/me25hage/Top_BNV/test/images/btagminus30.png')
#plt.savefig('btagminus.png')

plt.figure()
#lch.hist_err(btags[jetpt>=30],bins=100,range=(0,1.25))
plt.hist(btags[jetpt >= 30], bins=100, range=(0, 1.25))
plt.xlabel("CSV2 b-tag output, jet p$_T >= $ 30", fontsize=18)
plt.savefig("/home/me25hage/Top_BNV/test/images/btagplus30.png")

plt.figure()
    t0=d_tools.return_top_decays(pdgs)
    


    top_pt.append(pts[t0[0][0]])
    top_pt.append(pts[t0[1][0]])        

    W_pt.append(pts[t0[0][1]])
    W_pt.append(pts[t0[1][1]])
        
    bottom_pt.append(pts[t0[0][2]])
    bottom_pt.append(pts[t0[1][2]])

plt.figure(1)
#plt.hist(top_pt,bins=50)
lkn.hist_err(top_pt,bins=50, range=[400,600])
plt.title(r"$t$ $\bar{t}$ $p$$_t$")

'''plt.figure(2)
#plt.hist(W_pt,bins=50)
lkn.hist_err(W_pt,bins=50)
plt.title("W and Anti_W Pt")'''

plt.figure(3)
#plt.hist(bottom_pt,bins=50)
lkn.hist_err(bottom_pt,bins=50)
plt.title(r"$b$ $\bar{b}$ $p$$_t$")


plt.figure (4)
#plt.hist(muon_pt,bins=50)
                     top=0.95,
                     left=0.10,
                     right=0.95)

ax0.set_xlim(ranges[0])
#ax0.set_ylim(0.0,50.0)
#ax0.set_ylim(0.0,92.0)
ax0.set_xlabel("Ionization Energy (keVee)", fontsize=12)
ax0.set_ylabel("Events/0.025 keVee", fontsize=12)

ax1.set_xlim(ranges[1])

ax1.set_xlabel("Days since 12/4/2009", fontsize=12)
ax1.set_ylabel("Event/30.6 days", fontsize=12)

lch.hist_err(data[0], bins=nbins[0], range=ranges[0], axes=ax0)
h, xpts, ypts, xpts_err, ypts_err = lch.hist_err(data[1],
                                                 bins=nbins[1],
                                                 range=ranges[1],
                                                 axes=ax1)

ax1.set_ylim(0.0, 600)

# Do an acceptance correction of some t-bins by hand.
tbwidth = (ranges[1][1] - ranges[1][0]) / float(nbins[1])
acc_corr = np.zeros(len(ypts))
# For 15 bins
#acc_corr[2] = tbwidth/(tbwidth-7.0)
#acc_corr[3] = tbwidth/(tbwidth-6.0)
#acc_corr[10] = tbwidth/(tbwidth-3.0)
# For 30 bins
    ntops.append(ntop)
    combos.append(ncombos)
                   
    ##################################################################
    #### Find number of jets for QCD
    ##################################################################
    QCD_jets.append(len(jets))
    




#plt.figure(figsize=(9,9))

'''plt.figure(1)
#plt.subplot(3,3,1)
#plt.hist(invariant_mass_W,bins=150,range=(0,400))
lkn.hist_err(invariant_mass_W,bins=200,range=(0,400))
name = r"Hadronic Decay of W $%s$" % (sys.argv[1].split('/')[-1])
plt.title(name)
plt.ylabel(r"Frequency")
plt.xlabel(r"Invariant Mass")'''

'''plt.figure(2)

#plt.subplot(1,2,1)
plt.hist(invariant_mass_Z,bins=100, range=(0,200))
#lkn.hist_err(invariant_mass_Z,bins=200)
plt.xlim([0,200])
#plt.ylim([0,250])
#find the percentage of top quark events that 
#have a pt>400

count = 0
for pt in top_pt:
    if pt > 400:
        count += 1

fraction = float(count)/len(top_pt)
print "Fraction of top with pt>400: %f" % (fraction)
'''
######################################################
tag = sys.argv[1].split('/')[-1].split('.')[0]

plt.figure()
lch.hist_err(top_mass,bins=50,range=(0,500))
plt.title("%s: Top Mass" % (tag))


'''
plt.figure()

plt.subplot(121)
lch.hist_err(top_momentum,bins=50,range=(0,1500))
plt.title("%s: Top momentum" % (tag))

plt.subplot(122)
lch.hist_err(top_pt,bins=50,range=(0,400))
plt.title("%s: Top pt" % (tag))
'''
xlo = 0.133
xhi = 0.1470
mu = (xlo + xhi) / 2
sigma = 0.0085
slope = 0.5

# Index the range of energies
index0 = energies > xlo
index1 = energies < xhi
index = index0 * index1

x = energies[index]

plt.figure()
lch.hist_err(x, bins=50)

################################################################################
# Now fit the data.
# Mean
# width
# slope
# number of events in Gaussian
# number of events in background
################################################################################
npts = len(x)
print "npts: ", npts
params_starting_vals = [mu, sigma, slope, 0.95 * npts, 0.05 * npts]
fixed_parameters = [xlo, xhi, npts]
params_final_vals = optimize.fmin(negative_log_likelihood,
                                  params_starting_vals[:],
tdays,energies = cu.get_cogent_data(infile_name,first_event=first_event,calibration=999)

# peaks go from high amplitued to low amplitude
xlo = [0.170,0.1566,0.1475,0.1330,0.120,0.106,0.106,0.106,0.97,0.088,0.080,0.073]
xhi = [0.178,0.1690,0.1565,0.1470,0.124,0.116,0.116,0.116,0.104,0.95,0.087,0.080]

index0 = energies>xlo[-1]
index1 = energies<xhi[0]
index = index0*index1

x = energies[index]

print x

plt.figure()
lch.hist_err(x,bins=200)

################################################################################
# Now fit the data.
# Mean
# width
# slope
# number of events in Gaussian
# number of events in background
################################################################################
npts = len(x)
print "npts: ",npts

mu = np.ones(len(xlo))
sigma = np.ones(len(xlo))
nsig = np.ones(len(xlo))
Exemplo n.º 23
0
    for i in range(nmuon):
        v = tree.muonpt[i]
        #print(v)
        values.append(v)

    for i in range(njet):
        v = tree.jetpt[i]
        #print(v)
        valuesjet.append(v)

values = np.array(values)
valuesjet = np.array(valuesjet)
valueselectron = np.array(valueselectron)

plt.figure()
lch.hist_err(values[values < 200])
plt.xlabel(r'$p_T \mu$')

plt.figure()
lch.hist_err(valuesjet[valuesjet < 200])
plt.xlabel(r'$p_T {\rm jets}$')

plt.figure()
lch.hist_err(valueselectron[valueselectron < 200])
plt.xlabel(r'$p_T e$')

plt.figure()
plt.subplot(1, 2, 1)
lch.hist_err(valuesmet[0])
plt.subplot(1, 2, 2)
lch.hist_err(valuesmet[1])
Exemplo n.º 24
0
plots = [numMuons, muonPX, muonPY, muonPZ, muonPT, muonE, muonPhi, muonEta]
titles = [
    "numMuons", "muonPX", "muonPY", "muonPZ", "muonPT", "muonE", "muonPhi",
    "muonEta"
]

bins = 50

plt.figure(figsize=(10, len(plots) * 5))
plt.subplots_adjust(hspace=.75)
for i, m in enumerate(plots):
    plot = plots[i]
    plt.subplot(len(plots) / 2 + 4, 2, i + 1)
    plt.hist(plot, bins)
    lch.hist_err(plot, bins)
    plt.title(titles[i])

etaDiff = []

for e in range(len(muonEta)):
    etaDiff.append(muonEta[e] - etaFunction[e])

plt.subplot(len(plots) / 2 + 4, 2, i + 2)
plt.hist(etaDiff, bins)
lch.hist_err(etaDiff, bins)
plt.title("Eta Difference")

phiDiff = []

for p in range(len(muonPhi)):
def main():

    #lumi_file_name = 'lumi_info.pkl'
    #lumi_info = pickle.load( open( lumi_file_name, "rb" ) )

    filenames = sys.argv[1:]

    #data,tot_lumi = tbt.chain_pickle_files(filenames,lumi_info)
    #print("tot_lumi: ",tot_lumi)

    T = ROOT.TChain("T")
    print("Will open files:")
    for f in filenames:
        print(f)
        T.Add(f)

    ntops = []
    topmass = []
    wmass = []
    csvs = []
    angles = []
    dRs = []
    wH = []
    njets = []
    leadmupt = []
    leadmueta = []
    subleadmupt = []
    subleadmueta = []
    metpt = []
    triggers = [[], [], [], []]

    nentries = T.GetEntries()
    for i in range(nentries):
        T.GetEntry(i)

        njets.append(T.njet)
        ntop = T.ntop
        ntops.append(ntop)
        for n in range(ntop):
            topmass.append(T.topmass[n])
            wmass.append(T.wmass[n])
            dRs.append(T.wdR[n])
            wH.append(T.wH[n])
            angles.append(T.wangle[n])

        for n in range(T.njet):
            csvs.append(T.jetcsv[n])

        leadmupt.append(T.leadmupt)
        leadmueta.append(T.leadmueta)
        subleadmupt.append(T.subleadmupt)
        subleadmueta.append(T.subleadmueta)
        metpt.append(T.METpt)

        triggers[0].append(T.trig_HLT_IsoMu24_accept)
        triggers[1].append(T.trig_HLT_IsoTkMu24_accept)
        triggers[2].append(T.trig_HLT_IsoMu22_eta2p1_accept)
        triggers[3].append(T.trig_HLT_IsoTkMu22_eta2p1_accept)

    ntops = np.array(ntops)
    topmass = np.array(topmass)
    wmass = np.array(wmass)
    csvs = np.array(csvs)
    angles = np.array(angles)
    dRs = np.array(dRs)
    wH = np.array(wH)
    njets = np.array(njets)
    leadmupt = np.array(leadmupt)
    leadmueta = np.array(leadmueta)
    subleadmupt = np.array(subleadmupt)
    subleadmueta = np.array(subleadmueta)
    metpt = np.array(metpt)
    triggers[0] = np.array(triggers[0])
    triggers[1] = np.array(triggers[1])
    triggers[2] = np.array(triggers[2])
    triggers[3] = np.array(triggers[3])
    '''
    for a in zip(topmass, wmass, csvs, angles, dRs, njets):
        print(a)
        a = np.array(a)
    '''

    ################################################################################
    plt.figure()
    plt.subplot(3, 3, 1)
    lch.hist_err(topmass, bins=100, range=(0, 600), color='k')
    plt.xlabel('Top Mass (GeV)')

    plt.subplot(3, 3, 2)
    lch.hist_err(wmass, bins=100, range=(0, 300), color='k')
    plt.xlabel('W Mass (GeV)')

    plt.subplot(3, 3, 3)
    lch.hist_err(csvs, bins=110, range=(-11, 1.1), color='k')
    plt.xlabel('CSV variable')

    plt.subplot(3, 3, 4)
    lch.hist_err(angles, bins=100, range=(0, 3.2), color='k')
    plt.xlabel('Angles')

    plt.subplot(3, 3, 5)
    #plt.plot(wmass,angles,'.',markersize=0.5,alpha=0.2)
    lch.hist_2D(wmass,
                angles,
                xbins=100,
                ybins=100,
                xrange=(0, 300),
                yrange=(0, 3.14))
    plt.xlim(50, 150)
    plt.ylim(0, 3.2)
    plt.xlabel('W Mass')
    plt.ylabel('Angles')

    plt.subplot(3, 3, 6)
    lch.hist_err(dRs, bins=100, range=(0, 3.2), color='k')
    plt.xlabel('dRs')

    plt.subplot(3, 3, 7)
    lch.hist_2D(dRs,
                angles,
                xbins=100,
                ybins=100,
                xrange=(0, 6.28),
                yrange=(0, 3.14))
    plt.xlabel('dRs')
    plt.ylabel('Angles')

    plt.subplot(3, 3, 8)
    lch.hist_err(wH, bins=100, range=(0, 250), color='k')
    plt.xlabel('scalar H')

    plt.subplot(3, 3, 9)
    lch.hist_err(ntops, bins=6, range=(0, 6), color='k')
    plt.xlabel('ntops')

    plt.tight_layout()

    ################################################################################
    # Cut on the wmass
    index = wmass > 70.0
    index *= wmass < 95.0
    #index = (np.abs(angles - dRs)<=0.45)

    plt.figure()
    plt.title('W Mass Cuts')
    plt.subplot(3, 3, 1)
    lch.hist_err(topmass[index], bins=100, range=(0, 600), color='k')
    plt.xlabel('Top Mass (GeV)')

    plt.subplot(3, 3, 2)
    lch.hist_err(wmass[index], bins=100, range=(0, 300), color='k')
    plt.xlabel('W Mass (GeV)')

    plt.subplot(3, 3, 4)
    lch.hist_err(angles[index], bins=100, range=(0, 3.2), color='k')
    plt.xlabel('Angles')

    plt.subplot(3, 3, 5)
    #plt.plot(wmass[index],angles[index],'.',markersize=0.5,alpha=0.2)
    lch.hist_2D(wmass[index],
                angles[index],
                xbins=100,
                ybins=100,
                xrange=(0, 300),
                yrange=(0, 3.14))
    plt.xlim(50, 150)
    plt.ylim(0, 3.2)
    plt.xlabel('W Mass')
    plt.ylabel('Angles')

    plt.subplot(3, 3, 6)
    lch.hist_err(dRs[index], bins=100, range=(0, 3.2), color='k')
    plt.xlabel('dRs')

    plt.subplot(3, 3, 7)
    lch.hist_2D(dRs[index],
                angles[index],
                xbins=100,
                ybins=100,
                xrange=(0, 6.28),
                yrange=(0, 3.14))
    plt.xlabel('dRs')
    plt.ylabel('Angles')

    plt.subplot(3, 3, 8)
    lch.hist_err(wH[index], bins=100, range=(0, 250), color='k')
    plt.xlabel('scalar H')

    plt.tight_layout()

    ############################################################################
    # Muons
    ############################################################################
    plt.figure()
    plt.subplot(3, 3, 1)
    lch.hist_err(leadmupt, bins=100, range=(0, 250), color='k')
    plt.xlabel(r'Leading muon p$_{T}$ (GeV/c)')

    plt.subplot(3, 3, 2)
    lch.hist_err(leadmueta, bins=100, range=(-3.0, 3.0), color='k')
    plt.xlabel(r'Leading muon $\eta$ (GeV/c)')

    plt.subplot(3, 3, 4)
    lch.hist_err(subleadmupt, bins=100, range=(0, 250), color='k')
    plt.xlabel(r'Sub-leading muon p$_{T}$ (GeV/c)')

    plt.subplot(3, 3, 5)
    lch.hist_err(subleadmueta, bins=100, range=(-3.0, 3.0), color='k')
    plt.xlabel(r'Sub-leading muon $\eta$ (GeV/c)')

    plt.subplot(3, 3, 7)
    lch.hist_err(metpt, bins=100, range=(0.0, 100.0), color='k')
    plt.xlabel(r'Missing E$_T$ (GeV)')

    plt.tight_layout()
    '''
    # For talk
    plt.figure()
    lch.hist_err(topmass[index],bins=100,range=(0,600),color='k')
    plt.hist(topmass[index],bins=100,range=(0,600),color='grey',alpha=0.2)
    plt.xlabel(r'Top candidate with W-mass cut (GeV/c$^2$)',fontsize=14)
    plt.tight_layout()
    plt.savefig('top.png')

    plt.figure()
    lch.hist_err(wmass,bins=100,range=(0,300),color='k')
    plt.hist(wmass,bins=100,range=(0,300),color='grey',alpha=0.2)
    plt.xlabel(r'W candidate (GeV/c$^2$)',fontsize=14)
    plt.tight_layout()
    plt.savefig('W.png')

    plt.figure()
    lch.hist_err(csvs,bins=110,range=(0,1.1),color='k')
    plt.hist(csvs,bins=100,range=(0,1.1),color='grey',alpha=0.2)
    plt.xlabel(r'CSVv2 variable',fontsize=14)
    plt.tight_layout()
    plt.savefig('csvv2.png')
    '''

    ############################################################################
    # Triggers
    ############################################################################
    plt.figure()
    plt.subplot(5, 4, 1)
    lch.hist_err(triggers[0], bins=2, range=(0, 2), color='k')
    plt.xlabel(r'Trigger 0')

    plt.subplot(5, 4, 2)
    lch.hist_err(triggers[1], bins=2, range=(0, 2), color='k')
    plt.xlabel(r'Trigger 1')

    plt.subplot(5, 4, 3)
    lch.hist_err(triggers[2], bins=2, range=(0, 2), color='k')
    plt.xlabel(r'Trigger 2')

    plt.subplot(5, 4, 4)
    lch.hist_err(triggers[3], bins=2, range=(0, 2), color='k')
    plt.xlabel(r'Trigger 3')

    for i in range(0, 4):
        for j in range(0, 4):
            plt.subplot(5, 4, 5 + i * 4 + j)
            lch.hist_err(triggers[i][triggers[j] == 1], bins=2, range=(0, 2))

    plt.tight_layout()

    plt.show()
        p_photons[npp] = p
        npp += 1
    
    p = mets(met)
    p_met[nm] = p
    nm += 1

###########################################################################
tag = sys.argv[1].split('/')[-1].split('.')[0]

print "Making the plots....."
# Histograms of momentum
plt.figure()

plt.subplot(321)
lch.hist_err(p_jets[p_jets>-999],bins=50,range=(0,400),fmt='o',markersize=5,color='black',ecolor='black')
plt.title("%s: Jet momentum" % (tag))
plt.locator_params(nbins=6)
#plt.xlabel("Momentum")

plt.subplot(322)
lch.hist_err(p_muons[p_muons>-999],bins=50,range=(0,300),fmt='o',markersize=5,color='red',ecolor='red')
plt.title("%s: Muon momentum" % (tag))
#plt.xlabel("Momentum")

plt.subplot(323)
lch.hist_err(p_electrons[p_electrons>-999],bins=50,range=(0,200),fmt='o',markersize=5,color='green',ecolor='green')
plt.title("%s: Electron momentum" % (tag))
#plt.xlabel("Momentum")

plt.subplot(324)

    #print days
    #print energies
    #print risetimes

    days = org_days[index]
    energies = org_energies[index]
    risetimes = org_risetimes[index]

    #print days

    if sys.argv[2]=="0" or sys.argv[2]=="2":
        ################################################################################
        fig = plt.figure(figsize=(8,4))
        ret,xpts,ypts,xpts_err,ypts_err = lch.hist_err(energies,bins=enbins,linewidth=2,range=(elo,ehi))
        name = "# interactions/ %0.2f keVee" % (ewidth)
        plt.ylabel(name,fontsize=14)
        plt.xlabel('Recoil energy (keVee)',fontsize=18)
        plt.ylim(0,25) # This might have to be changed for sliding or discrete
        plt.xlim(elo,ehi)
        if sys.argv[2]=="2":
            plt.yscale('log')
            plt.ylim(20)
        plt.tight_layout()
        name = "animation_plots/cogent_data_energy_%s_%04d.png" % (tag,i)
        plt.savefig(name)
        del ret,xpts,ypts,xpts_err,ypts_err 
        

        ################################################################################
Exemplo n.º 28
0
            val = deltat_range*np.random.rand()+deltat_min

            prob = pdfs.pdf_bmixing(val,[gamma,p_over_q,deltaM,deltaG,q1,q2])

            test = max_prob*np.random.rand()
            
            if test<prob:
                events[i] = np.append(events[i],val)
                n += 1

            subplots[0][i].set_xlim(0)

    for i in range(0,4):
        #subplots[1][i].hist(events[i],bins=50)
        figs[1].add_subplot(2,2,i+1)
        lch.hist_err(events[i],bins=50)
        subplots[1][i].set_xlim(deltat_min,deltat_max)
        subplots[1][i].set_ylim(0)
        #subplots[1][i].set_ylim(0,nevents/16)

    Npp = len(events[0])
    Nmm = len(events[1])
    Npm = len(events[2])
    Nmp = len(events[3])

    print "%d %d %d %d" % (Npp,Nmm,Npm,Nmp)

    Acp = (Npp-Nmm)/float(Npp+Nmm) 
    deltaAcp = np.sqrt((sqrt(Npp)/Npp)**2 + (sqrt(Nmm)/Nmm)**2)

    print "Acp: %f +/- %f" % (Acp,deltaAcp)
    # find left over jets that correspond to those with highest pt
    other_jets = m1[m0 == mass0[i]]
    other_pt = pt1[m0 == mass0[i]]

    # sort jets that are left to find highest pt
    index = np.argsort(other_pt)[-1]
    mass1[i] = other_jets[index]

    i += 1
    count += 1 + nvalues_for_this_event


print "Events: ", len(mass0[mass0 > 0])
plt.figure()
lch.hist_err(mass0[mass0 > 0], bins=125, range=(0, 1000))
plt.xlabel("mass0")

# plot of highest pt
plt.figure()
lch.hist_err(pt0_max[pt0_max > 0], bins=125, range=(0, 1000))
plt.xlabel("pt0_max")

plt.figure()
lch.hist_err(mass1[mass1 > 0], bins=125, range=(0, 1000))
plt.xlabel("mass1")

plt.figure()
lch.hist_2D(mass0, mass1, xbins=100, ybins=100, xrange=(0, 500), yrange=(0, 500))
plt.xlabel("mass0")
plt.ylabel("mass1")
Exemplo n.º 30
0
		#print(genpt[i])
		topPT.append(genpt[i])
        '''
print("The percent of boosted tops is: ", numBoosted/nentries*100)
print("The percent of muon decays is: ", muonCount/nentries*100)
print("The percent of electron decays is: ", electronCount/nentries*100)
print("The percent of tau decays is: ", tauCount/nentries*100)


pltLabels = ["$\Delta E (GeV)$","$\Delta p_x (GeV/c)$","$\Delta p_y (GeV/c)$","$\Delta p_z (GeV/c)$"]
#T
plt.figure()
for j in range(0,4):
    plt.subplot(2,2,j+1)
    plt.xlabel(pltLabels[j],fontsize=18)
    lch.hist_err(diffs[j],bins=125,range=(-1,1))
    plt.tight_layout()
plt.suptitle('Top')
plt.subplots_adjust(top = 0.88)

#Tbar
plt.figure()
for j in range(0,4):
    plt.subplot(2,2,j+1)
    plt.xlabel(pltLabels[j] + 'tbar',fontsize=18)
    lch.hist_err(diffsBar[j],bins=125,range=(-1,1))
    plt.tight_layout()
plt.suptitle('tbar')
plt.subplots_adjust(top = 0.88)

#W q q 
Exemplo n.º 31
0
tops = []

for i in range(nentries):
    tree.GetEntry(i)
    njets = tree.njet
    jetpt = tree.jetpt
    jeteta = tree.jeteta
    jetphi = tree.jetphi
    jete = tree.jete
    jetp4s = []

    if (njets >= 3):
        for jet in range(njets):
            jetx, jety, jetz = PTtoXYZ(jetpt[jet], jeteta[jet], jetphi[jet])
            p4 = [jete[jet], jetx, jety, jetz]
            jetp4s.append(p4)

        for j in range(njets):
            k = j + 1
            while (k < njets):
                top = invmass(jetp4s[j] + jetp4s[k])
                #print(top)
                k += 1
                #if (top <= 200 and top >= 150):
                #    print(top)
                tops.append(top)
plt.figure()
lch.hist_err(tops, bins=200)
plt.xlabel("Inv mass of 2 jets $(GeV/c^2)$")
plt.show()
Exemplo n.º 32
0
import numpy as np
import matplotlib.pylab as plt
import lichen.lichen as lch

f = ROOT.TFile(sys.argv[1])

tree = f.Get("TreeSemiLept")

nentries = tree.GetEntries()
numMuons = []
muonPX = []
muonPY = []
muonPZ = []

for entry in range(nentries):
    tree.GetEntry(entry)
    nmuon = tree.nmuon
    numMuons.append(nmuon)

    for i in range(nmuon):
        x = tree.muonpx[i]
        muonPX.append(x)

plt.subplot(211)
lch.hist_err(numMuons)
plt.subplot(212)
lch.hist_err(muonPX)

plt.show()

Exemplo n.º 33
0
# by the detector
first_event = 2750361.2

# We need to give the full path to the directory. This will obviously be 
# different on your machine, so you will want to edit this by hand. 
infile_name = '/Users/lm27apic/Documents/Dark_Matter_Research/dark_matter_data/low_gain.txt'
#infile_name = '/home/bellis/matts-work-environment/PyROOT/CoGeNT/data/low_gain.txt'
#infile_name = '/home/bellis/matts-work-environment/PyROOT/CoGeNT/data/high_gain.txt'

tdays,energies = cu.get_cogent_data(infile_name,first_event=first_event,calibration=0)

index0 = energies>0.0
index1 = energies<13.0

print len(energies)
print len(index0)
print len(index1)
index = index0*index1
x = energies[index]

plt.figure()
lch.hist_err(x,bins=250,range=(0.5,12.0))
plt.xlabel('Energy (keVee)',fontsize=18)
plt.ylabel('Number of Events',fontsize=18)
#plt.annotate('The K-shell decays',xy=(10.8,295),xytext=(10.8,310),arrowprops=dict(arrowstyle='->'))
plt.xlim(0.5,12.0)
plt.yscale('log')
plt.ylim(10)
plt.savefig('fulldata.png')
plt.show()
Exemplo n.º 34
0
fig0 = plt.figure(figsize=(12,4),dpi=100)
ax0 = fig0.add_subplot(1,2,1)
ax1 = fig0.add_subplot(1,2,2)

ax0.set_xlim(ranges[0])
#ax0.set_ylim(0.0,50.0)
#ax0.set_ylim(0.0,92.0)
ax0.set_xlabel("Ionization Energy (keVee)",fontsize=12)
ax0.set_ylabel("Events/0.025 keVee",fontsize=12)

ax1.set_xlim(ranges[1])

ax1.set_xlabel("Days since 12/4/2009",fontsize=12)
ax1.set_ylabel("Event/30.6 days",fontsize=12)

lch.hist_err(data[0],bins=nbins[0],range=ranges[0],axes=ax0)
h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(data[1],bins=nbins[1],range=ranges[1],axes=ax1)

# Do an acceptance correction of some t-bins by hand.
tbwidth = (ranges[1][1]-ranges[1][0])/float(nbins[1])
acc_corr = np.zeros(len(ypts))
# For 15 bins
#acc_corr[2] = tbwidth/(tbwidth-7.0)
#acc_corr[3] = tbwidth/(tbwidth-6.0)
#acc_corr[10] = tbwidth/(tbwidth-3.0)
# For 30 bins
#acc_corr[4] = tbwidth/(tbwidth-7.0)
#acc_corr[6] = tbwidth/(tbwidth-6.0)
#acc_corr[20] = tbwidth/(tbwidth-3.0)
# For 30 bins,full dataset
acc_corr[2] = tbwidth/(tbwidth-7.0)
Exemplo n.º 35
0
                                                    jetjeceta[jet],
                                                    jetjecphi[jet])
                p4JEC = [jetjece[jet], jetxJEC, jetyJEC, jetzJEC]
                jetp4JEC.append(p4JEC)
        if btag:
            for b in range(len(btagJets)):
                for j in range(0, len(jetp4) - 1):
                    for k in range(j + 1, len(jetp4)):
                        top.append(invmass([btagJets[b], jetp4[j], jetp4[k]]))
                        topJEC.append(
                            invmass([btagJetsJEC[b], jetp4JEC[j],
                                     jetp4JEC[k]]))
                        #print("---------")
                        #print(btagJetsJEC[b],jetp4JEC[j],jetp4JEC[k])
                        twoJets.append(invmass([jetp4[j], jetp4[k]]))
                        twoJetsJEC.append(invmass([jetp4JEC[j], jetp4JEC[k]]))

plt.figure()
lch.hist_err(top, bins=100, range=(0, 400), color='red', label='Before')
lch.hist_err(topJEC, bins=100, range=(0, 400), color='blue', label='After')
plt.xlabel("Invariant mass of 3 jets (GeV/c$^2$)", fontsize=18)
plt.legend()

plt.figure()
lch.hist_err(twoJets, bins=100, range=(0, 250), color='red', label='Before')
lch.hist_err(twoJetsJEC, bins=100, range=(0, 250), color='blue', label='After')
plt.xlabel("Invariant mass of 2 jets (GeV/c$^2$)", fontsize=18)
plt.legend()

plt.show()
#######################################################
#find the percentage of top quark events that 
#have a pt>400

count = 0
for pt in top_pt:
    if pt > 400:
        count += 1

fraction = float(count)/len(top_pt)
print "Fraction of top with pt>400: %f" % (fraction)

######################################################
tag = sys.argv[1].split('/')[-1].split('.')[0]

plt.figure()
lch.hist_err(top_mass,bins=50,range=(0,500))
plt.title("%s: Top Mass" % (tag))

plt.figure()

plt.subplot(121)
lch.hist_err(top_momentum,bins=50,range=(0,1500))
plt.title("%s: Top momentum" % (tag))

plt.subplot(122)
lch.hist_err(top_pt,bins=50,range=(0,400))
plt.title("%s: Top pt" % (tag))

plt.show()
Exemplo n.º 37
0
        #print "%-5d %-5d %8.5f" % (pdg,status,pt)

    t0 = d_tools.return_top_decays(pdgs)

    top_pt.append(pts[t0[0][0]])
    top_pt.append(pts[t0[1][0]])

    W_pt.append(pts[t0[0][1]])
    W_pt.append(pts[t0[1][1]])

    bottom_pt.append(pts[t0[0][2]])
    bottom_pt.append(pts[t0[1][2]])

plt.figure(1)
#plt.hist(top_pt,bins=50)
lkn.hist_err(top_pt, bins=50, range=[400, 600])
plt.title(r"$t$ $\bar{t}$ $p$$_t$")
'''plt.figure(2)
#plt.hist(W_pt,bins=50)
lkn.hist_err(W_pt,bins=50)
plt.title("W and Anti_W Pt")'''

plt.figure(3)
#plt.hist(bottom_pt,bins=50)
lkn.hist_err(bottom_pt, bins=50)
plt.title(r"$b$ $\bar{b}$ $p$$_t$")

plt.figure(4)
#plt.hist(muon_pt,bins=50)
lkn.hist_err(muon_pt, bins=50)
plt.title(r"$Muon$ $p$$_t$")
Exemplo n.º 38
0
def main():

    lumi_file_name = 'lumi_info.pkl'
    lumi_info = pickle.load(open(lumi_file_name, "rb"))

    filenames = sys.argv[1:]

    print("Will open files:")
    for f in filenames:
        print(f)

    data, tot_lumi = tbt.chain_pickle_files(filenames, lumi_info)
    print("tot_lumi: ", tot_lumi)

    topmass = data['topmass']
    wmass = data['wmass']
    csvs = data['csvs']
    angles = data['angles']
    dRs = data['dRs']
    #njets = data['njets']
    njets = data['njets']

    ################################################################################
    plt.figure()
    plt.subplot(3, 3, 1)
    lch.hist_err(topmass, bins=100, range=(0, 600), color='k')
    plt.xlabel('Top Mass (GeV)')

    plt.subplot(3, 3, 2)
    lch.hist_err(wmass, bins=100, range=(0, 300), color='k')
    plt.xlabel('W Mass (GeV)')

    plt.subplot(3, 3, 3)
    lch.hist_err(csvs, bins=110, range=(0, 1.1), color='k')
    plt.xlabel('Isolation Variable')

    plt.subplot(3, 3, 4)
    lch.hist_err(angles, bins=100, range=(0, 3.2), color='k')
    plt.xlabel('Angles')

    plt.subplot(3, 3, 5)
    #plt.plot(wmass,angles,'.',markersize=0.5,alpha=0.2)
    lch.hist_2D(wmass,
                angles,
                xbins=100,
                ybins=100,
                xrange=(0, 300),
                yrange=(0, 3.14))
    plt.xlim(50, 150)
    plt.ylim(0, 3.2)
    plt.xlabel('W Mass')
    plt.ylabel('Angles')

    plt.subplot(3, 3, 6)
    lch.hist_err(dRs, bins=100, range=(0, 3.2), color='k')
    plt.xlabel('dRs')

    plt.subplot(3, 3, 7)
    lch.hist_2D(dRs,
                angles,
                xbins=100,
                ybins=100,
                xrange=(0, 6.28),
                yrange=(0, 3.14))
    plt.xlabel('dRs')
    plt.ylabel('Angles')

    ################################################################################
    # Cut on the wmass
    index = wmass > 70.0
    index *= wmass < 95.0

    plt.figure()
    plt.title('W Mass Cuts')
    plt.subplot(3, 3, 1)
    lch.hist_err(topmass[index], bins=100, range=(0, 600), color='k')
    plt.xlabel('Top Mass (GeV)')

    plt.subplot(3, 3, 2)
    lch.hist_err(wmass[index], bins=100, range=(0, 300), color='k')
    plt.xlabel('W Mass (GeV)')

    plt.subplot(3, 3, 4)
    lch.hist_err(angles[index], bins=100, range=(0, 3.2), color='k')
    plt.xlabel('Angles')

    plt.subplot(3, 3, 5)
    #plt.plot(wmass[index],angles[index],'.',markersize=0.5,alpha=0.2)
    lch.hist_2D(wmass[index],
                angles[index],
                xbins=100,
                ybins=100,
                xrange=(0, 300),
                yrange=(0, 3.14))
    plt.xlim(50, 150)
    plt.ylim(0, 3.2)
    plt.xlabel('W Mass')
    plt.ylabel('Angles')

    plt.subplot(3, 3, 6)
    lch.hist_err(dRs[index], bins=100, range=(0, 3.2), color='k')
    plt.xlabel('dRs')

    plt.subplot(3, 3, 7)
    lch.hist_2D(dRs[index],
                angles[index],
                xbins=100,
                ybins=100,
                xrange=(0, 6.28),
                yrange=(0, 3.14))
    plt.xlabel('dRs')
    plt.ylabel('Angles')
    '''
    # For talk
    plt.figure()
    lch.hist_err(topmass[index],bins=100,range=(0,600),color='k')
    plt.hist(topmass[index],bins=100,range=(0,600),color='grey',alpha=0.2)
    plt.xlabel(r'Top candidate with W-mass cut (GeV/c$^2$)',fontsize=14)
    plt.tight_layout()
    plt.savefig('top.png')

    plt.figure()
    lch.hist_err(wmass,bins=100,range=(0,300),color='k')
    plt.hist(wmass,bins=100,range=(0,300),color='grey',alpha=0.2)
    plt.xlabel(r'W candidate (GeV/c$^2$)',fontsize=14)
    plt.tight_layout()
    plt.savefig('W.png')

    plt.figure()
    lch.hist_err(csvs,bins=110,range=(0,1.1),color='k')
    plt.hist(csvs,bins=100,range=(0,1.1),color='grey',alpha=0.2)
    plt.xlabel(r'CSVv2 variable',fontsize=14)
    plt.tight_layout()
    plt.savefig('csvv2.png')
    '''

    plt.show()

    return data
Exemplo n.º 39
0
################################################################################
def negative_log_likelihood(p, x, y):
    # Here you need to code up the sum of all of the negative log likelihoods (pdf)
    # for each data point.
    ret = np.sum(-1*np.log(pdf(p,x)))
    return ret

################################################################################
# Generate some fake data points
################################################################################
mu = 5.0
sigma = 0.5
x = np.random.normal(mu,sigma,1000)
plt.figure()
lch.hist_err(x,bins=25)
print x

#plt.figure()
#prob = mygauss(x,mu,1.0)
#lch.hist_err(prob,bins=25)
#print prob
#plt.show()

# Now fit the data.
params_starting_vals = [1.0,1.0]
params_final_vals = optimize.fmin(negative_log_likelihood, params_starting_vals[:],args=(x,x),full_output=True)

print "Final values"
print params_final_vals
fit_mu = params_final_vals[0][0]
    cut_bkg = cut_events_outside_subrange(cut_ranges_bkg,subranges[1],data_index=1)
    print(len(cut_bkg[0]))

    #cut_bkg = np.array(cut_bkg)
    #cut_bkg.transpose()

    #print cut_bkg

    new_bkgs.append(cut_bkg)

    for j in range(3):
        plt.subplot(1,3,j+1)
        #print cv
        #print data[j][0:10]
        if cv>0:
            lch.hist_err(data[j],color=bkg_colors[i],ecolor=bkg_colors[i])

plt.tight_layout()

print("HERE A")

fig2 = plt.figure(figsize=(12,6))
for j in range(3):
    plt.subplot(1,3,j+1)
    data = []
    colors = []
    weights = []
    for k in range(0,5):
        #print new_bkgs[k]
        if len(new_bkgs[k][j])>0:
            data.append(new_bkgs[k][j])
xlo = 0.133
xhi = 0.1470
mu = (xlo + xhi) / 2
sigma = 0.0085
slope = 0.5

# Index the range of energies
index0 = energies>xlo
index1 = energies<xhi
index = index0*index1

x = energies[index]

plt.figure()
lch.hist_err(x,bins=50)


################################################################################
# Now fit the data.
# Mean
# width
# slope
# number of events in Gaussian
# number of events in background
################################################################################
npts = len(x)
print "npts: ",npts
params_starting_vals = [mu, sigma, slope, 0.95*npts, 0.05*npts]
fixed_parameters = [xlo,xhi,npts]
params_final_vals = optimize.fmin(negative_log_likelihood, params_starting_vals[:],args=(x,fixed_parameters),full_output=True,maxiter=10000)
############################################################################
# Plot the data
############################################################################
#### THIS PART IS FOR TALKS
fig1 = plt.figure(figsize=(10,4),dpi=100)
ax11 = fig1.add_subplot(1,1,1)
fig1.subplots_adjust(left=0.08,right=0.95,bottom=0.15,top=0.95)

ax11.set_xlim(ranges[0])
#ax11.set_ylim(0.0,50.0)
#ax11.set_ylim(0.0,92.0)
ax11.set_xlabel("Ionization Energy (keVee)",fontsize=12)
ax11.set_ylabel("Events",fontsize=12)

lch.hist_err(data[0],bins=nbins[0],range=ranges[0],axes=ax11)

plt.savefig('cogent_full_range_0.png')

ax11.annotate(r'K-shell decays', xy=(9.5,350), xytext=(6,500), arrowprops=dict(facecolor='black', shrink=0.05),color='red',fontsize=24)
ax11.annotate(r'L-shell decays', xy=(1.5,300), xytext=(2,650), arrowprops=dict(facecolor='black', shrink=0.05),color='red',fontsize=24)
plt.savefig('cogent_full_range_1.png')
ax11.annotate(r'Low-mass WIMPs', xy=(2.0,200), xytext=(4,350), arrowprops=dict(facecolor='black', shrink=0.05),color='black',fontsize=24)
plt.savefig('cogent_full_range_2.png')


plt.show()
exit()


fig0 = plt.figure(figsize=(12,4),dpi=100)
#Finding top pt
    top_pt.append(pts[t0[0][0]])
    top_pt.append(pts[t0[1][0]])

    #Finding W pt
    W_pt.append(pts[t0[0][1]])
    W_pt.append(pts[t0[1][1]])

    #Finding bottom pt
    bottom_pt.append(pts[t0[0][2]])
    bottom_pt.append(pts[t0[1][2]])

plt.figure(1)
#plt.hist(top_pt,bins=50)
lkn.hist_err(top_pt, bins=100, range=(0, 300))
plt.title(r"Top and Antitop p$_T$")
plt.xlabel(r"p$_T$(GeV/c)")

plt.figure(2)
#plt.hist(W_pt,bins=50)
lkn.hist_err(W_pt, bins=100, range=(0, 300))
plt.title(r"W and Anti_W p$_T$")
plt.xlabel(r"p$_T$(GeV/c)")

plt.figure(3)
#plt.hist(bottom_pt,bins=50)
lkn.hist_err(bottom_pt, bins=100, range=(0, 300))
plt.title(r"B and Anti_b p$_T$")
plt.xlabel(r"p$_T$(GeV/c)")
Exemplo n.º 44
0
def main():
    
    ############################################################################
    # Make a figure on which to plot stuff.
    # This would be the same as making a TCanvas object.
    ############################################################################
    figs = []
    subplots = []
    for i in xrange(2):
        figs.append(plt.figure(figsize=(8,6),dpi=100,facecolor='w',edgecolor='k'))
        subplots.append([])
        for j in range(0,4):
            subplots[i].append(figs[i].add_subplot(2,2,j+1))

    ############################################################################
    # Generate values drawn from a normal (Gaussian) distribution.
    ############################################################################
    deltat_min = -20
    deltat_max =  20
    deltat_range =  deltat_max-deltat_min

    deltat_mc = []
    for i in range(0,4):
        deltat_mc.append(deltat_range*np.random.rand(10000) + deltat_min)

    print "deltat MC: %d" % (len(deltat_mc))

    deltat = np.linspace(deltat_min,deltat_max,1000)

    gamma = 1.0/1.547
    p_over_q = 1.01
    A = 1.0
    deltaM = 0.4
    deltaG = 0.0

    charges = [[+1,+1], [-1,-1], [+1,-1], [-1,+1]]

    maxes = []

    for i in range(0,4):

        q1 = charges[i][0]
        q2 = charges[i][1]
        N = pdfs.pdf_bmixing(deltat,[gamma,p_over_q,deltaM,deltaG,q1,q2])

        maxes.append(max(N))

        subplots[0][i].plot(deltat,N,'-',markersize=2)

    max_prob = max(maxes)

    #'''
    events = [np.array([]),np.array([]),np.array([]),np.array([])]
    n=0
    nevents = 1000
    print "Generating %d events." % (nevents)
    while n<nevents:

        if n%1000==0:
            print n

        for i in range(0,4):

            q1 = charges[i][0]
            q2 = charges[i][1]

            val = deltat_range*np.random.rand()+deltat_min

            prob = pdfs.pdf_bmixing(val,[gamma,p_over_q,deltaM,deltaG,q1,q2])

            test = max_prob*np.random.rand()
            
            if test<prob:
                events[i] = np.append(events[i],val)
                n += 1

    for i in range(0,4):
        #subplots[1][i].hist(events[i],bins=50)
        figs[1].add_subplot(2,2,i+1)
        lch.hist_err(events[i],bins=50)
        subplots[1][i].set_xlim(deltat_min,deltat_max)
        subplots[1][i].set_ylim(0)
        #subplots[1][i].set_ylim(0,nevents/16)

    Npp = len(events[0])
    Nmm = len(events[1])
    Npm = len(events[2])
    Nmp = len(events[3])

    print "%d %d %d %d" % (Npp,Nmm,Npm,Nmp)

    Acp = (Npp-Nmm)/float(Npp+Nmm) 
    deltaAcp = np.sqrt((sqrt(Npp)/Npp)**2 + (sqrt(Nmm)/Nmm)**2)

    print "Acp: %f +/- %f" % (Acp,deltaAcp)

    Acp = 2*(1-np.abs(1.0/p_over_q))

    print "Acp: %f" % (Acp)
    #'''

    # Fit function.
    gamma = 1.0/1.547
    p_over_q = 1.01
    A = 1.0
    deltaM = 0.4
    deltaG = 0.0
    #N = pdfs.pdf_bmixing(deltat,[gamma,p_over_q,deltaM,deltaG,q1,q2])
    n0 = Npp
    n1 = Nmm
    n2 = Npm 
    n3 = Nmp
    p0 = [gamma,p_over_q,deltaM,deltaG,n0,n1,n2,n3]
    print p0
    #p1 = sp.optimize.fmin(pdfs.extended_maximum_likelihood_function,p0,args=(events,deltat_mc), maxiter=10000, maxfun=10000)

    #print p1

    data = [events,deltat_mc]
    m = minuit.Minuit(pdfs.extended_maximum_likelihood_function_minuit,p=p0)
    print m.values
    m.migrad()

    # Need this command to display the figure.
    plt.show()
    if abs(pdgs[t0[0][3]]) > 6 and abs(pdgs[t0[1][3]]) < 6:
        if pdgs[t0[0][3]] == -11 or pdgs[t0[0][3]] == -13:
            dR_mu_b = d_tools.delta_R(etas, phis, t0[0][2], t0[0][3])
            del_R_mu_b.append(dR_mu_b[0])
        elif pdgs[t0[1][4]] == 11 or pdgs[t0[1][4]] == 13:
            dR_mu_b = d_tools.delta_R(etas, phis, t0[0][2], t0[0][4])
            del_R_mu_b.append(dR_mu_b[0])

plt.figure(1)
#plt.hist(del_R_top_antitop,bins=50)
nbins = 100
lorange = 0
hirange = 8
binwidth = (hirange - lorange) / float(nbins)
lkn.hist_err(del_R_top_antitop, bins=nbins, range=(lorange, hirange))
#plt.axis([0, 8, 0, 8])
plt.title(r" $\Delta R$ between $t$ and $\bar{t}$", fontsize=24)
plt.xlabel(r"$\Delta$R", fontsize=24)
label = r"Entries/%3.2f" % (binwidth)
plt.ylabel(label, fontsize=24)

plt.figure(2)
plt.subplot(2, 1, 1)
#plt.hist(del_R_W_B,bins=50)
lkn.hist_err(del_R_W_B, bins=100, range=(0, 8))
#plt.axis([0, 8, 0, 8])
plt.title(r"W and B $\Delta$R")
#plt.xlabel(r"$\Delta$R")

plt.subplot(2, 1, 2)
def main():

    ############################################################################
    # Parse the command lines.
    ############################################################################
    parser = argparse.ArgumentParser()
    parser.add_argument('--fit', dest='fit', type=int,\
            default=0, help='Which fit to perform (0,1,2)')
    parser.add_argument('--verbose', dest='verbose', action='store_true',\
            default=False, help='Verbose output')
    parser.add_argument('--dataset', dest='dataset', type=str,\
            default='nicole', help='Dataset to use in fitting. Nicoles simulated (nicole) or Juans pulser (juan)')
    parser.add_argument('--batch', dest='batch', action='store_true',\
            default=False, help='Run in batch mode (exit on completion).')

    args = parser.parse_args()

    ############################################################################

    #tag = 'pulser_onelognormal'
    #tag = 'pulser'
    #tag = 'pulser_zoomed_in'
    #tag = 'pulser_simulated_Nicole'
    #tag = 'pulser_simulated_Nicole_zoomed_in'
    #tag = 'pulser_simulated_Nicole_onelognormal'
    #tag = 'pulser_simulated_Nicole_no_fit'

    tag = "risetime_determination_%s" % (args.dataset)


    outfilename = "risetime_parameters_%s.py" % (tag)
    outfile = open(outfilename,'w')
    outfile.write("def risetime_parameters():\n\n")

    '''
    if args.help:
        parser.print_help()
        exit(-1)
    '''

    ############################################################################
    # Read in the data
    ############################################################################
    
    infile_name = 'data/pulser_data_325ns.dat' # SIMULATED DATA FROM NICOLE
    if args.dataset=='nicole':
        infile_name = 'data/pulser_data_325ns.dat' # SIMULATED DATA FROM NICOLE
    elif args.dataset=='juan':
        infile_name = 'data/pulser_data.dat' # FROM JUAN, 8/2/13, manually scanned pulser runs.

    tdays,energies,rise_times = get_3yr_cogent_data(infile_name,first_event=first_event,calibration=0)
    print (tdays)
    print (energies)
    print (rise_times)

    print (energies)
    if args.verbose:
        print_data(energies,tdays,rise_times)

    data = [energies.copy(),tdays.copy(),rise_times.copy()]
    print(("data before range cuts: ",len(data[0]),len(data[1]),len(data[2])))


    ############################################################################
    # Declare the ranges.
    ############################################################################
    ranges,subranges,nbins = parameters.fitting_parameters(args.fit)
    
    bin_widths = np.ones(len(ranges))
    for i,n,r in zip(list(range(len(nbins))),nbins,ranges):
        bin_widths[i] = (r[1]-r[0])/n

    # Cut events out that fall outside the range.
    data = cut_events_outside_range(data,ranges)
    data = cut_events_outside_subrange(data,subranges[1],data_index=1)

    if args.verbose:
        print_data(energies,tdays)

    print(("data after  range cuts: ",len(data[0]),len(data[1])))

    nevents = float(len(data[0]))

    '''
    plt.figure()
    plt.plot(energies,rise_times,'o',markersize=1.5)
    plt.yscale('log')
    plt.ylim(0.1,10)

    plt.figure()
    plt.plot(tdays,rise_times,'o',markersize=1.5)
    plt.yscale('log')
    plt.ylim(0.1,10)
    '''

    ############################################################################
    # Plot the data
    ############################################################################
    ############################################################################
    # Look at the rise-time information.
    ############################################################################

    # Will use this later when trying to figure out the energy dependence of 
    # the log-normal parameters.
    # define our (line) fitting function
    expfunc = lambda p, x: p[1]*np.exp(-p[0]*x) + p[2]
    errfunc = lambda p, x, y, err: (y - expfunc(p, x)) / err

    ############################################################################
    # Starting values for fits. 
    ############################################################################
    # For the data (two lognormals)
    #starting_params = [-0.6,0.6,0.2*nevents,  0.1,0.8,0.8*nevents]
    # For the pulser fast rise times (two lognormals)
    starting_params = [-0.6,0.5,0.6*nevents,  0.5,0.8,0.4*nevents]

    fit_parameters = []
    fit_errors = []
    fit_mnerrors = []
    nevs = []
    axrt = []

    elo = 0.0
    ehi = 1.0
    eoffset = 0.5

    ewidth = 0.15
    estep = 0.15

    #ewidth = 0.200
    #estep = 0.050

    expts = []

    figcount = 0
    for i in range(0,24):
        
        j = i
        if j%6==0:
            figrt = plt.figure(figsize=(12,6),dpi=100)
        axrt.append(figrt.add_subplot(2,3, i%6 + 1))

        #figrt = plt.figure(figsize=(6,4),dpi=100)
        #axrt.append(figrt.add_subplot(1,1,1))

        data_to_fit = []
        #h,xpts,ypts,xpts_err,ypts_err = lch.hist_err(data[1],bins=nbins[1],range=ranges[1],axes=ax1)

        if i>=0:
            elo = i*estep + eoffset
            ehi = elo + ewidth
            index0 = data[0]>=elo
            index1 = data[0]< ehi
            print((elo,ehi))
            index = index0*index1
            data_to_fit = data[2][index]

        if len(data_to_fit)>0:
            lch.hist_err(data_to_fit,bins=nbins[2],range=ranges[2],axes=axrt[j])
            plt.ylim(0)
            plt.xlim(ranges[2][0],ranges[2][1])
            name = "Energy: %0.2f-%0.2f (keVee)" % (elo,ehi)
            plt.text(0.20,0.75,name,transform=axrt[j].transAxes)
            print ("=======-------- E BIN ----------===========")
            print (name)

        nevents = len(data_to_fit)
        print(("Nevents for this fit: ",nevents))
        #starting_params = [-0.6,0.6,0.2*nevents,  0.6,0.55,0.8*nevents]
        # For pulser fits
        #starting_params = [-0.1,0.8,0.2*nevents,  0.6,0.55,0.8*nevents]
        '''
        if i==0:
            starting_params = [-0.6,0.6,0.2*nevents,  0.6,0.55,0.8*nevents]
        '''
        '''
        if elo>=1.0 and elo<1.2:    
            starting_params = [0.1,0.2,0.3*nevents,  0.2,3.0,0.7*nevents]
        '''
        ############################################################################
        # Declare the fit parameters
        ############################################################################
        params_dict = {}
        params_dict['flag'] = {'fix':True,'start_val':args.fit} 
        params_dict['var_rt'] = {'fix':True,'start_val':0,'limits':(ranges[2][0],ranges[2][1])}
        #params_dict['fast_logn_mean'] = {'fix':False,'start_val':0.005,'limits':(-2,2),'error':0.1}
        #params_dict['fast_logn_sigma'] = {'fix':False,'start_val':0.5,'limits':(0.01,5),'error':0.1}
        #params_dict['fast_num'] = {'fix':False,'start_val':0.2*nevents,'limits':(0.0,1.5*nevents),'error':0.1}
        #params_dict['slow_logn_mean'] = {'fix':False,'start_val':0.5,'limits':(-2,2),'error':0.1}
        #params_dict['slow_logn_sigma'] = {'fix':False,'start_val':1.0,'limits':(0.01,5),'error':0.1}
        #params_dict['slow_num'] = {'fix':False,'start_val':0.8*nevents,'limits':(0.0,1.5*nevents),'error':0.1}

        #starting_params = [1.0,1.2,0.6*nevents,  0.1,0.8,0.4*nevents]

        # Worked for 1.0-1.25
        #params_dict['fast_logn_mean'] = {'fix':False,'start_val':1.000,'limits':(-2,2),'error':0.1}
        #params_dict['fast_logn_sigma'] = {'fix':False,'start_val':1.2,'limits':(0.01,5),'error':0.1}
        #params_dict['fast_num'] = {'fix':False,'start_val':0.6*nevents,'limits':(0.0,1.5*nevents),'error':0.1}
        #params_dict['slow_logn_mean'] = {'fix':False,'start_val':0.1,'limits':(-2,2),'error':0.1}
        #params_dict['slow_logn_sigma'] = {'fix':False,'start_val':0.8,'limits':(0.01,5),'error':0.1}
        #params_dict['slow_num'] = {'fix':False,'start_val':0.4*nevents,'limits':(0.0,1.5*nevents),'error':0.1}

        params_dict['fast_logn_mean'] = {'fix':False,'start_val':starting_params[0],'limits':(-2,2),'error':0.01}
        params_dict['fast_logn_sigma'] = {'fix':False,'start_val':starting_params[1],'limits':(0.05,30),'error':0.01}
        params_dict['fast_num'] = {'fix':False,'start_val':nevents,'limits':(0.0,1.5*nevents),'error':0.01}

        #params_dict['slow_logn_mean'] = {'fix':False,'start_val':starting_params[3],'limits':(-2,2),'error':0.01}
        #params_dict['slow_logn_sigma'] = {'fix':False,'start_val':starting_params[4],'limits':(0.05,30),'error':0.01}
        #params_dict['slow_num'] = {'fix':False,'start_val':starting_params[5],'limits':(0.0,1.5*nevents),'error':0.01}

        # For the pulser fits
        #params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.000,'limits':(-0.002,0.002),'error':0.000001}
        #params_dict['slow_logn_sigma'] = {'fix':True,'start_val':1.000,'limits':(0.9005,1.002),'error':0.000001}
        #params_dict['slow_num'] = {'fix':True,'start_val':0.001,'limits':(0.0,0.002),'error':0.000001}

        # float them
        params_dict['slow_logn_mean'] = {'fix':False,'start_val':starting_params[3],'limits':(-2,2),'error':0.01}
        params_dict['slow_logn_sigma'] = {'fix':False,'start_val':starting_params[4],'limits':(0.05,30),'error':0.01}
        params_dict['slow_num'] = {'fix':False,'start_val':starting_params[5],'limits':(0.0,1.5*nevents),'error':0.01}
        # To try one lognormal
        #params_dict['slow_logn_mean'] = {'fix':True,'start_val':starting_params[3],'limits':(-2,2),'error':0.01}
        #params_dict['slow_logn_sigma'] = {'fix':True,'start_val':starting_params[4],'limits':(0.05,30),'error':0.01}
        #params_dict['slow_num'] = {'fix':True,'start_val':0.1,'limits':(0.0,1.5*nevents),'error':0.01}

        # Above some value, lock down the second log normal, as the distribution is pretty well 
        # fit with just one log-normal. 
        elomax = 2.8
        if args.dataset=='nicole':
            elomax = 2.8
        elif args.dataset=='juan':
            elomax = 2.2

        if elo>=elomax:
            params_dict['slow_logn_mean'] = {'fix':True,'start_val':0.0,'limits':(-2,2),'error':0.01}
            params_dict['slow_logn_sigma'] = {'fix':True,'start_val':1.0,'limits':(0.05,30),'error':0.01}
            params_dict['slow_num'] = {'fix':True,'start_val':1,'limits':(0.0,1.5*nevents),'error':0.01}

        '''
        if i==0:
            None
            # From Nicole's simulation.
            #params_dict['fast_logn_mean'] = {'fix':True,'start_val':-0.10,'limits':(-2,2),'error':0.01}
            # From Juan
            #params_dict['fast_logn_mean'] = {'fix':True,'start_val':-0.60,'limits':(-2,2),'error':0.01}
            #params_dict['slow_logn_sigma'] = {'fix':True,'start_val':0.50,'limits':(0.05,30),'error':0.01}
        '''

        # Try fixing the slow sigma
        #params_dict['slow_logn_sigma'] = {'fix':True,'start_val':0.52,'limits':(-2,2),'error':0.01}

        #figrt.subplots_adjust(left=0.07, bottom=0.15, right=0.95, wspace=0.2, hspace=None,top=0.85)
        #figrt.subplots_adjust(left=0.05, right=0.98)
        #figrt.subplots_adjust(left=0.15, right=0.98,bottom=0.15)
        figrt.subplots_adjust(left=0.07, right=0.98,bottom=0.10)
        #plt.show()
        #exit()

        ############################################################################
        # Fit
        ############################################################################

        if i>=0 and len(data_to_fit)>0:
            params_names,kwd = fitutils.dict2kwd(params_dict)
        
            #print data_to_fit
            f = fitutils.Minuit_FCN([[data_to_fit]],params_dict,emlf)

            # For maximum likelihood method.
            kwd['errordef'] = 0.5
            kwd['print_level'] = 0
            #print kwd

            m = minuit.Minuit(f,**kwd)

            m.print_param()

            m.migrad()
            #m.hesse()
            m.minos()

            print ("Finished fit!!\n")

            values = m.values # Dictionary
            errors = m.errors # Dictionary
            mnerrors = m.get_merrors()
            print ("MNERRORS: ")
            print (mnerrors)
            fit_parameters.append(values)
            fit_errors.append(errors)
            fit_mnerrors.append(mnerrors)
            nevs.append(len(data_to_fit))

            xpts = np.linspace(ranges[2][0],ranges[2][1],1000)
            tot_ypts = np.zeros(len(xpts))

            ypts  = pdfs.lognormal(xpts,values['fast_logn_mean'],values['fast_logn_sigma'],ranges[2][0],ranges[2][1])
            y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=values['fast_num'],fmt='r--',linewidth=2,axes=axrt[j])
            tot_ypts += y

            ypts  = pdfs.lognormal(xpts,values['slow_logn_mean'],values['slow_logn_sigma'],ranges[2][0],ranges[2][1])
            y,plot = plot_pdf(xpts,ypts,bin_width=bin_widths[2],scale=values['slow_num'],fmt='r:',linewidth=2,axes=axrt[j])
            tot_ypts += y

            axrt[j].plot(xpts,tot_ypts,'r',linewidth=2)

            axrt[j].set_ylabel(r'Events')
            axrt[j].set_xlabel(r'Rise time ($\mu$s)')
            axrt[j].set_xlim(0,5.0)

            '''
            name = "Plots/rt_slice_%d.png" % (figcount)
            if j%6==5:
                plt.savefig(name)
                figcount += 1
            '''

            #'''
            if math.isnan(values['fast_logn_mean']) == False:
                starting_params = [ \
                values['fast_logn_mean'], \
                values['fast_logn_sigma'], \
                values['fast_num'], \
                values['slow_logn_mean'], \
                values['slow_logn_sigma'],
                values['slow_num'] \
                ]
            #'''

            expts.append((ehi+elo)/2.0)

        if j%6==5:
            name = "Plots/rt_slice_%s_%d.png" % (tag,j/6)
            plt.savefig(name)

    print (fit_parameters)
    print (nevs)
    
    ypts = [[],[],[],[],[],[]]
    yerr = [[],[],[],[],[],[]]
    yerrlo = [[],[],[],[],[],[]]
    yerrhi = [[],[],[],[],[],[]]
    npts = []

    if len(expts)>0:
        #for i,fp,fe,n in zip(range(len(nevs)),fit_parameters,fit_errors,nevs):
        for i,fp,fe,n in zip(list(range(len(nevs))),fit_parameters,fit_mnerrors,nevs):
            print ("----------")
            #ypts[0].append(fp['fast_logn_mean'])
            #ypts[1].append(fp['fast_logn_sigma'])
            #ypts[2].append(fp['fast_num'])
            #ypts[3].append(fp['slow_logn_mean'])
            #ypts[4].append(fp['slow_logn_sigma'])
            #ypts[5].append(fp['slow_num'])

            pars = ['fast_logn_mean','fast_logn_sigma','fast_num',\
                    'slow_logn_mean','slow_logn_sigma','slow_num']

            for i,p in enumerate(pars):
                if p in fe:
                #if fe.has_key(p):
                    ypts[i].append(fp[p])
                    yerrlo[i].append(abs(fe[p]['lower']))
                    yerrhi[i].append(abs(fe[p]['upper']))
                else:
                    ypts[i].append(0.0)
                    yerrlo[i].append(0.0)
                    yerrhi[i].append(0.0)


            npts.append(n)

        for i in range(len(ypts)):
            ypts[i] = np.array(ypts[i])
            yerrlo[i] = np.array(yerrlo[i])
            yerrhi[i] = np.array(yerrhi[i])

        colors = ['r','b']
        labels = ['narrow','wide']

        ########################################################################
        # Use all or some of the points in the fit.
        ########################################################################
        index = np.arange(1,16)
        if args.dataset=='nicole':
            index = np.arange(1,16)
        elif args.dataset=='juan':
            index = np.arange(0,9)

        
        #xp = np.linspace(min(expts),max(expts),100)
        xp = np.linspace(min(expts),expts[17],100)
        if args.dataset=='nicole':
            xp = np.linspace(min(expts),expts[17],100)
        elif args.dataset=='juan':
            xp = np.linspace(min(expts),expts[8],100)

        expts = np.array(expts)

        fvals2 = plt.figure(figsize=(13,4),dpi=100)

        yfitpts = []

        for k in range(0,3):
            # Some of the broad rise times are set to 0.
            #index0s = ypts[3+k]!=0
            #index0s = np.ones(len(ypts[3+k])).astype(bool)
            index0s = np.ones(16).astype(bool)

            fvals2.add_subplot(1,3,k+1)

            tempypts = ypts[0+k]-ypts[3+k]
            # Fractional error
            tempyerrlo = np.sqrt((yerrlo[0+k])**2 + (yerrlo[3+k])**2)
            tempyerrhi = np.sqrt((yerrhi[0+k])**2 + (yerrhi[3+k])**2)
            if k>1:
                tempypts = ypts[0+k][index0s]/ypts[3+k][index0s]
                tempyerrlo = np.sqrt((yerrlo[0+k][index0s]/ypts[3+k][index0s])**2 + (yerrlo[3+k][index0s]*(ypts[0+k][index0s]/(ypts[3+k][index0s]**2)))**2)
                tempyerrhi = np.sqrt((yerrhi[0+k][index0s]/ypts[3+k][index0s])**2 + (yerrhi[3+k][index0s]*(ypts[0+k][index0s]/(ypts[3+k][index0s]**2)))**2)

            plt.errorbar(expts[index0s],tempypts[index0s],xerr=0.01,yerr=[tempyerrlo[index0s],tempyerrhi[index0s]],\
                    fmt='o',ecolor='k',mec='k',mfc='m',label='Ratio')

            if k==0:
                plt.ylabel(r'$\Delta \mu$')
            elif k==1:
                plt.ylabel(r'$\Delta \sigma$')
            elif k==2:
                plt.ylabel(r'# wide/# narrow')

            plt.xlim(0.5,3.5)
            plt.xlabel('Energy (keVee)')


            ########################################################################
            # Fit to exponentials.
            ########################################################################
            # Choose appropriate starting values, depending on the dataset.
            pinit = [1,1,1]
            if args.dataset=='nicole':
                if k==0:
                    pinit = [1.0, 1.0, -1.2]
                elif k==1:
                    #pinit = [1.0, -1.0, -0.5]
                    pinit = [-3.0,0.0015,-0.4]
                elif k==2:
                    pinit = [-2.0, 1.0, 2.0]
            elif args.dataset=='juan':
                if k==0:
                    pinit = [1.0, 1.0, -1.2]
                elif k==1:
                    #pinit = [1.0, -1.0, -0.5]
                    pinit = [-3.0,0.0015,-0.4]
                elif k==2:
                    pinit = [-2.0, 1.0, 2.0]
            
            out = leastsq(errfunc, pinit, args=(expts[index], tempypts[index], (tempyerrlo[index]+tempyerrhi[index])/2.0), full_output=1)
            z = out[0]
            zcov = out[1]
            #print "Differences and ratios: %d [%f,%f,%f]" % (k,z[0],z[1],z[2])
            variable = None
            if (k==0):
                variable = "fast_mean_rel_k"
            if (k==1):
                variable = "fast_sigma_rel_k"
            elif (k==2):
                variable = "fast_num_rel_k"
            output = "\t%s = [%f,%f,%f]\n" % (variable,z[0],z[1],z[2])
            print (output)
            outfile.write(output)
            #print "zcov: ",zcov
            '''
            if zcov is not None:
                print "Differences and ratios: %d [%f,%f,%f]" % (k,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]),np.sqrt(zcov[2][2]))
            '''
            yfitpts = expfunc(z,xp)
            #print zcov
            plt.plot(xp,yfitpts,'-',color='m')

        fvals2.subplots_adjust(left=0.10, right=0.98,bottom=0.15,wspace=0.25,hspace=0.25)
        name = 'Plots/rt_summary_%s_1.png' % (tag)
        plt.savefig(name)

        outfile.write("\n")

        ########################################################################
        # Try to fit the individual distributions.
        ########################################################################
        yfitpts = []
        for i in range(0,6):
            yfitpts.append(np.zeros(len(xp)))

        fvals = plt.figure(figsize=(13,4),dpi=100)
        for k in range(0,3):
            fvals.add_subplot(1,3,k+1)
            for ik in range(0,2):
                nindex = k+3*ik
                #print "HERERERERE"
                #print ypts[nindex]
                #print ypts[nindex][ypts[nindex]!=0]
                print((len(yerrlo[nindex][ypts[nindex]!=0])))
                print((len(yerrhi[nindex][ypts[nindex]!=0])))
                plt.errorbar(expts[ypts[nindex]!=0],ypts[nindex][ypts[nindex]!=0],xerr=0.01,yerr=[yerrlo[nindex][ypts[nindex]!=0],yerrhi[nindex][ypts[nindex]!=0]],\
                        fmt='o',ecolor='k',mec='k',mfc=colors[ik],label=labels[ik])

                #'''
                # Use part of the data
                #index0 = np.arange(0,3)
                #index1 = np.arange(7,len(expts))
                #index = np.append(index0,index1)

                # Use all or some of the points
                index = np.arange(1,16)
                if args.dataset=='nicole':
                    index = np.arange(1,15)
                elif args.dataset=='juan':
                    index = np.arange(0,7)

                ########################################################################
                # Fit to exponentials.
                ########################################################################
                pinit = [1,1,1]
                if ik==0 and k==0:
                    pinit = [1.0, 1.0, -1.2]
                elif ik==0 and k==1:
                    pinit = [4.0, 2.0, 0.0]
                elif ik==0 and k==2:
                    pinit = [2.0, 2000.0, 300.0]
                elif ik==1:
                    pinit = [3.0, 1.5, 0.5]
                
                out = leastsq(errfunc, pinit, args=(expts[index], ypts[nindex][index], (yerrlo[nindex][index]+yerrhi[nindex][index])/2.0), full_output=1)
                z = out[0]
                zcov = out[1]
                variable = None
                if (k==0):
                    variable = "fast_mean0_k"
                if (k==1):
                    variable = "fast_sigma0_k"
                elif (k==2):
                    variable = "fast_num0_k"
                #print "Data points: %d %d [%f,%f,%f]" % (k,ik,z[0],z[1],z[2])
                if (ik==0):
                    output = "\t%s = [%f,%f,%f]\n" % (variable,z[0],z[1],z[2])
                    outfile.write(output)
                    print (output)
                #print "Data points: %d %d [%f,%f,%f]" % (k,ik,np.sqrt(zcov[0][0]),np.sqrt(zcov[1][1]),np.sqrt(zcov[2][2]))
                yfitpts[nindex] = expfunc(z,xp)
                #print zcov
                plt.plot(xp,yfitpts[nindex],'-',color=colors[ik])
                #'''

            if k==0:
                plt.ylim(-1.5,1.5)
            elif k==1:
                plt.ylim(0,1.5)
            plt.xlabel('Energy (keVee)')
            if k==0:
                plt.ylabel(r'Lognormal $\mu$')
            elif k==1:
                plt.ylabel(r'Lognormal $\sigma$')
            elif k==2:
                plt.ylabel(r'Number of events')
            plt.legend()

        #fval
        '''
        fvals.add_subplot(2,3,4)
        plt.plot(xp,yfitpts[3]-yfitpts[0],'-',color='m')

        fvals.add_subplot(2,3,5)
        plt.plot(xp,yfitpts[4]-yfitpts[1],'-',color='m')

        fvals.add_subplot(2,3,6)
        plt.plot(xp,yfitpts[5]/yfitpts[2],'-',color='m')
        '''

        fvals.subplots_adjust(left=0.10, right=0.98,bottom=0.15,wspace=0.25,hspace=0.25)
        name = 'Plots/rt_summary_%s_0.png' % (tag)
        plt.savefig(name)

        np.savetxt('rt_parameters.txt',[expts,ypts[0],ypts[1],ypts[2],ypts[3],ypts[4],ypts[5],npts])
        #'''

    #print "Sum ypts[5]: ",sum(ypts[5])

    outfile.write("\n\treturn fast_mean_rel_k,fast_sigma_rel_k,fast_num_rel_k,fast_mean0_k,fast_sigma0_k,fast_num0_k\n")

    if not args.batch:
        plt.show()
Exemplo n.º 47
0
def main():

    lumi_file_name = 'lumi_info.pkl'
    lumi_info = pickle.load(open(lumi_file_name, "rb"))

    filenames = sys.argv[1:]

    MCfiles = []
    DATAfiles = []
    for filename in filenames:
        filename2 = filename.split('/')[-1]
        if filename2.split('DATASET')[0] == 'MC_':
            #print('**********************************')
            MCfiles.append(filename)
        else:
            DATAfiles.append(filename)
    '''
    for filename in MCfiles:
        print('MC: ', filename)
    for filename in DATAfiles:
        print('DATA: ', filename)
    '''
    mcdata = []
    #print("Will open files:")
    mcInfo = tbt.csvtodict("MCinfo.csv")
    weights = []
    mcEvents = []
    crosssection = []

    data, tot_lumi = tbt.chain_pickle_files(DATAfiles, lumi_info)
    print("tot_lumi: ", tot_lumi)

    for f in MCfiles:
        #print('f', f)
        mcdataTMP, tot_lumiMC = tbt.chain_pickle_files(f)
        mcdata.append(mcdataTMP)
        fnew = f.split('DATASET_crab_')[1].split('_NFILES')[0]
        nfiles = int(f.split('NFILES_')[1].split('_')[1].split('.')[0]) - int(
            f.split('NFILES_')[1].split('_')[0])
        crosssection = 1000 * (float(mcInfo[fnew]['cross_section'])
                               )  # Convert from pb to fb
        mcEvents = (float(mcInfo[fnew]['total_events']))
        print("crosssection: ", crosssection)
        print("MCEvents/crosssection: ", mcEvents / crosssection)
        print("MCEvents: ", mcEvents)
        print("tot_lumi: ", tot_lumi)
        print("nfiles: ", nfiles)
        print("nfiles_tot: ", mcInfo[fnew]['nfiles'])
        weights.append((crosssection * tot_lumi) /
                       (nfiles * mcEvents / float(mcInfo[fnew]['nfiles'])))

    topmassDATA = data['topmass']
    wmassDATA = data['wmass']
    csvsDATA = data['csvs']
    anglesDATA = data['angles']
    dRsDATA = data['dRs']
    #njets = data['njets']
    njetsDATA = data['njets']
    leadmuptDATA = data['leadmupt']
    leadmuetaDATA = data['leadmueta']

    topmassMC = []
    wmassMC = []
    csvsMC = []
    anglesMC = []
    dRsMC = []
    #njets = []
    njetsMC = []
    leadmuptMC = []
    leadmuetaMC = []

    for mc in mcdata:
        topmassMC.append(mc['topmass'])
        wmassMC.append(mc['wmass'])
        csvsMC.append(mc['csvs'])
        anglesMC.append(mc['angles'])
        dRsMC.append(mc['dRs'])
        #njets.append(mc['njets'])
        njetsMC.append(mc['njets'])
        leadmuptMC.append(mc['leadmupt'])
        leadmuetaMC.append(mc['leadmueta'])

    print('Weights', weights)

    bins = 100

    hweights = []
    for w, d in zip(weights, [topmassMC[0], topmassMC[1]]):
        print('weighting: ', w, len(d))
        hweights.append(w * np.ones(len(d)))

    plt.figure()
    vals = [topmassMC[0], topmassMC[1]]
    hw = weights_for_histos(weights, vals)
    plt.hist(vals, bins, range=(0, 1600), weights=hw, stacked=True)
    lch.hist_err(topmassDATA, bins, range=(0, 1600))

    plt.figure()
    vals = [leadmuptMC[0], leadmuptMC[1]]
    hw = weights_for_histos(weights, vals)
    plt.hist(vals, bins, range=(0, 200), weights=hw, stacked=True)
    lch.hist_err(leadmuptDATA, bins, range=(0, 200))

    plt.figure()
    vals = [leadmuetaMC[0], leadmuetaMC[1]]
    hw = weights_for_histos(weights, vals)
    plt.hist(vals, bins, range=(-3, 3), weights=hw, stacked=True)
    lch.hist_err(leadmuetaDATA, bins, range=(-3, 3))

    print(mcdata[0].keys())
    plt.figure()
    plt.subplot(2, 2, 1)
    plt.hist(mcdata[0]["trig_HLT_IsoMu24_accept"])
    plt.subplot(2, 2, 2)
    plt.hist(mcdata[0]["trig_HLT_IsoTkMu24_accept"])
    plt.subplot(2, 2, 3)
    plt.hist(mcdata[0]["trig_HLT_IsoMu22_eta2p1_accept"])
    plt.subplot(2, 2, 4)
    plt.hist(mcdata[0]["trig_HLT_IsoTkMu22_eta2p1_accept"])
    '''
    #lch.hist_err(topmass,bins=100,range=(0,600),color='k')
    plt.xlabel('Top Mass (GeV)')
     
    plt.subplot(3,3,2)
    #lch.hist_err(wmass,bins=100,range=(0,300),color='k')
    plt.xlabel('W Mass (GeV)')
    
    plt.subplot(3,3,3)
    #lch.hist_err(csvs,bins=110,range=(0,1.1),color='k')
    plt.xlabel('Isolation Variable')
    
    plt.subplot(3,3,4)
    #lch.hist_err(angles,bins=100,range=(0, 3.2),color='k')
    plt.xlabel('Angles')
    
    plt.subplot(3,3,5)
    #plt.plot(wmass,angles,'.',markersize=0.5,alpha=0.2)
    #lch.hist_2D(wmass,angles,xbins=100,ybins=100,xrange=(0,300),yrange=(0,3.14))
    plt.xlim(50,150)
    plt.ylim(0, 3.2)
    plt.xlabel('W Mass')
    plt.ylabel('Angles')
    
    plt.subplot(3,3,6)
    #lch.hist_err(dRs,bins=100,range=(0, 3.2),color='k')
    plt.xlabel('dRs')
    
    plt.subplot(3,3,7)
    #lch.hist_2D(dRs,angles,xbins=100,ybins=100,xrange=(0,6.28),yrange=(0,3.14))
    plt.xlabel('dRs')
    plt.ylabel('Angles')
    '''

    ################################################################################
    # Cut on the wmass
    #index = wmass>70.0
    #index *= wmass<95.0
    '''
    plt.figure()
    plt.title('W Mass Cuts')
    plt.subplot(3,3,1)
    #lch.hist_err(topmass[index],bins=100,range=(0,600),color='k')
    plt.xlabel('Top Mass (GeV)')

    plt.subplot(3,3,2)
    #lch.hist_err(wmass[index],bins=100,range=(0,300),color='k')
    plt.xlabel('W Mass (GeV)')

    plt.subplot(3,3,4)
    #lch.hist_err(angles[index],bins=100,range=(0,3.2),color='k')
    plt.xlabel('Angles')

    plt.subplot(3,3,5)
    #plt.plot(wmass[index],angles[index],'.',markersize=0.5,alpha=0.2)
    #lch.hist_2D(wmass[index],angles[index],xbins=100,ybins=100,xrange=(0,300),yrange=(0,3.14))
    plt.xlim(50,150)
    plt.ylim(0, 3.2)
    plt.xlabel('W Mass')
    plt.ylabel('Angles')

    plt.subplot(3,3,6)
    #lch.hist_err(dRs[index],bins=100,range=(0, 3.2),color='k')
    plt.xlabel('dRs')

    plt.subplot(3,3,7)
    #lch.hist_2D(dRs[index],angles[index],xbins=100,ybins=100,xrange=(0,6.28),yrange=(0,3.14))
    plt.xlabel('dRs')
    plt.ylabel('Angles')


    
    # For talk
    plt.figure()
    #lch.hist_err(topmass[index],bins=100,range=(0,600),color='k')
    plt.hist(topmass[index],bins=100,range=(0,600),color='grey',alpha=0.2)
    plt.xlabel(r'Top candidate with W-mass cut (GeV/c$^2$)',fontsize=14)
    plt.tight_layout()
    plt.savefig('top.png')

    plt.figure()
    #lch.hist_err(wmass,bins=100,range=(0,300),color='k')
    plt.hist(wmass,bins=100,range=(0,300),color='grey',alpha=0.2)
    plt.xlabel(r'W candidate (GeV/c$^2$)',fontsize=14)
    plt.tight_layout()
    plt.savefig('W.png')

    plt.figure()
    #lch.hist_err(csvs,bins=110,range=(0,1.1),color='k')
    plt.hist(csvs,bins=100,range=(0,1.1),color='grey',alpha=0.2)
    plt.xlabel(r'CSVv2 variable',fontsize=14)
    plt.tight_layout()
    plt.savefig('csvv2.png')
    
    '''
    plt.show()

    return data
        elif pdgs[t0[1][4]]==11 or pdgs[t0[1][4]]==13:
            dR_mu_b=d_tools.delta_R(etas,phis,t0[0][2],t0[0][4])
            del_R_mu_b.append(dR_mu_b[0])        








plt.figure(1)
#plt.hist(del_R_top_antitop,bins=50)
nbins=100; lorange=0; hirange=8
binwidth = (hirange-lorange)/float(nbins)
lkn.hist_err(del_R_top_antitop,bins=nbins,range=(lorange,hirange))
#plt.axis([0, 8, 0, 8])
plt.title(r" $\Delta R$ between $t$ and $\bar{t}$",fontsize=24)
plt.xlabel(r"$\Delta$R",fontsize=24)
label = r"Entries/%3.2f" % (binwidth)
plt.ylabel(label,fontsize=24)

plt.figure(2)
plt.subplot(2, 1, 1)
#plt.hist(del_R_W_B,bins=50)
lkn.hist_err(del_R_W_B,bins=100,range=(0,8))
#plt.axis([0, 8, 0, 8])
plt.title(r"W and B $\Delta$R")
#plt.xlabel(r"$\Delta$R")

plt.subplot(2, 1, 2)