def Coincidences_2D_plot(ce, data_sets, module_order, window):
    def plot_2D_bus(fig, sub_title, ce, vmin, vmax, duration):
        h, *_ = plt.hist2d(ce.wCh,
                           ce.gCh,
                           bins=[80, 40],
                           range=[[-0.5, 79.5], [79.5, 119.5]],
                           vmin=vmin,
                           vmax=vmax,
                           norm=LogNorm(),
                           cmap='jet')
        xlabel = 'Wire [Channel number]'
        ylabel = 'Grid [Channel number]'
        fig = stylize(fig, xlabel, ylabel, title=sub_title, colorbar=True)
        plt.colorbar()
        return fig, h

    # Filter clusters
    ce = filter_ce_clusters(window, ce)
    # Declare parameters (added with condition if empty array)
    if ce.shape[0] != 0:
        duration = window.measurement_time
        vmin = 1
        vmax = ce.shape[0] // 4500 + 5
    else:
        duration = 1
        vmin = 1
        vmax = 1
    title = 'Coincident events (2D)\nData set(s): %s' % data_sets
    height = 12
    width = 14
    # Ensure only coincident events are plotted
    ce = ce[(ce.wCh != -1) & (ce.gCh != -1)]
    # Retrieve text path
    dir_name = os.path.dirname(__file__)
    folder_path = os.path.join(
        dir_name, '../../text/%s/Coincidences_2D/' % window.data_sets)
    mkdir_p(folder_path)
    # Plot data and save matrices in text
    fig = plt.figure()
    for i, bus in enumerate(module_order):
        ce_bus = ce[ce.Bus == bus]
        number_events = ce_bus.shape[0]
        events_per_s = round(number_events / duration, 4)
        sub_title = ('Bus %d\n(%d events, %f events/s)' %
                     (bus, number_events, events_per_s))
        plt.subplot(3, 3, i + 1)
        fig, h = plot_2D_bus(fig, sub_title, ce_bus, vmin, vmax, duration)
        # Save matrix in text
        path = folder_path + 'Bus_' + str(bus) + '.txt'
        if window.createText.isChecked():
            np.savetxt(path, h, fmt="%d", delimiter=",")
    fig = set_figure_properties(fig, title, height, width)
    return fig
def Coincidences_Front_Top_Side_plot(df, data_sets, module_order,
                                     number_of_detectors, window):
    # Ensure we only plot coincident events
    df = df[(df.wCh != -1) & (df.gCh != -1)]
    df = filter_ce_clusters(window, df)
    # Define figure and set figure properties
    fig = plt.figure()
    title = ('Coincident events (Front, Top, Side)' +
             '\nData set(s): %s' % data_sets)
    height = 4
    width = 14
    fig = set_figure_properties(fig, title, height, width)
    if df.shape[0] != 0:
        vmin = 1
        vmax = df.shape[0] // 200 + 5
    else:
        vmin = 1
        vmax = 1
    # Retrieve text path
    dir_name = os.path.dirname(__file__)
    folder_path = os.path.join(
        dir_name, '../../text/%s/Projections_2D/' % window.data_sets)
    mkdir_p(folder_path)
    # Plot front view
    plt.subplot(1, 3, 1)
    __, h_front = plot_2D_Front(module_order, df, fig, number_of_detectors,
                                vmin, vmax)
    path_front = folder_path + 'Front.txt'
    if window.createText.isChecked():
        np.savetxt(path_front, h_front, fmt="%d", delimiter=",")
    # Plot top view
    plt.subplot(1, 3, 2)
    __, h_top = plot_2D_Top(module_order, df, fig, number_of_detectors, vmin,
                            vmax)
    path_top = folder_path + 'Top.txt'
    if window.createText.isChecked():
        np.savetxt(path_top, h_top, fmt="%d", delimiter=",")
    # Plot side view
    plt.subplot(1, 3, 3)
    __, h_side = plot_2D_Side(module_order, df, fig, number_of_detectors, vmin,
                              vmax)
    path_side = folder_path + 'Side.txt'
    if window.createText.isChecked():
        np.savetxt(path_side, h_side, fmt="%d", delimiter=",")
    return fig
def compare_all_shoulders(window):
    def get_statistical_uncertainty(value, a, b, c, d):
        da = np.sqrt(a)
        db = np.sqrt(b)
        dc = np.sqrt(c)
        dd = np.sqrt(d)
        dA = np.sqrt(da**2 + dc**2)
        dB = np.sqrt(db**2 + dd**2)
        return np.sqrt((dA / (a - c))**2 + (dB / (c - d))**2) * value

    # Declare parameters
    number_bins = int(window.dE_bins.text())
    sigma_interval = [3, 8]
    # Declare all input-paths
    dir_name = os.path.dirname(__file__)
    HR_folder = os.path.join(dir_name, '../../Clusters/MG_new/HR/')
    HR_files = np.array(
        [file for file in os.listdir(HR_folder) if file[-3:] == '.h5'])
    HR_files_sorted = sorted(HR_files, key=lambda element: get_energy(element))
    paths = append_folder_and_files(HR_folder, HR_files_sorted)
    # Get output path
    temp_folder = os.path.join(dir_name, '../../Results/Shoulder/temp/')
    mkdir_p(temp_folder)
    # Calculate He3-solid angle
    __, He3_solid_angle = get_He3_tubes_area_and_solid_angle()
    # Declare vectors where results will be stored
    detectors = ['ILL', 'ESS_CLB', 'ESS_PA']
    FoMs = {'ILL': [], 'ESS_CLB': [], 'ESS_PA': []}
    colors = {'ILL': 'blue', 'ESS_CLB': 'red', 'ESS_PA': 'green'}
    energies = []
    errors = {'ILL': [], 'ESS_CLB': [], 'ESS_PA': []}
    count = 0
    # Iterate through all data and calculate FoM
    for run in range(2):
        for detector in detectors:
            for i, path in enumerate(
                    paths[8:20]):  # Only look at 2 meV to 30 meV 8->16
                # Import parameters
                E_i = pd.read_hdf(path, 'E_i')['E_i'].iloc[0]
                calibration = (pd.read_hdf(
                    path, 'calibration')['calibration'].iloc[0])
                df_MG_temp = pd.read_hdf(path, 'coincident_events')
                df_MG = filter_ce_clusters(window, df_MG_temp)
                # Get MG dE-data
                df_MG_detector = detector_filter(df_MG, detector)
                dE_MG = get_MG_dE(df_MG_detector, calibration, E_i)
                # Get He3 dE-data
                dE_He3 = get_raw_He3_dE(calibration, E_i)
                # Produce histograms
                hist_MG, bins = np.histogram(dE_MG,
                                             bins=number_bins,
                                             range=[-E_i / 5, E_i / 5])
                hist_He3, __ = np.histogram(dE_He3,
                                            bins=number_bins,
                                            range=[-E_i / 5, E_i / 5])
                bin_centers = 0.5 * (bins[1:] + bins[:-1])
                # Fit data
                p0 = None
                area_MG, FWHM_MG, __, __, __, popt_MG, l_p_idx_MG, r_p_idx_MG, back_MG, MG_back_indices = Gaussian_fit(
                    bin_centers, hist_MG, p0)
                area_He3, FWHM_He3, __, __, __, popt_He3, l_p_idx_He3, r_p_idx_He3, back_He3, He3_back_indices = Gaussian_fit(
                    bin_centers, hist_He3, p0)
                # Normalize data
                norm_peak_area = area_He3 / area_MG
                normalized_hist_MG = hist_MG * norm_peak_area
                normalized_MG_back = back_MG * norm_peak_area
                # Compare difference at certain interval
                x0_MG = popt_MG[1]
                sigma_MG = abs(popt_MG[2])
                x0_He3 = popt_He3[1]
                sigma_He3 = abs(popt_He3[2])
                left_idx_MG = find_nearest(
                    bin_centers, x0_MG + sigma_interval[0] * sigma_MG)
                right_idx_MG = find_nearest(
                    bin_centers, x0_MG + sigma_interval[1] * sigma_MG)
                indices_MG = np.arange(left_idx_MG, right_idx_MG + 1, 1)
                left_idx_He3 = find_nearest(
                    bin_centers, x0_He3 + sigma_interval[0] * sigma_He3)
                right_idx_He3 = find_nearest(
                    bin_centers, x0_He3 + sigma_interval[1] * sigma_He3)
                indices_He3 = np.arange(left_idx_He3, right_idx_He3 + 1, 1)
                area_MG = sum(normalized_hist_MG[indices_MG]
                              ) - len(indices_MG) * normalized_MG_back
                area_He3 = sum(
                    hist_He3[indices_He3]) - len(indices_He3) * back_He3
                FoM = area_MG / area_He3
                # Find uncertainty
                error = get_statistical_uncertainty(
                    FoM, sum(hist_He3[indices_He3]), sum(hist_MG[indices_MG]),
                    sum(hist_MG[MG_back_indices]),
                    sum(hist_He3[He3_back_indices]))
                if run == 0:
                    FoMs[detector].append(FoM)
                    errors[detector].append(error)
                    if detector == 'ILL':
                        energies.append(E_i)
                else:
                    # Plot data

                    fig = plt.figure()
                    #main_title = 'Peak shape comparison $^3$He-tubes and Multi-Grid'
                    #main_title += '\nInterval: ' + str(sigma_interval) + '$\sigma$'
                    #fig.suptitle(main_title, x=0.5, y=1.02)
                    fig.set_figheight(6)
                    fig.set_figwidth(20)
                    plt.subplot(1, 3, 1)
                    plt.plot(bin_centers,
                             normalized_hist_MG,
                             color='red',
                             label='Multi-Grid',
                             zorder=5)
                    plt.plot(bin_centers[MG_back_indices],
                             normalized_hist_MG[MG_back_indices],
                             color='black',
                             label=None,
                             zorder=10)
                    plt.fill_between(bin_centers[indices_MG],
                                     normalized_hist_MG[indices_MG],
                                     np.ones(len(indices_MG)) *
                                     normalized_MG_back,
                                     facecolor='orange',
                                     label='Shoulder area',
                                     alpha=1,
                                     zorder=2)
                    plt.title(detector + ': ' + calibration)
                    plt.xlabel('$E_i$ - $E_f$ [meV]')
                    plt.ylabel('Normalized counts')
                    plt.yscale('log')
                    plt.grid(True, which='major', linestyle='--', zorder=0)
                    plt.grid(True, which='minor', linestyle='--', zorder=0)
                    plt.legend(loc=1)
                    plt.subplot(1, 3, 2)
                    plt.plot(bin_centers[He3_back_indices],
                             hist_He3[He3_back_indices],
                             color='black',
                             label=None,
                             zorder=6)
                    plt.plot(bin_centers,
                             hist_He3,
                             color='blue',
                             label='$^3$He-tubes',
                             zorder=5)
                    plt.fill_between(bin_centers[indices_He3],
                                     hist_He3[indices_He3],
                                     np.ones(len(indices_He3)) * back_He3,
                                     facecolor='purple',
                                     label='Shoulder area',
                                     alpha=1,
                                     zorder=2)
                    plt.title('$^3$He-tubes: ' + calibration)
                    plt.xlabel('$E_i$ - $E_f$ [meV]')
                    plt.ylabel('Normalized counts')
                    plt.yscale('log')
                    plt.grid(True, which='major', linestyle='--', zorder=0)
                    plt.grid(True, which='minor', linestyle='--', zorder=0)
                    plt.legend(loc=1)
                    plt.subplot(1, 3, 3)
                    for detector_temp in detectors:
                        plt.errorbar(energies,
                                     FoMs[detector_temp],
                                     errors[detector_temp],
                                     ecolor=colors[detector_temp],
                                     fmt='.',
                                     capsize=5,
                                     color=colors[detector_temp],
                                     label=detector_temp,
                                     zorder=5,
                                     linestyle='-')
                    #   plt.plot(energies, FoMs[detector_temp], '.-',
                    #            color=colors[detector_temp],
                    #           label=detector_temp, zorder=5)
                    plt.grid(True, which='major', linestyle='--', zorder=0)
                    plt.grid(True, which='minor', linestyle='--', zorder=0)
                    plt.xlabel('$E_i$ [meV]')
                    plt.ylabel('Figure-of-Merit')
                    plt.yscale('log')
                    plt.title('Figure-of-Merit')
                    if ((detector == 'ESS_PA') and (i == 4)):
                        pass
                    else:
                        plt.axvline(x=energies[i],
                                    color=colors[detector],
                                    zorder=5)
                    plt.legend(loc=2)
                    # Save fig
                    count += 1
                    output_path = temp_folder + str(count) + '.png'
                    plt.tight_layout()
                    fig.savefig(output_path, bbox_inches='tight')
                    output_path_pdf = os.path.join(
                        dir_name, '../../Results/pdf_files/%s.pdf' % count)
                    fig.savefig(output_path_pdf, bbox_inches='tight')
                    plt.close()

    images = []
    files = os.listdir(temp_folder)
    files = [
        file[:-4] for file in files
        if file[-9:] != '.DS_Store' and file != '.gitignore'
    ]

    output_path = os.path.join(
        dir_name, '../../Results/Shoulder/FOM_sweep_shoulder.gif')

    for filename in sorted(files, key=int):
        images.append(imageio.imread(temp_folder + filename + '.png'))
    imageio.mimsave(output_path, images)  #format='GIF', duration=0.33)
    shutil.rmtree(temp_folder, ignore_errors=True)
def compare_all_shoulders_5x5(window):
    # Declare parameters
    number_bins = 150
    sigma_interval = [3, 8]
    detectors = ['ILL', 'ESS_CLB', 'ESS_PA']
    FoMs = {'ILL': [], 'ESS_CLB': [], 'ESS_PA': []}
    colors = {'ILL': 'blue', 'ESS_CLB': 'red', 'ESS_PA': 'green'}
    energies = []
    errors = {'ILL': [], 'ESS_CLB': [], 'ESS_PA': []}
    count = 0
    # Get input-file paths
    dir_name = os.path.dirname(__file__)
    folder = os.path.join(dir_name, '../../Clusters/MG_V_5x5_HR/')
    files = np.array(
        [file for file in os.listdir(folder) if file[-3:] == '.h5'])
    files_sorted = sorted(
        files,
        key=lambda element: float(element[element.find('V_5x5_HR_') + len(
            'V_5x5_HR_'):element.find('_meV.h5')]))
    paths = np.core.defchararray.add(np.array(len(files_sorted) * [folder]),
                                     files_sorted)
    # Get output path
    temp_folder = os.path.join(dir_name, '../../Results/Shoulder/temp/')
    mkdir_p(temp_folder)
    for run in range(2):
        for detector in detectors:
            for i, path in enumerate(paths):
                # Import parameters
                E_i = pd.read_hdf(path, 'E_i')['E_i'].iloc[0]
                calibration = pd.read_hdf(path,
                                          'calibration')['calibration'].iloc[0]
                calibration = get_calibration(calibration, E_i)
                df_MG_temp = pd.read_hdf(path, 'coincident_events')
                df_MG = filter_ce_clusters(window, df_MG_temp)
                # Get MG dE-data
                df_MG_detector = detector_filter(df_MG, detector)
                dE_MG = get_MG_dE(df_MG_detector, calibration, E_i)
                # Get He3 dE-data
                dE_He3 = get_raw_He3_dE(calibration, E_i)
                # Produce histograms
                hist_MG, bins = np.histogram(dE_MG,
                                             bins=number_bins,
                                             range=[-E_i / 5, E_i / 5])
                hist_He3, __ = np.histogram(dE_He3,
                                            bins=number_bins,
                                            range=[-E_i / 5, E_i / 5])
                bin_centers = 0.5 * (bins[1:] + bins[:-1])
                # Normalize data
                p0 = None
                area_MG, FWHM_MG, __, __, __, popt_MG, l_p_idx_MG, r_p_idx_MG, back_MG = Gaussian_fit(
                    bin_centers, hist_MG, p0)
                area_He3, FWHM_He3, __, __, __, popt_He3, l_p_idx_He3, r_p_idx_He3, back_He3 = Gaussian_fit(
                    bin_centers, hist_He3, p0)
                norm_area = area_He3 / area_MG
                normalized_hist_MG = hist_MG * norm_area
                # THIS IS JUST TEMPORARY REMOVE AFTER USE
                fig = plt.figure()
                plt.plot(bin_centers,
                         normalized_hist_MG,
                         '-',
                         color='red',
                         label='Multi-Grid',
                         zorder=5)
                plt.plot(bin_centers,
                         hist_He3,
                         '-',
                         color='blue',
                         label='$^3$He-tubes',
                         zorder=5)
                plt.grid(True, which='major', linestyle='--', zorder=0)
                plt.grid(True, which='minor', linestyle='--', zorder=0)
                plt.xlabel('$E_i$ - $E_f$ [meV]')
                plt.ylabel('Normalized Counts')
                plt.yscale('log')
                plt.title(
                    'Energy transfer - All detectors (5x5 V-sample)\nData set: %s'
                    % calibration)
                plt.legend(loc=1)
                output_path_pdf = os.path.join(
                    dir_name, '../../Results/pdf_files/%s.pdf' % count)
                fig.savefig(output_path_pdf, bbox_inches='tight')
                plt.close()

                # Compare difference at certain interval
                x0_MG = popt_MG[1]
                sigma_MG = abs(popt_MG[2])
                x0_He3 = popt_He3[1]
                sigma_He3 = abs(popt_He3[2])
                left_idx_MG = find_nearest(
                    bin_centers, x0_MG + sigma_interval[0] * sigma_MG)
                right_idx_MG = find_nearest(
                    bin_centers, x0_MG + sigma_interval[1] * sigma_MG)
                indices_MG = np.arange(left_idx_MG, right_idx_MG + 1, 1)
                left_idx_He3 = find_nearest(
                    bin_centers, x0_He3 + sigma_interval[0] * sigma_He3)
                right_idx_He3 = find_nearest(
                    bin_centers, x0_He3 + sigma_interval[1] * sigma_He3)
                indices_He3 = np.arange(left_idx_He3, right_idx_He3 + 1, 1)
                area_MG = sum(
                    normalized_hist_MG[indices_MG]) - len(indices_MG) * back_MG
                area_He3 = sum(
                    hist_He3[indices_He3]) - len(indices_He3) * back_He3

                area_diff = sum(normalized_hist_MG[indices_MG] -
                                hist_He3[indices_MG])
                He3_peak_area = sum(
                    hist_He3[l_p_idx_He3:r_p_idx_He3] -
                    np.ones(len(bin_centers[l_p_idx_He3:r_p_idx_He3])) *
                    back_He3)
                FoM = area_diff / He3_peak_area
                # Find uncertainty
                a = sum(hist_MG[indices_MG])
                b = sum(hist_He3[indices_MG])
                c = sum(hist_He3[l_p_idx_He3:r_p_idx_He3])
                d = sum(
                    np.ones(len(bin_centers[l_p_idx_He3:r_p_idx_He3])) *
                    back_He3)
                da = np.sqrt(a)
                db = np.sqrt(b)
                dc = np.sqrt(c)
                dd = np.sqrt(d)
                uncertainty = np.sqrt((np.sqrt(da**2 + db**2) / (a - b))**2 +
                                      (np.sqrt(dc**2 + dd**2) / (c - d))**2)
                error = uncertainty * FoM

                if run == 0:
                    FoMs[detector].append(FoM)
                    errors[detector].append(error)
                    if detector == 'ILL':
                        energies.append(E_i)
                else:
                    # Plot data
                    fig = plt.figure()
                    #main_title = 'Peak shape comparison $^3$He-tubes and Multi-Grid'
                    #main_title += '\nInterval: ' + str(sigma_interval) + '$\sigma$'
                    #fig.suptitle(main_title, x=0.5, y=1.02)
                    fig.set_figheight(6)
                    fig.set_figwidth(14)
                    plt.subplot(1, 2, 1)
                    plt.plot(bin_centers,
                             normalized_hist_MG,
                             color='red',
                             label='Multi-Grid',
                             zorder=5)
                    plt.plot(bin_centers,
                             hist_He3,
                             color='blue',
                             label='$^3$He-tubes',
                             zorder=5)
                    plt.fill_between(bin_centers[indices_MG],
                                     normalized_hist_MG[indices_MG],
                                     hist_He3[indices_MG],
                                     facecolor='orange',
                                     label='Shoulder area',
                                     alpha=1,
                                     zorder=2)
                    plt.fill_between(
                        bin_centers[l_p_idx_He3:r_p_idx_He3],
                        hist_He3[l_p_idx_He3:r_p_idx_He3],
                        np.ones(len(bin_centers[l_p_idx_He3:r_p_idx_He3])) *
                        back_He3,
                        facecolor='purple',
                        label='$^3$He-peak area',
                        alpha=1,
                        zorder=2)
                    plt.title(detector + ': ' + calibration)
                    plt.xlabel('$E_i$ - $E_f$ [meV]')
                    plt.ylabel('Normalized counts')
                    plt.yscale('log')
                    plt.grid(True, which='major', linestyle='--', zorder=0)
                    plt.grid(True, which='minor', linestyle='--', zorder=0)
                    plt.legend(loc=1)
                    plt.subplot(1, 2, 2)
                    for detector_temp in detectors:
                        plt.errorbar(energies,
                                     FoMs[detector_temp],
                                     errors[detector_temp],
                                     ecolor=colors[detector_temp],
                                     fmt='.',
                                     capsize=5,
                                     color=colors[detector_temp],
                                     label=detector_temp,
                                     zorder=5,
                                     linestyle='-')
                    #   plt.plot(energies, FoMs[detector_temp], '.-',
                    #            color=colors[detector_temp],
                    #           label=detector_temp, zorder=5)
                    plt.grid(True, which='major', linestyle='--', zorder=0)
                    plt.grid(True, which='minor', linestyle='--', zorder=0)
                    plt.xlabel('$E_i$ [meV]')
                    plt.ylabel('Figure-of-Merit')
                    plt.title('Figure-of-Merit')
                    if ((detector == 'ESS_PA') and (i == 4)):
                        pass
                    else:
                        plt.axvline(x=energies[i],
                                    color=colors[detector],
                                    zorder=5)
                    plt.legend(loc=2)
                    # Save fig
                    count += 1
                    output_path = temp_folder + str(count) + '.png'
                    plt.tight_layout()
                    fig.savefig(output_path, bbox_inches='tight')
                    output_path_pdf = os.path.join(
                        dir_name, '../../Results/pdf_files/%s.pdf' % count)
                    #fig.savefig(output_path_pdf, bbox_inches='tight')

    images = []
    files = os.listdir(temp_folder)
    files = [
        file[:-4] for file in files
        if file[-9:] != '.DS_Store' and file != '.gitignore'
    ]

    output_path = os.path.join(
        dir_name, '../../Results/Shoulder/FOM_sweep_shoulder.gif')

    for filename in sorted(files, key=int):
        images.append(imageio.imread(temp_folder + filename + '.png'))
    imageio.mimsave(output_path, images)  #format='GIF', duration=0.33)
    shutil.rmtree(temp_folder, ignore_errors=True)
def background_dependence_on_ADC_threshold(df, data_sets, window):
    # Initial filter of clusters
    df = filter_ce_clusters(window, df)
    df = df[(df.wCh != -1) & (df.gCh != -1)]
    if data_sets == "['mvmelst_039.mvmelst']":
        df = df[df.Time < 1.5e12]
    # Declare parameters
    step = 20
    thresholds = np.arange(0, 1500 + step, step)
    number_thresholds = len(thresholds)
    # Declare data folder
    data = {'top': [thresholds, np.zeros(number_thresholds)],
            'bottom': [thresholds, np.zeros(number_thresholds)],
            'middle': [thresholds, np.zeros(number_thresholds)],
            'back': [thresholds, np.zeros(number_thresholds)],
            'reference': [thresholds, np.zeros(number_thresholds)]
            }
    # Create output folder
    dir_name = os.path.dirname(__file__)
    temp_folder = os.path.join(dir_name, '../../Results/temp_folder_ADC/')
    mkdir_p(temp_folder)
    # Iterate through data
    for run in [1, 2]:
        for i, threshold in enumerate(thresholds):
            df_temp = df[(df.wADC >= threshold) & (df.gADC >= threshold)]
            if run == 1:
                counts_top = df_temp[(df_temp.Bus >= 6) &
                                     (df_temp.Bus <= 8) &
                                     (df_temp.gCh == 119)
                                     ].shape[0]/(20*11)
                counts_bottom = df_temp[(df_temp.Bus >= 6) &
                                        (df_temp.Bus <= 8) &
                                        (df_temp.gCh == 80)
                                        ].shape[0]/(20*11)
                counts_back = df_temp[(df_temp.Bus >= 6) &
                                      (df_temp.Bus <= 8) &
                                      ((df_temp.wCh == 19) |
                                       (df_temp.wCh == 39) |
                                       (df_temp.wCh == 59) |
                                       (df_temp.wCh == 79)
                                       )
                                      ].shape[0]/(11*40)
                counts_middle = df_temp[((df_temp.gCh >= 95)
                                         & (df_temp.gCh <= 105)
                                         ) &
                                        (((df_temp.wCh >= 0) &
                                          (df_temp.wCh <= 9)) |
                                         ((df_temp.wCh >= 20) &
                                          (df_temp.wCh <= 29)) |
                                         ((df_temp.wCh >= 40) &
                                          (df_temp.wCh <= 49)) |
                                         ((df_temp.wCh >= 60) &
                                          (df_temp.wCh <= 69))
                                         ) &
                                        (df_temp.Bus >= 7)
                                        ].shape[0]/(10*10*7)
                counts_reference = df_temp[((df_temp.gCh >= 112)
                                            & (df_temp.gCh <= 117)
                                            ) &
                                           (((df_temp.wCh >= 0) &
                                             (df_temp.wCh <= 9)) |
                                            ((df_temp.wCh >= 20) &
                                             (df_temp.wCh <= 29)) |
                                            ((df_temp.wCh >= 40) &
                                             (df_temp.wCh <= 49)) |
                                            ((df_temp.wCh >= 60) &
                                             (df_temp.wCh <= 69))
                                            ) &
                                           (df_temp.Bus == 6)
                                           ].shape[0]/(6*10*4)
                data['top'][1][i] = counts_top
                data['bottom'][1][i] = counts_bottom
                data['middle'][1][i] = counts_middle
                data['back'][1][i] = counts_back
                data['reference'][1][i] = counts_reference
            else:
                path = temp_folder + str(threshold) + '.png'
                hist_3D_for_ADC_threshold(df_temp, data, threshold, path)
    # Save animation
    images = []
    files = os.listdir(temp_folder)
    files = [file[:-4] for file in files
             if file[-9:] != '.DS_Store' and file != '.gitignore']
    animation_path = os.path.join(dir_name,
                                  '../../Results/Animations/ADC_sweep_3D.gif')
    for filename in sorted(files, key=int):
        images.append(imageio.imread(temp_folder + filename + '.png'))
    imageio.mimsave(animation_path, images)
    shutil.rmtree(temp_folder, ignore_errors=True)
def signal_dependence_on_ADC_threshold(df, Ei, calibration, window):
    # Declare parameters
    bins_full = 1000
    bins_part = 500
    step = 20
    df = filter_ce_clusters(window, df)
    thresholds = np.arange(0, 1000 + step, step)
    number_thresholds = len(thresholds)
    ## Plot limits
    maximum_full = 1
    minimum_full = 0
    maximum_part = 1
    minimum_part = 0
    ## Bins with data
    gamma_bins = [320, 328]
    thermal_bins = [400, 550]
    fast_bins = [328, 343]
    back_bins = [800, 900]
    gamma_bins_part = [150, 225]
    fast_bins_part = [225, 350]
    # Declare data folder
    fast_neutrons = np.zeros(number_thresholds)
    thermal_neutrons = np.zeros(number_thresholds)
    gammas = np.zeros(number_thresholds)
    background = np.zeros(number_thresholds)
    # Create output folder
    dir_name = os.path.dirname(__file__)
    temp_folder = os.path.join(dir_name, '../../Results/temp_folder_ADC/')
    mkdir_p(temp_folder)
    # Iterate through data
    for run in [1, 2]:
        for i, threshold in enumerate(thresholds):
            df_temp = df[(df.wADC >= threshold) & (df.gADC >= threshold)]
            # Define figure and axises
            fig, (ax1, ax3) = plt.subplots(1, 2, figsize=(11, 5))
            left, bottom, width, height = [0.335, 0.6, 0.13, 0.25]
            ax2 = fig.add_axes([left, bottom, width, height])
            # Plot data
            ## First plot, first axis
            hist_full, bins_full = np.histogram(df_temp.ToF*62.5e-9*1e6,
                                                bins=bins_full,
                                                range=[0, 16667])
            bin_centers_full = 0.5 * (bins_full[1:] + bins_full[:-1])
            ### Plot full data
            ax1.plot(bin_centers_full, hist_full, color='black',
                     label=None)
            ax1.plot(bin_centers_full[thermal_bins[0]:thermal_bins[1]],
                     hist_full[thermal_bins[0]:thermal_bins[1]],
                     color='orange', label='Thermal')
            ax1.plot(bin_centers_full[fast_bins[0]:fast_bins[1]],
                     hist_full[fast_bins[0]:fast_bins[1]],
                     color='blue', label='Fast')
            ax1.plot(bin_centers_full[gamma_bins[0]:gamma_bins[1]],
                     hist_full[gamma_bins[0]:gamma_bins[1]],
                     color='red', label='Gamma')
            ax1.plot(bin_centers_full[back_bins[0]:back_bins[1]],
                     hist_full[back_bins[0]:back_bins[1]],
                     color='green', label='Background')
            ax1.set_ylim(minimum_full*0.8, maximum_full*1.5)
            ax1.set_yscale('log')
            ax1.set_xlabel('ToF [µs]')
            ax1.set_ylabel('Counts')
            ax1.legend(loc=2)
            ax1.set_title('ToF histogram: US - 70 meV')
            ## First plot, second axis
            hist_part, bins_part = np.histogram(df_temp.ToF*62.5e-9*1e6,
                                                bins=bins_part,
                                                range=[5250, 5750])
            bin_centers_part = 0.5 * (bins_part[1:] + bins_part[:-1])
            ax2.plot(bin_centers_part, hist_part, color='black')
            ax2.plot(bin_centers_part[gamma_bins_part[0]:gamma_bins_part[1]],
                     hist_part[gamma_bins_part[0]:gamma_bins_part[1]],
                     color='red')
            ax2.plot(bin_centers_part[fast_bins_part[0]:fast_bins_part[1]],
                     hist_part[fast_bins_part[0]:fast_bins_part[1]],
                     color='blue')
            ax2.set_yscale('log')
            ax2.set_ylim(minimum_part*0.8, maximum_part*1.5)
            ax2.set_xlabel('ToF [µs]')
            ax2.set_ylabel('Counts')
            if run == 1:
                if i == 1:
                    maximum_full = max(hist_full)
                    maximum_part = max(hist_part)
                if i == len(thresholds) - 1:
                    minimum_full = min(hist_full)
                    minimum_part = min(hist_part)
                # Save data
                fast_data = hist_part[fast_bins_part[0]:fast_bins_part[1]]
                fast_duration = (bin_centers_part[fast_bins_part[1]]
                                 - bin_centers_part[fast_bins_part[0]])
                thermal_data = hist_full[thermal_bins[0]:thermal_bins[1]]
                thermal_duration = (bin_centers_full[thermal_bins[1]]
                                    - bin_centers_full[thermal_bins[0]])
                gamma_data = hist_part[gamma_bins_part[0]:gamma_bins_part[1]]
                gamma_duration = (bin_centers_part[gamma_bins_part[1]]
                                  - bin_centers_part[gamma_bins_part[0]])
                background_data = hist_full[back_bins[0]:back_bins[1]]
                background_duration = (bin_centers_full[back_bins[1]]
                                       - bin_centers_full[back_bins[0]])
                fast_neutrons[i] = sum(fast_data)/fast_duration
                thermal_neutrons[i] = sum(thermal_data)/thermal_duration
                gammas[i] = sum(gamma_data)/gamma_duration
                background[i] = sum(background_data)/background_duration
                plt.close()
            else:
                ## Second plot
                ax3.plot(thresholds, thermal_neutrons, '.-', color='orange',
                         label='Thermal')
                ax3.plot(thresholds, fast_neutrons, '.-', color='blue',
                         label='Fast')
                ax3.plot(thresholds, gammas, '.-', color='red', label='Gamma')
                ax3.plot(thresholds, background, '.-', color='green',
                         label='Background')
                ax3.axvline(x=threshold, color='black')
                ax3.axvline(x=500, color='grey', linestyle='--')
                ax3.set_xlabel('Threshold [ADC channels]')
                ax3.set_ylabel('Counts/µs')
                ax3.grid(True, which='major', linestyle='--', zorder=0)
                ax3.grid(True, which='minor', linestyle='--', zorder=0)
                ax3.legend(loc=2)
                ax3.set_yscale('log')
                # Save data
                output_path = temp_folder + str(threshold) + '.png'
                fig.savefig(output_path, bbox_inches='tight')
    # Save animation
    images = []
    files = os.listdir(temp_folder)
    files = [file[:-4] for file in files
             if file[-9:] != '.DS_Store' and file != '.gitignore']
    animation_path = os.path.join(dir_name,
                                  '../../Results/Animations/ADC_sweep.gif')
    for filename in sorted(files, key=int):
        images.append(imageio.imread(temp_folder + filename + '.png'))
    imageio.mimsave(animation_path, images)
    shutil.rmtree(temp_folder, ignore_errors=True)