import matplotlib.pyplot as plt import scipy.interpolate as interp import os import pickle import numpy as np from scipy.optimize import curve_fit from collections import defaultdict # Input text file file_path = "training_samples.txt" # Output folder to save plots output_folder = "wp/plots2" os.makedirs(output_folder, exist_ok=True) # Counters count_1_peak = 0 count_good = 0 # Combined graphs combined_adj_time = [] combined_adj_ampl = [] peak_widths = [] # Dictionary to store combined data for each (side, chan) data_dict = defaultdict(lambda: {'time': [], 'ampl': []}) def gaussian(x, A, mu, sigma, bsl): """Gaussian function.""" return bsl + A * np.exp(-0.5 * ((x - mu) / sigma) ** 2) # Read and process the file with open(file_path, 'r') as file: i = 0 for line in file: # Skip comment lines if line.strip().startswith("#"): continue i += 1 # count lines from 1 # Early exit, for debug # if count_good > 100: # break; # Parse each line starting with "Samples" parts = line.strip().split() if len(parts) > 2 and parts[4] == "Samples": evnum = int(parts[0]) # Detector element side = int(parts[1]) chan = int(parts[2]) slot = int(parts[3]) # Get the number of samples specified num_samples = int(parts[5]) peaks_found = int(parts[9 + num_samples]) # Number of peaks found # Select only good single pulses if peaks_found != 1: continue else: count_1_peak += 1 peak_index = int(parts[10 + num_samples]) # Peak location condition if (peak_index < 3 or peak_index > 7): continue # Extract amplitudes based on the number of samples amplitudes = list(map(int, parts[6:6 + num_samples])) mean_val = float(parts[6 + num_samples]) # Mean as calculated in the C++ code min_val = int(parts[7 + num_samples]) # Minimum amplitude value max_val = int(parts[8 + num_samples]) # Maximum amplitude value # Peak size condition if (max_val - min_val) < 40: continue # Calculate average of first three amplitudes if peak_index > 3: start_avg = (amplitudes[0] + amplitudes[1] + amplitudes[2])/3. if abs(start_avg - min_val) > (max_val - min_val)/3: continue if peak_index < 6: end_avg = (amplitudes[9] + amplitudes[8] + amplitudes[7])/3. if abs(end_avg - min_val) > (max_val - min_val)/3: continue # Make sure it's a clean single peak not_good = 0 for j in range (2, num_samples-2): der1r = amplitudes[j+1] - amplitudes[j] der1l = amplitudes[j] - amplitudes[j-1] der2 = (der1r - der1l)/2 if (der1r*der1l < 0 and j != peak_index): print(f"Line {i}: found second inflection at {j}!") not_good += 1 if (peak_index > 3 or peak_index < 6) and not_good > 0: continue # Peak width condition HL = amplitudes[peak_index - 2] - min_val HR = amplitudes[peak_index + 2] - min_val HM = max_val - min_val if abs(HL - HM/2.) > HM/10 or abs(HR - HM/2.) > HM/10: continue # Increment counter count_good += 1 # Generate time intervals in nanoseconds time_ns = [(j - 5) * 25 for j in range(len(amplitudes))] # Print the amplitudes to stdout # print(f"Line {i}, Event {evnum}, side {side}, chan {chan}, slot {slot}, Peaks: {peaks_found}, Amplitudes: {amplitudes}") # Use parabolic interpolation to find peak_max t1 = time_ns[peak_index] P1 = amplitudes[peak_index] P0 = amplitudes[peak_index - 1] P2 = amplitudes[peak_index + 1] t_peak_parabolic = t1 - 25 * (P2 - P0)/(2 * (P0 - 2*P1 + P2)) h_peak_parabolic = P1 - (P2 - P0)*(P2 - P0)/(4 * (P0 - 2*P1 + P2)) # Fit with Gaussian - not used! if 1 > 2: # Initial fit params: amplitude, peak position, width (sigma) p0 = [h_peak_parabolic - min_val, t_peak_parabolic, 30., min_val] # Define fit range start_idx = max(0, peak_index - 2) end_idx = min(num_samples, peak_index + 2) x_vals = time_ns[start_idx:end_idx] y_vals = amplitudes[start_idx:end_idx] popt, _ = curve_fit(gaussian, x_vals, y_vals, p0=p0) peak_height = popt[0] + popt[3] peak_position = popt[1] baseline = popt[3] else: peak_height = h_peak_parabolic peak_position = t_peak_parabolic baseline = min_val # Splines interpolation x_interp = np.linspace(time_ns[0], time_ns[-1], 100) spline = interp.CubicSpline(time_ns, amplitudes) y_interp = spline(x_interp) h_max = np.max(y_interp) t_max = x_interp[np.argmax(y_interp)] # Plot amplitude vs. time plt.figure(figsize=(8, 4)) plt.plot(time_ns, amplitudes, marker='o', linestyle='-', color='b') plt.plot(x_interp, y_interp, linestyle='-.', color='teal', label=f"cubic splines: {t_max:.2f} ns") #plt.bar(time_ns, amplitudes, width=25, color='blue', edgecolor='black', alpha=0.7) #plt.ylim(900, 1600) # Set y-axis limits #plt.axhline(y=mean_val, color='green', linestyle='-', label='baseline') # Add horizontal line #plt.axhline(y=min_val, color='blue', linestyle='--', label='min') plt.axvline(t_peak_parabolic, color='red', linestyle='--', label=f"parabolic fit: {t_peak_parabolic:.2f} ns") plt.axhline(y=h_peak_parabolic, color='red', linestyle='--') if 1 > 2: plt.axvline(peak_position, color='black', linestyle=':', label=f"Gaussian fit: {peak_position:.2f} ns") plt.axhline(y=peak_height, color='black', linestyle=':') plt.plot([], [], ' ', label=f"max - min = {max_val - min_val}") # Extra legend entry plt.title(f"Line #{i}, Event {evnum}, side {side}, chan {chan}, slot {slot} - peaks counted: {peaks_found}") plt.xlabel("Time (ns)") plt.ylabel("Amplitude") plt.legend() plt.grid(True) # Save the plot as a PNG file if count_good < 300: output_file = os.path.join(output_folder, "samples_line{}_side{}_ch{}_slot{}_{}peaks.png".format(i, side, chan, slot, peaks_found)) plt.savefig(output_file) plt.close() # Shifted scaled pulse adj_ampl = [0] * num_samples adj_time = [0] * num_samples for j in range (0, num_samples): adj_ampl[j] = 100 * (amplitudes[j] - min_val)/(h_max - min_val) adj_time[j] = time_ns[j] - t_max plt.figure(figsize=(8, 4)) plt.plot(adj_time, adj_ampl, marker='D', linestyle='-', color='green') plt.title(f"Line #{i}, Event {evnum}, side {side}, chan {chan}") plt.xlabel("Adjusted time (ns)") plt.ylabel("Adjusted amplitude") plt.grid(True) if count_good < 10: # Save the plot as a PNG file output_file2 = os.path.join(output_folder, "selected_line{}_side{}_ch{}.png".format(i, side, chan)) plt.savefig(output_file2) plt.close() # Store data grouped by (side, chan, slot) data_dict[(side, chan, slot)]['time'].extend(adj_time) data_dict[(side, chan, slot)]['ampl'].extend(adj_ampl) combined_adj_time.extend(adj_time) combined_adj_ampl.extend(adj_ampl) # Combine the time and amplitude data into a list of tuples for sorting combined_data = list(zip(combined_adj_time, combined_adj_ampl)) # Sort the combined data by the time values (first element of each tuple) combined_data.sort(key=lambda x: x[0]) # Unzip the sorted data back into time and amplitude lists sorted_adj_time, sorted_adj_ampl = zip(*combined_data) # Plot all renormalised datasets combined plt.figure(figsize=(8, 4)) plt.plot(sorted_adj_time, sorted_adj_ampl, marker='o', linestyle='-', color='magenta') # Add title, labels, grid, and legend (if needed) plt.title(f"All {count_good} renormalised datasets combined") plt.xlabel("Realigned time (ns)") plt.ylabel("Renormalised amplitude") plt.xlim(-120, 120) # Fixed range for x-axis plt.grid(True) output_file3 = os.path.join(output_folder, "combined_pulses.png") plt.savefig(output_file3) plt.close() # Save pulse data data_dict_standard = dict(data_dict) with open("pulse_data.pkl", "wb") as f: pickle.dump((data_dict_standard), f) # Print results print(f"Found {count_good} good pulses, out of {count_1_peak} single peak pulses.") print("Plots saved in the folder: {}".format(output_folder))