Exemplo n.º 1
0
def getPeakTimes(n = [],
                 ybins = [],
                 expected_tdelay = 76.,
                 refl_peak_width = 5.,
                 plot= False,
                 debug = False):
    # ycenters
    ycenters = (ybins[1:] + ybins[:-1])/2.

    # bin width
    bin_width = ybins[1]-ybins[0]

    # Find the highest peak
    prompt_peak_index = n.argmax()

    t1 = ybins[prompt_peak_index]

    smooth_coeff = 1./bin_width

    nsmooth = ndimage.filters.gaussian_filter1d(n, sigma=smooth_coeff)
    nsmooth[nsmooth<=0] = 1

    # Select a range where the second peak can be
    refl_peak_index = prompt_peak_index + int(expected_tdelay/bin_width)
    refl_si = refl_peak_index - int(refl_peak_width/bin_width)
    refl_ei = refl_peak_index + int((refl_peak_width*2)/bin_width)
    refl_ei = np.min([refl_ei, ybins.size-1])
    


    # Peak finding algorithm
    peaks = detect_peaks(nsmooth[refl_si:refl_ei], 
                         mpd = 10*smooth_coeff,
                         edge='rising',show=False, mph=1.1)
    if peaks.size == 0:
        t2 = -1
    else:
        t2 = ybins[refl_si:refl_ei][peaks].max()

    terr1 = terr2 = 1.

    if plot:
        fig = plt.figure(figsize=(7,4))
        ax1 = fig.add_subplot(111)
        jplot.unfilledBar(ybins, n, color='0.7')
        jplot.unfilledBar(ybins, nsmooth)
        plt.yscale('log')
        plt.plot((ybins[refl_si:refl_ei][peaks]+ybins[refl_si:refl_ei][peaks-1])/2., 
                 nsmooth[refl_si:refl_ei][peaks], 'xg')
        plt.ylabel('N hits')
        plt.axvline(x = t2, ymin=0, ymax = n.max()*1.2, 
                    linestyle='--', color='k')
        plt.axvline(x = t1, ymin=0, ymax = n.max()*1.2, 
                    linestyle='--', color='k')
        print t1, terr1, t2, terr2

    return t1, terr1, t2, terr2
Exemplo n.º 2
0
def getGausTime(n=[], ybins=[], prompt_peak_width=4., plot=False, debug=False):

    # ycenters
    ycenters = (ybins[1:] + ybins[:-1]) / 2.

    # bin width
    bin_width = ybins[1] - ybins[0]

    # Find the highest peak
    prompt_peak_index = n.argmax()

    if n[prompt_peak_index] < 20:
        return -1, -1

    # First peak range (in bins)
    fit_s = prompt_peak_index - int(prompt_peak_width / bin_width)
    fit_e = prompt_peak_index + int(prompt_peak_width / bin_width)

    # Fit a gaussian +/- prompt_peak_width ns around the peak
    popt = [n[prompt_peak_index] / 2., ycenters[prompt_peak_index], 3.]
    try:
        popt, pcov = optimize.curve_fit(
            analysis.gaus,
            ycenters[fit_s:fit_e + 1],
            n[fit_s:fit_e + 1],
            popt,
        )
        perr = np.sqrt(np.diag(pcov))
        terr1 = perr[1]
        t1 = popt[1]
    except:
        terr1 = -1
        t1 = -1

    if plot:
        fig = plt.figure(figsize=(7, 4))
        ax1 = fig.add_subplot(111)
        jplot.unfilledBar(ybins, n, color='0.7')

        newx = np.linspace(ycenters[fit_s] - 3., ycenters[fit_e] + 3., 101)
        plt.plot(newx, analysis.gaus(newx, *popt), 'r')

        plt.yscale('log')
        plt.ylabel('N hits')
        plt.ylim([1., n[prompt_peak_index] * 1.3])

        return fig

        #raw_input()
    return t1, terr1
Exemplo n.º 3
0
def arrayDiagnostics(values, name, ax_lim = [None, None]):
    print 'Diagnostics', name
    print values.min(),values.max(), values.mean()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    if ax_lim[0] == None:
        ax_lim[0] = 0.
    if ax_lim[1] == None:
        ax_lim[1] = np.median((values[values>0]))*10
    xaxis = np.linspace(ax_lim[0], ax_lim[1], 100)
    b, x = np.histogram(values, xaxis)
    
    jplot.unfilledBar(x,b)
    plt.yscale('log')
    plt.xlabel(name)
    return fig, ax
Exemplo n.º 4
0
def plotOccupancy(pmt_list, pmt_info, hit_lim=[-1, -1]):
    pmt_list = pmt_list[:pmt_info['phi'].size]
    print pmt_list.shape, pmt_info['phi'].size
    pmt_radii = np.sqrt(np.sum(pmt_info['xyz']**2, axis=1))
    pmt_bool = (pmt_radii < 8500.) * (pmt_list > 0.)

    print hit_lim
    if hit_lim[0] < 0:
        aux = pmt_list.mean() - 2.5 * pmt_list.std()
        if aux < 0:
            hit_lim[0] = 0.
        else:
            hit_lim[0] = aux
    if hit_lim[1] < 0:
        hit_lim[1] = pmt_list.mean() + 1.5 * pmt_list.std()
    print hit_lim
    # Print the histogram of the occupancy
    f1 = plt.figure()
    xaxis = np.linspace(hit_lim[0], hit_lim[1], 201)
    b, x = np.histogram(pmt_list[pmt_bool], xaxis)
    jplot.unfilledBar(x, b)
    plt.xlabel('Nhits')
    plt.ylabel('Number of PMTs')
    plt.show()

    f2 = plt.figure(figsize=(12, 7))
    ax = f2.add_subplot(111)
    plt.scatter(pmt_info['phi'][pmt_bool] / np.pi,
                pmt_info['costheta'][pmt_bool],
                c=pmt_list[pmt_bool],
                cmap='jet',
                vmin=hit_lim[0],
                vmax=hit_lim[1],
                marker='o',
                s=18,
                lw=0)
    plt.colorbar()
    plt.xlim([-1, 1])
    plt.ylim([-1, 1])
    plt.xlabel('Phi / pi')
    plt.ylabel('cos(theta)')
    plt.show()
figs = []
colors = ['b', 'r', 'c', 'g']
fig = plt.figure(figsize=(9, 18))
recoz_edges = aehist['reco_cosZ_edges']
recoe_edges = aehist['reco_logE_edges']

plotlims = [0.9, 1.1]

counter = 1
for eband in range(aehist['nue_histo'].shape[0] - 1):

    fig.add_subplot(aehist['nue_histo'].shape[0], 2, counter)
    for i, hkey in enumerate(mchist.keys()):
        hratio = norm * aehist[hkey] / mchist[hkey][:, ::-1]
        jplot.unfilledBar(recoz_edges,
                          hratio[eband, :],
                          color=colors[i],
                          label=hkey)
    counter += 1
    plt.ylim(plotlims)
    plt.xlabel('cos(zenith)')

    fig.add_subplot(aehist['nue_histo'].shape[1], 2, counter)
    for i, hkey in enumerate(mchist.keys()):
        hratio = norm * aehist[hkey] / mchist[hkey][:, ::-1]
        jplot.unfilledBar(recoe_edges,
                          hratio[:, eband],
                          color=colors[i],
                          label=hkey)
    counter += 1
    #plt.legend(loc=0)
    plt.ylim(plotlims)
Exemplo n.º 6
0
def plotTOA( data = None,
             position = np.array([0,0,0]),
             theta_bins = 6,
             time_window = 120.,
             time_rebin=1,
             av_reference = False,
             color = None,
             label=None,
             newfig = True):

    time_bin = data['time_edges'][1]-data['time_edges'][0]
    # Time rebinning
    time_nbins = int(np.ceil(time_window/time_bin))
    nbins = 5
    
    theta_edges = np.linspace(0, 180, theta_bins+1)

    if av_reference:
        a = psup_r
        b = mynorm(position)
        c = mynorm(position-pmt_info['xyz'], axis=1)
        mod_ct = (a**2 + b**2 - c**2)/(2*a*b)
        mod_theta = np.rad2deg(np.arccos(mod_ct))
    else:
        mod_pos   = pmt_info['xyz']-position
        mod_ct    = mod_pos[:,2]/pmt_info['r']
        mod_theta = np.rad2deg(np.arccos(mod_ct))
        
    if newfig:
        fig = plt.figure(figsize=(12,7))

    #Rebin?
    time_edges = data['time_edges']
    if time_rebin > 1:
        new_time = time_edges[::time_rebin][:-1]
        time_edges = new_time

    
    for i in range(len(theta_edges)-1):
        mybool = pmtbool*(mod_theta>theta_edges[i])*(mod_theta<theta_edges[i+1])
        
        norm=1.

        
        hits = data['toa'][:len(mybool),:][mybool].sum(axis=0)*1.
        if time_rebin > 1:
            hout = hits.cumsum()[(time_rebin-1)::time_rebin]
            hdiff = hout[1:] - hout[:-1]
            hits = hdiff
        #print hits
        imax = hits.argmax()
        #print imax
        
        hits /= hits[imax-5:imax+5].sum()
        #print hits
        hits /= (2**i)
        
        if color == None:
            this_color= cs[i]
        else:
            this_color = color
        if label == None:
                mylabel = "%i" % theta_edges[i] + ' - ' + "%i" % theta_edges[i+1]
        else:
                mylabel = label
        jplot.unfilledBar(time_edges - time_edges[imax], #+t0[i], ##-data_t0,
                          hits*norm,#*1./real_data['toa'].sum(),
                          color = this_color,
                          label = label)
        
    plt.legend(bbox_to_anchor=(1.15, 1.),
               loc='upper right')
    plt.yscale('log')
    plt.xlim(-10, 100)
    #plt.ylim(10,400000)
    plt.ylabel('Hits')
    plt.xlabel('Corrected time residual (ns)')
            if this_time < 0:
                continue

            toa_series_manip[iPMT] = one_pmt.GetTime() - travel_time_manip
            toa_series_fit[iPMT] = one_pmt.GetTime() - travel_time_fit
            all_qhl[counter] += one_pmt.GetQHL()
            all_qhs[counter] += one_pmt.GetQHS()

        # First easy check - do the median
        all_median_manip[counter] = np.median(toa_series_manip[toa_series_manip>0])
        all_median_fit[counter] = np.median(toa_series_fit[toa_series_fit>0])

        if np.abs(all_median_manip[counter]-310) > median_tolerance:
            xaxis = np.arange(100, 325, 0.25)
            counts, x = np.histogram(toa_series_manip, xaxis)
            jplot.unfilledBar(xaxis, counts)
            plt.show()
            raw_input()
            
        if counter %1000 == 0:
            print counter
        
        
        
        counter += 1
        if counter == max_events:
            print 'Max number of events reached. Exiting!'
            exit_loop = True
        
        if exit_loop:
            break
            if this_time < 0:
                continue

            toa_series_manip[iPMT] = one_pmt.GetTime() - travel_time_manip
            toa_series_fit[iPMT] = one_pmt.GetTime() - travel_time_fit
            all_qhl[counter] += one_pmt.GetQHL()
            all_qhs[counter] += one_pmt.GetQHS()

        # First easy check - do the median
        all_median_manip[counter] = np.median(toa_series_manip[toa_series_manip>0])
        all_median_fit[counter] = np.median(toa_series_fit[toa_series_fit>0])

        if np.abs(all_median_manip[counter]-310) > median_tolerance:
            xaxis = np.arange(100, 325, 0.25)
            counts, x = np.histogram(toa_series_manip, xaxis)
            jplot.unfilledBar(xaxis, counts)
            plt.show()
            raw_input()
            
        if counter %1000 == 0:
            print counter
        
        
        
        counter += 1
        if counter == max_events:
            print 'Max number of events reached. Exiting!'
            exit_loop = True
        
        if exit_loop:
            break
def collectResults(options):
    indir = os.path.join(user.scans_dir, options.NAME)
    scan_info = pickle.load(open(os.path.join(indir,'OscFit_ScanSettings.pckl')))

    total_jobs = len(scan_info['theta23_map'])
    
    dm2_list     = scan_info['dm31_list']
    theta23_list = scan_info['theta23_list']



    fits_dir    = os.path.join(indir,'fits')
    infile_list = os.listdir(fits_dir)
    infile_list.sort()
    if len(infile_list) == 0:
        print '\n **** LLH scan: No files were found! Exiting ****'
        exit()


    fit_results = ['dm31','theta23','theta13','mix_angle','norm_e',
                   'atmmu_f','noise_f', 'norm_nu',
                   'norm_tau','numubar_e2','numubar_z2','gamma','axm_qe','axm_res',
                   'pid_bias','domeff','hole_ice','had_escale','norm_nc']

    skip_params = ['theta23', 'dm31','mix_angle']

    # Initialize scan results
    scan_results = {}
    for fit_key in fit_results:
        scan_results[fit_key] = []
    theta23_injected = []
    dm31_injected    = []

    missing_files = []
    nan_files     = []
    index = 0
    error = 0

    counter = 0
    # Lazy coding. Just look for the number
    for dm31_i in range(0, len(scan_info['dm31_list'])):
        if len(infile_list) == 0:
            break
        for theta23_i in range(0, len(scan_info['theta23_list'])):
            if len(infile_list) == 0:
                break
            required_task = 'Task_' + "%06i" % index + '.pckl'

            if required_task in infile_list:
                one_fit = pickle.load(open(os.path.join(fits_dir, required_task)))
                infile_list.pop(infile_list.index(required_task))
                if one_fit['llh'] == None or isnan(one_fit['llh']):# or not one_fit['successful_fit']:
                    #print one_fit['llh']
                    nan_files.append(index+1)
                else:
                    for fit_key in fit_results:
                        scan_results[fit_key].append( one_fit[fit_key])
                    dm31_injected.append(dm2_list[dm31_i])
                    theta23_injected.append(theta23_list[theta23_i])
            else:
                missing_files.append(index+1)

            index += 1

    theta23_injected = np.array(theta23_injected)
    dm31_injected = np.array(dm31_injected)
    print theta23_injected.shape
        
    print '\nLLH scan: Missing files -',len(missing_files)
    print 'LLH scan: NAN files -', len(nan_files)

    missing_files = missing_files+ nan_files

    if len(missing_files) > 0 and options.DOMISSING:
        print 'LLH scan: Trying to reprocess missing files with mode ', options.MODE, '. Continue?'
        raw_input()

        submit_string = ' '.join(['./run_mctest_scan.py -n', options.NAME,'-m',options.MODE,'-j ']) + \
            ','.join(["%i" % x for x in missing_files])
        print submit_string
        os.system(submit_string)
        exit()

    # Produce histograms and figures here

    # Theta23-Dm31 map
    fig = plt.figure()
    if scan_info['data_settings']['oscMode'] == 'TwoNeutrino':
        t23diff = np.array(theta23_injected) - np.array(scan_results['mix_angle'])
        plt.plot(theta23_injected, dm31_injected*10**3, 'xr')
        plt.plot(scan_results['mix_angle'], np.array(scan_results['dm31'])*10**3, '.b')
        plt.xlabel(r'$\sin^2(2\theta_{23})$', fontsize = 'large')
        t23key = 'Mixing angle'

    else:
        t23diff = np.sin(theta23_injected)**2 - np.sin(scan_results['theta23'])**2
        plt.plot(np.sin(theta23_injected)**2, dm31_injected*10**3, 'xr')
        plt.plot(np.sin(scan_results['theta23'])**2, np.array(scan_results['dm31'])*10**3, '.b')
        plt.xlabel(r'$\sin^2(\theta_{23})$', fontsize = 'large')
        t23key = 'sin(theta)**2'
    fig.savefig(os.path.join(indir,'FullScan.png'))

    fig = plt.figure()
    xaxis = np.linspace(np.min(t23diff), np.max(t23diff), 22)*1.1
    n, x = np.histogram(t23diff, xaxis)
    jplot.unfilledBar(x, n)
    plt.ylabel('Counts')
    plt.xlabel(t23key)
    fig.savefig(os.path.join(indir, 'Theta23.png'))

    fig = plt.figure()
    dm31diff = (dm31_injected - np.array(scan_results['dm31']))*10**3
    xaxis = np.linspace(np.min(dm31diff), np.max(dm31diff), 22)*1.1
    n, x = np.histogram(dm31diff, xaxis)
    jplot.unfilledBar(x, n)
    plt.ylabel('Counts')
    plt.xlabel('DM31 (10**3 eV)')
    fig.savefig(os.path.join(indir, 'DM31.png'))
        
               


    # Parameter-wise figures
    for one_key in fit_results:
        if one_key in skip_params:
            continue
        pdiff = np.array(scan_results[one_key]) - scan_info['data_settings'][one_key]
        if np.mean(pdiff) == 0:
            continue
        xaxis = np.linspace(np.min(pdiff), np.max(pdiff), 22)*1.1
        n, x = np.histogram(pdiff, xaxis)

        fig = plt.figure()
        jplot.unfilledBar(x, n)
        plt.xlabel(one_key)
        plt.ylabel('Counts')
        fig.savefig(os.path.join(indir, one_key + '.png'))
Exemplo n.º 10
0
def getDPeakTimes(n = [],
                     ybins = [],
                     expected_tdelay = 76.,
                  refl_peak_width=5.,
                     plot= False,
                     debug = False):

    if n.sum() == 0:
        return -1, -1, -1, -1
    
    # ycenters
    ycenters = (ybins[1:] + ybins[:-1])/2.

    # bin width
    bin_width = ybins[1]-ybins[0]


    smooth_coeff = 1./bin_width
    nsmooth = ndimage.filters.gaussian_filter1d(n, sigma=smooth_coeff)
    nsmooth[nsmooth<=0] = 1

    # Finding the peaks of the derivative
    dx = (ybins[1]-ybins[0])/2.
    ydn = ybins[1:-1]

    # Derivating, and smoothing over it
    dnsmooth = np.diff(np.log10(nsmooth))/dx  
    dnsmooth = ndimage.filters.gaussian_filter1d(dnsmooth, 
                                                 sigma=smooth_coeff)

    # Highest peak is easy
    prompt_minus = int(10./bin_width)
    prompt_region = [n.argmax()-prompt_minus, n.argmax()]

    try:
        prompt_peak_index = prompt_region[0]+dnsmooth[prompt_region[0]:prompt_region[1]].argmax()
    except:
        # Errors appear here when the histogram is too empty
        # print 'Not using this PMT'
        return -2, -2, -2, -2
    
    t1 = ydn[prompt_peak_index]
    refl_peak_index = prompt_peak_index + int(expected_tdelay/bin_width)
    refl_si = refl_peak_index - int(refl_peak_width/bin_width)
    refl_ei = refl_peak_index + int((refl_peak_width*2)/bin_width)
    refl_ei = np.min([refl_ei, ybins.size-1])

    #print refl_si, refl_ei

    # Finding the peaks
    dpeaks = detect_peaks(dnsmooth[refl_si:refl_ei], 
                          mpd = 10*smooth_coeff,
                          edge='rising',show=False, mph=0.001)

    if dpeaks.size == 0:
        t2 = -1
    else:
        t2 = ydn[refl_si:refl_ei][dpeaks].max()

    terr1 = terr2 = 1.


    if plot:
        fig = plt.figure(figsize=(7,4))
        ax1 = fig.add_subplot(111)

        print 'Peaks', dpeaks
        jplot.unfilledBar(ybins, np.log10(n)*dnsmooth.max()/np.log10(n.max()), color='0.7')
        jplot.plot(ydn, dnsmooth)

        jplot.plot([ydn[refl_si],ydn[refl_ei]], [1.,1.], 'or')

        if len(dpeaks) > 0:
            plt.plot((ydn[refl_si:refl_ei][dpeaks]+ydn[refl_si:refl_ei][dpeaks-1])/2.,
                     dnsmooth[refl_si:refl_ei][dpeaks], 'xg')
            plt.ylabel('N hits')
            plt.axvline(x = t2, ymin=0, ymax = dnsmooth.max()*1.2,
                        linestyle='--', color='k')
            plt.axvline(x = t1, ymin=0, ymax = dnsmooth.max()*1.2,
                        linestyle='--', color='k')

        print t1, terr1, t2, terr2


    return t1, terr1, t2, terr2
Exemplo n.º 11
0
def volumeAnalysis(data,
                   volume=[],
                   radius_range=[0, np.inf],
                   extra_conditions={},
                   theta_bins=41,
                   phi_bins=61,
                   plot_mode='histogram',
                   plot_nstd=2.,
                   radius_plot=True):
    if type(volume) != list:
        volume = [volume]
    radius_range = np.array(radius_range)

    mybool = np.array([False] * len(data['end_volume']))

    for one_volume in volume:
        mybool = mybool | (data['end_volume'] == one_volume)

    # Additional conditions
    for one_key in extra_conditions.keys():
        mybool *= data[one_key] >= extra_conditions[one_key].min()
        mybool *= data[one_key] <= extra_conditions[one_key].max()

    positions = data['end_position'][mybool, :]

    # Converting to spherical coordinates
    r = np.linalg.norm(positions, axis=1)
    rbool = (r > radius_range.min()) * (r < radius_range.max())

    phi = np.arctan2(positions[rbool, 1], positions[rbool, 0])
    theta = -1 * (np.arccos(positions[rbool, 2] / r[rbool]) - np.pi / 2.)

    # Plotting the events as function of r
    raxis = np.linspace(0, 8000., 201)
    raxis_eff = deepcopy(raxis)
    raxis_eff[-1] = np.inf

    if radius_plot:
        b, x = np.histogram(r, raxis_eff)

        fig1 = plt.figure(figsize=figsize_small)
        jplot.unfilledBar(raxis, b)
        jplot.unfilledBar(raxis,
                          b.max() * np.cumsum(b) * 1. / b.sum(),
                          color='green')
        plt.xlabel('Radius (mm)')
        plt.ylabel('Photons absorbed')

    if radius_range.max() < np.inf:
        # Do the vertical lines here
        plt.axvline(x=radius_range.min(),
                    ymax=b.max(),
                    linestyle='--',
                    color='r')
        plt.axvline(x=radius_range.max(),
                    ymax=b.max(),
                    linestyle='--',
                    color='r')

    # Axes for the projection
    paxis = np.linspace(-np.pi, np.pi, phi_bins)
    taxis = np.arccos(np.linspace(-1, 1, theta_bins))[::-1] - np.pi / 2.

    # Plotting the events in a projection - histogrammed
    fig2 = plt.figure(figsize=figsize)
    plt.title('Photons absorbed')
    ax = fig2.add_subplot(111, projection='mollweide')
    if plot_mode == 'histogram' or plot_mode == 'combo':
        b, x, y = np.histogram2d(theta, phi, [taxis, paxis])
        nonzero = b > 0
        bmean = b[nonzero].mean()
        bstd = b[nonzero].std()

        print 'Bin stats', b[nonzero].mean(), b[nonzero].std()

        plt.pcolor(paxis,
                   taxis,
                   b,
                   vmin=bmean - plot_nstd * bstd,
                   vmax=bmean + plot_nstd * bstd)
        plt.colorbar()

        return b, x, y

    if plot_mode == 'scatter' or plot_mode == 'combo':
        plt.plot(phi, theta, '.', color='black')
Exemplo n.º 12
0
                   native['time_edges'].max() - native_t0
               ])
    plt.ylim([-50, 150])
    plt.xlabel('PMT ID')
    plt.ylabel('TOA - t0 (ns)')
    plt.colorbar()

    sum_data = np.log10(native['toa'].sum(axis=1) + 1)
    nonzeroa = (sum_data > 0)
    nonzerob = nonzeroa[:pmt_info['phi'].size]
    occ = np.log10((native['toa'].sum(axis=1) + 1) / mc_triggers)

    fig = plt.figure(figsize=figsize)
    x = np.linspace(2, 3.5, 41)
    b, x = np.histogram(sum_data[nonzeroa], x)
    jplot.unfilledBar(x, b)
    plt.xlabel('log(Nhit)')
    plt.ylabel('PMTs')

    fig = plt.figure(figsize=figsize)

    #ax = fig.add_subplot(111, projection='mollweide')
    plt.scatter(pmt_info['phi'][nonzerob],
                pmt_info['costheta'][nonzerob],
                s=10.,
                c=sum_data[nonzeroa],
                edgecolor='',
                vmin=2.,
                vmax=3.2)
    plt.xlabel('phi')
    plt.ylabel('cos(theta)')
                time_array = np.concatenate((time_array,
                                             this_array[this_array > 0]))
            except:
                print 'PMT problematic', one_pmt, new_list[isoc]
                continue
                
            if ipmt % 500 == 0:
                print ipmt
                
        # PMT ready. Make histogram and store time delay
        time_residuals[:, one_pmt], pmt_delays[one_pmt] =  makeHistogram(time_array)
        
    data['time_residuals'] = time_residuals
    data['pmt_delays']     = pmt_delays
    pickle.dump(data, open(outfile_name,'w'))
    
    for reader in reader_list:
        reader.close()
    
    # Verification for one file
    fig = plt.figure()
    colors = ['b','r','g','m']
    for iTest, pmtid in enumerate(test_pmts):
        jplot.unfilledBar(residual_axis + data['pmt_delays'][pmtid],
                          data['time_residuals'][:,pmtid], color = colors[iTest])
    plt.yscale('log')
    fig.savefig(outfile_name.rstrip('.pckl') + '.png')



Exemplo n.º 14
0
def getGausTimes(n = [],
                 ybins = [],
                 expected_tdelay = 76.,
                 prompt_peak_width = 4.,
                 refl_peak_width = 4.5,
                 second_gaus = True,
                 plot = False,
                 debug = False):
    
    # ycenters
    ycenters = (ybins[1:] + ybins[:-1])/2.
    
    # bin width
    bin_width = ybins[1]-ybins[0]

    
    # Find the highest peak
    prompt_peak_index = n.argmax()
    
    # First peak range (in bins)
    fit_s = prompt_peak_index - int(prompt_peak_width/bin_width)
    fit_e = prompt_peak_index + int(prompt_peak_width/bin_width)
        
    
    # Fit a gaussian +/- prompt_peak_width ns around the peak
    popt =  [n[prompt_peak_index]/2., ycenters[prompt_peak_index],3.]

    
    try:
        popt, pcov = optimize.curve_fit(analysis.gaus,
                                        ycenters[fit_s:fit_e+1],
                                        n[fit_s:fit_e+1],
                                        popt,
                                        )
        perr = np.sqrt(np.diag(pcov))
        terr1 = perr[1]
        t1 = popt[1]
    except:
        terr1 = -1
        t1 = -1
    
    # Fit a gaussian around the second peak, expected_tdelay-refl_peak_width+2*refl_peak_width
    refl_peak_index = prompt_peak_index + int(expected_tdelay/bin_width)
    fit_s2 = refl_peak_index - int(refl_peak_width/bin_width)
    fit_e2 = refl_peak_index + int((refl_peak_width)/bin_width)
    fit_e2 = np.min([fit_e2, ybins.size-1])
    
    if refl_peak_index > (ybins.size-1):
        terr2 = -1
        t2 = -1
    else:
        if second_gaus:        
            try:
                popt2 = [n[refl_peak_index]/2.,ycenters[refl_peak_index],3.]
                popt2, pcov2 = optimize.curve_fit(analysis.gaus,
                                                  ycenters[fit_s2:fit_e2+1],
                                                  n[fit_s2:fit_e2+1],
                                                  popt2)
                perr2 = np.sqrt(np.diag(pcov2))
                terr2 = perr2[1]
                t2 = popt2[1]
            except:
                # There are errors here when the ToA histogram is empty
                terr2 = -1
                t2 = -1
        else:
            t2 = ycenters[fit_s2 + n[fit_s2:].argmax()]
            terr2 = -1
    if plot:

        print 'Times', t1, terr1, t2, terr2
        fig = plt.figure(figsize=(7,4))
        ax1 = fig.add_subplot(111)
        jplot.unfilledBar(ybins, n, color='0.7')

        newx = np.linspace(ycenters[fit_s],
                           ycenters[fit_e], 101)
        plt.plot(newx, analysis.gaus(newx, *popt), 'r')
        print t1+expected_tdelay
        plt.axvline(x = t1 + expected_tdelay-refl_peak_width,
                    ymin=0, ymax = n.max()*1.2,
                    linestyle='--', color = 'k')
        plt.axvline(x = t1 + expected_tdelay+refl_peak_width,
                    ymin=0, ymax = n.max()*1.2,
                    linestyle='--', color = 'k')
        if second_gaus:
            try:
                newx = np.linspace(ycenters[fit_s2],
                                   ycenters[fit_e2], 101)
                plt.plot(newx, analysis.gaus(newx, *popt2), 'r')    
                plt.xlim([ycenters[prompt_peak_index]-20., ycenters[refl_peak_index] + 20])
            except:
                print 'Could not plot second gaus (out of bounds)'
        else:
            plt.axvline(x = t2, ymin =0, ymax = n.max()*1.2)
        
        plt.yscale('log')
        plt.ylabel('N hits')
        plt.ylim([1., n[prompt_peak_index]*1.3])

        return fig
    
        #raw_input()
    return t1, terr1, t2, terr2
                print 'logE(reco_E)', logE_edges[logE], logE_edges[logE+1]

                # This is a histogram of the bin weights
                if doPlots and len(logw < 10) > 0:

                    fig = plt.figure(figsize=(12,6))
                    fig_title = flabel + '_' + \
                        "%0.2f" % cosZ_edges[cosZ] + '_' +  "%0.2f" % cosZ_edges[cosZ+1] + '___' + \
                        "%0.2f" % logE_edges[logE] + '_' +  "%0.2f" % logE_edges[logE+1]

                    # Distribution of event weights
                    fig.add_subplot(1,2,1)
                    xhist = np.linspace(0, 10, 101)
                    xhist[-1] = np.inf
                    bhist, x = np.histogram(logw, xhist)
                    jplot.unfilledBar(xhist, bhist)
                    plt.axvline(x=logw.mean()+2*logw.std(), lw=2, color='r', linestyle='-')
                    plt.axvline(x=logw.mean()+3*logw.std(), lw=2, color='r', linestyle='--')
                    plt.ylabel('N events')
                    plt.xlabel('weight (a.u.)')
                    plt.yscale('log')

                    # Effective area for one bin
                    fig.add_subplot(1,2,2)
                    plt.pcolor(trueE_edges, trueZ_edges, effarea_onebin, cmap='Blues')
                    plt.xlim([trueE_edges.min(), trueE_edges.max()])
                    plt.axvspan(logE_edges[logE], logE_edges[logE+1], lw=2,
                                facecolor='0.3', alpha=0.2)
                    plt.axhspan(cosZ_edges[cosZ], cosZ_edges[cosZ+1], lw=2,
                                facecolor='0.3', alpha=0.2)
Exemplo n.º 16
0
def compareTracking(set_list=[],
                    costheta_range=[-1, 1],
                    outdir='',
                    pltlabels=[]):
    reference = set_list[0]

    if len(pltlabels) == 0:
        pltlabels = generic_labels[:len(set_list)]

    set_bool = []
    for one_set in set_list:
        set_bool.append((one_set['costheta_dir'] >= costheta_range[0])*\
                        (one_set['costheta_dir'] <= costheta_range[1]))

    # Do the reference set first
    ref_gen = len(reference['end_volume'][set_bool[0]])
    labels_ref, values_ref = zip(
        *collections.Counter(reference['end_volume'][set_bool[0]]).items())
    labels_ref = np.array(labels_ref)
    values_ref = np.array(values_ref)
    sort_ref = np.argsort(labels_ref)
    labels_ref = labels_ref[sort_ref]
    values_ref = values_ref[sort_ref]

    values_list = []

    for i in range(1, len(set_list)):
        set_gen = len(set_list[i]['end_volume'][set_bool[i]])
        #print 'Difference in photons produced', ref_gen - set_gen, np.sqrt(ref_gen)

        labels, values = zip(*collections.Counter(set_list[i]['end_volume'][
            set_bool[i]]).items())
        # Check if there are differences in the fields
        diff_labels = list(set(labels_ref) - set(labels))
        if len(diff_labels) > 0:
            #print 'Labels missing ', diff_labels

            labels = list(labels) + diff_labels
            values = list(values) + [0] * len(diff_labels)

        labels = np.array(labels)
        values = np.array(values)
        onesort = np.argsort(labels)
        labels = labels[onesort]
        values = values[onesort]

        values_list.append(values)

    fig1 = plt.figure(figsize=(7, 7))
    ax1 = fig1.add_subplot(211)
    plt.title('cos(theta) = [' + "%.2f" % costheta_range[0] + ', ' +
              "%.2f" % costheta_range[1] + ']')
    indices = np.arange(len(labels_ref) + 1)
    jplot.unfilledBar(indices, values_ref, label=pltlabels[0])
    plt.xticks(indices + 0.5, labels_ref)
    plt.yscale('log')
    plt.xlim([0, indices[-1]])
    plt.ylabel('Photons')

    for i in range(len(values_list)):
        jplot.unfilledBar(indices,
                          values_list[i],
                          color=color_list[i],
                          label=pltlabels[i + 1])
    plt.legend(loc=0)

    ax2 = fig1.add_subplot(212, sharex=ax1)
    #fig2 = plt.figure()
    #plt.title('cos(theta) = [' + "%.2f" % costheta_range[0] + ', '+"%.2f" % costheta_range[1] + ']')
    plt.ylabel('Ratio')
    plt.plot([0, indices[-1]], [1, 1], '--k')
    ref_error = np.sqrt(values_ref) / values_ref
    for i in range(len(values_list)):
        ratio = values_list[i] * 1. / values_ref
        error = np.sqrt(2) * ratio * ref_error
        jplot.unfilledBar(indices, ratio, color=color_list[i])
        jplot.errorMarkVert(indices * 1.,
                            ratio,
                            yerror=error,
                            color=color_list[i])
        print ratio
    plt.xticks(indices + 0.5, labels_ref)
    plt.ylim([0.9, 1.1])
    #plt.ylim([0.65, 1.35])
    plt.xlim([0, indices[-1]])
    plt.subplots_adjust(hspace=0)

    fig3 = plt.figure(figsize=(7, 7))
    ax3 = fig3.add_subplot(211)

    plt.title('cos(theta) = [' + "%.2f" % costheta_range[0] + ', ' +
              "%.2f" % costheta_range[1] + ']')
    plt.ylabel('Photons')
    plt.xlabel('Steps taken')
    myx = np.arange(0.5, 17, 1)
    #myx[-1] = np.inf

    ref_steps, x = np.histogram(reference['n_steps'][set_bool[0]] - 1, myx)
    jplot.unfilledBar(myx, ref_steps, label=pltlabels[0])
    for i in range(1, len(set_list)):
        n_steps, x = np.histogram(set_list[i]['n_steps'][set_bool[i]] - 1, myx)
        jplot.unfilledBar(myx,
                          n_steps,
                          color=color_list[i - 1],
                          label=pltlabels[i])
    plt.yscale('log')
    plt.legend(loc=0)

    ax4 = fig3.add_subplot(212, sharex=ax3)
    plt.ylabel('Ratio')
    plt.xlabel('Steps taken')

    for i in range(1, len(set_list)):
        n_steps, x = np.histogram(set_list[i]['n_steps'][set_bool[i]] - 1, myx)
        ratio = n_steps * 1. / ref_steps
        error = np.sqrt(2) * ratio * np.sqrt(ref_steps) / ref_steps
        jplot.unfilledBar(myx, ratio, color=color_list[i - 1])
        jplot.errorMarkVert(myx, ratio, yerror=error, color=color_list[i - 1])
        print ratio
    plt.ylim([0.9, 1.1])
    #plt.ylim([0.65, 1.35])
    plt.subplots_adjust(hspace=0)

    if len(outdir) > 0:
        theta_str = "%.2f" % costheta_range[0] + '_' + "%.2f" % costheta_range[
            1]
        theta_str = theta_str.replace('.', '')
        fig1.savefig(os.path.join(outdir, 'EndPhotons_' + theta_str + '.pdf'),
                     dpi=200)
        #fig2.savefig(os.path.join(outdir, 'EndPhotonsRatio_'+theta_str+'.pdf'), dpi=200)
        fig3.savefig(os.path.join(outdir, 'Steps_' + theta_str + '.pdf'),
                     dpi=200)
        #fig4.savefig(os.path.join(outdir, 'StepsRatio_'+theta_str+'.pdf'), dpi=200)

    return
Exemplo n.º 17
0
def plotComparison(data=None,
                   datasets=[],
                   datakey='',
                   scale_factor=[],
                   labels=[],
                   figname='',
                   xaxis=np.arange(0, 100, 2),
                   xlabel='Nhits',
                   ylabel='Entries',
                   minall=-1,
                   outdir=None,
                   verbose=False):

    if len(scale_factor) == 0:
        scale_factor = [1.] * len(datasets)
    if len(labels) == 0:
        labels = datasets

    # Loop over the different levels
    for k, level in enumerate(['top', 'middle', 'bottom', 'all']):
        # Reading each of the files one by one
        if verbose: print '\n****', level, '*****'
        nbins = []
        myfig = plt.figure(figsize=(8, 5))

        if level == 'all':
            if minall < 0:
                xaxis = np.arange(1.3 * xaxis.max(), 2.3 * xaxis.max(),
                                  xaxis[1] - xaxis[0])
            else:
                xaxis = np.arange(minall, 2.3 * xaxis.max(),
                                  xaxis[1] - xaxis[0])

        for i, one_set in enumerate(datasets):
            n, x = np.histogram(data[one_set][datakey][:, k], xaxis)
            nbins.append(n)

            if verbose:
                print '\n', labels[i]

                print 'SUM ', data[one_set][datakey][:,
                                                     k].sum() * scale_factor[i]
                print 'Mean ', data[one_set][datakey][:, k].mean()
                print 'Std  ', data[one_set][datakey][:, k].std()

            if i == 0:
                baseline = data[one_set][datakey][:, k].mean()

            if i > 0:
                print one_set, level, 1 - data[one_set][datakey][:, k].mean(
                ) / baseline

            jplot.unfilledBar(xaxis,
                              nbins[-1] * scale_factor[i],
                              color=mycolors[i])
            jplot.errorMark(xaxis, nbins[-1]*scale_factor[i],
                            error=np.sqrt(nbins[-1])*scale_factor[i], color=mycolors[i],
                            label =labels[i] + '\n' + \
                                r'$\mu$' + '=' + "%.2f" % data[one_set][datakey][:,k].mean() + '\n'+\
                                r'$\sigma$' + '=' + "%.2f" % data[one_set][datakey][:,k].std())

        plt.title(level)

        plt.xlabel(xlabel)
        plt.ylabel(ylabel)

        #plt.ylim([0,])
        plt.legend(loc=0, ncol=1)
        if len(figname) > 0:
            myfig.savefig(os.path.join(outdir, figname + '_' + level + '.png'),
                          dpi=300)
            myfig.savefig(os.path.join(outdir, figname + '_' + level + '.pdf'))
    if iPhoton % 10000 == 0:
        print iPhoton

    if iPhoton == stop_at:
        print 'Momentum'
        print good_mom[iPhoton]
        print 'Position'
        print good_pos[iPhoton]
        break

    data['nsteps'][iPhoton] = len(good_pos[iPhoton])

# In[ ]:

b, x = np.histogram(data['delta_t'], np.linspace(0, 3.))
jplot.unfilledBar(x, b)
plt.xlabel('Time delay (ns)')
plt.show()

# In[ ]:

data['r'] = np.sqrt(data['y']**2 + data['x']**2)
phidiff = (data['phi_f'] - data['phi_i'])
phidiff[phidiff < 0] += np.pi * 2
data['phidiff'] = phidiff

# In[ ]:

print data['phi_i'][:10]
print data['phi_f'][:10]