Beispiel #1
0
def peak_drift(dg):
    """
    show any drift of the 1460 peak (5 minute bins)
    """
    cols = ['trapEmax', 'ts_glo']

    lh5_dir = os.path.expandvars(dg.config['lh5_dir'])
    hit_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB['hit_file']
    df_hit = lh5.load_dfs(hit_list, cols, 'ORSIS3302DecoderForEnergy/hit')
    df_hit.reset_index(inplace=True)
    rt_min = dg.fileDB['runtime'].sum()
    print(f'runtime: {rt_min:.2f} min')

    # settings
    # use uncalibrated energy
    elo, ehi, epb, etype = 3400, 3800, 1, 'trapEmax'
    df_hit = df_hit.query(f'trapEmax > {elo} and trapEmax < {ehi}').copy()

    # use calibrated energy (hit file)
    # elo, ehi, epb, etype = 1450, 1470, 1, 'trapEmax_cal'
    # df_hit = df_hit.query(f'trapEmax_cal > {elo} and trapEmax_cal < {ehi}').copy()

    # # diagnostic plot
    hE, xE, vE = pgh.get_hist(df_hit[etype], range=(elo, ehi), dx=epb)
    plt.plot(xE[1:], hE, c='b', ds='steps', lw=1)
    # plt.show()
    plt.savefig('./plots/oppi_1460_hist.pdf')
    plt.cla()

    t0 = df_hit['ts_glo'].values[0]
    df_hit['ts_adj'] = (df_hit['ts_glo'] - t0) / 60  # minutes after 0

    tlo, thi, tpb = 0, df_hit['ts_adj'].max(), 1

    nbx = int((thi - tlo) / tpb)
    nby = int((ehi - elo) / epb)

    h = plt.hist2d(df_hit['ts_adj'],
                   df_hit['trapEmax'],
                   bins=[nbx, nby],
                   range=[[tlo, thi], [elo, ehi]],
                   cmap='jet')

    plt.xlabel(f'Time ({tpb:.1f} min/bin)', ha='right', x=1)
    plt.ylabel('trapEmax', ha='right', y=1)
    plt.tight_layout()
    # plt.show()
    plt.savefig('./plots/oppi_1460_drift.png', dpi=300)
Beispiel #2
0
def plot_energy(runs):
    radius_arr_1 = []
    mean_energy_arr_1 = []
    std_energy_arr_1 = []
    mean_dcr_arr_1 = []
    std_dcr_arr_1 = []
    count_arr_1 = []

    radius_arr_2 = []
    mean_energy_arr_2 = []
    std_energy_arr_2 = []
    mean_dcr_arr_2 = []
    std_dcr_arr_2 = []
    count_arr_2 = []


    for run in runs:
        # get run files
        dg = DataGroup('cage.json', load=True)
        str_query = f'run=={run} and skip==False'
        dg.fileDB.query(str_query, inplace=True)

        #get runtime, startime, runtype
        runtype_list = np.array(dg.fileDB['runtype'])
        runtype = runtype_list[0]
        rt_min = dg.fileDB['runtime'].sum()
        u_start = dg.fileDB.iloc[0]['startTime']
        t_start = pd.to_datetime(u_start, unit='s')

        # get scan position

        if runtype == 'alp':
            alphaDB = pd.read_hdf('alphaDB.h5')
            scan_pos = alphaDB.loc[alphaDB['run']==run]
            radius = np.array(scan_pos['radius'])[0]
            angle = np.array(scan_pos['angle'])[0]
            angle_det = 270 + angle
            print(f'Radius: {radius}; Angle: {angle}')

        else:
            radius = 'n/a'
            angle = 'n/a'
            angle_det = 'n/a'

        # get hit df
        lh5_dir = dg.lh5_user_dir #if user else dg.lh5_dir
        hit_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB['hit_file']
        df_hit = lh5.load_dfs(hit_list, ['trapEmax', 'trapEmax_cal', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')

        # use baseline cut
        df_cut = df_hit.query('bl > 8500 and bl < 10000').copy()

        #creat new DCR
        const = 0.0555
        df_cut['dcr_linoff'] = df_cut['dcr_raw'] + const*df_cut['trapEmax']

        #create 0-50
        df_cut['tp0_50'] = df_cut['tp_50']- df_cut['tp_0']

        # create cut for alphas
        alpha_cut = 'dcr_linoff > 25 and dcr_linoff < 200 and tp0_50 > 100 and tp0_50 < 400 and trapEmax_cal < 6000'
        new_dcr_cut = df_cut.query(alpha_cut).copy()
        # len(new_dcr_cut)

        alpha_energy = np.array(new_dcr_cut['trapEmax_cal'])
        mean_energy = np.mean(alpha_energy)
        std_energy = np.std(alpha_energy)
#         std_energy = np.sqrt(len(new_dcr_cut['trapEmax']))

        alpha_dcr = np.array(new_dcr_cut['dcr_linoff'])
        mean_dcr = np.mean(alpha_dcr)
        std_dcr = np.std(alpha_dcr)
#         std_dcr = np.sqrt((len(new_dcr_cut['dcr_linoff'])))

        print(f'Energy std: {std_energy} \n DCR std: {std_dcr}')

        if radius%5 == 0:
            radius_arr_1.append(radius)
            mean_energy_arr_1.append(mean_energy)
            std_energy_arr_1.append(std_energy)
            mean_dcr_arr_1.append(mean_dcr)
            std_dcr_arr_1.append(std_dcr)
            count_arr_1.append(len(alpha_energy))

        else:
            radius_arr_2.append(radius)
            mean_energy_arr_2.append(mean_energy)
            std_energy_arr_2.append(std_energy)
            mean_dcr_arr_2.append(mean_dcr)
            std_dcr_arr_2.append(std_dcr)
            count_arr_2.append(len(alpha_energy))

    # make plots with errorbars
    fig, ax = plt.subplots()

    energy_plot = plt.errorbar(radius_arr_1, mean_energy_arr_1, yerr=std_energy_arr_1, marker = '.', ls='none', color = 'red', label='Scan 1')
    ax.set_xlabel('Radial position (mm)', fontsize=16)
    ax.set_ylabel('Mean energy (keV)', fontsize=16)
    plt.setp(ax.get_xticklabels(), fontsize=14)
    plt.setp(ax.get_yticklabels(), fontsize=14)


#     plt.yscale('log')
    plt.title('Mean energy of alphas by radial position \nnormal incidence', fontsize=16)


    plt.errorbar(radius_arr_2, mean_energy_arr_2, yerr=std_energy_arr_2, marker = '.', ls='none', color = 'blue', label='Scan 2')
    plt.legend()
    plt.tight_layout()

    plt.savefig('./plots/normScan/cal_normScan/errorbars_energy_deg.png', dpi=200)

    plt.clf()
    plt.close()

    fig, ax = plt.subplots()
    dcr_plot = plt.errorbar(radius_arr_1, mean_dcr_arr_1, yerr=std_dcr_arr_1, marker = '.', ls='none', color = 'red', label='Scan 1')
    ax.set_xlabel('Radial position (mm)', fontsize=16)
    ax.set_ylabel('Mean DCR value (arb)', fontsize=16)
    plt.setp(ax.get_xticklabels(), fontsize=14)
    plt.setp(ax.get_yticklabels(), fontsize=14)

    #    plt.yscale('log')
    plt.title('Mean DCR value by radial position \nnormal incidence', fontsize=16)


    plt.errorbar(radius_arr_2, mean_dcr_arr_2, yerr=std_dcr_arr_2, marker = '.', ls='none', color = 'blue', label='Scan 2')
    plt.legend()
    plt.tight_layout()

    plt.savefig('./plots/normScan/cal_normScan/errorbars_dcr_avg.png', dpi=200)

    plt.clf()
    plt.close()

    # make plots without errorbars
    fig, ax = plt.subplots()
    energy_plot = plt.plot(radius_arr_1, mean_energy_arr_1, '.r', label='Scan 1')
    ax.set_xlabel('Radial position (mm)', fontsize=16)
    ax.set_ylabel('Mean energy (keV)', fontsize=16)
    plt.setp(ax.get_xticklabels(), fontsize=14)
    plt.setp(ax.get_yticklabels(), fontsize=14)


#     plt.yscale('log')
    plt.title('Mean energy of alphas by radial position \nnormal incidence', fontsize=16)


    plt.plot(radius_arr_2, mean_energy_arr_2, '.b', label='Scan 2')
    plt.legend()
    plt.tight_layout()

    plt.savefig('./plots/normScan/cal_normScan/energy_deg.png', dpi=200)

    plt.clf()
    plt.close()

    fig, ax = plt.subplots()
    dcr_plot = plt.plot(radius_arr_1, mean_dcr_arr_1, '.r', label='Scan 1')
    ax.set_xlabel('Radial position (mm)', fontsize=16)
    ax.set_ylabel('Mean DCR value (arb)', fontsize=16)
    plt.setp(ax.get_xticklabels(), fontsize=14)
    plt.setp(ax.get_yticklabels(), fontsize=14)

    #    plt.yscale('log')
    plt.title('Mean DCR value by radial position \nnormal incidence', fontsize=16)

    plt.plot(radius_arr_2, mean_dcr_arr_2, '.b', label='Scan 2')
    plt.legend()
    plt.tight_layout()

    plt.savefig('./plots/normScan/cal_normScan/dcr_avg.png', dpi=200)

    # plt.clf()
    plt.close()
Beispiel #3
0
def dcr_AvE(runs, user=False, hit=True, cal=True, etype='trapEmax', cut=True):

    for run in runs:
        # get run files
        dg = DataGroup('$CAGE_SW/processing/cage.json', load=True)
        str_query = f'run=={run} and skip==False'
        dg.fileDB.query(str_query, inplace=True)

        #get runtime, startime, runtype
        runtype_list = np.array(dg.fileDB['runtype'])
        runtype = runtype_list[0]
        rt_min = dg.fileDB['runtime'].sum()
        u_start = dg.fileDB.iloc[0]['startTime']
        t_start = pd.to_datetime(u_start, unit='s')

        # get scan position

        if runtype == 'alp':
            alphaDB = pd.read_hdf(os.path.expandvars('$CAGE_SW/processing/alphaDB.h5'))
            scan_pos = alphaDB.loc[alphaDB['run']==run]
            radius = np.array(scan_pos['radius'])[0]
            angle = np.array(scan_pos['source'])[0]
            rotary = np.array(scan_pos['rotary'])[0]
            radius = int(radius)
            angle_det = int((-1*angle) - 90)
            if rotary <0:
                angle_det = int(angle + 270)
            print(f'Radius: {radius}; Angle: {angle_det}')

        else:
            radius = 'n/a'
            angle = 'n/a'
            angle_det = 'n/a'

        if cal==True:
            etype_cal = etype+'_cal'



        # get data and load into df
        lh5_dir = dg.lh5_user_dir if user else dg.lh5_dir

        if hit==True:
            print('Using hit files')
            file_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB['hit_file']
            if run<=117 and cal==True:
                df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')
            elif run>117 and cal==True:
                df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')

            elif run<=117 and cal==False:
                df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')
            elif run>117 and cal==False:
                df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')

        elif hit==False:
            print('Using dsp files')
            file_list = lh5_dir + dg.fileDB['dsp_path'] + '/' + dg.fileDB['dsp_file']
            if run<=117 and cal==True:
                df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')
            elif run>117 and cal==True:
                df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')

            elif run<=117 and cal==False:
                df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')
            elif run>117 and cal==False:
                df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')

        else:
            print('dont know what to do here! need to specify if working with calibrated/uncalibrated data, or dsp/hit files')



        # use baseline cut
        if run <=117:
            bl_cut_lo, bl_cut_hi = 8500, 10000
        if run>117:
            bl_cut_lo, bl_cut_hi = 9700, 9760

        df_cut = df.query(f'bl > {bl_cut_lo} and bl < {bl_cut_hi}').copy()

        #creat new DCR
        if run <= 86:
            const = 0.0555
            df_cut['dcr_linoff'] = df_cut['dcr_raw'] + const*df_cut['trapEmax']

        if run>86 and run <=117:
            const = -0.0225
            df_cut['dcr_linoff'] = df_cut['dcr_raw'] + const*df_cut['trapEmax']

        if run>117:
            const = -0.0003
            const2 = -0.0000003
            df_cut['dcr_linoff'] = df_cut['dcr'] + const*(df_cut['trapEftp']) + const2*(df_cut['trapEftp'])**2



        #create 0-50
        df_cut['tp0_50'] = df_cut['tp_50']- df_cut['tp_0']

        # create cut for alphas
        # alpha_cut = 'dcr_linoff > 25 and dcr_linoff < 200 and tp0_50 > 100 and tp0_50 < 400 and trapEmax_cal < 6000'
        # new_dcr_cut = df_cut.query(alpha_cut).copy()
        # len(new_dcr_cut)

        #-------------------------------------
        # Plots before alpha cuts
        #--------------------

        # select energy type and energy range
        if cal==False:
            elo, ehi, epb = 0, 10000, 10 #entire enerty range trapEftp
            e_unit = ' (uncal)'
        elif cal==True:
            elo, ehi, epb = 0, 6000, 10
            etype=etype_cal
            e_unit = ' (keV)'

        # Make (calibrated) energy spectrum_________

        fig, ax = plt.subplots()
        fig.suptitle(f'Energy', horizontalalignment='center', fontsize=16)

        nbx = int((ehi-elo)/epb)

        energy_hist, bins = np.histogram(df_cut[etype], bins=nbx,
                range=[elo, ehi])
        energy_rt = np.divide(energy_hist, rt_min * 60)

        plt.semilogy(bins[1:], energy_rt, ds='steps', c='b', lw=1) #, label=f'{etype}'

        ax.set_xlabel(f'{etype+e_unit}', fontsize=16)
        ax.set_ylabel('counts/sec', fontsize=16)
        plt.setp(ax.get_xticklabels(), fontsize=14)
        plt.setp(ax.get_yticklabels(), fontsize=14)

        ax.text(0.95, 0.83, f'r = {radius} mm \ntheta = {angle_det} deg', verticalalignment='bottom',
                    horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=14, bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10})

        # plt.legend()
        plt.title(f'\n{runtype} run {run}, {rt_min:.2f} mins', fontsize=12)
        plt.tight_layout()
        # plt.savefig(f'./plots/normScan/cal_normScan/{runtype}_energy_run{run}.png', dpi=200)
        if runtype=='alp':
            plt.savefig(f'./plots/angleScan/{runtype}_energy_{radius}mm_{angle_det}deg_run{run}.png', dpi=200)
        elif runtype=='bkg':
            plt.savefig(f'./plots/angleScan/{runtype}_energy_run{run}.png', dpi=200)
        plt.clf()
        plt.close()


        # AoE vs E---------------------------------
        fig, ax = plt.subplots()
        alo, ahi, apb = 0.0, 0.09, 0.0001
        if run>=60:
            alo, ahi, apb = 0.005, 0.0905, 0.0001
        if run>117:
            alo, ahi, apb = 0.0, 0.125, 0.001

        nbx = int((ehi-elo)/epb)
        nby = int((ahi-alo)/apb)

        fig.suptitle(f'A/E vs Energy', horizontalalignment='center', fontsize=16)

        h = plt.hist2d(df_cut[etype], df_cut['AoE'], bins=[nbx,nby],
                    range=[[elo, ehi], [alo, ahi]], cmap='viridis', norm=LogNorm())

        cb = plt.colorbar()
        cb.set_label("counts", ha = 'right', va='center', rotation=270, fontsize=14)
        cb.ax.tick_params(labelsize=12)
        ax.set_xlabel(f'{etype+e_unit}', fontsize=16)
        ax.set_ylabel('A/E (arb)', fontsize=16)
        plt.setp(ax.get_xticklabels(), fontsize=14)
        plt.setp(ax.get_yticklabels(), fontsize=14)


        ax.text(0.95, 0.83, f'r = {radius} mm \ntheta = {angle_det} deg', verticalalignment='bottom',
                    horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=14, bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10})

        # plt.legend()
        plt.title(f'\n{runtype} run {run}, {rt_min:.2f} mins', fontsize=12)
        plt.tight_layout()
        # plt.savefig(f'./plots/normScan/cal_normScan/{runtype}_AoE_run{run}.png', dpi=200)
        if runtype=='alp':
            plt.savefig(f'./plots/angleScan/{runtype}_AoE_{radius}mm_{angle_det}deg_run{run}.png', dpi=200)
        elif runtype=='bkg':
            plt.savefig(f'./plots/angleScan/{runtype}_AoE_run{run}.png', dpi=200)
        # plt.show()

        plt.clf()
        plt.close()

        # DCR vs E___________

        fig, ax = plt.subplots()

        if run>=60 and run<117:
            dlo, dhi, dpb = -100, 300, 0.6
        elif run>117:
            dlo, dhi, dpb = -20., 60, 0.1

        nbx = int((ehi-elo)/epb)
        nby = int((dhi-dlo)/dpb)

        fig.suptitle(f'DCR vs Energy', horizontalalignment='center', fontsize=16)

        h = plt.hist2d(df_cut[etype], df_cut['dcr_linoff'], bins=[nbx,nby],
                    range=[[elo, ehi], [dlo, dhi]], cmap='viridis', norm=LogNorm())

        cb = plt.colorbar()
        cb.set_label("counts", ha = 'right', va='center', rotation=270, fontsize=14)
        cb.ax.tick_params(labelsize=12)
        ax.set_xlabel('Energy (keV)', fontsize=16)
        ax.set_ylabel('DCR (arb)', fontsize=16)
        plt.setp(ax.get_xticklabels(), fontsize=14)
        plt.setp(ax.get_yticklabels(), fontsize=14)

        # plt.legend()

        ax.text(0.95, 0.83, f'r = {radius} mm \ntheta = {angle_det} deg', verticalalignment='bottom',
                    horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=14, bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10})

        plt.title(f'\n{runtype} run {run}, {rt_min:.2f} mins', fontsize=12)
        plt.tight_layout()
        # plt.savefig(f'./plots/normScan/cal_normScan/{runtype}_dcr_run{run}.png', dpi=200)
        if runtype=='alp':
            plt.savefig(f'./plots/angleScan/{runtype}_DCR_{radius}mm_{angle_det}deg_run{run}.png', dpi=200)
        elif runtype=='bkg':
            plt.savefig(f'./plots/angleScan/{runtype}_DCR_run{run}.png', dpi=200)
        # plt.show()
        plt.clf()
        plt.close()

        # DCR vs A/E___________

        fig, ax = plt.subplots()
        nbx = int((ahi-alo)/apb)
        nby = int((dhi-dlo)/dpb)

        fig.suptitle(f'A/E vs DCR', horizontalalignment='center', fontsize=16)

        h = plt.hist2d(df_cut['AoE'], df_cut['dcr_linoff'], bins=[nbx,nby],
                    range=[[alo, ahi], [dlo, dhi]], cmap='viridis', norm=LogNorm())

        cb = plt.colorbar()
        cb.set_label("counts", ha = 'right', va='center', rotation=270, fontsize=14)
        cb.ax.tick_params(labelsize=12)
        ax.set_xlabel('A/E (arb)', fontsize=16)
        ax.set_ylabel('DCR (arb)', fontsize=16)
        plt.setp(ax.get_xticklabels(), fontsize=12)
        plt.setp(ax.get_yticklabels(), fontsize=14)

        # plt.legend()
        ax.text(0.95, 0.83, f'r = {radius} mm \ntheta = {angle_det} deg', verticalalignment='bottom',
                    horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=14, bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10})

        plt.title(f'\n{runtype} run {run}, {rt_min:.2f} mins', fontsize=12)
        plt.tight_layout()
        # plt.savefig(f'./plots/normScan/cal_normScan/{runtype}_AoE_vs_dcr_run{run}.png', dpi=200)
        if runtype=='alp':
            plt.savefig(f'./plots/angleScan/{runtype}_AoEvDCR_{radius}mm_{angle_det}deg_run{run}.png', dpi=200)
        elif runtype=='bkg':
            plt.savefig(f'./plots/angleScan/{runtype}_AoEvDCR_run{run}.png', dpi=200)
        # plt.show()
        plt.clf()
        plt.close()

        # DCR vs tp_50___________

        fig, ax = plt.subplots()
        fig.suptitle(f'DCR vs 50% rise time', horizontalalignment='center', fontsize=16)

        tlo, thi, tpb = 0, 800, 10

        nbx = int((dhi-dlo)/dpb)
        nby = int((thi-tlo)/tpb)

        alpha_dcr_hist = plt.hist2d(df_cut['dcr_linoff'], df_cut['tp0_50'], bins=[nbx,nby],
                range=[[dlo, dhi], [tlo, thi]], cmap='viridis', norm=LogNorm())

        cb = plt.colorbar()
        cb.set_label("counts", ha = 'right', va='center', rotation=270, fontsize=14)
        cb.ax.tick_params(labelsize=12)
        ax.set_xlabel('DCR (arb)', fontsize=16)
        ax.set_ylabel('tp 0-50 (ns)', fontsize=16)
        plt.setp(ax.get_xticklabels(), fontsize=14)
        plt.setp(ax.get_yticklabels(), fontsize=14)

        # plt.legend()
        ax.text(0.95, 0.83, f'r = {radius} mm \ntheta = {angle_det} deg', verticalalignment='bottom',
                    horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=14, bbox={'facecolor': 'white', 'alpha': 0.95, 'pad': 10})

        plt.title(f'\n{runtype} run {run}, {rt_min:.2f} mins', fontsize=12)
        plt.tight_layout()
        # plt.savefig(f'./plots/normScan/cal_normScan/{runtype}_dcr_vs_tp0_50_run{run}.png', dpi=200)
        if runtype=='alp':
            plt.savefig(f'./plots/angleScan/{runtype}_DCRvTp050_{radius}mm_{angle_det}deg_run{run}.png', dpi=200)
        elif runtype=='bkg':
            plt.savefig(f'./plots/angleScan/{runtype}_DCRvTp050_run{run}.png', dpi=200)
        # plt.show()
        plt.clf()
        plt.close()

        # 1D AoE_________

        fig, ax = plt.subplots()
        fig.suptitle(f'A/E', horizontalalignment='center', fontsize=16)

        aoe_hist, bins = np.histogram(df_cut['AoE'], bins=nbx,
                range=[alo, ahi])

        plt.semilogy(bins[1:], aoe_hist, ds='steps', c='b', lw=1) #, label=f'{etype}'

        ax.set_xlabel('A/E (arb)', fontsize=16)
        ax.set_ylabel('counts', fontsize=16)
        plt.setp(ax.get_xticklabels(), fontsize=14)
        plt.setp(ax.get_yticklabels(), fontsize=14)

        ax.text(0.95, 0.83, f'r = {radius} mm \ntheta = {angle_det} deg', verticalalignment='bottom',
                    horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=14, bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10})

        # plt.legend()
        plt.title(f'\n{runtype} run {run}, {rt_min:.2f} mins', fontsize=12)
        plt.tight_layout()
        # plt.savefig(f'./plots/normScan/cal_normScan/{runtype}_1d_aoe_run{run}.png', dpi=200)
        if runtype=='alp':
            plt.savefig(f'./plots/angleScan/{runtype}_1dAoE_{radius}mm_{angle_det}deg_run{run}.png', dpi=200)
        elif runtype=='bkg':
            plt.savefig(f'./plots/angleScan/{runtype}_1dAoE_run{run}.png', dpi=200)
        plt.clf()
        plt.close()
Beispiel #4
0
def getDataFrame(run, user=True, hit=True, cal=True, lowE=False, dsp_list=[]):
    # get run files
    dg = DataGroup('$CAGE_SW/processing/cage.json', load=True)
    str_query = f'run=={run} and skip==False'
    dg.fileDB.query(str_query, inplace=True)

    #get runtime, startime, runtype
    runtype_list = np.array(dg.fileDB['runtype'])
    runtype = runtype_list[0]
    rt_min = dg.fileDB['runtime'].sum()
    u_start = dg.fileDB.iloc[0]['startTime']
    t_start = pd.to_datetime(u_start, unit='s')

    # get scan position

    if runtype == 'alp':
        alphaDB = pd.read_hdf(
            os.path.expandvars('$CAGE_SW/processing/alphaDB.h5'))
        scan_pos = alphaDB.loc[alphaDB['run'] == run]
        radius = np.array(scan_pos['radius'])[0]
        angle = np.array(scan_pos['source'])[0]
        rotary = np.array(scan_pos['rotary'])[0]
        #radius = int(radius)
        angle_det = int((-1 * angle) - 90)
        if rotary < 0:
            angle_det = int(angle + 270)
        print(f'Radius: {radius}; Angle: {angle_det}; Rotary: {rotary}')

    else:
        radius = 'n/a'
        angle = 'n/a'
        angle_det = 'n/a'
        rotary = 'n/a'

    # print(etype, etype_cal, run)
    # exit()

    print(f'user: {user}; cal: {cal}; hit: {hit}')

    # get data and load into df
    lh5_dir = dg.lh5_user_dir if user else dg.lh5_dir

    if cal == True:
        default_dsp_list = [
            'energy', 'trapEmax', 'trapEftp', 'trapEftp_cal', 'bl', 'bl_sig',
            'bl_slope', 'lf_max', 'A_10', 'AoE', 'dcr', 'tp_0', 'tp_10',
            'tp_90', 'tp_50', 'tp_80', 'tp_max', 'ToE'
        ]

    else:
        default_dsp_list = [
            'energy', 'trapEmax', 'trapEftp', 'bl', 'bl_sig', 'bl_slope',
            'lf_max', 'A_10', 'AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50',
            'tp_80', 'tp_max', 'ToE'
        ]

    if len(dsp_list) < 1:
        print(
            f'No options specified for DSP list! Using default: {default_dsp_list}'
        )
        dsp_list = default_dsp_list

    if hit == True:
        print('Using hit files')
        file_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB[
            'hit_file']

        if lowE == True:
            file_list = lh5_dir + dg.fileDB['hit_path'] + '/lowE/' + dg.fileDB[
                'hit_file']
            print(f'Using lowE calibration files \n {file_list}')

        if cal == True:
            df = lh5.load_dfs(file_list, dsp_list,
                              'ORSIS3302DecoderForEnergy/hit')

        if cal == False:
            df = lh5.load_dfs(file_list, dsp_list,
                              'ORSIS3302DecoderForEnergy/hit')

    elif hit == False:
        print('Using dsp files')
        file_list = lh5_dir + dg.fileDB['dsp_path'] + '/' + dg.fileDB[
            'dsp_file']
        if cal == True:
            df = lh5.load_dfs(file_list, dsp_list,
                              'ORSIS3302DecoderForEnergy/dsp')
        if cal == False:
            df = lh5.load_dfs(file_list, dsp_list,
                              'ORSIS3302DecoderForEnergy/dsp')

    else:
        print(
            'dont know what to do here! need to specify if working with calibrated/uncalibrated data, or dsp/hit files'
        )

    return (df, dg, runtype, rt_min, radius, angle_det, rotary)
Beispiel #5
0
def get_hists(runs,
              user=False,
              hit=True,
              cal=True,
              etype='trapEftp',
              bl_cut=True):

    hist_arr = []
    if cal == True:
        etype_cal = etype + '_cal'

    for run in runs:
        # get run files
        dg = DataGroup('$CAGE_SW/processing/cage.json', load=True)
        str_query = f'run=={run} and skip==False'
        dg.fileDB.query(str_query, inplace=True)

        #get runtime, startime, runtype
        runtype_list = np.array(dg.fileDB['runtype'])
        runtype = runtype_list[0]
        rt_min = dg.fileDB['runtime'].sum()
        u_start = dg.fileDB.iloc[0]['startTime']
        t_start = pd.to_datetime(u_start, unit='s')

        # get scan position

        if runtype == 'alp':
            alphaDB = pd.read_hdf(
                os.path.expandvars('$CAGE_SW/processing/alphaDB.h5'))
            scan_pos = alphaDB.loc[alphaDB['run'] == run]
            radius = np.array(scan_pos['radius'])[0]
            angle = np.array(scan_pos['source'])[0]
            rotary = np.array(scan_pos['rotary'])[0]
            radius = int(radius)
            angle_det = int((-1 * angle) - 90)
            if rotary < 0:
                angle_det = int(angle + 270)
            print(f'Radius: {radius}; Angle: {angle_det}')

        else:
            radius = 'n/a'
            angle = 'n/a'
            angle_det = 'n/a'

        # print(etype, etype_cal, run)
        # exit()

        # get data and load into df
        lh5_dir = dg.lh5_user_dir if user else dg.lh5_dir

        if hit == True:
            print('Using hit files')
            file_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB[
                'hit_file']
            if run < 117 and cal == True:
                df = lh5.load_dfs(file_list, [
                    'energy', 'trapEmax', 'trapEmax_cal', 'bl', 'bl_sig',
                    'A_10', 'AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max',
                    'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'
                ], 'ORSIS3302DecoderForEnergy/hit')
            elif run >= 117 and cal == True:
                df = lh5.load_dfs(file_list, [
                    'energy', 'trapEmax', 'trapEftp', 'trapEmax_cal',
                    'trapEftp_cal', 'bl', 'bl_sig', 'bl_slope', 'lf_max',
                    'A_10', 'AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50',
                    'tp_80', 'tp_max'
                ], 'ORSIS3302DecoderForEnergy/hit')

            elif run < 117 and cal == False:
                df = lh5.load_dfs(file_list, [
                    f'{etype}', 'bl', 'bl_sig', 'A_10', 'AoE', 'ts_sec',
                    'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90',
                    'tp_50', 'tp_80', 'tp_max'
                ], 'ORSIS3302DecoderForEnergy/hit')
            elif run >= 117 and cal == False:
                df = lh5.load_dfs(file_list, [
                    f'{etype}', 'bl', 'bl_sig', 'bl_slope', 'lf_max', 'A_10',
                    'AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80',
                    'tp_max'
                ], 'ORSIS3302DecoderForEnergy/hit')

        elif hit == False:
            print('Using dsp files')
            file_list = lh5_dir + dg.fileDB['dsp_path'] + '/' + dg.fileDB[
                'dsp_file']
            if run < 117 and cal == True:
                df = lh5.load_dfs(file_list, [
                    f'{etype}', f'{etype_cal}', 'bl', 'bl_sig', 'A_10', 'AoE',
                    'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10',
                    'tp_90', 'tp_50', 'tp_80', 'tp_max'
                ], 'ORSIS3302DecoderForEnergy/dsp')
            elif run >= 117 and cal == True:
                df = lh5.load_dfs(file_list, [
                    f'{etype}', f'{etype_cal}', 'bl', 'bl_sig', 'bl_slope',
                    'lf_max', 'A_10', 'AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90',
                    'tp_50', 'tp_80', 'tp_max'
                ], 'ORSIS3302DecoderForEnergy/dsp')

            elif run < 117 and cal == False:
                df = lh5.load_dfs(file_list, [
                    f'{etype}', 'bl', 'bl_sig', 'A_10', 'AoE', 'ts_sec',
                    'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90',
                    'tp_50', 'tp_80', 'tp_max'
                ], 'ORSIS3302DecoderForEnergy/dsp')
            elif run >= 117 and cal == False:
                df = lh5.load_dfs(file_list, [
                    f'{etype}', 'bl', 'bl_sig', 'bl_slope', 'lf_max', 'A_10',
                    'AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80',
                    'tp_max'
                ], 'ORSIS3302DecoderForEnergy/dsp')

        else:
            print(
                'dont know what to do here! need to specify if working with calibrated/uncalibrated data, or dsp/hit files'
            )

        if bl_cut == True:
            # use baseline cut
            print('Using baseline cut')
            if run < 117:
                bl_cut_lo, bl_cut_hi = 8500, 10000
            if run >= 117:
                bl_cut_lo, bl_cut_hi = 9700, 9760

            df_cut = df.query(f'bl > {bl_cut_lo} and bl < {bl_cut_hi}').copy()

        else:
            print('Not using baseline cut')
            df_cut = df

        # select energy type and energy range
        if cal == False:
            elo, ehi, epb = 0, 10000, 10  #entire enerty range trapEftp
            e_unit = ' (uncal)'
        elif cal == True:
            elo, ehi, epb = 0, 6000, 5
            etype = etype_cal
            e_unit = ' (keV)'

        # create energy histograms
        ene_hist, bins = np.histogram(df_cut[etype],
                                      bins=nbx,
                                      range=([elo, ehi]))
        ene_hist_norm = np.divide(ene_hist, (rt_min))

        hist_arr.append(ene_hist_norm)

    return (hist_arr, bins)
Beispiel #6
0
def plot_wfs(run, cycle, etype, user=False, hit=True, cal=True):
    """
    show waveforms in different enery regions.
    use the dsp or hit file to select events
    """
    dg = DataGroup('$CAGE_SW/processing/cage.json', load=True)
    str_query = f'cycle=={cycle} and skip==False'
    dg.fileDB.query(str_query, inplace=True)

    #get runtime, startime, runtype
    runtype_list = np.array(dg.fileDB['runtype'])
    runtype = runtype_list[0]
    rt_min = dg.fileDB['runtime'].sum()
    u_start = dg.fileDB.iloc[0]['startTime']
    t_start = pd.to_datetime(u_start, unit='s')


    # get data and load into df
    lh5_dir = dg.lh5_user_dir if user else dg.lh5_dir
    if cal==True:
        etype_cal = etype + '_cal'

    if hit==True:
        print('Using hit files')
        file_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB['hit_file']
        if run<=117 and cal==True:
            df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')
        elif run>117 and cal==True:
            df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')

        elif run<=117 and cal==False:
            df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')
        elif run>117 and cal==False:
            df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/hit')

    elif hit==False:
        print('Using dsp files')
        file_list = lh5_dir + dg.fileDB['dsp_path'] + '/' + dg.fileDB['dsp_file']
        if run<=117 and cal==True:
            df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')
        elif run>117 and cal==True:
            df = lh5.load_dfs(file_list, [f'{etype}', f'{etype_cal}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')

        elif run<=117 and cal==False:
            df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig','A_10','AoE', 'ts_sec', 'dcr_raw', 'dcr_ftp', 'dcr_max', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')
        elif run>117 and cal==False:
            df = lh5.load_dfs(file_list, [f'{etype}', 'bl','bl_sig', 'bl_slope', 'lf_max', 'A_10','AoE', 'dcr', 'tp_0', 'tp_10', 'tp_90', 'tp_50', 'tp_80', 'tp_max'], 'ORSIS3302DecoderForEnergy/dsp')

    else:
        print('dont know what to do here! need to specify if working with calibrated/uncalibrated data, or dsp/hit files')


    waveforms = []

    n_eranges = 10 #number of steps between lower and higher energy limits
    nwfs= 50 #number of waveforms to average for superpulse
    emin = 500 #lower energy limit
    emax = 15000 #higher energy limit

    eranges = np.linspace(emin, emax, n_eranges) #set up energy slices
    for e in eranges:
        #get events within 1% of energy
        elo = e-(0.01*e)
        ehi = e+(0.01*e)
        idx = df[etype].loc[(df[etype] >= elo) & (df[etype] <= ehi)].index[:nwfs]
        raw_store = lh5.Store()
        tb_name = 'ORSIS3302DecoderForEnergy/raw'
        lh5_dir = dg.lh5_dir
        raw_list = lh5_dir + dg.fileDB['raw_path'] + '/' + dg.fileDB['raw_file']
        f_raw = raw_list.values[0] # fixme, only works for one file rn
        data_raw, nrows = raw_store.read_object(tb_name, f_raw, start_row=0, n_rows=idx[-1]+1)

        wfs_all = (data_raw['waveform']['values']).nda
        wfs = wfs_all[idx.values, :]
        # baseline subtraction
        bl_means = wfs[:,:800].mean(axis=1)
        wf_blsub = (wfs.transpose() - bl_means).transpose()
        ts = np.arange(0, wf_blsub.shape[1]-1, 1)
        super_wf = np.mean(wf_blsub, axis=0)
        wf_max = np.amax(super_wf)
        superpulse = np.divide(super_wf, wf_max)
        waveforms.append(superpulse)

    fig, ax = plt.subplots(figsize=(9,8))
    ax = plt.axes()

    # set up colorbar to plot waveforms of different energies different colors
    colors = plt.cm.viridis(np.linspace(0, 1, n_eranges))
    c = np.arange(0, n_eranges)
    norm = mpl.colors.Normalize(vmin=c.min(), vmax=c.max())
    cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.jet)
    cmap.set_array([])

    for n in range(n_eranges):
        plt.plot(ts, waveforms[n][:len(waveforms[n])-1], c=cmap.to_rgba(n))

    cb = fig.colorbar(cmap, ticks=list(eranges))
    cb.set_label("Energy", ha = 'right', va='center', rotation=270, fontsize=20)
    cb.ax.tick_params(labelsize=18)

#     plt.xlim(3800, 8000)
#     plt.ylim(0.4, 1.01)
    plt.setp(ax.get_xticklabels(), fontsize=16)
    plt.setp(ax.get_yticklabels(), fontsize=16)
    plt.title(f'Waveforms, {emin}-{emax} trapEftp, {n_eranges} steps', fontsize=20)
    plt.xlabel('clock cycles', fontsize=20)
    plt.savefig(f'./plots/angleScan/waveforms/wfs_fallingEdge_cycle{cycle}.png', dpi=300)
Beispiel #7
0
def pole_zero(dg):
    """
    NOTE: I think this result might be wrong, for the CAGE amp it should be
    around 250 usec.  Need to check.
    """
    # load hit data
    lh5_dir = os.path.expandvars(dg.config['lh5_dir'])
    hit_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB['hit_file']
    df_hit = lh5.load_dfs(hit_list, ['trapEmax'],
                          'ORSIS3302DecoderForEnergy/hit')
    df_hit.reset_index(inplace=True)
    rt_min = dg.fileDB['runtime'].sum()
    # print(f'runtime: {rt_min:.2f} min')

    # load waveforms
    etype = 'trapEmax_cal'
    nwfs = 20
    elo, ehi = 1455, 1465

    # select waveforms
    idx = df_hit[etype].loc[(df_hit[etype] >= elo)
                            & (df_hit[etype] <= ehi)].index[:nwfs]
    raw_store = lh5.Store()
    tb_name = 'ORSIS3302DecoderForEnergy/raw'
    raw_list = lh5_dir + dg.fileDB['raw_path'] + '/' + dg.fileDB['raw_file']
    f_raw = raw_list.values[0]  # fixme, only works for one file rn
    data_raw = raw_store.read_object(tb_name,
                                     f_raw,
                                     start_row=0,
                                     n_rows=idx[-1] + 1)

    wfs_all = data_raw['waveform']['values'].nda
    wfs = wfs_all[idx.values, :]
    df_wfs = pd.DataFrame(wfs)
    # print(df_wfs)

    # simple test function to compute pole-zero constant for a few wfs.
    # the final one should become a dsp processor
    clock = 1e8  # 100 MHz
    istart = 5000
    iwinlo, iwinhi, iwid = 500, 2500, 20  # two-point slope
    # ts = np.arange(istart, df_wfs.shape[1]-1, 1) / 1e3 # usec
    ts = np.arange(0, df_wfs.shape[1] - 1 - istart, 1) / 1e3  # usec

    def get_rc(row):
        # two-point method
        wf = row[istart:-1].values
        wflog = np.log(wf)
        win1 = np.mean(np.log(row[istart + iwinlo:istart + iwinlo + iwid]))
        win2 = np.mean(np.log(row[istart + iwinhi:istart + iwinhi + iwid]))
        slope = (win2 - win1) / (ts[iwinhi] - ts[iwinlo])
        tau = 1 / slope

        # # diagnostic plot: check against expo method
        # guess_tau = 60
        # a = wf.max()
        # expdec = lambda x : a * np.exp(-x / guess_tau)
        # logdec = lambda x : np.log(a * np.exp(-x / guess_tau))
        # slopeway = lambda x: wflog[0] + x / tau
        # plt.plot(ts, wflog, '-r', lw=1)
        # plt.plot(ts, logdec(ts), '-b', lw=1)
        # plt.plot(ts, slopeway(ts), '-k', lw=1)
        # plt.show()
        # exit()

        return tau

        # return tau

    res = df_wfs.apply(get_rc, axis=1)

    tau_avg, tau_std = res.mean(), res.std()
    print(f'average RC decay constant: {tau_avg:.2f} pm {tau_std:.2f}')
Beispiel #8
0
def data_cleaning(dg):
    """
    using parameters in the hit file, plot 1d and 2d spectra to find cut values.

    columns in file:
        ['trapE', 'bl', 'bl_sig', 'A_10', 'AoE', 'packet_id', 'ievt', 'energy',
        'energy_first', 'timestamp', 'crate', 'card', 'channel', 'energy_cal',
        'trapE_cal']

    note, 'energy_first' from first value of energy gate.
    """
    i_plot = 0  # run all plots after this number

    # get file list and load hit data
    lh5_dir = dg.lh5_user_dir if user else dg.lh5_dir
    lh5_dir = os.path.expandvars(dg.config['lh5_dir'])
    hit_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB['hit_file']
    df_hit = lh5.load_dfs(hit_list, ['trapEmax'],
                          'ORSIS3302DecoderForEnergy/hit')
    # print(df_hit)
    print(df_hit.columns)

    # get info about df -- 'describe' is very convenient
    dsc = df_hit[['bl', 'bl_sig', 'A_10', 'ts_sec']].describe()
    # print(dsc)
    # exit()

    if i_plot <= 0:
        # bl vs energy

        elo, ehi, epb = 0, 50, 1
        blo, bhi, bpb = 0, 10000, 100
        nbx = int((ehi - elo) / epb)
        nby = int((bhi - blo) / bpb)

        h = plt.hist2d(df_hit['trapEmax_cal'],
                       df_hit['bl'],
                       bins=[nbx, nby],
                       range=[[elo, ehi], [blo, bhi]],
                       cmap='jet')

        cb = plt.colorbar(h[3], ax=plt.gca())
        plt.xlabel('trapEmax_cal', ha='right', x=1)
        plt.ylabel('bl', ha='right', y=1)
        plt.tight_layout()
        # plt.show()
        plt.savefig('./plots/oppi_bl_vs_e.png', dpi=300)
        cb.remove()
        plt.cla()

        # make a formal baseline cut from 1d histogram
        hE, bins, vE = pgh.get_hist(df_hit['bl'], range=(blo, bhi), dx=bpb)
        xE = bins[1:]
        plt.semilogy(xE, hE, c='b', ds='steps')

        bl_cut_lo, bl_cut_hi = 8000, 9500
        plt.axvline(bl_cut_lo, c='r', lw=1)
        plt.axvline(bl_cut_hi, c='r', lw=1)

        plt.xlabel('bl', ha='right', x=1)
        plt.ylabel('counts', ha='right', y=1)
        # plt.show()
        plt.savefig('./plots/oppi_bl_cut.png')
        plt.cla()

    if i_plot <= 1:
        # A_10/trapEmax_cal vs trapEmax_cal (A/E vs E)

        # use baseline cut
        df_cut = df_hit.query('bl > 8000 and bl < 9500').copy()

        # add new A/E column
        df_cut['aoe'] = df_cut['A_10'] / df_cut['trapEmax_cal']

        # alo, ahi, apb = -1300, 350, 1
        # elo, ehi, epb = 0, 250, 1
        alo, ahi, apb = 0, 0.4, 0.005
        # elo, ehi, epb = 0, 3000, 10
        elo, ehi, epb = 0, 6000, 10

        nbx = int((ehi - elo) / epb)
        nby = int((ahi - alo) / apb)

        h = plt.hist2d(df_cut['trapEmax_cal'],
                       df_cut['aoe'],
                       bins=[nbx, nby],
                       range=[[elo, ehi], [alo, ahi]],
                       cmap='jet',
                       norm=LogNorm())

        plt.xlabel('trapEmax_cal', ha='right', x=1)
        plt.ylabel('A/E', ha='right', y=1)
        plt.tight_layout()
        # plt.show()
        plt.savefig('./plots/oppi_aoe_vs_e.png', dpi=300)
        plt.cla()

    if i_plot <= 2:
        # show effect of baseline cut on low-energy spectrum

        df_cut = df_hit.query('bl > 8000 and bl < 9500')

        etype = 'trapEmax_cal'
        elo, ehi, epb = 0, 250, 0.5

        # no cuts
        h1, x1, v1 = pgh.get_hist(df_hit[etype], range=(elo, ehi), dx=epb)
        x1 = x1[1:]
        plt.plot(x1, h1, c='k', lw=1, ds='steps', label='raw')

        # baseline cut
        h2, x2, v2 = pgh.get_hist(df_cut[etype], range=(elo, ehi), dx=epb)
        plt.plot(x1, h2, c='b', lw=1, ds='steps', label='bl cut')

        plt.xlabel(etype, ha='right', x=1)
        plt.ylabel('counts', ha='right', y=1)
        plt.legend()
        # plt.show()
        plt.savefig('./plots/oppi_lowe_cut.png')
        plt.cla()

    if i_plot <= 3:
        # show DCR vs E
        etype = 'trapEmax_cal'
        elo, ehi, epb = 0, 6000, 10
        dlo, dhi, dpb = -1000, 1000, 10

        nbx = int((ehi - elo) / epb)
        nby = int((dhi - dlo) / dpb)

        h = plt.hist2d(df_cut['trapEmax_cal'],
                       df_cut['dcr'],
                       bins=[nbx, nby],
                       range=[[elo, ehi], [dlo, dhi]],
                       cmap='jet',
                       norm=LogNorm())

        plt.xlabel('trapEmax_cal', ha='right', x=1)
        plt.ylabel('DCR', ha='right', y=1)
        plt.tight_layout()
        # plt.show()
        plt.savefig('./plots/oppi_dcr_vs_e.png', dpi=300)
        plt.cla()
Beispiel #9
0
def show_wfs(dg):
    """
    show waveforms in different enery regions.
    use the hit file to select events
    """
    # get file list and load hit data
    lh5_dir = dg.lh5_user_dir  #if user else dg.lh5_dir
    hit_list = lh5_dir + dg.fileDB['hit_path'] + '/' + dg.fileDB['hit_file']
    df_hit = lh5.load_dfs(
        hit_list,
        ['trapEmax', 'trapEmax_cal', 'bl', 'AoE', 'dcr_raw', 'tp_0', 'tp_50'],
        'ORSIS3302DecoderForEnergy/hit')
    # print(df_hit)
    # print(df_hit.columns)

    # settings
    # etype = 'trapEmax'
    etype = 'trapEmax_cal'
    nwfs = 20

    #creat new DCR
    const = 0.0555
    df_hit['dcr_linoff'] = df_hit['dcr_raw'] + const * df_hit['trapEmax']

    #create 0-50
    df_hit['tp0_50'] = df_hit['tp_50'] - df_hit['tp_0']

    # elo, ehi, epb = 0, 100, 0.2 # low-e region
    # elo, ehi, epb = 0, 20, 0.2 # noise region
    elo, ehi, epb = 351, 355, 1  # 351 peak, cal
    # elo, ehi, epb = 1452, 1468, 1 # good physics events
    #     elo, ehi, epb = 7100, 7200, 1 # good physics events, uncal
    # elo, ehi, epb = 6175, 6250, 1 # overflow peak
    # elo, ehi, epb = 5000, 5200, 0.2 # lower overflow peak

    # # diagnostic plot
    # hE, xE, vE = pgh.get_hist(df_hit[etype], range=(elo, ehi), dx=epb)
    # plt.plot(xE[1:], hE, c='b', ds='steps')
    # plt.show()
    # exit()

    # select bulk waveforms
    idx = df_hit[etype].loc[(df_hit[etype] >= elo)
                            & (df_hit[etype] <= ehi)].index[:nwfs]

    raw_store = lh5.Store()
    tb_name = 'ORSIS3302DecoderForEnergy/raw'
    lh5_dir = dg.lh5_dir
    raw_list = lh5_dir + dg.fileDB['raw_path'] + '/' + dg.fileDB['raw_file']
    f_raw = raw_list.values[0]  # fixme, only works for one file rn
    data_raw, nrows = raw_store.read_object(tb_name,
                                            f_raw,
                                            start_row=0,
                                            n_rows=idx[-1] + 1)

    bulk_wfs_all = (data_raw['waveform']['values']).nda
    bulk_wfs = bulk_wfs_all[idx.values, :]
    ts = np.arange(0, bulk_wfs.shape[1] - 1, 1)

    # select alpha waveforms
    dlo = 25
    dhi = 200
    tlo = 100
    thi = 400
    blmin = 8500
    blmax = 10000
    alpha_idx = df_hit[etype].loc[(df_hit['dcr_linoff'] > dlo)
                                  & (df_hit['dcr_linoff'] < dhi)
                                  & (df_hit['tp0_50'] > tlo) &
                                  (df_hit['tp0_50'] < thi) &
                                  (df_hit['bl'] > blmin) &
                                  (df_hit['bl'] < blmax)
                                  & (df_hit[etype] < 12000)].index[:nwfs]

    raw_store = lh5.Store()
    tb_name = 'ORSIS3302DecoderForEnergy/raw'
    raw_list = lh5_dir + dg.fileDB['raw_path'] + '/' + dg.fileDB['raw_file']
    f_raw = raw_list.values[0]  # fixme, only works for one file rn
    data_raw, nrows = raw_store.read_object(tb_name,
                                            f_raw,
                                            start_row=0,
                                            n_rows=alpha_idx[-1] + 1)

    alpha_wfs_all = data_raw['waveform']['values'].nda
    alpha_wfs = alpha_wfs_all[alpha_idx.values, :]
    ats = np.arange(0, alpha_wfs.shape[1] - 1, 1)

    # plot wfs
    for iwf in range(bulk_wfs.shape[0]):
        plt.plot(ts,
                 bulk_wfs[iwf, :len(bulk_wfs[iwf]) - 1],
                 lw=1,
                 color='blue',
                 label='Bulk')

    plt.xlabel('time (clock ticks)', ha='right', x=1)
    plt.ylabel('ADC', ha='right', y=1)

    #     # plot alpha wfs
    #     for aiwf in range(alpha_wfs.shape[0]):
    #         plt.plot(ats, alpha_wfs[aiwf,:len(alpha_wfs[aiwf])-1], lw=1, color = 'red', label = 'Alpha')

    #     plt.title('Alpha versus bulk events')
    plt.title('right 351 Wfs run 82')
    plt.xlabel('time (clock ticks)', ha='right', x=1)
    plt.ylabel('ADC', ha='right', y=1)
    plt.xlim(3500, 4500)
    plt.ylim(9100, 10300)
    # plt.legend(loc='upper left')
    # plt.show()
    plt.savefig('./plots/normScan/zoom_350_right_waveforms_run82.png', dpi=300)