Esempio n. 1
0
 def He3_Energy_action(self):
     parameters = get_He3_filter_parameters(self)
     df_red = filter_He3(self.He3_df, parameters)
     number_bins = int(self.dE_bins.text())
     plot_energy = True
     fig = plt.figure()
     plt.subplot(1, 2, 1)
     hist_full, bins_full = energy_plot_He3(df_red, number_bins,
                                            plot_energy, 'Full Data')
     hist_pileup, bins_pileup = energy_plot_He3(df_red[df_red.PileUp == 1],
                                                number_bins, plot_energy,
                                                'Pile Up Events')
     plt.legend()
     plt.subplot(1, 2, 2)
     plt.grid(True, which='major', linestyle='--', zorder=0)
     plt.grid(True, which='minor', linestyle='--', zorder=0)
     plt.xlabel('Energy (meV)')
     plt.ylabel('Fraction of Counts (PileUp/Full)')
     plt.title('Investigation of Pileup')
     plt.plot(bins_full,
              hist_pileup / hist_full,
              color='black',
              zorder=5,
              label='PileUpEvents/AllEvents')
     plt.xscale('log')
     plt.legend()
     fig.show()
Esempio n. 2
0
 def He3_PHS_action(self):
     number_bins = int(self.phsBins.text())
     parameters = get_He3_filter_parameters(self)
     df_red = filter_He3(self.He3_df, parameters)
     fig = plt.figure()
     He3_PHS_plot(df_red, number_bins)
     fig.show()
Esempio n. 3
0
 def He3_pileup_action(self):
     # Filter data
     parameters_He3 = get_He3_filter_parameters(self)
     He3_red = filter_He3(self.He3_df, parameters_He3)
     # Plot data
     fig = plt.figure()
     fig.set_figheight(15)
     fig.set_figwidth(15)
     he3_pileup_plot(He3_red)
     plt.tight_layout()
     fig.show()
Esempio n. 4
0
 def He3_ToF_action(self):
     number_bins = int(self.tofBins.text())
     parameters = get_He3_filter_parameters(self)
     df_red = filter_He3(self.He3_df, parameters)
     fig = plt.figure()
     hist, bins = He3_ToF_plot(df_red, number_bins, range=[0, 71429])
     # Save histogram in ASCII-format
     dir_name = os.path.dirname(__file__)
     output_path = os.path.join(
         dir_name, '../output/ToF_%s.txt' % self.He3_data_sets[5:-5])
     np.savetxt(output_path,
                np.transpose(np.array([bins, hist])),
                delimiter=",",
                header='ToF (µs), Counts')
     plt.legend()
     fig.show()
Esempio n. 5
0
 def ToF_MG_vs_ToF_He3_action(self):
     # Get filter parameters for MG and He-3
     parameters_MG = get_filter_parameters(self)
     parameters_He3 = get_He3_filter_parameters(self)
     # Filter data
     MG_red = filter_clusters(self.ce, parameters_MG)
     He3_red = filter_He3(self.He3_df, parameters_He3)
     # Declare paremeters
     number_bins = int(self.tofBins.text())
     MG_label, He3_label = self.data_sets, self.He3_data_sets
     useMaxNorm = True
     # Plot data
     fig = plt.figure()
     He3_ToF_plot(He3_red, number_bins, He3_label)
     ToF_histogram(MG_red, number_bins, MG_label)
     plt.legend()
     fig.show()
Esempio n. 6
0
 def Wavelength_overlay_action(self):
     paths = QFileDialog.getOpenFileNames(self, "", "../data")[0]
     number_bins = int(self.dE_bins.text())
     origin_voxel = [
         int(self.bus_origin.text()),
         int(self.gCh_origin.text()),
         int(self.wCh_origin.text())
     ]
     MG_filter_parameters = get_filter_parameters(self)
     He3_filter_parameters = get_He3_filter_parameters(self)
     fig = plt.figure()
     # Multi-Grid
     for i, path in enumerate(paths):
         label = path.rsplit('/', 1)[-1]
         ce = pd.read_hdf(path, 'ce')
         ce_filtered = filter_clusters(ce, MG_filter_parameters)
         duration = get_duration(ce)
         norm = 1 / duration
         energy = calculate_energy(ce_filtered, origin_voxel)
         plt.hist(meV_to_A(energy),
                  bins=number_bins,
                  range=[0, 10],
                  zorder=5,
                  histtype='step',
                  label=label,
                  weights=norm * np.ones(len(energy)))
         print('Progress: %d/%d' % (i + 1, len(paths)))
     # He-3
     He3_df_red = filter_He3(self.He3_df, He3_filter_parameters)
     energy_He3 = calculate_He3_energy(He3_df_red)
     norm_He3 = 1 / 54304
     plt.hist(meV_to_A(energy_He3),
              bins=number_bins,
              range=[0, 10],
              zorder=5,
              histtype='step',
              label='2019_09_HZB_He3InBeam54304s_overnight.lst',
              weights=norm * np.ones(len(energy_He3)))
     plt.grid(True, which='major', linestyle='--', zorder=0)
     plt.grid(True, which='minor', linestyle='--', zorder=0)
     plt.ylabel('Counts (Normalized to duration)')
     plt.xlabel('Wavelength [Å]')
     plt.title('Wavelength Distribution')
     plt.legend(loc=1)
     fig.show()
Esempio n. 7
0
def prepare_data(origin_voxel, MG_filter_parameters, He3_filter_parameters):
    """
    Data is returned in following order:

    1. Multi-Grid Coated Radial Blades, beam
    2. Multi-Grid Non-Coated Radial Blades, beam
    3. Multi-Grid Coated Radial Blades, background
    4. Multi-Grid Non-Coated Radial Blades, background
    5. He-3, beam
    6. He-3, background

    Within each data-list, data is returned in following order

   (1. Energies - Beam Removed) <- Only for MG
    2. Energies - Full
    3. Histogram
    4. Bin centers
   (5. Peaks)
   (6. Widths)
   (7. PileUp) <- Only for He-3
   (8. ADCs) <- Only for He-3

    """
    # Declare parameters, such as distance offset and He3 duration
    dirname = os.path.dirname(__file__)
    number_bins = 5000
    start = 0.8  # [meV]
    end = 80  # [meV]
    MG_distance_offsets = [1.5e-3, 0, 1.5e-3, 0]
    He3_distance_offset = 3e-3
    He3_durations = [54304, 58094]
    # Declare heights used as threshold in peak finding algorithm
    heights_MG_coated = [20000, 10000]
    heights_MG_non_coated = [8000, 1000] # CHANGE TO [12000, 1000] when normal scattering analysis
    heights_He3 = [20000, 1000]
    heights_vec_MG = [heights_MG_coated, heights_MG_non_coated]
    # Declare file names
    MG_COATED = 'mvmelst_165_191002_111641_Det2_overnight3.h5'
    MG_COATED_BACKGROUND = 'mvmelst_169_191003_075039_Det2_He3InBeam_overnight4.h5'
    MG_NON_COATED = 'mvmelst_135_190930_141618_Det1_overnight2_30x80_14x60.h5'
    MG_NON_COATED_BACKGROUND = 'mvmelst_141_191001_120405_He3InBeam_overnight3.h5'
    HE_3 = '2019_09_HZB_He3InBeam54304s_overnight.h5'
    HE_3_BACKGROUND = '2019_09_HZB_out_of_beam_overnight_58094s.h5'
    MG_file_names = [MG_COATED, MG_NON_COATED, MG_COATED_BACKGROUND, MG_NON_COATED_BACKGROUND]
    He3_file_names = [HE_3, HE_3_BACKGROUND]
    # Declare list to store all data
    full_data = []
    # Store Multi-Grid data
    print('Multi-Grid...')
    for i, file_name in enumerate(MG_file_names):
        path = os.path.join(dirname, '../../../data/Lineshape/%s' % file_name)
        # Calculate energies and histograms
        df = pd.read_hdf(path, 'ce')
        df_red = filter_clusters(df, MG_filter_parameters)
        duration = get_duration(df)
        energies = calculate_energy(df_red, origin_voxel, MG_distance_offsets[i])
        hist, bins = get_hist(energies, number_bins, start, end)
        # Calculate energy for when row which neutron beam hits is removed
        energies_no_beam = None
        if i == 0:
            df_no_beam = df_red[~((((df_red.Bus * 4) + df_red.wCh//20) == 6) &
                                    (df_red.gCh >= 86) &
                                    (df_red.gCh <= 89))]
            energies_no_beam = calculate_energy(df_no_beam, origin_voxel, MG_distance_offsets[i])
        elif i == 1:
            df_no_beam = df_red[~((((df_red.Bus * 4) + df_red.wCh//20) == 6) &
                                    (df_red.gCh >= 87) &
                                    (df_red.gCh <= 89))]
            energies_no_beam = calculate_energy(df_no_beam, origin_voxel, MG_distance_offsets[i])
        # Store data
        data = [energies_no_beam, energies, hist, bins]
        if i < 2:
            # If it is a beam measurement, extract peaks
            peaks, __ = get_peaks(hist, heights_vec_MG[i], number_bins)
            widths, *_ = peak_widths(hist, peaks)
            data.extend([peaks, widths])
        full_data.append(data)
    # Store He-3 data
    print('He-3...')
    for i, (file_name, duration) in enumerate(zip(He3_file_names, He3_durations)):
        path = os.path.join(dirname, '../../../data/Lineshape/%s' % file_name)
        df = pd.read_hdf(path, 'df')
        df_red = filter_He3(df, He3_filter_parameters)
        energies = calculate_He3_energy(df_red, He3_distance_offset)
        hist, bins = get_hist(energies, number_bins, start, end)
        data = [None, energies, hist, bins]
        if i < 1:
            # If it is a beam measurement, extract peaks and pile up info
            peaks, __ = get_peaks(hist, heights_He3, number_bins)
            widths, *_ = peak_widths(hist, peaks)
            data.extend([peaks, widths, df_red.PileUp, df_red.ADC])
        full_data.append(data)
    return full_data
def plot_efficiency(He3_energies, MG_energies,
                    He3_areas, MG_areas,
                    He3_err, MG_err,
                    monitor_norm_He3, monitor_norm_MG,
                    window):
    """
    Calculates the efficiency of the Multi-Grid detector at energy 'Ei'. Does
    through analysis in energy transfer spectra in three steps:

    1. Calculate number of counts in elastic peak, removing the background
    2. Get normalization on solid angle and, in the case of He-3, efficiency
    3. Normalize peak data and take fraction between Multi-Grid and He-3

    Args:
        MG_dE_values (numpy array): Energy transfer values from Multi-Grid
        He3_dE_values (numpy array): Energy transfer values from He-3 tubes
        Ei (float): Incident energy in meV
        parameters (dict): Dictionary containing the parameters on how the data
                           is reduced. Here we are only interested in the
                           filters which affects the total surface area.

    Returns:
        MG_efficiency (float): Efficiency of the Multi-Grid at energy Ei
    """

    fig = plt.figure()
    fig.set_figheight(5)
    fig.set_figwidth(15)
    # Load calculated efficiencies, as a function of lambda
    dirname = os.path.dirname(__file__)
    He3_efficiency_path = os.path.join(dirname, '../../../../tables/He3_efficiency.txt')
    MG_efficiency_path = os.path.join(dirname, '../../../../tables/MG_efficiency.txt')
    He3_efficiency = np.loadtxt(He3_efficiency_path, delimiter=",", unpack=True)
    MG_efficiency_calc = np.loadtxt(MG_efficiency_path, delimiter=",", unpack=True)[[0, 2]]
    # Remove elements in MG data which are not recorded in He-3
    MG_energies = np.delete(MG_energies, [0, 2, len(MG_energies)-5])
    MG_areas = np.delete(MG_areas, [0, 2, len(MG_areas)-5])
    MG_err = np.delete(MG_err, [0, 2, len(MG_err)-5])
    # Iterate through energies to find matching efficiency from calculation to our measured data points
    He3_efficiency_datapoints = []
    for energy in He3_energies:
        # Save He3 efficiencies for data points
        idx = find_nearest(A_to_meV(He3_efficiency[0]), energy)
        He3_efficiency_datapoints.append(He3_efficiency[1][idx])
    He3_efficiency_datapoints = np.array(He3_efficiency_datapoints)
    # Rescale our curve to fit calibration
    idx = find_nearest(He3_efficiency[0], 2.5)
    calculated_efficiency_at_2_5_A = He3_efficiency[1][idx]
    He3_calculation_norm_upper = 0.964/calculated_efficiency_at_2_5_A
    He3_calculation_norm_average = 0.957/calculated_efficiency_at_2_5_A
    He3_calculation_norm_lower = 0.950/calculated_efficiency_at_2_5_A
    # Calculate average, as well as upper and lower bound for uncertainity estimation
    He3_efficiency_datapoints_upper = He3_efficiency_datapoints * He3_calculation_norm_upper
    He3_efficiency_datapoints_average = He3_efficiency_datapoints * He3_calculation_norm_average
    He3_efficiency_datapoints_lower = He3_efficiency_datapoints * He3_calculation_norm_lower
    # Calculated measured efficiency
    MG_efficiency = (MG_areas*monitor_norm_MG)/(He3_areas*(1/He3_efficiency_datapoints_average)*monitor_norm_He3)
    MG_efficiency_stat_unc = np.sqrt((MG_err/MG_areas) ** 2 + (He3_err/He3_areas) ** 2) * MG_efficiency
    # Calculate uncertainities
    MG_efficiency_upper = (MG_areas*monitor_norm_MG)/(He3_areas*(1/He3_efficiency_datapoints_upper)*monitor_norm_He3)
    MG_efficiency_lower = (MG_areas*monitor_norm_MG)/(He3_areas*(1/He3_efficiency_datapoints_lower)*monitor_norm_He3)
    upper_errors = MG_efficiency_upper - MG_efficiency + MG_efficiency_stat_unc
    lower_errors = MG_efficiency - MG_efficiency_lower + MG_efficiency_stat_unc
    full_errors = np.array([lower_errors, upper_errors])
    # Plot areas
    plt.subplot(1, 3, 1)
    plt.errorbar(He3_energies,
                 He3_areas*monitor_norm_He3,
                 He3_err*monitor_norm_He3,
                 fmt='.-', capsize=5,  color='red', label='He-3', zorder=5)
    plt.errorbar(MG_energies,
                 MG_areas*monitor_norm_MG,
                 MG_err*monitor_norm_MG,
                 fmt='.-', capsize=5,  color='blue', label='Multi-Grid', zorder=5)
    plt.xlabel('Energy (meV)')
    plt.ylabel('Peak area (Counts normalized by beam monitor counts)')
    plt.xlim(2, 120)
    plt.grid(True, which='major', linestyle='--', zorder=0)
    plt.grid(True, which='minor', linestyle='--', zorder=0)
    plt.title('Comparison MG and He-3')
    plt.legend()
    plt.xscale('log')
    plt.subplot(1, 3, 2)
    plt.xlabel('Energy (meV)')
    plt.ylabel('Efficiency')
    plt.xlim(2, 120)
    plt.errorbar(MG_energies, MG_efficiency, full_errors, fmt='.-',
                capsize=5, color='blue', label='Measured MG efficiency', zorder=5)
    plt.plot(A_to_meV(MG_efficiency_calc[0]), MG_efficiency_calc[1], color='black',
             label='MG (90° incident angle)', zorder=5)
    #plt.plot(He3_energies, He3_efficiency_datapoints, color='red',
    #         marker='o', linestyle='', label='He-3, Calculated', zorder=5)
    plt.grid(True, which='major', linestyle='--', zorder=0)
    plt.grid(True, which='minor', linestyle='--', zorder=0)
    plt.title('Efficiency measurement')
    plt.xscale('log')
    plt.legend()
    plt.subplot(1, 3, 3)
    plt.xlabel('Wavelength (Å)')
    plt.ylabel('Efficiency')
    plt.errorbar(meV_to_A(MG_energies), MG_efficiency, full_errors, fmt='.-',
                 capsize=5, color='blue', label='Measured MG efficiency', zorder=5)
    plt.grid(True, which='major', linestyle='--', zorder=0)
    plt.grid(True, which='minor', linestyle='--', zorder=0)
    plt.plot(MG_efficiency_calc[0], MG_efficiency_calc[1], color='black',
             label='MG (90° incident angle)', zorder=5)
    #plt.plot(meV_to_A(He3_energies), He3_efficiency_datapoints, color='red',
    #         marker='o', linestyle='', label='He-3, Calculated', zorder=5)
    plt.title('Efficiency measurement')
    plt.legend()
    plt.tight_layout()
    fig.show()


    # Plot only efficiency vs lambda_sweep

    # Get pile-up fraction
    parameters = get_He3_filter_parameters(window)
    df_red = filter_He3(window.He3_df, parameters)
    number_bins = int(window.dE_bins.text())
    plot_energy = False
    hist_full, bins_full = energy_plot_He3(df_red, number_bins, plot_energy, 'All events')
    hist_pileup, bins_pileup = energy_plot_He3(df_red[df_red.PileUp == 1], number_bins, plot_energy, 'Pile-up Events')
    pileup_fraction = hist_pileup/hist_full

    # Plot together with efficiency
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    ax1.plot(MG_efficiency_calc[0], MG_efficiency_calc[1], color='black',
             label='Multi-Grid detector: calculated', zorder=5)
    ax1.errorbar(meV_to_A(MG_energies), MG_efficiency, full_errors, fmt='.-',
                 capsize=5, color='blue', label='Multi-Grid detector: measured', zorder=5)
    ax1.plot(bins_full, pileup_fraction, color='green', zorder=5, label='Helium-3 tube: pile-up fraction')
    #ymin = 0
    #ymax = max(MG_efficiency)
    #y_ticks = np.linspace(ymin, ymax, 5)
    #ax1.set_ylim(ymin, ymax)
    ax1.set_xlim(0, 6.25)
    other_y_axis_lim = ax1.get_ylim()
    ax2.set_ylim(other_y_axis_lim)

    ax2.spines['right'].set_color('green')
    ax2.yaxis.label.set_color('green')
    ax2.tick_params(axis='y', colors='green')

    #ax2.set_ylim(ymin, ymax)
    #ax1.set_yticks(y_ticks)
    #ax2.set_yticks(y_ticks)
    ax1.tick_params('y', color='black')
    ax2.tick_params('y', color='green')
    ax1.set_xlabel('Wavelength (Å)')
    ax1.set_ylabel('Efficiency')
    ax2.set_ylabel('Helium-3 pile-up fraction')
    ax1.grid(True, which='major', linestyle='--', zorder=0)
    ax1.grid(True, which='minor', linestyle='--', zorder=0)
    #ax1.set_title('Figure-of-Merit')
    ax1.legend()
    fig.show()

    # Plot together with saturation
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    ax1.errorbar(meV_to_A(He3_energies),
                 He3_areas*monitor_norm_He3,
                 He3_err*monitor_norm_He3,
                 fmt='.-', capsize=5,  color='red', label='Helium-3 tube', zorder=5)
    ax1.errorbar(meV_to_A(MG_energies),
                 MG_areas*monitor_norm_MG,
                 MG_err*monitor_norm_MG,
                 fmt='.-', capsize=5,  color='blue', label='Multi-Grid detector', zorder=5)
    ax2.plot(bins_full, pileup_fraction, color='green', zorder=5, label='Helium-3 tube: pile-up fraction')
    ax1.plot([], [], color='green', label='Helium-3 tube: pile-up fraction')

    #ymin = 0
    #ymax = max(MG_efficiency)
    #y_ticks = np.linspace(ymin, ymax, 5)
    #ax1.set_ylim(ymin, ymax)
    ax1.set_xlim(0, 6.25)
    #ax1.set_ylim(other_y_axis_lim)
    ax2.set_ylim(other_y_axis_lim)

    ax2.spines['right'].set_color('green')
    ax2.yaxis.label.set_color('green')
    ax2.tick_params(axis='y', colors='green')

    #ax2.set_ylim(ymin, ymax)
    #ax1.set_yticks(y_ticks)
    #ax2.set_yticks(y_ticks)
    ax1.tick_params('y', color='black')
    ax2.tick_params('y', color='green')
    ax1.set_xlabel('Wavelength (Å)')
    ax1.set_ylabel('Peak area (Counts normalized by beam monitor counts)')
    ax2.set_ylabel('Helium-3 pile-up fraction')
    ax1.grid(True, which='major', linestyle='--', zorder=0)
    ax1.grid(True, which='minor', linestyle='--', zorder=0)
    #ax1.set_title('Figure-of-Merit')
    ax1.legend()
    fig.show()
Esempio n. 9
0
 def He3_Ch_action(self):
     fig = plt.figure()
     parameters = get_He3_filter_parameters(self)
     df_red = filter_He3(self.He3_df, parameters)
     He3_Ch_plot(df_red)
     fig.show()