def main():
    topology = [2, 1]
    pmt_array = PMT_Array(topology, "summary")
    pmt_array.set_pmt_id("GAO607", 0)
    pmt_array.set_pmt_id("GAO612", 1)

    # store_res(pmt_array)
    plot_res()
    plot_base_drift()
def read_file(date: str, voltage: int, root_file_name: str,
              pmt_array: PMT_Array):
    file = ROOT.TFile(root_file_name, "READ")
    file.cd()

    fit_parameter = [None for i in range(pmt_array.get_pmt_total_number())]

    for i_om in range(pmt_array.get_pmt_total_number()):
        charge_hist = file.Get(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_charge_spectrum_" + str(voltage) + "V")
        amp_hist = file.Get(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_amplitude_spectrum_" + str(voltage) + "V")
        baseline_hist = file.Get(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_baseline_distribution_" + str(voltage) + "V")

        try:
            charge_hist.GetEntries()
            amp_hist.GetEntries()
            baseline_hist.GetEntries()
        except AttributeError:
            # print(root_file_name, ": No entries :", date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() + "_charge_spectrum_" + str(voltage) + "V")
            continue

        mu_guess = charge_hist.GetMaximumBin() * charge_hist.GetBinWidth(0)
        fit_vals = do_bi_1000(charge_hist, mu_guess)

        freq, bin_centres = [], []
        for i_bin in range(0, charge_hist.GetNbinsX()):
            freq.append(charge_hist.GetBinContent(i_bin + 1))
            bin_centres.append(i_bin * charge_hist.GetBinWidth(i_bin + 1) +
                               charge_hist.GetBinWidth(i_bin + 1))
        freq, bin_centres, bin_width = np.array(freq), np.array(
            bin_centres), charge_hist.GetBinWidth(3)
        plot_fit([freq, bin_centres, bin_width], fit_vals, date, str(i_om))

        if fit_vals[-1][0] == -1:
            pass
        else:
            pars = {
                # TODO: add the correlation matrix to this
                "mu": fit_vals[0][0],
                "mu_err": fit_vals[0][1],
                "sig": fit_vals[1][0],
                "sig_err": fit_vals[1][1],
                "base_mu": baseline_hist.GetMean(),
                "base_sig": baseline_hist.GetStdDev(),
                "chi2": fit_vals[-1][0],
                "ndof": fit_vals[-1][1]
            }
            fit_parameter[i_om] = pars

    file.Close()
    return fit_parameter
def store_res(pmt_array: PMT_Array):
    out_file = open(f"/Users/williamquinn/Desktop/PMT_Project/res_vs_time.csv",
                    "w")
    out_file.write("pmt,date,res,res_err,chi_2,ndof,base_mean,base_sig\n")

    filenames_txt = "/Users/williamquinn/Desktop/PMT_Project/filenames.txt"

    try:
        print(">>> Reading data from file: {}".format(filenames_txt))
        date_file = open(filenames_txt, 'r')
    except FileNotFoundError:
        raise Exception("Error opening data file {}".format(filenames_txt))

    filenames = np.loadtxt(filenames_txt,
                           delimiter=',',
                           dtype={
                               'names': ['filename'],
                               'formats': ['S100']
                           },
                           unpack=True)

    for i_file in tqdm(range(filenames.size)):
        file = filenames[i_file][0].decode("utf-8")

        date = file.split("_")[0]
        voltage = int(file.split("_")[1].split("A")[1])

        if voltage != 1000:
            continue

        fit_pars = read_file(
            date, voltage,
            "/Users/williamquinn/Desktop/PMT_Project/data/1000V/" + file,
            pmt_array)

        for i_om in range(pmt_array.get_pmt_total_number()):

            if fit_pars[i_om] is None:
                continue

            mu = fit_pars[i_om]["mu"]
            mu_err = fit_pars[i_om]["mu_err"]
            sig = fit_pars[i_om]["sig"]
            sig_err = fit_pars[i_om]["sig_err"]
            chi_2 = fit_pars[i_om]["chi2"]
            ndof = fit_pars[i_om]["ndof"]
            baseline_mean = fit_pars[i_om]["base_mu"]
            baseline_sig = fit_pars[i_om]["base_sig"]

            res = sig / mu
            res_err = res * ((sig_err / sig)**2 + (mu_err / mu)**2)

            out_file.write(
                f'{i_om},{date},{res},{res_err},{chi_2},{ndof},{baseline_mean},{baseline_sig}\n'
            )

    out_file.close()

    print("<<<< FINISHED >>>")
Exemple #4
0
def read_file(date: str, voltage: int, root_file_name: str, pmt_array: PMT_Array, output_file_location: str):

    file = ROOT.TFile(root_file_name, "READ")
    file.cd()

    apulse_info = [[] for i in range(pmt_array.get_pmt_total_number())]

    for i_om in range(pmt_array.get_pmt_total_number()):
        apulse_num_hist = file.Get(date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                                   "_apulse_num_" + str(voltage) + "V")
        apulse_time_hist = file.Get(date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                                    "_apulse_times_" + str(voltage) + "V")
        apulse_amplitude_hist = file.Get(date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                                          "_apulse_amplitudes_" + str(voltage) + "V")

        he_apulse_num_hist = file.Get(date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                                      "_he_apulse_num_" + str(voltage) + "V")
        he_apulse_amplitude_hist = file.Get(date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                                         "_he_apulse_amplitudes_" + str(voltage) + "V")

        try:
            apulse_num_hist.GetEntries()
            apulse_time_hist.GetEntries()
            apulse_amplitude_hist.GetEntries()
            he_apulse_num_hist.GetEntries()
            he_apulse_amplitude_hist.GetEntries()
        except:
            continue

        apulse_rate = 0
        for i_bin in range(2, apulse_num_hist.GetNbinsX()):
            apulse_rate += apulse_num_hist.GetBinContent(i_bin)

        apulse_rate = (apulse_rate/apulse_num_hist.GetEntries()) * 100
        apulse_rate_err = (np.sqrt(1/apulse_rate + 1/apulse_num_hist.GetEntries())) * apulse_rate

        he_apulse_rate = 0
        for i_bin in range(2, he_apulse_num_hist.GetNbinsX()):
            he_apulse_rate += he_apulse_num_hist.GetBinContent(i_bin)

        he_apulse_rate = (he_apulse_rate/apulse_num_hist.GetEntries()) * 100
        he_apulse_rate_err = (np.sqrt(1/he_apulse_rate + 1/apulse_num_hist.GetEntries())) * he_apulse_rate
        '''c1 = ROOT.TCanvas()
        charge_hist.Draw()
        bi_fit.Draw("same")
        c1.SetGrid()
        c1.Update()
        ROOT.gStyle.SetOptFit(1)
        c1.SaveAs(name)'''

        pars = {
            "apulse_rate": apulse_rate,
            "apulse_rate_err": apulse_rate_err,
            "he_apulse_rate": he_apulse_rate,
            "he_apulse_rate_err": he_apulse_rate_err
        }
        apulse_info[i_om].append(pars)

    file.Close()
    return apulse_info
Exemple #5
0
def process_xml_file(input_data_file_name: str, pmt_array: PMT_Array):
    print(">>> Parsing the data file...")
    processing_start = TIME.time()

    # parse an xml file by name
    xml_file = minidom.parse(input_data_file_name)
    events = xml_file.getElementsByTagName('event')
    parse_time = TIME.time() - processing_start
    print(">>> File is good. Parse time: %.3f s" % parse_time)
    print(">>> Number of Events: {}".format(len(events)))

    event_counter = 0
    percentage_counter = 1
    print(">>> Looping over events")
    temp_start = TIME.time()
    for event_index, event in enumerate(events):

        if event_counter == int(len(events) / 20):
            event_counter = 0
            intermediate = TIME.time()
            time_length = intermediate - temp_start
            print(">>>\n>>>  %.3f s.\n" % (intermediate - temp_start))
            temp_start = intermediate
            print("Processed {}% of data...".format(percentage_counter * 5))
            estimate = time_length * (20 - percentage_counter)
            print(">>> Estimated time till termination %.3f seconds\n\n" %
                  estimate)
            percentage_counter += 1

        traces = event.getElementsByTagName('trace')
        for trace_index, trace in enumerate(traces):
            # Channel refers to the pmt number
            channel_id = int(trace.attributes['channel'].value)

            # Important Code:
            # This is where you pass the data to the OOP code which does all the analysis for you
            # Ideally this would be in the main analysis.py file
            ##########################################################################################################
            pmt_waveform = PMT_Waveform(
                trace.firstChild.data.split(" "),
                pmt_array.get_pmt_object_number(channel_id))
            # check waveform to see if you want to fill histograms
            # The pulse trigger logic is in PMT_Waveform.py
            if pmt_waveform.get_pulse_trigger():
                pmt_waveform.fill_pmt_hists()
            else:
                pass
            del pmt_waveform
            ##########################################################################################################

        event_counter += 1
def main():
    # Handle the input arguments:
    ##############################
    args = pmt_parse_arguments()
    input_directory = args.i
    config_file_name = args.c
    output_directory = args.o
    ##############################

    filenames_txt = input_directory + "/filenames.txt"

    try:
        print(">>> Reading data from file: {}".format(filenames_txt))
        date_file = open(filenames_txt, 'r')
    except FileNotFoundError as fnf_error:
        print(fnf_error)
        raise Exception("Error opening data file {}".format(filenames_txt))

    filenames = np.loadtxt(filenames_txt,
                           delimiter=',',
                           dtype={
                               'names': ['filename'],
                               'formats': ['S100']
                           },
                           unpack=True)

    topology = [2, 1]
    pmt_array = PMT_Array(topology, "summary")
    pmt_array.set_pmt_id("GAO607", 0)
    pmt_array.set_pmt_id("GAO612", 1)

    # Set the cuts you wish to apply
    # If you don't do this the defaults are used
    if config_file_name is not None:
        pmt_array.apply_setting(config_file_name)
        print_settings(pmt_array)

    for i_file in tqdm.tqdm(range(filenames.size)):
        file = filenames[i_file][0].decode("utf-8")

        try:
            read_tree(input_directory + "/" + file, pmt_array,
                      output_directory,
                      file.split(".root")[0] + "_output.root")
        except:
            print("error reading file:", input_directory + "/" + file)
Exemple #7
0
def read_tree(root_file_name: str, pmt_array: PMT_Array,
              output_file_location: str, output_file_name: str):

    file = ROOT.TFile(root_file_name, "READ")
    file.cd()

    date = root_file_name.split("/")[-1].split("_")[0]
    voltage = int(root_file_name.split("/")[-1].split("_")[1].split("A")[1])

    if voltage == 1000:
        max_amp = 400
    else:
        max_amp = 1000
    max_charge = 60

    tree = file.T

    # Create the histograms that we will want to store
    # these will be used to extract the resolution
    charge_hists = []
    amp_hists = []
    baselines = []
    apulse_nums_hists = []
    he_apulse_nums_hists = []
    apulse_times_hists = []
    apulse_amplitudes_hists = []
    he_apulse_amplitudes_hists = []
    for i_om in range(pmt_array.get_pmt_total_number()):
        nbins = pmt_array.get_pmt_object_number(i_om).get_setting("nbins")

        charge_hist = ROOT.TH1D(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_charge_spectrum_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_charge_spectrum_" + str(voltage) + "V", nbins, 0, max_charge)
        amp_hist = ROOT.TH1D(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_amplitude_spectrum_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_amplitude_spectrum_" + str(voltage) + "V", nbins, 0, max_amp)
        baseline = ROOT.TH1D(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_baseline_distribution_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_baseline_distribution_" + str(voltage) + "V", nbins, 978, 981)
        apulse_num = ROOT.TH1I(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_apulse_num_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_apulse_num_" + str(voltage) + "V", 20, 0, 20)
        he_apulse_num = ROOT.TH1I(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_he_apulse_num_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_he_apulse_num_" + str(voltage) + "V", 20, 0, 20)
        apulse_time = ROOT.TH1I(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_apulse_times_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_apulse_times_" + str(voltage) + "V", 7000, 0, 7000)
        apulse_amplitude = ROOT.TH1D(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_apulse_amplitudes_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_apulse_amplitudes_" + str(voltage) + "V", nbins, 0, 500)
        he_apulse_amplitude = ROOT.TH1D(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_he_apulse_amplitudes_" + str(voltage) + "V",
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_he_apulse_amplitudes_" + str(voltage) + "V", nbins, 0, 500)
        charge_hists.append(charge_hist)
        amp_hists.append(amp_hist)
        baselines.append(baseline)
        apulse_nums_hists.append(apulse_num)
        he_apulse_nums_hists.append(he_apulse_num)
        apulse_times_hists.append(apulse_time)
        apulse_amplitudes_hists.append(apulse_amplitude)
        he_apulse_amplitudes_hists.append(he_apulse_amplitude)

    output_file = ROOT.TFile(
        output_file_location + "/ROOT_files/" + str(voltage) + "V/" +
        output_file_name, "RECREATE")
    output_file.cd()

    for event in tree:
        # Access the information inside the NTuple

        OM_ID = event.OM_ID
        if OM_ID == 0 or OM_ID == 1:
            pass
        else:
            continue

        pulse_amplitude = int(event.pulse_amplitude)
        pulse_charge = event.pulse_charge
        pulse_baseline = event.pulse_baseline
        apulse_num = event.apulse_num
        apulse_times = event.apulse_times
        apulse_amplitudes = event.apulse_amplitudes
        apulse_shapes = event.apulse_shapes

        charge_hists[OM_ID].Fill(pulse_charge)
        amp_hists[OM_ID].Fill(pulse_amplitude)
        baselines[OM_ID].Fill(pulse_baseline)

        # Now apply new amplitude and shape cuts
        new_apulse_num = 0
        he_new_apulse_num = 0
        filer_list = []
        he_filter_list = []

        try:
            for i_apulse in range(apulse_num):
                if apulse_shapes[i_apulse] > pmt_array.get_pmt_object_number(OM_ID).get_setting("mf_shape_threshold")\
                        and apulse_amplitudes[i_apulse] > pmt_array.get_pmt_object_number(OM_ID).get_setting("mf_amp_threshold")\
                        and apulse_times[i_apulse] > pmt_array.get_pmt_object_number(OM_ID).get_setting("sweep_range")[0]:
                    if pmt_array.get_pmt_object_number(OM_ID).get_setting(
                            "he_region")[0] <= apulse_times[
                                i_apulse] <= pmt_array.get_pmt_object_number(
                                    OM_ID).get_setting("he_region")[1]:
                        he_filter_list.append(True)
                        he_new_apulse_num += 1
                        he_apulse_amplitudes_hists[OM_ID].Fill(
                            apulse_amplitudes[i_apulse])
                    else:
                        he_filter_list.append(False)
                    filer_list.append(True)
                    new_apulse_num += 1
                    apulse_amplitudes_hists[OM_ID].Fill(
                        apulse_amplitudes[i_apulse])
                    apulse_times_hists[OM_ID].Fill(apulse_times[i_apulse])
                else:
                    filer_list.append(False)
                    he_filter_list.append(False)
            apulse_nums_hists[OM_ID].Fill(new_apulse_num)
            he_apulse_nums_hists[OM_ID].Fill(he_new_apulse_num)
        except:
            pass

    for i_om in range(pmt_array.get_pmt_total_number()):
        if charge_hists[i_om].GetEntries() > 0:
            output_file.cd()
            charge_hists[i_om].Write()
            amp_hists[i_om].Write()
            baselines[i_om].Write()
            apulse_nums_hists[i_om].Write()
            apulse_times_hists[i_om].Write()
            apulse_amplitudes_hists[i_om].Write()
            he_apulse_nums_hists[i_om].Write()
            he_apulse_amplitudes_hists[i_om].Write()
        else:
            pass

    file.Close()
    output_file.Close()
Exemple #8
0
def main():

    # Handle the input arguments:
    ##############################
    args = sncd_parse_arguments()
    input_data_file_name = args.i
    config_file_name = args.c
    output_file_name = args.o
    sweep_bool = "True"
    ##############################

    # Do some string manipulation to get the date and time from the file name
    #################################################
    date, time = "0000", "0000"
    voltage = 1400
    #################################################

    # Check to see if the data file exists
    try:
        print(">>> Reading data from file: {}".format(input_data_file_name))
        date_file = open(input_data_file_name, 'r')
    except FileNotFoundError as fnf_error:
        print(fnf_error)
        raise Exception(
            "Error opening data file {}".format(input_data_file_name))

    file = ROOT.TFile(input_data_file_name, "READ")
    output_file = ROOT.TFile(output_file_name, "RECREATE")
    file.cd()

    tree = file.T
    tree.Print()

    num_events = 10000

    topology = [4, 1]
    pmt_array = PMT_Array(topology, date + "_" + time)
    pmt_array.set_pmt_id("GAO607_" + date + "_" + time, 0)
    pmt_array.set_pmt_id("GAO612_" + date + "_" + time, 1)
    pmt_array.set_pmt_id("Injected_GAO607_" + date + "_" + time, 2)
    pmt_array.set_pmt_id("Injected_GAO612_" + date + "_" + time, 3)

    # Set the cuts you wish to apply
    # If you don't do this the defaults are used
    if config_file_name is not None:
        pmt_array.apply_setting(config_file_name)

    if sweep_bool == "True":
        pmt_array.set_sweep_bool(True)
        if voltage == 1000:
            pmt_array.set_pmt_templates(
                "~/Desktop/191008_A1000_B1000_templates.root", [
                    "A1000_B1000_Ch0_Template", "A1000_B1000_Ch1_Template",
                    "A1000_B1000_Ch0_Template", "A1400_B1400_Ch1_Template"
                ])
        elif voltage == 1400:
            pmt_array.set_pmt_templates(
                "~/Desktop/190621_A1400_B1400_templates.root", [
                    "A1400_B1400_Ch0_Template", "A1400_B1400_Ch1_Template",
                    "A1400_B1400_Ch0_Template", "A1400_B1400_Ch1_Template"
                ])

    amp_cut = pmt_array.get_pmt_object_number(0).get_setting(
        "mf_amp_threshold")
    shape_cut = pmt_array.get_pmt_object_number(0).get_setting(
        "mf_shape_threshold")

    t_injected = [[], []]
    a_injected = [[], []]
    a_injected_failure = [[], []]
    t_injected_success = [[], []]
    t_injected_failure = [[], []]
    mf_a_injected = [[], []]
    mf_s_injected = [[], []]

    num = [0, 0]
    enum = [0, 0]
    iterator = 0

    ran_range = 52

    injected_array = [[[], []], [[], []]]
    best_array = [[[], []], [[], []]]
    random_array = [[[], []], [[], []]]
    x_best_array = [[], []]

    for event in tqdm.tqdm(tree):
        OM_ID = event.OM_ID
        waveform = np.array(event.waveform)

        # Get template for injecting into data
        template_pulse = pmt_array.get_pmt_object_number(
            OM_ID).get_template_pmt_pulse()

        # Get the amplitude of the template so we can normalise to 1
        temp_amplitude = np.amin(template_pulse)

        # Create random numbers
        random_amp = rand.randrange(0, ran_range - 1, 2)
        random_time = rand.randrange(
            800,
            pmt_array.get_pmt_object_number(OM_ID).get_waveform_length() -
            template_pulse.size)
        '''print("A: ",random_amp)
        print("t: ",random_time)'''

        factor = random_amp / temp_amplitude

        injected_data = np.zeros_like(waveform)

        j = 0
        for i in range(injected_data.size):
            if i >= random_time:
                injected_data[i] = int(template_pulse[j] * factor)
                j += 1
                if j == template_pulse.size:
                    break

        pmt_waveform = PMT_Waveform(waveform,
                                    pmt_array.get_pmt_object_number(OM_ID))
        pmt_waveform_injected = PMT_Waveform(
            waveform - injected_data,
            pmt_array.get_pmt_object_number(OM_ID + 2))
        plt.plot(waveform - injected_data, 'r-', label="injected")
        plt.plot(waveform, 'b-', label="raw data")
        plt.xlabel("time /ns")
        plt.ylabel("ADC unit /mV")
        plt.legend(loc="lower right")
        plt.grid(True)
        plt.show()
        check = False

        if pmt_waveform.get_pmt_pulse_trigger():
            i_shape = 0
            i_amp = 0
            r_shape = 0
            r_amp = 0

            for index, value in enumerate(
                    pmt_waveform_injected.get_pmt_pulse_times()):
                if random_time == value + 800:
                    num[OM_ID] += 1
                    i_shape = pmt_waveform_injected.pmt_waveform_sweep_shape[
                        value]
                    i_amp = pmt_waveform_injected.pmt_waveform_sweep_amp[value]
                    r_shape = pmt_waveform.pmt_waveform_sweep_shape[value]
                    r_amp = pmt_waveform.pmt_waveform_sweep_amp[value]
                    check = True

            # Store random numbers
            t_injected[OM_ID].append(random_time)

            if check:
                a_injected[OM_ID].append(random_amp)
                t_injected_success[OM_ID].append(random_time)
                mf_a_injected[OM_ID].append(i_amp)
                mf_s_injected[OM_ID].append(i_shape)
            else:
                a_injected_failure[OM_ID].append(random_amp)
                t_injected_failure[OM_ID].append(random_time)

            injected_array[OM_ID][0].append(i_shape)
            injected_array[OM_ID][1].append(i_amp)
            random_array[OM_ID][0].append(r_shape)
            random_array[OM_ID][1].append(r_amp)

            best_shape = np.amax(pmt_waveform.pmt_waveform_sweep_shape)
            i_best = np.argmax(pmt_waveform.pmt_waveform_sweep_shape)
            best_amplitude = pmt_waveform.pmt_waveform_sweep_amp[i_best]

            x_best_array[OM_ID].append(i_best)
            best_array[OM_ID][0].append(best_shape)
            best_array[OM_ID][1].append(best_amplitude)
            '''fig, ax1 = plt.subplots()

            color = 'tab:red'
            ax1.set_xlabel('timestamp (ns)')
            ax1.set_ylabel('shape', color=color)
            ax1.plot(pmt_waveform.pmt_waveform_sweep_amp, color=color)
            ax1.plot(pmt_waveform.get_pmt_pulse_times(), pmt_waveform.pmt_waveform_sweep_amp[pmt_waveform.get_pmt_pulse_times()], "x", color='tab:green')
            ax1.tick_params(axis='y', labelcolor=color)
            ax1.plot(np.zeros_like(pmt_waveform.pmt_waveform_sweep_shape), "--", color="gray")
            plt.show(block=False)
            plt.pause(0.5)
            plt.close()'''

            enum[OM_ID] += 1
        iterator += 1
        if iterator == num_events:
            break
        #bar.update(iterator)

    #bar.finish()

    print("Percentage injected found: ", num[0] / enum[0], "% ch0",
          num[1] / enum[1], "% ch1")

    for i in range(2):
        plt.plot(t_injected[i], injected_array[i][0], 'r.', label="injected")
        plt.plot(t_injected[i], random_array[i][0], 'g.', label="random")
        plt.plot(t_injected[i], best_array[i][0], 'b.', label="best")
        plt.xlabel("time /ns")
        plt.ylabel("shape index")
        plt.title("Channel: {} events: {}".format(i, num_events))
        plt.grid(True)
        plt.legend(loc="lower right")
        plt.axhline(y=shape_cut, color='k', linestyle='-')
        plt.savefig(
            "/Users/willquinn/Desktop/pmt_sim_results/shape_index_vs_time_ch{}"
            .format(i))
        plt.show()

        plt.hist(injected_array[i][0],
                 bins=100,
                 range=(0, 1),
                 alpha=0.5,
                 label="injected")
        plt.hist(random_array[i][0],
                 bins=100,
                 range=(0, 1),
                 alpha=0.5,
                 label="random")
        plt.hist(best_array[i][0],
                 bins=100,
                 range=(0, 1),
                 alpha=0.5,
                 label="best")
        plt.xlabel("shape index")
        plt.ylabel("counts")
        plt.title("Channel: {} events: {}".format(i, num_events))
        plt.grid(True)
        plt.yscale('log')
        plt.legend(loc="upper left")
        plt.axvline(x=shape_cut, color='r', linestyle='-')
        plt.savefig(
            "/Users/willquinn/Desktop/pmt_sim_results/shape_index_vs_time_hist_ch{}"
            .format(i))
        plt.show()

        plt.plot(t_injected_failure[i],
                 a_injected_failure[i],
                 'r.',
                 label="failures")
        plt.plot(t_injected_success[i], a_injected[i], 'g.', label="success")
        plt.xlabel("time /ns")
        plt.title("Channel: {} events: {}".format(i, num_events))
        plt.ylabel("amplitude injected")
        plt.grid(True)
        plt.legend(loc="lower right")
        plt.savefig(
            "/Users/willquinn/Desktop/pmt_sim_results/amplitude_success_vs_failures_ch{}"
            .format(i))
        plt.show()

        plt.hist(a_injected_failure[i],
                 bins=int(ran_range / 2),
                 range=(0, ran_range),
                 alpha=0.5,
                 label="failures")
        plt.hist(a_injected[i],
                 bins=int(ran_range / 2),
                 range=(0, ran_range),
                 alpha=0.5,
                 label="success")
        plt.xlabel("amplitude injected")
        plt.title("Channel: {} events: {}".format(i, num_events))
        plt.ylabel("counts")
        plt.grid(True)
        plt.legend(loc="upper left")
        plt.text(
            0, 0,
            'Success percentage: {}%'.format(round(num[0] / enum[0] * 100), 4))
        plt.savefig(
            "/Users/willquinn/Desktop/pmt_sim_results/amplitude_success_vs_failures_hist_ch{}"
            .format(i))
        plt.show()

        new_mf_a_y = []
        new_mf_a_y_err = []
        new_mf_a_x = np.histogram(a_injected[i],
                                  bins=int(ran_range / 2),
                                  range=(0, ran_range))
        x = []
        for j in range(new_mf_a_x[0].size):

            temp = []
            for k in range(len(a_injected[i])):
                if a_injected[i][k] == j * (ran_range / new_mf_a_x[0].size):
                    temp.append(mf_a_injected[i][k])
            x.append(j * (ran_range / new_mf_a_x[0].size))
            new_mf_a_y.append(np.average(temp))
            new_mf_a_y_err.append(np.std(temp))

        plt.plot(a_injected[i], mf_a_injected[i], 'b.')
        plt.errorbar(x, new_mf_a_y, yerr=new_mf_a_y_err, fmt='ro')
        plt.xlabel("random amplitude injected /mV")
        plt.title("Channel: {} events: {}".format(i, num_events))
        plt.ylabel("amplitude index")
        plt.axhline(y=amp_cut, color='g', linestyle='-')
        plt.grid(True)
        plt.savefig(
            "/Users/willquinn/Desktop/pmt_sim_results/inj_vs_mf_amplitudes_ch{}"
            .format(i))
        plt.show()

        new_mf_s_y = []
        new_mf_s_y_err = []
        new_mf_s_x = np.histogram(a_injected[i],
                                  bins=int(ran_range / 2),
                                  range=(0, ran_range))
        x = []
        for j in range(new_mf_s_x[0].size):
            temp = []
            for k in range(len(a_injected[i])):
                if a_injected[i][k] == j * (ran_range / new_mf_a_x[0].size):
                    temp.append(mf_s_injected[i][k])
            x.append(j * (ran_range / new_mf_a_x[0].size))
            new_mf_s_y.append(np.average(temp))
            new_mf_s_y_err.append(np.std(temp))

        plt.plot(a_injected[i], mf_s_injected[i], 'b.')
        plt.errorbar(x, new_mf_s_y, yerr=new_mf_s_y_err, fmt='ro')
        plt.xlabel("random amplitude injected /mV")
        plt.title("Channel: {} events: {}".format(i, num_events))
        plt.ylabel("shape index")
        plt.grid(True)
        plt.savefig(
            "/Users/willquinn/Desktop/pmt_sim_results/inj_amp_vs_shape_ch{}".
            format(i))
        plt.show()

    output_file.Close()
Exemple #9
0
def main():

    # Handle the file inputs
    args = sncd_parse_arguments()
    input_data_filename = args.i
    output_data_filename = args.o
    config_file_name = args.c
    main_wall = args.w

    if main_wall == 'fr':
        main_wall = 1
    elif main_wall == 'it':
        main_wall = 0

    num_events = 1000000
    num_bins = 100
    max_amp = 1000

    # isolate the run number for naming convienience
    run_number = input_data_filename.split("_")[1]

    # Check to see if file exists - standard
    try:
        data_file = open(input_data_filename, 'r')
    except FileNotFoundError as fnf_error:
        print(fnf_error)
        raise Exception("Error opening data file")

    # Set up the pmt array
    topology = [13, 20]
    num_pmts = topology[0] * topology[1]
    pmt_array = PMT_Array(topology, run_number)
    for i in range(topology[0]):
        for j in range(topology[1]):
            num = i + topology[0] * j
            pmt_array.set_pmt_id("M:{}.{}.{}".format(main_wall, j, i), num)

    # Configure the array of PMTs - not as important here just yet
    if config_file_name is not None:
        pmt_array.apply_setting(config_file_name)

    cable_lengths = read_cable_lengths()

    # Open file
    file = ROOT.TFile(input_data_filename, "READ")
    file.cd()

    # The tree inside is called "T"
    tree = file.T

    # Counter for testing
    event_counter = [0 for i in range(num_pmts)]

    # raw_amplitudes = [[] for i in range(num_pmts)]
    '''templates = read_average_waveforms("~/Desktop/test_template.root", num_pmts)
    amp_hists = ROOT.TList()

    output_file = ROOT.TFile(output_data_filename, "RECREATE")

    for i_om in tqdm.tqdm(range(num_pmts)):
        temp_hist = ROOT.TH1D(pmt_array.get_pmt_object_number(i_om).get_pmt_id() + "_amplitude_index_spectrum",
                              pmt_array.get_pmt_object_number(i_om).get_pmt_id() + "_amplitude_index_spectrum",
                              num_bins, 0, max_amp)
        amp_hists.Add(temp_hist)'''

    h_map = ROOT.TH2I("event_map", "event_map", topology[1], 0, topology[1],
                      topology[0], 0, topology[0])

    create_log("output.txt")

    x = []

    # Run over file to create containers
    for event in tqdm.tqdm(tree):

        event_num = event.event_num
        row = event.row
        col = event.column
        OM_ID = event.OM_ID
        charge = -1 * event.charge
        baseline = event.baseline
        amplitude = -1 * event.amplitude
        fall_time = event.fall_time
        rise_time = event.rise_time
        peak_time = event.peak_time
        calo_hit_num = event.calo_hit_num
        calo_tdc = event.calo_tdc
        run_num = event.run_num
        wall_num = event.wall_num
        trig_num = event.trig_id

        if col == 9 and row == 7:
            x.append(trig_num)

        #print("calo_hit_num:", calo_hit_num, "event_num:", event_num, "trig_num:", trig_num)
        # raw_amplitudes[OM_ID].append(amplitude)

        h_map.Fill(col, row, 1)
        '''pmt_waveform = PMT_Waveform(event.waveform, pmt_array.get_pmt_object_number(OM_ID))
        peak = pmt_waveform.get_pmt_pulse_peak_position()

        if peak > 51:
            try:
                amplitude_index = np.dot(pmt_waveform.get_pmt_waveform_reduced()[peak - 50:peak + 350], templates[OM_ID])
                # raw_amplitudes[OM_ID].append(amplitude_index)
                amp_hists[OM_ID].Fill(amplitude_index)

            except:
                print("Waveform", len(pmt_waveform.get_pmt_waveform_reduced()[peak - 50:peak + 350]))
                print("Template", len(templates[OM_ID]))'''
        '''if event_counter[0] == num_events:
            break
        event_counter[OM_ID] += 1'''

        # del pmt_waveform

    sel_evnts = []
    for i, val in enumerate(x):
        if val in sel_evnts:
            pass
        else:
            sel_evnts.append(val)

    y = [[] for i in range(len(sel_evnts))]
    sel_evnts = np.array(sel_evnts)

    for event in tqdm.tqdm(tree):
        event_num = event.event_num
        row = event.row
        col = event.column
        OM_ID = event.OM_ID
        charge = -1 * event.charge
        baseline = event.baseline
        amplitude = -1 * event.amplitude
        fall_time = event.fall_time
        rise_time = event.rise_time
        peak_time = event.peak_time
        calo_hit_num = event.calo_hit_num
        calo_tdc = event.calo_tdc
        run_num = event.run_num
        wall_num = event.wall_num
        trig_num = event.trig_id
        pulse_time = event.calo_time

        val = calo_tdc * 6.25 - 400 + pulse_time * 6.25

        if len(np.where(sel_evnts == trig_num)[0]) > 0:
            output_log(
                "run_167_output.txt", "{},{},{},{},{},"
                "{},{},{},{},{},"
                "{}".format(event_num, row, col, OM_ID, peak_time,
                            calo_hit_num, calo_tdc, run_num, wall_num,
                            trig_num, pulse_time))
    '''amp_bins = [i*max_amp/num_bins for i in range(num_bins)]
    amp_cuts = []

    # output_file.cd()
    for i_om in tqdm.tqdm(range(num_pmts)):
        #amp_hists[i_om].SaveAs("/Users/willquinn/Desktop/PDFs/amplitude_index_"+str(i_om)+".pdf")
        #amp_hists[i_om].Write()
        plt.hist(raw_amplitudes[i_om], bins=amp_bins, color='g')
        plt.xlabel("Amplitude /mV")
        plt.ylabel("Counts")
        plt.title(pmt_array.get_pmt_object_number(i_om).get_pmt_id() + "_amplitude_spectrum Events: " + str(event_counter[i_om]))
        plt.savefig("/Users/willquinn/Desktop/PDFs/om_" + str(i_om) + "_amplitude_spectrum_HT")
        plt.grid()
        plt.yscale('log')
        plt.close()
    # output_file.Close()'''

    ROOT.gStyle.SetOptStat(0)
    canvas = ROOT.TCanvas()
    canvas.cd()
    h_map.Draw("colztext")
    canvas.Update()
    canvas.SaveAs("~/Desktop/map.png")

    return
    '''raw_amplitudes_array = []
    for i_om in tqdm.tqdm(range(num_pmts)):

        plt.hist(raw_amplitudes[i_om], bins=amp_bins, color='g', log=True)
        plt.xlabel("amplitude /mV")
        plt.ylabel("counts")
        plt.grid()
        plt.xlim(1500, max_amp)
        plt.title("OM " + pmt_array.get_pmt_object_number(i_om).get_pmt_id() + " Events: " + str(event_counter[i_om]))
        plt.savefig("/Users/willquinn/Desktop/PDFs/amplitude_index_spectrum_"+str(i_om))
        plt.close()

        pass'''
    '''temp_array, bin_edges = np.histogram(raw_amplitudes[i_om], bins=amp_bins)
        peak_amp_pos = np.argmax(temp_array)
        # peak_amp = np.amax(temp_array)
        amp_cuts.append(peak_amp_pos * max_amp/num_bins)
        # raw_amplitudes_array.append(temp_array)'''
    '''template_waveforms = [np.zeros(400) for j in range(num_pmts)]
Exemple #10
0
def main():
    # Handle the input arguments:
    ##############################
    args = pmt_parse_arguments()
    input_directory = args.i
    # config_file_name = args.c
    output_directory = args.o
    ##############################

    filenames_txt = input_directory + "/filenames.txt"

    try:
        print(">>> Reading data from file: {}".format(filenames_txt))
        date_file = open(filenames_txt, 'r')
    except FileNotFoundError as fnf_error:
        print(fnf_error)
        raise Exception("Error opening data file {}".format(filenames_txt))

    filenames = np.loadtxt(filenames_txt, delimiter=',', dtype={
        'names': ['filename'],
        'formats': ['S100']}, unpack=True)

    topology = [2, 1]
    pmt_array = PMT_Array(topology, "summary")
    pmt_array.set_pmt_id("GAO607", 0)
    pmt_array.set_pmt_id("GAO612", 1)

    '''# Set the cuts you wish to apply
    # If you don't do this the defaults are used
    if config_file_name is not None:
        pmt_array.apply_setting(config_file_name)
        # print_settings(pmt_array)'''

    # Set up the containers for the summary
    apulse_rates = [[] for i in range(pmt_array.get_pmt_total_number())]
    apulse_rates_err = [[] for i in range(pmt_array.get_pmt_total_number())]
    he_apulse_rates = [[] for i in range(pmt_array.get_pmt_total_number())]
    he_apulse_rates_err = [[] for i in range(pmt_array.get_pmt_total_number())]
    dates = [[] for i in range(pmt_array.get_pmt_total_number())]

    out_files = [output_directory+'/apulse_num_ch0.txt', output_directory+'/apulse_num_ch1.txt']
    create_file(out_files[0])
    create_file(out_files[1])

    for i_file in tqdm.tqdm(range(filenames.size)):
        file = filenames[i_file][0].decode("utf-8")

        date = file.split("_")[0]
        voltage = int(file.split("_")[1].split("A")[1])

        if voltage == 1400:
            pass
        else:
            continue

        apulse_info = read_file(date, voltage, input_directory + "/" + file, pmt_array, output_directory)

        for i_om in range(pmt_array.get_pmt_total_number()):

            if len(apulse_info[i_om]) > 0:
                pass
            else:
                continue

            apulse_rate = apulse_info[i_om][0]["apulse_rate"]
            he_apulse_rate = apulse_info[i_om][0]["he_apulse_rate"]

            apulse_rate_err = apulse_info[i_om][0]["apulse_rate_err"]
            he_apulse_rate_err = apulse_info[i_om][0]["he_apulse_rate_err"]


            apulse_rates[i_om].append(apulse_rate)
            apulse_rates_err[i_om].append(apulse_rate_err/10)
            he_apulse_rates[i_om].append(he_apulse_rate)
            he_apulse_rates_err[i_om].append(he_apulse_rate_err/10)
            dates[i_om].append(int(date))

            write_to_file(out_files[i_om], '{},{},{},{},{}'.format(date, apulse_rate, apulse_rate_err, he_apulse_rate, he_apulse_rate_err))

    # Plot individual summaries
    for i_om in range(pmt_array.get_pmt_total_number()):

        if len(apulse_rates[i_om]) > 0:
            pass
        else:
            continue
        date = process_date(dates[i_om])

        try:
            start = np.where(date == 0)[0][0]
        except:
            start = np.where(date == 1)[0][0]
        mid = np.where(date == 98)[0][0]

        print(date)

        print("start:", start)

        plt.figure(num=None, figsize=(9, 5), dpi=80, facecolor='w', edgecolor='k')
        plt.errorbar(date[:start + 1], np.array(apulse_rates[i_om][:start + 1]), yerr=np.array(apulse_rates_err[i_om][:start + 1]),
                 fmt="g.", label="Atmospheric He")
        plt.errorbar(date[start+1:mid + 1], np.array(apulse_rates[i_om][start+1:mid + 1]), yerr=np.array(apulse_rates_err[i_om][start+1:mid + 1]),
                 fmt="b.", label="1% He")
        plt.errorbar(date[mid+1:], np.array(apulse_rates[i_om][mid+1:]), yerr=np.array(apulse_rates_err[i_om][mid+1:]),
                 fmt="r.", label="10% He")
        plt.axvline(date[start], 0, 100, ls='--', color='k')
        plt.axvline(date[mid], 0, 100, ls='--', color='k')
        plt.xlabel("exposure days relative to 191106")
        plt.ylabel("Afterpulse rate /%")
        plt.title(pmt_array.get_pmt_object_number(i_om).get_pmt_id() + " afterpulse rate vs exposure time")
        plt.grid()
        plt.ylim(10,90)
        plt.legend(loc='upper left')
        plt.savefig(output_directory + "/summary_plots/" +
                    pmt_array.get_pmt_object_number(i_om).get_pmt_id() + "_apulse_rate_vs_time")
        plt.close()

        plt.figure(num=None, figsize=(9, 5), dpi=80, facecolor='w', edgecolor='k')
        plt.errorbar(date[:start + 1], np.array(he_apulse_rates[i_om][:start + 1]), yerr=np.array(he_apulse_rates_err[i_om][:start + 1]),
                 fmt="g.", label="Atmospheric He")
        plt.errorbar(date[start + 1:mid + 1], np.array(he_apulse_rates[i_om][start + 1:mid + 1]), yerr=np.array(he_apulse_rates_err[i_om][start + 1:mid + 1]),
                 fmt="b.", label="1% He")
        plt.errorbar(date[mid + 1:], np.array(he_apulse_rates[i_om][mid + 1:]), yerr=np.array(he_apulse_rates_err[i_om][mid + 1:]),
                 fmt="r.", label="10% He")
        plt.axvline(date[start], 0, 100, ls='--', color='k')
        plt.axvline(date[mid], 0, 100, ls='--', color='k')
        plt.xlabel("exposure days relative to 191106")
        plt.ylabel("Normalised apulse number")
        plt.title(pmt_array.get_pmt_object_number(i_om).get_pmt_id() + " afterpulse rate vs exposure time")
        plt.grid()
        # plt.ylim(150,300)
        plt.legend(loc='lower right')
        plt.savefig(output_directory + "/summary_plots/" +
                    pmt_array.get_pmt_object_number(i_om).get_pmt_id() + "_he_apulse_rate_vs_time")
        plt.close()

    # Plot ratio
    x_date = []
    ratio = []
    ratio_err = []
    gain_ratio = []
    he_ratio = []
    he_ratio_err = []
    for i in range(len(dates[0])):
        for j in range(len(dates[1])):
            if dates[0][i] == dates[1][j]:
                x_date.append(dates[0][i])

                if apulse_rates[1][j] == 0:
                    pass
                else:
                    ratio.append(apulse_rates[0][i] / apulse_rates[1][j])

                if he_apulse_rates[1][j] == 0:
                    pass
                else:
                    he_ratio.append(he_apulse_rates[0][i] / he_apulse_rates[1][j])

                break

    x_date = process_date(x_date)

    plt.plot(x_date, ratio, "k.")
    plt.axvline(98, color="r", ls="--")
    plt.axvline(0, color="b", ls="--")
    plt.xlabel("exposure days relative to 191106")
    plt.ylabel("Ratio apulse rate Ch0/Ch1")
    plt.title("Ratio of after pulse rates of CH 0 & 1 vs time")
    plt.grid()
    #plt.xlim(np.amin(np.array(x_date)), np.amax(np.array(x_date)))
    #plt.ylim(0, 2)
    plt.savefig(output_directory + "/summary_plots/apulse_rate_ratio_vs_time")
    plt.close()

    plt.plot(x_date, he_ratio, "k.")
    plt.axvline(98, color="r", ls="--")
    plt.axvline(0, color="b", ls="--")
    plt.xlabel("exposure days relative to 191106")
    plt.ylabel("Ratio apulse rate Ch0/Ch1")
    plt.title("Ratio of after pulse rates of CH 0 & 1 vs time")
    plt.grid()
    #plt.xlim(np.amin(np.array(x_date)), np.amax(np.array(x_date)))
    # plt.ylim(0, 2)
    plt.savefig(output_directory + "/summary_plots/he_apulse_rate_ratio_vs_time")
    plt.close()
Exemple #11
0
def read_file(date: str, voltage: int, root_file_name: str,
              pmt_array: PMT_Array, output_file_location: str):
    file = ROOT.TFile(root_file_name, "READ")
    file.cd()

    fit_parameter = [[] for i in range(pmt_array.get_pmt_total_number())]

    for i_om in range(pmt_array.get_pmt_total_number()):
        charge_hist = file.Get(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_charge_spectrum_" + str(voltage) + "V")
        amp_hist = file.Get(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_amplitude_spectrum_" + str(voltage) + "V")
        baseline_hist = file.Get(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_baseline_distribution_" + str(voltage) + "V")

        try:
            charge_hist.GetEntries()
            amp_hist.GetEntries()
            baseline_hist.GetEntries()
        except:
            continue

        mu_guess = charge_hist.GetMaximumBin() * charge_hist.GetBinWidth(0)
        lower_range = mu_guess - 9
        higher_range = mu_guess + 6

        bi_fit = ROOT.TF1(
            "fit", "[0]*(7.08*TMath::Gaus(x,[1],[2])"
            " + 1.84*TMath::Gaus(x,[1]*(1 + 72.144/975.651),[2]*1.036)"
            " + 0.44*TMath::Gaus(x,[1]*(1 + 84.154/975.651),[2]*1.042))"
            " + [3]*(exp([4]*x)/(1 + exp((x - [5])/[6])))", lower_range,
            higher_range)
        bi_fit = ROOT.TF1("fit", bismuth_string[i_om], lower_range,
                          higher_range)
        bi_fit.SetParNames("A", "mu", "sig", "B", "e", "c_e", "s")
        # bi_fit.SetParNames("A", "mu", "sig", "B", "ce_exp", "ce")

        bi_fit.SetParLimits(0, 0, 600)
        bi_fit.SetParLimits(1, mu_guess - 1, mu_guess + 1)
        bi_fit.SetParLimits(2, 1, 1.2)
        bi_fit.SetParLimits(3, 100, 500)
        bi_fit.SetParLimits(4, 0.001, 0.1)
        bi_fit.SetParLimits(5, mu_guess - 6, mu_guess)
        bi_fit.SetParLimits(6, 1, 3)
        bi_fit.SetParameters(100, mu_guess, 1, 400, 0.05, mu_guess - 2, 2)

        name = output_file_location + "/plots/" + date + "_" + pmt_array.get_pmt_object_number(
            i_om).get_pmt_id() + "_charge_spectrum_fit.pdf"

        charge_hist.Fit(bi_fit, "0Q", "", lower_range, higher_range)
        charge_hist.SetXTitle("Charge /pC")
        charge_hist.SetYTitle("Counts")
        charge_hist.SetTitle(
            date + "_" + pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            "_charge_spectrum_fit")

        c1 = ROOT.TCanvas()
        charge_hist.Draw()
        bi_fit.Draw("same")
        c1.SetGrid()
        c1.Update()
        ROOT.gStyle.SetOptFit(1)
        c1.SaveAs(name)
        '''print(">>>")
        print("Fit output:")
        for i in range(3):
            print(bi_fit.GetParName(i), bi_fit.GetParameter(i), "+/-", bi_fit.GetParError(i))
        print("Chi2/NDoF:", bi_fit.GetChisquare(), "/", bi_fit.GetNDF(), "=", bi_fit.GetChisquare() / bi_fit.GetNDF())
        print(">>>")'''
        if bi_fit.GetNDF() == 0:
            pass
        else:
            pars = {
                "mu": bi_fit.GetParameter(1),
                "mu_err": bi_fit.GetParError(1),
                "sig": bi_fit.GetParameter(2),
                "sig_err": bi_fit.GetParError(2),
                "base_mu": baseline_hist.GetMean(),
                "base_sig": baseline_hist.GetStdDev(),
                "gain": amp_hist.GetMaximumBin(),
                "chi2": bi_fit.GetChisquare() / bi_fit.GetNDF()
            }
            fit_parameter[i_om].append(pars)

    file.Close()
    return fit_parameter
Exemple #12
0
def main():
    # Handle the input arguments:
    ##############################
    args = pmt_parse_arguments()
    input_directory = args.i
    # config_file_name = args.c
    output_directory = args.o
    ##############################

    out_files = [
        output_directory + '/res_vs_time_ch0.txt',
        output_directory + '/res_vs_time_ch1.txt'
    ]
    create_file(out_files[0])
    create_file(out_files[1])

    filenames_txt = input_directory + "/filenames.txt"

    try:
        print(">>> Reading data from file: {}".format(filenames_txt))
        date_file = open(filenames_txt, 'r')
    except FileNotFoundError as fnf_error:
        print(fnf_error)
        raise Exception("Error opening data file {}".format(filenames_txt))

    filenames = np.loadtxt(filenames_txt,
                           delimiter=',',
                           dtype={
                               'names': ['filename'],
                               'formats': ['S100']
                           },
                           unpack=True)

    topology = [2, 1]
    pmt_array = PMT_Array(topology, "summary")
    pmt_array.set_pmt_id("GAO607", 0)
    pmt_array.set_pmt_id("GAO612", 1)
    '''# Set the cuts you wish to apply
    # If you don't do this the defaults are used
    if config_file_name is not None:
        pmt_array.apply_setting(config_file_name)
        # print_settings(pmt_array)'''

    # Set up the containers for the summary
    resolutions = [[] for i in range(pmt_array.get_pmt_total_number())]
    resolutions_err = [[] for i in range(pmt_array.get_pmt_total_number())]
    dates = [[] for i in range(pmt_array.get_pmt_total_number())]
    gains = [[] for i in range(pmt_array.get_pmt_total_number())]
    gains_err = [[] for i in range(pmt_array.get_pmt_total_number())]
    baseline_means = [[] for i in range(pmt_array.get_pmt_total_number())]
    baseline_sigs = [[] for i in range(pmt_array.get_pmt_total_number())]
    fit_chi2 = [[] for i in range(pmt_array.get_pmt_total_number())]

    for i_file in tqdm.tqdm(range(filenames.size)):
        file = filenames[i_file][0].decode("utf-8")

        date = file.split("_")[0]
        voltage = int(file.split("_")[1].split("A")[1])

        if voltage == 1000:
            pass
        else:
            continue

        fit_parameters = read_file(date, voltage, input_directory + "/" + file,
                                   pmt_array, output_directory)

        for i_om in range(pmt_array.get_pmt_total_number()):

            if len(fit_parameters[i_om]) > 0:
                pass
            else:
                continue

            mu = fit_parameters[i_om][0]["mu"]
            mu_err = fit_parameters[i_om][0]["mu_err"]
            sig = fit_parameters[i_om][0]["sig"]
            sig_err = fit_parameters[i_om][0]["sig_err"]
            chi_2 = fit_parameters[i_om][0]["chi2"]
            gain = fit_parameters[i_om][0]["gain"]
            baseline_mean = fit_parameters[i_om][0]["base_mu"]
            baseline_sig = fit_parameters[i_om][0]["base_sig"]

            res, res_err = get_resolution(mu, mu_err, sig, sig_err)

            resolutions[i_om].append(res)
            resolutions_err[i_om].append(res_err)
            dates[i_om].append(int(date))
            gains[i_om].append(gain)
            baseline_means[i_om].append(baseline_mean)
            baseline_sigs[i_om].append(baseline_sig)
            fit_chi2[i_om].append(chi_2)

            write_to_file(
                out_files[i_om],
                '{},{},{},{},{}'.format(date, res, res_err, chi_2, gain))

    # Plot individual summaries
    for i_om in range(pmt_array.get_pmt_total_number()):

        if len(resolutions[i_om]) > 0:
            pass
        else:
            continue
        date = process_date(dates[i_om])

        try:
            start = np.where(date == 0)[0][0]
        except:
            start = np.where(date == 1)[0][0]
        mid = np.where(date == 98)[0][0]

        # print("start:",start)

        plt.plot(date[:start + 1],
                 np.array(gains[i_om][:start + 1]) * 2,
                 "g.",
                 label="Atmospheric He")
        plt.plot(date[start + 1:mid + 1],
                 np.array(gains[i_om][start + 1:mid + 1]) * 2,
                 "b.",
                 label="1% He")
        plt.plot(date[mid + 1:],
                 np.array(gains[i_om][mid + 1:]) * 2,
                 "r.",
                 label="10% He")
        plt.axvline(date[start], 0, 100, ls='--', color='k')
        plt.axvline(date[mid], 0, 100, ls='--', color='k')
        plt.xlabel("exposure days relative to 190611")
        plt.ylabel("PMT gain at 1Mev /mV")
        plt.title(
            pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            " Gain at 1MeV vs exposure time")
        plt.grid()
        plt.ylim(150, 300)
        plt.legend(loc='lower right')
        plt.savefig(output_directory + "/summary_plots/" +
                    pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                    "_gains_vs_time.png")
        plt.close()

        plt.errorbar(date,
                     baseline_means[i_om],
                     yerr=baseline_sigs[i_om],
                     fmt='k.-',
                     ecolor='r')
        plt.grid()
        plt.xlabel("exposure days relative to 190611")
        plt.ylabel("Baseline mean /mV")
        plt.title(
            pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            " Baseline mean vs exposure time")
        plt.savefig(output_directory + "/summary_plots/" +
                    pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                    "_baseline_mean_vs_time.png")

        plt.close()
        '''plt.plot(date, baseline_sigs[i_om])
        plt.xlabel("exposure days relative to 190611")
        plt.ylabel("Baseline std-dev")
        plt.title(pmt_array.get_pmt_object_number(i_om).get_pmt_id() + " Baseline std-dev vs exposure time")
        plt.savefig(output_directory + "/summary_plots/" +
                    pmt_array.get_pmt_object_number(i_om).get_pmt_id() + "_baseline_sigma_vs_time")
        plt.close()'''

        res_filter = []
        for i_date in range(len(date)):
            if 1 < resolutions[i_om][i_date] < 3.75 and fit_chi2[i_om][
                    i_date] < 10:
                res_filter.append(True)
            else:
                res_filter.append(False)

        popt, pcov = curve_fit(
            linear,
            np.array(date[start:])[res_filter[start:]],
            np.array(resolutions[i_om][start:])[res_filter[start:]],
            sigma=np.array(resolutions_err[i_om][start:])[res_filter[start:]],
            p0=[0.001, 2],
            bounds=[[0, 0], [0.002, 3.5]],
            maxfev=500000)
        x_array = np.linspace(date[start], np.amax(date), 2)
        chi_2 = chi2(
            np.array(resolutions[i_om][start:])[res_filter[start:]],
            np.array(resolutions_err[i_om][start:])[res_filter[start:]],
            linear(date[start:][res_filter[start:]], *popt), len(popt))

        plt.errorbar(date[:start + 1],
                     resolutions[i_om][:start + 1],
                     yerr=resolutions_err[i_om][:start + 1],
                     fmt="g.",
                     label="Atmospheric He")
        plt.plot(np.array(date[start:])[res_filter[start:]],
                 np.array(resolutions[i_om][start:])[res_filter[start:]],
                 'ko',
                 label="used values")
        plt.errorbar(date[start + 1:mid + 1],
                     resolutions[i_om][start + 1:mid + 1],
                     yerr=resolutions_err[i_om][start + 1:mid + 1],
                     fmt="b.",
                     label="1% He")
        plt.errorbar(date[mid + 1:],
                     resolutions[i_om][mid + 1:],
                     yerr=resolutions_err[i_om][mid + 1:],
                     fmt="r.",
                     label="10% He")
        plt.plot(x_array, linear(x_array, *popt), 'k-')
        plt.xlabel(
            "exposure days relative to 190611 \n $y = (${:.1e}$ ± ${:.0e})$x + (${:.1e}$ ± ${:.0e}$)$ $\chi^2_R = {:.2}$"
            .format(popt[0], np.sqrt(pcov[0, 0]), popt[1], np.sqrt(pcov[1, 1]),
                    chi_2))
        plt.ylabel("Resolution at 1MeV /% $\sigma / \mu$")
        plt.title(
            pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            " Resolution vs exposure time")
        plt.axvline(date[start], 0, 100, ls='--', color='k')
        plt.axvline(date[mid], 0, 100, ls='--', color='k')
        plt.grid()
        plt.ylim(2, 4.5)
        plt.xlim(np.amin(date), np.amax(date))
        plt.legend(loc='upper right')
        plt.tight_layout()
        plt.savefig(output_directory + "/summary_plots/" +
                    pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                    "_resolution_vs_time.png")
        plt.close()

        plt.plot(np.array(date[start:])[res_filter[start:]],
                 np.array(fit_chi2[i_om][start:])[res_filter[start:]],
                 'ko',
                 label="used values")
        plt.plot(date[:start + 1],
                 fit_chi2[i_om][:start + 1],
                 "g.",
                 label="Atmospheric He")
        plt.plot(date[start + 1:mid + 1],
                 fit_chi2[i_om][start + 1:mid + 1],
                 "b.",
                 label="1% He")
        plt.plot(date[mid + 1:],
                 fit_chi2[i_om][mid + 1:],
                 "r.",
                 label="10% He")
        plt.xlabel("exposure days relative to 190611")
        plt.ylabel("$\chi^2_R$")
        plt.title(
            pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
            " Resolution fit $\chi^2_R$ vs exposure time")
        plt.grid()
        plt.axvline(date[start], 0, 100, ls='--', color='k')
        plt.axvline(date[mid], 0, 100, ls='--', color='k')
        plt.legend(loc='upper right')
        plt.xlim(np.amin(date), np.amax(date))
        plt.ylim(0, 10)
        plt.tight_layout()
        plt.savefig(output_directory + "/summary_plots/" +
                    pmt_array.get_pmt_object_number(i_om).get_pmt_id() +
                    "_resolution_vs_time_chi2.png")
        plt.close()

    # Plot ratio
    x_date = []
    ratio = []
    ratio_err = []
    gain_ratio = []
    for i in range(len(dates[0])):
        for j in range(len(dates[1])):
            if dates[0][i] == dates[1][j]:
                x_date.append(dates[0][i])
                ratio.append(resolutions[0][i] / resolutions[1][j])
                ratio_err.append(
                    resolutions[0][i] / resolutions[1][j] *
                    np.sqrt((resolutions_err[0][i] / resolutions[0][i])**2 +
                            (resolutions_err[1][j] / resolutions[1][j])**2))
                gain_ratio.append(gains[0][i] / gains[1][j])
                break

    popt, pcov = curve_fit(linear,
                           x_date,
                           ratio,
                           sigma=ratio_err,
                           p0=[1, 1],
                           bounds=[[0, 0], [10, 10]])
    x_date = process_date(x_date)
    x_array = np.linspace(np.amin(x_date), np.amax(x_date), 2)
    chi_2 = chi2(ratio, ratio_err, linear(x_date, *popt), 2)

    plt.errorbar(x_date, ratio, yerr=ratio_err, fmt="k.")
    plt.plot(
        x_array,
        linear(x_array, *popt),
        "g-",
        label=
        "$y = (${:.1e}$ ± ${:.0e})$\\times x + (${:.1e}$ ± ${:.0e}$) \chi^2_R = {:.2}$"
        .format(popt[0], np.sqrt(pcov[0, 0]), popt[1], np.sqrt(pcov[1, 1]),
                chi_2))
    plt.axvline(98, color="r", ls="--")
    plt.axvline(0, color="b", ls="--")
    plt.xlabel("exposure days relative to 190611")
    plt.ylabel("Ratio res_Ch0/res_Ch1")
    plt.title("Ratio of resolution of CH 0 & 1 vs time")
    plt.grid()
    plt.xlim(np.amin(np.array(x_date)), np.amax(np.array(x_date)))
    plt.ylim(0, 2)
    plt.savefig(output_directory +
                "/summary_plots/resolution_ratio_vs_time.png")
    plt.close()

    plt.plot(x_date, gain_ratio, "k.")
    plt.axvline(98, color="r", ls="--")
    plt.axvline(0, color="b", ls="--")
    plt.xlabel("exposure days relative to 190611")
    plt.ylabel("Ratio gain_Ch0/gain_Ch1")
    plt.title("Ratio of gain of CH 0 & 1 vs time")
    plt.grid()
    plt.xlim(np.amin(np.array(x_date)), np.amax(np.array(x_date)))
    plt.ylim(0.7, 1)
    plt.savefig(output_directory + "/summary_plots/gain_ratio_vs_time.png")
    plt.close()

    print("<<<< FINISHED >>>")
Exemple #13
0
def process_crd_file(input_data_file_name: str, pmt_array: PMT_Array,
                     waveform_output_file: ROOT.TFile):

    try:
        pmt_data_file = open(input_data_file_name, 'r')
    except FileNotFoundError as fnf_error:
        print(fnf_error)
        raise Exception("Error opening data file. Skip to the next file...")

    new_waveform_bool = False
    line_number_int = 0

    # print(pmt_array.get_pmt_object_number(0).get_histogram_dict().keys())

    for pmt_data_index, pmt_data_line in enumerate(
            pmt_data_file.readlines()[10:]):
        pmt_data_line_tokens = pmt_data_line.split(" ")

        if pmt_data_line_tokens[0] == "=" and pmt_data_line_tokens[1] == "HIT":
            new_waveform_bool = True
            line_number_int = 0
        else:
            pass

        if new_waveform_bool and line_number_int == 1:
            pmt_slot_number = int(pmt_data_line_tokens[1])  # Column
            pmt_channel_number = int(pmt_data_line_tokens[3])  # Row

            pmt_number = int(pmt_slot_number +
                             pmt_array.get_pmt_topology()[1] *
                             pmt_channel_number)
            '''if pmt_slot_number == 0:
                print(pmt_slot_number, pmt_channel_number)
                print(pmt_number)'''
            event_id_LTO = int(pmt_data_line_tokens[5])
            event_id_HT = int(pmt_data_line_tokens[7])
            pmt_waveform_peak_cell = int(pmt_data_line_tokens[27])
            pmt_waveform_charge = float(pmt_data_line_tokens[29])
            pmt_waveform_rise_time = float(pmt_data_line_tokens[39])
            if int(event_id_HT) != 0:
                pass
            elif int(event_id_LTO) != 0:
                pass
            else:
                pass

        elif new_waveform_bool and line_number_int == 2:
            if event_id_HT != 0:

                pmt_adc_values = []
                for i_adc in range(len(pmt_data_line_tokens)):
                    pmt_adc_values.append(pmt_data_line_tokens[i_adc])

                pmt_waveform = PMT_Waveform(
                    pmt_adc_values,
                    pmt_array.get_pmt_object_position(
                        [pmt_channel_number, pmt_slot_number]))
                if pmt_waveform.get_pulse_trigger():
                    '''print("results: ", pmt_waveform.get_results_dict())
                    print("")'''
                    '''print("MF Amplitude: ",pmt_waveform.get_pmt_pulse_mf_amp())
                    print("MF Shape: ", pmt_waveform.get_pmt_pulse_mf_shape())
                    print("Amplitude: ", pmt_waveform.get_pmt_pulse_peak_amplitude())
                    print("")'''
                    #print("Slot: ", pmt_channel_number, "Channel: ", pmt_channel_number)
                    pmt_waveform.fill_pmt_hists()

                if pmt_waveform.get_pmt_apulse_trigger():
                    print("pre_pulse")
                    pmt_waveform.save_pmt_waveform_histogram(
                        waveform_output_file)
                    temp_hist = ROOT.TH1I(
                        pmt_waveform.get_pmt_trace_id(),
                        pmt_waveform.get_pmt_trace_id(),
                        pmt_waveform.get_pmt_waveform_length(), 0,
                        pmt_waveform.get_pmt_waveform_length())

                    for i_value in range(
                            pmt_waveform.get_pmt_waveform_length()):
                        temp_hist.SetBinContent(
                            i_value + 1,
                            pmt_waveform.get_pmt_waveform()[i_value])

                    waveform_output_file.cd()
                    temp_hist.Write()
                    del temp_hist

                del pmt_waveform

            new_waveform_bool = False

        line_number_int += 1
    pmt_data_file.close()