from jfcal import JungfrauCalibration from jfcal.utils import create_histogram_from_data from jfcal import GAINTYPE from aare import GaussianChargeSharingKb, add_colorbar from .DataClasses import LinearFitResult import matplotlib.pyplot as plt import numpy as np from enum import Enum class Parameters(Enum): ELASTIC_SCATTERING_INTERCEPT = "elastic_scattering_intercept" ELASTIC_SCATTERING_SLOPE = "elastic_scattering_slope" K_ALPHA_MEAN = "k_alpha_mean" SIGMA = "sigma" K_ALPHA_AMPLITUDE = "k_alpha_amplitude" RATIO_AMPLITUDE_CHARGE_SHARING = "ratio_amplitude_charge_sharing" RATIO_MEAN_K_BETA = "ratio_mean_k_beta" RATIO_AMPLITUDE_K_BETA = "ratio_amplitude_k_beta" def plot_fitted_Copper_peaks(histogram_values : np.ndarray, hist_bin_centers : np.ndarray, function_parameters : np.ndarray, pixel : tuple[int, int], Count_range : tuple[int, int] = None, ADU_range : tuple[int, int] = None, axis : plt.Axes = None, show_plot : bool = True) -> plt.Axes: """ Plot the histogram of the ADU values along with the fitted function for a specific pixel. Parameters ---------- histogram_values : np.ndarray The histogram values for all pixels. hist_bin_centers : np.ndarray The bin centers for the histogram. function_parameters : np.ndarray The parameters of the fitted function for all pixels. pixel : tuple[int, int] The pixel coordinates to plot the histogram and fitted function for. Count_range : tuple[int, int], optional The range of counts to display on the y-axis. Default is None. ADU_range : tuple[int, int], optional The range of ADU values to display on the x-axis. If None, it will be set to the range of the bin edges. Default is None. axis : plt.Axes, optional The axis to plot on. If None, a new figure and axis will be created. show_plot : bool, optional Whether to display the plot. Default is True. Returns ------- plt.Axes The axis with the histogram and fitted function plot. """ variable_name_width = 8 variable_width = 8 decimal_places = 3 alpha = "\u03B1" beta = "\u03B2" sigma = "\u03C3" mu = "\u03BC" function_parameter = function_parameters[pixel[0], pixel[1], :] fit_label = ( f"{f'k{alpha}_{mu}:':<{variable_name_width}}{function_parameter[2]:>{variable_width}.{decimal_places}f}\n" f"{f'{sigma}:':<{variable_name_width}}{function_parameter[3]:>{variable_width}.{decimal_places}f}\n" f"{f'k{alpha}_N:':<{variable_name_width}}{function_parameter[4]:>{variable_width}.{decimal_places}f}\n" f"{f'C:':<{variable_name_width}}{function_parameter[5]:>{variable_width}.{decimal_places}f}\n" f"{f'k{beta}_m:':<{variable_name_width}}{function_parameter[6]:>{variable_width}.{decimal_places}f}\n" f"{f'k{beta}_f:':<{variable_name_width}}{function_parameter[7]:>{variable_width}.{decimal_places}f}" ) model = GaussianChargeSharingKb(max_calls = 4000, compute_errors = False, tolerance = 1e-2) func = lambda x : model(x, function_parameter) ax = plot_fitted_function(histogram_values[pixel[0], pixel[1], :], hist_bin_centers, function=func, Count_range = Count_range, bin_range = ADU_range, label = fit_label, xlabel = "ADU", title = f"Fitted Function for pixel {pixel}", axis = axis) if show_plot: plt.show() return ax def plot_fitted_parameter(fitted_parameter, parameter_name : str, suppress_outliers: bool = True): """ Plot the parameter for all pixels. Parameters ---------- fitted_parameter : np.ndarray The array of fitted parameters for all pixels. parameter_name : str The name of the parameter to plot. Must be one of the following: "elastic_scattering_intercept", "elastic_scattering_slope", "k_alpha_mean", "sigma", "k_alpha_amplitude", "ratio_amplitude_charge_sharing", "ratio_mean_k_beta", "ratio_amplitude_k_beta". suppress_outliers : bool, optional Whether to suppress outliers in the plot. Default is True. """ match parameter_name: case Parameters.ELASTIC_SCATTERING_INTERCEPT.value: plot_parameter(fitted_parameter[:, :, 0], parameter_name="Elastic scattering intercept", suppress_outliers=suppress_outliers) case Parameters.ELASTIC_SCATTERING_SLOPE.value: plot_parameter(fitted_parameter[:, :, 1], parameter_name="Elastic scattering slope", suppress_outliers=suppress_outliers) case Parameters.K_ALPHA_MEAN.value: plot_parameter(fitted_parameter[:, :, 2], parameter_name="Cu K_alpha mean", suppress_outliers=suppress_outliers) case Parameters.SIGMA.value: plot_parameter(fitted_parameter[:, :, 3], parameter_name="Charge sharing sigma", suppress_outliers=suppress_outliers) case Parameters.K_ALPHA_AMPLITUDE.value: plot_parameter(fitted_parameter[:, :, 4], parameter_name="Cu K_alpha amplitude", suppress_outliers=suppress_outliers) case Parameters.RATIO_AMPLITUDE_CHARGE_SHARING.value: plot_parameter(fitted_parameter[:, :, 5], parameter_name="Charge sharing amplitude ratio", suppress_outliers=suppress_outliers) case Parameters.RATIO_MEAN_K_BETA.value: plot_parameter(fitted_parameter[:, :, 6], parameter_name="Cu K_beta mean ratio", suppress_outliers=suppress_outliers) case Parameters.RATIO_AMPLITUDE_K_BETA.value: plot_parameter(fitted_parameter[:, :, 7], parameter_name="Cu K_beta amplitude ratio", suppress_outliers=suppress_outliers) case _: raise ValueError(f"Unknown parameter name: {parameter_name}. Valid options are: {[param.value for param in Parameters]}") def plot_parameter_histogram(fitted_parameter: np.ndarray, parameter_name : str, bin_range : tuple[float, float] = None, bin_width : float = None, axis : plt.Axes = None, show_plot : bool = True) -> plt.Axes: """ Plot the histogram of the fitted parameter for all pixels. Parameters ---------- fitted_parameter : np.ndarray The array of fitted parameters for all pixels. parameter_name : str The name of the parameter to plot. Must be one of the following: "elastic_scattering_intercept", "elastic_scattering_slope", "k_alpha_mean", "sigma", "k_alpha_amplitude", "ratio_amplitude_charge_sharing", "ratio_mean_k_beta", "ratio_amplitude_k_beta". bin_range : tuple[float, float], optional The range of bin values to display on the x-axis. If None, it will be set to the range of the bin edges. Default is None. bin_width : float, optional The width of the bins for the histogram. If None, it will be set to the default bin width of bin_range / 200. Default is None. axis : plt.Axes, optional The axis to plot on. If None, a new figure and axis will be created. show_plot : bool, optional Whether to display the plot. Default is True. Returns ------- plt.Axes The axis with the histogram plot. """ match parameter_name: case Parameters.ELASTIC_SCATTERING_INTERCEPT.value: data = fitted_parameter[:, :, 0].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"Elastic scattering intercept", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case Parameters.ELASTIC_SCATTERING_SLOPE.value: data = fitted_parameter[:, :, 1].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"Elastic scattering slope", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case Parameters.K_ALPHA_MEAN.value: data = fitted_parameter[:, :, 2].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"$k_\alpha$ mean", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case Parameters.SIGMA.value: data = fitted_parameter[:, :, 3].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"$\sigma$", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case Parameters.K_ALPHA_AMPLITUDE.value: data = fitted_parameter[:, :, 4].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"$k_\alpha$ amplitude", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case Parameters.RATIO_AMPLITUDE_CHARGE_SHARING.value: data = fitted_parameter[:, :, 5].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"Ratio amplitude charge sharing", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case Parameters.RATIO_MEAN_K_BETA.value: data = fitted_parameter[:, :, 6].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"Ratio $k_\beta$ mean", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case Parameters.RATIO_AMPLITUDE_K_BETA.value: data = fitted_parameter[:, :, 7].flatten() histogram = create_histogram_from_data(data, bin_range = bin_range, bin_width = bin_width) ax = plot_histogram(histogram, histogram.axes[0].centers[:], xlabel=r"Ratio $k_\beta$ amplitude", label = f"Mean: {np.mean(data):.3f}\nStd: {np.std(data):.3f}", axis=axis) case _: raise ValueError(f"Unknown parameter name: {parameter_name}. Valid options are: {[param.value for param in Parameters]}") if show_plot: plt.show() return ax def plot_backplane_pulsing(voltage_signals : np.ndarray, bp_signals : np.ndarray, fit_result : LinearFitResult, pixel : tuple[int, int], gain : GAINTYPE = None, x_lim : tuple[float, float] = None, y_lim : tuple[float, float] = None, axis : plt.Axes = None, show_plot : bool = True) -> plt.Axes: """ Plot the backplane pulsing signals for a specific pixel. Parameters ---------- voltage_signals : np.ndarray The voltage signals for all pixels. bp_signals : np.ndarray The backplane pulsing signals for all pixels. fit_result : LinearFitResult The result of the backplane pulsing linear fit. y_lim : tuple[float, float], optional The y-axis limits for the plot. Default is None. pixel : tuple[int, int] The pixel coordinates to plot the backplane pulsing signals for. gain : GAINTYPE, optional The gain type to plot the backplane pulsing signals for. Default is None, which plots all gain types. axis : plt.Axes, optional The axis to plot on. If None, a new figure and axis will be created. show_plot : bool, optional Whether to display the plot. Default is True. Returns ------- plt.Axes The axis with the backplane pulsing signals plot. """ if axis is None: fig, ax = plt.subplots(figsize = (8,5)) else: ax = axis plot_gain0 = False plot_gain1 = False plot_gain0 = True if gain is None or gain == GAINTYPE.G0 or gain == GAINTYPE.HG0 else False plot_gain1 = True if gain is None or gain == GAINTYPE.G1 else False switch_gain1 = np.argmax(bp_signals[*pixel, :] >> 14 == 1) if plot_gain0: ax.plot(voltage_signals[:switch_gain1], bp_signals[*pixel, :switch_gain1], label="gain0") fit_range = fit_result.fitrange_1[pixel[0], pixel[1], :] ax.plot(voltage_signals[fit_range[0]:fit_range[1]], fit_result.fitted_parameters[*pixel, 0] + fit_result.fitted_parameters[*pixel, 1] * voltage_signals[fit_range[0]:fit_range[1]], label="fitted gain0") if plot_gain1: ax.plot(voltage_signals[switch_gain1:], bp_signals[*pixel, switch_gain1:], label="gain1") fit_range = fit_result.fitrange_2[pixel[0], pixel[1], :] ax.plot(voltage_signals[fit_range[0]:fit_range[1]], fit_result.fitted_parameters[*pixel, 2] + fit_result.fitted_parameters[*pixel, 3] * voltage_signals[fit_range[0]:fit_range[1]], label="fitted gain1") ax.legend() ax.set_xlabel("Backplane pulsing signal [mV]") ax.set_ylabel("Signal [ADU]") if y_lim is not None: ax.set_ylim(*y_lim) if x_lim is not None: ax.set_xlim(*x_lim) ax.set_title(f"Backplane pulsing signals for pixel {pixel}") if show_plot: plt.show() return ax def plot_current_source(exposure_times : np.ndarray, mean_cs : np.ndarray, fit_result : LinearFitResult, pixel : tuple[int, int], logscale : bool = False, gain : list[GAINTYPE] = None, axis : plt.Axes = None, show_plot : bool = True) -> plt.Axes: """ Plot the current source signals for a specific pixel. Parameters ---------- exposure_times : np.ndarray The exposure times for all pixels. mean_cs : np.ndarray The mean current source signals for all pixels. fit_result : LinearFitResult The result of the backplane pulsing linear fit. pixel : tuple[int, int] The pixel coordinates to plot the current source signals for. logscale : bool, optional Whether to use a logarithmic scale for the x-axis. Default is False. gain : list[GAINTYPE], optional The gain types to plot the current source signals for. Default is None. axis : plt.Axes, optional The axis to plot on. If None, a new figure and axis will be created. show_plot : bool, optional Whether to display the plot. Default is True. Returns ------- plt.Axes The axis with the current source signals plot. """ if axis is None: fig, ax = plt.subplots(figsize = (8,5)) else: ax = axis gain1_switch = np.argmax(mean_cs[*pixel, :] >> 14 == 1) gain2_switch = np.argmax(mean_cs[*pixel, :] >> 14 == 3) plot_gain0 = False plot_gain1 = False plot_gain2 = False if gain is None: gain = [GAINTYPE.G0, GAINTYPE.G1, GAINTYPE.G2] for gain_type in gain: if gain_type == GAINTYPE.G0 or gain_type == GAINTYPE.HG0: plot_gain0 = True elif gain_type == GAINTYPE.G1: plot_gain1 = True elif gain_type == GAINTYPE.G2: plot_gain2 = True else: raise ValueError(f"Unsupported gain type: {gain_type}. Supported gain types are GAINTYPE.G0, GAINTYPE.HG0, GAINTYPE.G1, and GAINTYPE.G2.") if plot_gain0: if logscale: ax.semilogx(exposure_times[:gain1_switch], mean_cs[*pixel, :gain1_switch], label="gain0") else: ax.plot(exposure_times[:gain1_switch], mean_cs[*pixel, :gain1_switch], label="gain0") if plot_gain1: fit_rangeg1 = fit_result.fitrange_1[pixel[0], pixel[1], :] if logscale: ax.semilogx(exposure_times[gain1_switch:gain2_switch], mean_cs[*pixel, gain1_switch:gain2_switch], label="gain1") ax.semilogx(exposure_times[fit_rangeg1[0]:fit_rangeg1[1]], fit_result.fitted_parameters[*pixel, 0] + fit_result.fitted_parameters[*pixel, 1] * exposure_times[fit_rangeg1[0]:fit_rangeg1[1]], label="fitted line") else: ax.plot(exposure_times[gain1_switch:gain2_switch], mean_cs[*pixel, gain1_switch:gain2_switch], label="gain1") ax.plot(exposure_times[fit_rangeg1[0]:fit_rangeg1[1]], fit_result.fitted_parameters[*pixel, 0] + fit_result.fitted_parameters[*pixel, 1] * exposure_times[fit_rangeg1[0]:fit_rangeg1[1]], label="fitted line") if plot_gain2: fit_range2 = fit_result.fitrange_2[pixel[0], pixel[1], :] if logscale: ax.semilogx(exposure_times[gain2_switch:], mean_cs[*pixel, gain2_switch:], label="gain2") ax.semilogx(exposure_times[fit_range2[0]:fit_range2[1]], fit_result.fitted_parameters[*pixel, 2] + fit_result.fitted_parameters[*pixel, 3] * exposure_times[fit_range2[0]:fit_range2[1]], label="fitted line") else: ax.plot(exposure_times[gain2_switch:], mean_cs[*pixel, gain2_switch:], label="gain2") ax.plot(exposure_times[fit_range2[0]:fit_range2[1]], fit_result.fitted_parameters[*pixel, 2] + fit_result.fitted_parameters[*pixel, 3] * exposure_times[fit_range2[0]:fit_range2[1]], label="fitted line") ax.legend() ax.set_xlabel("Exposure time [s]") ax.set_ylabel("Signal [ADU]") if logscale: ax.set_xscale("log") ax.set_title(f"Current source signals for pixel {pixel}") if show_plot: plt.show() return ax def plot_histogram(histogram_data : np.ndarray, bin_centers : np.ndarray, Count_range : tuple[int, int] = None, bin_range : tuple[int, int] = None, label : str = None, title : str = None, xlabel : str = None, axis : plt.Axes = None) -> plt.Axes: """ Plot the histogram of the pedestal values. Parameters ---------- histogram_data : np.ndarray The histogram data to plot. bin_centers : np.ndarray The centers of the bins for the histogram. Count_range : tuple[int, int], optional The range of counts to display on the y-axis. Default is None. bin_range : tuple[int, int], optional The range of bin values to display on the x-axis. If None, it will be set to the range of the bin edges. Default is None. label : str, optional The label for the histogram. Default is None. title : str, optional The title for the plot. Default is None. xlabel : str, optional The label for the x-axis. Default is None. axis : plt.Axes, optional The axis to plot on. If None, a new figure and axis will be created. Returns ------- plt.Axes The axis with the histogram plot. """ if axis is None: fig, ax = plt.subplots(figsize = (8,5)) else: ax = axis mean = np.average(bin_centers, weights=histogram_data) std = np.sqrt( np.average((bin_centers - mean)**2, weights=histogram_data) ) label = f"{label} mean: {mean:.2f}, std: {std:.2f}" if label is not None else f"mean: {mean:.2f}, std: {std:.2f}" bin_width = bin_centers[1] - bin_centers[0] bin_edges = bin_centers - bin_width/2 bin_edges = np.append(bin_edges, bin_centers[-1] + bin_width/2) ax.stairs(histogram_data, bin_edges, label = label, zorder = 3) if bin_range is None: bin_range = (bin_centers[0]-0.01*bin_centers[0], bin_centers[-1]+0.01*bin_centers[-1]) if Count_range is not None: ax.set_ylim(*Count_range) ax.set_xlim(*bin_range) ax.grid(zorder = 0) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel('Counts') ax.set_title(title) if label is not None: plt.legend(loc="center left", bbox_to_anchor=(1.02, 0.5)) return ax def plot_fitted_function(histogram_data : np.ndarray, bin_edges : np.ndarray, function : callable, Count_range : tuple[int, int] = None, bin_range : tuple[int, int] = None, label : str = None, xlabel : str = None, title : str = None, axis : plt.Axes = None) -> plt.Axes: """ Plot the histogram of the pedestal values along with the fitted function. Parameters ---------- histogram_data : np.ndarray The histogram data to plot. bin_edges : np.ndarray The edges of the bins for the histogram. function : callable The fitted function to plot. Count_range : tuple[int, int], optional The range of counts to display on the y-axis. Default is None. bin_range : tuple[int, int], optional The range of bin values to display on the x-axis. If None, it will be set to the range of the bin edges. Default is None. label : str, optional The label for the fitted function. Default is None. xlabel : str, optional The label for the x-axis. Default is None. title : str, optional The title for the plot. Default is None. axis : plt.Axes, optional The axis to plot on. If None, a new figure and axis will be created. Returns ------- plt.Axes The axis with the histogram and fitted function plot. """ ax = plot_histogram(histogram_data, bin_edges, Count_range = Count_range, bin_range = bin_range, xlabel = xlabel, axis = axis, title = title) bin_centers = bin_edges[:-1] + np.diff(bin_edges)/2 ax.plot(bin_centers, function(bin_centers), label=label, color='red', zorder=4) if label is not None: ax.legend(prop={"family": "monospace", "size": 10}, loc= 'upper left') return ax def plot_parameter(fit_parameter : np.ndarray, parameter_name : str, suppress_outliers : bool = True) -> None: """ Plot the parameter for all pixels. Parameters ---------- fit_parameter : np.ndarray The parameter values to plot. parameter_name : str The name of the parameter to plot - used for plot title. suppress_outliers : bool, optional Whether to suppress outliers in the plot (True, don't plot outliers). Default is True. """ fig, ax = plt.subplots(figsize = (15,5)) im = ax.imshow(fit_parameter) #suppress outliers for colorbar if suppress_outliers: mean = np.mean(fit_parameter) std = np.std(fit_parameter) im.set_clim(mean-3*std,mean+3*std) ax.set_xlabel('Pixel X') ax.set_ylabel('Pixel Y') ax.set_title(parameter_name) add_colorbar(ax, im) plt.show()